samagotchi 0.181.0 → 0.183.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +93 -1
  3. data/bin/chi +4 -1
  4. data/docs/architecture.md +17 -7
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +58 -10
  8. data/docs/configuration.md +3 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +172 -3
  11. data/docs/internals/bridge.md +23 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +29 -8
  14. data/docs/internals/inline-widgets.md +3 -1
  15. data/docs/internals/prompt-caching.md +9 -1
  16. data/docs/internals/remote-sessions.md +38 -7
  17. data/docs/internals/web-frontend.md +116 -26
  18. data/docs/internals/working-set.md +1 -1
  19. data/docs/mcp-server.md +80 -0
  20. data/docs/plugins.md +308 -21
  21. data/docs/sessions.md +7 -4
  22. data/docs/sub-agent.md +9 -0
  23. data/docs/testing.md +3 -1
  24. data/docs/thin-clients.md +146 -0
  25. data/lib/samagotchi/answer_display.rb +3 -2
  26. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  27. data/lib/samagotchi/block_fix.rb +220 -0
  28. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  29. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  30. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  31. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  32. data/lib/samagotchi/bridge.rb +69 -69
  33. data/lib/samagotchi/bridge_client.rb +9 -0
  34. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  35. data/lib/samagotchi/bundle_command/check.rb +36 -19
  36. data/lib/samagotchi/bundle_command.rb +50 -21
  37. data/lib/samagotchi/bundle_manifest.rb +101 -4
  38. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  40. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  41. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  42. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  43. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  44. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  45. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  46. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  47. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  48. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  49. data/lib/samagotchi/command_intake.rb +7 -0
  50. data/lib/samagotchi/commands/registry.rb +8 -3
  51. data/lib/samagotchi/config.rb +3 -0
  52. data/lib/samagotchi/continue_intent.rb +8 -0
  53. data/lib/samagotchi/continue_offer.rb +24 -15
  54. data/lib/samagotchi/engine/block_fix.rb +332 -0
  55. data/lib/samagotchi/engine/cards.rb +14 -5
  56. data/lib/samagotchi/engine/events.rb +10 -15
  57. data/lib/samagotchi/engine/models.rb +1 -1
  58. data/lib/samagotchi/engine/plugins.rb +3 -0
  59. data/lib/samagotchi/engine/recap.rb +1 -1
  60. data/lib/samagotchi/engine/side_requests.rb +8 -6
  61. data/lib/samagotchi/engine/sign_in.rb +142 -0
  62. data/lib/samagotchi/engine/turn_end.rb +3 -3
  63. data/lib/samagotchi/engine.rb +47 -27
  64. data/lib/samagotchi/engine_snapshots.rb +1 -1
  65. data/lib/samagotchi/events.rb +1 -0
  66. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  67. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  68. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  69. data/lib/samagotchi/hold_stop.rb +4 -4
  70. data/lib/samagotchi/idle_client.rb +10 -6
  71. data/lib/samagotchi/idle_recap.rb +19 -11
  72. data/lib/samagotchi/idle_reminders.rb +7 -5
  73. data/lib/samagotchi/idle_scheduler.rb +7 -10
  74. data/lib/samagotchi/inline_widgets.rb +12 -0
  75. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  76. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  77. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  78. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  79. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  80. data/lib/samagotchi/kernel_loop.rb +7 -5
  81. data/lib/samagotchi/llm/chat_loop.rb +2 -0
  82. data/lib/samagotchi/llm/http.rb +96 -5
  83. data/lib/samagotchi/markdown_parser.rb +28 -0
  84. data/lib/samagotchi/mcp_command.rb +110 -0
  85. data/lib/samagotchi/mcp_server/http.rb +112 -0
  86. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  87. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  88. data/lib/samagotchi/mcp_server/text.rb +155 -0
  89. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  90. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  91. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  92. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  93. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  94. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  95. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  96. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  97. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  98. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  99. data/lib/samagotchi/plugin/api.rb +6 -1
  100. data/lib/samagotchi/plugin/card.rb +36 -11
  101. data/lib/samagotchi/plugin/context.rb +63 -6
  102. data/lib/samagotchi/plugin/http.rb +40 -15
  103. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  104. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  105. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  106. data/lib/samagotchi/plugin/loader.rb +18 -11
  107. data/lib/samagotchi/plugin/secrets.rb +266 -0
  108. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  109. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  110. data/lib/samagotchi/queued_command.rb +28 -4
  111. data/lib/samagotchi/recap_setup.rb +13 -4
  112. data/lib/samagotchi/ref.rb +3 -2
  113. data/lib/samagotchi/relay_verifier.rb +8 -7
  114. data/lib/samagotchi/relay_watcher.rb +4 -4
  115. data/lib/samagotchi/run_options.rb +2 -1
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +244 -0
  118. data/lib/samagotchi/session_access/contract.rb +8 -0
  119. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  120. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  121. data/lib/samagotchi/session_access/exchange.rb +173 -0
  122. data/lib/samagotchi/session_access/local.rb +38 -6
  123. data/lib/samagotchi/session_access/remote.rb +23 -2
  124. data/lib/samagotchi/session_access.rb +1 -0
  125. data/lib/samagotchi/session_chain/delete.rb +39 -81
  126. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  127. data/lib/samagotchi/session_command_catalog.rb +10 -0
  128. data/lib/samagotchi/session_commands.rb +17 -0
  129. data/lib/samagotchi/session_config.rb +4 -4
  130. data/lib/samagotchi/session_delete_command.rb +129 -3
  131. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  132. data/lib/samagotchi/session_manager/listing.rb +4 -4
  133. data/lib/samagotchi/session_manager/removal.rb +38 -12
  134. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  135. data/lib/samagotchi/session_manager.rb +1 -0
  136. data/lib/samagotchi/session_observer.rb +27 -0
  137. data/lib/samagotchi/steer_cut.rb +4 -3
  138. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  139. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  140. data/lib/samagotchi/testing/boundary.rb +4 -0
  141. data/lib/samagotchi/testing/bundle.rb +48 -2
  142. data/lib/samagotchi/testing/fake_http.rb +60 -15
  143. data/lib/samagotchi/testing/host.rb +4 -1
  144. data/lib/samagotchi/testing/recorder.rb +45 -5
  145. data/lib/samagotchi/tools/tool_index.rb +14 -3
  146. data/lib/samagotchi/version.rb +1 -1
  147. data/lib/samagotchi/web/app.rb +20 -6
  148. data/lib/samagotchi/web/ask_routes.rb +292 -0
  149. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  150. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  151. data/lib/samagotchi/web/mcp_route.rb +88 -0
  152. data/lib/samagotchi/web/message_display.rb +6 -1
  153. data/lib/samagotchi/web/participant_view.rb +1 -1
  154. data/lib/samagotchi/web/public/app.js +7 -8
  155. data/lib/samagotchi/web/public/block_fix.js +270 -0
  156. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  157. data/lib/samagotchi/web/public/block_frame.js +77 -13
  158. data/lib/samagotchi/web/public/block_host.js +45 -9
  159. data/lib/samagotchi/web/public/block_regions.js +126 -0
  160. data/lib/samagotchi/web/public/block_renderers.css +12 -0
  161. data/lib/samagotchi/web/public/block_watch.js +16 -2
  162. data/lib/samagotchi/web/public/card.js +22 -9
  163. data/lib/samagotchi/web/public/card_actions.js +21 -0
  164. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  165. data/lib/samagotchi/web/public/card_registry.js +3 -2
  166. data/lib/samagotchi/web/public/data.js +15 -12
  167. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  168. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  169. data/lib/samagotchi/web/public/format.js +3 -0
  170. data/lib/samagotchi/web/public/index.html +52 -7
  171. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  172. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  173. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  174. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  175. data/lib/samagotchi/web/public/refs.js +5 -3
  176. data/lib/samagotchi/web/public/region_hit.js +144 -0
  177. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  178. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  179. data/lib/samagotchi/web/public/session_actions.js +105 -100
  180. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  181. data/lib/samagotchi/web/public/turn_block.js +5 -2
  182. data/lib/samagotchi/web/server.rb +6 -4
  183. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  184. data/lib/samagotchi/web/session_control.rb +84 -30
  185. data/lib/samagotchi/web/session_create.rb +2 -2
  186. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  187. data/lib/samagotchi/worker/child_side.rb +3 -2
  188. data/lib/samagotchi/worker/command_queue.rb +13 -13
  189. data/lib/samagotchi/worker/leave.rb +3 -3
  190. data/lib/samagotchi/worker/scratch.rb +6 -6
  191. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  192. data/lib/samagotchi/worker/startup.rb +3 -3
  193. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  194. data/lib/samagotchi/worker.rb +42 -24
  195. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  196. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  197. data/lib/samagotchi/worker_inbound.rb +12 -7
  198. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  199. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  200. metadata +42 -1
