samagotchi 0.183.0 → 0.184.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +40 -1
- data/docs/architecture.md +11 -10
- data/docs/bundles.md +1 -1
- data/docs/configuration.md +2 -1
- data/docs/internals/bridge.md +1 -1
- data/docs/internals/bundles.md +6 -2
- data/docs/internals/engine.md +2 -1
- data/docs/internals/participants.md +1 -1
- data/docs/internals/prompt-caching.md +8 -1
- data/docs/internals/remote-sessions.md +19 -3
- data/docs/internals/web-frontend.md +15 -10
- data/docs/internals/web-push.md +11 -0
- data/docs/internals/working-set.md +238 -6
- data/docs/mcp-server.md +5 -1
- data/docs/memory.md +2 -1
- data/docs/plugins.md +6 -6
- data/docs/scheduling.md +14 -0
- data/docs/sessions.md +1 -1
- data/docs/thin-clients.md +29 -10
- data/lib/samagotchi/bridge_client.rb +12 -4
- data/lib/samagotchi/bundle_command/check.rb +20 -2
- data/lib/samagotchi/bundle_manifest.rb +5 -1
- data/lib/samagotchi/bundles/mcp/http_client.rb +79 -54
- data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
- data/lib/samagotchi/bundles/system/manifest.yml +2 -2
- data/lib/samagotchi/bundles/system/self_map.md +7 -2
- data/lib/samagotchi/engine/session.rb +14 -6
- data/lib/samagotchi/engine/turn_helpers.rb +4 -3
- data/lib/samagotchi/mcp_server/http.rb +3 -3
- data/lib/samagotchi/mcp_server/protocol.rb +23 -4
- data/lib/samagotchi/mcp_server/stdio.rb +1 -0
- data/lib/samagotchi/mcp_server/tools.rb +2 -1
- data/lib/samagotchi/model_notes.rb +34 -12
- data/lib/samagotchi/prompt_files.rb +11 -4
- data/lib/samagotchi/prompt_layout.rb +88 -0
- data/lib/samagotchi/prompt_part.rb +82 -20
- data/lib/samagotchi/reply_wait.rb +6 -3
- data/lib/samagotchi/schedule_command.rb +18 -4
- data/lib/samagotchi/schedules.rb +40 -8
- data/lib/samagotchi/session_access/ask.rb +53 -12
- data/lib/samagotchi/session_access/exchange.rb +5 -2
- data/lib/samagotchi/session_access/local.rb +11 -2
- data/lib/samagotchi/session_inbox.rb +15 -0
- data/lib/samagotchi/session_manager/delivery.rb +8 -4
- data/lib/samagotchi/system_prompt.rb +196 -161
- data/lib/samagotchi/tools/memory.rb +11 -3
- data/lib/samagotchi/turn_stages/warmup.rb +2 -2
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +1 -2
- data/lib/samagotchi/web/ask_routes.rb +89 -19
- data/lib/samagotchi/web/mcp_route.rb +7 -4
- data/lib/samagotchi/web/public/delete_sheet.js +20 -18
- data/lib/samagotchi/web/public/removal_sheet_model.js +3 -4
- data/lib/samagotchi/web/public/running_tasks.js +0 -16
- data/lib/samagotchi/web/public/session_actions.js +0 -9
- data/lib/samagotchi/web/public/working_set_view.js +167 -21
- data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
- data/lib/samagotchi/web/public/ws_peek.js +3 -1
- data/lib/samagotchi/web/public/ws_preview.css +30 -0
- data/lib/samagotchi/web/public/ws_reader.js +7 -3
- data/lib/samagotchi/web/public/ws_sections.js +37 -7
- data/lib/samagotchi/web/push/notifier.rb +33 -6
- data/lib/samagotchi/web/server.rb +1 -1
- data/lib/samagotchi/web/session_hub.rb +26 -4
- data/lib/samagotchi/web/working_set_routes.rb +93 -5
- data/lib/samagotchi/worker_link.rb +2 -2
- data/lib/samagotchi/working_set.rb +162 -90
- data/lib/samagotchi/working_set_locator.rb +221 -0
- data/lib/samagotchi/working_set_own_changes.rb +221 -0
- data/lib/samagotchi/working_set_part.rb +281 -0
- metadata +6 -1
|
@@ -68,6 +68,8 @@ class Plugin
|
|
|
68
68
|
def later(seconds) = with(deadline: deadline + seconds)
|
|
69
69
|
end
|
|
70
70
|
|
|
71
|
+
State = Data.define(:era, :session_id, :protocol)
|
|
72
|
+
|
|
71
73
|
# HttpClient's token: for a server with no token (nil) or a static one
|
|
72
74
|
# (bearer_token_env: the block looks it up at each request and raises
|
|
73
75
|
# Refused when its variable is unset): there is nothing to refresh.
|
|
@@ -85,8 +87,6 @@ class Plugin
|
|
|
85
87
|
def inspect = "#<#{self.class.name.split("::").last}>"
|
|
86
88
|
end
|
|
87
89
|
|
|
88
|
-
attr_reader :era
|
|
89
|
-
|
|
90
90
|
# @param url [String] http(s)
|
|
91
91
|
# @param headers [Hash{String=>String}] sent as given
|
|
92
92
|
# @param token [#call, #refresh_token!] #call → the bearer token, or nil
|
|
@@ -102,9 +102,8 @@ class Plugin
|
|
|
102
102
|
@log = log
|
|
103
103
|
@next_id = 0
|
|
104
104
|
@mutex = Mutex.new
|
|
105
|
-
@
|
|
106
|
-
@
|
|
107
|
-
@protocol = nil
|
|
105
|
+
@renewal = Mutex.new
|
|
106
|
+
@state = State.new(nil, nil, nil)
|
|
108
107
|
end
|
|
109
108
|
|
|
110
109
|
# scheme://host, and the port when it isn't the scheme's: never the
|
|
@@ -119,7 +118,9 @@ class Plugin
|
|
|
119
118
|
"(not a URL)"
|
|
120
119
|
end
|
|
121
120
|
|
|
122
|
-
def
|
|
121
|
+
def era = @mutex.synchronize { @state.era }
|
|
122
|
+
|
|
123
|
+
def inspect = "#<HttpClient #{label} era=#{era || "none"}>"
|
|
123
124
|
|
|
124
125
|
def pretty_print(printer) = printer.text(inspect)
|
|
125
126
|
|
|
@@ -133,55 +134,64 @@ class Plugin
|
|
|
133
134
|
# cancel: (Plugin#stop_of; not stdio's poll), for #request too
|
|
134
135
|
# @return [Hash] what Plugin#info_of reads ("instructions")
|
|
135
136
|
def handshake(timeout:, cancelled:)
|
|
136
|
-
|
|
137
|
-
|
|
137
|
+
# Nothing else runs on a client before its first handshake returns.
|
|
138
|
+
publish(State.new(:discover, nil, nil))
|
|
139
|
+
discover_error = nil
|
|
138
140
|
begin
|
|
139
|
-
result = post("server/discover", {}, Budget.for(timeout), cancelled)
|
|
141
|
+
result = post("server/discover", {}, Budget.for(timeout), cancelled, state: state)
|
|
140
142
|
offered = Array(result["supportedVersions"])
|
|
141
|
-
return result.tap {
|
|
143
|
+
return result.tap { publish(State.new(:modern, nil, nil)) } if offered.include?(MODERN)
|
|
142
144
|
rescue Refused, Client::Timeout, Client::Cancelled, Client::Dead
|
|
143
145
|
raise
|
|
144
146
|
rescue RpcError => e
|
|
145
147
|
offered = Array(e.data.is_a?(Hash) ? e.data["supported"] : nil) if e.code == -32_022
|
|
146
|
-
|
|
148
|
+
discover_error = e if offered.nil? || offered.empty?
|
|
149
|
+
rescue Client::Error => e
|
|
147
150
|
offered = nil
|
|
151
|
+
discover_error = e
|
|
148
152
|
end
|
|
149
|
-
legacy(Budget.for(timeout), cancelled, offered)
|
|
153
|
+
legacy(Budget.for(timeout), cancelled, offered, initial: true, discover_error: discover_error)
|
|
150
154
|
end
|
|
151
155
|
|
|
152
156
|
# @param timeout [Numeric] the whole call's, a re-handshake included
|
|
153
157
|
# @return [Hash] the result
|
|
154
158
|
def request(method, params = nil, timeout:, cancelled: nil)
|
|
155
159
|
budget = Budget.for(timeout)
|
|
156
|
-
|
|
157
|
-
|
|
160
|
+
if state.era == :expired
|
|
161
|
+
@renewal.synchronize { renew(budget, cancelled) if state.era == :expired }
|
|
162
|
+
end
|
|
163
|
+
sent_state = state
|
|
164
|
+
raise Client::Error, "#{method} before the handshake" unless %i[modern legacy].include?(sent_state.era)
|
|
158
165
|
|
|
159
|
-
post(method, params, budget, cancelled)
|
|
166
|
+
post(method, params, budget, cancelled, state: sent_state)
|
|
160
167
|
rescue Expired
|
|
161
|
-
raise if @
|
|
162
|
-
|
|
163
|
-
@
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
168
|
+
raise if @renewal.owned?
|
|
169
|
+
|
|
170
|
+
@renewal.synchronize do
|
|
171
|
+
current = state
|
|
172
|
+
if current.era == :legacy && !current.equal?(sent_state)
|
|
173
|
+
sent_state = current
|
|
174
|
+
else
|
|
175
|
+
renew(budget, cancelled)
|
|
176
|
+
end
|
|
177
|
+
post(method, params, budget, cancelled, state: state)
|
|
169
178
|
end
|
|
170
179
|
end
|
|
171
180
|
|
|
172
181
|
# A legacy session's best-effort DELETE; nothing for the modern era.
|
|
173
182
|
def close
|
|
174
|
-
|
|
183
|
+
snapshot = state
|
|
184
|
+
return nil unless snapshot.era == :legacy && snapshot.session_id
|
|
175
185
|
|
|
176
186
|
# A controller of its own: a cancelled turn's (ctx.http's default) would skip it.
|
|
177
|
-
@http.request("DELETE", @url, headers: headers_for("DELETE", nil), timeout: CLOSE_TIMEOUT,
|
|
187
|
+
@http.request("DELETE", @url, headers: headers_for("DELETE", nil, snapshot), timeout: CLOSE_TIMEOUT,
|
|
178
188
|
cancel: Samagotchi::CancellationController.new)
|
|
179
189
|
nil
|
|
180
190
|
rescue Samagotchi::Plugin::HttpError, Client::Error => e
|
|
181
191
|
@log.call("close_failed", error: e.class.name)
|
|
182
192
|
nil
|
|
183
193
|
ensure
|
|
184
|
-
|
|
194
|
+
publish(snapshot.with(session_id: nil)) if snapshot
|
|
185
195
|
end
|
|
186
196
|
|
|
187
197
|
private
|
|
@@ -190,32 +200,42 @@ class Plugin
|
|
|
190
200
|
# the era :expired, so the next request tries again; its error is the
|
|
191
201
|
# server's state, never the tool's (Unavailable, no schema note).
|
|
192
202
|
def renew(budget, cancelled)
|
|
193
|
-
legacy(budget, cancelled, nil)
|
|
203
|
+
legacy(budget, cancelled, nil, initial: false, discover_error: nil)
|
|
194
204
|
rescue Client::Timeout, Client::Cancelled, Client::Dead, Client::Unavailable
|
|
195
205
|
raise
|
|
196
206
|
rescue Client::Error => e
|
|
197
207
|
raise Client::Unavailable, e.message
|
|
198
208
|
ensure
|
|
199
|
-
|
|
209
|
+
publish(State.new(:expired, nil, nil)) unless state.era == :legacy
|
|
200
210
|
end
|
|
201
211
|
|
|
202
212
|
# initialize, then notifications/initialized, in one +budget+.
|
|
203
|
-
def legacy(budget, cancelled, offered)
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
213
|
+
def legacy(budget, cancelled, offered, initial:, discover_error:)
|
|
214
|
+
in_flight = State.new(:initialize, nil, nil)
|
|
215
|
+
publish(in_flight) if initial
|
|
216
|
+
initialized = false
|
|
217
|
+
result, session_id = post("initialize", { protocolVersion: LEGACY, capabilities: {},
|
|
218
|
+
clientInfo: { name: "chi", version: Samagotchi::VERSION } },
|
|
219
|
+
budget, cancelled, state: in_flight, session: true)
|
|
220
|
+
initialized = true
|
|
221
|
+
in_flight = State.new(:legacy, session_id,
|
|
222
|
+
result["protocolVersion"].is_a?(String) ? result["protocolVersion"] : LEGACY)
|
|
223
|
+
publish(in_flight)
|
|
224
|
+
post("notifications/initialized", nil, budget, cancelled, state: in_flight, notification: true)
|
|
212
225
|
result
|
|
213
226
|
rescue Client::Timeout, Client::Cancelled, Client::Dead, Refused
|
|
214
227
|
raise
|
|
215
228
|
rescue Client::Error => e
|
|
216
|
-
|
|
229
|
+
publish(State.new(:expired, nil, nil)) unless initial || initialized
|
|
230
|
+
if offered && !offered.empty?
|
|
231
|
+
raise Client::Unavailable, "speaks MCP #{offered.join(", ")}, not #{MODERN} or #{LEGACY} (#{e.message})"
|
|
232
|
+
end
|
|
233
|
+
raise if discover_error.nil? || discover_error.message == e.message
|
|
234
|
+
|
|
235
|
+
message = "#{e.message} (server/discover: #{discover_error.message})"
|
|
236
|
+
raise e.class, message if [Client::Error, Client::Unavailable].include?(e.class)
|
|
217
237
|
|
|
218
|
-
raise Client::Unavailable,
|
|
238
|
+
raise Client::Unavailable, message
|
|
219
239
|
end
|
|
220
240
|
|
|
221
241
|
# One message on the wire, and its answer, in what is left of +budget+.
|
|
@@ -223,20 +243,20 @@ class Plugin
|
|
|
223
243
|
# sends the message again; the time a renew takes, before the message or
|
|
224
244
|
# after its 401, isn't the budget's.
|
|
225
245
|
# @return [Hash, nil] the result (nil for a notification)
|
|
226
|
-
def post(method, params, budget, cancelled, notification: false, session: false, renewed: false)
|
|
246
|
+
def post(method, params, budget, cancelled, state:, notification: false, session: false, renewed: false)
|
|
227
247
|
id = notification ? nil : @mutex.synchronize { @next_id += 1 }
|
|
228
|
-
message = { jsonrpc: "2.0", id: id, method: method, params: params_for(params) }.compact
|
|
248
|
+
message = { jsonrpc: "2.0", id: id, method: method, params: params_for(params, state) }.compact
|
|
229
249
|
asked = monotonic
|
|
230
|
-
headers = headers_for(method, params)
|
|
250
|
+
headers = headers_for(method, params, state)
|
|
231
251
|
budget = budget.later(monotonic - asked)
|
|
232
252
|
raise Client::Timeout, timed_out(method, budget) if (left = budget.left) <= 0
|
|
233
253
|
|
|
234
254
|
timer = Samagotchi::CancellationController.new
|
|
235
255
|
budgeted(cancelled, timer, left) do
|
|
236
256
|
@http.stream("POST", @url, body: JSON.generate(message), headers: headers, timeout: [left, 0.05].max, cancel: timer) do |res|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
257
|
+
refuse(res, headers.keys.any? { |name| name.casecmp?("authorization") }, state) unless res.ok?
|
|
258
|
+
result = answer(res, id)
|
|
259
|
+
session ? [result, res.headers["mcp-session-id"]] : result
|
|
240
260
|
end
|
|
241
261
|
end
|
|
242
262
|
rescue Refused => e
|
|
@@ -248,7 +268,8 @@ class Plugin
|
|
|
248
268
|
raise unless @token.refresh_token!(sent)
|
|
249
269
|
|
|
250
270
|
@log.call("token_renewed")
|
|
251
|
-
post(method, params, budget.later(monotonic - asked), cancelled,
|
|
271
|
+
post(method, params, budget.later(monotonic - asked), cancelled, state: state,
|
|
272
|
+
notification: notification, session: session, renewed: true)
|
|
252
273
|
rescue Samagotchi::Plugin::HttpCancelled
|
|
253
274
|
raise Client::Timeout, timed_out(method, budget) if timer&.reason == :budget
|
|
254
275
|
|
|
@@ -330,14 +351,18 @@ class Plugin
|
|
|
330
351
|
result
|
|
331
352
|
end
|
|
332
353
|
|
|
354
|
+
def state = @mutex.synchronize { @state }
|
|
355
|
+
|
|
356
|
+
def publish(value) = @mutex.synchronize { @state = value }
|
|
357
|
+
|
|
333
358
|
# A status that isn't 2xx, in words; never its body unless it is a
|
|
334
359
|
# JSON-RPC error.
|
|
335
|
-
def refuse(res, token_sent)
|
|
360
|
+
def refuse(res, token_sent, state)
|
|
336
361
|
status = res.status
|
|
337
362
|
raise Client::Unavailable, "redirected (#{status})#{redirect_to(res)}: set url: to the new address" if status.between?(300, 399)
|
|
338
363
|
raise Refused.new(token_sent ? "refused the token (401)" : "needs a token or sign-in (401)", status: 401) if status == 401
|
|
339
364
|
raise Refused.new("refused (403)", status: 403) if status == 403
|
|
340
|
-
raise Expired, "the session expired (404)" if status == 404 &&
|
|
365
|
+
raise Expired, "the session expired (404)" if status == 404 && state.era == :legacy && state.session_id
|
|
341
366
|
|
|
342
367
|
message = error_body(res) if content_type(res) == "application/json"
|
|
343
368
|
raise RpcError, message["error"] if message.is_a?(Hash) && message["error"].is_a?(Hash) && message["error"].key?("code")
|
|
@@ -367,8 +392,8 @@ class Plugin
|
|
|
367
392
|
nil
|
|
368
393
|
end
|
|
369
394
|
|
|
370
|
-
def params_for(params)
|
|
371
|
-
return params unless %i[discover modern].include?(
|
|
395
|
+
def params_for(params, state)
|
|
396
|
+
return params unless %i[discover modern].include?(state.era)
|
|
372
397
|
|
|
373
398
|
given = (params || {}).transform_keys(&:to_s)
|
|
374
399
|
given.merge("_meta" => meta.merge(given["_meta"].is_a?(Hash) ? given["_meta"] : {}))
|
|
@@ -381,19 +406,19 @@ class Plugin
|
|
|
381
406
|
end
|
|
382
407
|
|
|
383
408
|
# The config's headers, then chi's own (the config can't name them).
|
|
384
|
-
def headers_for(method, params)
|
|
409
|
+
def headers_for(method, params, state)
|
|
385
410
|
headers = @headers.merge("Accept" => ACCEPT, "Content-Type" => "application/json")
|
|
386
411
|
token = @token.call
|
|
387
412
|
headers["Authorization"] = "Bearer #{token}" if token
|
|
388
|
-
case
|
|
413
|
+
case state.era
|
|
389
414
|
when :discover, :modern
|
|
390
415
|
headers["MCP-Protocol-Version"] = MODERN
|
|
391
416
|
headers["Mcp-Method"] = method
|
|
392
417
|
name = params.is_a?(Hash) ? (params[:name] || params["name"]) : nil
|
|
393
418
|
headers["Mcp-Name"] = name.to_s if method == "tools/call" && name
|
|
394
419
|
when :legacy
|
|
395
|
-
headers["MCP-Protocol-Version"] =
|
|
396
|
-
headers["Mcp-Session-Id"] =
|
|
420
|
+
headers["MCP-Protocol-Version"] = state.protocol
|
|
421
|
+
headers["Mcp-Session-Id"] = state.session_id if state.session_id
|
|
397
422
|
end
|
|
398
423
|
headers
|
|
399
424
|
end
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: mcp
|
|
3
|
-
version: 0.9.
|
|
3
|
+
version: 0.9.1
|
|
4
4
|
scope: system
|
|
5
5
|
description: "Tools from MCP servers (stdio or HTTP): each server in config.yml bundles: mcp: servers: runs for the session; their tools go into chi's tool index: the model searches them with find_tools and calls one with call_tool (<server>/<tool>); /mcp lists them"
|
|
6
6
|
trust_level: reviewed
|
|
@@ -11,7 +11,7 @@ plugin:
|
|
|
11
11
|
# Loaded in this order, before plugin.rb (HttpClient's errors subclass Client's, OAuth's HttpClient's).
|
|
12
12
|
parts:
|
|
13
13
|
client.rb: sha256:19fcca8ded80d45bdfb75715a8c14ac16fb6edae9aa49a5bb99619a021378fdf
|
|
14
|
-
http_client.rb: sha256:
|
|
14
|
+
http_client.rb: sha256:f6a1f423dfdeb436c396b8d88bbafe57a32a549e9d342e3b9a17fc8776cb0991
|
|
15
15
|
oauth.rb: sha256:c779e8e7971715c15494b8e755f4a1cff1b4358b96a3ef8db6b330f066c0f152
|
|
16
16
|
tools.rb: sha256:607743a06f191dc24b6aa032e67ed6c95a75cb27310361f6572ca15d5dc50635
|
|
17
17
|
content.rb: sha256:28461822ea1181c3abe790d3f01391babe6b1d974d4606117c42ba1da209b132
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: samagotchi-system
|
|
3
|
-
version: 0.
|
|
3
|
+
version: 0.184.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
|
-
self_map.md: sha256:
|
|
8
|
+
self_map.md: sha256:f741a8280214298cc5322c06a081995a3e1de139cfc56530925c13c59546d6da
|
|
9
9
|
config_modification_protocol.md: sha256:03fdf3ea3138449bc73f73eaa5604cc5d702777c20499ec13ca32b7696e6d37f
|
|
10
10
|
memory_guide.md: sha256:272443ff8292631b28239cb8431d6e8dd19aa23fc53d05e1a10c11696a0a5d8d
|
|
11
11
|
delegated.md: sha256:a0d6ddcd4a8be06526d964898611775fd251cfd9d145a9d16afaccaa503597bd
|
|
@@ -55,7 +55,9 @@
|
|
|
55
55
|
commands (`anytime:` ones run mid-turn), model tools (they can return images I see), hooks,
|
|
56
56
|
cards, side answers (`ask_model`), System 1 judgments (`chi.judgment`, `ctx.judge`), HTTP calls (`ctx.http`),
|
|
57
57
|
child sessions and services (e.g. MCP server processes). Shipped: `btw` (`/btw` side question),
|
|
58
|
-
`mcp` (MCP server tools, searched with find_tools and called with call_tool; a screenshot comes as a picture; a toolkit's
|
|
58
|
+
`mcp` (MCP server tools, searched with find_tools and called with call_tool; a screenshot comes as a picture; a toolkit's
|
|
59
|
+
undeclared built-ins too, as chi/<tool>; remote servers too, one answering 401 needs the user's `/mcp login NAME`,
|
|
60
|
+
and `/callback ADDRESS` is theirs to paste, never the model's), `guardrails` (rules), `known-names` (typo guard), `source-links`
|
|
59
61
|
(turns source refs like JIRA-123 in an answer into links in the web, and a one-line note), `loop-guard`
|
|
60
62
|
(denies a repeated tool call with the same result, stops the turn after a few, and cuts thinking that
|
|
61
63
|
repeats itself, asking me again), `check-in` (after N tool
|
|
@@ -66,10 +68,13 @@
|
|
|
66
68
|
tell the user to restart the session. The plugin API: `docs/plugins.md`; what each shipped bundle does: `docs/bundles.md`. Writing one: read
|
|
67
69
|
`docs/bundle-authoring.md` in my source dir first.
|
|
68
70
|
|
|
71
|
+
An MCP host or a script can drive me: `docs/mcp-server.md`, `docs/thin-clients.md`.
|
|
72
|
+
|
|
69
73
|
## Where things live (relative to the source dir)
|
|
70
74
|
- `docs/`: `cli.md` (flags, subcommands, the terminal's commands), `configuration.md` (config.yml keys,
|
|
71
75
|
hosts, the server api), `hooks.md` (hook events table), `plugins.md` (plugin API), `bundles.md` (each shipped bundle: btw, mcp, cost-cap…),
|
|
72
|
-
`guardrails.md`, `memory.md`, `sessions.md`. `README.md` is only the
|
|
76
|
+
`guardrails.md`, `memory.md`, `sessions.md`, `mcp-server.md`, `thin-clients.md`, `sub-agent.md`. `README.md` is only the
|
|
77
|
+
quickstart.
|
|
73
78
|
- `lib/samagotchi/tools/<tool>.rb`: each tool's real limits and defaults (e.g. `execute.rb`,
|
|
74
79
|
`output_guardrails.rb`). Tool descriptions are summaries, not the spec.
|
|
75
80
|
- A tool that isn't in `lib/samagotchi/tools/` comes from an installed bundle's plugin
|
|
@@ -77,18 +77,26 @@ module Samagotchi
|
|
|
77
77
|
# a level change builds it again. A build that
|
|
78
78
|
# misses the cache names the model and the level through its own
|
|
79
79
|
# lambdas (#model_identity, #turn_thinking), which resolve again.
|
|
80
|
-
|
|
80
|
+
# +record+: false builds without recording (the turn-end warm-up's
|
|
81
|
+
# prompt, which nothing sends as the session's: the session keeps the
|
|
82
|
+
# parts, notes and memory index of the prompt its turn sent).
|
|
83
|
+
def system_prompt(model = nil, record: true)
|
|
81
84
|
model ||= effective_model
|
|
82
85
|
chat = model.chat?
|
|
83
86
|
level = chat ? nil : @model_settings.thinking_level(model)
|
|
84
|
-
|
|
87
|
+
# One Built: a #reset! on another thread right after the build leaves it whole.
|
|
88
|
+
built = @prompt_builder.built_for(chat: chat, thinking: level,
|
|
89
|
+
layers: model.llm_context_layers(@model_settings.llm_context_session_args),
|
|
90
|
+
record: record)
|
|
91
|
+
return built.prompt unless record
|
|
92
|
+
|
|
85
93
|
# The memory indexes this prompt holds: /stats, the snapshot, analytics.json.
|
|
86
|
-
@metrics.memory_index =
|
|
94
|
+
@metrics.memory_index = built.memory_index
|
|
87
95
|
# The model notes it carries: the session records them (/stats, /model, the web).
|
|
88
|
-
record_prompt_notes(
|
|
96
|
+
record_prompt_notes(built.notes)
|
|
89
97
|
# And the sizes of its parts (PromptPart), for the web's head view.
|
|
90
|
-
record_prompt_parts(
|
|
91
|
-
prompt
|
|
98
|
+
record_prompt_parts(built.prompt_parts)
|
|
99
|
+
built.prompt
|
|
92
100
|
end
|
|
93
101
|
|
|
94
102
|
# The base prompt (specs, plugins' declarations).
|
|
@@ -49,12 +49,13 @@ module Samagotchi
|
|
|
49
49
|
|
|
50
50
|
# The stage over the kernel and the Engine's PromptWarmup (built in
|
|
51
51
|
# #initialize, once the kernel and the reminder queue are). Its one
|
|
52
|
-
# callable is the system prompt, built late
|
|
53
|
-
# host's probe goes with
|
|
52
|
+
# callable is the system prompt, built late and not recorded (the
|
|
53
|
+
# session keeps the parts its turn sent); the host's probe goes with
|
|
54
|
+
# each call (#next_turn_waiting, set after).
|
|
54
55
|
def build_turn_warmup
|
|
55
56
|
TurnStages::Warmup.new(prompt_warmup: @prompt_warmup, kernel: @kernel, turn_state: @turn_state,
|
|
56
57
|
model_settings: @model_settings, reminder_queue: @reminder_queue,
|
|
57
|
-
system_prompt: ->(model) { system_prompt(model) })
|
|
58
|
+
system_prompt: ->(model) { system_prompt(model, record: false) })
|
|
58
59
|
end
|
|
59
60
|
private :build_turn_warmup
|
|
60
61
|
|
|
@@ -59,7 +59,7 @@ module Samagotchi
|
|
|
59
59
|
|
|
60
60
|
def header_refusal(env, message)
|
|
61
61
|
params = message["params"].is_a?(Hash) ? message["params"] : {}
|
|
62
|
-
id = message
|
|
62
|
+
id = Protocol.request_id(message)
|
|
63
63
|
version = env["HTTP_MCP_PROTOCOL_VERSION"]
|
|
64
64
|
meta_version = params.dig("_meta", VERSION_META)
|
|
65
65
|
unless version == meta_version
|
|
@@ -86,13 +86,13 @@ module Samagotchi
|
|
|
86
86
|
|
|
87
87
|
session = env["HTTP_MCP_SESSION_ID"]
|
|
88
88
|
unless session.is_a?(String) && SESSION_ID.match?(session)
|
|
89
|
-
return Protocol.error_body(message
|
|
89
|
+
return Protocol.error_body(Protocol.request_id(message), Protocol::INVALID_REQUEST, "Bad Request: Missing session ID")
|
|
90
90
|
end
|
|
91
91
|
|
|
92
92
|
version = env["HTTP_MCP_PROTOCOL_VERSION"]
|
|
93
93
|
return nil if version.nil? || LEGACY_VERSIONS.include?(version)
|
|
94
94
|
|
|
95
|
-
Protocol.error_body(message
|
|
95
|
+
Protocol.error_body(Protocol.request_id(message), Protocol::INVALID_REQUEST,
|
|
96
96
|
"Bad Request: Unsupported protocol version #{version} (supported: #{LEGACY_VERSIONS.join(", ")})")
|
|
97
97
|
end
|
|
98
98
|
|
|
@@ -130,6 +130,18 @@ module Samagotchi
|
|
|
130
130
|
{ jsonrpc: "2.0", id: id, error: error }
|
|
131
131
|
end
|
|
132
132
|
|
|
133
|
+
def self.valid_id?(message)
|
|
134
|
+
return false unless message.is_a?(Hash)
|
|
135
|
+
return true unless message.key?("id")
|
|
136
|
+
|
|
137
|
+
id = message["id"]
|
|
138
|
+
id.is_a?(String) || id.nil? || id.is_a?(Integer) || (id.is_a?(Float) && id.finite?)
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def self.request_id(message)
|
|
142
|
+
valid_id?(message) && message.key?("id") ? message["id"] : nil
|
|
143
|
+
end
|
|
144
|
+
|
|
133
145
|
# @param tools [#list, #call]
|
|
134
146
|
# @param instructions [String, nil] what the server says it is
|
|
135
147
|
# @param name [String] serverInfo's name
|
|
@@ -156,17 +168,24 @@ module Samagotchi
|
|
|
156
168
|
def handle(message, era: nil)
|
|
157
169
|
era ||= self.class.era_of(message)
|
|
158
170
|
unless message.is_a?(Hash) && message["jsonrpc"] == "2.0"
|
|
159
|
-
return error(
|
|
171
|
+
return error(self.class.request_id(message), INVALID_REQUEST, "Invalid Request", era)
|
|
172
|
+
end
|
|
173
|
+
return nil if message.key?("result") || message.key?("error")
|
|
174
|
+
unless message.key?("method")
|
|
175
|
+
return error(self.class.request_id(message), INVALID_REQUEST, "Invalid Request", era)
|
|
160
176
|
end
|
|
161
|
-
return nil unless message.key?("id")
|
|
177
|
+
return nil unless message.key?("id")
|
|
162
178
|
|
|
163
|
-
id = message
|
|
179
|
+
id = self.class.request_id(message)
|
|
164
180
|
method = message["method"]
|
|
165
181
|
params = message.fetch("params", {})
|
|
166
182
|
return error(id, INVALID_REQUEST, "Invalid Request", era) unless method.is_a?(String) && params.is_a?(Hash)
|
|
167
183
|
if params.key?("_meta") && !params["_meta"].is_a?(Hash)
|
|
168
184
|
return error(id, INVALID_REQUEST, "Invalid Request: params._meta is an object", era)
|
|
169
185
|
end
|
|
186
|
+
unless self.class.valid_id?(message)
|
|
187
|
+
return error(nil, INVALID_REQUEST, "Invalid Request: id is a string, a number or null", era)
|
|
188
|
+
end
|
|
170
189
|
|
|
171
190
|
# A modern connection's initialize is -32601 whatever it names.
|
|
172
191
|
if era == :modern && method != "initialize" && (refused = version_refusal(id, params))
|
|
@@ -175,7 +194,7 @@ module Samagotchi
|
|
|
175
194
|
|
|
176
195
|
dispatch(id, method, params, era)
|
|
177
196
|
rescue StandardError => e
|
|
178
|
-
error(
|
|
197
|
+
error(self.class.request_id(message), INTERNAL_ERROR, "Internal error: #{e.message}", era)
|
|
179
198
|
end
|
|
180
199
|
|
|
181
200
|
private
|
|
@@ -61,6 +61,7 @@ module Samagotchi
|
|
|
61
61
|
|
|
62
62
|
def lock_era(message)
|
|
63
63
|
return if @era || !message.is_a?(Hash) || !message.key?("id") || !message["method"].is_a?(String)
|
|
64
|
+
return unless Protocol.valid_id?(message)
|
|
64
65
|
|
|
65
66
|
@era = Protocol.era_of(message)
|
|
66
67
|
@log&.call("mcp: #{@era} era (#{message["method"]})")
|
|
@@ -23,7 +23,8 @@ module Samagotchi
|
|
|
23
23
|
# well inside Claude Code HTTP's 60 s and Codex's 300 s).
|
|
24
24
|
SLICE = 25
|
|
25
25
|
# The most seconds a chi_ask or a chi_answer takes in all
|
|
26
|
-
# (Web::AskRoutes::ASK_MAX_SECONDS)
|
|
26
|
+
# (Web::AskRoutes::ASK_MAX_SECONDS); under --remote about a minute for
|
|
27
|
+
# a slow worker (the other chi web's routes make their own tries).
|
|
27
28
|
CAP = 35
|
|
28
29
|
LIST_LIMIT = 20
|
|
29
30
|
LIST_MAX = 50
|
|
@@ -120,29 +120,51 @@ module Samagotchi
|
|
|
120
120
|
return nil unless entries
|
|
121
121
|
return nil unless ModelMatch.match?(entries, name: name, key: key, small: small)
|
|
122
122
|
|
|
123
|
-
body =
|
|
124
|
-
return nil
|
|
125
|
-
|
|
126
|
-
body = with_overlay(body, stem, scope, [key, fallback_key], env: env)
|
|
123
|
+
body = body_at(path, [key, fallback_key], dir: Tools::MemoryRead.memories_dir(scope, env: env))
|
|
124
|
+
return nil unless body
|
|
127
125
|
|
|
128
126
|
Note.new(name: stem, scope: scope, body: body, chars: body.length, digest: Digest::SHA256.hexdigest(body)[0, 12])
|
|
129
127
|
rescue StandardError
|
|
130
128
|
nil
|
|
131
129
|
end
|
|
132
130
|
|
|
131
|
+
# A note's body as the prompt carries it: the file at +path+ without
|
|
132
|
+
# its models: line, stripped, its model overlay in +dir+ (the note's
|
|
133
|
+
# scope's folder) appended (#with_overlay) for the first of +keys+ that
|
|
134
|
+
# has one; nil when the body is empty. The prompt's build (#for) and the
|
|
135
|
+
# working set's re-fetch of a note part (with the saved keys and dir).
|
|
136
|
+
def body_at(path, keys, dir:)
|
|
137
|
+
body = File.read(path, encoding: "UTF-8").sub(/\A[^\n]*\n?/, "").strip
|
|
138
|
+
return nil if body.empty?
|
|
139
|
+
|
|
140
|
+
with_overlay(body, File.basename(path, ".md"), keys, dir: dir)
|
|
141
|
+
end
|
|
142
|
+
|
|
133
143
|
# The note's model overlay appended as memory_read appends one: the
|
|
134
144
|
# key's, else the fallback key's. The file is read by its own path, not
|
|
135
|
-
# by name through memory_read (whose names are comma lists). +
|
|
136
|
-
#
|
|
137
|
-
def with_overlay(body, stem,
|
|
145
|
+
# by name through memory_read (whose names are comma lists). +dir+: the
|
|
146
|
+
# scope's folder the overlay sits in.
|
|
147
|
+
def with_overlay(body, stem, keys, dir:)
|
|
148
|
+
overlay, overlay_key = overlay_path(stem, keys, dir: dir)
|
|
149
|
+
return body unless overlay
|
|
150
|
+
|
|
151
|
+
# The key as given in the label (prompt bytes), stripped in the path.
|
|
152
|
+
"#{body}#{Tools::MemoryRead::SEPARATOR}Model-specific guidance (#{overlay_key}):\n" \
|
|
153
|
+
"#{File.read(overlay, encoding: "UTF-8").strip}"
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# The note +stem+'s model overlay file in +dir+ for the first of +keys+
|
|
157
|
+
# that has one: [path, the key as given (unstripped)], or nil. The
|
|
158
|
+
# build (#with_overlay) and the working set's files of a note part
|
|
159
|
+
# (WorkingSet::Locator#composed).
|
|
160
|
+
def overlay_path(stem, keys, dir:)
|
|
138
161
|
keys.compact.each do |overlay_key|
|
|
139
|
-
|
|
140
|
-
next unless overlay && File.file?(overlay)
|
|
162
|
+
next if overlay_key.to_s.strip.empty?
|
|
141
163
|
|
|
142
|
-
|
|
143
|
-
|
|
164
|
+
overlay = File.join(dir, "#{stem}.#{overlay_key.to_s.strip}.md")
|
|
165
|
+
return [overlay, overlay_key] if File.file?(overlay)
|
|
144
166
|
end
|
|
145
|
-
|
|
167
|
+
nil
|
|
146
168
|
end
|
|
147
169
|
|
|
148
170
|
# A model overlay of a note (`model_notes_a.<key>.md`) is read with
|
|
@@ -117,11 +117,18 @@ module Samagotchi
|
|
|
117
117
|
# the file is empty or can't be read.
|
|
118
118
|
# @return [String, nil]
|
|
119
119
|
def section(path, header)
|
|
120
|
-
content =
|
|
121
|
-
|
|
120
|
+
content = content(path)
|
|
121
|
+
content && "#{header}\n#{content}"
|
|
122
|
+
end
|
|
122
123
|
|
|
123
|
-
|
|
124
|
-
|
|
124
|
+
# +path+'s text as the prompt carries it under its header: stripped;
|
|
125
|
+
# nil when empty or unreadable. The prompt's build (#section) and the
|
|
126
|
+
# working set's re-fetch of an AGENTS.md part.
|
|
127
|
+
# @return [String, nil]
|
|
128
|
+
def content(path)
|
|
129
|
+
content = File.read(path, encoding: "UTF-8").strip
|
|
130
|
+
content.empty? ? nil : content
|
|
131
|
+
rescue StandardError # degrade-ok: an unreadable file is left out of the prompt, as before
|
|
125
132
|
nil
|
|
126
133
|
end
|
|
127
134
|
end
|