samagotchi 0.101.0 → 0.103.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 (111) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +67 -1
  3. data/bin/chi +31 -196
  4. data/docs/architecture.md +62 -6
  5. data/docs/cli.md +154 -7
  6. data/docs/configuration.md +32 -5
  7. data/docs/guardrails.md +2 -1
  8. data/docs/internals/bundles.md +1 -1
  9. data/docs/internals/engine.md +1 -1
  10. data/docs/internals/llm-context-forget.md +25 -1
  11. data/docs/internals/prompt-caching.md +8 -1
  12. data/docs/internals/remote-sessions.md +303 -0
  13. data/docs/internals/working-set.md +174 -15
  14. data/docs/plugins.md +32 -5
  15. data/docs/sessions.md +38 -14
  16. data/docs/sub-agent.md +8 -0
  17. data/docs/testing.md +7 -0
  18. data/lib/samagotchi/answer_command.rb +27 -25
  19. data/lib/samagotchi/bridge/turn_accumulator.rb +16 -0
  20. data/lib/samagotchi/bridge.rb +33 -7
  21. data/lib/samagotchi/bridge_client/event_stream.rb +81 -12
  22. data/lib/samagotchi/bridge_client/stream_request.rb +77 -0
  23. data/lib/samagotchi/bridge_client.rb +22 -38
  24. data/lib/samagotchi/bundle_command/check.rb +5 -1
  25. data/lib/samagotchi/bundle_command/try/command.rb +6 -6
  26. data/lib/samagotchi/bundle_command/try/sandbox.rb +3 -3
  27. data/lib/samagotchi/bundle_command.rb +4 -4
  28. data/lib/samagotchi/bundles/claude-peer/manifest.yml +2 -2
  29. data/lib/samagotchi/bundles/claude-peer/scripts/pair +30 -1
  30. data/lib/samagotchi/bundles/codex-peer/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/codex-peer/scripts/pair +49 -4
  32. data/lib/samagotchi/bundles/guardrails/guardrails/rules.yml +7 -4
  33. data/lib/samagotchi/bundles/guardrails/manifest.yml +1 -1
  34. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  35. data/lib/samagotchi/chi_invocation.rb +43 -0
  36. data/lib/samagotchi/cli/command.rb +3 -2
  37. data/lib/samagotchi/cli/flags.rb +5 -0
  38. data/lib/samagotchi/cli/parent_wait.rb +22 -13
  39. data/lib/samagotchi/commands/registry.rb +12 -1
  40. data/lib/samagotchi/config.rb +89 -53
  41. data/lib/samagotchi/context_command.rb +80 -73
  42. data/lib/samagotchi/engine.rb +138 -15
  43. data/lib/samagotchi/idle_recap.rb +7 -1
  44. data/lib/samagotchi/idle_scheduler.rb +16 -1
  45. data/lib/samagotchi/kernel_loop.rb +13 -1
  46. data/lib/samagotchi/launch_mode.rb +22 -0
  47. data/lib/samagotchi/llm_context_edit.rb +32 -10
  48. data/lib/samagotchi/llm_context_forget.rb +24 -8
  49. data/lib/samagotchi/llm_context_view.rb +19 -7
  50. data/lib/samagotchi/memory_bundle/installer.rb +2 -0
  51. data/lib/samagotchi/memory_bundle/manifest.rb +13 -2
  52. data/lib/samagotchi/message_parts.rb +8 -3
  53. data/lib/samagotchi/note_command.rb +8 -7
  54. data/lib/samagotchi/parent_report.rb +55 -43
  55. data/lib/samagotchi/plugin/context.rb +2 -2
  56. data/lib/samagotchi/prompt.rb +1 -1
  57. data/lib/samagotchi/recap_command.rb +68 -0
  58. data/lib/samagotchi/recap_setup.rb +27 -14
  59. data/lib/samagotchi/remote_command.rb +170 -0
  60. data/lib/samagotchi/remotes.rb +130 -0
  61. data/lib/samagotchi/run_options.rb +233 -0
  62. data/lib/samagotchi/send_command/busy.rb +58 -0
  63. data/lib/samagotchi/send_command/parent_gate.rb +23 -10
  64. data/lib/samagotchi/send_command/wait_target.rb +16 -3
  65. data/lib/samagotchi/send_command.rb +186 -118
  66. data/lib/samagotchi/session.rb +48 -16
  67. data/lib/samagotchi/session_access/contract.rb +129 -0
  68. data/lib/samagotchi/session_access/dispatch.rb +133 -0
  69. data/lib/samagotchi/session_access/http_transport.rb +109 -0
  70. data/lib/samagotchi/session_access/local.rb +349 -0
  71. data/lib/samagotchi/session_access/remote.rb +638 -0
  72. data/lib/samagotchi/session_access/web_bridge_client.rb +181 -0
  73. data/lib/samagotchi/session_access.rb +141 -0
  74. data/lib/samagotchi/session_archive_command.rb +9 -5
  75. data/lib/samagotchi/session_commands.rb +53 -6
  76. data/lib/samagotchi/session_config.rb +411 -0
  77. data/lib/samagotchi/session_delete_command.rb +8 -4
  78. data/lib/samagotchi/session_manager.rb +7 -2
  79. data/lib/samagotchi/session_setup.rb +15 -10
  80. data/lib/samagotchi/sessions_command.rb +42 -16
  81. data/lib/samagotchi/terminal_ui/attach_launcher.rb +54 -18
  82. data/lib/samagotchi/terminal_ui/attach_link.rb +104 -0
  83. data/lib/samagotchi/terminal_ui/attached_loop.rb +82 -76
  84. data/lib/samagotchi/terminal_ui/formatting.rb +10 -3
  85. data/lib/samagotchi/terminal_ui/local_link.rb +130 -0
  86. data/lib/samagotchi/terminal_ui/version_lines.rb +5 -3
  87. data/lib/samagotchi/terminal_ui.rb +8 -6
  88. data/lib/samagotchi/testing/bundle.rb +3 -2
  89. data/lib/samagotchi/title_command.rb +9 -11
  90. data/lib/samagotchi/version.rb +1 -1
  91. data/lib/samagotchi/web/app.rb +387 -79
  92. data/lib/samagotchi/web/public/app.js +2 -0
  93. data/lib/samagotchi/web/public/commands.js +8 -2
  94. data/lib/samagotchi/web/public/data.js +6 -4
  95. data/lib/samagotchi/web/public/index.html +37 -3
  96. data/lib/samagotchi/web/public/stage_frame.js +7 -2
  97. data/lib/samagotchi/web/public/stage_view.js +3 -2
  98. data/lib/samagotchi/web/public/stream_handlers.js +7 -1
  99. data/lib/samagotchi/web/public/turn_html.js +5 -0
  100. data/lib/samagotchi/web/public/working_set.js +247 -24
  101. data/lib/samagotchi/web/public/working_set_rail.js +39 -12
  102. data/lib/samagotchi/web/public/working_set_view.js +198 -25
  103. data/lib/samagotchi/web/session_access_routes.rb +343 -0
  104. data/lib/samagotchi/worker.rb +9 -6
  105. data/lib/samagotchi/worker_sidecar.rb +12 -5
  106. data/lib/samagotchi/working_set.rb +132 -20
  107. data/lib/samagotchi/working_set_command.rb +222 -0
  108. data/lib/samagotchi/working_set_pin.rb +34 -0
  109. data/lib/samagotchi/working_set_steer.rb +414 -0
  110. metadata +23 -2
  111. data/lib/samagotchi/bundle_session_settings.rb +0 -251
