samagotchi 0.183.0 → 0.184.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 (72) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +40 -1
  3. data/docs/architecture.md +11 -10
  4. data/docs/bundles.md +1 -1
  5. data/docs/configuration.md +2 -1
  6. data/docs/internals/bridge.md +1 -1
  7. data/docs/internals/bundles.md +6 -2
  8. data/docs/internals/engine.md +2 -1
  9. data/docs/internals/participants.md +1 -1
  10. data/docs/internals/prompt-caching.md +8 -1
  11. data/docs/internals/remote-sessions.md +19 -3
  12. data/docs/internals/web-frontend.md +15 -10
  13. data/docs/internals/web-push.md +11 -0
  14. data/docs/internals/working-set.md +238 -6
  15. data/docs/mcp-server.md +5 -1
  16. data/docs/memory.md +2 -1
  17. data/docs/plugins.md +6 -6
  18. data/docs/scheduling.md +14 -0
  19. data/docs/sessions.md +1 -1
  20. data/docs/thin-clients.md +29 -10
  21. data/lib/samagotchi/bridge_client.rb +12 -4
  22. data/lib/samagotchi/bundle_command/check.rb +20 -2
  23. data/lib/samagotchi/bundle_manifest.rb +5 -1
  24. data/lib/samagotchi/bundles/mcp/http_client.rb +79 -54
  25. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  26. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  27. data/lib/samagotchi/bundles/system/self_map.md +7 -2
  28. data/lib/samagotchi/engine/session.rb +14 -6
  29. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  30. data/lib/samagotchi/mcp_server/http.rb +3 -3
  31. data/lib/samagotchi/mcp_server/protocol.rb +23 -4
  32. data/lib/samagotchi/mcp_server/stdio.rb +1 -0
  33. data/lib/samagotchi/mcp_server/tools.rb +2 -1
  34. data/lib/samagotchi/model_notes.rb +34 -12
  35. data/lib/samagotchi/prompt_files.rb +11 -4
  36. data/lib/samagotchi/prompt_layout.rb +88 -0
  37. data/lib/samagotchi/prompt_part.rb +82 -20
  38. data/lib/samagotchi/reply_wait.rb +6 -3
  39. data/lib/samagotchi/schedule_command.rb +18 -4
  40. data/lib/samagotchi/schedules.rb +40 -8
  41. data/lib/samagotchi/session_access/ask.rb +53 -12
  42. data/lib/samagotchi/session_access/exchange.rb +5 -2
  43. data/lib/samagotchi/session_access/local.rb +11 -2
  44. data/lib/samagotchi/session_inbox.rb +15 -0
  45. data/lib/samagotchi/session_manager/delivery.rb +8 -4
  46. data/lib/samagotchi/system_prompt.rb +196 -161
  47. data/lib/samagotchi/tools/memory.rb +11 -3
  48. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  49. data/lib/samagotchi/version.rb +1 -1
  50. data/lib/samagotchi/web/app.rb +1 -2
  51. data/lib/samagotchi/web/ask_routes.rb +89 -19
  52. data/lib/samagotchi/web/mcp_route.rb +7 -4
  53. data/lib/samagotchi/web/public/delete_sheet.js +20 -18
  54. data/lib/samagotchi/web/public/removal_sheet_model.js +3 -4
  55. data/lib/samagotchi/web/public/running_tasks.js +0 -16
  56. data/lib/samagotchi/web/public/session_actions.js +0 -9
  57. data/lib/samagotchi/web/public/working_set_view.js +167 -21
  58. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  59. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  60. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  61. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  62. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  63. data/lib/samagotchi/web/push/notifier.rb +33 -6
  64. data/lib/samagotchi/web/server.rb +1 -1
  65. data/lib/samagotchi/web/session_hub.rb +26 -4
  66. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  67. data/lib/samagotchi/worker_link.rb +2 -2
  68. data/lib/samagotchi/working_set.rb +162 -90
  69. data/lib/samagotchi/working_set_locator.rb +221 -0
  70. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  71. data/lib/samagotchi/working_set_part.rb +281 -0
  72. metadata +6 -1
