samagotchi 0.121.1 → 0.123.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 (107) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +67 -1
  3. data/bin/chi +4 -1
  4. data/docs/architecture.md +19 -7
  5. data/docs/cli.md +32 -1
  6. data/docs/configuration.md +55 -5
  7. data/docs/guardrails.md +119 -7
  8. data/docs/internals/engine.md +11 -2
  9. data/docs/internals/participants.md +76 -20
  10. data/docs/internals/prompt-caching.md +19 -7
  11. data/docs/internals/web-push.md +7 -3
  12. data/docs/memory.md +33 -0
  13. data/docs/plugins.md +3 -2
  14. data/docs/sessions.md +14 -4
  15. data/lib/samagotchi/bridge/turn_accumulator.rb +3 -1
  16. data/lib/samagotchi/bridge.rb +8 -4
  17. data/lib/samagotchi/bridge_client/event_stream.rb +5 -1
  18. data/lib/samagotchi/bridge_client/stream_open.rb +8 -2
  19. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  20. data/lib/samagotchi/bundles/system/memory_guide.md +13 -0
  21. data/lib/samagotchi/config.rb +11 -0
  22. data/lib/samagotchi/delivery.rb +7 -0
  23. data/lib/samagotchi/engine.rb +289 -12
  24. data/lib/samagotchi/event_fanout.rb +0 -1
  25. data/lib/samagotchi/gem_update.rb +41 -4
  26. data/lib/samagotchi/guardrail_wiring.rb +46 -12
  27. data/lib/samagotchi/guardrails/approval.rb +42 -4
  28. data/lib/samagotchi/guardrails/gate.rb +1 -1
  29. data/lib/samagotchi/guardrails/pair_boundary.rb +172 -0
  30. data/lib/samagotchi/guardrails/pair_command.rb +365 -0
  31. data/lib/samagotchi/guardrails/review_paths.rb +41 -7
  32. data/lib/samagotchi/guardrails/shell_lex.rb +7 -5
  33. data/lib/samagotchi/guardrails/shell_paths.rb +10 -1
  34. data/lib/samagotchi/guardrails/verdict.rb +7 -0
  35. data/lib/samagotchi/guardrails.rb +1 -0
  36. data/lib/samagotchi/guardrails_command.rb +6 -1
  37. data/lib/samagotchi/kernel_loop.rb +20 -0
  38. data/lib/samagotchi/llm/chat_loop.rb +4 -0
  39. data/lib/samagotchi/log_line.rb +1 -1
  40. data/lib/samagotchi/memory_orphans.rb +11 -0
  41. data/lib/samagotchi/participant_mode.rb +85 -0
  42. data/lib/samagotchi/participants.rb +7 -5
  43. data/lib/samagotchi/plugin/api.rb +7 -4
  44. data/lib/samagotchi/process_group.rb +13 -0
  45. data/lib/samagotchi/review_apply.rb +10 -2
  46. data/lib/samagotchi/review_start.rb +42 -10
  47. data/lib/samagotchi/run_options.rb +1 -0
  48. data/lib/samagotchi/session.rb +14 -1
  49. data/lib/samagotchi/session_access/contract.rb +1 -1
  50. data/lib/samagotchi/session_access/local.rb +5 -2
  51. data/lib/samagotchi/session_access/remote.rb +32 -12
  52. data/lib/samagotchi/session_access/web_bridge_client.rb +9 -2
  53. data/lib/samagotchi/session_manager.rb +21 -7
  54. data/lib/samagotchi/session_participants.rb +18 -3
  55. data/lib/samagotchi/session_setup.rb +8 -4
  56. data/lib/samagotchi/sessions_command.rb +1 -1
  57. data/lib/samagotchi/share_command.rb +2 -2
  58. data/lib/samagotchi/steer.rb +13 -6
  59. data/lib/samagotchi/system_one/client.rb +16 -7
  60. data/lib/samagotchi/system_one/log.rb +25 -5
  61. data/lib/samagotchi/system_prompt.rb +20 -4
  62. data/lib/samagotchi/terminal_ui/question_prompt.rb +17 -1
  63. data/lib/samagotchi/terminal_ui.rb +2 -1
  64. data/lib/samagotchi/tool_runner.rb +11 -1
  65. data/lib/samagotchi/toolkit.rb +27 -8
  66. data/lib/samagotchi/toolkit_binding.rb +149 -7
  67. data/lib/samagotchi/toolkit_command.rb +15 -3
  68. data/lib/samagotchi/toolkit_report_command.rb +320 -0
  69. data/lib/samagotchi/toolkit_suggest.rb +377 -0
  70. data/lib/samagotchi/tools/builtins.rb +14 -1
  71. data/lib/samagotchi/tools/memory.rb +1 -1
  72. data/lib/samagotchi/update_command.rb +7 -6
  73. data/lib/samagotchi/version.rb +1 -1
  74. data/lib/samagotchi/web/app.rb +12 -13
  75. data/lib/samagotchi/web/grants.rb +17 -5
  76. data/lib/samagotchi/web/message_display.rb +6 -1
  77. data/lib/samagotchi/web/participant_access.rb +4 -1
  78. data/lib/samagotchi/web/participant_review.rb +8 -4
  79. data/lib/samagotchi/web/participant_view.rb +12 -4
  80. data/lib/samagotchi/web/participants_admin.rb +10 -6
  81. data/lib/samagotchi/web/principal.rb +3 -4
  82. data/lib/samagotchi/web/public/app.js +34 -10
  83. data/lib/samagotchi/web/public/bubbles.js +3 -2
  84. data/lib/samagotchi/web/public/delivery_line.js +8 -6
  85. data/lib/samagotchi/web/public/participant.html +1 -1
  86. data/lib/samagotchi/web/public/participant.js +12 -13
  87. data/lib/samagotchi/web/public/participant_model.js +20 -8
  88. data/lib/samagotchi/web/public/participant_names.js +29 -8
  89. data/lib/samagotchi/web/public/participants_panel.js +17 -3
  90. data/lib/samagotchi/web/public/question_card.js +12 -2
  91. data/lib/samagotchi/web/public/question_cards.js +7 -0
  92. data/lib/samagotchi/web/public/stream_handlers.js +6 -2
  93. data/lib/samagotchi/web/public/tools_overview.js +42 -0
  94. data/lib/samagotchi/web/public/turn_events.js +7 -5
  95. data/lib/samagotchi/web/public/turn_html.js +2 -2
  96. data/lib/samagotchi/web/public/turn_view.js +6 -4
  97. data/lib/samagotchi/web/public/update_notice.js +31 -2
  98. data/lib/samagotchi/web/push/notifier.rb +28 -1
  99. data/lib/samagotchi/web/server.rb +7 -3
  100. data/lib/samagotchi/web/session_access_routes.rb +5 -4
  101. data/lib/samagotchi/web/session_control.rb +4 -2
  102. data/lib/samagotchi/web/session_hub.rb +24 -3
  103. data/lib/samagotchi/web/start_dir.rb +10 -5
  104. data/lib/samagotchi/web/update_check.rb +179 -0
  105. data/lib/samagotchi/worker.rb +60 -8
  106. data/lib/samagotchi/worker_link.rb +1 -0
  107. metadata +8 -1
