samagotchi 0.105.0 → 0.107.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 (131) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +168 -1
  3. data/bin/chi +2 -0
  4. data/docs/architecture.md +10 -3
  5. data/docs/cli.md +90 -9
  6. data/docs/configuration.md +9 -5
  7. data/docs/guardrails.md +63 -1
  8. data/docs/hooks.md +9 -0
  9. data/docs/internals/engine.md +22 -4
  10. data/docs/internals/participants.md +319 -45
  11. data/docs/internals/prompt-caching.md +2 -1
  12. data/docs/internals/remote-sessions.md +12 -5
  13. data/docs/internals/working-set.md +8 -2
  14. data/docs/plugins.md +31 -1
  15. data/docs/releasing.md +2 -0
  16. data/docs/sessions.md +36 -1
  17. data/docs/sub-agent.md +2 -0
  18. data/docs/testing.md +5 -1
  19. data/lib/samagotchi/bridge/turn_accumulator.rb +19 -3
  20. data/lib/samagotchi/bridge.rb +39 -1
  21. data/lib/samagotchi/bridge_client/stream_request.rb +10 -3
  22. data/lib/samagotchi/bridge_client.rb +4 -1
  23. data/lib/samagotchi/bundles/coordinator/manifest.yml +6 -5
  24. data/lib/samagotchi/bundles/coordinator/plugin.rb +85 -5
  25. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +18 -0
  26. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  27. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  28. data/lib/samagotchi/client_id.rb +21 -9
  29. data/lib/samagotchi/config.rb +16 -1
  30. data/lib/samagotchi/continue_offer.rb +60 -3
  31. data/lib/samagotchi/delivery.rb +10 -0
  32. data/lib/samagotchi/engine.rb +62 -6
  33. data/lib/samagotchi/guardrail_wiring.rb +13 -3
  34. data/lib/samagotchi/guardrails/review_boundary.rb +97 -0
  35. data/lib/samagotchi/guardrails/review_paths.rb +93 -0
  36. data/lib/samagotchi/guardrails.rb +1 -0
  37. data/lib/samagotchi/hook_routes.rb +5 -2
  38. data/lib/samagotchi/hooks/registry.rb +12 -3
  39. data/lib/samagotchi/idle_recap.rb +9 -0
  40. data/lib/samagotchi/model_profile.rb +5 -3
  41. data/lib/samagotchi/parent_report.rb +39 -5
  42. data/lib/samagotchi/participant_messages.rb +27 -0
  43. data/lib/samagotchi/participants.rb +46 -9
  44. data/lib/samagotchi/participants_watch.rb +90 -0
  45. data/lib/samagotchi/plugin/api.rb +2 -1
  46. data/lib/samagotchi/plugin/context.rb +7 -1
  47. data/lib/samagotchi/plugin/sessions.rb +25 -0
  48. data/lib/samagotchi/plugin/side_question.rb +9 -1
  49. data/lib/samagotchi/remote_command.rb +1 -1
  50. data/lib/samagotchi/remotes.rb +23 -8
  51. data/lib/samagotchi/reply_wait/poll.rb +18 -3
  52. data/lib/samagotchi/review_apply.rb +123 -0
  53. data/lib/samagotchi/review_command.rb +121 -0
  54. data/lib/samagotchi/review_start.rb +161 -0
  55. data/lib/samagotchi/run_options.rb +18 -3
  56. data/lib/samagotchi/send_command/wait_target.rb +5 -0
  57. data/lib/samagotchi/send_command.rb +43 -3
  58. data/lib/samagotchi/session.rb +33 -5
  59. data/lib/samagotchi/session_access/contract.rb +12 -2
  60. data/lib/samagotchi/session_access/dispatch.rb +8 -2
  61. data/lib/samagotchi/session_access/http_transport.rb +10 -1
  62. data/lib/samagotchi/session_access/local.rb +50 -11
  63. data/lib/samagotchi/session_access/remote.rb +34 -3
  64. data/lib/samagotchi/session_access/web_bridge_client.rb +1 -1
  65. data/lib/samagotchi/session_access.rb +29 -13
  66. data/lib/samagotchi/session_chain.rb +10 -2
  67. data/lib/samagotchi/session_commands.rb +6 -0
  68. data/lib/samagotchi/session_continue.rb +4 -3
  69. data/lib/samagotchi/session_inbox.rb +31 -5
  70. data/lib/samagotchi/session_manager.rb +68 -6
  71. data/lib/samagotchi/session_metrics/side_totals.rb +21 -7
  72. data/lib/samagotchi/session_metrics.rb +88 -1
  73. data/lib/samagotchi/session_review.rb +28 -0
  74. data/lib/samagotchi/share_command.rb +68 -23
  75. data/lib/samagotchi/side_usage.rb +4 -2
  76. data/lib/samagotchi/steer.rb +37 -1
  77. data/lib/samagotchi/terminal_ui/attach_link.rb +5 -0
  78. data/lib/samagotchi/terminal_ui/attached_loop.rb +58 -8
  79. data/lib/samagotchi/terminal_ui/formatting.rb +66 -5
  80. data/lib/samagotchi/terminal_ui/local_link.rb +7 -0
  81. data/lib/samagotchi/terminal_ui/participant_commands.rb +77 -0
  82. data/lib/samagotchi/terminal_ui/remote_link.rb +6 -2
  83. data/lib/samagotchi/terminal_ui/status_row.rb +11 -2
  84. data/lib/samagotchi/terminal_ui.rb +5 -0
  85. data/lib/samagotchi/testing/host.rb +4 -2
  86. data/lib/samagotchi/testing/recorder.rb +3 -1
  87. data/lib/samagotchi/testing/sessions.rb +10 -2
  88. data/lib/samagotchi/toolkit.rb +21 -3
  89. data/lib/samagotchi/turn_checkpoint.rb +13 -0
  90. data/lib/samagotchi/version.rb +1 -1
  91. data/lib/samagotchi/web/app.rb +151 -41
  92. data/lib/samagotchi/web/grants.rb +172 -18
  93. data/lib/samagotchi/web/participant_access.rb +273 -46
  94. data/lib/samagotchi/web/participant_review.rb +208 -0
  95. data/lib/samagotchi/web/participant_stream_filter.rb +258 -0
  96. data/lib/samagotchi/web/participant_view.rb +426 -0
  97. data/lib/samagotchi/web/public/app.js +75 -6
  98. data/lib/samagotchi/web/public/bubbles.js +3 -3
  99. data/lib/samagotchi/web/public/chip_popover.js +10 -3
  100. data/lib/samagotchi/web/public/data.js +30 -2
  101. data/lib/samagotchi/web/public/delivery_line.js +79 -15
  102. data/lib/samagotchi/web/public/index.html +97 -27
  103. data/lib/samagotchi/web/public/info_bar.js +17 -6
  104. data/lib/samagotchi/web/public/info_bar_model.js +15 -6
  105. data/lib/samagotchi/web/public/live_turn.js +3 -0
  106. data/lib/samagotchi/web/public/participant.html +172 -0
  107. data/lib/samagotchi/web/public/participant.js +447 -0
  108. data/lib/samagotchi/web/public/participant_model.js +220 -0
  109. data/lib/samagotchi/web/public/participant_names.js +53 -0
  110. data/lib/samagotchi/web/public/participants_panel.js +379 -0
  111. data/lib/samagotchi/web/public/question_cards.js +1 -0
  112. data/lib/samagotchi/web/public/review_apply.js +34 -0
  113. data/lib/samagotchi/web/public/review_start.js +101 -0
  114. data/lib/samagotchi/web/public/send_turn.js +25 -1
  115. data/lib/samagotchi/web/public/session_actions.js +44 -3
  116. data/lib/samagotchi/web/public/session_state.js +3 -0
  117. data/lib/samagotchi/web/public/start_page.js +38 -2
  118. data/lib/samagotchi/web/public/stream_handlers.js +18 -1
  119. data/lib/samagotchi/web/public/tokens.css +12 -0
  120. data/lib/samagotchi/web/public/turn_events.js +16 -5
  121. data/lib/samagotchi/web/public/turn_html.js +9 -4
  122. data/lib/samagotchi/web/public/turn_view.js +7 -1
  123. data/lib/samagotchi/web/public/working_set_view.js +3 -3
  124. data/lib/samagotchi/web/qr.rb +14 -0
  125. data/lib/samagotchi/web/running.rb +52 -0
  126. data/lib/samagotchi/web/server.rb +13 -0
  127. data/lib/samagotchi/web/session_access_routes.rb +3 -0
  128. data/lib/samagotchi/web/session_summary.rb +3 -0
  129. data/lib/samagotchi/worker.rb +121 -7
  130. data/lib/samagotchi/worker_inbound.rb +12 -4
  131. metadata +22 -1
