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
@@ -0,0 +1,277 @@
1
+ // The working set popover's prompt peek: a "From the start" row's ▸ opens,
2
+ // under the row, the text chi was sent for that prompt part (chi web's GET
3
+ // …/working_set/part, a slice of the session's saved head: WorkingSetPart).
4
+ // A memory's text and an .md file's render through the reader's markdown
5
+ // cache (+md+: ws_markdown.js), anything else as its source; the line chi
6
+ // adds before it folds under "chi adds a line before it". Tools open as
7
+ // their declared names and sizes. A prompt peek has no foot buttons: a
8
+ // memory never read has no timeline, and the row's name is not a link.
9
+ //
10
+ // One row, several holds (a note also preloaded, a prompt memory also
11
+ // read): one tab per hold, its kind and size ("note · ~0.9k"), and "read ·
12
+ // t1·s1" for the item's read, which is the item peek's (ws_peek.js, +itemPeek+)
13
+ // and opens first when there is one. When the sent text isn't there, one
14
+ // line says why (the route's words, case C of the plan), the source now
15
+ // under it when chi could fetch it.
16
+ //
17
+ // A stale hold (the row's partStates, from chi web's GET: its source
18
+ // changed since chi was sent it) gets a "now · changed" tab right after
19
+ // its own: the part route's &now=1, its diff from the sent text drawn as
20
+ // the reader draws a diff (diff_view.js). It opens first when the row has
21
+ // no read. Under it, when chi gets the new text (the route's rebuild: a
22
+ // live worker at its prompt's next build, else at its next turn), and,
23
+ // when chi changed it and it changed again after (the row's partByChi,
24
+ // current false), a line naming chi's edit.
25
+ //
26
+ // A hold chi changed itself ("edited" in partStates: the view lays the
27
+ // GET's by_chi on the row) gets an "edited · t3·s2" tab ("removed · …")
28
+ // in its place: the same &now=1 answer, headed "chi edited <label> at
29
+ // t3·s2", its diff, and the line that says both facts (the prompt still
30
+ // sends the old text; chi has the new text from its edit). An older
31
+ // cached peek sees no stale there and shows the sent text.
32
+ //
33
+ // Made by ws_reader.js createWorkingSetPreview and handed to the view as
34
+ // its peek's +part+ (no new export on ws_reader.js): a view without it
35
+ // (an older cached ws_reader.js) draws today's rows. One peek open at a
36
+ // time across both kinds: opening here closes the item peek.
37
+
38
+ import { html, nothing } from "./vendor/lit-html.js";
39
+ import { api } from "./data.js";
40
+ import { diffCounts, diffTemplate } from "./diff_view.js";
41
+ import { createLatest } from "./latest.js";
42
+ import { textTemplate } from "./ws_cards.js";
43
+ import { peekMarkdownTemplate, peekText } from "./ws_markdown.js";
44
+ import { tokensText } from "./working_set.js";
45
+
46
+ // The part route's path for session +id+ and part +key+ (PromptPart.keys);
47
+ // +now+: with the source now and its diff.
48
+ export function partPath(id, key, { now = false } = {}) {
49
+ return `/api/sessions/${encodeURIComponent(id)}/working_set/part?key=${encodeURIComponent(key)}${now ? "&now=1" : ""}`;
50
+ }
51
+
52
+ // The part route's answer.
53
+ export function getWorkingSetPart(id, key, opts = {}) {
54
+ return api(partPath(id, key, opts));
55
+ }
56
+
57
+ // A hold's tab word, by the part's kind.
58
+ const HOLD_WORDS = { notes: "note", preloads: "preload" };
59
+ const MEMORY_KINDS = ["identity", "notes", "preloads"];
60
+ const SENT = "in the prompt · sent with every request";
61
+ // A now tab's words when its row's read is stale too: both causes (the row says one "stale").
62
+ const BOTH_CHANGED = "read changed · prompt text changed";
63
+ // When chi's prompt gets the source now (the part route's rebuild).
64
+ const REBUILD_LIVE = "when its prompt is next built (a restart, a model switch)";
65
+ const REBUILD_NEXT = "at its next turn";
66
+ const STILL_SENT = "Its prompt still sends the old text with every request; chi has the new text from its edit.";
67
+ const PROMPT_GETS = { restart: "The prompt gets it when it is next built (a restart, a model switch).", next_turn: "The prompt gets it when it is next built (at its next turn)." };
68
+
69
+ // Whether the row's read is stale too (its item stale and read; one chi only wrote is stale by that write).
70
+ const readStale = (r) => r?.state === "stale" && (r.ops || []).includes("read");
71
+ // A part key's kind ("notes:model_notes_y@system" → "notes").
72
+ const kindOf = (key) => String(key).split(":", 1)[0];
73
+ // A stale hold's now tab: "now:" and its part's key.
74
+ const NOW = "now:";
75
+ const nowOf = (key) => (String(key).startsWith(NOW) ? String(key).slice(NOW.length) : null);
76
+ // A hold chi changed itself: "edited:" and its part's key.
77
+ const EDITED = "edited:";
78
+ const editedOf = (key) => (String(key).startsWith(EDITED) ? String(key).slice(EDITED.length) : null);
79
+ // The &now=1 tabs' part key (a now tab's, an edited tab's), else null.
80
+ const sourceOf = (key) => nowOf(key) ?? editedOf(key);
81
+
82
+ // Whether a part's text renders as markdown: a memory's, an .md file's.
83
+ function renders(part) {
84
+ if (!part) return false;
85
+ if (MEMORY_KINDS.includes(part.kind)) return true;
86
+ return (part.kind === "agents" || part.kind === "appended") && /\.md$/i.test(String(part.ref || ""));
87
+ }
88
+
89
+ // +text+ rendered (+md+ has its HTML) or as its source.
90
+ function bodyTemplate(text, part, md) {
91
+ const rendered = md && renders(part) ? peekMarkdownTemplate(text, md) : null;
92
+ if (rendered) return rendered;
93
+ return textTemplate(renders(part) ? peekText(text) : text, { fold: Infinity });
94
+ }
95
+
96
+ const leadTemplate = (lead) => (lead ? html`<details class="ws-lead"><summary>chi adds a line before it</summary><pre>${lead}</pre></details>` : nothing);
97
+
98
+ // The tools' names and sizes (a size only where the build had one per tool).
99
+ function toolsTemplate(tools) {
100
+ return html`<div class="ws-tools">${tools.map((t) => html`<span class="ws-tool-n">${t.name}</span><span class="ws-tool-k">${Number.isFinite(t.chars) ? tokensText(Math.ceil(t.chars / 4)) : ""}</span>`)}</div>`;
101
+ }
102
+
103
+ // +session()+: the open session's id; +getPart(id, key)+: the part route;
104
+ // +itemPeek+: the rows' item peek (ws_peek.js; its template is the "read"
105
+ // tab); +md+: the reader's markdown cache; +onChange()+: the peek's content
106
+ // changed (the popover redraws and places itself again).
107
+ export function createPartPeek({ session, getPart = getWorkingSetPart, itemPeek = null, md = null, onChange = () => {} }) {
108
+ let openId = null;
109
+ let itemId = null;
110
+ let row = null;
111
+ let tab = null;
112
+ // Answers by part key, for the open row; whether one failed.
113
+ let answers = new Map();
114
+ let failed = new Set();
115
+ const latest = createLatest(() => `${session()}|${openId}|${tab}`);
116
+
117
+ // The row's tabs: its read, then each part's, a stale one's now after it.
118
+ const holdsOf = (r, read) => [
119
+ ...(read ? ["read"] : []),
120
+ ...(r?.partKeys || []).flatMap((key, i) => {
121
+ const st = r.partStates?.[i];
122
+ return st === "stale" ? [key, `${NOW}${key}`] : st === "edited" ? [key, `${EDITED}${key}`] : [key];
123
+ }),
124
+ ];
125
+ // The tab a row opens on: its read, else a changed part's now or edited tab, else its first.
126
+ const firstOf = (holds) => (holds.includes("read") ? "read" : holds.find((key) => sourceOf(key)) || holds[0] || null);
127
+ // A part's own change on the open row (+r+'s partByChi, its tag), by part key.
128
+ const ownOf = (r, key) => {
129
+ const i = (r?.partKeys || []).indexOf(key);
130
+ return i < 0 ? { change: null, tag: "" } : { change: r.partByChi?.[i] || null, tag: r.partTags?.[i] || "" };
131
+ };
132
+
133
+ function load(key) {
134
+ const id = session();
135
+ if (!id || !key || key === "read" || answers.has(key)) return;
136
+ const fresh = latest.begin();
137
+ const now = sourceOf(key);
138
+ Promise.resolve()
139
+ .then(() => (now ? getPart(id, now, { now: true }) : getPart(id, key)))
140
+ .then((answer) => {
141
+ if (!fresh()) return;
142
+ answers.set(key, answer);
143
+ failed.delete(key);
144
+ onChange();
145
+ })
146
+ .catch(() => {
147
+ if (!fresh()) return;
148
+ failed.add(key);
149
+ onChange();
150
+ });
151
+ }
152
+
153
+ // Shows +key+ (a part key, or "read": the item peek's).
154
+ function show(key) {
155
+ tab = key;
156
+ if (key === "read") {
157
+ if (itemPeek && !itemPeek.isOpen(itemId)) itemPeek.toggle(itemId, row);
158
+ } else {
159
+ if (itemPeek?.any()) itemPeek.close();
160
+ load(key);
161
+ }
162
+ }
163
+
164
+ function close() {
165
+ if (openId && tab === "read") itemPeek?.close();
166
+ openId = null;
167
+ itemId = null;
168
+ row = null;
169
+ tab = null;
170
+ answers = new Map();
171
+ failed = new Set();
172
+ latest.drop();
173
+ }
174
+
175
+ // A now tab's body (+key+: its part's): what changed since chi was sent
176
+ // it, as a diff, and when chi gets it; chi's edit when it changed again
177
+ // after chi's own change. A head changed since (case C 4-5): build 1's
178
+ // line and the source under it.
179
+ function nowBody(data, r, key) {
180
+ const now = data.now;
181
+ if (!data.sent) return null;
182
+ // The route fetched nothing (the guard refused, the part no longer fetchable): never the sent text under "now".
183
+ if (!now) return html`<div class="ws-peek-note">Couldn't fetch its source now.</div>`;
184
+ const { change, tag } = ownOf(r, key);
185
+ const again = change && change.current === false && tag ? html`<div class="ws-peek-copy warn">chi edited it at ${tag}; it changed again after that.</div>` : nothing;
186
+ const when = data.rebuild ? html`<div class="ws-peek-copy">chi gets the new text ${data.rebuild === "restart" ? REBUILD_LIVE : REBUILD_NEXT}.</div>` : nothing;
187
+ if (now.gone) return html`<div class="ws-peek-note">Its source is gone now.</div>${again}${when}`;
188
+ const counts = now.diff?.text ? html`<div class="ws-peek-h"><span class="ws-peek-t">${readStale(r) ? `${data.part?.label || "It"}: ${BOTH_CHANGED}` : `${data.part?.label || "It"} changed after chi's prompt was built`}</span><span class="ws-peek-c">${diffCounts(now.diff)}</span></div>` : nothing;
189
+ return html`${counts}<div class="ws-peek-b">${diffTemplate(now.diff)}</div>${again}${when}`;
190
+ }
191
+
192
+ // An edited tab's body: chi's own change (the &now=1 answer: sent → now),
193
+ // and the line that says both facts; a remove, its one line.
194
+ function editedBody(data, r, key) {
195
+ if (!data.sent) return null;
196
+ const { change, tag } = ownOf(r, key);
197
+ const at = tag ? ` at ${tag}` : "";
198
+ // The words follow chi's call, as the row's do: a remove says removed; an edit or a write says edited (an
199
+ // AGENTS.md chi's write emptied reads gone, and is still chi's edit).
200
+ if (change?.op === "remove") {
201
+ return html`<div class="ws-peek-copy">chi removed it${at}; its prompt still sends it until it is next built.</div>`;
202
+ }
203
+ const now = data.now;
204
+ if (!now) return html`<div class="ws-peek-note">Couldn't fetch its source now.</div>`;
205
+ const head = html`<div class="ws-peek-h"><span class="ws-peek-t">chi edited ${data.part?.label || "it"}${at}</span>${now.diff?.text ? html`<span class="ws-peek-c">${diffCounts(now.diff)}</span>` : nothing}</div>`;
206
+ const gets = PROMPT_GETS[data.rebuild] ? ` ${PROMPT_GETS[data.rebuild]}` : "";
207
+ const body = now.gone ? html`<div class="ws-peek-note">Its source is gone now.</div>` : html`<div class="ws-peek-b">${diffTemplate(now.diff)}</div>`;
208
+ return html`${head}${body}<div class="ws-peek-copy">${STILL_SENT}${gets}</div>`;
209
+ }
210
+
211
+ function partBody(key, r) {
212
+ if (failed.has(key)) return html`<div class="ws-peek-note">Couldn't load the prompt part.</div>`;
213
+ const data = answers.get(key);
214
+ if (!data) return html`<div class="ws-peek-note">Loading…</div>`;
215
+ const changed = nowOf(key) ? nowBody(data, r, nowOf(key)) : editedOf(key) ? editedBody(data, r, editedOf(key)) : null;
216
+ if (changed) return changed;
217
+ if (Array.isArray(data.tools)) return html`<div class="ws-peek-b">${toolsTemplate(data.tools)}</div>`;
218
+ if (data.sent) return html`<div class="ws-peek-b">${bodyTemplate(data.sent.text, data.part, md)}</div>${leadTemplate(data.sent.lead)}`;
219
+ const now = data.now?.gone ? html`<div class="ws-peek-note">Its source is gone now.</div>`
220
+ : data.now ? html`<div class="ws-peek-b">${bodyTemplate(data.now.text, data.part, md)}</div>` : nothing;
221
+ return html`<div class="ws-peek-note">${data.note || ""}</div>${now}`;
222
+ }
223
+
224
+ const peek = {
225
+ // +id+'s row opened, or closed when it was. +read+: the row's item has
226
+ // a read to peek at (the item peek's tab, first), +item+ its id there
227
+ // (working_set.js steerId: the timeline's way in).
228
+ toggle(id, r, { read = false, item = null } = {}) {
229
+ if (openId === id) close();
230
+ else if (!holdsOf(r, read).length) return;
231
+ else {
232
+ if (openId) close();
233
+ if (itemPeek?.any()) itemPeek.close();
234
+ openId = id;
235
+ itemId = item;
236
+ row = r;
237
+ show(firstOf(holdsOf(r, read)));
238
+ }
239
+ onChange();
240
+ },
241
+ isOpen: (id) => openId === id,
242
+ any: () => openId !== null,
243
+ close,
244
+ // A tab of the open row chosen.
245
+ tab(key) {
246
+ if (!openId || key === tab) return;
247
+ show(key);
248
+ onChange();
249
+ },
250
+ // The peek under +r+ (the open row); +read+: its item has a read, +readTag+
251
+ // its step tag ("t1·s1").
252
+ template(r, { read = false, readTag = "" } = {}) {
253
+ const holds = holdsOf(r, read);
254
+ const current = holds.includes(tab) ? tab : holds[0];
255
+ // A tab gone (its row's states changed): the one shown instead is asked for, never left loading.
256
+ if (current !== tab && current !== "read") {
257
+ tab = current;
258
+ load(current);
259
+ }
260
+ const tabs = holds.length > 1 ? html`<div class="ws-tabs" role="tablist">${holds.map((key) => {
261
+ const own = editedOf(key) ? ownOf(r, editedOf(key)) : null;
262
+ const words = key === "read" ? `read${readTag ? ` · ${readTag}` : ""}` : nowOf(key) ? "now · changed"
263
+ : own ? `${own.change?.op === "remove" ? "removed" : "edited"}${own.tag ? ` · ${own.tag}` : ""}`
264
+ : `${HOLD_WORDS[kindOf(key)] || "in the prompt"} · ${tokensText(r.partSizes?.[r.partKeys.indexOf(key)])}`;
265
+ const title = nowOf(key) ? (readStale(r) ? BOTH_CHANGED : "its source changed after chi's prompt was built")
266
+ : own ? "chi changed it itself: the new text is in its conversation" : nothing;
267
+ return html`<button type="button" class=${`ws-tab${key === current ? " on" : ""}${nowOf(key) ? " warn" : ""}`} title=${title} role="tab" aria-selected=${String(key === current)} @click=${() => peek.tab(key)}>${words}</button>`;
268
+ })}</div>` : nothing;
269
+ if (current === "read") return html`<div class="ws-peek ws-held" role="region" aria-label="What chi has">${tabs}${itemPeek ? itemPeek.template(r) : nothing}</div>`;
270
+ const data = answers.get(current);
271
+ const declared = Array.isArray(data?.tools) ? ` · ${data.tools.length} declared` : "";
272
+ const head = holds.length < 2 && (data?.sent || data?.tools) ? html`<div class="ws-peek-h"><span class="ws-peek-t">${SENT}${declared}</span></div>` : nothing;
273
+ return html`<div class="ws-peek ws-part-peek" role="region" aria-label="What chi was sent">${tabs}${head}${partBody(current, r)}</div>`;
274
+ },
275
+ };
276
+ return peek;
277
+ }
@@ -32,7 +32,9 @@ import { peekMarkdownTemplate, peekText, renderableEvent } from "./ws_markdown.j
32
32
  // step whose tool batch hasn't ended.
