samagotchi 0.101.0 → 0.103.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 (111) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +67 -1
  3. data/bin/chi +31 -196
  4. data/docs/architecture.md +62 -6
  5. data/docs/cli.md +154 -7
  6. data/docs/configuration.md +32 -5
  7. data/docs/guardrails.md +2 -1
  8. data/docs/internals/bundles.md +1 -1
  9. data/docs/internals/engine.md +1 -1
  10. data/docs/internals/llm-context-forget.md +25 -1
  11. data/docs/internals/prompt-caching.md +8 -1
  12. data/docs/internals/remote-sessions.md +303 -0
  13. data/docs/internals/working-set.md +174 -15
  14. data/docs/plugins.md +32 -5
  15. data/docs/sessions.md +38 -14
  16. data/docs/sub-agent.md +8 -0
  17. data/docs/testing.md +7 -0
  18. data/lib/samagotchi/answer_command.rb +27 -25
  19. data/lib/samagotchi/bridge/turn_accumulator.rb +16 -0
  20. data/lib/samagotchi/bridge.rb +33 -7
  21. data/lib/samagotchi/bridge_client/event_stream.rb +81 -12
  22. data/lib/samagotchi/bridge_client/stream_request.rb +77 -0
  23. data/lib/samagotchi/bridge_client.rb +22 -38
  24. data/lib/samagotchi/bundle_command/check.rb +5 -1
  25. data/lib/samagotchi/bundle_command/try/command.rb +6 -6
  26. data/lib/samagotchi/bundle_command/try/sandbox.rb +3 -3
  27. data/lib/samagotchi/bundle_command.rb +4 -4
  28. data/lib/samagotchi/bundles/claude-peer/manifest.yml +2 -2
  29. data/lib/samagotchi/bundles/claude-peer/scripts/pair +30 -1
  30. data/lib/samagotchi/bundles/codex-peer/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/codex-peer/scripts/pair +49 -4
  32. data/lib/samagotchi/bundles/guardrails/guardrails/rules.yml +7 -4
  33. data/lib/samagotchi/bundles/guardrails/manifest.yml +1 -1
  34. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  35. data/lib/samagotchi/chi_invocation.rb +43 -0
  36. data/lib/samagotchi/cli/command.rb +3 -2
  37. data/lib/samagotchi/cli/flags.rb +5 -0
  38. data/lib/samagotchi/cli/parent_wait.rb +22 -13
  39. data/lib/samagotchi/commands/registry.rb +12 -1
  40. data/lib/samagotchi/config.rb +89 -53
  41. data/lib/samagotchi/context_command.rb +80 -73
  42. data/lib/samagotchi/engine.rb +138 -15
  43. data/lib/samagotchi/idle_recap.rb +7 -1
  44. data/lib/samagotchi/idle_scheduler.rb +16 -1
  45. data/lib/samagotchi/kernel_loop.rb +13 -1
  46. data/lib/samagotchi/launch_mode.rb +22 -0
  47. data/lib/samagotchi/llm_context_edit.rb +32 -10
  48. data/lib/samagotchi/llm_context_forget.rb +24 -8
  49. data/lib/samagotchi/llm_context_view.rb +19 -7
  50. data/lib/samagotchi/memory_bundle/installer.rb +2 -0
  51. data/lib/samagotchi/memory_bundle/manifest.rb +13 -2
  52. data/lib/samagotchi/message_parts.rb +8 -3
  53. data/lib/samagotchi/note_command.rb +8 -7
  54. data/lib/samagotchi/parent_report.rb +55 -43
  55. data/lib/samagotchi/plugin/context.rb +2 -2
  56. data/lib/samagotchi/prompt.rb +1 -1
  57. data/lib/samagotchi/recap_command.rb +68 -0
  58. data/lib/samagotchi/recap_setup.rb +27 -14
  59. data/lib/samagotchi/remote_command.rb +170 -0
  60. data/lib/samagotchi/remotes.rb +130 -0
  61. data/lib/samagotchi/run_options.rb +233 -0
  62. data/lib/samagotchi/send_command/busy.rb +58 -0
  63. data/lib/samagotchi/send_command/parent_gate.rb +23 -10
  64. data/lib/samagotchi/send_command/wait_target.rb +16 -3
  65. data/lib/samagotchi/send_command.rb +186 -118
  66. data/lib/samagotchi/session.rb +48 -16
  67. data/lib/samagotchi/session_access/contract.rb +129 -0
  68. data/lib/samagotchi/session_access/dispatch.rb +133 -0
  69. data/lib/samagotchi/session_access/http_transport.rb +109 -0
  70. data/lib/samagotchi/session_access/local.rb +349 -0
  71. data/lib/samagotchi/session_access/remote.rb +638 -0
  72. data/lib/samagotchi/session_access/web_bridge_client.rb +181 -0
  73. data/lib/samagotchi/session_access.rb +141 -0
  74. data/lib/samagotchi/session_archive_command.rb +9 -5
  75. data/lib/samagotchi/session_commands.rb +53 -6
  76. data/lib/samagotchi/session_config.rb +411 -0
  77. data/lib/samagotchi/session_delete_command.rb +8 -4
  78. data/lib/samagotchi/session_manager.rb +7 -2
  79. data/lib/samagotchi/session_setup.rb +15 -10
  80. data/lib/samagotchi/sessions_command.rb +42 -16
  81. data/lib/samagotchi/terminal_ui/attach_launcher.rb +54 -18
  82. data/lib/samagotchi/terminal_ui/attach_link.rb +104 -0
  83. data/lib/samagotchi/terminal_ui/attached_loop.rb +82 -76
  84. data/lib/samagotchi/terminal_ui/formatting.rb +10 -3
  85. data/lib/samagotchi/terminal_ui/local_link.rb +130 -0
  86. data/lib/samagotchi/terminal_ui/version_lines.rb +5 -3
  87. data/lib/samagotchi/terminal_ui.rb +8 -6
  88. data/lib/samagotchi/testing/bundle.rb +3 -2
  89. data/lib/samagotchi/title_command.rb +9 -11
  90. data/lib/samagotchi/version.rb +1 -1
  91. data/lib/samagotchi/web/app.rb +387 -79
  92. data/lib/samagotchi/web/public/app.js +2 -0
  93. data/lib/samagotchi/web/public/commands.js +8 -2
  94. data/lib/samagotchi/web/public/data.js +6 -4
  95. data/lib/samagotchi/web/public/index.html +37 -3
  96. data/lib/samagotchi/web/public/stage_frame.js +7 -2
  97. data/lib/samagotchi/web/public/stage_view.js +3 -2
  98. data/lib/samagotchi/web/public/stream_handlers.js +7 -1
  99. data/lib/samagotchi/web/public/turn_html.js +5 -0
  100. data/lib/samagotchi/web/public/working_set.js +247 -24
  101. data/lib/samagotchi/web/public/working_set_rail.js +39 -12
  102. data/lib/samagotchi/web/public/working_set_view.js +198 -25
  103. data/lib/samagotchi/web/session_access_routes.rb +343 -0
  104. data/lib/samagotchi/worker.rb +9 -6
  105. data/lib/samagotchi/worker_sidecar.rb +12 -5
  106. data/lib/samagotchi/working_set.rb +132 -20
  107. data/lib/samagotchi/working_set_command.rb +222 -0
  108. data/lib/samagotchi/working_set_pin.rb +34 -0
  109. data/lib/samagotchi/working_set_steer.rb +414 -0
  110. metadata +23 -2
  111. data/lib/samagotchi/bundle_session_settings.rb +0 -251
