samagotchi 0.192.0 → 0.194.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 (190) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +128 -1
  3. data/docs/architecture.md +3 -3
  4. data/docs/bundle-authoring.md +1 -1
  5. data/docs/bundles.md +82 -40
  6. data/docs/cli.md +47 -17
  7. data/docs/configuration.md +75 -8
  8. data/docs/context.md +8 -5
  9. data/docs/desktop.md +3 -0
  10. data/docs/guardrails.md +20 -5
  11. data/docs/hooks.md +1 -0
  12. data/docs/internals/bridge.md +3 -1
  13. data/docs/internals/bundles.md +2 -2
  14. data/docs/internals/engine.md +46 -3
  15. data/docs/internals/pages.md +4 -4
  16. data/docs/internals/panes.md +66 -0
  17. data/docs/internals/participants.md +5 -3
  18. data/docs/internals/peers.md +176 -27
  19. data/docs/internals/prompt-caching.md +6 -1
  20. data/docs/internals/remote-sessions.md +6 -0
  21. data/docs/internals/session-lifecycle.md +12 -4
  22. data/docs/internals/web-frontend.md +106 -22
  23. data/docs/internals/working-set.md +5 -1
  24. data/docs/peers.md +150 -27
  25. data/docs/plugins.md +48 -7
  26. data/docs/releasing.md +30 -2
  27. data/docs/scheduling.md +3 -2
  28. data/docs/sessions.md +16 -7
  29. data/docs/sub-agent.md +6 -4
  30. data/docs/system-one.md +4 -0
  31. data/docs/testing.md +38 -3
  32. data/docs/thin-clients.md +27 -11
  33. data/lib/samagotchi/bridge/card_store.rb +1 -1
  34. data/lib/samagotchi/broadcast/triage_model.rb +17 -0
  35. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  36. data/lib/samagotchi/bundles/claude-peer/plugin.rb +24 -5
  37. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +61 -24
  38. data/lib/samagotchi/bundles/claude-peer/scripts/pair +31 -8
  39. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  40. data/lib/samagotchi/bundles/codex-peer/plugin.rb +62 -6
  41. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +57 -19
  42. data/lib/samagotchi/bundles/codex-peer/scripts/pair +28 -7
  43. data/lib/samagotchi/bundles/coordinator/manifest.yml +2 -2
  44. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +31 -0
  45. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  46. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  47. data/lib/samagotchi/bundles/mcp/plugin.rb +0 -7
  48. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  49. data/lib/samagotchi/chi_invocation.rb +7 -0
  50. data/lib/samagotchi/client.rb +18 -0
  51. data/lib/samagotchi/codex_rollout.rb +93 -0
  52. data/lib/samagotchi/compat.rb +8 -1
  53. data/lib/samagotchi/config.rb +19 -6
  54. data/lib/samagotchi/continue_offer.rb +13 -1
  55. data/lib/samagotchi/delivery.rb +2 -2
  56. data/lib/samagotchi/effective_model.rb +28 -2
  57. data/lib/samagotchi/engine/cards.rb +9 -4
  58. data/lib/samagotchi/engine/hooks.rb +8 -0
  59. data/lib/samagotchi/engine/models.rb +197 -7
  60. data/lib/samagotchi/engine/plugins.rb +2 -0
  61. data/lib/samagotchi/engine/side_requests.rb +72 -13
  62. data/lib/samagotchi/engine/toolkit.rb +1 -1
  63. data/lib/samagotchi/engine/turn_helpers.rb +1 -1
  64. data/lib/samagotchi/engine.rb +11 -8
  65. data/lib/samagotchi/engine_snapshots.rb +16 -3
  66. data/lib/samagotchi/events.rb +1 -0
  67. data/lib/samagotchi/guardrails/pair_boundary.rb +49 -18
  68. data/lib/samagotchi/hooks.rb +3 -1
  69. data/lib/samagotchi/host_registry.rb +146 -16
  70. data/lib/samagotchi/idle_client.rb +13 -2
  71. data/lib/samagotchi/idle_recap.rb +33 -3
  72. data/lib/samagotchi/idle_target.rb +27 -7
  73. data/lib/samagotchi/jsonl_store.rb +13 -2
  74. data/lib/samagotchi/llm/adapter_common.rb +4 -2
  75. data/lib/samagotchi/llm/anthropic_messages.rb +14 -2
  76. data/lib/samagotchi/llm/errors.rb +35 -4
  77. data/lib/samagotchi/llm/model_listing.rb +19 -0
  78. data/lib/samagotchi/llm/openai_chat.rb +8 -2
  79. data/lib/samagotchi/llm/prompt_cache.rb +5 -0
  80. data/lib/samagotchi/model_binding.rb +46 -4
  81. data/lib/samagotchi/model_catalog.rb +68 -8
  82. data/lib/samagotchi/model_profile.rb +35 -0
  83. data/lib/samagotchi/models_command.rb +8 -4
  84. data/lib/samagotchi/pages/launch.rb +1 -1
  85. data/lib/samagotchi/panes/kitty.rb +122 -0
  86. data/lib/samagotchi/panes.rb +185 -0
  87. data/lib/samagotchi/peer_announce.rb +245 -0
  88. data/lib/samagotchi/peer_cold.rb +92 -0
  89. data/lib/samagotchi/peer_command.rb +121 -20
  90. data/lib/samagotchi/peer_continue.rb +42 -16
  91. data/lib/samagotchi/peer_exchanges.rb +7 -0
  92. data/lib/samagotchi/peer_mailbox.rb +50 -10
  93. data/lib/samagotchi/peer_pair_here.rb +149 -0
  94. data/lib/samagotchi/peer_presence.rb +434 -0
  95. data/lib/samagotchi/peer_receipts.rb +33 -6
  96. data/lib/samagotchi/peer_say.rb +46 -21
  97. data/lib/samagotchi/peer_wait_expiry.rb +47 -0
  98. data/lib/samagotchi/plugin/api.rb +13 -1
  99. data/lib/samagotchi/plugin/card.rb +68 -11
  100. data/lib/samagotchi/plugin/context.rb +33 -2
  101. data/lib/samagotchi/plugin/panes.rb +54 -0
  102. data/lib/samagotchi/plugin/peer.rb +170 -63
  103. data/lib/samagotchi/plugin/peer_pairing.rb +290 -0
  104. data/lib/samagotchi/plugin/peer_start.rb +301 -0
  105. data/lib/samagotchi/plugin/peer_start_hook.rb +207 -0
  106. data/lib/samagotchi/plugin/peers.rb +89 -9
  107. data/lib/samagotchi/recap_setup.rb +40 -3
  108. data/lib/samagotchi/self_report.rb +25 -6
  109. data/lib/samagotchi/send_command.rb +6 -6
  110. data/lib/samagotchi/served_lookup.rb +225 -0
  111. data/lib/samagotchi/served_ref.rb +41 -0
  112. data/lib/samagotchi/session_access/contract.rb +6 -0
  113. data/lib/samagotchi/session_access/local.rb +149 -40
  114. data/lib/samagotchi/session_access/remote.rb +4 -4
  115. data/lib/samagotchi/session_access/remote_peers.rb +8 -5
  116. data/lib/samagotchi/session_chain/links.rb +8 -3
  117. data/lib/samagotchi/session_commands.rb +40 -8
  118. data/lib/samagotchi/session_continue.rb +11 -6
  119. data/lib/samagotchi/session_lifecycle/allowed.rb +4 -2
  120. data/lib/samagotchi/session_manager/delivery.rb +5 -0
  121. data/lib/samagotchi/session_manager/lifecycle.rb +58 -7
  122. data/lib/samagotchi/session_manager/removal.rb +3 -0
  123. data/lib/samagotchi/session_manager/spawn.rb +6 -1
  124. data/lib/samagotchi/session_model_settings.rb +7 -3
  125. data/lib/samagotchi/session_stores.rb +25 -11
  126. data/lib/samagotchi/sessions_command.rb +16 -3
  127. data/lib/samagotchi/system_one/http_backend.rb +111 -10
  128. data/lib/samagotchi/system_one/runs.rb +5 -2
  129. data/lib/samagotchi/system_prompt.rb +11 -4
  130. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -1
  131. data/lib/samagotchi/terminal_ui/formatting.rb +26 -12
  132. data/lib/samagotchi/terminal_ui/status_row.rb +20 -3
  133. data/lib/samagotchi/terminal_ui.rb +1 -1
  134. data/lib/samagotchi/testing/boundary.rb +0 -1
  135. data/lib/samagotchi/testing/bundle.rb +6 -2
  136. data/lib/samagotchi/testing/host.rb +1 -0
  137. data/lib/samagotchi/testing/recorder.rb +3 -0
  138. data/lib/samagotchi/turn_endings.rb +6 -2
  139. data/lib/samagotchi/user_typed.rb +29 -0
  140. data/lib/samagotchi/version.rb +1 -1
  141. data/lib/samagotchi/web/app.rb +8 -20
  142. data/lib/samagotchi/web/participant_review.rb +1 -1
  143. data/lib/samagotchi/web/participant_view.rb +1 -1
  144. data/lib/samagotchi/web/peer_routes.rb +40 -15
  145. data/lib/samagotchi/web/public/agent_rows.js +206 -0
  146. data/lib/samagotchi/web/public/agent_runs.js +595 -0
  147. data/lib/samagotchi/web/public/answer_fold.js +41 -44
  148. data/lib/samagotchi/web/public/app.js +4 -4
  149. data/lib/samagotchi/web/public/block_fix.js +1 -1
  150. data/lib/samagotchi/web/public/card.js +26 -10
  151. data/lib/samagotchi/web/public/cards_place.js +6 -4
  152. data/lib/samagotchi/web/public/context_chips.js +24 -2
  153. data/lib/samagotchi/web/public/copy.js +8 -2
  154. data/lib/samagotchi/web/public/data.js +2 -1
  155. data/lib/samagotchi/web/public/format.js +9 -1
  156. data/lib/samagotchi/web/public/history_reveal.js +5 -2
  157. data/lib/samagotchi/web/public/index.html +56 -2
  158. data/lib/samagotchi/web/public/info_bar_model.js +1 -1
  159. data/lib/samagotchi/web/public/model_pick.js +18 -5
  160. data/lib/samagotchi/web/public/model_picker.js +1 -1
  161. data/lib/samagotchi/web/public/page_view.js +1 -1
  162. data/lib/samagotchi/web/public/pages.css +1 -7
  163. data/lib/samagotchi/web/public/peer_chip.js +15 -5
  164. data/lib/samagotchi/web/public/peer_data.js +4 -2
  165. data/lib/samagotchi/web/public/peer_mailbox_api.js +2 -1
  166. data/lib/samagotchi/web/public/peer_note.js +4 -2
  167. data/lib/samagotchi/web/public/peer_row.js +37 -0
  168. data/lib/samagotchi/web/public/peer_wait.js +36 -0
  169. data/lib/samagotchi/web/public/quiet_notes.js +12 -1
  170. data/lib/samagotchi/web/public/revise_stack.js +5 -2
  171. data/lib/samagotchi/web/public/send_turn.js +11 -3
  172. data/lib/samagotchi/web/public/served_ref.js +9 -0
  173. data/lib/samagotchi/web/public/session_fields.js +1 -0
  174. data/lib/samagotchi/web/public/session_state.js +4 -0
  175. data/lib/samagotchi/web/public/stage_missing.js +23 -6
  176. data/lib/samagotchi/web/public/stream_handlers.js +16 -0
  177. data/lib/samagotchi/web/public/turn_block.js +4 -0
  178. data/lib/samagotchi/web/public/version_notices.js +7 -1
  179. data/lib/samagotchi/web/session_control.rb +19 -10
  180. data/lib/samagotchi/web/session_show.rb +20 -0
  181. data/lib/samagotchi/web/update_ops.rb +2 -2
  182. data/lib/samagotchi/worker/command_queue.rb +3 -0
  183. data/lib/samagotchi/worker/mail.rb +24 -1
  184. data/lib/samagotchi/worker.rb +8 -5
  185. data/lib/samagotchi/worker_inbound/mail.rb +34 -6
  186. data/lib/samagotchi/worker_inbound.rb +11 -3
  187. data/lib/samagotchi/worker_link.rb +13 -1
  188. data/lib/samagotchi/worker_wakes.rb +33 -5
  189. metadata +22 -2
  190. data/lib/samagotchi/web/public/pages_group.js +0 -67
