samagotchi 0.192.0 → 0.194.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +128 -1
  3. data/docs/architecture.md +3 -3
  4. data/docs/bundle-authoring.md +1 -1
  5. data/docs/bundles.md +82 -40
  6. data/docs/cli.md +47 -17
  7. data/docs/configuration.md +75 -8
  8. data/docs/context.md +8 -5
  9. data/docs/desktop.md +3 -0
  10. data/docs/guardrails.md +20 -5
  11. data/docs/hooks.md +1 -0
  12. data/docs/internals/bridge.md +3 -1
  13. data/docs/internals/bundles.md +2 -2
  14. data/docs/internals/engine.md +46 -3
  15. data/docs/internals/pages.md +4 -4
  16. data/docs/internals/panes.md +66 -0
  17. data/docs/internals/participants.md +5 -3
  18. data/docs/internals/peers.md +176 -27
  19. data/docs/internals/prompt-caching.md +6 -1
  20. data/docs/internals/remote-sessions.md +6 -0
  21. data/docs/internals/session-lifecycle.md +12 -4
  22. data/docs/internals/web-frontend.md +106 -22
  23. data/docs/internals/working-set.md +5 -1
  24. data/docs/peers.md +150 -27
  25. data/docs/plugins.md +48 -7
  26. data/docs/releasing.md +30 -2
  27. data/docs/scheduling.md +3 -2
  28. data/docs/sessions.md +16 -7
  29. data/docs/sub-agent.md +6 -4
  30. data/docs/system-one.md +4 -0
  31. data/docs/testing.md +38 -3
  32. data/docs/thin-clients.md +27 -11
  33. data/lib/samagotchi/bridge/card_store.rb +1 -1
  34. data/lib/samagotchi/broadcast/triage_model.rb +17 -0
  35. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  36. data/lib/samagotchi/bundles/claude-peer/plugin.rb +24 -5
  37. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +61 -24
  38. data/lib/samagotchi/bundles/claude-peer/scripts/pair +31 -8
  39. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  40. data/lib/samagotchi/bundles/codex-peer/plugin.rb +62 -6
  41. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +57 -19
  42. data/lib/samagotchi/bundles/codex-peer/scripts/pair +28 -7
  43. data/lib/samagotchi/bundles/coordinator/manifest.yml +2 -2
  44. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +31 -0
  45. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  46. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  47. data/lib/samagotchi/bundles/mcp/plugin.rb +0 -7
  48. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  49. data/lib/samagotchi/chi_invocation.rb +7 -0
  50. data/lib/samagotchi/client.rb +18 -0
  51. data/lib/samagotchi/codex_rollout.rb +93 -0
  52. data/lib/samagotchi/compat.rb +8 -1
  53. data/lib/samagotchi/config.rb +19 -6
  54. data/lib/samagotchi/continue_offer.rb +13 -1
  55. data/lib/samagotchi/delivery.rb +2 -2
  56. data/lib/samagotchi/effective_model.rb +28 -2
  57. data/lib/samagotchi/engine/cards.rb +9 -4
  58. data/lib/samagotchi/engine/hooks.rb +8 -0
  59. data/lib/samagotchi/engine/models.rb +197 -7
  60. data/lib/samagotchi/engine/plugins.rb +2 -0
  61. data/lib/samagotchi/engine/side_requests.rb +72 -13
  62. data/lib/samagotchi/engine/toolkit.rb +1 -1
  63. data/lib/samagotchi/engine/turn_helpers.rb +1 -1
  64. data/lib/samagotchi/engine.rb +11 -8
  65. data/lib/samagotchi/engine_snapshots.rb +16 -3
  66. data/lib/samagotchi/events.rb +1 -0
  67. data/lib/samagotchi/guardrails/pair_boundary.rb +49 -18
  68. data/lib/samagotchi/hooks.rb +3 -1
  69. data/lib/samagotchi/host_registry.rb +146 -16
  70. data/lib/samagotchi/idle_client.rb +13 -2
  71. data/lib/samagotchi/idle_recap.rb +33 -3
  72. data/lib/samagotchi/idle_target.rb +27 -7
  73. data/lib/samagotchi/jsonl_store.rb +13 -2
  74. data/lib/samagotchi/llm/adapter_common.rb +4 -2
  75. data/lib/samagotchi/llm/anthropic_messages.rb +14 -2
  76. data/lib/samagotchi/llm/errors.rb +35 -4
  77. data/lib/samagotchi/llm/model_listing.rb +19 -0
  78. data/lib/samagotchi/llm/openai_chat.rb +8 -2
  79. data/lib/samagotchi/llm/prompt_cache.rb +5 -0
  80. data/lib/samagotchi/model_binding.rb +46 -4
  81. data/lib/samagotchi/model_catalog.rb +68 -8
  82. data/lib/samagotchi/model_profile.rb +35 -0
  83. data/lib/samagotchi/models_command.rb +8 -4
  84. data/lib/samagotchi/pages/launch.rb +1 -1
  85. data/lib/samagotchi/panes/kitty.rb +122 -0
  86. data/lib/samagotchi/panes.rb +185 -0
  87. data/lib/samagotchi/peer_announce.rb +245 -0
  88. data/lib/samagotchi/peer_cold.rb +92 -0
  89. data/lib/samagotchi/peer_command.rb +121 -20
  90. data/lib/samagotchi/peer_continue.rb +42 -16
  91. data/lib/samagotchi/peer_exchanges.rb +7 -0
  92. data/lib/samagotchi/peer_mailbox.rb +50 -10
  93. data/lib/samagotchi/peer_pair_here.rb +149 -0
  94. data/lib/samagotchi/peer_presence.rb +434 -0
  95. data/lib/samagotchi/peer_receipts.rb +33 -6
  96. data/lib/samagotchi/peer_say.rb +46 -21
  97. data/lib/samagotchi/peer_wait_expiry.rb +47 -0
  98. data/lib/samagotchi/plugin/api.rb +13 -1
  99. data/lib/samagotchi/plugin/card.rb +68 -11
  100. data/lib/samagotchi/plugin/context.rb +33 -2
  101. data/lib/samagotchi/plugin/panes.rb +54 -0
  102. data/lib/samagotchi/plugin/peer.rb +170 -63
  103. data/lib/samagotchi/plugin/peer_pairing.rb +290 -0
  104. data/lib/samagotchi/plugin/peer_start.rb +301 -0
  105. data/lib/samagotchi/plugin/peer_start_hook.rb +207 -0
  106. data/lib/samagotchi/plugin/peers.rb +89 -9
  107. data/lib/samagotchi/recap_setup.rb +40 -3
  108. data/lib/samagotchi/self_report.rb +25 -6
  109. data/lib/samagotchi/send_command.rb +6 -6
  110. data/lib/samagotchi/served_lookup.rb +225 -0
  111. data/lib/samagotchi/served_ref.rb +41 -0
  112. data/lib/samagotchi/session_access/contract.rb +6 -0
  113. data/lib/samagotchi/session_access/local.rb +149 -40
  114. data/lib/samagotchi/session_access/remote.rb +4 -4
  115. data/lib/samagotchi/session_access/remote_peers.rb +8 -5
  116. data/lib/samagotchi/session_chain/links.rb +8 -3
  117. data/lib/samagotchi/session_commands.rb +40 -8
  118. data/lib/samagotchi/session_continue.rb +11 -6
  119. data/lib/samagotchi/session_lifecycle/allowed.rb +4 -2
  120. data/lib/samagotchi/session_manager/delivery.rb +5 -0
  121. data/lib/samagotchi/session_manager/lifecycle.rb +58 -7
  122. data/lib/samagotchi/session_manager/removal.rb +3 -0
  123. data/lib/samagotchi/session_manager/spawn.rb +6 -1
  124. data/lib/samagotchi/session_model_settings.rb +7 -3
  125. data/lib/samagotchi/session_stores.rb +25 -11
  126. data/lib/samagotchi/sessions_command.rb +16 -3
  127. data/lib/samagotchi/system_one/http_backend.rb +111 -10
  128. data/lib/samagotchi/system_one/runs.rb +5 -2
  129. data/lib/samagotchi/system_prompt.rb +11 -4
  130. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -1
  131. data/lib/samagotchi/terminal_ui/formatting.rb +26 -12
  132. data/lib/samagotchi/terminal_ui/status_row.rb +20 -3
  133. data/lib/samagotchi/terminal_ui.rb +1 -1
  134. data/lib/samagotchi/testing/boundary.rb +0 -1
  135. data/lib/samagotchi/testing/bundle.rb +6 -2
  136. data/lib/samagotchi/testing/host.rb +1 -0
  137. data/lib/samagotchi/testing/recorder.rb +3 -0
  138. data/lib/samagotchi/turn_endings.rb +6 -2
  139. data/lib/samagotchi/user_typed.rb +29 -0
  140. data/lib/samagotchi/version.rb +1 -1
  141. data/lib/samagotchi/web/app.rb +8 -20
  142. data/lib/samagotchi/web/participant_review.rb +1 -1
  143. data/lib/samagotchi/web/participant_view.rb +1 -1
  144. data/lib/samagotchi/web/peer_routes.rb +40 -15
  145. data/lib/samagotchi/web/public/agent_rows.js +206 -0
  146. data/lib/samagotchi/web/public/agent_runs.js +595 -0
  147. data/lib/samagotchi/web/public/answer_fold.js +41 -44
  148. data/lib/samagotchi/web/public/app.js +4 -4
  149. data/lib/samagotchi/web/public/block_fix.js +1 -1
  150. data/lib/samagotchi/web/public/card.js +26 -10
  151. data/lib/samagotchi/web/public/cards_place.js +6 -4
  152. data/lib/samagotchi/web/public/context_chips.js +24 -2
  153. data/lib/samagotchi/web/public/copy.js +8 -2
  154. data/lib/samagotchi/web/public/data.js +2 -1
  155. data/lib/samagotchi/web/public/format.js +9 -1
  156. data/lib/samagotchi/web/public/history_reveal.js +5 -2
  157. data/lib/samagotchi/web/public/index.html +56 -2
  158. data/lib/samagotchi/web/public/info_bar_model.js +1 -1
  159. data/lib/samagotchi/web/public/model_pick.js +18 -5
  160. data/lib/samagotchi/web/public/model_picker.js +1 -1
  161. data/lib/samagotchi/web/public/page_view.js +1 -1
  162. data/lib/samagotchi/web/public/pages.css +1 -7
  163. data/lib/samagotchi/web/public/peer_chip.js +15 -5
  164. data/lib/samagotchi/web/public/peer_data.js +4 -2
  165. data/lib/samagotchi/web/public/peer_mailbox_api.js +2 -1
  166. data/lib/samagotchi/web/public/peer_note.js +4 -2
  167. data/lib/samagotchi/web/public/peer_row.js +37 -0
  168. data/lib/samagotchi/web/public/peer_wait.js +36 -0
  169. data/lib/samagotchi/web/public/quiet_notes.js +12 -1
  170. data/lib/samagotchi/web/public/revise_stack.js +5 -2
  171. data/lib/samagotchi/web/public/send_turn.js +11 -3
  172. data/lib/samagotchi/web/public/served_ref.js +9 -0
  173. data/lib/samagotchi/web/public/session_fields.js +1 -0
  174. data/lib/samagotchi/web/public/session_state.js +4 -0
  175. data/lib/samagotchi/web/public/stage_missing.js +23 -6
  176. data/lib/samagotchi/web/public/stream_handlers.js +16 -0
  177. data/lib/samagotchi/web/public/turn_block.js +4 -0
  178. data/lib/samagotchi/web/public/version_notices.js +7 -1
  179. data/lib/samagotchi/web/session_control.rb +19 -10
  180. data/lib/samagotchi/web/session_show.rb +20 -0
  181. data/lib/samagotchi/web/update_ops.rb +2 -2
  182. data/lib/samagotchi/worker/command_queue.rb +3 -0
  183. data/lib/samagotchi/worker/mail.rb +24 -1
  184. data/lib/samagotchi/worker.rb +8 -5
  185. data/lib/samagotchi/worker_inbound/mail.rb +34 -6
  186. data/lib/samagotchi/worker_inbound.rb +11 -3
  187. data/lib/samagotchi/worker_link.rb +13 -1
  188. data/lib/samagotchi/worker_wakes.rb +33 -5
  189. metadata +22 -2
  190. data/lib/samagotchi/web/public/pages_group.js +0 -67
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ # Whether the plugin command running on this thread was typed by a person
5
+ # at a UI: the web (a card's button keeps its tab's id) or an attached
6
+ # TUI, never `chi send` (the model's own shell can run it), a tool call,
7
+ # a delegate or a participant (ClientId interactive: false). What acts as
8
+ # the user on their screen, or writes another agent's settings, runs only
9
+ # then (claude-peer's Show and Add the start hook). Set by
10
+ # SessionCommands#run_bundle_command from CommandQueue's user_ui?, read
11
+ # by ctx.user_typed?. Like CacheConfirm.asking: per thread, nested, and a
12
+ # thread the command starts doesn't inherit it.
13
+ module UserTyped
14
+ KEY = :samagotchi_user_typed
15
+
16
+ module_function
17
+
18
+ # Run +block+ with +flag+ as this thread's answer.
19
+ def as(flag)
20
+ previous = Thread.current[KEY]
21
+ Thread.current[KEY] = flag ? true : false
22
+ yield
23
+ ensure
24
+ Thread.current[KEY] = previous
25
+ end
26
+
27
+ def typed? = Thread.current[KEY] == true
28
+ end
29
+ end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.192.0"
4
+ VERSION = "0.194.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -1160,33 +1160,21 @@ module Samagotchi
1160
1160
 
