samagotchi 0.184.0 → 0.185.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +45 -1
  3. data/docs/architecture.md +1 -1
  4. data/docs/bundles.md +62 -35
  5. data/docs/cli.md +10 -1
  6. data/docs/configuration.md +1 -1
  7. data/docs/context.md +76 -10
  8. data/docs/guardrails.md +7 -2
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/block-renderers.md +4 -2
  11. data/docs/internals/bridge.md +6 -2
  12. data/docs/internals/llm-context-forget.md +6 -0
  13. data/docs/internals/participants.md +4 -1
  14. data/docs/internals/remote-sessions.md +3 -1
  15. data/docs/internals/session-lifecycle.md +1 -1
  16. data/docs/internals/web-frontend.md +23 -6
  17. data/docs/mcp-server.md +6 -2
  18. data/docs/scheduling.md +5 -0
  19. data/docs/sessions.md +12 -2
  20. data/docs/sub-agent.md +48 -3
  21. data/docs/thin-clients.md +9 -2
  22. data/lib/samagotchi/agent_caller.rb +97 -0
  23. data/lib/samagotchi/bridge.rb +7 -7
  24. data/lib/samagotchi/bundles/claude-peer/manifest.yml +14 -8
  25. data/lib/samagotchi/bundles/claude-peer/plugin.rb +3 -3
  26. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +49 -30
  27. data/lib/samagotchi/bundles/claude-peer/scripts/pair +2 -2
  28. data/lib/samagotchi/bundles/claude-peer/scripts/pair-remote +123 -0
  29. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +11 -3
  30. data/lib/samagotchi/bundles/codex-peer/manifest.yml +10 -8
  31. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  32. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +29 -8
  33. data/lib/samagotchi/bundles/codex-peer/scripts/pair +1 -1
  34. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +11 -3
  35. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  36. data/lib/samagotchi/bundles/mcp/http_client.rb +19 -2
  37. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  38. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/system/self_map.md +2 -0
  40. data/lib/samagotchi/client_id.rb +61 -1
  41. data/lib/samagotchi/command_intake.rb +16 -8
  42. data/lib/samagotchi/context_absorber.rb +212 -46
  43. data/lib/samagotchi/delivery.rb +15 -0
  44. data/lib/samagotchi/driver_command.rb +68 -0
  45. data/lib/samagotchi/engine/block_fix.rb +2 -2
  46. data/lib/samagotchi/engine.rb +13 -5
  47. data/lib/samagotchi/engine_peers.rb +6 -0
  48. data/lib/samagotchi/guardrails/pair_boundary.rb +1 -1
  49. data/lib/samagotchi/mcp_command.rb +7 -2
  50. data/lib/samagotchi/mcp_server/tools.rb +9 -3
  51. data/lib/samagotchi/objectives_track.rb +2 -1
  52. data/lib/samagotchi/owner_prompt.rb +5 -1
  53. data/lib/samagotchi/parent_report.rb +9 -5
  54. data/lib/samagotchi/plugin/peer.rb +10 -4
  55. data/lib/samagotchi/reply_wait.rb +12 -3
  56. data/lib/samagotchi/schedules.rb +10 -7
  57. data/lib/samagotchi/send_command/parent_gate.rb +3 -1
  58. data/lib/samagotchi/send_command.rb +45 -8
  59. data/lib/samagotchi/session.rb +9 -1
  60. data/lib/samagotchi/session_access/ask.rb +5 -2
  61. data/lib/samagotchi/session_access/contract.rb +2 -0
  62. data/lib/samagotchi/session_access/local.rb +2 -1
  63. data/lib/samagotchi/session_access/remote.rb +18 -2
  64. data/lib/samagotchi/session_access.rb +4 -2
  65. data/lib/samagotchi/session_command_catalog.rb +8 -0
  66. data/lib/samagotchi/session_commands.rb +9 -0
  67. data/lib/samagotchi/session_continue.rb +4 -1
  68. data/lib/samagotchi/session_inbox.rb +2 -0
  69. data/lib/samagotchi/session_inbox_delivery.rb +4 -2
  70. data/lib/samagotchi/session_manager/delivery.rb +50 -5
  71. data/lib/samagotchi/session_manager/spawn.rb +7 -1
  72. data/lib/samagotchi/steer.rb +95 -20
  73. data/lib/samagotchi/terminal_ui/formatting.rb +12 -2
  74. data/lib/samagotchi/tool_activity.rb +4 -0
  75. data/lib/samagotchi/tool_declarations.rb +22 -1
  76. data/lib/samagotchi/tool_names.rb +4 -0
  77. data/lib/samagotchi/toolkit.rb +3 -2
  78. data/lib/samagotchi/tools/ask_session.rb +208 -0
  79. data/lib/samagotchi/tools/builtin_calls.rb +1 -0
  80. data/lib/samagotchi/tools/builtins.rb +5 -0
  81. data/lib/samagotchi/turn_checkpoint.rb +19 -2
  82. data/lib/samagotchi/turn_stages/context_judge.rb +3 -1
  83. data/lib/samagotchi/turn_stages/objectives.rb +4 -2
  84. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +3 -0
  85. data/lib/samagotchi/version.rb +1 -1
  86. data/lib/samagotchi/visitor.rb +37 -0
  87. data/lib/samagotchi/web/app.rb +1 -1
  88. data/lib/samagotchi/web/ask_routes.rb +6 -4
  89. data/lib/samagotchi/web/message_display.rb +15 -2
  90. data/lib/samagotchi/web/public/app.js +1 -1
  91. data/lib/samagotchi/web/public/block_fix.js +11 -3
  92. data/lib/samagotchi/web/public/history_shape.js +3 -1
  93. data/lib/samagotchi/web/public/index.html +8 -0
  94. data/lib/samagotchi/web/public/peer_links.js +27 -4
  95. data/lib/samagotchi/web/public/peer_note.js +19 -3
  96. data/lib/samagotchi/web/public/peer_text.js +45 -0
  97. data/lib/samagotchi/web/public/picture_regions.js +2 -2
  98. data/lib/samagotchi/web/public/turn_events.js +19 -0
  99. data/lib/samagotchi/web/public/working_set_view.js +11 -2
  100. data/lib/samagotchi/web/session_control.rb +1 -1
  101. data/lib/samagotchi/web/session_create.rb +11 -7
  102. data/lib/samagotchi/worker/command_queue.rb +5 -2
  103. data/lib/samagotchi/worker/senders.rb +79 -0
  104. data/lib/samagotchi/worker.rb +21 -18
  105. data/lib/samagotchi/worker_inbound.rb +12 -4
  106. data/lib/samagotchi/worker_participant_gate.rb +1 -3
  107. data/lib/samagotchi/worker_wakes.rb +12 -0
  108. metadata +8 -1
