samagotchi 0.183.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 (151) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +84 -1
  3. data/docs/architecture.md +12 -11
  4. data/docs/bundles.md +63 -36
  5. data/docs/cli.md +10 -1
  6. data/docs/configuration.md +3 -2
  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 +7 -3
  12. data/docs/internals/bundles.md +6 -2
  13. data/docs/internals/engine.md +2 -1
  14. data/docs/internals/llm-context-forget.md +6 -0
  15. data/docs/internals/participants.md +5 -2
  16. data/docs/internals/prompt-caching.md +8 -1
  17. data/docs/internals/remote-sessions.md +22 -4
  18. data/docs/internals/session-lifecycle.md +1 -1
  19. data/docs/internals/web-frontend.md +37 -15
  20. data/docs/internals/web-push.md +11 -0
  21. data/docs/internals/working-set.md +238 -6
  22. data/docs/mcp-server.md +11 -3
  23. data/docs/memory.md +2 -1
  24. data/docs/plugins.md +6 -6
  25. data/docs/scheduling.md +19 -0
  26. data/docs/sessions.md +13 -3
  27. data/docs/sub-agent.md +48 -3
  28. data/docs/thin-clients.md +38 -12
  29. data/lib/samagotchi/agent_caller.rb +97 -0
  30. data/lib/samagotchi/bridge.rb +7 -7
  31. data/lib/samagotchi/bridge_client.rb +12 -4
  32. data/lib/samagotchi/bundle_command/check.rb +20 -2
  33. data/lib/samagotchi/bundle_manifest.rb +5 -1
  34. data/lib/samagotchi/bundles/claude-peer/manifest.yml +14 -8
  35. data/lib/samagotchi/bundles/claude-peer/plugin.rb +3 -3
  36. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +49 -30
  37. data/lib/samagotchi/bundles/claude-peer/scripts/pair +2 -2
  38. data/lib/samagotchi/bundles/claude-peer/scripts/pair-remote +123 -0
  39. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +11 -3
  40. data/lib/samagotchi/bundles/codex-peer/manifest.yml +10 -8
  41. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  42. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +29 -8
  43. data/lib/samagotchi/bundles/codex-peer/scripts/pair +1 -1
  44. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +11 -3
  45. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  46. data/lib/samagotchi/bundles/mcp/http_client.rb +96 -54
  47. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  48. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  49. data/lib/samagotchi/bundles/system/self_map.md +9 -2
  50. data/lib/samagotchi/client_id.rb +61 -1
  51. data/lib/samagotchi/command_intake.rb +16 -8
  52. data/lib/samagotchi/context_absorber.rb +212 -46
  53. data/lib/samagotchi/delivery.rb +15 -0
  54. data/lib/samagotchi/driver_command.rb +68 -0
  55. data/lib/samagotchi/engine/block_fix.rb +2 -2
  56. data/lib/samagotchi/engine/session.rb +14 -6
  57. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  58. data/lib/samagotchi/engine.rb +13 -5
  59. data/lib/samagotchi/engine_peers.rb +6 -0
  60. data/lib/samagotchi/guardrails/pair_boundary.rb +1 -1
  61. data/lib/samagotchi/mcp_command.rb +7 -2
  62. data/lib/samagotchi/mcp_server/http.rb +3 -3
  63. data/lib/samagotchi/mcp_server/protocol.rb +23 -4
  64. data/lib/samagotchi/mcp_server/stdio.rb +1 -0
  65. data/lib/samagotchi/mcp_server/tools.rb +11 -4
  66. data/lib/samagotchi/model_notes.rb +34 -12
  67. data/lib/samagotchi/objectives_track.rb +2 -1
  68. data/lib/samagotchi/owner_prompt.rb +5 -1
  69. data/lib/samagotchi/parent_report.rb +9 -5
  70. data/lib/samagotchi/plugin/peer.rb +10 -4
  71. data/lib/samagotchi/prompt_files.rb +11 -4
  72. data/lib/samagotchi/prompt_layout.rb +88 -0
  73. data/lib/samagotchi/prompt_part.rb +82 -20
  74. data/lib/samagotchi/reply_wait.rb +16 -4
  75. data/lib/samagotchi/schedule_command.rb +18 -4
  76. data/lib/samagotchi/schedules.rb +49 -14
  77. data/lib/samagotchi/send_command/parent_gate.rb +3 -1
  78. data/lib/samagotchi/send_command.rb +45 -8
  79. data/lib/samagotchi/session.rb +9 -1
  80. data/lib/samagotchi/session_access/ask.rb +58 -14
  81. data/lib/samagotchi/session_access/contract.rb +2 -0
  82. data/lib/samagotchi/session_access/exchange.rb +5 -2
  83. data/lib/samagotchi/session_access/local.rb +13 -3
  84. data/lib/samagotchi/session_access/remote.rb +18 -2
  85. data/lib/samagotchi/session_access.rb +4 -2
  86. data/lib/samagotchi/session_command_catalog.rb +8 -0
  87. data/lib/samagotchi/session_commands.rb +9 -0
  88. data/lib/samagotchi/session_continue.rb +4 -1
  89. data/lib/samagotchi/session_inbox.rb +17 -0
  90. data/lib/samagotchi/session_inbox_delivery.rb +4 -2
  91. data/lib/samagotchi/session_manager/delivery.rb +58 -9
  92. data/lib/samagotchi/session_manager/spawn.rb +7 -1
  93. data/lib/samagotchi/steer.rb +95 -20
  94. data/lib/samagotchi/system_prompt.rb +196 -161
  95. data/lib/samagotchi/terminal_ui/formatting.rb +12 -2
  96. data/lib/samagotchi/tool_activity.rb +4 -0
  97. data/lib/samagotchi/tool_declarations.rb +22 -1
  98. data/lib/samagotchi/tool_names.rb +4 -0
  99. data/lib/samagotchi/toolkit.rb +3 -2
  100. data/lib/samagotchi/tools/ask_session.rb +208 -0
  101. data/lib/samagotchi/tools/builtin_calls.rb +1 -0
  102. data/lib/samagotchi/tools/builtins.rb +5 -0
  103. data/lib/samagotchi/tools/memory.rb +11 -3
  104. data/lib/samagotchi/turn_checkpoint.rb +19 -2
  105. data/lib/samagotchi/turn_stages/context_judge.rb +3 -1
  106. data/lib/samagotchi/turn_stages/objectives.rb +4 -2
  107. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +3 -0
  108. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  109. data/lib/samagotchi/version.rb +1 -1
  110. data/lib/samagotchi/visitor.rb +37 -0
  111. data/lib/samagotchi/web/app.rb +2 -3
  112. data/lib/samagotchi/web/ask_routes.rb +95 -23
  113. data/lib/samagotchi/web/mcp_route.rb +7 -4
  114. data/lib/samagotchi/web/message_display.rb +15 -2
  115. data/lib/samagotchi/web/public/app.js +1 -1
  116. data/lib/samagotchi/web/public/block_fix.js +11 -3
  117. data/lib/samagotchi/web/public/delete_sheet.js +20 -18
  118. data/lib/samagotchi/web/public/history_shape.js +3 -1
  119. data/lib/samagotchi/web/public/index.html +8 -0
  120. data/lib/samagotchi/web/public/peer_links.js +27 -4
  121. data/lib/samagotchi/web/public/peer_note.js +19 -3
  122. data/lib/samagotchi/web/public/peer_text.js +45 -0
  123. data/lib/samagotchi/web/public/picture_regions.js +2 -2
  124. data/lib/samagotchi/web/public/removal_sheet_model.js +3 -4
  125. data/lib/samagotchi/web/public/running_tasks.js +0 -16
  126. data/lib/samagotchi/web/public/session_actions.js +0 -9
  127. data/lib/samagotchi/web/public/turn_events.js +19 -0
  128. data/lib/samagotchi/web/public/working_set_view.js +178 -23
  129. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  130. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  131. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  132. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  133. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  134. data/lib/samagotchi/web/push/notifier.rb +33 -6
  135. data/lib/samagotchi/web/server.rb +1 -1
  136. data/lib/samagotchi/web/session_control.rb +1 -1
  137. data/lib/samagotchi/web/session_create.rb +11 -7
  138. data/lib/samagotchi/web/session_hub.rb +26 -4
  139. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  140. data/lib/samagotchi/worker/command_queue.rb +5 -2
  141. data/lib/samagotchi/worker/senders.rb +79 -0
  142. data/lib/samagotchi/worker.rb +21 -18
  143. data/lib/samagotchi/worker_inbound.rb +12 -4
  144. data/lib/samagotchi/worker_link.rb +2 -2
  145. data/lib/samagotchi/worker_participant_gate.rb +1 -3
  146. data/lib/samagotchi/worker_wakes.rb +12 -0
  147. data/lib/samagotchi/working_set.rb +162 -90
  148. data/lib/samagotchi/working_set_locator.rb +221 -0
  149. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  150. data/lib/samagotchi/working_set_part.rb +281 -0
  151. metadata +13 -1
