samagotchi 0.187.0 → 0.189.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 (184) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +96 -1
  3. data/bin/chi +2 -0
  4. data/docs/architecture.md +13 -7
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +139 -120
  7. data/docs/cli.md +46 -8
  8. data/docs/configuration.md +4 -4
  9. data/docs/context.md +18 -162
  10. data/docs/guardrails.md +6 -3
  11. data/docs/hooks.md +2 -1
  12. data/docs/internals/attached-context.md +19 -37
  13. data/docs/internals/bridge.md +1 -0
  14. data/docs/internals/bundles.md +3 -3
  15. data/docs/internals/engine.md +2 -2
  16. data/docs/internals/llm-context-forget.md +5 -6
  17. data/docs/internals/objectives.md +1 -0
  18. data/docs/internals/pages.md +71 -21
  19. data/docs/internals/peers.md +149 -0
  20. data/docs/internals/remote-sessions.md +7 -4
  21. data/docs/internals/session-lifecycle.md +19 -6
  22. data/docs/internals/web-frontend.md +63 -39
  23. data/docs/internals/web-push.md +12 -6
  24. data/docs/memory.md +1 -1
  25. data/docs/pages.md +70 -16
  26. data/docs/peers.md +144 -0
  27. data/docs/plugins.md +77 -28
  28. data/docs/releasing.md +1 -1
  29. data/docs/scheduling.md +71 -8
  30. data/docs/sessions.md +12 -8
  31. data/docs/sub-agent.md +5 -5
  32. data/docs/testing.md +1 -1
  33. data/lib/samagotchi/bridge.rb +3 -3
  34. data/lib/samagotchi/bundle_command/api_calls.rb +2 -1
  35. data/lib/samagotchi/bundle_command/check.rb +1 -1
  36. data/lib/samagotchi/bundle_manifest.rb +34 -5
  37. data/lib/samagotchi/bundles/claude-peer/manifest.yml +11 -18
  38. data/lib/samagotchi/bundles/claude-peer/plugin.rb +22 -16
  39. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +48 -39
  40. data/lib/samagotchi/bundles/claude-peer/scripts/pair +15 -73
  41. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +16 -16
  42. data/lib/samagotchi/bundles/codex-peer/manifest.yml +11 -15
  43. data/lib/samagotchi/bundles/codex-peer/plugin.rb +35 -24
  44. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +51 -40
  45. data/lib/samagotchi/bundles/codex-peer/scripts/pair +18 -54
  46. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +16 -16
  47. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  48. data/lib/samagotchi/bundles/schedules/manifest.yml +11 -0
  49. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +159 -0
  50. data/lib/samagotchi/bundles/skills/manifest.yml +2 -2
  51. data/lib/samagotchi/bundles/skills/plugin.rb +14 -8
  52. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  53. data/lib/samagotchi/bundles/system/self_map.md +2 -2
  54. data/lib/samagotchi/bundles/system/skill_pages.md +9 -4
  55. data/lib/samagotchi/client_id.rb +15 -1
  56. data/lib/samagotchi/config.rb +8 -7
  57. data/lib/samagotchi/context_absorber.rb +23 -277
  58. data/lib/samagotchi/context_sources.rb +17 -69
  59. data/lib/samagotchi/engine/messages.rb +12 -1
  60. data/lib/samagotchi/engine/plugins.rb +1 -1
  61. data/lib/samagotchi/engine.rb +7 -6
  62. data/lib/samagotchi/engine_peers.rb +0 -3
  63. data/lib/samagotchi/guardrail_wiring.rb +2 -0
  64. data/lib/samagotchi/guardrails/chi_dirs.rb +4 -3
  65. data/lib/samagotchi/guardrails/parent_approvals.rb +6 -5
  66. data/lib/samagotchi/guardrails/protected_paths.rb +6 -3
  67. data/lib/samagotchi/inline_widgets.rb +11 -3
  68. data/lib/samagotchi/installed_bundles/manifest.rb +8 -1
  69. data/lib/samagotchi/log_line.rb +1 -1
  70. data/lib/samagotchi/memory_bundle/asset_installer.rb +3 -2
  71. data/lib/samagotchi/memory_bundle/builder.rb +1 -0
  72. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  73. data/lib/samagotchi/note_move.rb +3 -1
  74. data/lib/samagotchi/page_command.rb +25 -13
  75. data/lib/samagotchi/pages/builder.rb +7 -8
  76. data/lib/samagotchi/pages/bundled.rb +83 -0
  77. data/lib/samagotchi/pages/launch.rb +22 -4
  78. data/lib/samagotchi/pages/runner.rb +7 -2
  79. data/lib/samagotchi/pages/runtime.rb +83 -0
  80. data/lib/samagotchi/pages/store.rb +29 -7
  81. data/lib/samagotchi/pages.rb +47 -3
  82. data/lib/samagotchi/peer_command.rb +192 -0
  83. data/lib/samagotchi/peer_continue.rb +105 -0
  84. data/lib/samagotchi/peer_exchanges.rb +3 -3
  85. data/lib/samagotchi/peer_mailbox.rb +360 -0
  86. data/lib/samagotchi/peer_note.rb +208 -0
  87. data/lib/samagotchi/peer_receipts.rb +247 -0
  88. data/lib/samagotchi/peer_registry.rb +44 -0
  89. data/lib/samagotchi/peer_roster.rb +79 -0
  90. data/lib/samagotchi/peer_say.rb +168 -0
  91. data/lib/samagotchi/plugin/api.rb +29 -21
  92. data/lib/samagotchi/plugin/context.rb +7 -0
  93. data/lib/samagotchi/plugin/loader.rb +3 -3
  94. data/lib/samagotchi/plugin/peer.rb +175 -64
  95. data/lib/samagotchi/plugin/peers.rb +70 -0
  96. data/lib/samagotchi/run_options.rb +3 -2
  97. data/lib/samagotchi/schedule_command.rb +88 -39
  98. data/lib/samagotchi/schedule_display.rb +101 -0
  99. data/lib/samagotchi/schedules/busy_part.rb +146 -0
  100. data/lib/samagotchi/schedules/edit_part.rb +120 -0
  101. data/lib/samagotchi/schedules/history_part.rb +51 -0
  102. data/lib/samagotchi/schedules/listing_part.rb +52 -0
  103. data/lib/samagotchi/schedules/notices_part.rb +116 -0
  104. data/lib/samagotchi/schedules/protection_part.rb +103 -0
  105. data/lib/samagotchi/schedules/recurrence.rb +103 -0
  106. data/lib/samagotchi/schedules.rb +134 -330
  107. data/lib/samagotchi/session_access/contract.rb +18 -1
  108. data/lib/samagotchi/session_access/local.rb +140 -14
  109. data/lib/samagotchi/session_access/remote.rb +6 -3
  110. data/lib/samagotchi/session_access/remote_peers.rb +75 -0
  111. data/lib/samagotchi/session_chain/delete.rb +7 -5
  112. data/lib/samagotchi/session_continue.rb +12 -0
  113. data/lib/samagotchi/session_inbox_delivery.rb +5 -2
  114. data/lib/samagotchi/session_lifecycle/allowed.rb +2 -1
  115. data/lib/samagotchi/session_lifecycle.rb +3 -2
  116. data/lib/samagotchi/session_manager/delivery.rb +5 -3
  117. data/lib/samagotchi/session_manager/removal.rb +18 -9
  118. data/lib/samagotchi/session_manager/spawn.rb +2 -1
  119. data/lib/samagotchi/session_manager.rb +1 -0
  120. data/lib/samagotchi/session_protection.rb +99 -0
  121. data/lib/samagotchi/session_retention.rb +21 -6
  122. data/lib/samagotchi/session_stores.rb +17 -0
  123. data/lib/samagotchi/sessions_command.rb +4 -0
  124. data/lib/samagotchi/steer.rb +1 -1
  125. data/lib/samagotchi/system_prompt.rb +1 -1
  126. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  127. data/lib/samagotchi/terminal_ui/formatting.rb +4 -1
  128. data/lib/samagotchi/testing/boundary.rb +17 -13
  129. data/lib/samagotchi/testing/bundle.rb +40 -5
  130. data/lib/samagotchi/testing/install.rb +4 -4
  131. data/lib/samagotchi/testing/recording_api.rb +2 -1
  132. data/lib/samagotchi/tools/cancel_schedule.rb +5 -2
  133. data/lib/samagotchi/tools/context_read.rb +0 -14
  134. data/lib/samagotchi/tools/list_schedules.rb +8 -3
  135. data/lib/samagotchi/turn_outcome.rb +41 -0
  136. data/lib/samagotchi/version.rb +1 -1
  137. data/lib/samagotchi/web/app.rb +2 -13
  138. data/lib/samagotchi/web/message_display.rb +4 -2
  139. data/lib/samagotchi/web/page_routes.rb +13 -8
  140. data/lib/samagotchi/web/peer_routes.rb +133 -0
  141. data/lib/samagotchi/web/public/app.js +23 -29
  142. data/lib/samagotchi/web/public/bubbles.js +2 -2
  143. data/lib/samagotchi/web/public/cards_place.js +20 -1
  144. data/lib/samagotchi/web/public/context_chips.js +45 -46
  145. data/lib/samagotchi/web/public/history_reveal.js +4 -1
  146. data/lib/samagotchi/web/public/history_shape.js +3 -2
  147. data/lib/samagotchi/web/public/index.html +24 -2
  148. data/lib/samagotchi/web/public/notify.js +1 -1
  149. data/lib/samagotchi/web/public/owner_claim.js +7 -5
  150. data/lib/samagotchi/web/public/page_links.js +1 -1
  151. data/lib/samagotchi/web/public/page_view.js +10 -6
  152. data/lib/samagotchi/web/public/pages.css +9 -2
  153. data/lib/samagotchi/web/public/pages_group.js +21 -19
  154. data/lib/samagotchi/web/public/pages_list.js +73 -0
  155. data/lib/samagotchi/web/public/pages_model.js +54 -0
  156. data/lib/samagotchi/web/public/pages_wiring.js +66 -0
  157. data/lib/samagotchi/web/public/peer_chip.js +60 -74
  158. data/lib/samagotchi/web/public/peer_data.js +13 -11
  159. data/lib/samagotchi/web/public/peer_links.js +12 -7
  160. data/lib/samagotchi/web/public/peer_mailbox_api.js +20 -0
  161. data/lib/samagotchi/web/public/peer_note.js +7 -3
  162. data/lib/samagotchi/web/public/peer_text.js +4 -4
  163. data/lib/samagotchi/web/public/quiet_notes.js +199 -0
  164. data/lib/samagotchi/web/public/revise_stack.js +4 -3
  165. data/lib/samagotchi/web/public/session_view.js +2 -2
  166. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  167. data/lib/samagotchi/web/public/turn_block.js +7 -3
  168. data/lib/samagotchi/web/public/turn_events.js +6 -0
  169. data/lib/samagotchi/web/public/views.js +77 -23
  170. data/lib/samagotchi/web/push/attention.rb +3 -2
  171. data/lib/samagotchi/web/push/notifier.rb +4 -3
  172. data/lib/samagotchi/web/server.rb +3 -1
  173. data/lib/samagotchi/web/session_access_routes.rb +3 -20
  174. data/lib/samagotchi/web/session_hub.rb +64 -19
  175. data/lib/samagotchi/worker/leave.rb +3 -0
  176. data/lib/samagotchi/worker/mail.rb +73 -0
  177. data/lib/samagotchi/worker/startup.rb +3 -0
  178. data/lib/samagotchi/worker/wake_turns.rb +20 -5
  179. data/lib/samagotchi/worker.rb +12 -6
  180. data/lib/samagotchi/worker_inbound/mail.rb +214 -0
  181. data/lib/samagotchi/worker_inbound.rb +43 -46
  182. data/lib/samagotchi/worker_wakes.rb +26 -21
  183. metadata +35 -2
  184. data/lib/samagotchi/peer_sources.rb +0 -58