@@ -14,16 +14,20 @@ module Samagotchi
14
14
  # carries the turn's id), or TurnCheckpoint's line for a turn killed
15
15
  # before its first boundary (stamped, no id). A !command's output, a
16
16
  # declined continue's reason and KernelLoop's recovery prompt are
17
- # neither; steers, notes and reminders carry their kind.
17
+ # neither; steers, notes and reminders carry their kind. A visitor's
18
+ # opener (an agent's in a session it doesn't drive) carries its source.
18
19
  def message?(message)
19
20
  field(message, :role).to_s == "user" &&
20
21
  !Steer.participant_author?(field(message, :author)) &&
22
+ !(field(message, :kind).to_s.empty? && !field(message, :source).to_s.empty?) &&
21
23
  !%w[input steer note reminder].include?(field(message, :kind).to_s) &&
22
24
  !field(message, :preserve_literals) &&
23
25
  !(field(message, :turn_id) || field(message, MessageTime::KEY)).nil?
24
26
  end
25
27
 
26
28
  # Whether a turn by +author+ is the owner's own: not a participant's.
29
+ # The callers ask Visitor.of? beside it, for a visitor's turn (its
30
+ # origin's client id).
27
31
  def turn?(author:) = !Steer.participant_author?(author)
28
32
 
29
33
  def field(hash, key)
@@ -75,14 +75,18 @@ module Samagotchi
75
75
  end
76
76
  end
77
77
 
78
- # The reasons a worker refuses a participant's queued turn
79
- # (WorkerParticipantGate#refusal), as its settled record's cancel_reason.
78
+ # The reasons a worker refuses a queued turn before it runs, as its
79
+ # settled record's cancel_reason: a participant's
80
+ # (WorkerParticipantGate#refusal), and a visitor's at session.max_wakes
81
+ # (Worker#refuse_visitor, Visitor::CAP_REASON).
80
82
  REFUSED_LINES = { "revoked" => ParticipantMessages::TOKEN_ENDED,
81
83
  "outdated" => ParticipantMessages::TOKEN_OUTDATED,
82
- "cap_reached" => ParticipantMessages::CAP_REACHED }.freeze
84
+ "cap_reached" => ParticipantMessages::CAP_REACHED,
85
+ "max_wakes" => "session.max_wakes turns ran in a row with no message from this session's owner; " \
86
+ "it runs again after their next message" }.freeze
83
87
 
84
- # A participant's turn the worker refused before it ran: by its
85
- # cancel_reason (chi web's participant wait sends no outcome).
88
+ # A participant's or a visitor's turn the worker refused before it ran:
89
+ # by its cancel_reason (chi web's participant wait sends no outcome).
86
90
  def refused?(result)
87
91
  result.status == :no_reply && REFUSED_LINES.key?(result.cancel_reason.to_s) &&
88
92
  [nil, "canceled"].include?(result.outcome)
@@ -74,6 +74,8 @@ module Samagotchi
74
74
  LAST_SEND = "last-send.json"
75
75
  SKILL_FILE = "chi-peer-SKILL.md"
76
76
  PAIR_PLACEHOLDER = "__CHI_PEER_PAIR__"
77
+ # scripts/pair-remote's path (claude-peer's skill: the SSH pairing).
78
+ PAIR_REMOTE_PLACEHOLDER = "__CHI_PEER_PAIR_REMOTE__"
77
79
  PAYLOADS_PLACEHOLDER = "__CHI_PEER_PAYLOADS__"
78
80
  DIFF_LINES = 20
79
81
  # Under the session's data dir: the moved message went (or was tried).
@@ -261,8 +263,8 @@ module Samagotchi
261
263
  end
262
264
 
263
265
  def send_text(ctx, kind, text)
264
- "#{deliver(ctx, kind: kind, title: text_title(text), text: text, by: "user", salt: command_salt)}; #{self.class::NAME}'s answer comes as the " \
265
- "#{self.class::OUTBOX} context"
266
+ "#{deliver(ctx, kind: kind, title: text_title(text), text: text, by: "user", salt: command_salt)}; #{self.class::NAME}'s answer comes as a " \
267
+ "note with its text (#{self.class::OUTBOX})"
266
268
  rescue SendError => e
267
269
  "#{self.class::COMMAND}: #{e.message}"
268
270
  end
@@ -345,7 +347,10 @@ module Samagotchi
345
347
  "#{peer::NAME} \"pair with chi #{id.to_s[0, 8]}\"."]
346
348
  end
347
349
  lines << "last send: #{last_send_line(ctx)}" if id && last_send(ctx)
348
- lines << "last answer (#{peer::OUTBOX}): #{outbox_line(outbox)}" if outbox
350
+ if outbox
351
+ lines << "last message from #{peer::NAME} (#{peer::OUTBOX}, its text in the conversation): " \
352
+ "#{outbox_line(outbox)}"
353
+ end
349
354
  lines << "skill: **differs from this bundle's**: #{peer::COMMAND} install-skill (Replace), then pair again" if skill_differs?(ctx)