@@ -17,6 +17,7 @@ require_relative "thinking"
17
17
  require_relative "prompt_files"
18
18
  require_relative "plugin/prompt_sections"
19
19
  require_relative "prompt_part"
20
+ require_relative "prompt_layout"
20
21
  require "json"
21
22
 
22
23
  module Samagotchi
@@ -30,6 +31,13 @@ module Samagotchi
30
31
  # What changes during a session (the profile after a model switch, the
31
32
  # tools a plugin replaces, the attached session, the thinking level) is
32
33
  # read at build time through the lookups; the memory lists are fixed.
34
+ #
35
+ # Each builder returns its Section with its Items (a memory, a file, a
36
+ # plugin's section, an index: chi's lead before it and its own text),
37
+ # recorded where it renders them; the prompt_parts derive from the items
38
+ # with each one's place in the prompt (PromptLayout), so the saved head
39
+ # (messages[0]) can be sliced back into them (docs/internals/working-set.md,
40
+ # Prompt parts as sent). #built_for answers the whole Built.
33
41
  class SystemPrompt
34
42
  # The model a session runs on, as the prompt names it: the resolved
35
43
  # ref, its host ("name, host:port" or url), the memory overlay key, and
@@ -100,16 +108,49 @@ module Samagotchi
100
108
  #
101
109
  # parts: the Sections the prompt is joined from (stable ones, then the
102
110
  # 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).
111
+ # prompt_parts: the same as sizes, one PromptPart per Item, the tools
112
+ # part first (#prompt_parts).
105
113
  Built = Data.define(:prompt, :memory_index, :notes, :files, :sections, :stable_length, :surface, :memory_names, :parts,
106
114
  :prompt_parts, :prompt_memories)
107
115
 
116
+ # One item of a section, recorded by the builder where it renders it: a
117
+ # memory (identity, a note, a preload), a file, a plugin's section, an
118
+ # index, or a whole one-item section (base, kit, the volatile lines).
119
+ # The prompt holds it as lead + text: lead is what chi adds before the
120
+ # item's own text (the "System identity …:" line, a note's "## name"
121
+ # and the first note of a scope its heading, a file's header line); ""
122
+ # for a section that is one item. label, ref, scope: the PromptPart's.
123
+ # chars: what the item's part is charged when it is not its section's
124
+ # first (the first part takes the rest of the section's text: its joins
125
+ # and, for notes, the scope headings; PromptPart's rule). params: how
126
+ # to fetch it again (PromptPart#params), nil for what chi makes itself.
127
+ Item = Data.define(:kind, :label, :ref, :scope, :lead, :text, :chars, :params) do
128
+ def initialize(kind:, label:, text:, ref: nil, scope: nil, lead: "", chars: nil, params: nil)
129
+ super(kind: kind, label: label, ref: ref, scope: scope, lead: lead, text: text, chars: chars || (lead.length + text.length),
130
+ params: params)
131
+ end
132
+
133
+ # The item as the prompt holds it.
134
+ def sent = "#{lead}#{text}"
135
+ end
136
+
108
137
  # One part of the prompt: its kind (KINDS), what it was made from (the
109
138
  # memory names of identity and preloads, the files of agents and
110
139
  # 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)
140
+ # elsewhere), its text, as the prompt holds it, and its Items, whose
141
+ # sent texts joined by +join+ are that text.
142
+ Section = Data.define(:kind, :ref, :text, :items, :join) do
143
+ # A section of +items+ (Item), its text their sent texts joined.
144
+ def self.of(kind, items, ref: nil, join: "\n\n")
145
+ items = items.freeze
146
+ new(kind: kind, ref: ref, text: items.map(&:sent).join(join), items: items, join: join)
147
+ end
148
+
149
+ # A section that is one item: +text+ whole, no lead.
150
+ def self.whole(kind, text, label:)
151
+ of(kind, [Item.new(kind: kind, label: label, text: text)])
152
+ end
153
+ end
113
154
 
