samagotchi 0.184.0 → 0.186.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 (119) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/docs/architecture.md +1 -1
  4. data/docs/bundles.md +62 -35
  5. data/docs/cli.md +10 -1
  6. data/docs/configuration.md +19 -1
  7. data/docs/context.md +76 -10
  8. data/docs/guardrails.md +20 -2
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/block-renderers.md +4 -2
  11. data/docs/internals/bridge.md +7 -2
  12. data/docs/internals/engine.md +15 -1
  13. data/docs/internals/llm-context-forget.md +6 -0
  14. data/docs/internals/participants.md +4 -1
  15. data/docs/internals/prompt-caching.md +14 -0
  16. data/docs/internals/remote-sessions.md +10 -1
  17. data/docs/internals/session-lifecycle.md +1 -1
  18. data/docs/internals/web-frontend.md +23 -6
  19. data/docs/mcp-server.md +6 -2
  20. data/docs/scheduling.md +5 -0
  21. data/docs/sessions.md +12 -2
  22. data/docs/sub-agent.md +48 -3
  23. data/docs/thin-clients.md +76 -4
  24. data/lib/samagotchi/agent_caller.rb +97 -0
  25. data/lib/samagotchi/bridge.rb +7 -7
  26. data/lib/samagotchi/bundles/claude-peer/manifest.yml +14 -8
  27. data/lib/samagotchi/bundles/claude-peer/plugin.rb +3 -3
  28. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +49 -30
  29. data/lib/samagotchi/bundles/claude-peer/scripts/pair +2 -2
  30. data/lib/samagotchi/bundles/claude-peer/scripts/pair-remote +123 -0
  31. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +11 -3
  32. data/lib/samagotchi/bundles/codex-peer/manifest.yml +10 -8
  33. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  34. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +29 -8
  35. data/lib/samagotchi/bundles/codex-peer/scripts/pair +1 -1
  36. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +11 -3
  37. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  38. data/lib/samagotchi/bundles/mcp/http_client.rb +19 -2
  39. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  40. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  41. data/lib/samagotchi/bundles/system/self_map.md +2 -0
  42. data/lib/samagotchi/client_id.rb +61 -1
  43. data/lib/samagotchi/command_intake.rb +16 -8
  44. data/lib/samagotchi/config.rb +3 -1
  45. data/lib/samagotchi/context_absorber.rb +215 -46
  46. data/lib/samagotchi/delivery.rb +15 -0
  47. data/lib/samagotchi/driver_command.rb +68 -0
  48. data/lib/samagotchi/engine/block_fix.rb +2 -2
  49. data/lib/samagotchi/engine.rb +20 -5
  50. data/lib/samagotchi/engine_peers.rb +6 -0
  51. data/lib/samagotchi/guardrails/pair_boundary.rb +1 -1
  52. data/lib/samagotchi/llm/chat_loop.rb +16 -2
  53. data/lib/samagotchi/mcp_command.rb +7 -2
  54. data/lib/samagotchi/mcp_server/tools.rb +9 -3
  55. data/lib/samagotchi/objectives_track.rb +2 -1
  56. data/lib/samagotchi/owner_prompt.rb +5 -1
  57. data/lib/samagotchi/parent_report.rb +9 -5
  58. data/lib/samagotchi/plain_reply.rb +75 -0
  59. data/lib/samagotchi/plugin/peer.rb +10 -4
  60. data/lib/samagotchi/reply_for.rb +254 -0
  61. data/lib/samagotchi/reply_wait.rb +12 -3
  62. data/lib/samagotchi/schedules.rb +10 -7
  63. data/lib/samagotchi/send_command/parent_gate.rb +3 -1
  64. data/lib/samagotchi/send_command.rb +45 -8
  65. data/lib/samagotchi/session.rb +9 -1
  66. data/lib/samagotchi/session_access/ask.rb +10 -4
  67. data/lib/samagotchi/session_access/contract.rb +2 -0
  68. data/lib/samagotchi/session_access/exchange/token.rb +42 -7
  69. data/lib/samagotchi/session_access/exchange.rb +5 -2
  70. data/lib/samagotchi/session_access/local.rb +6 -3
  71. data/lib/samagotchi/session_access/remote.rb +23 -3
  72. data/lib/samagotchi/session_access.rb +4 -2
  73. data/lib/samagotchi/session_command_catalog.rb +8 -0
  74. data/lib/samagotchi/session_commands.rb +9 -0
  75. data/lib/samagotchi/session_continue.rb +4 -1
  76. data/lib/samagotchi/session_inbox.rb +2 -0
  77. data/lib/samagotchi/session_inbox_delivery.rb +4 -2
  78. data/lib/samagotchi/session_manager/delivery.rb +80 -5
  79. data/lib/samagotchi/session_manager/spawn.rb +7 -1
  80. data/lib/samagotchi/steer.rb +119 -22
  81. data/lib/samagotchi/terminal_ui/formatting.rb +12 -2
  82. data/lib/samagotchi/tool_activity.rb +4 -0
  83. data/lib/samagotchi/tool_declarations.rb +22 -1
  84. data/lib/samagotchi/tool_names.rb +4 -0
  85. data/lib/samagotchi/toolkit.rb +3 -2
  86. data/lib/samagotchi/tools/ask_session.rb +208 -0
  87. data/lib/samagotchi/tools/builtin_calls.rb +1 -0
  88. data/lib/samagotchi/tools/builtins.rb +5 -0
  89. data/lib/samagotchi/turn_anchors.rb +65 -17
  90. data/lib/samagotchi/turn_checkpoint.rb +21 -2
  91. data/lib/samagotchi/turn_stages/context_judge.rb +3 -1
  92. data/lib/samagotchi/turn_stages/objectives.rb +4 -2
  93. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +3 -0
  94. data/lib/samagotchi/version.rb +1 -1
  95. data/lib/samagotchi/visitor.rb +37 -0
  96. data/lib/samagotchi/web/app.rb +1 -1
  97. data/lib/samagotchi/web/ask_routes.rb +68 -21
  98. data/lib/samagotchi/web/message_display.rb +15 -2
  99. data/lib/samagotchi/web/participant_access.rb +1 -1
  100. data/lib/samagotchi/web/public/app.js +1 -1
  101. data/lib/samagotchi/web/public/block_fix.js +11 -3
  102. data/lib/samagotchi/web/public/history_shape.js +3 -1
  103. data/lib/samagotchi/web/public/index.html +8 -0
  104. data/lib/samagotchi/web/public/peer_links.js +27 -4
  105. data/lib/samagotchi/web/public/peer_note.js +19 -3
  106. data/lib/samagotchi/web/public/peer_text.js +62 -0
  107. data/lib/samagotchi/web/public/picture_regions.js +2 -2
  108. data/lib/samagotchi/web/public/turn_events.js +19 -0
  109. data/lib/samagotchi/web/public/working_set_view.js +11 -2
  110. data/lib/samagotchi/web/session_access_routes.rb +30 -2
  111. data/lib/samagotchi/web/session_control.rb +22 -3
  112. data/lib/samagotchi/web/session_create.rb +11 -7
  113. data/lib/samagotchi/worker/command_queue.rb +5 -2
  114. data/lib/samagotchi/worker/senders.rb +79 -0
  115. data/lib/samagotchi/worker.rb +22 -18
  116. data/lib/samagotchi/worker_inbound.rb +12 -4
  117. data/lib/samagotchi/worker_participant_gate.rb +1 -3
  118. data/lib/samagotchi/worker_wakes.rb +12 -0
  119. metadata +10 -1