33
33
  const STEP_RUNNING = "chi read this in the step still running. It shows here when that step's tools finish.";
34
34
 
35
- // The popover's width while a row is peeked (it is 420 otherwise).
35
+ // The popover's width while a row is peeked. Kept for an older cached
36
+ // working_set_view.js, which imports it (the view is 520 wide always now):
37
+ // goes at the next release.
36
38
  export const PEEK_WIDTH = 520;
37
39
 
38
40
  // +session()+: the open session's id; +getItem(id, kind, key, opts)+: the item
@@ -27,6 +27,36 @@
27
27
  .ws-popover.sheet .ws-peek-f>button{flex:1;height:44px;text-align:center}
28
28
  .ws-popover.sheet .ws-peek-f>button+button{border-left:1px solid var(--border)}
29
29
 
30
+ /* The prompt peek (ws_part_peek.js): a "From the start" row's sent text,
31
+ the line chi adds before it folded, the tools' names and sizes, one tab
32
+ per hold. A held row's read tab is the item peek, drawn inside it. */
33
+ .ws-part-peek .ws-peek-b{padding:0}
34
+ .ws-part-peek .ws-peek-b .wsr-md{padding:8px 12px}
35
+ .ws-lead{margin:6px 12px 8px;border:1px dashed var(--border-strong);border-radius:6px;font-size:11.5px;color:var(--ws-muted)}
36
+ .ws-lead>summary{cursor:pointer;padding:4px 8px}
37
+ .ws-lead>pre{margin:0;padding:6px 8px;border-top:1px dashed var(--border-strong);font:11px ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;color:var(--text-2)}
38
+ .ws-tools{display:grid;grid-template-columns:1fr auto;gap:2px 12px;padding:8px 12px;max-height:220px;overflow:auto;font:11.5px ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--text-2)}
39
+ .ws-tool-k{color:var(--ws-faint);text-align:right;font-variant-numeric:tabular-nums}
40
+ .ws-tabs{display:flex;gap:2px;padding:4px 6px 0;border-bottom:1px solid var(--border)}
41
+ .ws-tab{padding:5px 10px;border:1px solid transparent;border-bottom:0;border-radius:6px 6px 0 0;background:transparent;color:var(--ws-muted);font:inherit;font-size:12px;cursor:pointer}
42
+ .ws-tab.on{color:var(--text);background:var(--bg-panel);border-color:var(--border);margin-bottom:-1px;padding-bottom:6px}
43
+ .ws-tab:hover:not(:disabled){filter:none}@media(hover:hover){.ws-tab:not(.on):hover{color:var(--text-2)}}
44
+ .ws-held>.ws-peek{margin:0;border:0;border-radius:0}
45
+ /* A prompt row whose source changed since chi was sent it, and its now tab. */
46
+ .ws-row .st.ws-pstale{color:var(--warn-text)}
47
+ .ws-tab.warn,.ws-tab.warn.on{color:var(--warn-text)}
48
+ @media(hover:hover){.ws-tab.warn:not(.on):hover{color:var(--warn-bright)}}
49
+ /* A prompt row whose source chi changed itself: "edited" in the plain secondary colour (not the warn one); a
50
+ phone's sheet drops its part words (D7), and a part row keeps "edited" where it drops its sub text. The
51
+ peek's copy lines under the diff: when chi gets the new text, and (warn) chi's edit it changed again after. */
52
+ .ws-row .st.ws-pedited{color:var(--text-2)}
53
+ .ws-popover.sheet .ws-pwords{display:none}
54
+ .ws-popover.sheet .ws-row.part .st.ws-pedited{display:block}
55
+ .ws-peek-copy{padding:7px 12px 9px;border-top:1px solid var(--border);font-size:12px;line-height:1.45;color:var(--text-2)}
56
+ .ws-peek-copy.warn{color:var(--warn-text)}
57
+ .ws-peek-copy.warn+.ws-peek-copy{border-top:0;padding-top:0}
58
+ .ws-popover.sheet .ws-tabs{flex-wrap:wrap}
59
+
30
60
  /* A tool row's way in. */
