samagotchi 0.182.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.
Files changed (197) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +107 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +22 -11
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +28 -6
  8. data/docs/configuration.md +4 -2
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +14 -6
  12. data/docs/internals/bundles.md +26 -5
  13. data/docs/internals/engine.md +20 -9
  14. data/docs/internals/participants.md +1 -1
  15. data/docs/internals/prompt-caching.md +8 -1
  16. data/docs/internals/remote-sessions.md +40 -5
  17. data/docs/internals/web-frontend.md +96 -31
  18. data/docs/internals/web-push.md +11 -0
  19. data/docs/internals/working-set.md +239 -7
  20. data/docs/mcp-server.md +84 -0
  21. data/docs/memory.md +2 -1
  22. data/docs/plugins.md +309 -22
  23. data/docs/scheduling.md +14 -0
  24. data/docs/sessions.md +4 -4
  25. data/docs/sub-agent.md +9 -0
  26. data/docs/testing.md +3 -1
  27. data/docs/thin-clients.md +165 -0
  28. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  29. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  30. data/lib/samagotchi/bridge.rb +59 -68
  31. data/lib/samagotchi/bridge_client.rb +12 -4
  32. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  33. data/lib/samagotchi/bundle_command/check.rb +55 -20
  34. data/lib/samagotchi/bundle_command.rb +50 -21
  35. data/lib/samagotchi/bundle_manifest.rb +105 -4
  36. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  37. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  38. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  39. data/lib/samagotchi/bundles/mcp/http_client.rb +432 -0
  40. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  41. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  42. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  43. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  44. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  45. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  46. data/lib/samagotchi/bundles/system/self_map.md +7 -2
  47. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  48. data/lib/samagotchi/command_intake.rb +7 -0
  49. data/lib/samagotchi/commands/registry.rb +8 -3
  50. data/lib/samagotchi/continue_offer.rb +24 -15
  51. data/lib/samagotchi/engine/block_fix.rb +4 -4
  52. data/lib/samagotchi/engine/cards.rb +14 -5
  53. data/lib/samagotchi/engine/events.rb +10 -15
  54. data/lib/samagotchi/engine/models.rb +1 -1
  55. data/lib/samagotchi/engine/plugins.rb +3 -0
  56. data/lib/samagotchi/engine/recap.rb +1 -1
  57. data/lib/samagotchi/engine/session.rb +14 -6
  58. data/lib/samagotchi/engine/side_requests.rb +1 -1
  59. data/lib/samagotchi/engine/sign_in.rb +142 -0
  60. data/lib/samagotchi/engine/turn_end.rb +3 -3
  61. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  62. data/lib/samagotchi/engine.rb +43 -27
  63. data/lib/samagotchi/engine_snapshots.rb +1 -1
  64. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  65. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  66. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  67. data/lib/samagotchi/hold_stop.rb +4 -4
  68. data/lib/samagotchi/idle_recap.rb +19 -11
  69. data/lib/samagotchi/idle_reminders.rb +7 -5
  70. data/lib/samagotchi/idle_scheduler.rb +7 -10
  71. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  72. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  73. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  74. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  75. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  76. data/lib/samagotchi/llm/http.rb +96 -5
  77. data/lib/samagotchi/mcp_command.rb +110 -0
  78. data/lib/samagotchi/mcp_server/http.rb +112 -0
  79. data/lib/samagotchi/mcp_server/protocol.rb +263 -0
  80. data/lib/samagotchi/mcp_server/stdio.rb +93 -0
  81. data/lib/samagotchi/mcp_server/text.rb +155 -0
  82. data/lib/samagotchi/mcp_server/tools.rb +246 -0
  83. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  84. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  85. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  86. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  87. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  88. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  89. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  90. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  91. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  92. data/lib/samagotchi/model_notes.rb +34 -12
  93. data/lib/samagotchi/plugin/api.rb +6 -1
  94. data/lib/samagotchi/plugin/card.rb +36 -11
  95. data/lib/samagotchi/plugin/context.rb +63 -6
  96. data/lib/samagotchi/plugin/http.rb +40 -15
  97. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  98. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  99. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  100. data/lib/samagotchi/plugin/loader.rb +18 -11
  101. data/lib/samagotchi/plugin/secrets.rb +266 -0
  102. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  103. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  104. data/lib/samagotchi/prompt_files.rb +11 -4
  105. data/lib/samagotchi/prompt_layout.rb +88 -0
  106. data/lib/samagotchi/prompt_part.rb +82 -20
  107. data/lib/samagotchi/queued_command.rb +28 -4
  108. data/lib/samagotchi/recap_setup.rb +13 -4
  109. data/lib/samagotchi/ref.rb +3 -2
  110. data/lib/samagotchi/relay_verifier.rb +8 -7
  111. data/lib/samagotchi/relay_watcher.rb +4 -4
  112. data/lib/samagotchi/reply_wait.rb +6 -3
  113. data/lib/samagotchi/run_options.rb +2 -1
  114. data/lib/samagotchi/schedule_command.rb +18 -4
  115. data/lib/samagotchi/schedules.rb +40 -8
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +285 -0
  118. data/lib/samagotchi/session_access/contract.rb +5 -0
  119. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  120. data/lib/samagotchi/session_access/exchange.rb +176 -0
  121. data/lib/samagotchi/session_access/local.rb +34 -6
  122. data/lib/samagotchi/session_access/remote.rb +4 -1
  123. data/lib/samagotchi/session_command_catalog.rb +10 -0
  124. data/lib/samagotchi/session_commands.rb +17 -0
  125. data/lib/samagotchi/session_config.rb +4 -4
  126. data/lib/samagotchi/session_inbox.rb +15 -0
  127. data/lib/samagotchi/session_manager/delivery.rb +8 -4
  128. data/lib/samagotchi/session_observer.rb +27 -0
  129. data/lib/samagotchi/steer_cut.rb +4 -3
  130. data/lib/samagotchi/system_prompt.rb +196 -161
  131. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  132. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  133. data/lib/samagotchi/testing/boundary.rb +4 -0
  134. data/lib/samagotchi/testing/bundle.rb +48 -2
  135. data/lib/samagotchi/testing/fake_http.rb +60 -15
  136. data/lib/samagotchi/testing/host.rb +4 -1
  137. data/lib/samagotchi/testing/recorder.rb +45 -5
  138. data/lib/samagotchi/tools/memory.rb +11 -3
  139. data/lib/samagotchi/tools/tool_index.rb +14 -3
  140. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  141. data/lib/samagotchi/version.rb +1 -1
  142. data/lib/samagotchi/web/app.rb +9 -8
  143. data/lib/samagotchi/web/ask_routes.rb +362 -0
  144. data/lib/samagotchi/web/mcp_route.rb +91 -0
  145. data/lib/samagotchi/web/public/app.js +2 -3
  146. data/lib/samagotchi/web/public/block_frame.js +72 -11
  147. data/lib/samagotchi/web/public/block_host.js +44 -8
  148. data/lib/samagotchi/web/public/block_regions.js +126 -0
  149. data/lib/samagotchi/web/public/card.js +22 -9
  150. data/lib/samagotchi/web/public/card_actions.js +21 -0
  151. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  152. data/lib/samagotchi/web/public/card_registry.js +3 -2
  153. data/lib/samagotchi/web/public/data.js +15 -12
  154. data/lib/samagotchi/web/public/delete_sheet.js +231 -169
  155. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  156. data/lib/samagotchi/web/public/format.js +3 -0
  157. data/lib/samagotchi/web/public/index.html +52 -7
  158. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  159. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  160. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  161. data/lib/samagotchi/web/public/refs.js +5 -3
  162. data/lib/samagotchi/web/public/region_hit.js +144 -0
  163. data/lib/samagotchi/web/public/removal_sheet_model.js +274 -0
  164. data/lib/samagotchi/web/public/running_tasks.js +3 -17
  165. data/lib/samagotchi/web/public/session_actions.js +96 -100
  166. data/lib/samagotchi/web/public/working_set_view.js +167 -21
  167. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  168. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  169. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  170. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  171. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  172. data/lib/samagotchi/web/push/notifier.rb +33 -6
  173. data/lib/samagotchi/web/server.rb +1 -1
  174. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  175. data/lib/samagotchi/web/session_control.rb +31 -9
  176. data/lib/samagotchi/web/session_create.rb +2 -2
  177. data/lib/samagotchi/web/session_hub.rb +26 -4
  178. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  179. data/lib/samagotchi/worker/child_side.rb +3 -2
  180. data/lib/samagotchi/worker/command_queue.rb +13 -13
  181. data/lib/samagotchi/worker/leave.rb +3 -3
  182. data/lib/samagotchi/worker/scratch.rb +6 -6
  183. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  184. data/lib/samagotchi/worker/startup.rb +3 -3
  185. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  186. data/lib/samagotchi/worker.rb +32 -21
  187. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  188. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  189. data/lib/samagotchi/worker_inbound.rb +12 -7
  190. data/lib/samagotchi/worker_link.rb +2 -2
  191. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  192. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  193. data/lib/samagotchi/working_set.rb +162 -90
  194. data/lib/samagotchi/working_set_locator.rb +221 -0
  195. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  196. data/lib/samagotchi/working_set_part.rb +281 -0
  197. metadata +36 -1