@@ -2,7 +2,9 @@
2
2
 
3
3
  require "delegate"
4
4
  require_relative "../bridge_client"
5
+ require_relative "../agent_caller"
5
6
  require_relative "../client_id"
7
+ require_relative "../command_intake"
6
8
  require_relative "../reply_wait"
7
9
  require_relative "../session"
8
10
  require_relative "../session_command_catalog"
@@ -11,6 +13,8 @@ require_relative "../turn_flow"
11
13
  require_relative "../session_access/ask"
12
14
  require_relative "../session_access/exchange"
13
15
  require_relative "../session_access/exchange/token"
16
+ require_relative "../reply_for"
17
+ require_relative "../turn_anchors"
14
18
  require_relative "request_body"
15
19
 
16
20
  module Samagotchi
@@ -81,12 +85,14 @@ module Samagotchi
81
85
  private
82
86
 
83
87
  # POST /api/sessions/:id/ask {prompt, timeout, queue, client_id,
84
- # request_id}: the message delivered (to a chain's newest link; a
88
+ # request_id, reply_for}: the message delivered (to a chain's newest link; a
85
89
  # running session queues it as its own turn unless queue is false) and
86
90
  # its answer waited for, all within ASK_MAX_SECONDS. A request_id (a
87
91
  # message's, not a command's) names its turn: a retry whose turn the
88
92
  # session knows waits on it again, nothing sent and no second history
89
- # line (SessionAccess::Ask#call). 200 wait_result_json's fields +
93
+ # line (SessionAccess::Ask#call). A reply_for (ReplyFor.parse: a name
94
+ # or the values) rides a message's turn as its anchor (a line the
95
+ # Bridge runs as a command, #runs_as_command?: kept in hand only). 200 wait_result_json's fields +
90
96
  # session_id (+ asked, the id given, when another link ran it; +
91
97
  # token when the status is timeout: POST …/wait {token} goes on; +
92
98
  # request_id when one was given); 200 {status: command} for a session
@@ -102,6 +108,11 @@ module Samagotchi
102
108
  prompt, client_id, options, error = ask_request(id, body)
103
109
  return error if error
104
110
 
111
+ reply_for, error = ask_reply_for(body)
112
+ return error if error
113
+
114
+ options[:anchors] = TurnAnchors.new(reply_for: reply_for) if reply_for && !runs_as_command?(prompt, client_id)
115
+
105
116
  gated = ask_gate(id, prompt, client_id)
106
117
  return gated if gated
107
118
 
@@ -115,7 +126,7 @@ module Samagotchi
115
126
  cancelled: stopping, **options)
116
127
  rebound = outcome.is_a?(SessionAccess::Ask::Reply) && outcome.rebound
117
128
  record_history(body, prompt) unless outcome.is_a?(SessionAccess::Ask::Refused) || rebound
118
- ask_response(id, outcome, request_id: options[:request_id])
129
+ ask_response(id, outcome, request_id: options[:request_id], reply_for: reply_for)
119
130
  rescue SessionManager::OwnedByTUI => e
120
131
  owned_by_tui(e)
121
132
  end
@@ -152,6 +163,34 @@ module Samagotchi
152
163
  [nil, nil, nil, error_response(400, "invalid_prompt", e.message)]
153
164
  end
154
165
 
166
+ # The body's reply_for: [nil or a ReplyFor, nil] or [nil, a 400
167
+ # invalid_ask]. A name is resolved here (config.yml's surfaces:, read
168
+ # now), so the session saves values: a later config edit leaves old
169
+ # turns as they were.
170
+ def ask_reply_for(body)
171
+ [ReplyFor.parse(body["reply_for"]), nil]
172
+ rescue ReplyFor::Invalid => e
173
+ [nil, error_response(400, "invalid_ask", e.message)]
174
+ end
175
+
176
+ # Whether the Bridge runs +prompt+ from +sender+ as a session command
177
+ # or a shell line (Bridge#handle_post_turn's rule: the registry's
178
+ # command? and CommandIntake.allowed?), so a turn's anchor would be
179
+ # dropped: an unknown /word ("/tmp is full, what now?") is a message
180
+ # and keeps it. chi web knows the built-ins only, so a bundle's command
181
+ # carries the anchor too, which the worker ignores as it runs it.
182
+ def runs_as_command?(prompt, sender)
183
+ SessionCommandCatalog.builtin_registry.command?(prompt) && CommandIntake.allowed?(sender)
184
+ end
185
+
186
+ # A line a worker may run as a session command or a shell line, by its
187
+ # shape (COMMAND_SHAPE): a request_id is refused for it (#ask_request_id),
188
+ # a bundle's command included.
189
+ def command_line?(prompt)
190
+ line = prompt.strip
191
+ line.start_with?("!") || COMMAND_SHAPE.match?(line)
192
+ end
193
+
155
194
  # The body's request_id: [nil or it, nil] or [nil, a 400]. A session
