samagotchi 0.175.0 → 0.177.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 (71) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +50 -1
  3. data/bin/chi +1 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/cli.md +11 -4
  6. data/docs/configuration.md +1 -0
  7. data/docs/internals/bridge.md +2 -2
  8. data/docs/internals/engine.md +2 -2
  9. data/docs/internals/participants.md +13 -6
  10. data/docs/internals/prompt-caching.md +3 -0
  11. data/docs/internals/web-frontend.md +38 -11
  12. data/docs/internals/working-set.md +77 -6
  13. data/docs/sessions.md +3 -2
  14. data/lib/samagotchi/bridge.rb +11 -4
  15. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  16. data/lib/samagotchi/config.rb +3 -0
  17. data/lib/samagotchi/engine/models.rb +11 -0
  18. data/lib/samagotchi/engine/session.rb +9 -0
  19. data/lib/samagotchi/engine.rb +1 -0
  20. data/lib/samagotchi/engine_snapshots.rb +3 -0
  21. data/lib/samagotchi/participant_uploads.rb +14 -1
  22. data/lib/samagotchi/prompt_part.rb +66 -0
  23. data/lib/samagotchi/session.rb +10 -1
  24. data/lib/samagotchi/system_prompt.rb +191 -12
  25. data/lib/samagotchi/version.rb +1 -1
  26. data/lib/samagotchi/web/app.rb +15 -2
  27. data/lib/samagotchi/web/participant_images.rb +16 -12
  28. data/lib/samagotchi/web/participant_show.rb +1 -1
  29. data/lib/samagotchi/web/participant_view.rb +27 -1
  30. data/lib/samagotchi/web/public/app.js +7 -2
  31. data/lib/samagotchi/web/public/composer_fold.js +3 -1
  32. data/lib/samagotchi/web/public/composer_grip.js +18 -10
  33. data/lib/samagotchi/web/public/composer_mount.js +17 -6
  34. data/lib/samagotchi/web/public/ctx_tokens.js +33 -0
  35. data/lib/samagotchi/web/public/index.html +43 -9
  36. data/lib/samagotchi/web/public/restore.js +3 -1
  37. data/lib/samagotchi/web/public/session_fields.js +10 -4
  38. data/lib/samagotchi/web/public/session_prefs.js +92 -0
  39. data/lib/samagotchi/web/public/session_state.js +14 -1
  40. data/lib/samagotchi/web/public/session_store.js +1 -1
  41. data/lib/samagotchi/web/public/session_sync.js +3 -0
  42. data/lib/samagotchi/web/public/session_view.js +33 -3
  43. data/lib/samagotchi/web/public/stage_asking.js +20 -11
  44. data/lib/samagotchi/web/public/stage_cloud.js +3 -2
  45. data/lib/samagotchi/web/public/stage_missing.js +3 -5
  46. data/lib/samagotchi/web/public/stage_model.js +2 -1
  47. data/lib/samagotchi/web/public/stage_view.js +6 -1
  48. data/lib/samagotchi/web/public/stage_view_memory.js +76 -0
  49. data/lib/samagotchi/web/public/stream_handlers.js +10 -5
  50. data/lib/samagotchi/web/public/tokens.css +2 -2
  51. data/lib/samagotchi/web/public/turn_events.js +1 -1
  52. data/lib/samagotchi/web/public/working_set.js +51 -7
  53. data/lib/samagotchi/web/public/working_set_rail.js +22 -7
  54. data/lib/samagotchi/web/public/working_set_view.js +188 -58
  55. data/lib/samagotchi/web/public/ws_reader.js +2 -0
  56. data/lib/samagotchi/web/public/ws_sections.js +251 -0
  57. data/lib/samagotchi/web/server.rb +6 -2
  58. data/lib/samagotchi/web/session_show.rb +13 -2
  59. data/lib/samagotchi/worker/child_side.rb +123 -0
  60. data/lib/samagotchi/worker/command_queue.rb +350 -0
  61. data/lib/samagotchi/worker/leave.rb +286 -0
  62. data/lib/samagotchi/worker/scratch.rb +99 -0
  63. data/lib/samagotchi/worker/signal_grace.rb +96 -0
  64. data/lib/samagotchi/worker/startup.rb +92 -0
  65. data/lib/samagotchi/worker/wake_turns.rb +190 -0
  66. data/lib/samagotchi/worker.rb +25 -1065
  67. data/lib/samagotchi/worker_exit_claim.rb +12 -0
  68. data/lib/samagotchi/working_set.rb +32 -4
  69. data/lib/samagotchi/working_set_command.rb +3 -2
  70. data/lib/samagotchi/working_set_steer.rb +21 -3
  71. metadata +13 -1
