samagotchi 0.183.0 → 0.185.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +84 -1
  3. data/docs/architecture.md +12 -11
  4. data/docs/bundles.md +63 -36
  5. data/docs/cli.md +10 -1
  6. data/docs/configuration.md +3 -2
  7. data/docs/context.md +76 -10
  8. data/docs/guardrails.md +7 -2
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/block-renderers.md +4 -2
  11. data/docs/internals/bridge.md +7 -3
  12. data/docs/internals/bundles.md +6 -2
  13. data/docs/internals/engine.md +2 -1
  14. data/docs/internals/llm-context-forget.md +6 -0
  15. data/docs/internals/participants.md +5 -2
  16. data/docs/internals/prompt-caching.md +8 -1
  17. data/docs/internals/remote-sessions.md +22 -4
  18. data/docs/internals/session-lifecycle.md +1 -1
  19. data/docs/internals/web-frontend.md +37 -15
  20. data/docs/internals/web-push.md +11 -0
  21. data/docs/internals/working-set.md +238 -6
  22. data/docs/mcp-server.md +11 -3
  23. data/docs/memory.md +2 -1
  24. data/docs/plugins.md +6 -6
  25. data/docs/scheduling.md +19 -0
  26. data/docs/sessions.md +13 -3
  27. data/docs/sub-agent.md +48 -3
  28. data/docs/thin-clients.md +38 -12
  29. data/lib/samagotchi/agent_caller.rb +97 -0
  30. data/lib/samagotchi/bridge.rb +7 -7
  31. data/lib/samagotchi/bridge_client.rb +12 -4
  32. data/lib/samagotchi/bundle_command/check.rb +20 -2
  33. data/lib/samagotchi/bundle_manifest.rb +5 -1
  34. data/lib/samagotchi/bundles/claude-peer/manifest.yml +14 -8
  35. data/lib/samagotchi/bundles/claude-peer/plugin.rb +3 -3
  36. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +49 -30
  37. data/lib/samagotchi/bundles/claude-peer/scripts/pair +2 -2
  38. data/lib/samagotchi/bundles/claude-peer/scripts/pair-remote +123 -0
  39. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +11 -3
  40. data/lib/samagotchi/bundles/codex-peer/manifest.yml +10 -8
  41. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  42. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +29 -8
  43. data/lib/samagotchi/bundles/codex-peer/scripts/pair +1 -1
  44. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +11 -3
  45. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  46. data/lib/samagotchi/bundles/mcp/http_client.rb +96 -54
  47. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  48. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  49. data/lib/samagotchi/bundles/system/self_map.md +9 -2
  50. data/lib/samagotchi/client_id.rb +61 -1
  51. data/lib/samagotchi/command_intake.rb +16 -8
  52. data/lib/samagotchi/context_absorber.rb +212 -46
  53. data/lib/samagotchi/delivery.rb +15 -0
  54. data/lib/samagotchi/driver_command.rb +68 -0
  55. data/lib/samagotchi/engine/block_fix.rb +2 -2
  56. data/lib/samagotchi/engine/session.rb +14 -6
  57. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  58. data/lib/samagotchi/engine.rb +13 -5
  59. data/lib/samagotchi/engine_peers.rb +6 -0
  60. data/lib/samagotchi/guardrails/pair_boundary.rb +1 -1
  61. data/lib/samagotchi/mcp_command.rb +7 -2
  62. data/lib/samagotchi/mcp_server/http.rb +3 -3
  63. data/lib/samagotchi/mcp_server/protocol.rb +23 -4
  64. data/lib/samagotchi/mcp_server/stdio.rb +1 -0
  65. data/lib/samagotchi/mcp_server/tools.rb +11 -4
  66. data/lib/samagotchi/model_notes.rb +34 -12
  67. data/lib/samagotchi/objectives_track.rb +2 -1
  68. data/lib/samagotchi/owner_prompt.rb +5 -1
  69. data/lib/samagotchi/parent_report.rb +9 -5
  70. data/lib/samagotchi/plugin/peer.rb +10 -4
  71. data/lib/samagotchi/prompt_files.rb +11 -4
  72. data/lib/samagotchi/prompt_layout.rb +88 -0
  73. data/lib/samagotchi/prompt_part.rb +82 -20
  74. data/lib/samagotchi/reply_wait.rb +16 -4
  75. data/lib/samagotchi/schedule_command.rb +18 -4
  76. data/lib/samagotchi/schedules.rb +49 -14
  77. data/lib/samagotchi/send_command/parent_gate.rb +3 -1
  78. data/lib/samagotchi/send_command.rb +45 -8
  79. data/lib/samagotchi/session.rb +9 -1
  80. data/lib/samagotchi/session_access/ask.rb +58 -14
  81. data/lib/samagotchi/session_access/contract.rb +2 -0
  82. data/lib/samagotchi/session_access/exchange.rb +5 -2
  83. data/lib/samagotchi/session_access/local.rb +13 -3
  84. data/lib/samagotchi/session_access/remote.rb +18 -2
  85. data/lib/samagotchi/session_access.rb +4 -2
  86. data/lib/samagotchi/session_command_catalog.rb +8 -0
  87. data/lib/samagotchi/session_commands.rb +9 -0
  88. data/lib/samagotchi/session_continue.rb +4 -1
  89. data/lib/samagotchi/session_inbox.rb +17 -0
  90. data/lib/samagotchi/session_inbox_delivery.rb +4 -2
  91. data/lib/samagotchi/session_manager/delivery.rb +58 -9
  92. data/lib/samagotchi/session_manager/spawn.rb +7 -1
  93. data/lib/samagotchi/steer.rb +95 -20
  94. data/lib/samagotchi/system_prompt.rb +196 -161
  95. data/lib/samagotchi/terminal_ui/formatting.rb +12 -2
  96. data/lib/samagotchi/tool_activity.rb +4 -0
  97. data/lib/samagotchi/tool_declarations.rb +22 -1
  98. data/lib/samagotchi/tool_names.rb +4 -0
  99. data/lib/samagotchi/toolkit.rb +3 -2
  100. data/lib/samagotchi/tools/ask_session.rb +208 -0
  101. data/lib/samagotchi/tools/builtin_calls.rb +1 -0
  102. data/lib/samagotchi/tools/builtins.rb +5 -0
  103. data/lib/samagotchi/tools/memory.rb +11 -3
  104. data/lib/samagotchi/turn_checkpoint.rb +19 -2
  105. data/lib/samagotchi/turn_stages/context_judge.rb +3 -1
  106. data/lib/samagotchi/turn_stages/objectives.rb +4 -2
  107. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +3 -0
  108. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  109. data/lib/samagotchi/version.rb +1 -1
  110. data/lib/samagotchi/visitor.rb +37 -0
  111. data/lib/samagotchi/web/app.rb +2 -3
  112. data/lib/samagotchi/web/ask_routes.rb +95 -23
  113. data/lib/samagotchi/web/mcp_route.rb +7 -4
  114. data/lib/samagotchi/web/message_display.rb +15 -2
  115. data/lib/samagotchi/web/public/app.js +1 -1
  116. data/lib/samagotchi/web/public/block_fix.js +11 -3
  117. data/lib/samagotchi/web/public/delete_sheet.js +20 -18
  118. data/lib/samagotchi/web/public/history_shape.js +3 -1
  119. data/lib/samagotchi/web/public/index.html +8 -0
  120. data/lib/samagotchi/web/public/peer_links.js +27 -4
  121. data/lib/samagotchi/web/public/peer_note.js +19 -3
  122. data/lib/samagotchi/web/public/peer_text.js +45 -0
  123. data/lib/samagotchi/web/public/picture_regions.js +2 -2
  124. data/lib/samagotchi/web/public/removal_sheet_model.js +3 -4
  125. data/lib/samagotchi/web/public/running_tasks.js +0 -16
  126. data/lib/samagotchi/web/public/session_actions.js +0 -9
  127. data/lib/samagotchi/web/public/turn_events.js +19 -0
  128. data/lib/samagotchi/web/public/working_set_view.js +178 -23
  129. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  130. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  131. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  132. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  133. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  134. data/lib/samagotchi/web/push/notifier.rb +33 -6
  135. data/lib/samagotchi/web/server.rb +1 -1
  136. data/lib/samagotchi/web/session_control.rb +1 -1
  137. data/lib/samagotchi/web/session_create.rb +11 -7
  138. data/lib/samagotchi/web/session_hub.rb +26 -4
  139. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  140. data/lib/samagotchi/worker/command_queue.rb +5 -2
  141. data/lib/samagotchi/worker/senders.rb +79 -0
  142. data/lib/samagotchi/worker.rb +21 -18
  143. data/lib/samagotchi/worker_inbound.rb +12 -4
  144. data/lib/samagotchi/worker_link.rb +2 -2
  145. data/lib/samagotchi/worker_participant_gate.rb +1 -3
  146. data/lib/samagotchi/worker_wakes.rb +12 -0
  147. data/lib/samagotchi/working_set.rb +162 -90
  148. data/lib/samagotchi/working_set_locator.rb +221 -0
  149. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  150. data/lib/samagotchi/working_set_part.rb +281 -0
  151. metadata +13 -1