@@ -9,8 +9,8 @@ module Samagotchi
9
9
  # and which run on this machine only (refused under a remote, exit 2:
10
10
  # "chi <cmd> runs on this machine only: run it on <remote>"). The v1 scope is the remote-sessions plan's
11
11
  # D3: send, answer, note, a session's context (add, push, ls, show, rm)
12
- # and sessions list/stop/restart/archive/unarchive/delete, and chi share
13
- # (the shared-sessions plan's P2); the rest
12
+ # and sessions list/stop/restart/archive/unarchive/delete, chi share
13
+ # (the shared-sessions plan's P2) and chi review (P5); the rest
14
14
  # stays local. bin/chi's subcommands that act on the machine, not on
15
15
  # sessions, are MACHINE. The run flags (chi --attach, -p, --resume: a
16
16
  # session in this terminal, a remote attach there) are RUN's.
@@ -122,11 +122,21 @@ module Samagotchi
122
122
  "share --name" => SUPPORTED,
123
123
  "share --agent" => SUPPORTED,
124
124
  "share --expires" => SUPPORTED,
125
+ "share --cap" => SUPPORTED,
126
+ "share cap" => SUPPORTED,
125
127
  "share ls" => SUPPORTED,
126
128
  "share ls --format" => SUPPORTED,
