samagotchi 0.176.0 → 0.177.1

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 (77) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +47 -1
  3. data/docs/architecture.md +5 -4
  4. data/docs/cli.md +12 -5
  5. data/docs/internals/bundles.md +4 -3
  6. data/docs/internals/participants.md +10 -6
  7. data/docs/internals/prompt-caching.md +3 -0
  8. data/docs/internals/session-lifecycle.md +167 -0
  9. data/docs/internals/web-frontend.md +25 -8
  10. data/docs/internals/working-set.md +78 -6
  11. data/docs/plugins.md +1 -1
  12. data/docs/releasing.md +3 -2
  13. data/docs/sessions.md +8 -5
  14. data/docs/testing.md +4 -2
  15. data/lib/samagotchi/bridge.rb +3 -3
  16. data/lib/samagotchi/bundle_command/check.rb +1 -1
  17. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  18. data/lib/samagotchi/compat.rb +1 -1
  19. data/lib/samagotchi/engine/models.rb +11 -0
  20. data/lib/samagotchi/engine/session.rb +16 -0
  21. data/lib/samagotchi/engine.rb +1 -0
  22. data/lib/samagotchi/engine_snapshots.rb +3 -0
  23. data/lib/samagotchi/memory_bundle/shipped_update.rb +1 -1
  24. data/lib/samagotchi/note_delivery.rb +9 -4
  25. data/lib/samagotchi/plugin/sessions.rb +2 -1
  26. data/lib/samagotchi/prompt_part.rb +66 -0
  27. data/lib/samagotchi/revise_anchor.rb +2 -0
  28. data/lib/samagotchi/schedules.rb +3 -1
  29. data/lib/samagotchi/session.rb +10 -1
  30. data/lib/samagotchi/session_chain/delete.rb +28 -5
  31. data/lib/samagotchi/session_chain/delete_preview.rb +2 -2
  32. data/lib/samagotchi/session_inbox.rb +29 -0
  33. data/lib/samagotchi/session_inbox_delivery.rb +13 -5
  34. data/lib/samagotchi/session_lifecycle/allowed.rb +66 -0
  35. data/lib/samagotchi/session_lifecycle/canonical.rb +49 -0
  36. data/lib/samagotchi/session_lifecycle/reading.rb +65 -0
  37. data/lib/samagotchi/session_lifecycle.rb +59 -0
  38. data/lib/samagotchi/session_manager/delivery.rb +29 -6
  39. data/lib/samagotchi/session_manager/lifecycle.rb +22 -14
  40. data/lib/samagotchi/session_manager/removal.rb +16 -8
  41. data/lib/samagotchi/session_manager/spawn.rb +2 -2
  42. data/lib/samagotchi/sessions_command.rb +1 -1
  43. data/lib/samagotchi/system_prompt.rb +211 -12
  44. data/lib/samagotchi/tool_names.rb +1 -1
  45. data/lib/samagotchi/tools/memory.rb +29 -0
  46. data/lib/samagotchi/turn_anchors.rb +5 -0
  47. data/lib/samagotchi/verify_anchor.rb +2 -0
  48. data/lib/samagotchi/version.rb +1 -1
  49. data/lib/samagotchi/web/participant_show.rb +4 -5
  50. data/lib/samagotchi/web/participant_view.rb +4 -6
  51. data/lib/samagotchi/web/public/app.js +3 -0
  52. data/lib/samagotchi/web/public/ctx_tokens.js +33 -0
  53. data/lib/samagotchi/web/public/data.js +6 -2
  54. data/lib/samagotchi/web/public/delete_sheet.js +42 -5
  55. data/lib/samagotchi/web/public/index.html +43 -9
  56. data/lib/samagotchi/web/public/session_fields.js +10 -4
  57. data/lib/samagotchi/web/public/session_prefs.js +5 -2
  58. data/lib/samagotchi/web/public/session_state.js +14 -1
  59. data/lib/samagotchi/web/public/session_store.js +1 -1
  60. data/lib/samagotchi/web/public/session_view.js +1 -1
  61. data/lib/samagotchi/web/public/stream_handlers.js +7 -3
  62. data/lib/samagotchi/web/public/tokens.css +2 -2
  63. data/lib/samagotchi/web/public/working_set.js +51 -7
  64. data/lib/samagotchi/web/public/working_set_view.js +188 -58
  65. data/lib/samagotchi/web/public/ws_sections.js +252 -0
  66. data/lib/samagotchi/web/session_control.rb +4 -3
  67. data/lib/samagotchi/web/session_show.rb +13 -2
  68. data/lib/samagotchi/web/session_summary.rb +7 -0
  69. data/lib/samagotchi/worker/command_queue.rb +5 -1
  70. data/lib/samagotchi/worker/startup.rb +1 -1
  71. data/lib/samagotchi/worker.rb +1 -0
  72. data/lib/samagotchi/worker_boot.rb +9 -6
  73. data/lib/samagotchi/worker_presence.rb +4 -0
  74. data/lib/samagotchi/working_set.rb +32 -4
  75. data/lib/samagotchi/working_set_command.rb +3 -2
  76. data/lib/samagotchi/working_set_steer.rb +14 -3
  77. metadata +9 -1