1161
1161
  def handle_models(_req)
1162
1162
  default = Degrade.call(:web, "default_model_unresolved") { ModelProfile.required_model_name }
1163
- models = []
1164
1163
  warnings = []
1165
1164
  begin
1166
1165
  registry = host_registry
1167
1166
  results = await_model_lists(registry)
1168
- if results.nil?
1169
- warnings << "the hosts are still listing their models"
1170
- else
1171
- default_host = registry.default_entry&.name
1172
- listing = ModelCatalog.listing(results, registry: registry)
1173
- warnings.concat(listing.warnings)
1174
- # the web's own spelling, kept as it was: bare on the default host
1175
- listing.rows.each do |row|
1176
- model = { name: row.host == default_host ? row.id : "#{row.host}:#{row.id}", host: row.host, id: row.id }
1177
- model[:configured] = true if row.configured
1178
- model[:unavailable] = true if row.unavailable
1179
- models << model
1180
- end
1181
- end
1167
+ warnings << "the hosts are still listing their models" if results.nil?
1168
+ listing = results && ModelCatalog.listing(results, registry: registry)
1169
+ warnings.concat(listing.warnings) if listing
1170
+ # The web's spelling, the served rows, the default (ModelCatalog.web_models).
1171
+ models, default = ModelCatalog.web_models(listing, registry: registry, default: default)
1182
1172
  rescue StandardError => e
