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
@@ -33,6 +33,7 @@ import { api } from "./data.js";
33
33
  import { createLatest } from "./latest.js";
34
34
  import { diffTemplate } from "./diff_view.js";
35
35
  import { createPeek } from "./ws_peek.js";
36
+ import { createPartPeek, getWorkingSetPart } from "./ws_part_peek.js";
36
37
  import { setTimelineWayIn } from "./ws_way_in.js";
37
38
  import { cardTemplate } from "./ws_cards.js";
38
39
  import { bandBox, countsText, eventTag, fileStrip, itemPath, linesText, timelineCards } from "./ws_timeline.js";
@@ -75,7 +76,7 @@ function itemName(item) {
75
76
  // (undrop; null: none); +renderMarkdown(text)+: a text's markdown HTML or
76
77
  // null (none: every text as its source).
77
78
  export function createWorkingSetPreview({ centerEl, session, state = () => ({}), getItem = getWorkingSetItem, sendLine = null,
78
- renderMarkdown = null, doc = document, win = window }) {
79
+ renderMarkdown = null, getPart = getWorkingSetPart, doc = document, win = window }) {
79
80
  let workingSet = null;
80
81
  // The open item ({kind, key}), its answer, the memory's now, the tab.
81
82
  let open = null;
@@ -91,9 +92,12 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
91
92
  // One cache for both places: HTML that came redraws the open one(s).
92
93
  const cache = renderMarkdown ? createRenderCache(renderMarkdown, () => {
93
94
  if (open && !el.hidden) draw();
94
- if (peek.any()) workingSet?.peekChanged();
95
+ if (peek.any() || peek.part.any()) workingSet?.peekChanged();
95
96
  }) : null;
96
97
  const peek = createPeek({ session, getItem, sigOf, onChange: () => workingSet?.peekChanged(), md: cache });
98
+ // The "From the start" rows' prompt peek (ws_part_peek.js), handed over on
99
+ // the peek: a view without it (an older cached one) ignores it.
100
+ peek.part = createPartPeek({ session, getPart, itemPeek: peek, md: cache, onChange: () => workingSet?.peekChanged() });
97
101
 
98
102
  const el = doc.createElement("section");
99
103
  el.className = "ws-reader";
@@ -355,6 +359,6 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
355
359
  },
356
360
  // The session forgotten (another one, the start page: session_view.js
357
361
  // forgetSession): closed, the stage no longer inert.
358
- reset() { close({ refocus: false }); peek.close(); },
362
+ reset() { close({ refocus: false }); peek.part.close(); peek.close(); },
359
363
  };
360
364
  }