@@ -13,7 +13,8 @@ module Samagotchi
13
13
  # the previous one a delete would bring back), :delegate_unmovable (a
14
14
  # delegate the deleted link's continue moved can't go back: +ids+,
15
15
  # +detail+ says why), :chain_scheduled (a schedule is on the chain a
16
- # chain delete would take: +schedule_id+).
16
+ # chain delete would take: +schedule_id+), :plan_changed (the plan no
17
+ # longer matches the digest the caller confirmed).
17
18
  class DeleteRefused < StandardError
18
19
  attr_reader :session_id, :reason, :schedule_id, :ids
19
20
 
@@ -40,6 +41,7 @@ module Samagotchi
40
41
  "#{@ids.map { |id| id[0, 8] }.join(", ")}, moved here by the continue, can't go back to the previous link" \
41
42
  "#{": #{detail}" if detail}"
42
43
  when :chain_scheduled then "an enabled schedule runs on this chain#{cancel}"
44
+ when :plan_changed then "what this delete would do changed since it was shown; review the new plan and try again"
43
45
  else "session #{@session_id} can't be deleted now (#{@reason})"
44
46
  end
45
47
  end
@@ -193,8 +195,12 @@ module Samagotchi
193
195
  # (:continuing) while a continue of the session is in flight
194
196
  # @raise [DeleteRefused] also :scheduled for a schedule's anchor or
195
197
  # head, and with the keywords :continuing and :delegate_unmovable
198
+ # @param still [#call, nil] the caller's own check, read again under
199
+ # the deleting lock (#remove_files; DeleteRefused :changed when it no
200
+ # longer holds): an empty session's discard. Not with the chain keywords.
196
201
  def delete_session(id_or_prefix, state_dir: nil, stop: false, wait: STOP_WAIT, purge_runs: true,
197
- allow_scheduled: false, revive_previous: false, refuse_continuing: false)
202
+ allow_scheduled: false, revive_previous: false, refuse_continuing: false, expect: nil,
203
+ still: nil)
198
204
  sd = state_dir || Session.default_state_dir
199
205
  given = id_or_prefix.to_s
200
206
  # Only a plain id: anything else could name a path outside the state dir.
@@ -209,10 +215,11 @@ module Samagotchi
209
215
  if revive_previous || refuse_continuing
210
216
  require_relative "../session_chain/delete"
211
217
  return SessionChain::Delete.link(id, state_dir: sd, stop: stop, wait: wait, revive_previous: revive_previous,
212
- refuse_continuing: refuse_continuing)
218
+ refuse_continuing: refuse_continuing, expect: expect)
213
219
  end
214
220
 
215
- delete_resolved(id, state_dir: sd, stop: stop, wait: wait, purge_runs: purge_runs, allow_scheduled: allow_scheduled)
221
+ delete_resolved(id, state_dir: sd, stop: stop, wait: wait, purge_runs: purge_runs, allow_scheduled: allow_scheduled,
222
+ still: still)
216
223
  end
217
224
 
218
225
  # Delete every link of +id+'s chain with their delegates
@@ -223,7 +230,7 @@ module Samagotchi
223
230
  # @return [Hash] SessionChain::Delete.chain's
224
231
  # @raise [ArgumentError] unknown id (Session::AmbiguousId for a prefix of several)
225
232
  # @raise [DeleteRefused, OwnedByTUI] nothing was deleted
226
- def delete_chain(id_or_prefix, state_dir: nil, stop: false, wait: STOP_WAIT)
233
+ def delete_chain(id_or_prefix, state_dir: nil, stop: false, wait: STOP_WAIT, expect: nil)
227
234
  sd = state_dir || Session.default_state_dir
228
235
  given = id_or_prefix.to_s
229
236
  raise Session::NotFound, given unless Session.valid_id?(given)
@@ -232,21 +239,22 @@ module Samagotchi
232
239
  raise Session::NotFound, given unless Session.exist?(id, state_dir: sd)
233
240
 
234
241
  require_relative "../session_chain/delete"
235
- SessionChain::Delete.chain(id, state_dir: sd, stop: stop, wait: wait)
242
+ SessionChain::Delete.chain(id, state_dir: sd, stop: stop, wait: wait, expect: expect)
236
243
  end
237
244
 
238
245
  # #delete_session's checks and removal for a full id that exists:
239
246
  # the schedule refusal, the one-turn run, the worker (stopped with
240
247
  # +stop+), then #remove_files. SessionChain::Delete's last step.
241
248
  # @return [Hash] {id:, removed:, stopped:}
242
- def delete_resolved(id, state_dir:, stop: false, wait: STOP_WAIT, purge_runs: true, allow_scheduled: false)
249
+ def delete_resolved(id, state_dir:, stop: false, wait: STOP_WAIT, purge_runs: true, allow_scheduled: false,
250
+ still: nil)
243
251
  sd = state_dir
244
252
  path = Session.session_file(id, state_dir: sd)
