samagotchi 0.193.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 (138) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +77 -1
  3. data/docs/bundle-authoring.md +1 -1
  4. data/docs/bundles.md +37 -12
  5. data/docs/cli.md +26 -10
  6. data/docs/configuration.md +71 -5
  7. data/docs/desktop.md +3 -0
  8. data/docs/guardrails.md +11 -1
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/engine.md +46 -3
  11. data/docs/internals/panes.md +66 -0
  12. data/docs/internals/peers.md +101 -5
  13. data/docs/internals/prompt-caching.md +4 -0
  14. data/docs/internals/session-lifecycle.md +9 -2
  15. data/docs/internals/web-frontend.md +16 -4
  16. data/docs/peers.md +79 -5
  17. data/docs/plugins.md +42 -4
  18. data/docs/sessions.md +15 -6
  19. data/docs/sub-agent.md +6 -4
  20. data/docs/system-one.md +4 -0
  21. data/docs/testing.md +3 -0
  22. data/lib/samagotchi/bridge/card_store.rb +1 -1
  23. data/lib/samagotchi/broadcast/triage_model.rb +17 -0
  24. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  25. data/lib/samagotchi/bundles/claude-peer/plugin.rb +24 -5
  26. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +28 -7
  27. data/lib/samagotchi/bundles/claude-peer/scripts/pair +31 -8
  28. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  29. data/lib/samagotchi/bundles/codex-peer/plugin.rb +62 -6
  30. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +23 -2
  31. data/lib/samagotchi/bundles/codex-peer/scripts/pair +28 -7
  32. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  33. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  34. data/lib/samagotchi/chi_invocation.rb +7 -0
  35. data/lib/samagotchi/client.rb +18 -0
  36. data/lib/samagotchi/codex_rollout.rb +93 -0
  37. data/lib/samagotchi/config.rb +15 -6
  38. data/lib/samagotchi/effective_model.rb +28 -2
  39. data/lib/samagotchi/engine/cards.rb +9 -4
  40. data/lib/samagotchi/engine/hooks.rb +8 -0
  41. data/lib/samagotchi/engine/models.rb +180 -7
  42. data/lib/samagotchi/engine/side_requests.rb +72 -13
  43. data/lib/samagotchi/engine/toolkit.rb +1 -1
  44. data/lib/samagotchi/engine/turn_helpers.rb +1 -1
  45. data/lib/samagotchi/engine.rb +11 -8
  46. data/lib/samagotchi/engine_snapshots.rb +16 -3
  47. data/lib/samagotchi/events.rb +1 -0
  48. data/lib/samagotchi/hooks.rb +3 -1
  49. data/lib/samagotchi/host_registry.rb +146 -16
  50. data/lib/samagotchi/idle_client.rb +13 -2
  51. data/lib/samagotchi/idle_recap.rb +33 -3
  52. data/lib/samagotchi/idle_target.rb +27 -7
  53. data/lib/samagotchi/llm/adapter_common.rb +4 -2
  54. data/lib/samagotchi/llm/anthropic_messages.rb +3 -2
  55. data/lib/samagotchi/llm/errors.rb +35 -4
  56. data/lib/samagotchi/llm/model_listing.rb +19 -0
  57. data/lib/samagotchi/llm/openai_chat.rb +3 -2
  58. data/lib/samagotchi/model_binding.rb +46 -4
  59. data/lib/samagotchi/model_catalog.rb +68 -8
  60. data/lib/samagotchi/model_profile.rb +35 -0
  61. data/lib/samagotchi/models_command.rb +8 -4
  62. data/lib/samagotchi/panes/kitty.rb +122 -0
  63. data/lib/samagotchi/panes.rb +185 -0
  64. data/lib/samagotchi/peer_announce.rb +245 -0
  65. data/lib/samagotchi/peer_command.rb +97 -11
  66. data/lib/samagotchi/peer_continue.rb +10 -0
  67. data/lib/samagotchi/peer_mailbox.rb +30 -7
  68. data/lib/samagotchi/peer_pair_here.rb +149 -0
  69. data/lib/samagotchi/peer_presence.rb +434 -0
  70. data/lib/samagotchi/peer_say.rb +17 -10
  71. data/lib/samagotchi/peer_wait_expiry.rb +47 -0
  72. data/lib/samagotchi/plugin/api.rb +12 -1
  73. data/lib/samagotchi/plugin/card.rb +68 -11
  74. data/lib/samagotchi/plugin/context.rb +20 -1
  75. data/lib/samagotchi/plugin/panes.rb +54 -0
  76. data/lib/samagotchi/plugin/peer.rb +52 -10
  77. data/lib/samagotchi/plugin/peer_pairing.rb +290 -0
  78. data/lib/samagotchi/plugin/peer_start.rb +301 -0
  79. data/lib/samagotchi/plugin/peer_start_hook.rb +207 -0
  80. data/lib/samagotchi/plugin/peers.rb +76 -3
  81. data/lib/samagotchi/recap_setup.rb +40 -3
  82. data/lib/samagotchi/self_report.rb +25 -6
  83. data/lib/samagotchi/send_command.rb +6 -6
  84. data/lib/samagotchi/served_lookup.rb +225 -0
  85. data/lib/samagotchi/served_ref.rb +41 -0
  86. data/lib/samagotchi/session_access/contract.rb +6 -0
  87. data/lib/samagotchi/session_access/local.rb +54 -6
  88. data/lib/samagotchi/session_access/remote.rb +4 -4
  89. data/lib/samagotchi/session_access/remote_peers.rb +7 -4
  90. data/lib/samagotchi/session_commands.rb +40 -8
  91. data/lib/samagotchi/session_continue.rb +6 -2
  92. data/lib/samagotchi/session_lifecycle/allowed.rb +4 -2
  93. data/lib/samagotchi/session_manager/delivery.rb +5 -0
  94. data/lib/samagotchi/session_manager/lifecycle.rb +58 -7
  95. data/lib/samagotchi/session_manager/removal.rb +3 -0
  96. data/lib/samagotchi/session_model_settings.rb +7 -3
  97. data/lib/samagotchi/session_stores.rb +9 -0
  98. data/lib/samagotchi/sessions_command.rb +16 -3
  99. data/lib/samagotchi/system_one/http_backend.rb +111 -10
  100. data/lib/samagotchi/system_prompt.rb +11 -4
  101. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -1
  102. data/lib/samagotchi/terminal_ui/formatting.rb +26 -12
  103. data/lib/samagotchi/terminal_ui/status_row.rb +20 -3
  104. data/lib/samagotchi/terminal_ui.rb +1 -1
  105. data/lib/samagotchi/testing/bundle.rb +6 -2
  106. data/lib/samagotchi/turn_endings.rb +6 -2
  107. data/lib/samagotchi/user_typed.rb +29 -0
  108. data/lib/samagotchi/version.rb +1 -1
  109. data/lib/samagotchi/web/app.rb +8 -20
  110. data/lib/samagotchi/web/participant_review.rb +1 -1
  111. data/lib/samagotchi/web/participant_view.rb +1 -1
  112. data/lib/samagotchi/web/peer_routes.rb +33 -13
  113. data/lib/samagotchi/web/public/app.js +1 -1
  114. data/lib/samagotchi/web/public/card.js +26 -10
  115. data/lib/samagotchi/web/public/context_chips.js +24 -2
  116. data/lib/samagotchi/web/public/copy.js +8 -2
  117. data/lib/samagotchi/web/public/data.js +2 -1
  118. data/lib/samagotchi/web/public/format.js +9 -1
  119. data/lib/samagotchi/web/public/index.html +18 -0
  120. data/lib/samagotchi/web/public/info_bar_model.js +1 -1
  121. data/lib/samagotchi/web/public/model_pick.js +18 -5
  122. data/lib/samagotchi/web/public/model_picker.js +1 -1
  123. data/lib/samagotchi/web/public/peer_chip.js +15 -5
  124. data/lib/samagotchi/web/public/peer_data.js +4 -2
  125. data/lib/samagotchi/web/public/peer_wait.js +36 -0
  126. data/lib/samagotchi/web/public/served_ref.js +9 -0
  127. data/lib/samagotchi/web/public/session_fields.js +1 -0
  128. data/lib/samagotchi/web/public/session_state.js +4 -0
  129. data/lib/samagotchi/web/public/stage_missing.js +23 -6
  130. data/lib/samagotchi/web/public/stream_handlers.js +16 -0
  131. data/lib/samagotchi/web/public/version_notices.js +7 -1
  132. data/lib/samagotchi/web/session_control.rb +19 -10
  133. data/lib/samagotchi/web/session_show.rb +20 -0
  134. data/lib/samagotchi/web/update_ops.rb +2 -2
  135. data/lib/samagotchi/worker/command_queue.rb +3 -0
  136. data/lib/samagotchi/worker/mail.rb +14 -1
  137. data/lib/samagotchi/worker.rb +1 -0
  138. metadata +18 -1
