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
@@ -0,0 +1,232 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The mcp bundle's fourth plugin part (manifest.yml plugin: parts:, loaded
4
+ # before plugin.rb): a server's tools, from its tools/list cache to chi's
5
+ # tool index (Plugin#index, #publish), with what makes a tool uncallable (a
6
+ # bad schema, a name clash), and /mcp's listing of them.
7
+ require "json"
8
+ require "time"
9
+ require "samagotchi/tools/tool_index"
10
+
11
+ class Plugin
12
+ private
13
+
14
+ # ── The tools/list cache ──────────────────────────────────────────────
15
+
16
+ # Where the server's cache is: tools-<server>.json, the name sanitized.
17
+ def cache_path(server, ctx)
18
+ File.join(ctx.data_dir, "tools-#{server.name.gsub(/[^A-Za-z0-9_.-]+/, "_")}.json")
19
+ end
20
+
21
+ # Take the server's tools from its cache: true when it holds this
22
+ # config's list (the server is then :cached, not started).
23
+ def load_cache(server, ctx)
24
+ data = JSON.parse(File.read(cache_path(server, ctx)))
25
+ return false unless data.is_a?(Hash) && data["digest"] == server.digest && data["tools"].is_a?(Array)
26
+
27
+ server.listed = data["tools"].select { |tool| tool.is_a?(Hash) && tool["name"] }
28
+ server.info = data["info"].is_a?(String) ? data["info"] : nil
29
+ server.cached_at = begin
30
+ Time.iso8601(data["saved_at"].to_s)
31
+ rescue ArgumentError
32
+ nil
33
+ end
34
+ server.state = :cached
35
+ true
36
+ rescue SystemCallError, JSON::ParserError
37
+ false
38
+ end
39
+
40
+ # Written aside and renamed: workers share the dir.
41
+ def save_cache(server, ctx)
42
+ Samagotchi::AtomicFile.write(cache_path(server, ctx),
43
+ JSON.generate({ digest: server.digest, saved_at: Time.now.utc.iso8601, info: server.info,
44
+ tools: server.listed }.compact))
45
+ rescue SystemCallError => e
46
+ ctx.log.warn("mcp_cache_not_written", server: server.name, msg: e.message)
47
+ end
48
+
49
+ # ── Tools ─────────────────────────────────────────────────────────────
50
+
51
+ # Index the server's tools, the tools: filter applied: each named, its
52
+ # schema checked (a bad one is kept, marked, and said once). The whole
53
+ # list is built, then swapped in: a search on another thread never sees
54
+ # half a list. Their estimated tokens go to the log when they changed.
55
+ def index(server, ctx)
56
+ wanted = server.config["tools"] && Array(server.config["tools"]).map(&:to_s)
57
+ listed = server.listed || []
58
+ listed = listed.select { |tool| wanted.any? { |w| File.fnmatch(w, tool["name"], File::FNM_EXTGLOB) } } if wanted
59
+ tokens = 0
60
+ tools = listed.map do |listed_tool|
61
+ tool = McpTool.new(server: server.name, name: listed_tool["name"].to_s,
62
+ chi_name: tool_name(server.name, listed_tool["name"]), description: description(listed_tool),
63
+ schema: listed_tool["inputSchema"] || { "type" => "object", "properties" => {} }, error: nil)
64
+ tokens += definition_tokens(tool.chi_name, tool.description, tool.schema)
65
+ tool
66
+ rescue StandardError => e # a schema chat_schemas can't read raises more than ArgumentError
67
+ error = e.message.sub(/\Atool \S+: /, "")
68
+ left_out("MCP tool #{server.name}/#{tool.name} can't be called: #{error}", ctx)
69
+ tool.with(error: error)
70
+ end
71
+ server.tools = tools.freeze
72
+ say_clashes(ctx)
73
+ publish
74
+ return if tokens == server.tokens
75
+
76
+ server.tokens = tokens
77
+ ctx.log.info("mcp_tools_estimated", server: server.name, tools: offered(server).size, tokens: tokens)
78
+ end
79
+
80
+ # Said once (a notice and the log), not at each index.
81
+ def left_out(text, ctx)
82
+ first = @left_out_lock.synchronize { @left_out.include?(text) ? false : (@left_out << text) }
83
+ return unless first
84
+
85
+ ctx.log.warn("mcp_tool_left_out", msg: text)
86
+ ctx.notify(text, level: :warn)
87
+ end
88
+
89
+ # Tools of every server whose mcp_<server>_<tool> another tool has too
90
+ # (two servers, git-hub and git_hub; names alike up to NAME_CHARS):
91
+ # guardrail rules and approvals key on that name, so neither is called.
92
+ # Said once per clash; checked after each server's index, so whichever
93
+ # server comes second says it.
94
+ def say_clashes(ctx)
95
+ @servers.flat_map(&:tools).group_by(&:chi_name).each do |chi_name, same|
96
+ next if same.size < 2
97
+
98
+ left_out("MCP tools #{same.map { |t| "#{t.server}/#{t.name}" }.join(" and ")} can't be called: " \
99
+ "both are #{chi_name} to guardrail rules", ctx)
100
+ end
101
+ end
102
+
103
+ # The other indexed tools with +tool+'s mcp_<server>_<tool>.
104
+ def clashes(tool)
105
+ @servers.flat_map(&:tools).select { |t| t.chi_name == tool.chi_name && [t.server, t.name] != [tool.server, tool.name] }
106
+ end
107
+
108
+ # Why call_tool refuses +tool+, nil when it can call it.
109
+ def refusal(tool)
110
+ return tool.error if tool.error
111
+
112
+ others = clashes(tool)
113
+ "name clash with #{others.map { |t| "#{t.server}/#{t.name}" }.join(", ")} (#{tool.chi_name})" unless others.empty?
114
+ end
115
+
116
+ # The server's tools call_tool can call (no bad schema, no name clash).
117
+ def offered(server) = server.tools.reject { |tool| refusal(tool) }
118
+
119
+ # The marks a search and /mcp give a tool call_tool refuses.
120
+ def mark(tool)
121
+ return "(bad schema)" if tool.error
122
+
123
+ others = clashes(tool)
124
+ "(name clash with #{others.map { |t| "#{t.server}/#{t.name}" }.join(", ")})" unless others.empty?
125
+ end
126
+
127
+ # A tool's definition as the chat path sends it (LLM::ChatLoop#tool_definitions:
128
+ # the chat schema, wrapped as a function), in estimated tokens
129
+ # (TokenUsage::CHARS_PER_TOKEN). The native prompts (Gemma, Qwen) render a
130
+ # flatter schema, so it is an upper bound there.
131
+ # @raise [ArgumentError] a bad schema
132
+ def definition_tokens(name, description, schema)
133
+ Samagotchi::Tools::ToolIndex.spec_tokens(Samagotchi::Plugin::Api.tool_spec(name, description, schema: schema) { nil })
134
+ end
135
+
136
+ # Every server's tools into chi's index, a group each: its state (what a
137
+ # search's notes say), its summary line, and its tools with the marks
138
+ # and refusals of now (a clash with another server's tool too, so all of
139
+ # them each time). After each index and each state change a note reads;
140
+ # one at a time, so the last one published is the newest.
141
+ def publish
142
+ return unless @source
143
+
144
+ @publish.synchronize do
145
+ groups = @servers.map do |server|
146
+ state = { starting: :starting, failed: :failed, needs_sign_in: :needs_user }.fetch(server.state, :ready)
147
+ tools = Array(server.tools).map do |tool|
148
+ Samagotchi::Tools::ToolIndex::Tool.new(group: tool.server, name: tool.name, description: tool.description,
149
+ schema: tool.schema, acts_as: tool.chi_name, refusal: refusal(tool),
150
+ mark: mark(tool))
151
+ end
152
+ Samagotchi::Tools::ToolIndex::Group.new(name: server.name, summary: server_summary(server), state: state,
153
+ error: group_error(server, state), tools: tools)
154
+ end
155
+ @source.publish(groups)
156
+ end
157
+ end
158
+
159
+ # What a group's note and a call that misses its tools say: a failed
160
+ # server's error; for one that needs sign-in a line for any turn's author
161
+ # (a search reaches a participant's turn too, which can't run the command).
162
+ def group_error(server, state)
163
+ case state
164
+ when :failed then server.error
165
+ when :needs_user then "#{server.name} needs sign-in (the session's owner runs /mcp login #{server.name})"
166
+ end
167
+ end
168
+
169
+ # The server's line in find_tools: its description: from config, else the first
170
+ # sentence of its instructions, else nothing (its line has the tool
171
+ # count). Never its tool names: a model that knows them calls them
172
+ # blind, without a search (a smoke run's Splash did).
173
+ def server_summary(server)
174
+ given = server.config["description"].to_s.strip
175
+ return given unless given.empty?
176
+
177
+ server.info
178
+ end
179
+
180
+ # ── /mcp's listing ────────────────────────────────────────────────────
181
+
182
+ def listing
183
+ return "No servers. Add them in config.yml under `bundles: mcp: servers:` (docs/bundles.md, The mcp bundle)." if @servers.empty?
184
+
185
+ servers = @servers.map do |server|
186
+ marker = if @source && !@source.declared_groups.include?(server.name)
187
+ " (not in toolkit #{@ctx.toolkit})"
188
+ end
189
+ head = "**#{server.name}**: #{state_text(server)}#{marker}"
190
+ # Sorted: a server lists its tools in its own (often grouped) order.
191
+ tools = server.tools.sort_by(&:name).map { |t| ["- `#{t.server}/#{t.name}`", mark(t)].compact.join(" ") }
192
+ tools.empty? ? head : "#{head}\n#{tools.join("\n")}"
193
+ end
194
+ [*servers, totals_text].join("\n\n")
195
+ end
196
+
197
+ # /mcp's last line: what every request carries, and the servers' tools'
198
+ # tokens. When another tool took both names (chi's tool index left its
199
+ # tools out: a load warning), that the model can't reach them.
200
+ def totals_text
201
+ if @source.declared_names.empty?
202
+ return "The search and call tools aren't declared in this session (other tools have their names; see the " \
203
+ "load warnings), so the model can't reach the tools above."
204
+ end
205
+
206
+ total = @servers.sum { |server| OFFERED.include?(server.state) ? server.tokens : 0 }
207
+ "Every request carries #{@source.declared_names.join(" and ")}: ~#{thousands(@source.declared_tokens)} tokens. " \
208
+ "The tools above, ~#{thousands(total)} tokens, reach the model only in a search's answer " \
209
+ "(estimated: their JSON as the chat API gets it, ÷ #{format("%g", Samagotchi::TokenUsage::CHARS_PER_TOKEN)})."
210
+ end
211
+
212
+ def state_text(server)
213
+ count = offered(server).size
214
+ tools = "#{count} tool#{"s" unless count == 1}"
215
+ case server.state
216
+ when :cached then "cached (not started), #{tools}, #{tokens_text(server)}"
217
+ when :running then "#{server.url ? "connected" : "running"} (#{server.client.label}), #{tools}, #{tokens_text(server)}"
218
+ when :starting then "starting"
219
+ when :failed then server.tools.empty? ? "failed: #{server.error}" : "failed (#{tools}): #{server.error}"
220
+ when :needs_sign_in
221
+ elsewhere = server.token.respond_to?(:kept) && (server.token.kept rescue nil) # degrade-ok: the store's error is the call's
222
+ elsewhere ? "signed in from another session: connects on its next call" : "needs sign-in (/mcp login #{server.name})"
223
+ else "stopped: #{server.error}"
224
+ end
225
+ rescue Samagotchi::Plugin::Service::Stopped
226
+ "stopped"
227
+ end
228
+
229
+ def tokens_text(server) = "~#{thousands(server.tokens)} tokens"
230
+
231
+ def thousands(number) = number.to_s.reverse.scan(/\d{1,3}/).join(",").reverse
232
+ end
@@ -102,16 +102,24 @@ bundles:
102
102
  timeout: 60 # per call, seconds; startup_timeout: 10