350
355
  lines << transport_line
351
356
  ctx.card(id: peer::STATUS_CARD, title: "#{peer::BUNDLE}: #{paired ? "paired" : "not paired"}",
@@ -401,6 +406,7 @@ module Samagotchi
401
406
  return [target, nil] unless source
402
407
 
403
408
  substitutions = { PAIR_PLACEHOLDER => File.join(File.dirname(source), "pair"),
409
+ PAIR_REMOTE_PLACEHOLDER => File.join(File.dirname(source), "pair-remote"),
404
410
  PAYLOADS_PLACEHOLDER => tilde(ctx.data_dir) }.merge(skill_substitutions(ctx))
405
411
  [target, substitutions.reduce(File.read(source)) { |skill, (placeholder, value)| skill.gsub(placeholder, value) }]
406
412
  end
@@ -462,7 +468,7 @@ module Samagotchi
462
468
  def follow_up(kind)
463
469
  case kind
464
470
  when "context" then "#{self.class::NAME} takes it in; it answers only if something in it is wrong."
465
- else "#{self.class::NAME}'s answer comes as an update of the #{self.class::OUTBOX} context; don't wait or poll."
471
+ else "#{self.class::NAME}'s answer comes as a note with its text (#{self.class::OUTBOX}); don't wait or poll."
466
472
  end
467
473
  end
468
474
 
@@ -206,9 +206,18 @@ module Samagotchi
206
206
 
207
207
  running = session.status == Session::STATUS_RUNNING && session.interrupted_turn&.enqueued_id == id
208
208
  queued = SessionInbox.waiting_input(session_dir, id) == :turn_end
209
- ended = session.last_turn&.enqueued_id == id || !SessionInbox.reply_for(session_dir, id).nil? ||
210
- !TurnCheckpoint.settled_turn(session_dir, id).nil?
211
- running || queued || ended || !SessionInbox.merged_into(session_dir, id).nil?
209
+ running || queued || ended_turn?(session, session_dir: session_dir, turn: id) ||
210
+ !SessionInbox.merged_into(session_dir, id).nil?
211
+ end
212
+
213
+ # Whether +turn+ has ended: the last one to have ended, one with its
214
+ # reply file, or one settled (refused, canceled, killed).
215
+ def ended_turn?(session, session_dir:, turn:)
216
+ id = turn.to_s
217
+ return false if id.empty?
218
+
219
+ session.last_turn&.enqueued_id == id || !SessionInbox.reply_for(session_dir, id).nil? ||
220
+ !TurnCheckpoint.settled_turn(session_dir, id).nil?
212
221
  end
213
222
 
214
223
  # Whether the session's live worker names TURN_IDS_FEATURE.
@@ -507,7 +507,8 @@ module Samagotchi
507
507
  if verdict
508
508
  kind, reason = verdict
509
509
  status = kind == :skip ? "skipped" : "failed"
510
- updated = status == "skipped" ? skipped(current, reason) : failed(current, reason)
510
+ updated = status == "skipped" ? skipped(current, reason) : failed(current, reason) if current.enabled
511
+ updated ||= current.with(last_result: reason)
511
512
  file.entries[position] = updated
512
513
  outcome = Outcome.new(id: current.id, title: current.title, status: status, detail: reason, entry: updated)
513
514
  next
@@ -697,7 +698,7 @@ module Samagotchi
697
698
  file.entries[position] = nil
698
699
  file.entries.compact!
699
700
  else
700
- changed = entry.with(enabled: enabled, last_result: enabled ? "enabled" : "disabled")
701
+ changed = file.entries[position].with(enabled: enabled, last_result: enabled ? "enabled" : "disabled")
701
702
  # Enabled again with a fresh budget: its next skip must not end it at once.
702
703
  file.entries[position] = enabled ? changed.with(skips: 0, failures: 0) : changed
703
704
  end
@@ -826,15 +827,17 @@ module Samagotchi
826
827
 
827
828
  def skipped(entry, reason)
828
829
  skips = entry.skips + 1
829
- disabled = skips >= entry.max_skips
830
+ within_budget = skips < entry.max_skips
830
831
  entry.with(skips: skips, firing_since: nil, firing_token: nil, pending_session_id: nil, pending_turn_id: nil,
831
- last_result: disabled ? "disabled: #{reason}" : "skipped", enabled: !disabled)
832
+ last_result: within_budget ? "skipped" : "disabled: #{reason}",
833
+ enabled: within_budget && (entry.enabled || entry.recurrence[:kind] == "date"))
832
834
  end
833
835
 
834
836
  def failed(entry, reason)
835
837
  failures = entry.failures + 1
838
+ within_budget = failures < entry.max_failures
836
839
  entry.with(failures: failures, firing_since: nil, firing_token: nil, pending_session_id: nil, pending_turn_id: nil,
837
- last_result: reason, enabled: failures < entry.max_failures)
840
+ last_result: reason, enabled: within_budget && (entry.enabled || entry.recurrence[:kind] == "date"))
838
841
  end
839
842
 
840
843
  def pending_detail(entry)
@@ -1192,8 +1195,8 @@ module Samagotchi
1192
1195
  Outcome.new(id: entry.id, title: entry.title, status: status, detail: message, entry: entry)
1193
1196
  end
1194
1197
 
1195
- # A run-now refused before anything was tried: the same counters a tick
1196
- # moves for a skip or a failure. `due_was` is untouched — run-now is not a
1198
+ # A run-now refused before anything was tried: an enabled schedule moves
1199
+ # the same counters a tick does. `due_was` is untouched — run-now is not a
1197
1200
  # scheduled occurrence, so there is no occurrence to put the clock back to.