@@ -1,34 +1,64 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "digest"
3
4
  require_relative "token_usage"
4
5
 
5
6
  module Samagotchi
6
- # One part of a session's system prompt, as its size: what the session
7
- # file's `prompt_parts` records at each prompt build and the web's head view
8
- # draws (the text itself is not kept). kind: a SystemPrompt::KINDS word, or
9
- # "tools" (the tool declarations, wherever the model gets them); label: what
10
- # the row says ("AGENTS.md", "N declared"); chars: the part's length in the
11
- # prompt (a multi-item section's headings and joins are in its first part,
12
- # so a section's parts sum to its text); tokens: chars at TokenUsage's one
13
- # ratio; ref: the bare memory name (identity, notes, preloads), the file
14
- # path (agents, appended), "bundle/name" (plugins), the scope (indexes),
15
- # else nil; scope: a memory part's scope, "project" or "system" (identity:
16
- # system; a note: its own; a preload: the scope that answered), so the
17
- # page tells a project x from a system x; nil for other kinds and in a
18
- # file written before it (the page then matches by name alone).
19
- PromptPart = Data.define(:kind, :label, :chars, :tokens, :ref, :scope) do
20
- def initialize(kind:, label:, chars:, tokens:, ref: nil, scope: nil)
7
+ # One part of a session's system prompt, as its size and its place: what
8
+ # the session file's `prompt_parts` records at each prompt build and the
9
+ # web's head view draws (the text itself is not kept: the sent prompt is,
10
+ # as the session's messages[0]). kind: a SystemPrompt::KINDS word, or
11
+ # "tools" (the tool declarations, wherever the model gets them); label:
12
+ # what the row says ("AGENTS.md", "N declared"); chars: the part's length
13
+ # in the prompt (a multi-item section's headings and joins are in its
14
+ # first part, so a section's parts sum to its text); tokens: chars at
15
+ # TokenUsage's one ratio; ref: the bare memory name (identity, notes,
16
+ # preloads), the file path (agents, appended), "bundle/name" (plugins),
17
+ # the scope (indexes), else nil; scope: a memory part's scope, "project"
18
+ # or "system" (identity: system; a note: its own; a preload: the scope
19
+ # that answered), so the page tells a project x from a system x; nil for
20
+ # other kinds and in a file written before it (the page then matches by
21
+ # name alone).
22
+ #
23
+ # Where it sits in the prompt the build made (docs/internals/working-set.md,
24
+ # Prompt parts as sent), each nil in a file an older chi wrote and left
25
+ # out of #to_h when nil, as scope is:
26
+ # at: the offset its lead starts at; len: its length, lead included (NOT
27
+ # chars: a section's first part is charged its joins); lead: the lead's
28
+ # length (what chi adds before the item's own text: the "System identity
29
+ # …:" line, a note's "## name", a file's header), so the sent slice is
30
+ # head[at, len] and the item's own text head[at + lead, len - lead]. The
31
+ # tools part has one only where the declarations are in the prompt
32
+ # (native: inside the base text, whose slice leaves them out, or Gemma's
33
+ # tail); on a chat host they are a request field. digest: 12 hex of
34
+ # SHA-256 over the item's own text (as PromptNote's); head: 16 hex of
35
+ # SHA-256 of the whole built prompt, the same on every part of a build,
36
+ # so a reader knows whether a saved head is the one the parts were built
37
+ # with. params: how to fetch the item again (string keys): a memory's
38
+ # requested_scope, model_key, fallback_model_key, project_dir,
39
+ # system_dir; a file's path; the tools' [{name, chars}] (chars only where
40
+ # the renderer gives one per tool).
41
+ PromptPart = Data.define(:kind, :label, :chars, :tokens, :ref, :scope, :at, :len, :lead, :digest, :head, :params) do
42
+ def initialize(kind:, label:, chars:, tokens:, ref: nil, scope: nil, at: nil, len: nil, lead: nil, digest: nil, head: nil,
43
+ params: nil)
21
44
  super