@@ -0,0 +1,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.181.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.
@@ -399,6 +399,9 @@ module Samagotchi
399
399
  # Opt-in: the page checks each finished turn against a reload of it (one full read per turn end) and chi web logs
400
400
  # reload_checked, with reload_mismatch and the kinds that differed (counts only, no content).
401
401
  Entry.new(key: "web.reload_check", yaml_path: %w[web reload_check], type: :bool, default: false, expose: %i[env config cli], lifecycle: :web_start),
402
+ # auto: a block the owner's page can't draw in the newest answer (a chi-ui picks, a bundle's diagram) is asked
403
+ # for again once, on the side, and the answer patched (docs/internals/block-renderers.md); off: it stays source.
404
+ Entry.new(key: "web.block_fix", yaml_path: %w[web block_fix], type: :enum, default: "auto", expose: %i[env config], enum_values: %w[auto off], lifecycle: :web_start),
402
405
  # Quick replies next to Annotate in the page's selection bubble, "|"-separated (a YAML list works too); "" leaves only Annotate.
403
406
  Entry.new(key: "web.annotate_presets", yaml_path: %w[web annotate_presets], type: :string, default: "Agreed|Could you please elaborate?", expose: %i[env config cli], lifecycle: :web_start),
404
407
  # What a file ref (a tool row's file, a diff line) opens on this machine: a preset (vscode, vscode-insiders, cursor, zed, none) or a URL template with {path} and an optional {line} (Web::Editor).
@@ -82,6 +82,14 @@ module Samagotchi
82
82
  end
83
83
  end
84
84
 
85
+ # Whether +id+'s continue lock is held now, without creating its
86
+ # session folder or lock file. Read-only callers use this for a preview.
87
+ def lock_held?(id, state_dir:)
88
+ return false unless Session.valid_id?(id)
89
+
90
+ locked?(File.join(Session.session_dir(id, state_dir: state_dir), LOCK))
91
+ end
92
+
85
93
  # Whether a continue holds the lock at +path+: a shared try that fails.
86
94
  # The try is let go at once (the file is closed).
87
95
  def locked?(path)
@@ -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)