1198
1201
  # The result goes back under the lock before any pruning, so a prune that
1199
1202
  # raises midway cannot lose the new head.
@@ -34,7 +34,9 @@ module Samagotchi
34
34
  end
35
35
 
36
36
  # A /continue yes (or bare /continue) from a parent agent's process.
37
- def self.parent_continue?(prompt) = TurnFlow.continue_yes?(prompt) && Guardrails::ParentApprovals.parent_process?
37
+ def self.parent_continue?(prompt, env: ENV)
38
+ TurnFlow.continue_yes?(prompt) && Guardrails::ParentApprovals.parent_process?(env: env)
39
+ end
38
40
 
39
41
  # The first refusal of a parent's /continue yes among targets whose
40
42
  # own parent_answers are +values+, held to this process's config.yml
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "agent_caller"
3
4
  require_relative "client_id"
4
5
  require_relative "delivery"
5
6
  require_relative "terminal_ui/formatting"
@@ -42,7 +43,6 @@ module Samagotchi
42
43
  include CLI::Command
43
44
  include CLI::ParentWait
44
45
 
45
- CLIENT_ID = ClientId::CLI_SEND
46
46
  # The cap on one turn's images the Bridge checks.
47
47
  MAX_IMAGES = ImageStore::MAX_TURN_REFS
48
48
  # A cut's outcomes in the Bridge's ack (SteerCut#cut_for_steer).
@@ -57,8 +57,8 @@ module Samagotchi
57
57
  def self.pause(seconds) = sleep(seconds)
58
58
 
59
59
  USAGE = <<~TEXT
60
- Usage: chi send [-m TEXT] [--image PATH]... [--cut | --queue] (ID|PREFIX)...
61
- chi send --new [--dir DIR] [--model M] [--llm-context LAYERS] [--thinking LEVEL] [--toolkit NAME] [--set KEY=VALUE]... [--parent-answers LEVEL] [-m TEXT] [--image PATH]...
60
+ Usage: chi send [-m TEXT] [--image PATH]... [--cut | --queue] [--as NAME] (ID|PREFIX)...
61
+ chi send --new [--dir DIR] [--model M] [--llm-context LAYERS] [--thinking LEVEL] [--toolkit NAME] [--set KEY=VALUE]... [--parent-answers LEVEL] [--driver NAME] [-m TEXT] [--image PATH]...
62
62
  chi send --new --continues (ID|PREFIX|last:ID) [--model M] [-m TEXT] [--image PATH]...
63
63
  chi send --wait [--timeout S] [--format json] [-m TEXT] [--image PATH]... (--new | ID)
64
64
  chi send --queue --wait [--timeout S] [--format json] [-m TEXT] ID
@@ -123,6 +123,17 @@ module Samagotchi
123
123
  questions: hard, standard or soft, only stricter than
124
124
  config.yml's guardrails.parent_answers (a looser one
125
125
  warns; config.yml's applies)
126
+ --driver NAME
127
+ (--new) name the agent NAME its driver (its messages go
128
+ in uncounted, with no header); an agent that creates
129
+ one drives it
130
+ --as NAME send as the agent NAME (agent:NAME; lowercase letters,
131
+ digits, - and _, up to 32), not as you. Without it, an
132
+ agent's marker names the sender (CLAUDECODE: claude,
133
+ CODEX_THREAD_ID: codex, AI_AGENT: its value; inside a
134
+ chi session its own, chi-ID8, and --as is ignored).
135
+ An agent's message restarts no stopped session, brings
136
+ back no archived one and runs no ! line
126
137
  --wait wait for the answer and print it (one session); the
127
138
  other lines go to stderr. Exit 3: it waits for an
128
139
  answer from you: the question, its options and the
@@ -191,6 +202,8 @@ module Samagotchi
191
202
  f.value "--timeout"
192
203
  f.value "--format"
193
204
  f.value "--turn"
205
+ f.value "--as", key: :as
206
+ f.value "--driver", key: :driver
194
207
  # Starting a turn in every live session at once is too easy to do
195
208
  # by accident.
196
209
  f.refuse "--all", "there is no --all: name the sessions"
@@ -258,8 +271,10 @@ module Samagotchi
258
271
  # @param argv [Array<String>] the arguments after "send"
259
272
  # @param access [SessionAccess::Local, nil] where the sessions are;
260
273
  # default this machine's, in +state_dir+
261
- def initialize(argv, stdin: $stdin, stdout: $stdout, stderr: $stderr, state_dir: nil, access: nil)
274
+ # @param env [Hash] where the agent markers are read (ENV; specs pass their own)
275
+ def initialize(argv, stdin: $stdin, stdout: $stdout, stderr: $stderr, state_dir: nil, access: nil, env: ENV)
262
276
  @argv = argv.dup
277
+ @env = env
263
278
  @stdin = stdin
264
279
  @stdout = stdout
265
280
  @stderr = stderr
@@ -279,6 +294,9 @@ module Samagotchi
279
294
  @waiting = options[:wait] == true
280
295
  @cut = options[:cut] == true
281
296
  @queue = options[:queue] == true
297
+ return CLI::Exit::USAGE unless (@agent = agent_name(options))
298
+
299
+ @agent = nil if @agent == :owner
282
300
  prompt = compose(utf8(read_stdin), utf8(options[:message]))
283
301
  # Before the wait-only case, which would drop the images.
284
302
  return usage_error("--image needs a message: pass -m TEXT or pipe it in") if prompt.nil? && !options[:images].empty?
@@ -377,7 +395,7 @@ module Samagotchi
377
395
  return usage_error("at most #{MAX_IMAGES} images") if options[:images].size > MAX_IMAGES
378
396
  return new_options(options) if options[:new]
379
397
 