22
45
  end
23
46
 
47
+ # The fields that say where a part sits (left out of #to_h when nil).
48
+ PLACE = %i[at len lead digest head params].freeze
49
+
24
50
  # A part of +chars+ characters, its tokens counted by the one ratio.
25
- def self.build(kind:, label:, chars:, ref: nil, scope: nil)
26
- new(kind: kind.to_s, label: label.to_s, chars: chars, tokens: tokens_for(chars), ref: ref&.to_s, scope: scope&.to_s)
51
+ def self.build(kind:, label:, chars:, ref: nil, scope: nil, **place)
52
+ new(kind: kind.to_s, label: label.to_s, chars: chars, tokens: tokens_for(chars), ref: ref&.to_s, scope: scope&.to_s,
53
+ **place.slice(*PLACE))
27
54
  end
28
55
 
29
56
  # @return [Integer] the tokens +chars+ characters count as
30
57
  def self.tokens_for(chars) = (chars / TokenUsage::CHARS_PER_TOKEN).ceil
31
58
 
59
+ # The short digests: an item's text (12 hex), the whole prompt (16).
60
+ def self.digest_of(text, size = 12) = Digest::SHA256.hexdigest(text.to_s)[0, size]
61
+
32
62
  # A saved or wire record (string or symbol keys); nil without a kind.
33
63
  def self.from_h(raw)
34
64
  return raw if raw.is_a?(PromptPart)
@@ -41,9 +71,22 @@ module Samagotchi
41
71
  chars = get.call(:chars)
42
72
  chars = chars.is_a?(Numeric) ? chars.to_i : 0
43
73
  tokens = get.call(:tokens)
74
+ int = ->(key) { get.call(key).is_a?(Integer) ? get.call(key) : nil }
75
+ text = ->(key) { get.call(key).is_a?(String) ? get.call(key) : nil }
76
+ params = get.call(:params)
44
77
  new(kind: kind, label: get.call(:label).to_s, chars: chars,
45
78
  tokens: tokens.is_a?(Numeric) ? tokens.to_i : tokens_for(chars), ref: get.call(:ref)&.to_s,
46
- scope: get.call(:scope)&.to_s)
79
+ scope: get.call(:scope)&.to_s, at: int.call(:at), len: int.call(:len), lead: int.call(:lead),
80
+ digest: text.call(:digest), head: text.call(:head), params: params.is_a?(Hash) ? stringified(params) : nil)
81
+ end
82
+
83
+ # +value+ with string keys all the way down (params as a file reads them).
84
+ def self.stringified(value)
85
+ case value
86
+ when Hash then value.to_h { |key, inner| [key.to_s, stringified(inner)] }
87
+ when Array then value.map { |inner| stringified(inner) }
88
+ else value
89
+ end
47
90
  end
48
91
 
49
92
  # The records of a saved list (others dropped).
@@ -52,11 +95,30 @@ module Samagotchi
52
95
  Array(raw).filter_map { |entry| from_h(entry) }
53
96
  end
54
97
 