@@ -96,34 +96,29 @@ module Samagotchi
96
96
  # doesn't hide a wake asked since the session's last one.
97
97
  # +fetched_at+ is the last success, +checked_at+ the last try (the
98
98
  # poller's clock: a failing source isn't run again every tick).
99
- # +re+ comes with the revision too: the send a peer's answer names
100
- # (Plugin::Peer.send_id; nil for none, an older snapshot's or skill's).
101
99
  Snapshot = Data.define(:text, :summary, :revision, :serial, :fetched_at, :checked_at, :wake, :wake_serial, :hint,
102
- :error, :error_since, :re) do
103
- def initialize(text:, summary:, revision:, serial:, fetched_at:, checked_at:, wake:, wake_serial:, hint:, error:,
104
- error_since:, re: nil) = super
105
-
100
+ :error, :error_since) do
106
101
  def self.empty
107
102
  new(text: nil, summary: nil, revision: nil, serial: 0, fetched_at: nil, checked_at: nil, wake: false,
108
- wake_serial: nil, hint: nil, error: nil, error_since: nil, re: nil)
103
+ wake_serial: nil, hint: nil, error: nil, error_since: nil)
109
104
  end
110
105
 
111
106
  def to_h
112
107
  { "text" => text, "summary" => summary, "revision" => revision, "serial" => serial,
113
108
  "fetched_at" => fetched_at, "checked_at" => checked_at, "wake" => (wake ? true : nil),
114
109
  "wake_serial" => wake_serial, "hint" => hint,
115
- "error" => error, "error_since" => error_since, "re" => re }.compact
110
+ "error" => error, "error_since" => error_since }.compact
116
111
  end