31
61
  .activity-ws{flex:none;padding:0 6px;border:1px solid var(--ws-act-border);border-radius:4px;background:transparent;font-size:11px;line-height:16px;color:var(--ws-muted);cursor:pointer;opacity:0}
32
62
  .activity-row:hover .activity-ws,.activity-row:focus-within .activity-ws{opacity: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)
@@ -266,7 +266,7 @@ module Samagotchi
266
266
  # @return [Array, nil] the response, or nil to go on
267
267
  def turn_refusal(id, body, prompt, images)
268
268
  vision = body["check_vision"] == true && !images.empty?
269
- return nil unless vision || App::CLI_SEND_IDS.include?(body["client_id"])
269
+ return nil unless vision || ClientId.parent_line?(body["client_id"])
270
270
 
271
271
  session = @session_class.load(id, state_dir: default_state_dir)
272
272
  refused = parent_gate(prompt, client_id: body["client_id"], values: [session.parent_answers])
@@ -34,10 +34,6 @@ module Samagotchi
34
34
  # What a continue takes from the previous link: refused beside it.
35
35
  CONTINUE_TAKES = %w[dir llm_context thinking settings toolkit tools no_tools parent_answers].freeze
36
36
 
37
- # chi send's client ids: its lines are checked as chi send checks them
38
- # (#parent_gate).
39
- CLI_SEND_IDS = [ClientId::CLI_SEND, ClientId::CLI_ANSWER].freeze
40
-
41
37
  private