@@ -8,7 +8,7 @@ require_relative "session_commands"
8
8
  require_relative "parent_answers_command"
9
9
  require_relative "session_inbox"
10
10
  require_relative "session_manager"
11
- require_relative "bundle_session_settings"
11
+ require_relative "session_config"
12
12
  require_relative "session_chain"
13
13
  require_relative "context_quote"
14
14
  require_relative "reply_wait"
@@ -25,6 +25,8 @@ require_relative "cli/flags"
25
25
  require_relative "cli/parent_wait"
26
26
  require_relative "send_command/parent_gate"
27
27
  require_relative "send_command/wait_target"
28
+ require_relative "send_command/busy"
29
+ require_relative "session_access/local"
28
30
 
29
31
  module Samagotchi
30
32
  # `chi send`: put text into sessions as the user's message, the same as
@@ -46,7 +48,7 @@ module Samagotchi
46
48
 
47
49
  USAGE = <<~TEXT
48
50
  Usage: chi send [-m TEXT] [--image PATH]... [--cut | --queue] (ID|PREFIX)...
49
- chi send --new [--dir DIR] [--model M] [--llm-context LAYERS] [--thinking LEVEL] [--toolkit NAME] [--set BUNDLE.KEY=VALUE]... [--parent-answers LEVEL] [-m TEXT] [--image PATH]...
51
+ chi send --new [--dir DIR] [--model M] [--llm-context LAYERS] [--thinking LEVEL] [--toolkit NAME] [--set KEY=VALUE]... [--parent-answers LEVEL] [-m TEXT] [--image PATH]...
50
52
  chi send --new --continues (ID|PREFIX|last:ID) [--model M] [-m TEXT] [--image PATH]...