380
- %i[dir model continues thinking toolkit].each { |key| return usage_error("--#{key} needs --new") if options[key] }
398
+ %i[dir model continues thinking toolkit driver].each { |key| return usage_error("--#{key} needs --new") if options[key] }
381
399
  TOOLKIT_FLAGS.each { |key, flag| return usage_error("#{flag} needs --new") unless Array(options[key]).empty? }
382
400
  LLM_CONTEXT_FLAGS.each { |key, flag| return usage_error("#{flag} needs --new") if options[key] }
383
401
  return usage_error("--set needs --new") unless Array(options[:sets]).empty?
@@ -396,6 +414,8 @@ module Samagotchi
396
414
 
397
415
  def new_options(options)
398
416
  return usage_error("--new takes no session ids: it starts one session") unless options[:ids].empty?
417
+ return usage_error("--driver takes an agent's name: lowercase letters, digits, - and _") if options[:driver] && !AgentCaller.clean(options[:driver])
418
+ return usage_error("--continues keeps the previous session's driver; leave out --driver") if options[:driver] && options[:continues]
399
419
 
400
420
  if options[:continues]
401
421
  taken = [("--dir" if options[:dir])] +
@@ -564,6 +584,8 @@ module Samagotchi
564
584
  setup = options[:setup_words] || SessionSetup.from_request(llm_context: options[:llm_context], thinking: options[:thinking],
565
585
  toolkit: options[:toolkit_value], settings: options[:settings],
566
586
  parent_answers: options[:parent_answers])
587
+ # --driver: the agent the owner names as its driver (Session#driver).
588
+ start[:driver] = ClientId.agent(AgentCaller.clean(options[:driver])) if options[:driver]
567
589
  SessionAccess::NewSession.new(**start, working_directory: options[:dir], model_name: options[:model], setup: setup)
568
590
  end
569
591
 
@@ -727,9 +749,24 @@ module Samagotchi
727
749
 
728
750
  SENT_COMMAND = "sent as a session command"
729
751
 
730
- # chi send's client id, or chi answer's for a parent agent's /continue
731
- # yes (the worker holds that to its guardrails.parent_answers).
732
- def client_id_for(prompt) = ParentGate.parent_continue?(prompt) ? ClientId::CLI_ANSWER : CLIENT_ID
752
+ # chi send's client id (an agent's, agent:<name>, when one sends:
753
+ # #agent_name), or chi answer's for a parent agent's /continue yes (the
754
+ # worker holds that to its guardrails.parent_answers): an agent's
755
+ # always is one, a marker-less process's when ParentGate says so.
756
+ def client_id_for(prompt)
757
+ continue = @agent ? TurnFlow.continue_yes?(prompt) : ParentGate.parent_continue?(prompt, env: @env)
758
+ continue ? ClientId::CLI_ANSWER : AgentCaller.send_id(name: @agent)
759
+ end
760
+
761
+ # Who sends (AgentCaller.send_name): the agent's name, :owner for none,
762
+ # or nil after a usage error (an --as that is not a name).
763
+ def agent_name(options)
764
+ name, error, note = AgentCaller.send_name(as: options[:as], env: @env)
765
+ return usage_error(error) && nil if error
766
+
767
+ @stderr.puts("chi send: #{note}") if note
768
+ name || :owner
769
+ end
733
770
 
734
771
  # Whether +text+ may be a session command, which only its worker knows
735
772
  # (a bundle's too).
@@ -290,6 +290,14 @@ module Samagotchi
290
290
  # continue) and an idle session. Set once, by spawn_session; a
291
291
  # continue and a fork don't carry it.
292
292
  SessionField.plain("first_turn_client_id", nil, optional: true),
293
+ # The agent that drives this session (agent:<name>, a ClientId): the
294
+ # one that created it (spawn_session, a prompt or none), or the one
295
+ # the owner named (chi send --new --driver, /driver). Its messages are
296
+ # as chi send's were (no header, never counted: Visitor); any other
297
+ # agent's are a visitor's. A continue keeps it
298
+ # (SessionContinue.spawn_continuation); a fork and a delegate child
299
+ # have none. nil: no agent drives it.
300
+ SessionField.plain("driver", nil, optional: true),
293
301
  # A Verify fresh child's requester, rules and claim (VerifyFreshOrigin),
294
302
  # nil for any other session. Set once, at spawn (VerifyFresh.start).
295
303
  # Autoloaded on the first one (the bundle test kit's load budget).
@@ -309,7 +317,7 @@ module Samagotchi
309
317
  attr_accessor :id, :metadata_version, :mode, :model_name, :model_typed, :working_directory, :messages,
310
318
  :created_at, :updated_at, :status, :last_prompt, :first_preview, :title, :test_run,
311
319
  :used_memory_names, :preloaded_memory_names, :muted_memory_names, :parent_id, :scratch,
312
- :continues, :first_turn_id, :first_turn_client_id, :project_id
320
+ :continues, :first_turn_id, :first_turn_client_id, :driver, :project_id
313
321
  attr_writer :project_root, :delegate
314
322
  attr_reader :appended_prompt_files, :written_by
315
323
 
@@ -4,6 +4,7 @@ require_relative "exchange"
4
4
  require_relative "exchange/token"
5
5
  require_relative "../bridge_client"
6
6
  require_relative "../bridge_secret"
7
+ require_relative "../agent_caller"
7
8
  require_relative "../client_id"
8
9
  require_relative "../parent_answers_command"
9
10
  require_relative "../reply_wait/target"
@@ -164,7 +165,9 @@ module Samagotchi
164
165
  # session asked and its chain's newest link); none: config.yml's
165
166
  # value alone (fail closed)
166
167
  # @return [String, Refused] the client_id to send as, or why not