114
155
  KINDS = %i[base identity notes preloads agents appended kit plugins indexes participants model location session].freeze
115
156
 
@@ -131,14 +172,26 @@ module Samagotchi
131
172
  # @param layers [Array<Symbol>] the turn's LLM context layers: the
132
173
  # native prompt declares the tools they add (Tools::ToolSurface#declared)
133
174
  def build(chat: false, thinking: nil, layers: [])
175
+ built_for(chat: chat, thinking: thinking, layers: layers).prompt
176
+ end
177
+
178
+ # The Built #build returns the prompt of, so a caller reads the prompt,
179
+ # its parts, notes and index from one object (Engine#system_prompt): a
180
+ # #reset! on another thread may land right after, and the readers
181
+ # below (#prompt_parts…) would then answer nothing.
182
+ # @param record [Boolean] whether this build becomes the prompt's last-build record
183
+ # @return [Built]
184
+ def built_for(chat: false, thinking: nil, layers: [], record: true)
134
185
  key = [chat, thinking, layers]
135
186
  cache = @cache
136
187
  built = cache[key] || (cache[key] = build_prompt(chat: chat, thinking: thinking, layers: layers))
137
188
  @memory_index = built.memory_index
138
- @last = built
139
- @last_prompt_memory_names = built.memory_names
140
- @last_prompt_memories = built.prompt_memories
141
- built.prompt
189
+ if record
190
+ @last = built
191
+ @last_prompt_memory_names = built.memory_names
192
+ @last_prompt_memories = built.prompt_memories
193
+ end
194
+ built
142
195
  end
143
196
 
144
197
  # The memory indexes the prompt #build returned last holds, per scope
@@ -224,44 +277,30 @@ module Samagotchi
224
277
 
225
278
  private
226
279
 
227
- # One #build's work: the prompt and what it read, in a Built. The
228
- # @section_* and @measured_* scratch is this build's (the turn thread's)
229
- # alone: #reset! never touches it.
280
+ # One #build's work: the prompt and what it read, in a Built. Each
281
+ # builder returns its Section with its Items; nothing is kept between
282
+ # builds (#reset! never touches a build in flight).
230
283
  def build_prompt(chat:, thinking:, layers:)
231
- @section_identity_memory_name = nil
232
- @section_activated_memory_names = []
233
- @section_notes = nil
234
- @section_files = []
235
- @section_plugins = []
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 = {}
243
284
  surface = tool_surface(layers)
244
- prompt = system_prompt_with_index(assist_system_prompt(chat: chat, surface: surface),
245
- chat: chat, thinking: thinking, surface: surface)
285
+ composed = compose(assist_system_prompt(chat: chat, surface: surface), chat: chat, thinking: thinking, surface: surface)
286
+ sections = composed.sections
246
287
  prompt_parts = Degrade.call(:prompt, "prompt_parts_failed", fallback: []) do
247
- prompt_parts_for(@section_parts, chat: chat, surface: surface)
288
+ prompt_parts_for(sections, prompt: composed.prompt, chat: chat, surface: surface)
248
289
  end
249
- prompt_memories = prompt_memories_for(@section_parts)
250
- Built.new(prompt: prompt, memory_index: @measured_index, notes: @section_notes || [],
251
- files: @section_files.freeze, sections: @section_plugins.freeze, stable_length: @measured_stable_length,
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)
290
+ by_kind = sections.to_h { |section| [section.kind, section] }
291
+ files = %i[agents appended].flat_map { |kind| Array(by_kind[kind]&.ref) }
292
+ memory_names = [by_kind[:identity]&.ref, *Array(by_kind[:preloads]&.ref)].compact.uniq
293
+ Built.new(prompt: composed.prompt, memory_index: composed.memory_index, notes: Array(by_kind[:notes]&.ref),
294
+ files: files.freeze, sections: Array(by_kind[:plugins]&.ref).freeze, stable_length: composed.stable_length,
295
+ surface: surface, memory_names: memory_names.freeze, parts: sections.freeze, prompt_parts: prompt_parts.freeze,
296
+ prompt_memories: prompt_memories_for(sections))
254
297
  end
