synabun 2.4.2 → 2.4.4

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 (220) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +83 -34
  4. package/lib/release-npm-ci.mjs +23 -1
  5. package/mcp-server/dist/http.d.ts.map +1 -1
  6. package/mcp-server/dist/http.js +8 -1
  7. package/mcp-server/dist/http.js.map +1 -1
  8. package/mcp-server/dist/services/identity.d.ts +2 -0
  9. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  10. package/mcp-server/dist/services/identity.js +4 -0
  11. package/mcp-server/dist/services/identity.js.map +1 -1
  12. package/mcp-server/dist/services/memory-client.d.ts +5 -0
  13. package/mcp-server/dist/services/memory-client.d.ts.map +1 -1
  14. package/mcp-server/dist/services/memory-client.js +21 -2
  15. package/mcp-server/dist/services/memory-client.js.map +1 -1
  16. package/mcp-server/dist/services/memory-writer.d.ts +3 -0
  17. package/mcp-server/dist/services/memory-writer.d.ts.map +1 -1
  18. package/mcp-server/dist/services/memory-writer.js +7 -1
  19. package/mcp-server/dist/services/memory-writer.js.map +1 -1
  20. package/mcp-server/dist/services/neural-interface.d.ts +11 -1
  21. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  22. package/mcp-server/dist/services/neural-interface.js +68 -18
  23. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  24. package/mcp-server/dist/services/typesafe-config.d.ts +38 -2
  25. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  26. package/mcp-server/dist/services/typesafe-config.js +260 -8
  27. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  28. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  29. package/mcp-server/dist/tools/agents.d.ts +3 -1
  30. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  31. package/mcp-server/dist/tools/agents.js +11 -6
  32. package/mcp-server/dist/tools/agents.js.map +1 -1
  33. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -1
  34. package/mcp-server/dist/tools/browser-extension-setup.js +8 -2
  35. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -1
  36. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  37. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  38. package/mcp-server/dist/tools/browser-observe.js +113 -27
  39. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  40. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  41. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  42. package/mcp-server/dist/tools/browser-readers.js +17 -0
  43. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  44. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  45. package/mcp-server/dist/tools/remember.js +6 -2
  46. package/mcp-server/dist/tools/remember.js.map +1 -1
  47. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  48. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  49. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  50. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  51. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  52. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  53. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  54. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  55. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  56. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  57. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  58. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  59. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  60. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  61. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  62. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  63. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  64. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  65. package/mcp-server/package-lock.json +5 -5
  66. package/mcp-server/package.json +1 -1
  67. package/mcp-server/src/http.ts +8 -1
  68. package/mcp-server/src/services/identity.ts +5 -0
  69. package/mcp-server/src/services/memory-client.ts +32 -12
  70. package/mcp-server/src/services/memory-writer.ts +5 -2
  71. package/mcp-server/src/services/neural-interface.ts +66 -19
  72. package/mcp-server/src/services/typesafe-config.ts +268 -7
  73. package/mcp-server/src/tools/agents.ts +12 -6
  74. package/mcp-server/src/tools/browser-extension-setup.ts +8 -2
  75. package/mcp-server/src/tools/browser-observe.ts +117 -28
  76. package/mcp-server/src/tools/browser-readers.ts +19 -0
  77. package/mcp-server/src/tools/remember.ts +6 -1
  78. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  79. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  80. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  81. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  82. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  83. package/neural-interface/i18n/en.json +189 -1
  84. package/neural-interface/i18n/pt-BR.json +196 -8
  85. package/neural-interface/lib/assistant-api.js +123 -0
  86. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  87. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  88. package/neural-interface/lib/assistant-dispatch.js +302 -44
  89. package/neural-interface/lib/assistant-envelope.js +40 -0
  90. package/neural-interface/lib/assistant-memory.js +3 -1
  91. package/neural-interface/lib/assistant-persona.js +6 -0
  92. package/neural-interface/lib/assistant-router.js +18 -8
  93. package/neural-interface/lib/assistant-runtime.js +182 -11
  94. package/neural-interface/lib/assistant-task-prompt.js +15 -2
  95. package/neural-interface/lib/browser-connection-state.js +20 -0
  96. package/neural-interface/lib/browser-extension-adapter.js +221 -17
  97. package/neural-interface/lib/browser-extension-archive.js +149 -0
  98. package/neural-interface/lib/browser-extension-bridge.js +46 -10
  99. package/neural-interface/lib/browser-extension-folder.js +635 -76
  100. package/neural-interface/lib/browser-extension-package.js +201 -0
  101. package/neural-interface/lib/browser-extension-pin.js +84 -0
  102. package/neural-interface/lib/browser-extension-pin.json +35 -0
  103. package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +111 -13
  104. package/neural-interface/lib/browser-extension-setup.js +108 -19
  105. package/neural-interface/lib/browser-extension-update.js +104 -0
  106. package/neural-interface/lib/browser-extraction.js +38 -14
  107. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  108. package/neural-interface/lib/claude-history.js +12 -1
  109. package/neural-interface/lib/cli-install.js +23 -3
  110. package/neural-interface/lib/cli-update-planner.js +67 -4
  111. package/neural-interface/lib/confined-fs.js +25 -0
  112. package/neural-interface/lib/coordination/operations.js +2 -0
  113. package/neural-interface/lib/db.js +39 -16
  114. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  115. package/neural-interface/lib/git-bash/manager.js +28 -3
  116. package/neural-interface/lib/git-status-runner.js +31 -3
  117. package/neural-interface/lib/loop-inventory.js +162 -0
  118. package/neural-interface/lib/loop-stall.js +74 -4
  119. package/neural-interface/lib/memory-session-capture.js +157 -66
  120. package/neural-interface/lib/native-loop-providers.js +82 -13
  121. package/neural-interface/lib/native-loop-runtime.js +23 -2
  122. package/neural-interface/lib/opencode-protocol.js +4 -2
  123. package/neural-interface/lib/opencode-shell-read.js +107 -0
  124. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  125. package/neural-interface/lib/opencode-turn-release.js +173 -0
  126. package/neural-interface/lib/opencode-v2-client.js +4 -1
  127. package/neural-interface/lib/opencode-v2-ws-requests.js +34 -0
  128. package/neural-interface/lib/opencode2-client.js +341 -6
  129. package/neural-interface/lib/opencode2-translate.js +161 -4
  130. package/neural-interface/lib/peer-identity.js +62 -16
  131. package/neural-interface/lib/session-cache-builder.js +66 -18
  132. package/neural-interface/lib/session-capture-gate.js +42 -0
  133. package/neural-interface/lib/session-indexer.js +28 -20
  134. package/neural-interface/lib/teams/scheduler.js +3 -2
  135. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  136. package/neural-interface/lib/ui-blob-api.js +14 -5
  137. package/neural-interface/lib/ui-blob-store.js +302 -39
  138. package/neural-interface/lib/whatsapp/bridge.js +52 -6
  139. package/neural-interface/package-lock.json +5 -5
  140. package/neural-interface/package.json +1 -1
  141. package/neural-interface/public/extension-setup.html +6 -2
  142. package/neural-interface/public/shared/agy/agy-panel.js +38 -10
  143. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  144. package/neural-interface/public/shared/assistant/asst-api.js +67 -0
  145. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  146. package/neural-interface/public/shared/assistant/asst-panel.js +354 -11
  147. package/neural-interface/public/shared/assistant/asst-rack-styles.js +23 -0
  148. package/neural-interface/public/shared/assistant/asst-render.js +343 -10
  149. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  150. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  151. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  152. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  153. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  154. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  155. package/neural-interface/public/shared/assistant/asst-styles.js +21 -0
  156. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  157. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  158. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  159. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  160. package/neural-interface/public/shared/browser-extension-updates.js +88 -0
  161. package/neural-interface/public/shared/cdx/cdx-tabs.js +25 -0
  162. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  163. package/neural-interface/public/shared/extension-setup/es-page.js +25 -12
  164. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  165. package/neural-interface/public/shared/extension-update-view.js +34 -0
  166. package/neural-interface/public/shared/mtc/mtc-panel.js +17 -2
  167. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
  168. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
  169. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +34 -2
  170. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  171. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +26 -1
  172. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +39 -6
  173. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +20 -1
  174. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  175. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +350 -0
  176. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  177. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  178. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +40 -0
  179. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  180. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  181. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  182. package/neural-interface/public/shared/settings/settings-browser-extension.js +61 -13
  183. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  184. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  185. package/neural-interface/public/shared/styles.css +4 -0
  186. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  187. package/neural-interface/public/shared/tray-auto-close.js +36 -6
  188. package/neural-interface/public/shared/ui-claude-panel.js +130 -1
  189. package/neural-interface/public/shared/ui-native-loop-router.js +45 -3
  190. package/neural-interface/public/shared/ui-notifications.js +23 -4
  191. package/neural-interface/public/shared/ui-scroll-follow.js +4 -0
  192. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  193. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  194. package/neural-interface/public/shared/worker-end.js +18 -0
  195. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  196. package/neural-interface/scripts/rebuild-pty.js +10 -0
  197. package/neural-interface/server.js +725 -308
  198. package/npm-shrinkwrap.json +5 -5
  199. package/package.json +1 -2
  200. package/browser-extension/content.js +0 -231
  201. package/browser-extension/engine.js +0 -658
  202. package/browser-extension/icons/icon-128.png +0 -0
  203. package/browser-extension/icons/icon-16.png +0 -0
  204. package/browser-extension/icons/icon-32.png +0 -0
  205. package/browser-extension/icons/icon-48.png +0 -0
  206. package/browser-extension/icons/status-off-16.png +0 -0
  207. package/browser-extension/icons/status-off-32.png +0 -0
  208. package/browser-extension/icons/status-off-48.png +0 -0
  209. package/browser-extension/icons/status-on-16.png +0 -0
  210. package/browser-extension/icons/status-on-32.png +0 -0
  211. package/browser-extension/icons/status-on-48.png +0 -0
  212. package/browser-extension/manifest.json +0 -58
  213. package/browser-extension/popup-strings.js +0 -250
  214. package/browser-extension/popup-view.js +0 -151
  215. package/browser-extension/popup.css +0 -166
  216. package/browser-extension/popup.html +0 -108
  217. package/browser-extension/popup.js +0 -359
  218. package/browser-extension/service-worker.js +0 -283
  219. package/browser-extension/setup-content.js +0 -36
  220. package/browser-extension/tokens.css +0 -326
