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
@@ -236,6 +236,8 @@ const workingSet = view === "stage" && document.body.dataset.workingSet === "1"
236
236
  ? createWorkingSet({
237
237
  historyEl, stageRoot: () => turnDom.root, state: () => current, session: () => selected, infoEl: infoTextEl,
238
238
  onChange: () => updateInfoBar(), getWorkingSet,
239
+ // A drop or undrop from the list: the session's command, as typed.
240
+ sendLine: (line) => (selected ? sendCommand(selected, line, { clientId }) : null),
239
241
  })
240
242
  : null;
241
243
  document.body.classList.toggle("working-set", !!workingSet);
@@ -109,13 +109,19 @@ const WEB_LOCAL_REPLIES = {
109
109
  "/detach": "/detach: a terminal's command; close the tab to leave, the worker keeps running",
110
110
  "/exit": "/exit: close the tab to leave; stop in the session bar stops the worker",
111
111
  "/quit": "/quit: close the tab to leave; stop in the session bar stops the worker",
112
- "/recap": "/recap: not in the web yet; a recap shows here by itself when you come back to an idle session, and /recap in a terminal (chi --attach) makes one now",
112
+ "/recap": "/recap: not in the web yet; a recap shows here by itself when you come back to an idle session, and /recap in a terminal (chi --attach) makes one now. /recap on|off|default sets this session's recap here too",
113
113
  "/unqueue": "/unqueue: a terminal's command; here the × on a message queued for after the turn removes it",
114
114
  "/stats": "/stats: not in the web yet; each turn shows its time, the session bar the context use and speed (hover ctx for tokens and cost), and /stats in a terminal (chi --attach) has the rest",
115
115
  };
116
116
 
117
+ // The ones whose words after the name are the worker's (/recap off): the
118
+ // page answers only the bare name.
119
+ const WORKER_WITH_WORDS = new Set(["/recap"]);
120
+
117
121
  export function webLocalReply(text) {
118
- const name = String(text || "").trim().split(/\s+/)[0].toLowerCase();
122
+ const words = String(text || "").trim().split(/\s+/);
123
+ const name = words[0].toLowerCase();
124
+ if (WORKER_WITH_WORDS.has(name) && words.length > 1) return null;
119
125
  return WEB_LOCAL_REPLIES[name] || null;
120
126
  }
121
127
 
@@ -197,9 +197,10 @@ export function unarchiveSession(id, opts = {}) {
197
197
  return api(`/api/sessions/${encodeURIComponent(id)}/unarchive`, { method: "POST", body: JSON.stringify({}), ...opts });
198
198
  }
199
199
 
200
- // Deletes the session for good; the server stops a live worker first.
200
+ // Deletes the session for good; force=true has the server stop a live
201
+ // worker first (the page's confirm says so; without it, 409 worker_running).
201
202
  export function deleteSession(id, opts = {}) {
202
- return api(`/api/sessions/${encodeURIComponent(id)}`, { method: "DELETE", ...opts });
203
+ return api(`/api/sessions/${encodeURIComponent(id)}?force=true`, { method: "DELETE", ...opts });
203
204
  }
204
205
 
205
206
  // One EventSource listener per handler, named by the handler's key (the
@@ -298,8 +299,9 @@ export function openEvents(handlers = {}, opts = {}) {
298
299
  };
299
300
  }
300
301
 
301
- // A session's working set as the model has it (WorkingSet: {items, at}),
302
- // what the stage view's working set overlays on its rows (web.working_set).
302
+ // A session's working set as the model has it (WorkingSet: {items, at,
303
+ // running}), what the stage view's working set overlays on its rows
304
+ // (web.working_set).
303
305
  export function getWorkingSet(id, opts = {}) {
304
306
  return api(`/api/sessions/${encodeURIComponent(id)}/working_set`, opts);
305
307
  }
@@ -905,14 +905,16 @@ body.working-set .ts-live{position:relative;padding-right:264px}
905
905
  /* The server's states (WorkingSet): stale faded; forgotten struck, faint and faded (a group only when all its members are). The words are the popover's and the titles' (colour is never alone). */
906
906
  .ws-item.stale{opacity:.55}
907
907
  .ws-item.forgotten{opacity:.5}
908
- .ws-item.forgotten .t,.ws-row.forgotten .t,.ws-foot .l.forgotten{text-decoration:line-through;color:var(--text-faint)}
908
+ .ws-item.forgotten,.ws-item.dropped{opacity:.5}
909
+ .ws-item.forgotten .t,.ws-row.forgotten .t,.ws-foot .l.forgotten,.ws-item.dropped .t,.ws-row.dropped .t,.ws-foot .l.dropped{text-decoration:line-through;color:var(--text-faint)}
909
910
  .ws-row.stale .k,.ws-row.stale .t,.ws-foot .l.stale{opacity:.55}