117
112
 
118
113
  # A snapshot 0.32.0 wrote has no wake_serial: its wake is the latest
119
- # revision's.
114
+ # revision's. A peer's answer an older chi pushed had a "re": ignored.
120
115
  def self.from_h(data)
121
116
  serial = data["serial"].to_i
122
117
  wake = data["wake"] == true
123
118
  new(text: data["text"], summary: data["summary"], revision: data["revision"], serial: serial,
124
119
  fetched_at: data["fetched_at"], checked_at: data["checked_at"] || data["fetched_at"], wake: wake,
125
120
  wake_serial: data["wake_serial"]&.to_i || (serial if wake), hint: data["hint"], error: data["error"],
126
- error_since: data["error_since"], re: ContextSources.send_ref(data["re"]))
121
+ error_since: data["error_since"])
127
122
  end
128
123
 
129
124
  def text? = !text.nil?
@@ -157,10 +152,7 @@ module Samagotchi
157
152
  end
158
153
 
159
154
  # What a command printed or a push sent (the contract, ContextSources.parse_output).
160
- # +re+ (optional: a command, an older caller) is the send a peer's answer names.
161
- Fetched = Data.define(:text, :summary, :wake, :hint, :re) do
162
- def initialize(text:, summary:, wake:, hint:, re: nil) = super
163
- end
155
+ Fetched = Data.define(:text, :summary, :wake, :hint)
164
156
 
165
157
  # A source a plugin proposed for a session, not attached
166
158
  # (ctx.context.propose): its spec (+url+, through an installed bundle's
@@ -285,7 +277,7 @@ module Samagotchi
285
277
  Snapshot.new(text: fetched.text, revision: revision, serial: previous.serial + 1, fetched_at: stamp,
286
278
  checked_at: stamp, summary: fetched.summary || ContextSources.plain_summary(previous.text, fetched.text),
287
279
  wake: fetched.wake, wake_serial: fetched.wake ? previous.serial + 1 : previous.wake_serial,
288
- hint: fetched.hint || previous.hint, error: nil, error_since: nil, re: fetched.re)
280
+ hint: fetched.hint || previous.hint, error: nil, error_since: nil)
289
281
  end
290
282
  write_snapshot(name, written)
291
283
  end
@@ -423,33 +415,18 @@ module Samagotchi
423
415
  # (its movable: false).
424
416
  Stayed = Data.define(:name, :why) do
425
417
  def label = why == :pushed ? "pushed" : "not movable"
426
-
427
- # The peer whose pairing this is ("Claude"), for a pushed
428
- # <peer>-inbox or <peer>-outbox (the peer bundles' names: the move
429
- # runs where no plugin is loaded, so the name is all there is; it
430
- # only words the note, PeerSources decides what a peer is); nil for
431
- # any other.
432
- def peer
433
- leg = why == :pushed && ContextSources.peer_leg(name)
434
- leg ? ContextSources.peer_label(leg.first) : nil
435
- end
436
-
437
- def inbox? = name.end_with?("-inbox")
438
418
  end
439
419
  # A source a continue left with the previous link (+from+), as the new
440
420
  # link's left.json keeps it: its +name+ and +hint+, the snapshot's (a
441
- # pushed hint: a peer's re-pair pushes its new inbox there) else the
442
- # source's. ctx.context.left_behind reads it (Plugin::Peer asks the peer
443
- # to pair again at that inbox).
421
+ # pushed hint) else the source's. ctx.context.left_behind reads it.
444
422
  Left = Data.define(:name, :hint, :from) do
445
423
  def to_h = { "name" => name, "hint" => hint, "from" => from }.compact
446
424
 
447
425
  def self.from_h(data) = new(name: data["name"].to_s, hint: data["hint"]&.to_s, from: data["from"]&.to_s)
448
426
  end
449
427
 
450
- # A peer pairing's source name, by name only (ContextSources.peer_leg).
451
- PEER_NAME = /\A([a-z][a-z0-9]*)-(inbox|outbox)\z/
452
- # A push's re (the send a peer's answer names).
428
+ # A send's id (Plugin::Peer.send_id), as a peer's message names it
429
+ # (PeerMailbox: its re).
453
430
  RE_RE = /\A[a-z0-9-]{1,32}\z/
454
431
 
455
432
  # What ContextSources.move did: the names it took to the new session
@@ -471,23 +448,8 @@ module Samagotchi
471
448
  lines.join(" ")
472
449
  end
473
450
 