55
- # The record (the wire's, the file's): without scope when it has none,
56
- # so a part that has no scope reads as an older chi wrote it.
98
+ # Each part's key, from the parts list alone (chi web's route takes it,
99
+ # the page's ws_sections.js startRows has the twin): "kind:ref" (the
100
+ # label without a ref), "@scope" when it has one, "#n" for the nth
101
+ # repeat of that in parts order (a duplicate preload: "preloads:x#2").
102
+ # spec/shared/prompt_part_keys.json holds both sides to one list.
103
+ # @param parts [Array<PromptPart, Hash>]
104
+ # @return [Array<String>]
105
+ def self.keys(parts)
106
+ seen = Hash.new(0)
107
+ list(parts).map do |part|
108
+ key = "#{part.kind}:#{part.ref || part.label}"
109
+ key = "#{key}@#{part.scope}" if part.scope
110
+ seen[key] += 1
111
+ seen[key] == 1 ? key : "#{key}##{seen[key]}"
112
+ end
113
+ end
114
+
115
+ # The record (the wire's, the file's): without scope and the place
116
+ # fields when it has none, so a part that has none reads as an older
117
+ # chi wrote it.
57
118
  def to_h
58
119
  hash = super
59
120
  hash.delete(:scope) if scope.nil?
121
+ PLACE.each { |key| hash.delete(key) if hash[key].nil? }
60
122
  hash
61
123
  end
62
124
 
@@ -13,16 +13,40 @@ module Samagotchi
13
13
  # after, a basename) and +enqueued_id+ (a file-delivered command's sender).
14
14
  # +author+: who sent it when it wasn't the owner ("p:<id>", as a turn's
15
15
  # origin author), nil for the owner.
16
+ # +private_args+: the arguments of a command whose catalog entry keeps
17
+ # them out of sight (/callback's address holds a one-time code): +line+,
18
+ # what every event, log line, bubble and echo reads, is then
19
+ # "/callback …", and only #run_line has them.
16
20
  QueuedCommand = Data.define(:command_id, :client_id, :line, :card, :mid_turn, :after_seq, :after_file, :enqueued_id,
17
- :author) do
21
+ :author, :private_args) do
18
22
  def initialize(command_id:, line:, client_id: nil, card: false, mid_turn: nil, after_seq: nil, after_file: nil,
19
- enqueued_id: nil, author: nil) = super
23
+ enqueued_id: nil, author: nil, private_args: nil) = super
24
+
25
+ # What #line shows for a command with private arguments.
26
+ HIDDEN = "…"
20
27
 
21
28
  # A new command with a fresh id.
22
- def self.mint(line, client_id: nil, card: false, author: nil)
23
- new(command_id: SecureRandom.uuid, client_id: client_id, line: line, card: card ? true : false, author: author)
29
+ # @param private_args [Boolean] its entry keeps the arguments out of
30
+ # sight (Commands::Registry#private_args?)
31
+ def self.mint(line, client_id: nil, card: false, author: nil, private_args: false)
32
+ args = nil
33
+ if private_args
34
+ name, rest = line.to_s.strip.split(/\s+/, 2)
35
+ if rest && !rest.empty?
36
+ args = rest
37
+ line = "#{name} #{HIDDEN}"
38
+ end
39
+ end
40
+ new(command_id: SecureRandom.uuid, client_id: client_id, line: line, card: card ? true : false, author: author,
41
+ private_args: args)
24
42
  end
25
43
 
44
+ # The line the session runs: #line, with its private arguments back.
45
+ def run_line = private_args ? "#{line.delete_suffix(" #{HIDDEN}")} #{private_args}" : line
46
+
47
+ # Never the private arguments (a log line or an error may print it).
48
+ def inspect = private_args ? super.sub(private_args.inspect, HIDDEN.inspect) : super
49
+
26
50
  # The fields its command_queued and command_ran name: card only when
27
51
  # it is a card's, author only when it isn't the owner's.
28
52
  # @return [Hash]
@@ -26,7 +26,14 @@ module Samagotchi
26
26
  # own recap.enabled (chi --set recap.enabled=true) only as the kwarg.
27
27
  #
28
28
  # @param recap [Hash, false, nil] the Engine's `recap:` kwarg
29
- # @param engine [Engine] the recap job's engine
29
+ # @param turn_state [TurnState] the Engine's (Engine#turn_state); a
30
+ # rebuilt job gets the same one
31
+ # @param messages_json [#call] → the conversation the recap summarizes,
32
+ # as a JSON string (Engine#messages_json_for_recap)
33
+ # @param emit_recap [#call] (recap:, generation:, covered:, created_at:)
34
+ # announces a written recap (Engine#emit_recap)
35
+ # @param on_usage [#call] (usage) records a recap request's SideUsage
36
+ # (Engine#note_side_usage)
30
37
  # @param host_registry [HostRegistry]
31
38
  # @param session_target [#call] → the session's current model as a recap target
32
39
  # @param session_id [#call] → String, nil
@@ -34,7 +41,7 @@ module Samagotchi
34
41
  # @param session_config [#call] → the session's own core settings
35
42
  # (SessionConfig::Settings#core), read once here
36
43
  # @return [IdleRecap, nil]
37
- def self.build(recap, engine:, host_registry:, session_target:, session_id:, state_dir:, session_config: -> { {} })
44
+ def self.build(recap, turn_state:, messages_json:, emit_recap:, on_usage:, host_registry:, session_target:, session_id:, state_dir:, session_config: -> { {} })
38
45
  return nil if recap == false
39
46
 
40
47
  session = session_config.call || {}
@@ -71,7 +78,9 @@ module Samagotchi
71
78
  end
72
79
 