@@ -6,6 +6,7 @@ require_relative "participant_exposure"
6
6
  require_relative "../session_metrics"
7
7
  require_relative "../review_start"
8
8
  require_relative "../guardrails/review_paths"
9
+ require_relative "../participant_mode"
9
10
 
10
11
  module Samagotchi
11
12
  module Web
@@ -49,6 +50,7 @@ module Samagotchi
49
50
  # current_turn, waiting_for_owner, queued: {mine, others}, last_event_id}
50
51
  def handle_review(req, id)
51
52
  session = @session_class.load(id, state_dir: default_state_dir)
53
+ mode = ParticipantMode.live(session, state_dir: default_state_dir).to_s
52
54
  viewer = participant_viewer(req, session)
53
55
  live = bridge_get_json(id, "snapshot")
54
56
  turn_snapshot = live && live["snapshot"]
@@ -63,7 +65,7 @@ module Samagotchi
63
65
  status = displayed_status(session, state)
64
66
  status = Session::STATUS_IDLE if status == Session::STATUS_RUNNING && current.nil?
65
67
  json_response(200, {
66
- viewer: review_viewer(req, id, session: session, state: state, queued: queued, viewer: viewer),
68
+ viewer: review_viewer(req, id, session: session, state: state, queued: queued, viewer: viewer, mode: mode),
67
69
  session: { id: session.id, title: participant_title(session), status: status },
68
70
  subjects: review_subjects(session, viewer),
69
71
  participants: participant_names(id).map { |entry| entry.slice(:id, :name, :kind) },
@@ -149,12 +151,14 @@ module Samagotchi
149
151
  # participant view (no composer, no usage: the owner has /stats).
150
152
  # +state+ the live worker's session state (nil without one), +queued+
151
153
  # its queue.
152
- def review_viewer(req, id, session:, state:, queued:, viewer:)
153
- return { kind: "owner", can_comment: false } if principal(req).owner?
154
+ def review_viewer(req, id, session:, state:, queued:, viewer:, mode:)
155
+ return { kind: "owner", can_comment: false, mode: mode } if principal(req).owner?
154
156
 
155
157
  grant = principal(req).grant
156
158
  capped = !participant_cap_refusal(grant).nil?
157
- { kind: "participant", id: grant.id, name: grant.name, participant_kind: grant.kind, can_comment: !capped,
159
+ # Theirs: pair only when their grant was issued to act (ParticipantMode.live_for).
160
+ mode = ParticipantMode.live_for(session, grant, state_dir: default_state_dir).to_s
161
+ { kind: "participant", id: grant.id, name: grant.name, participant_kind: grant.kind, mode: mode, can_comment: !capped,
158
162
  cap_reached: capped, session_id: id,
159
163
  usage: review_usage(grant, session: session, state: state, queued: queued, viewer: viewer) }
160
164
  end
@@ -3,6 +3,7 @@
3
3
  require_relative "../output_formatter"
4
4
  require_relative "../steer"
5
5
  require_relative "../turn_origin"
6
+ require_relative "../participant_mode"
6
7
 
7
8
  module Samagotchi
8
9
  module Web
@@ -36,6 +37,9 @@ module Samagotchi
36
37
  def own?(author) = !self.author.nil? && author.to_s == self.author
37
38
  end
38
39
 
40
+ # A turn's participant_mode values the view passes on (ParticipantMode).
41
+ PARTICIPANT_MODES = [ParticipantMode::REVIEW.to_s, ParticipantMode::PAIR.to_s].freeze
42
+
39
43
  # The stream's event types a participant gets, each rebuilt by the
40
44
  # method named. Every other type is dropped.
41
45
  EVENTS = {
@@ -109,7 +113,7 @@ module Samagotchi
109
113
  origin = TurnOrigin.of(field(event, :origin))
110
114
  author = field(event, :author) || origin.author
111
115
  out = { "type" => "turn_started", **id_fields(event), **time_field(event) }
112
- out.merge!(author_fields(author, field(event, :author_name), viewer))
116
+ out.merge!(author_fields(author, field(event, :author_name), viewer, field(event, :participant_mode)))
113
117
  prompt = field(event, :prompt)
114
118
  if field(event, :continue)
115
119
  out["continue"] = true
@@ -202,7 +206,8 @@ module Samagotchi
202
206
  out["content"] = field(message, :content).to_s
203
207
  out["turn_id"] = turn_id.to_s if turn_id
204
208
  out["merged"] = true if merged
205
- out.merge!(author_fields(field(message, :author), field(message, :author_name), viewer))
209
+ out.merge!(author_fields(field(message, :author), field(message, :author_name), viewer,
210
+ field(message, :participant_mode)))
206
211
  images = field(message, :images)
207
212
  out["images"] = images.size if images.is_a?(Array) && !images.empty?
208
213
  out
@@ -277,12 +282,15 @@ module Samagotchi
277
282
  end
278
283
 
279
284
  # A turn's author as a participant sees it: the participant's id and
280
- # name, or none for the owner's; +mine+ for the viewer's own.
281
- def author_fields(author, name, viewer)
285
+ # name, or none for the owner's; +mine+ for the viewer's own; the
286
+ # turn's +mode+ (its participant_mode stamp: review or pair) when
287
+ # it has one.
288
+ def author_fields(author, name, viewer, mode = nil)
282
289
  return {} unless Steer.participant_author?(author)
283
290
 
284
291
  out = { "author" => author.to_s }
285
292
  out["author_name"] = name.to_s if name.is_a?(String) && !name.empty?
293
+ out["participant_mode"] = mode.to_s if PARTICIPANT_MODES.include?(mode.to_s)
286
294
  out["mine"] = true if viewer.own?(author)
287
295
  out
288
296
  end
@@ -24,14 +24,16 @@ module Samagotchi
24
24
  # for a session that isn't a review session (ReviewStart.share_warning,
25
25
  # null for one), which the panel shows before its Invite; and
26
26
  # +identity_header+: the header this chi web's auth proxy names the
27
- # signed-in user in (null without one), for the Invite's email field.
27
+ # signed-in user in (null without one), for the Invite's email field;
28
+ # +mode+: what a participant invited now gets, "pair" or "review"
29
+ # (ReviewStart.share_terms), for the panel's words.
28
30
  def handle_participants_list(_req, id = nil)
29
31
  now = @grants.now
30
32
  grants = @grants.list(session_id: id).map { |grant| grant.public_h(now) }
31
33
  return json_response(200, { participants: grants }) unless id
32
34
 
33
- warning = ReviewStart.share_warning(Session.load(id, state_dir: default_state_dir))
34
- json_response(200, { participants: with_spend(id, grants), warning: warning,
35
+ terms = ReviewStart.share_terms(Session.load(id, state_dir: default_state_dir), state_dir: default_state_dir)
36
+ json_response(200, { participants: with_spend(id, grants), warning: terms.warning, mode: terms.mode.to_s,
35
37
  identity_header: @public_url&.identity_header })
36
38
  rescue Grants::Unwritable => e
37
39
  grants_unwritable(e)
@@ -67,13 +69,15 @@ module Samagotchi
67
69
  cap = body["cap"]
68
70
  return error_response(400, "invalid_participant", Grants::CAP_RANGE) unless cap.nil? || Grants.cap?(cap)
69
71
 
72
+ # The grant is stamped pair only when the warning that comes back says
73
+ # their turns act (one read: ReviewStart.share_terms).
74
+ terms = ReviewStart.share_terms(Session.load(id, state_dir: default_state_dir), state_dir: default_state_dir)
70
75
  issued = Participants.invite(@grants, session_id: id, name: body["name"], kind: (body["kind"] || "human").to_s,
71
76
  ttl: ttl, cap: cap, identity: body["identity"], public_url: @public_url,
72
- state_dir: default_state_dir)
77
+ mode: terms.grant_mode, state_dir: default_state_dir)
73
78
  link = participant_link(req, id, issued.token, expires_at: issued.grant.expires_at)
74
- warning = ReviewStart.share_warning(Session.load(id, state_dir: default_state_dir))
75
79
  json_response(201, { participant: issued.grant.public_h(@grants.now), token: issued.token,
76
- link: link, lan: !@lan.nil? || !@public_url.nil?, qr_svg: QR.svg(link), warning: warning })
80
+ link: link, lan: !@lan.nil? || !@public_url.nil?, qr_svg: QR.svg(link), warning: terms.warning })
77
81
  rescue Grants::Invalid => e
78
82
  error_response(400, "invalid_participant", e.message)
79
83
  rescue Grants::Unwritable => e
@@ -2,14 +2,13 @@
2
2
 
3
3
  module Samagotchi
4
4
  module Web
5
- # Who a chi web request is (App#principal_for). Today there is one
6
- # kind: the owner, a peer on this machine or a request with the
7
- # Web::Token access token. The routes' permission column
5
+ # Who a chi web request is (App#principal_for): the owner or a
6
+ # participant admitted by a grant. The routes' permission column
8
7
  # (App::ROUTES, :owner or :participant) is checked against it, and a
9
8
  # turn's author comes from it, never from the request body. See
10
9
  # docs/internals/remote-sessions.md (Trust model).
11
10
  #
12
- # +kind+ :owner; +grant+ what a non-owner principal was admitted by
11
+ # +kind+ :owner or :participant; +grant+ what admitted a participant
13
12
  # (nil for the owner).
14
13
  Principal = Data.define(:kind, :grant) do
15
14
  def owner? = kind == :owner
@@ -68,7 +68,7 @@ import { readStored, writeStored } from "./storage.js";
68
68
  import { createCommandList } from "./command_list.js";
69
69
  import { ALL_SESSIONS_HASH, sessionHash, sessionIdFromHash } from "./route.js";
70
70
  import { scopeDir, scopeTemplate } from "./scope.js";
71
- import { render } from "./vendor/lit-html.js";
71
+ import { html, render } from "./vendor/lit-html.js";
72
72
  import { shouldFollowScroll } from "./scroll.js";
73
73
  import { SHORT_WINDOW_QUERY, stripAutoHidden } from "./strip.js";
74
74
  import { createStripGrip } from "./strip_grip.js";
@@ -76,7 +76,7 @@ import { waitingOn } from "./notify.js";
76
76
  import { applySessionEvent, sortedByUpdated } from "./sessions_list.js";
77
77
  import { createNotifications } from "./notifications.js";
78
78
  import { renameShown, tabTitle, topBarTitle } from "./session_title.js";
79
- import { restartConfirmText, versionNotice } from "./update_notice.js";
79
+ import { mergeVersionState, restartConfirmText, versionNotice } from "./update_notice.js";
80
80
  import {
81
81
  appendAboveLiveTiming, mergeTiming, normalizeTiming,
82
82
  } from "./timing.js";
@@ -489,25 +489,49 @@ function openSessionEvents() {
489
489
 
490
490
  const EVENTS_REOPEN_MS = 3000;
491
491
 
492
- // Which chi serves this page now and which is the newest installed (the
493
- // events snapshot, and `chi` frames when that changes). A toast says when
494
- // chi web was upgraded while this tab stayed open (offering the reload,
495
- // never forcing it) or when a newer chi is installed than chi web runs.
492
+ // The chi versions carried by each event snapshot and `chi` frame. A toast
493
+ // says when chi web was upgraded, a newer one is installed, or an aged one
494
+ // is available to update to.
496
495
  // Once per notice per tab: every reconnect's snapshot says it again.
497
496
  const versions = { served: null, installed: null };
498
497
  // The sessions whose Restart is under way (their button says so): one
499
498
  // session's restart never blocks another's.
500
499
  const restartingIds = new Set();
500
+ // An available release's notice is once per version per browser, not per
501
+ // tab: chi web says it in every snapshot until the owner updates.
502
+ const AVAILABLE_SHOWN_KEY = "chi_update_available_shown";
501
503
  const versionNoticesShown = new Set();
504
+ const availableShown = readStored(AVAILABLE_SHOWN_KEY);
505
+ if (availableShown) versionNoticesShown.add(`available:${availableShown}`);
502
506
  function noticeVersions(data) {
503
- if (typeof data.version === "string") versions.served = data.version;
504
- versions.installed = typeof data.installed === "string" ? data.installed : null;
507
+ Object.assign(versions, mergeVersionState(versions, data));
505
508
  const notice = versionNotice({ loaded: document.body.dataset.version, served: versions.served,
506
- installed: versions.installed, shown: versionNoticesShown });
509
+ installed: versions.installed, available: versions.available,
510
+ updateBlocked: versions.updateBlocked, shown: versionNoticesShown });
507
511
  updateInfoBar(); // the worker badge compares with the newest installed
508
512
  if (!notice) return;
509
513
  versionNoticesShown.add(notice.key);
510
- showToast(notice.text, notice.reload ? { label: "Reload", run: () => location.reload() } : null, { sticky: true });
514
+ if (notice.key.startsWith("available:")) writeStored(AVAILABLE_SHOWN_KEY, notice.key.slice("available:".length));
515
+ const text = notice.releaseUrl
516
+ ? html`${notice.text} <a href=${notice.releaseUrl} target="_blank" rel="noopener noreferrer">RubyGems</a>`
517
+ : notice.text;
518
+ const action = notice.reload
519
+ ? { label: "Reload", run: () => location.reload() }
520
+ : notice.command
521
+ ? { label: "Copy", run: () => copyUpdateCommand(notice.command) }
522
+ : null;
523
+ showToast(text, action, { sticky: true });
524
+ }
525
+
526
+ function copyUpdateCommand(command) {
527
+ if (!navigator.clipboard?.writeText) {
528
+ showToast(`Clipboard unavailable; run ${command}`);
529
+ return;
530
+ }
531
+ navigator.clipboard.writeText(command).then(
532
+ () => showToast(`Copied ${command}`),
533
+ () => showToast(`Couldn't copy ${command}`),
534
+ );
511
535
  }
512
536
 
513
537
  // The selected session's card changed: its owner and, without a live
@@ -160,9 +160,9 @@ export function createBubbles({
160
160
  // The bubble a reload draws (turn_html.js), with this page's own fields.
161
161
  // +delivery+: how it went into a running turn (next_step, cut, queue): its
162
162
  // queued badge says what it waits for.
163
- function makeUserBubble(prompt, { state = null, label = null, enqueuedId = null, own = false, images = null, delivery = null, author = null } = {}) {
163
+ function makeUserBubble(prompt, { state = null, label = null, enqueuedId = null, own = false, images = null, delivery = null, author = null, turnId = null } = {}) {
164
164
  removeHint();
165
- const div = elementOf(userBubbleTemplate({ content: prompt }, {
165
+ const div = elementOf(userBubbleTemplate({ content: prompt, turn_id: turnId }, {
166
166
  label, state, own, enqueuedId, delivery, author, key: normalize(prompt), thumbs: thumbsTemplate(selected(), images),
167
167
  }));
168
168
  return placeFollowing(div);
@@ -224,6 +224,7 @@ export function createBubbles({
224
224
  else liveTurn.unmatchedMerge = true;
225
225
  }
226
226
  }
227
+ if (started && event.type === "turn_started" && event.turn_id) started.dataset.turnId = event.turn_id;
227
228
  return started;
228
229
  }
229
230
 
@@ -20,9 +20,10 @@
20
20
  // read-only review turn): while the composer holds it (hold(), till it is
21
21
  // sent, emptied or Esc'd) Enter queues it, and the line says so.
22
22
  //
23
- // While a participant's review turn runs, the worker queues the owner's
24
- // input behind it whatever it asks (never a steer or a cut into a
25
- // read-only turn): Enter queues, no cut is offered, and the line says so.
23
+ // While a participant's turn runs (a review turn, or a working session's
24
+ // pair turn), the worker queues the owner's input behind it whatever it
25
+ // asks (never a steer or a cut into their turn): Enter queues, no cut is
26
+ // offered, and the line says so.
26
27
  //
27
28
  // deliveryLine is pure (node tests); deliveryLineTemplate is its lit view.
28
29
  import { html, nothing, render } from "./vendor/lit-html.js";
@@ -41,9 +42,10 @@ export const APPLY_QUEUES = "your Apply turn queues for after this turn · Esc t
41
42
  export const APPLY_QUEUES_SHORT = "Apply: queued after the turn";
42
43
  // The same to a worker without the delivery feature: Enter refuses it.
43
44
  export const APPLY_CANT_QUEUE = "your Apply turn can't queue on this worker (restart it) · Esc to steer it in instead";
44
- // The line while a participant's review turn runs (the worker queues).
45
- export const PARTICIPANT_TURN_QUEUES = "goes in as your own turn after this participant's review turn";
46
- export const PARTICIPANT_TURN_QUEUES_SHORT = "after their review turn";
45
+ // The line while a participant's turn runs (the worker queues), whichever
46
+ // mode: review or pair.
47
+ export const PARTICIPANT_TURN_QUEUES = "goes in as your own turn after this participant's turn";
48
+ export const PARTICIPANT_TURN_QUEUES_SHORT = "after their turn";
47
49
  // The idle row: the keys (the placeholder's hint before the row existed).
48
50
  export const IDLE_HINT = "Enter to send · Shift+Enter newline · ↑ history";
49
51
 
@@ -200,7 +200,7 @@ button.small{font-size:12px;padding:2px 8px}
200
200
  </div>
201
201
  <div class="p-foot">
202
202
  <div class="p-usage" id="usage" aria-label="Your usage" hidden></div>
203
- <div class="p-hint">⏎ sends, ⇧⏎ a new line, ↑ an earlier comment. The model answers in a read-only turn; the owner sees everything.</div>
203
+ <div class="p-hint" id="hint">⏎ sends, ⇧⏎ a new line, ↑ an earlier comment. The model answers in a read-only turn; the owner sees everything.</div>
204
204
  </div>
205
205
  </div>
206
206
  </footer>
@@ -12,9 +12,11 @@
12
12
  // (spend vs cap, queue, link expiry, model). The owner's participant view
13
13
  // mounts none.
14
14
  import {
15
- authorColor, participantAuthor, authorLabel, toolLine, toolsSummary, refusalText, dequeueText, endedText, streamURL, reloads, endsLiveTurn, liveFrom, applyLive,
15
+ authorColor, participantAuthor, authorLabel, toolLine, refusalText, dequeueText, endedText, streamURL, reloads, endsLiveTurn, liveFrom, applyLive,
16
16
  liveText, withToolSteps, pickSubject, subjectBody, subjectsKey, narrowView, retryDelay, retries, threadGaps, usageItems,
17
+ modeCopy,
17
18
  } from "./participant_model.js";
19
+ import { toolsOverview } from "./tools_overview.js";
18
20
  import { fullTime } from "./format.js";
19
21
  import { createAuthLost, lostAnswer } from "./auth_lost.js";
20
22
  import { REPLACE_SESSION_TEXT, fragmentCode, tradeFragmentCode } from "./token_fragment.js";
@@ -40,7 +42,6 @@ const $ = (id) => document.getElementById(id);
40
42
  const body = document.body.dataset;
41
43
  const ownerView = body.viewer === "owner";
42
44
  const sessionId = body.session || new URLSearchParams(location.hash.slice(1)).get("s") || "";
43
- const phone = window.matchMedia("(max-width: 640px)");
44
45
 
45
46
  let data = null;
46
47
  let live = null;
@@ -209,7 +210,9 @@ function render() {
209
210
  return chip;
210
211
  }));
211
212
  $("viewBanner").hidden = !ownerView;
212
- $("note").textContent = ownerView ? "" : "You can comment and ask; the model answers in a turn that can only read. The owner sees everything.";
213
+ const copy = modeCopy(viewer.mode);
214
+ $("note").textContent = ownerView ? "" : copy.note;
215
+ $("hint").textContent = `⏎ sends, ⇧⏎ a new line, ↑ an earlier comment. ${copy.hint}`;
213
216
  $("head").hidden = false;
214
217
  $("main").hidden = false;
215
218
  renderPlan();
@@ -277,13 +280,14 @@ function messageNode(message) {
277
280
  const when = fullTime(message.at);
278
281
  if (when) node.title = when;
279
282
  if (user) {
283
+ if (message.turn_id) node.dataset.turnId = message.turn_id;
280
284
  node.style.setProperty("--author-color", authorColor(message.author));
281
285
  // Whose it is, for an annotation's label (participant_annotate.js).
282
286
  Object.assign(node.dataset, messageAuthorData(message));
283
287
  const who = el("div", "p-who");
284
288
  who.append(el("b", "", authorLabel(message)));
285
289
  if (message.merged) who.append(el("span", "p-tag", "added mid-turn"));
286
- if (message.author) who.append(el("span", "p-tag", "review"));
290
+ if (message.author) who.append(el("span", "p-tag", modeCopy(message.participant_mode).tag));
287
291
  node.append(who);
288
292
  const text = message.content + (message.images ? `\n[${message.images} image${message.images > 1 ? "s" : ""}]` : "");
289
293
  node.append(el("div", "p-bubble", text));
@@ -304,16 +308,11 @@ function messageNode(message) {
304
308
  return node;
305
309
  }
306
310
 
307
- // +open+: the list's state as the reader left it, else open when short on
308
- // a wide screen.
311
+ // +open+: the overview's state as the reader left it.
309
312
  function toolsNode(rows, open = null) {
310
- if (rows.length === 1) {
311
- const row = rows[0];
312
- return el("div", `p-tools p-tool-one${row.status === "error" ? " error" : row.status === "running" ? " running" : ""}`, `↳ ${toolLine(row)}`);
313
- }
314
313
  const details = el("details", "p-tools");
315
- details.open = open ?? (!phone.matches && rows.length <= 4);
316
- details.append(el("summary", "", `${rows.length} tool${rows.length > 1 ? "s" : ""}: ${toolsSummary(rows)}`));
314
+ details.open = open ?? false;
315
+ details.append(el("summary", "", toolsOverview(rows)));
317
316
  const list = el("ul");
318
317
  for (const row of rows) list.append(el("li", row.status === "error" ? "error" : row.status === "running" ? "running" : "", toolLine(row)));
319
318
  details.append(list);
@@ -382,7 +381,7 @@ function currentTurnNodes() {
382
381
  const nodes = [];
383
382
  if (turn.prompt !== undefined || turn.automatic) {
384
383
  nodes.push(messageNode({ role: "user", content: turn.automatic ? "An automatic turn" : turn.prompt, author: turn.author,
385
- author_name: turn.author_name, mine: turn.mine, automatic: turn.automatic, at: turn.at }));
384
+ author_name: turn.author_name, mine: turn.mine, automatic: turn.automatic, at: turn.at, turn_id: turn.turn_id }));
386
385
  }
387
386
  const reply = el("div", "p-msg reply live");
388
387
  fillLive(reply, $("liveReply"));
@@ -38,14 +38,6 @@ export function toolLine(row) {
38
38
  return row?.path ? `${row.tool} ${row.path}` : String(row?.tool || "tool");
39
39
  }
40
40
 
41
- // A tool rows' summary: "read docs/plan.md", "read docs/plan.md + 2 more".
42
- export function toolsSummary(rows) {
43
- const list = Array.isArray(rows) ? rows : [];
44
- if (list.length === 0) return "";
45
- const first = toolLine(list[0]);
46
- return list.length === 1 ? first : `${first} + ${list.length - 1} more`;
47
- }
48
-
49
41
  // The conversation with each run of text-less tool steps (a reply that
50
42
  // only called tools) folded into the next reply's rows, or one row group
51
43
  // when no reply follows: one "3 tools: …" line instead of three.
@@ -271,6 +263,26 @@ export function leftText(iso, now = Date.now()) {
271
263
  return `${Math.max(1, Math.floor(left / MINUTE_MS))} min left`;
272
264
  }
273
265
 
266
+ // What the page says a participant's turn does, by the session's mode
267
+ // (viewer.mode: ParticipantMode.live on the server): a review turn only
268
+ // reads; a pair turn (a working session's) acts with the session's tools
269
+ // under the owner's guardrails. +tag+ is a message's: its own stamp
270
+ // (participant_mode), a message without one a review's.
271
+ export const MODE_COPY = {
272
+ review: {
273
+ note: "You can comment and ask; the model answers in a turn that can only read. The owner sees everything.",
274
+ hint: "The model answers in a read-only turn; the owner sees everything.",
275
+ tag: "review",
276
+ },
277
+ pair: {
278
+ note: "You can ask the model to work in this session: your turns use its tools, writes included, under the owner's "
279
+ + "guardrails, and what needs approval goes to the owner. The owner sees everything.",
280
+ hint: "The model works in this session; the owner approves what needs it and sees everything.",
281
+ tag: "pair",
282
+ },
283
+ };
284
+ export const modeCopy = (mode) => MODE_COPY[mode] || MODE_COPY.review;
285
+
274
286
  export function usageItems(usage, now = Date.now()) {
275
287
  if (!usage || typeof usage !== "object") return [];
276
288
  const items = [];
@@ -25,15 +25,35 @@ export function participantName(author) {
25
25
 
26
26
  // A participant's badge: {author, name, color}, and unnamed: true when
27
27
  // neither the prompt nor the list named them yet; null for the owner's.
28
- export function authorBadge(author, name = null) {
28
+ // +mode+: the turn's participant_mode stamp ("review", "pair"; the
29
+ // message's, or turn_started's), kept as mode: when known.
30
+ export function authorBadge(author, name = null, mode = null) {
29
31
  if (!author || author === "owner") return null;
30
32
  const known = name || participantName(author);
31
- return { author, name: known || UNNAMED, color: authorColor(author), ...(known ? {} : { unnamed: true }) };
33
+ return { author, name: known || UNNAMED, color: authorColor(author), ...(known ? {} : { unnamed: true }), ...(mode ? { mode } : {}) };
32
34
  }
33
35
 
34
- // A badge's text and tooltip (turn_html.js userBubbleTemplate).
35
- export const authorBadgeText = (name) => `${name} · review`;
36
- export const authorBadgeTitle = (name) => `A review comment from ${name}, a participant: its turn could only read`;
36
+ // A badge's text and tooltip (turn_html.js userBubbleTemplate), by the
37
+ // turn's mode: a pair turn (a working session's) acted with the session's
38
+ // tools; a review turn, or one whose mode isn't known (a queued prompt, a
39
+ // message from before the stamp), could only read.
40
+ export const PAIR = "pair";
41
+ export const authorBadgeText = (name, mode = null) => (mode === PAIR ? `${name} · pair` : `${name} · review`);
42
+ export const authorBadgeTitle = (name, mode = null) => (mode === PAIR
43
+ ? `A turn from ${name}, a participant: it acted with this session's tools, its asks came to you`
44
+ : `A review comment from ${name}, a participant: its turn could only read`);
45
+
46
+ // The badge on +bubble+ (a prompt drawn before its turn started) takes the
47
+ // turn's +mode+ once turn_started names it.
48
+ export function setBadgeMode(bubble, mode) {
49
+ const badge = bubble?.querySelector?.(".author-badge");
50
+ if (!badge || !mode) return;
51
+ bubble.dataset.participantMode = mode;
52
+ if (badge.dataset.unnamed) return;
53
+ const name = participantName(bubble.dataset.author) || badge.textContent.replace(/ · (review|pair)$/, "");
54
+ badge.textContent = authorBadgeText(name, mode);
55
+ badge.title = authorBadgeTitle(name, mode);
56
+ }
37
57
 
38
58
  // The badges under +root+ drawn before the list named their participant
39
59
  // (data-unnamed) take the name now known. Bubbles are drawn once
@@ -42,10 +62,11 @@ export const authorBadgeTitle = (name) => `A review comment from ${name}, a part
42
62
  export function nameUnnamedBadges(root) {
43
63
  let named = 0;
44
64
  for (const badge of root?.querySelectorAll?.(".author-badge[data-unnamed]") || []) {
45
- const name = participantName(badge.closest("[data-author]")?.dataset.author);
65
+ const bubble = badge.closest("[data-author]");
66
+ const name = participantName(bubble?.dataset.author);
46
67
  if (!name) continue;
47
- badge.textContent = authorBadgeText(name);
48
- badge.title = authorBadgeTitle(name);
68
+ badge.textContent = authorBadgeText(name, bubble?.dataset.participantMode);
69
+ badge.title = authorBadgeTitle(name, bubble?.dataset.participantMode);
49
70
  badge.removeAttribute("data-unnamed");
50
71
  named += 1;
51
72
  }
@@ -181,22 +181,30 @@ function inviteTemplate(invite, { canShare }) {
181
181
  ${invite.qr_svg ? html`<div class="pp-qr" .innerHTML=${invite.qr_svg}></div>` : nothing}</div>`;
182
182
  }
183
183
 
184
+ // The empty list's line, by the session's mode.
185
+ export const EMPTY_REVIEW = "Nobody yet. Invite a person (or an agent) to review: their comments become read-only review turns; you see and approve everything.";
186
+ export const EMPTY_PAIR = "Nobody yet. Invite a person (or an agent) to work with you here: their turns act with this session's tools under your guardrails, and their asks come to you.";
187
+
184
188
  // The popover's content: the participants, the Invite form (or the link it
185
189
  // gave), the participant view.
186
190
  // +working+: the server's warning for a session that isn't a review session
187
191
  // (shown before the Invite, with Start a review of it), null for one.
192
+ // +pair+: a participant invited now gets pair turns (the list's mode: a
193
+ // working session on a worker with pair turns): the empty list says their
194
+ // turns act; otherwise (a review session, an older worker) that they read.
188
195
  // +identityHeader+: the header chi web's auth proxy names the signed-in
189
196
  // user in (the list's identity_header), null without one: then the Invite
190
197
  // has no email field (a bound link could never open).
191
198
  export function panelTemplate(grants, { now, sessionId, invite = null, error = null, capFor = null, canShare = false,
192
- busy = false, working = null, reviewing = false, identityHeader = null } = {}) {
199
+ busy = false, working = null, reviewing = false, identityHeader = null,
200
+ pair = false } = {}) {
193
201
  const rows = (grants || []).map((g) => rowModel(g, now));
194
202
  const active = rows.filter((row) => row.active);
195
203
  const ended = rows.filter((row) => !row.active);
196
204
  return html`<div class="ctx-pop-head"><strong>Participants</strong><span class="ctx-pop-kind">this session</span
197
205
  ><button type="button" class="ctx-pop-close" data-act="close" aria-label="Close">×</button></div>
198
206
  ${active.length ? html`<ul class="pp-list">${active.map((row) => rowTemplate(row, { capFor }))}</ul>`
199
- : html`<div class="ctx-pop-meta">Nobody yet. Invite a person (or an agent) to review: their comments become read-only review turns; you see and approve everything.</div>`}
207
+ : html`<div class="ctx-pop-meta">${pair ? EMPTY_PAIR : EMPTY_REVIEW}</div>`}
200
208
  ${ended.length ? html`<details class="pp-ended"><summary>Ended (${ended.length})</summary><ul class="pp-list">${
201
209
  ended.map((row) => rowTemplate(row, { capFor }))}</ul></details>` : nothing}
202
210
  <div class="ctx-pop-error" role="alert" ?hidden=${!error}>${error || ""}</div>
@@ -233,6 +241,9 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
233
241
  // The open session's share warning (GET …/participants), null for a
234
242
  // review session.
235
243
  let working = null;
244
+ // What a participant invited now gets (GET …/participants mode: "pair" or
245
+ // "review", the server's ReviewStart.share_terms), never guessed from the warning.
246
+ let inviteMode = null;
236
247
  // The header chi web's proxy names the user in (GET …/participants), null
237
248
  // without one: the Invite's email field.
238
249
  let identityHeader = null;
@@ -268,7 +279,7 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
268
279
 
269
280
  function draw() {
270
281
  render(panelTemplate(grants, { now: clock(), sessionId: session(), invite, error, capFor, busy,
271
- working: startReview ? working : null, reviewing: reviewing(), identityHeader,
282
+ working: startReview ? working : null, pair: inviteMode === "pair", reviewing: reviewing(), identityHeader,
272
283
  canShare: typeof win.navigator?.share === "function" }), shell.pop);
273
284
  shell.replace();
274
285
  }
@@ -277,6 +288,7 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
277
288
  if (!id) {
278
289
  grants = null;
279
290
  working = null;
291
+ inviteMode = null;
280
292
  loadedFor = null;
281
293
  setParticipantNames([]);
282
294
  onChange();
@@ -287,6 +299,7 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
287
299
  if (id !== session()) return;
288
300
  grants = Array.isArray(body.participants) ? body.participants : [];
289
301
  working = typeof body.warning === "string" ? body.warning : null;
302
+ inviteMode = typeof body.mode === "string" ? body.mode : null;
290
303
  identityHeader = typeof body.identity_header === "string" && body.identity_header ? body.identity_header : null;
291
304
  loadedFor = id;
292
305
  if (setParticipantNames(grants)) onNames();
@@ -296,6 +309,7 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
296
309
  if (loadedFor !== id) {
297
310
  grants = [];
298
311
  working = null;
312
+ inviteMode = null;
299
313
  setParticipantNames([]);
300
314
  }
301
315
  }
@@ -63,10 +63,19 @@ export function relayView(pq) {
63
63
  };
64
64
  }
65
65
 
66
- // @return {null | {tool, what, isCommand, where, why, paths?, preview?, delegate?}};
66
+ // Who asks when a participant's turn asks (approval.author, Approval.payload):
67
+ // their name, else their id; null for the owner's own turns.
68
+ export function approvalAsker(pq) {
69
+ const a = (pq && pq.approval) || {};
70
+ if (!a.author) return null;
71
+ return a.author_name ? String(a.author_name) : String(a.author).replace(/^p:/, "");
72
+ }
73
+
74
+ // @return {null | {tool, what, isCommand, where, why, paths?, preview?, delegate?, asker?}};
67
75
  // paths are what +what+ joins when it shows paths (the card draws a ref
68
76
  // for each); preview is an edit/write's dry-run diff (diff_view.js draws
69
- // it); delegate is relayView's, for a delegate's approval
77
+ // it); delegate is relayView's, for a delegate's approval; asker is
78
+ // approvalAsker's, for a participant's turn's ask
70
79
  export function approvalView(pq) {
71
80
  if (!isApproval(pq)) return null;
72
81
  const a = pq.approval || {};
@@ -94,6 +103,7 @@ export function approvalView(pq) {
94
103
  why: `${reason} (${who})`,
95
104
  ...(a.preview && typeof a.preview === "object" ? { preview: a.preview } : {}),
96
105
  ...(relayView(pq) ? { delegate: relayView(pq) } : {}),
106
+ ...(approvalAsker(pq) ? { asker: approvalAsker(pq), askedBy: String(a.asked_by || "") } : {}),
97
107
  };
98
108
  }
99
109
 
@@ -320,6 +320,13 @@ export function createQuestionCards({
320
320
  box.className = "approval-details";
321
321
  // A delegate's approval: who asks, and its task.
322
322
  if (view.delegate) box.appendChild(renderDelegateLine(view.delegate));
323
+ // A participant's turn asks: the server's line (Approval::ASKED_BY), else their name.
324
+ if (view.asker) {
325
+ const who = doc.createElement("div");
326
+ who.className = "approval-delegate approval-asker";
327
+ who.textContent = view.askedBy || view.asker;
328
+ box.appendChild(who);
329
+ }
323
330
  const tool = doc.createElement("div");
324
331
  tool.className = "approval-tool";
325
332
  tool.textContent = view.tool;
@@ -53,6 +53,7 @@ import {
53
53
  } from "./turn_events.js";
54
54
  import { commandView, drawCommandBubble, historyHasCommandBubble } from "./commands.js";
55
55
  import { keepEarlyRestore, restoreAction } from "./restore.js";
56
+ import { PAIR, setBadgeMode } from "./participant_names.js";
56
57
 
57
58
  export function createStreamHandlers(deps) {
58
59
  const {
@@ -159,9 +160,12 @@ export function createStreamHandlers(deps) {
159
160
  liveTurn.cutAfter = data.cut_after ?? null;
160
161
  liveTurn.serverGen = null;
161
162
  // A participant's review turn: its id and author, for Apply at its end
162
- // (turn_completed names neither).
163
+ // (turn_completed names neither). A pair turn acted itself: no Apply.
163
164
  const author = data.author || data.origin?.author;
164
- liveTurn.review = author && author !== "owner" && data.turn_id ? { turn_id: data.turn_id, author, author_name: data.author_name } : null;
165
+ const pair = data.participant_mode === PAIR;
166
+ liveTurn.review = author && author !== "owner" && data.turn_id && !pair ? { turn_id: data.turn_id, author, author_name: data.author_name } : null;
167
+ // Its prompt drawn while queued takes the turn's mode now.
168
+ if (data.participant_mode) setBadgeMode(promptBubble, data.participant_mode);
165
169
  // The owner's input queues behind it (the composer's delivery line).
166
170
  liveTurn.participantTurn = !!(author && author !== "owner");
167
171
  setTurnRunning(true);