51
53
  chi send --wait [--timeout S] [--format json] [-m TEXT] [--image PATH]... (--new | ID)
52
54
  chi send --queue --wait [--timeout S] [--format json] [-m TEXT] ID
@@ -67,7 +69,8 @@ module Samagotchi
67
69
  --new start a new session with the message instead, as the
68
70
  web does, and print its id
69
71
  --dir DIR (--new) its folder, the project it belongs to; default
70
- the current one
72
+ the current one (with --remote: required, that
73
+ machine's absolute path)
71
74
  --continues ID
72
75
  (--new) start the next link of that session's chain:
73
76
  in its folder, on its model (or --model's; one whose
@@ -92,12 +95,15 @@ module Samagotchi
92
95
  (full, lean, child, a config or bundle one; default
93
96
  config's toolkit.default), and tools declared on top
94
97
  of it or left out (repeatable, a comma list too)
95
- --set BUNDLE.KEY=VALUE
96
- (--new) a bundle setting for this session, over
97
- config.yml's bundles: (repeatable; a key its bundle's
98
- manifest lists in session_settings:; numbers (3,
99
- .5) and booleans (true, off, no) are typed, the
100
- rest is text: --set cost-cap.cap=3)
98
+ --set KEY=VALUE
99
+ (--new) a setting for this session, as chi --set:
100
+ a core key a session may set (recap.enabled,
101
+ recap.sentences), typed by it, or BUNDLE.KEY over
102
+ config.yml's bundles: (a key its bundle's manifest
103
+ lists in session_settings:; numbers (3, .5) and
104
+ booleans (true, off, no) are typed, the rest is
105
+ text); repeatable: --set recap.enabled=false,
106
+ --set cost-cap.cap=3
101
107
  --parent-answers LEVEL
102
108
  (--new) what a parent agent may answer on its
103
109
  questions: hard, standard or soft, only stricter than
@@ -142,8 +148,9 @@ module Samagotchi
142
148
  queue), with --cut also cut (now, waits, off)
143
149
  Exit with --wait: 0 answered, 1 failed or gone, 2 usage, 3 a
144
150
  question waits, 4 still running (--timeout), 130 Ctrl-C.
145
- Only sessions on this machine. Answers show in the attached TUI
146
- or web page, not here.
151
+ Sessions on this machine, or another's: chi --remote NAME send …
152
+ (chi remote). Answers show in the attached TUI or web page, not
153
+ here.
147
154
  Find ids with: chi sessions list --live [--scope=all] [--format tsv]
148
155
  TEXT
149
156
 
@@ -203,18 +210,44 @@ module Samagotchi
203
210
 
204
211
  UNKNOWN_VISION = VisionSupport::Answer.new(value: nil, reason: nil)
205
212
 
213
+ # What to say when +answer+ (.vision_answer's for +model_name+) is a
214
+ # no, or nil: the words chi send and chi web's turn and create routes
215
+ # refuse images with.
216
+ def self.vision_refusal(model_name, answer)
217
+ return nil unless answer.no?
218
+
219
+ name = model_name.to_s.strip
220
+ name = Samagotchi::Config.get("default.model").to_s.strip if name.empty?
221
+ name = "the model" if name.empty?
222
+ "#{name} can't take images (#{answer.reason}); send text only or switch the model (/model)"
223
+ end
224
+
225
+ # The model a --continues link of +previous+ runs, for the images
226
+ # check: +model+'s (blank: the previous link's, else the default it
227
+ # falls back to; SessionContinue.model_for).
228
+ # @return [Array(String, String)] [model_name, model_typed]
229
+ # @raise [ModelProfile::MissingModel] a model it can't start on
230
+ def self.continued_model(previous, model)
231
+ choice = SessionContinue.model_for(previous, model)
232
+ inherited = model.to_s.strip.empty? && choice.warning.nil?
233
+ inherited ? [previous.model_name, previous.model_typed] : [choice.model, nil]
234
+ end
235
+
206
236
  # A no from the config (models: / hosts: vision: false) holds without
207
237
  # the server.
208
238
  def self.configured_no?(answer) = answer.reason.to_s.include?("sets vision: false")
209
239
  private_class_method :configured_no?
210
240
 
211
241
  # @param argv [Array<String>] the arguments after "send"
212
- def initialize(argv, stdin: $stdin, stdout: $stdout, stderr: $stderr, state_dir: nil)
242
+ # @param access [SessionAccess::Local, nil] where the sessions are;
243
+ # default this machine's, in +state_dir+
244
+ def initialize(argv, stdin: $stdin, stdout: $stdout, stderr: $stderr, state_dir: nil, access: nil)
213
245
  @argv = argv.dup