1183
1173
  warnings << e.message
1184
1174
  end
1185
- if default && models.none? { |m| m[:name].casecmp?(default) }
1186
- models.unshift({ name: default, host: nil, id: default })
1187
- end
1175
+ models ||= default ? [{ name: default, host: nil, id: default }] : []
1188
1176
  add_sampling(models, registry)
1189
- payload = { default: default, models: models }
1177
+ payload = { default: default, models: models, default_host: registry&.default_entry&.name }
1190
1178
  payload[:warning] = warnings.join("; ") unless warnings.empty?
1191
1179
  toolkits = toolkits_listing(registry)
1192
1180
  payload[:toolkits] = toolkits if toolkits
@@ -1286,7 +1274,7 @@ module Samagotchi
1286
1274
  return {} unless served.is_a?(String) && !served.empty? && !model.empty?
1287
1275
 
1288
1276
  registry = host_registry
1289
- asked = registry.bare_name(model)
1277
+ asked = registry.sent_model_id(model)
1290
1278
  return {} unless persisted["served_model_for"] == asked
1291
1279
 
1292
1280
  { served_model: served, served_model_for: asked, served_expected_by: saved_served_expected_by(registry, model, served) }
@@ -133,7 +133,7 @@ module Samagotchi
133
133
  ref = (state.is_a?(Hash) && state["model_name"]) || session.model_name
