samagotchi 0.186.0 → 0.188.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 (153) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +4 -0
  4. data/docs/architecture.md +8 -4
  5. data/docs/bundles.md +124 -120
  6. data/docs/cli.md +26 -5
  7. data/docs/configuration.md +4 -4
  8. data/docs/context.md +18 -162
  9. data/docs/guardrails.md +3 -1
  10. data/docs/hooks.md +2 -1
  11. data/docs/internals/attached-context.md +19 -37
  12. data/docs/internals/bridge.md +1 -0
  13. data/docs/internals/engine.md +2 -2
  14. data/docs/internals/inline-widgets.md +18 -0
  15. data/docs/internals/llm-context-forget.md +5 -6
  16. data/docs/internals/objectives.md +1 -0
  17. data/docs/internals/pages.md +175 -0
  18. data/docs/internals/peers.md +149 -0
  19. data/docs/internals/remote-sessions.md +7 -4
  20. data/docs/internals/web-frontend.md +65 -40
  21. data/docs/internals/web-push.md +1 -1
  22. data/docs/memory.md +8 -1
  23. data/docs/pages.md +151 -0
  24. data/docs/peers.md +141 -0
  25. data/docs/plugins.md +52 -27
  26. data/docs/sessions.md +8 -4
  27. data/docs/sub-agent.md +5 -5
  28. data/lib/samagotchi/bridge.rb +3 -3
  29. data/lib/samagotchi/bundle_command/api_calls.rb +2 -1
  30. data/lib/samagotchi/bundle_command/check.rb +1 -1
  31. data/lib/samagotchi/bundles/claude-peer/manifest.yml +11 -18
  32. data/lib/samagotchi/bundles/claude-peer/plugin.rb +22 -16
  33. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +48 -39
  34. data/lib/samagotchi/bundles/claude-peer/scripts/pair +15 -73
  35. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +16 -16
  36. data/lib/samagotchi/bundles/codex-peer/manifest.yml +11 -15
  37. data/lib/samagotchi/bundles/codex-peer/plugin.rb +35 -24
  38. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +51 -40
  39. data/lib/samagotchi/bundles/codex-peer/scripts/pair +18 -54
  40. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +16 -16
  41. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  42. data/lib/samagotchi/bundles/skills/manifest.yml +2 -2
  43. data/lib/samagotchi/bundles/skills/plugin.rb +14 -8
  44. data/lib/samagotchi/bundles/system/manifest.yml +5 -2
  45. data/lib/samagotchi/bundles/system/self_map.md +5 -1
  46. data/lib/samagotchi/bundles/system/skill_pages.md +93 -0
  47. data/lib/samagotchi/client_id.rb +15 -1
  48. data/lib/samagotchi/config.rb +8 -7
  49. data/lib/samagotchi/context_absorber.rb +23 -277
  50. data/lib/samagotchi/context_sources.rb +17 -69
  51. data/lib/samagotchi/engine/messages.rb +12 -1
  52. data/lib/samagotchi/engine/plugins.rb +1 -1
  53. data/lib/samagotchi/engine.rb +7 -6
  54. data/lib/samagotchi/engine_peers.rb +0 -3
  55. data/lib/samagotchi/guardrail_wiring.rb +2 -0
  56. data/lib/samagotchi/guardrails/chi_dirs.rb +4 -3
  57. data/lib/samagotchi/guardrails/parent_approvals.rb +6 -5
  58. data/lib/samagotchi/guardrails/protected_paths.rb +6 -3
  59. data/lib/samagotchi/inline_widgets.rb +73 -0
  60. data/lib/samagotchi/log_line.rb +1 -1
  61. data/lib/samagotchi/note_move.rb +3 -1
  62. data/lib/samagotchi/page_command.rb +243 -0
  63. data/lib/samagotchi/pages/builder.rb +186 -0
  64. data/lib/samagotchi/pages/launch.rb +193 -0
  65. data/lib/samagotchi/pages/runner.rb +154 -0
  66. data/lib/samagotchi/pages/store.rb +152 -0
  67. data/lib/samagotchi/pages.rb +119 -0
  68. data/lib/samagotchi/peer_command.rb +192 -0
  69. data/lib/samagotchi/peer_continue.rb +99 -0
  70. data/lib/samagotchi/peer_exchanges.rb +3 -3
  71. data/lib/samagotchi/peer_mailbox.rb +360 -0
  72. data/lib/samagotchi/peer_note.rb +208 -0
  73. data/lib/samagotchi/peer_receipts.rb +247 -0
  74. data/lib/samagotchi/peer_registry.rb +44 -0
  75. data/lib/samagotchi/peer_roster.rb +79 -0
  76. data/lib/samagotchi/peer_say.rb +168 -0
  77. data/lib/samagotchi/plugin/api.rb +29 -21
  78. data/lib/samagotchi/plugin/context.rb +7 -0
  79. data/lib/samagotchi/plugin/loader.rb +3 -3
  80. data/lib/samagotchi/plugin/peer.rb +175 -64
  81. data/lib/samagotchi/plugin/peers.rb +70 -0
  82. data/lib/samagotchi/run_options.rb +3 -1
  83. data/lib/samagotchi/schedule_command.rb +10 -3
  84. data/lib/samagotchi/schedule_display.rb +32 -0
  85. data/lib/samagotchi/session_access/contract.rb +19 -2
  86. data/lib/samagotchi/session_access/local.rb +132 -14
  87. data/lib/samagotchi/session_access/remote.rb +4 -2
  88. data/lib/samagotchi/session_access/remote_peers.rb +75 -0
  89. data/lib/samagotchi/session_continue.rb +12 -0
  90. data/lib/samagotchi/session_inbox_delivery.rb +5 -2
  91. data/lib/samagotchi/session_manager/delivery.rb +5 -3
  92. data/lib/samagotchi/session_manager/removal.rb +2 -0
  93. data/lib/samagotchi/session_manager/spawn.rb +2 -1
  94. data/lib/samagotchi/session_manager.rb +1 -0
  95. data/lib/samagotchi/session_stores.rb +17 -0
  96. data/lib/samagotchi/steer.rb +1 -1
  97. data/lib/samagotchi/system_prompt.rb +1 -1
  98. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  99. data/lib/samagotchi/terminal_ui/formatting.rb +4 -1
  100. data/lib/samagotchi/testing/boundary.rb +4 -13
  101. data/lib/samagotchi/testing/bundle.rb +40 -5
  102. data/lib/samagotchi/testing/install.rb +4 -4
  103. data/lib/samagotchi/testing/recording_api.rb +2 -1
  104. data/lib/samagotchi/tools/context_read.rb +0 -14
  105. data/lib/samagotchi/tools/list_schedules.rb +8 -3
  106. data/lib/samagotchi/version.rb +1 -1
  107. data/lib/samagotchi/web/app.rb +7 -18
  108. data/lib/samagotchi/web/message_display.rb +4 -2
  109. data/lib/samagotchi/web/page_routes.rb +116 -0
  110. data/lib/samagotchi/web/peer_routes.rb +133 -0
  111. data/lib/samagotchi/web/public/app.js +35 -95
  112. data/lib/samagotchi/web/public/bubbles.js +2 -2
  113. data/lib/samagotchi/web/public/cards_place.js +20 -1
  114. data/lib/samagotchi/web/public/context_chips.js +45 -46
  115. data/lib/samagotchi/web/public/history_reveal.js +4 -1
  116. data/lib/samagotchi/web/public/history_shape.js +3 -2
  117. data/lib/samagotchi/web/public/index.html +16 -0
  118. data/lib/samagotchi/web/public/notify.js +1 -1
  119. data/lib/samagotchi/web/public/page_blocks.js +58 -0
  120. data/lib/samagotchi/web/public/page_links.js +33 -0
  121. data/lib/samagotchi/web/public/page_model.js +68 -0
  122. data/lib/samagotchi/web/public/page_route.js +24 -0
  123. data/lib/samagotchi/web/public/page_table.js +74 -0
  124. data/lib/samagotchi/web/public/page_table_model.js +76 -0
  125. data/lib/samagotchi/web/public/page_view.js +219 -0
  126. data/lib/samagotchi/web/public/pages.css +77 -0
  127. data/lib/samagotchi/web/public/pages_group.js +65 -0
  128. data/lib/samagotchi/web/public/peer_chip.js +60 -74
  129. data/lib/samagotchi/web/public/peer_data.js +13 -11
  130. data/lib/samagotchi/web/public/peer_links.js +12 -7
  131. data/lib/samagotchi/web/public/peer_mailbox_api.js +20 -0
  132. data/lib/samagotchi/web/public/peer_note.js +7 -3
  133. data/lib/samagotchi/web/public/peer_text.js +4 -4
  134. data/lib/samagotchi/web/public/quiet_notes.js +199 -0
  135. data/lib/samagotchi/web/public/revise_stack.js +4 -3
  136. data/lib/samagotchi/web/public/session_view.js +2 -2
  137. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  138. data/lib/samagotchi/web/public/turn_block.js +7 -3
  139. data/lib/samagotchi/web/public/turn_events.js +6 -0
  140. data/lib/samagotchi/web/public/views.js +161 -0
  141. data/lib/samagotchi/web/push/attention.rb +3 -2
  142. data/lib/samagotchi/web/session_access_routes.rb +3 -20
  143. data/lib/samagotchi/web/viewer.rb +1 -1
  144. data/lib/samagotchi/worker/leave.rb +3 -0
  145. data/lib/samagotchi/worker/mail.rb +73 -0
  146. data/lib/samagotchi/worker/startup.rb +3 -0
  147. data/lib/samagotchi/worker/wake_turns.rb +20 -5
  148. data/lib/samagotchi/worker.rb +12 -6
  149. data/lib/samagotchi/worker_inbound/mail.rb +214 -0
  150. data/lib/samagotchi/worker_inbound.rb +43 -46
  151. data/lib/samagotchi/worker_wakes.rb +26 -21
  152. metadata +39 -2
  153. data/lib/samagotchi/peer_sources.rb +0 -58