474
- # Each stayed source with why; a peer's pairing as one group, saying
475
- # what chi does about it (Plugin::Peer posts the moved message to an
476
- # inbox left behind; an outbox alone hears of it on its next push's
477
- # refusal), never whether it worked.
478
- def left_words
479
- stayed.group_by { |s| s.peer || s }.values.map do |group|
480
- peer = group.first.peer
481
- next "#{group.first.name} (#{group.first.label})" unless peer
482
-
483
- how = if group.any?(&:inbox?)
484
- "#{peer}'s pairing: chi asks #{peer} to pair again with this session"
485
- else
486
- "#{peer} pairs again when it next answers"
487
- end
488
- "#{group.map(&:name).join(", ")} (#{how})"
489
- end
490
- end
451
+ # Each stayed source with why.
452
+ def left_words = stayed.map { |stayed| "#{stayed.name} (#{stayed.label})" }
491
453
 
492
454
  # A UI's few words (chi send --new --continues); nil for nothing.
493
455
  def words
@@ -722,32 +684,18 @@ module Samagotchi
722
684
 
723
685
  def revision_of(text) = Digest::SHA256.hexdigest(text.to_s)
724
686
 
725
- # The peer and the leg of a <peer>-inbox / <peer>-outbox name
726
- # (["claude", "outbox"]); nil for any other. By name only, for where no
727
- # plugin is loaded (a move, chi web): it words and labels, PeerSources
728
- # in the worker decides what is a peer's (and what may wake chi).
729
- def peer_leg(name)
730
- match = PEER_NAME.match(name.to_s)
731
- match && [match[1], match[2]]
732
- end
733
-
734
- # The peer's name as chi words it ("Claude" for claude).
735
- def peer_label(peer) = peer.to_s.capitalize
736
-
737
687
  # The contract: stdout that parses as a JSON object with a string "text"
738
- # is {text, summary, wake, hint, re}; anything else is all text. Unknown
739
- # keys are ignored; summary and hint become one line, cut; re (a peer's
740
- # answer naming its send) is kept only when it is RE_RE.
688
+ # is {text, summary, wake, hint}; anything else is all text. Unknown
689
+ # keys are ignored (an older peer skill's re among them); summary and
690
+ # hint become one line, cut.
741
691
  # @return [Fetched]
742
692
  # @raise [Invalid] nothing to keep (empty, or over TEXT_MAX_BYTES)
743
693
  def parse_output(raw)
744
694
  raw = raw.to_s.dup.force_encoding(Encoding::UTF_8).scrub
745
695
  data = json_object(raw)
746
696
  fetched = if data.is_a?(Hash) && data["text"].is_a?(String)
747
- Log.debug(:context, "invalid_peer_ref") if !data["re"].nil? && !send_ref(data["re"])
748
697
  Fetched.new(text: data["text"].scrub, summary: one_line(data["summary"], SUMMARY_MAX_CHARS),
749
- wake: data["wake"] == true, hint: one_line(data["hint"], LINE_MAX_CHARS),
750
- re: send_ref(data["re"]))
698
+ wake: data["wake"] == true, hint: one_line(data["hint"], LINE_MAX_CHARS))
751
699
  else
752
700
  Fetched.new(text: raw, summary: nil, wake: false, hint: nil)
753
701
  end
@@ -759,7 +707,7 @@ module Samagotchi
759
707
  fetched
760
708
  end
761
709
 
762
- # A push's re: a String of RE_RE, else nil.
710
+ # A send ref (a peer message's re): a String of RE_RE, else nil.
763
711
  def send_ref(value) = value.is_a?(String) && value.match?(RE_RE) ? value : nil
764
712
 
765
713
  def json_object(raw)
@@ -49,7 +49,8 @@ module Samagotchi
49
49
  announce({ type: :context_added, session_id: session.id, note_id: note[:note_id], source: note[:source],
50
50
  label: ContextNote.label_of(message), from_session: note[:from_session],
51
51
  from_cwd: note[:from_cwd], text: note[:text], context_source: note[:context_source],
52
- created_at: note[:created_at], objectives: entry, peer: note[:peer] }.compact)
52
+ created_at: note[:created_at], objectives: entry, peer: note[:peer],
53
+ **wake_marks(message) }.compact)
53
54
  announce_objectives(session) if entry
54
55
  @objectives_stage.note(session, note, recorder: system_one_recorder, state_dir: session_state_dir)
55
56
  message
@@ -127,6 +128,16 @@ module Samagotchi
127
128
  def clone_messages(messages)
128
129
  Array(messages).map(&:dup)
129
130
  end
131
+
132
+ private
133
+
134
+ # A wake note's opening marks for its :context_added (a web page draws
135
+ # it as the turn's opening live, as a reload does); a plain note's none.
136
+ def wake_marks(message)
137
+ return {} unless message[:turn_start]
138
+
139
+ { turn_start: true, turn_id: message[:turn_id] }
140
+ end
130
141
  end
131
142
  end
132
143
  end
@@ -64,7 +64,7 @@ module Samagotchi
64
64
  },
65
65
  toolkits: @toolkit_binding.plugin_kits,
66
66
  tool_index: @tool_index,
67
- peer_sources: @peer_sources,
67
+ peer_registry: @peer_registry,
68
68
  prompt_sections: @prompt_sections,
69
69
  prompt_changed: -> { prompt_changed! },
70
70
  judgments: @judgments,
@@ -33,7 +33,7 @@ require_relative "tools/builtins"
33
33
  require_relative "tools/task_runtime"
34
34
  require_relative "tools/tool_index"
35
35
  require_relative "tools/tool_surface"
36
- require_relative "peer_sources"
36
+ require_relative "peer_registry"
37
37
  require_relative "session_commands"
38
38
  require_relative "plugin/loader"
39
39
  require_relative "plugin/card"
@@ -405,9 +405,9 @@ module Samagotchi
405
405
  # The tools plugins load (ctx.load_tools), staged until a turn's
406
406
  # messages are built (#append_tool_loads).
407
407
  @tool_loads = ToolLoads.new
408
- # The context sources the peer bundles declare as a peer agent's
409
- # answers (chi.peer_source); the worker's ContextAbsorber asks it.
410
- @peer_sources = PeerSources.new
408
+ # The peers the loaded bundles declare (chi.peer): the worker's mail
409
+ # path (WorkerInbound#absorb_mail) takes their messages.
410
+ @peer_registry = PeerRegistry.new
411
411
  # The system-prompt text plugins add (chi.prompt_section), run when