@@ -0,0 +1,251 @@
1
+ // The working set's head view (docs/internals/working-set.md, The head
2
+ // view): the popover's list as what is in chi's head, in three sections.
3
+ // start From the start: the system prompt's parts (the session's
4
+ // prompt_parts), in prompt order, the tools part first. A memory
5
+ // part (identity, a model note, a preload) IS a memory row: merged
6
+ // with the session set's rows of that name and scope (`same`: a
7
+ // scope either side lacks matches by name alone, an older worker's
8
+ // or a set item not read yet), else a row of its own (identity:
9
+ // the set never lists it; a system x beside a project x read: key
10
+ // `x@system`, no actions). Other parts are `part` rows: a label, a
11
+ // sub, their tokens, no actions.
12
+ // read Read in this session: today's files / memories / urls sections
13
+ // (working_set.js bodySections), minus the memories shown in start.
14
+ // talk Conversation: one row (drawn at section level, no header, no
15
+ // fold), the rest of the context: the context's
16
+ // tokens minus the parts' and the held items'. Mixed units (parts and
17
+ // items are chars/4, the context's the server's count or the
18
+ // calibrated estimate): the "~" says so.
19
+ // No parts (an old session or worker, a participant): none of this, the
20
+ // list is today's (headSections returns null).
21
+ //
22
+ // No DOM: `node --test` covers the rules; working_set_view.js draws them.
23
+ // A module of its own: static JS is cached at unversioned URLs, and a new
24
+ // export on an old module would blank the page.
25
+ import { bodySections, itemKey, tokensText } from "./working_set.js";
26
+
27
+ // The sections folded by hand, per session (session_prefs.js): a JSON list
28
+ // of section keys. None: all open.
29
+ export const WS_SECTION_FOLD = "chi_ws_sections_folded";
30
+
31
+ export const MEMORY_PARTS = Object.freeze(["identity", "notes", "preloads"]);
32
+
33
+ // What a memory part's row says it is.
34
+ const MEMORY_WORDS = { identity: "identity memory", notes: "model note", preloads: "preloaded" };
35
+ // A part row's sub text, by kind (the tools part's is its label, "31 declared").
36
+ const PART_SUBS = { agents: "project instructions", appended: "appended", plugins: "plugin section" };
37
+
38
+ // A memory's name as memory_read takes it: a leading project/ or system/
39
+ // scope is not part of it (an older page's preloaded key).
40
+ export function memoryName(name) {
41
+ const m = /^(project|system)\/(.+)$/.exec(String(name || "").trim());
42
+ return m ? m[2] : String(name || "").trim();
43
+ }
44
+
45
+ const struck = (item) => item.state === "forgotten" || item.state === "dropped";
46
+ const held = (item) => !item.muted && !item.added && !struck(item);
47
+ const sum = (list, of) => list.reduce((n, x) => n + (Number.isFinite(of(x)) ? of(x) : 0), 0);
48
+
49
+ // Whether two scopes can be the same memory's: equal, or either unknown
50
+ // (an older worker's part or item, a set item the server hasn't read).
51
+ const sameScope = (a, b) => !a || !b || a === b;
52
+
53
+ // Whether +item+ (a set item) is the memory +part+ names: its name, and its
54
+ // scope when both know theirs.
55
+ export const same = (part, item) => item.kind === "memory" && memoryName(item.key) === memoryName(part.ref) && sameScope(part.scope, item.scope);
56
+
57
+ // A part's row: never an item the set or a steer line knows.
58
+ function partRow(part, key) {
59
+ const tools = part.kind === "tools";
60
+ return {
61
+ kind: "part", key, partKind: part.kind, label: tools ? "tools" : String(part.label || part.kind),
62
+ sub: tools ? String(part.label || "") : PART_SUBS[part.kind] || "", partTokens: Number.isFinite(part.tokens) ? part.tokens : 0,
63
+ ops: [], at: null, count: 0, state: "live",
64
+ };
65
+ }
66
+
67
+ // A memory part's row: the set's rows of that name merged (its read one
68
+ // first: its tokens, its key for steering), or one of its own under +key+
69
+ // (+scoped+: the name is another scope's row's too, so its words say its
70
+ // scope).
71
+ function memoryRow(part, name, matches, key, scoped) {
72
+ const main = matches.find((m) => m.ops.includes("read")) || matches[0];
73
+ const base = main ? { ...main } : { kind: "memory", key, label: name, ops: [], at: null, count: 0, state: "live" };
74
+ const ops = [...new Set(matches.flatMap((m) => m.ops))];
75
+ const at = matches.map((m) => m.at).find(Boolean) || base.at || null;
76
+ return {
77
+ ...base, ops, at, label: name, preloaded: true, partKind: part.kind, partScope: part.scope || null,
78
+ partTokens: Number.isFinite(part.tokens) ? part.tokens : 0, mergedKeys: matches.map(itemKey), ...(scoped ? { scopeWord: part.scope } : {}),
79
+ };
80
+ }
81
+
82
+ // A start memory row's read still sent (read, not forgotten or dropped):
83
+ // what "held twice", its "+X" and the conversation's arithmetic count.
84
+ const readHeld = (row) => row.kind === "memory" && !!row.partKind && row.ops.includes("read") && !struck(row);
85
+
86
+ // Whether a start memory row is in the prompt and its read is held too.
87
+ export const heldTwice = (row) => readHeld(row);
88
+
89
+ // A start memory row's words: what it is in the prompt (a read again is
90
+ // its "held twice" tag, or the turn lens's note).
91
+ export const memoryPartWords = (row) => [MEMORY_WORDS[row.partKind] || "in the prompt", row.scopeWord || ""].filter(Boolean).join(" · ");
92
+
93
+ // The keys of the set's items a start memory row stands for: never new to
94
+ // the head in a turn lens (the prompt had them from the start).
95
+ export function promptKeys(sections) {
96
+ return new Set((sections?.find((s) => s.key === "start")?.rows || []).flatMap((r) => r.mergedKeys || []));
97
+ }
98
+
99
+ // A start row's tokens: the part's, and "+X" for a memory's read (its item
100
+ // tokens: a preloaded row carries none of its own, so the two never
101
+ // double-count). "~0.6k +0.4k".
102
+ export function startTokensText(row) {
103
+ const own = tokensText(row.partTokens);
104
+ if (!readHeld(row) || !Number.isFinite(row.tokens)) return own;
105
+ return `${own} +${tokensText(row.tokens).replace(/^~/, "")}`;
106
+ }
107
+
108
+ // The held-twice note under a start memory row in a turn lens whose items
109
+ // read it: "read again in this turn: already in the prompt, held twice (+X)".
110
+ export function heldTwiceNote(row, turnItem) {
111
+ if (!readHeld(row) || !turnItem?.ops?.includes("read")) return "";
112
+ const extra = Number.isFinite(row.tokens) ? ` (+${tokensText(row.tokens).replace(/^~/, "")})` : "";
113
+ return `read again in this turn: already in the prompt, held twice${extra}`;
114
+ }
115
+
116
+ // The head view's sections for +set+ ({items, muted}: the session's set,
117
+ // overlaid), or null without parts (today's list). +parts+: the session's
118
+ // prompt_parts; +ctxTokens+: the context's tokens now (null: unknown);
119
+ // +turns+: how many turns the session has (the conversation row's).
120
+ // @return [{key, title, meta, tokens, rows?, inner?}] start, read, talk?
121
+ export function headSections(set, budget, { parts = null, ctxTokens = null, turns = 0, inTurn = false } = {}) {
122
+ if (!Array.isArray(parts) || !parts.length) return null;
123
+ const { rows, used, partNames } = startRows(set, parts);
124
+ const partsTokens = sum(rows, (r) => r.partTokens);
125
+ // A preloaded memory never read is the prompt's, never "read in this
126
+ // session": one no part names (a ref-less preloads / notes part, whose
127
+ // items' sizes didn't line up; a preload that failed to load) stays out.
128
+ const rest = {
129
+ items: normalized(set.items, used, partNames).filter((item) => !used.has(item) && !(item.preloaded && !item.ops.includes("read"))),
130
+ muted: set.muted,
131
+ };
132
+ const readItems = rest.items;
133
+ const out = readItems.filter(struck).length;
134
+ // The read section's tokens: its held items'; the start rows' reads count
135
+ // into the conversation's arithmetic, not into either section.
136
+ const readTokens = sum(readItems.filter(held), (i) => i.tokens);
137
+ const heldTokens = readTokens + sum(rows.filter(readHeld), (r) => r.tokens);
138
+ const sections = [
139
+ { key: "start", title: "From the start", meta: inTurn ? "in every turn" : `${rows.length} part${rows.length === 1 ? "" : "s"} · in every turn`, tokens: partsTokens, rows },
140
+ {
141
+ key: "read", title: "Read in this session", meta: [`${readItems.filter(held).length} held`, out ? `${out} out` : ""].filter(Boolean).join(" · "),
142
+ tokens: readTokens, inner: bodySections(rest, budget),
143
+ },
144
+ ];
145
+ const talk = Number.isFinite(ctxTokens) ? ctxTokens - partsTokens - heldTokens : NaN;
146
+ if (talk > 0) {
147
+ const row = { kind: "talk", key: "conversation", label: "conversation", sub: `${turns} turn${turns === 1 ? "" : "s"}`, partTokens: talk, ops: [], at: null, count: 0, state: "live" };
148
+ sections.push({ key: "talk", title: "Conversation", meta: "", tokens: talk, rows: [row] });
149
+ }
150
+ return sections;
151
+ }
152
+
153
+ // The session set's items as the head view sees them (+parts+: the
154
+ // session's prompt_parts; none: the items as they are): an item another
155
+ // scope's part names (a project x read beside a system x preload) is a
156
+ // plain read, not the prompt's (preloaded: false). The Read section and a
157
+ // turn lens's counts (turnLens) both read this list.
158
+ export function headItems(set, parts) {
159
+ if (!Array.isArray(parts) || !parts.length) return set.items;
160
+ const { used, partNames } = startRows(set, parts);
161
+ return normalized(set.items, used, partNames);
162
+ }
163
+
164
+ // +items+ with each one no start row shows, named by a memory part, made
165
+ // a plain read (a copy; the rest unchanged).
166
+ function normalized(items, used, partNames) {
167
+ return items.map((item) => (!used.has(item) && item.preloaded && item.kind === "memory" && partNames.has(memoryName(item.key)) ? { ...item, preloaded: false } : item));
168
+ }
169
+
170
+ // The start section's rows for +parts+, the set's items they show (+used+,
171
+ // by identity) and the memory names the parts claim (+partNames+).
172
+ function startRows(set, parts) {
173
+ // The set's items a start row shows, by identity: a key can be two
174
+ // memories' (a project x read, a system x in the prompt).
175
+ const used = new Set();
176
+ const memories = set.items.filter((item) => item.kind === "memory");
177
+ const rows = [];
178
+ const keys = new Set();
179
+ const seenMemory = new Map();
180
+ // Names a part claims: a set item of that name no part matched (another
181
+ // scope's) reads as read, not as the prompt's.
182
+ const partNames = new Set();
183
+ for (const part of parts) {
184
+ if (!part || !part.kind) continue;
185
+ if (MEMORY_PARTS.includes(part.kind) && part.ref) {
186
+ const name = memoryName(part.ref);
187
+ partNames.add(name);
188
+ const again = (seenMemory.get(name) || []).find((r) => sameScope(r.partScope, part.scope));
189
+ // A memory in two parts (a note also preloaded): one row, both sizes.
190
+ if (again) {
191
+ again.partTokens += Number.isFinite(part.tokens) ? part.tokens : 0;
192
+ if (!again.partScope && part.scope) again.partScope = part.scope;
193
+ continue;
194
+ }
195
+ const matches = memories.filter((m) => !used.has(m) && same(part, m));
196
+ matches.forEach((m) => used.add(m));
197
+ // Its own row's key: the name, or name@scope when another row or
198
+ // item holds that name (never two rows of one key).
199
+ const taken = keys.has(`memory:${name}`) || memories.some((m) => memoryName(m.key) === name && !matches.includes(m));
200
+ const own = !matches.length && taken ? `${name}@${part.scope || part.kind}` : name;
201
+ const row = memoryRow(part, name, matches, own, taken && !!part.scope);
202
+ seenMemory.set(name, [...(seenMemory.get(name) || []), row]);
203
+ keys.add(itemKey(row));
204
+ rows.push(row);
205
+ continue;
206
+ }
207
+ let key = `${part.kind}:${part.ref ?? part.label ?? ""}`;
208
+ for (let n = 2; keys.has(`part:${key}`); n += 1) key = `${part.kind}:${part.ref ?? part.label ?? ""}#${n}`;
209
+ keys.add(`part:${key}`);
210
+ rows.push(partRow(part, key));
211
+ }
212
+ return { rows, used, partNames };
213
+ }
214
+
215
+ // +touched+ (a turn lens: the turn's items by key) with each start memory
216
+ // row's merged keys under its own key, so a read of `system/x` lights the
217
+ // row of `x` (the set holds both spellings). A turn's rows come from tool
218
+ // titles, which carry no scope: a part-only row (no merged item, e.g.
219
+ // `x@system`) lights by its bare name too (a turn that read a project x,
220
+ // never as held twice: that row holds no read). A row with a merged item
221
+ // lights by its items' keys only. The map given is not changed.
222
+ export function lensTouched(sections, touched) {
223
+ if (!touched || !sections) return touched;
224
+ const out = new Map(touched);
225
+ for (const row of sections.find((s) => s.key === "start")?.rows || []) {
226
+ if (!row.mergedKeys || out.has(itemKey(row))) continue;
227
+ const keys = row.mergedKeys.length ? row.mergedKeys : [`memory:${row.label}`];
228
+ const hit = keys.find((k) => touched.has(k));
229
+ if (hit) out.set(itemKey(row), touched.get(hit));
230
+ }
231
+ return out;
232
+ }
233
+
234
+ // The section keys folded, from the stored value (a JSON list); unreadable: none.
235
+ // Conversation never folds (one row): an older page's stored "talk" is ignored.
236
+ export function foldedSections(stored) {
237
+ try {
238
+ const list = JSON.parse(stored || "[]");
239
+ return new Set(Array.isArray(list) ? list.filter((k) => typeof k === "string" && k !== "talk") : []);
240
+ } catch (_) {
241
+ return new Set();
242
+ }
243
+ }
244
+
245
+ // The head line in the session lens: "in chi's head now · ~X of Y" (Y the
246
+ // window; no "of Y" when unknown), "" without the context's tokens.
247
+ export function headLine(ctxTokens, windowTokens) {
248
+ if (!Number.isFinite(ctxTokens)) return "";
249
+ const of = Number.isFinite(windowTokens) && windowTokens > 0 ? ` of ${tokensText(windowTokens).replace(/^~/, "")}` : "";
250
+ return `in chi's head now · ${tokensText(ctxTokens)}${of}`;
251
+ }
@@ -170,6 +170,7 @@ module Samagotchi
170
170
  annotate_presets: Config::BY_KEY["web.annotate_presets"].default,