@@ -7,18 +7,24 @@ require "open3"
7
7
  require "securerandom"
8
8
  require "tempfile"
9
9
  require "time"
10
+ require_relative "../config"
10
11
  require_relative "../paths"
11
12
  require_relative "../session"
12
13
  require_relative "../peer_exchanges"
14
+ require_relative "../peer_mailbox"
15
+ require_relative "../peer_note"
13
16
 
14
17
  module Samagotchi
15
18
  module Plugin
16
19
  # The base of the peer bundles' plugins (claude-peer, codex-peer;
17
- # docs/bundles.md): a live link between a chi session and another agent's
18
- # session the user works with. The peer pairs (its chi-peer skill,
19
- # scripts/pair): it attaches the `<peer>-inbox` context, whose hint says
20
- # where to send (a subclass's #check_hint!), and `<peer>-outbox`, where
21
- # its answers come back as pushes that wake chi.
20
+ # docs/bundles.md, docs/peers.md): a live link between a chi session and
21
+ # another agent's session the user works with. The peer pairs (its
22
+ # chi-peer skill, scripts/pair: `chi peer pair NAME <id> --address …`):
23
+ # the pairing's address says where to send (a subclass's #check_hint!).
24
+ # Its answers come back as messages in the session's mailbox (`chi peer
25
+ # say`), which the worker takes as the peer's notes (chi.peer NAME,
26
+ # WorkerInbound#absorb_mail). A note too long to hold its text points at
27
+ # the `<peer>_read` tool, declared here.
22
28
  #