412
412
  # the prompt is built (#build_system_prompt's sections:).
413
413
  @prompt_sections = Plugin::PromptSections.new
@@ -672,8 +672,8 @@ module Samagotchi
672
672
  # built-ins, and the ones bundle plugins add
673
673
  attr_reader :command_registry
674
674
 
675
- # @return [PeerSources] the sources the peer bundles declared
676
- attr_reader :peer_sources
675
+ # @return [PeerRegistry] the peers the loaded bundles declared (chi.peer)
676
+ attr_reader :peer_registry
677
677
 
678
678
  # ── Plugin init tasks (chi.init) ──────────────────────────────────────
679
679
 
@@ -1212,6 +1212,7 @@ module Samagotchi
1212
1212
  unless turn.continue
1213
1213
  user_message = { role: "user", content: turn.prompt, turn_id: turn.id, **author_fields(turn.origin.author),
1214
1214
  **participant_mode_fields(turn.context), MessageTime::KEY => turn.at }
1215
+ user_message[:client_id] = turn.origin.client_id if turn.origin.client_id
1215
1216
  user_message[:verify] = turn.verify.to_h if turn.verify
1216
1217
  user_message[:images] = image_refs unless image_refs.empty?
1217
1218
  # Only an opener from a sender the model reads a header for
@@ -34,9 +34,6 @@ module Samagotchi
34
34
  def reasoning_history = engine.reasoning_history_override
35
35
  # The kits a delegate may start its child on (Engine#toolkit_kits).
36
36
  def toolkit_names = engine.toolkit_kits.keys
37
- # The peer's name when +name+ is a source a peer bundle declared
38
- # (PeerSources), for context_read's header.
39
- def peer_label(name) = engine.peer_sources&.label_for(name)
40
37
 
41
38
  # The session's objectives now (the objectives tool), nil outside one.
42
39
  def objectives
@@ -269,6 +269,7 @@ module Samagotchi
269
269
  @protected ||= begin
270
270
  require_relative "installed_bundles"
271
271
  require_relative "context_sources"
272
+ require_relative "peer_mailbox"
272
273
  require_relative "chi_home"
273
274
  require_relative "chi_shim"
274
275
  require_relative "paths"
@@ -278,6 +279,7 @@ module Samagotchi
278
279
  config_path: Samagotchi::ConfigFile.global_path,
279
280
  hooks_dir: Hooks::Loader.hooks_dir,
280
281
  context_dir: ContextSources.root,
282
+ mailbox_dir: PeerMailbox.root,
281
283
  runs_dir: File.join(File.dirname(@approvals.path, 2), "system_one"),
282
284
  home_path: ChiHome.path,
283
285
  shim_path: ChiShim.path,
@@ -13,7 +13,7 @@ module Samagotchi
13
13
  # (read each call). Each surface keeps its set:
14
14
  # .protected the config dir, the hooks dir, the approval store's
15
15
  # dir, the installed bundles' dir, attached context,
16
- # System 1's saved runs: an ask only the user may answer
16
+ # the peer mailbox, System 1's saved runs: an ask only the user may answer
17
17
  # (ParentApprovals.chi_files?)
18
18
  # .touches .protected and the session repo's git hooks dir: a
19
19
  # rule's touches: chi_dirs (Targets#touches_chi?)
@@ -28,13 +28,14 @@ module Samagotchi
28
28
  module_function
29
29
 
30
30
  # chi's config dir, the hooks dir, the approval store's dir, the
31
- # installed bundles' dir, attached context and System 1's saved runs
31
+ # installed bundles' dir, attached context, the peer mailbox (a message
32
+ # there speaks as a peer) and System 1's saved runs
32
33
  # (labels there may train a model: no agent writes them).
33
34
  def protected
34
35
  hooks = begin Hooks::Loader.hooks_dir rescue nil end
35
36
  bundles = begin MemoryPaths.bundles_dir rescue nil end
36
37
  [ConfigFile.config_dir, hooks, File.join(Paths.state_dir, "guardrails"), bundles, File.join(Paths.state_dir, "context"),
37
- File.join(Paths.state_dir, "system_one")]
38
+ File.join(Paths.state_dir, "mailbox"), File.join(Paths.state_dir, "system_one")]
38
39
  .compact.map { |dir| dir.to_s.chomp("/") }.reject(&:empty?).uniq
39
40
  end
40
41
 
@@ -32,11 +32,12 @@ module Samagotchi
32
32
  AGENT_MARKERS = ["CLAUDECODE", "AI_AGENT", "CODEX_THREAD_ID", PARENT_SESSION_ENV].freeze
33
33
  # Rules only the user may allow (Verdict::PROTECTED_RULES).
34
34
  PROTECTED_RULES = Verdict::PROTECTED_RULES
35
- # A shell command naming chi's config, hooks, guardrails or attached
36
- # context as text (broad: a parent may not allow what only looks like
37
- # one). samagotchi/context stops before a word character or a dot, so
38
- # chi's own lib/samagotchi/context_*.rb isn't one.
39
- CHI_TEXT = %r{\.config/samagotchi|samagotchi/config\.yml|samagotchi/hooks|samagotchi/guardrails|samagotchi/context(?![\w.])|memories/\.bundles}
35
+ # A shell command naming chi's config, hooks, guardrails, attached
36
+ # context or the peer mailbox as text (broad: a parent may not allow
37
+ # what only looks like one). samagotchi/context and samagotchi/mailbox
38
+ # stop before a word character or a dot, so chi's own
39
+ # lib/samagotchi/context_*.rb isn't one.
40
+ CHI_TEXT = %r{\.config/samagotchi|samagotchi/config\.yml|samagotchi/hooks|samagotchi/guardrails|samagotchi/context(?![\w.])|samagotchi/mailbox(?![\w.])|memories/\.bundles}
40
41
  # The guardrails bundle's ask before a memory removal: its paths are in
41
42
  # the config dir, yet a parent may answer it.
42
43
  MEMORY_REMOVE_RULE = "memory-remove"
@@ -14,8 +14,9 @@ module Samagotchi
14
14
  # deny: the approval store's dir, installed bundles (.bundles/:
15
15
  # hooks, rules, manifests), attached context (a source's