171
171
  editor: Config::BY_KEY["web.editor"].default, new_token: false,
172
172
  working_set: Config::BY_KEY["web.working_set"].default, tunnel: nil, start_dir_from: :flag,
173
+ stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
173
174
  reload_check: Config::BY_KEY["web.reload_check"].default,
174
175
  restarted: false, restart_argv: ["web"], exec: nil)
175
176
  handed_on = false # a :restart leaves Serve to the next process, a run turns it off itself
@@ -230,7 +231,8 @@ module Samagotchi
230
231
  Push.preflight!(public_url)
231
232
  options = { port: port, host: host, url: url, open_browser: open_browser, markdown: markdown,
232
233
  annotate_presets: annotate_presets, editor: editor, lan: lan, working_set: working_set,
233
- reload_check: reload_check, public_url: public_url, start_dir: start_dir }
234
+ stage_collapsed: stage_collapsed, reload_check: reload_check, public_url: public_url,
235
+ start_dir: start_dir }
234
236
  started = if plan
235
237
  with_tunnel(provider, plan) do |up|
236
238
  start(**options, public_notes: provider.start_lines(plan, restarted: restarted), on_bound: up)
@@ -459,6 +461,7 @@ module Samagotchi
459
461
  annotate_presets: Config::BY_KEY["web.annotate_presets"].default, hub: nil, lan: nil,