910
- .ws-row.forgotten .k,.ws-row.forgotten .t,.ws-foot .l.forgotten{opacity:.5}
911
+ .ws-row.forgotten .k,.ws-row.forgotten .t,.ws-foot .l.forgotten,.ws-row.dropped .k,.ws-row.dropped .t,.ws-foot .l.dropped{opacity:.5}
911
912
  .ws-item.enter{animation:ws-in .2s ease}
912
913
  @keyframes ws-in{from{opacity:0}}
913
914
  .ws-item.leave,.ws-more.leave{opacity:0;pointer-events:none}
914
915
  /* Just entered (FLASH_MS): an accent dot for the glyph and a tint; it settles (the tint fades 800 ms). */
915
916
  .ws-item.fresh{background:var(--accent-tint)}
917
+ .ws-item.pending{outline:1px dashed var(--warn-border);outline-offset:-1px;background:var(--warn-bg)}
916
918
  .ws-item.fresh .k{font-size:0;display:flex;align-items:center;justify-content:center;height:var(--ws-line)}
917
919
  .ws-item.fresh .k::before{content:"";display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 2px var(--accent-ring)}
918
920
  .ws-more{padding-left:17px;font-family:ui-sans-serif,system-ui,sans-serif;font-size:11px;color:var(--text-faint);font-variant-numeric:tabular-nums}
@@ -972,7 +974,7 @@ button.ws-row:hover:not(:disabled){filter:none;background:var(--bg-hover)}
972
974
  .ws-row a.t:hover{text-decoration:underline}
973
975
  .ws-row .e{flex:none;color:var(--accent);font-weight:600}
974
976
  .ws-row .n{flex:none;color:var(--text-faint)}
975
- .ws-row .st{flex:none;margin-left:auto;font-family:ui-sans-serif,system-ui,sans-serif;font-size:11px;color:var(--text-faint)}
977
+ .ws-row .st{flex:0 4 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-left:auto;font-family:ui-sans-serif,system-ui,sans-serif;font-size:11px;color:var(--text-faint)}
976
978
  .ws-row .chev{flex:none;margin-left:auto;font-family:ui-sans-serif,system-ui,sans-serif;font-size:11px;color:var(--text-faint)}
977
979
  .ws-row .ws-step{flex:none}
978
980
  .ws-row .tk,.ws-row .c{flex:none;font-family:ui-sans-serif,system-ui,sans-serif;font-size:11px;color:var(--text-faint);font-variant-numeric:tabular-nums}
@@ -980,12 +982,44 @@ button.ws-row:hover:not(:disabled){filter:none;background:var(--bg-hover)}
980
982
  .ws-row.fresh{background:var(--accent-tint)}
981
983
  .ws-row.fresh .k{color:var(--accent)}
982
984
  .ws-row.muted{opacity:.6}
985
+ /* Steering (drop / undrop, pin / unpin): a row's actions on hover and keyboard focus (always where there is no hover); a pending op's row dashed warn with its pill, the footer counting them; a pinned row's 📌. */
986
+ .ws-pin{flex:none;font-size:10px;line-height:1}
987
+ .ws-act{flex:none;display:inline-flex;gap:4px;opacity:0}
988
+ .ws-row:hover .ws-act,.ws-row:focus-within .ws-act,.ws-ghead:hover .ws-act,.ws-ghead:focus-within .ws-act,.ws-row.pending .ws-act{opacity:1}
989
+ @media (hover:none){.ws-act{opacity:1}}
990
+ .ws-act-b{flex:none;padding:0 6px;border:1px solid var(--border-strong);border-radius:4px;background:transparent;font-family:ui-sans-serif,system-ui,sans-serif;font-size:11px;font-weight:400;line-height:16px;color:var(--text-muted);cursor:pointer}
991
+ .ws-act-b:hover:not(:disabled){filter:none;color:var(--accent);border-color:var(--accent);background:var(--accent-bg)}
992
+ .ws-act-b:disabled{opacity:.5;cursor:default}
993
+ .ws-ghead{display:flex;align-items:center;gap:4px}
994
+ .ws-ghead>.ws-group-head{flex:1;min-width:0}
995
+ .ws-row.pending{border:1px dashed var(--warn-border);background:var(--warn-bg)}
996
+ .ws-row.pending:hover{background:var(--warn-bg)}
997
+ /* A pending row: its pill and undo take the tokens' and the step tag's room, so the name stays readable. */
998
+ .ws-row.pending .tk,.ws-row.pending .ws-step{display:none}
999
+ .ws-pend{flex:none;padding:0 6px;border:1px solid var(--warn-border);border-radius:999px;background:var(--warn-bg);color:var(--warn-text);font-family:ui-sans-serif,system-ui,sans-serif;font-size:10.5px;line-height:15px;white-space:nowrap}
1000
+ .ws-pending{display:flex;align-items:center;gap:6px;margin-top:8px;padding:4px 8px;border:1px dashed var(--warn-border);border-radius:6px;background:var(--warn-bg);color:var(--warn-text);font-size:11.5px;line-height:20px}
1001
+ .ws-pending .ws-act-b{flex:none;margin-left:auto;white-space:nowrap;color:var(--warn-text);border-color:var(--warn-border)}
1002
+ .ws-pending-t{min-width:0}
1003
+ /* A phone's sheet: one line, the rows' pills say when. */
1004
+ .ws-popover.sheet .ws-pending-when{display:none}
1005
+ .ws-popover.sheet .ws-row .ws-act{display:none}
1006
+ .ws-strip{display:flex;gap:8px;padding:2px 6px 6px 26px}
1007
+ .ws-strip .ws-act-b{padding:0 14px;font-size:12.5px;line-height:28px;border-radius:6px}
983
1008
  .ws-popover.sheet{border-radius:14px}
