samagotchi 0.191.0 → 0.193.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 (141) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +91 -1
  3. data/docs/architecture.md +8 -7
  4. data/docs/bundles.md +46 -29
  5. data/docs/cli.md +37 -15
  6. data/docs/configuration.md +10 -4
  7. data/docs/context.md +8 -5
  8. data/docs/guardrails.md +9 -4
  9. data/docs/internals/bridge.md +3 -1
  10. data/docs/internals/bundles.md +2 -2
  11. data/docs/internals/inline-widgets.md +2 -1
  12. data/docs/internals/pages.md +4 -4
  13. data/docs/internals/participants.md +6 -8
  14. data/docs/internals/peers.md +75 -22
  15. data/docs/internals/prompt-caching.md +2 -1
  16. data/docs/internals/remote-sessions.md +9 -0
  17. data/docs/internals/session-lifecycle.md +36 -21
  18. data/docs/internals/web-frontend.md +195 -25
  19. data/docs/internals/working-set.md +5 -1
  20. data/docs/peers.md +71 -22
  21. data/docs/plugins.md +7 -4
  22. data/docs/releasing.md +30 -2
  23. data/docs/scheduling.md +10 -3
  24. data/docs/sessions.md +3 -3
  25. data/docs/testing.md +36 -5
  26. data/docs/thin-clients.md +114 -12
  27. data/lib/samagotchi/bridge.rb +2 -3
  28. data/lib/samagotchi/bundles/claude-peer/manifest.yml +2 -2
  29. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +33 -17
  30. data/lib/samagotchi/bundles/codex-peer/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +34 -17
  32. data/lib/samagotchi/bundles/coordinator/manifest.yml +2 -2
  33. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +31 -0
  34. data/lib/samagotchi/bundles/mcp/manifest.yml +4 -2
  35. data/lib/samagotchi/bundles/mcp/plugin.rb +7 -405
  36. data/lib/samagotchi/bundles/mcp/server_config.rb +158 -0
  37. data/lib/samagotchi/bundles/mcp/sign_in.rb +261 -0
  38. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  39. data/lib/samagotchi/client_id.rb +2 -19
  40. data/lib/samagotchi/compat.rb +6 -5
  41. data/lib/samagotchi/config.rb +7 -0
  42. data/lib/samagotchi/continue_offer.rb +13 -1
  43. data/lib/samagotchi/delivery.rb +3 -7
  44. data/lib/samagotchi/engine/models.rb +17 -0
  45. data/lib/samagotchi/engine/plugins.rb +2 -0
  46. data/lib/samagotchi/guardrails/pair_boundary.rb +49 -18
  47. data/lib/samagotchi/jsonl_store.rb +13 -2
  48. data/lib/samagotchi/llm/anthropic_messages.rb +11 -0
  49. data/lib/samagotchi/llm/openai_chat.rb +5 -0
  50. data/lib/samagotchi/llm/prompt_cache.rb +5 -0
  51. data/lib/samagotchi/pages/launch.rb +1 -1
  52. data/lib/samagotchi/peer_cold.rb +92 -0
  53. data/lib/samagotchi/peer_command.rb +24 -9
  54. data/lib/samagotchi/peer_continue.rb +32 -16
  55. data/lib/samagotchi/peer_exchanges.rb +7 -0
  56. data/lib/samagotchi/peer_mailbox.rb +21 -4
  57. data/lib/samagotchi/peer_receipts.rb +33 -6
  58. data/lib/samagotchi/peer_say.rb +34 -16
  59. data/lib/samagotchi/plugin/api.rb +2 -1
  60. data/lib/samagotchi/plugin/context.rb +13 -1
  61. data/lib/samagotchi/plugin/peer.rb +118 -53
  62. data/lib/samagotchi/plugin/peers.rb +13 -6
  63. data/lib/samagotchi/schedule_command.rb +1 -0
  64. data/lib/samagotchi/schedules/prune_part.rb +32 -0
  65. data/lib/samagotchi/schedules.rb +14 -9
  66. data/lib/samagotchi/session.rb +7 -0
  67. data/lib/samagotchi/session_access/local.rb +98 -37
  68. data/lib/samagotchi/session_access/remote.rb +1 -1
  69. data/lib/samagotchi/session_access/remote_peers.rb +3 -3
  70. data/lib/samagotchi/session_chain/links.rb +8 -3
  71. data/lib/samagotchi/session_continue.rb +15 -7
  72. data/lib/samagotchi/session_lifecycle.rb +4 -0
  73. data/lib/samagotchi/session_manager/delivery.rb +0 -6
  74. data/lib/samagotchi/session_manager/lifecycle.rb +30 -17
  75. data/lib/samagotchi/session_manager/listing.rb +2 -1
  76. data/lib/samagotchi/session_manager/removal.rb +7 -5
  77. data/lib/samagotchi/session_manager/spawn.rb +8 -4
  78. data/lib/samagotchi/session_manager.rb +4 -0
  79. data/lib/samagotchi/session_row.rb +2 -0
  80. data/lib/samagotchi/session_stores.rb +16 -11
  81. data/lib/samagotchi/session_transition.rb +61 -15
  82. data/lib/samagotchi/system_one/runs.rb +5 -2
  83. data/lib/samagotchi/testing/boundary.rb +0 -1
  84. data/lib/samagotchi/testing/host.rb +1 -0
  85. data/lib/samagotchi/testing/recorder.rb +3 -0
  86. data/lib/samagotchi/tools/cancel_schedule.rb +10 -6
  87. data/lib/samagotchi/version.rb +1 -1
  88. data/lib/samagotchi/web/app.rb +3 -1
  89. data/lib/samagotchi/web/ask_create.rb +138 -0
  90. data/lib/samagotchi/web/ask_routes.rb +56 -9
  91. data/lib/samagotchi/web/last_ask.rb +78 -0
  92. data/lib/samagotchi/web/peer_routes.rb +10 -5
  93. data/lib/samagotchi/web/public/agent_rows.js +206 -0
  94. data/lib/samagotchi/web/public/agent_runs.js +595 -0
  95. data/lib/samagotchi/web/public/answer_fold.js +41 -44
  96. data/lib/samagotchi/web/public/answer_refs.js +3 -9
  97. data/lib/samagotchi/web/public/answer_write.js +28 -0
  98. data/lib/samagotchi/web/public/app.js +75 -99
  99. data/lib/samagotchi/web/public/block_fix.js +30 -12
  100. data/lib/samagotchi/web/public/cards_place.js +6 -4
  101. data/lib/samagotchi/web/public/chains.js +3 -1
  102. data/lib/samagotchi/web/public/command_list.js +5 -3
  103. data/lib/samagotchi/web/public/composer.js +9 -6
  104. data/lib/samagotchi/web/public/composer_mount.js +18 -11
  105. data/lib/samagotchi/web/public/draft_keys.js +10 -0
  106. data/lib/samagotchi/web/public/drafts.js +278 -0
  107. data/lib/samagotchi/web/public/history_reveal.js +5 -2
  108. data/lib/samagotchi/web/public/index.html +38 -2
  109. data/lib/samagotchi/web/public/owner_claim.js +7 -12
  110. data/lib/samagotchi/web/public/page_view.js +1 -1
  111. data/lib/samagotchi/web/public/pages.css +1 -7
  112. data/lib/samagotchi/web/public/peer_mailbox_api.js +2 -1
  113. data/lib/samagotchi/web/public/peer_note.js +4 -2
  114. data/lib/samagotchi/web/public/peer_row.js +37 -0
  115. data/lib/samagotchi/web/public/prompt_history.js +6 -0
  116. data/lib/samagotchi/web/public/quiet_notes.js +12 -1
  117. data/lib/samagotchi/web/public/revise_stack.js +5 -2
  118. data/lib/samagotchi/web/public/send_turn.js +62 -23
  119. data/lib/samagotchi/web/public/session_actions.js +80 -16
  120. data/lib/samagotchi/web/public/session_prefs.js +9 -3
  121. data/lib/samagotchi/web/public/session_view.js +7 -2
  122. data/lib/samagotchi/web/public/turn_block.js +4 -0
  123. data/lib/samagotchi/web/public/turn_events.js +0 -2
  124. data/lib/samagotchi/web/public/unqueue.js +22 -9
  125. data/lib/samagotchi/web/public/viewer_self.js +1 -6
  126. data/lib/samagotchi/web/public/views.js +12 -1
  127. data/lib/samagotchi/web/session_access_routes.rb +6 -3
  128. data/lib/samagotchi/web/session_control.rb +4 -2
  129. data/lib/samagotchi/web/session_create.rb +50 -33
  130. data/lib/samagotchi/web/session_hub.rb +52 -36
  131. data/lib/samagotchi/web/session_summary.rb +45 -7
  132. data/lib/samagotchi/web/start_dir.rb +6 -4
  133. data/lib/samagotchi/worker/mail.rb +11 -1
  134. data/lib/samagotchi/worker.rb +7 -5
  135. data/lib/samagotchi/worker_inbound/mail.rb +34 -6
  136. data/lib/samagotchi/worker_inbound.rb +11 -3
  137. data/lib/samagotchi/worker_link.rb +13 -1
  138. data/lib/samagotchi/worker_presence.rb +22 -6
  139. data/lib/samagotchi/worker_wakes.rb +33 -5
  140. metadata +12 -2
  141. data/lib/samagotchi/web/public/pages_group.js +0 -67