245
253
  dir = Session.session_dir(id, state_dir: sd)
246
254
  refuse_scheduled!(id, sd) unless allow_scheduled
247
255
 
248
256
  held = release_for_delete!(id, state_dir: sd, stop: stop, wait: wait)
249
- removed = remove_files(id, path, dir, state_dir: sd, purge_runs: purge_runs)
257
+ removed = remove_files(id, path, dir, state_dir: sd, purge_runs: purge_runs, still: still)
250
258
  { id: id, removed: removed, stopped: held }
251
259
  end
252
260
 
@@ -195,8 +195,8 @@ module Samagotchi
195
195
  # landing between the check and the resume is a small window, left as
196
196
  # is. An archived parent with a later link wakes that link (one hop:
197
197
  # ChildReports reads its predecessor's rings, no further).
198
- # @return [Symbol] :woken, or why not (:gone, :stopped, :archived,
199
- # :scratch, :owned, :starting)
198
+ # @return [Symbol] :woken, or why not (:gone, :deleting: a deleter
199
+ # holds its lock, :stopped, :archived, :scratch, :owned, :starting)
200
200
  def wake_for_report(session_id, state_dir: nil)
201
201
  sd = state_dir || Session.default_state_dir
202
202
  outcome = SessionInbox.wake(:ring, session_id, state_dir: sd, owner: ->(id) { session_owner(id, state_dir: sd) }).wake
@@ -325,7 +325,7 @@ module Samagotchi
325
325
  next false
326
326
  rescue Samagotchi::SessionManager::RestartRefused => e
327
327
  @stdout.flush
328
- @stderr.puts %i[not_running unsupported fallback_held stopped failed].include?(e.reason) ? e.message : "session #{id}: #{e.message}"
328
+ @stderr.puts %i[not_running unsupported fallback_held stopped stop_marked failed].include?(e.reason) ? e.message : "session #{id}: #{e.message}"
329
329
  next false
330
330
  rescue ArgumentError => e
331
331
  @stdout.flush
@@ -16,6 +16,8 @@ require_relative "memory_bundle/index_size"
16
16
  require_relative "thinking"
17
17
  require_relative "prompt_files"
18
18
  require_relative "plugin/prompt_sections"
19
+ require_relative "prompt_part"
20
+ require "json"
19
21
 
20
22
  module Samagotchi
21
23
  # The system prompt an Engine gives its model: the base prompt (tool
@@ -95,7 +97,21 @@ module Samagotchi
95
97
  # plugins' sections it holds, its stable part's length (chat) and the
96
98
  # Tools::ToolSurface it declares (the tools, the not-loaded line, the
97
99
  # kit's prompt text).
98
- Built = Data.define(:prompt, :memory_index, :notes, :files, :sections, :stable_length, :surface)
100
+ #
101
+ # parts: the Sections the prompt is joined from (stable ones, then the
102
+ # volatile ones), in prompt order; Gemma's tail declarations are not one.
103
+ # prompt_parts: the same as sizes, one PromptPart per memory, file and
104
+ # plugin section, the tools part first (#prompt_parts).
105
+ Built = Data.define(:prompt, :memory_index, :notes, :files, :sections, :stable_length, :surface, :memory_names, :parts,
106
+ :prompt_parts, :prompt_memories)
107
+
108
+ # One part of the prompt: its kind (KINDS), what it was made from (the
109
+ # memory names of identity and preloads, the files of agents and
110
+ # appended, the notes of notes, the plugins' Built of plugins; nil
111
+ # elsewhere) and its text, as the prompt holds it.
112
+ Section = Data.define(:kind, :ref, :text)
113
+
114
+ KINDS = %i[base identity notes preloads agents appended kit plugins indexes participants model location session].freeze
99
115
 
100
116
  # The full prompt: #base wrapped with the index and the rest. Built once
101
117
  # per loop and level (until #reset!) so the prompt prefix, and the
@@ -120,6 +136,8 @@ module Samagotchi
120
136
  built = cache[key] || (cache[key] = build_prompt(chat: chat, thinking: thinking, layers: layers))
121
137
  @memory_index = built.memory_index
122
138
  @last = built
139
+ @last_prompt_memory_names = built.memory_names
140
+ @last_prompt_memories = built.prompt_memories
123
141
  built.prompt
124
142
  end
125
143
 
@@ -137,6 +155,24 @@ module Samagotchi
137
155
  # @return [Array<ModelNotes::Note>, nil]
138
156
  def prompt_notes = @last&.notes
139
157
 
158
+ # The sizes of the parts the prompt #build returned last is made of
159
+ # (PromptPart: the tools first, then each memory, file and plugin
160
+ # section in prompt order; chars at TokenUsage's one ratio). Worked out
161
+ # once with the prompt, kept with it. [] before a build and after
162
+ # #reset!.
163
+ # @return [Array<PromptPart>]
164
+ def prompt_parts = @last&.prompt_parts || []
165
+
166
+ # The identity and preloaded memories the last prompt build actually
167
+ # rendered; retained across reset! until another build completes.
168
+ # @return [Array<String>]
169
+ def prompt_memory_names = @last_prompt_memory_names || []
170
+
171
+ # The identity and preloaded memories in the last built prompt, with the
172
+ # scope each memory answered from; retained across reset! like the names.
173
+ # @return [Array<Array(String, String, nil)>]
174
+ def prompt_memories = @last_prompt_memories || []
175
+
140
176
  # The files whose text the prompt #build returned last holds, as