127
129
  "share revoke" => SUPPORTED,
128
130
  "share revoke --all" => SUPPORTED,
129
131
 
132
+ # A review session (docs/sessions.md): the remote's chi web checks
133
+ # the files against its own project; --dir is required there
134
+ # unless --from (D4).
135
+ "review" => SUPPORTED,
136
+ "review --dir" => SUPPORTED,
137
+ "review --model" => SUPPORTED,
138
+ "review --from" => SUPPORTED,
139
+
130
140
  "broadcast" => LOCAL_ONLY
131
141
  }.freeze
132
142
 
@@ -78,7 +78,10 @@ module Samagotchi
78
78
  end
79
79
 
80
80
  # The session command against the remote: refused (exit 2), or run
81
- # with a Remote. A failure to reach it is the command's line, exit 1.
81
+ # with a Remote. A failure to reach it is the command's line, exit 1;
82
+ # a refusal the command doesn't word itself is its line too: exit 2
83
+ # when chi web refused a value (BadRequest, a usage error here), 1
84
+ # for any other.
82
85
  # @param subcommands [Hash] bin/chi's SUBCOMMANDS
83
86
  # @return [Integer] the exit status
84
87
  def run(subcommands, stderr: $stderr, transport: nil)
@@ -100,7 +103,10 @@ module Samagotchi
100
103
  rescue Remotes::Invalid => e
101
104
  stderr.puts("Error: #{e.message}")
102
105
  CLI::Exit::USAGE
103
- rescue RemoteFailed => e
106
+ rescue BadRequest => e
107
+ stderr.puts("chi #{@argv.first}: #{e.message}")
108
+ CLI::Exit::USAGE
109
+ rescue RemoteFailed, Refused => e
104
110
  stderr.puts("chi #{@argv.first}: #{e.message}")
105
111
  CLI::Exit::FAILED
106
112
  end
@@ -74,6 +74,13 @@ module Samagotchi
74
74
  failed("no answer within #{@open_timeout} s")
75
75
  rescue Net::ReadTimeout
76
76
  failed("it took the request but sent no answer within #{read_timeout} s")
77
+ rescue Net::WriteTimeout
78
+ failed("it took no request within #{read_timeout} s")
79
+ rescue Timeout::Error
80
+ failed("no answer in time")
81
+ rescue Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError
82
+ # Something else listens there (an SSH banner, another server).
83
+ failed("it didn't answer HTTP (is it chi web's port?)")
77
84
  rescue SocketError => e
78
85
  failed(e.message.include?("getaddrinfo") ? "can't find host #{@uri.host}" : e.message)
79
86
  rescue Errno::EHOSTUNREACH, Errno::ENETUNREACH
@@ -87,7 +94,9 @@ module Samagotchi
87
94
  private
88
95
 
89
96
  def http(read_timeout)
90
- Net::HTTP.new(@uri.host, @uri.port).tap do |http|
97
+ # hostname: an IPv6 address bare ([::1] is the URL's); Net::HTTP
98
+ # brackets it in Host.
99
+ Net::HTTP.new(@uri.hostname, @uri.port).tap do |http|
91
100
  http.use_ssl = @uri.scheme == "https"
92
101
  http.open_timeout = @open_timeout
93
102
  http.read_timeout = read_timeout
@@ -12,11 +12,13 @@ require_relative "../context_sources"
12
12
  require_relative "../send_command/busy"
13
13
  require_relative "../chi_invocation"
14
14
  require_relative "../worker_sidecar"
15
+ require_relative "../review_start"
15
16
  require_relative "../launch_mode"
16
17
  require_relative "../participants"
17
18
  require_relative "../config"
18
19
  require_relative "../web/grants"
19
20
  require_relative "../web/info_probe"
21
+ require_relative "../web/running"
20
22
 
21
23
  module Samagotchi
22
24
  # Loaded on first use: SessionManager and its ~80 files only when a
@@ -38,6 +40,9 @@ module Samagotchi
38
40
 
39
41
  def remote? = false
40
42
 
43
+ # This machine's sessions are the owner's.
44
+ def participant? = false
45
+
41
46
  # The printed commands' spelling: this machine's chi.
42
47
  # @return [ChiInvocation]
43
48
  def invocation = ChiInvocation::HERE
@@ -110,8 +115,11 @@ module Samagotchi
110
115
  # @return [Session] the session created (its id, model_warning,
111
116
  # continues, moved_children)