@@ -1,7 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "json"
4
+ require_relative "peer_announce"
4
5
  require_relative "peer_mailbox"
6
+ require_relative "peer_pair_here"
5
7
  require_relative "peer_say"
6
8
  require_relative "peer_roster"
7
9
  require_relative "session"
@@ -12,17 +14,24 @@ require_relative "session_access/local"
12
14
 
13
15
  module Samagotchi
14
16
  # `chi peer`: a peer agent's side of a session (PeerMailbox). The pair
15
- # scripts run pair; the peer's skill runs say for every message and quotes
16
- # the line it prints (what chi did with it, PeerSay); ls is what the owner
17
- # or the peer looks at. Through --remote the remote's chi web does the
17
+ # scripts run pair (pair --here with no id); the peer's skill runs say for
18
+ # every message and quotes the line it prints (what chi did with it,
19
+ # PeerSay); ls is what the owner or the peer looks at; announce is Claude
20
+ # Code's and Codex's start hook (PeerAnnounce). Through --remote the remote's chi web does the
18
21
  # same (SessionAccess::Remote).
19
22
  class PeerCommand
20
23
  include CLI::Command
21
24
 
22
25
  USAGE = <<~TEXT
23
- Usage: chi peer <pair|unpair|say|ls> [options]
24
- pair NAME ID [--address ADDR] [--from TEXT] pair peer NAME with session ID
25
- --address: where chi's sends go (none: it only answers); --from: who paired
26
+ Usage: chi peer <pair|unpair|say|ls|announce> [options]
27
+ pair NAME ID [--address ADDR] [--from TEXT] [--peer-session ID] pair peer NAME with session ID
28
+ --address: where chi's sends go (none: it only answers); --from: who paired;
29
+ --peer-session: the peer's own session id (a resume finds its pairings by it)
30
+ pair NAME --here --address ADDR [--from TEXT] [--peer-session ID]
31
+ no id: the session that waits for NAME in this folder's project, else its live session paired
32
+ with this peer already (said paired), else its one live session
33
+ announce NAME a peer's start hook (stdin: the hook's JSON): claude lists this Claude
34
+ here; codex pairs a new interactive Codex with a waiting session
26
35
  unpair NAME ID end the pairing (its messages stay)