23
29
  # The `<peer>_send` tool sends a part of the work (a plan step, a diff, a
24
30
  # finding): a header, `chi <id> · <kind> · <title>`, a `ref: <send id>`
@@ -48,20 +54,22 @@ module Samagotchi
48
54
  # quote. Such a text is titled by its first quoted line, not the quote's
49
55
  # `From your thinking:` label.
50
56
  #
51
- # A continue leaves the pairing with the previous link (its inbox and
52
- # outbox are pushed sources: ContextSources.move). The new link's quiet
53
- # init task (#pair_again) posts the `moved` message to the inbox left
54
- # behind, once, so the peer pairs again with the new id; its chi-peer
55
- # skill knows how it paired.
57
+ # A continue leaves the pairing with the previous link (its mailbox
58
+ # stays there). The new link's quiet init task (#tell_moved) posts the
59
+ # `moved` message to the address the previous link's pairing names
60
+ # (ctx.peers.left_behind), once, so the peer pairs again with the new
61
+ # id; its chi-peer skill knows how it paired.
56
62
  #
57
- # A subclass (the bundle's Plugin) sets the strings, as constants:
58
- # INBOX, OUTBOX ("<peer>-inbox", "-outbox"), BUNDLE, NAME (the peer, as
59
- # the model and user call it: "Claude"), APP (its product: "Claude
60
- # Code"), COMMAND ("/claude"), TOOL, TOOL_DESCRIPTION, TOOL_PARAMS,
61
- # USAGE, STATUS_CARD, SKILL_CARD, CHECKED_ON and SCRIPTS_DIRS (beside the
62
- # bundle's own file), and the transport, as the hooks below that raise
63
- # NotImplementedError. Its constants are read as self.class::X: a bare
64
- # name here would find only this class's.
63
+ # A subclass (the bundle's Plugin) sets the strings, as constants: PEER
64
+ # (its mailbox name: "claude"), BUNDLE, NAME (the peer, as the model and
65
+ # user call it: "Claude", PeerMailbox.label of PEER), APP (its product:
66
+ # "Claude Code"), COMMAND ("/claude"), TOOL, READ_TOOL, TOOL_DESCRIPTION,
67
+ # TOOL_PARAMS, USAGE, STATUS_CARD, SKILL_CARD, CHECKED_ON, SCRIPTS_DIRS
68
+ # (beside the bundle's own file), LEGACY_INBOX and LEGACY_OUTBOX (the
69
+ # context sources an older bundle paired through: the status card's
70
+ # "paired the old way" line only; remove after the next release), and the transport, as the hooks
71
+ # below that raise NotImplementedError. Its constants are read as
72
+ # self.class::X: a bare name here would find only this class's.
65
73
  class Peer
66
74
  KINDS = %w[validate context question].freeze
67
75
  # A part up to this long goes inline: the peer reads it with no file
@@ -80,6 +88,9 @@ module Samagotchi
80
88
  DIFF_LINES = 20
81
89
  # Under the session's data dir: the moved message went (or was tried).
82
90
  MOVED_MARKER = "moved-posted"
91
+ # The <peer>_read tool's page, at most (its output's cap, as context_read's).
92
+ READ_DEFAULT_CHARS = 10_000
93
+ READ_MIN_CHARS = 2_000
83
94
  # The label line a web quote starts with (annotations.js sourceLabel).
84
95
  QUOTE_LABEL = /\AFrom (?:your thinking|your earlier step|the .+ call|my earlier message):\z/
85
96
 
@@ -108,6 +119,10 @@ module Samagotchi
108
119
 
109
120
  def register(chi)
110
121
  peer = self.class
122
+ unless peer.const_defined?(:PEER) && peer.const_defined?(:READ_TOOL)
123
+ raise ArgumentError, "chi.peer_source is gone: upgrade this bundle " \
124
+ "(chi bundle install #{peer::BUNDLE} --force)"
125
+ end
111
126
  # Two args: the run's tool id salts the send id, the same one the
112
127
  # block's deliver gets (ctx.tool_id).
113
128
  refs = lambda do |args, tool_id = nil|
@@ -127,11 +142,15 @@ module Samagotchi
127
142
  "it; install-skill: install #{peer::NAME}'s chi-peer skill", anytime: true do |args, ctx|
128
143
  run_command(args.to_s.strip, ctx)
129
144
  end
145
+ chi.tool peer::READ_TOOL, read_description, params: READ_PARAMS, label: "read #{peer::NAME}'s message",
146
+ preview: ->(args) { "##{args["serial"]}" } do |args, ctx|
147
+ read_message(ctx, args)
148
+ end
130
149
  chi.annotation "Confirm with #{peer::NAME}", command: "#{peer::COMMAND} validate"