42
38
 
43
39
  def handle_create(req)
@@ -91,11 +87,19 @@ module Samagotchi
91
87
  parent_answers, error = request_parent_answers(body["parent_answers"])
92
88
  return error if error
93
89
 
90
+ # driver: the agent (agent:<name>) the owner names its driver (chi
91
+ # send --new --driver); none: its creator when that is an agent.
92
+ driver = body["driver"]
93
+ unless driver.nil? || (ClientId.agent?(driver) && ClientId.agent(ClientId.agent_name(driver)) == driver)
94
+ return error_response(400, "invalid_driver", "driver is an agent's id: agent:<name>")
95
+ end
96
+
94
97
  model = (body["model"] || body["model_name"]).to_s.strip
95
98
  refused = create_refusal(body, idle ? body["preview"] : prompt, values: [parent_answers], model: model)
96
99
  return refused if refused
97
100
 
98
101
  folder = { working_directory: dir || start_dir }
102
+ folder[:driver] = driver if driver
99
103
  # model: the model the session starts on (the start page's picker,
100
104
  # spelled as GET /api/models lists it); blank means the default.
101
105
  folder[:model_name] = model unless model.empty?
@@ -178,7 +182,7 @@ module Samagotchi
178
182
  # for #create_refusal; nil when the previous link isn't there