255
298
 
256
299
  def prompt_memories_for(sections)
257
300
  sections.flat_map do |section|
258
301
  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
- []
302
+ when :identity, :preloads then section.items.map { |item| [item.ref, item.scope] }
303
+ else []
265
304
  end
266
305
  end.map(&:freeze).uniq.freeze
267
306
  end
@@ -271,65 +310,46 @@ module Samagotchi
271
310
  LABELS = { base: "base prompt", kit: "toolkit prompt", participants: "participants", model: "model",
272
311
  location: "location", session: "session" }.freeze
273
312
 
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]
313
+ # The PromptParts of +sections+ (a build's, whose +prompt+ they are),
314
+ # the tools part first: one per Item, with its place (PromptLayout). A
315
+ # multi-item section's headings and joins go into its first part's
316
+ # chars, so the parts sum to the section's text.
317
+ def prompt_parts_for(sections, prompt:, chat:, surface:)
318
+ declarations = chat ? nil : tool_declarations(surface)
319
+ layout = PromptLayout.new(prompt, sections, declarations: declarations, tail: !chat && gemma_tail_declarations?)
320
+ tools_chars = chat ? JSON.generate(surface.schemas).length : declarations.length
321
+ parts = sections.flat_map { |section| section_parts(section, layout) }
322
+ if layout.tools_in_base?
281
323
  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
324
+ parts[base] = parts[base].with(chars: parts[base].chars - tools_chars, tokens: PromptPart.tokens_for(parts[base].chars - tools_chars)) if base
325
+ end
326
+ tools = PromptPart.build(kind: :tools, label: "#{surface.declared_names.size} declared", chars: tools_chars,
327
+ params: { "tools" => tool_sizes(surface, chat: chat) }, **layout.tools_place)
328
+ [tools, *parts]
329
+ end
330
+
331
+ # The declared tools' names and sizes: chat, each schema as the tools
332
+ # field sends it (their sum is not the part's chars: the field's own
333
+ # brackets and commas); native, each declaration as rendered, except
334
+ # Qwen's one JSON list, which gives no per-tool length: names only.
335
+ def tool_sizes(surface, chat:)
336
+ per_tool = !chat && profile.name != "qwen36" ? ToolDeclarations.native_schemas(surface) : nil
337
+ surface.declared.each_with_index.map do |entry, index|
338
+ chars = chat ? JSON.generate(entry.schema).length : per_tool && ToolDeclarations.gemma_declaration(per_tool[index]).length
339
+ chars ? { "name" => entry.name, "chars" => chars } : { "name" => entry.name }
283
340
  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
341
  end
296
342
 
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
-
343
+ def section_parts(section, layout)
344
+ items = section.items
301
345
  # 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)
346
+ rest = items.drop(1).sum(&:chars)
347
+ items.each_with_index.map do |item, index|
348
+ PromptPart.build(kind: section.kind, label: item.label, ref: item.ref, scope: item.scope,
349
+ chars: index.zero? ? section.text.length - rest : item.chars, params: item.params, **layout.place(item))
306
350
  end
307
351
  end
308
352
 
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
353
  # A file part's label: its path under the work tree +top+ (AGENTS.md,
334
354
  # docs/rules.md), else with ~ for the home directory.
335
355
  def file_label(path, top)
@@ -338,14 +358,6 @@ module Samagotchi
338
358
  path.delete_prefix("#{top}/")
339
359
  end