@@ -7,8 +7,31 @@
7
7
  // so nothing restarts; a fold fades the absorbed lines out in place and the
8
8
  // lines below slide up once (each line sits at its slot by a transform).
9
9
  // Collapsed (kept per browser), it is its head line only, with the newest
10
- // entry ticking through it.
11
- import { BUDGETS, ariaLabel, fold, isFresh, labelTitle, nextSettle, shown } from "./working_set.js";
10
+ // entry ticking through it. Read-only: steering is the expanded view's; a
11
+ // line with a pending op (a /working-set line queued for the turn's end) is
12
+ // dashed, its title saying what applies next turn; an item added that the
13
+ // turn's set doesn't hold is a dashed `+ name · next turn` line of its own.
14
+
15
+ // A pending op's words on a line's title.
16
+ const PENDING_WORDS = { drop: "drops", undrop: "comes back", pin: "pinned", unpin: "unpinned", add: "read again" };
17
+
18
+ // The pending ops of +label+'s members (+pending+: working_set.js
19
+ // pendingSteers' Map), as "drops next turn" words; "" when none.
20
+ export function pendingText(label, pending) {
21
+ if (!pending?.size) return "";
22
+ const ops = [...new Set(label.members.map((m) => pending.get(steerId(m))).filter(Boolean))];
23
+ return ops.length ? `${ops.map((op) => PENDING_WORDS[op]).join(", ")} next turn` : "";
24
+ }
25
+ import { addedItems, BUDGETS, ariaLabel, fold, GLYPHS, isFresh, labelTitle, nextSettle, shown, steerId } from "./working_set.js";
26
+
27
+ // The pending adds +items+ doesn't hold as lines: `+ name · next turn`.
28
+ export function addLabels(items, pending) {
29
+ if (!pending?.size) return [];
30
+ return addedItems(pending, items).map((item) => ({
31
+ id: `add:${steerId(item)}`, type: "leaf", kind: item.kind, glyph: "+", text: `${GLYPHS[item.kind] ? `${GLYPHS[item.kind]} ` : ""}${item.kind === "file" ? item.path.split("/").pop() : item.label} · next turn`,
32
+ n: 1, edited: 0, cut: 0, state: "live", members: [], added: true,
33
+ }));
34
+ }
12
35
  import { readStored, writeStored } from "./storage.js";
13
36
  import { reducedMotion } from "./stage_frame.js";
14
37
 