103
103
  servers:
104
104
  files: # server name
105
- command: [npx, -y, "@modelcontextprotocol/server-filesystem", ~/scratch] # stdio only; array (or one string, shell-split)
105
+ command: [npx, -y, "@modelcontextprotocol/server-filesystem", ~/scratch] # a local (stdio) server; array (or one string, shell-split)
106
106
  env: {NODE_OPTIONS: "--no-warnings"} # optional, added to chi's env
107
107
  cwd: ~/scratch # optional; default the session's cwd
108
108
  tools: [read_*, list_directory] # optional filter (globs)
109
109
  description: files in ~/scratch # optional: the server's line in find_tools (default: its instructions' first sentence)
110
110
  attach_image_paths: true # default: an answer that is only an image's path (temp dir/cwd) is attached as a picture
111
111
  start: lazy # default: tools from the saved tools/list, the server starts on the first call; eager: with every session
112
+ context7: # a remote (HTTP) server: url: instead of command: (never both)
113
+ url: https://mcp.context7.com/mcp
114
+ bearer_token_env: CONTEXT7_TOKEN # optional: sent as Authorization: Bearer <the variable's value>; never the token itself in config
115
+ headers: {X-Example: "1"} # optional, sent as given (not for secrets; not Accept, Content-Type, Mcp-*)
116
+ linear: # a remote server with no static token that answers 401: /mcp login linear signs in (OAuth)
117
+ url: https://mcp.linear.app/mcp
118
+ oauth: {client_id: Iv1.abc, issuer: https://id.example} # optional, a client the user registered; scopes:, redirect_port:, client_secret_env:
119
+ client_metadata_url: https://…/client.json # optional: chi's client id metadata document (default: chi's own; false: none)
112
120
  ```
113
121
 
114
- A guardrail rule's `tool:` may be a glob (`tool: "mcp_*"`, verdict `ask`) to cover every MCP tool: a `call_tool` acts as `mcp_<server>_<tool>`, so `tool: "mcp_github_*"` covers one server's (a `find_tools` search is never asked about); see `docs/guardrails.md`. A server's optional `description:` is its line in `find_tools`' description. The mcp bundle saves each server's tool list in `$XDG_STATE_HOME/samagotchi/plugins/mcp/tools-<server>.json` (keyed by a digest of command/env/cwd): a changed server config is picked up by the next session start, which shows "Starting MCP server x (config changed, …)".
122
+ A guardrail rule's `tool:` may be a glob (`tool: "mcp_*"`, verdict `ask`) to cover every MCP tool: a `call_tool` acts as `mcp_<server>_<tool>`, so `tool: "mcp_github_*"` covers one server's (a `find_tools` search is never asked about); see `docs/guardrails.md`. A server's optional `description:` is its line in `find_tools`' description. The mcp bundle saves each server's tool list in `$XDG_STATE_HOME/samagotchi/plugins/mcp/tools-<server>.json` (keyed by a digest of command/env/cwd, or of url/headers/bearer_token_env for a remote server: never the token's value): a changed server config is picked up by the next session start, which shows "Starting MCP server x (config changed, …)".
115
123
 
116
124
  **Preservation rule**: `ConfigFile.write_default_model!` and `ConfigFile.write_model_alias!` (`/model --default`, `/model --alias`) change one key on its own line of the text (`ConfigTextEdit`: the user's comments and layout stay; a new key goes at the end of its section, a missing section at the end of the file), check that the result parses to the old data plus that key (else they dump the whole file from it), and write through `AtomicFile` (a unique temp file renamed over config.yml, through a symlink, keeping its mode). Never overwrite the file with only scalar keys — that would clobber `hooks:` / `model_aliases:` / `hosts:` / `recap:` / `guardrails:` / `bundles:`.
117
125
 
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.182.0
3
+ version: 0.183.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
7
7
  identity.md: sha256:29c2f7df9f6c5acbc5ec17000a4490741e55e426af15ca0d81c8706edd9bd027
8
8
  self_map.md: sha256:750822b3488b302c6e32638e6224f270d8e06b50ea85cd6e0bb5a6ff12eed1d8
9
- config_modification_protocol.md: sha256:7bced9b4e03f50c215e1c0bb786a9bfb51f5c1b71ace961ba16ccf6890270f72
9
+ config_modification_protocol.md: sha256:03fdf3ea3138449bc73f73eaa5604cc5d702777c20499ec13ca32b7696e6d37f
10
10
  memory_guide.md: sha256:272443ff8292631b28239cb8431d6e8dd19aa23fc53d05e1a10c11696a0a5d8d
11
11
  delegated.md: sha256:a0d6ddcd4a8be06526d964898611775fd251cfd9d145a9d16afaccaa503597bd
@@ -5,6 +5,7 @@ require_relative "../reply_wait"
5
5
  require_relative "../parent_report"
6
6
  require_relative "exit"
7
7
  require_relative "../session_access"
8
+ require_relative "../session_access/exchange"
8
9
 
9
10
  module Samagotchi
10
11
  module CLI
@@ -64,9 +65,7 @@ module Samagotchi
64
65
  # @return [Integer] the exit status
65
66
  def wait_for_reply(id, target:, timeout:)
66
67
  report_turn_id = target.report_turn_id
67
- result = @access.wait_reply(id, **target.to_h, timeout: timeout, poll_interval: self.class::POLL_INTERVAL)
68
- result.turn_id = report_turn_id if report_turn_id && !report_turn_id.to_s.empty?
69
- result.text = result.text&.dup&.force_encoding(Encoding::UTF_8)&.scrub
68
+ result = exchange.wait(id, target, timeout: timeout, poll_interval: self.class::POLL_INTERVAL)
70
69
  @reported = true
71
70
  # What a parent may pick there: config.yml tightened by the session's
72
71
  # own. Machine-local (this machine's config.yml): remotely the
@@ -89,6 +88,9 @@ module Samagotchi
89
88
  Exit::FAILED
90
89
  end
91
90
 
91
+ # The wait's Exchange (chi send builds its own, with its pause).
92
+ def exchange = @exchange ||= SessionAccess::Exchange.new(@access)
93
+
92
94
  # More keys for the error object, after session_id: {} (chi send's
93
95
  # names the id asked).
94
96
  def error_extra = {}
@@ -40,6 +40,13 @@ module Samagotchi
40
40
  # command, with chi send's trust.
41
41
  ALLOWED_IDS = [ClientId::CLI_ANSWER].freeze
42
42
 
43
+ # The Bridge's answer to a /turn line whose command hides its arguments
44
+ # (/callback's one-time code) that can't run as a command (with images,
45
+ # from a sender above): refused, never a message for the model.
46
+ PRIVATE_REFUSED = [{ "Allow" => "POST" }, 400,
47
+ { error: "private_command",
48
+ detail: "/callback runs only as a command: send it alone, without images" }].freeze
49
+
43
50
  module_function
44
51
 
45
52
  # Whether a message from +client_id+ may run as a session command: the
@@ -40,7 +40,7 @@ module Samagotchi
40
40
  # @!attribute annotations [Array<Annotation>] its selection-bar pills
41
41
  # (a bundle's command; empty for the rest)
42
42
  Entry = Struct.new(:id, :name, :description, :mid_turn, :local, :uis, :match, :handler, :source, :annotations,
43
- keyword_init: true) do
43
+ :private_args, keyword_init: true) do
44
44
  def match?(text) = match.call(text)
45
45
 
46
46
  # Whether every line of it runs at once, a turn running or not (D8).
@@ -107,12 +107,13 @@ module Samagotchi
107
107
  # @param annotations [Array<Annotation>] see Entry
108
108
  # @return [Entry]
109
109
  def register(name, description, id: nil, anytime: false, mid_turn: nil, local: false, uis: nil, match: nil,
110
- source: "core", annotations: [], &handler)
110
+ source: "core", annotations: [], private_args: false, &handler)
111
111
  raise ArgumentError, "command #{name} is already registered" unless name_free?(name, local: local, source: source)
112
112
 
113
113
  entry = Entry.new(id: id || name.delete_prefix("/").to_sym, name: name, description: description,
114
114
  mid_turn: mid_turn || (anytime ? :anytime : :refuse), local: local, uis: uis, match: match || default_match(name),
115
- handler: handler, source: source, annotations: annotations.dup.freeze)
115
+ handler: handler, source: source, annotations: annotations.dup.freeze,
116
+ private_args: private_args ? true : false)
116
117
  @entries << entry
117
118
  entry
118
119
  end
@@ -125,6 +126,10 @@ module Samagotchi
125
126
 
126
127
  def command?(line) = !lookup(line).nil?
127
128
 
129
+ # Whether +line+'s command keeps its arguments out of sight
130
+ # (QueuedCommand.mint's private_args: /callback's address).
131
+ def private_args?(line) = lookup(line)&.private_args == true
132
+
128
133
  # Whether every line of +line+'s command runs at once, a turn running
129
134
  # or not (D8). A line whose #mid_turn is :anytime but whose command's
130
135
  # isn't always (/model) runs at once only while a turn runs.
@@ -31,7 +31,13 @@ module Samagotchi
31
31
  # whoever answered (chi answer) ends on it.
32
32
  NOT_CONTINUED = "not_continued"
33
33
 
34
- # @param engine [Engine] announces, records activity, holds the question
34
+ # @param engine [Engine] the session, and the continue steer
35
+ # (#steer_next_turn, #drop_carried_steers)
36
+ # @param turn_state [TurnState] the Engine's (Engine#turn_state): records
37
+ # activity
38
+ # @param question_desk [QuestionDesk] the Engine's (Engine#question_desk):
39
+ # holds the question
40
+ # @param event_log [SessionObserver] the Engine's event log: announces, under its lock
35
41
  # @param turn_flow [TurnFlow] owns the offer
36
42
  # @param run_turn [#call] (prompt, **turn_args, &block) the worker's
37
43
  # run_engine_turn
@@ -41,9 +47,12 @@ module Samagotchi
41
47
  # +participant_refused+ (author → reason or nil): why a participant's
42
48
  # turn may no longer run ("revoked", "outdated", "cap_reached": Worker's check).
43
49
  # @param save [#call] saves the session (a refused Continue's Stop)
44
- def initialize(engine:, turn_flow:, run_turn:, max_iterations:, queue_command: nil, participant_refused: ->(_) {},
50
+ def initialize(engine:, event_log:, turn_state:, question_desk:, turn_flow:, run_turn:, max_iterations:, queue_command: nil, participant_refused: ->(_) {},
45
51
  save: -> {})
46
52
  @engine = engine
53
+ @event_log = event_log
54
+ @turn_state = turn_state
55
+ @question_desk = question_desk
47
56
  @save = save
48
57
  @turn_flow = turn_flow
49
58
  @run_turn = run_turn
@@ -80,11 +89,11 @@ module Samagotchi
80
89
 
81
90
  @continue_steer = nil
82
91
  close("dropped")
83
- @engine.synchronize_events do
92
+ @event_log.synchronize do
84
93
  @turn_flow.drop_offer!
85
- @engine.announce(type: :continue_resolved, decision: "dropped", client_id: origin.client_id)
94
+ @event_log.announce(type: :continue_resolved, decision: "dropped", client_id: origin.client_id)
86
95
  end
87
- @engine.record_activity
96
+ @turn_state.record_activity
88
97
  end
89
98
 
90
99
  # Whether a command's +result+ answered the offer that was pending
@@ -106,7 +115,7 @@ module Samagotchi
106
115
  return refuse_continue(reason, command)
107
116
  end
108
117
 
109
- @engine.announce(type: :continue_resolved, decision: result.decision.to_s, client_id: command.client_id)
118
+ @event_log.announce(type: :continue_resolved, decision: result.decision.to_s, client_id: command.client_id)
110
119
  return if result.resume
111
120
 
112
121
  session = @engine.session
@@ -130,7 +139,7 @@ module Samagotchi
130
139
 
131
140
  # An offer answered without a turn ("no") is activity: the recap
132
141
  # written at the offer (it says the turn stopped) gets rewritten.
133
- @engine.record_activity unless result.resume
142
+ @turn_state.record_activity unless result.resume
134
143
  end
135
144
 
136
145
  # The continue offer was answered yes: resume the conversation without a
@@ -157,7 +166,7 @@ module Samagotchi
157
166
  close("answered")
158
167
  if author && (reason = @participant_refused.call(author))
159
168
  @continue_steer = nil
160
- return @engine.synchronize_events { refuse_continue(reason, command) }
169
+ return @event_log.synchronize { refuse_continue(reason, command) }
161
170
  end
162
171
 
163
172
  steer = @continue_steer
@@ -190,7 +199,7 @@ module Samagotchi
190
199
  return unless @asked
191
200
 
192
201
  @asked = false
193
- @engine.withdraw_question(reason)
202
+ @question_desk.withdraw(reason)
194
203
  end
195
204
 
196
205
  private
@@ -210,9 +219,9 @@ module Samagotchi
210
219
  def refuse_continue(reason, command)
211
220
  author = @engine.session&.last_turn&.participant_author
212
221
  enqueued_id = offer_turn_id
213
- @engine.announce(type: :continue_resolved, decision: "refused", reason: reason.to_s, client_id: command.client_id)
214
- @engine.announce(type: :hook_notice, hook: "participants", level: :warn, between_turns: true,
215
- text: format(REFUSED_NOTICE, who: Steer.participant_id(author), reason: REFUSED_WHY.fetch(reason.to_s, reason.to_s)))
222
+ @event_log.announce(type: :continue_resolved, decision: "refused", reason: reason.to_s, client_id: command.client_id)
223
+ @event_log.announce(type: :hook_notice, hook: "participants", level: :warn, between_turns: true,
224
+ text: format(REFUSED_NOTICE, who: Steer.participant_id(author), reason: REFUSED_WHY.fetch(reason.to_s, reason.to_s)))
216
225
  @turn_flow.abort_continue!
217
226
  session = @engine.session
218
227
  session.last_turn = LastTurn.new(outcome: NOT_CONTINUED, ended_at: Time.now.iso8601(3), enqueued_id: enqueued_id) if session
@@ -233,7 +242,7 @@ module Samagotchi
233
242
  def offer_turn_id = @engine.session&.last_turn&.enqueued_id
234
243
 
235
244
  def announce_offer(offer = @turn_flow.offer)
236
- @engine.announce(type: :continue_offered, context: offer[:context], no_interrupt: offer[:no_interrupt])
245
+ @event_log.announce(type: :continue_offered, context: offer[:context], no_interrupt: offer[:no_interrupt])
237
246
  ask
238
247
  end
239
248
 
@@ -243,8 +252,8 @@ module Samagotchi
243
252
  return unless awaiting?
244
253
 
245
254
  @asked = true
246
- @engine.post_question(question_fields(@turn_flow.offer), on_answer: method(:answered),
247
- on_superseded_close: method(:ask))
255
+ @question_desk.post(question_fields(@turn_flow.offer), on_answer: method(:answered),
256
+ on_superseded_close: method(:ask))
248
257
  end
249
258
 
250
259
  def question_fields(offer)
@@ -17,7 +17,7 @@ module Samagotchi
17
17
  # else its display only, or nothing when the answer is gone.
18
18
  # Writes @block_fix_running, @block_fix_ready, @block_fix_turns (under
19
19
  # @block_fix_mutex; the counter on the turn thread), reads @session,
20
- # @side_judgments, @session_observer.
20
+ # @side_judgments, @event_log.
21
21
  module BlockFixPart
22
22
  # What a pending result knows of its answer: its place in the
23
23
  # conversation, its digest then (Bridge::TurnDrawings.digest), and the
@@ -323,9 +323,9 @@ module Samagotchi
323
323
  ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - result.started) * 1000).round
324
324
  Log.info(:model, "block_fix_#{state}", lang: result.lang, key: result.key, bytes: result.fixed.to_s.bytesize,
325
325
  ms: ms, landed: landed, reason: reason)
326
- @session_observer.notify({ type: :block_fix, turn_id: result.turn_id, key: result.key, lang: result.lang,
327
- state: state, landed: landed, reason: reason, was_digest: was_digest,
328
- digest: digest }.compact)
326
+ @event_log.notify({ type: :block_fix, turn_id: result.turn_id, key: result.key, lang: result.lang,
327
+ state: state, landed: landed, reason: reason, was_digest: was_digest,
328
+ digest: digest }.compact)
329
329
  end
330
330
  end
331
331
  end
@@ -12,17 +12,26 @@ module Samagotchi
12
12
  # ── Cards ───────────────────────────────────────────────────────────────
13
13
 
14
14
  # Show a card in every UI (docs/plugins.md, Cards): {type: :card, id:,
15
- # source:, title:, body:, level:, actions: [{label:, command:}], in_turn:}.
15
+ # source:, title:, body:, level:, actions: [{label:, command:} |
16
+ # {label:, url:}], in_turn:}.
16
17
  # Where it goes (held while the plugins load, an anytime command's, an
17
18
  # init task's, a turn event, else announced) is EventRoutes#route's,
18
19
  # marked in_turn: (CARD_MARKS). A card with the id of an earlier one
19
- # replaces it (btw's "thinking…" → the answer).
20
+ # replaces it (btw's "thinking…" → the answer). +between_turns+: never a
21
+ # running turn's: while one runs it is shown as an anytime command's
22
+ # card is (a sign-in flow's, a plugin thread's that must not land in a
23
+ # turn's block, which the web collapses).
20
24
  # @param source [String] who shows it (a bundle's name)
21
- # @param actions [Array<Hash>] {label:, command:}; a command is a line
22
- # the session runs, as typed (D3)
25
+ # @param actions [Array<Hash>] {label:, command:}, a line the session
26
+ # runs as typed (D3), or {label:, url:}, an http(s) address a UI opens
27
+ # (it sends nothing; Plugin::Card.build checks it)
23
28
  # @return [String] the card's id
24
29
  # @raise [ArgumentError] a card without a title, or a bad action
25
- def show_card(source:, title:, body: "", actions: [], level: :info, id: nil)
30
+ def show_card(source:, title:, body: "", actions: [], level: :info, id: nil, between_turns: false)
31
+ if between_turns && turn_running?
32
+ return running_anytime { show_card(source: source, title: title, body: body, actions: actions, level: level, id: id) }
33
+ end
34
+
26
35
  card = Plugin::Card.build(source: source, title: title, body: body, actions: actions, level: level, id: id)
27
36
  command = Thread.current[running_command_key]
28
37
  card[:command] = command if command
@@ -8,10 +8,10 @@ require_relative "../working_set"
8
8
 
9
9
  module Samagotchi
10
10
  class Engine
11
- # The event log: persistent observers, #announce (ANNOUNCEABLE_EVENTS),
11
+ # The event log: persistent observers, #announce (the log's ANNOUNCEABLE_EVENTS),
12
12
  # the event lock, held announcements, the load events, and the stream
13
13
  # and emit helpers (EventFanout's, forwarded). Writes
14
- # @guardrail_failures_announced; reads @session_observer, @event_fanout,
14
+ # @guardrail_failures_announced; reads @event_log, @event_fanout,
15
15
  # @extension_load, @guardrail_failures, @plugin_failures.
16
16
  module EventsPart
17
17
  # Subscribe a persistent observer to engine events.
@@ -23,38 +23,33 @@ module Samagotchi
23
23
  # @param observer [#call] receives event hashes (with `event_seq:` merged in)
24
24
  # @return [Samagotchi::SessionObserver::SubscribedObserver] handle to unsubscribe
25
25
  def subscribe(observer:)
26
- @session_observer.subscribe(observer: observer)
26
+ @event_log.subscribe(observer: observer)
27
27
  end
28
28
 
29
29
  # Unsubscribe a previously-registered observer.
30
30
  # @param handle [Samagotchi::SessionObserver::SubscribedObserver]
31
31
  # @return [Boolean] whether the observer was removed (nil/unknown never raises)
32
32
  def unsubscribe(handle:)
33
- @session_observer.unsubscribe(handle: handle)
33
+ @event_log.unsubscribe(handle: handle)
34
34
  end
35
35
 
36
36
  # @return [Integer] total engine events emitted so far (locally monotonic)
37
37
  def event_count
38
- @session_observer.event_count
38
+ @event_log.event_count
39
39
  end
40
40
 
41
- # Put a transport-level event into the ordered event log. Unlike turn
42
- # events it reaches only persistent observers (no turn sink, no memory
43
- # capture).
44
- # @param event [Hash] with :type in ANNOUNCEABLE_EVENTS
41
+ # Put a transport-level event into the ordered event log
42
+ # (SessionObserver#announce, which checks the type).
43
+ # @param event [Hash] with :type in SessionObserver::ANNOUNCEABLE_EVENTS
45
44
  # @raise [ArgumentError] for any other type
46
45
  def announce(event)
47
- unless ANNOUNCEABLE_EVENTS.include?(event[:type])
48
- raise ArgumentError, "cannot announce #{event[:type].inspect} (allowed: #{ANNOUNCEABLE_EVENTS.join(", ")})"
49
- end
50
-
51
- @session_observer.notify(event)
46
+ @event_log.announce(event)
52
47
  end
53
48
 
54
49
  # Run the block with the event log held: no event is numbered or
55
50
  # delivered meanwhile, and events the block emits keep their order.
56
51
  def synchronize_events(&)
57
- @session_observer.synchronize(&)
52
+ @event_log.synchronize(&)
58
53
  end
59
54
 
60
55
  def reserve_enqueued_id(id) = @turn_state.reserve_enqueued_id(id)
@@ -228,7 +228,7 @@ module Samagotchi
228
228
  window_source: window.source.to_s, source: "switch" }
229
229
  event = { type: :context_status, usage: usage, bucket: display&.dig(:bucket),
230
230
  context_window_tokens: window&.tokens, context_window_source: window&.source&.to_s }
231
- @session_observer.notify(event)
231
+ @event_log.notify(event)
232
232
  event
233
233
  rescue StandardError => e
234
234
  Log.warn(:model, "switched_context_failed", error: e.class.name, msg: e.message.to_s[0, 200])
@@ -151,6 +151,7 @@ module Samagotchi
151
151
  cancelled: lambda {
152
152
  (task = current_init_task) ? task.cancelled? : active_cancel_controller&.cancelled?
153
153
  },
154
+ current_cancel: -> { (task = current_init_task) ? task.cancel : active_cancel_controller },
154
155
  card: ->(**card) { show_card(**card) },
155
156
  steer: ->(text, label) { steer(text, source: hook_source(label)) },
156
157
  stop_turn: ->(reason, label) { hook_stop_turn(reason, label) },
@@ -173,6 +174,8 @@ module Samagotchi
173
174
  []
174
175
  end,
175
176
  state_dir: -> { session_state_dir },
177
+ secrets_store: ->(bundle) { Plugin::Secrets::FileStore.for_bundle(bundle) },
178
+ sign_in: ->(bundle, **options, &build) { start_sign_in(bundle: bundle, build: build, **options) },
176
179
  scratch: -> { @scratch },
177
180
  setup: -> { SessionSetup.of(@session, forked: true) },
178
181
  # The files whose text the built system prompt holds; [] until a
@@ -29,7 +29,7 @@ module Samagotchi
29
29
  def emit_recap(recap:, generation:, covered: nil, created_at: nil)
30
30
  event = { type: :recap_ready, recap: recap, generation: generation, covered: covered }
31
31
  event[:created_at] = created_at if created_at
32
- @session_observer.notify(event)
32
+ @event_log.notify(event)
33
33
  end
34
34
 
35
35
  # @return [IdleRecap, nil] the idle recap detector, or nil when disabled
@@ -36,7 +36,7 @@ module Samagotchi
36
36
  usage = usage.with(author: side_author(usage.kind)) if usage.author.nil?
37
37
  synchronize_events do
38
38
  block = @metrics.add_side(usage)
39
- @session_observer.notify(type: :side_usage, kind: usage.kind, side: block)
39
+ @event_log.notify(type: :side_usage, kind: usage.kind, side: block)
40
40
  end
41
41
  sid = @metrics.session_id
42
42
  return if sid.nil? || turn_running?