@@ -243,11 +243,10 @@ function stillRunning(result, choice) {
243
243
  // stopped, what stays. +which+: "this" or "chain"; +result+: the route's
244
244
  // 200; +plan+: the sheet's. +back+: a session to offer opening (the link
245
245
  // that came back, else a delegate left running), or null; +sticky+ true for
246
- // a chain delete that kept a link part-way. +withTasks+ false
247
- // leaves the stopped tasks out (an older cached caller adds them itself).
246
+ // a chain delete that kept a link part-way.
248
247
  // @return {text, back, sticky?}
249
- export function deleteToast(which, result, plan, id, { withTasks = true } = {}) {
250
- const tasks = withTasks ? tasksStoppedSuffix(result) : "";
248
+ export function deleteToast(which, result, plan, id) {
249
+ const tasks = tasksStoppedSuffix(result);
251
250
  const running = stillRunning(result, which === "chain" ? plan?.chain : plan?.link);
252
251
  const keeps = running.length === 1
253
252
  ? ` · ${short(running[0])} keeps running`
@@ -47,22 +47,6 @@ function taskEntries(listing) {
47
47
  (Array.isArray(listing?.[kind]) ? listing[kind] : []).map((task) => ({ task, kind })));
48
48
  }
49
49
 
50
- // The second confirm of a delete or an archive refused for background tasks
51
- // still running (409 tasks_running): which, and whether to stop them and
52
- // +verb+ ("delete" / "archive") the session. +listing+ is the 409's tasks.
53
- // Unused since the delete sheet; kept while an older cached
54
- // session_actions.js may import it (web-frontend.md); goes at the next
55
- // release.
56
- export function tasksConfirmText(id, listing, verb) {
57
- const n = tasksCount(listing);
58
- const one = n === 1;
59
- return [
60
- `Session ${String(id).slice(0, 8)} started ${n} background task${one ? "" : "s"} that ${one ? "is" : "are"} still running:`,
61
- tasksLine(listing, id),
62
- `Stop ${one ? "it" : "them"} and ${verb} the session?`,
63
- ].join("\n");
64
- }
65
-
66
50
  // What a delete's or an archive's toast adds for the tasks it stopped (its
67
51
  // 200's tasks_stopped / tasks_not_stopped): " · stopped 2 background tasks",
68
52
  // " · 1 not stopped: npm run dev"; "" when it stopped none.
@@ -75,11 +75,6 @@ export function createSessionActions({
75
75
  notShown(host, `delete ${id.slice(0, 8)}`, error);
76
76
  if (!eventsLive()) refresh();
77
77
  },
78
- // Kept for an older cached delete_sheet.js (0.182.0), which calls it
79
- // for a session in no chain, its sheet closed (it was the browser's
80
- // confirm): a reload brings the sheet. Goes at the next release.
81
- plain: () => notShown(host, `delete ${id.slice(0, 8)}`,
82
- { message: "this page is out of date; reload it and delete again" }),
83
78
  });
84
79
  host.wire(flow);
85
80
  }