141
177
  # absolute paths in prompt order: the AGENTS.md chain, then the
142
178
  # appended files (append_system_prompt:, --append-system-prompt). [] before a
@@ -192,16 +228,122 @@ module Samagotchi
192
228
  # @section_* and @measured_* scratch is this build's (the turn thread's)
193
229
  # alone: #reset! never touches it.
194
230
  def build_prompt(chat:, thinking:, layers:)
231
+ @section_identity_memory_name = nil
232
+ @section_activated_memory_names = []
195
233
  @section_notes = nil
196
234
  @section_files = []
197
235
  @section_plugins = []
198
236
  @measured_stable_length = nil
237
+ @section_parts = []
238
+ @section_file_chars = []
239
+ @section_item_chars = {}
240
+ @section_preload_chars = []
241
+ @section_preload_scopes = []
242
+ @section_index_chars = {}
199
243
  surface = tool_surface(layers)
200
244
  prompt = system_prompt_with_index(assist_system_prompt(chat: chat, surface: surface),
201
245
  chat: chat, thinking: thinking, surface: surface)
246
+ prompt_parts = Degrade.call(:prompt, "prompt_parts_failed", fallback: []) do
247
+ prompt_parts_for(@section_parts, chat: chat, surface: surface)
248
+ end
249
+ prompt_memories = prompt_memories_for(@section_parts)
202
250
  Built.new(prompt: prompt, memory_index: @measured_index, notes: @section_notes || [],
203
251
  files: @section_files.freeze, sections: @section_plugins.freeze, stable_length: @measured_stable_length,
204
- surface: surface)
252
+ surface: surface, memory_names: [@section_identity_memory_name, *@section_activated_memory_names].compact.uniq.freeze,
253
+ parts: @section_parts.freeze, prompt_parts: prompt_parts.freeze, prompt_memories: prompt_memories)
254
+ end
255
+
256
+ def prompt_memories_for(sections)
257
+ sections.flat_map do |section|
258
+ case section.kind
259
+ when :identity
260
+ section.ref ? [[section.ref, "system"]] : []
261
+ when :preloads
262
+ Array(section_items(section)).map { |_, name, _, scope| [name, scope] }
263
+ else
264
+ []
265
+ end
266
+ end.map(&:freeze).uniq.freeze
267
+ end
268
+
269
+ # ── The parts' sizes ───────────────────────────────────────────────────────
270
+
271
+ LABELS = { base: "base prompt", kit: "toolkit prompt", participants: "participants", model: "model",
272
+ location: "location", session: "session" }.freeze
273
+
274
+ # The PromptParts of +sections+ (a build's), the tools part first. A
275
+ # multi-item section is one part per item; its headings and joins go
276
+ # into its first part, so the parts sum to the section's text.
277
+ def prompt_parts_for(sections, chat:, surface:)
278
+ tools_chars = tools_chars(chat: chat, surface: surface)
279
+ parts = sections.flat_map { |part| section_parts(part) }
280
+ if tools_chars[:from_base]
281
+ base = parts.index { |part| part.kind == "base" }
282
+ parts[base] = PromptPart.build(kind: :base, label: parts[base].label, chars: parts[base].chars - tools_chars[:chars]) if base
283
+ end
284
+ [PromptPart.build(kind: :tools, label: "#{surface.declared_names.size} declared", chars: tools_chars[:chars]), *parts]
285
+ end
286
+
287
+ # The tool declarations' size, once. chat: the schemas as the request's
288
+ # tools field sends them. Native: the declarations text, inside the base
289
+ # prompt (from_base: its chars move out of the base part) or, on Gemma,
290
+ # after the last section (nothing to move).
291
+ def tools_chars(chat:, surface:)
292
+ return { chars: JSON.generate(surface.schemas).length, from_base: false } if chat
293
+
294
+ { chars: tool_declarations(surface).length, from_base: !gemma_tail_declarations? }
295
+ end
296
+
297
+ def section_parts(section)
298
+ items = section_items(section)
299
+ return [PromptPart.build(kind: section.kind, label: LABELS.fetch(section.kind, section.kind), chars: section.text.length)] if items.nil?
300
+
301
+ # The first item's own chars are the rest of the text.
302
+ rest = items.drop(1).sum { |item| item[2] }
303
+ items.each_with_index.map do |(label, ref, chars, scope), index|
304
+ PromptPart.build(kind: section.kind, label: label, ref: ref, scope: scope,
305
+ chars: index.zero? ? section.text.length - rest : chars)
306
+ end
307
+ end
308
+
309
+ # [label, ref, own chars, scope] per item of a section made of several
310
+ # (scope: a memory part's, else nil), nil for a section that is one part.
311
+ def section_items(section)
312
+ case section.kind
313
+ when :identity then [[section.ref.to_s, section.ref, section.text.length, "system"]] if section.ref
314
+ when :notes
315
+ # In the text's order: it groups the notes by scope.
316
+ Array(section.ref).group_by(&:scope).values.flatten(1).map do |note|
317
+ [note.name, note.name, "## #{note.name}\n#{note.body}".length, note.scope]
318
+ end
319
+ when :preloads
320
+ scopes = @section_preload_scopes
321
+ item_list(Array(section.ref), @section_preload_chars) { |name| [name, name] }
322
+ &.each_with_index&.map { |item, index| [*item, scopes&.[](index)] }
323
+ when :agents, :appended
324
+ top = MemoryPaths.work_tree_root(Dir.pwd)
325
+ item_list(Array(section.ref), @section_item_chars[section.kind]) { |path| [file_label(path, top), path] }
326
+ when :plugins
327
+ Array(section.ref).map { |built| ["#{built.bundle}: #{built.name}", "#{built.bundle}/#{built.name}", built.prompt_text.length] }
328
+ when :indexes
329
+ [["project memory index", "project", @section_index_chars[:project]], ["system memory index", "system", @section_index_chars[:system]]]
330
+ end&.then { |items| items.empty? ? nil : items }
331
+ end
332
+
333
+ # A file part's label: its path under the work tree +top+ (AGENTS.md,
334
+ # docs/rules.md), else with ~ for the home directory.
335
+ def file_label(path, top)
336
+ return Paths.tilde(path) unless top && path.start_with?("#{top}/")
337
+
338
+ path.delete_prefix("#{top}/")
339
+ end
340
+
341
+ # [label, ref, chars] per ref (+yield+ gives label and ref), nil when
342
+ # the recorded chars don't line up with the refs.
343
+ def item_list(refs, chars)
344
+ return nil unless chars && chars.size == refs.size
345
+
346
+ refs.each_with_index.map { |ref, index| [*yield(ref), chars[index]] }
205
347
  end