16
16
  # command runs later, outside the gate; chi context writes
17
- # it) and System 1's saved runs (a label there may train a
18
- # model); nothing legitimate writes there through a tool
17
+ # it), the peer mailbox (a message there speaks as a peer
18
+ # agent; chi peer writes it) and System 1's saved runs (a
19
+ # label there may train a model); nothing legitimate writes there through a tool
19
20
  # that says it writes.
20
21
  # ask (once / session): config.yml, home.json (the chi home: the
21
22
  # Ruby every chi launch boots), the chi shim (ChiShim: the
@@ -47,12 +48,13 @@ module Samagotchi
47
48
  # @param config_path [String] config.yml
48
49
  # @param hooks_dir [String] the plain hooks dir
49
50
  # @param context_dir [String, nil] <state dir>/context (ContextSources.root)
51
+ # @param mailbox_dir [String, nil] <state dir>/mailbox (PeerMailbox.root)
50
52
  # @param runs_dir [String, nil] <state dir>/system_one (SystemOne::Runs)
51
53
  # @param home_path [String, nil] home.json (ChiHome.path)
52
54
  # @param shim_path [String, nil] the chi shim (ChiShim.path)
53
55
  # @param plugins_dir [String, nil] <state dir>/plugins (the bundles' data, their secrets/ in it)
54
56
  def initialize(store_dir:, bundles_dir:, config_path:, hooks_dir:, context_dir: nil, runs_dir: nil, home_path: nil, shim_path: nil,
55
- plugins_dir: nil)
57
+ plugins_dir: nil, mailbox_dir: nil)
56
58
  @plugins_dir = plugins_dir
57
59
  # The same, spelled out: this state dir's own plugins/<x>/secrets.
58
60
  @secrets_text = plugins_dir && Regexp.union(SECRETS_TEXT, *([plugins_dir.to_s.chomp("/")] | PathResolve.reals(plugins_dir.to_s.chomp("/"))).map do |dir|
@@ -62,6 +64,7 @@ module Samagotchi
62
64
  ["guardrail-store", store_dir, "the approval store belongs to the user"],
63
65
  ["installed-bundles", bundles_dir, "installed bundles (hooks, rules, manifests) are changed by chi bundle install"],
64
66
  ["chi-context", context_dir, "attached context sources run commands; change them with chi context"],
67
+ ["chi-mailbox", mailbox_dir, "a message there speaks as a peer agent; chi peer writes the peer mailbox"],
65
68
  ["system-one-runs", runs_dir, "System 1's saved runs are chi's own record"]
66
69
  ]
67
70
  @ask = [
@@ -210,13 +210,22 @@ module Samagotchi
210
210
 
211
211
  case value
212
212
  when Hash, Array then nested(value, path, depth, open)
213
- when String then value.encoding == Encoding::UTF_8 && value.valid_encoding? ? value : value.dup.force_encoding(Encoding::UTF_8).scrub
213
+ when String then text(value)
214
214
  when Symbol, Integer, Float then value.to_s
215
215
  when nil then nil
216
216
  else raise Refused, "#{path || "the data"} must be text, not #{shown(value)}"
217
217
  end
218
218
  end
219
219
 
220
+ def text(value)
221
+ value = value.to_s
222
+ if [Encoding::BINARY, Encoding::US_ASCII].include?(value.encoding)
223
+ value.dup.force_encoding(Encoding::UTF_8).scrub
224
+ else
225
+ value.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
226
+ end
227
+ end
228
+
220
229
  def nested(value, path, depth, open)
221
230
  open[value] = true
222
231
  if value.is_a?(Array)
@@ -229,8 +238,7 @@ module Samagotchi
229
238
  end
230
239
 
231
240
  def key(key, path)
232
- return key if key.is_a?(String)
233
- return key.to_s if key.is_a?(Symbol) || key.is_a?(Integer)
241
+ return text(key) if key.is_a?(String) || key.is_a?(Symbol) || key.is_a?(Integer)
234
242
 
235
243
  raise Refused, "#{path || "the data"} has a key that isn't text"
236
244
  end
@@ -43,6 +43,9 @@ module Samagotchi
43
43
  # script_names the scripts/ files it lists
44
44
  # context_providers Array<ContextProviders::Provider>
45
45
  # block_renderers Array<BlockRenderers::Renderer>
46
+ # pages the page scripts (pages:, Pages::Bundled): the
47
+ # kept manifest's only, [] from the record (a
48
+ # key a later manifest gains is never mirrored)
46
49
  # session_settings, session_setting_types, settings, setting_types
47
50
  # as Manifest reads them (settings nil when
48
51
  # the manifest said nothing of them)
@@ -62,7 +65,7 @@ module Samagotchi
62
65
  # the first chi that read it), {} from the record
63
66
  # origin :kept or :record
64
67
  class Manifest < Data.define(:name, :version, :requires_chi, :trust_level, :description, :needs,
65
- :script_names, :context_providers, :block_renderers, :session_settings,
68
+ :script_names, :context_providers, :block_renderers, :pages, :session_settings,
66
69
  :session_setting_types, :settings, :setting_types, :file_descriptions,
67
70
  :plugin_required, :plugin_parts, :includes, :unknown_keys, :floor_keys, :problems,
68
71
  :origin)
@@ -135,6 +138,7 @@ module Samagotchi
135
138
  script_names: pick.call("scripts", kept.scripts.keys, mirrored.script_names),
136
139
  context_providers: pick.call("context_providers", kept.context_providers, mirrored.context_providers),
137
140
  block_renderers: pick.call("block_renderers", kept.block_renderers, mirrored.block_renderers),
141
+ pages: pick.call("pages", kept.pages, mirrored.pages),
138
142
  session_settings: session.session_settings, session_setting_types: session.session_setting_types,
139
143
  settings: settings.settings, setting_types: settings.setting_types,
140
144
  file_descriptions: pick.call("files", kept.file_descriptions, mirrored.file_descriptions),
@@ -160,6 +164,7 @@ module Samagotchi
160
164
  script_names: bundle.scripts.keys,
161
165
  context_providers: parsed(problems, "context_providers", []) { ContextProviders.parse_list(raw["context_providers"]) },
162
166
  block_renderers: parsed(problems, "block_renderers", []) { BlockRenderers.parse_list(raw["block_renderers"]) },
167
+ pages: [],
163
168
  session_settings: list(raw["session_settings"]) || [],
164
169
  session_setting_types: types(raw["session_setting_types"]),
165
170
  settings: list(raw["settings"]),
@@ -218,6 +223,8 @@ module Samagotchi
218
223
  def context_providers? = !context_providers.empty?
219
224
 
220
225
  def block_renderers? = !block_renderers.empty?
226
+
227
+ def pages? = !pages.empty?
221
228
  end
222
229
  end
223
230
  end
@@ -16,7 +16,7 @@ module Samagotchi
16
16
  # (debug dumps) are indented by four spaces and belong to the record above.
17
17
  module LogLine
18
18
  LEVELS = %w[DEBUG INFO WARN ERROR].freeze
19
- TAGS = %w[turn http worker bridge web attached idle recap hooks plugins guardrails config memory model context broadcast toolkit system_one prompt].freeze
19
+ TAGS = %w[turn http worker bridge web attached idle recap hooks plugins guardrails config memory model context peer broadcast toolkit system_one prompt].freeze
20
20
  INDENT = " "
21
21
 
22
22
  Record = Struct.new(:ts, :level, :tag, :pid, :sid, :event, :fields, :payload, keyword_init: true)
@@ -317,9 +317,10 @@ module Samagotchi
317
317
  end
318
318
  end
319
319
 
320
- # A file only a block renderer's load names: the page loads it, nothing runs it.
320
+ # A file only a block renderer's load or pages: names: a page loads
321
+ # it (the browser's, or a page runner's Ruby), nothing execs it.
321
322
  def page_only?(file)
322
- @manifest.block_renderers.any? { |renderer| renderer.load.include?(file) } &&
323
+ (@manifest.block_renderers.any? { |renderer| renderer.load.include?(file) } || @manifest.pages.include?(file)) &&
323
324
  @manifest.context_providers.none? { |provider| provider.cmd.include?(file) }
324
325
  end
325
326
 
@@ -228,6 +228,7 @@ module Samagotchi
228
228
  scripts: parts.scripts.transform_values { |src| InstalledBundles::FileDigest.sha256(src) },
229
229
  context_providers: parts.context_providers,
230
230
  block_renderers: parts.block_renderers,
231
+ pages: manifest&.pages || [],
231
232
  file_descriptions: manifest ? manifest.file_descriptions.slice(*files_map.keys) : {},
232
233
  session_settings: manifest&.session_settings || [],
233
234
  session_setting_types: manifest&.session_setting_types || {},
@@ -49,7 +49,7 @@ module Samagotchi
49
49
  plugin: plugin(bundle, provenance, dir),
50
50
  scripts: copies(bundle.scripts, provenance.scripts_dir, File.join(dir, "scripts")),
51
51
  requires_chi: manifest.requires_chi, needs: manifest.needs,
52
- context_providers: manifest.context_providers, block_renderers: manifest.block_renderers,
52
+ context_providers: manifest.context_providers, block_renderers: manifest.block_renderers, pages: manifest.pages,
53
53
  session_settings: manifest.session_settings, session_setting_types: manifest.session_setting_types,
54
54
  settings: manifest.settings, setting_types: manifest.setting_types
55
55
  )