@@ -325,10 +320,6 @@ export function createSessionActions({
325
320
  if (!answer.ok) throw answer.error;
326
321
  return answer.result;
327
322
  },
328
- // Kept for an older cached delete_sheet.js (0.182.0), which ignores
329
- // +archive+ and reads a delete plan: the refusal, so it lands in
330
- // +failed+ and says it. Goes at the next release.
331
- deletePlan: () => Promise.reject(error),
332
323
  },
333
324
  done: (_which, result) => archived(id, true, result, undo),
334
325
  failed: (failure) => notShown(host, `archive ${id.slice(0, 8)}`, failure),
@@ -145,6 +145,21 @@ const TASK_CLIENT = "task:";
145
145
  // A durable schedule's firing (chi schedule, the schedule tools):
146
146
  // system:schedule:<schedule id>.
147
147
  const SCHEDULE_CLIENT = "system:schedule:";
148
+ // An agent's chi send (ClientId::AGENT_PREFIX): agent:<name>, its name
149
+ // cleaned again as ClientId.agent_name cleans it (a thin client's id comes
150
+ // as it typed it): lowercase letters, digits, - and _, up to 32; none left
151
+ // is "agent".
152
+ const AGENT_CLIENT = "agent:";
153
+ function agentName(id) {
154
+ const name = id.slice(AGENT_CLIENT.length).toLowerCase().replace(/[^a-z0-9_-]/g, "").slice(0, 32);
155
+ return name || "agent";
156
+ }
157
+ // Another chi session's question (ask_session): session:<id8>, cleaned as
158
+ // ClientId.session_name cleans it.
159
+ const SESSION_CLIENT = "session:";
160
+ function sessionName(id) {
161
+ return id.slice(SESSION_CLIENT.length).replace(/[^A-Za-z0-9_-]/g, "").slice(0, 8) || "?";
162
+ }
148
163
 
149
164
  // A task id as people read it: the random part a task_create id ends with
150
165
  // (it starts with the time), else its first 8 chars (TaskRecord.short_id).