206
348
 
207
349
  # The session's tools as a build under +layers+ declares them, read
@@ -348,21 +490,59 @@ module Samagotchi
348
490
  thinking_token = chat ? "" : Thinking.native(thinking || turn_thinking, profile).system_token
349
491
  indexes = { project: read_memory_index("project"), system: read_memory_index("system") }
350
492
  @measured_index = measure_indexes(indexes)
351
- memory_sections = [
352
- "Project memories:\n#{indexes[:project]}",
353
- "System memories:\n#{indexes[:system]}"
354
- ].join("\n\n")
355
- stable = [thinking_token + base, not_loaded_line(surface), rg_guidance, system_identity_section, model_notes_section, explicit_memory_section,
356
- project_specific_description, appended_section, kit_prompt_section(surface), plugin_prompt_section, memory_sections]
357
- stable_text = stable.compact.join("\n")
358
- volatile = [participants_section, current_model, project_location, current_session].compact
493
+ memory_sections = %i[project system].map { |scope| memory_sections_head(indexes, scope) }.join("\n\n")
494
+ # Built eagerly and in this order: the builders set the @section_* scratch.
495
+ base_text = [thinking_token + base, not_loaded_line(surface), rg_guidance].compact.join("\n")
496
+ @section_index_chars = { project: memory_sections_head(indexes, :project).length,
497
+ system: memory_sections_head(indexes, :system).length }
498
+ stable = [
499
+ Section.new(kind: :base, ref: nil, text: base_text),
500
+ section(:identity, -> { @section_identity_memory_name }) { system_identity_section },
501
+ section(:notes, -> { @section_notes }) { model_notes_section },
502
+ section(:preloads, -> { Array(@section_activated_memory_names).dup }) { explicit_memory_section },
503
+ files_section(:agents) { project_specific_description },
504
+ files_section(:appended) { appended_section },
505
+ section(:kit, nil) { kit_prompt_section(surface) },
506
+ section(:plugins, -> { @section_plugins }) { plugin_prompt_section },
507
+ Section.new(kind: :indexes, ref: %i[project system], text: memory_sections)
508
+ ].compact
509
+ stable_text = stable.map(&:text).join("\n")
510
+ volatile = [section(:participants, nil) { participants_section }, section(:model, nil) { current_model },
511
+ section(:location, nil) { project_location }, section(:session, nil) { current_session }].compact
512
+ @section_parts = stable + volatile
359
513
  return with_tail_declarations(stable_text, chat: chat, surface: surface) if volatile.empty?
360
514
 
361
- prompt = "#{stable_text}\n#{volatile.join("\n")}"
515
+ prompt = "#{stable_text}\n#{volatile.map(&:text).join("\n")}"
362
516
  @measured_stable_length = stable_text.length + 1 if chat
363
517
  with_tail_declarations(prompt, chat: chat, surface: surface)
364
518
  end
365
519
 