@@ -4,10 +4,12 @@ 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"
10
11
  require_relative "../session"
12
+ require_relative "../session_inbox"
11
13
  require_relative "../turn_flow"
12
14
  require_relative "../send_command/parent_gate"
13
15
 
@@ -34,12 +36,17 @@ module Samagotchi
34
36
  # ReplyWait::Result, +token+ for a :timeout (the next wait's).
35
37
  # #answer's: +answered_here+ false when the question was no longer
36
38
  # open (answered elsewhere first, or a newer one waits): what came
37
- # next is still waited for, as chi answer does.
38
- Reply = Data.define(:session_id, :asked, :result, :token, :answered_here) do
39
- def initialize(session_id:, asked:, result:, token:, answered_here: true) = super
39
+ # next is still waited for, as chi answer does. +rebound+: a request_id
40
+ # whose turn was already known, so nothing was sent this time (the
41
+ # first ask's turn waited on again).
42
+ Reply = Data.define(:session_id, :asked, :result, :token, :answered_here, :rebound) do
43
+ def initialize(session_id:, asked:, result:, token:, answered_here: true, rebound: false) = super
40
44
  end
41
45
 
42
- # The line ran as a session command (/model x): no reply comes.
46
+ # The line ran as a session command (/model x): no reply comes. A
47
+ # /continue yes with an offer standing (an idle session's continue
48
+ # question, its worker running) is a Reply instead: it waits on the
49
+ # continued turn (#continue_follows?).
43
50
  Ran = Data.define(:session_id)