460
462
  editor: Config::BY_KEY["web.editor"].default, token_path: Token.path,
461
463
  working_set: Config::BY_KEY["web.working_set"].default, public_url: nil, public_notes: [],
464
+ stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
462
465
  reload_check: Config::BY_KEY["web.reload_check"].default,
463
466
  on_bound: nil, start_dir: Dir.pwd, update_check: nil, auto_update: nil)
464
467
  config_restart_unsubscribe = ConfigFile.watch_restart_settings!(process: :web) do |message|
@@ -476,7 +479,8 @@ module Samagotchi
476
479
  push = push_runtime(public_url, state_dir)
477
480
  app = App.new(manager: manager, state_dir: state_dir, markdown: markdown,
478
481
  annotate_presets: annotate_presets, editor: editor, hub: hub, lan: lan_option, working_set: working_set,
479
- reload_check: reload_check, public_url: public_url, public_token: public_token, push: push, start_dir: start_dir)
482
+ stage_collapsed: stage_collapsed, reload_check: reload_check, public_url: public_url,
483
+ public_token: public_token, push: push, start_dir: start_dir)
480
484
  # update.auto: install; a stand-in app (a spec's) has no operations to run.
481
485
  auto_update ||= AutoUpdate.new(hub: hub, ops: app.update_ops, check: update_check, preflight: method(:restart_preflight)) if app.respond_to?(:update_ops)