112
117
  # @raise [SessionContinue::Refused, SessionManager::ArchiveRefused,
113
- # SessionManager::OwnedByTUI] refused; StandardError: could not start
118
+ # SessionManager::OwnedByTUI, ReviewStart::Refused] refused;
119
+ # StandardError: could not start
114
120
  def create(spec)
121
+ return create_review(spec) if spec.review
122
+
115
123
  start = spec.preview ? { prompt: spec.prompt, preview: spec.preview } : { prompt: spec.prompt }
116
124
  if spec.continues
117
125
  return SessionManager.continue_session(spec.continues, **start, model: spec.model_name, **dir)
@@ -121,6 +129,18 @@ module Samagotchi
121
129
  setup: spec.setup, **dir)
122
130
  end
123
131
 
132
+ # A review session (ReviewStart): a fork of review.from, or a fresh
133
+ # one in the spec's folder.
134
+ def create_review(spec)
135
+ review = spec.review
136
+ if review.from
137
+ return ReviewStart.fork(from: review.from, subjects: review.subjects, model: spec.model_name, state_dir: state_dir!)
138
+ end
139
+
140
+ ReviewStart.start(subjects: review.subjects, dir: spec.working_directory || Dir.pwd, model: spec.model_name,
141
+ setup: spec.setup || SessionSetup.new, state_dir: state_dir!)
142
+ end
143
+
124
144
  # Whether a just-created session's worker came up (its Bridge
125
145
  # answers) within +timeout+ seconds.
126
146
  def await_worker(id, timeout:)
@@ -339,16 +359,18 @@ module Samagotchi
339
359
  grants.list(session_id: id).map { |grant| ParticipantView.from_h(grant.public_h(grants.now)) }
340
360
  end
341
361
 
342
- # The link names this machine's chi web: its LAN address when one
343
- # runs on the LAN (web.port), else 127.0.0.1 (+lan+ false).
362
+ # The link names this machine's chi web: its LAN address and port
363
+ # when one runs on the LAN (the port it recorded, else web.port),
364
+ # else 127.0.0.1 (+lan+ false).
344
365
  # @return [Invitation]
345
366
  # @raise [ArgumentError] no such session
346
367
  # @raise [BadRequest] a bad name, kind or ttl, an archived session
347
- def invite(id, name:, kind:, ttl: nil)
348
- issued = Participants.invite(grants, session_id: id, name: name, kind: kind, ttl: ttl, state_dir: state_dir!)
368
+ def invite(id, name:, kind:, ttl: nil, cap: nil)
369
+ issued = Participants.invite(grants, session_id: id, name: name, kind: kind, ttl: ttl, cap: cap, state_dir: state_dir!)
349
370
  ip, port = local_web
350
371
  Invitation.new(participant: ParticipantView.from_h(issued.grant.public_h(grants.now)), token: issued.token,
351
- link: "http://#{ip || "127.0.0.1"}:#{port}/?token=#{issued.token}#s=#{id}", lan: !ip.nil?)
372
+ link: "http://#{ip || "127.0.0.1"}:#{port}/?token=#{issued.token}#s=#{id}", lan: !ip.nil?,
373
+ warning: ReviewStart.share_warning(Session.load(id, **dir)))
352
374
  rescue Web::Grants::Invalid => e
353
375
  raise BadRequest.new(e.message, code: "invalid_participant")
354
376
  end
@@ -359,6 +381,17 @@ module Samagotchi
359
381
  .map { |grant| ParticipantView.from_h(grant.public_h(grants.now)) }
360
382
  end
361
383
 
384
+ # @return [ParticipantView] the participant with their new cap
385
+ # @raise [BadRequest] a cap out of range, or no such active participant
386
+ def set_participant_cap(id, participant:, cap:)
387
+ grant = Participants.set_cap(grants, session_id: id, id: participant, cap: cap, state_dir: state_dir!)
388
+ raise BadRequest.new(Participants.no_participant(participant, id), code: "invalid_participant") unless grant
389
+
390
+ ParticipantView.from_h(grant.public_h(grants.now))
391
+ rescue Web::Grants::Invalid => e
392
+ raise BadRequest.new(e.message, code: "invalid_participant")
393
+ end
394
+
362
395
  private
363
396
 
364
397
  def grants = @grants ||= Web::Grants.new(Web::Grants.path(state_dir: state_dir!))
@@ -367,12 +400,18 @@ module Samagotchi
367
400
  WEB_PORT = 4567
368
401
  LOCAL_PROBE_TIMEOUT = 1.0
369
402
 
370
- # [LAN ip or nil, port] of this machine's chi web (GET /api/info).
403
+ # [LAN ip or nil, port] of this machine's chi web (GET /api/info):
404
+ # the port the running one recorded (Web::Running) when a chi web
405
+ # answers there, else config's web.port.
371
406
  def local_web
