samagotchi 0.182.0 → 0.183.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 (161) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +16 -6
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +28 -6
  8. data/docs/configuration.md +2 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +13 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +18 -8
  14. data/docs/internals/remote-sessions.md +24 -5
  15. data/docs/internals/web-frontend.md +88 -28
  16. data/docs/internals/working-set.md +1 -1
  17. data/docs/mcp-server.md +80 -0
  18. data/docs/plugins.md +308 -21
  19. data/docs/sessions.md +3 -3
  20. data/docs/sub-agent.md +9 -0
  21. data/docs/testing.md +3 -1
  22. data/docs/thin-clients.md +146 -0
  23. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  24. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  25. data/lib/samagotchi/bridge.rb +59 -68
  26. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  27. data/lib/samagotchi/bundle_command/check.rb +36 -19
  28. data/lib/samagotchi/bundle_command.rb +50 -21
  29. data/lib/samagotchi/bundle_manifest.rb +101 -4
  30. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  32. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  33. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  34. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  35. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  36. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  37. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  38. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  41. data/lib/samagotchi/command_intake.rb +7 -0
  42. data/lib/samagotchi/commands/registry.rb +8 -3
  43. data/lib/samagotchi/continue_offer.rb +24 -15
  44. data/lib/samagotchi/engine/block_fix.rb +4 -4
  45. data/lib/samagotchi/engine/cards.rb +14 -5
  46. data/lib/samagotchi/engine/events.rb +10 -15
  47. data/lib/samagotchi/engine/models.rb +1 -1
  48. data/lib/samagotchi/engine/plugins.rb +3 -0
  49. data/lib/samagotchi/engine/recap.rb +1 -1
  50. data/lib/samagotchi/engine/side_requests.rb +1 -1
  51. data/lib/samagotchi/engine/sign_in.rb +142 -0
  52. data/lib/samagotchi/engine/turn_end.rb +3 -3
  53. data/lib/samagotchi/engine.rb +43 -27
  54. data/lib/samagotchi/engine_snapshots.rb +1 -1
  55. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  56. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  57. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  58. data/lib/samagotchi/hold_stop.rb +4 -4
  59. data/lib/samagotchi/idle_recap.rb +19 -11
  60. data/lib/samagotchi/idle_reminders.rb +7 -5
  61. data/lib/samagotchi/idle_scheduler.rb +7 -10
  62. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  63. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  64. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  65. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  66. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  67. data/lib/samagotchi/llm/http.rb +96 -5
  68. data/lib/samagotchi/mcp_command.rb +110 -0
  69. data/lib/samagotchi/mcp_server/http.rb +112 -0
  70. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  71. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  72. data/lib/samagotchi/mcp_server/text.rb +155 -0
  73. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  74. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  75. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  76. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  77. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  78. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  79. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  80. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  81. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  82. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  83. data/lib/samagotchi/plugin/api.rb +6 -1
  84. data/lib/samagotchi/plugin/card.rb +36 -11
  85. data/lib/samagotchi/plugin/context.rb +63 -6
  86. data/lib/samagotchi/plugin/http.rb +40 -15
  87. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  88. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  89. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  90. data/lib/samagotchi/plugin/loader.rb +18 -11
  91. data/lib/samagotchi/plugin/secrets.rb +266 -0
  92. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  93. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  94. data/lib/samagotchi/queued_command.rb +28 -4
  95. data/lib/samagotchi/recap_setup.rb +13 -4
  96. data/lib/samagotchi/ref.rb +3 -2
  97. data/lib/samagotchi/relay_verifier.rb +8 -7
  98. data/lib/samagotchi/relay_watcher.rb +4 -4
  99. data/lib/samagotchi/run_options.rb +2 -1
  100. data/lib/samagotchi/send_command.rb +54 -41
  101. data/lib/samagotchi/session_access/ask.rb +244 -0
  102. data/lib/samagotchi/session_access/contract.rb +5 -0
  103. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  104. data/lib/samagotchi/session_access/exchange.rb +173 -0
  105. data/lib/samagotchi/session_access/local.rb +25 -6
  106. data/lib/samagotchi/session_access/remote.rb +4 -1
  107. data/lib/samagotchi/session_command_catalog.rb +10 -0
  108. data/lib/samagotchi/session_commands.rb +17 -0
  109. data/lib/samagotchi/session_config.rb +4 -4
  110. data/lib/samagotchi/session_observer.rb +27 -0
  111. data/lib/samagotchi/steer_cut.rb +4 -3
  112. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  113. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  114. data/lib/samagotchi/testing/boundary.rb +4 -0
  115. data/lib/samagotchi/testing/bundle.rb +48 -2
  116. data/lib/samagotchi/testing/fake_http.rb +60 -15
  117. data/lib/samagotchi/testing/host.rb +4 -1
  118. data/lib/samagotchi/testing/recorder.rb +45 -5
  119. data/lib/samagotchi/tools/tool_index.rb +14 -3
  120. data/lib/samagotchi/version.rb +1 -1
  121. data/lib/samagotchi/web/app.rb +8 -6
  122. data/lib/samagotchi/web/ask_routes.rb +292 -0
  123. data/lib/samagotchi/web/mcp_route.rb +88 -0
  124. data/lib/samagotchi/web/public/app.js +2 -3
  125. data/lib/samagotchi/web/public/block_frame.js +72 -11
  126. data/lib/samagotchi/web/public/block_host.js +44 -8
  127. data/lib/samagotchi/web/public/block_regions.js +126 -0
  128. data/lib/samagotchi/web/public/card.js +22 -9
  129. data/lib/samagotchi/web/public/card_actions.js +21 -0
  130. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  131. data/lib/samagotchi/web/public/card_registry.js +3 -2
  132. data/lib/samagotchi/web/public/data.js +15 -12
  133. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  134. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  135. data/lib/samagotchi/web/public/format.js +3 -0
  136. data/lib/samagotchi/web/public/index.html +52 -7
  137. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  138. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  139. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  140. data/lib/samagotchi/web/public/refs.js +5 -3
  141. data/lib/samagotchi/web/public/region_hit.js +144 -0
  142. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  143. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  144. data/lib/samagotchi/web/public/session_actions.js +105 -100
  145. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  146. data/lib/samagotchi/web/session_control.rb +31 -9
  147. data/lib/samagotchi/web/session_create.rb +2 -2
  148. data/lib/samagotchi/worker/child_side.rb +3 -2
  149. data/lib/samagotchi/worker/command_queue.rb +13 -13
  150. data/lib/samagotchi/worker/leave.rb +3 -3
  151. data/lib/samagotchi/worker/scratch.rb +6 -6
  152. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  153. data/lib/samagotchi/worker/startup.rb +3 -3
  154. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  155. data/lib/samagotchi/worker.rb +32 -21
  156. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  157. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  158. data/lib/samagotchi/worker_inbound.rb +12 -7
  159. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  160. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  161. metadata +31 -1