44
51
 
45
52
  # Nothing went in. +kind+ :unknown (+error+ the resolve's
@@ -82,9 +89,17 @@ module Samagotchi
82
89
  # @param cancelled [#call, nil] true stops the wait (status :canceled);
83
90
  # before the delivery, the call (Refused :canceled). The exchange's
84
91
  # own cancelled: (the same) cuts its waits for a continue
92
+ # @param request_id [String, nil] the client's key for this ask (a
93
+ # message, never a command): its turn's enqueued id is
94
+ # SessionInbox.enqueued_id_for("ask:" + it). A turn of that id the
95
+ # session knows (running, queued, ended: ReplyWait.known_turn?) is
96
+ # waited on again, nothing sent (Reply rebound), unless it only waits
97
+ # as an input file with no worker running (#waiting_turn?); else the
98
+ # delivery carries the id, which the Bridge dedupes
85
99
  # @return [Reply, Ran, Refused]
86
100
  def call(given, prompt:, client_id:, queue:, timeout:, cap:, continuing_wait: Exchange::CONTINUING_WAIT,
87
- cancelled: nil)
101
+ cancelled: nil, request_id: nil)
102
+ enqueued_id = SessionInbox.enqueued_id_for("ask:#{request_id}") if request_id
88
103
  deadline = @clock.call + cap
89
104
  # Everything before the wait ends by here, so its MIN_SLICE fits.
90
105
  ready_by = deadline - MIN_SLICE
@@ -98,11 +113,22 @@ module Samagotchi
98
113
  return Refused.new(kind: :canceled, session_id: at.id) if cancelled&.call
99
114
 
100
115
  session = @access.show(at.id)
116
+ start = (@access.prepare_wait(at.id, session: session, turn: enqueued_id) if enqueued_id)
117
+ # A turn known only as an input file no worker reads is sent again
118
+ # (with E: the worker runs it once), so the delivery wakes one.
119
+ if start&.known_turn && (start.live || !@access.waiting_turn?(at.id, enqueued_id))
120
+ # chi send --wait --turn E's binding, queued as the first copy was
121
+ # sent (a queue never merges: no merge fallback onto another turn).
122
+ target = ReplyWait::Target.wait_only(start, requested: enqueued_id).with(queued: queue)
123
+ return wait(at, target, slice: slice(timeout, deadline), cancelled: cancelled, rebound: true)
124
+ end
125
+
101
126
  busy = @access.busy(at.id, queue: queue, session: session)