372
- port = Config.get("web.port").to_s.to_i
373
- port = WEB_PORT unless port.positive?
374
- info = Web::InfoProbe.call("127.0.0.1", port, timeout: LOCAL_PROBE_TIMEOUT)
375
- [info.is_a?(Hash) ? info["lan"] : nil, port]
407
+ configured = Config.get("web.port").to_s.to_i
408
+ configured = WEB_PORT unless configured.positive?
409
+ recorded = Web::Running.port(path: Web::Running.path(state_dir: state_dir!))
410
+ [recorded, configured].compact.uniq.each do |port|
411
+ info = Web::InfoProbe.call("127.0.0.1", port, timeout: LOCAL_PROBE_TIMEOUT)
412
+ return [info["lan"], port] if info.is_a?(Hash)
413
+ end
414
+ [nil, configured]
376
415
  end
377
416
 
378
417
  def dir = @state_dir ? { state_dir: @state_dir } : {}
@@ -58,6 +58,14 @@ module Samagotchi
58
58
  def remote? = true
59
59
  def name = @entry.name
60
60
 
61
+ # Web::Grants::PREFIX, without loading chi web.
62
+ PARTICIPANT_PREFIX = "chp_"
63
+
64
+ # Whether the token is a participant's (chi share's link), not the
65
+ # owner's: their turns are queued review turns, their waits take only
66
+ # a turn of theirs.
67
+ def participant? = @entry.token.to_s.start_with?(PARTICIPANT_PREFIX)
68
+
61
69
  # The printed commands' spelling: chi --remote NAME.
62
70
  # @return [ChiInvocation]
63
71
  def invocation = ChiInvocation.new(remote: name)
@@ -245,13 +253,13 @@ module Samagotchi
245
253
  # @param ttl [Integer, nil] seconds; nil: the grant's default
246
254
  # @return [Invitation]
247
255
  # @raise [BadRequest] a bad name, kind or ttl, an archived session
248
- def invite(id, name:, kind:, ttl: nil)
249
- reply = request(:post, "#{session_path(id)}/participants", body: { name: name, kind: kind, ttl: ttl }.compact)
256
+ def invite(id, name:, kind:, ttl: nil, cap: nil)
257
+ reply = request(:post, "#{session_path(id)}/participants", body: { name: name, kind: kind, ttl: ttl, cap: cap }.compact)
250
258
  raise_refusal(reply) unless reply.status == 201
251
259
 
252
260
  json = reply.json
253
261
  Invitation.new(participant: ParticipantView.from_h(json.fetch("participant")), token: json.fetch("token"),
254
- link: json.fetch("link"), lan: json["lan"] == true)
262
+ link: json.fetch("link"), lan: json["lan"] == true, warning: json["warning"])
255
263
  end
256
264
 
257
265
  # Revokes one participant (+participant+), a session's, or with no
@@ -265,6 +273,15 @@ module Samagotchi
265
273
  Array(reply.json["revoked"]).map { |row| ParticipantView.from_h(row) }
266
274
  end
267
275
 
276
+ # @return [ParticipantView] the participant with their new cap
277
+ # @raise [BadRequest] a cap out of range, or no such active participant
278
+ def set_participant_cap(id, participant:, cap:)
279
+ reply = request(:post, "#{session_path(id)}/participants/#{participant}/cap", body: { cap: cap })
280
+ raise_refusal(reply) unless reply.status == 200
281
+
282
+ ParticipantView.from_h(reply.json.fetch("participant"))
283
+ end
284
+
268
285
  def note(id, text:, source:)
269
286
  reply = request(:post, "#{session_path(id)}/notes", body: { text: text, source: source })
270
287
  json = reply.json.is_a?(Hash) ? reply.json : {}
@@ -441,6 +458,7 @@ module Samagotchi
441
458
  # @param fetched [ContextSources::Fetched]
442
459
  # @return [ContextPush]
443
460
  def context_push(target, name, fetched)
461
+ ContextSources.check_name!(name)
444
462
  reply = request(:post, "#{session_path(target.session_id)}/context/#{name}/push",
445
463
  body: { text: fetched.text, summary: fetched.summary, wake: fetched.wake, hint: fetched.hint })
446
464
  case reply.status
@@ -630,6 +648,8 @@ module Samagotchi
630
648
  end
631
649
 
632
650
  def create_body(spec)
651
+ return review_body(spec) if spec.review
652
+
633
653
  body = { model: spec.model_name, client_id: spec.client_id, history: false }
634
654
  if spec.preview || spec.idle
635
655
  body.merge!(idle: true, preview: spec.preview)
@@ -646,6 +666,17 @@ module Samagotchi
646
666
  body.compact
647
667
  end
648
668
 
