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
@@ -0,0 +1,185 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "open3"
4
+ require_relative "config"
5
+ require_relative "panes/kitty"
6
+
7
+ module Samagotchi
8
+ # Panes: where an agent's own UI runs (a kitty window) and where the human
9
+ # can walk in. A pane carries no peer message. #list, #find a pid's
10
+ # window, #show it (focus-window), #open a background tab running a
11
+ # command, #alive? and #paste into it: show, open and paste act as the
12
+ # user on their screen, so ctx.panes runs them only under the user-typed
13
+ # seam (Plugin::Panes, UserTyped). One
14
+ # driver, kitty, through `kitty @ --to unix:<socket>`, with kitty's own
15
+ # KITTY_* variables taken out of its env (as the desktop helper's
16
+ # KittyRunner#kittyEnv does: a worker started from a kitty window must
17
+ # not talk to that one, nor fill in the ${KITTY_PID} kitty keeps
18
+ # literal). kitty.listen_on and kitty.binary are read when used
19
+ # (Config.get is live). No kitty (listen_on unset, not running, the pid
20
+ # in no window): nothing found, no error; #open raises the one
21
+ # Unavailable. See docs/internals/panes.md.
22
+ class Panes
23
+ # A window: its +driver+ ("kitty"), +key+ (`<socket>#<window id>`),
24
+ # +title+ (cleaned), +cwd+ and the +pids+ of its foreground processes.
25
+ Pane = Data.define(:driver, :key, :title, :cwd, :pids)
26
+
27
+ # A window #open made: what a caller keeps to show, check or paste
28
+ # into it later (claude-peer keeps it in its own session state, never in
29
+ # the mailbox, which any local process may write).
30
+ PaneRef = Data.define(:driver, :key) do
31
+ def to_h = { "driver" => driver, "key" => key }
32
+
33
+ # nil unless +data+ is a ref's hash with a key Kitty.parse takes.
34
+ def self.from_h(data)
35
+ return nil unless data.is_a?(Hash) && data["driver"] == "kitty" && Kitty.parse(data["key"])
36
+
37
+ new(driver: "kitty", key: data["key"])
38
+ end
39
+ end
40
+
41
+ # What #open raises: the message says why, for the user.
42
+ class Error < StandardError; end
43
+
44
+ # No kitty answers: the one refusal of every pane that would open.
45
+ class Unavailable < Error
46
+ def initialize(msg = "kitty isn't running or `kitty.listen_on` isn't set") = super
47
+ end
48
+
49
+ LS_SECONDS = 2
50
+ SHOW_SECONDS = 5
51
+ # A launch that takes long may still open its tab: it isn't killed at
52
+ # SHOW_SECONDS, so a slow kitty doesn't leave a tab no ref names.
53
+ LAUNCH_SECONDS = 15
54
+
55
+ # Panes as the config says now.
56
+ def self.from_config(env: ENV)
57
+ new(listen_on: Config.get("kitty.listen_on"), binary: Config.get("kitty.binary"), env: env.to_h)
58
+ end
59
+
60
+ def initialize(listen_on:, binary:, env:)
61
+ @listen_on = listen_on
62
+ @binary = binary.to_s
63
+ @env = env.to_h.reject { |key, _| key.start_with?("KITTY_") }
64
+ end
65
+
66
+ # Every window of every live kitty listen_on names, in socket order.
67
+ # @return [Array<Pane>]
68
+ def list
69
+ Kitty.sockets(@listen_on, @env).flat_map do |socket|
70
+ out, ok = kitty(socket, ["ls"], LS_SECONDS)
71
+ ok ? Kitty.panes(out, socket) : []
72
+ end
73
+ end
74
+
75
+ # The window whose foreground processes include +pid+ (membership:
76
+ # never the window's own pid, a login wrapper or a launcher's sh sits
77
+ # in between), or nil.
78
+ # @return [Pane, nil]
79
+ def find(pid:)
80
+ return nil unless pid.is_a?(Integer) && pid.positive?
81
+
82
+ list.find { |pane| pane.pids.include?(pid) }
83
+ end
84
+
85
+ # Brings +pane+'s window to the front (its tab, its OS window).
86
+ # @return [Boolean] whether kitty did (false: the window is gone)
87
+ def show(pane)
88
+ socket, id = known(pane)
89
+ return false unless socket
90
+
91
+ _, ok = kitty(socket, ["focus-window", "--match", "id:#{id}"], SHOW_SECONDS)
92
+ ok
93
+ end
94
+
95
+ # Opens a background tab (launch --type=tab --keep-focus: a tab only,
96
+ # an os-window's --keep-focus doesn't keep it) running +command+ (argv)
97
+ # in +cwd+, its tab titled +title+, in the kitty whose OS window is
98
+ # focused, else the one started last (Kitty.target).
99
+ # @return [PaneRef]
100
+ # @raise [Unavailable] no kitty answers
101
+ # @raise [Error] kitty didn't open it
102
+ def open(command:, cwd:, title:)
103
+ argv = Array(command).map(&:to_s)
104
+ raise ArgumentError, "no command to open" if argv.empty? || argv.first.empty?
105
+
106
+ lists = Kitty.sockets(@listen_on, @env).filter_map do |socket|
107
+ out, ok = kitty(socket, ["ls"], LS_SECONDS)
108
+ [socket, out] if ok
109
+ end
110
+ socket = Kitty.target(lists) or raise Unavailable
111
+
112
+ out, ok = kitty(socket, ["launch", "--type=tab", "--keep-focus", "--cwd", cwd.to_s, "--tab-title", title.to_s, *argv],
113
+ LAUNCH_SECONDS)
114
+ id = Integer(out.to_s.strip, 10, exception: false)
115
+ raise Error, "kitty didn't open the tab" unless ok && id
116
+
117
+ PaneRef.new(driver: "kitty", key: "#{socket}##{id}")
118
+ end
119
+
120
+ # Whether +ref+'s window is still there (`ls --match id:N` on its socket).
121
+ def alive?(ref)
122
+ socket, id = known(ref)
123
+ return false unless socket
124
+
125
+ _, ok = kitty(socket, ["ls", "--match", "id:#{id}"], LS_SECONDS)
126
+ ok
127
+ end
128
+
129
+ # Pastes +text+ into +ref+'s window as one bracketed paste (the
130
+ # helper's KittyRunner#send: send-text reports nothing for a gone
131
+ # window, so #alive? first), then presses Enter when +enter+.
132
+ # @return [Boolean] whether kitty took it (false: the window is gone)
133
+ def paste(ref, text, enter: true)
134
+ return false unless alive?(ref)
135
+
136
+ socket, id = known(ref)
137
+ match = ["--match", "id:#{id}"]
138
+ _, ok = kitty(socket, ["send-text", *match, "--bracketed-paste=disable", "--stdin"], SHOW_SECONDS,
139
+ stdin: Kitty.bracketed(text))
140
+ return false unless ok
141
+ return true unless enter
142
+
143
+ kitty(socket, ["send-key", *match, "enter"], SHOW_SECONDS).last
144
+ end
145
+
146
+ private
147
+
148
+ # [socket, window id] of +ref+ (a Pane or a PaneRef) when its socket is
149
+ # one of listen_on's own (Kitty.sockets), else nil: a ref read back from
150
+ # a file (a bundle's state.json, which chi's own tools can write) never
151
+ # aims kitty @ at a socket kitty.listen_on doesn't name.
152
+ def known(ref)
153
+ socket, id = Kitty.parse(ref&.key)
154
+ return nil unless socket && ref.driver == "kitty" && Kitty.sockets(@listen_on, @env).include?(socket)
155
+
156
+ [socket, id]
157
+ end
158
+
159
+ # [stdout, success] of `kitty @ --to unix:<socket> <args>`, killed past
160
+ # +seconds+; +stdin+ written to it first.
161
+ def kitty(socket, args, seconds, stdin: nil)
162
+ return ["", false] if @binary.empty? || !File.executable?(@binary)
163
+
164
+ Open3.popen3(@env, @binary, "@", "--to", "unix:#{socket}", *args, unsetenv_others: true, pgroup: true) do |input, stdout, stderr, wait|
165
+ input.write(stdin) if stdin
166
+ input.close
167
+ reader = Thread.new { stdout.read }
168
+ Thread.new { stderr.read }
169
+ unless wait.join(seconds)
170
+ kill(wait.pid)
171
+ return ["", false]
172
+ end
173
+ [reader.value.to_s, wait.value.success?]
174
+ end
175
+ rescue SystemCallError, IOError
176
+ ["", false]
177
+ end
178
+
179
+ def kill(pid)
180
+ Process.kill("KILL", -pid)
181
+ rescue SystemCallError
182
+ nil
183
+ end
184
+ end
185
+ end
@@ -0,0 +1,245 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "codex_rollout"
5
+ require_relative "memory_paths"
6
+ require_relative "peer_mailbox"
7
+ require_relative "peer_presence"
8
+ require_relative "session"
9
+
10
+ module Samagotchi
11
+ # `chi peer announce NAME`: a peer's SessionStart hook (the peer bundles'
12
+ # start hook, `/<peer> install-skill`'s "Add the start hook"). Its stdout
13
+ # enters the peer's start context, so what it prints costs no turn.
14
+ # Who the peer is comes from one of two readers (an Announcer):
15
+ # - Claude Code's (`announce claude`, any name but codex): nothing unless
16
+ # CLAUDE_CODE_SESSION_ATTENDED is 1 (a headless run, a nested
17
+ # `claude -p`; subagents fire no SessionStart); its socket is the
18
+ # address; it lists itself here and refreshes its pairings;
19
+ # - Codex's (`announce codex`): the hook's stdin only (Codex gives the
20
+ # hook no env of its own: it runs under Codex's app-server daemon), a
21
+ # SessionStart with source startup whose rollout's first line says an
22
+ # interactive Codex (CodexRollout); the thread id is the address; it
23
+ # lists nothing (no pid, no socket: PeerPresence.live? can't hold) and
24
+ # only takes a mark (steps 3 and 4: a thread with a pairing takes none).
25
+ # For Claude it:
26
+ # 1. reads Claude's hook env (above);
27
+ # 2. lists this Claude here (PeerPresence::PeerHere), superseding a live
28
+ # entry on the same socket under another session id (a /clear): its
29
+ # pairing files and its links' peer_session move to the new id;
30
+ # 3. refreshes each pairing this Claude made (paired/<its session>/)
31
+ # with the new socket, through SessionAccess::Local#peer_pair (its
32
+ # busy, continue and worker-age rules), when the chain's live link is
33
+ # still paired with it ("chi <id8>: pairing refreshed"); a Claude that
34
+ # has a pairing takes no mark;
35
+ # 4. pairs the one fresh mark of its project (claimed first: a lost claim
36
+ # says nothing; a refused pairing gives it back), or names the
37
+ # sessions when two or more wait.
38
+ # Any failure prints nothing. As unauthenticated as pair and say: any
39
+ # local process can list itself; the owner's Pair is what trusts a row.
40
+ # See docs/internals/peers.md.
41
+ class PeerAnnounce
42
+ TITLE_CHARS = 60
43
+ STDIN_MAX_BYTES = 65_536
44
+ STDIN_SECONDS = 2
45
+
46
+ # The peer that announces: its +session+ (the peer's own id), the
47
+ # +address+ chi sends to, its +cwd+ and +project+, its +pid+ (0: none),
48
+ # whether it +lists_itself+ here (a PeerHere), who paired (+from+) and
49
+ # what a line calls it (+app+: "Claude Code", "Codex").
50
+ Announcer = Data.define(:session, :address, :cwd, :project, :pid, :lists_itself, :from, :app)
51
+
52
+ # @param access [SessionAccess::Local]
53
+ # @param sleeper [#call] CodexRollout's wait between tries
54
+ def initialize(peer, stdin:, env:, access:, state_dir:, now: -> { Time.now }, sleeper: ->(seconds) { sleep(seconds) })
55
+ @peer = peer
56
+ @stdin = stdin
57
+ @env = env
58
+ @access = access
59
+ @state_dir = state_dir
60
+ @now = now
61
+ @sleeper = sleeper
62
+ end
63
+
64
+ # @return [Array<String>] the lines for the peer's start context (none: say nothing)
65
+ def run
66
+ return [] unless PeerMailbox.valid_name?(@peer)
67
+
68
+ announcer = this_peer or return []
69
+ if announcer.lists_itself
70
+ entry = here_entry(announcer)
71
+ superseded = PeerPresence.announce!(entry, state_dir: @state_dir)
72
+ superseded.each { |old| retag(old, entry.session) }
73
+ end
74
+ refreshed = refresh(announcer)
75
+ return refreshed.lines if refreshed.paired
76
+
77
+ take_mark(announcer)
78
+ rescue StandardError, ScriptError # degrade-ok: any failure says nothing to Claude (its start context)
79
+ []
80
+ end
81
+
82
+ # The title a line names: one line, no control characters, TITLE_CHARS.
83
+ def self.title_line(text)
84
+ line = text.to_s.gsub(/[[:cntrl:]]/, " ").gsub(/\s+/, " ").strip
85
+ line.length > TITLE_CHARS ? "#{line[0, TITLE_CHARS - 1]}…" : line
86
+ end
87
+
88
+ # The id8 and title of chi session +id+: "3f2a9c1e (Daily review)".
89
+ def self.named(id, state_dir:)
90
+ title = title_of(id, state_dir: state_dir)
91
+ title.empty? ? id[0, 8] : "#{id[0, 8]} (#{title})"
92
+ end
93
+
94
+ # Chi session +id+'s title as one line ("" when it can't be read).
95
+ def self.title_of(id, state_dir:)
96
+ title_line(Session.load(id, state_dir: state_dir).display_title)
97
+ rescue StandardError # degrade-ok: a session that can't be read is named by its id alone
98
+ ""
99
+ end
100
+
101
+ private
102
+
103
+ # Refreshing found +paired+ (a live pairing of this Claude's, refreshed
104
+ # or already on this socket): no mark is taken.
105
+ Refreshed = Data.define(:paired, :lines)
106
+
107
+ # The Codex peer's name: its reader is #codex_peer.
108
+ CODEX = "codex"
109
+
110
+ # This peer as an Announcer; nil when it isn't one to announce (a
111
+ # headless run) or something it needs is missing.
112
+ def this_peer = @peer == CODEX ? codex_peer : claude_peer
113
+
114
+ # Claude Code, from the hook's stdin and env.
115
+ def claude_peer
116
+ return nil unless @env["CLAUDE_CODE_SESSION_ATTENDED"] == "1"
117
+
118
+ input = read_input
119
+ session = input["session_id"].is_a?(String) ? input["session_id"] : @env["CLAUDE_CODE_SESSION_ID"]
120
+ address = @env["CLAUDE_CODE_MESSAGING_SOCKET"].to_s
121
+ return nil unless PeerPresence.peer_session?(session) && address.start_with?("/")
122
+
123
+ cwd = [input["cwd"], @env["CLAUDE_PROJECT_DIR"]].find { |dir| dir.is_a?(String) && dir.start_with?("/") } || Dir.pwd
124
+ Announcer.new(session: session, address: address, cwd: cwd, project: project_of(cwd), pid: pid_of(address),
125
+ lists_itself: true, from: "Claude Code in #{cwd}", app: "Claude Code")
126
+ end
127
+
128
+ # Codex, from the hook's stdin alone: a SessionStart with source
129
+ # startup (never a resume, clear, compact or fork) whose rollout says a
130
+ # fresh interactive Codex (CodexRollout). Its address is its thread id.
131
+ def codex_peer
132
+ input = read_input
133
+ session = input["session_id"]
134
+ cwd = input["cwd"]
135
+ return nil unless input["hook_event_name"] == "SessionStart" && input["source"] == "startup" &&
136
+ PeerPresence.peer_session?(session) && cwd.is_a?(String) && cwd.start_with?("/")
137
+ return nil unless CodexRollout.interactive_start?(input["transcript_path"], session: session, codex_home: codex_home,
138
+ sleeper: @sleeper)
139
+
140
+ Announcer.new(session: session, address: session, cwd: cwd, project: project_of(cwd), pid: 0, lists_itself: false,
141
+ from: "Codex in #{cwd}", app: "Codex")
142
+ end
143
+
144
+ # The hook env's CODEX_HOME (the daemon's: the env of the Codex that
145
+ # started it), else ~/.codex.
146
+ def codex_home
147
+ dir = @env["CODEX_HOME"].to_s.strip
148
+ dir.empty? ? File.join(Dir.home, ".codex") : File.expand_path(dir)
149
+ end
150
+
151
+ def here_entry(announcer)
152
+ PeerPresence::PeerHere.new(peer: @peer, session: announcer.session, address: announcer.address, cwd: announcer.cwd,
153
+ project: announcer.project, pid: announcer.pid, at: @now.call.utc.iso8601)
154
+ end
155
+
156
+ # CLAUDE_PID, else the number in the socket's name (cc-socks/<pid>.sock).
157
+ def pid_of(address)
158
+ Integer(@env["CLAUDE_PID"].to_s, 10, exception: false) || Integer(File.basename(address)[/\A(\d+)\.sock\z/, 1].to_s, 10, exception: false) || 0
159
+ end
160
+
161
+ def project_of(cwd)
162
+ MemoryPaths.project_key(cwd)
163
+ rescue StandardError # degrade-ok: no project (a ProjectIdConflict): no mark is taken
164
+ nil
165
+ end
166
+
167
+ # The hook's stdin JSON ({} for none, a terminal or garbage), read
168
+ # within STDIN_SECONDS.
169
+ def read_input
170
+ return {} if @stdin.nil? || (@stdin.respond_to?(:tty?) && @stdin.tty?)
171
+
172
+ data = JSON.parse(read_stdin.to_s)
173
+ data.is_a?(Hash) ? data : {}
174
+ rescue JSON::ParserError, EncodingError, IOError, SystemCallError
175
+ {}
176
+ end
177
+
178
+ def read_stdin
179
+ return @stdin.read(STDIN_MAX_BYTES) unless @stdin.is_a?(IO)
180
+
181
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + STDIN_SECONDS
182
+ buffer = +""
183
+ while buffer.bytesize < STDIN_MAX_BYTES
184
+ left = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
185
+ break unless left.positive? && @stdin.wait_readable(left)
186
+
187
+ chunk = @stdin.read_nonblock(STDIN_MAX_BYTES - buffer.bytesize, exception: false)
188
+ break if chunk.nil?
189
+ next if chunk == :wait_readable
190
+
191
+ buffer << chunk
192
+ end
193
+ buffer
194
+ end
195
+
196
+ # A superseded session's links (a /clear): their peer_session renamed.
197
+ def retag(old, new)
198
+ PeerPresence.paired_sessions(@peer, new, state_dir: @state_dir).each do |chi|
199
+ @access.peer_retag(chi, @peer, from: old, to: new)
200
+ end
201
+ end
202
+
203
+ def refresh(entry)
204
+ lines = []
205
+ found = false
206
+ PeerPresence.paired_sessions(@peer, entry.session, state_dir: @state_dir).each do |chi|
207
+ paired = @access.peer_refresh(chi, @peer, address: entry.address, peer_session: entry.session)
208
+ next unless paired
209
+
210
+ found = true
211
+ lines << "chi #{(paired.forwarded_to || chi)[0, 8]}: pairing refreshed" if paired.status == :paired
212
+ end
213
+ Refreshed.new(paired: found, lines: lines)
214
+ end
215
+
216
+ def take_mark(entry)
217
+ return [] unless entry.project
218
+
219
+ marks = PeerPresence.marks(@peer, project: entry.project, state_dir: @state_dir, now: @now.call)
220
+ return [] if marks.empty?
221
+ return [several(marks, entry.app)] if marks.size > 1
222
+
223
+ claim = PeerPresence.claim(@peer, marks.first.session, state_dir: @state_dir, now: @now.call) or return []
224
+ paired = @access.peer_pair(marks.first.session, @peer, address: entry.address, from: entry.from,
225
+ peer_session: entry.session)
226
+ unless paired.status == :paired
227
+ PeerPresence.release(claim)
228
+ return []
229
+ end
230
+
231
+ on = paired.forwarded_to || marks.first.session
232
+ ["paired with chi #{self.class.named(on, state_dir: @state_dir)}: chi sends parts for you to validate; answer " \
233
+ "with the chi-peer skill"]
234
+ rescue StandardError
235
+ PeerPresence.release(claim)
236
+ []
237
+ end
238
+
239
+ def several(marks, app)
240
+ names = marks.map { |mark| self.class.named(mark.session, state_dir: @state_dir) }
241
+ "#{marks.size} chi sessions wait for a #{app} session here: #{names.join(", ")}; ask your user which, then " \
242
+ "pair with chi <id>"
243
+ end
244
+ end
245
+ end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+ require_relative "analytics_file"
5
+ require_relative "degrade"
6
+ require_relative "peer_exchanges"
7
+ require_relative "peer_mailbox"
8
+
9
+ module Samagotchi
10
+ # The peer mail's cold hold (WorkerInbound::MailPart#mail_hold, reason
11
+ # :cold): a message a peer starts on its own (no +re+ naming a send of
12
+ # chi's), or an agreeing closer (VERDICT OK), doesn't wake chi while its
13
+ # prompt cache is cold: a turn then re-reads the whole conversation at
14
+ # the write price. It waits as a note for the user's next message. An
15
+ # answer chi asked for still wakes it (docs/peers.md, Held reasons).
16
+ #
17
+ # "Cold": the host keeps a TTL'd cache for the session (its requests carry
18
+ # breakpoints: Engine#remote_cache_ttl; a local model has none), the last
19
+ # turn ended longer ago than that TTL (Session#last_turn's ended_at: saved,
20
+ # so a new worker reads it; a ContinueOffer stamp or a failed turn's taken
21
+ # as it is, which is never earlier than the last request), and the
22
+ # conversation is above FLOOR_TOKENS (analytics.json's context.used_tokens),
23
+ # so a small session is never held. Anything unknown is warm: no ended_at
24
+ # (a new link), no count, an unparsable time.
25
+ module PeerCold
26
+ # A conversation this small is never held: its re-read is cheap.
27
+ FLOOR_TOKENS = 20_000
28
+
29
+ module_function
30
+
31
+ # @param ttl [Integer, nil] seconds the host keeps the cache; nil: no breakpoints
32
+ # @param last_turn [LastTurn, nil] the session's last turn
33
+ # @param used_tokens [Integer, nil] the conversation's size
34
+ # @param now [Time]
35
+ def cold?(ttl:, last_turn:, used_tokens:, now:)
36
+ return false unless ttl.is_a?(Integer) && ttl.positive?
37
+ return false unless used_tokens.is_a?(Integer) && used_tokens > FLOOR_TOKENS
38
+
39
+ ended = ended_at(last_turn)
40
+ !ended.nil? && now - ended > ttl
41
+ end
42
+
43
+ # The conversation's size the last turn saved (analytics.json), nil
44
+ # when there is none.
45
+ # @return [Integer, nil]
46
+ def used_tokens(session_dir)
47
+ value = AnalyticsFile.read(session_dir)&.dig("context", "used_tokens")
48
+ value.is_a?(Integer) ? value : nil
49
+ end
50
+
51
+ # Whether +message+ (a PeerMessage of +peer+'s in +session_id+) is an
52
+ # answer chi asked for: its +re+ names a "sent" row of PeerExchanges in
53
+ # this session or in the one it continues (an answer forwarded after a
54
+ # continue names the previous link's send) that no earlier message of
55
+ # the peer's claimed (PeerExchanges.joined: one answer claims a send),
56
+ # so an old or repeated +re+ doesn't wake chi cold. A log that is there
57
+ # and can't be read counts as asked: never hold an answer on a doubt.
58
+ def asked_for?(message, peer, session_id:, continues:, state_dir:)
59
+ re = message.re
60
+ return false if re.nil? || re.to_s.empty?
61
+
62
+ Degrade.call(:peer, "peer_exchanges_unreadable", fallback: true) do
63
+ ids = [continues, session_id].compact
64
+ sends = ids.flat_map { |id| PeerExchanges.read!(id, state_dir: state_dir) }
65
+ .select { |entry| entry["peer"].to_s == peer.to_s && %w[sent send_failed].include?(entry["t"]) }
66
+ next false unless sends.any? { |entry| entry["t"] == "sent" && entry["id"] == re }
67
+
68
+ answers = ids.flat_map { |id| earlier_answers(id, peer, message, own: id == session_id, state_dir: state_dir) }
69
+ mine = { "t" => "answer", "peer" => peer.to_s, "re" => re, "serial" => message.serial, "at" => message.at }
70
+ PeerExchanges.joined(sends + answers + [mine], last: sends.size + answers.size + 1)
71
+ .any? { |row| row[:id] == re && row.dig(:answer, :serial) == message.serial && row.dig(:answer, :at) == message.at }
72
+ end
73
+ end
74
+
75
+ # The peer's messages in +id+ before +message+ (in its own session, the
76
+ # lower serials; in the previous link, all), as PeerExchanges answer rows.
77
+ def earlier_answers(id, peer, message, own:, state_dir:)
78
+ PeerMailbox.messages(id, peer.to_s, since: 0, state_dir: state_dir).filter_map do |entry|
79
+ next unless entry.is_a?(PeerMailbox::PeerMessage) && (!own || entry.serial < message.serial)
80
+
81
+ { "t" => "answer", "peer" => peer.to_s, "re" => entry.re, "serial" => entry.serial, "at" => entry.at }
82
+ end
83
+ end
84
+
85
+ def ended_at(last_turn)
86
+ stamp = last_turn&.ended_at
87
+ stamp ? Time.iso8601(stamp.to_s) : nil
88
+ rescue ArgumentError
89
+ nil
90
+ end
91
+ end
92
+ end