156
195
  # command never runs as a turn of that id (the Bridge's command path
157
196
  # takes none), so a retry would run it again: refused. Any line the
@@ -164,8 +203,7 @@ module Samagotchi
164
203
  return [nil, error_response(400, "invalid_ask", "request_id is 1 to 128 printable ASCII characters")]
165
204
  end
166
205
 
167
- line = prompt.strip
168
- if line.start_with?("!") || COMMAND_SHAPE.match?(line)
206
+ if command_line?(prompt)
169
207
  return [nil, error_response(400, "invalid_ask", "request_id is for messages, not session commands")]
170
208
  end
171
209
 
@@ -174,11 +212,12 @@ module Samagotchi
174
212
 
175
213
  # Who asks: the owner (WEB_UNNAMED) unless the body names a sender
176
214
  # (owner_sender's rule); a parent agent's /continue yes sent as
177
- # cli:send goes in as cli:answer, as chi send sends it (the worker
178
- # holds that one to guardrails.parent_answers).
215
+ # cli:send or an agent's id (ClientId.parent_line?) goes in as
216
+ # cli:answer, as chi send sends it (the worker holds that one to
217
+ # guardrails.parent_answers).
179
218
  def ask_sender(client_id, prompt)
180
219
  sender = owner_sender({ "client_id" => client_id })
181
- sender == ClientId::CLI_SEND && TurnFlow.continue_yes?(prompt) ? ClientId::CLI_ANSWER : sender
220
+ TurnFlow.continue_yes?(prompt) ? AgentCaller.continue_id(sender) : sender
182
221
  end
183
222
 
184
223
  # A parent agent's line refused before anything is sent, as POST
@@ -186,7 +225,7 @@ module Samagotchi
186
225
  # session asked and of its chain's newest link (where it goes).
187
226
  # @return [Array, nil] the response, or nil to go on
188
227
  def ask_gate(id, prompt, client_id)
189
- return nil unless App::CLI_SEND_IDS.include?(client_id)
228
+ return nil unless ClientId.parent_line?(client_id)
190
229
 
191
230
  asked = session_access.resolve(id)
192
231
  ids = [asked, session_access.head(asked).id].uniq
@@ -201,18 +240,21 @@ module Samagotchi
201
240
  end
202
241
 
203
242
  # The ask's answer for an Ask value (+request_id+ echoed when given:
204
- # the client sees this chi web used it).
205
- def ask_response(id, outcome, request_id: nil)
243
+ # the client sees this chi web used it), shaped for +reply_for+ (the
244
+ # request's: a /continue yes's too, which opens no message), its token
245
+ # carrying it for the next wait.
246
+ def ask_response(id, outcome, request_id: nil, reply_for: nil)
206
247
  case outcome
207
248
  when SessionAccess::Ask::Ran then json_response(200, { status: "command", session_id: outcome.session_id })
208
- when SessionAccess::Ask::Refused then ask_refused(id, outcome)
249
+ when SessionAccess::Ask::Refused then ask_refused(id, outcome, reply_for: reply_for)
209
250
  else
210
251
  result = outcome.result
211
252
  return error_response(503, "server_stopping", "chi web is stopping; wait again") if result.status == :canceled
212
253
 
213
- json = wait_result_json(result, session_access.parent_strategy(outcome.session_id)).merge(session_id: outcome.session_id)
254
+ json = wait_result_json(result, session_access.parent_strategy(outcome.session_id), reply_for: reply_for)
255
+ .merge(session_id: outcome.session_id)
214
256
  json[:asked] = outcome.asked if outcome.asked && outcome.asked != outcome.session_id
215
- json[:token] = outcome.token if outcome.token
257
+ json[:token] = SessionAccess::Exchange::Token.carrying(outcome.token, reply_for) if outcome.token
216
258
  json[:request_id] = request_id if request_id
217
259
  json_response(200, json)
218
260
  end
@@ -222,7 +264,7 @@ module Samagotchi
222
264
  ASK_BUSY_WORDS = { "busy" => "a turn is running: ask with queue, or wait for it",
223
265
  "waiting" => "a question waits for an answer" }.freeze
224
266
 
225
- def ask_refused(id, refused)
267
+ def ask_refused(id, refused, reply_for: nil)
226
268
  case refused.kind
227
269
  when :canceled then error_response(503, "server_stopping", "chi web is stopping; ask again")
228
270
  when :unknown
@@ -233,7 +275,9 @@ module Samagotchi
233
275
  when :continuing then refusal(409, "continuing", refused.message, session_id: refused.session_id)
234
276
  when :busy
235
277
  words = ASK_BUSY_WORDS.fetch(refused.busy.error)
236
- json_response(409, busy_json(refused.busy).merge(detail: words, message: words))
278
+ json = busy_json(refused.busy).merge(detail: words, message: words)
279
+ json[:question] = question_json(refused.busy.question, reply_for) if refused.busy.question
280
+ json_response(409, json.merge(needs_detail_fields(reply_for, refused.busy.question)))
237
281
  else refused_delivery(refused.result)
238
282
  end
239
283
  end
@@ -256,6 +300,7 @@ module Samagotchi
256
300
  end
257
301
 
258
302
  session_id, target = SessionAccess::Exchange::Token.load(body["token"])
303
+ reply_for = SessionAccess::Exchange::Token.reply_for(body["token"])
259
304
  # The URL's id may be a prefix (as the ask's): resolved first (no
260
305
  # such session, or several: session_route's 404).
261
306
  full = session_access.resolve(id)
@@ -265,7 +310,7 @@ module Samagotchi
265
310
  **wait_extras)
266
311
  return error_response(503, "server_stopping", "chi web is stopping; wait again") if result.status == :canceled
267
312
 