@@ -162,6 +177,8 @@ export function clientLabel(clientId) {
162
177
  if (id.startsWith(CONTEXT_CLIENT) && id.length > CONTEXT_CLIENT.length) return `context ${id.slice(CONTEXT_CLIENT.length)} changed`;
163
178
  if (id.startsWith(TASK_CLIENT) && id.length > TASK_CLIENT.length) return `task ${shortTaskId(id.slice(TASK_CLIENT.length))} finished`;
164
179
  if (id.startsWith(SCHEDULE_CLIENT)) return "schedule";
180
+ if (id.startsWith(AGENT_CLIENT)) return `agent ${agentName(id)}`;
181
+ if (id.startsWith(SESSION_CLIENT)) return `session ${sessionName(id)}`;
165
182
  const colon = id.indexOf(":");
166
183
  let label = labelFor(id);
167
184
  if (label === undefined && colon >= 0) label = labelFor(id.slice(0, colon + 1));
@@ -201,6 +218,8 @@ const STEER_CUT_FOR = {
201
218
  parent_agent: "the parent agent's message",
202
219
  };
203
220
  export function steerCutLine({ source } = {}) {
221
+ const id = String(source || "");
222
+ if (id.startsWith(AGENT_CLIENT)) return `↪ cut in for a message from the agent ${agentName(id)}`;
204
223
  return `↪ cut in for ${STEER_CUT_FOR[source] || "your message"}`;
205
224
  }
206
225
 
@@ -42,10 +42,9 @@ import { repeat } from "./vendor/directives/repeat.js";
42
42
  import { createChipPopover, SHEET_SHARE, SHEET_TALL } from "./chip_popover.js";
43
43
  import { stillOn } from "./latest.js";
44
44
  import { showRow } from "./refs.js";
45
- import { PEEK_WIDTH } from "./ws_peek.js";
46
45
  import { read as readPref, write as writePref } from "./session_prefs.js";
47
46
  import {
48
- foldedSections, headItems, headLine, headSections, heldTwice, heldTwiceNote, lensTouched, memoryPartWords, promptKeys, startTokensText, WS_SECTION_FOLD,
47
+ foldedSections, headItems, headLine, headSections, heldTwice, heldTwiceNote, lensTouched, memoryName, memoryPartWords, promptKeys, startTokensText, WS_SECTION_FOLD,
49
48
  } from "./ws_sections.js";
50
49
  import {
51
50
  addedItems, addLine, bodySections, BUDGETS, dropRefusal, footprint, footprintText, forgetOn, GLYPHS, INVERSE, isFresh, itemKey, itemsOfTurn, labelText,
@@ -53,12 +52,33 @@ import {
53
52
  steerId, steerLine, stepRange, stepTag, tokensText, turnLens, undroppable,
54
53
  } from "./working_set.js";
55
54
  import { serverSig } from "./ws_item_sig.js";
55
+ import { placeOf } from "./ws_timeline.js";
56
56
  import { heldOrder, recencyOrder } from "./ws_order.js";
57
57
 
58
+ // The popover's width, open row or not (a peek no longer widens it: the rows
59
+ // stayed put only at one width).
60
+ const WIDTH = 520;
61
+ // A stale start row's title words (ws_part_peek.js's now tab says the same).
62
+ const PART_CHANGED = "changed after chi's prompt was built";
63
+ const BOTH_CHANGED = "read changed · prompt text changed";
64
+ // A prompt row whose source chi changed itself (the GET's by_chi, current):
65
+ // its title after "chi edited it at …".
66
+ const OWN_EDITED = "the new text is in its conversation; its prompt still sends the old text until it is next built";
67
+ const OWN_REMOVED = "its prompt still sends it until it is next built";
68
+
58
69
  // The popover's files fold to this many lines (groups open in place, one at
59
70
  // a time), its memories past this many to one group.
60
71
  const POP_BUDGET = 6;
61
72
 
73
+ function sessionPreloads(st) {
74
+ const parts = Array.isArray(st.promptParts) ? st.promptParts : [];
75
+ const prompt = parts
76
+ .filter((part) => ["identity", "preloads"].includes(part?.kind) && typeof part.ref === "string")
77
+ .map((part) => memoryName(part.ref))
78
+ .filter(Boolean);
79
+ return [...new Set([...(st.preloadedMemories || []), ...prompt])];
80
+ }
81
+
62
82
  // A row a peek opens on: one the session's runs touched (not an add, a
63
83
  // muted or a preloaded-only memory).
64
84
  function peekable(item) {
@@ -198,11 +218,69 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
198
218
  let stripOpen = null;
199
219
  const listeners = new Set();
200
220
  const lit = (items) => overlay(items, server);
221
+ // The prompt parts whose source changed since chi was sent them (chi
222
+ // web's GET's parts, WorkingSetPart.states): a GET's word, kept across
223
+ // the events' sets (takeServer), asked again at each open, a rebuilt
224
+ // prompt and a hand-off.
225
+ const partStates = () => (Array.isArray(server?.parts) ? server.parts : null);
226
+ // What the states say, to tell two answers' apart ("" for none).
227
+ const partsSig = (parts) => (Array.isArray(parts) && parts.length ? JSON.stringify(parts) : "");
228
+ // chi's own change of each stale part the GET named (by_chi: {tool_id,
229
+ // step, op, current}), by part key. Read here, off the GET's parts, not
230
+ // through ws_sections.js (an older cached one maps states to "stale").
231
+ const partChanges = () => new Map((partStates() || []).filter((s) => s && typeof s.key === "string" && s.by_chi && typeof s.by_chi === "object").map((s) => [s.key, s.by_chi]));
232
+ // Where a call sits in the page's turns ({turn, step, row}), by its chi id
233
+ // (ws_timeline.js placeOf over every turn's items), or null.
234
+ const placeFor = (toolId) => {
235
+ for (const items of [...turns.map((t) => t.items), live?.items || []]) {
236
+ for (const item of items || []) {
237
+ const at = placeOf({ tool_id: toolId }, item);
238
+ if (at) return at;
239
+ }
240
+ }
241
+ return null;
242
+ };
243
+ // A change's step tag: its place in the turns ("t3·s2"), else the
244
+ // server's step ("step 5"); +where+ the title's words.
245
+ const changeTag = (change) => {
246
+ const at = placeFor(change.tool_id);
247
+ if (at) return { at, text: stepTag({ at }, { session: true }), where: `turn ${at.turn + 1}, step ${at.step + 1}` };
248
+ const step = Number.isFinite(change.step) ? `step ${change.step}` : "";
249
+ return { at: null, text: step, where: step || "a step" };
250
+ };
251
+ // A start row with chi's own changes laid on it: each stale part chi's
252
+ // current change made "edited" (partStates; the peek's edited tab), the
253
+ // row partEdited ({op, tag}) when no part of it is stale any more;
254
+ // partByChi and partTags beside partKeys for the peek's lines (a stale
255
+ // part chi changed, then it changed again). A row without partKeys (an
256
+ // older cached ws_sections.js) as it is.
257
+ const ownRow = (row) => {
258
+ const keys = row?.partKeys;
259
+ if (!Array.isArray(keys) || !Array.isArray(row.partStates)) return row;
260
+ const changes = partChanges();
261
+ const byChi = keys.map((key) => changes.get(key) || null);
262
+ if (!byChi.some(Boolean)) return row;
263
+ const tags = byChi.map((change) => (change ? changeTag(change) : null));
264
+ const partStates = row.partStates.map((st, i) => (st === "stale" && byChi[i]?.current === true ? "edited" : st));
265
+ const partStale = partStates.includes("stale");
266
+ const edited = !partStale && partStates.includes("edited");
267
+ const last = edited ? partStates.map((st, i) => (st === "edited" ? i : -1)).filter((i) => i >= 0).sort((a, b) => (byChi[a].step || 0) - (byChi[b].step || 0)).at(-1) : -1;
268
+ return { ...row, partStates, partStale, partByChi: byChi, partTags: tags.map((t) => t?.text || ""), partEdited: edited ? { op: byChi[last].op, tag: tags[last] } : null };
269
+ };
270
+ // The session's prompt parts as built (each part's head and digest): a new
271
+ // build asks the GET again, so a rebuilt prompt's stale states go.
272
+ let builtSig = null;
273
+ let builtOf = null;
274
+ const builtSigOf = (parts) => JSON.stringify((Array.isArray(parts) ? parts : []).map((p) => [p?.kind, p?.head, p?.digest]));
275
+ // The prompt peek of "From the start" rows (ws_part_peek.js), on the peek
276
+ // a newer ws_reader.js makes; none (an older cached one): today's rows.
277
+ const part = peek?.part || null;
278
+ const anyPeek = () => !!(peek?.any() || part?.any());
201
279
 
202
280
  const sessionSet = () => {
203
281
  const st = state();
204
282
  const set = sessionItems({
205
- turns: turns.map((t) => t.items), live: live?.items || [], preloaded: st.preloadedMemories, notes: st.promptNotes, muted: st.mutedMemories,
283
+ turns: turns.map((t) => t.items), live: live?.items || [], preloaded: sessionPreloads(st), notes: st.promptNotes, muted: st.mutedMemories,
206
284
  used: st.usedMemories,
207
285
  });
208
286
  return { items: lit(set.items), muted: set.muted };
@@ -214,8 +292,8 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
214
292
  const promptOf = (t) => (live && t === live.ordinal ? live.prompt : turns[t]?.prompt || "");
215
293
 
216
294
  const popover = createChipPopover({
217
- id: "workingSetPopover", className: "ctx-popover ws-popover", width: () => (peek?.any() ? PEEK_WIDTH : 420), el: infoEl, anchor: ".ws-chip",
218
- openers: ".ws-chip, .ts-ws, .ws-foot", sheet: true, label: "Working set", sheetShare: () => (peek?.any() ? SHEET_TALL : SHEET_SHARE),
295
+ id: "workingSetPopover", className: "ctx-popover ws-popover", width: () => WIDTH, el: infoEl, anchor: ".ws-chip",
296
+ openers: ".ws-chip, .ts-ws, .ws-foot", sheet: true, label: "Working set", sheetShare: () => (anyPeek() ? SHEET_TALL : SHEET_SHARE),
219
297
  // The chip opens the session lens; the rail and a footprint set theirs
220
298
  // before they open it.
221
299
  summary: (anchor) => {
@@ -236,7 +314,7 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
236
314
  draw();
237
315
  if (opening) fetchServer();
238
316
  },
239
- onClose: () => { openGroup = null; openKeys = null; peek?.close(); onChange(); },
317
+ onClose: () => { openGroup = null; openKeys = null; part?.close(); peek?.close(); onChange(); },
240
318
  // The foot's + add (the popover's submit): one KEY as typed (quoted
241
319
  // when it has spaces).
242
320
  onSubmit: (form) => {
@@ -300,7 +378,9 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
300
378
  // +start+: a "From the start" memory row (ws_sections.js): its part's
301
379
  // words and tokens, no "prompt" tag (the section says it), "held twice"
302
380
  // when it was read again, and the note in a turn lens that read it.
303
- function rowTemplate(row0, { session: inSession, group = null, now, pend = new Map(), forget = false, touched = null, start = false }) {
381
+ function rowTemplate(given, { session: inSession, group = null, now, pend = new Map(), forget = false, touched = null, start = false }) {
382
+ // A start row with chi's own changes of its parts laid on it (ownRow).
383
+ const row0 = start ? ownRow(given) : given;
304
384
  // +row0+ is the session's item: its state, tokens, actions, peek. +item+ is
305
385
  // what the lens shows of it: the turn's `at`, ops and count (the step tag,
306
386
  // the words, the edited mark) and nothing else.
@@ -347,23 +427,72 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
347
427
  const isPending = pill !== nothing;
348
428
  const strip = stripOpen === id && buttons !== nothing;
349
429
  const open = item.kind === "file" ? html`<button type="button" class="ws-act-b open ref" data-ref-kind="file" data-ref-path=${item.ref?.path || full}>open</button>` : nothing;
350
- // The ▸ that peeks at what chi has of it (the owner's: +peek+).
351
- const canPeek = peek && peekable(row0);
352
- const peeked = canPeek && peek.isOpen(id);
353
- const toggle = canPeek ? html`<button type="button" class="ws-peek-toggle" data-ws="peek" data-ws-id=${id} aria-expanded=${String(peeked)} aria-label=${`What chi has of ${name}`} title="What chi has of it">${peeked ? "▾" : "▸"}</button>` : nothing;
354
- const row = html`<div class=${`ws-row ${item.kind}${row0.added ? " added" : ""}${fresh ? " fresh" : ""}${row0.muted ? " muted" : ""}${group ? " member" : ""}${state}${isPending ? " pending" : ""}${strip ? " strip-open" : ""}${peeked ? " peeked" : ""}${canPeek ? " peekable" : ""}${note ? " twice" : ""}${lensClass}`} data-ws-id=${id}>${toggle}<span class="k">${glyph}</span>${nameEl}${pin}${edited ? html`<span class="e">✎</span>` : nothing}<span class="st">${words}</span>${pill}${tokens ? html`<span class="tk" title=${start ? "about its tokens in the prompt, + its reads'" : `about ${row0.tokens} tokens of it are sent`}>${tokens}</span>` : nothing}${tagEl}${buttons !== nothing ? html`<span class="ws-act">${buttons}</span>` : nothing}</div>`;
430
+ // The ▸ that peeks at what chi has of it (the owner's: +peek+); a start
431
+ // row's opens the prompt peek, its read (when it has one) a tab of it;
432
+ // a row without its parts' keys (an older cached ws_sections.js) keeps today's.
433
+ const prompt = start && !!part && !!row0.partKeys?.length;
434
+ const partId = prompt ? `start:${itemKey(row0)}` : null;
435
+ const canPeek = prompt || (peek && peekable(row0));
436
+ const peeked = prompt ? part.isOpen(partId) : canPeek && peek.isOpen(id);
437
+ // Its read tab: the item peek, when it has one. A row chi only wrote has none: its edited tab (or the now
438
+ // tab's "chi edited it" line) says that write.
439
+ const readTab = !!peek && peekable(row0) && !(row0.partByChi?.some(Boolean) && !row0.ops.includes("read"));
440
+ const toggle = prompt ? partToggle(partId, row0, name, peeked, { read: readTab, item: id })
441
+ : canPeek ? html`<button type="button" class="ws-peek-toggle" data-ws="peek" data-ws-id=${id} aria-expanded=${String(peeked)} aria-label=${`What chi has of ${name}`} title="What chi has of it">${peeked ? "▾" : "▸"}</button>` : nothing;
442
+ const peekEl = !peeked ? nothing : prompt ? part.template(row0, { read: readTab, readTag: stepTag({ ...row0, preloaded: false, at: row0.last || row0.at }, { session: true }) }) : peek.template(row0);
443
+ // A prompt row whose source changed since chi was sent it says "stale" in place of its words, kept in
444
+ // its title; a read stale too: still one word, both causes in the title.
445
+ const pstale = start && !item.added && row0.partStale;
446
+ // A prompt row whose source chi changed itself: ✎, its words then "edited" (the read's own stale wins), its
447
+ // tag the call's.
448
+ const pedited = start && !item.added && !!row0.partEdited && row0.state !== "stale";
449
+ // The call's tag in place of the row's own (a turn lens's step), beside "held twice".
450
+ if (pedited) tagEl = start && inSession && heldTwice(row0) ? html`${tagEl}${ownTagTemplate(row0.partEdited)}` : ownTagTemplate(row0.partEdited);
451
+ const staleTitle = pstale ? `${row0.state === "stale" ? `${memoryPartWords(row0)} · ${row0.ops.includes("read") ? BOTH_CHANGED : PART_CHANGED}` : `${what} · ${PART_CHANGED}`}${fresh ? " · just now" : ""}` : "";
452
+ const row = html`<div class=${`ws-row ${item.kind}${row0.added ? " added" : ""}${fresh ? " fresh" : ""}${row0.muted ? " muted" : ""}${group ? " member" : ""}${state}${isPending ? " pending" : ""}${strip ? " strip-open" : ""}${peeked ? " peeked" : ""}${canPeek ? " peekable" : ""}${note ? " twice" : ""}${lensClass}`} data-ws-id=${id}>${toggle}<span class="k">${glyph}</span>${nameEl}${pin}${edited || pedited ? html`<span class="e">✎</span>` : nothing}${pstale ? staleTemplate(staleTitle) : pedited ? ownTemplate(memoryPartWords(row0), row0.partEdited) : html`<span class="st">${words}</span>`}${pill}${tokens ? html`<span class="tk" title=${start ? "about its tokens in the prompt, + its reads'" : `about ${row0.tokens} tokens of it are sent`}>${tokens}</span>` : nothing}${tagEl}${buttons !== nothing ? html`<span class="ws-act">${buttons}</span>` : nothing}</div>`;
355
453
  // One template either way, so the tapped row stays the same node (a
356
454
  // click outside the popover closes it).
357
455
  const noteEl = note ? html`<div class="ws-note twice" role="note">${note}</div>` : nothing;
358
- return html`${row}${noteEl}${strip ? html`<div class="ws-strip">${buttons}${open}</div>` : nothing}${peeked ? peek.template(row0) : nothing}`;
456
+ return html`${row}${noteEl}${strip ? html`<div class="ws-strip">${buttons}${open}</div>` : nothing}${peekEl}`;
359
457
  }
360
458
 
361
- // A prompt part's row: its label, its sub, its tokens; read-only, no
362
- // peek. Never touched by a turn: dim in a turn lens.
363
- function partRowTemplate(row, { touched = null }) {
459
+ // A prompt row's "stale": its source changed since chi was sent it.
460
+ const staleTemplate = (title = `its source ${PART_CHANGED}`) => html`<span class="st ws-pstale" title=${title}>stale</span>`;
461
+
462
+ // A prompt row chi changed itself: its part words (a phone's sheet hides them, .ws-pwords) then "edited"
463
+ // ("removed"), the title saying both facts.
464
+ function ownTemplate(words, own) {
465
+ const removed = own.op === "remove";
466
+ const title = `${words ? `${words} · ` : ""}chi ${removed ? "removed" : "edited"} it at ${own.tag.where}: ${removed ? OWN_REMOVED : OWN_EDITED}`;
467
+ return html`<span class="st ws-pedited" title=${title}>${words ? html`<span class="ws-pwords">${words} · </span>` : nothing}${removed ? "removed" : "edited"}</span>`;
468
+ }
469
+
470
+ // Its tag: the call's place, a jump as the read rows' (a plain "step N" without one).
471
+ function ownTagTemplate(own) {
472
+ const { at, text, where } = own.tag;
473
+ if (!text) return nothing;
474
+ const title = `chi ${own.op === "remove" ? "removed" : "edited"} it at ${where}: go to the call`;
475
+ return at ? html`<button type="button" class="ws-step p ws-own" data-ws="jump" data-at=${atAttr(at)} title=${title}>${text}</button>`
476
+ : html`<span class="ws-step p ws-own" title=${title}>${text}</span>`;
477
+ }
478
+
479
+ // A start row's ▸: the prompt peek (+opts+: its read, its item's id).
480
+ function partToggle(id, row, name, peeked, opts) {
481
+ return html`<button type="button" class="ws-peek-toggle" data-ws-part-peek=${id} aria-expanded=${String(peeked)} aria-label=${`What chi was sent of ${name}`} title="What chi was sent" @click=${() => part.toggle(id, row, opts)}>${peeked ? "▾" : "▸"}</button>`;
482
+ }
483
+
484
+ // A prompt part's row: its label, its sub, its tokens; read-only. Its ▸
485
+ // (with the prompt peek: a newer ws_reader.js) opens what chi was sent.
486
+ // Never touched by a turn: dim in a turn lens.
487
+ function partRowTemplate(given, { touched = null }) {
488
+ const row = ownRow(given);
364
489
  const lensClass = touched ? " dim" : "";
365
490
  const tokens = tokensText(row.partTokens);
366
- return html`<div class=${`ws-row ${row.kind}${lensClass}`} data-ws-part=${row.key}><span class="k"></span><span class="t" title=${row.sub ? `${row.label}: ${row.sub}` : row.label}>${row.label}</span>${row.sub ? html`<span class="st">${row.sub}</span>` : nothing}${tokens ? html`<span class="tk" title="about its tokens in every request">${tokens}</span>` : nothing}</div>`;
491
+ const opens = !!part && !!row.partKeys?.length;
492
+ const id = opens ? `start:part:${row.key}` : null;
493
+ const peeked = opens && part.isOpen(id);
494
+ const toggle = opens ? partToggle(id, row, row.label, peeked, {}) : nothing;
495
+ return html`<div class=${`ws-row ${row.kind}${lensClass}${opens ? " peekable" : ""}${peeked ? " peeked" : ""}`} data-ws-part=${row.key}>${toggle}<span class="k"></span><span class="t" title=${row.sub ? `${row.label}: ${row.sub}` : row.label}>${row.label}</span>${row.partEdited ? html`<span class="e">✎</span>` : nothing}${row.partStale ? staleTemplate(row.sub ? `${row.sub} · ${PART_CHANGED}` : undefined) : row.partEdited ? ownTemplate(row.sub, row.partEdited) : row.sub ? html`<span class="st">${row.sub}</span>` : nothing}${tokens ? html`<span class="tk" title="about its tokens in every request">${tokens}</span>` : nothing}${row.partEdited ? ownTagTemplate(row.partEdited) : nothing}</div>${peeked ? part.template(row) : nothing}`;
367
496
  }
368
497
 
369
498
  // The Conversation section as one row at section level ("Conversation ·
@@ -465,7 +594,7 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
465
594
  const set = { ...full, items: heldOrder(full.items, openKeys) };
466
595
  // The head view (no parts: today's list); a turn's read of `system/x`
467
596
  // lights the start row of `x`, and a prompt memory is never new.
468
- const head = headSections(set, POP_BUDGET, { parts: st.promptParts, ctxTokens: st.ctxTokens, turns: last + 1, inTurn: !inSession });
597
+ const head = headSections(set, POP_BUDGET, { parts: st.promptParts, ctxTokens: st.ctxTokens, turns: last + 1, inTurn: !inSession, states: partStates() });
469
598
  const inPrompt = promptKeys(head);
470
599
  const picked = inSession ? null : turnLens(headItems(set, st.promptParts).filter((item) => !inPrompt.has(itemKey(item))), turnItems(at), at);
471
600
  const opts = { session: inSession, now, pend, forget, touched: lensTouched(head, picked?.touched || null) };
@@ -552,7 +681,8 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
552
681
  }
553
682
  } else if (act.dataset.ws === "peek" && peek) {
554
683
  const item = rowItem(act.dataset.wsId);
555
- if (item) peek.toggle(act.dataset.wsId, item);
684
+ // One peek at a time across both kinds.
685
+ if (item) { part?.close(); peek.toggle(act.dataset.wsId, item); }
556
686
  } else if (act.dataset.ws === "timeline" && onTimeline) {
557
687
  const item = rowItem(act.dataset.wsId);
558
688
  if (popover.isOpen()) popover.close();
@@ -635,10 +765,20 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
635
765
  }
636
766
 
637
767
  // A newer server snapshot redraws every form; an older one (a GET that
638
- // answered after a newer event) is dropped. +how+: newerSnapshot's.
768
+ // answered after a newer event) is dropped, all but its parts. +how+:
769
+ // newerSnapshot's. The parts (the stale prompt parts) are a GET's word
770
+ // alone: an event's set carries none, so the session's last GET's stay
771
+ // (stale lasts until chi rebuilds its prompt; #sessionChanged and a
772
+ // hand-off ask again), and a GET an event overtook still gives them.
639
773
  function takeServer(snapshot, how) {
640
- const next = newerSnapshot(server, snapshot, how);
641
- if (next === server) return;
774
+ let next = newerSnapshot(server, snapshot, how);
775
+ const same = !!server && serverOf === session();
776
+ if (next === server) {
777
+ if (how?.event || !same || !Array.isArray(snapshot?.items) || partsSig(snapshot.parts) === partsSig(server.parts)) return;
778
+ next = withParts(server, snapshot.parts);
779
+ } else if (how?.event && same && !("parts" in next) && server.parts) {
780
+ next = withParts(next, server.parts);
781
+ }
642
782
  server = next;
643
783
  serverOf = session();
644
784
  changed();
@@ -649,6 +789,12 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
649
789
  if (how?.event && popover.isOpen()) peek?.refresh();
650
790
  }
651
791
 
792
+ // +snapshot+ with +parts+ (none: without the field).
793
+ function withParts(snapshot, parts) {
794
+ const { parts: _drop, ...rest } = snapshot;
795
+ return Array.isArray(parts) && parts.length ? { ...rest, parts } : rest;
796
+ }
797
+
652
798
  // The server's set for the open session, asked again; an answer for a
653
799
  // session no longer open is dropped.
654
800
  function fetchServer() {
@@ -692,7 +838,14 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
692
838
  if (popover.isOpen()) popover.refresh();
693
839
  },
694
840
  // Prompt memories changed; the open session list reads them from state.
841
+ // A new prompt build (its parts' heads or digests) asks the server's set
842
+ // again: its stale states are the build's.
695
843
  sessionChanged() {
844
+ const sig = builtSigOf(state().promptParts);
845
+ const rebuilt = builtOf === session() && builtSig !== null && sig !== builtSig;
846
+ builtSig = sig;
847
+ builtOf = session();
848
+ if (rebuilt) fetchServer();
696
849
  if (popover.isOpen()) popover.refresh();
697
850
  },
698
851
  // The context's tokens or window changed (a chunk, a context_status):
@@ -702,7 +855,7 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
702
855
  const st = state();
703
856
  const inSession = curLens() === null;
704
857
  const set = sessionSet();
705
- const head = headSections(set, POP_BUDGET, { parts: st.promptParts, ctxTokens: st.ctxTokens, turns: lastTurn() + 1, inTurn: !inSession });
858
+ const head = headSections(set, POP_BUDGET, { parts: st.promptParts, ctxTokens: st.ctxTokens, turns: lastTurn() + 1, inTurn: !inSession, states: partStates() });
706
859
  if (tokenText(lensLines(st, set, head, inSession), head) !== shownTokens) popover.refresh();
707
860
  },
708
861
  // A :working_set_updated event's set ({items, at}).
@@ -750,6 +903,8 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
750
903
  turns.push({ items, prompt });
751
904
  live = null;
752
905
  changed();
906
+ // A turn's end: the stale states asked again when there are some, or the list is open.
907
+ if (server?.parts || popover.isOpen()) fetchServer();
753
908
  return footprintNode(lit(items), ordinal);
754
909
  },
755
910
  // The running turn left without a hand-off (a reset): forgotten.