134
134
  return nil if ref.to_s.empty?
135
135
 
136
- name = host_registry.bare_name(ref.to_s)
136
+ name = host_registry.sent_model_id(ref.to_s)
137
137
  name.to_s.empty? ? nil : Redact.text(name.to_s, viewer)
138
138
  rescue StandardError
139
139
  nil
@@ -86,7 +86,7 @@ module Samagotchi
86
86
  after_generation after_tool_call after_turn answer_display before_generation before_tool_call before_turn block_fix
87
87
  card command_output command_queued command_ran context_added empty_answer_retry
88
88
  generation_cancelled generation_progress generation_started guardrail_warning hook_notice
89
- llm_context_edited merged_input objectives_updated part_settled participants_changed pending_input_merged plugin_init_finished
89
+ llm_context_edited merged_input objectives_updated part_settled participants_changed peer_wait_ended pending_input_merged plugin_init_finished
90
90
  plugin_init_started plugin_init_wait question question_relay reasoning_history_refused
91
91
  recap_ready reminder_injected sampling_refused session_end session_start side_usage steer_cut thinking_dropped
92
92
  thinking_refused tool_dispatch_completed tool_dispatch_started used_memories_updated
@@ -3,6 +3,7 @@
3
3
  require "json"
4
4
  require_relative "../peer_exchanges"
5
5
  require_relative "../peer_mailbox"
6
+ require_relative "../peer_presence"
6
7
  require_relative "../peer_roster"
7
8
  require_relative "../peer_say"
8
9
  require_relative "request_body"