102
127
  return Refused.new(kind: :busy, session_id: at.id, busy: busy) if busy
103
128
 
104
- start = @access.prepare_wait(at.id, session: session)
105
- result = @exchange.attempt(at, prompt, client_id: client_id, queue: queue).result
129
+ start ||= @access.prepare_wait(at.id, session: session)
130
+ more = enqueued_id ? { enqueued_id: enqueued_id } : {}
131
+ result = @exchange.attempt(at, prompt, client_id: client_id, queue: queue, **more).result
106
132
  if result.continued?
107
133
  follow_until ||= [@clock.call + continuing_wait, ready_by].min
108
134
  again = @exchange.relocate(at, follow_until, bounded: true)
@@ -114,9 +140,17 @@ module Samagotchi
114
140
  next
115
141
  end
116
142
  return Refused.new(kind: :undelivered, session_id: at.id, result: result) unless result.accepted?
117
- return Ran.new(session_id: at.id) if result.command?
118
143
 
119
- return wait(at, start, result, queue: queue, slice: slice(timeout, deadline), cancelled: cancelled)
144
+ if result.command?
145
+ return Ran.new(session_id: at.id) unless continue_follows?(prompt, start)
146
+
147
+ # The continue turn runs under the offered turn's id (own_turn),
148
+ # as chi answer follows it: the worker's ack is not read.
149
+ return wait(at, ReplyWait::Target.answer(start), slice: slice(timeout, deadline), cancelled: cancelled)
150
+ end
151
+
152
+ target = @exchange.bind(start, result, queue: queue)
153
+ return wait(at, target, slice: slice(timeout, deadline), cancelled: cancelled)
120
154
  end
121
155
  end
122
156
 
@@ -131,7 +165,9 @@ module Samagotchi
131
165
  # session asked and its chain's newest link); none: config.yml's
132
166
  # value alone (fail closed)
133
167
  # @return [String, Refused] the client_id to send as, or why not
134
- 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)
135
171
  sessions = Array(session).compact
136
172
  values = sessions.empty? ? [nil] : sessions.map(&:parent_answers)
137
173
  continue = TurnFlow.continue_yes?(prompt)
@@ -139,7 +175,7 @@ module Samagotchi
139
175
  refusal ||= ParentAnswersCommand::REFUSED if SendCommand::ParentGate.loosens_any?(prompt, values)
140
176
  return Refused.new(kind: :parent_refused, session_id: sessions.first&.id, message: refusal) if refusal
141
177
 
142
- continue ? ClientId::CLI_ANSWER : ClientId::CLI_SEND
178
+ continue ? ClientId::CLI_ANSWER : AgentCaller.send_id(name: name)
143
179
  end
144
180
 
145
181
  # The answer to the question session +id+ waits on, then one slice of
@@ -220,12 +256,20 @@ module Samagotchi
220
256
 
221
257
  def answer_refused(kind, id, message) = Refused.new(kind: kind, session_id: id, message: message)
222
258
 
223
- def wait(at, start, delivered, queue:, slice:, cancelled:)
224
- target = @exchange.bind(start, delivered, queue: queue)
259
+ # A /continue yes the worker ran as a command, on a session idle with
260
+ # its continue offer standing (start's own_turn, ReplyWait.own_turn)
261
+ # and a worker running it: the offer lives only in that worker's
262
+ # memory, so with none (a new one says nothing to continue) a wait
263
+ # would hand out tokens with no end.
264
+ def continue_follows?(prompt, start)
265
+ TurnFlow.continue_yes?(prompt) && !start.running && start.live && !start.own_turn.to_s.empty?
266
+ end
267
+
268
+ def wait(at, target, slice:, cancelled:, rebound: false)
225
269
  more = cancelled ? { cancelled: cancelled } : {}
226
270
  result = @exchange.wait(at.id, target, timeout: slice, **more)
227
271
  token = Exchange::Token.dump(at.id, target) if result.status == :timeout
228
- Reply.new(session_id: at.id, asked: at.asked, result: result, token: token)
272
+ Reply.new(session_id: at.id, asked: at.asked, result: result, token: token, rebound: rebound)
229
273
  end
230
274
 
231
275
  # The wait's slice: +timeout+, cut to the time the cap leaves, never