@@ -157,16 +180,17 @@ export function createWorkingSetRail({ live, stage, onOpen, onChange }) {
157
180
 
158
181
  // A state (the server's: stale faded, forgotten struck) is a class and a
159
182
  // mark on the same line: it never refolds and never moves a line.
160
- function fillLine(node, label, fresh) {
183
+ function fillLine(node, label, fresh, pend) {
161
184
  const state = label.state && label.state !== "live" ? ` ${label.state}` : "";
162
- node.className = `ws-item ${label.kind}${label.type !== "leaf" ? " group" : ""}${fresh ? " fresh" : ""}${state}`;
185
+ node.className = `ws-item ${label.kind}${label.type !== "leaf" ? " group" : ""}${fresh ? " fresh" : ""}${state}${pend ? " pending" : ""}`;
163
186
  const [k, t, n, e, c] = node.children;
164
187
  k.textContent = label.glyph || "";
165
188
  t.textContent = label.text;
166
189
  n.textContent = label.count ? `· ${label.count}` : "";
167
190
  e.textContent = label.edited ? (label.type === "leaf" ? "✎" : `✎${label.edited}`) : "";
168
191
  c.textContent = label.type !== "leaf" && label.cut ? `✂${label.cut}` : "";
169
- node.title = labelTitle(label);
192
+ if (label.added) node.title = "added: the model reads it at the next turn's start";
193
+ else node.title = pend ? `${labelTitle(label)}\n${pend}` : labelTitle(label);
170
194
  }
171
195
 
172
196
  // A line at its slot. A new line is placed before it is in the page (no
@@ -185,8 +209,9 @@ export function createWorkingSetRail({ live, stage, onOpen, onChange }) {
185
209
  }
186
210
 
187
211
  // Draws +items+ (the running turn's, working_set.js itemsOfTurn); +ctxPct+
188
- // the ring's value (null: no ring yet).
189
- function draw(items, { ctxPct = null, now = Date.now() } = {}) {
212
+ // the ring's value (null: no ring yet); +pending+ the queued steer ops
213
+ // (working_set.js pendingSteers).
214
+ function draw(items, { ctxPct = null, now = Date.now(), pending = null } = {}) {
190
215
  // A turn joined mid-way (a reload, another tab): what is there already
191
216
  // is not new.
192
217
  for (const item of items) {
@@ -194,7 +219,8 @@ export function createWorkingSetRail({ live, stage, onOpen, onChange }) {
194
219
  if (!seen.has(id)) seen.set(id, first ? -Infinity : now);
195
220
  }
196
221
  first = false;
197
- const budget = form() === "rail" ? BUDGETS.rail : BUDGETS.row;
222
+ const adds = addLabels(items, pending);
223
+ const budget = Math.max(1, (form() === "rail" ? BUDGETS.rail : BUDGETS.row) - adds.length);
198
224
  const folded = fold(items, budget, { kept });
199
225
  kept = folded.groups;
200
226
  const view = shown(folded.labels, budget);
@@ -222,8 +248,9 @@ export function createWorkingSetRail({ live, stage, onOpen, onChange }) {
222
248
 
223
249
  // The lines, by key: an unchanged one is left alone.
224
250
  const animate = !reducedMotion();
225
- const lines = view.labels.map((label) => ({ id: label.id, label, fresh: freshOf(label) }));
251
+ const lines = view.labels.map((label) => ({ id: label.id, label, fresh: freshOf(label), pend: pendingText(label, pending) }));
226
252
  if (view.more) lines.push({ id: "more", more: view.more });
253
+ for (const label of adds) lines.push({ id: label.id, label, fresh: false, pend: "added next turn" });
227
254
  const ids = new Set(lines.map((l) => l.id));
228
255
  for (const [id, entry] of nodes) {
229
256
  if (ids.has(id)) continue;
@@ -235,7 +262,7 @@ export function createWorkingSetRail({ live, stage, onOpen, onChange }) {
235
262
  }
236
263
  lines.forEach((line, i) => {
237
264
  let entry = nodes.get(line.id);
238
- const key = JSON.stringify(line.more ? ["more", line.more] : [line.id, line.label.text, line.label.count || "", line.label.n, line.label.edited, line.label.cut || 0, line.label.state || "live", line.fresh]);
265
+ const key = JSON.stringify(line.more ? ["more", line.more] : [line.id, line.label.text, line.label.count || "", line.label.n, line.label.edited, line.label.cut || 0, line.label.state || "live", line.fresh, line.pend]);
239
266
  if (!entry) {
240
267
  const node = line.more ? el("div", "ws-more") : lineNode(line.label);
241
268
  entry = { node, key: null, slot: -1 };
@@ -247,14 +274,14 @@ export function createWorkingSetRail({ live, stage, onOpen, onChange }) {
247
274
  if (entry.key !== key) {
248
275
  entry.key = key;
249
276
  if (line.more) entry.node.textContent = `+ ${line.more} more`;
250
- else fillLine(entry.node, line.label, line.fresh);
277
+ else fillLine(entry.node, line.label, line.fresh, line.pend);
251
278
  }
252
279
  if (entry.slot !== i) {
253
280
  place(entry.node, i);
254
281
  entry.slot = i;
255
282
  }
256
283
  });
257
- rail.classList.toggle("empty", !items.length);
284
+ rail.classList.toggle("empty", !items.length && !adds.length);
258
285
  scheduleSettle(now);
259
286
  }
260
287
 
@@ -5,9 +5,29 @@
5
5
  // and the step tags' jump to a call. The rail is working_set_rail.js's; the
6
6
  // rules are working_set.js's.
7
7
  //
8
+ // Steering (drop / undrop, pin / unpin, + add): the list's rows and groups post
9
+ // `/working-set drop|undrop|pin|unpin|add KEY…` lines (+sendLine+, the session
10
+ // command route). The list's foot (the sheet's last row) adds what the user
11
+ // types (a path, memory:NAME or a URL); a stale or forgotten row offers
12
+ // refresh (an add of it). An add is pending until the next turn sends its
13
+ // note: the server's snapshot lists it (adds) between turns, a queued line
14
+ // mid-turn; an added item the set doesn't hold yet is a `+ name` row with
15
+ // `reads next turn` and an undo (unadd). Between turns one runs at once: its command_ran re-reads the
16
+ // conversation and the re-emitted set strikes the item `dropped` (or marks
17
+ // it pinned). A row offers pin only when the session's strategy has the
18
+ // forget layer (forgetOn: pins guard against the model's forget); a pinned
19
+ // row shows its 📌 and unpin under any strategy, since its drop waits for
20
+ // the unpin. While a
21
+ // turn runs it is queued: its command_queued (waits: "turn_end"; any
22
+ // client's, and the snapshot's replay after a reload) makes it pending, a
23
+ // dashed-warn row with a pill and an undo (the inverse line, queued after
24
+ // it), until its command_ran. On a phone's sheet a tap on a row opens its
25
+ // action strip under it, one at a time.
26
+ //
8
27
  // The server's projection (WorkingSet: a :working_set_updated event, a GET
9
28
  // working_set when a session's set is seeded and when the expanded view
10
- // opens) is one session-wide snapshot, the newer by its at kept; every form
29
+ // opens) is one session-wide snapshot: an event always taken, a GET's
30
+ // answer unless an event overtook it (working_set.js newerSnapshot); every form
11
31
  // overlays its state and tokens on the rows' items by key (working_set.js
12
32
  // overlay), so a state is the item's now, not then. A new snapshot redraws
13
33
  // them all: the chip, the open popover, the footprints in place and the rail
@@ -21,8 +41,9 @@ import { html, nothing, render, svg } from "./vendor/lit-html.js";
21
41
  import { createChipPopover } from "./chip_popover.js";
22
42
  import { showRow } from "./refs.js";
23
43
  import {
24
- BUDGETS, fold, footprint, footprintText, GLYPHS, isFresh, itemsOfTurn, labelText, labelTitle, newerSnapshot, opsText, overlay,
25
- sessionItems, stepRange, stepTag, tokensText,
44
+ addedItems, addLine, BUDGETS, dropRefusal, fold, footprint, footprintText, forgetOn, GLYPHS, INVERSE, isFresh, itemsOfTurn, labelText,
45
+ labelTitle, newerSnapshot, opsText, overlay, parseSteerLine, pendingSteers, pinnable, refreshable, serverAddIds, sessionItems, STEER_OPS,
46
+ steerId, steerLine, stepRange, stepTag, tokensText, undroppable,
26
47
  } from "./working_set.js";
27
48
 
28
49
  // The popover's files fold to this many lines (groups open in place, one at
@@ -83,7 +104,7 @@ export function footprintTemplate(items, ordinal) {
83
104
  const sep = html` <span class="sep">·</span> `;
84
105
  const parts = fp.labels.map((l, i) => html`${i ? sep : nothing}<span class=${`l ${l.kind}${l.state && l.state !== "live" ? ` ${l.state}` : ""}`} title=${labelTitle(l)}>${l.glyph ? html`<span class="k">${l.glyph}</span> ` : nothing}${labelText({ ...l, glyph: "" })}</span>${footTag(l)}`);
85
106
  const text = footprintText(items, BUDGETS.footprint);
86
- return html`<div class="ws-foot" role="button" tabindex="0" data-ws-turn=${ordinal} data-ws-sig=${footSig(items)} aria-label=${`Working set of this turn: ${text.replace(/^touched /, "")}. Open the list.`}><span class="w">touched</span> ${parts}${fp.tail ? html`${sep}<span class="w">${fp.tail}</span>` : nothing}${fp.edited ? html`${sep}<span class="e">edited ${fp.edited}</span>` : nothing}${fp.forgotten ? html`${sep}<span class="f">${fp.forgotten} forgotten</span>` : nothing}</div>`;
107
+ return html`<div class="ws-foot" role="button" tabindex="0" data-ws-turn=${ordinal} data-ws-sig=${footSig(items)} aria-label=${`Working set of this turn: ${text.replace(/^touched /, "")}. Open the list.`}><span class="w">touched</span> ${parts}${fp.tail ? html`${sep}<span class="w">${fp.tail}</span>` : nothing}${fp.edited ? html`${sep}<span class="e">edited ${fp.edited}</span>` : nothing}${fp.forgotten ? html`${sep}<span class="f">${fp.forgotten} forgotten</span>` : nothing}${fp.dropped ? html`${sep}<span class="f">${fp.dropped} dropped</span>` : nothing}</div>`;
87
108
  }
88
109
 
89
110
  // What a footprint shows that can change after it is drawn: its items'
@@ -122,7 +143,10 @@ function memberName(item, group) {
122
143
  // +infoEl+: the session bar's line (the chip's popover is delegated there);
123
144
  // +onChange()+: the chip's count or dot changed (app.js updateInfoBar).
124
145
  // +getWorkingSet(id)+: the server's projection (data.js; null: none asked).
125
- export function createWorkingSet({ historyEl, stageRoot = () => null, state, session = () => null, infoEl, onChange = () => {}, getWorkingSet = null, doc = document }) {
146
+ // +sendLine(line)+: posts a steer line as the session's command (null: no
147
+ // steering, the list reads only).
148
+ export function createWorkingSet({ historyEl, stageRoot = () => null, state, session = () => null, infoEl, onChange = () => {}, getWorkingSet = null,
149
+ sendLine = null, doc = document }) {
126
150
  // The finished turns' sets ({items, prompt}), the running turn's (null:
127
151
  // none), the rail's first-sight times (its fresh cue), the session count
128
152
  // at the last open (the chip's dot).
@@ -135,9 +159,16 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
135
159
  let view = { scope: "session", turn: null };
136
160
  let openGroup = null;
137
161
  // The server's snapshot ({items, at}) and the session it is of; what
138
- // redraws the rail when it changes.
162
+ // redraws the rail when it changes. +events+ counts the events taken, so
163
+ // a GET knows whether one came while it was on its way.
139
164
  let server = null;
140
165
  let serverOf = null;
166
+ let events = 0;
167
+ // The steer lines queued for after the running turn, by command id, and
168
+ // the session they are of; the row whose action strip is open (a sheet).
169
+ const queued = new Map();
170
+ let queuedOf = null;
171
+ let stripOpen = null;
141
172
  const listeners = new Set();
142
173
  const lit = (items) => overlay(items, server);
143
174
 
@@ -173,13 +204,69 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
173
204
  if (opening) fetchServer();
174
205
  },
175
206
  onClose: () => { openGroup = null; onChange(); },
207
+ // The foot's + add (the popover's submit): one KEY as typed (quoted
208
+ // when it has spaces).
209
+ onSubmit: (form) => {
210
+ if (!form?.matches?.(".ws-add")) return;
211
+ const input = form.querySelector(".ws-add-in");
212
+ const line = sendLine && addLine(input?.value);
213
+ if (!line) return;
214
+ input.value = "";
215
+ Promise.resolve(sendLine(line)).catch(() => {});
216
+ },
176
217
  });
177
218
 
178
- function rowTemplate(item, { session: inSession, group = null, now }) {
219
+ // The pending ops: the server's adds (made between turns), then the
220
+ // queued lines.
221
+ const pending = () => pendingSteers([...queued.values()], state().dir, serverAddIds(server));
222
+ // The pending adds the set doesn't hold yet, as rows.
223
+ const adding = (pend = pending()) => addedItems(pend, sessionSet().items, server, state().dir);
224
+
225
+ // A steer button: +op+ on +items+ ("undo" sends the inverse of a pending op).
226
+ function actButton(op, items, { label = op, title = "", disabled = false } = {}) {
227
+ // JSON: an id may hold spaces (a file under "my notes/").
228
+ const ids = JSON.stringify(items.map(steerId));
229
+ return html`<button type="button" class=${`ws-act-b ${op}`} data-ws="steer" data-op=${op} data-ids=${ids} title=${title} ?disabled=${disabled}>${label}</button>`;
230
+ }
231
+
232
+ // A pending op's pill.
233
+ const PILLS = { drop: "drops next turn", undrop: "back next turn", pin: "applies next turn", unpin: "applies next turn",
234
+ add: "reads next turn" };
235
+
236
+ // What a row offers: a pending op's pill and undo, an undrop, a drop (or
237
+ // why not), a pin or an unpin; nothing for an item no op applies to.
238
+ function rowActions(item, pend, forget) {
239
+ if (!sendLine) return { pill: nothing, buttons: nothing };
240
+ let op = pend.get(steerId(item));
241
+ // A drop queued for a pinned item: the worker refuses it (unpin it
242
+ // first), so it isn't pending; the row offers its greyed drop.
243
+ if (op === "drop" && item.pinned) op = undefined;
244
+ if (op) {
245
+ const when = op === "add" ? "the next turn's note asks the model to read it first" : "applies at the next turn's start";
246
+ const pill = html`<span class="ws-pend" title=${when}>${PILLS[op]}</span>`;
247
+ return { pill, buttons: actButton(INVERSE[op], [item], { label: "undo", title: `take back the queued ${op}` }) };
248
+ }
249
+ const undrop = actButton("undrop", [item], { title: "send it whole again from the next request (a cache break)" });
250
+ // Dropped, or a drop on some reads with nothing else of it sent (the
251
+ // model's layers stubbed the rest): undrop is all it offers.
252
+ if (item.state === "dropped" || (undroppable(item) && item.state === "forgotten")) return { pill: nothing, buttons: undrop };
253
+ const buttons = [];
254
+ const why = dropRefusal(item);
255
+ if (why !== null) buttons.push(actButton("drop", [item], { title: why || "send a stub instead of its reads from the next turn's start", disabled: !!why }));
256
+ if (item.pinned) buttons.push(actButton("unpin", [item], { title: "the model's forget_outputs may forget it again" }));
257
+ else if (forget && pinnable(item)) buttons.push(actButton("pin", [item], { title: "keep it from the model's forget_outputs (its later reads too)" }));
258
+ // A drop on some of its reads, others still sent: undrop takes it back.
259
+ if (undroppable(item)) buttons.push(undrop);
260
+ if (refreshable(item)) buttons.push(actButton("add", [item], { label: "refresh", title: "the next turn's note asks the model to read it again" }));
261
+ return { pill: nothing, buttons: buttons.length ? buttons : nothing };
262
+ }
263
+
264
+ function rowTemplate(item, { session: inSession, group = null, now, pend = new Map(), forget = false }) {
179
265
  const fresh = isFresh(seenAt(item), now);
180
266
  const tag = stepTag(item, { session: inSession });
181
- const words = `${opsText(item)}${fresh ? " · just now" : ""}`;
182
- const glyph = item.muted ? GLYPHS.muted : fresh ? "●" : GLYPHS[item.kind] || "";
267
+ // An added row's words: what it is (a phone's tap on them opens its strip).
268
+ const words = item.added ? "added" : `${opsText(item)}${fresh ? " · just now" : ""}`;
269
+ const glyph = item.added ? "+" : item.muted ? GLYPHS.muted : fresh ? "●" : GLYPHS[item.kind] || "";
183
270
  const name = memberName(item, group);
184
271
  const full = item.kind === "file" ? item.path || item.key : item.kind === "url" ? item.url || item.key : item.key;
185
272
  let nameEl;
@@ -201,7 +288,16 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
201
288
  const edited = item.kind === "file" && item.ops.includes("edit");
202
289
  const state = item.state && item.state !== "live" ? ` ${item.state}` : "";
203
290
  const tokens = tokensText(item.tokens);
204
- return html`<div class=${`ws-row ${item.kind}${fresh ? " fresh" : ""}${item.muted ? " muted" : ""}${group ? " member" : ""}${state}`}><span class="k">${glyph}</span>${nameEl}${edited ? html`<span class="e">✎</span>` : nothing}<span class="st">${words}</span>${tokens ? html`<span class="tk" title=${`about ${item.tokens} tokens of it are sent`}>${tokens}</span>` : nothing}${tagEl}</div>`;
291
+ const id = steerId(item);
292
+ const { pill, buttons } = rowActions(item, pend, forget);
293
+ const pin = item.pinned ? html`<span class="ws-pin" title="pinned: the model's forget_outputs refuses it">📌</span>` : nothing;
294
+ const isPending = pill !== nothing;
295
+ const strip = stripOpen === id && buttons !== nothing;
296
+ 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;
297
+ const row = html`<div class=${`ws-row ${item.kind}${item.added ? " added" : ""}${fresh ? " fresh" : ""}${item.muted ? " muted" : ""}${group ? " member" : ""}${state}${isPending ? " pending" : ""}${strip ? " strip-open" : ""}`} data-ws-id=${id}><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=${`about ${item.tokens} tokens of it are sent`}>${tokens}</span>` : nothing}${tagEl}${buttons !== nothing ? html`<span class="ws-act">${buttons}</span>` : nothing}</div>`;
298
+ // One template either way, so the tapped row stays the same node (a
299
+ // click outside the popover closes it).
300
+ return html`${row}${strip ? html`<div class="ws-strip">${buttons}${open}</div>` : nothing}`;
205
301
  }
206
302
 
207
303
  // A section's labels: leaves as rows, groups as an opener row and, open,
@@ -211,8 +307,11 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
211
307
  if (label.type === "leaf") return rowTemplate(label.members[0], opts);
212
308
  const open = openGroup === label.id;
213
309
  const state = label.state && label.state !== "live" ? ` ${label.state}` : "";
214
- const head = html`<button type="button" class=${`ws-row ws-group-head ${label.kind}${state}`} data-ws="group" data-id=${label.id} aria-expanded=${String(open)} title=${labelTitle(label)}><span class="k">${open ? "▾" : "▸"}</span><span class="t">${label.glyph ? `${label.glyph} ` : ""}${label.text}</span>${label.count ? html`<span class="n">· ${label.count}</span>` : nothing}${label.edited ? html`<span class="e">✎${label.edited}</span>` : nothing}${label.cut ? html`<span class="c" title=${`${label.cut} forgotten`}>✂${label.cut}</span>` : nothing}<span class="chev">${open ? "close" : "open"}</span></button>`;
215
- return html`${head}${open ? label.members.map((m) => rowTemplate(m, { ...opts, group: label })) : nothing}`;
310
+ const head = html`<button type="button" class=${`ws-row ws-group-head ${label.kind}${state}`} data-ws="group" data-id=${label.id} aria-expanded=${String(open)} title=${labelTitle(label)}><span class="k">${open ? "▾" : "▸"}</span><span class="t">${label.glyph ? `${label.glyph} ` : ""}${label.text}</span>${label.count ? html`<span class="n">· ${label.count}</span>` : nothing}${label.edited ? html`<span class="e">✎${label.edited}</span>` : nothing}${label.cut ? html`<span class="c" title=${`${label.cut} cut (forgotten or dropped)`}>✂${label.cut}</span>` : nothing}<span class="chev">${open ? "close" : "open"}</span></button>`;
311
+ // A group drops its members that can be, not pending already.
312
+ const droppable = sendLine ? label.members.filter((m) => dropRefusal(m) === "" && !opts.pend.has(steerId(m))) : [];
313
+ const act = droppable.length ? html`<span class="ws-act">${actButton("drop", droppable, { label: `drop ${droppable.length}`, title: "send stubs instead of their reads from the next turn's start" })}</span>` : nothing;
314
+ return html`<div class="ws-ghead">${head}${act}</div>${open ? label.members.map((m) => rowTemplate(m, { ...opts, group: label })) : nothing}`;
216
315
  });
217
316
  }
218
317
 
@@ -224,7 +323,9 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
224
323
  const files = set.items.filter((i) => i.kind === "file");
225
324
  const memories = set.items.filter((i) => i.kind === "memory");
226
325
  const urls = set.items.filter((i) => i.kind === "url");
227
- const opts = { session: inSession, now };
326
+ const pend = pending();
327
+ const forget = forgetOn(st.llmContext);
328
+ const opts = { session: inSession, now, pend, forget };
228
329
  const fileLabels = fold(files, POP_BUDGET).labels;
229
330
  // Memories are rows of their own; past the budget one group that opens.
230
331
  const memoryLabels = fold(memories, memories.length > POP_BUDGET ? 1 : Infinity).labels;
@@ -232,13 +333,17 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
232
333
  const memMeta = [`${memories.length - preloaded} used`, preloaded ? `${preloaded} preloaded` : "", set.muted.length ? `${set.muted.length} muted` : ""].filter(Boolean).join(" · ");
233
334
  const turnLabel = view.turn !== null && view.turn >= 0 ? `turn ${view.turn + 1}` : "this turn";
234
335
  const pct = Number.isFinite(st.ctxPct) ? ` · ctx ${Math.round(st.ctxPct)} %` : "";
235
- const empty = !set.items.length && !set.muted.length;
336
+ const added = sendLine ? adding(pend) : [];
337
+ const empty = !set.items.length && !set.muted.length && !added.length;
236
338
  const tpl = html`<div class="ctx-pop-head"><strong>working set</strong><span class="ws-scope" role="group" aria-label="Scope"><button type="button" class=${!inSession ? "on" : ""} aria-pressed=${String(!inSession)} data-ws="scope" data-scope="turn" ?disabled=${view.turn === null || view.turn < 0}>${turnLabel}</button><button type="button" class=${inSession ? "on" : ""} aria-pressed=${String(inSession)} data-ws="scope" data-scope="session">session</button></span><span class="ctx-pop-kind">${set.items.length} item${set.items.length === 1 ? "" : "s"}${pct}</span>${ringTemplate(st.ctxPct)}<button type="button" class="ctx-pop-close" data-act="close" aria-label="Close">×</button></div>
237
339
  ${empty ? html`<div class="ctx-pop-meta">Nothing yet: the files, memories and URLs ${inSession ? "this session's turns read" : "this turn reads"} show here.</div>` : nothing}
238
340
  ${files.length ? html`<div class="ctx-pop-meta">files · ${files.length}</div>${labelsTemplate(fileLabels, opts)}` : nothing}
239
341
  ${memories.length || set.muted.length ? html`<div class="ctx-pop-meta">memories${memMeta ? ` · ${memMeta}` : ""}</div>${labelsTemplate(memoryLabels, opts)}${set.muted.map((m) => rowTemplate(m, opts))}` : nothing}
240
342
  ${urls.length ? html`<div class="ctx-pop-meta">urls · ${urls.length}</div>${labelsTemplate(fold(urls, POP_BUDGET).labels, opts)}` : nothing}
241
- <div class="ctx-pop-meta ws-hint">A file opens its ref; a step tag goes to the call. Esc closes.</div>`;
343
+ ${added.length ? html`<div class="ctx-pop-meta">adding · ${added.length}</div>${added.map((it) => rowTemplate(it, opts))}` : nothing}
344
+ ${pend.size ? html`<div class="ws-pending" role="status"><span class="ws-pending-t">${pend.size} change${pend.size === 1 ? "" : "s"} pending<span class="ws-pending-when"> · apply at the next turn's start</span></span><button type="button" class="ws-act-b" data-ws="undo-all">undo all</button></div>` : nothing}
345
+ ${sendLine ? html`<form class="ws-add" data-ws="add-form"><input class="ws-add-in" type="text" name="key" placeholder="+ path, memory:NAME or URL" aria-label="Add to the working set: a path, memory:NAME or a URL" autocomplete="off" autocapitalize="off" spellcheck="false" enterkeyhint="go"><button type="submit" class="ws-act-b">add</button></form>` : nothing}
346
+ <div class="ctx-pop-meta ws-hint">A file opens its ref; a step tag goes to the call.${sendLine ? " Drop sends stubs instead of an item's reads from the next turn; add asks the model to read one first." : ""}${sendLine && forget ? " Pin keeps an item from the model's forget." : ""} Esc closes.</div>`;
242
347
  render(tpl, popover.pop);
243
348
  }
244
349
 
@@ -267,10 +372,37 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
267
372
  return [turn, step, row].every(Number.isInteger) ? { turn, step, row } : null;
268
373
  };
269
374
 
375
+ // Posts +op+ for the ids (the items' steer words, from the set).
376
+ function steer(op, ids) {
377
+ if (!sendLine || !ids.length) return;
378
+ const all = [...sessionSet().items, ...turnItems(view.turn), ...adding()];
379
+ const byId = new Map(all.map((it) => [steerId(it), it]));
380
+ const items = ids.map((id) => byId.get(id)).filter(Boolean);
381
+ if (items.length) Promise.resolve(sendLine(steerLine(op, items, state().dir))).catch(() => {});
382
+ }
383
+
270
384
  popover.pop.addEventListener("click", (e) => {
271
385
  const act = e.target.closest("[data-ws]");
386
+ // A sheet's row: a tap outside its links and buttons opens its strip.
387
+ if (!act && popover.pop.classList.contains("sheet")) {
388
+ const row = e.target.closest(".ws-row[data-ws-id]");
389
+ if (row && !e.target.closest("a, button, .ref")) {
390
+ stripOpen = stripOpen === row.dataset.wsId ? null : row.dataset.wsId;
391
+ draw();
392
+ popover.replace();
393
+ }
394
+ return;
395
+ }
272
396
  if (!act) return;
273
- if (act.dataset.ws === "jump") {
397
+ if (act.dataset.ws === "steer") {
398
+ steer(act.dataset.op, JSON.parse(act.dataset.ids || "[]"));
399
+ } else if (act.dataset.ws === "undo-all") {
400
+ const pend = pending();
401
+ for (const op of STEER_OPS) {
402
+ const ids = [...pend].filter(([, o]) => o === op).map(([id]) => id);
403
+ steer(INVERSE[op], ids);
404
+ }
405
+ } else if (act.dataset.ws === "jump") {
274
406
  const at = parseAt(act.dataset.at);
275
407
  if (at) jump(at);
276
408
  } else if (act.dataset.ws === "scope") {
@@ -312,6 +444,12 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
312
444
  if (popover.isOpen()) popover.refresh();
313
445
  }
314
446
 
447
+ // The pending ops changed: the list and the rail's marks.
448
+ function pendingChanged() {
449
+ changed();
450
+ for (const fn of listeners) fn();
451
+ }
452
+
315
453
  // The footprints on the page (the history's, the hand-off's) drawn again
316
454
  // in place when their items' states changed: the same node (its focus,
317
455
  // the popover's opener), its children and label replaced.
@@ -332,9 +470,9 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
332
470
  }
333
471
 
334
472
  // A newer server snapshot redraws every form; an older one (a GET that
335
- // answered after a newer event) is dropped.
336
- function takeServer(snapshot) {
337
- const next = newerSnapshot(server, snapshot);
473
+ // answered after a newer event) is dropped. +how+: newerSnapshot's.
474
+ function takeServer(snapshot, how) {
475
+ const next = newerSnapshot(server, snapshot, how);
338
476
  if (next === server) return;
339
477
  server = next;
340
478
  serverOf = session();
@@ -348,9 +486,10 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
348
486
  function fetchServer() {
349
487
  const id = session();
350
488
  if (!getWorkingSet || !id) return;
489
+ const asked = events;
351
490
  Promise.resolve()
352
491
  .then(() => getWorkingSet(id))
353
- .then((snapshot) => { if (session() === id) takeServer(snapshot); })
492
+ .then((snapshot) => { if (session() === id) takeServer(snapshot, { overtaken: events !== asked }); })
354
493
  .catch(() => {});
355
494
  }
356
495
 
@@ -360,21 +499,55 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
360
499
  seed(list) {
361
500
  turns = list.slice();
362
501
  live = null;
363
- if (popover.isOpen()) popover.close();
364
- // Another session's snapshot goes; the same session's (a resync)
365
- // stays until the newer one comes.
502
+ // The snapshot's replay (after this) brings the queued lines again.
503
+ queued.clear();
504
+ queuedOf = session();
505
+ stripOpen = null;
506
+ // Another session's snapshot goes; the same session's (a resync, after
507
+ // a steer from the list) stays until the newer one comes, and so does
508
+ // the open list.
366
509
  if (serverOf !== session()) {
510
+ if (popover.isOpen()) popover.close();
367
511
  server = null;
368
512
  serverOf = session();
513
+ } else if (popover.isOpen()) {
514
+ if (view.turn !== null && view.turn >= turns.length) view = { scope: "session", turn: turns.length - 1 };
515
+ popover.refresh();
369
516
  }
370
517
  openedCount = sessionSet().items.length;
371
518
  refreshFootprints();
372
519
  fetchServer();
373
520
  },
521
+ // The session's strategy changed (/llm-context's command_ran): the open
522
+ // list redraws, its pin buttons shown only under forget (forgetOn).
523
+ strategyChanged() {
524
+ if (popover.isOpen()) popover.refresh();
525
+ },
374
526
  // A :working_set_updated event's set ({items, at}).
375
- update(snapshot) { takeServer(snapshot); },
376
- // +fn()+ runs after each new server snapshot (the rail's redraw).
527
+ update(snapshot) {
528
+ events += 1;
529
+ takeServer(snapshot, { event: true });
530
+ },
531
+ // +fn()+ runs after each new server snapshot and each change of the
532
+ // pending ops (the rail's redraw).
377
533
  onServer(fn) { listeners.add(fn); },
534
+ // A command queued for after the running turn (its command_queued,
535
+ // waits "turn_end"): a steer line is pending until its command_ran.
536
+ commandQueued(event) {
537
+ if (queuedOf !== session()) {
538
+ queued.clear();
539
+ queuedOf = session();
540
+ }
541
+ if (event?.waits !== "turn_end" || !event.command_id || !parseSteerLine(event.line)) return;
542
+ queued.set(event.command_id, event.line);
543
+ pendingChanged();
544
+ },
545
+ // A command ran (or was dropped): its line is no longer pending.
546
+ commandRan(event) {
547
+ if (event?.command_id && queued.delete(event.command_id)) pendingChanged();
548
+ },
549
+ // The steer lines pending (for the specs and the rail).
550
+ pending: () => pending(),
378
551
  // The running turn's items (its model +turn+), its ordinal the next
379
552
  // turn's; the chip follows.
380
553
  liveItems(turn, prompt = "") {