268
- json = wait_result_json(result, session_access.parent_strategy(full)).merge(session_id: full)
313
+ json = wait_result_json(result, session_access.parent_strategy(full), reply_for: reply_for).merge(session_id: full)
269
314
  json[:token] = body["token"] if result.status == :timeout
270
315
  json_response(200, json)
271
316
  rescue SessionAccess::Exchange::Token::Invalid => e
@@ -299,8 +344,10 @@ module Samagotchi
299
344
  # went in before the wait, so a wait that fails (chi web stopping, the
300
345
  # session deleted, its files unreadable) is still a 200: wait_error
301
346
  # {error: server_stopping | not_found | wait_failed, detail} in place
302
- # of reply (an answer retried would be 409).
303
- def answered_wait(id, question_id, start, seconds, answered:)
347
+ # of reply (an answer retried would be 409). +reply_for+: the pending
348
+ # turn's (its saved opener's, read before the answer went in), which
349
+ # shapes the reply and rides its token.
350
+ def answered_wait(id, question_id, start, seconds, answered:, reply_for: nil)
304
351
  head = answered ? { status: "answered" } : { status: "not_pending", answered_here: false }
305
352
  head = { **head, session_id: id, id: question_id }
306
353
  target = ReplyWait::Target.answer(start)
@@ -309,8 +356,8 @@ module Samagotchi
309
356
  return answer_wait_error(head, "server_stopping", "chi web is stopping; the answer went in")
310
357
  end
311
358
 
312
- reply = wait_result_json(result, session_access.parent_strategy(id))
313
- reply[:token] = SessionAccess::Exchange::Token.dump(id, target) if result.status == :timeout
359
+ reply = wait_result_json(result, session_access.parent_strategy(id), reply_for: reply_for)
360
+ reply[:token] = SessionAccess::Exchange::Token.dump(id, target, reply_for: reply_for) if result.status == :timeout
314
361
  json_response(200, { **head, reply: reply })
315
362
  rescue ArgumentError => e # deleted while waiting
316
363
  answer_wait_error(head, "not_found", e.message)
@@ -4,6 +4,7 @@ require_relative "../session"
4
4
  require_relative "../answer_refs"
5
5
  require_relative "../answer_tail"
6
6
  require_relative "../block_fix/stamp"
7
+ require_relative "../context_absorber"
7
8
  require_relative "../context_note"
8
9
  require_relative "../image_store"
9
10
  require_relative "../message_parts"
@@ -97,8 +98,8 @@ module Samagotchi
97
98
  # but that (a text-less step) is kept with empty content
98
99
  # @param cwd [String, nil] the session's working directory (the parts'
99
100
  # tool titles are relative to it)
100
- # @param markdown [Boolean] false: no html for a delegate report or an
101
- # answer (the participant review drops both and renders its replies
101
+ # @param markdown [Boolean] false: no html for a delegate report, an
102
+ # answer or a peer's text (the participant review drops them and renders its replies
102
103
  # from their redacted text, ParticipantReview#with_reply_html)
103
104
  # @param drawings [Array<Bridge::TurnDrawings::Line>, nil] the owner
104
105
  # show's lines (TurnDrawings.cover against +msgs+): each item of a
@@ -130,6 +131,8 @@ module Samagotchi
130
131
  note[:context_source] = context_source.to_s if context_source
131
132
  peer = Samagotchi::ContextNote.fetch(m, :peer)
132
133
  note[:peer] = peer if peer.is_a?(Hash)
134
+ peer_html = markdown && peer_text_html(peer, note[:content])
135
+ note[:peer_html] = peer_html if peer_html
133
136
  payload = Samagotchi::ContextNote.fetch(m, :objectives)
134
137
  entry = payload && Samagotchi::Objectives.entry(payload, before: objectives)
135
138
  if entry
@@ -245,6 +248,16 @@ module Samagotchi
245
248
  []
246
249
  end
247
250
 
251
+ # A peer's text in its note (+peer+'s `inline`), rendered as an
252
+ # answer is: the bubble draws it at once (peer_note.js), so a history
253
+ # read asks for no render per bubble. nil without a block or a renderer.
254
+ def peer_text_html(peer, content)
255
+ return nil unless peer.is_a?(Hash) && (peer["inline"] || peer[:inline]) && @markdown_renderer.available?
256
+
257
+ text = Samagotchi::ContextAbsorber.peer_text_of(content)
258
+ text && @markdown_renderer.render(text)
259
+ end
260
+
248
261
  # The ✂ marks of the outputs right after the model message at +index+,
249
262
  # by output id, as its parts have them (a stub's size from its own
250
263
  # output): its parts are read only when +marks+ (the session's, by
@@ -326,7 +326,7 @@ module Samagotchi
326
326
  prompt = body["prompt"].to_s
327
327
  return error_response(400, "missing_fields", "prompt is required") if prompt.strip.empty?
328
328
 
329
- anchors = TurnAnchors.from(body)
329
+ anchors = TurnAnchors.from_turn_route(body)
330
330
  revises = anchors.revises&.turn_id
331
331
  reason = participant_turn_refusal(grant, prompt, body) || participant_revise_refusal(grant, id, anchors)
332
332
  return participant_turn_refused(grant, prompt, *reason, revises: revises) if reason