@@ -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
@@ -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,12 +119,21 @@ 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
@@ -116,6 +142,62 @@ module Samagotchi
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
+
119
201
  # The tail naming the chain's live link a command of +id+ ran on.
120
202
  def continued(id, forwarded_to) = forwarded_to ? " (session #{id[0, 8]} continued as #{forwarded_to[0, 8]})" : ""
121
203
 
@@ -125,6 +207,10 @@ module Samagotchi
125
207
 
126
208
  name, id = checked
127
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
128
214
  unless ended.unpaired
129
215
  error_line("#{command_name}: #{(ended.forwarded_to || id)[0, 8]} isn't paired with #{name}#{continued(id, ended.forwarded_to)}")
130
216
  return CLI::Exit::FAILED
@@ -154,7 +240,7 @@ module Samagotchi
154
240
  return CLI::Exit::FAILED
155
241
  end
156
242
 
157
- @stdout.puts(said.line(name))
243
+ @stdout.puts(said.line(name, id: id, via: @access.invocation))
158
244
  said.receipt&.state == "refused" ? CLI::Exit::FAILED : 0
159
245
  end
160
246
 
@@ -2,6 +2,7 @@
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"
@@ -39,6 +40,7 @@ module Samagotchi
39
40
  # @return [Integer] how many messages the note holds
40
41
  def carry(from:, to:, state_dir:)
41
42
  carry_links(from, to, state_dir)
43
+ carry_waits(from, to, state_dir)
42
44
  rows = unread(from, state_dir: state_dir)
43
45
  return 0 if rows.empty?
44
46
 
@@ -56,6 +58,14 @@ module Samagotchi
56
58
  []
57
59
  end
58
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
+
59
69
  # [peer, PeerMessage] of every message +id+ hadn't read, by its time,
60
70
  # then peer, then serial (the worker's order).
61
71
  def unread(id, state_dir:)