samagotchi 0.184.0 → 0.185.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 (108) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +45 -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 +1 -1
  7. data/docs/context.md +76 -10
  8. data/docs/guardrails.md +7 -2
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/block-renderers.md +4 -2
  11. data/docs/internals/bridge.md +6 -2
  12. data/docs/internals/llm-context-forget.md +6 -0
  13. data/docs/internals/participants.md +4 -1
  14. data/docs/internals/remote-sessions.md +3 -1
  15. data/docs/internals/session-lifecycle.md +1 -1
  16. data/docs/internals/web-frontend.md +23 -6
  17. data/docs/mcp-server.md +6 -2
  18. data/docs/scheduling.md +5 -0
  19. data/docs/sessions.md +12 -2
  20. data/docs/sub-agent.md +48 -3
  21. data/docs/thin-clients.md +9 -2
  22. data/lib/samagotchi/agent_caller.rb +97 -0
  23. data/lib/samagotchi/bridge.rb +7 -7
  24. data/lib/samagotchi/bundles/claude-peer/manifest.yml +14 -8
  25. data/lib/samagotchi/bundles/claude-peer/plugin.rb +3 -3
  26. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +49 -30
  27. data/lib/samagotchi/bundles/claude-peer/scripts/pair +2 -2
  28. data/lib/samagotchi/bundles/claude-peer/scripts/pair-remote +123 -0
  29. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +11 -3
  30. data/lib/samagotchi/bundles/codex-peer/manifest.yml +10 -8
  31. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  32. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +29 -8
  33. data/lib/samagotchi/bundles/codex-peer/scripts/pair +1 -1
  34. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +11 -3
  35. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  36. data/lib/samagotchi/bundles/mcp/http_client.rb +19 -2
  37. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  38. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/system/self_map.md +2 -0
  40. data/lib/samagotchi/client_id.rb +61 -1
  41. data/lib/samagotchi/command_intake.rb +16 -8
  42. data/lib/samagotchi/context_absorber.rb +212 -46
  43. data/lib/samagotchi/delivery.rb +15 -0
  44. data/lib/samagotchi/driver_command.rb +68 -0
  45. data/lib/samagotchi/engine/block_fix.rb +2 -2
  46. data/lib/samagotchi/engine.rb +13 -5
  47. data/lib/samagotchi/engine_peers.rb +6 -0
  48. data/lib/samagotchi/guardrails/pair_boundary.rb +1 -1
  49. data/lib/samagotchi/mcp_command.rb +7 -2
  50. data/lib/samagotchi/mcp_server/tools.rb +9 -3
  51. data/lib/samagotchi/objectives_track.rb +2 -1
  52. data/lib/samagotchi/owner_prompt.rb +5 -1
  53. data/lib/samagotchi/parent_report.rb +9 -5
  54. data/lib/samagotchi/plugin/peer.rb +10 -4
  55. data/lib/samagotchi/reply_wait.rb +12 -3
  56. data/lib/samagotchi/schedules.rb +10 -7
  57. data/lib/samagotchi/send_command/parent_gate.rb +3 -1
  58. data/lib/samagotchi/send_command.rb +45 -8
  59. data/lib/samagotchi/session.rb +9 -1
  60. data/lib/samagotchi/session_access/ask.rb +5 -2
  61. data/lib/samagotchi/session_access/contract.rb +2 -0
  62. data/lib/samagotchi/session_access/local.rb +2 -1
  63. data/lib/samagotchi/session_access/remote.rb +18 -2
  64. data/lib/samagotchi/session_access.rb +4 -2
  65. data/lib/samagotchi/session_command_catalog.rb +8 -0
  66. data/lib/samagotchi/session_commands.rb +9 -0
  67. data/lib/samagotchi/session_continue.rb +4 -1
  68. data/lib/samagotchi/session_inbox.rb +2 -0
  69. data/lib/samagotchi/session_inbox_delivery.rb +4 -2
  70. data/lib/samagotchi/session_manager/delivery.rb +50 -5
  71. data/lib/samagotchi/session_manager/spawn.rb +7 -1
  72. data/lib/samagotchi/steer.rb +95 -20
  73. data/lib/samagotchi/terminal_ui/formatting.rb +12 -2
  74. data/lib/samagotchi/tool_activity.rb +4 -0
  75. data/lib/samagotchi/tool_declarations.rb +22 -1
  76. data/lib/samagotchi/tool_names.rb +4 -0
  77. data/lib/samagotchi/toolkit.rb +3 -2
  78. data/lib/samagotchi/tools/ask_session.rb +208 -0
  79. data/lib/samagotchi/tools/builtin_calls.rb +1 -0
  80. data/lib/samagotchi/tools/builtins.rb +5 -0
  81. data/lib/samagotchi/turn_checkpoint.rb +19 -2
  82. data/lib/samagotchi/turn_stages/context_judge.rb +3 -1
  83. data/lib/samagotchi/turn_stages/objectives.rb +4 -2
  84. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +3 -0
  85. data/lib/samagotchi/version.rb +1 -1
  86. data/lib/samagotchi/visitor.rb +37 -0
  87. data/lib/samagotchi/web/app.rb +1 -1
  88. data/lib/samagotchi/web/ask_routes.rb +6 -4
  89. data/lib/samagotchi/web/message_display.rb +15 -2
  90. data/lib/samagotchi/web/public/app.js +1 -1
  91. data/lib/samagotchi/web/public/block_fix.js +11 -3
  92. data/lib/samagotchi/web/public/history_shape.js +3 -1
  93. data/lib/samagotchi/web/public/index.html +8 -0
  94. data/lib/samagotchi/web/public/peer_links.js +27 -4
  95. data/lib/samagotchi/web/public/peer_note.js +19 -3
  96. data/lib/samagotchi/web/public/peer_text.js +45 -0
  97. data/lib/samagotchi/web/public/picture_regions.js +2 -2
  98. data/lib/samagotchi/web/public/turn_events.js +19 -0
  99. data/lib/samagotchi/web/public/working_set_view.js +11 -2
  100. data/lib/samagotchi/web/session_control.rb +1 -1
  101. data/lib/samagotchi/web/session_create.rb +11 -7
  102. data/lib/samagotchi/worker/command_queue.rb +5 -2
  103. data/lib/samagotchi/worker/senders.rb +79 -0
  104. data/lib/samagotchi/worker.rb +21 -18
  105. data/lib/samagotchi/worker_inbound.rb +12 -4
  106. data/lib/samagotchi/worker_participant_gate.rb +1 -3
  107. data/lib/samagotchi/worker_wakes.rb +12 -0
  108. metadata +8 -1