214
246
  @stdin = stdin
215
247
  @stdout = stdout
216
248
  @stderr = stderr
217
249
  @state_dir = state_dir || Session.default_state_dir
250
+ @access = access || SessionAccess::Local.new(state_dir: @state_dir)
218
251
  end
219
252
 
220
253
  private
@@ -256,17 +289,24 @@ module Samagotchi
256
289
 
257
290
  # A parent agent's /continue yes held to guardrails.parent_answers,
258
291
  # and a /parent-answers that loosens: refused before anything is sent.
259
- gate = ParentGate.new(options, state_dir: @state_dir)
260
- if prompt && (refusal = gate.continue_refusal(prompt))
261
- @stderr.puts("chi send: #{refusal}")
262
- return CLI::Exit::FAILED
263
- end
264
- if prompt && gate.loosens?(prompt)
265
- error_line("chi send: refused: #{ParentAnswersCommand::REFUSED}")
266
- return CLI::Exit::FAILED
292
+ # Machine-local (the targets' session files, this machine's
293
+ # config.yml): remotely the server's (its /turn and create routes
294
+ # check the line chi send's client_id marks; the worker checks a
295
+ # CLI_ANSWER /continue again).
296
+ unless @access.remote?
297
+ gate = ParentGate.new(options, state_dir: @state_dir)
298
+ if prompt && (refusal = gate.continue_refusal(prompt))
299
+ @stderr.puts("chi send: #{refusal}")
300
+ return CLI::Exit::FAILED
301
+ end
302
+ if prompt && gate.loosens?(prompt)
303
+ error_line("chi send: refused: #{ParentAnswersCommand::REFUSED}")
304
+ return CLI::Exit::FAILED
305
+ end
267
306
  end
268
307
  # A file that is not there or not an image: a run-time failure (1),
269
308
  # reported in the --format json line too; --image itself was fine.
309
+ # Client-side on any backend: the files are this machine's.
270
310
  return CLI::Exit::FAILED unless ingest_images(options[:images])
271
311
 
272
312
  return run_new(prompt, options) if options[:new]
@@ -369,11 +409,13 @@ module Samagotchi
369
409
 
370
410
  options[:parent_answers] = level
371
411
  end
412
+ return remote_new_options(options, words) if @access.remote?
413
+
372
414
  toolkit = Toolkit.from_flags(name: options[:toolkit], add: options[:tools], remove: options[:no_tools])
373
415
  options[:toolkit_value] = toolkit if toolkit
374
416
  begin
375
- options[:bundle_settings] = BundleSessionSettings.from_flags(options[:sets]) unless Array(options[:sets]).empty?
376
- rescue BundleSessionSettings::Error => e
417
+ options[:settings] = SessionConfig.from_flags(options[:sets]) unless Array(options[:sets]).empty?
418
+ rescue SessionConfig::Error => e
377
419
  return usage_error(e.message)
378
420
  end
379
421
 
@@ -384,6 +426,35 @@ module Samagotchi
384
426
  options
385
427
  end
386
428
 
429
+ # --new against a remote: its folder is given, as that machine's
430
+ # absolute path (D4: none is guessed from this one's), and the setup
431
+ # flags go as typed (SetupWords): the toolkit's default, the bundles a
432
+ # --set names and the folder are the remote's to check.
433
+ def remote_new_options(options, llm_words)
434
+ unless options[:continues]
435
+ # One line: the fix is in it, the whole usage would bury it.
436
+ return usage_error("--new on #{remote_name} needs --dir: a folder there", usage: nil) unless options[:dir]
437
+ unless options[:dir].start_with?("/")
438
+ return usage_error("--dir is a folder on #{remote_name}: give its absolute path", usage: nil)
439
+ end
440
+ end
441
+
442
+ settings = Array(options[:sets]).to_h do |pair|
443
+ key, sep, value = pair.partition("=")
444
+ return usage_error("--set takes KEY=VALUE, not #{pair}") if sep.empty? || key.strip.empty?
445
+
446
+ [key.strip, value]
447
+ end
448
+ options[:setup_words] = SessionAccess::SetupWords.new(
449
+ llm_context: (llm_words unless llm_words.empty?), thinking: options[:thinking]&.to_s,
450
+ toolkit: options[:toolkit], tools: Array(options[:tools]), no_tools: Array(options[:no_tools]),
451
+ settings: (settings unless settings.empty?), parent_answers: options[:parent_answers]
452
+ )
453
+ options
454
+ end
455
+
456
+ def remote_name = @access.respond_to?(:name) ? @access.name : "the remote"
457
+
387
458
  # With both, stdin is the context quoted above the message; with one,
388
459
  # it goes in as is. nil when both are blank.