340
360
 
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]] }
347
- end
348
-
349
361
  # The session's tools as a build under +layers+ declares them, read
350
362
  # from the Registry now (one per build: the declarations, the
351
363
  # not-loaded line and the kit's text agree).
@@ -395,7 +407,7 @@ module Samagotchi
395
407
  tools = if gemma_tail_declarations?
396
408
  "Your tools are declared at the end of this system prompt."
397
409
  else
398
- "You have access to the following tools:\n\n#{tool_declarations(surface)}\n"
410
+ "#{PromptLayout::TOOLS_LEAD}#{tool_declarations(surface)}\n"
399
411
  end
400
412
 
401
413
  <<~SYS
@@ -487,60 +499,55 @@ module Samagotchi
487
499
  # and the session close the prompt (Gemma's tool declarations still
488
500
  # follow them).
489
501
  def system_prompt_with_index(base, chat: false, thinking: nil, surface: tool_surface([]))
502
+ compose(base, chat: chat, thinking: thinking, surface: surface).prompt
503
+ end
504
+
505
+ # #system_prompt_with_index's prompt with what its build measured: the
506
+ # Sections in prompt order, the indexes' sizes and the stable length.
507
+ Composed = Data.define(:prompt, :sections, :memory_index, :stable_length)
508
+
509
+ def compose(base, chat:, thinking:, surface:)
490
510
  thinking_token = chat ? "" : Thinking.native(thinking || turn_thinking, profile).system_token
491
511
  indexes = { project: read_memory_index("project"), system: read_memory_index("system") }
492
- @measured_index = measure_indexes(indexes)
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.
512
+ memory_index = measure_indexes(indexes)
513
+ # Built eagerly and in this order (the warnings, the activated names).
495
514
  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
515
  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)
516
+ Section.whole(:base, base_text, label: LABELS[:base]),
517
+ system_identity_section,
518
+ model_notes_section,
519
+ explicit_memory_section,
520
+ project_specific_description,
521
+ appended_section,
522
+ whole_section(:kit) { kit_prompt_section(surface) },
523
+ plugin_prompt_section,
524
+ Section.of(:indexes, %i[project system].map { |scope| index_item(indexes, scope) }, ref: %i[project system])
508
525
  ].compact
509
526
  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
513
- return with_tail_declarations(stable_text, chat: chat, surface: surface) if volatile.empty?
527
+ volatile = [whole_section(:participants) { participants_section }, whole_section(:model) { current_model },
528
+ whole_section(:location) { project_location }, whole_section(:session) { current_session }].compact
529
+ sections = (stable + volatile).freeze
530
+ if volatile.empty?
531
+ return Composed.new(prompt: with_tail_declarations(stable_text, chat: chat, surface: surface), sections: sections,
532
+ memory_index: memory_index, stable_length: nil)
533
+ end
514
534
 
515
535
  prompt = "#{stable_text}\n#{volatile.map(&:text).join("\n")}"
516
- @measured_stable_length = stable_text.length + 1 if chat
517
- with_tail_declarations(prompt, chat: chat, surface: surface)
536
+ Composed.new(prompt: with_tail_declarations(prompt, chat: chat, surface: surface), sections: sections,
537
+ memory_index: memory_index, stable_length: chat ? stable_text.length + 1 : nil)
518
538
  end
519
539
 
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]}"
540
+ # One scope's block of the indexes section: "Project memories:" and the text.
541
+ def index_item(indexes, scope)
542
+ Item.new(kind: :indexes, label: "#{scope} memory index", ref: scope.to_s, lead: "#{scope.to_s.capitalize} memories:\n",
543
+ text: indexes[scope].to_s)
523
544
  end
524
545
 
525
- # A Section of +kind+ with what the block (a builder) returns, nil when
546
+ # A one-item Section of +kind+ with what the block returns, nil when
526
547
  # 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, &)
548
+ def whole_section(kind)
529
549
  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