@@ -8,6 +8,7 @@ require_relative "../objectives_audit"
8
8
  require_relative "../objectives_track"
9
9
  require_relative "../owner_prompt"
10
10
  require_relative "../system_one/client"
11
+ require_relative "../visitor"
11
12
 
12
13
  module Samagotchi
13
14
  module TurnStages
@@ -41,7 +42,8 @@ module Samagotchi
41
42
  # reminder's or a delegate's prompt isn't one.
42
43
  # @param recorder [SystemOne::Recorder] the audit's runs (built for this call)
43
44
  def incoming(turn, recorder:)
44
- return unless turn.prompt.is_a?(String) && turn.origin.human? && OwnerPrompt.turn?(author: turn.origin.author)
45
+ return unless turn.prompt.is_a?(String) && turn.origin.human? && OwnerPrompt.turn?(author: turn.origin.author) &&
46
+ !Visitor.of?(turn.origin.client_id, turn.session)
45
47
 
46
48
  audit(turn.context.state_dir, recorder).incoming(turn.session, turn.prompt)
47
49
  end
@@ -51,7 +53,7 @@ module Samagotchi
51
53
  # @param recorder [SystemOne::Recorder] the audit's runs (built for this
52
54
  # call: after a before_turn hook's model switch, the new model)
53
55
  def outgoing(turn, result, recorder:)