520
+ # One scope's block of the indexes section.
521
+ def memory_sections_head(indexes, scope)
522
+ "#{scope.to_s.capitalize} memories:\n#{indexes[scope]}"
523
+ end
524
+
525
+ # A Section of +kind+ with what the block (a builder) returns, nil when
526
+ # that is nil (never when it is empty: an "" part stays in the prompt).
527
+ # +ref+ is read after the block ran, so it may name what the builder set.
528
+ def section(kind, ref = nil, &)
529
+ text = yield
530
+ if text.nil?
531
+ nil
532
+ else
533
+ Section.new(kind: kind, ref: ref.respond_to?(:call) ? ref.call : ref, text: text)
534
+ end
535
+ end
536
+
537
+ # A Section whose ref is the files its builder added to @section_files.
538
+ def files_section(kind, &block)
539
+ before = @section_files&.size || 0
540
+ section(kind, nil, &block)&.then do |part|
541
+ @section_item_chars[kind] = Array(@section_file_chars)[before..].dup if @section_item_chars
542
+ part.with(ref: Array(@section_files)[before..].dup)
543
+ end
544
+ end
545
+
366
546
  # The tools the session's toolkit leaves out, named once right after the
367
547
  # base prompt: sessions on another toolkit already differ at the tools,
368
548
  # and nothing later (a memory write) moves it. nil when none are (full):
@@ -432,6 +612,7 @@ module Samagotchi
432
612
  next if body.start_with?("Error:")
433
613
  next if body.strip.empty?
434
614
 
615
+ @section_identity_memory_name = name
435
616
  return "System identity (auto-loaded, scope=system):\n#{body}"
436
617
  end
437
618
  nil
@@ -546,7 +727,11 @@ module Samagotchi
546
727
  # status line. The memory-body injection itself stays here — the
547
728
  # SystemPrompt is the single source of truth for the system prompt.
548
729
  @activated_memory_names << actual_name
549
- entries << "this memory is required by the user in the current context: memory name: #{actual_name}\n#{body}"
730
+ @section_activated_memory_names << actual_name
731
+ entry = "this memory is required by the user in the current context: memory name: #{actual_name}\n#{body}"
732
+ @section_preload_chars&.push(entry.length)
733
+ @section_preload_scopes&.push(scope || answered_scope(body, actual_name))
734
+ entries << entry
550
735
  end
551
736
  end
552
737
 
@@ -555,6 +740,18 @@ module Samagotchi
555
740
  entries.join("\n\n")
556
741
  end
557
742
 
743
+ # The scope whose file answered a bare preload's read (memory_read
744
+ # falls back project -> system): its file under the project's memories
745
+ # is the project's, else the system's. nil without the read's record (a
746
+ # plain String body).
747
+ def answered_scope(body, name)
748
+ read = body.respond_to?(:reads) ? body.reads[name] : nil
749
+ return nil unless read.is_a?(Hash)
750
+
751
+ dir = read[:project_dir]
752
+ dir && read[:path].to_s.start_with?("#{dir}/") ? "project" : "system"
753
+ end
754
+
558
755
  def split_memory_scope(raw)
559
756
  value = raw.to_s.strip
560
757
  if value.include?("/")
@@ -577,6 +774,7 @@ module Samagotchi
577
774
  return nil if sections.empty?
578
775
 
579
776
  @section_files&.concat(sections.map(&:path))
777
+ @section_file_chars&.concat(sections.map { |section| section.text.length })
580
778
  sections.map(&:text).join("\n\n")
581
779
  end
582
780
  end
@@ -603,6 +801,7 @@ module Samagotchi
603
801
  next unless text
604
802
 
605
803
  @section_files&.push(path)
804
+ @section_file_chars&.push(text.length)
606
805
  sections << text
607
806
  end
608
807
  sections.empty? ? nil : sections.join("\n\n")
@@ -4,7 +4,7 @@ module Samagotchi
4
4
  # chi's built-in tools' names, and the fixed texts some of them write into
5
5
  # their results, apart from the tool classes: the code that only names a
6
6
  # tool or matches a result to draw a row (ToolActivity, ToolView, FileRef,
7
- # ObjectivesBacking) reads them here and loads no tool class (Tools::Execute
7
+ # Objectives::Backing) reads them here and loads no tool class (Tools::Execute
8
8
  # alone brings TaskRuntime, Shell, Leftovers, the process group…).
9
9
  #
10
10
  # Each tool class keeps its own constants, read from here
@@ -76,6 +76,35 @@ module Samagotchi
76
76
  nil
77
77
  end
78
78
 