550
+ text.nil? ? nil : Section.whole(kind, text, label: LABELS.fetch(kind, kind.to_s))
544
551
  end
545
552
 
546
553
  # The tools the session's toolkit leaves out, named once right after the
@@ -587,8 +594,13 @@ module Samagotchi
587
594
  def plugin_prompt_section
588
595
  Degrade.call(:prompt, "plugin_section_failed") do
589
596
  built = Array(@sections_lookup.call)
590
- @section_plugins = built
591
- Plugin::PromptSections.text(built)
597
+ next nil if Plugin::PromptSections.text(built).nil?
598
+
599
+ items = built.map do |one|
600
+ Item.new(kind: :plugins, label: "#{one.bundle}: #{one.name}", ref: "#{one.bundle}/#{one.name}",
601
+ lead: one.prompt_text.delete_suffix(one.text.to_s), text: one.text.to_s)
602
+ end
603
+ Section.of(:plugins, items, ref: built)
592
604
  end
593
605
  end
594
606
 
@@ -612,8 +624,9 @@ module Samagotchi
612
624
  next if body.start_with?("Error:")
613
625
  next if body.strip.empty?
614
626
 
615
- @section_identity_memory_name = name
616
- return "System identity (auto-loaded, scope=system):\n#{body}"
627
+ item = Item.new(kind: :identity, label: name, ref: name, scope: "system", params: memory_params("system"),
628
+ lead: "System identity (auto-loaded, scope=system):\n", text: body.to_s)
629
+ return Section.of(:identity, [item], ref: name)
617
630
  end
618
631
  nil
619
632
  end
@@ -624,20 +637,39 @@ module Samagotchi
624
637
  # line left out. nil without any, so the prompt stays as it was.
625
638
  def model_notes_section
626
639
  Degrade.call(:prompt, "model_notes_failed") do
627
- @section_notes = []
628
640
  notes = Array(@model_notes_lookup.call)
629
641
  return nil if notes.empty?
630
642
 
631
643
  ref = @model_lookup.call&.ref
632
- notes.group_by(&:scope).map do |scope, list|
644
+ # In the text's order: a heading per scope, the scope's notes under it.
645
+ items = notes.group_by(&:scope).flat_map do |scope, list|
633
646
  heading = ref.to_s.empty? ? "Model notes (scope=#{scope}):" : "Model notes (for #{ref}, scope=#{scope}):"
634
- [heading, *list.map { |note| "## #{note.name}\n#{note.body}" }].join("\n\n")
635
- end.join("\n\n").tap { @section_notes = notes }
647
+ list.each_with_index.map do |note, index|
648
+ own = "## #{note.name}\n"
649
+ Item.new(kind: :notes, label: note.name, ref: note.name, scope: note.scope, text: note.body.to_s,
650
+ lead: index.zero? ? "#{heading}\n\n#{own}" : own, chars: own.length + note.body.to_s.length,
651
+ params: memory_params(note.scope))
652
+ end
653
+ end
654
+ Section.of(:notes, items, ref: notes)
636
655
  end
637
656
  end
638
657
 
639
658
  # ── Memory helpers ─────────────────────────────────────────────────────────
640
659
 
660
+ # How a prompt memory is fetched again (PromptPart#params): the scope
661
+ # asked for (nil: a bare name, project then system), the overlay keys
662
+ # and both scopes' folders as this build read them. A note's
663
+ # requested_scope is its own scope.
664
+ def memory_params(scope)
665
+ keys = overlay_keys
666
+ Degrade.call(:prompt, "memory_params_failed") do
667
+ { "requested_scope" => scope, "model_key" => keys[:model_key], "fallback_model_key" => keys[:fallback_model_key],
668
+ "project_dir" => File.expand_path(Tools::MemoryRead.memories_dir("project")),
669
+ "system_dir" => File.expand_path(Tools::MemoryRead.memories_dir("system")) }
670
+ end
671
+ end
672
+
641
673
  # The session model's overlay keys, so the prompt's own memory bodies