389
460
  def compose(context, message)
@@ -406,6 +477,8 @@ module Samagotchi
406
477
  model, typed = continued_model(options)
407
478
  return 1 if model == false
408
479
 
480
+ # Machine-local (this machine's model registry): remotely the
481
+ # server's (P2: the create route checks vision).
409
482
  if images && (refusal = vision_refusal(model, typed: typed))
410
483
  error_line("chi send: refused: #{refusal}")
411
484
  return 1
@@ -416,21 +489,11 @@ module Samagotchi
416
489
  # says whether it ran as one.
417
490
  through_worker = images || command_like?(prompt)
418
491
  begin
419
- start = through_worker ? { prompt: nil, preview: prompt } : { prompt: prompt }
420
- session = if options[:continues]
421
- SessionManager.continue_session(options[:continues], **start, model: options[:model],
422
- state_dir: @state_dir)
423
- else
424
- SessionManager.spawn_session(**start, working_directory: options[:dir],
425
- model_name: options[:model],
426
- setup: SessionSetup.new(llm_context: options[:llm_context],
427
- thinking: options[:thinking],
428
- toolkit: options[:toolkit_value],
429
- bundle_settings: options[:bundle_settings] || {},
430
- parent_answers: options[:parent_answers]),
431
- state_dir: @state_dir)
432
- end
433
- rescue SessionContinue::Refused, SessionManager::ArchiveRefused, SessionManager::OwnedByTUI => e
492
+ session = @access.create(new_session_spec(prompt, options, through_worker: through_worker))
493
+ rescue SessionAccess::BadRequest => e
494
+ return usage_error(e.message)
495
+ rescue SessionContinue::Refused, SessionManager::ArchiveRefused, SessionManager::OwnedByTUI,
496
+ SessionAccess::Refused => e
434
497
  error_line("chi send: refused: #{e.message}")
435
498
  return 1
436
499
  rescue StandardError => e
@@ -438,9 +501,13 @@ module Samagotchi
438
501
  return 1
439
502
  end
440
503
  error_line("chi send: warning: #{session.model_warning}") if session.model_warning
441
- if (capped = Guardrails::ParentPolicy.capped_note(options[:parent_answers]))
442
- error_line("chi send: warning: --parent-answers #{capped}")
443
- end
504
+ # Remotely the server's config.yml caps it (its create's warning).
505
+ capped = if @access.remote?
506
+ session.parent_answers_warning
507
+ else
508
+ Guardrails::ParentPolicy.capped_note(options[:parent_answers])
509
+ end
510
+ error_line("chi send: warning: --parent-answers #{capped}") if capped
444
511
  if through_worker
445
512
  return 1 unless deliver_new(session, prompt)
446
513
  else
@@ -450,23 +517,45 @@ module Samagotchi
450
517
  return 0 unless options[:wait]
451
518
  return report_command(session.id) if @sent_command
452
519
 