54
- return unless OwnerPrompt.turn?(author: turn.origin.author)
56
+ return unless OwnerPrompt.turn?(author: turn.origin.author) && !Visitor.of?(turn.origin.client_id, turn.session)
55
57
 
56
58
  audit(turn.context.state_dir, recorder).outgoing(turn.session, result.text)
57
59
  end
@@ -7,6 +7,7 @@ require_relative "../system_one/client"
7
7
  require_relative "../toolkit"
8
8
  require_relative "../toolkit_suggest"
9
9
  require_relative "../tools/tool_index"
10
+ require_relative "../visitor"
10
11
 
11
12
  module Samagotchi
12
13
  # The steps of a turn that keep state across its preparation, each a
@@ -162,6 +163,8 @@ module Samagotchi
162
163
  # read from disk) and the log (read whole) only when it gets there.
163
164
  kits = nil
164
165
  candidates = nil
166
+ # A visitor's prompt (Visitor) is not the owner's, as a participant's isn't.
167
+ return if Visitor.of?(turn.origin.client_id, session)
165
168
  return unless ToolkitSuggest.eligible?(
166
169
  session: session, prompt: turn.prompt, author: turn.origin.author,
167
170
  candidate_count: lambda {
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.184.0"
4
+ VERSION = "0.185.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "client_id"
4
+
5
+ module Samagotchi
6
+ # Whether a turn's sender is a visitor in a session: an agent's
7
+ # (agent:<name>) that is not the session's driver (Session#driver), or
8
+ # another chi session's question (session:<id8>, ask_session). A
9
+ # visitor's turn opens with one header line naming it (Steer::OPENER_HEADERS),
10
+ # counts toward session.max_wakes (Worker#run_prompt) and is not the
11
+ # owner's prompt (OwnerPrompt). The driver's turns are as chi send's
12
+ # were. No Engine: the Worker and the turn stages both ask it.
13
+ module Visitor
14
+ # The refused visitor turn's cancel_reason (TurnCheckpoint.record_refused):
15
+ # a code, whose sentence is ParentReport::REFUSED_LINES'.
16
+ CAP_REASON = "max_wakes"
17
+
18
+ module_function
19
+
20
+ # @param session [Session, nil] the session the turn runs in
21
+ def of?(client_id, session)
22
+ return true if ClientId.session?(client_id)
23
+
24
+ ClientId.agent?(client_id) && client_id.to_s != driver_of(session)
25
+ end
26
+
27
+ # Whether +client_id+ is the session's driver.
28
+ def driver?(client_id, session)
29
+ ClientId.agent?(client_id) && client_id.to_s == driver_of(session)
30
+ end
31
+
32
+ def driver_of(session)
33
+ session.respond_to?(:driver) ? session.driver.to_s : ""
34
+ end
35
+ private_class_method :driver_of
36
+ end
37
+ end
@@ -1126,7 +1126,7 @@ module Samagotchi
1126
1126
  # delegates: chi --remote sessions delete --dry-run asks for this first.
1127
1127
  DELETE_PLAN_FEATURE = "delete_plan_all"
1128
1128
  INFO_FEATURES = ["dir", "newest_workers", SessionAccessRoutes::FEATURE, SessionAccessRoutes::ATTACH_FEATURE,
1129
- BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE, DELETE_PLAN_FEATURE, ASK_FEATURE, McpRoute::FEATURE].freeze
1129
+ BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE, DELETE_PLAN_FEATURE, ASK_FEATURE, McpRoute::FEATURE, Delivery::AGENT_FEATURE].freeze
1130
1130
 
1131
1131
  # The models a new session can start on, spelled as chi spells them
1132
1132
  # elsewhere: bare for the default host (what default.model holds), and
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "delegate"
4
4
  require_relative "../bridge_client"
5
+ require_relative "../agent_caller"
5
6
  require_relative "../client_id"
6
7
  require_relative "../reply_wait"
7
8
  require_relative "../session"
@@ -174,11 +175,12 @@ module Samagotchi
174
175
 
175
176
  # Who asks: the owner (WEB_UNNAMED) unless the body names a sender
176
177
  # (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).
178
+ # cli:send or an agent's id (ClientId.parent_line?) goes in as
179
+ # cli:answer, as chi send sends it (the worker holds that one to
180
+ # guardrails.parent_answers).
179
181
  def ask_sender(client_id, prompt)
180
182
  sender = owner_sender({ "client_id" => client_id })
181
- sender == ClientId::CLI_SEND && TurnFlow.continue_yes?(prompt) ? ClientId::CLI_ANSWER : sender
183
+ TurnFlow.continue_yes?(prompt) ? AgentCaller.continue_id(sender) : sender
182
184
  end
183
185
 
184
186
  # A parent agent's line refused before anything is sent, as POST
@@ -186,7 +188,7 @@ module Samagotchi
186
188
  # session asked and of its chain's newest link (where it goes).
187
189
  # @return [Array, nil] the response, or nil to go on
188
190
  def ask_gate(id, prompt, client_id)
189
- return nil unless App::CLI_SEND_IDS.include?(client_id)
191
+ return nil unless ClientId.parent_line?(client_id)
190
192
 
191
193
  asked = session_access.resolve(id)
192
194
  ids = [asked, session_access.head(asked).id].uniq
@@ -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
@@ -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,45 @@
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"]);
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) => `${escape(o)}${/\w$/.test(o) ? "\\b" : ""}`;
24
+ // Steer::FORGED_BREAKS and FORGED_LEAD: a line starts after any of these
25
+ // breaks; spaces, format characters and markdown leads may come first.
26
+ const BREAKS = "\\n\\r\\u2028\\u2029\\u0085\\v\\f";
27
+ const LEAD = `(?:(?![${BREAKS}])[\\p{White_Space}\\p{Cf}>*_\`~])*`;
28
+ const QUOTED = new RegExp(`(^|[${BREAKS}])(${LEAD})\\(quoted\\) (?=\\[(?:${PEER_FORGED_OPENINGS.map(opening).join("|")})`
29
+ + `${PEER_FORGED_LINES.map((line) => `|${opening(line)}`).join("")})`, "giu");
30
+ const OPEN = /^\[PEER MESSAGE from [^\]\n]*\]$/;
31
+ const CLOSE = "[END PEER MESSAGE]";
32
+
33
+ // The peer's text as it pushed it (the quoting undone), and the note's
34
+ // content without the block (+rest+: the summary and chi's lines), from
35
+ // +content+; null when it holds no block (an older note, a long answer).
36
+ export function peerBlock(content) {
37
+ const lines = String(content ?? "").split("\n");
38
+ const open = lines.findIndex((line) => OPEN.test(line));
39
+ if (open < 0) return null;
40
+ const close = lines.lastIndexOf(CLOSE);
41
+ if (close <= open) return null;
42
+ const text = lines.slice(open + 1, close).join("\n").replace(QUOTED, "$1$2");
43
+ const rest = [...lines.slice(0, open), ...lines.slice(close + 1)].join("\n");
44
+ return { text, rest };
45
+ }
@@ -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 };
@@ -266,7 +266,7 @@ module Samagotchi
266
266
  # @return [Array, nil] the response, or nil to go on