669
+ # A review session's create (chi review): its subjects as typed,
670
+ # checked by the server against its own files; a fork names its
671
+ # source and takes its folder.
672
+ def review_body(spec)
673
+ review = { subjects: spec.review.subjects, from: spec.review.from }.compact
674
+ body = { review: review, model: spec.model_name }
675
+ body[:dir] = spec.working_directory unless spec.review.from
676
+ body.merge!(setup_body(spec.setup)) if spec.setup && !spec.review.from
677
+ body.compact
678
+ end
679
+
649
680
  def setup_body(words)
650
681
  llm = words.llm_context&.to_h { |field, word| [LLM_CONTEXT_KEYS.fetch(field), word] }
651
682
  { llm_context: llm, thinking: words.thinking, toolkit: words.toolkit,
@@ -203,7 +203,7 @@ module Samagotchi
203
203
  return refused("tls_unsupported") if uri.scheme == "https"
204
204
 
205
205
  token = @remote.entry.token
206
- opened = BridgeClient::StreamRequest.open(host: uri.host, port: uri.port,
206
+ opened = BridgeClient::StreamRequest.open(host: uri.hostname, port: uri.port,
207
207
  path: "/api/sessions/#{@session_id}/stream#{query}",
208
208
  last_event_id: last_event_id, timeout: timeout,
209
209
  headers: token ? { "Authorization" => "Bearer #{token}" } : {})
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "participant_messages"
4
+
3
5
  module Samagotchi
4
6
  # The seam between chi's session commands (chi send, answer, note,
5
7
  # session-scope context, sessions list/stop/restart/archive/unarchive/
@@ -33,40 +35,40 @@ module Samagotchi
33
35
  class AuthRefused < RemoteFailed; end
34
36
 
35
37
  # The errors a participant's token meets (docs/internals/participants.md),
36
- # one message each, built from the remote's label ("remote studio
37
- # (http://…)"). chi web's code for each is its CODE.
38
+ # each the server's own words (ParticipantMessages) led by the remote's
39
+ # label ("remote studio (http://…)"). chi web's code for each is its CODE.
38
40
 
39
41
  # 401 token_revoked: the owner revoked the grant, or archived or
40
42
  # deleted its session.
41
43
  class TokenRevoked < AuthRefused
42
44
  CODE = "token_revoked"
43
- def initialize(label) = super("#{label}: this review link was revoked by the session's owner")
45
+ def initialize(label) = super("#{label}: #{ParticipantMessages::TOKEN_REVOKED}")
44
46
  end
45
47
 
46
48
  # 401 token_expired: the grant's time ran out.
47
49
  class TokenExpired < AuthRefused
48
50
  CODE = "token_expired"
49
- def initialize(label) = super("#{label}: this review link expired: ask the session's owner for a new one")
51
+ def initialize(label) = super("#{label}: #{ParticipantMessages::TOKEN_EXPIRED}")
50
52
  end
51
53
 
52
54
  # 403 not_permitted: a participant's token on a route only the session's
53
55
  # owner may use.
54
56
  class NotPermitted < RemoteFailed
55
57
  CODE = "not_permitted"
56
- def initialize(label) = super("#{label}: this token is a participant's: only the session's owner can do that")
58
+ def initialize(label) = super("#{label}: #{ParticipantMessages::NOT_PERMITTED}")
57
59
  end
58
60
 
59
61
  # 429 too_many_turns (P3b): the participant's turns already wait in the
60
62
  # queue up to their limit.
61
63
  class TooManyTurns < RemoteFailed
62
64
  CODE = "too_many_turns"
63
- def initialize(label) = super("#{label}: this participant has too many turns waiting: wait for one to finish")
65
+ def initialize(label) = super("#{label}: #{ParticipantMessages::TOO_MANY_TURNS}")
64
66
  end
65
67
 
66
68
  # 429 cap_reached (P3b): the participant's grant spent its cap.
67
69
  class CapReached < RemoteFailed
68
70
  CODE = "cap_reached"
69
- def initialize(label) = super("#{label}: this participant's spending cap is reached: ask the session's owner to raise it")
71
+ def initialize(label) = super("#{label}: #{ParticipantMessages::CAP_REACHED}")
70
72
  end
71
73
 
72
74
  # A remote's chi web refused a request for a reason this machine checks
@@ -91,16 +93,20 @@ module Samagotchi
91
93
  # One participant's grant as chi share ls shows it
92
94
  # (Web::Grants::Grant#public_h): never its token or digest. +state+
93
95
  # "active", "revoked" or "expired".
96
+ # +cap+ dollars and +queue+ turns (nil from a chi web before them).
94
97
  ParticipantView = Data.define(:id, :session_id, :kind, :name, :role, :created_at, :expires_at, :revoked_at,
95
- :revoked_by, :last_used_at, :state) do
98
+ :revoked_by, :last_used_at, :state, :cap, :queue) do
96
99
  def self.from_h(hash) = new(**members.to_h { |key| [key, hash[key] || hash[key.to_s]] })
97
100
  end
98
101
 
99
102
  # What chi share made: the participant, their token and the link that
100
103
  # carries it (both shown this once: chi keeps only a digest), and
101
104
  # whether that chi web listens on the LAN (+lan+ false: the link works
102
- # on that machine only).
103
- Invitation = Data.define(:participant, :token, :link, :lan) do
105
+ # on that machine only), and the warning for sharing a working session
106
+ # (ReviewStart.share_warning; nil for a review session).
107
+ Invitation = Data.define(:participant, :token, :link, :lan, :warning) do
108
+ def initialize(participant:, token:, link:, lan:, warning: nil) = super
109
+
104
110
  def inspect = "#<Invitation #{participant.id}>"
105
111
  alias_method :to_s, :inspect
106
112
  end
@@ -117,11 +123,21 @@ module Samagotchi
117
123
  # bundles). +client_id+ (chi send's, or chi answer's for a parent's
118
124
  # /continue yes) and +images+ (images follow) are for a Remote's server,
119
125
  # which checks the first line and the model as chi send checks them
120
- # here (Local checks before it creates).
126
+ # here (Local checks before it creates). +review+ (a Review) makes it a
127
+ # review session (chi review): idle, no prompt, and with +review.from+
128
+ # a review fork of that session (its folder and setup: the rest is nil).
121
129
  NewSession = Data.define(:prompt, :preview, :continues, :working_directory, :model_name, :setup, :client_id,
122
- :images, :idle) do
130
+ :images, :idle, :review) do
123
131
  def initialize(prompt:, preview: nil, continues: nil, working_directory: nil, model_name: nil, setup: nil,
124
- client_id: nil, images: false, idle: false) = super
132
+ client_id: nil, images: false, idle: false, review: nil) = super
133
+ end
134
+
135
+ # A review session to create (NewSession#review): +subjects+ as typed
136
+ # (relative to the session's folder; the side that has the files checks
137
+ # them, ReviewStart.check_subjects), +from+ the session a review fork
138
+ # starts from (an id, a prefix or last:<id>), or nil.
139
+ Review = Data.define(:subjects, :from) do
140
+ def initialize(subjects: [], from: nil) = super(subjects: Array(subjects).map(&:to_s), from: from)
125
141
  end