@@ -437,7 +437,7 @@ function findInTurnRoots(selector) {
437
437
  // The open session's peers (peer_data.js, owner only) and their exchange drawn in the conversation (peer_links.js).
438
438
  const peers = contextChips ? createPeers({ sessionId: () => store.selected, onChange: () => { peerLinks.draw(); contextChips.peersChanged(); },
439
439
  hasPeer: () => peerLinks.hasPeer() || contextChips.rows.some((row) => row.peer) }) : null;
440
- const peerLinks = peers && createPeerLinks({ peers, roots: turnRoots, running: () => liveTurn.running, showText: (name) => contextChips.showText?.(name) });
440
+ const peerLinks = peers && createPeerLinks({ peers, roots: turnRoots, running: () => liveTurn.running, showText: (name) => contextChips.showText?.(name), renderMarkdown });
441
441
  // The running turn as the page follows it (live_turn.js): whether one
442
442
  // runs, its timing line and the turns this page saw end (live_timing.js),
443
443
  // its merges' bubble flags, its turn-end reads.
@@ -136,6 +136,7 @@ export function createBlockFix({ roots, sessionId, features, bridgeUp = () => tr
136
136
  }
137
137
  if (status === 200) { setFixNote(pre, "nohelp"); return; }
138
138
  if (status === 202) {
139
+ if (typeof body.key === "string" && body.key) pre.dataset.blockFixKey = body.key;
139
140
  // Running, unless the worker's word already came.
140
141
  if (asking(pre)) giveUpLater(turnId);
141
142
  return;
@@ -195,13 +196,20 @@ export function createBlockFix({ roots, sessionId, features, bridgeUp = () => tr
195
196
  noticeSession();
196
197
  const turnId = data?.turn_id;
197
198
  if (!turnId) return;
198
- if (pending.has(turnId)) { timers.clearTimeout(pending.get(turnId)); pending.delete(turnId); }
199
+ const asked = askedIn(turnId);
200
+ const relevant = data.key ? asked.filter((pre) => !pre.dataset.blockFixKey || pre.dataset.blockFixKey === data.key) : asked;
201
+ if (!relevant.length) return;
202
+ for (const pre of relevant) delete pre.dataset.blockFixAsked;
203
+ if (pending.has(turnId) && !askedIn(turnId).some(asking)) {
204
+ timers.clearTimeout(pending.get(turnId));
205
+ pending.delete(turnId);
206
+ }
199
207
  if (data.state === "fixed") {
200
- for (const pre of askedIn(turnId)) redrawOnce(turnId, codeText(pre));
208
+ for (const pre of relevant) redrawOnce(turnId, codeText(pre));
201
209
  refresh(sessionId(), turnId);
202
210
  return;
203
211
  }
204
- for (const pre of askedIn(turnId)) setFixNote(pre, "nohelp");
212
+ for (const pre of relevant) setFixNote(pre, "nohelp");
205
213
  }
206
214
 
207
215
  function scan(el) {
@@ -57,12 +57,14 @@ function sameBut(a, b, key) {
57
57
 
58
58
  // What a reader reads of +el+: its text, without the copy button, the
59
59
  // time dividers and a peer answer's late slots (peer_links.js fills them
60
- // from GET …/peers, which an offscreen reload doesn't read), whitespace
60
+ // from GET …/peers, which an offscreen reload doesn't read), a peer's text
61
+ // as its source (peer_links.js swaps in its markdown later), whitespace
61
62
  // collapsed.
62
63
  function textOf(el) {
63
64
  if (!el) return "";
64
65
  const copy = el.cloneNode(true);
65
66
  copy.querySelectorAll(".copy-btn, .time-gap, [data-peer-slot]").forEach((node) => node.remove());
67
+ copy.querySelectorAll("[data-peer-md]").forEach((node) => { node.textContent = node.dataset.peerMd; });
66
68
  return copy.textContent.replace(/\s+/g, " ").trim();
67
69
  }
68
70
 
@@ -513,6 +513,14 @@ button.system-one-wrong,.system-one-wrong.marked{flex:none;padding:1px 6px;borde
513
513
  A send's state (peer_exchange.js pillTemplate) is a pill in the chip's shape after the row's params. */
514
514
  .bubble.note.peer-answer{border:1px solid var(--border-strong);border-radius:10px;background:var(--bg-panel);opacity:1;font-size:13px;color:var(--text);white-space:normal;display:flex;flex-direction:column;gap:8px}
515
515
  .bubble.note.peer-answer .note-text{max-height:none;overflow:visible;line-height:1.5}
516
+ .bubble.note.peer-answer .peer-text{line-height:1.5;white-space:pre-wrap;overflow-wrap:anywhere}
517
+ .bubble.note.peer-answer .peer-text.markdown{white-space:normal}
518
+ .bubble.note.peer-answer .peer-text.md-compact{
519
+ --md-heading-size:14.5px;--md-heading-color:var(--text);
520
+ --md-subheading-size:14px;--md-subheading-color:var(--text-2);
521
+ --md-strong-color:var(--text);--md-blockquote-color:var(--text-muted);--md-code-color:var(--text);
522
+ --md-pre-size:12.5px;--md-cell-size:13px
523
+ }
516
524
  .peer-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 8px}
517
525
  .peer-who{font-weight:700;color:var(--text-bright)}
518
526
  .peer-mark{margin-left:auto;display:inline-flex;align-items:baseline;gap:8px}
@@ -30,7 +30,7 @@ export function upTemplate(exchange) {
30
30
  }
31
31
 
32
32
  // "Read the full answer": the newest answer of a peer only (its outbox keeps
33
- // one text).
33
+ // one text), and not one whose bubble holds its text (data-peer-inline).
34
34
  export function fullTemplate(newest) {
35
35
  return newest ? html`<button type="button" class="peer-full" data-peer-full="1">Read the full answer</button>` : nothing;
36
36
  }
@@ -38,11 +38,16 @@ export function fullTemplate(newest) {
38
38
  // +peers+ the model (peer_data.js); +roots+() the elements a turn's rows can
39
39
  // be in (the history and the stage); +running+() whether a turn runs;
40
40
  // +showText+(source) opens that context source's text (context_chips.js);
41
- // +behavior+() the scroll's.
41
+ // +renderMarkdown+(text) a text's sanitized markdown HTML or null
42
+ // (markdown_place.js; none: the peer's text stays plain); +behavior+() the
43
+ // scroll's.
42
44
  //
43
45
  // @return {draw(), drawn(), hasPeer(), hasSend(id), showSend(id), reset()}
44
- export function createPeerLinks({ peers, roots, running = () => false, showText = () => {}, behavior = smooth } = {}) {
46
+ export function createPeerLinks({ peers, roots, running = () => false, showText = () => {}, renderMarkdown = null, behavior = smooth } = {}) {
45
47
  const all = (selector) => roots().filter(Boolean).flatMap((root) => [...root.querySelectorAll(selector)]);
48
+ // The peer texts already asked for (each is asked once; a failed read
49
+ // keeps the plain text).
50
+ const asked = new WeakSet();
46
51
 
47
52
  // A slot of the running turn (the stage's, or a turn opened in the history).
48
53
  const live = (slot) => running() && !!slot.closest(".turn-stage, [data-opened-turn]");
@@ -81,10 +86,28 @@ export function createPeerLinks({ peers, roots, running = () => false, showText
81
86
  const up = note.querySelector(":scope > .peer-head > .peer-up-slot");
82
87
  if (up) render(upTemplate(answerOf(note)), up);
83
88
  const full = note.querySelector(":scope > .peer-foot > .peer-full-slot");
84
- if (full) render(fullTemplate(newest.get(note.dataset.peerSource || "") === note && !!note.dataset.peerSource), full);
89
+ const last = newest.get(note.dataset.peerSource || "") === note && !!note.dataset.peerSource;
90
+ if (full) render(fullTemplate(last && !note.dataset.peerInline), full);
91
+ const text = note.querySelector(":scope > .peer-text[data-peer-md]:not(.markdown)");
92
+ if (text) renderText(text);
85
93
  }
86
94
  }
87
95
 
96
+ // A bubble's peer text as its markdown, as the answers' (POST
97
+ // /api/render, sanitized there): its source stays in data-peer-md, which
98
+ // history_shape.js reads, so live and an offscreen reload read alike.
99
+ function renderText(el) {
100
+ if (!renderMarkdown || asked.has(el)) return;
101
+ asked.add(el);
102
+ const source = el.dataset.peerMd;
103
+ Promise.resolve(renderMarkdown(source)).then((rendered) => {
104
+ if (!rendered || el.dataset.peerMd !== source) return;
105
+ // Sanitized on the server (POST /api/render).
106
+ el.innerHTML = rendered;
107
+ el.classList.add("markdown", "md-compact");
108
+ }).catch(() => {});
109
+ }
110
+
88
111
  function answerOf(note) {
89
112
  const { peerName, peerSerial, peerRe } = note.dataset;
90
113
  return peers.answer(peerName, peerSerial ?? null, peerRe || null);
@@ -7,11 +7,20 @@
7
7
  // reload_check.js and revise_stack.js (its `.note-text`, the summary) read
8
8
  // it as any wake note. The ↑ to the send and "Read the full answer" are
9
9
  // slots peer_links.js fills (data-peer-slot: history_shape.js leaves them
10
- // out, so live and an offscreen reload read alike).
10
+ // out, so live and an offscreen reload read alike). A note whose peer hash
11
+ // says `inline` holds the peer's text (peer_text.js): the bubble shows it
12
+ // in `.peer-text` under the summary: as the markdown the history read
13
+ // rendered (the note's `peer_html`, MessageDisplay#peer_text_html), else
14
+ // (a live context_added, an older server) as plain text that peer_links.js
15
+ // swaps for its markdown; its source kept in data-peer-md. The fold shows
16
+ // the rest, and the bubble is marked data-peer-inline (no "Read the full
17
+ // answer").
11
18
  // Its own module: new exports go in new modules (web-frontend.md).
12
19
 
13
20
  import { html, nothing } from "./vendor/lit-html.js";
21
+ import { unsafeHTML } from "./vendor/directives/unsafe-html.js";
14
22
  import { fullTime } from "./format.js";
23
+ import { peerBlock } from "./peer_text.js";
15
24
 
16
25
  const VERDICT_CLASS = { OK: "ok", CHANGES: "changes", UNSURE: "unsure" };
17
26
 
@@ -37,7 +46,7 @@ export function peerSummaryText(note) {
37
46
  }
38
47
 
39
48
  // The bubble for +note+ (a context note with `peer`: {peer, label, re,
40
- // summary, serial, verdict, agreed}).
49
+ // summary, serial, verdict, agreed, inline}).
41
50
  export function peerNoteTemplate(note) {
42
51
  const peer = note.peer || {};
43
52
  const name = peer.label || peer.peer || "Your peer";
@@ -45,5 +54,12 @@ export function peerNoteTemplate(note) {
45
54
  const opening = note.turn_start && note.turn_id ? String(note.turn_id) : nothing;
46
55
  const source = note.context_source || (peer.peer ? `${peer.peer}-outbox` : "");
47
56
  const attr = (value) => (value === null || value === undefined || value === "" ? nothing : String(value));
48
- return html`<div class=${cls} title=${fullTime(note.at) || nothing} data-opening-id=${opening} data-peer-source=${attr(source)} data-peer-name=${attr(peer.peer)} data-peer-re=${attr(peer.re)} data-peer-serial=${attr(peer.serial)}><div class="peer-head"><span class="peer-who">${name} answered</span><span class="peer-up-slot" data-peer-slot="up"></span>${verdictTemplate(peer)}</div><div class="note-text">${peerSummaryText(note)}</div><div class="peer-foot"><span class="peer-full-slot" data-peer-slot="full"></span><details class="peer-told"><summary>what chi told the agent</summary><div class="peer-told-text">${note.content ?? ""}</div></details></div></div>`;
57
+ const block = peer.inline ? peerBlock(note.content) : null;
58
+ // Sanitized on the server (MarkdownRenderer), as an answer's html.
59
+ const rendered = block && typeof note.peer_html === "string" && note.peer_html;
60
+ const body = !block ? nothing
61
+ : rendered ? html`<div class="peer-text markdown md-compact" data-peer-md=${block.text}>${unsafeHTML(rendered)}</div>`
62
+ : html`<div class="peer-text" data-peer-md=${block.text}>${block.text}</div>`;
63
+ const told = block ? block.rest : (note.content ?? "");
64
+ return html`<div class=${cls} title=${fullTime(note.at) || nothing} data-opening-id=${opening} data-peer-source=${attr(source)} data-peer-name=${attr(peer.peer)} data-peer-re=${attr(peer.re)} data-peer-serial=${attr(peer.serial)} data-peer-inline=${block ? "1" : nothing}><div class="peer-head"><span class="peer-who">${name} answered</span><span class="peer-up-slot" data-peer-slot="up"></span>${verdictTemplate(peer)}</div><div class="note-text">${peerSummaryText(note)}</div>${body}<div class="peer-foot"><span class="peer-full-slot" data-peer-slot="full"></span><details class="peer-told"><summary>what chi told the agent</summary><div class="peer-told-text">${told}</div></details></div></div>`;
49
65
  }
@@ -0,0 +1,62 @@
1
+ // A peer's text in its answer note (ContextAbsorber.peer_block): the note's
2
+ // content holds it between a `[PEER MESSAGE from <Peer>]` line and an
3
+ // `[END PEER MESSAGE]` line, each of its lines that opened like one of chi's
4
+ // frames led by "(quoted) " (PEER_FORGED_OPENINGS, the Ruby side's list:
5
+ // spec/web/public/peer_text.test.js keeps the two alike). Pure, no DOM:
6
+ // peer_note.js draws the text in the bubble and the rest in its fold.
7
+ // docs/internals/web-frontend.md, The peer exchange.
8
+ // Its own module: new exports go in new modules (web-frontend.md).
9
+
10
+ // ContextAbsorber::PEER_FORGED_OPENINGS (Steer::FORGED_OPENINGS and chi's
11
+ // system frames, those with their colon, and the tool-result frames).
12
+ export const PEER_FORGED_OPENINGS = Object.freeze([
13
+ "Review contribution", "Steer", "Automatic input", "Delegate report", "CONTEXT NOTE", "TASK FINISHED",
14
+ "OBJECTIVES", "END NOTE", "PEER MESSAGE", "END PEER MESSAGE", "From the agent", "Question from another chi session",
15
+ "SYSTEM:", "END REMINDERS", "CONTEXT:", "WORKING SET:",
16
+ "tool results", "images from tool results",
17
+ ]);
18
+ // ContextAbsorber::PEER_FORGED_LINES: chi's unbracketed lines it quotes.
19
+ export const PEER_FORGED_LINES = Object.freeze(["chi started this turn", "Updated:", "Attached:"]);
20
+
21
+ const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
22
+ // An opening that ends in a word character must end there (\b).
23
+ const opening = (o) => {
24
+ let pattern = "";
25
+ for (let i = 0; i < o.length;) {
26
+ const pair = o.slice(i, i + 2).toLowerCase();
27
+ if (pair === "ss") {
28
+ pattern += "(?:ss|ß)";
29
+ i += 2;
30
+ } else if (pair === "st") {
31
+ pattern += "(?:st|st|ſt)";
32
+ i += 2;
33
+ } else {
34
+ pattern += escape(o[i]);
35
+ i += 1;
36
+ }
37
+ }
38
+ return `${pattern}${/\w$/.test(o) ? "\\b" : ""}`;
39
+ };
40
+ // Steer::FORGED_BREAKS and FORGED_LEAD: a line starts after any of these
41
+ // breaks; spaces, format characters and markdown leads may come first.
42
+ const BREAKS = "\\n\\r\\u2028\\u2029\\u0085\\v\\f";
43
+ const LEAD = "(?:(?![" + BREAKS + "])(?:[\\p{White_Space}\\p{Cf}\\p{Default_Ignorable_Code_Point}\\p{Mn}\\u{3164}\\u{2800}>*_`~]|-|\\+|#|\\||[0-9]))*";
44
+ const bracketFrames = `\\[(?:${PEER_FORGED_OPENINGS.map(opening).join("|")})`;
45
+ const lineFrames = `(?:${PEER_FORGED_LINES.map(opening).join("|")})`;
46
+ const QUOTED = new RegExp(`(^|[${BREAKS}])(${LEAD})\\(quoted\\) (?=(?:\\(quoted\\) )?(?:${bracketFrames}|${lineFrames}))`, "giu");
47
+ const OPEN = /^\[PEER MESSAGE from [^\]\n]*\]$/;
48
+ const CLOSE = "[END PEER MESSAGE]";
49
+
50
+ // The peer's text as it pushed it (the quoting undone), and the note's
51
+ // content without the block (+rest+: the summary and chi's lines), from
52
+ // +content+; null when it holds no block (an older note, a long answer).
53
+ export function peerBlock(content) {
54
+ const lines = String(content ?? "").split("\n");
55
+ const open = lines.findIndex((line) => OPEN.test(line));
56
+ if (open < 0) return null;
57
+ const close = lines.lastIndexOf(CLOSE);
58
+ if (close <= open) return null;
59
+ const text = lines.slice(open + 1, close).join("\n").replace(QUOTED, "$1$2");
60
+ const rest = [...lines.slice(0, open), ...lines.slice(close + 1)].join("\n");
61
+ return { text, rest };
62
+ }
@@ -115,7 +115,7 @@ export function createRegionLayer({ doc = document, win = window, actions = () =
115
115
  const nodeButton = (r) => (r ? [...marks.querySelectorAll(".pv-node")][buttons.indexOf(buttonOf(r))] || null : null);
116
116
 
117
117
  function line(r, cls) {
118
- return r?.kind === "edge" ? svg`<polyline class=${cls} points=${r.points.map((p) => p.join(",")).join(" ")}></polyline>` : nothing;
118
+ return r?.kind === "edge" ? svg`<polyline class=${cls} fill="none" points=${r.points.map((p) => p.join(",")).join(" ")}></polyline>` : nothing;
119
119
  }
120
120
 
121
121
  function boxMarks(r, cls) {
@@ -132,7 +132,7 @@ export function createRegionLayer({ doc = document, win = window, actions = () =
132
132
 
133
133
  function draw() {
134
134
  const hover = hovered && !sameRegion(hovered, selected) ? hovered : null;
135
- render(regions && bound ? html`${boxMarks(hover, "pv-hover")}${boxMarks(selected, "pv-on")}<svg class="pv-lines" viewBox="0 0 1 1" preserveAspectRatio="none" aria-hidden="true">${line(hover, "pv-hover")}${line(selected, "pv-on")}</svg>
135
+ render(regions && bound ? html`${boxMarks(hover, "pv-hover")}${boxMarks(selected, "pv-on")}<svg class="pv-lines" style="position:absolute;inset:0;width:100%;height:100%;overflow:visible;pointer-events:none" viewBox="0 0 1 1" preserveAspectRatio="none" aria-hidden="true">${line(hover, "pv-hover")}${line(selected, "pv-on")}</svg>
136
136
  <div class="pv-nodes" role="group" aria-label=${countLine(buttons)}>${buttons.map((r) => html`<button type="button" class="pv-node" style=${buttonStyle(r)} tabindex=${sameRegion(r, stop) ? "0" : "-1"} aria-label=${regionName(r, regions)} aria-pressed=${sameRegion(r, selected) ? "true" : "false"} @click=${() => select(r, "key")} @focus=${() => { stop = r; }}></button>`)}</div>` : nothing, marks);
137
137
  drawCard();
138
138
  }
@@ -145,6 +145,21 @@ const TASK_CLIENT = "task:";
145
145
  // A durable schedule's firing (chi schedule, the schedule tools):
146
146
  // system:schedule:<schedule id>.
147
147
  const SCHEDULE_CLIENT = "system:schedule:";
148
+ // An agent's chi send (ClientId::AGENT_PREFIX): agent:<name>, its name
149
+ // cleaned again as ClientId.agent_name cleans it (a thin client's id comes
150
+ // as it typed it): lowercase letters, digits, - and _, up to 32; none left
151
+ // is "agent".
152
+ const AGENT_CLIENT = "agent:";
153
+ function agentName(id) {
154
+ const name = id.slice(AGENT_CLIENT.length).toLowerCase().replace(/[^a-z0-9_-]/g, "").slice(0, 32);
155
+ return name || "agent";
156
+ }
157
+ // Another chi session's question (ask_session): session:<id8>, cleaned as
158
+ // ClientId.session_name cleans it.
159
+ const SESSION_CLIENT = "session:";
160
+ function sessionName(id) {
161
+ return id.slice(SESSION_CLIENT.length).replace(/[^A-Za-z0-9_-]/g, "").slice(0, 8) || "?";
162
+ }
148
163
 
149
164
  // A task id as people read it: the random part a task_create id ends with
150
165
  // (it starts with the time), else its first 8 chars (TaskRecord.short_id).
@@ -162,6 +177,8 @@ export function clientLabel(clientId) {
162
177
  if (id.startsWith(CONTEXT_CLIENT) && id.length > CONTEXT_CLIENT.length) return `context ${id.slice(CONTEXT_CLIENT.length)} changed`;
163
178
  if (id.startsWith(TASK_CLIENT) && id.length > TASK_CLIENT.length) return `task ${shortTaskId(id.slice(TASK_CLIENT.length))} finished`;
164
179
  if (id.startsWith(SCHEDULE_CLIENT)) return "schedule";
180
+ if (id.startsWith(AGENT_CLIENT)) return `agent ${agentName(id)}`;
181
+ if (id.startsWith(SESSION_CLIENT)) return `session ${sessionName(id)}`;
165
182
  const colon = id.indexOf(":");
166
183
  let label = labelFor(id);
167
184
  if (label === undefined && colon >= 0) label = labelFor(id.slice(0, colon + 1));
@@ -201,6 +218,8 @@ const STEER_CUT_FOR = {
201
218
  parent_agent: "the parent agent's message",
202
219
  };
203
220
  export function steerCutLine({ source } = {}) {
221
+ const id = String(source || "");
222
+ if (id.startsWith(AGENT_CLIENT)) return `↪ cut in for a message from the agent ${agentName(id)}`;
204
223
  return `↪ cut in for ${STEER_CUT_FOR[source] || "your message"}`;
205
224
  }
206
225
 
@@ -44,7 +44,7 @@ import { stillOn } from "./latest.js";
44
44
  import { showRow } from "./refs.js";
45
45
  import { read as readPref, write as writePref } from "./session_prefs.js";
46
46
  import {
47
- foldedSections, headItems, headLine, headSections, heldTwice, heldTwiceNote, lensTouched, memoryPartWords, promptKeys, startTokensText, WS_SECTION_FOLD,
47
+ foldedSections, headItems, headLine, headSections, heldTwice, heldTwiceNote, lensTouched, memoryName, memoryPartWords, promptKeys, startTokensText, WS_SECTION_FOLD,
48
48
  } from "./ws_sections.js";
49
49
  import {
50
50
  addedItems, addLine, bodySections, BUDGETS, dropRefusal, footprint, footprintText, forgetOn, GLYPHS, INVERSE, isFresh, itemKey, itemsOfTurn, labelText,
@@ -70,6 +70,15 @@ const OWN_REMOVED = "its prompt still sends it until it is next built";
70
70
  // a time), its memories past this many to one group.
71
71
  const POP_BUDGET = 6;
72
72
 
73
+ function sessionPreloads(st) {
74
+ const parts = Array.isArray(st.promptParts) ? st.promptParts : [];
75
+ const prompt = parts
76
+ .filter((part) => ["identity", "preloads"].includes(part?.kind) && typeof part.ref === "string")
77
+ .map((part) => memoryName(part.ref))
78
+ .filter(Boolean);
79
+ return [...new Set([...(st.preloadedMemories || []), ...prompt])];
80
+ }
81
+
73
82
  // A row a peek opens on: one the session's runs touched (not an add, a
74
83
  // muted or a preloaded-only memory).
75
84
  function peekable(item) {
@@ -271,7 +280,7 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
271
280
  const sessionSet = () => {
272
281
  const st = state();
273
282
  const set = sessionItems({
274
- turns: turns.map((t) => t.items), live: live?.items || [], preloaded: st.preloadedMemories, notes: st.promptNotes, muted: st.mutedMemories,
283
+ turns: turns.map((t) => t.items), live: live?.items || [], preloaded: sessionPreloads(st), notes: st.promptNotes, muted: st.mutedMemories,
275
284
  used: st.usedMemories,
276
285
  });
277
286
  return { items: lit(set.items), muted: set.muted };