@@ -25,8 +26,9 @@ module Samagotchi
25
26
  private
26
27
 
27
28
  # GET /api/sessions/:id/peers → {peers: [{name, label, paired_at, from,
28
- # address, can_send, messages, exchanges}]}: a row per peer with a
29
- # mailbox folder (the peer chip's only feed). +exchanges+ joins chi's
29
+ # address, can_send, messages, exchanges, waiting}]}: a row per peer with a
30
+ # mailbox folder or a wait (the peer chip's only feed; waiting: {until}
31
+ # while this session waits for one, #waiting_rows). +exchanges+ joins chi's
30
32
  # sends (peer_exchanges.jsonl) with the answers: the log's (an older
31
33
  # pairing's) and the mailbox's messages (PeerExchanges.joined,
32
34
  # unchanged). +messages+: the newest (PeerRoster), with their receipts
@@ -39,15 +41,30 @@ module Samagotchi
39
41
  entries.each_key { |name| rows[name] ||= peer_row(name) }
40
42
  PeerRoster.build(id, state_dir: default_state_dir).each do |peer|
41
43
  row = (rows[peer.name] ||= peer_row(peer.name))
44
+ # Its peer gone (its inbox socket missing): the chip's "ended" (peer-handshake scene 5), and no sends.
45
+ ended = peer.paired? && PeerMailbox.socket_gone?(peer.address)
42
46
  row.merge!(paired_at: peer.paired_at, from: peer.from, address: peer.address,
43
- can_send: peer.paired? && !peer.address.nil?,
47
+ can_send: peer.paired? && !peer.address.nil? && !ended, ended: ended,
44
48
  messages: peer.messages.map { |message| message.to_h.merge("words" => PeerRoster.state_words(message.receipt)) })
45
49
  (entries[peer.name] ||= []).concat(answer_entries(peer))
46
50
  end
47
51
  rows.each_value { |row| row[:exchanges] = PeerExchanges.joined(entries.fetch(row[:name], [])) }
52
+ waiting_rows(id, rows)
48
53
  json_response(200, { peers: rows.values })
49
54
  end
50
55
 
56
+ # A peer this session waits for (/<peer> pair, PeerPresence): its row
57
+ # (made when there is none) with waiting: {until}. A stale wait is
58
+ # absent here, and stays on disk for the session's worker to say it
59
+ # ran out (PeerWaitExpiry).
60
+ def waiting_rows(id, rows)
61
+ PeerPresence.session_marks(id, state_dir: default_state_dir).each do |peer, mark|
62
+ next if mark.stale?
63
+
64
+ (rows[peer] ||= peer_row(peer).merge(exchanges: []))[:waiting] = { until: mark.until_at.utc.iso8601 }
65
+ end
66
+ end
67
+
51
68
  def peer_row(peer)
52
69
  { name: peer, label: PeerMailbox.label(peer), paired_at: nil, from: nil, address: nil, can_send: false, messages: [] }
53
70
  end
@@ -77,29 +94,37 @@ module Samagotchi
77
94
  json_response(200, message.to_h.merge("receipt" => receipt&.to_h))
78
95
  end
79
96
 
80
- # DELETE /api/sessions/:id/peers/:name (Unpair) → {unpaired: whether
81
- # there was a pairing}; the messages stay.
97
+ # DELETE /api/sessions/:id/peers/:name (Unpair, and the waiting chip's
98
+ # Cancel: Local#peer_unpair ends the session's wait for the peer too)
99
+ # → {unpaired: whether there was a pairing, waited: whether a wait
100
+ # ended, forwarded_to: the chain's live link it ended too, when the
101
+ # session was continued}; the messages stay.
82
102
  def handle_peer_unpair(_req, id, name)
83
103
  @session_class.load(id, state_dir: default_state_dir)
84
104
  return invalid_peer(name) unless PeerMailbox.valid_name?(name)
85
105
 
86
- json_response(200, { unpaired: session_access.peer_unpair(id, name) })
106
+ ended = session_access.peer_unpair(id, name)
107
+ json_response(200, { unpaired: ended.unpaired, waited: (true if ended.waited), forwarded_to: ended.forwarded_to }.compact)
87
108
  end
88
109
 
89
- # POST /api/sessions/:id/peers/:name/pair {address, from} → 200
90
- # {status: "paired", link}; 409 {status: continued (next_id) |
91
- # old_worker, detail}.
110
+ # POST /api/sessions/:id/peers/:name/pair {address, from, peer_session}
111
+ # → 200
112
+ # {status: "paired", link, forwarded_to: the chain's live link it
113
+ # paired, when the session was continued}; 409 {status: continued
114
+ # (next_id) | old_worker, detail}.
92
115
  def handle_peer_pair(req, id, name)