73
80
  IdleRecap.new(
74
- engine: engine,
81
+ turn_state: turn_state,
82
+ messages_json: messages_json,
83
+ emit_recap: emit_recap,
75
84
  target: target,
76
85
  inactivity: recap_number_setting(kwarg_config, :inactivity, "recap.inactivity", IdleRecap::DEFAULT_INACTIVITY_SECONDS, :float),
77
86
  min_user_turns: recap_number_setting(kwarg_config, :min_user_turns, "recap.min_user_turns", IdleRecap::DEFAULT_MIN_USER_TURNS, :int),
@@ -79,7 +88,7 @@ module Samagotchi
79
88
  sentences: recap_sentences(string_config(kwarg_config, :sentences) || registry_string("recap.sentences", session: session)),
80
89
  store: RecapStore.new(session_id_lookup: -> { session_id.call }, state_dir_lookup: -> { state_dir.call }),
81
90
  session_id: -> { session_id.call },
82
- on_usage: ->(usage) { engine.note_side_usage(usage) }
91
+ on_usage: on_usage
83
92
  )
84
93
  end
85
94
 
@@ -35,8 +35,9 @@ module Samagotchi
35
35
  # @return [Boolean] +url+ is an http or https URL with a host and no
36
36
  # userinfo (a "https://github.com@evil.example/" shows one host and
37
37
  # opens another, and a token in it would be copied around)
38
- def self.http_url?(url)
39
- return false if url.length > MAX_URL
38
+ # +max+ is the length cap (a card's url action allows more: Plugin::Card)
39
+ def self.http_url?(url, max: MAX_URL)
40
+ return false if url.length > max
40
41
 
41
42
  uri = URI.parse(url)
42
43
  uri.is_a?(URI::HTTP) && !uri.host.to_s.empty? && uri.userinfo.nil?
@@ -14,9 +14,10 @@ module Samagotchi
14
14
  # answers its own question with that, only when it is about this session
15
15
  # and the question pending now, and is answered.
16
16
  class RelayVerifier
17
- # @param engine [Engine] this (the child's) worker's Engine
18
- def initialize(engine:, state_dir:, session_id:)
19
- @engine = engine
17
+ # @param question_desk [QuestionDesk] this (the child's) worker's question
18
+ # desk (Engine#question_desk)
19
+ def initialize(question_desk:, state_dir:, session_id:)
20
+ @question_desk = question_desk
20
21
  @state_dir = state_dir
21
22
  @session_id = session_id
22
23
  end
@@ -42,15 +43,15 @@ module Samagotchi
42
43
  parent_agent = relay["by"] != "user"
43
44
  client_id = "#{ClientId::RELAY_PREFIX}#{parent_id[0, 8]}"
44
45
  if answer["dismissed"]
45
- return not_pending(question_id) unless @engine.cancel_question("dismissed", id: question_id)
46
+ return not_pending(question_id) unless @question_desk.cancel("dismissed", id: question_id)
46
47
 
47
48
  log("relay_answered", relay_id, id: question_id, dismissed: true, by: relay["by"])
48
49
  return [{}, 200, { status: "dismissed", question_id: question_id }]
49
50
  end
50
51
 
51
52
  selected = labels(answer["selected_indices"], question_id) or return unverified("the answer's option is out of range", relay_id)
52
- result = @engine.answer_question(id: question_id, selected: selected, freeform: answer["freeform"],
53
- client_id: client_id, parent_agent: parent_agent)
53
+ result = @question_desk.answer(id: question_id, selected: selected, freeform: answer["freeform"],
54
+ client_id: client_id, parent_agent: parent_agent)
54
55
  log("relay_answered", relay_id, id: question_id, by: relay["by"])
55
56
  [{}, 200, { status: "answered", question_id: question_id, answer: result.to_h }]
56
57
  rescue QuestionDesk::NotPending
@@ -67,7 +68,7 @@ module Samagotchi
67
68
  # parent's are relabelled; the order is the same). nil when one is out
68
69
  # of range; [] for a freeform-only deny.
69
70
  def labels(indices, question_id)
70
- pending = @engine.pending_question
71
+ pending = @question_desk.pending
71
72
  return [] unless pending && pending.id.to_s == question_id
72
73
 
73
74
  options = Array(pending.options)
@@ -15,20 +15,20 @@ module Samagotchi
15
15
 
16
16
  module_function
17
17
 
18
- # @param engine [Engine] the child's
18
+ # @param question_desk [QuestionDesk] the child's (Engine#question_desk)
19
19
  # @param parent_dir [String] the parent session's folder (its sidecar)
20
20
  # @param live [#call] whether the parent's worker is up
21
21
  # @return [Thread]