79
+ # Whether +target+ names a memory held in the prompt. A bare target
80
+ # matches by name; an explicitly scoped target also matches an
81
+ # unscoped prompt entry by name for older prompt data.
82
+ def self.prompt_memory?(target, memories)
83
+ target_scope, target_name = prompt_memory_target(target)
84
+ return false if target_name.empty?
85
+
86
+ Array(memories).any? do |memory|
87
+ prompt_name, prompt_scope = memory.is_a?(Array) ? memory : [memory, nil]
88
+ prompt_name = prompt_memory_name(prompt_name)
89
+ prompt_scope = normalize_scope(prompt_scope)
90
+ prompt_name == target_name && (!target_scope || !prompt_scope || target_scope == prompt_scope)
91
+ end
92
+ end
93
+
94
+ def self.prompt_memory_target(value)
95
+ name = value.to_s.strip
96
+ scope, name = name.split("/", 2) if name.include?("/")
97
+ [normalize_scope(scope), scope && VALID_SCOPES.include?(scope) ? name : value.to_s.strip]
98
+ end
99
+ private_class_method :prompt_memory_target
100
+
101
+ def self.prompt_memory_name(value)
102
+ name = value.to_s.strip
103
+ scope, suffix = name.split("/", 2) if name.include?("/")
104
+ scope && VALID_SCOPES.include?(scope) ? suffix : name
105
+ end
106
+ private_class_method :prompt_memory_name
107
+
79
108
  def self.overlay_prefix(key) = "#{SEPARATOR}Model-specific guidance (#{key}):\n"
80
109
 
81
110
  def self.append_overlay(body, overlay_text, key) = "#{body}#{overlay_prefix(key)}#{overlay_text}"
@@ -40,6 +40,11 @@ module Samagotchi
40
40
  # A :prompt_restored event's fields.
41
41
  def to_h = { verify: verify&.to_h, revises: revises&.to_h }.compact
42
42
 
43
+ # What a participant sees of each anchor.
44
+ def participant_view
45
+ self.class.members.to_h { |member| [member.to_s, public_send(member)&.participant_view] }.compact
46
+ end
47
+
43
48
  # Engine#run_turn's keywords.
44
49
  def kwargs = { verify:, revises: }.compact
45
50
  end
@@ -21,6 +21,8 @@ module Samagotchi
21
21
  def to_h = { turn_id:, quote: }
22
22
 
23
23
  def to_file = { "turn_id" => turn_id, "quote" => quote }
24
+
25
+ def participant_view = to_file
24
26
  end
25
27
 
26
28
  # The shape of the turn id an anchor names (ReviseAnchor's too).
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.176.0"
4
+ VERSION = "0.177.1"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -3,6 +3,7 @@
3
3
  require "json"
4
4
  require_relative "participant_view"
5
5
  require_relative "viewer"
6
+ require_relative "session_summary"
6
7
  require_relative "../bridge/turn_accumulator"
7
8
  require_relative "../worker_link"
8
9
  require_relative "../verify_anchor"
@@ -89,8 +90,7 @@ module Samagotchi
89
90
  # delivery line, the stale-worker badge), its verdicts (filtered) and whether Verify fresh can run.
90
91
  def participant_session_json(reads, features, viewer)
91
92
  session = reads.session
92
- status = displayed_status(session, reads.state)
93
- status = Session::STATUS_IDLE if status == Session::STATUS_RUNNING && reads.turn_snapshot && reads.current_turn.nil?
93
+ status = SessionSummary.shown_status(session, reads.state, reads.turn_snapshot, owner: session_owner(session.id))
94
94
  dir = Session.session_dir(reads.id, state_dir: default_state_dir)