93
116
  body = body_hash(req, RequestBody::CONTEXT_PUSH_BODY_LIMIT) or return error_response(400, "invalid_json", "invalid JSON body")
94
117
  return invalid_peer(name) unless PeerMailbox.valid_name?(name)
95
118
 
96
- address, from = body.values_at("address", "from")
97
- unless [address, from].all? { |value| value.nil? || value.is_a?(String) }
98
- return error_response(400, "invalid_fields", "address and from are strings")
119
+ address, from, peer_session = body.values_at("address", "from", "peer_session")
120
+ unless [address, from, peer_session].all? { |value| value.nil? || value.is_a?(String) }
121
+ return error_response(400, "invalid_fields", "address, from and peer_session are strings")
99
122
  end
100
123
 
101
- paired = session_access.peer_pair(id, name, address: address, from: from)
102
- return json_response(200, { status: "paired", link: paired.link.to_h }) if paired.status == :paired
124
+ paired = session_access.peer_pair(id, name, address: address, from: from, peer_session: peer_session)
125
+ if paired.status == :paired
126
+ return json_response(200, { status: "paired", link: paired.link.to_h, forwarded_to: paired.forwarded_to }.compact)
127
+ end
103
128
 
104
129
  json_response(409, { status: paired.status.to_s, next_id: paired.next_id, in_flight: (true if paired.in_flight),
105
130
  detail: paired.refusal }.compact)
@@ -121,7 +146,7 @@ module Samagotchi
121
146
 
122
147
  said = session_access.peer_say(id, name, text: body["text"], summary: string_or_nil(body["summary"]),
123
148
  wake: body["wake"] == true, re: string_or_nil(body["re"]), wait: wait)
124
- line = said.line(name)
149
+ line = said.line(name, id: id)
125
150
  # An older chi --remote knows no busy status: it prints the detail.
126
151
  json_response(said.received? ? 200 : 409, said.to_h.merge("line" => line, **(said.status == :busy ? { "detail" => line } : {})))
127
152
  rescue PeerMailbox::Invalid => e