22
- def start(engine:, question_id:, relay_id:, parent_dir:, interval: INTERVAL,
22
+ def start(question_desk:, question_id:, relay_id:, parent_dir:, interval: INTERVAL,
23
23
  live: -> { WorkerLink.resolve(parent_dir, unlink: false).live? })
24
24
  Thread.new do
25
25
  loop do
26
26
  sleep(interval)
27
- break unless relayed?(engine.pending_question, question_id, relay_id)
27
+ break unless relayed?(question_desk.pending, question_id, relay_id)
28
28
  next if live.call
29
29
 
30
30
  Log.info(:bridge, "relay_parent_gone", id: question_id)
31
- engine.annotate_question(question_id, relayed_to: nil, reason: "parent_gone")
31
+ question_desk.annotate(question_id, relayed_to: nil, reason: "parent_gone")
32
32
  break
33
33
  end
34
34
  rescue StandardError => e
@@ -196,15 +196,18 @@ module Samagotchi
196
196
  end
197
197
 
198
198
  # Whether +turn+ is a turn the caller can wait for: running now, queued
199
- # as its own turn, the last one to have ended, or an input a turn's
200
- # drain merged (its merge record: the wait follows it to that turn).
199
+ # as its own turn, the last one to have ended, one that ended with its
200
+ # reply file (SessionInbox.input_taken?'s evidence) or was settled, or
201
+ # an input a turn's drain merged (its merge record: the wait follows it
202
+ # to that turn).
201
203
  def known_turn?(session, session_dir:, turn:)
202
204
  id = turn.to_s
203
205
  return false if id.empty?
204
206
 
205
207
  running = session.status == Session::STATUS_RUNNING && session.interrupted_turn&.enqueued_id == id
206
208
  queued = SessionInbox.waiting_input(session_dir, id) == :turn_end
207
- ended = session.last_turn&.enqueued_id == id || !TurnCheckpoint.settled_turn(session_dir, id).nil?
209
+ ended = session.last_turn&.enqueued_id == id || !SessionInbox.reply_for(session_dir, id).nil? ||
210
+ !TurnCheckpoint.settled_turn(session_dir, id).nil?
208
211
  running || queued || ended || !SessionInbox.merged_into(session_dir, id).nil?
209
212
  end
210
213
 
@@ -214,8 +214,9 @@ module Samagotchi
214
214
  chi home [set [--ruby PATH] | doctor] the Ruby every chi launch boots
215
215
  chi project [init [DIR]] this folder's project; init makes a folder in no git repository one
216
216
  chi schedule <add|list|show|tick|run-now|enable|disable|cancel> durable schedules that outlive every worker
217
+ chi mcp serve chi as an MCP server on stdio (claude mcp add chi -- chi mcp serve)
217
218
  chi remote <add|ls|rm> other machines' chi web, for chi --remote NAME
218
- chi --remote NAME <send|answer|note|context|sessions|share> … those commands on that machine (or CHI_REMOTE=NAME)
219
+ chi --remote NAME <send|answer|note|context|sessions|share|mcp> … those commands on that machine (or CHI_REMOTE=NAME)
219
220
  chi --remote NAME --attach ID | --resume ID | --dir DIR [-p TEXT] a session on that machine, in this terminal
220
221
  chi self version, paths, model and bundles
221
222
  chi update [--dry-run] update this chi, its bundles and the desktop helper
@@ -186,7 +186,11 @@ module Samagotchi
186
186
 
187
187
  result = @schedules.tick(dry_run: @opts[:dry_run] ? true : false)
188
188
  if @opts[:format] == "json"
189
- @stdout.puts(JSON.pretty_generate({ "locked" => result.locked, "outcomes" => result.outcomes.map { |outcome| { "id" => outcome.id, "status" => outcome.status, "detail" => outcome.detail } } }))
189
+ outcomes = result.outcomes.map do |outcome|
190
+ line = { "id" => outcome.id, "status" => outcome.status, "detail" => outcome.detail }
191
+ outcome.disabled ? line.merge("disabled" => true) : line
192
+ end
193
+ @stdout.puts(JSON.pretty_generate({ "locked" => result.locked, "outcomes" => outcomes }))
190
194
  return CLI::Exit::OK
191
195
  end
192
196
 
@@ -201,7 +205,7 @@ module Samagotchi
201
205
 
202
206
  result.outcomes.each do |outcome|
203
207
  word = outcome.status == "dry" ? "would fire" : outcome.status
204
- @stdout.puts("#{outcome.id} #{word} #{outcome.detail}")
208
+ @stdout.puts("#{outcome.id} #{word} #{outcome.detail}#{" (disabled)" if outcome.disabled}")
205
209
  end
206
210
  CLI::Exit::OK
207
211
  rescue Schedules::Corrupt => e
@@ -216,7 +220,7 @@ module Samagotchi
216
220
  return failed("no schedule #{id}") if result.nil?
217
221
 
218
222
  if result.is_a?(Schedules::Outcome)
219
- @stdout.puts("#{id}: #{result.status} · #{result.detail}")
223
+ @stdout.puts("#{id}: #{result.status} · #{result.detail}#{" (disabled)" if result.disabled}")
220
224
  return result.status == "failed" ? CLI::Exit::FAILED : CLI::Exit::OK
221
225
  end
222
226
 
@@ -242,7 +246,17 @@ module Samagotchi
242
246
  def entry_line(entry)
243
247
  note = ""
244
248
  note += " skips #{entry.skips} of #{entry.max_skips} (#{skip_window(entry)})" if entry.skips.positive?
245
- note += " disabled after #{entry.failures} failures" unless entry.enabled
249
+ unless entry.enabled
250
+ note += if entry.last_result == "disabled"
251
+ " disabled"
252
+ elsif entry.skips >= entry.max_skips
253
+ " disabled after #{entry.skips} #{entry.skips == 1 ? "skip" : "skips"}"
254
+ elsif entry.failures >= entry.max_failures
255
+ " disabled after #{entry.failures} #{entry.failures == 1 ? "failure" : "failures"}"
256
+ else
257
+ " disabled"
258
+ end
259
+ end
246
260
  note += " last: #{entry.last_result}" if entry.last_result
247
261
  "#{entry.id} #{entry.mode} #{entry.recurrence_words} #{clock(entry.next_due)} #{entry.head[0, 8]}#{note}"
248
262
  end
@@ -163,9 +163,10 @@ module Samagotchi
163
163
  )
164
164
 
165
165
  # What one entry did in a tick: "fired", "skipped", "missed", "failed" or