@@ -0,0 +1,158 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The mcp bundle's server-config plugin part (manifest.yml plugin: parts:, loaded
4
+ # before plugin.rb): a server's config resolved into its command/env/cwd or
5
+ # url/headers and digest, and why a config is refused.
6
+ require "digest"
7
+ require "json"
8
+ require "shellwords"
9
+ require "uri"
10
+
11
+ class Plugin
12
+ # The headers chi sets itself on a remote server's requests.
13
+ # The wire's own (host, content-length…) too: one set in config.yml would break every request.
14
+ OWN_HEADERS = %w[accept content-type mcp-protocol-version mcp-method mcp-name mcp-session-id
15
+ host content-length connection transfer-encoding].freeze
16
+
17
+ # The oauth: map's keys (all optional).
18
+ OAUTH_KEYS = %w[client_id issuer client_secret_env scopes redirect_port].freeze
19
+
20
+ private
21
+
22
+ # The command, env and cwd the server runs with, and their digest (the
23
+ # cache's key: command, args, env names and values, and the cwd; the
24
+ # env itself is never stored).
25
+ def resolve(server, ctx)
26
+ return resolve_url(server) if server.config.key?("url")
27
+
28
+ command = server.config["command"]
29
+ command = Shellwords.split(command) if command.is_a?(String)
30
+ server.command = Array(command).map(&:to_s)
31
+ env = server.config["env"].is_a?(Hash) ? server.config["env"] : {}
32
+ server.env = env.to_h { |key, value| [key.to_s, value.to_s] }
33
+ server.cwd = server.config["cwd"] ? File.expand_path(server.config["cwd"].to_s) : ctx.cwd
34
+ server.digest = Digest::SHA256.hexdigest(JSON.generate([server.command, server.env.sort, server.cwd]))
35
+ end
36
+
37
+ # A remote server's url, headers, token variable and oauth: map, and
38
+ # their digest (never the token's value: a rotated token isn't a changed
39
+ # config). The oauth: map joins the digest only when it is set: a server
40
+ # without one keeps the digest it had before sign-in came (its cache).
41
+ def resolve_url(server)
42
+ server.command = []
43
+ server.env = server.config["env"].is_a?(Hash) ? server.config["env"].to_h { |k, v| [k.to_s, v.to_s] } : {}
44
+ server.url = server.config["url"].to_s
45
+ server.headers = server.config["headers"].is_a?(Hash) ? server.config["headers"] : {}
46
+ server.token_env = server.config["bearer_token_env"]&.to_s
47
+ server.oauth = server.config["oauth"] if server.config.key?("oauth")
48
+ server.signs_in = server.token_env.nil? && server.headers.keys.none? { |name| name.to_s.casecmp?("authorization") }
49
+ digested = [server.url, server.headers.map { |k, v| [k.to_s, v.to_s] }.sort, server.token_env]
50
+ digested << (server.oauth.is_a?(Hash) ? server.oauth.map { |k, v| [k.to_s, v] }.sort_by(&:first) : server.oauth) if server.config.key?("oauth")
51
+ server.digest = Digest::SHA256.hexdigest(JSON.generate(digested))
52
+ end
53
+
54
+ # Why the server's config can't start it, nil when it can.
55
+ def config_error(server)
56
+ where = "bundles: mcp: servers: #{server.name}"
57
+ if server.url && server.config.key?("command")
58
+ return "set command: (a local server) or url: (a remote one), not both (#{where})"
59
+ end
60
+ return url_error(server, where) if server.url
61
+
62
+ "no command (#{where}: command: [...] or url: ...)" if server.command.empty?
63
+ end
64
+
65
+ def url_error(server, where)
66
+ uri = begin
67
+ URI.parse(server.url)
68
+ rescue URI::Error
69
+ nil
70
+ end
71
+ return "url: must be an http(s) URL (#{where})" unless uri.is_a?(URI::HTTP) && !uri.host.to_s.empty?
72
+ return "bearer_token_env: must name an environment variable (#{where})" if server.token_env&.strip&.empty?
73
+ return "headers: must be a map of names to values (#{where})" unless server.config["headers"].nil? || server.config["headers"].is_a?(Hash)
74
+
75
+ server.headers.each do |name, value|
76
+ unless name.is_a?(String) && value.is_a?(String) && name.match?(/\A[!#$%&'*+\-.^_`|~0-9A-Za-z]+\z/) &&
77
+ !value.match?(/[\r\n\0]/)
78
+ return "headers: #{name.to_s[0, 40].inspect} must be a name and a one-line text value (#{where})"
79
+ end
80
+ if OWN_HEADERS.include?(name.downcase) || (server.token_env && name.casecmp?("authorization"))
81
+ return "headers: #{name} is chi's to set (#{where})"
82
+ end
83
+ end
84
+ oauth_error(server, where) if server.config.key?("oauth")
85
+ end
86
+
87
+ # Why a remote server's oauth: map can't be used, nil when it can: a
88
+ # client registered by hand is bound to its provider (issuer:), and a
89
+ # server signs in or has a static token, never both.
90
+ def oauth_error(server, where)
91
+ oauth = server.oauth
92
+ return "oauth: must be a map (#{where})" unless oauth.is_a?(Hash)
93
+ return "oauth: and bearer_token_env: are one or the other (#{where})" if server.token_env
94
+ if server.headers.keys.any? { |name| name.to_s.casecmp?("authorization") }
95
+ return "oauth: and an Authorization header are one or the other (#{where})"
96
+ end
97
+
98
+ unknown = oauth.keys.map(&:to_s) - OAUTH_KEYS
99
+ return "oauth: #{unknown.first[0, 40]} isn't one of #{OAUTH_KEYS.join(", ")} (#{where})" unless unknown.empty?
100
+
101
+ id = oauth["client_id"]
102
+ return "oauth: client_id: must be a text (#{where})" if oauth.key?("client_id") && !(id.is_a?(String) && !id.strip.empty?)
103
+ return "oauth: issuer: is required with client_id: (#{where})" if id && !oauth.key?("issuer")
104
+ return "oauth: issuer: goes with client_id: (#{where})" if oauth.key?("issuer") && !id
105
+ return "oauth: issuer: must be an https address (#{where})" if id && !issuer_address?(oauth["issuer"])
106
+
107
+ secret_env = oauth["client_secret_env"]
108
+ if oauth.key?("client_secret_env")
109
+ return "oauth: client_secret_env: must name an environment variable (#{where})" unless secret_env.is_a?(String) && !secret_env.strip.empty?
110
+ return "oauth: client_secret_env: goes with client_id: (#{where})" unless id
111
+ end
112
+ scopes = oauth["scopes"]
113
+ if oauth.key?("scopes") && !(scopes.is_a?(Array) && scopes.all? { |scope| scope.is_a?(String) && scope.match?(/\A[!#-\[\]-~]+\z/) })
114
+ return "oauth: scopes: must be a list of scope names (#{where})"
115
+ end
116
+
117
+ port = oauth["redirect_port"]
118
+ "oauth: redirect_port: must be a port, 1024 to 65535 (#{where})" if oauth.key?("redirect_port") && !(port.is_a?(Integer) && port.between?(1024, 65_535))
119
+ end
120
+
121
+ # An https address with a host (http only on a loopback host: local
122
+ # development), no query or fragment: what an issuer is.
123
+ def issuer_address?(value)
124
+ uri = URI.parse(value.to_s)
125
+ return false unless uri.is_a?(URI::HTTP) && !uri.host.to_s.empty? && uri.query.nil? && uri.fragment.nil? && uri.userinfo.nil?
126
+
127
+ uri.scheme == "https" || loopback_host?(uri.host)
128
+ rescue URI::Error
129
+ false
130
+ end
131
+
132
+ def loopback_host?(host) = %w[127.0.0.1 ::1 [::1] localhost].include?(host.to_s.downcase)
133
+
134
+ # A remote server's bearer token (HttpClient's token:), looked up at each
135
+ # request (never kept): the env a stdio server would get (its env:, then
136
+ # the project env: #server_env), then the worker's.
137
+ # @return [HttpClient::StaticToken]
138
+ def token_lookup(server)
139
+ return HttpClient::StaticToken.new { nil } unless server.token_env
140
+
141
+ HttpClient::StaticToken.new do
142
+ value = env_value(server, server.token_env).to_s
143
+ raise HttpClient::Refused, "#{server.token_env} is not set" if value.empty?
144
+ # An env file saved with CRLF line ends; a header can't carry it.
145
+ raise HttpClient::Refused, "#{server.token_env} holds a line break: set it on one line" if value.match?(/[\r\n\0]/)
146
+
147
+ value
148
+ end
149
+ end
150
+
151
+ # +variable+'s value for the server: its env:, the project env, then the
152
+ # worker's; nil when unset or empty.
153
+ def env_value(server, variable)
154
+ value = server_env(server)[variable].to_s
155
+ value = ENV[variable].to_s if value.empty?
156
+ value.empty? ? nil : value
157
+ end
158
+ end
@@ -0,0 +1,261 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The mcp bundle's sign-in plugin part (manifest.yml plugin: parts:, loaded
4
+ # before plugin.rb): /mcp login|logout and a 401's sign-in card, wired to
5
+ # the OAuth in oauth.rb.
6
+ require "digest"
7
+ require "uri"
8
+
9
+ class Plugin
10
+ private
11
+
12
+ # ── Sign-in (the OAuth in oauth.rb; here its wiring) ──────────────────
13
+
14
+ # Why /mcp login|logout can't act on server +name+, nil when it can.
15
+ def sign_in_refusal(name)
16
+ server = @servers.find { |s| s.name == name }
17
+ return "no MCP server #{name}#{" (#{@servers.map(&:name).join(", ")})" unless @servers.empty?}" unless server
18
+ return "#{name} is a local server: sign-in is for remote ones (url:)" unless server.url
19
+ return "#{name} has a static token (bearer_token_env: or an Authorization header): it doesn't sign in" unless server.signs_in
20
+ return "#{name}'s url: has a query: chi can't sign in to it (it would go out with the sign-in)" if URI.parse(server.url).query
21
+
22
+ config_error(server)
23
+ end
24
+
25
+ # /mcp login NAME: answers at once; discovery, the client, the flow and
26
+ # the exchange run on a thread of the plugin's (OAuth::Login), whose
27
+ # result or error replaces the flow's card.
28
+ def login(name, ctx)
29
+ refusal = sign_in_refusal(name)
30
+ return refusal if refusal
31
+ return "sign-in needs the web or a terminal: this run is one-shot" if ctx.frontend == :one_shot
32
+ if @settings.key?("client_metadata_url") && @settings["client_metadata_url"] != false && client_metadata_url.nil?
33
+ return "bundles: mcp: client_metadata_url: must be an https address with a path (chi's client document)"
34
+ end
35
+ return "this chi can't sign in (it has no ctx.sign_in)" unless ctx.respond_to?(:sign_in) && ctx.respond_to?(:secrets)
36
+
37
+ server = @servers.find { |s| s.name == name }
38
+ return "#{name} is signed in already (from another session): connected." if signed_in_elsewhere?(server, ctx)
39
+
40
+ started = @sign_in_lock.synchronize do
41
+ next false if @sign_ins[name]&.alive? || @sign_in_cancel.cancelled?
42
+
43
+ @sign_ins[name] = Thread.new { sign_in(server, ctx) }
44
+ end
45
+ return "a sign-in to #{name} is already waiting: finish it in the browser, or let it time out" unless started
46
+
47
+ "Opening sign-in for #{name}…"
48
+ end
49
+
50
+ # The login's thread: every error ends on a card, never raised into nothing.
51
+ def sign_in(server, ctx)
52
+ login = OAuth::Login.new(ctx: ctx, server: server, secret_lookup: ->(name) { env_value(server, name) },
53
+ client_metadata_url: client_metadata_url, cimd_refused: @cimd_refused, cancel: @sign_in_cancel,
54
+ log: ->(event, **fields) { ctx.log.info("mcp_#{event}", **fields) })
55
+ card_id = login.run
56
+ signed_in(server, card_id, ctx) if card_id
57
+ rescue OAuth::Refusal => e
58
+ ctx.log.warn("mcp_sign_in_failed", server: server.name, error: e.class.name)
59
+ ctx.card(id: e.card_id, title: "Sign-in to #{server.name} failed", body: e.message, level: :warn, between_turns: true)
60
+ rescue StandardError => e
61
+ ctx.log.warn("mcp_sign_in_failed", server: server.name, error: e.class.name)
62
+ ctx.card(title: "Sign-in to #{server.name} failed", body: "chi's sign-in broke (#{e.class.name}); the debug log has it",
63
+ level: :warn, between_turns: true)
64
+ end
65
+
66
+ # Kept: the server connects as a lazy start does (handshake, tools/list,
67
+ # the cache), with spawn directly when its service already runs (a 401
68
+ # met during a call, a sign-out), then the flow's card says so.
69
+ def signed_in(server, card_id, ctx)
70
+ server.token.forget
71
+ begin
72
+ reconnect(server, ctx)
73
+ count = offered(server).size
74
+ ctx.card(id: card_id, title: "Signed in to #{server.name}", body: "#{count} tool#{"s" unless count == 1}, ready to use.",
75
+ between_turns: true)
76
+ rescue StandardError => e
77
+ if needs_sign_in?(server, e)
78
+ signed_out(server, ctx, e)
79
+ return
80
+ end
81
+
82
+ ctx.log.warn("mcp_server_failed", server: server.name, error: e.class.name, msg: e.message, signed_in: true)
83
+ ctx.card(id: card_id, title: "Signed in, but #{server.name} didn't connect", body: e.message, level: :warn,
84
+ between_turns: true)
85
+ end
86
+ end
87
+
88
+ # Connect a server that has a sign-in now (spawn when its service
89
+ # already runs, else its first start), then it runs; its "needs sign-in"
90
+ # card loses its button (a later refusal shows it again).
91
+ def reconnect(server, ctx)
92
+ @restart.synchronize do
93
+ if server.service.state == :running
94
+ old = server.client
95
+ spawn(server, ctx, cancelled: @sign_in_cancel)
96
+ old.close unless old.equal?(server.client)
97
+ else
98
+ server.service.value
99
+ end
100
+ @sign_in_lock.synchronize do
101
+ server.state = :running
102
+ server.error = nil
103
+ end
104
+ end
105
+ publish
106
+ return unless @sign_in_lock.synchronize { server.card_shown.tap { server.card_shown = false } }
107
+
108
+ ctx.card(id: "mcp-sign-in-#{server.name}", title: "#{server.name} needs sign-in", body: "Signed in since.", between_turns: true)
109
+ end
110
+
111
+ # A server that needs sign-in, signed in to meanwhile from another
112
+ # session (the kept token, read again): connected now. False when there
113
+ # is no kept token, or it doesn't connect.
114
+ def signed_in_elsewhere?(server, ctx)
115
+ return false unless server.state == :needs_sign_in && server.token.respond_to?(:kept)
116
+
117
+ server.token.forget
118
+ kept = kept_digest(server)
119
+ return false if kept.nil? || kept == server.refused
120
+
121
+ reconnect(server, ctx)
122
+ ctx.log.info("mcp_signed_in_elsewhere", server: server.name)
123
+ true
124
+ rescue StandardError => e
125
+ server.refused = kept_digest(server) # what it holds after a renew, too: not tried again
126
+ ctx.log.warn("mcp_server_failed", server: server.name, error: e.class.name, msg: e.message, signed_in_elsewhere: true)
127
+ false
128
+ end
129
+
130
+ # 16 hex of the SHA-256 of the kept access token, nil without one.
131
+ def kept_digest(server)
132
+ kept = server.token.respond_to?(:kept) && server.token.kept
133
+ kept ? Digest::SHA256.hexdigest(kept["access_token"])[0, 16] : nil
134
+ rescue StandardError
135
+ nil
136
+ end
137
+
138
+ # Whether the kept sign-in is newer than the token +error+ refused (or,
139
+ # none sent, whether there is one now): another session or a login
140
+ # signed in after the request went out.
141
+ def newer_sign_in?(server, error)
142
+ kept = server.token.respond_to?(:kept) && server.token.kept
143
+ return false unless kept
144
+
145
+ error.sent_digest.nil? || Digest::SHA256.hexdigest(kept["access_token"])[0, 16] != error.sent_digest
146
+ rescue StandardError
147
+ false
148
+ end
149
+
150
+ # /mcp logout NAME: the kept token goes (the provider's revocation asked,
151
+ # best effort), the client closes, the server needs sign-in. chi's
152
+ # registration with the provider stays.
153
+ def logout(name, ctx)
154
+ refusal = sign_in_refusal(name)
155
+ return refusal if refusal
156
+
157
+ server = @servers.find { |s| s.name == name }
158
+ kept = server.token.kept
159
+ ctx.secrets.delete(server.token.name)
160
+ server.token.forget
161
+ OAuth.revoke(ctx.http, kept, log: ->(event, **fields) { ctx.log.info("mcp_#{event}", server: name, **fields) }) if kept
162
+ server.client&.close
163
+ server.state = :needs_sign_in
164
+ publish
165
+ "Signed out of #{name}."
166
+ rescue Samagotchi::Plugin::Secrets::Unavailable, Samagotchi::Plugin::Secrets::Busy => e
167
+ "#{name}'s sign-in wasn't forgotten: #{e.message}"
168
+ end
169
+
170
+ # Whether +error+ means the server wants a sign-in: a 401 from one that signs in.
171
+ def needs_sign_in?(server, error) = server.signs_in && error.is_a?(HttpClient::Refused) && error.status == 401
172
+
173
+ # The server needs sign-in: its state (said once), its card, and the
174
+ # line its call answers.
175
+ # Nil when +error+ (the 401) was for an older token than the kept one: the
176
+ # state stays, the next request sends the new token.
177
+ def signed_out(server, ctx, error = nil)
178
+ if error && newer_sign_in?(server, error)
179
+ server.token.forget
180
+ return nil
181
+ end
182
+
183
+ first = @sign_in_lock.synchronize { server.state == :needs_sign_in ? false : (server.state = :needs_sign_in) }
184
+ if first
185
+ server.refused = kept_digest(server)
186
+ server.error = nil
187
+ publish
188
+ ctx.log.info("mcp_needs_sign_in", server: server.name)
189
+ end
190
+ offer_sign_in(server, ctx)
191
+ "Error: #{sign_in_line(server, ctx.turn_author)}"
192
+ end
193
+
194
+ # What a call of a server that needs sign-in answers: the owner's
195
+ # command, or (a participant's turn) who signs in, no command.
196
+ def sign_in_line(server, author = nil)
197
+ return "#{server.name} needs sign-in: the session's owner signs in" if author
198
+
199
+ "#{server.name} needs sign-in: the user runs /mcp login #{server.name}"
200
+ end
201
+
202
+ # The "needs sign-in" card, once per server per worker, never a turn's;
203
+ # none on a one-shot; on a participant's turn held for the owner's next
204
+ # turn end or command.
205
+ def offer_sign_in(server, ctx)
206
+ return if ctx.frontend == :one_shot
207
+
208
+ if ctx.turn_author
209
+ @sign_in_lock.synchronize { @held_cards << server.name unless @held_cards.include?(server.name) }
210
+ return
211
+ end
212
+ first = @sign_in_lock.synchronize { server.card_shown ? false : (server.card_shown = true) }
213
+ return unless first
214
+
215
+ ctx.card(id: "mcp-sign-in-#{server.name}", title: "#{server.name} needs sign-in",
216
+ body: "The server asks chi to sign in. Sign in opens its provider's page in your browser.",
217
+ actions: [{ label: "Sign in", command: "/mcp login #{server.name}" }], between_turns: true)
218
+ end
219
+
220
+ def show_held_cards(ctx)
221
+ names = @sign_in_lock.synchronize { @held_cards.slice!(0..) }
222
+ names.each do |name|
223
+ server = @servers.find { |s| s.name == name }
224
+ offer_sign_in(server, ctx) if server&.state == :needs_sign_in
225
+ end
226
+ end
227
+
228
+ # chi's client document's address (bundles: mcp: client_metadata_url:,
229
+ # else CLIENT_METADATA_URL): an https address with a path, else nil
230
+ # (false: none, never a CIMD client_id).
231
+ def client_metadata_url
232
+ value = @settings.fetch("client_metadata_url", CLIENT_METADATA_URL)
233
+ return nil if value == false
234
+
235
+ uri = URI.parse(value.to_s)
236
+ uri.is_a?(URI::HTTPS) && !uri.host.to_s.empty? && uri.path.to_s.length > 1 && uri.userinfo.nil? ? value.to_s : nil
237
+ rescue URI::Error
238
+ nil
239
+ end
240
+
241
+ # The service's stop: the waiting sign-ins end (core stops their flows
242
+ # too), their threads get a moment to put their cards right.
243
+ def stop_sign_ins
244
+ @sign_in_cancel.cancel!
245
+ threads = @sign_in_lock.synchronize { @sign_ins.values }
246
+ threads.each { |thread| thread.join(2) }
247
+ end
248
+
249
+ # A remote server's token object: OAuth::Token for one that signs in
250
+ # (with this chi's ctx.secrets), else the static one.
251
+ def token_of(server, ctx)
252
+ return token_lookup(server) unless server.signs_in && ctx.respond_to?(:secrets)
253
+
254
+ oauth = server.oauth.is_a?(Hash) ? server.oauth : {}
255
+ variable = oauth["client_secret_env"]
256
+ client = oauth["client_id"] ? { id: oauth["client_id"], issuer: oauth["issuer"] } : nil
257
+ OAuth::Token.new(secrets: ctx.secrets, resource: URI.parse(server.url).query ? nil : OAuth.canonical(server.url),
258
+ http: ctx.http, client: client, client_secret: -> { variable && env_value(server, variable) },
259
+ log: ->(event, **fields) { ctx.log.info("mcp_#{event}", server: server.name, **fields) })
260
+ end
261
+ end
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.191.0
3
+ version: 0.193.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:
@@ -62,12 +62,6 @@ module Samagotchi
62
62
  # their author (Steer::PARTICIPANT_PREFIX, "p:<id>"), which says who
63
63
  # wrote a turn: this says which sender delivered it.
64
64
  PARTICIPANT_PREFIX = "participant:"
65
- # compat shim review_client_id: the legacy review:<id> participant id
66
- # used before 0.172 (still in turn_drawings.jsonl, input files and an
67
- # older chi web still running): read it as a participant's, never the
68
- # owner's, and send it to a worker without Delivery::PARTICIPANT_ID_FEATURE.
69
- LEGACY_REVIEW_PREFIX = "review:"
70
-
71
65
  # A worker's own first prompt (spawn_session's) when no sender was
72
66
  # saved for it (WorkerInbound#initial_origin: a person's session saves
73
67
  # no first_turn_client_id, nor did an older chi): the owner's, as chi
@@ -144,10 +138,7 @@ module Samagotchi
144
138
  Sender.new(match: RELAY_PREFIX, **unattended),
145
139
  agent,
146
140
  session_question,
147
- participant,
148
- # compat shim review_client_id: the legacy review:<id> id uses the
149
- # participant sender row too.
150
- participant.with(match: LEGACY_REVIEW_PREFIX)
141
+ participant
151
142
  ].freeze
152
143
 
153
144
  # No client id: reaches only a worker's own seams (an input file from
@@ -256,17 +247,9 @@ module Samagotchi
256
247
  # grant): participant:<participant id>.
257
248
  def participant(participant_id) = "#{PARTICIPANT_PREFIX}#{participant_id}"
258
249
 
259
- # Whether +client_id+ is a participant's (participant:, or legacy
260
- # review:).
250
+ # Whether +client_id+ is a participant's.
261
251
  def participant?(client_id) = sender(client_id).wake == :participant
262
252
 
263
- # compat shim review_client_id: translate participant:<id> for a worker
264
- # that still expects review:<id>.
265
- def legacy_participant(client_id)
266
- id = client_id.to_s
267
- id.start_with?(PARTICIPANT_PREFIX) ? "#{LEGACY_REVIEW_PREFIX}#{id.delete_prefix(PARTICIPANT_PREFIX)}" : client_id
268
- end
269
-
270
253
  # The client id a delegating parent's task and follow-ups carry:
271
254
  # delegate:<parent8>.
272
255
  def delegate(parent_id) = "#{DELEGATE_PREFIX}#{parent_id.to_s[0, 8]}"
@@ -18,11 +18,12 @@ module Samagotchi
18
18
  MIN_AGE_DAYS = 14
19
19
 
20
20
  SHIMS = [
21
- Shim.new(id: :review_client_id, added_in: "0.172.0", added_on: "2026-11-14", remove_after: "0.173.0",
22
- files: ["lib/samagotchi/client_id.rb", "lib/samagotchi/session_manager/delivery.rb",
23
- "lib/samagotchi/web/public/turn_events.js", "lib/samagotchi/web/public/viewer_self.js"],
24
- what: "A participant's client id from before participant:<id> (review:<id>: drawings, input files, an " \
25
- "older chi web) reads as a participant's, and a worker without participant_client_id is sent it")
21
+ Shim.new(id: :agent_client_id, added_in: "0.185.0", added_on: "2026-11-22", remove_after: "0.195.0",
22
+ files: %w[lib/samagotchi/delivery.rb lib/samagotchi/session_manager/delivery.rb
23
+ lib/samagotchi/session_access/remote.rb spec/session_access_remote_spec.rb
24
+ spec/session_manager/delivery_spec.rb],
25
+ what: "an agent's client id (agent:<name>) sent as chi send's to a worker or chi web " \
26
+ "from before agent: senders (Delivery::AGENT_FEATURE)")
26
27
  ].freeze
27
28
 
28
29
  module_function
@@ -258,6 +258,10 @@ module Samagotchi
258
258
  # wake isn't counted here); then they wait as notes, and the say's line says so. 0: a peer's message never
259
259
  # wakes chi. Not context.wake's: that is attached context's only.
260
260
  Entry.new(key: "peer.turns", yaml_path: %w[peer turns], type: :integer, default: 3, expose: %i[env config cli], lifecycle: :next_matching_turn_display_poll_write),
261
+ # A pairing the model sends to after this many minutes with no exchange (no send, no message from the peer,
262
+ # no pairing, one continue back included) is dormant: the send asks the owner first in a turn they started
263
+ # from the web or a TUI, and is refused in any other. 0: never asks.
264
+ Entry.new(key: "peer.quiet_minutes", yaml_path: %w[peer quiet_minutes], type: :integer, default: 30, expose: %i[env config cli], lifecycle: :next_matching_turn_display_poll_write),
261
265
  # The candidate judge (ContextJudge): off (no conversation text goes to a System 1 host); audit (asks and logs
262
266
  # context_candidates.jsonl, attaches nothing); on (ContextCandidateChoice: p ≥ threshold attaches quietly,
263
267
  # offer_threshold ≤ p < threshold shows one card). Its host and model are system_one.host and .model.
@@ -411,6 +415,9 @@ module Samagotchi
411
415
  # The folder chi web starts in (Web::StartDir): its bare page shows that folder's project, and a new session
412
416
  # without a folder (the all view's) starts there. Unset: the folder chi web runs in. chi web --start-dir wins.
413
417
  Entry.new(key: "web.start_dir", yaml_path: %w[web start_dir], type: :string, default: nil, expose: %i[env config], lifecycle: :web_start),
418
+ # The folder a thin client's one-call create (POST /api/sessions with reply_for, timeout or request_id) starts
419
+ # in when it names no dir (Web::AskCreate; ~ and home-relative work). Unset: web.start_dir's. Read per create.
420
+ Entry.new(key: "web.ask_dir", yaml_path: %w[web ask_dir], type: :string, default: nil, expose: %i[env config], lifecycle: :session_creation),
414
421
  # Participants (chi share): a new grant's lifetime (Nh or Nd, 1h to 30d), and what a grant without its own
415
422
  # takes: its spending cap in dollars ($0 to $1000) and how many of its turns may wait (0 to 20). Read when used.
416
423
  Entry.new(key: "web.participants.expires", yaml_path: %w[web participants expires], type: :string, default: "7d", expose: %i[env config], lifecycle: :next_matching_turn_display_poll_write),
@@ -162,6 +162,7 @@ module Samagotchi
162
162
  offer = @turn_flow.offer
163
163
  resume_from = @turn_flow.resume_from
164
164
  enqueued_id = offer_turn_id
165
+ offer_client = @turn_state.last_context&.origin&.client_id
165
166
  author = @engine.session&.last_turn&.participant_author
166
167
  close("answered")
167
168
  if author && (reason = @participant_refused.call(author))
@@ -179,7 +180,7 @@ module Samagotchi
179
180
  Log.warn(:worker, "turn_not_begun", continue: true, error: e.class.name, msg: e.message)
180
181
  return announce_offer(offer)
181
182
  end
182
- origin = TurnOrigin.new(client_id: command.client_id, enqueued_id: enqueued_id, author: author)
183
+ origin = TurnOrigin.new(client_id: continue_client(command, offer_client), enqueued_id: enqueued_id, author: author)
183
184
  @run_turn.call(nil, continue: true, origin: origin, resumed: true, resume_from: resume_from,
184
185
  max_iterations: @max_iterations.call(offer[:no_interrupt])) do |result, error|
185
186
  if error
@@ -241,6 +242,17 @@ module Samagotchi
241
242
  # nil when it ran no input (a reminder turn, a delegate's first).
242
243
  def offer_turn_id = @engine.session&.last_turn&.enqueued_id
243
244
 
245
+ # Who the continue turn runs as: the answer's sender, except that a
246
+ # person's tap (ClientId::CARD_ANSWER, which names no screen and so
247
+ # isn't interactive) continues an offer turn sent from a web tab or a
248
+ # TUI as that screen's, so the turn stays interactive as it was
249
+ # (ctx.turn_interactive?: a dormant peer send asks there).
250
+ def continue_client(command, offer_client)
251
+ return command.client_id unless command.client_id == ClientId::CARD_ANSWER && ClientId.interactive?(offer_client)
252
+
253
+ offer_client
254
+ end
255
+
244
256
  def announce_offer(offer = @turn_flow.offer)
245
257
  @event_log.announce(type: :continue_offered, context: offer[:context], no_interrupt: offer[:no_interrupt])
246
258
  ask
@@ -62,17 +62,13 @@ module Samagotchi
62
62
  # Workers advertise REVIEW_FEATURE too: an older chi web refuses
63
63
  # participants' turns to a worker without it.
64
64
  PAIR_FEATURE = "pair_turns"
65
- # A worker that reads a participant's client id as participant:<id>
66
- # (ClientId::PARTICIPANT_PREFIX). One without it reads only review:<id>
67
- # (an unknown id to it: never the owner's, but its lines' source would
68
- # be automatic:… and a participant's Verify fresh child would ring its
69
- # parent), so chi web sends it the old id (SessionManager's delivery).
65
+ # The previous release's chi web checks this before sending participant:<id>.
70
66
  PARTICIPANT_ID_FEATURE = "participant_client_id"
71
67
  # A worker (Bridge::FEATURES) or a chi web (Web::App::INFO_FEATURES)
72
68
  # that reads an agent's client id (ClientId::AGENT_PREFIX). One without
73
69
  # it would read agent:<name> as an unknown sender (automatic), so it is
74
- # sent chi send's id instead: today's owner row (compat shim
75
- # agent_client_id).
70
+ # sent chi send's id instead: today's owner row.
71
+ # compat shim agent_client_id
76
72
  AGENT_FEATURE = "agent_sender"
77
73
  # A worker (Bridge::FEATURES) that runs another session's question
78
74
  # (ClientId::SESSION_PREFIX, ask_session) as a visitor's turn. One
@@ -1,10 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../config"
4
+ require_relative "../degrade"
4
5
  require_relative "../effective_model"
5
6
  require_relative "../failure_line"
6
7
  require_relative "../llm/backend"
7
8
  require_relative "../llm/errors"
9
+ require_relative "../llm/prompt_cache"
8
10
  require_relative "../log"
9
11
  require_relative "../model_notes"
10
12
  require_relative "../model_profile"
@@ -248,6 +250,21 @@ module Samagotchi
248
250
  end
249
251
  private :model_switched_since_last_turn?
250
252
 
253
+ # How long the effective model's host keeps this session's prompt
254
+ # cache, in seconds (cache.ttl: PromptCache.ttl_seconds), when its chat
255
+ # requests carry breakpoints (its chat host's adapter's
256
+ # cache_breakpoints?); nil when they carry none: a local model, a host
257
+ # that sends none, no model. The peer mail's cold hold reads it
258
+ # (WorkerInbound::MailPart).
259
+ # @return [Integer, nil]
260
+ def remote_cache_ttl
261
+ Degrade.call(:model, "remote_cache_ttl_unknown") do
262
+ model = effective_model
263
+ adapter = model.chat? ? @host_registry.adapter_for(model.entry) : nil
264
+ LLM::PromptCache.ttl_seconds if adapter.respond_to?(:cache_breakpoints?) && adapter.cache_breakpoints?(model.bare)
265
+ end
266
+ end
267
+
251
268
  private
252
269
 
253
270
  # Pick the loop for +model+ (EffectiveModel); the chat loop is pointed
@@ -3,6 +3,7 @@
3
3
  require_relative "../answer_display"
4
4
  require_relative "../bundle_settings_check"
5
5
  require_relative "../cache_confirm"
6
+ require_relative "../client_id"
6
7
  require_relative "../log"
7
8
  require_relative "../plugin/context"
8
9
  require_relative "../plugin/loader"
@@ -186,6 +187,7 @@ module Samagotchi
186
187
  cost: -> { @metrics.cost },
187
188
  usage: -> { @metrics.usage },
188
189
  turn_author: -> { turn_author },
190
+ turn_interactive: -> { ClientId.interactive?(turn_context&.origin&.client_id) },
189
191
  # A plugin's prompt section is in the stable part: a full re-read.
190
192
  cache_confirm: ->(line, changed) { CacheConfirm.ask(line: line, cost: :full, changed: changed, engine: self) },
191
193
  candidate_proposed: ->(_candidate) { judge_late_candidates },