482
486
  webrick = nil
@@ -297,6 +297,10 @@ module Samagotchi
297
297
  refs.empty? ? pending.except(key) : pending.merge(key => refs)
298
298
  end
299
299
 
300
+ # The session file's prompt parts as the wire has them ([] for a file
301
+ # without the field).
302
+ def saved_prompt_parts(session) = Array(session.prompt_parts).map(&:to_h)
303
+
300
304
  # The full show's session part: the file's, with what a live worker's
301
305
  # state +snapshot+ knows first (its model, status, served model,
302
306
  # prompt notes and chips); without one, the served model from
@@ -310,6 +314,9 @@ module Samagotchi
310
314
  served_expected_by: snapshot["served_expected_by"])
311
315
  # The model notes its prompt carries now (a /model there changes them).
312
316
  session_json = session_json.merge(prompt_notes: snapshot["prompt_notes"]) if snapshot["prompt_notes"].is_a?(Array)
317
+ # And the sizes of its parts (the head view's "From the start"); an
318
+ # older worker's snapshot has none: the file's, [] for an older file.
319
+ session_json = session_json.merge(prompt_parts: snapshot["prompt_parts"].is_a?(Array) ? snapshot["prompt_parts"] : saved_prompt_parts(session))
313
320
  # The newest context estimate the worker has (a turn in flight: the