@@ -1,9 +1,11 @@
1
1
  import { continueRefusal, continuedText, openChildrenTemplate, openerText } from "./chains.js";
2
- import { cantText, deleteConfirmText, goneSessionNotice } from "./format.js";
3
- import { tasksConfirmText, tasksCount, tasksStoppedSuffix } from "./running_tasks.js";
2
+ import { cantText, goneSessionNotice } from "./format.js";
3
+ import { tasksStoppedSuffix } from "./running_tasks.js";
4
4
  import { sessionHash } from "./route.js";
5
5
  import { inTree } from "./sessions_list.js";
6
- import { isChained, listAfterDelete, deleteToast, runDeleteFlow } from "./delete_sheet.js";
6
+ import { stillOn } from "./latest.js";
7
+ import { listAfterDelete, runDeleteFlow } from "./delete_sheet.js";
8
+ import { deleteToast } from "./removal_sheet_model.js";
7
9
 
8
10
  // What the page does to a whole session (used by app.js): Continue, Archive
9
11
  // and Unarchive, Delete and Stop, from the info bar's buttons, a card's or a
@@ -25,113 +27,77 @@ import { isChained, listAfterDelete, deleteToast, runDeleteFlow } from "./delete
25
27
  // from another session it displaced, or null), +restoreDraft(draft, opener)+
26
28
  // (that draft back, never over newer text), +closeLiveStream()+ (the live
27
29
  // stream's close, the stream left as it is) and +workerGone(id)+ the page's.