@@ -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
 
@@ -120,8 +120,10 @@ module Samagotchi
120
120
  # takes (nil: none)
121
121
  # @param check [#call, nil] called with the session read: a refusal
122
122
  # String, or nil to go on
123
+ # @param enqueued_id [String, nil] the turn's id, the caller's (an
124
+ # ask's request_id): passed to deliver_turn only when given
123
125
  # @return [Attempted, Stopped]
124
- def attempt(target, prompt, client_id:, queue: false, cut: false, images: nil, check: nil)
126
+ def attempt(target, prompt, client_id:, queue: false, cut: false, images: nil, check: nil, enqueued_id: nil)
125
127
  id = target.id
126
128
  session = @access.show(id)
127
129
  if check && (refusal = check.call(session))
@@ -134,8 +136,9 @@ module Samagotchi
134
136
  delivery = if queue then Delivery::QUEUE
135
137
  elsif cut && running then Delivery::CUT
136
138
  end
139
+ more = enqueued_id ? { enqueued_id: enqueued_id } : {}
137
140
  result = @access.deliver_turn(id, prompt: prompt, client_id: client_id, images: refs, delivery: delivery,
138
- follow: target.via != :pinned)
141
+ follow: target.via != :pinned, **more)
139
142
  Attempted.new(target: target, session: session, owner: owner, running: running, delivery: delivery, refs: refs,
140
143
  result: result)
141
144
  end
@@ -92,6 +92,12 @@ module Samagotchi
92
92
  # @return [OwnerLock::Owner, nil] the worker or one-turn chi run that owns it
93
93
  def owner(id) = SessionManager.session_owner(id, **dir)
94
94
 
95
+ # Whether +turn+ (an enqueued id) waits as an unclaimed input file of
96
+ # session +id+ (Ask's request_id check: such a turn with no worker
97
+ # running is delivered again, which wakes one; the worker runs the id
98
+ # once). This machine's only: Remote never takes a request_id.
99
+ def waiting_turn?(id, turn) = !SessionInbox.waiting_input(session_dir(id), turn).nil?
100
+
95
101
  # SessionManager.session_rows: the SessionRows chi sessions list
96
102
  # prints and chi note --all reaches (chi web's summaries route answers
97
103
  # their #to_summary_h).
@@ -153,8 +159,9 @@ module Samagotchi
153
159
  return SessionContinue.run(spec.continues, **start, model: spec.model_name, client_id: spec.client_id, **dir)
154
160
  end
155
161
 
162
+ driver = spec.driver ? { driver: spec.driver } : {}
156
163
  SessionManager.spawn_session(**start, working_directory: spec.working_directory, model_name: spec.model_name,
157
- setup: spec.setup, client_id: spec.client_id, **dir)
164
+ setup: spec.setup, client_id: spec.client_id, **driver, **dir)
158
165
  end
159
166
 
160
167
  # Whether a just-created session's worker came up (its Bridge
@@ -196,8 +203,11 @@ module Samagotchi
196
203
  # @param bridge [#call, nil] the worker's Bridge client (chi web's
197
204
  # live_bridge_client: POST …/ask delivers as POST …/turn does); nil:
198
205
  # SessionManager's own wait
199
- def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false, manager: nil, bridge: nil)
200
- routing = { manager: manager, bridge: bridge }.compact
206
+ # @param enqueued_id [String, nil] the turn's id (an ask's request_id's);
207
+ # nil: SessionManager mints one
208
+ def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false, manager: nil, bridge: nil,
209
+ enqueued_id: nil)
210
+ routing = { manager: manager, bridge: bridge, enqueued_id: enqueued_id }.compact
201
211
  SessionManager.deliver_turn(id, prompt: prompt, client_id: client_id, images: images, delivery: delivery,
202
212
  follow: follow, **routing, **dir)
203
213
  end
@@ -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]
@@ -4,6 +4,7 @@ require "fileutils"
4
4
  require "json"
5
5
  require "time"
6
6
  require "securerandom"
7
+ require "digest"
7
8
  require_relative "atomic_file"
8
9
  require_relative "context_note"
9
10
  require_relative "delivery"
@@ -256,6 +257,20 @@ module Samagotchi
256
257
 
257
258
  def self.new_enqueued_id = SecureRandom.uuid
258
259
 