642
674
  # (identity, preloads) get `<name>.<key>.md` as memory_read gives it.
643
675
  def overlay_keys
@@ -711,7 +743,7 @@ module Samagotchi
711
743
  def explicit_memory_section
712
744
  return nil if @requested_memories.empty?
713
745
 
714
- entries = []
746
+ items = []
715
747
  @activated_memory_names ||= []
716
748
  @requested_memories.each do |raw|
717
749
  names = raw.split(",").map(&:strip).reject(&:empty?)
@@ -727,17 +759,16 @@ module Samagotchi
727
759
  # status line. The memory-body injection itself stays here — the
728
760
  # SystemPrompt is the single source of truth for the system prompt.
729
761
  @activated_memory_names << actual_name
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
762
+ items << Item.new(kind: :preloads, label: actual_name, ref: actual_name, scope: scope || answered_scope(body, actual_name),
763
+ params: memory_params(scope),
764
+ lead: "this memory is required by the user in the current context: memory name: #{actual_name}\n",
765
+ text: body.to_s)
735
766
  end
736
767
  end
737
768
 
738
- return nil if entries.empty?
769
+ return nil if items.empty?
739
770
 
740
- entries.join("\n\n")
771
+ Section.of(:preloads, items, ref: items.map(&:ref))
741
772
  end
742
773
 
743
774
  # The scope whose file answered a bare preload's read (memory_read
@@ -773,9 +804,8 @@ module Samagotchi
773
804
  sections = PromptFiles.agents_sections(Dir.pwd)
774
805
  return nil if sections.empty?
775
806
 
776
- @section_files&.concat(sections.map(&:path))
777
- @section_file_chars&.concat(sections.map { |section| section.text.length })
778
- sections.map(&:text).join("\n\n")
807
+ top = MemoryPaths.work_tree_root(Dir.pwd)
808
+ Section.of(:agents, sections.map { |section| file_item(:agents, section, top) }, ref: sections.map(&:path))
779
809
  end
780
810
  end
781
811
 
@@ -789,7 +819,7 @@ module Samagotchi
789
819
  cwd = Dir.pwd
790
820
  top = MemoryPaths.work_tree_root(cwd)
791
821
  seen = Set.new((skip_agent_description? ? [] : PromptFiles.agents_paths(cwd)).map { |path| canonical_path(path) })
792
- sections = []
822
+ items = []
793
823
  appended_candidates(cwd).each do |path, source|
794
824
  next unless seen.add?(canonical_path(path))
795
825
 
@@ -800,14 +830,19 @@ module Samagotchi
800
830
  text = PromptFiles.section(path, "Appended from #{PromptFiles.display_path(path, top: top)}:")
801
831
  next unless text
802
832
 
803
- @section_files&.push(path)
804
- @section_file_chars&.push(text.length)
805
- sections << text
833
+ items << file_item(:appended, PromptFiles::Section.new(path: path, text: text), top)
806
834
  end
807
- sections.empty? ? nil : sections.join("\n\n")
835
+ items.empty? ? nil : Section.of(:appended, items, ref: items.map(&:ref))
808
836
  end
809
837
  end
810
838
 
839
+ # A file's Item: its PromptFiles::Section, the header line its lead.
840
+ def file_item(kind, section, top)
841
+ lead, text = section.text.split("\n", 2)
842
+ Item.new(kind: kind, label: file_label(section.path, top), ref: section.path, lead: "#{lead}\n", text: text.to_s,
843
+ params: { "path" => section.path })
844
+ end
845
+
811
846
  # [absolute path, "config" | "cli"], in prompt order.
812
847
  def appended_candidates(cwd)
813
848
  @config_appended.map { |entry| [File.expand_path(entry, cwd), "config"] } +
@@ -105,6 +105,16 @@ module Samagotchi
105
105
  end