166
- # "dry" (a --dry-run's "would fire"). +detail+ is the reason.
167
- Outcome = Data.define(:id, :title, :status, :detail, :entry) do
168
- def initialize(id:, status:, title: nil, detail: nil, entry: nil) = super
166
+ # "dry" (a --dry-run's "would fire"). +detail+ is the reason. +disabled+:
167
+ # this skip or failure used up a recurring entry's budget (#mark_disabled).
168
+ Outcome = Data.define(:id, :title, :status, :detail, :entry, :disabled, :session_id) do
169
+ def initialize(id:, status:, title: nil, detail: nil, entry: nil, disabled: false, session_id: nil) = super
169
170
  end
170
171
 
171
172
  # A whole tick.
@@ -348,6 +349,7 @@ module Samagotchi
348
349
  pending = []
349
350
  prune_after = []
350
351
  links = nil
352
+ started = []
351
353
 
352
354
  FileUtils.mkdir_p(@store_dir)
353
355
  FileUtils.mkdir_p(@state_dir)
@@ -359,7 +361,7 @@ module Samagotchi
359
361
  end
360
362
 
361
363
  file = read(strict: true)
362
- list = file.entries.grep(Entry)
364
+ list = started = file.entries.grep(Entry)
363
365
  # Ordered by the moment each entry is due, then id: with one chain
364
366
  # firing per tick, the entries of that chain take turns (a skipped
365
367
  # entry keeps its `next_due`, so the earliest waiting one goes next).
@@ -465,7 +467,7 @@ module Samagotchi
465
467
  end
466
468
  links ||= links_now unless prune_after.empty?
467
469
  prune_after.each { |entry| prune(entry, links) }
468
- Tick.new(locked: false, outcomes: outcomes)
470
+ Tick.new(locked: false, outcomes: dry_run ? outcomes : mark_disabled(outcomes, started, links: links))
469
471
  end
470
472
 
471
473
  # Fire one entry now, whatever its next_due says (`chi schedule run-now`).
@@ -515,10 +517,10 @@ module Samagotchi
515
517
  file.entries[position] = reserved
516
518
  end
517
519
 
518
- return outcome if outcome
520
+ return mark_disabled([outcome], [entry], links: links).first if outcome
519
521
  return Outcome.new(id: entry.id, title: entry.title, status: "failed", detail: "no such schedule") unless reserved
520
522
 
521
- fire_and_record(reserved, links)
523
+ mark_disabled([fire_and_record(reserved, links)], [entry], links: links).first
522
524
  end
523
525
 
524
526
  # Minutes between the hub's ticks when schedule.auto_tick is on.
@@ -695,7 +697,9 @@ module Samagotchi
695
697
  file.entries[position] = nil
696
698
  file.entries.compact!
697
699
  else
698
- file.entries[position] = entry.with(enabled: enabled, last_result: enabled ? "enabled" : "disabled")
700
+ changed = entry.with(enabled: enabled, last_result: enabled ? "enabled" : "disabled")
701
+ # Enabled again with a fresh budget: its next skip must not end it at once.
702
+ file.entries[position] = enabled ? changed.with(skips: 0, failures: 0) : changed
699
703
  end
700
704
  end
701
705
  entry
@@ -792,6 +796,34 @@ module Samagotchi
792
796
  enabled: one_off ? false : entry.enabled)
793
797
  end
794
798
 
799
+ # The skips and failures that turned off a recurring entry that was on when
800
+ # the pass began (+before+), as the file has it now: one diff covers every
801
+ # path that records one. A `date` one-off is spent, not disabled; an entry
802
+ # off within budget is an owner's `chi schedule disable`.
803
+ def mark_disabled(outcomes, before, links: nil)
804
+ ended = outcomes.select { |outcome| %w[skipped failed].include?(outcome.status) }.map(&:id)
805
+ status_by_id = outcomes.select { |outcome| %w[skipped failed].include?(outcome.status) }
806
+ .to_h { |outcome| [outcome.id, outcome.status] }
807
+ on = before.select { |entry| entry.enabled && entry.recurrence[:kind] != "date" && ended.include?(entry.id) }.map(&:id)
808
+ return outcomes if on.empty?
809
+
810
+ off = read.entries.grep(Entry).select do |entry|
811
+ budget_reached = case status_by_id[entry.id]
812
+ when "skipped" then entry.skips >= entry.max_skips
813
+ when "failed" then entry.failures >= entry.max_failures
814
+ else false
815
+ end
816
+ on.include?(entry.id) && !entry.enabled && budget_reached
817
+ end
818
+ links ||= links_now unless off.empty?
819
+ off.each do |entry|
820
+ index = outcomes.rindex { |outcome| outcome.id == entry.id && %w[skipped failed].include?(outcome.status) }
821
+ session_id = target_of(entry, links).first || entry.head
822
+ outcomes[index] = outcomes[index].with(disabled: true, entry: entry, session_id: session_id)
823
+ end
824
+ outcomes
825
+ end
826
+
795
827
  def skipped(entry, reason)
796
828
  skips = entry.skips + 1
797
829
  disabled = skips >= entry.max_skips
@@ -28,6 +28,7 @@ require_relative "cli/parent_wait"
28
28
  require_relative "send_command/parent_gate"
29
29
  require_relative "send_command/busy"
30
30
  require_relative "session_access/local"
31
+ require_relative "session_access/exchange"
31
32
 
32
33
  module Samagotchi
33
34
  # `chi send`: put text into sessions as the user's message, the same as
@@ -792,27 +793,25 @@ module Samagotchi
792
793
 
793
794
  id = target.id
794
795
  short = target.label