260
+ # The enqueued id a client's own key names (an ask's request_id): the
261
+ # same key always gives the same id, shaped as a UUID v5 (SHA-256's
262
+ # first 128 bits, the version and variant bits set), so a Bridge keeps
263
+ # it (ENQUEUED_ID_UUID) and dedupes a retry.
264
+ # @param key [String]
265
+ # @return [String]
266
+ def self.enqueued_id_for(key)
267
+ bytes = Digest::SHA256.digest(key.to_s).bytes.first(16)
268
+ bytes[6] = (bytes[6] & 0x0f) | 0x50
269
+ bytes[8] = (bytes[8] & 0x3f) | 0x80
270
+ hex = bytes.pack("C*").unpack1("H*")
271
+ "#{hex[0, 8]}-#{hex[8, 4]}-#{hex[12, 4]}-#{hex[16, 4]}-#{hex[20, 12]}"
272
+ end
273
+
259
274
  def self.valid_enqueued_id?(id) = id.is_a?(String) && ENQUEUED_ID_UUID.match?(id)
260
275
 
261
276
  def self.output_name(timestamp, enqueued_id)
@@ -375,6 +390,8 @@ module Samagotchi
375
390
  # participant's file waits, as before.
376
391
  def self.turn_end_data?(data, running_author: nil)
377
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"])
378
395
 
379
396
  author = Steer.sender_author(data["author"])
380
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
@@ -176,6 +176,9 @@ module Samagotchi
176
176
  # stand-in (the web's specs); #session_owner is optional
177
177
  # @param bridge [#call, nil] returns the BridgeClient or nil; defaults to
178
178
  # the session's sidecar, waiting TURN_BRIDGE_WAIT for a new worker's
179
+ # @param enqueued_id [String, nil] the turn's id, the caller's (an ask's
180
+ # request_id: SessionInbox.enqueued_id_for), so a retry with the same
181
+ # one is the Bridge's duplicate and the file's one claim; nil mints one
179
182
  # @return [DeliverResult] :accepted (via the Bridge or a file),
180
183
  # :refused when the Bridge refused the request (any 4xx with an
181
184
  # error: bad images, a delivery it doesn't run) or a queue would reach
@@ -186,13 +189,14 @@ module Samagotchi
186
189
  # @raise [ArgumentError] no such session, or no client_id
187
190
  def deliver_turn(session_id, prompt:, client_id:, images: [], delivery: nil, no_interrupt: false,
188
191
  author: nil, pending_limit: nil, anchors: nil, follow: false, state_dir: nil, manager: self,
189
- bridge: nil)
192
+ bridge: nil, enqueued_id: nil)
190
193
  raise ArgumentError, "deliver_turn needs the sender's client_id" if client_id.to_s.empty?
191
194
 
192
195
  follow_guard(session_id, state_dir, follow) do
193
196
  deliver_turn_now(session_id, prompt: prompt, client_id: client_id, images: images, delivery: delivery,
194
197
  no_interrupt: no_interrupt, author: author, pending_limit: pending_limit,
195
- anchors: anchors, state_dir: state_dir, manager: manager, bridge: bridge)
198
+ anchors: anchors, state_dir: state_dir, manager: manager, bridge: bridge,
199
+ enqueued_id: enqueued_id)
196
200
  end
197
201
  end
198
202
 
@@ -222,7 +226,7 @@ module Samagotchi
222
226
  end
223
227
 
224
228
  private def deliver_turn_now(session_id, prompt:, client_id:, images:, delivery:, no_interrupt:, author:,
225
- pending_limit:, anchors:, state_dir:, manager:, bridge:)
229
+ pending_limit:, anchors:, state_dir:, manager:, bridge:, enqueued_id: nil)
226
230
  anchors = TurnAnchors.from(anchors)
227
231
  session_dir = Session.session_dir(session_id, state_dir: state_dir || Session.default_state_dir)
228
232
  bridge ||= lambda do
@@ -234,8 +238,12 @@ module Samagotchi
234
238
  refused = start_for_send(manager, session_id, state_dir, client_id, before: true)
235
239
  return refused if refused
236
240
 
237
- enqueued_id = SessionInbox.new_enqueued_id
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
238
245
  if (client = bridge.call)
246
+ agent_reader = worker_has?(client, Delivery::AGENT_FEATURE) if ClientId.agent?(client_id)
239
247
  if (missing = anchors.present.find { |anchor| !worker_has?(client, anchor.class::FEATURE) })