267
267
  def turn_refusal(id, body, prompt, images)
268
268
  vision = body["check_vision"] == true && !images.empty?
269
- return nil unless vision || App::CLI_SEND_IDS.include?(body["client_id"])
269
+ return nil unless vision || ClientId.parent_line?(body["client_id"])
270
270
 
271
271
  session = @session_class.load(id, state_dir: default_state_dir)
272
272
  refused = parent_gate(prompt, client_id: body["client_id"], values: [session.parent_answers])
@@ -34,10 +34,6 @@ module Samagotchi
34
34
  # What a continue takes from the previous link: refused beside it.
35
35
  CONTINUE_TAKES = %w[dir llm_context thinking settings toolkit tools no_tools parent_answers].freeze
36
36
 
37
- # chi send's client ids: its lines are checked as chi send checks them
38
- # (#parent_gate).
39
- CLI_SEND_IDS = [ClientId::CLI_SEND, ClientId::CLI_ANSWER].freeze
40
-
41
37
  private
42
38
 
43
39
  def handle_create(req)
@@ -91,11 +87,19 @@ module Samagotchi
91
87
  parent_answers, error = request_parent_answers(body["parent_answers"])
92
88
  return error if error
93
89
 
90
+ # driver: the agent (agent:<name>) the owner names its driver (chi
91
+ # send --new --driver); none: its creator when that is an agent.
92
+ driver = body["driver"]
93
+ unless driver.nil? || (ClientId.agent?(driver) && ClientId.agent(ClientId.agent_name(driver)) == driver)
94
+ return error_response(400, "invalid_driver", "driver is an agent's id: agent:<name>")
95
+ end
96
+
94
97
  model = (body["model"] || body["model_name"]).to_s.strip