167
- def agent_line(prompt, session:)
168
+ # @param name [String, nil] the agent's name (AgentCaller): its line
169
+ # goes as agent:<name>; nil: chi send's
170
+ def agent_line(prompt, session:, name: nil)
168
171
  sessions = Array(session).compact
169
172
  values = sessions.empty? ? [nil] : sessions.map(&:parent_answers)
170
173
  continue = TurnFlow.continue_yes?(prompt)
@@ -172,7 +175,7 @@ module Samagotchi
172
175
  refusal ||= ParentAnswersCommand::REFUSED if SendCommand::ParentGate.loosens_any?(prompt, values)
173
176
  return Refused.new(kind: :parent_refused, session_id: sessions.first&.id, message: refusal) if refusal
174
177
 
175
- continue ? ClientId::CLI_ANSWER : ClientId::CLI_SEND
178
+ continue ? ClientId::CLI_ANSWER : AgentCaller.send_id(name: name)
176
179
  end
177
180
 
178
181
  # The answer to the question session +id+ waits on, then one slice of
@@ -55,6 +55,8 @@ module Samagotchi
55
55
  "send --timeout" => SUPPORTED,
56
56
  "send --format" => SUPPORTED,
57
57
  "send --turn" => SUPPORTED,
58
+ "send --as" => SUPPORTED,
59
+ "send --driver" => SUPPORTED,
58
60
  # Refused on both (there is no --all).
59
61
  "send --all" => SUPPORTED,
60
62
 
@@ -159,8 +159,9 @@ module Samagotchi
159
159
  return SessionContinue.run(spec.continues, **start, model: spec.model_name, client_id: spec.client_id, **dir)
160
160
  end
161
161
 
162
+ driver = spec.driver ? { driver: spec.driver } : {}
162
163
  SessionManager.spawn_session(**start, working_directory: spec.working_directory, model_name: spec.model_name,
163
- setup: spec.setup, client_id: spec.client_id, **dir)
164
+ setup: spec.setup, client_id: spec.client_id, **driver, **dir)
164
165
  end
165
166
 
166
167
  # Whether a just-created session's worker came up (its Bridge
@@ -17,6 +17,8 @@ require_relative "../model_profile"
17
17
  require_relative "../grants"
18
18
  require_relative "http_transport"
19
19
  require_relative "../chi_invocation"
20
+ require_relative "../client_id"
21
+ require_relative "../delivery"
20
22
 
21
23
  module Samagotchi
22
24
  autoload :SessionManager, File.expand_path("../session_manager", __dir__)
@@ -251,7 +253,7 @@ module Samagotchi
251
253
  # @param follow [Boolean] +id+ is the head #head resolved: sent only
252
254
  # when true (an older chi web ignores it and delivers as before)
253
255
  def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false)
254
- body = { prompt: prompt, client_id: client_id, history: false }
256
+ body = { prompt: prompt, client_id: sent_id(client_id), history: false }
255
257
  body[:follow] = true if follow
256
258
  body[:images] = images.map { |ref| { file: ref[:file], name: ref[:name] } } unless images.empty?
257
259
  body[:check_vision] = true unless images.empty?
@@ -751,6 +753,17 @@ module Samagotchi
751
753
  reply
752
754
  end
753
755
 
756
+ # compat shim agent_client_id: +client_id+ as that chi web reads it:
757
+ # an agent's (agent:<name>) to one from before agent: senders goes as
758
+ # chi send's, today's owner row (Delivery::AGENT_FEATURE in its
759
+ # /api/info features).
760
+ def sent_id(client_id)
761
+ return client_id unless ClientId.agent?(client_id)
762
+
763
+ check_server!
764
+ Array(@features).include?(Delivery::AGENT_FEATURE) ? client_id : ClientId::CLI_SEND
765
+ end
766
+
754
767
  def check_server!
755
768
  return if @checked
756
769
 
@@ -870,7 +883,7 @@ module Samagotchi
870
883
  end
871
884
 
872
885
  def create_body(spec)
873
- body = { model: spec.model_name, client_id: spec.client_id, history: false }
886
+ body = { model: spec.model_name, client_id: sent_id(spec.client_id), history: false }
874
887
  if spec.preview || spec.idle
875
888
  body.merge!(idle: true, preview: spec.preview)
876
889
  else
@@ -882,6 +895,9 @@ module Samagotchi
882
895
  else
883
896
  body[:dir] = spec.working_directory
884
897
  body.merge!(setup_body(spec.setup)) if spec.setup
898
+ # An older chi web ignores it: no driver named (its creator's id
899
+ # downgraded too, #sent_id).
900
+ body[:driver] = spec.driver if spec.driver
885
901
  end
886
902
  body.compact
887
903
  end
@@ -141,10 +141,12 @@ module Samagotchi
141
141
  # /continue yes) and +images+ (images follow) are for a Remote's server,
142
142
  # which checks the first line and the model as chi send checks them
143
143
  # here (Local checks before it creates).
144
+ # +driver+: the agent (agent:<name>) chi send --new --driver names its
145
+ # driver; nil: its creator, when an agent (Session#driver).
144
146
  NewSession = Data.define(:prompt, :preview, :continues, :working_directory, :model_name, :setup, :client_id,
145
- :images, :idle) do
147
+ :images, :idle, :driver) do
146
148
  def initialize(prompt:, preview: nil, continues: nil, working_directory: nil, model_name: nil, setup: nil,
147
- client_id: nil, images: false, idle: false) = super
149
+ client_id: nil, images: false, idle: false, driver: nil) = super
148
150
  end
149
151
 
150
152
  # chi send --new's setup flags as typed, for a Remote: +llm_context+
@@ -31,6 +31,10 @@ module Samagotchi
31
31
  THINKING_COMMAND = ThinkingCommand::NAME
32
32
  TOOLKIT_COMMAND = ToolkitCommand::NAME
