samagotchi 0.181.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 (200) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +93 -1
  3. data/bin/chi +4 -1
  4. data/docs/architecture.md +17 -7
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +58 -10
  8. data/docs/configuration.md +3 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +172 -3
  11. data/docs/internals/bridge.md +23 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +29 -8
  14. data/docs/internals/inline-widgets.md +3 -1
  15. data/docs/internals/prompt-caching.md +9 -1
  16. data/docs/internals/remote-sessions.md +38 -7
  17. data/docs/internals/web-frontend.md +116 -26
  18. data/docs/internals/working-set.md +1 -1
  19. data/docs/mcp-server.md +80 -0
  20. data/docs/plugins.md +308 -21
  21. data/docs/sessions.md +7 -4
  22. data/docs/sub-agent.md +9 -0
  23. data/docs/testing.md +3 -1
  24. data/docs/thin-clients.md +146 -0
  25. data/lib/samagotchi/answer_display.rb +3 -2
  26. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  27. data/lib/samagotchi/block_fix.rb +220 -0
  28. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  29. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  30. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  31. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  32. data/lib/samagotchi/bridge.rb +69 -69
  33. data/lib/samagotchi/bridge_client.rb +9 -0
  34. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  35. data/lib/samagotchi/bundle_command/check.rb +36 -19
  36. data/lib/samagotchi/bundle_command.rb +50 -21
  37. data/lib/samagotchi/bundle_manifest.rb +101 -4
  38. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  40. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  41. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  42. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  43. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  44. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  45. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  46. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  47. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  48. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  49. data/lib/samagotchi/command_intake.rb +7 -0
  50. data/lib/samagotchi/commands/registry.rb +8 -3
  51. data/lib/samagotchi/config.rb +3 -0
  52. data/lib/samagotchi/continue_intent.rb +8 -0
  53. data/lib/samagotchi/continue_offer.rb +24 -15
  54. data/lib/samagotchi/engine/block_fix.rb +332 -0
  55. data/lib/samagotchi/engine/cards.rb +14 -5
  56. data/lib/samagotchi/engine/events.rb +10 -15
  57. data/lib/samagotchi/engine/models.rb +1 -1
  58. data/lib/samagotchi/engine/plugins.rb +3 -0
  59. data/lib/samagotchi/engine/recap.rb +1 -1
  60. data/lib/samagotchi/engine/side_requests.rb +8 -6
  61. data/lib/samagotchi/engine/sign_in.rb +142 -0
  62. data/lib/samagotchi/engine/turn_end.rb +3 -3
  63. data/lib/samagotchi/engine.rb +47 -27
  64. data/lib/samagotchi/engine_snapshots.rb +1 -1
  65. data/lib/samagotchi/events.rb +1 -0
  66. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  67. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  68. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  69. data/lib/samagotchi/hold_stop.rb +4 -4
  70. data/lib/samagotchi/idle_client.rb +10 -6
  71. data/lib/samagotchi/idle_recap.rb +19 -11
  72. data/lib/samagotchi/idle_reminders.rb +7 -5
  73. data/lib/samagotchi/idle_scheduler.rb +7 -10
  74. data/lib/samagotchi/inline_widgets.rb +12 -0
  75. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  76. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  77. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  78. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  79. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  80. data/lib/samagotchi/kernel_loop.rb +7 -5
  81. data/lib/samagotchi/llm/chat_loop.rb +2 -0
  82. data/lib/samagotchi/llm/http.rb +96 -5
  83. data/lib/samagotchi/markdown_parser.rb +28 -0
  84. data/lib/samagotchi/mcp_command.rb +110 -0
  85. data/lib/samagotchi/mcp_server/http.rb +112 -0
  86. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  87. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  88. data/lib/samagotchi/mcp_server/text.rb +155 -0
  89. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  90. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  91. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  92. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  93. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  94. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  95. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  96. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  97. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  98. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  99. data/lib/samagotchi/plugin/api.rb +6 -1
  100. data/lib/samagotchi/plugin/card.rb +36 -11
  101. data/lib/samagotchi/plugin/context.rb +63 -6
  102. data/lib/samagotchi/plugin/http.rb +40 -15
  103. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  104. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  105. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  106. data/lib/samagotchi/plugin/loader.rb +18 -11
  107. data/lib/samagotchi/plugin/secrets.rb +266 -0
  108. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  109. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  110. data/lib/samagotchi/queued_command.rb +28 -4
  111. data/lib/samagotchi/recap_setup.rb +13 -4
  112. data/lib/samagotchi/ref.rb +3 -2
  113. data/lib/samagotchi/relay_verifier.rb +8 -7
  114. data/lib/samagotchi/relay_watcher.rb +4 -4
  115. data/lib/samagotchi/run_options.rb +2 -1
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +244 -0
  118. data/lib/samagotchi/session_access/contract.rb +8 -0
  119. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  120. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  121. data/lib/samagotchi/session_access/exchange.rb +173 -0
  122. data/lib/samagotchi/session_access/local.rb +38 -6
  123. data/lib/samagotchi/session_access/remote.rb +23 -2
  124. data/lib/samagotchi/session_access.rb +1 -0
  125. data/lib/samagotchi/session_chain/delete.rb +39 -81
  126. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  127. data/lib/samagotchi/session_command_catalog.rb +10 -0
  128. data/lib/samagotchi/session_commands.rb +17 -0
  129. data/lib/samagotchi/session_config.rb +4 -4
  130. data/lib/samagotchi/session_delete_command.rb +129 -3
  131. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  132. data/lib/samagotchi/session_manager/listing.rb +4 -4
  133. data/lib/samagotchi/session_manager/removal.rb +38 -12
  134. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  135. data/lib/samagotchi/session_manager.rb +1 -0
  136. data/lib/samagotchi/session_observer.rb +27 -0
  137. data/lib/samagotchi/steer_cut.rb +4 -3
  138. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  139. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  140. data/lib/samagotchi/testing/boundary.rb +4 -0
  141. data/lib/samagotchi/testing/bundle.rb +48 -2
  142. data/lib/samagotchi/testing/fake_http.rb +60 -15
  143. data/lib/samagotchi/testing/host.rb +4 -1
  144. data/lib/samagotchi/testing/recorder.rb +45 -5
  145. data/lib/samagotchi/tools/tool_index.rb +14 -3
  146. data/lib/samagotchi/version.rb +1 -1
  147. data/lib/samagotchi/web/app.rb +20 -6
  148. data/lib/samagotchi/web/ask_routes.rb +292 -0
  149. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  150. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  151. data/lib/samagotchi/web/mcp_route.rb +88 -0
  152. data/lib/samagotchi/web/message_display.rb +6 -1
  153. data/lib/samagotchi/web/participant_view.rb +1 -1
  154. data/lib/samagotchi/web/public/app.js +7 -8
  155. data/lib/samagotchi/web/public/block_fix.js +270 -0
  156. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  157. data/lib/samagotchi/web/public/block_frame.js +77 -13
  158. data/lib/samagotchi/web/public/block_host.js +45 -9
  159. data/lib/samagotchi/web/public/block_regions.js +126 -0
  160. data/lib/samagotchi/web/public/block_renderers.css +12 -0
  161. data/lib/samagotchi/web/public/block_watch.js +16 -2
  162. data/lib/samagotchi/web/public/card.js +22 -9
  163. data/lib/samagotchi/web/public/card_actions.js +21 -0
  164. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  165. data/lib/samagotchi/web/public/card_registry.js +3 -2
  166. data/lib/samagotchi/web/public/data.js +15 -12
  167. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  168. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  169. data/lib/samagotchi/web/public/format.js +3 -0
  170. data/lib/samagotchi/web/public/index.html +52 -7
  171. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  172. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  173. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  174. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  175. data/lib/samagotchi/web/public/refs.js +5 -3
  176. data/lib/samagotchi/web/public/region_hit.js +144 -0
  177. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  178. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  179. data/lib/samagotchi/web/public/session_actions.js +105 -100
  180. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  181. data/lib/samagotchi/web/public/turn_block.js +5 -2
  182. data/lib/samagotchi/web/server.rb +6 -4
  183. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  184. data/lib/samagotchi/web/session_control.rb +84 -30
  185. data/lib/samagotchi/web/session_create.rb +2 -2
  186. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  187. data/lib/samagotchi/worker/child_side.rb +3 -2
  188. data/lib/samagotchi/worker/command_queue.rb +13 -13
  189. data/lib/samagotchi/worker/leave.rb +3 -3
  190. data/lib/samagotchi/worker/scratch.rb +6 -6
  191. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  192. data/lib/samagotchi/worker/startup.rb +3 -3
  193. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  194. data/lib/samagotchi/worker.rb +42 -24
  195. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  196. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  197. data/lib/samagotchi/worker_inbound.rb +12 -7
  198. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  199. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  200. metadata +42 -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 {
@@ -46,6 +46,7 @@
46
46
  // gapClock the page's last activity (time_gaps.js
47
47
  // createGapClock; renderHistory seeds it)
48
48
  // addTimeGap(text, {before}) a gap's divider (bubbles.js)
49
+ // blockFix(data) a block fix's word (block_fix.js onEvent); absent: none
49
50
 
50
51
  import { routeChunk } from "./chunk_router.js";
51
52
  import { extractCtxPct, generationTokens } from "./ctx.js";
@@ -75,7 +76,7 @@ export function createStreamHandlers(deps) {
75
76
  appendChunk, readTurnEnd, applyFinalMarkdown, refreshTimingFromSession, makeUserBubble, addEndBubble,
76
77
  commandBubble, addCommandBubble, addNoteBubble, findInTurnRoots, setUsedMemories, showRecap,
77
78
  showGuardrailWarning, showHookNotice, onInitEvent, upsertCard, refreshCardBodies, syncModelPick,
78
- gapClock = null, addTimeGap = () => null,
79
+ gapClock = null, addTimeGap = () => null, blockFix = null,
79
80
  } = deps;
80
81
  // Activity starts (a turn, a reminder, a note) at +time+ (the event's;
81
82
  // none: now): a gap's divider above +before+ (else at the end) when a
@@ -440,6 +441,9 @@ export function createStreamHandlers(deps) {
440
441
  question_cancelled: (data) => {
441
442
  questionCards.resolveQuestion(data.id, { cancelled: true, reason: data.reason });
442
443
  },
444
+ // The worker's word on a block fix it was asked for (block_fix.js): a
445
+ // fixed answer is read again and drawn; a failed or dropped one says so.
446
+ block_fix: (data) => blockFix?.(data),
443
447
  // A side request (the recap, /btw, a plugin's ctx.ask_model) counted:
444
448
  // the server's whole side block, for the ctx tooltip's line at once.
445
449
  side_usage: (data) => {
@@ -969,10 +969,13 @@ function drawnTurnNodes(group, items, { thumbs, capabilities = {}, cards = null
969
969
 
970
970
  // The live answer bubble as the reload draws it from its saved message
971
971
  // (its markdown, refs, display: answerBubbleTemplate), when one of the
972
- // turn's texts says what it says; else as live drew it.
972
+ // turn's texts says what it says, or the answer had a block fixed in its
973
+ // text since (block_fixed: what streamed is the block before the fix);
974
+ // else as live drew it.
973
975
  function savedAnswer(el, group, items, kind) {
974
976
  const text = el.textContent.trim();
975
- const at = [group.answer, ...[...(group.texts || [])].reverse()].find((i) => i != null && String(items[i]?.content ?? "").trim() === text);
977
+ const said = [group.answer, ...[...(group.texts || [])].reverse()].find((i) => i != null && String(items[i]?.content ?? "").trim() === text);
978
+ const at = said ?? (group.answer != null && items[group.answer]?.block_fixed ? group.answer : null);
976
979
  if (at == null) return el;
977
980
  const turnId = kind === "completed" ? group.drawing?.end?.turn_id || null : null;
978
981
  return nodesOf(answerBubbleTemplate(items[at], { at, turnId })).firstElementChild;
@@ -172,6 +172,7 @@ module Samagotchi
172
172
  working_set: Config::BY_KEY["web.working_set"].default, tunnel: nil, start_dir_from: :flag,
173
173
  stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
174
174
  reload_check: Config::BY_KEY["web.reload_check"].default,
175
+ block_fix: Config::BY_KEY["web.block_fix"].default,
175
176
  restarted: false, restart_argv: ["web"], exec: nil)
176
177
  handed_on = false # a :restart leaves Serve to the next process, a run turns it off itself
177
178
  start_given = !start_dir.to_s.strip.empty?
@@ -231,8 +232,8 @@ module Samagotchi
231
232
  Push.preflight!(public_url)
232
233
  options = { port: port, host: host, url: url, open_browser: open_browser, markdown: markdown,
233
234
  annotate_presets: annotate_presets, editor: editor, lan: lan, working_set: working_set,
234
- stage_collapsed: stage_collapsed, reload_check: reload_check, public_url: public_url,
235
- start_dir: start_dir }
235
+ stage_collapsed: stage_collapsed, reload_check: reload_check, block_fix: block_fix,
236
+ public_url: public_url, start_dir: start_dir }
236
237
  started = if plan
237
238
  with_tunnel(provider, plan) do |up|
238
239
  start(**options, public_notes: provider.start_lines(plan, restarted: restarted), on_bound: up)
@@ -463,6 +464,7 @@ module Samagotchi
463
464
  working_set: Config::BY_KEY["web.working_set"].default, public_url: nil, public_notes: [],
464
465
  stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
465
466
  reload_check: Config::BY_KEY["web.reload_check"].default,
467
+ block_fix: Config::BY_KEY["web.block_fix"].default,
466
468
  on_bound: nil, start_dir: Dir.pwd, update_check: nil, auto_update: nil)
467
469
  config_restart_unsubscribe = ConfigFile.watch_restart_settings!(process: :web) do |message|
468
470
  Samagotchi::Log.warn(:config, "restart_required", echo: "Warning: config: #{message}")
@@ -479,8 +481,8 @@ module Samagotchi
479
481
  push = push_runtime(public_url, state_dir)
480
482
  app = App.new(manager: manager, state_dir: state_dir, markdown: markdown,
481
483
  annotate_presets: annotate_presets, editor: editor, hub: hub, lan: lan_option, working_set: working_set,
482
- stage_collapsed: stage_collapsed, reload_check: reload_check, public_url: public_url,
483
- public_token: public_token, push: push, start_dir: start_dir)
484
+ stage_collapsed: stage_collapsed, reload_check: reload_check, block_fix: block_fix,
485
+ public_url: public_url, public_token: public_token, push: push, start_dir: start_dir)
484
486
  # update.auto: install; a stand-in app (a spec's) has no operations to run.
485
487
  auto_update ||= AutoUpdate.new(hub: hub, ops: app.update_ops, check: update_check, preflight: method(:restart_preflight)) if app.respond_to?(:update_ops)
486
488
  webrick = nil
@@ -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
@@ -500,12 +522,16 @@ module Samagotchi
500
522
  # lists, keep it for good. A live idle worker is stopped first; a turn
501
523
  # running in it or a delegate, a one-turn chi run's session and a scratch one
502
524
  # are refused (409). Background tasks it or a delegate started that
503
- # still run: 409 tasks_running, unless the body says {stop_tasks: true}
504
- # (then stopped first; the 200 names them, #task_fields).
525
+ # still run: 409 tasks_running (with +sessions+, how many the archive
526
+ # hides), unless the body says {stop_tasks: true} (then stopped first;
527
+ # the 200 names them, #task_fields). With {tasks: [ids]} too only
528
+ # those are stopped, and a running one not named refuses (the sheet's
529
+ # tap: #running_tasks_policy).
505
530
  def handle_archive(req, id)
506
531
  body = parse_json(request_body(req, 4096))
532
+ body = {} unless body.is_a?(Hash)
507
533
  result = @manager.archive_session(id, state_dir: @state_dir, wait: STOP_WAIT_SECONDS,
508
- running_tasks: running_tasks_policy(body.is_a?(Hash) && body["stop_tasks"]))
534
+ running_tasks: running_tasks_policy(body["stop_tasks"], body_tasks(body)))
509
535
  (result.archived + result.discarded).each { |sid| @hub&.touch(sid) }
510
536
  json_response(200, { status: "archived", session_id: result.id, archived: result.archived,
511
537
  stopped: result.stopped, discarded: result.discarded,
@@ -529,12 +555,14 @@ module Samagotchi
529
555
  # worker_running, as chi sessions delete without --force. A one-turn chi run's
530
556
  # session is always refused. Background tasks the delete's sessions
531
557
  # started that still run: 409 tasks_running, unless ?stop_tasks=true
532
- # (then stopped first; the 200 names them, #task_fields).
558
+ # (then stopped first; the 200 names them, #task_fields); with
559
+ # &tasks=<id,id> only those (#running_tasks_policy). Every session's
560
+ # stopped delegates go with it (SessionManager::DELEGATES).
533
561
  def handle_delete(req, id)
534
562
  result = @manager.delete_session(id, state_dir: @state_dir, stop: truthy_param?(req.GET["force"]),
535
563
  wait: STOP_WAIT_SECONDS, revive_previous: true, refuse_continuing: true,
536
564
  expect: req.GET["expect"],
537
- running_tasks: running_tasks_policy(req.GET["stop_tasks"]))
565
+ running_tasks: running_tasks_policy(req.GET["stop_tasks"], query_tasks(req)))
538
566
  touch_deleted(result[:id], result)
539
567
  json_response(200, { status: "deleted", session_id: result[:id], stopped: result[:stopped],
540
568
  unarchived: Array(result[:unarchived]), moved_back: Array(result[:moved_back]),
@@ -546,12 +574,13 @@ module Samagotchi
546
574
  delete_refused(e)
547
575
  end
548
576
 
549
- # DELETE /api/sessions/:id/chain?force=&stop_tasks=: every link of the
550
- # chain with their delegates (SessionManager.delete_chain). Query-only.
577
+ # DELETE /api/sessions/:id/chain?force=&stop_tasks=&tasks=: every link
578
+ # of the chain with their delegates (SessionManager.delete_chain).
579
+ # Query-only.
551
580
  def handle_delete_chain(req, id)
552
581
  result = @manager.delete_chain(id, state_dir: @state_dir, stop: truthy_param?(req.GET["force"]),
553
582
  wait: STOP_WAIT_SECONDS, expect: req.GET["expect"],
554
- running_tasks: running_tasks_policy(req.GET["stop_tasks"]))
583
+ running_tasks: running_tasks_policy(req.GET["stop_tasks"], query_tasks(req)))
555
584
  touch_deleted(id, result)
556
585
  json_response(200, { status: "deleted", session_id: id, deleted: result[:deleted], left: result[:left],
557
586
  left_running: result[:left_running], unarchived: result[:unarchived],
@@ -563,14 +592,19 @@ module Samagotchi
563
592
  delete_refused(e)
564
593
  end
565
594
 
566
- # GET /api/sessions/:id/delete_plan: what the delete sheet shows for a
567
- # chained session (SessionChain::Delete::Preview: the plan and the
568
- # refusals the delete itself runs), {chained: false} for one in no
569
- # chain. One session listing walk per call; the page asks only for a
570
- # chained session, as the sheet opens. No query or body read; no-store
571
- # (json_response's).
595
+ # GET /api/sessions/:id/delete_plan: what the delete sheet shows for
596
+ # any session (SessionChain::Delete::Preview: the plan and the
597
+ # refusals the delete itself runs, each choice's delegates, running
598
+ # tasks and workers); {chained: false, link} for one in no chain (an
599
+ # older page asked only for a chained one). A folder whose session
600
+ # file is gone answers too, as the delete still takes it. One shared
601
+ # session-row snapshot serves the link and chain choices; Links lists
602
+ # on its own. Each call read-only checks the session's continue lock.
603
+ # No query or body read; no-store (json_response's).
572
604
  def handle_delete_plan(_req, id)
573
- return unknown_session(id) unless Session.exist?(id, state_dir: @state_dir || Session.default_state_dir)
605
+ sd = @state_dir || Session.default_state_dir
606
+ on_disk = File.exist?(Session.session_file(id, state_dir: sd)) || Dir.exist?(Session.session_dir(id, state_dir: sd))
607
+ return unknown_session(id) unless on_disk
574
608
 
575
609
  require_relative "../session_chain/delete_preview"
576
610
  json_response(200, SessionChain::Delete::Preview.call(id, state_dir: @state_dir))
@@ -586,11 +620,28 @@ module Samagotchi
586
620
  end
587
621
 
588
622
  # A user's delete or archive: refused on running tasks (REFUSE), or,
589
- # asked to (+stop_tasks+: the page's second confirm, --stop-tasks),
590
- # stopped by "user".
591
- def running_tasks_policy(stop_tasks)
623
+ # asked to (+stop_tasks+: the page's sheet, --stop-tasks), stopped by
624
+ # "user". +named+ (task ids, the ones the sheet showed) makes the stop
625
+ # take only those and refuse on another that runs (Policy.stop's
626
+ # only); nil stops whatever runs. Without +stop_tasks+ it is ignored.
627
+ def running_tasks_policy(stop_tasks, named = nil)
592
628
  policies = SessionManager::RunningTasks::Policy
593
- truthy_param?(stop_tasks) ? policies.stop(by: "user") : policies::REFUSE
629
+ truthy_param?(stop_tasks) ? policies.stop(by: "user", only: named) : policies::REFUSE
630
+ end
631
+
632
+ # The body's tasks as ids, nil when not given; anything but a list of
633
+ # strings names none (so the stop refuses on any task that runs).
634
+ def body_tasks(body)
635
+ return nil unless body.key?("tasks")
636
+
637
+ body["tasks"].is_a?(Array) ? body["tasks"].grep(String) : []
638
+ end
639
+
640
+ # ?tasks=<id,id> as ids ([] for an empty one), nil when not given.
641
+ def query_tasks(req)
642
+ return nil unless req.GET.key?("tasks")
643
+
644
+ req.GET["tasks"].to_s.split(",").map(&:strip).reject(&:empty?)
594
645
  end
595
646
 
596
647
  # The 200's tasks_stopped, tasks_not_stopped and tasks_ended (each
@@ -604,8 +655,10 @@ module Samagotchi
604
655
  # was stopped, a chain's links (the words name them).
605
656
  def tasks_running_fields(error, op)
606
657
  links = error.respond_to?(:links) ? error.links : []
607
- { op: op, tasks: error.tasks.to_wire, worker_stopped: error.worker_stopped, stopped_worker: error.stopped_worker,
608
- links: (links unless links.empty?) }
658
+ fields = { op: op, tasks: error.tasks.to_wire, worker_stopped: error.worker_stopped, stopped_worker: error.stopped_worker,
659
+ links: (links unless links.empty?) }
660
+ fields[:stopped_workers] = error.stopped_workers if error.respond_to?(:stopped_workers) && !error.stopped_workers.empty?
661
+ fields
609
662
  end
610
663
 
611
664
  # 409 with the refusal's reason as its code, and what a remote client
@@ -654,6 +707,7 @@ module Samagotchi
654
707
  def archive_refused(error)
655
708
  if error.reason == :tasks_running
656
709
  return refusal_response(409, "tasks_running", error, session_id: error.session_id, reason: "tasks_running",
710
+ sessions: error.sessions,
657
711
  **tasks_running_fields(error, "archive"))
658
712
  end
659
713