179
183
  # (continue_from says so).
180
184
  def continue_refusal(given, body, line, model:)
181
- return nil unless body["check_vision"] == true || CLI_SEND_IDS.include?(body["client_id"])
185
+ return nil unless body["check_vision"] == true || ClientId.parent_line?(body["client_id"])
182
186
 
183
187
  previous = Session.load(SessionChain.resolve(given, state_dir: default_state_dir), state_dir: default_state_dir)
184
188
  create_refusal(body, line, values: [previous.parent_answers], model: model, previous: previous)
@@ -220,9 +224,9 @@ module Samagotchi
220
224
  # @return [Array, nil] the response, or nil to go on
221
225
  def parent_gate(line, client_id:, values:)
222
226
  line = line.to_s
223
- return nil unless CLI_SEND_IDS.include?(client_id)
227
+ return nil unless ClientId.parent_line?(client_id)
224
228
 
225
- if client_id == ClientId::CLI_ANSWER && TurnFlow.continue_yes?(line) &&
229
+ if (client_id == ClientId::CLI_ANSWER || ClientId.agent?(client_id)) && TurnFlow.continue_yes?(line) &&
226
230
  (refusal = SendCommand::ParentGate.continue_refusal_for(values))
227
231
  return error_response(403, "parent_continue_refused", refusal)
228
232
  end