106
106
  private_class_method :prompt_memory_name
107
107
 
108
+ # The text a Resolved entry reads as: its file, its overlay appended
109
+ # (#append_overlay). memory_read's body of one name and the prompt's
110
+ # identity and preloads (SystemPrompt, through #call); the working
111
+ # set's re-fetch of a prompt part resolves with the saved keys and
112
+ # composes here too, so the two never differ. +read+: the file reader.
113
+ def self.compose(resolved, read: ->(path) { File.read(path, encoding: "UTF-8") })
114
+ body = read.call(resolved.path)
115
+ resolved.overlay_path ? append_overlay(body, read.call(resolved.overlay_path), resolved.overlay_key) : body
116
+ end
117
+
108
118
  def self.overlay_prefix(key) = "#{SEPARATOR}Model-specific guidance (#{key}):\n"
109
119
 
110
120
  def self.append_overlay(body, overlay_text, key) = "#{body}#{overlay_prefix(key)}#{overlay_text}"
@@ -166,9 +176,7 @@ module Samagotchi
166
176
  next
167
177
  end
168
178
 
169
- body = File.read(resolved.path, encoding: "UTF-8")
170
- body = append_overlay(body, File.read(resolved.overlay_path, encoding: "UTF-8"), resolved.overlay_key) if resolved.overlay_path
171
- results << body
179
+ results << compose(resolved)
172
180
  reads[name] = { path: resolved.path, overlay_path: resolved.overlay_path, requested_scope: scope,
173
181
  model_key: model_key, fallback_model_key: fallback_model_key, project_dir: project_dir }
174
182
  end
@@ -19,8 +19,8 @@ module Samagotchi
19
19
  # @param turn_state [TurnState] whether steers are carried to the next turn
20
20
  # @param model_settings [SessionModelSettings] the effective model now, the next turn's LLM context strategy
21
21
  # @param reminder_queue [ReminderQueue] whether a reminder is due
22
- # @param system_prompt [#call] (model) the system prompt (Engine#system_prompt): called last, only
23
- # once every check passed, as building it has side effects (the memory index metric, the prompt notes)
22
+ # @param system_prompt [#call] (model) the system prompt (Engine#system_prompt with record: false: a
23
+ # warm-up records no parts, notes or memory index): called last, only once every check passed
24
24
  def initialize(prompt_warmup:, kernel:, turn_state:, model_settings:, reminder_queue:, system_prompt:)
25
25
  @prompt_warmup = prompt_warmup
26
26
  @kernel = kernel
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.183.0"
4
+ VERSION = "0.184.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -342,9 +342,8 @@ module Samagotchi
342
342
  ["POST", %r{\A/api/sessions/([^/]+)/context\z}, :handle_context_add, :owner, :session],
343
343
  ["POST", %r{\A/api/sessions/([^/]+)/context/([^/]+)/push\z}, :handle_context_push, :owner, :session],
344
344
  ["DELETE", %r{\A/api/sessions/([^/]+)/context/([^/]+)\z}, :handle_context_delete, :owner, :session],
345
- ["GET", %r{\A/api/sessions/([^/]+)/working_set\z}, :handle_working_set, :participant, :session],
345
+ *WorkingSetRoutes::ROUTES,
346
346
  ["GET", %r{\A/api/sessions/([^/]+)/prompt_history\z}, :handle_prompt_history, :participant, :session],
347
- ["GET", %r{\A/api/sessions/([^/]+)/working_set/item\z}, :handle_working_set_item, :owner, :session],
348
347
  ["GET", %r{\A/api/sessions/([^/]+)/participants\z}, :handle_participants_list, :owner, :session],
349
348
  ["POST", %r{\A/api/sessions/([^/]+)/participants\z}, :handle_participants_invite, :owner, :session],
350
349
  ["DELETE", %r{\A/api/sessions/([^/]+)/participants\z}, :handle_participants_revoke, :owner, :session],