984
1009
  /* A phone's sheet: the name, the scope and × on the first line, the count and the ring under them. */
985
1010
  .ws-popover.sheet .ctx-pop-close{order:2}
986
1011
  .ws-popover.sheet .ctx-pop-head>.ctx-pop-kind{order:3;flex:1 0 calc(100% - 30px)}
987
1012
  .ws-popover.sheet .ctx-pop-head>.ws-ring{order:4}
988
1013
  .ws-popover.sheet .ws-row{height:30px;line-height:30px}
1014
+ /* + add: the list's foot (a sheet's last row), one KEY typed; an added item the set doesn't hold yet is a pending row of its own. */
1015
+ .ws-add{display:flex;align-items:center;gap:6px;margin-top:8px}
1016
+ .ws-add-in{flex:1;min-width:0;height:26px;box-sizing:border-box;padding:0 8px;border:1px dashed var(--border-strong);border-radius:6px;background:transparent;color:var(--text);font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}
1017
+ .ws-add-in::placeholder{color:var(--text-faint)}
1018
+ .ws-add-in:focus{outline:none;border-style:solid;border-color:var(--accent)}
1019
+ .ws-add .ws-act-b{line-height:22px;padding:0 10px}
1020
+ .ws-row.added .k{color:var(--warn-text);font-weight:600}
1021
+ .ws-popover.sheet .ws-add-in{height:34px;font-size:16px}
1022
+ .ws-popover.sheet .ws-add .ws-act-b{line-height:32px;padding:0 14px;font-size:12.5px;border-radius:6px}
989
1023
  /* The session bar's chip, in the mem chip's place: a dot (the accent: changed since its list was last opened) and the count. */
990
1024
  #infoBar .meta .ws-chip{display:inline-flex;align-items:center;gap:5px;padding:2px 7px;border:1px solid transparent;cursor:pointer;font-family:inherit;font-weight:400;white-space:nowrap;font-variant-numeric:tabular-nums}
991
1025
  #infoBar .meta .ws-chip:hover:not(:disabled){filter:none;color:var(--text);border-color:var(--accent-border);background:var(--accent-bg)}
@@ -183,7 +183,12 @@ export function createStageFrame({ stage, scroller, status, cloud, queuedSlot, h
183
183
  reveal,
184
184
  // A new turn, or none: no height held yet.
185
185
  resetHeld: () => { held = null; },
186
- // The tallest content seen is forgotten (a new turn, the cloud closed by hand).
187
- forgetContent: () => { maxContent = 0; },
186
+ // The tallest content seen and the height held for it are forgotten (a
187
+ // new turn, the cloud closed by hand): the frame refits to what shows now.
188
+ forgetContent: () => {
189
+ maxContent = 0;
190
+ held = null;
191
+ fitFrame();
192
+ },
188
193
  };
189
194
  }