126
142
 
127
143
  # chi send --new's setup flags as typed, for a Remote: +llm_context+
@@ -70,12 +70,20 @@ module Samagotchi
70
70
  # @return [String]
71
71
  def note_text(previous, recap:)
72
72
  head = "This session continues #{previous.id[0, 8]} (#{clock(previous.created_at) || previous.created_at}), the previous link of its chain."
73
+ "#{head}#{recap_text(recap)}"
74
+ end
75
+
76
+ # +recap+ as a note's tail: " Its recap, as of <time>:\n<text>" (cut
77
+ # to RECAP_CHARS), or " It left no recap."
78
+ # @param recap [Hash, nil] RecapStore.read's
79
+ # @return [String]
80
+ def recap_text(recap)
73
81
  text = recap && recap[:text].to_s.strip
74
- return "#{head} It left no recap." if text.nil? || text.empty?
82
+ return " It left no recap." if text.nil? || text.empty?
75
83
 
76
84
  text = "#{text[0, RECAP_CHARS - 1]}…" if text.length > RECAP_CHARS
77
85
  as_of = clock(recap[:created_at])
78
- "#{head} Its recap#{", as of #{as_of}" if as_of}:\n#{text}"
86
+ " Its recap#{", as of #{as_of}" if as_of}:\n#{text}"
79
87
  end
80
88
 
81
89
  # What web `continue →` prefills in +previous+'s next link: +previous+'s
@@ -158,6 +158,12 @@ module Samagotchi
158
158
  # runs (the worker's POST turn/dequeue); the web has × on the bubble.
159
159
  registry.register("/unqueue", "remove your newest queued message before it runs", local: true, uis: [:attached],
160
160
  match: ->(text) { text.casecmp?("/unqueue") })
161
+ # chi share for the attached session (TerminalUI::ParticipantCommands):
162
+ # a participant's turns run on its worker, so the REPL points there.
163
+ registry.register("/share", "invite someone to review this session (/share NAME [--agent] [--expires 3d] [--cap 2])",
164
+ local: true, uis: [:attached], match: ->(text) { text.match?(%r{\A/share(?:\s.*)?\z}i) })
165
+ registry.register("/participants", "list this session's participants (revoke [P], cap P DOLLARS)",
166
+ local: true, uis: [:attached], match: ->(text) { text.match?(%r{\A/participants(?:\s.*)?\z}i) })
161
167
  registry
162
168
  end
163
169
 
@@ -204,7 +204,7 @@ module Samagotchi
204
204
  end