28
- // +alert+ / +confirm+: the browser's.
30
+ // +confirm+: the browser's (Stop's, when nothing else runs).
29
31
  export function createSessionActions({
30
32
  selected, store, sessions, setSessions, api, eventsLive, refresh,
31
33
  select, clearSelection, showNotice, toast, addCreatedSession, fillOpener, restoreDraft, closeLiveStream, workerGone,
32
- alert = (text) => globalThis.alert(text), confirm = (text) => globalThis.confirm(text),
34
+ confirm = (text) => globalThis.confirm(text),
33
35
  // The Stop sheet (stop_sheet.js): +open(id, holds)+ shows it and answers
34
36
  // true; nothing to stop (or no sheet wired) is false, and Stop is the
35
37
  // confirm.
36
38
  stopSheet = { open: () => false },
37
- // A card's delete sheet (delete_sheet.js createDeleteSheet): +host(anchor)+
38
- // draws a chained session's choices at it.
39
+ // The delete sheet's shell (delete_sheet.js createDeleteSheet):
40
+ // +host(anchor, id)+ draws a delete's or an archive's sheet at it.
39
41
  deleteSheet = null,
42
+ // The page's document: where a card's control and ⋯ are found.
43
+ doc = globalThis.document,
40
44
  }) {
41
45
  // The session this tab is stopping: its stream may close before the stop
42
46
  // request returns (workerGone reads it).
43
47
  let stoppingId = null;
44
48
 
45
- // Delete a session (the ⋯ More panel's Delete, an all-sessions card's ✕).
46
- // A chained session gets the delete sheet (delete_sheet.js): in the More
47
- // panel's place (deleteIn), at the card's ✕ (+anchor+), else at ⋯. Any
48
- // other keeps today's confirm. The list drops what went without a reload.
49
- // The server stops a live worker first and refuses a session a terminal
50
- // chi has open.
51
- async function confirmDelete(id, { anchor = null } = {}) {
49
+ // Delete a session (the ⋯ More panel's Delete, an all-sessions card's ✕):
50
+ // the delete sheet (delete_sheet.js) says what goes, what is stopped first
51
+ // and what stays, from the server's plan; in the More panel's place
52
+ // (deleteIn), at the card's ✕ (+anchor+), else at ⋯. A refusal the plan
53
+ // carries (a terminal's one-turn run, a schedule) is the sheet's Can't
54
+ // delete. The list drops what went without a reload.
55
+ function confirmDelete(id, { anchor = null } = {}) {
52
56
  const sess = sessions().find((s) => s.id === id) || { id };
53
- if (sess.owner === "tui") {
54
- alert(`Session ${id.slice(0, 8)} is open in a terminal chi; close it there first.`);
55
- return;
56
- }
57
- if (deleteSheet && api.deletePlan && isChained(sess, sessions())) {
58
- const at = anchor || globalThis.document?.querySelector("#infoMoreBtn");
59
- if (at) { startDeleteFlow(id, sess, deleteSheet.host(at, id)); return; }
60
- }
61
- await plainDelete(id, sess);
57
+ const at = anchor || doc?.querySelector("#infoMoreBtn");
58
+ if (!deleteSheet || !api.deletePlan || !at) return;
59
+ startDeleteFlow(id, sess, deleteSheet.host(at, id));
62
60
  }
63
61
 
64
- // The More panel's Delete: true when it took +host+ (a chained session).
62
+ // The More panel's Delete: it always takes +host+ (the panel turns into
63
+ // the sheet), so no second popover opens inside More's click.
65
64
  function deleteIn(id, host) {
66
- const sess = sessions().find((s) => s.id === id);
67
- if (!sess || sess.owner === "tui" || !api.deletePlan || !isChained(sess, sessions())) return false;
68
- startDeleteFlow(id, sess, host);
65
+ if (!id || !api.deletePlan) return false;
66
+ startDeleteFlow(id, sessions().find((s) => s.id === id) || { id }, host);
69
67
  return true;
70
68
  }
71
69
 
72
70
  function startDeleteFlow(id, sess, host) {
73
71
  const flow = runDeleteFlow({
74
- id, session: sess, host, api,
72
+ id, session: sess, host, api, sessions,
75
73
  done: (which, result, plan) => afterDelete(id, which, result, plan),
76
- plain: () => plainDelete(id, sess),
77
- failed: (error) => alert(`Could not delete session ${id.slice(0, 8)}: ${error.message}`),
74
+ failed: (error) => {
75
+ notShown(host, `delete ${id.slice(0, 8)}`, error);
76
+ if (!eventsLive()) refresh();
77
+ },
78
+ // Kept for an older cached delete_sheet.js (0.182.0), which calls it
79
+ // for a session in no chain, its sheet closed (it was the browser's
80
+ // confirm): a reload brings the sheet. Goes at the next release.
81
+ plain: () => notShown(host, `delete ${id.slice(0, 8)}`,
82
+ { message: "this page is out of date; reload it and delete again" }),
78
83
  });
79
84
  host.wire(flow);
80
85
  }
81
86
 
87
+ // A delete or archive that didn't happen, when its sheet no longer shows
88
+ // why (an older cached delete_sheet.js closes it first): a sticky toast.
89
+ function notShown(host, what, error) {
90
+ if (!host.live || host.live()) return;
91
+ toast(cantText(what, error), null, { sticky: true });
92
+ }
93
+
82
94
  function afterDelete(id, which, result, plan) {
83
95
  setSessions(listAfterDelete(sessions(), result));
84
96
  const gone = new Set(result.deleted || [id]);
85
97
  if (gone.has(selected())) clearSelection();
86
98
  if (!eventsLive()) refresh();
87
- const { text, back } = deleteToast(which, result, plan, id);
88
- toast(`${text}${tasksStoppedSuffix(result)}`, back ? { label: `Open ${back.slice(0, 8)}`, run: () => select(back) } : null);
89
- }
90
-
91
- // Today's confirm: a session in no chain. A session whose background
92
- // tasks still run is refused (409 tasks_running, nothing deleted): a
93
- // second confirm names them, and OK sends the delete again with
94
- // stopTasks (they are stopped, then the session goes).
95
- async function plainDelete(id, sess) {
96
- if (!confirm(deleteConfirmText(sess))) return;
97
- try {
98
- await api.deleteSession(id);
99
- } catch (e) {
100
- if (e.code === "tasks_running") { await deleteStoppingTasks(id, e.body?.tasks); return; }
101
- deleteFailed(id, e);
102
- return;
103
- }
104
- dropDeleted(id);
105
- }
106
-
107
- async function deleteStoppingTasks(id, listing) {
108
- if (!confirm(tasksConfirmText(id, listing, "delete"))) return;
109
- toast(stoppingText(listing));
110
- let result;
111
- try {
112
- result = await api.deleteSession(id, { stopTasks: true });
113
- } catch (e) {
114
- deleteFailed(id, e);
115
- return;
116
- }
117
- dropDeleted(id);
118
- toast(`Deleted ${id.slice(0, 8)}${tasksStoppedSuffix(result)}`);
119
- }
120
-
121
- function deleteFailed(id, e) {
122
- alert(`Could not delete session ${id.slice(0, 8)}: ${e.message}`);
123
- if (!eventsLive()) refresh();
124
- }
125
-
126
- function dropDeleted(id) {
127
- setSessions(sessions().filter((s) => s.id !== id));
128
- if (selected() === id) clearSelection();
129
- }
130
-
131
- // The toast while a delete or an archive stops the tasks (about 4 s at most).
132
- function stoppingText(listing) {
133
- const n = tasksCount(listing);
134
- return `Stopping ${n} background task${n === 1 ? "" : "s"}…`;
99
+ const { text, back, sticky = false } = deleteToast(which, result, plan, id);
100
+ toast(text, back ? { label: `Open ${back.slice(0, 8)}`, run: () => select(back) } : null, { sticky });
135
101
  }
136
102
 
137
103
  // The open session no longer exists: back to the start page, saying why.
@@ -282,10 +248,11 @@ export function createSessionActions({
282
248
  // the open session's worker was stopped (it, or a delegate of the archived
283
249
  // one), its stream ending is a stop, not a lost worker.
284
250
  // +stopTasks+: the archive stops the background tasks the tree started
285
- // first (else a session whose tasks still run is refused: 409
286
- // tasks_running; a batch passes nothing, and skips it with that reason).
251
+ // first, only +tasks+ (the ids the sheet named) when given (else a session
252
+ // whose tasks still run is refused: 409 tasks_running; a batch passes
253
+ // nothing, and skips it with that reason).
287
254
  // @return {ok: true, result} | {ok: false, error}
288
- async function archiveOne(id, archive, { stopTasks = false } = {}) {
255
+ async function archiveOne(id, archive, { stopTasks = false, tasks = null } = {}) {
289
256
  // A live worker in the tree is stopped by the archive: the open
290
257
  // session's stream ending then is a stop.
291
258
  const open = selected();
@@ -293,7 +260,7 @@ export function createSessionActions({
293
260
  if (mine) stoppingId = mine;
294
261
  try {
295
262
  const result = archive
296
- ? await api.archiveSession(id, ...(stopTasks ? [{ stopTasks: true }] : []))
263
+ ? await api.archiveSession(id, ...(stopTasks ? [{ stopTasks: true, ...(tasks ? { tasks } : {}) }] : []))
297
264
  : await api.unarchiveSession(id);
298
265
  markArchived(archive ? result.archived : result.unarchived, archive);
299
266
  if (mine && mine === selected() && (result.stopped || []).includes(mine)) stoppedWorker(mine);
@@ -306,35 +273,73 @@ export function createSessionActions({
306
273
  }
307
274
  }
308
275
 
309
- // No confirm, unless background tasks the tree started still run (409
310
- // tasks_running): then the confirm names them, and OK archives again with
311
- // stopTasks. Undo only unarchives: stopped tasks stay stopped.
312
- async function setArchived(id, archive, { undo = true } = {}) {
313
- const short = id.slice(0, 8);
314
- let answer = await archiveOne(id, archive);
315
- let suffix = "";
316
- if (!answer.ok && archive && answer.error?.code === "tasks_running") {
317
- const listing = answer.error.body?.tasks;
318
- if (!confirm(tasksConfirmText(id, listing, "archive"))) return;
319
- toast(stoppingText(listing));
320
- answer = await archiveOne(id, true, { stopTasks: true });
321
- if (answer.ok) suffix = tasksStoppedSuffix(answer.result);
322
- }
276
+ // No confirm: one tap and the toast's Undo. Unless the archive can't
277
+ // happen as it is (a 409): background tasks the tree started still run
278
+ // (tasks_running) opens the sheet in Archive's words, whose button archives
279
+ // stopping the tasks it named; any other refusal is its Can't archive. The
280
+ // sheet is at the control tapped: +anchor+ (⋯ for the open session's), else
281
+ // the card's archive button, found by the session's id. Undo only
282
+ // unarchives: stopped tasks stay stopped.
283
+ // A sheet opened since for another session (a card's ✕ while the archive
284
+ // was out) keeps its place: the refusal is a sticky toast instead
285
+ // (latest.js stillOn on the shell's session).
286
+ async function setArchived(id, archive, { undo = true, anchor = null } = {}) {
287
+ const sheetSame = deleteSheet?.openFor ? stillOn(() => deleteSheet.openFor()) : () => true;
288
+ const answer = await archiveOne(id, archive);
323
289
  if (!answer.ok) {
324
- alert(`Could not ${archive ? "archive" : "unarchive"} session ${short}: ${answer.error.message}`);
290
+ const taken = !sheetSame() && deleteSheet.openFor() !== id;
291
+ const at = archive && deleteSheet && !taken ? anchor || archiveAnchor(id) : null;
292
+ if (at) askArchive(id, answer.error, at, undo);
293
+ else {
294
+ toast(cantText(`${archive ? "archive" : "unarchive"} ${id.slice(0, 8)}`, answer.error), null, { sticky: true });
295
+ if (!eventsLive()) refresh();
296
+ }
325
297
  return;
326
298
  }
327
- // markArchived's list redrew the lists and the bar already.
299
+ archived(id, archive, answer.result, undo);
300
+ }
301
+
302
+ // markArchived's list redrew the lists and the bar already.
303
+ function archived(id, archive, result, undo) {
328
304
  if (!eventsLive()) refresh();
329
305
  const what = archive ? "Archived" : "Unarchived";
330
- toast(`${what} ${short}${suffix}`, undo ? { label: "Undo", run: () => setArchived(id, !archive, { undo: false }) } : null);
306
+ toast(`${what} ${id.slice(0, 8)}${archive ? tasksStoppedSuffix(result) : ""}`,
307
+ undo ? { label: "Undo", run: () => setArchived(id, !archive, { undo: false }) } : null);
308
+ }
309
+
310
+ // A card's archive button for +id+ that has a box (the strip's, the list's
311
+ // or the all-sessions view's), else ⋯.
312
+ function archiveAnchor(id) {
313
+ const cards = [...(doc?.querySelectorAll(`[data-arch="${id}"]`) || [])];
314
+ return cards.find((el) => el.getClientRects?.().length) || doc?.querySelector("#infoMoreBtn") || null;
315
+ }
316
+
317
+ function askArchive(id, error, at, undo) {
318
+ const host = deleteSheet.host(at, id);
319
+ host.wire(runDeleteFlow({
320
+ id, session: sessions().find((s) => s.id === id) || { id }, host, sessions,
321
+ archive: { refusal: error },
322
+ api: {
323
+ archive: async (sid, opts) => {
324
+ const answer = await archiveOne(sid, true, opts);
325
+ if (!answer.ok) throw answer.error;
326
+ return answer.result;
327
+ },
328
+ // Kept for an older cached delete_sheet.js (0.182.0), which ignores
329
+ // +archive+ and reads a delete plan: the refusal, so it lands in
330
+ // +failed+ and says it. Goes at the next release.
331
+ deletePlan: () => Promise.reject(error),
332
+ },
333
+ done: (_which, result) => archived(id, true, result, undo),
334
+ failed: (failure) => notShown(host, `archive ${id.slice(0, 8)}`, failure),
335
+ }));
331
336
  }
332
337
 
333
338
  // The info bar's Archive / Unarchive: the open session's, by its state.
334
339
  function toggleArchiveSelected() {
335
340
  if (!selected()) return;
336
341
  if (selectedArchived()) setArchived(selected(), false);
337
- else setArchived(selected(), true);
342
+ else setArchived(selected(), true, { anchor: doc?.querySelector("#infoMoreBtn") || null });
338
343
  }
339
344
 
340
345
  return {
@@ -17,6 +17,8 @@ require_relative "../session_metrics"
17
17
  require_relative "../version"
18
18
  require_relative "request_body"
19
19
  require_relative "session_hub"
20
+ require_relative "ask_routes"
21
+ require_relative "mcp_route"
20
22
 
21
23
  module Samagotchi
22
24
  module Web
@@ -30,9 +32,11 @@ module Samagotchi
30
32
  # parse_json, …) answer. See docs/architecture.md (chi web's routes for
31
33
  # the session commands).
32
34
  module SessionAccessRoutes
33
- # A wait route answers within this many seconds (status timeout); the
34
- # client asks again until its own --timeout.
35
- WAIT_MAX_SECONDS = 30.0
35
+ include AskRoutes
36
+ include McpRoute
37
+
38
+ # WAIT_MAX_SECONDS (a wait route's slice) is AskRoutes', included above.
39
+
36
40
  # GET /api/info's feature: this chi web has these routes (a remote
37
41
  # client checks it before its first session command).
38
42
  FEATURE = "session_commands"
@@ -198,8 +202,11 @@ module Samagotchi
198
202
  # Session) and parent_strategy, what a parent may pick on the
199
203
  # session's questions here (ParentReport.strategy_for). A timeout
200
204
  # status: ask again. 503 server_stopping when chi web stops mid-wait.
205
+ # A body with token (a thin client's) is #handle_token_wait's.
201
206
  def handle_wait(req, id)
202
207
  body = body_hash(req) or return error_response(400, "invalid_json", "invalid JSON body")
208
+ return handle_token_wait(req, id, body) if body.key?("token")
209
+
203
210
  options, error = wait_options(body)
204
211
  return error if error
205
212
  return participant_wait(req, id, options) unless principal(req).owner?
@@ -233,15 +240,11 @@ module Samagotchi
233
240
  owner_grace: numbers["owner_grace"], queued: body["queued"] == true, ended_before: body["ended_before"] == true }, nil]
234
241
  end
235
242
 
243
+ # The body's baseline, checked as a wait token's is (Token.baseline).
236
244
  def wait_baseline(raw)
237
- return [nil, nil] if raw.nil?
238
-
239
- fields = { "messages" => Integer, "question_id" => String, "last_turn" => String }
240
- unless raw.is_a?(Hash) && raw.all? { |key, value| fields.key?(key) && (value.nil? || value.is_a?(fields[key])) }
241
- return [nil, error_response(400, "invalid_wait", "baseline is {messages, question_id, last_turn}")]
242
- end
243
-
244
- [ReplyWait::Baseline.new(**raw.transform_keys(&:to_sym)), nil]
245
+ [SessionAccess::Exchange::Token.baseline(raw), nil]
246
+ rescue SessionAccess::Exchange::Token::Invalid => e
247
+ [nil, error_response(400, "invalid_wait", e.message)]
245
248
  end
246
249
 
247
250
  RESULT_FIELDS = %i[text file outcome limit error_kind retryable cancel_reason stopped_by kept_steps turn_id origin].freeze
@@ -57,6 +57,14 @@ module Samagotchi
57
57
  qid = body["id"]
58
58
  return error_response(400, "missing_fields", "id is required") if qid.to_s.strip.empty?
59
59
 
60
+ # wait: a thin client's answer that also waits for what comes next
61
+ # (AskRoutes#answered_wait), its start read before the answer goes in.
62
+ wait, error = answer_wait_option(body)
63
+ return error if error
64
+
65
+ start = answer_wait_start(id, session, qid) if wait
66
+ return session_not_found(id) if wait && !start
67
+
60
68
  # client_id: only chi answer's (a parent agent's answer, which the
61
69
  # worker holds to its guardrails.parent_answers) is passed on; any
62
70
  # other is dropped, so a forward can only tighten (an answer never
@@ -65,19 +73,27 @@ module Samagotchi
65
73
  request = once_more_on_late do |client|
66
74
  client.answer(id: qid, selected: body["selected"], freeform: body["freeform"], client_id: client_id)
67
75
  end
68
- relay(id, bridge_client(id), request, what: "the answer was not sent", cant: "answer questions") do |reply|
76
+ # With wait, the relay answers :answered / :not_pending and the wait
77
+ # runs after it: relay's rescues are the answer's, not the wait's.
78
+ relayed = relay(id, bridge_client(id), request, what: "the answer was not sent", cant: "answer questions") do |reply|
69
79
  case reply.status
70
80
  when 200
71
81
  @hub&.resolve_question(id, question_id: qid)
82
+ next :answered if wait
83
+
72
84
  json_response(200, { status: "answered", session_id: id, id: qid })
73
85
  # Another client answered first (or the question was cancelled).
74
- when 409 then error_response(409, "question_not_pending", reply_detail(reply, "question not pending"))
86
+ when 409
87
+ next :not_pending if wait
88
+
89
+ error_response(409, "question_not_pending", reply_detail(reply, "question not pending"))
75
90
  when 400 then error_response(400, "invalid_answer", reply_detail(reply, "answer rejected"))
76
91
  # The worker's guardrails.parent_answers refused a parent's option.
77
92
  when 403 then json_response(403, { error: "parent_answer_refused", reason: reply.json&.dig("reason"),
78
93
  detail: reply_detail(reply, "the worker refused that option") })
79
94
  end
80
95
  end
96
+ relayed.is_a?(Symbol) ? answered_wait(id, qid, start, wait, answered: relayed == :answered) : relayed
81
97
  end
82
98
 
83
99
  # A request to the worker sent once more when the worker dropped it as
@@ -223,18 +239,24 @@ module Samagotchi
223
239
  follow: body["follow"] == true,
224
240
  state_dir: @state_dir, manager: @manager,
225
241
  bridge: -> { live_bridge_client(id) })
242
+ return refused_delivery(result) unless result.status == :accepted
243
+
244
+ record_history(body, prompt)
245
+ # via: bridge or file (the worker was gone: its input file), which
246
+ # names the turn a remote chi send --wait follows (ReplyWait::Target).
247
+ json_response(202, result.ack.merge("via" => result.via.to_s))
248
+ rescue SessionManager::OwnedByTUI => e
249
+ owned_by_tui(e)
250
+ end
251
+
252
+ # A delivery that did not go in (POST …/turn's, POST …/ask's): the
253
+ # worker's refusal as it answered it, 504 worker_timeout, or 500.
254
+ def refused_delivery(result)
226
255
  case result.status
227
- when :accepted
228
- record_history(body, prompt)
229
- # via: bridge or file (the worker was gone: its input file), which
230
- # names the turn a remote chi send --wait follows (ReplyWait::Target).
231
- json_response(202, result.ack.merge("via" => result.via.to_s))
232
256
  when :refused then json_response(result.code, result.ack)
233
257
  when :timeout then error_response(504, "worker_timeout", result.detail)
234
258
  else error_response(500, "enqueue_failed", "could not write turn input")
235
259
  end
236
- rescue SessionManager::OwnedByTUI => e
237
- owned_by_tui(e)
238
260
  end
239
261
 
240
262
  # A turn refused before it goes in, as chi send refuses it on its own
@@ -125,7 +125,7 @@ module Samagotchi
125
125
  record_history(body, prompt) if !idle && PromptHistory.shell_line?(prompt.to_s.strip)
126
126
  json_response(201, session_to_json(session).merge(bridge_port: port, model_warning: session.model_warning,
127
127
  parent_answers_warning: Guardrails::ParentPolicy.capped_note(parent_answers),
128
- first_turn_id: session.first_turn_id))
128
+ first_turn_id: session.first_turn_id, **create_token(session)))
129
129
  end
130
130
 
131
131
  # POST /api/sessions with continues: <id, prefix or last:id>: the next
@@ -171,7 +171,7 @@ module Samagotchi
171
171
  model_warning: session.model_warning,
172
172
  opener: session.opener,
173
173
  moved_context: session.moved_context&.to_h,
174
- first_turn_id: session.first_turn_id))
174
+ first_turn_id: session.first_turn_id, **create_token(session)))
175
175
  end
176
176
 
177
177
  # The previous link's parent_answers and the model the new one runs,
@@ -19,7 +19,8 @@ module Samagotchi
19
19
  # Verify fresh hand-off. Writes @owes_parent, @asked_parent and
20
20
  # @reporting_turn (also written by #run_engine_turn, with @initial_turn
21
21
  # from #run_initial_prompt; #initialize sets them). Reads @session,
22
- # @state_dir, @session_dir, @engine, @child_reports and @initial_turn.
22
+ # @state_dir, @session_dir, @engine, @event_log, @child_reports and
23
+ # @initial_turn.
23
24
  module ChildSidePart
24
25
  private
25
26
 
@@ -44,7 +45,7 @@ module Samagotchi
44
45
  return unless save_or_log(:fresh_verdicts) { save_session }
45
46
 
46
47
  FileUtils.rm_f(files)
47
- added.each { |record| @engine.announce(type: :verdict_recorded, verdict: record) }
48
+ added.each { |record| @event_log.announce(type: :verdict_recorded, verdict: record) }
48
49
  rescue StandardError => e
49
50
  Log.warn(:worker, "fresh_verdicts_failed", error: e.class.name, msg: e.message)
50
51
  end
@@ -15,12 +15,12 @@ module Samagotchi
15
15
  # any queued prompt, and refuses or drops what arrives mid-turn. Includes
16
16
  # the "what waits" predicates #input_pending?, #held_for_offer? and
17
17
  # #nothing_queued?. LOCK RULE: the queue is touched with the event log held
18
- # (@engine.synchronize_events): #on_command on a Bridge thread, the pops
18
+ # (@event_log.synchronize): #on_command on a Bridge thread, the pops
19
19
  # and re-pushes in #next_ready_command, #refuse_queued_commands and
20
20
  # #drop_queued_commands. The `empty?` peeks (those, #input_pending?,
21
21
  # #nothing_queued?, #start's next_turn_waiting lambda) are benign by
22
22
  # design. Writes @command_queue's contents (created in #initialize).
23
- # Reads @engine, @session_dir, @commands (built in #start),
23
+ # Reads @engine, @event_log, @turn_state, @session_dir, @commands (built in #start),
24
24
  # @continue_offer, @turn_end_seq, @turn_end_type (#start's observer),
25
25
  # @turn_flow and @waker.
26
26
  module CommandQueuePart
@@ -72,7 +72,7 @@ module Samagotchi
72
72
  def next_ready_command
73
73
  return nil if @command_queue.empty?
74
74
 
75
- @engine.synchronize_events do
75
+ @event_log.synchronize do
76
76
  commands = drain_commands
77
77
  first = commands.first
78
78
  ready = first && ready_command?(first) ? commands.shift : nil
@@ -111,7 +111,7 @@ module Samagotchi
111
111
  def refuse_queued_commands(mid_turn: false)
112
112
  return if @command_queue.empty?
113
113
 
114
- @engine.synchronize_events do
114
+ @event_log.synchronize do
115
115
  drain_commands.each do |command|
116
116
  during = mid_turn || command.after_seq.to_i < @turn_end_seq
117
117
  case (during ? turn_answer(command, ended: !mid_turn) : :keep)
@@ -144,7 +144,7 @@ module Samagotchi
144
144
  def waiting_for_turn_end(command)
145
145
  return command unless command.mid_turn == :loop && @engine.command_registry.mid_turn(command.line) == :queue
146
146
 
147
- @engine.announce(type: :command_queued, **command.event_fields, waits: "turn_end")
147
+ @event_log.announce(type: :command_queued, **command.event_fields, waits: "turn_end")
148
148
  command.with(mid_turn: :queue)
149
149
  end
150
150
 
@@ -164,7 +164,7 @@ module Samagotchi
164
164
  def drop_queued_commands
165
165
  return if @command_queue.nil? || @command_queue.empty? || @engine.nil?
166
166
 
167
- @engine.synchronize_events do
167
+ @event_log.synchronize do
168
168
  drain_commands.each { |command| drop_command(command, "dropped: the session's worker stopped before it ran") }
169
169
  end
170
170
  rescue StandardError => e
@@ -181,11 +181,11 @@ module Samagotchi
181
181
  awaiting = @continue_offer.awaiting?
182
182
  result, shown = run_command_line(command)
183
183
  resolved = @continue_offer.resolved?(awaiting, result)
184
- @engine.synchronize_events do
184
+ @event_log.synchronize do
185
185
  @continue_offer.announce_resolved(result, command) if resolved
186
186
  announce_command(command, status: result.status.to_s, output: result.output, changed: Array(result.changed),
187
187
  confirm: result.confirm)
188
- shown.each { |event| @engine.announce(event) }
188
+ shown.each { |event| @event_log.announce(event) }
189
189
  end
190
190
  save_or_log(:command) { save_session } unless Array(result.changed).empty?
191
191
  user_input(command.client_id) if resolved
@@ -199,7 +199,7 @@ module Samagotchi
199
199
  def run_command_line(command)
200
200
  @engine.holding_announcements do
201
201
  command_result(command) do
202
- @commands.run(command.line, confirm: confirm?(command), as_parent: as_parent?(command), user_ui: user_ui?(command))
202
+ @commands.run(command.run_line, confirm: confirm?(command), as_parent: as_parent?(command), user_ui: user_ui?(command))
203
203
  end
204
204
  end
205
205
  end
@@ -258,7 +258,7 @@ module Samagotchi
258
258
  # :refuse while a turn runs, :loop idle
259
259
  def on_command(command, after_file: nil)
260
260
  registry = @engine.command_registry
261
- policy = if @engine.turn_running? then registry.mid_turn(command.line)
261
+ policy = if @turn_state.running? then registry.mid_turn(command.line)
262
262
  else registry.anytime?(command.line) ? :anytime : :loop
263
263
  end
264
264
  if policy == :anytime
@@ -268,7 +268,7 @@ module Samagotchi
268
268
 
269
269
  after_file ||= newest_input_file if policy == :queue
270
270
  # The count says which turn ends came before it.
271
- @command_queue << command.with(after_seq: @engine.event_count, mid_turn: policy, after_file: after_file)
271
+ @command_queue << command.with(after_seq: @event_log.event_count, mid_turn: policy, after_file: after_file)
272
272
  @waker.wake
273
273
  policy
274
274
  end
@@ -294,7 +294,7 @@ module Samagotchi
294
294
  @engine.spawn_anytime do
295
295
  result = command_result(command) do
296
296
  @engine.running_anytime do
297
- @commands.run(command.line, confirm: confirm?(command), as_parent: as_parent?(command), user_ui: user_ui?(command))
297
+ @commands.run(command.run_line, confirm: confirm?(command), as_parent: as_parent?(command), user_ui: user_ui?(command))
298
298
  end
299
299
  end
300
300
  # Saved before its command_ran: a client that reads the file on the reply finds it.
@@ -331,7 +331,7 @@ module Samagotchi
331
331
  SessionSetting::ALL.each { |setting| event[setting.key] = setting.summary(@engine) if setting.changed_by?(changed) }
332
332
  event[:confirm] = confirm.to_h if confirm
333
333
  event[:output_truncated] = true if text.length > COMMAND_OUTPUT_LIMIT
334
- @engine.announce(event)
334
+ @event_log.announce(event)
335
335
  end
336
336
 
337
337
  # +text+ as its :command_ran carries it: over the limit, its head to a
@@ -13,7 +13,7 @@ module Samagotchi
13
13
  # carried reminders, the recap, the discard). Writes @marked_leaving
14
14
  # (#mark_leaving) and @discard (#left), and the exit claim through its own
15
15
  # methods; reads @exit_claim, @idle_exit, @hold_stop, @session, @session_id,
16
- # @session_dir, @state_dir, @default_model, @engine, @bridge, @owner_lock,
16
+ # @session_dir, @state_dir, @default_model, @engine, @event_log, @bridge, @owner_lock,
17
17
  # @waker and @task_wakes.
18
18
  module LeavePart
19
19
  # /exit held by background tasks a finish wake waits for: how to end them.
@@ -109,7 +109,7 @@ module Samagotchi
109
109
  # decided under the lock), false when something came in since the request
110
110
  def leave_on_request
111
111
  stop_bridge_after do
112
- @engine.synchronize_events do
112
+ @event_log.synchronize do
113
113
  # One read: the kind and the asker of the same exit.
114
114
  taken = @exit_claim.taken
115
115
  restart = taken&.restart?
@@ -143,7 +143,7 @@ module Samagotchi
143
143
  # @return [Boolean] false when something came in since #due?
144
144
  def leave_idle
145
145
  stop_bridge_after do
146
- @engine.synchronize_events do
146
+ @event_log.synchronize do
147
147
  next false unless @idle_exit.due?
148
148
 
149
149
  @bridge&.close_intake
@@ -14,7 +14,7 @@ module Samagotchi
14
14
  # SCRATCH_JOIN_GRACE and SCRATCH_GONE_AFTER. Writes @unattended_since
15
15
  # (the scratch thread and the loop, no lock: a monotonic stamp, benign).
16
16
  # Reads @poll_interval, @session, @bridge, @started_at (#start), @engine,
17
- # @session_id and @waker. #scratch? and @scratch_watch (#start_background,
17
+ # @turn_state, @question_desk, @event_log, @session_id and @waker. #scratch? and @scratch_watch (#start_background,
18
18
  # #teardown) stay in Worker.
19
19
  module ScratchPart
20
20
  # How long a scratch worker waits for its terminal's first stream
@@ -46,11 +46,11 @@ module Samagotchi
46
46
  end
47
47
 
48
48
  def cancel_unattended_turn
49
- return unless @engine.turn_running? && scratch_unattended?
49
+ return unless @turn_state.running? && scratch_unattended?
50
50
 
51
51
  Log.info(:worker, "scratch_turn_cancelled", sid: @session_id)
52
- @engine.cancel_question(SessionManager::STOP_CANCEL_REASON) if @engine.pending_question
53
- @engine.cancel_current_turn!(SessionManager::STOP_CANCEL_REASON.to_sym)
52
+ @question_desk.cancel(SessionManager::STOP_CANCEL_REASON) if @question_desk.pending
53
+ @turn_state.cancel!(SessionManager::STOP_CANCEL_REASON.to_sym)
54
54
  @waker.wake
55
55
  end
56
56
 
@@ -83,9 +83,9 @@ module Samagotchi
83
83
  # @return [Boolean] false when a client came back since
84
84
  def leave_scratch
85
85
  stop_bridge_after do
86
- @engine.synchronize_events do
86
+ @event_log.synchronize do
87
87
  # A turn still running is the scratch watch's to cancel first.
88
- next false unless scratch_unattended? && !@engine.turn_running?
88
+ next false unless scratch_unattended? && !@turn_state.running?
89
89
 
90
90
  @bridge&.close_intake
91
91
  @engine.stop_idle(join: false)