95
98
  refused = create_refusal(body, idle ? body["preview"] : prompt, values: [parent_answers], model: model)
96
99
  return refused if refused
97
100
 
98
101
  folder = { working_directory: dir || start_dir }
102
+ folder[:driver] = driver if driver
99
103
  # model: the model the session starts on (the start page's picker,
100
104
  # spelled as GET /api/models lists it); blank means the default.
101
105
  folder[:model_name] = model unless model.empty?
@@ -178,7 +182,7 @@ module Samagotchi
178
182
  # for #create_refusal; nil when the previous link isn't there
179
183
  # (continue_from says so).
180
184
  def continue_refusal(given, body, line, model:)
181
- return nil unless body["check_vision"] == true || CLI_SEND_IDS.include?(body["client_id"])
185
+ return nil unless body["check_vision"] == true || ClientId.parent_line?(body["client_id"])
182
186
 
183
187
  previous = Session.load(SessionChain.resolve(given, state_dir: default_state_dir), state_dir: default_state_dir)
184
188
  create_refusal(body, line, values: [previous.parent_answers], model: model, previous: previous)
@@ -220,9 +224,9 @@ module Samagotchi
220
224
  # @return [Array, nil] the response, or nil to go on
221
225
  def parent_gate(line, client_id:, values:)
222
226
  line = line.to_s
223
- return nil unless CLI_SEND_IDS.include?(client_id)
227
+ return nil unless ClientId.parent_line?(client_id)
224
228
 
225
- if client_id == ClientId::CLI_ANSWER && TurnFlow.continue_yes?(line) &&
229
+ if (client_id == ClientId::CLI_ANSWER || ClientId.agent?(client_id)) && TurnFlow.continue_yes?(line) &&
226
230
  (refusal = SendCommand::ParentGate.continue_refusal_for(values))
227
231
  return error_response(403, "parent_continue_refused", refusal)
228
232
  end
@@ -218,9 +218,12 @@ module Samagotchi
218
218
  def confirm?(command) = ClientId.interactive?(command.client_id) && !command.card
219
219
 
220
220
  # Whether +command+ is a parent agent's (chi answer's marker, which chi
221
- # send and a parent's attach give a /continue yes too): held to
221
+ # send and a parent's attach give a /continue yes too, or an agent's
222
+ # id that reached the worker unmapped): held to
222
223
  # guardrails.parent_answers (SessionCommands#continue_answer).
223
- def as_parent?(command) = command.client_id.to_s == ClientId::CLI_ANSWER
224
+ def as_parent?(command)
225
+ command.client_id.to_s == ClientId::CLI_ANSWER || ClientId.agent?(command.client_id)
226
+ end
224
227
 
225
228
  # Whether +command+ is a user's at a UI (a web tab, a chi TUI, a card's
226
229
  # click), not a parent agent's: only such a line loosens