@@ -122,12 +122,14 @@ export function heldTwiceNote(row, turnItem) {
122
122
  // The head view's sections for +set+ ({items, muted}: the session's set,
123
123
  // overlaid), or null without parts (today's list). +parts+: the session's
124
124
  // prompt_parts; +ctxTokens+: the context's tokens now (null: unknown);
125
- // +turns+: how many turns the session has (the conversation row's).
125
+ // +turns+: how many turns the session has (the conversation row's);
126
+ // +states+: chi web's GET's parts ([{key, state}]: the parts whose source
127
+ // changed since chi was sent it, WorkingSetPart.states; none: none stale).
126
128
  // @return [{key, title, meta, tokens, rows?, inner?, twice?}] read, talk?, start
127
129
  // (start's +twice+: how many of its rows are held twice)
128
- export function headSections(set, budget, { parts = null, ctxTokens = null, turns = 0, inTurn = false } = {}) {
130
+ export function headSections(set, budget, { parts = null, ctxTokens = null, turns = 0, inTurn = false, states = null } = {}) {
129
131
  if (!Array.isArray(parts) || !parts.length) return null;
130
- const { rows, used, partNames } = startRows(set, parts);
132
+ const { rows, used, partNames } = startRows(set, parts, states);
131
133
  const partsTokens = sum(rows, (r) => r.partTokens);
132
134
  // A preloaded memory never read is the prompt's, never "read in this
133
135
  // session": one no part names (a ref-less preloads / notes part, whose
@@ -176,8 +178,12 @@ function normalized(items, used, partNames) {
176
178
  }
177
179
 
178
180
  // The start section's rows for +parts+, the set's items they show (+used+,
179
- // by identity) and the memory names the parts claim (+partNames+).
180
- function startRows(set, parts) {
181
+ // by identity) and the memory names the parts claim (+partNames+). +states+
182
+ // (headSections'): each row's partStates beside its partKeys ("stale" or
183
+ // null), and partStale when one of them is.
184
+ function startRows(set, parts, states = null) {
185
+ const stateOf = new Map((Array.isArray(states) ? states : []).filter((s) => s && typeof s.key === "string").map((s) => [s.key, s.state]));
186
+ const partState = (key) => (stateOf.get(key) === "stale" ? "stale" : null);
181
187
  // The set's items a start row shows, by identity: a key can be two
182
188
  // memories' (a project x read, a system x in the prompt).
183
189
  const used = new Set();
@@ -188,14 +194,32 @@ function startRows(set, parts) {
188
194
  // Names a part claims: a set item of that name no part matched (another
189
195
  // scope's) reads as read, not as the prompt's.
190
196
  const partNames = new Set();
197
+ // Each part's key for chi web's part route (PromptPart.keys' twin,
198
+ // spec/shared/prompt_part_keys.json): kind:ref (the label without one),
199
+ // @scope, #n for the nth repeat. A row keeps the keys of the parts it
200
+ // stands for (partKeys: a note also preloaded has two) and their tokens
201
+ // (partSizes, the peek's tab words).
202
+ const seenKeys = new Map();
203
+ const keyOf = (part) => {
204
+ let key = `${part.kind}:${part.ref ?? part.label}`;
205
+ if (part.scope) key = `${key}@${part.scope}`;
206
+ const n = (seenKeys.get(key) || 0) + 1;
207
+ seenKeys.set(key, n);
208
+ return n === 1 ? key : `${key}#${n}`;
209
+ };
191
210
  for (const part of parts) {
192
211
  if (!part || !part.kind) continue;
212
+ const partKey = keyOf(part);
193
213
  if (MEMORY_PARTS.includes(part.kind) && part.ref) {
194
214
  const name = memoryName(part.ref);
195
215
  partNames.add(name);
196
216
  const again = (seenMemory.get(name) || []).find((r) => sameScope(r.partScope, part.scope));
197
217
  // A memory in two parts (a note also preloaded): one row, both sizes.
198
218
  if (again) {
219
+ again.partKeys.push(partKey);
220
+ again.partStates.push(partState(partKey));
221
+ again.partStale = again.partStale || !!partState(partKey);
222
+ again.partSizes.push(Number.isFinite(part.tokens) ? part.tokens : 0);
199
223
  again.partTokens += Number.isFinite(part.tokens) ? part.tokens : 0;
200
224
  if (!again.partScope && part.scope) again.partScope = part.scope;
201
225
  continue;
@@ -206,7 +230,10 @@ function startRows(set, parts) {
206
230
  // item holds that name (never two rows of one key).
207
231
  const taken = keys.has(`memory:${name}`) || memories.some((m) => memoryName(m.key) === name && !matches.includes(m));
208
232
  const own = !matches.length && taken ? `${name}@${part.scope || part.kind}` : name;
209
- const row = memoryRow(part, name, matches, own, taken && !!part.scope);
233
+ const row = {
234
+ ...memoryRow(part, name, matches, own, taken && !!part.scope), partKeys: [partKey], partStates: [partState(partKey)], partStale: !!partState(partKey),
235
+ partSizes: [Number.isFinite(part.tokens) ? part.tokens : 0],
236
+ };
210
237
  seenMemory.set(name, [...(seenMemory.get(name) || []), row]);
211
238
  keys.add(itemKey(row));
212
239
  rows.push(row);
@@ -215,7 +242,10 @@ function startRows(set, parts) {
215
242
  let key = `${part.kind}:${part.ref ?? part.label ?? ""}`;
216
243
  for (let n = 2; keys.has(`part:${key}`); n += 1) key = `${part.kind}:${part.ref ?? part.label ?? ""}#${n}`;
217
244
  keys.add(`part:${key}`);
218
- rows.push(partRow(part, key));
245
+ rows.push({
246
+ ...partRow(part, key), partKeys: [partKey], partStates: [partState(partKey)], partStale: !!partState(partKey),
247
+ partSizes: [Number.isFinite(part.tokens) ? part.tokens : 0],
248
+ });
219
249
  }
220
250
  return { rows, used, partNames };
221
251
  }
@@ -47,8 +47,13 @@ module Samagotchi
47
47
  SHOW_TTL = 12 * 3600
48
48
  # A failed, done or verdict turn: stale soon, no need to wake the phone.
49
49
  EVENT_TTL = 600
50
- # A newly available chi is useful for a day while the phone is away.
50
+ # A newly available chi is useful for a day while the phone is away; so
51
+ # is a schedule chi web's tick turned off.
51
52
  UPDATE_TTL = 24 * 3600
53
+ # Shown even with a chi web page in front: the page has no word for it.
54
+ UNSEEN_ON_PAGE = %w[schedule].freeze
55
+ # A disabled schedule's body: its last reason, clipped.
56
+ REASON_MAX = 120
52
57
  # The kinds of AutoUpdate's notices: [key kind, title, body] from the version and the notice's notes.
53
58
  AUTO_NOTICES = {
54
59
  "installed" => lambda do |version, notes|
@@ -231,6 +236,8 @@ module Samagotchi
231
236
  notice_update(event)
232
237
  when "chi_notice"
233
238
  notice_auto_update(event)
239
+ when "schedule_disabled"
240
+ notice_schedule_disabled(event)
234
241
  end
235
242
  end
236
243
 
@@ -256,13 +263,33 @@ module Samagotchi
256
263
  enqueue_update("chi:#{kind}:#{version}", title, body) if kind
257
264
  end
258
265
 
266
+ # A recurring schedule chi web's tick turned off (SessionHub#publish_disabled).
267
+ # The key's +at+ (the tick's time) lets a later disable of the same
268
+ # schedule notify again; its chi: prefix keeps it out of WAITING_TAG.
269
+ def notice_schedule_disabled(event)
270
+ data = event.data
271
+ id = data[:id]
272
+ return unless id.is_a?(String) && !id.empty?
273
+
274
+ short = id[0, 8]
275
+ name = data[:title].to_s.strip
276
+ title = Attention.clip("Schedule disabled: #{name.empty? ? short : name}", Attention::TITLE_MAX)
277
+ count = data[:count].to_i
278
+ reason = Attention.clip(data[:reason].to_s.strip, REASON_MAX)
279
+ body = "#{data[:kind]} #{count} #{count == 1 ? "time" : "times"}#{": #{reason}" unless reason.empty?}\n" \
280
+ "chi schedule enable #{short}"
281
+ summary = @by_id[data[:session_id]]
282
+ enqueue_update("chi:schedule_disabled:#{id}:#{data[:at]}", title, body,
283
+ reason: "schedule", url: summary ? Notifier.session_url(summary) : "/")
284
+ end
285
+
259
286
  # Once per key in this process (AutoUpdate keeps its own record across restarts).
260
- def enqueue_update(key, title, body)
287
+ def enqueue_update(key, title, body, reason: "update", url: "/")
261
288
  return if @updates_seen[key]
262
289
 
263
290
  @updates_seen[key] = true
264
- attention = Attention::Event.new(reason: "update", session_id: nil, key: key, hold: nil)
265
- @queue << Show.new(attention: attention, title: title, body: body, at: @now.call, url: "/")
291
+ attention = Attention::Event.new(reason: reason, session_id: nil, key: key, hold: nil)
292
+ @queue << Show.new(attention: attention, title: title, body: body, at: @now.call, url: url)
266
293
  end
267
294
 
268
295
  # A blocked install (a checkout, Bundler, an unwritable gem dir) names its own command on the page.
@@ -354,7 +381,7 @@ module Samagotchi
354
381
  return if subs.empty?
355
382
 
356
383
  key = show.attention.key
357
- if @presence&.present?
384
+ if @presence&.present? && !UNSEEN_ON_PAGE.include?(show.attention.reason)
358
385
  Log.info(:web, "push_skipped", reason: "present", kind: show.attention.reason)
359
386
  return handled(key)
360
387
  end
@@ -410,7 +437,7 @@ module Samagotchi
410
437
  def deliver(subs, payload, show, final: false)
411
438
  reason = show.attention.reason
412
439
  waiting = Attention.waiting?(reason)
413
- ttl = if reason == "update"
440
+ ttl = if %w[update schedule].include?(reason)
414
441
  UPDATE_TTL
415
442
  else
416
443
  waiting ? SHOW_TTL : EVENT_TTL
@@ -515,7 +515,7 @@ module Samagotchi
515
515
  if push
516
516
  # The Notifier seeds from the hub's snapshot, which is empty before
517
517
  # a scan: one now, so what is already open never pushes.
518
- hub.scan
518
+ hub.scan(tick: false)
519
519
  notifier = Push::Notifier.new(store: push.store, client: push.client, origin: push.origin,
520
520
  presence: push.presence).start(hub)
521
521
  Samagotchi::Log.info(:web, "push", devices: push.store.for_origin(push.origin).size)
@@ -51,7 +51,9 @@ module Samagotchi
51
51
 
52
52
  # What a subscriber gets: `session` with {session: summary} for an
53
53
  # upsert, `session_gone` with {id:} for a removal, `chi` with
54
- # the #chi_state fields when chi version state changes. seq is monotonic per
54
+ # the #chi_state fields when chi version state changes, `chi_notice`
55
+ # (#publish_notice) and `schedule_disabled` (#publish_disabled) for
56
+ # the Push::Notifier. seq is monotonic per
55
57
  # hub, for the log's sake: there is no replay.
56
58
  Event = Struct.new(:type, :seq, :data, keyword_init: true)
57
59
 
@@ -150,7 +152,7 @@ module Samagotchi
150
152
  # +full_probe_interval+ it also probes every session's owner and
151
153
  # gives the retention sweep its chance (it used to run on
152
154
  # GET /api/sessions, which the page no longer calls).
153
- def scan
155
+ def scan(tick: true)
154
156
  full = @monitor.synchronize do
155
157
  full = full_probe_due?
156
158
  SessionContinue.repair_interrupted(state_dir: @state_dir)
@@ -163,7 +165,7 @@ module Samagotchi
163
165
  end
164
166
  sweep_if_due if full
165
167
  # Outside the projection's lock: a firing can wait for a recap.
166
- schedule_tick
168
+ schedule_tick if tick
167
169
  nil
168
170
  end
169
171
 
@@ -385,7 +387,10 @@ module Samagotchi
385
387
  end
386
388
 
387
389
  def run_schedule_tick
388
- Samagotchi::Schedules.new(state_dir: @state_dir).tick
390
+ schedules = Samagotchi::Schedules.new(state_dir: @state_dir)
391
+ now = Time.now
392
+ result = schedules.tick(now: now)
393
+ publish_disabled(result, now) if result.is_a?(Samagotchi::Schedules::Tick)
389
394
  rescue StandardError => e
390
395
  Log.warn(:web, "schedule_tick_failed", error: e.class.name, msg: e.message)
391
396
  ensure
@@ -395,6 +400,23 @@ module Samagotchi
395
400
  end
396
401
  end
397
402
 
403
+ # A recurring schedule this tick turned off (Schedules::Outcome#disabled):
404
+ # one `schedule_disabled` event each, for the Push::Notifier (the page has
405
+ # no listener), emitted the way #publish_notice does. +at+ is the tick's
406
+ # time; +session_id+ is the session the schedule acts on.
407
+ def publish_disabled(result, now)
408
+ result.outcomes.select(&:disabled).each do |outcome|
409
+ entry = outcome.entry
410
+ kind = outcome.status == "skipped" ? "skipped" : "failed"
411
+ data = { id: outcome.id, title: outcome.title, kind: kind,
412
+ count: kind == "skipped" ? entry.skips : entry.failures,
413
+ reason: outcome.detail, session_id: outcome.session_id, at: now.utc.iso8601 }
414
+ @monitor.synchronize { emit("schedule_disabled", data) }
415
+ rescue StandardError => e
416
+ Log.warn(:web, "schedule_disabled_failed", id: outcome.id, error: e.class.name, msg: e.message)
417
+ end
418
+ end
419
+
398
420
  # A change (the first look too, unless it finds nothing) is a `chi`
399
421
  # event: chi web's terminal line and the open tabs hear it.
400
422
  def check_installed
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "uri"
4
4
  require_relative "../working_set"
5
+ require_relative "../working_set_part"
5
6
  require_relative "../llm_context_view"
6
7
  require_relative "../session_setting"
7
8
  require_relative "../memory_paths"
@@ -18,6 +19,14 @@ module Samagotchi
18
19
  # llm_context summary names, its folder (+cwd+) and its +pins+.
19
20
  Source = Data.define(:messages, :strategy, :cwd, :pins)
20
21
 
22
+ # The routes (App::ROUTES takes them whole): the set, an item's
23
+ # timeline, a prompt part as sent. Before /api/sessions/:id.
24
+ ROUTES = [
25
+ ["GET", %r{\A/api/sessions/([^/]+)/working_set\z}, :handle_working_set, :participant, :session],
26
+ ["GET", %r{\A/api/sessions/([^/]+)/working_set/item\z}, :handle_working_set_item, :owner, :session],
27
+ ["GET", %r{\A/api/sessions/([^/]+)/working_set/part\z}, :handle_working_set_part, :owner, :session]
28
+ ].freeze
29
+
21
30
  private
22
31
 
23
32
  # GET /api/sessions/:id/working_set: the working set as the model has
@@ -33,11 +42,25 @@ module Samagotchi
33
42
  # the session's messages, behind that turn's events, and the page
34
43
  # keeps theirs (working_set.js newerSnapshot).
35
44
  # A participant's is filtered (ParticipantView.working_set: the
36
- # project's files only).
45
+ # project's files only). The owner's also says which "From the start"
46
+ # parts are stale (parts: [{key, state}], WorkingSetPart.states: the
47
+ # source's text now differs from what was sent; no field: none is),
48
+ # whichever of the
49
+ # three answered, with the parts the part route reads (#prompt_source):
50
+ # so a live idle worker's and an older worker's sessions get them too.
51
+ # A stale part chi changed itself carries by_chi (the same source's
52
+ # messages; while a turn runs only a current one). Never a
53
+ # participant's (no prompt text, D4).
37
54
  def handle_working_set(req, id)
38
55
  session = @session_class.load(id, state_dir: default_state_dir)
39
- set = working_set_payload(id, session)
40
- return json_response(200, set) if principal(req).owner?
56
+ live = bridge_get_json(id, "snapshot")
57
+ set = working_set_payload(session, live)
58
+ if principal(req).owner?
59
+ parts, messages = prompt_source(live, session)
60
+ parts = WorkingSetPart.states(parts, root: MemoryPaths.system_dir, cwd: session.working_directory, messages: messages,
61
+ running: set[:running] == true)
62
+ return json_response(200, parts.empty? ? set : set.merge(parts: parts))
63
+ end
41
64
 
42
65
  viewer = participant_viewer(req, session)
43
66
  # Redacted as the stream's event is (ParticipantView.event): a file name may hold a secret's shape.
@@ -91,8 +114,73 @@ module Samagotchi
91
114
  json_response(200, body)
92
115
  end
93
116
 
94
- def working_set_payload(id, session)
117
+ # GET /api/sessions/:id/working_set/part?key=[&now=1]: one "From the
118
+ # start" part as chi sent it (WorkingSetPart.answer: the slice of the
119
+ # saved head, or the line that says why not and, under a changed head,
120
+ # the source now). +now+: with the slice, the source now and its diff
121
+ # (a stale row's "now" tab) and when chi gets it (rebuild: restart with
122
+ # a live worker, else next_turn). Owner only: participants see no prompt text. The parts and
123
+ # messages[0] come from one source: a live worker's complete snapshot
124
+ # frame, else the session file. The file is read only when the snapshot
125
+ # is missing or a source lookup needs the session's working directory.
126
+ def handle_working_set_part(req, id)
127
+ key = req.GET["key"].to_s
128
+ return error_response(400, "invalid_part", WorkingSetPart::INVALID) if key.strip.empty?
129
+
95
130
  live = bridge_get_json(id, "snapshot")
131
+ source = prompt_snapshot(live)
132
+ if source
133
+ parts, messages = source
134
+ cwd = live["working_directory"]
135
+ if cwd.nil? && prompt_part_needs_cwd?(parts, messages, key, req.GET["now"] == "1")
136
+ session = @session_class.load(id, state_dir: default_state_dir)
137
+ cwd = session.working_directory
138
+ end
139
+ else
140
+ session = @session_class.load(id, state_dir: default_state_dir)
141
+ parts = session.prompt_parts
142
+ messages = session.messages
143
+ cwd = session.working_directory
144
+ end
145
+ body = WorkingSetPart.answer(parts: parts, messages: messages, key: key,
146
+ older_worker: !live.nil? && WorkingSetPart.older_worker?(live.dig("snapshot", "chi_version")),
147
+ running: !live&.dig("snapshot", "current_turn").nil?, root: MemoryPaths.system_dir,
148
+ cwd: cwd, now: req.GET["now"] == "1", live: !live.nil?)
149
+ return error_response(404, "unknown_part", WorkingSetPart::UNKNOWN) unless body
150
+
151
+ json_response(200, body)
152
+ end
153
+
154
+ # A complete live snapshot source for the part route; otherwise nil.
155
+ def prompt_snapshot(live)
156
+ state = live.is_a?(Hash) ? live["session_state_snapshot"] : nil
157
+ snapshot = live.is_a?(Hash) ? live["snapshot"] : nil
158
+ return unless state.is_a?(Hash) && state["prompt_parts"].is_a?(Array) &&
159
+ snapshot.is_a?(Hash) && snapshot["messages"].is_a?(Array)
160
+
161
+ [state["prompt_parts"], snapshot["messages"]]
162
+ end
163
+
164
+ def prompt_part_needs_cwd?(parts, messages, key, now)
165
+ parts = PromptPart.list(parts)
166
+ index = PromptPart.keys(parts).index(key)
167
+ part = parts[index]
168
+ return false unless part && part.at && WorkingSet::Locator::FETCHED.include?(part.kind)
169
+
170
+ head = Array(messages).first
171
+ text = head.is_a?(Hash) && ContextNote.system_head?(head) ? (head[:content] || head["content"]) : nil
172
+ text.is_a?(String) && (now || PromptPart.digest_of(text, 16) != part.head)
173
+ end
174
+
175
+ # Prompt data for the working-set list route, which already loads the session.
176
+ def prompt_source(live, session)
177
+ state = live.is_a?(Hash) ? live["session_state_snapshot"] : nil
178
+ return [state["prompt_parts"], Array(live.dig("snapshot", "messages"))] if state.is_a?(Hash) && state["prompt_parts"].is_a?(Array)
179
+
180
+ [session.prompt_parts, session.messages]
181
+ end
182
+
183
+ def working_set_payload(session, live)
96
184
  worker_snapshot = live && live["snapshot"]
97
185
  running = !worker_snapshot&.dig("current_turn").nil?
98
186
  turn_set = running && running_working_set(live["snapshot"]["working_set"])
@@ -114,7 +202,7 @@ module Samagotchi
114
202
  def working_set_source(live, session)
115
203
  messages = live_or_saved(live && live["snapshot"], "messages") { session.messages }
116
204
  # A snapshot's entries have string keys (paired_runs reads symbols).
117
- messages = Array(messages).map { |message| message.is_a?(Hash) ? message.transform_keys(&:to_sym) : message }
205
+ messages = WorkingSetPart.symbolized(messages)
118
206
  llm_context = SessionSetting::LLM_CONTEXT.snapshot_value(live && live["session_state_snapshot"]) do
119
207
  SessionSetting::LLM_CONTEXT.saved_summary(session, registry: host_registry)
120
208
  end
@@ -58,8 +58,8 @@ module Samagotchi
58
58
  # The client for this worker (BridgeClient.for_sidecar: its port and its
59
59
  # secret from this one read).
60
60
  # @return [BridgeClient]
61
- def client(session_id, host: BridgeClient::HOST, read_timeout: BridgeClient::READ_TIMEOUT)
62
- BridgeClient.for_sidecar(session_id, sidecar, host: host, read_timeout: read_timeout)
61
+ def client(session_id, host: BridgeClient::HOST, read_timeout: BridgeClient::READ_TIMEOUT, deadline_margin: nil)
62
+ BridgeClient.for_sidecar(session_id, sidecar, host: host, read_timeout: read_timeout, deadline_margin: deadline_margin)
63
63
  end
64
64
 
65
65
  def port = sidecar.port