@@ -0,0 +1,206 @@
1
+ // The closed row of an item agents write to each other: a delegate report
2
+ // (a user line chi brought in, data-source "delegate_report") and a peer's
3
+ // answer (peer_note.js, `.bubble.note.peer-answer`). Its element and its
4
+ // words, drawn from the bubble it sits before: a report's "delegate report ·
5
+ // ‹first line› · N lines", a peer answer's "<name> <verdict> <summary> N
6
+ // lines" (peer_row.js). Which bubble gets one, its key and its stored open
7
+ // state are the owner's (answer_fold.js); this module only draws.
8
+ //
9
+ // A module of its own: static JS is cached at unversioned URLs, and a new
10
+ // export on an old module would blank the page. It imports only what
11
+ // answer_fold.js exported in the last release, and neither module uses the
12
+ // other's bindings at its top level (answer_fold.js re-exports reportLabel
13
+ // from here: an import cycle that is safe that way).
14
+ import { bubbleCopyText } from "./copy.js";
15
+ import { clip } from "./format.js";
16
+ import { foldLabel, foldRowText, lineCount } from "./answer_fold.js";
17
+ import { peerRowWords } from "./peer_row.js";
18
+ import { rowLabel } from "./quiet_notes.js";
19
+
20
+ export const REPORTS = '.bubble.user[data-source="delegate_report"]';
21
+ export const PEERS = ".bubble.note.peer-answer";
22
+ export const AGENT_ITEMS = `${REPORTS}, ${PEERS}`;
23
+
24
+ const ROW_CLASS = "answer-fold";
25
+ // A row's label, at most this long (CSS cuts it to the row's width).
26
+ const LABEL_CHARS = 160;
27
+
28
+ export const isReport = (bubble) => !!bubble?.matches?.(REPORTS);
29
+ export const isPeer = (bubble) => !!bubble?.matches?.(PEERS);
30
+
31
+ // A delegate report's lines before its body: "session: <id>",
32
+ // "status: <s>", "---".
33
+ const REPORT_HEADER = /^(?:(?:session|status):\s|---\s*$)/;
34
+
35
+ // A report row's label: its origin label (the bubble's) and its first
36
+ // heading or first line after the header.
37
+ export function reportLabel(text, origin = "") {
38
+ const body = String(text ?? "").replace(/\r\n?/g, "\n").split("\n").filter((l) => !REPORT_HEADER.test(l.trim())).join("\n");
39
+ const first = foldLabel(body);
40
+ return clip([origin.trim(), first].filter(Boolean).join(" · "), LABEL_CHARS);
41
+ }
42
+
43
+ // A peer answer's row words (peer_row.js) from its bubble: the peer's label
44
+ // (".peer-who" is "<label> answered"), the server's verdict (the pill's
45
+ // class), the summary it sent (none: `.note-text` is a fallback,
46
+ // peer_note.js marks it), the lines of its own text (`.peer-text`'s
47
+ // source; none without a body).
48
+ const VERDICTS = { ok: "OK", changes: "CHANGES", unsure: "UNSURE" };
49
+
50
+ // The server's verdict of a peer answer's bubble (OK, CHANGES, UNSURE), or
51
+ // null.
52
+ export function peerVerdict(bubble) {
53
+ const pill = bubble.querySelector(":scope > .peer-head .peer-verdict");
54
+ const verdict = pill ? Object.keys(VERDICTS).find((k) => pill.classList.contains(k)) : null;
55
+ return verdict ? VERDICTS[verdict] : null;
56
+ }
57
+
58
+ // A peer answer's name as its bubble says it ("<label> answered").
59
+ export function peerName(bubble) {
60
+ const who = bubble.querySelector(":scope > .peer-head > .peer-who")?.textContent || "";
61
+ return who.replace(/\s+answered\s*$/, "").trim() || bubble.dataset.peerName || "peer";
62
+ }
63
+
64
+ function peerRowOf(bubble) {
65
+ const note = bubble.querySelector(":scope > .note-text");
66
+ const body = bubble.querySelector(":scope > .peer-text");
67
+ const text = body ? (body.dataset.peerMd ?? body.textContent) : null;
68
+ const who = bubble.querySelector(":scope > .peer-head > .peer-who")?.textContent || "";
69
+ return peerRowWords({
70
+ name: who.replace(/\s+answered\s*$/, ""),
71
+ verdict: peerVerdict(bubble),
72
+ summary: note && !note.hasAttribute("data-fallback") ? note.textContent : "",
73
+ first: (text !== null ? foldLabel(text, { display: true }) : "") || note?.textContent || "",
74
+ lines: text !== null ? lineCount(text) : null,
75
+ });
76
+ }
77
+
78
+ // Writes only what changed: the owner's settle redraws every row, and a
79
+ // write that changes nothing still wakes the other observers on #history.
80
+ function setText(el, text) {
81
+ if (el && el.textContent !== text) el.textContent = text;
82
+ }
83
+
84
+ function setState(row, { folded, title, classes = {} }) {
85
+ const expanded = folded ? "false" : "true";
86
+ if (row.getAttribute("aria-expanded") !== expanded) row.setAttribute("aria-expanded", expanded);
87
+ if (row.title !== title) row.title = title;
88
+ for (const [name, on] of Object.entries({ folded, ...classes })) {
89
+ if (row.classList.contains(name) !== on) row.classList.toggle(name, on);
90
+ }
91
+ }
92
+
93
+ function drawPeerRow(row, bubble) {
94
+ const folded = bubble.classList.contains("folded");
95
+ const words = peerRowOf(bubble);
96
+ setState(row, { folded, title: folded ? "Show the answer" : "Fold the answer" });
97
+ for (const part of ["name", "verdict", "summary", "size"]) setText(row.querySelector(`.answer-fold-${part}`), words[part]);
98
+ }
99
+
100
+ // The row's spans: a report's own row "label size", a compact row (a peer
101
+ // answer's, a report's or a note's inside a run line, the mock-up's panel
102
+ // row) "name verdict summary size". Rebuilt when the shape changes.
103
+ const SHAPES = { label: ["label", "size"], compact: ["name", "verdict", "summary", "size"] };
104
+
105
+ function shape(row, want) {
106
+ if (row.dataset.shape === want) return;
107
+ const doc = row.ownerDocument;
108
+ row.replaceChildren(...SHAPES[want].map((part) => {
109
+ const el = doc.createElement("span");
110
+ el.className = `answer-fold-${part}`;
111
+ return el;
112
+ }));
113
+ row.dataset.shape = want;
114
+ }
115
+
116
+ const squash = (text) => String(text ?? "").replace(/\s+/g, " ").trim();
117
+
118
+ // A report's name in a line: the child's session ("child ab12cd", its
119
+ // header's `session:`), else its origin label.
120
+ function reportName(text, origin) {
121
+ const id = /^session:\s*(\S+)/m.exec(String(text ?? ""))?.[1];
122
+ return id ? `child ${id.slice(0, 6)}` : squash(origin) || "report";
123
+ }
124
+
125
+ // A report inside a run line: the mock-up's panel row, "child ab12cd ‹first
126
+ // line› N lines", opening to its text (CSS joins them).
127
+ function drawReportLineRow(row, bubble) {
128
+ shape(row, "compact");
129
+ const folded = bubble.classList.contains("folded");
130
+ const text = bubbleCopyText(bubble);
131
+ setState(row, {
132
+ folded, title: folded ? "Show the report" : "Fold the report",
133
+ classes: { report: false, prompt: false, steered: false, compact: true, "report-row": true },
134
+ });
135
+ const n = lineCount(text);
136
+ const words = { name: reportName(text, bubble.querySelector(":scope > .origin-label")?.textContent || ""), verdict: "",
137
+ summary: reportLabel(text), size: `${n} line${n === 1 ? "" : "s"}` };
138
+ for (const part of SHAPES.compact) setText(row.querySelector(`:scope > .answer-fold-${part}`), words[part]);
139
+ }
140
+
141
+ function drawReportRow(row, bubble) {
142
+ shape(row, "label");
143
+ const folded = bubble.classList.contains("folded");
144
+ const text = bubbleCopyText(bubble);
145
+ const own = { label: reportLabel(text, bubble.querySelector(":scope > .origin-label")?.textContent || "") };
146
+ const { label, size } = foldRowText(text, { folded, ...own });
147
+ setState(row, {
148
+ folded, title: folded ? "Show the report" : "Fold the report",
149
+ classes: { report: true, prompt: false, steered: bubble.classList.contains("steered"), compact: false, "report-row": false },
150
+ });
151
+ const [labelEl, sizeEl] = row.children;
152
+ setText(labelEl, label);
153
+ setText(sizeEl, size);
154
+ }
155
+
156
+ // Draws +row+ from +bubble+ (a report or a peer answer): its words, and its
157
+ // folded state from the bubble's class. +inLine+: under a run line, where a
158
+ // report's row is the compact panel row (a peer answer's always is).
159
+ export function drawAgentRow(row, bubble, { inLine = false } = {}) {
160
+ if (isPeer(bubble)) drawPeerRow(row, bubble);
161
+ else if (inLine) drawReportLineRow(row, bubble);
162
+ else drawReportRow(row, bubble);
163
+ }
164
+
165
+ // A quiet item's words as its compact row in a line: its name (the notes
166
+ // row's, quiet_notes.js) and its text after that name.
167
+ export function noteRowWords(el) {
168
+ const name = rowLabel([el]).names[0] || "note";
169
+ let text;
170
+ if (el.matches(".steer-row")) text = el.querySelector(".steer-text")?.textContent;
171
+ else if (el.querySelector(":scope > .note-text")) text = el.querySelector(":scope > .note-text").textContent;
172
+ else text = el.textContent;
173
+ let said = squash(text);
174
+ if (said.startsWith(`${name}: `)) said = said.slice(name.length + 2);
175
+ if (el.matches(".objectives-entry")) said = said.replace(/^Objectives\s*/, "");
176
+ return { name, summary: said };
177
+ }
178
+
179
+ // A note's compact row in a line (closed: the note is hidden under it; a tap
180
+ // shows it, never stored).
181
+ export function makeNoteRow(doc) {
182
+ const row = doc.createElement("button");
183
+ row.type = "button";
184
+ row.className = `${ROW_CLASS} compact note-row folded`;
185
+ shape(row, "compact");
186
+ row.setAttribute("aria-expanded", "false");
187
+ return row;
188
+ }
189
+
190
+ export function drawNoteRow(row, el, open) {
191
+ const { name, summary } = noteRowWords(el);
192
+ setState(row, { folded: !open, title: open ? "Hide the note" : "Show the note" });
193
+ for (const [part, text] of [["name", name], ["verdict", ""], ["summary", summary], ["size", ""]]) {
194
+ setText(row.querySelector(`:scope > .answer-fold-${part}`), text);
195
+ }
196
+ }
197
+
198
+ // A new row for +bubble+ (a report or a peer answer), not drawn yet.
199
+ export function makeAgentRow(doc, bubble) {
200
+ const peer = isPeer(bubble);
201
+ const row = doc.createElement("button");
202
+ row.type = "button";
203
+ row.className = peer ? `${ROW_CLASS} peer compact` : ROW_CLASS;
204
+ shape(row, peer ? "compact" : "label");
205
+ return row;
206
+ }