27
36
  say NAME ID (--wake|--nowake) [--summary TEXT] [--re REF] [-m TEXT] [--wait SECONDS]
28
37
  a message from NAME (stdin without -m); prints what chi did with it.
@@ -33,13 +42,17 @@ module Samagotchi
33
42
  ID: a session id or unique prefix. Find ids with: chi sessions list [--live]
34
43
  TEXT
35
44
 
36
- SUBCOMMANDS = %w[pair unpair say ls].freeze
45
+ SUBCOMMANDS = %w[pair unpair say ls announce].freeze
37
46
 
38
47
  FLAGS = {
39
48
  "pair" => CLI::Flags.new(help: HELP_WORDS) do |f|
40
49
  f.value "--address"
41
50
  f.value "--from"
51
+ f.value "--peer-session"
52
+ f.switch "--here"
42
53
  end,
54
+ # The hook passes no flags; anything else is ignored (it prints nothing).
55
+ "announce" => CLI::Flags.new(help: HELP_WORDS),
43
56
  "unpair" => CLI::Flags.new(help: HELP_WORDS),
44
57
  "say" => CLI::Flags.new(help: HELP_WORDS) do |f|
45
58
  f.switch "--wake"
@@ -56,7 +69,9 @@ module Samagotchi
56
69
  # @param access [SessionAccess::Local, SessionAccess::Remote, nil] where
57
70
  # the sessions are; default this machine's, in +state_dir+
58
71
  # @param sleeper [#call, nil] a say's wait between two looks (specs)
59
- def initialize(argv, stdin: $stdin, stdout: $stdout, stderr: $stderr, state_dir: nil, access: nil, sleeper: nil)
72
+ # @param env [Hash] announce reads Claude Code's hook env from it
73
+ def initialize(argv, stdin: $stdin, stdout: $stdout, stderr: $stderr, state_dir: nil, access: nil, sleeper: nil, env: ENV)
74
+ @env = env
60
75
  @argv = argv.dup
61
76
  @stdin = stdin
62
77
  @stdout = stdout
@@ -74,6 +89,8 @@ module Samagotchi
74
89
  return 0
75
90
  end
76
91
  return usage_error("unknown subcommand #{@sub}") unless SUBCOMMANDS.include?(@sub)
92
+ # The start hook's: never a word on stderr, always exit 0.
93
+ return run_announce(@argv[1]) if @sub == "announce"
77
94
 
78
95
  parsed = parse_flags(FLAGS.fetch(@sub), @argv[1..])
79
96
  return parsed if parsed.is_a?(Integer)
@@ -102,31 +119,105 @@ module Samagotchi
102
119
  end
103
120
 
104
121
  def run_pair(options, args)
122
+ return run_pair_here(options, args) if options[:here]
123
+
105
124
  checked = name_and_id(args)
106
125
  return checked if checked.is_a?(Integer)
107
126
 
108
127
  name, id = checked
109
- paired = @access.peer_pair(id, name, address: options[:address], from: options[:from])
110
- unless paired.status == :paired
128
+ paired = @access.peer_pair(id, name, address: options[:address], from: options[:from],
129
+ peer_session: options[:peer_session])
130
+ paired_line(name, id, paired)
131
+ end
132
+
133
+ # The pairing's line ("3f2a9c1e paired with Claude"; :same, a pairing
134
+ # kept as it was, says the same), or its refusal.
135
+ def paired_line(name, id, paired)
136
+ unless %i[paired same].include?(paired.status)
111
137
  error_line("#{command_name}: #{paired.refusal}")
112
138
  return CLI::Exit::FAILED
113
139
  end
114
140
 
115
- @stdout.puts("#{id[0, 8]} paired with #{PeerMailbox.label(name)}")
141
+ @stdout.puts("#{(paired.forwarded_to || id)[0, 8]} paired with #{PeerMailbox.label(name)}#{continued(id, paired.forwarded_to)}")
116
142
  0
117
143
  end
118
144
 
145
+ # pair NAME --here (PeerPairHere): the session that waits in this
146
+ # folder's project, else its one live session; else exit 1 with the
147
+ # candidates. A refused pairing gives a claimed mark back.
148
+ def run_pair_here(options, args)
149
+ return usage_error("give the peer's NAME and no session ID with --here") unless args.size == 1
150
+ return usage_error(PeerMailbox.name_problem(args.first)) unless PeerMailbox.valid_name?(args.first)
151
+ return usage_error("--here needs --address (where chi's sends go)") if options[:address].to_s.empty?
152
+
153
+ name = args.first
154
+ here = PeerPairHere.new(name, access: @access, state_dir: @state_dir)
155
+ peer_session = here.peer_session(options[:peer_session], options[:address])
156
+ found = here.resolve(peer_session: peer_session, address: options[:address])
157
+ if found.refusal
158
+ found.refusal.each_with_index { |line, index| error_line(index.zero? ? "#{command_name}: #{line}" : line) }
159
+ return CLI::Exit::FAILED
160
+ end
161
+ if (same = found.same)
162
+ # The project's session already paired with this peer wins: kept as
163
+ # it is when nothing changed, else paired again with this address
164
+ # and peer session (its own, when none was given).
165
+ peer_session ||= same.peer_session
166
+ kept = same.address.to_s == options[:address].to_s && same.peer_session == peer_session
167
+ return paired_line(name, found.id, PeerPaired.new(status: :same, link: same)) if kept
168
+ end
169
+
170
+ paired = begin
171
+ @access.peer_pair(found.id, name, address: options[:address], from: options[:from],
172
+ peer_session: peer_session)
173
+ rescue StandardError
174
+ PeerPresence.release(found.claim)
175
+ raise
176
+ end
177
+ PeerPresence.release(found.claim) unless paired.status == :paired
178
+ ended_gone(name, found.gone) if found.gone && paired.status == :paired
179
+ paired_line(name, found.id, paired)
180
+ end
181
+
182
+ # The pairing --here replaced, its peer gone: its pairing file dropped,
183
+ # and said on stderr (the pair script reads stdout's first word).
184
+ def ended_gone(name, gone)
185
+ old = gone.link
186
+ PeerPresence.drop_paired(name, old.peer_session, gone.head, state_dir: @state_dir) if old.peer_session
187
+ error_line("#{command_name}: the #{PeerMailbox.label(name)} chi #{gone.head[0, 8]} was paired with is gone " \
188
+ "(no inbox at #{old.address}): that pairing ended")
189
+ end
190
+
191
+ # announce NAME (PeerAnnounce): its lines on stdout, for the peer's start
192
+ # context; nothing on any failure, exit 0.
193
+ def run_announce(name)
194
+ lines = PeerAnnounce.new(name.to_s, stdin: @stdin, env: @env, access: @access, state_dir: @state_dir).run
195
+ lines.each { |line| @stdout.puts(line) }
196
+ 0
197
+ rescue StandardError # degrade-ok: the start hook prints nothing on any failure (PeerAnnounce)
198
+ 0
199
+ end
200
+
201
+ # The tail naming the chain's live link a command of +id+ ran on.
202
+ def continued(id, forwarded_to) = forwarded_to ? " (session #{id[0, 8]} continued as #{forwarded_to[0, 8]})" : ""
203
+
119
204
  def run_unpair(_options, args)
120
205
  checked = name_and_id(args)
121
206
  return checked if checked.is_a?(Integer)
122
207
 
123
208
  name, id = checked
124
- unless @access.peer_unpair(id, name)
125
- error_line("#{command_name}: #{id[0, 8]} isn't paired with #{name}")
209
+ ended = @access.peer_unpair(id, name)
210
+ if !ended.unpaired && ended.waited
211
+ @stdout.puts("#{(ended.forwarded_to || id)[0, 8]} stopped waiting for #{PeerMailbox.label(name)}#{continued(id, ended.forwarded_to)}")
212
+ return 0
213
+ end
214
+ unless ended.unpaired
215
+ error_line("#{command_name}: #{(ended.forwarded_to || id)[0, 8]} isn't paired with #{name}#{continued(id, ended.forwarded_to)}")
126
216
  return CLI::Exit::FAILED
127
217
  end
128
218
 
129
- @stdout.puts("#{id[0, 8]} unpaired from #{PeerMailbox.label(name)} (its messages stay)")
219
+ @stdout.puts("#{(ended.forwarded_to || id)[0, 8]} unpaired from #{PeerMailbox.label(name)} (its messages stay)" \
220
+ "#{continued(id, ended.forwarded_to)}")
130
221
  0
131
222
  end
132
223
 
@@ -149,7 +240,7 @@ module Samagotchi
149
240
  return CLI::Exit::FAILED
150
241
  end
151
242
 
152
- @stdout.puts(said.line(name))
243
+ @stdout.puts(said.line(name, id: id, via: @access.invocation))
153
244
  said.receipt&.state == "refused" ? CLI::Exit::FAILED : 0
154
245
  end
155
246
 
@@ -170,17 +261,27 @@ module Samagotchi
170
261
  return usage_error("give the session ID") unless args.size == 1
171
262
 
172
263
  id = @access.resolve_id(args.first)
173
- peers = @access.peer_list(id)
264
+ on = live_link(id)
265
+ peers = @access.peer_list(on)
174
266
  if options[:format] == "json"
175
267
  @stdout.puts(JSON.pretty_generate(peers.map(&:to_h)))
176
- elsif peers.empty?
177
- @stdout.puts("no peers")
178
- else
179
- peers.each { |peer| print_peer(peer) }
268
+ return 0
180
269
  end
270
+
271
+ @stdout.puts("session #{id[0, 8]} continued as #{on[0, 8]}: its peers") unless on == id
272
+ @stdout.puts("no peers") if peers.empty?
273
+ peers.each { |peer| print_peer(peer) }
181
274
  0
182
275
  end
183
276
 
277
+ # The link ls lists for +id+: its chain's live link when it was continued
278
+ # (the access's head, as chi send's), else +id+ (a continue in flight
279
+ # too: its new link isn't saved yet).
280
+ def live_link(id)
281
+ resolved = @access.head(id)
282
+ resolved.via == :head ? resolved.id : id
283
+ end
284
+
184
285
  def print_peer(peer)
185
286
  paired = peer.paired? ? "paired #{peer.paired_at}#{" by #{peer.from}" if peer.from}" : "not paired"
186
287
  @stdout.puts("#{peer.name} #{paired}#{" sends to #{peer.address}" if peer.address}")
@@ -2,20 +2,23 @@
2
2
 
3
3
  require_relative "peer_mailbox"
4
4
  require_relative "peer_note"
5
+ require_relative "peer_presence"
5
6
  require_relative "peer_receipts"
6
7
  require_relative "session_inbox"
7
8
  require_relative "log"
8
9
 
9
10
  module Samagotchi
10
- # A continue's peer step (SessionContinue::CARRY :peers): the pairing and
11
- # the mailbox stay with the previous link (the peer is told the new id,
12
- # Plugin::Peer#tell_moved, and pairs again), and what the peers said that
13
- # the previous link hadn't read reaches the new link as ONE note: the
14
- # messages its worker never took (untaken), and those it took as notes no
15
- # turn read (receipts still held or noted). Read only: nothing in the
16
- # previous link's mailbox or receipts changes, so a failed continue has
17
- # nothing to undo (the note goes with the failed link). Runs in the new
18
- # link's before_spawn, both workers down. See docs/internals/peers.md.
11
+ # A continue's peer step (SessionContinue::CARRY :peers): the pairings
12
+ # follow the chain (each link.json copied to the new link as it is, so the
13
+ # peer does nothing: chi's next send names the new id, and a say to the old
14
+ # id goes to the new link, SessionAccess::Local#peer_say), and what the
15
+ # peers said that the previous link hadn't read reaches the new link as ONE
16
+ # note: the messages its worker never took (untaken), and those it took as
17
+ # notes no turn read (receipts still held or noted). The previous link's
18
+ # mailbox and receipts are only read; the copies and the note are the new
19
+ # link's alone, so a failed continue's undo is its delete (the link's
20
+ # mailbox folder goes with it, :peer_mailbox). Runs in the new link's
21
+ # before_spawn, both workers down. See docs/internals/peers.md.
19
22
  module PeerContinue
20
23
  # The note's source (what its frame says it is from).
21
24
  NOTE_SOURCE = "peer messages"
@@ -24,15 +27,20 @@ module Samagotchi
24
27
  NOTE_MAX_BYTES = SessionInbox::NOTE_MAX_BYTES - 1024
25
28
  CUT = "\n[... the rest of this message stayed with the previous link; read it with %s ...]"
26
29
  MORE = "[more messages stayed with the previous link]"
27
- LAST_LINE = "This is background, not a task: don't act on it unless your user asks you to. A peer pairs again " \
28
- "with this session to answer here."
30
+ LAST_LINE = "This is background, not a task: don't act on it unless your user asks you to. The peers stay " \
31
+ "paired with this session and answer here."
29
32
 
30
33
  module_function
31
34
 
32
- # Writes the note into +to+ when +from+'s peers left messages unread.
33
- # Best effort: a failure is logged and the link starts without it.
35
+ # Copies +from+'s pairings into +to+, then writes the note into +to+
36
+ # when +from+'s peers left messages unread. Each best effort: a failure
37
+ # is logged and the link starts without it (a pairing not copied: the
38
+ # peer's say to the old id is refused naming the new one, and its skill
39
+ # pairs again).
34
40
  # @return [Integer] how many messages the note holds
35
41
  def carry(from:, to:, state_dir:)
42
+ carry_links(from, to, state_dir)
43
+ carry_waits(from, to, state_dir)
36
44
  rows = unread(from, state_dir: state_dir)
37
45
  return 0 if rows.empty?
38
46
 
@@ -43,6 +51,21 @@ module Samagotchi
43
51
  0
44
52
  end
45
53
 
54
+ def carry_links(from, to, state_dir)
55
+ PeerMailbox.carry_links(from: from, to: to, state_dir: state_dir)
56
+ rescue StandardError => e
57
+ Log.warn(:peer, "peer_continue_links_failed", sid: to, from: from, error: e.class.name, msg: e.message.to_s[0, 200])
58
+ []
59
+ end
60
+
61
+ # +from+'s waits for a peer (/claude pair's mark), moved to +to+.
62
+ def carry_waits(from, to, state_dir)
63
+ PeerPresence.carry(from: from, to: to, state_dir: state_dir)
64
+ rescue StandardError => e
65
+ Log.warn(:peer, "peer_continue_wait_failed", sid: to, from: from, error: e.class.name, msg: e.message.to_s[0, 200])
66
+ []
67
+ end
68
+
46
69
  # [peer, PeerMessage] of every message +id+ hadn't read, by its time,
47
70
  # then peer, then serial (the worker's order).
48
71
  def unread(id, state_dir:)
@@ -83,16 +106,19 @@ module Samagotchi
83
106
  # frames is quoted), cut past MESSAGE_MAX_BYTES.
84
107
  def message_part(peer, message, from)
85
108
  label = PeerMailbox.label(peer)
86
- text = bounded(message.text, from)
109
+ text = bounded(message.text, PeerNote.read_pointer(peer, message.serial, box: from.to_s[0, 8]))
87
110
  "Message ##{message.serial} from your peer agent #{label}:\n#{"> #{message.summary}\n" if message.summary}" \
88
111
  "#{PeerNote.block(label, text)}"
89
112
  end
90
113
 
91
- def bounded(text, from)
114
+ # +text+ cut past MESSAGE_MAX_BYTES, ending in CUT with +read+: the
115
+ # <peer>_read call that reads the whole message from the previous link
116
+ # (its box: the previous id's first 8, Plugin::Peers#message).
117
+ def bounded(text, read)
92
118
  return text if text.bytesize <= MESSAGE_MAX_BYTES
93
119
 
94
120
  kept = +""
95
- cut = CUT % "chi peer ls #{from}"
121
+ cut = CUT % read
96
122
  limit = MESSAGE_MAX_BYTES - cut.bytesize
97
123
  text.each_char do |char|
98
124
  break if kept.bytesize + char.bytesize > limit
@@ -21,6 +21,13 @@ module Samagotchi
21
21
  STORE.lines(Session.session_dir(session_id, state_dir: state_dir))
22
22
  end
23
23
 
24
+ # #read, but a log that is there and can't be read raises
25
+ # (JsonlStore#lines!): the cold hold counts that as asked.
26
+ # @raise [SystemCallError]
27
+ def read!(session_id, state_dir:)
28
+ STORE.lines!(Session.session_dir(session_id, state_dir: state_dir))
29
+ end
30
+
24
31
  # Process in timestamp order, breaking equal timestamps by append order.
25
32
  # Failed sends cannot claim an answer. One answer can claim a send; any
26
33
  # further answers remain visible as unclaimed.
@@ -16,6 +16,7 @@ module Samagotchi
16
16
  # worker did with each message, is PeerReceipts, in the session's own
17
17
  # folder).
18
18
  # <session id>/<peer>/link.json PeerLink: the pairing (chi peer pair)
19
+ # .here/ PeerPresence: who is here, who waits (not a session id)
19
20
  # <session id>/<peer>/in/<serial>.json PeerMessage: one message (chi peer say)
20
21
  # <session id>/<peer>/lock the say's, while it picks a serial and writes
21
22
  # No head file: the next serial is max(the newest file, taken) + 1, and
@@ -56,16 +57,29 @@ module Samagotchi
56
57
  class Full < Invalid; end
57
58
 
58
59
  # A pairing: the +peer+'s name, the +address+ chi's sends go to (nil:
59
- # answers only), when it was made and by whom (+from+, free text).
60
- PeerLink = Data.define(:peer, :address, :paired_at, :from) do
61
- def to_h = { "peer" => peer, "address" => address, "paired_at" => paired_at, "from" => from }
60
+ # answers only), when it was made and by whom (+from+, free text), and
61
+ # the peer's own session id when the pairing knows it (+peer_session+:
62
+ # Claude Code's session id, stable across a resume; PeerPresence). An
63
+ # older chi drops +peer_session+ on its continue and its re-pair.
64
+ PeerLink = Data.define(:peer, :address, :paired_at, :from, :peer_session) do
65
+ def initialize(peer:, address:, paired_at:, from:, peer_session: nil) = super
66
+
67
+ # Its address an inbox socket path that is no socket now (that Claude
68
+ # ended). A thread id (Codex) or no address (answers only) never is.
69
+ def socket_gone? = PeerMailbox.socket_gone?(address)
70
+
71
+ def to_h
72
+ base = { "peer" => peer, "address" => address, "paired_at" => paired_at, "from" => from }
73
+ peer_session ? base.merge("peer_session" => peer_session) : base
74
+ end
62
75
 
63
76
  # @return [PeerLink, nil] nil for a value of the wrong shape
64
77
  def self.from_h(data)
65
78
  return nil unless data.is_a?(Hash) && data["peer"].is_a?(String) && data["paired_at"].is_a?(String)
66
- return nil unless [data["address"], data["from"]].all? { |value| value.nil? || value.is_a?(String) }
79
+ return nil unless [data["address"], data["from"], data["peer_session"]].all? { |value| value.nil? || value.is_a?(String) }
67
80
 
68
- new(peer: data["peer"], address: data["address"], paired_at: data["paired_at"], from: data["from"])
81
+ new(peer: data["peer"], address: data["address"], paired_at: data["paired_at"], from: data["from"],
82
+ peer_session: data["peer_session"])
69
83
  end
70
84
  end
71
85
 
@@ -136,6 +150,14 @@ module Samagotchi
136
150
 
137
151
  module_function
138
152
 
153
+ # Whether a pairing's +address+ is an inbox socket path that is no
154
+ # socket now (that Claude ended: PeerLink#socket_gone?, chi web's
155
+ # "ended" chip). A thread id (Codex) or no address never is.
156
+ def socket_gone?(address)
157
+ path = address.to_s.strip
158
+ path.start_with?("/") && !File.socket?(path)
159
+ end
160
+
139
161
  # <state dir>/mailbox; +state_dir+ is the sessions dir (SessionPaths.default_state_dir).
140
162
  def root(state_dir: nil)
141
163
  File.join(File.dirname(state_dir || SessionPaths.default_state_dir), DIR)
@@ -188,15 +210,33 @@ module Samagotchi
188
210
 
189
211
  # Pairs +peer+ with the session: link.json written whole, the in folder made.
190
212
  # @return [PeerLink]
191
- def pair(session_id, peer, address:, from:, state_dir: nil, now: Time.now)
213
+ def pair(session_id, peer, address:, from:, peer_session: nil, state_dir: nil, now: Time.now)
214
+ link = PeerLink.new(peer: peer, address: address&.to_s, paired_at: now.utc.iso8601, from: from&.to_s,
215
+ peer_session: peer_session&.to_s)
216
+ write_link(session_id, link, state_dir: state_dir)
217
+ end
218
+
219
+ # A continue's copy of +from+'s pairings into +to+ (SessionContinue's
220
+ # :peers step), each as it is: its address, who paired and when. The
221
+ # messages stay with +from+.
222
+ # @return [Array<String>] the peers whose pairing was copied
223
+ def carry_links(from:, to:, state_dir: nil)
224
+ links(from, state_dir: state_dir).map do |link|
225
+ write_link(to, link, state_dir: state_dir)
226
+ link.peer
227
+ end
228
+ end
229
+
230
+ # link.json written whole for +link+'s peer, the in folder made.
231
+ # @return [PeerLink]
232
+ def write_link(session_id, link, state_dir: nil)
192
233
  session = session_dir(session_id, state_dir: state_dir)
193
234
  raise Invalid, "#{session_id}'s mailbox folder is a link; chi doesn't follow links there" if File.symlink?(session)
194
235
 
195
- dir = peer_dir(session_id, peer, state_dir: state_dir)
196
- refuse_links!(peer, dir)
236
+ dir = peer_dir(session_id, link.peer, state_dir: state_dir)
237
+ refuse_links!(link.peer, dir)
197
238
  FileUtils.mkdir_p(File.join(dir, IN_DIR))
198
- refuse_links!(peer, dir)
199
- link = PeerLink.new(peer: peer, address: address&.to_s, paired_at: now.utc.iso8601, from: from&.to_s)
239
+ refuse_links!(link.peer, dir)
200
240
  AtomicFile.write(File.join(dir, LINK_FILE), "#{JSON.generate(link.to_h)}\n")
201
241
  link
202
242
  end
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "memory_paths"
4
+ require_relative "peer_announce"
5
+ require_relative "peer_mailbox"
6
+ require_relative "peer_presence"
7
+ require_relative "session_chain"
8
+
9
+ module Samagotchi
10
+ # `chi peer pair NAME --here`: the pair script with no id ("pair with
11
+ # chi"). Which session: the one fresh mark of this folder's project
12
+ # (claimed first); else, of the sessions of that project a worker runs
13
+ # now (by MemoryPaths.project_key, so a worktree's session counts: not
14
+ # `sessions list --cwd`, a path-prefix filter), the one already paired
15
+ # with this peer (by its peer session, or by this address: a Codex its
16
+ # start hook paired, whose older script passes no --peer-session), the
17
+ # pairing kept as it is (+same+), else the only one; else none, with the
18
+ # candidates. Also the path of a Claude started before its start hook.
19
+ class PeerPairHere
20
+ # What it found: +id+ to pair (and the +claim+ taken on its mark), or a
21
+ # +refusal+ (its lines: the first one the reason, then the candidates);
22
+ # +gone+: the pairing on +id+'s chain whose peer is gone, which this
23
+ # pairing replaces; +same+: the pairing (a PeerLink) of +id+, a live
24
+ # session, with this peer already, which wins.
25
+ Found = Data.define(:id, :claim, :refusal, :gone, :same) do
26
+ def initialize(id:, claim:, refusal:, gone: nil, same: nil) = super
27
+ end
28
+ # A pairing whose peer is gone (PeerLink#socket_gone?): +link+, on the
29
+ # chain's live link +head+.
30
+ Gone = Data.define(:head, :link)
31
+
32
+ # @param access [SessionAccess::Local]
33
+ def initialize(peer, access:, state_dir:, cwd: Dir.pwd, now: -> { Time.now })
34
+ @peer = peer
35
+ @access = access
36
+ @state_dir = state_dir
37
+ @cwd = cwd
38
+ @now = now
39
+ end
40
+
41
+ # +peer_session+ and +address+ are this peer's: a session paired with
42
+ # another live peer is refused (owner: never replaced silently; a pair
43
+ # with its id still replaces), the same one pairs again, and one whose
44
+ # peer is gone (its socket missing, as /claude pair ends it) is
45
+ # replaced, named in +gone+.
46
+ # @return [Found]
47
+ def resolve(peer_session: nil, address: nil)
48
+ found = pick(peer_session: peer_session, address: address)
49
+ return found if found.refusal || found.same
50
+
51
+ head, link = other_pairing(found.id, peer_session, address)
52
+ return found unless link
53
+ return found.with(gone: Gone.new(head: head, link: link)) if link.socket_gone?
54
+
55
+ PeerPresence.release(found.claim)
56
+ refused("chi #{found.id[0, 8]} is paired with another #{PeerMailbox.label(@peer)} already; /#{@peer} unpair there first", [])
57
+ end
58
+
59
+ # The peer session pairing from +address+: the one given, else the
60
+ # PeerHere listed at that address.
61
+ def peer_session(given, address)
62
+ return given if given
63
+ return nil if address.nil?
64
+
65
+ PeerPresence.here(@peer, state_dir: @state_dir).find { |entry| entry.address == address }&.session
66
+ end
67
+
68
+ private
69
+
70
+ # The one fresh mark (claimed), else the live session of the project
71
+ # already paired with this peer, else the one live session; a mark
72
+ # another pairing holds now (hidden from #marks while claimed) is
73
+ # refused, never passed over for the live one. A stopped session's
74
+ # pairing never wins (a resumed Codex keeps its thread for days).
75
+ def pick(peer_session:, address:)
76
+ project = MemoryPaths.project_key(@cwd)
77
+ marks = PeerPresence.marks(@peer, project: project, state_dir: @state_dir, now: @now.call)
78
+ if marks.size == 1
79
+ claim = PeerPresence.claim(@peer, marks.first.session, state_dir: @state_dir, now: @now.call)
80
+ return claim ? Found.new(id: marks.first.session, claim: claim, refusal: nil) : pairing_now(marks.first.session)
81
+ elsif marks.size > 1
82
+ return refused("#{marks.size} chi sessions wait for #{PeerMailbox.label(@peer)} in this project: pair with one's id",
83
+ marks.map { |mark| " #{mark.session[0, 8]} waiting #{PeerAnnounce.title_of(mark.session, state_dir: @state_dir)}".rstrip })
84
+ end
85
+ paired = paired_here(project, peer_session, address) and return paired
86
+
87
+ found = live(project)
88
+ found.id && PeerPresence.claimed?(@peer, found.id, state_dir: @state_dir, now: @now.call) ? pairing_now(found.id) : found
89
+ rescue MemoryPaths::ProjectIdConflict, ArgumentError => e
90
+ refused("can't tell this folder's project (#{e.message}): pair with an id", [])
91
+ end
92
+
93
+ def pairing_now(id)
94
+ refused("a #{PeerMailbox.label(@peer)} is pairing with chi #{id[0, 8]} now: try again, or pair with its id", [])
95
+ end
96
+
97
+ # [head, link]: the chain's live link of +id+ and its pairing with
98
+ # another peer, or [head, nil]: none, or this peer's own (this address:
99
+ # the same socket is the same Claude, a /clear's new session id too;
100
+ # else, when both are named, this peer session: a resume's new socket).
101
+ def other_pairing(id, peer_session, address)
102
+ head = SessionChain::Links.new(state_dir: @state_dir).first_live(id) || id
103
+ link = PeerMailbox.link(head, @peer, state_dir: @state_dir) or return [head, nil]
104
+ return [head, nil] if !address.to_s.empty? && link.address.to_s == address.to_s
105
+ return [head, nil] if link.peer_session && peer_session && link.peer_session == peer_session
106
+
107
+ [head, link]
108
+ end
109
+
110
+ # Found with +same+: the live session of +project+ whose pairing with
111
+ # this peer is this +peer_session+'s or at this +address+; nil: none.
112
+ def paired_here(project, peer_session, address)
113
+ project_rows(project).each do |row|
114
+ link = PeerMailbox.link(row.id, @peer, state_dir: @state_dir) or next
115
+ next unless (peer_session && link.peer_session == peer_session) || (!address.to_s.empty? && link.address.to_s == address.to_s)
116
+
117
+ return Found.new(id: row.id, claim: nil, refusal: nil, same: link)
118
+ end
119
+ nil
120
+ end
121
+
122
+ # The live sessions of +project+ (read once).
123
+ def project_rows(project)
124
+ @project_rows ||= begin
125
+ cache = {}
126
+ @access.summaries(live: true, include_tests: true).select do |row|
127
+ cache.fetch(row.cwd) { cache[row.cwd] = key_of(row.cwd) } == project
128
+ end
129
+ end
130
+ end
131
+
132
+ def live(project)
133
+ rows = project_rows(project)
134
+ return Found.new(id: rows.first.id, claim: nil, refusal: nil) if rows.size == 1
135
+ return refused("no live chi session in this project: start one, or pair with an id", []) if rows.empty?
136
+
137
+ refused("#{rows.size} live chi sessions in this project: pair with one's id",
138
+ rows.map { |row| " #{row.id[0, 8]} #{row.status} #{PeerAnnounce.title_line(row.title.to_s.empty? ? row.desc : row.title)}" })
139
+ end
140
+
141
+ def key_of(cwd)
142
+ cwd.to_s.empty? ? nil : MemoryPaths.project_key(cwd)
143
+ rescue StandardError # degrade-ok: a row whose folder has no project is no candidate
144
+ nil
145
+ end
146
+
147
+ def refused(reason, candidates) = Found.new(id: nil, claim: nil, refusal: [reason, *candidates])
148
+ end
149
+ end