33
33
  PARENT_ANSWERS_COMMAND = ParentAnswersCommand::NAME
34
+ # DriverCommand::NAME (a spec keeps them the same): the class loads
35
+ # when the command runs (SessionCommands), not with the catalog (the
36
+ # bundle test kit's load budget).
37
+ DRIVER_COMMAND = "/driver"
34
38
  TITLE_COMMAND = TitleCommand::NAME
35
39
  REASONING_HISTORY_COMMAND = ReasoningHistoryCommand::NAME
36
40
  WORKING_SET_COMMAND = WorkingSetCommand::NAME
@@ -96,6 +100,10 @@ module Samagotchi
96
100
  "never looser than config.yml's)",
97
101
  id: :parent_answers, mid_turn: show_mid_turn(PARENT_ANSWERS_COMMAND),
98
102
  match: ->(text) { text.match?(%r{\A/parent-answers(?:\s+.*)?\z}) }) { |text| parent_answers(text) }
103
+ # Only a field: naming the driver doesn't wait for the turn. A user's
104
+ # at a UI (#run's user_ui:).
105
+ registry.register(DRIVER_COMMAND, "show or name the agent that drives this session (NAME|none)",
106
+ id: :driver, anytime: true, match: ->(text) { text.match?(%r{\A/driver(?:\s+.*)?\z}) }) { |text| driver(text) }
99
107
  # Only a name: renaming a running session doesn't wait for its turn.
100
108
  registry.register(TITLE_COMMAND, "show or set this session's title (--clear: back to its first message)",
101
109
  id: :title, anytime: true, match: ->(text) { text.match?(%r{\A/title(?:\s+.*)?\z}) }) { |text| title(text) }
@@ -32,6 +32,7 @@ module Samagotchi
32
32
  # Loaded on first use (a /objectives line): keeps the bundle test kit's
33
33
  # load budget (spec/samagotchi/testing/sandbox_spec.rb).
34
34
  autoload :ObjectivesCommand, File.expand_path("objectives_command", __dir__)
35
+ autoload :DriverCommand, File.expand_path("driver_command", __dir__)
35
36
 
36
37
  # The session commands a session worker runs (a -p one-shot too): /model,
37
38
  # /models, /llm-context, /guardrails, /context, !rollback, !cmd and the answer to a continue offer. They act on
@@ -189,6 +190,7 @@ module Samagotchi
189
190
  # an anytime command runs on another thread against this instance.
190
191
  return continue_command(text, as_parent: as_parent) if entry.id == :continue
191
192
  return parent_answers(text, user_ui: user_ui) if entry.id == :parent_answers
193
+ return driver(text, user_ui: user_ui) if entry.id == :driver
192
194
  return callback(text, as_parent: as_parent) if entry.id == :callback
193
195
 
194
196
  instance_exec(text, &entry.handler)
@@ -522,6 +524,13 @@ module Samagotchi
522
524
  reply(output, status: status, changed: changed ? [:parent_answers] : [])
523
525
  end
524
526
 
527
+ # /driver (DriverCommand); :driver in changed when it named one.
528
+ def driver(text, user_ui: false)
529
+ output, changed, status = DriverCommand.new(engine: @engine, save: ->(session) { save_setup(session) })
530
+ .run(text.delete_prefix(DRIVER_COMMAND), user_ui: user_ui)
531
+ reply(output, status: status, changed: changed ? [:driver] : [])
532
+ end
533
+
525
534
  # /working-set (WorkingSetCommand): an op that changes the conversation
526
535
  # (changed :messages: the worker saves it, the web reads it again)
527
536
  # closes the rollback window (a rollback past it would drop it
@@ -477,7 +477,10 @@ module Samagotchi
477
477
  model_name: choice.model, setup: SessionSetup.of(previous), review: previous.review,
478
478
  continues: previous.id, note: SessionChain.note_text(previous, recap: recap, state_dir: state_dir),
479
479
  note_source: SessionChain::NOTE_SOURCE, state_dir: state_dir, before_spawn: before_spawn, client_id: client_id,
480
- session_id: session_id
480
+ # The chain's driver, nil too: an agent continuing a session it
481
+ # doesn't drive is a visitor in the new link (not SessionSetup,
482
+ # which a fork copies).
483
+ session_id: session_id, driver: previous.driver
481
484
  )
482
485
  link.moved_children = move
483
486
  link.moved_context = carried[:context]
@@ -390,6 +390,8 @@ module Samagotchi
390
390
  # participant's file waits, as before.
391
391
  def self.turn_end_data?(data, running_author: nil)
392
392
  return true if Array(data["images"]).any? || Delivery.queue?(data["delivery"]) || TurnAnchors.named_in?(data)
393
+ # Another session's question (ask_session) is a turn of its own.
394
+ return true if ClientId.session?(data["client_id"])
393
395
 
394
396
  author = Steer.sender_author(data["author"])
395
397
  running_author ? author != running_author : Steer.participant_author?(data["author"])
@@ -172,8 +172,10 @@ module Samagotchi
172
172
  # the sender, ClientId.wake_kind): they start an idle session as a send
173
173
  # does, but a stop and an archive are the owner's (the sender is
174
174
  # refused, SessionManager::DeliverResult::STOPPED / ARCHIVED). They
175
- # stay on the id they name. :automatic is any sender chi doesn't name.
176
- **%i[schedule plugin delegate participant automatic].to_h do |kind|
175
+ # stay on the id they name. :agent is an agent's chi send (it follows a
176
+ # chain itself: SendCommand#target). :automatic is any sender chi
177
+ # doesn't name.
178
+ **%i[schedule plugin delegate participant agent automatic].to_h do |kind|
177
179
  [kind, WakePolicy.new(kind: kind, resolves: :pinned, starts: true, unstops: false, starts_archived: false,
178
180
  refuse_tui: true, refuse_scratch: true)]