314
321
  # last request's), so a page opened mid-turn shows the percent at
315
322
  # once. Owner show only: a participant's show is ParticipantView's
@@ -317,7 +324,7 @@ module Samagotchi
317
324
  # nothing, so its page reads as it always did.
318
325
  session_json = session_json.merge(context_status: snapshot["context_status"]) if snapshot.key?("context_status")
319
326
  else
320
- session_json = session_json.merge(saved_served_model(session, persisted))
327
+ session_json = session_json.merge(saved_served_model(session, persisted), prompt_parts: saved_prompt_parts(session))
321
328
  end
322
329
  # The per-session settings' chips (the info bar's ⚙ chip: llm ctx, think
323
330
  # and reasoning; the tools chip): the worker's, else worked out here from the
@@ -361,7 +368,7 @@ module Samagotchi
361
368
  state = tail && tail["session_state_snapshot"]
362
369
  state = nil unless state.is_a?(Hash)
363
370
  if state
364
- status, used, notes = state.values_at("status", "used_memory_names", "prompt_notes")
371
+ status, used, notes, parts = state.values_at("status", "used_memory_names", "prompt_notes", "prompt_parts")
365
372
  answer = tail["answer"]
366
373
  cwd = tail_working_directory(id, tail, answer)
367
374
  answer = without_file_refs(answer) unless cwd