131
- chi.init("Asking #{peer::NAME} to pair again", quiet: true) { |ctx| pair_again(ctx) }
132
- # The outbox source is the peer's answers: its own wake budget and
133
- # line (context.peer_turns).
134
- chi.peer_source peer::OUTBOX, label: peer::NAME
150
+ chi.init("Telling #{peer::NAME} the session moved", quiet: true) { |ctx| tell_moved(ctx) }
151
+ # Its messages in the mailbox are this peer's: its notes, its wake
152
+ # budget and lines (peer.turns).
153
+ chi.peer peer::PEER
135
154
  chi.on(:before_turn) do |event|
136
155
  @lock.synchronize { @before_turn = Array(event[:messages]) }
137
156
  end
@@ -178,28 +197,27 @@ module Samagotchi
178
197
  "sent to #{self.class::NAME}: #{kind} · #{title}#{" (the text in #{where})" unless where == "inline"}"
179
198
  end
180
199
 
181
- # A continue's new link whose previous link kept this peer's INBOX
182
- # (ctx.context.left_behind): posts the moved message to that inbox's
183
- # hint, once (a marker under the session's data dir: a worker restart
200
+ # A continue's new link whose previous link was paired with this peer
201
+ # (ctx.peers.left_behind, with an address): posts the moved message
202
+ # there, once (a marker under the session's data dir: a worker restart
184
203
  # doesn't post again). A post that fails is logged and dropped: no
185
- # retry, and the peer's next push to the old id is refused with the
186
- # new one (its skill pairs again then).
204
+ # retry, and the peer's next say to the old id is refused with the new
205
+ # one (its skill pairs again then).
187
206
  # @return [String] what it did (the quiet init task's summary)
188
- def pair_again(ctx)
207
+ def tell_moved(ctx)
189
208
  peer = self.class
190
209
  previous = ctx.continues or return "not a continue"
191
210
  id = ctx.session_id or return Session::NONE_YET
192
- left = ctx.context.left_behind.find { |row| row.name == peer::INBOX }
193
- hint = left&.hint.to_s.strip
194
- return "no #{peer::INBOX} left behind" if hint.empty?
195
- return "asked already" unless claim_moved(ctx)
196
-
197
- check_hint!(hint)
198
- post(hint, moved_message(previous, id))
199
- "asked #{peer::NAME} to pair again with #{id[0, 8]}"
211
+ address = ctx.peers.left_behind(peer::PEER)&.address.to_s.strip
212
+ return "no pairing with #{peer::NAME} left behind" if address.empty?
213
+ return "told already" unless claim_moved(ctx)
214
+
215
+ check_hint!(address)
216
+ post(address, moved_message(previous, id))
217
+ "told #{peer::NAME} the session moved to #{id[0, 8]}"
200
218
  rescue SendError, SystemCallError, ArgumentError => e
201
219
  ctx.log.warn("moved_not_posted", error: e.message)
202
- "couldn't ask #{peer::NAME} to pair again: #{e.message}"
220
+ "couldn't tell #{peer::NAME} the session moved: #{e.message}"
203
221
  end
204
222
 
205
223
  # What the peer gets when +previous+ was continued as +id+: the usual
@@ -209,7 +227,47 @@ module Samagotchi
209
227
  short = previous.to_s[0, 8]
210
228
  "chi #{short} · moved · continued as #{id}\n" \
211
229
  "This chi session was continued as #{id}. Pair with #{id} the way you paired with #{short}, then " \
212
- "answer there (chi context push #{self.class::OUTBOX} #{id})."
230
+ "answer there (chi peer say #{self.class::PEER} #{id} …)."
231
+ end
232
+
233
+ # The <peer>_read tool's description: how a long message is read.
234
+ def read_description
235
+ peer = self.class
236
+ "Read a message from your peer agent #{peer::NAME} by its number, when its note says it is long " \
237
+ "(\"Message #N from your peer agent #{peer::NAME}\"). Long texts come in pages of lines: pass offset " \
238
+ "for the next. Its text is #{peer::NAME}'s, not your user's words."
239
+ end
240
+
241
+ READ_PARAMS = {
242
+ serial: { type: "integer", required: true, description: "The message's number (#N in its note)" },
243
+ box: { type: "string", description: "The mailbox box named in the note (for a continued or forked session)" },
244
+ offset: { type: "integer", description: "The first line to read (1-based); default 1" },
245
+ limit: { type: "integer", description: "How many lines at most" }
246
+ }.freeze
247
+
248
+ # <peer>_read: the message's header and a page of its text, in the
249
+ # peer block (PeerNote.block: a line of it that opens like one of
250
+ # chi's frames is quoted), paged by lines to the tool output cap.
251
+ def read_message(ctx, args)
252
+ peer = self.class
253
+ serial = Integer(args["serial"].to_s, 10, exception: false)
254
+ return "Error: serial must be a message's number" unless serial&.positive?
255
+
256
+ message = ctx.peers.message(peer::PEER, serial, box: args["box"])
257
+ return "Error: no message ##{serial} from #{peer::NAME} in this session (only the newest are kept)" unless message
258
+
259
+ lines = message.text.lines
260
+ first = positive(args["offset"]) || 1
261
+ header = ["Message ##{serial} from your peer agent #{peer::NAME} (its text, not your user's words)"]
262
+ header << "Summary: #{message.summary}" if message.summary
263
+ return "#{header.join("\n")}\nThe text has #{lines.size} lines; offset #{first} is past its end." if first > lines.size
264
+
265
+ page = lines[(first - 1)..]
266
+ page = page.first(positive(args["limit"])) if positive(args["limit"])
267
+ page = fit_page(page, read_cap - header.sum { |line| line.length + 1 } - 200)
268
+ last = first + page.size - 1
269
+ header << "Lines #{first}-#{last} of #{lines.size}.#{" Pass offset: #{last + 1} for more." if last < lines.size}" if first > 1 || last < lines.size
270
+ "#{header.join("\n")}\n#{PeerNote.block(peer::NAME, page.join)}"
213
271
  end
214
272
 
215
273
  private
@@ -249,6 +307,10 @@ module Samagotchi
249
307
  # More placeholders the installed skill fills in: {placeholder => text}.
250
308
  def skill_substitutions(_ctx) = {}
251
309
 
310
+ # What the transport needs once the skill is written (codex-peer: its
311
+ # sandbox's writable root).
312
+ def skill_installed(_ctx) = nil
313
+
252
314
  def run_command(args, ctx)
253
315
  verb = args.split(/\s+/, 2).first
254
316
  # The rest as typed: a pasted selection keeps its lines.
@@ -264,7 +326,7 @@ module Samagotchi
264
326
 
265
327
  def send_text(ctx, kind, text)
266
328
  "#{deliver(ctx, kind: kind, title: text_title(text), text: text, by: "user", salt: command_salt)}; #{self.class::NAME}'s answer comes as a " \
267
- "note with its text (#{self.class::OUTBOX})"
329
+ "message with its text"
268
330
  rescue SendError => e
269
331
  "#{self.class::COMMAND}: #{e.message}"
270
332
  end
@@ -306,50 +368,99 @@ module Samagotchi
306
368
  end
307
369
 
308
370
  # The session's attached sources; none when they can't be read (a new
309
- # session not saved yet; a corrupt session file).
371
+ # session not saved yet; a corrupt session file). Only the status
372
+ # card's "paired the old way" line reads them (LEGACY_INBOX, LEGACY_OUTBOX).
310
373
  def sources(ctx)
311
374
  ctx.context.list
312
375
  rescue ArgumentError, SystemCallError
313
376
  []
314
377
  end
315
378
 
379
+ # Whether an older bundle's pairing (its LEGACY_INBOX or LEGACY_OUTBOX
380
+ # context source) is attached.
381
+ def paired_the_old_way?(ctx)
382
+ old = [self.class::LEGACY_INBOX, self.class::LEGACY_OUTBOX]
383
+ sources(ctx).any? { |source| old.include?(source[:name]) }
384
+ end
385
+
386
+ def positive(value)
387
+ number = Integer(value.to_s, 10, exception: false)
388
+ number if number&.positive?
389
+ end
390
+
391
+ # The tool output cap a <peer>_read page fits (max_tool_output_chars).
392
+ def read_cap
393
+ value = Config.get("max_tool_output_chars").to_i
394
+ [value.positive? ? value : READ_DEFAULT_CHARS, READ_MIN_CHARS].max
395
+ end
396
+
397
+ # The lines of +page+ that fit in +room+ characters, at least one
398
+ # (cut to the room when one line is over it).
399
+ def fit_page(page, room)
400
+ room = [room, 200].max
401
+ kept = []
402
+ used = 0
403
+ page.each do |line|
404
+ break if used + line.length > room && kept.any?
405
+
406
+ kept << (line.length > room ? line[0, room] : line)
407
+ used += line.length
408
+ end
409
+ kept
410
+ end
411
+
316
412
  def role(message) = field(message, :role).to_s
317
413
  def kind(message) = field(message, :kind).to_s
318
414
  def field(hash, key) = hash.is_a?(Hash) ? hash[key] || hash[key.to_s] : nil
319
415
 
320
- # The paired peer's inbox hint: the inbox context's hint, checked by
321
- # the transport.
416
+ # Where the paired peer takes sends: the pairing's address
417
+ # (ctx.peers.link), checked by the transport.
322
418
  # @raise [SendError]
323
419
  def peer_hint!(ctx)
324
420
  peer = self.class
325
- inbox = sources(ctx).find { |source| source[:name] == peer::INBOX }
326
- hint = inbox && inbox[:hint].to_s.strip
327
- if hint.nil? || hint.empty?
328
- raise SendError, "no #{peer::INBOX}: pair from #{peer::NAME} (install its skill with #{peer::COMMAND} " \
329
- "install-skill, then tell #{peer::NAME} \"pair with chi #{ctx.session_id.to_s[0, 8]}\")"
421
+ link = ctx.peers.link(peer::PEER)
422
+ unless link
423
+ raise SendError, "#{peer::NAME} isn't paired: pair from #{peer::NAME} (install its skill with " \
424
+ "#{peer::COMMAND} install-skill, then tell #{peer::NAME} \"pair with chi " \
425
+ "#{ctx.session_id.to_s[0, 8]}\")"
330
426
  end
331
- check_hint!(hint)
332
- hint
427
+ address = link.address.to_s.strip
428
+ raise SendError, answers_only_line if address.empty?
429
+
430
+ check_hint!(address)
431
+ address
432
+ end
433
+
434
+ # A pairing with no address: the peer can answer, chi can't send.
435
+ def answers_only_line
436
+ peer = self.class
437
+ "#{peer::NAME} paired for answers only (it runs where chi can't reach it): chi can't send to it; pair " \
438
+ "again from #{peer::NAME} with an address chi can reach"
333
439
  end
334
440
 
335
441
  # The status card; nil, so the command adds no text.
336
442
  def status(ctx)
337
443
  peer = self.class
338
444
  id = ctx.session_id
339
- sources = id ? sources(ctx) : []
340
- inbox, outbox = [peer::INBOX, peer::OUTBOX].map { |name| sources.find { |source| source[:name] == name } }
341
- hint = inbox && inbox[:hint].to_s.strip
342
- paired = !(hint.nil? || hint.empty?)
343
- lines = if paired
344
- paired_lines(hint)
445
+ link = id && ctx.peers.link(peer::PEER)
446
+ address = link&.address.to_s.strip
447
+ lines = if link && !address.empty?
448
+ paired_lines(address)
449
+ elsif link
450
+ ["**paired** for answers only: #{peer::NAME} can answer here, chi can't send to it (it paired " \
451
+ "with no address chi can reach)"]
452
+ elsif id && paired_the_old_way?(ctx)
453
+ ["**paired the old way: pair again** (install the skill first: Install skill below, then tell " \
454
+ "#{peer::NAME} \"pair with chi #{id[0, 8]}\")."]
345
455
  else
346
456
  ["**not paired.** In #{peer::APP}, install the chi-peer skill (Install skill below), then tell " \
347
457
  "#{peer::NAME} \"pair with chi #{id.to_s[0, 8]}\"."]
348
458
  end
459
+ paired = !link.nil?
349
460
  lines << "last send: #{last_send_line(ctx)}" if id && last_send(ctx)
350
- if outbox
351
- lines << "last message from #{peer::NAME} (#{peer::OUTBOX}, its text in the conversation): " \
352
- "#{outbox_line(outbox)}"
461
+ if link
462
+ last = ctx.peers.last_message(peer::PEER)
463
+ lines << "last message from #{peer::NAME} (its text in the conversation): #{message_line(last)}"
353
464
  end
354
465
  lines << "skill: **differs from this bundle's**: #{peer::COMMAND} install-skill (Replace), then pair again" if skill_differs?(ctx)
355
466
  lines << transport_line
@@ -372,10 +483,10 @@ module Samagotchi
372
483
  "#{ago(sent["at"])} · #{sent["kind"]} · #{sent["title"]} (#{sent["chars"]} chars, #{where})"
373
484
  end
374
485
 
375
- def outbox_line(outbox)
376
- return "none yet" unless outbox[:fetched_at]
486
+ def message_line(message)
487
+ return "none yet" unless message
377
488
 
378
- [outbox[:summary], ago(outbox[:fetched_at])].compact.join(" · ")
489
+ ["##{message.serial}", message.summary, ago(message.at)].compact.join(" · ")
379
490
  end
380
491
 
381
492
  def ago(stamp)
@@ -442,6 +553,7 @@ module Samagotchi
442
553
  def write_skill(ctx, target, text)
443
554
  FileUtils.mkdir_p(File.dirname(target))
444
555
  File.write(target, text)
556
+ skill_installed(ctx)
445
557
  ctx.card(id: self.class::SKILL_CARD, title: "#{self.class::NAME}'s chi-peer skill",
446
558
  body: "Installed `#{target}`. #{installed_line(ctx.session_id.to_s[0, 8])}")
447
559
  nil
@@ -468,7 +580,7 @@ module Samagotchi
468
580
  def follow_up(kind)
469
581
  case kind
470
582
  when "context" then "#{self.class::NAME} takes it in; it answers only if something in it is wrong."
471
- else "#{self.class::NAME}'s answer comes as a note with its text (#{self.class::OUTBOX}); don't wait or poll."
583
+ else "#{self.class::NAME}'s answer comes as a message with its text; don't wait or poll."
472
584
  end
473
585
  end
474
586
 
@@ -493,8 +605,7 @@ module Samagotchi
493
605
  end
494
606
 
495
607
  def exchange(ctx, **entry)
496
- peer = ContextSources.peer_leg(self.class::INBOX)&.first || self.class::NAME.downcase
497
- PeerExchanges.append(ctx.session_id, { peer: peer, **entry }, state_dir: ctx.session_state_dir)
608
+ PeerExchanges.append(ctx.session_id, { peer: self.class::PEER, **entry }, state_dir: ctx.session_state_dir)
498
609
  rescue SystemCallError, IOError, JSON::GeneratorError => e
499
610
  ctx.log.warn("peer_exchange_not_saved", error: e.message)
500
611
  end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../peer_mailbox"
4
+ require_relative "../peer_receipts"
5
+ require_relative "../session"
6
+
7
+ module Samagotchi
8
+ module Plugin
9
+ # ctx.peers (docs/plugins.md, Peers): what a peer bundle reads of its
10
+ # peer's side of the session (PeerMailbox): the pairing (where its
11
+ # sends go) and the peer's messages. Read only: a peer pairs and says
12
+ # through `chi peer` (its pair script, its skill); the worker takes the
13
+ # messages (WorkerInbound#absorb_mail). Plugin::Peer is its caller.
14
+ class Peers
15
+ # @param host [Host] session_id and state_dir
16
+ # @param continues [#call] the id of the session this one continues, or nil
17
+ def initialize(host, continues:)
18
+ @host = host
19
+ @continues = continues
20
+ end
21
+
22
+ # This session's pairing with +name+ ("claude").
23
+ # @return [PeerMailbox::PeerLink, nil] nil when not paired (or no session yet)
24
+ def link(name) = read_link(@host.session_id.call, name)
25
+
26
+ # The pairing a continue left with the previous link: a continue
27
+ # doesn't move it, so the peer is told the new id (Plugin::Peer
28
+ # #tell_moved) and pairs again.
29
+ # @return [PeerMailbox::PeerLink, nil] nil when this session continues none, or it wasn't paired
30
+ def left_behind(name) = read_link(@continues.call, name)
31
+
32
+ # +name+'s message +serial+ (its text, summary, wake, re, at).
33
+ # @return [PeerMailbox::PeerMessage, nil] nil when it isn't there (trimmed) or isn't good
34
+ def message(name, serial, box: nil)
35
+ id = @host.session_id.call or return nil
36
+ expected = @host.session_id.call && PeerReceipts.read(id, state_dir: state_dir).peer(name.to_s).box
37
+ return nil if box && expected != box
38
+
39
+ PeerMailbox.message(id, name.to_s, serial, state_dir: state_dir)
40
+ rescue PeerMailbox::Invalid, SessionPaths::InvalidId
41
+ nil
42
+ end
43
+
44
+ # +name+'s newest message that is still in the mailbox.
45
+ # @return [PeerMailbox::PeerMessage, nil]
46
+ def last_message(name)
47
+ id = @host.session_id.call or return nil
48
+ PeerMailbox.serials(id, name.to_s, state_dir: state_dir).reverse_each do |serial|
49
+ found = PeerMailbox.message(id, name.to_s, serial, state_dir: state_dir)
50
+ return found if found
51
+ end
52
+ nil
53
+ rescue PeerMailbox::Invalid, SessionPaths::InvalidId
54
+ nil
55
+ end
56
+
57
+ private
58
+
59
+ def state_dir = @host.state_dir&.call || Session.default_state_dir
60
+
61
+ def read_link(id, name)
62
+ return nil unless id
63
+
64
+ PeerMailbox.link(id, name.to_s, state_dir: state_dir)
65
+ rescue PeerMailbox::Invalid, SessionPaths::InvalidId
66
+ nil
67
+ end
68
+ end
69
+ end
70
+ end
@@ -200,10 +200,12 @@ module Samagotchi
200
200
  chi note [--source NAME] [-m TEXT] ID...|--all background context for sessions
201
201
  chi broadcast [-m TEXT] [--all] [--dry-run] | log | deliver a note for every session it may concern
202
202
  chi context <add|push|ls|show|refresh|rm|mute|unmute> live external text attached to sessions
203
+ chi peer <pair|unpair|say|ls> … a peer agent's side of a session (its messages to chi)
203
204
  chi send [-m TEXT] ID...|--new a message into sessions, as if typed there
204
205
  chi answer ID --question QID --option N answer a question a session waits on
205
206
  chi share ID --name NAME | ls [ID] | cap ID P D | revoke ID [P]|--all invite people into a session
206
207
  chi memory <ls|rm> [--scope project|system] the memories; rm moves one to the bundle trash
208
+ chi page <run|list|rm> [NAME] pages: scripts under ~/.config/samagotchi/pages that say what to show
207
209
  chi bundle <install|upgrade|uninstall|status|diff|list|build|trash|new|test|check|try>
208
210
  chi guardrails replay [--dry-run] [--threshold T] [--model M] seed System 1's record from answered approvals
209
211
  chi guardrails rule <id> print "asks" if that rule votes ask on this machine now
@@ -216,7 +218,7 @@ module Samagotchi
216
218
  chi schedule <add|list|show|tick|run-now|enable|disable|cancel> durable schedules that outlive every worker
217
219
  chi mcp serve chi as an MCP server on stdio (claude mcp add chi -- chi mcp serve)
218
220
  chi remote <add|ls|rm> other machines' chi web, for chi --remote NAME
219
- chi --remote NAME <send|answer|note|context|sessions|share|mcp> … those commands on that machine (or CHI_REMOTE=NAME)
221
+ chi --remote NAME <send|answer|note|context|peer|sessions|share|mcp> … those commands on that machine (or CHI_REMOTE=NAME)
220
222
  chi --remote NAME --attach ID | --resume ID | --dir DIR [-p TEXT] a session on that machine, in this terminal
221
223
  chi self version, paths, model and bundles
222
224
  chi update [--dry-run] update this chi, its bundles and the desktop helper
@@ -6,6 +6,7 @@ require "time"
6
6
  require_relative "cli/command"
7
7
  require_relative "cli/exit"
8
8
  require_relative "cli/flags"
9
+ require_relative "schedule_display"
9
10
  require_relative "schedules"
10
11
  require_relative "session"
11
12
 
@@ -156,7 +157,8 @@ module Samagotchi
156
157
  print_tick_warning
157
158
  return CLI::Exit::OK
158
159
  end
159
- entries.each { |entry| @stdout.puts(entry_line(entry)) }
160
+ name_width = ScheduleDisplay.name_width(entries)
161
+ entries.each { |entry| @stdout.puts(entry_line(entry, name_width: name_width)) }
160
162
  print_tick_warning
161
163
  CLI::Exit::OK
162
164
  end
@@ -243,7 +245,11 @@ module Samagotchi
243
245
  iso.to_s
244
246
  end
245
247
 
246
- def entry_line(entry)
248
+ # One `list` row: id, name, mode, recurrence, next due, target head, and the
249
+ # notes (skips, why it is disabled, the last result). +name_width+ is the
250
+ # widest name among the rows printed; without it the name column is just
251
+ # the name.
252
+ def entry_line(entry, name_width: nil)
247
253
  note = ""
248
254
  note += " skips #{entry.skips} of #{entry.max_skips} (#{skip_window(entry)})" if entry.skips.positive?
249
255
  unless entry.enabled
@@ -258,7 +264,8 @@ module Samagotchi
258
264
  end
259
265
  end
260
266
  note += " last: #{entry.last_result}" if entry.last_result
261
- "#{entry.id} #{entry.mode} #{entry.recurrence_words} #{clock(entry.next_due)} #{entry.head[0, 8]}#{note}"
267
+ "#{entry.id} #{ScheduleDisplay.name(entry, width: name_width)} #{entry.mode} #{entry.recurrence_words} " \
268
+ "#{clock(entry.next_due)} #{entry.head[0, 8]}#{note}"
262
269
  end
263
270
 
264
271
  # A skip budget as a time window: 3 of 12 at a 5 minute tick is about 1 hour
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ # What a schedule is called when it is listed: `chi schedule list` and the
5
+ # `list_schedules` tool both use this, so a schedule reads the same in the
6
+ # terminal and to the model. The name is its title when it has one; a schedule
7
+ # made without a title is named by the start of its prompt, in quotes, cut at
8
+ # PROMPT_CHARS with "…" where the cut falls. The name is display only: the
9
+ # entry keeps its title as given (nil when there is none) and its whole prompt.
10
+ module ScheduleDisplay
11
+ # How much of a titleless prompt the name shows.
12
+ PROMPT_CHARS = 30
13
+
14
+ # @param entry [Schedules::Entry]
15
+ # @param width [Integer, nil] pad to this width — the widest name among the
16
+ # rows being printed — so the columns after the name line up; without it
17
+ # the name is just the name.
18
+ def self.name(entry, width: nil)
19
+ given = entry.title.to_s.strip
20
+ if given.empty?
21
+ words = entry.prompt.to_s.gsub(/\s+/, " ").strip
22
+ given = words.length > PROMPT_CHARS ? "\"#{words[0, PROMPT_CHARS]}…\"" : "\"#{words}\""
23
+ end
24
+ width ? given.ljust(width) : given
25
+ end
26
+
27
+ # The width of the name column for these entries.
28
+ def self.name_width(entries)
29
+ entries.map { |entry| name(entry) }.map(&:length).max
30
+ end
31
+ end
32
+ end
@@ -10,7 +10,7 @@ module Samagotchi
10
10
  # "chi <cmd> runs on this machine only: run it on <remote>"). The v1 scope is the remote-sessions plan's
11
11
  # D3: send, answer, note, a session's context (add, push, ls, show, rm)
12
12
  # and sessions list/stop/restart/archive/unarchive/delete, chi share
13
- # (the shared-sessions plan's P2); the rest
13
+ # (the shared-sessions plan's P2), chi peer (peer-mailbox); the rest
14
14
  # stays local. bin/chi's subcommands that act on the machine, not on
15
15
  # sessions, are MACHINE. The run flags (chi --attach, -p, --resume: a
16
16
  # session in this terminal, a remote attach there) are RUN's.
@@ -26,7 +26,7 @@ module Samagotchi
26
26
  # bin/chi subcommands that act on this machine: never sessions. chi
27
27
  # remote (this machine's list of remotes) runs here under a remote too
28
28
  # (Dispatch); the others are refused there.
29
- MACHINE = %w[bootstrap update models desktop memory bundle guardrails toolkit judgments remote home project schedule].freeze
29
+ MACHINE = %w[bootstrap update models desktop memory page bundle guardrails toolkit judgments remote home project schedule].freeze
30
30
 
31
31
  # "command", "command sub" or either with a flag (its long name) →
32
32
  # SUPPORTED or LOCAL_ONLY. A LOCAL_ONLY command or subcommand lists
@@ -150,6 +150,23 @@ module Samagotchi
150
150
  "mcp" => SUPPORTED,
151
151
  "mcp serve" => SUPPORTED,
152
152
 
153
+ # A peer agent's side of a session (PeerMailbox): the remote's chi
154
+ # web pairs and writes, and a say waits there (POST …/say, wait:).
155
+ "peer" => SUPPORTED,
156
+ "peer pair" => SUPPORTED,
157
+ "peer pair --address" => SUPPORTED,
158
+ "peer pair --from" => SUPPORTED,
159
+ "peer unpair" => SUPPORTED,
160
+ "peer say" => SUPPORTED,
161
+ "peer say --wake" => SUPPORTED,
162
+ "peer say --nowake" => SUPPORTED,
163
+ "peer say --summary" => SUPPORTED,
164
+ "peer say --re" => SUPPORTED,
165
+ "peer say --message" => SUPPORTED,
166
+ "peer say --wait" => SUPPORTED,
167
+ "peer ls" => SUPPORTED,
168
+ "peer ls --format" => SUPPORTED,
169
+
153
170
  "broadcast" => LOCAL_ONLY
154
171
  }.freeze
155
172