95
95
  { id: session.id, title: participant_title(session), status: status,
96
96
  bridge_up: !reads.turn_snapshot.nil?, worker_features: Array(features),
@@ -197,11 +197,10 @@ module Samagotchi
197
197
  shown = messages_for_display(raw, parts: true, cwd: session.working_directory, markdown: false)
198
198
  messages = ParticipantView.messages(shown, viewer)
199
199
  answer = participant_answer(messages, turn_id.empty? ? nil : turn_id)
200
- status = displayed_status(session, reads.state)
201
- status = Session::STATUS_IDLE if status == Session::STATUS_RUNNING && reads.turn_snapshot && reads.current_turn.nil?
200
+ status = SessionSummary.shown_status(session, reads.state, reads.turn_snapshot, owner: session_owner(session.id))
202
201
  json_response(200, {
203
202
  tail: true,
204
- session: { id: id, status: status, used_memory_names: [], prompt_notes: [] },
203
+ session: { id: id, status: status, used_memory_names: [], prompt_notes: [], prompt_parts: [] },
205
204
  messages: with_reply_html([answer].compact),
206
205
  # The owner's chi web's own setup notes: never a participant's.
207
206
  markdown_warning: nil,
@@ -4,8 +4,7 @@ require_relative "../output_formatter"
4
4
  require_relative "../model_markup"
5
5
  require_relative "../steer"
6
6
  require_relative "../turn_origin"
7
- require_relative "../revise_anchor"
8
- require_relative "../verify_anchor"
7
+ require_relative "../turn_anchors"
9
8
  require_relative "../redact"
10
9
  require_relative "../file_ref"
11
10
  require_relative "../image_store"
@@ -138,8 +137,8 @@ module Samagotchi
138
137
  # their image refs (#image_refs), the Revise draft's turn id and the
139
138
  # origin's ids the page matches it by (restore.js restoreAction). nil
140
139
  # for anyone else's, the owner's or an automatic turn (decided by the
141
- # origin's author, which chi web stamped). Never source, the error, a
142
- # Verify claim's quote or anything else the owner's event carries.
140
+ # origin's author, which chi web stamped). Only a parsed Verify claim is
141
+ # carried beyond those fields.
143
142
  def prompt_restored(event, viewer)
144
143
  origin = field(event, :origin)
145
144
  return nil unless origin.is_a?(Hash)
@@ -150,8 +149,7 @@ module Samagotchi
150
149
  out = { "type" => "prompt_restored", **seq(event), "prompt" => field(event, :prompt).to_s }
151
150
  images = image_refs(field(event, :images), author, viewer)
152
151
  out["images"] = images if images
153
- revises = ReviseAnchor.from(field(event, :revises))
154
- out["revises"] = { "turn_id" => revises.turn_id } if revises
152
+ out.merge!(TurnAnchors.new(verify: field(event, :verify), revises: field(event, :revises)).participant_view)
155
153
  out["origin"] = { "client_id" => field(origin, :client_id).to_s, "enqueued_id" => field(origin, :enqueued_id).to_s,
156
154
  "author" => author.to_s }
157
155
  out
@@ -1599,6 +1599,9 @@ store.on("paintActive", () => lists.paintActive());
1599
1599
  store.on("settingsPanel", () => settingsControl?.refresh());
1600
1600
  // The working set's list offers pin only under forget.
1601
1601
  store.on("workingSetStrategy", () => workingSet?.strategyChanged());
1602
+ store.on("workingSet", () => workingSet?.sessionChanged());
1603
+ // ?.(): a page holding an older working_set_view.js cached (the mixed-cache rule).
1604
+ store.on("workingSetTokens", () => workingSet?.tokensChanged?.());
1602
1605
  store.on("featureGates", () => featureGates.check(store.current));
1603
1606
  store.on("composer", composerMode.update);
1604
1607
  store.on("composer", () => objectives.redraw());
@@ -0,0 +1,33 @@
1
+ // The context's token count, next to its % (ctx.js): what the working set's
2
+ // head view says is in chi's head ("~X of Y") and what its Conversation row is
3
+ // the rest of. The same data ctx.js extractCtxPct reads: a :context_status's
4
+ // usage.estimated_used_tokens, a :generation_chunk's counts.total_tokens; on
5
+ // load the live worker's newest % back into tokens, else the saved
6
+ // timing.context.used_tokens.
7
+ //
8
+ // A module of its own: static JS is cached at unversioned URLs, and a new
9
+ // export on an old module would blank the page.
10
+
11
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
12
+
13
+ // The tokens in context a stream event says (+data+: a :context_status or a
14
+ // :generation_chunk), null when it says none.
15
+ export function ctxTokensOf(data) {
16
+ if (!data || typeof data !== "object") return null;
17
+ const used = num(data.usage?.estimated_used_tokens);
18
+ if (used !== null) return used;
19
+ return num(data.counts?.total_tokens);
20
+ }
21
+
22
+ // On load: the live worker's newest % (+pct+, counted against the window or
23
+ // the smaller budget) as tokens when the window is known, else the saved
24
+ // count (+context+: the session's timing.context). null when neither is.
25
+ export function loadedCtxTokens({ pct = null, context = null, budgetTokens = null } = {}) {
26
+ const window = num(context?.window_tokens);
27
+ if (num(pct) !== null && window && window > 0) {
28
+ const budget = num(budgetTokens);
29
+ const against = budget && budget > 0 ? Math.min(budget, window) : window;
30
+ return Math.round((pct / 100) * against);
31
+ }
32
+ return num(context?.used_tokens);
33
+ }
@@ -282,13 +282,17 @@ export function unarchiveSession(id, opts = {}) {
282
282
  // Deletes the session for good; force=true has the server stop a live
283
283
  // worker first (the page's confirm says so; without it, 409 worker_running).
284
284
  export function deleteSession(id, opts = {}) {
285
- return api(`/api/sessions/${encodeURIComponent(id)}?force=true`, { method: "DELETE", ...opts });
285
+ const { expect, ...apiOpts } = opts;
286
+ const plan = expect == null ? "" : `&expect=${encodeURIComponent(expect)}`;
287
+ return api(`/api/sessions/${encodeURIComponent(id)}?force=true${plan}`, { method: "DELETE", ...apiOpts });
286
288
  }
287
289
 
288
290
  // Deletes every link of the session's chain with their delegates (running
289
291
  // ones are left running); force: the links' workers are stopped first.
290
292
  export function deleteChain(id, opts = {}) {
291
- return api(`/api/sessions/${encodeURIComponent(id)}/chain?force=true`, { method: "DELETE", ...opts });
293
+ const { expect, ...apiOpts } = opts;
294
+ const plan = expect == null ? "" : `&expect=${encodeURIComponent(expect)}`;
295
+ return api(`/api/sessions/${encodeURIComponent(id)}/chain?force=true${plan}`, { method: "DELETE", ...apiOpts });
292
296
  }
293
297
 
294
298
  // What deleting a chained session would do, for the delete sheet