453
- wait_for_reply(session.id, cursor: nil, baseline: baseline_of(session, question_id: nil),
520
+ start = @access.prepare_wait(session.id, session: session, created: true)
521
+ wait_for_reply(session.id, cursor: start.cursor, baseline: start.baseline,
454
522
  timeout: options[:timeout], **WaitTarget.first_message(@delivered).to_h)
455
523
  end
456
524
 
525
+ # What chi send --new asks to create: through the worker (images, a
526
+ # session command), it starts idle with the message as its preview.
527
+ # Without --dir its folder is the current one (spawn_session's
528
+ # default): machine-local, so remotely --dir is required (D4).
529
+ # @return [SessionAccess::NewSession]
530
+ def new_session_spec(prompt, options, through_worker:)
531
+ start = through_worker ? { prompt: nil, preview: prompt } : { prompt: prompt }
532
+ # For a remote's create route, which checks them as this machine does
533
+ # before it creates (the first line's client_id, the images' model).
534
+ start = start.merge(client_id: client_id_for(prompt), images: !@images.empty?)
535
+ if options[:continues]
536
+ return SessionAccess::NewSession.new(**start, continues: options[:continues], model_name: options[:model])
537
+ end
538
+
539
+ setup = options[:setup_words] || SessionSetup.new(llm_context: options[:llm_context], thinking: options[:thinking],
540
+ toolkit: options[:toolkit_value], settings: options[:settings],
541
+ parent_answers: options[:parent_answers])
542
+ SessionAccess::NewSession.new(**start, working_directory: options[:dir], model_name: options[:model], setup: setup)
543
+ end
544
+
457
545
  # The model the new session will run, for the images check: --model
458
546
  # (nil: the default), or with --continues the one the new link will run
459
547
  # (SessionContinue.model_for: --model's, else the previous link's, else
460
- # the default it falls back to).
548
+ # the default it falls back to). Machine-local (the previous link's
549
+ # file, this machine's models): remotely the server's, with the vision
550
+ # check (P2).
461
551
  # @return [Array, false] [model_name, model_typed], or false after the
462
552
  # error line (no such session, a model it can't start on)
463
553
  def continued_model(options)
464
- return [options[:model], nil] unless options[:continues]
554
+ # Remotely the server reads the previous link (its vision check).
555
+ return [options[:model], nil] unless options[:continues] && !@access.remote?
465
556
 
466
557
  previous = Session.load(SessionChain.resolve(options[:continues], state_dir: @state_dir), state_dir: @state_dir)
467
- choice = SessionContinue.model_for(previous, options[:model])
468
- inherited = options[:model].to_s.strip.empty? && choice.warning.nil?
469
- inherited ? [previous.model_name, previous.model_typed] : [choice.model, nil]
558
+ self.class.continued_model(previous, options[:model])
470
559
  rescue ModelProfile::MissingModel => e
471
560
  error_line("chi send: could not start a session: #{e.message}")
472
561
  false
@@ -492,40 +581,21 @@ module Samagotchi
492
581
  # @return [Integer] the exit status
493
582
  def run_wait(prompt, options)
494
583
  id = resolve(options[:ids].first) or return 1
495
- session = Session.load(id, state_dir: @state_dir)
496
- if session.status == Session::STATUS_RUNNING && (owner = SessionManager.session_owner(id, state_dir: @state_dir)) &&
497
- (!@queue || session.waiting_question(live: owner.worker?))
498
- # The turn waits on a question: the message would only queue
499
- # behind it, and the answer goes in with chi answer.
500
- if (waiting = session.waiting_question(live: owner.worker?))
501
- # The whole question (its options, its tags) for what a parent may
502
- # give: config.yml tightened by the session's own parent_answers.
503
- strategy = Guardrails::ParentPolicy.for_session(session)
504
- question = ParentReport.question(session.pending_question, strategy: strategy)
505
- if ParentReport.approval?(waiting)
506
- error_line("#{id[0, 8]} waiting for an approval: #{ParentReport.approval_advice(question, strategy: strategy)} " \
507
- "(#{ParentReport.answer_with(id, question)})")
508
- else
509
- error_line("#{id[0, 8]} waiting for an answer: #{ParentReport.answer_with(id, question)} (or --text); " \
510
- "chi --attach #{id} shows it")
511
- end
512
- else
513
- error_line("#{id[0, 8]} busy: a turn is running; wait or attach")
514
- end
584
+ # Local: one read for the check and the baseline; remotely the
585
+ # server's wait prepare route reads both (Busy's words).
586
+ session = @access.show(id) unless @access.remote?
587
+ if (busy = @access.busy(id, queue: @queue, session: session))
588
+ error_line("#{id[0, 8]} #{busy.message(via: @access.invocation)}")
515
589
  return 1
516
590
  end
517
591
 
518
- cursor = ReplyWait.newest_reply(id, state_dir: @state_dir)
519
- baseline = baseline_of(session)
520
- running_turn = if session.status == Session::STATUS_RUNNING
521
- ReplyWait.own_turn(session, session_dir: Session.session_dir(id, state_dir: @state_dir))
522
- end
592
+ start = @access.prepare_wait(id, session: session)
523
593
  return 1 unless deliver(id, prompt)
524
594
  return report_command(id) if @sent_command
525
595
 
526
- target = WaitTarget.message(@delivered, queue: @queue, running: session.status == Session::STATUS_RUNNING,
527
- running_turn: running_turn)
528
- wait_for_reply(id, cursor: cursor, baseline: baseline, timeout: options[:timeout], **target.to_h)
596
+ target = WaitTarget.message(@delivered, queue: @queue, running: start.running,
597
+ running_turn: (start.own_turn if start.running))
598
+ wait_for_reply(id, cursor: start.cursor, baseline: start.baseline, timeout: options[:timeout], **target.to_h)
529
599
  end
530
600
 
531
601
  # --wait with no message: the session's next reply, sending nothing,
@@ -543,24 +613,15 @@ module Samagotchi
543
613
  # @return [Integer] the exit status
544
614
  def run_wait_only(options)
545
615
  id = resolve(options[:ids].first) or return 1
546
- session = Session.load(id, state_dir: @state_dir)
547
- session_dir = Session.session_dir(id, state_dir: @state_dir)
548
616
  requested_turn = options[:turn]&.to_s
549
- if requested_turn && !ReplyWait.known_turn?(session, session_dir: session_dir, turn: requested_turn)
617
+ start = @access.prepare_wait(id, turn: requested_turn)
618
+ if requested_turn && !start.known_turn
550
619
  error_line("chi send: turn #{requested_turn} is not a running, queued, or last ended turn")
551
620
  return 1
552
621
  end
553
- live = session.status == Session::STATUS_RUNNING || SessionManager.session_owner(id, state_dir: @state_dir)
554
- target = WaitTarget.wait_only(session, session_dir: session_dir, requested: requested_turn)
555
- wait_for_reply(id, cursor: ReplyWait.newest_reply(id, state_dir: @state_dir),
556
- baseline: baseline_of(session),
557
- timeout: options[:timeout], owner_grace: live ? self.class::WORKER_GONE_AFTER : nil, **target.to_h)
558
- end
559
-
560
- # The session as it was before the message went in (ReplyWait's
561
- # baseline).
562
- def baseline_of(session, **)
563
- ReplyWait.baseline_of(session, **)
622
+ target = WaitTarget.after(start, requested: requested_turn)
623
+ wait_for_reply(id, cursor: start.cursor, baseline: start.baseline,
624
+ timeout: options[:timeout], owner_grace: start.live ? self.class::WORKER_GONE_AFTER : nil, **target.to_h)
564
625
  end
565
626
 
566
627
  # A new idle session's first turn, with the images. Its worker's Bridge
@@ -568,14 +629,15 @@ module Samagotchi
568
629
  # and the spawned one takes its lock only once it runs.
569
630
  # @return [Boolean] whether the message was queued
570
631
  def deliver_new(session, prompt)
571
- dir = Session.session_dir(session.id, state_dir: @state_dir)
572
632
  result = nil
573
633
  begin
574
- refs = copy_images(dir)
575
- if BridgeClient.wait_for(session.id, session_dir: dir, timeout: SessionManager::TURN_BRIDGE_WAIT)
576
- result = SessionManager.deliver_turn(session.id, prompt: prompt, client_id: client_id_for(prompt), images: refs,
577
- state_dir: @state_dir)
634
+ refs = upload_images(session.id)
635
+ if @access.await_worker(session.id, timeout: SessionManager::TURN_BRIDGE_WAIT)
636
+ result = @access.deliver_turn(session.id, prompt: prompt, client_id: client_id_for(prompt), images: refs)
578
637
  end
638
+ rescue SessionAccess::Refused => e
639
+ @info.puts("#{session.id} refused: #{e.message}")
640
+ return false
579
641
  rescue StandardError => e
580
642
  @info.puts("#{session.id} failed: #{e.message}")
581
643
  return false
@@ -583,11 +645,12 @@ module Samagotchi
583
645
  # Kept, not deleted: it holds the images, and the message shows as
584
646
  # its preview; the user can attach and send it again.
585
647
  unless result
586
- @info.puts("#{session.id} failed: its worker did not start; the session is kept (chi --attach #{session.id})")
648
+ attach = @access.invocation.attach(session.id)
649
+ @info.puts("#{session.id} failed: its worker did not start; the session is kept#{" (#{attach})" if attach}")
587
650
  return false
588
651
  end
589
652
  unless result.accepted?
590
- @info.puts("#{session.id} failed: #{result.detail || "could not queue it"}")
653
+ @info.puts("#{session.id} #{refused_word(result)}: #{result.detail || "could not queue it"}")
591
654
  return false
592
655
  end
593
656
 
@@ -599,6 +662,19 @@ module Samagotchi
599
662
 
600
663
  SENT_COMMAND = "sent as a session command"
601
664
 
665
+ # A remote's refusals of what this machine checks before sending (a
666
+ # parent's /continue yes, a loosening /parent-answers, images to a
667
+ # model that can't see them): its turn route's error codes.
668
+ REMOTE_REFUSALS = %w[parent_answers_refused parent_continue_refused no_vision].freeze
669
+
670
+ # How a delivery that didn't go in reads: refused (a worker older than
671
+ # queueing would steer it; a remote refused it as chi send refuses it
672
+ # here) or failed.
673
+ def refused_word(result)
674
+ refused = result.error == Delivery::QUEUE_UNAVAILABLE["error"] || REMOTE_REFUSALS.include?(result.error)
675
+ refused ? "refused" : "failed"
676
+ end
677
+
602
678
  # chi send's client id, or chi answer's for a parent agent's /continue
603
679
  # yes (the worker holds that to its guardrails.parent_answers).
604
680
  def client_id_for(prompt) = ParentGate.parent_continue?(prompt) ? ClientId::CLI_ANSWER : CLIENT_ID
@@ -633,13 +709,13 @@ module Samagotchi
633
709
  CLI::Exit::FAILED
634
710
  end
635
711
 
636
- def local_refusal(name, id) = SessionCommands.ui_only_refusal(name, id, runner: "chi send")
712
+ def local_refusal(name, id) = SessionCommands.ui_only_refusal(name, id, runner: "chi send", remote: @access.invocation.remote)
637
713
 
638
714
  # --wait after a message that ran as a session command: no reply comes
639
715
  # for it. Its output shows where the session is open.
640
716
  # @return [Integer] 0
641
717
  def report_command(id)
642
- detail = "#{SENT_COMMAND}: no reply to wait for (its output shows in chi --attach #{id} or the web)"
718
+ detail = "#{SENT_COMMAND}: no reply to wait for (its output shows in #{@access.invocation.open_it(id)})"
643
719
  if @json
644
720
  @stdout.puts(JSON.generate({ status: "command", session_id: id, detail: detail }))
645
721
  @stdout.flush
@@ -653,14 +729,16 @@ module Samagotchi
653
729
  # @return [Boolean] whether the message was queued
654
730
  def deliver(id, prompt)
655
731
  short = id[0, 8]
656
- session = Session.load(id, state_dir: @state_dir)
732
+ session = @access.show(id)
733
+ # Machine-local (this machine's model registry): remotely the
734
+ # server's (P2), as for --new.
657
735
  if !@images.empty? && (refusal = vision_refusal(session.model_name, typed: session.model_typed))
658
736
  @info.puts("#{short} refused: #{refusal}")
659
737
  return false
660
738
  end
661
- owner = SessionManager.session_owner(id, state_dir: @state_dir)
739
+ owner = @access.owner(id)
662
740
  running = owner && session.status == Session::STATUS_RUNNING
663
- refs = copy_images(Session.session_dir(id, state_dir: @state_dir))
741
+ refs = upload_images(id)
664
742
  # --cut asks the running turn for a cut (to an idle session an
665
743
  # ordinary message: nothing to cut). --queue always goes as a queue,
666
744
  # idle or not: the Bridge acks next_step to an idle worker and the
@@ -670,12 +748,9 @@ module Samagotchi
670
748
  delivery = if @queue then Delivery::QUEUE
671
749
  elsif @cut && running then Delivery::CUT
672
750
  end
673
- result = SessionManager.deliver_turn(id, prompt: prompt, client_id: client_id_for(prompt), images: refs, state_dir: @state_dir,
674
- delivery: delivery)
751
+ result = @access.deliver_turn(id, prompt: prompt, client_id: client_id_for(prompt), images: refs, delivery: delivery)
675
752
  unless result.accepted?
676
- # A worker older than queueing would steer it: refused, not sent.
677
- word = result.error == Delivery::QUEUE_UNAVAILABLE["error"] ? "refused" : "failed"
678
- @info.puts("#{short} #{word}: #{result.detail || "could not queue it"}")
753
+ @info.puts("#{short} #{refused_word(result)}: #{result.detail || "could not queue it"}")
679
754
  return false
680
755
  end
681
756
 
@@ -752,14 +827,12 @@ module Samagotchi
752
827
  # What to say when +model_name+ is known not to take images, or nil
753
828
  # (it does, or it is unknown: sent as before). Asked once per model.
754
829
  def vision_refusal(model_name, typed: nil)
830
+ # Remotely the server's (check_vision on its turn and create routes).
831
+ return nil if @access.remote?
832
+
755
833
  @vision ||= {}
756
834
  answer = @vision[[model_name.to_s, typed.to_s]] ||= self.class.vision_answer(model_name, typed: typed)
757
- return nil unless answer.no?
758
-
759
- name = model_name.to_s.strip
760
- name = Samagotchi::Config.get("default.model").to_s.strip if name.empty?
761
- name = "the model" if name.empty?
762
- "#{name} can't take images (#{answer.reason}); send text only or switch the model (/model)"
835
+ self.class.vision_refusal(model_name, answer)
763
836
  end
764
837
 
765
838
  # Each --image read, converted and downscaled once, into a scratch
@@ -778,13 +851,8 @@ module Samagotchi
778
851
  false
779
852
  end
780
853
 
781
- # The images' files copied into a session dir, as the refs a turn takes.
782
- def copy_images(session_dir)
783
- @images.map do |ref|
784
- ImageStore.copy_file(ref, from: @image_dir, to: session_dir)
785
- { file: ref[:file], name: ref[:name] }
786
- end
787
- end
854
+ # The images' files copied into the session, as the refs a turn takes.
855
+ def upload_images(id) = @access.upload_images(id, @images, from: @image_dir)
788
856
 
789
857
  def with_images
790
858
  case @images.size