@@ -0,0 +1,527 @@
1
+ // ─────────────────────────────────────────────────────────────────────────────
2
+ // Background tasks of one conversation (no DOM, no socket, no provider)
3
+ //
4
+ // A shell command the agent started in the background, or a watch (Monitor),
5
+ // returns at once: its tool card closes while the work goes on for minutes or
6
+ // hours. This registry keeps what the session itself said about each one, so a
7
+ // panel can show what still runs, what it is doing now and how it ended.
8
+ //
9
+ // It knows no provider. An adapter turns a provider's own stream into facts
10
+ // (bg-tasks-claude.js for Claude Code; Codex, OpenCode and Antigravity can add
11
+ // theirs) and `applyBgFact` folds them in:
12
+ // { kind: 'call', toolUseId, type: 'shell' | 'watch', description, command, timeoutMs, at }
13
+ // { kind: 'result', toolUseId, taskId, outputFile, timeoutMs, persistent, isError, at }
14
+ // { kind: 'started', taskId, toolUseId, type, description, at } (the provider's own task start)
15
+ // { kind: 'notice', taskId, toolUseId, status, summary, outputFile, event, reason, at, uid }
16
+ // { kind: 'updated', taskId, status, error, endedAt }
17
+ // { kind: 'live', tasks: [{ id, type, description, ambient }] } (the whole live set: replace)
18
+ // { kind: 'stopping', taskId, by: 'owner' | 'agent' } / { kind: 'stop-failed', taskId, error }
19
+ // { kind: 'ended-all', at } (the process that ran them is gone)
20
+ // The server rebuilds the same registry from the transcript (lib/claude-bg-tasks.js), so a reload or a restart
21
+ // starts from what the session recorded, never from page memory. What a task printed is never in here: a panel
22
+ // reads that in pages, for the owner's eyes only.
23
+ // ─────────────────────────────────────────────────────────────────────────────
24
+
25
+ /** The English words of the view; `bgTasks.*` in i18n/en.json must equal them (tests/bg-tasks-model.test.mjs). */
26
+ export const BG_TASKS_COPY = Object.freeze({
27
+ title: 'Background tasks',
28
+ toggle: 'Background tasks',
29
+ badgeTitle: '{count} running in the background',
30
+ back: 'Back to the conversation',
31
+ empty: 'Nothing has run in the background in this conversation.',
32
+ clearFinished: 'Clear finished',
33
+ kindShell: 'shell',
34
+ kindWatch: 'watch',
35
+ statusRunning: 'running',
36
+ statusCompleted: 'completed',
37
+ statusFailed: 'failed',
38
+ statusStopped: 'stopped',
39
+ statusExpired: 'expired',
40
+ statusEnded: 'ended',
41
+ statusUnknown: 'checking',
42
+ stoppedByOwner: 'Stopped by you',
43
+ stoppedByAgent: 'Stopped by the agent',
44
+ stopping: 'Stopping…',
45
+ stop: 'Stop',
46
+ stopConfirm: 'Stop this task?',
47
+ stopYes: 'Stop it',
48
+ stopNo: 'Keep running',
49
+ stopFailed: 'Could not stop it: {error}',
50
+ exitCode: 'exit {code}',
51
+ events: 'Events',
52
+ eventCount: '{count} events',
53
+ eventCountOne: '1 event',
54
+ noEvents: 'No events yet.',
55
+ expiresIn: 'expires in {time}',
56
+ outputLabel: 'Output of the background task',
57
+ loadFull: 'Open full output',
58
+ loading: 'Loading…',
59
+ jump: 'Jump to latest',
60
+ copy: 'Copy',
61
+ copied: 'Copied',
62
+ noOutputYet: 'Nothing printed yet.',
63
+ noOutput: 'It printed nothing.',
64
+ outputGone: 'Its output file is no longer there.',
65
+ needsRestart: 'Its output shows once the SynaBun server has restarted.',
66
+ outputPartial: 'Showing the last {shown} of {size}.',
67
+ outputCapped: 'Showing the last {shown} of {size}: the whole output is too long to show here.',
68
+ noticeFinished: '{kind} {status}',
69
+ noticeEvent: 'Watch event',
70
+ noticeStale: 'stale: the task had already ended',
71
+ noticeOpen: 'Show in Background tasks',
72
+ ended: 'The session that ran it is gone.',
73
+ });
74
+
75
+ /** A `BG_TASKS_COPY` sentence with its `{params}` filled in. */
76
+ export function fillBgCopy(key, params = {}) {
77
+ return String(BG_TASKS_COPY[key] ?? key).replace(/\{(\w+)\}/g, (whole, name) => (params[name] != null ? params[name] : whole));
78
+ }
79
+
80
+ const RUNNING = new Set(['running', 'unknown']);
81
+ export const FINISHED_STATUSES = Object.freeze(['completed', 'failed', 'stopped', 'expired', 'ended']);
82
+ const FINISHED = new Set(FINISHED_STATUSES);
83
+ /** How many finished tasks a registry keeps (the oldest go first). */
84
+ export const MAX_FINISHED_TASKS = 30;
85
+ /** How many tool calls it remembers while their results are on the way. */
86
+ const MAX_CALLS = 200;
87
+ /** How many events of a watch it keeps (the count goes on). */
88
+ export const MAX_TASK_EVENTS = 50;
89
+ const MAX_TEXT = 300;
90
+ const MAX_EVENT = 2000;
91
+
92
+ const clip = (value, n = MAX_TEXT) => {
93
+ const s = String(value ?? '').replace(/\s+$/u, '');
94
+ return s.length > n ? `${s.slice(0, n - 1)}…` : s;
95
+ };
96
+ const plainId = (value) => (typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : '');
97
+ const time = (value, fallback) => (Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : fallback);
98
+
99
+ export function createBgRegistry() {
100
+ return { tasks: new Map(), calls: new Map(), seen: new Set(), cleared: new Set(), version: 0, liveSeen: false };
101
+ }
102
+
103
+ export const isBgRunning = (task) => !!task && RUNNING.has(task.status);
104
+ export const isBgFinished = (task) => !!task && FINISHED.has(task.status);
105
+
106
+ function newTask(id, at) {
107
+ return {
108
+ id, type: 'shell', toolUseId: '', description: '', command: '', outputFile: '',
109
+ startedAt: at, endedAt: 0, status: 'running', exitCode: null, summary: '', error: '',
110
+ events: [], eventCount: 0, lastEvent: '', timeoutMs: 0, persistent: false,
111
+ stoppedBy: '', stopping: false, stopError: '', seenLive: false,
112
+ };
113
+ }
114
+
115
+ function finish(task, status, at) {
116
+ task.status = status;
117
+ task.stopping = false;
118
+ if (!task.endedAt) task.endedAt = at;
119
+ }
120
+
121
+ /** The exit code a summary names ("… completed (exit code 2)"), or null. */
122
+ export function exitCodeOf(summary) {
123
+ const m = /exit code:?\s*(-?\d+)/i.exec(String(summary || ''));
124
+ return m ? Number(m[1]) : null;
125
+ }
126
+
127
+ /** Whether a watch's notice says its deadline ended it. */
128
+ export function saysExpired(summary) {
129
+ return /\bexpired\b|\btimed out\b/i.test(String(summary || ''));
130
+ }
131
+
132
+ const TAG = (body, name) => {
133
+ const m = new RegExp(`<${name}>([\\s\\S]*?)</${name}>`).exec(body);
134
+ return m ? m[1].trim() : '';
135
+ };
136
+
137
+ /**
138
+ * Every `<task-notification>` block of a text, read into fields. Text outside the tags is the CLI's own advice to
139
+ * the model and is left out. `{ taskId, toolUseId, outputFile, status, summary, event }` per block.
140
+ */
141
+ export function parseTaskNotifications(text) {
142
+ const out = [];
143
+ const src = String(text || '');
144
+ if (!src.includes('<task-notification>')) return out;
145
+ const re = /<task-notification>([\s\S]*?)<\/task-notification>/g;
146
+ let m;
147
+ while ((m = re.exec(src)) && out.length < 50) {
148
+ const body = m[1];
149
+ const taskId = plainId(TAG(body, 'task-id'));
150
+ if (!taskId) continue;
151
+ out.push({
152
+ taskId,
153
+ toolUseId: plainId(TAG(body, 'tool-use-id')),
154
+ outputFile: TAG(body, 'output-file').slice(0, 4096),
155
+ status: TAG(body, 'status').toLowerCase().slice(0, 40),
156
+ summary: clip(TAG(body, 'summary')),
157
+ event: TAG(body, 'event').slice(0, MAX_EVENT),
158
+ });
159
+ }
160
+ return out;
161
+ }
162
+
163
+ /** The kind a provider's task type stands for, or '' when it is not a shell or a watch. */
164
+ export function kindOfTaskType(type) {
165
+ const t = String(type || '').toLowerCase();
166
+ if (!t) return '';
167
+ if (t.includes('monitor') || t === 'watch') return 'watch';
168
+ if (t === 'local_bash' || t === 'shell' || t === 'bash') return 'shell';
169
+ return '';
170
+ }
171
+
172
+ function rememberCall(reg, fact) {
173
+ const id = plainId(fact.toolUseId);
174
+ if (!id) return;
175
+ reg.calls.set(id, {
176
+ type: fact.type === 'watch' ? 'watch' : 'shell',
177
+ description: clip(fact.description, 200),
178
+ command: clip(fact.command, 1000),
179
+ timeoutMs: Math.max(0, Number(fact.timeoutMs) || 0),
180
+ background: fact.background === true,
181
+ at: time(fact.at, Date.now()),
182
+ });
183
+ while (reg.calls.size > MAX_CALLS) reg.calls.delete(reg.calls.keys().next().value);
184
+ }
185
+
186
+ function taskFor(reg, taskId, toolUseId, at) {
187
+ const id = plainId(taskId);
188
+ if (!id || reg.cleared.has(id)) return null;
189
+ let task = reg.tasks.get(id);
190
+ if (!task) {
191
+ task = newTask(id, at);
192
+ reg.tasks.set(id, task);
193
+ }
194
+ const callId = plainId(toolUseId);
195
+ if (callId && !task.toolUseId) task.toolUseId = callId;
196
+ const call = task.toolUseId ? reg.calls.get(task.toolUseId) : null;
197
+ if (call) {
198
+ task.type = call.type;
199
+ if (!task.description) task.description = call.description;
200
+ if (!task.command) task.command = call.command;
201
+ if (!task.timeoutMs && call.timeoutMs) task.timeoutMs = call.timeoutMs;
202
+ if (call.at && call.at < task.startedAt) task.startedAt = call.at;
203
+ }
204
+ return task;
205
+ }
206
+
207
+ function trimFinished(reg) {
208
+ const finished = [...reg.tasks.values()].filter(isBgFinished).sort((a, b) => a.endedAt - b.endedAt);
209
+ for (const old of finished.slice(0, Math.max(0, finished.length - MAX_FINISHED_TASKS))) reg.tasks.delete(old.id);
210
+ }
211
+
212
+ /**
213
+ * Fold one fact into the registry.
214
+ * @returns {{ task: object|null, notice: object|null }} what changed; `notice` (for a notice fact) carries
215
+ * `stale: true` when its task had already ended before it arrived
216
+ */
217
+ export function applyBgFact(reg, fact, now = Date.now()) {
218
+ const none = { task: null, notice: null };
219
+ if (!reg || !fact || typeof fact !== 'object') return none;
220
+ const at = time(fact.at, now);
221
+ let task = null;
222
+ let notice = null;
223
+ switch (fact.kind) {
224
+ case 'call':
225
+ rememberCall(reg, fact);
226
+ return none;
227
+ case 'result': {
228
+ const call = reg.calls.get(plainId(fact.toolUseId));
229
+ // Only a call that went to the background has a task id in its result.
230
+ if (!call || fact.isError || !plainId(fact.taskId)) return none;
231
+ task = taskFor(reg, fact.taskId, fact.toolUseId, at);
232
+ if (!task) return none;
233
+ if (fact.outputFile && !task.outputFile) task.outputFile = String(fact.outputFile).slice(0, 4096);
234
+ if (Number(fact.timeoutMs) > 0) task.timeoutMs = Number(fact.timeoutMs);
235
+ if (fact.persistent === true) task.persistent = true;
236
+ break;
237
+ }
238
+ case 'started': {
239
+ const kind = kindOfTaskType(fact.type);
240
+ const known = reg.tasks.has(plainId(fact.taskId)) || reg.calls.has(plainId(fact.toolUseId));
241
+ // Agents, workflows and MCP tasks have cards of their own: only shells and watches are listed.
242
+ if (!kind && !known) return none;
243
+ task = taskFor(reg, fact.taskId, fact.toolUseId, at);
244
+ if (!task) return none;
245
+ if (kind && !reg.calls.has(task.toolUseId)) task.type = kind;
246
+ if (!task.description && fact.description) task.description = clip(fact.description, 200);
247
+ break;
248
+ }
249
+ case 'notice': {
250
+ const id = plainId(fact.taskId);
251
+ if (!id) return none;
252
+ // One delivery is folded once (a stream can say it twice: as it is queued and as it is read).
253
+ if (fact.uid) {
254
+ if (reg.seen.has(fact.uid)) return none;
255
+ reg.seen.add(fact.uid);
256
+ if (reg.seen.size > 2000) reg.seen.delete(reg.seen.values().next().value);
257
+ }
258
+ const existed = reg.tasks.get(id);
259
+ const wasFinished = isBgFinished(existed);
260
+ // A notice for a task that is not a shell or a watch of this registry (an agent's report) is not listed.
261
+ if (!existed && !reg.calls.has(plainId(fact.toolUseId)) && !fact.event && !/^(?:background command|monitor)\b/i.test(String(fact.summary || ''))) return none;
262
+ task = taskFor(reg, id, fact.toolUseId, at);
263
+ if (!task) return none;
264
+ if (!reg.calls.has(task.toolUseId) && (fact.event || /^monitor\b/i.test(String(fact.summary || '')))) task.type = 'watch';
265
+ if (fact.outputFile && !task.outputFile) task.outputFile = String(fact.outputFile).slice(0, 4096);
266
+ const status = String(fact.status || '').toLowerCase();
267
+ if (fact.event) {
268
+ task.eventCount += 1;
269
+ task.lastEvent = clip(String(fact.event).split('\n').filter(Boolean).pop() || '', 200);
270
+ task.events.push({ at, text: String(fact.event).slice(0, MAX_EVENT) });
271
+ if (task.events.length > MAX_TASK_EVENTS) task.events.splice(0, task.events.length - MAX_TASK_EVENTS);
272
+ }
273
+ const isFinal = status === 'completed' || status === 'failed' || status === 'stopped' || status === 'killed';
274
+ // After the end, a summary is only taken from another final report (a late event keeps the end's words).
275
+ if (fact.summary && (!wasFinished || isFinal)) task.summary = clip(fact.summary);
276
+ if (isFinal) {
277
+ const code = exitCodeOf(fact.summary);
278
+ if (code != null) task.exitCode = code;
279
+ let end = status === 'killed' ? 'stopped' : status;
280
+ if (task.type === 'watch' && saysExpired(fact.summary)) end = 'expired';
281
+ if (!wasFinished) finish(task, end, at);
282
+ if (end === 'stopped' && !task.stoppedBy) task.stoppedBy = fact.reason === 'worker_restart' ? '' : 'agent';
283
+ }
284
+ notice = {
285
+ taskId: id, type: task.type, description: task.description, status: status || (fact.event ? 'event' : ''),
286
+ summary: clip(fact.summary), event: fact.event ? clip(fact.event, 600) : '', exitCode: task.exitCode,
287
+ // Something the task reported after it had ended (a watch's event behind its end) is stale; the same end
288
+ // told twice (the SDK's own report and the queued one) is a repeat, which a transcript shows once.
289
+ stale: wasFinished && !isFinal, repeat: wasFinished && isFinal, at,
290
+ };
291
+ break;
292
+ }
293
+ case 'updated': {
294
+ task = reg.tasks.get(plainId(fact.taskId)) || null;
295
+ if (!task) return none;
296
+ const status = String(fact.status || '').toLowerCase();
297
+ if (fact.error) task.error = clip(fact.error);
298
+ if ((status === 'completed' || status === 'failed' || status === 'killed') && !isBgFinished(task)) {
299
+ finish(task, status === 'killed' ? 'stopped' : status, time(fact.endedAt, at));
300
+ }
301
+ break;
302
+ }
303
+ case 'live': {
304
+ // The provider's whole live set: a task in it runs; one it no longer names has ended (its own notice may
305
+ // never come when the process is gone). A task the registry learnt about while no live set was known yet
306
+ // (rebuilt from a transcript: 'unknown') is decided by the first set either way.
307
+ const list = Array.isArray(fact.tasks) ? fact.tasks : [];
308
+ const live = new Set(list.map(t => plainId(t?.id)).filter(Boolean));
309
+ reg.liveSeen = true;
310
+ let changed = false;
311
+ for (const t of reg.tasks.values()) {
312
+ if (live.has(t.id)) {
313
+ if (t.status === 'unknown') { t.status = 'running'; changed = true; }
314
+ t.seenLive = true;
315
+ continue;
316
+ }
317
+ if (t.status === 'unknown' || (t.status === 'running' && t.seenLive)) { finish(t, 'ended', at); changed = true; }
318
+ }
319
+ // A live shell or watch this registry has no entry for (a page that started after it did) gets one.
320
+ for (const t of list) {
321
+ const id = plainId(t?.id);
322
+ const kind = kindOfTaskType(t?.type);
323
+ if (!id || !kind || t?.ambient === true && kind !== 'watch' || reg.tasks.has(id) || reg.cleared.has(id)) continue;
324
+ const entry = newTask(id, at);
325
+ entry.type = kind;
326
+ entry.description = clip(t.description || '', 200);
327
+ entry.seenLive = true;
328
+ reg.tasks.set(id, entry);
329
+ changed = true;
330
+ }
331
+ if (changed) reg.version += 1;
332
+ trimFinished(reg);
333
+ return { task: null, notice: null, changed };
334
+ }
335
+ case 'stopping': {
336
+ task = reg.tasks.get(plainId(fact.taskId)) || null;
337
+ if (!task) return none;
338
+ task.stoppedBy = fact.by === 'agent' ? 'agent' : 'owner';
339
+ task.stopError = '';
340
+ if (isBgRunning(task)) task.stopping = true;
341
+ break;
342
+ }
343
+ case 'stop-failed': {
344
+ task = reg.tasks.get(plainId(fact.taskId)) || null;
345
+ if (!task) return none;
346
+ task.stopping = false;
347
+ if (task.stoppedBy === 'owner' && isBgRunning(task)) task.stoppedBy = '';
348
+ task.stopError = clip(fact.error || 'unknown error', 200);
349
+ break;
350
+ }
351
+ case 'ended-all': {
352
+ let changed = false;
353
+ for (const t of reg.tasks.values()) if (isBgRunning(t)) { finish(t, 'ended', at); changed = true; }
354
+ if (changed) reg.version += 1;
355
+ return { task: null, notice: null, changed };
356
+ }
357
+ default:
358
+ return none;
359
+ }
360
+ reg.version += 1;
361
+ trimFinished(reg);
362
+ return { task, notice };
363
+ }
364
+
365
+ /** How many tasks still run (the badge). */
366
+ export function runningBgCount(reg) {
367
+ let n = 0;
368
+ for (const t of reg?.tasks?.values?.() || []) if (isBgRunning(t)) n += 1;
369
+ return n;
370
+ }
371
+
372
+ /** Forget the finished tasks (until the tab closes, a rebuild does not bring them back). @returns how many */
373
+ export function clearFinishedBg(reg) {
374
+ let n = 0;
375
+ for (const t of [...(reg?.tasks?.values?.() || [])]) {
376
+ if (!isBgFinished(t)) continue;
377
+ reg.tasks.delete(t.id);
378
+ reg.cleared.add(t.id);
379
+ n += 1;
380
+ }
381
+ if (n) reg.version += 1;
382
+ return n;
383
+ }
384
+
385
+ /** "42s", "3m 05s", "1h 02m". */
386
+ export function fmtBgDuration(ms) {
387
+ const s = Math.max(0, Math.floor((Number(ms) || 0) / 1000));
388
+ if (s < 60) return `${s}s`;
389
+ const m = Math.floor(s / 60);
390
+ if (m < 60) return `${m}m ${String(s % 60).padStart(2, '0')}s`;
391
+ return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`;
392
+ }
393
+
394
+ const STATUS_KEYS = { running: 'statusRunning', completed: 'statusCompleted', failed: 'statusFailed', stopped: 'statusStopped', expired: 'statusExpired', ended: 'statusEnded', unknown: 'statusUnknown' };
395
+
396
+ /**
397
+ * The rows of the view: running first (newest first), then what finished (newest first). Words are copy keys,
398
+ * so a panel shows them in its locale: `{ key, params }`.
399
+ */
400
+ export function bgTaskRows(reg, now = Date.now()) {
401
+ const list = [...(reg?.tasks?.values?.() || [])];
402
+ list.sort((a, b) => (isBgRunning(a) ? 0 : 1) - (isBgRunning(b) ? 0 : 1)
403
+ || (isBgRunning(a) ? b.startedAt - a.startedAt : (b.endedAt || 0) - (a.endedAt || 0)));
404
+ return list.map((t) => {
405
+ const running = isBgRunning(t);
406
+ const elapsed = running ? now - t.startedAt : ((t.endedAt || now) - t.startedAt);
407
+ let note = null;
408
+ if (t.stopping) note = { key: 'stopping' };
409
+ else if (t.status === 'stopped' && t.stoppedBy === 'owner') note = { key: 'stoppedByOwner' };
410
+ else if (t.status === 'stopped' && t.stoppedBy === 'agent') note = { key: 'stoppedByAgent' };
411
+ else if (t.stopError) note = { key: 'stopFailed', params: { error: t.stopError } };
412
+ else if (t.status === 'ended') note = { key: 'ended' };
413
+ let expires = null;
414
+ if (running && t.type === 'watch' && t.timeoutMs > 0 && !t.persistent) {
415
+ const left = t.startedAt + t.timeoutMs - now;
416
+ if (left > 0) expires = { key: 'expiresIn', params: { time: fmtBgDuration(left) } };
417
+ }
418
+ return {
419
+ id: t.id,
420
+ type: t.type,
421
+ kindKey: t.type === 'watch' ? 'kindWatch' : 'kindShell',
422
+ description: t.description || t.command || t.id,
423
+ command: t.command,
424
+ status: t.status,
425
+ statusKey: STATUS_KEYS[t.status] || 'statusUnknown',
426
+ running,
427
+ finished: !running,
428
+ canStop: running && !t.stopping,
429
+ duration: elapsed > 0 ? fmtBgDuration(elapsed) : '',
430
+ exitCode: t.exitCode,
431
+ summary: t.summary,
432
+ note,
433
+ expires,
434
+ eventCount: t.eventCount,
435
+ lastEvent: t.lastEvent,
436
+ events: t.events.slice(),
437
+ hasOutput: !!t.outputFile,
438
+ };
439
+ });
440
+ }
441
+
442
+ /** One line for a task-notification card in the transcript: `{ key, params, stale }` plus the plain fields. */
443
+ export function noticeCardView(notice, task = null) {
444
+ if (!notice) return null;
445
+ const kindKey = (task?.type || notice.type) === 'watch' ? 'kindWatch' : 'kindShell';
446
+ const isEvent = !!notice.event && !['completed', 'failed', 'stopped', 'killed'].includes(notice.status);
447
+ const status = notice.status === 'killed' ? 'stopped' : notice.status;
448
+ return {
449
+ taskId: notice.taskId,
450
+ kindKey,
451
+ isEvent,
452
+ statusKey: isEvent ? '' : (STATUS_KEYS[(task?.type === 'watch' && saysExpired(notice.summary)) ? 'expired' : status] || ''),
453
+ description: task?.description || notice.description || notice.summary || notice.taskId,
454
+ detail: isEvent ? String(notice.event).split('\n').filter(Boolean).pop() || '' : (notice.summary || ''),
455
+ exitCode: notice.exitCode,
456
+ stale: !!notice.stale,
457
+ };
458
+ }
459
+
460
+ /** What a panel keeps between reloads besides the transcript: which finished tasks were cleared, which the owner stopped. */
461
+ export function bgPrefsOf(reg) {
462
+ const ownerStopped = [...(reg?.tasks?.values?.() || [])].filter(t => t.stoppedBy === 'owner').map(t => t.id);
463
+ return { cleared: [...(reg?.cleared || [])].slice(-200), ownerStopped: ownerStopped.slice(-200) };
464
+ }
465
+
466
+ /** Put a registry rebuilt by the server (`serializeBgRegistry`) under this one, keeping what the page knew. */
467
+ export function mergeRebuiltBg(reg, rebuilt, prefs = null) {
468
+ if (!reg || !rebuilt) return false;
469
+ for (const id of Array.isArray(prefs?.cleared) ? prefs.cleared : []) { const p = plainId(id); if (p) reg.cleared.add(p); }
470
+ const owner = new Set((Array.isArray(prefs?.ownerStopped) ? prefs.ownerStopped : []).map(plainId).filter(Boolean));
471
+ let changed = false;
472
+ for (const raw of Array.isArray(rebuilt.tasks) ? rebuilt.tasks : []) {
473
+ const id = plainId(raw?.id);
474
+ if (!id || reg.cleared.has(id)) continue;
475
+ const mine = reg.tasks.get(id);
476
+ const incoming = { ...newTask(id, time(raw.startedAt, Date.now())), ...pickTask(raw) };
477
+ if (owner.has(id) && incoming.status === 'stopped') incoming.stoppedBy = 'owner';
478
+ if (!mine) {
479
+ // A task the transcript has no end for runs only if the live set says so.
480
+ if (incoming.status === 'running') incoming.status = reg.liveSeen ? 'ended' : 'unknown';
481
+ if (incoming.status === 'ended' && !incoming.endedAt) incoming.endedAt = Date.now();
482
+ reg.tasks.set(id, incoming);
483
+ changed = true;
484
+ continue;
485
+ }
486
+ // What the page saw live is newer; the transcript fills what it lacks (events before the reload, the path).
487
+ if (!mine.outputFile && incoming.outputFile) { mine.outputFile = incoming.outputFile; changed = true; }
488
+ if (!mine.command && incoming.command) { mine.command = incoming.command; changed = true; }
489
+ if (!mine.description && incoming.description) { mine.description = incoming.description; changed = true; }
490
+ if (incoming.eventCount > mine.eventCount) {
491
+ mine.eventCount = incoming.eventCount; mine.events = incoming.events; mine.lastEvent = incoming.lastEvent; changed = true;
492
+ }
493
+ if (isBgFinished(incoming) && !isBgFinished(mine)) {
494
+ Object.assign(mine, { status: incoming.status, endedAt: incoming.endedAt, exitCode: incoming.exitCode, summary: incoming.summary, stopping: false });
495
+ if (owner.has(id) && incoming.status === 'stopped') mine.stoppedBy = 'owner';
496
+ changed = true;
497
+ }
498
+ if (owner.has(id) && mine.status === 'stopped') mine.stoppedBy = 'owner';
499
+ }
500
+ if (changed) { reg.version += 1; trimFinished(reg); }
501
+ return changed;
502
+ }
503
+
504
+ const TASK_FIELDS = ['type', 'toolUseId', 'description', 'command', 'outputFile', 'startedAt', 'endedAt', 'status', 'exitCode', 'summary', 'error', 'eventCount', 'lastEvent', 'timeoutMs', 'persistent', 'stoppedBy'];
505
+
506
+ function pickTask(raw) {
507
+ const out = {};
508
+ for (const k of TASK_FIELDS) if (raw[k] !== undefined) out[k] = raw[k];
509
+ out.type = raw.type === 'watch' ? 'watch' : 'shell';
510
+ out.status = RUNNING.has(raw.status) || FINISHED.has(raw.status) ? raw.status : 'running';
511
+ out.events = (Array.isArray(raw.events) ? raw.events : []).slice(-MAX_TASK_EVENTS).map(e => ({ at: time(e?.at, 0), text: String(e?.text ?? '').slice(0, MAX_EVENT) }));
512
+ out.exitCode = Number.isFinite(raw.exitCode) ? raw.exitCode : null;
513
+ return out;
514
+ }
515
+
516
+ /** The registry as JSON (the server's rebuild, a test's snapshot). */
517
+ export function serializeBgRegistry(reg) {
518
+ return {
519
+ tasks: [...(reg?.tasks?.values?.() || [])].map((t) => {
520
+ const out = {};
521
+ for (const k of TASK_FIELDS) out[k] = t[k];
522
+ out.events = t.events.slice(-MAX_TASK_EVENTS);
523
+ out.id = t.id;
524
+ return out;
525
+ }),
526
+ };
527
+ }