179
181
  end
@@ -239,7 +239,11 @@ module Samagotchi
239
239
  return refused if refused
240
240
 
241
241
  enqueued_id ||= SessionInbox.new_enqueued_id
242
+ # Whether the worker that answered reads an agent: id (nil: no Bridge
243
+ # answered): the file fallback below keeps it when it does.
244
+ agent_reader = nil
242
245
  if (client = bridge.call)
246
+ agent_reader = worker_has?(client, Delivery::AGENT_FEATURE) if ClientId.agent?(client_id)
243
247
  if (missing = anchors.present.find { |anchor| !worker_has?(client, anchor.class::FEATURE) })
244
248
  return DeliverResult.new(status: :refused, code: 409, ack: missing.class::UNAVAILABLE)
245
249
  end
@@ -249,6 +253,8 @@ module Samagotchi
249
253
  # A participant's turn only to a worker that runs it under the
250
254
  # owner's rules: an older one would run it read-only.
251
255
  return pair_unavailable if Steer.participant_author?(author) && !worker_has?(client, Delivery::PAIR_FEATURE)
256
+ # Another session's question only to a worker that runs it as a visitor's.
257
+ return ask_unavailable if ClientId.session?(client_id) && !worker_has?(client, Delivery::ASK_FEATURE)
252
258
  # A participant's Revise only to a worker that checks it at the
253
259
  # stamp (ParticipantRevise): an older one would stamp it unchecked.
254
260
  if Steer.participant_author?(author) && anchors.revises && !worker_has?(client, ReviseAnchor::PARTICIPANT_FEATURE)
@@ -261,6 +267,9 @@ module Samagotchi
261
267
  if ClientId.participant?(client_id) && !worker_has?(client, Delivery::PARTICIPANT_ID_FEATURE)
262
268
  client_id = ClientId.legacy_participant(client_id)
263
269
  end
270
+ # compat shim agent_client_id: a worker from before agent: reads
271
+ # an agent's line as chi send's (today's owner row).
272
+ client_id = ClientId::CLI_SEND if ClientId.agent?(client_id) && !agent_reader
264
273
 
265
274
  begin
266
275
  options = { prompt: prompt, client_id: client_id, enqueued_id: enqueued_id }
@@ -297,11 +306,27 @@ module Samagotchi
297
306
  # still holding the session with its Bridge gone (exiting) may be an
298
307
  # older one, which would run it without the pair boundary.
299
308
  # (A one-turn chi run holding it is refused as for anyone, below.)
300
- if Steer.participant_author?(author) && (holder = delivery_presence(manager, session_id, state_dir)).owned? &&
301
- !holder.tui_owned?
302
- return DeliverResult.new(status: :timeout, via: :file,
303
- ack: { "error" => "worker_timeout",
304
- "detail" => "the session's worker is exiting, so the message was not sent; send it again" })
309
+ # So is another session's question (ask_session: an older worker runs
310
+ # it with no header).
311
+ if (Steer.participant_author?(author) || ClientId.session?(client_id)) &&
312
+ (holder = delivery_presence(manager, session_id, state_dir)).owned? && !holder.tui_owned?
313
+ return exiting_refused
314
+ end
315
+
316
+ # compat shim agent_client_id: an agent's file while a worker holds
317
+ # the session and no Bridge answered (a 413, a 5xx or a socket error
318
+ # from one that did keeps the id it read: agent_reader). Its
319
+ # sidecar's features say which worker it is: one without
320
+ # agent_sender reads chi send's id instead (today's owner row); one
321
+ # it can't tell (exiting, its sidecar gone) is refused, as a
322
+ # participant's is, never run as the owner. A worker that starts for
323
+ # the file reads the agent's id.
324
+ if ClientId.agent?(client_id) && agent_reader.nil? &&
325
+ (holder = delivery_presence(manager, session_id, state_dir)).owned? && !holder.tui_owned?
326
+ case sidecar_agent_reader(session_dir)
327
+ when false then client_id = ClientId::CLI_SEND
328
+ when nil then return exiting_refused
329
+ end
305
330
  end
306
331
  input = { prompt: prompt, client_id: client_id, enqueued_id: enqueued_id, state_dir: state_dir }
307
332
  input[:images] = images unless images.empty?
@@ -427,6 +452,26 @@ module Samagotchi
427
452
  DeliverResult.new(status: :refused, code: 409, ack: Delivery::QUEUE_UNAVAILABLE)
428
453
  end
429
454
 
455
+ # A message held back while an exiting worker holds the session: the
456
+ # file's reader is unknown (a participant's, a session's question, an
457
+ # agent's the sidecar can't vouch for).
458
+ private def exiting_refused
459
+ DeliverResult.new(status: :timeout, via: :file,
460
+ ack: { "error" => "worker_timeout",
461
+ "detail" => "the session's worker is exiting, so the message was not sent; send it again" })
462
+ end
463
+
464
+ # Whether the worker whose sidecar is in +session_dir+ reads an agent:
465
+ # id (Delivery::AGENT_FEATURE): true, false, or nil when there is no
466
+ # sidecar to read (a worker leaving, starting, or gone).
467
+ private def sidecar_agent_reader(session_dir)
468
+ link = WorkerLink.resolve(session_dir, unlink: false)
469
+ sidecar = link.respond_to?(:sidecar) ? link.sidecar : nil
470
+ sidecar ? Array(sidecar.features).include?(Delivery::AGENT_FEATURE) : nil
471
+ end
472
+
473
+ private def ask_unavailable = DeliverResult.new(status: :refused, code: 409, ack: Delivery::ASK_UNAVAILABLE)
474
+
430
475
  private def pair_unavailable
431
476
  DeliverResult.new(status: :refused, code: 409, ack: Delivery::PAIR_UNAVAILABLE)
432
477
  end