205
205
  link = SessionManager.spawn_session(
206
206
  prompt: start, preview: preview, title: previous.title, working_directory: previous.working_directory,
207
- model_name: choice.model, setup: SessionSetup.of(previous),
207
+ model_name: choice.model, setup: SessionSetup.of(previous), review: previous.review,
208
208
  continues: previous.id, note: SessionChain.note_text(previous, recap: recap),
209
209
  note_source: SessionChain::NOTE_SOURCE, state_dir: state_dir, before_spawn: before_spawn
210
210
  )
@@ -300,8 +300,9 @@ module Samagotchi
300
300
  # IdleRecap#request_now) and wait, up to +wait+ seconds, for recap.json
301
301
  # to change. A worker that is gone wrote its recap when it left; one
302
302
  # that has nothing new to say, too short a conversation, or recaps off
303
- # answers at once. Best effort: the continue goes on without.
304
- private_class_method def self.recap_before_archive(id, state_dir, wait:)
303
+ # answers at once. Best effort: the continue goes on without. A review
304
+ # fork (ReviewStart) asks the same, with nothing archived after.
305
+ def self.recap_before_archive(id, state_dir, wait:)
305
306
  return unless SessionManager.worker_live?(id, state_dir: state_dir)
306
307
 
307
308
  dir = Session.session_dir(id, state_dir: state_dir)
@@ -8,6 +8,7 @@ require_relative "atomic_file"
8
8
  require_relative "delivery"
9
9
  require_relative "log"
10
10
  require_relative "session"
11
+ require_relative "steer"
11
12
 
12
13
  module Samagotchi
13
14
  # A session directory's file inbox and outbox (see SessionManager for the
@@ -248,31 +249,56 @@ module Samagotchi
248
249
 
249
250
  # Whether a mid-turn drain leaves this unclaimed input file for a turn
250
251
  # of its own instead of merging it at a step boundary: a queued message
251
- # (`delivery: queue`) or an image message (steering merges text only).
252
+ # (`delivery: queue`), an image message (steering merges text only), or
253
+ # a participant's, whatever its delivery says: theirs always runs as its
254
+ # own turn, never inside another author's (D6; chi web queues it, and
255
+ # this is the worker's own layer).
252
256
  # The drain skips such a file without stopping at it, so a later text
253
257
  # line still merges; the drain's file filter reads this one predicate,
254
258
  # so what a boundary leaves changes in one place.
255
259
  def self.waits_for_turn_end?(input_file)
256
260
  data = JSON.parse(File.read(input_file))
257
- data.is_a?(Hash) && (Array(data["images"]).any? || Delivery.queue?(data["delivery"]))
261
+ data.is_a?(Hash) && turn_end_data?(data)
258
262
  rescue JSON::ParserError, SystemCallError
259
263
  false
260
264
  end
261
265
 
266
+ # Whether an unclaimed input file may be a participant's (it names a
267
+ # participant author): what the worker holds while the owner's Continue
268
+ # offer stands (Worker#run_input_files). An unreadable file counts:
269
+ # holding it costs nothing (it runs no turn), running it unread could.
270
+ def self.participant_input?(input_file)
271
+ data = JSON.parse(File.read(input_file))
272
+ !data.is_a?(Hash) || Steer.participant_author?(data["author"])
273
+ rescue JSON::ParserError, SystemCallError
274
+ true
275
+ end
276
+
277
+ # A parsed input file's #waits_for_turn_end?.
278
+ def self.turn_end_data?(data)
279
+ Array(data["images"]).any? || Delivery.queue?(data["delivery"]) || Steer.participant_author?(data["author"])
280
+ end
281
+
262
282
  # How the unclaimed input file carrying +enqueued_id+ waits: :turn_end
263
283
  # (a queue or an image message: it runs as a turn of its own, never
264
284
  # merged, #waits_for_turn_end?), :merges (a running turn's drain may
265
285
  # take it as a steer), or nil when none waits.
266
286
  # @return [Symbol, nil]
267
287
  def self.waiting_input(session_dir, enqueued_id)
288
+ data = waiting_input_data(session_dir, enqueued_id) or return nil
289
+ turn_end_data?(data) ? :turn_end : :merges
290
+ end
291
+
292
+ # The unclaimed input file carrying +enqueued_id+, as parsed; nil when
293
+ # none waits.
294
+ # @return [Hash, nil]
295
+ def self.waiting_input_data(session_dir, enqueued_id)
268
296
  id = enqueued_id.to_s
269
297
  return nil if id.empty?
270
298
 
271
299
  find_new_input_files(session_dir).each do |file|
272
300
  data = JSON.parse(File.read(file))
273
- next unless data.is_a?(Hash) && data["enqueued_id"] == id
274
-
275
- return Array(data["images"]).any? || Delivery.queue?(data["delivery"]) ? :turn_end : :merges
301
+ return data if data.is_a?(Hash) && data["enqueued_id"] == id
276
302
  rescue JSON::ParserError, SystemCallError
277
303
  next
278
304
  end