@@ -7,6 +7,7 @@ require_relative "archive_store"
7
7
  require_relative "context_move"
8
8
  require_relative "log"
9
9
  require_relative "objectives"
10
+ require_relative "peer_continue"
10
11
  require_relative "session"
11
12
  require_relative "session_chain"
12
13
  require_relative "session_inbox"
@@ -27,7 +28,8 @@ module Samagotchi
27
28
  # The notes a continue writes into its new link itself (the chain note,
28
29
  # ChildMove's, the attached context's, the objectives' carry): a failed
29
30
  # continue deletes them with the link.
30
- CONTINUE_SOURCES = [SessionChain::NOTE_SOURCE, ContextMove::NOTE_SOURCE, Objectives::SOURCE].freeze
31
+ CONTINUE_SOURCES = [SessionChain::NOTE_SOURCE, ContextMove::NOTE_SOURCE, Objectives::SOURCE,
32
+ PeerContinue::NOTE_SOURCE].freeze
31
33
 
32
34
  module_function
33
35
 
@@ -17,16 +17,25 @@ module Samagotchi
17
17
  class PageCommand
18
18
  include CLI::Command
19
19
 
20
- USAGE = <<~TEXT
21
- Usage: chi page <run|list|rm> [options]
22
- run NAME [--format text|json] run ~/.config/samagotchi/pages/NAME.rb in a process of its own (in the
23
- pages folder, cut at #{Pages::TIMEOUT_SECONDS} s with what it started), store what it built and print a summary of
24
- each block (json: the stored page). A failed run keeps the last good result. Exit 1 when the
25
- script raised, was stopped or broke a limit, when there is no such page or it is already running.
20
+ # The help, with the folder chi page reads its scripts from as the user
21
+ # sees it (~ for the home folder). Read when printed, so a config home set
22
+ # after load (XDG_CONFIG_HOME) names its own pages folder.
23
+ def self.usage(pages_dir: Paths.tilde(Pages.scripts_dir))
24
+ <<~TEXT
25
+ Usage: chi page <run|list|rm> [options]
26
+ run NAME [--format text|json] run #{pages_dir}/NAME.rb (else an installed bundle's page NAME) in a process of its own (in the
27
+ pages folder, cut at #{Pages::TIMEOUT_SECONDS} s with what it started), store what it built and print a summary of
28
+ each block (json: the stored page). A failed run keeps the last good result. Exit 1 when the
29
+ script raised, was stopped or broke a limit, when there is no such page or it is already running.
26
30
  list [--format text|json] every page: its title, when it last ran or failed (and on which line),
27
- (never ran), and "changed" when the script changed since the result was made
28
- rm NAME remove a page: its script and its stored result
29
- TEXT
31
+ (never ran), "changed" when the script changed since the result was made, and the bundle a page
32
+ comes with (json: bundle, and script: the path of the script it runs)
33
+ rm NAME remove a page: its script and its stored result (a bundle's page stays: uninstall the bundle)
34
+ TEXT
35
+ end
36
+
37
+ # The help as chi loaded, for callers that want the text itself.
38
+ USAGE = usage
30
39
 
31
40
  SUBCOMMANDS = %w[run list rm].freeze
32
41
 
@@ -53,7 +62,7 @@ module Samagotchi
53
62
  def run
54
63
  @sub = @argv[0]
55
64
  if @sub.nil? || HELP_WORDS.include?(@sub)
56
- @stdout.puts(USAGE)
65
+ @stdout.puts(usage_text)
57
66
  return CLI::Exit::OK
58
67
  end
59
68
  return usage_error("unknown subcommand #{@sub}") unless SUBCOMMANDS.include?(@sub)
@@ -64,7 +73,7 @@ module Samagotchi
64
73
  send(:"run_#{@sub}", parsed.options, parsed.args)
65
74
  rescue Pages::BadName => e
66
75
  usage_error(e.message)
67
- rescue Pages::Missing, Pages::Busy => e
76
+ rescue Pages::Missing, Pages::Busy, Pages::FromBundle => e
68
77
  error_line("#{command_name}: #{e.message}")
69
78
  CLI::Exit::FAILED
70
79
  rescue Interrupt
@@ -96,6 +105,7 @@ module Samagotchi
96
105
 
97
106
  def command_name = @sub && SUBCOMMANDS.include?(@sub) ? "chi page #{@sub}" : "chi page"
98
107
  def usage_on_error = nil
108
+ def usage_text = self.class.usage
99
109
 
100
110
  def one_name(args)
101
111
  return usage_error("give the page's NAME") if args.empty?
@@ -179,7 +189,8 @@ module Samagotchi
179
189
  pages = Pages::Store.list
180
190
  if format == "json"
181
191
  @stdout.puts(JSON.generate(pages.map do |page|
182
- page.to_json_hash.except("blocks").merge("state" => page.state.to_s, "changed" => page.changed?)
192
+ page.to_json_hash.except("blocks").merge("state" => page.state.to_s, "changed" => page.changed?,
193
+ "bundle" => page.bundle, "script" => page.script)
183
194
  end))
184
195
  elsif pages.empty?
185
196
  @stdout.puts("no pages (a page is a script at #{Paths.tilde(Pages.scripts_dir)}/NAME.rb)")
@@ -193,7 +204,8 @@ module Samagotchi
193
204
  table = pages.map do |page|
194
205
  # A control character (a newline, a tab) in a title would break the row.
195
206
  title = page.state == :never_ran ? "(never ran)" : page.title.to_s.gsub(/[[:cntrl:]]+/, " ")
196
- [page.name, title, [status(page), ("changed" if page.changed?)].compact.join(", ")]
207
+ notes = [status(page), ("changed" if page.changed?), ("#{page.bundle} bundle" if page.bundle)]
208
+ [page.name, title, notes.compact.reject(&:empty?).join(", ")]
197
209
  end
198
210
  widths = table.transpose.map { |column| column.map(&:length).max }
199
211
  table.each do |row|
@@ -54,8 +54,7 @@ module Samagotchi
54
54
 
55
55
  # A value as text, scrubbed to valid UTF-8.
56
56
  def self.text_of(value)
57
- text = value.to_s
58
- text.encoding == Encoding::UTF_8 && text.valid_encoding? ? text : text.dup.force_encoding(Encoding::UTF_8).scrub
57
+ InlineWidgets::DataTree.text(value)
59
58
  end
60
59
 
61
60
  private
@@ -116,8 +115,8 @@ module Samagotchi
116
115
 
117
116
  def columns(columns)
118
117
  pairs = case columns
119
- when Hash then columns.map { |k, label| [k.to_s, Builder.text_of(label)] }
120
- when Array then columns.map { |k| [k.to_s, k.to_s] }
118
+ when Hash then columns.map { |k, label| [Builder.text_of(k), Builder.text_of(label)] }
119
+ when Array then columns.map { |k| [Builder.text_of(k), Builder.text_of(k)] }
121
120
  else raise Refused, "#{@where}: columns: must be a Hash of key => label or a list of keys"
122
121
  end
123
122
  raise Refused, "#{@where}: columns: is empty" if pairs.empty?
@@ -130,7 +129,7 @@ module Samagotchi
130
129
  raise Refused, "#{@where}: format: must be a Hash of column => :money or :count" unless format.is_a?(Hash)
131
130
 
132
131
  format.to_h do |k, value|
133
- k = k.to_s
132
+ k = Builder.text_of(k)
134
133
  raise Refused, "#{@where}: format names #{k.inspect}, which is no column" unless keys.include?(k)
135
134
  unless value.is_a?(Symbol) && FORMATS.include?(value)
136
135
  raise Refused, "#{@where}: column #{k.inspect} has format #{value.inspect} (use :money or :count)"
@@ -147,7 +146,7 @@ module Samagotchi
147
146
  rows.each_with_index.map do |row, index|
148
147
  raise Refused, "#{@where}: row #{index + 1} isn't a mapping" unless row.is_a?(Hash)
149
148
 
150
- row.transform_keys(&:to_s)
149
+ row.transform_keys { |key| Builder.text_of(key) }
151
150
  end
152
151
  end
153
152
 
@@ -159,7 +158,7 @@ module Samagotchi
159
158
  end
160
159
 
161
160
  Array(key).map do |k|
162
- k = k.to_s
161
+ k = Builder.text_of(k)
163
162
  raise Refused, "#{@where}: key names #{k.inspect}, which is no column" unless keys.include?(k)
164
163
 
165
164
  k
@@ -169,7 +168,7 @@ module Samagotchi
169
168
  def total(total, keys)
170
169
  raise Refused, "#{@where}: total: must be a Hash by column" unless total.is_a?(Hash)
171
170
 
172
- total = total.transform_keys(&:to_s)
171
+ total = total.transform_keys { |key| Builder.text_of(key) }
173
172
  extra = total.keys - keys
174
173
  raise Refused, "#{@where}: total names #{extra.first.inspect}, which is no column" unless extra.empty?
175
174