@@ -341,7 +341,7 @@ export function createStageView({
341
341
  if (rail) {
342
342
  const { items, ordinal } = workingSet.liveItems(turn, promptWords());
343
343
  stampRows(blockEl, turn, ordinal);
344
- rail.draw(items, { ctxPct: workingSet.ctxPct() });
344
+ rail.draw(items, { ctxPct: workingSet.ctxPct(), pending: workingSet.pending() });
345
345
  }
346
346
  const calls = slots.ticks.length;
347
347
  // An ended turn says each thing once: its steps in the chip (the label
@@ -437,7 +437,8 @@ export function createStageView({
437
437
  function setCloud(open) {
438
438
  cloudOpen = open;
439
439
  cloudBody.hidden = !open || cloud.hidden;
440
- // Closed by hand: its room isn't held at the scroller's end.
440
+ // Closed by hand: its room isn't held (the stage shrinks back to what
441
+ // shows).
441
442
  if (!open) frame.forgetContent();
442
443
  cloud.classList.toggle("open", open);
443
444
  stage.classList.toggle("cloud-open", open);
@@ -228,6 +228,8 @@ export function createStreamHandlers(deps) {
228
228
  // the conversation (!rollback, !cmd, a continue answered no) re-reads it.
229
229
  command_ran: async (data) => {
230
230
  const id = selected();
231
+ // A queued /working-set line is no longer pending (the list's pill).
232
+ workingSet?.commandRan(data);
231
233
  const view = commandView(data, clientId);
232
234
  if (view.modelName && view.modelName !== state().model) {
233
235
  state().model = view.modelName;
@@ -242,6 +244,8 @@ export function createStreamHandlers(deps) {
242
244
  state().llmContext = data.llm_context;
243
245
  updateInfoBar();
244
246
  llmContextControl.refresh();
247
+ // The working set's list offers pin only under forget.
248
+ workingSet?.strategyChanged();
245
249
  }
246
250
  // /thinking (or /model) changed the level the next turn runs at.
247
251
  if (data.thinking) {
@@ -290,6 +294,8 @@ export function createStreamHandlers(deps) {
290
294
  // turn: its bubble goes here, so the cards it shows come after it. One
291
295
  // queued for after the turn (/model X mid-turn) shows waiting here.
292
296
  command_queued: (data) => {
297
+ // A /working-set line queued for after the turn: pending in the list.
298
+ workingSet?.commandQueued(data);
293
299
  // A card's action waits for its command_ran: shown only if it answers.
294
300
  if ((data.anytime || data.waits) && !data.card && !commandBubble(data.command_id)) addCommandBubble(commandView(data, clientId));
295
301
  },
@@ -311,7 +317,7 @@ export function createStreamHandlers(deps) {
311
317
  },
312
318
  // The server's working set (WorkingSet), at a request and at turn end;
313
319
  // ignored with web.working_set off.
314
- working_set_updated: (data) => { workingSet?.update({ items: data.items, at: data.at }); },
320
+ working_set_updated: (data) => { workingSet?.update({ items: data.items, at: data.at, ...(data.adds ? { adds: data.adds } : {}) }); },
315
321
  context_status: (data) => {
316
322
  const current = state();
317
323
  // After /model (Engine#announce_switched_context!): the new model's
@@ -60,6 +60,11 @@ export function llmEditLine(edit) {
60
60
  const tokens = Number(edit.tokens) > 0 ? ` · ~${compactTokens(Number(edit.tokens))}` : "";
61
61
  return `✂ stubbed: ${edit.note || "stale"}${tokens}`;
62
62
  }
63
+ // The user's drop (/working-set drop, the working set's list).
64
+ if (edit.kind === "drop") {
65
+ const tokens = Number(edit.tokens) > 0 ? ` · ~${compactTokens(Number(edit.tokens))}` : "";
66
+ return `✂ dropped by the user${tokens}`;
67
+ }
63
68
  return "";
64
69
  }
65
70
 
@@ -14,8 +14,13 @@
14
14
  // touch unions its ops and bumps its count, never its at: within a turn
15
15
  // the set is append-only, which keeps the fold stable. state is "live" from
16
16
  // the rows; the server's projection (GET working_set, :working_set_updated:
17
- // WorkingSet) overlays its state (live, stale, forgotten) and tokens by key
18
- // (overlay), never its at.
17
+ // WorkingSet) overlays its state (live, stale, forgotten, dropped) and
18
+ // tokens (and whether the user pinned it) by key (overlay), never its at.
19
+ // The user steers it with `/working-set drop|undrop|pin|unpin|add|unadd KEY…`
20
+ // lines (steerLine, addLine); one queued for after the running turn is
21
+ // pending (pendingSteers) until its command_ran, and an add stays pending
22
+ // until the next turn sends its note (the server's adds). Pins show only
23
+ // under a strategy with the forget layer (forgetOn).
19
24
 
20
25
  export const FLASH_MS = 4000;
21
26
  // Labels per form: the rail's four lines, the row's and the footprint's
@@ -186,7 +191,7 @@ export function sessionItems({ turns = [], live = [], preloaded = [], muted = []
186
191
 
187
192
  // ── the server's truth ────────────────────────────────────────────────────
188
193
 
189
- export const STATES = Object.freeze(["live", "stale", "forgotten"]);
194
+ export const STATES = Object.freeze(["live", "stale", "forgotten", "dropped"]);
190
195
  const ELLIPSIS = "\u2026";
191
196
 
192
197
  // The server's items by "kind:key", and its URLs (a cut row key matches one
@@ -215,9 +220,11 @@ function serverItem(index, item) {
215
220
  return index.urls.find((it) => String(it.key).startsWith(head)) || null;
216
221
  }
217
222
 
218
- // +items+ with the server's state and tokens (+server+: a snapshot {items,
219
- // at}, or null); an item it doesn't know stays live, without tokens. New
220
- // objects only where something changed; never touches at, ops or count.
223
+ // +items+ with the server's state, tokens, pinned and hasDrop (its
224
+ // has_drop: some output holds the user's drop) (+server+: a snapshot
225
+ // {items, at}, or null); an item it doesn't know stays live, without
226
+ // tokens, unpinned. New objects only where something changed; never
227
+ // touches at, ops or count.
221
228
  export function overlay(items, server) {
222
229
  if (!server) return items;
223
230
  const index = serverIndex(server);
@@ -225,21 +232,37 @@ export function overlay(items, server) {
225
232
  const found = serverItem(index, item);
226
233
  const state = found ? found.state : "live";
227
234
  const tokens = found && Number.isFinite(found.tokens) ? found.tokens : undefined;
228
- if (item.state === state && item.tokens === tokens) return item;
235
+ // A cut URL row's full key, the one a steer line names.
236
+ const serverKey = found && found.key !== item.key ? found.key : undefined;
237
+ const pinned = found?.pinned === true ? true : undefined;
238
+ const hasDrop = found?.has_drop === true ? true : undefined;
239
+ if (item.state === state && item.tokens === tokens && item.serverKey === serverKey && item.pinned === pinned && item.hasDrop === hasDrop) return item;
229
240
  const next = { ...item, state };
241
+ if (pinned) next.pinned = true;
242
+ else delete next.pinned;
243
+ if (hasDrop) next.hasDrop = true;
244
+ else delete next.hasDrop;
230
245
  if (tokens === undefined) delete next.tokens;
231
246
  else next.tokens = tokens;
247
+ if (serverKey === undefined) delete next.serverKey;
248
+ else next.serverKey = serverKey;
232
249
  return next;
233
250
  });
234
251
  }
235
252
 
236
- // Which snapshot to keep: +next+ when there is none yet or it is built from
237
- // as much of the conversation as the kept one (its at), else +kept+. A GET
238
- // that answered after a newer event never wins over it.
239
- export function newerSnapshot(kept, next) {
253
+ // Which snapshot to keep, +next+ or +kept+. Events come in the order the
254
+ // server built them, so an event (+event+) always wins: a smaller at is a
255
+ // rollback that shortened the conversation, not an older set. A GET's
256
+ // answer loses to an event that came while it was on its way (+overtaken+),
257
+ // and, asked while a turn runs (its running: it is built from the session's
258
+ // messages, behind that turn's events), to a kept one from more of the
259
+ // conversation (its at).
260
+ export function newerSnapshot(kept, next, { event = false, overtaken = false } = {}) {
240
261
  if (!next || !Array.isArray(next.items) || !Number.isFinite(next.at)) return kept;
241
- if (!kept || next.at >= kept.at) return next;
242
- return kept;
262
+ if (!kept || event) return next;
263
+ if (overtaken) return kept;
264
+ if (next.running && next.at < kept.at) return kept;
265
+ return next;
243
266
  }
244
267
 
245
268
  // Tokens as the popover shows them: "~840", "~1.2k", "~12k".
@@ -251,13 +274,17 @@ export function tokensText(tokens) {
251
274
  }
252
275
 
253
276
  const isForgotten = (item) => item.state === "forgotten";
254
- const isFaded = (item) => item.state === "stale" || item.state === "forgotten";
255
-
256
- // A group's state: forgotten when all its members are, stale when all are
257
- // stale or forgotten, else live (spec §3: struck only when all forgotten,
258
- // faded when all stale or forgotten).
277
+ // Nothing of it is sent: the model forgot it, or the user dropped it.
278
+ const isStruck = (item) => item.state === "forgotten" || item.state === "dropped";
279
+ const isFaded = (item) => item.state === "stale" || isStruck(item);
280
+
281
+ // A group's state: dropped when all its members are, forgotten when all are
282
+ // struck (forgotten or dropped), stale when all are stale or struck, else
283
+ // live (spec §3: struck only when all forgotten, faded when all stale or
284
+ // forgotten).
259
285
  export function groupState(members) {
260
- if (members.length && members.every(isForgotten)) return "forgotten";
286
+ if (members.length && members.every((m) => m.state === "dropped")) return "dropped";
287
+ if (members.length && members.every(isStruck)) return "forgotten";
261
288
  if (members.length && members.every(isFaded)) return "stale";
262
289
  return "live";
263
290
  }
@@ -278,7 +305,7 @@ export function leafText(item) {
278
305
  function leafLabel(item) {
279
306
  return {
280
307
  id: `${item.kind}:${item.key}`, type: "leaf", kind: item.kind, glyph: GLYPHS[item.kind] || "", text: leafText(item),
281
- n: 1, edited: edited(item) ? 1 : 0, cut: isForgotten(item) ? 1 : 0, state: item.state || "live", members: [item],
308
+ n: 1, edited: edited(item) ? 1 : 0, cut: isStruck(item) ? 1 : 0, state: item.state || "live", members: [item],
282
309
  };
283
310
  }
284
311
 
@@ -295,7 +322,7 @@ function groupLabel(spec, members) {
295
322
  const edits = members.filter(edited).length;
296
323
  // The state marks (spec §3): ✂n the forgotten members, the group's own
297
324
  // state from all of them.
298
- const marks = { cut: members.filter(isForgotten).length, state: groupState(members) };
325
+ const marks = { cut: members.filter(isStruck).length, state: groupState(members) };
299
326
  if (spec.type === "dir") {
300
327
  return { id: `dir:${spec.dir}`, type: "dir", kind: "file", glyph: "", text: dirLabel(spec.dir), count: plural(n, "file"), n, edited: edits, ...marks, members, dir: spec.dir };
301
328
  }
@@ -451,9 +478,16 @@ export function opsText(item) {
451
478
 
452
479
  // A label as the screen reader says it ("web/public 9 files 2 edited").
453
480
  function spoken(label) {
454
- if (label.type === "dir") return `${label.text.replace(/^…\//, "").replace(/\/$/, "")} ${label.count}${label.edited ? ` ${label.edited} edited` : ""}${label.cut ? ` ${label.cut} forgotten` : ""}`;
481
+ if (label.type === "dir") return `${label.text.replace(/^…\//, "").replace(/\/$/, "")} ${label.count}${label.edited ? ` ${label.edited} edited` : ""}${cutWords(label)}`;
455
482
  if (label.type === "leaf") return `${label.kind === "memory" ? "memory " : label.kind === "url" ? "url " : ""}${label.text}${label.edited ? " edited" : ""}${label.state && label.state !== "live" ? ` ${label.state}` : ""}`;
456
- return `${label.text}${label.cut ? ` ${label.cut} forgotten` : ""}`;
483
+ return `${label.text}${cutWords(label)}`;
484
+ }
485
+
486
+ // A group's struck members in words: " 2 forgotten, 1 dropped".
487
+ function cutWords(label) {
488
+ const dropped = label.members.filter((m) => m.state === "dropped").length;
489
+ const forgotten = label.cut - dropped;
490
+ return [forgotten ? ` ${forgotten} forgotten` : "", dropped ? ` ${dropped} dropped` : ""].filter(Boolean).join(",");
457
491
  }
458
492
 
459
493
  // The rail's (or row's, footprint's) aria-label: the folded text spoken.
@@ -476,7 +510,8 @@ export function footprint(items, budget = BUDGETS.footprint) {
476
510
  const kinds = new Set(rest.map((m) => m.kind));
477
511
  tail = kinds.size === 1 ? `+${plural(rest.length, KIND_WORDS[[...kinds][0]])}` : `+${rest.length} more`;
478
512
  }
479
- return { labels: head, tail, edited: items.filter(edited).length, forgotten: items.filter(isForgotten).length };
513
+ return { labels: head, tail, edited: items.filter(edited).length, forgotten: items.filter(isForgotten).length,
514
+ dropped: items.filter((i) => i.state === "dropped").length };
480
515
  }
481
516
 
482
517
  // A label's text as the footprint and the row draw it: its glyph, text,
@@ -498,6 +533,7 @@ export function footprintText(items, budget = BUDGETS.footprint) {
498
533
  if (fp.tail) parts.push(fp.tail);
499
534
  if (fp.edited) parts.push(`edited ${fp.edited}`);
500
535
  if (fp.forgotten) parts.push(`${fp.forgotten} forgotten`);
536
+ if (fp.dropped) parts.push(`${fp.dropped} dropped`);
501
537
  return `touched ${parts.join(" · ")}`;
502
538
  }
503
539
 
@@ -518,3 +554,190 @@ export function nextSettle(seenTimes, now, ms = FLASH_MS) {
518
554
  }
519
555
  return next;
520
556
  }
557
+
558
+ // ── steering (drop / undrop, pin / unpin) ─────────────────────────────────
559
+
560
+ export const STEER_COMMAND = "/working-set";
561
+ const STEER_LINE = /^\/working-set\s+(drop|undrop|pin|unpin|add|unadd)\s+(\S.*)$/;
562
+ const URL_WORD = /^[a-z][a-z0-9+.-]*:\/\//i;
563
+ export const INVERSE = Object.freeze({ drop: "undrop", undrop: "drop", pin: "unpin", unpin: "pin", add: "unadd", unadd: "add" });
564
+ export const STEER_OPS = Object.freeze(Object.keys(INVERSE));
565
+
566
+ // The word a steer line names +item+ by (WorkingSetSteer.target): a file's
567
+ // path, relative to +dir+ (the session's folder, which the worker resolves
568
+ // it against) when inside it, else absolute; memory:NAME; a URL (the
569
+ // server's full one for a cut row).
570
+ export function steerWord(item, dir = "") {
571
+ if (item.kind === "memory") return `memory:${item.key}`;
572
+ if (item.kind === "url") return item.serverKey || item.key;
573
+ const base = String(dir || "").replace(/\/+$/, "");
574
+ return base && item.key.startsWith(`${base}/`) ? item.key.slice(base.length + 1) : item.key;
575
+ }
576
+
577
+ // The id the page keys an item by ("file:/abs/a.rb"), from a steer word; a
578
+ // relative path is +dir+'s.
579
+ function wordId(word, dir = "") {
580
+ if (word.startsWith("memory:")) return `memory:${word.slice("memory:".length)}`;
581
+ if (URL_WORD.test(word)) return `url:${word}`;
582
+ const base = String(dir || "").replace(/\/+$/, "");
583
+ if (!base || word.startsWith("/")) return `file:${word}`;
584
+ return `file:${base}/${word.replace(/^(\.\/)+/, "")}`;
585
+ }
586
+
587
+ // An item's id as steer lines name it.
588
+ export function steerId(item) {
589
+ return wordId(steerWord(item));
590
+ }
591
+
592
+ // A line's words as the worker reads them (WorkingSetSteer.words):
593
+ // whitespace-separated, a quoted one ("…" or '…') keeps its spaces, a
594
+ // backslash escapes its quote or itself; an unclosed quote runs to the end.
595
+ const WORD = /\s*(?:"((?:[^"\\]|\\.)*)"?|'((?:[^'\\]|\\.)*)'?|(\S+))/ys;
596
+ export function steerWords(text) {
597
+ const words = [];
598
+ const source = String(text || "");
599
+ WORD.lastIndex = 0;
600
+ let m;
601
+ while (WORD.lastIndex < source.length && (m = WORD.exec(source))) {
602
+ const quoted = m[1] ?? m[2];
603
+ const word = quoted === undefined ? m[3] : quoted.replace(/\\(["'\\])/g, "$1");
604
+ if (word) words.push(word);
605
+ }
606
+ return words;
607
+ }
608
+
609
+ // +word+ as a line names it (WorkingSetSteer.quote): quoted when it has
610
+ // whitespace or starts with a quote, else as it is.
611
+ export function quoteWord(word) {
612
+ return /\s|^["']/.test(word) ? `"${word.replace(/["\\]/g, "\\$&")}"` : word;
613
+ }
614
+
615
+ // The line that does +op+ to +items+ ("/working-set drop lib/a.rb memory:x"),
616
+ // a file inside +dir+ (the session's folder) by its relative path, a key
617
+ // with spaces quoted.
618
+ export function steerLine(op, items, dir = "") {
619
+ return `${STEER_COMMAND} ${op} ${items.map((item) => quoteWord(steerWord(item, dir))).join(" ")}`;
620
+ }
621
+
622
+ // A steer line's op and ids ({op, ids}), or null for any other line; a
623
+ // relative path is +dir+'s.
624
+ export function parseSteerLine(line, dir = "") {
625
+ const m = STEER_LINE.exec(String(line || "").trim());
626
+ if (!m) return null;
627
+ return { op: m[1], ids: steerWords(m[2]).map((word) => wordId(word, dir)) };
628
+ }
629
+
630
+ // The ops queued for after the running turn (+lines+, in queue order), per
631
+ // item id: its last op ("drop", "undrop", "pin", "unpin", "add"). An op
632
+ // followed by its inverse nets to nothing (the worker runs both, the second
633
+ // undoing the first); a pin after a drop is the pin (it takes the pending
634
+ // drop off), a drop after a pin is refused (the pin stays). +adds+: the ids
635
+ // the server's snapshot says are added already (made between turns, its
636
+ // adds), pending before any line; an unadd with no add pending is refused.
637
+ // A relative path is +dir+'s (the session's folder).
638
+ export function pendingSteers(lines, dir = "", adds = []) {
639
+ const pending = new Map(adds.map((id) => [id, "add"]));
640
+ for (const line of lines) {
641
+ const parsed = parseSteerLine(line, dir);
642
+ if (!parsed) continue;
643
+ for (const id of parsed.ids) {
644
+ // A drop after a pending pin: the worker refuses it (unpin it first).
645
+ if (parsed.op === "drop" && pending.get(id) === "pin") continue;
646
+ // An unadd of nothing added: the worker refuses it.
647
+ if (parsed.op === "unadd" && pending.get(id) !== "add") continue;
648
+ if (pending.get(id) === INVERSE[parsed.op]) pending.delete(id);
649
+ else pending.set(id, parsed.op);
650
+ }
651
+ }
652
+ return pending;
653
+ }
654
+
655
+ // Why +item+ can't be dropped (a title for its disabled button), "" when
656
+ // it can, null when it has no drop at all (muted, dropped already, or the
657
+ // server doesn't know it yet: a running call). A pinned one asks for an
658
+ // unpin first (WorkingSetSteer::Refused's words).
659
+ export function dropRefusal(item) {
660
+ if (item.muted || item.state === "dropped") return null;
661
+ if (item.preloaded && !item.ops.includes("read")) return "preloaded into the system prompt: not dropped from here";
662
+ if (!Number.isFinite(item.tokens)) return null;
663
+ if (item.pinned) return "pinned by the user: unpin it first";
664
+ if (!item.ops.includes("read")) return "only edited or written: nothing of it to drop";
665
+ if (item.state === "forgotten") return "forgotten: nothing of it is sent";
666
+ return "";
667
+ }
668
+
669
+ // Whether +item+ offers pin or unpin: one the server knows (its tokens), an
670
+ // edit-only one too (its later reads are covered), not a muted or dropped
671
+ // one, nor one holding a drop (undrop it first), nor a memory only preloaded.
672
+ export function pinnable(item) {
673
+ if (item.muted || item.state === "dropped" || item.hasDrop) return false;
674
+ if (item.preloaded && !item.ops.includes("read")) return false;
675
+ return Number.isFinite(item.tokens);
676
+ }
677
+
678
+ // Whether the strategy an llm ctx summary names ({strategy: "stale,forget"},
679
+ // session_state's llmContext) has the forget layer: pins mean something
680
+ // only there.
681
+ export function forgetOn(llmContext) {
682
+ return String(llmContext?.strategy || "").split(/[\s,|]+/).includes("forget");
683
+ }
684
+
685
+ // Whether +item+ offers undrop: dropped, or holding the user's drop on some
686
+ // of its outputs (hasDrop: the rest forgotten by the model's layers, or
687
+ // still sent).
688
+ export function undroppable(item) {
689
+ return item.state === "dropped" || item.hasDrop === true;
690
+ }
691
+
692
+ // ── + add ─────────────────────────────────────────────────────────────────
693
+
694
+ // The line that adds what the user typed (one KEY: a path, memory:NAME or a
695
+ // URL; quoted when it has spaces), or null for nothing typed.
696
+ export function addLine(text) {
697
+ const word = String(text || "").trim();
698
+ return word ? `${STEER_COMMAND} add ${quoteWord(word)}` : null;
699
+ }
700
+
701
+ // The ids (kind:key) of a server snapshot's adds (WorkingSet::Add: the
702
+ // adds the next turn's note asks the model to read).
703
+ export function serverAddIds(server) {
704
+ return (server?.adds || []).filter((a) => a && a.kind && a.key).map((a) => `${a.kind}:${a.key}`);
705
+ }
706
+
707
+ // An item for an id ("file:/abs/a.rb", "memory:x", "url:https://…") that
708
+ // the set doesn't hold yet: a pending add's row (added), a file by its path
709
+ // relative to +dir+ when inside it; +label+ the server's name when it has one.
710
+ export function addedItem(id, dir = "", label = "") {
711
+ const at = id.indexOf(":");
712
+ const kind = id.slice(0, at);
713
+ const key = id.slice(at + 1);
714
+ const item = { kind, key, ops: [], at: null, count: 0, state: "live", added: true };
715
+ if (kind === "file") {
716
+ const base = String(dir || "").replace(/\/+$/, "");
717
+ item.path = label || (base && key.startsWith(`${base}/`) ? key.slice(base.length + 1) : key);
718
+ item.label = item.path;
719
+ } else if (kind === "url") {
720
+ item.url = key;
721
+ item.label = urlLabel(key);
722
+ } else {
723
+ item.label = key;
724
+ }
725
+ return item;
726
+ }
727
+
728
+ // The pending adds of items +items+ doesn't hold, as rows (addedItem), in
729
+ // the order they were added; the server's labels where it has them.
730
+ export function addedItems(pending, items, server = null, dir = "") {
731
+ const held = new Set(items.map(steerId));
732
+ const labels = new Map((server?.adds || []).map((a) => [`${a.kind}:${a.key}`, a.label]));
733
+ return [...pending].filter(([id, op]) => op === "add" && !held.has(id)).map(([id]) => addedItem(id, dir, labels.get(id) || ""));
734
+ }
735
+
736
+ // Whether +item+ offers refresh (an add of an item the set holds: the model
737
+ // reads it again): stale, or forgotten without a drop of the user's (undrop
738
+ // brings that back); one the server knows, not muted nor only preloaded.
739
+ export function refreshable(item) {
740
+ if (item.muted || item.added || (item.preloaded && !item.ops.includes("read"))) return false;
741
+ if (!Number.isFinite(item.tokens)) return false;
742
+ return item.state === "stale" || (item.state === "forgotten" && item.hasDrop !== true);
743
+ }