795
- session = @access.show(id)
796
- # Machine-local (this machine's model registry): remotely the
797
- # server's (P2), as for --new.
798
- if !@images.empty? && (refusal = vision_refusal(session.model_name, typed: session.model_typed))
799
- @info.puts("#{short} refused: #{refusal}")
800
- return false
801
- end
802
- owner = @access.owner(id)
803
- running = owner && session.status == Session::STATUS_RUNNING
804
- refs = upload_images(id)
805
796
  # --cut asks the running turn for a cut (to an idle session an
806
797
  # ordinary message: nothing to cut). --queue always goes as a queue,
807
798
  # idle or not: the Bridge acks next_step to an idle worker and the
808
799
  # file still carries it, so a turn another client starts first never
809
800
  # merges it, and its turn and reply carry its enqueued_id (the
810
801
  # --wait's turn:); a worker older than queueing is refused.
811
- delivery = if @queue then Delivery::QUEUE
812
- elsif @cut && running then Delivery::CUT
813
- end
814
- result = @access.deliver_turn(id, prompt: prompt, client_id: client_id_for(prompt), images: refs, delivery: delivery,
815
- follow: target.via != :pinned)
802
+ # The vision check is machine-local (this machine's model registry):
803
+ # remotely the server's (P2), as for --new.
804
+ pass = exchange.attempt(target, prompt, client_id: client_id_for(prompt), queue: @queue, cut: @cut,
805
+ images: ImageUpload.new(method(:upload_images)), check: method(:image_check))
806
+ if pass.is_a?(SessionAccess::Exchange::Stopped)
807
+ @info.puts("#{short} refused: #{pass.refusal}")
808
+ return false
809
+ end
810
+ owner = pass.owner
811
+ running = pass.running
812
+ refs = pass.refs
813
+ delivery = pass.delivery
814
+ result = pass.result
816
815
  if result.continued?
817
816
  # Copied in before the refusal: not the old link's to keep.
818
817
  @access.discard_images(id, refs)
@@ -973,38 +972,52 @@ module Samagotchi
973
972
  # is never sent to (a send would un-archive it beside the new one).
974
973
  # @return [SessionInbox::Resolved, Unsent]
975
974
  def target(given)
976
- id = @access.resolve(given)
977
- head = @access.head(id)
978
- deadline = monotonic + self.class::CONTINUING_WAIT
979
- waited = head.continuing?
980
- while head.continuing? && monotonic < deadline
981
- self.class.pause(self.class::CONTINUING_POLL)
982
- head = @access.head(id)
983
- end
984
- return Unsent.new(line: "#{id[0, 8]} refused: #{head.continuing_refusal}", error: false, asked: id) if head.continuing?
975
+ found = exchange.locate(given)
976
+ return unsent_of(found) if found.is_a?(SessionAccess::Exchange::Unsent)
985
977
 
986
- (@continued_here ||= {})[head.id] = true if waited
987
- head
988
- rescue ArgumentError => e
989
- Unsent.new(line: "#{command_name}: #{e.message}", error: true)
978
+ (@continued_here ||= {})[found.target.id] = true if found.waited
979
+ found.target
980
+ end
981
+
982
+ # An Exchange::Unsent as the line chi send prints: a continue in
983
+ # flight's refusal (info), or the resolve's error (+error+ true).
984
+ def unsent_of(found)
985
+ if found.reason == :continuing
986
+ Unsent.new(line: "#{found.asked[0, 8]} refused: #{found.message}", error: false, asked: found.asked)
987
+ else
988
+ Unsent.new(line: "#{command_name}: #{found.message}", error: true)
989
+ end
990
990
  end
991
991
 
992
992
  # +refused+'s id resolved again after a continue took its link
993
- # (#deliver): #target, pausing between looks while it still names that
994
- # link, until +deadline+. The new link's worker is the continue's spawn
995
- # to start (#delivery_note).
993
+ # (#deliver): Exchange#relocate, until +deadline+. The new link's
994
+ # worker is the continue's spawn to start (#delivery_note).
996
995
  # @return [SessionInbox::Resolved, Unsent, nil] nil: out of time
997
996
  def follow_again(refused, deadline)
998
- while monotonic < deadline
999
- self.class.pause(self.class::CONTINUING_POLL)
1000
- again = target(refused.asked)
1001
- return again unless again.is_a?(SessionInbox::Resolved)
1002
- next if again.id == refused.id
1003
-
1004
- (@continued_here ||= {})[again.id] = true
1005
- return again
1006
- end
1007
- nil
997
+ again = exchange.relocate(refused, deadline) { |look| (@continued_here ||= {})[look.target.id] = true }
998
+ return nil unless again
999
+ return unsent_of(again) if again.is_a?(SessionAccess::Exchange::Unsent)
1000
+
1001
+ (@continued_here ||= {})[again.target.id] = true
1002
+ again.target
1003
+ end
1004
+
1005
+ # The send's Exchange: the class's pause and continue wait, read when
1006
+ # it is built (the specs stub both).
1007
+ def exchange
1008
+ @exchange ||= SessionAccess::Exchange.new(@access, pause: ->(seconds) { self.class.pause(seconds) },
1009
+ continuing_wait: self.class::CONTINUING_WAIT,
1010
+ continuing_poll: self.class::CONTINUING_POLL)
1011
+ end
1012
+
1013
+ # Exchange#attempt's images: this send's, copied into each target.
1014
+ ImageUpload = Data.define(:uploader) do
1015
+ def upload(id) = uploader.call(id)
1016
+ end
1017
+
1018
+ # Exchange#attempt's check: images to a model known not to take them.
1019
+ def image_check(session)
1020
+ vision_refusal(session.model_name, typed: session.model_typed) unless @images.empty?
1008
1021
  end
1009
1022
 
1010
1023
  def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)