@@ -371,9 +378,13 @@ module Samagotchi
371
378
  status = displayed_status(session)
372
379
  used = session.used_memory_names
373
380
  notes = session.prompt_notes.map(&:to_h)
381
+ parts = saved_prompt_parts(session)
374
382
  messages = last_assistant_for_display(session.messages, turn_id: turn_id, cwd: session.working_directory)
375
383
  end
376
384
  session_json = { id: id, status: status, used_memory_names: Array(used), prompt_notes: Array(notes) }
385
+ # A live worker's state without the key (an older worker) leaves it out:
386
+ # unknown, not none, so the page keeps the parts it has. No file read.
387
+ session_json[:prompt_parts] = parts if parts.is_a?(Array)
377
388
  live_metrics = state && state["metrics"]
378
389
  timing = recent_timing(id, live_metrics)
379
390
  json_response(200, {
@@ -0,0 +1,123 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+
5
+ require_relative "../child_reports"
6
+ require_relative "../client_id"
7
+ require_relative "../continue_offer"
8
+ require_relative "../llm/errors"
9
+ require_relative "../log"
10
+ require_relative "../verify_fresh"
11
+
12
+ module Samagotchi
13
+ class Worker
14
+ # A delegate child's rings to its parent and the Verify fresh hand-off:
15
+ # #forward_fresh_verdicts (the child's side), #absorb_fresh_verdicts (the
16
+ # parent's half), #settle_child_reports, #merges_lost?,
17
+ # #ring_parent_after_turn, #reports_to_parent? and #ring_question. The
18
+ # name is the audit's; #absorb_fresh_verdicts is the parent's half of the
19
+ # Verify fresh hand-off. Writes @owes_parent, @asked_parent and
20
+ # @reporting_turn (also written by #run_engine_turn, with @initial_turn
21
+ # from #run_initial_prompt; #initialize sets them). Reads @session,
22
+ # @state_dir, @session_dir, @engine, @child_reports and @initial_turn.
23
+ module ChildSidePart
24
+ private
25
+
26
+ # A Verify fresh child's verdicts this turn recorded go to its parent
27
+ # (VerifyFresh.forward), after the save: the parent's card shows them.
28
+ # A fresh child never rings (ChildRing.ring): nothing enters the
29
+ # parent's conversation.
30
+ def forward_fresh_verdicts(before)
31
+ return unless @session.verify_fresh
32
+
33
+ added = @session.verdicts.drop(before)
34
+ VerifyFresh.forward(@session, added, state_dir: @state_dir) unless added.empty?
35
+ end
36
+
37
+ # The parent's side, between turns: the verdicts its Verify fresh
38
+ # children forwarded join the session's (saved, then their files go)
39
+ # and the UIs hear each (:verdict_recorded).
40
+ def absorb_fresh_verdicts
41
+ added, files = VerifyFresh.take(@session, @session_dir)
42
+ return if files.empty?
43
+
44
+ return unless save_or_log(:fresh_verdicts) { save_session }
45
+
46
+ FileUtils.rm_f(files)
47
+ added.each { |record| @engine.announce(type: :verdict_recorded, verdict: record) }
48
+ rescue StandardError => e
49
+ Log.warn(:worker, "fresh_verdicts_failed", error: e.class.name, msg: e.message)
50
+ end
51
+
52
+ # The delegate reports this turn took: a kept turn moves the cursors on
53
+ # and deletes their rings; a rolled-back one leaves the rings for the
54
+ # next turn. Once either way: the model reads a report in the
55
+ # conversation, or the next turn brings it (unless a later !rollback
56
+ # erases a kept turn, which drops what it read).
57
+ def settle_child_reports(rolled_back:)
58
+ rolled_back ? @child_reports.release : @child_reports.commit
59
+ end
60
+
61
+ # Whether +error+ ended the turn without its loop's conversation: a
62
+ # failure the loops didn't mark (LLM::FailedTurn), one past their end
63
+ # (the Engine's own end of the turn, say). The Engine kept the turn's
64
+ # start only, so the reports its loop merged are not in the
65
+ # conversation: their rings stay for the next turn, even when the turn
66
+ # itself stays (a reminder or continue turn). Not one raised after the
67
+ # turn ended (the Engine's post-turn work): the turn was kept as it
68
+ # ended, completed or canceled, the reports in it (a turn TurnFlow
69
+ # takes back is a restore, above).
70
+ def merges_lost?(error)
71
+ return false if error.nil? || error.is_a?(LLM::FailedTurn)
72
+
73
+ !KEPT_TURN_OUTCOMES.include?(@session.last_turn&.outcome)
74
+ end
75
+
76
+ # The Engine's turn endings that keep the turn's conversation (#merges_lost?).
77
+ KEPT_TURN_OUTCOMES = %w[completed canceled].freeze
78
+
79
+ # A delegate child's turn that was its parent's (#reports_to_parent?)
80
+ # rings the parent, after the save: the parent reads a settled child.
81
+ # A question it rang about that still waits makes the next turn ring
82
+ # too, whoever starts it (the user answering Continue on the web).
83
+ def ring_parent_after_turn
84
+ ChildRing.ring(@session, why: "turn_end", state_dir: @state_dir) if @reporting_turn
85
+ @owes_parent = @asked_parent && !@session.pending_question.nil?
86
+ @asked_parent = false
87
+ @reporting_turn = false
88
+ end
89
+
90
+ # Whether the turn starting now is a delegate child's parent's: its
91
+ # task (the initial prompt), a follow-up, a continue the parent
92
+ # answered, a reminder, anything but a human typing into the child
93
+ # (ClientId.human?), and any turn after a question the parent
94
+ # was rung about.
95
+ def reports_to_parent?(origin)
96
+ return false unless @session.delegate?
97
+
98
+ @initial_turn || @owes_parent || !ClientId.human?(origin.client_id)
99
+ end
100
+
101
+ # The Engine published a question (after the question desk saved it).
102
+ # In a turn that reports to the parent, the model's own question, the
103
+ # step-limit continue and a hook's question ring it (the parent reports
104
+ # or relays a hook's: ChildReports). Approvals don't: the relay takes
105
+ # them while the parent waits. Nor does a card relayed from this
106
+ # session's own child (relay set): the hop is the parent's wait.
107
+ def ring_question(event)
108
+ return unless @reporting_turn
109
+
110
+ pending = event[:pending_question] || {}
111
+ kind = pending[:kind].to_s
112
+ return unless RINGING_KINDS.include?(kind)
113
+ return if pending[:relay]
114
+
115
+ ChildRing.ring(@session, why: "question", state_dir: @state_dir)
116
+ @asked_parent = true
117
+ end
118
+
119
+ # The kinds of question that ring a delegate child's parent (#ring_question).
120
+ RINGING_KINDS = ["", ContinueOffer::KIND, "hook"].freeze
121
+ end
122
+ end
123
+ end