240
248
  return DeliverResult.new(status: :refused, code: 409, ack: missing.class::UNAVAILABLE)
241
249
  end
@@ -245,6 +253,8 @@ module Samagotchi
245
253
  # A participant's turn only to a worker that runs it under the
246
254
  # owner's rules: an older one would run it read-only.
247
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)
248
258
  # A participant's Revise only to a worker that checks it at the
249
259
  # stamp (ParticipantRevise): an older one would stamp it unchecked.
250
260
  if Steer.participant_author?(author) && anchors.revises && !worker_has?(client, ReviseAnchor::PARTICIPANT_FEATURE)
@@ -257,6 +267,9 @@ module Samagotchi
257
267
  if ClientId.participant?(client_id) && !worker_has?(client, Delivery::PARTICIPANT_ID_FEATURE)
258
268
  client_id = ClientId.legacy_participant(client_id)
259
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
260
273
 
261
274
  begin
262
275
  options = { prompt: prompt, client_id: client_id, enqueued_id: enqueued_id }
@@ -293,11 +306,27 @@ module Samagotchi
293
306
  # still holding the session with its Bridge gone (exiting) may be an
294
307
  # older one, which would run it without the pair boundary.
295
308
  # (A one-turn chi run holding it is refused as for anyone, below.)
296
- if Steer.participant_author?(author) && (holder = delivery_presence(manager, session_id, state_dir)).owned? &&
297
- !holder.tui_owned?
298
- return DeliverResult.new(status: :timeout, via: :file,
299
- ack: { "error" => "worker_timeout",
300
- "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
301
330
  end
302
331
  input = { prompt: prompt, client_id: client_id, enqueued_id: enqueued_id, state_dir: state_dir }
303
332
  input[:images] = images unless images.empty?
@@ -423,6 +452,26 @@ module Samagotchi
423
452
  DeliverResult.new(status: :refused, code: 409, ack: Delivery::QUEUE_UNAVAILABLE)
424
453
  end
425
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
+
426
475
  private def pair_unavailable
427
476
  DeliverResult.new(status: :refused, code: 409, ack: Delivery::PAIR_UNAVAILABLE)
428
477
  end
@@ -59,12 +59,15 @@ module Samagotchi
59
59
  # @param client_id [String, nil] who sent +prompt+ (a ClientId); required
60
60
  # even when nil is intentional for a session with no initial prompt
61
61
  # @param session_id [String, nil] an id reserved by a durable operation
62
+ # @param driver [String, nil, Symbol] its driver (Session#driver):
63
+ # :creator (the default) is +client_id+ when it is an agent's; a
64
+ # continue passes the previous link's, nil included
62
65
  # @return [Session] with #seed_images_dropped: refs whose file was gone,
63
66
  # and #model_warning: an id its host's saved list doesn't have
64
67
  def spawn_session(prompt:, client_id:, mode: "assist", working_directory: nil, model_name: nil, state_dir: nil,
65
68
  parent_id: nil, messages: [], images_from: nil, preview: nil, title: nil, delegate: false,
66
69
  setup: SessionSetup.new, continues: nil, note: nil, note_source: "chi", before_spawn: nil,
67
- review: nil, verify_fresh: nil, scratch: false, session_id: nil)
70
+ review: nil, verify_fresh: nil, scratch: false, session_id: nil, driver: :creator)
68
71
  sd = state_dir || Session.default_state_dir
69
72
  if session_id && (!Session.valid_id?(session_id) || Session.exist?(session_id, state_dir: sd))
70
73
  raise ArgumentError, "invalid or existing session id #{session_id.inspect}"
@@ -110,6 +113,9 @@ module Samagotchi
110
113
  session.first_turn_id = SecureRandom.uuid
111
114
  session.first_turn_client_id = client_id unless ClientId.human?(client_id)
112
115
  end
116
+ # With a prompt or without (chi send --new's idle create, its line
117
+ # sent next): its creator's first turn is the driver's too.
118
+ session.driver = driver == :creator ? (client_id if ClientId.agent?(client_id)) : driver
113
119
  # The worker takes last_prompt and clears it, and messages are saved at
114
120
  # the turn's end: until then this is the only preview a list has.
115
121
  session.first_preview = Session.preview_of(preview.to_s.strip.empty? ? prompt : preview)