synabun 2.4.3 → 2.4.5

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 (177) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +66 -36
  4. package/docs/whatsapp.md +3 -3
  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 +12 -1
  21. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  22. package/mcp-server/dist/services/neural-interface.js +68 -17
  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 +19 -4
  30. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  31. package/mcp-server/dist/tools/agents.js +85 -17
  32. package/mcp-server/dist/tools/agents.js.map +1 -1
  33. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  34. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  35. package/mcp-server/dist/tools/browser-observe.js +113 -27
  36. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  37. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  38. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  39. package/mcp-server/dist/tools/browser-readers.js +17 -0
  40. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  41. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  42. package/mcp-server/dist/tools/remember.js +6 -2
  43. package/mcp-server/dist/tools/remember.js.map +1 -1
  44. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  45. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  46. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  47. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  48. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  49. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  50. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  51. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  52. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  53. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  54. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  55. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  56. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  57. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  58. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  59. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  60. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  61. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  62. package/mcp-server/package-lock.json +2 -2
  63. package/mcp-server/package.json +1 -1
  64. package/mcp-server/src/http.ts +8 -1
  65. package/mcp-server/src/services/identity.ts +5 -0
  66. package/mcp-server/src/services/memory-client.ts +32 -12
  67. package/mcp-server/src/services/memory-writer.ts +5 -2
  68. package/mcp-server/src/services/neural-interface.ts +67 -19
  69. package/mcp-server/src/services/typesafe-config.ts +268 -7
  70. package/mcp-server/src/tools/agents.ts +79 -17
  71. package/mcp-server/src/tools/browser-observe.ts +117 -28
  72. package/mcp-server/src/tools/browser-readers.ts +19 -0
  73. package/mcp-server/src/tools/remember.ts +6 -1
  74. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  75. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  76. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  77. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  78. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  79. package/neural-interface/i18n/en.json +487 -8
  80. package/neural-interface/i18n/pt-BR.json +487 -8
  81. package/neural-interface/lib/agents-studio-api.js +7 -2
  82. package/neural-interface/lib/antigravity/home.js +43 -8
  83. package/neural-interface/lib/antigravity/tool-call.js +14 -0
  84. package/neural-interface/lib/assistant-api.js +90 -0
  85. package/neural-interface/lib/assistant-brains/antigravity.js +4 -2
  86. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  87. package/neural-interface/lib/assistant-dispatch.js +276 -42
  88. package/neural-interface/lib/assistant-memory.js +3 -1
  89. package/neural-interface/lib/assistant-persona.js +14 -3
  90. package/neural-interface/lib/assistant-route-gate.js +11 -2
  91. package/neural-interface/lib/assistant-router.js +18 -8
  92. package/neural-interface/lib/assistant-runtime.js +103 -6
  93. package/neural-interface/lib/assistant-spilled-output.js +53 -0
  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-default.js +22 -2
  97. package/neural-interface/lib/browser-extension-adapter.js +221 -15
  98. package/neural-interface/lib/browser-extension-bridge.js +89 -9
  99. package/neural-interface/lib/browser-extension-folder.js +50 -11
  100. package/neural-interface/lib/browser-extension-package.js +6 -5
  101. package/neural-interface/lib/browser-extension-pin.json +15 -13
  102. package/neural-interface/lib/browser-extension-protocol.js +141 -14
  103. package/neural-interface/lib/browser-extension-setup.js +210 -40
  104. package/neural-interface/lib/browser-extension-update.js +104 -0
  105. package/neural-interface/lib/browser-extraction.js +38 -14
  106. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  107. package/neural-interface/lib/claude-history.js +12 -1
  108. package/neural-interface/lib/confined-fs.js +25 -0
  109. package/neural-interface/lib/coordination/operations.js +2 -0
  110. package/neural-interface/lib/db.js +39 -16
  111. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  112. package/neural-interface/lib/git-bash/manager.js +28 -3
  113. package/neural-interface/lib/git-status-runner.js +31 -3
  114. package/neural-interface/lib/loop-inventory.js +162 -0
  115. package/neural-interface/lib/loop-stall.js +74 -4
  116. package/neural-interface/lib/memory-session-capture.js +157 -66
  117. package/neural-interface/lib/native-loop-providers.js +73 -13
  118. package/neural-interface/lib/native-loop-runtime.js +3 -0
  119. package/neural-interface/lib/opencode-protocol.js +4 -2
  120. package/neural-interface/lib/peer-identity.js +62 -16
  121. package/neural-interface/lib/remote-policy.js +24 -7
  122. package/neural-interface/lib/session-cache-builder.js +66 -18
  123. package/neural-interface/lib/session-capture-gate.js +42 -0
  124. package/neural-interface/lib/session-indexer.js +28 -20
  125. package/neural-interface/lib/teams/README.md +22 -1
  126. package/neural-interface/lib/teams/api.js +79 -6
  127. package/neural-interface/lib/teams/index.js +2 -0
  128. package/neural-interface/lib/teams/recovery.js +68 -0
  129. package/neural-interface/lib/teams/scheduler.js +352 -31
  130. package/neural-interface/lib/teams/worktrees.js +123 -30
  131. package/neural-interface/lib/ui-blob-api.js +14 -5
  132. package/neural-interface/lib/ui-blob-store.js +302 -39
  133. package/neural-interface/package-lock.json +2 -2
  134. package/neural-interface/package.json +1 -1
  135. package/neural-interface/public/extension-setup.html +7 -2
  136. package/neural-interface/public/shared/agents/studio/ax-api.js +16 -0
  137. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +318 -13
  138. package/neural-interface/public/shared/agents/studio/ax-teams.js +141 -9
  139. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  140. package/neural-interface/public/shared/assistant/asst-api.js +42 -0
  141. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  142. package/neural-interface/public/shared/assistant/asst-panel.js +285 -10
  143. package/neural-interface/public/shared/assistant/asst-render.js +205 -4
  144. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  145. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  146. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  147. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  148. package/neural-interface/public/shared/assistant/asst-styles.js +20 -0
  149. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  150. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  151. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  152. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  153. package/neural-interface/public/shared/browser-extension-updates.js +90 -0
  154. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  155. package/neural-interface/public/shared/extension-setup/es-page.js +41 -15
  156. package/neural-interface/public/shared/extension-setup/es-view.js +51 -11
  157. package/neural-interface/public/shared/extension-update-view.js +34 -0
  158. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +8 -4
  159. package/neural-interface/public/shared/settings/settings-ai-browser.js +23 -3
  160. package/neural-interface/public/shared/settings/settings-browser-extension.js +581 -197
  161. package/neural-interface/public/shared/settings/settings-extension-diagrams.js +116 -0
  162. package/neural-interface/public/shared/settings/settings-extension-guide.js +222 -0
  163. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  164. package/neural-interface/public/shared/settings/settings-ia.js +2 -2
  165. package/neural-interface/public/shared/settings/settings-shell.js +5 -0
  166. package/neural-interface/public/shared/styles.css +200 -13
  167. package/neural-interface/public/shared/ui-claude-panel.js +110 -1
  168. package/neural-interface/public/shared/ui-notifications.js +23 -4
  169. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  170. package/neural-interface/public/shared/ui-settings.js +48 -11
  171. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  172. package/neural-interface/public/shared/worker-end.js +18 -0
  173. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  174. package/neural-interface/scripts/rebuild-pty.js +10 -0
  175. package/neural-interface/server.js +503 -281
  176. package/npm-shrinkwrap.json +2 -2
  177. package/package.json +1 -1
@@ -0,0 +1,183 @@
1
+ // ─────────────────────────────────────────────────────────────────────────────
2
+ // Claude Code background tasks, from the session's own transcript
3
+ //
4
+ // The Background tasks view of a panel that runs Claude Code (the Claude Code
5
+ // side panel, the Assistant) asks two things here:
6
+ // list(found) the session's background shells and watches, rebuilt from its transcript with the
7
+ // same registry and adapter the page folds live messages with
8
+ // (public/shared/bg-tasks/), so a reload or a server restart starts from what the
9
+ // session recorded, never from page memory;
10
+ // output(found, q) a page of what one of them printed.
11
+ // `found` is a transcript the caller located and confined (lib/path-confine.js findSessionTranscript).
12
+ //
13
+ // An output file is read only when the session itself reported it for that task (the result text of its tool
14
+ // call, or its task-notification), and only where Claude Code writes them: `claude-<uid>/<project>/<session>/tasks/`
15
+ // under the temporary folder, or `<config dir>/projects/<project>/<session>/tool-results|tasks/`. The request
16
+ // names a task id, never a path; the real path (every link resolved) must be inside one of those folders, its
17
+ // session folder must be the session's, and the file is opened without following a link (lib/confined-fs.js).
18
+ // What is read is scrubbed of SynaBun's run secrets with what lies on both sides of the page
19
+ // (lib/opencode-shell-read.js readSafeShellOutputPage), exactly as the OpenCode panel's shell output is. It goes
20
+ // to the owner's page only: never into a model's context, a transcript or a meter.
21
+ // ─────────────────────────────────────────────────────────────────────────────
22
+
23
+ import { statSync, realpathSync } from 'node:fs';
24
+ import { tmpdir } from 'node:os';
25
+ import { basename, dirname, join } from 'node:path';
26
+ import { readConfinedRange } from './confined-fs.js';
27
+ import { isInside, PathConfineError } from './path-confine.js';
28
+ import { readSafeShellOutputPage, SHELL_OUTPUT_PAGE_BYTES } from './opencode-shell-read.js';
29
+ import { applyBgFact, createBgRegistry, isBgRunning, serializeBgRegistry } from '../public/shared/bg-tasks/bg-tasks-model.js';
30
+ import { claudeFactsFromTranscriptLine } from '../public/shared/bg-tasks/bg-tasks-claude.js';
31
+
32
+ /** The most of a transcript read in one step while it is folded. */
33
+ const TRANSCRIPT_CHUNK = 4 * 1024 * 1024;
34
+ /** How many transcripts keep their folded registry. */
35
+ const CACHE_SIZE = 12;
36
+ // Only lines that can carry a fact are parsed (a transcript reaches tens of MB).
37
+ const MARKERS = ['"Bash"', '"Monitor"', '"TaskStop"', '"KillShell"', '"KillBash"', 'backgroundTaskId', '"taskId"', 'queue-operation'];
38
+
39
+ const TASK_ID = /^[A-Za-z0-9_-]{1,128}$/;
40
+ const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
41
+
42
+ const realOrNull = (p) => { try { return realpathSync(p); } catch { return null; } };
43
+
44
+ /**
45
+ * The folders Claude Code writes task output under, for this user: `<tmp>/claude-<uid>` for every temporary
46
+ * folder it may use (`CLAUDE_CODE_TMPDIR`, `/tmp`, the OS one) and `<configDir>/projects`.
47
+ */
48
+ export function claudeOutputRoots({ configDirs = [], env = process.env, uid = typeof process.getuid === 'function' ? process.getuid() : null, platform = process.platform, tmp = tmpdir() } = {}) {
49
+ const temps = [env?.CLAUDE_CODE_TMPDIR, platform === 'win32' ? null : '/tmp', tmp].filter(Boolean);
50
+ const names = uid == null ? ['claude'] : [`claude-${uid}`];
51
+ const roots = [];
52
+ for (const t of temps) for (const n of names) roots.push(join(t, n));
53
+ for (const c of configDirs) if (c) roots.push(join(c, 'projects'));
54
+ return [...new Set(roots)];
55
+ }
56
+
57
+ /**
58
+ * Whether `file` is an output file of task `taskId` of session `sessionId` under one of `roots`, every link
59
+ * resolved. → `{ root, real }` (the real root and the real file) or null.
60
+ */
61
+ export function confineTaskOutput(file, { sessionId, taskId, roots = [] } = {}) {
62
+ if (typeof file !== 'string' || !file || !TASK_ID.test(String(taskId || '')) || !SESSION_ID.test(String(sessionId || ''))) return null;
63
+ // The name the session reported must already be the task's: `<taskId>.output` (or `<taskId>.<ext>` in tool-results).
64
+ const name = basename(file);
65
+ if (!(name === `${taskId}.output` || name.startsWith(`${taskId}.`))) return null;
66
+ const real = realOrNull(file);
67
+ if (!real) return null;
68
+ // The real file still is the task's, directly in the session's tasks or tool-results folder.
69
+ if (basename(real) !== name) return null;
70
+ const folder = basename(dirname(real));
71
+ if (folder !== 'tasks' && folder !== 'tool-results') return null;
72
+ if (basename(dirname(dirname(real))) !== sessionId) return null;
73
+ for (const root of roots) {
74
+ const realRoot = realOrNull(root);
75
+ if (realRoot && isInside(realRoot, real)) return { root: realRoot, real };
76
+ }
77
+ return null;
78
+ }
79
+
80
+ /** A raw page of a file, cut at UTF-8 character boundaries: `{ status, data: { output, cursor, size } }`. */
81
+ export function readFilePage(root, real, { cursor = 0, limit = SHELL_OUTPUT_PAGE_BYTES } = {}) {
82
+ let from = Math.max(0, Math.floor(Number(cursor) || 0));
83
+ const want = Math.max(1, Math.min(SHELL_OUTPUT_PAGE_BYTES, Math.floor(Number(limit) || SHELL_OUTPUT_PAGE_BYTES)));
84
+ let { bytes, size } = readConfinedRange(root, real, { start: from, length: want });
85
+ // A page that starts inside a character starts at the next one.
86
+ let skip = 0;
87
+ while (skip < bytes.length && skip < 3 && (bytes[skip] & 0xc0) === 0x80) skip += 1;
88
+ if (skip) { bytes = bytes.subarray(skip); from += skip; }
89
+ // A page that ends inside a character ends before it (the next page starts there).
90
+ // (Never down to nothing at the end of the file: a file that really ends inside a character is read as it is,
91
+ // or the reader would ask for the same byte forever.)
92
+ let end = bytes.length;
93
+ let i = end - 1;
94
+ let back = 0;
95
+ while (i >= 0 && back < 3 && (bytes[i] & 0xc0) === 0x80) { i -= 1; back += 1; }
96
+ if (i >= 0) {
97
+ const lead = bytes[i];
98
+ const need = lead >= 0xf0 ? 4 : lead >= 0xe0 ? 3 : lead >= 0xc0 ? 2 : 1;
99
+ if (need > 1 && end - i < need && !(i === 0 && from + bytes.length >= size)) end = i;
100
+ }
101
+ const output = bytes.subarray(0, end).toString('utf8');
102
+ return { status: 200, data: { output, cursor: from + end, size } };
103
+ }
104
+
105
+ /**
106
+ * createClaudeBgTasks({ roots }) — `roots(found)` → the folders output may be read from for that transcript
107
+ * (claudeOutputRoots with the account's config dir).
108
+ */
109
+ export function createClaudeBgTasks({ roots = () => claudeOutputRoots(), cacheSize = CACHE_SIZE } = {}) {
110
+ const cache = new Map(); // realPath → { ino, offset, rest, reg }
111
+
112
+ function fold(entry, text) {
113
+ const lines = (entry.rest + text).split('\n');
114
+ entry.rest = lines.pop() || '';
115
+ for (const line of lines) {
116
+ if (!line || !MARKERS.some(m => line.includes(m))) continue;
117
+ let obj;
118
+ try { obj = JSON.parse(line); } catch { continue; }
119
+ for (const fact of claudeFactsFromTranscriptLine(obj)) applyBgFact(entry.reg, fact);
120
+ }
121
+ }
122
+
123
+ /** The registry of a transcript, folded from where the last read stopped (a file that grew is read on). */
124
+ function registryFor(found) {
125
+ if (!found?.realPath || !found?.realFolder) throw new PathConfineError(404, 'Transcript not found.');
126
+ let st;
127
+ try { st = statSync(found.realPath); } catch { throw new PathConfineError(404, 'Transcript not found.'); }
128
+ let entry = cache.get(found.realPath);
129
+ if (!entry || entry.ino !== st.ino || st.size < entry.offset) {
130
+ entry = { ino: st.ino, offset: 0, rest: '', reg: createBgRegistry() };
131
+ }
132
+ cache.delete(found.realPath);
133
+ cache.set(found.realPath, entry);
134
+ while (cache.size > cacheSize) cache.delete(cache.keys().next().value);
135
+ while (entry.offset < st.size) {
136
+ const { bytes } = readConfinedRange(found.realFolder, found.realPath, { start: entry.offset, length: Math.min(TRANSCRIPT_CHUNK, st.size - entry.offset) });
137
+ if (!bytes.length) break;
138
+ // Whole lines only: a line cut by the chunk (or still being written) waits in `rest`.
139
+ entry.offset += bytes.length;
140
+ fold(entry, bytes.toString('utf8'));
141
+ }
142
+ return entry.reg;
143
+ }
144
+
145
+ return {
146
+ registryFor,
147
+ /** → { tasks } (serializeBgRegistry). */
148
+ list(found) {
149
+ return serializeBgRegistry(registryFor(found));
150
+ },
151
+ /**
152
+ * A page of one task's output: `{ status, data: { output, cursor, size, from } }`, or `{ ok: false, status, code, error }`.
153
+ * `sessionId` is the transcript's session; `running` says the task may still write (from the caller's live view).
154
+ */
155
+ async output(found, { sessionId, taskId, cursor, tail, limit, running = null } = {}) {
156
+ if (!TASK_ID.test(String(taskId || ''))) return { ok: false, status: 400, code: 'TASK_ID_INVALID', error: 'That is not a background task of this conversation.' };
157
+ const reg = registryFor(found);
158
+ const task = reg.tasks.get(taskId);
159
+ if (!task) return { ok: false, status: 404, code: 'TASK_UNKNOWN', error: 'That is not a background task of this conversation.' };
160
+ if (!task.outputFile) return { ok: false, status: 404, code: 'OUTPUT_NOT_REPORTED', error: 'The session has not said where this task writes yet.' };
161
+ const place = confineTaskOutput(task.outputFile, { sessionId, taskId, roots: roots(found) });
162
+ if (!place) {
163
+ // Gone (the temporary folder was cleaned), or a path that is not one of Claude Code's own output files.
164
+ let exists = false;
165
+ try { statSync(task.outputFile); exists = true; } catch { exists = false; }
166
+ return exists
167
+ ? { ok: false, status: 403, code: 'OUTPUT_NOT_ALLOWED', error: 'That file is not where Claude Code keeps this session\'s task output.' }
168
+ : { ok: false, status: 404, code: 'OUTPUT_GONE', error: 'The output file of that task is no longer there.' };
169
+ }
170
+ const read = (q) => {
171
+ try { return readFilePage(place.root, place.real, q); }
172
+ catch (err) { return { ok: false, status: Number(err?.status) || 500, error: err?.message || 'The output could not be read.' }; }
173
+ };
174
+ const stillRunning = typeof running === 'boolean' ? running : isBgRunning(task);
175
+ const page = await readSafeShellOutputPage(read, { cursor, tail, limit, running: stillRunning });
176
+ if (!page || page.ok === false || !(Number(page.status) < 400)) {
177
+ return { ok: false, status: Number(page?.status) >= 400 ? Number(page.status) : 502, code: 'OUTPUT_FAILED', error: page?.error || 'The output could not be read.' };
178
+ }
179
+ return { status: 200, data: page.data };
180
+ },
181
+ forget(realPath) { cache.delete(realPath); },
182
+ };
183
+ }
@@ -11,6 +11,8 @@
11
11
  // - `isMeta` user lines are injected by the CLI, not typed by the user;
12
12
  // - every line carries a `uuid`.
13
13
 
14
+ import { parseTaskNotifications } from '../public/shared/bg-tasks/bg-tasks-model.js';
15
+
14
16
  const MAX_TEXT = 64_000;
15
17
  const MAX_RESULT_TEXT = 32_000;
16
18
  const MAX_STRING = 20_000; // one string inside a structured result
@@ -192,7 +194,16 @@ export function historyRowsFromEntry(obj) {
192
194
  if (obj.type === 'attachment' && obj.attachment?.type === 'queued_command') {
193
195
  const a = obj.attachment;
194
196
  const kind = a.origin?.kind || (a.commandMode && a.commandMode !== 'prompt' ? a.commandMode : '');
195
- if (kind && kind !== 'human') out.rows.push({ role: 'system', subtype: 'origin', origin: a.origin && typeof a.origin === 'object' ? a.origin : { kind } });
197
+ if (kind && kind !== 'human') {
198
+ const row = { role: 'system', subtype: 'origin', origin: a.origin && typeof a.origin === 'object' ? a.origin : { kind } };
199
+ // A background task's report, read into its fields (the panel draws a card linked to the task, never the markup).
200
+ const notifications = kind === 'task-notification' && typeof a.prompt === 'string' ? parseTaskNotifications(a.prompt).slice(0, 10) : [];
201
+ if (notifications.length) {
202
+ row.notifications = notifications;
203
+ if (obj.timestamp || a.timestamp) row.timestamp = obj.timestamp || a.timestamp;
204
+ }
205
+ out.rows.push(row);
206
+ }
196
207
  else if (typeof a.prompt === 'string' && a.prompt.trim()) out.rows.push({ role: 'user', text: a.prompt.slice(0, MAX_TEXT), queued: true });
197
208
  return out;
198
209
  }
@@ -99,6 +99,31 @@ export function readConfinedFileWithMetadata(base, path, { maxBytes = MAX_FILE_B
99
99
  } finally { try { closeSync(fd); } catch {} }
100
100
  }
101
101
 
102
+ /**
103
+ * At most `length` bytes of one regular file inside `base`, from byte `start`, with the file's size at the time
104
+ * of the read: opened and verified the same way (a link out of `base`, a FIFO or a folder is refused). For files
105
+ * read in pages while another process writes them (a background command's output).
106
+ * @returns {{ bytes: Buffer, size: number }}
107
+ */
108
+ export function readConfinedRange(base, path, { start = 0, length = 0 } = {}) {
109
+ const real = canonicalInside(base, path);
110
+ const fd = openExisting(real, constants.O_RDONLY);
111
+ try {
112
+ const st = verifyOpened(fd, real);
113
+ if (!st.isFile()) throw new PathConfineError(400, 'Not a regular file.');
114
+ const from = Math.max(0, Math.floor(Number(start) || 0));
115
+ const want = Math.max(0, Math.min(Math.floor(Number(length) || 0), MAX_FILE_BYTES, Math.max(0, st.size - from)));
116
+ const buf = Buffer.allocUnsafe(want);
117
+ let got = 0;
118
+ while (got < want) {
119
+ const n = readSync(fd, buf, got, want - got, from + got);
120
+ if (n <= 0) break;
121
+ got += n;
122
+ }
123
+ return { bytes: got === want ? buf : buf.subarray(0, got), size: st.size };
124
+ } finally { try { closeSync(fd); } catch {} }
125
+ }
126
+
102
127
  /**
103
128
  * A read stream of one regular file inside `base`, opened and verified the
104
129
  * same way (for files too large to read at once: transcripts).
@@ -63,6 +63,8 @@ export const RUN_EVENT_REASONS = Object.freeze({
63
63
  stopped: { kind: K.RUN_STOPPED, mailbox: true },
64
64
  completed: { kind: K.RUN_COMPLETED, mailbox: false },
65
65
  user_intervened: { kind: K.RUN_NOTICE, mailbox: true },
66
+ // A steer (assistant-dispatch.js steerRun): logged as a notice; the brain hears the user's own steer as user_intervened.
67
+ steered: { kind: K.RUN_NOTICE, mailbox: false },
66
68
  queue_started: { kind: K.RUN_PROGRESS, mailbox: true },
67
69
  suspended: { kind: K.RUN_PROGRESS, mailbox: true },
68
70
  resumed: { kind: K.RUN_PROGRESS, mailbox: true },
@@ -42,22 +42,42 @@ export function getDbPath() {
42
42
  return envPath;
43
43
  }
44
44
 
45
+ function ensureSessionCacheSchema(d) {
46
+ d.exec(SESSION_CACHE_SQL);
47
+ const columns = () => new Set(d.prepare('PRAGMA table_info(session_cache)').all().map(c => c.name));
48
+ const required = ['account_id', 'file_identity', 'content_fingerprint'];
49
+ const existing = columns();
50
+ for (const name of required) {
51
+ if (existing.has(name)) continue;
52
+ // Another connection may finish the same additive migration first.
53
+ try { d.exec(`ALTER TABLE session_cache ADD COLUMN ${name} TEXT`); }
54
+ catch (err) { if (!columns().has(name)) throw err; }
55
+ }
56
+ const verified = columns();
57
+ if (!required.every(name => verified.has(name))) throw new Error('Incomplete session_cache schema');
58
+ d.exec(SESSION_FTS_SQL);
59
+ }
60
+
45
61
  export function getDb() {
46
- if (!db) {
47
- const dbPath = getDbPath();
48
- const dir = dirname(dbPath);
49
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
62
+ if (db) return db;
63
+ const dir = dirname(getDbPath());
64
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
50
65
 
51
- db = sharedDb();
52
- try { db.exec(SESSION_CACHE_SQL); } catch { /* session_cache migration */ }
66
+ const opened = sharedDb();
67
+ const { timeout } = opened.prepare('PRAGMA busy_timeout').get();
68
+ // A retry of these synchronous ALTERs must not stack two 5-second busy waits.
69
+ try {
70
+ opened.exec(`PRAGMA busy_timeout = ${Math.min(timeout, 50)}`);
53
71
  try {
54
- const sessionCacheColumns = new Set(
55
- db.prepare('PRAGMA table_info(session_cache)').all().map((column) => String(column?.name || '')),
56
- );
57
- if (!sessionCacheColumns.has('account_id')) db.exec('ALTER TABLE session_cache ADD COLUMN account_id TEXT');
58
- } catch { /* additive session_cache migration */ }
59
- try { db.exec(SESSION_FTS_SQL); } catch { /* FTS5 may already exist */ }
72
+ ensureSessionCacheSchema(opened);
73
+ } catch (err) {
74
+ if (![5, 6].includes(err.errcode & 0xff)) throw err; // SQLITE_BUSY / SQLITE_LOCKED
75
+ ensureSessionCacheSchema(opened);
76
+ }
77
+ } finally {
78
+ opened.exec(`PRAGMA busy_timeout = ${timeout}`);
60
79
  }
80
+ db = opened;
61
81
  return db;
62
82
  }
63
83
 
@@ -75,6 +95,8 @@ CREATE TABLE IF NOT EXISTS session_cache (
75
95
  file_path TEXT,
76
96
  file_size INTEGER,
77
97
  file_mtime TEXT,
98
+ file_identity TEXT,
99
+ content_fingerprint TEXT,
78
100
  body_size INTEGER,
79
101
  deleted INTEGER DEFAULT 0,
80
102
  account_id TEXT,
@@ -817,13 +839,14 @@ export function upsertSessionCache(entry) {
817
839
  const d = getDb();
818
840
  d.prepare(`INSERT OR REPLACE INTO session_cache
819
841
  (session_id, provider, project, project_path, git_branch, first_prompt, message_count,
820
- created, modified, file_path, file_size, file_mtime, body_size, deleted, account_id)
821
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
842
+ created, modified, file_path, file_size, file_mtime, file_identity, content_fingerprint, body_size, deleted, account_id)
843
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
822
844
  entry.session_id, entry.provider, entry.project || null, entry.project_path || null,
823
845
  entry.git_branch || null, entry.first_prompt || null, entry.message_count || 0,
824
846
  entry.created || null, entry.modified || null, entry.file_path || null,
825
- entry.file_size || null, entry.file_mtime || null, entry.body_size || 0,
826
- entry.deleted ? 1 : 0, entry.account_id || null,
847
+ entry.file_size || null, entry.file_mtime || null,
848
+ entry.file_identity || null, entry.content_fingerprint || null,
849
+ entry.body_size || 0, entry.deleted ? 1 : 0, entry.account_id || null,
827
850
  );
828
851
  }
829
852
 
@@ -309,8 +309,8 @@ export function createOpencodeCompletionEngine({
309
309
  // An OpenCode SynaBun does not drive (OpenCode 1, an OpenCode 2 older than the minimum) never starts; a version
310
310
  // not known here (a command line in Settings) is told by what answers.
311
311
  const detected = await detectOpencode();
312
- if (detected && typeof detected === 'object' && detected.supported === false && detected.major != null) {
313
- throw new Error(detected.reason || `OpenCode ${detected.major} is not supported`);
312
+ if (detected && typeof detected === 'object' && detected.supported === false && (detected.major != null || (!detected.path && !detected.commandLine))) {
313
+ throw new Error(detected.reason || (detected.major != null ? `OpenCode ${detected.major} is not supported` : 'OpenCode is not installed.'));
314
314
  }
315
315
  if (mine !== epoch) throw new Error('The completion server was stopped while it was starting');
316
316
  const password = passwordFrom === 'stdout' ? null : newPassword();
@@ -151,6 +151,20 @@ export function createGitBashManager({
151
151
  return out;
152
152
  }
153
153
 
154
+ // Prime the managed selection at manager creation. Requests keep using the
155
+ // cached result while an expired resolution waits for the next event-loop turn.
156
+ let managed = off || platform !== 'win32' ? null : copies().find(copy => copy.ok)?.git ?? null;
157
+ let managedCheckedAt = now();
158
+ let refreshTimer = null;
159
+ function scheduleRefresh() {
160
+ if (refreshTimer) return;
161
+ refreshTimer = setImmediate(() => {
162
+ refreshTimer = null;
163
+ try { refresh(); } catch (err) { log(`[git-bash] Refresh failed: ${err.message}`); }
164
+ });
165
+ refreshTimer.unref();
166
+ }
167
+
154
168
  function refresh() {
155
169
  let next;
156
170
  // macOS, Linux, the kill switch: nothing to look at (no settings read, no PATH walked).
@@ -160,7 +174,10 @@ export function createGitBashManager({
160
174
  try { settingsBash = settingsValue(); } catch { settingsBash = null; }
161
175
  let searchPath = '';
162
176
  try { searchPath = pathValue(); } catch { searchPath = pathEnvValue(env); }
163
- next = resolveGitBash({ platform, env, settingsValue: settingsBash, pathValue: searchPath, copies: copies(), ownRoots, ...(isFile ? { isFile } : {}) });
177
+ const checked = copies();
178
+ managed = checked.find(copy => copy.ok)?.git ?? null;
179
+ managedCheckedAt = now();
180
+ next = resolveGitBash({ platform, env, settingsValue: settingsBash, pathValue: searchPath, copies: checked, ownRoots, ...(isFile ? { isFile } : {}) });
164
181
  }
165
182
  const changed = !same(current, next);
166
183
  current = next;
@@ -256,9 +273,16 @@ export function createGitBashManager({
256
273
  return gitBashChildEnv(base, r, { platform });
257
274
  }
258
275
 
259
- function gitExecutable() {
276
+ function managedGitExecutable() {
277
+ if (off || platform !== 'win32') return null;
278
+ if (now() - managedCheckedAt > maxAgeMs) scheduleRefresh();
279
+ return managed;
280
+ }
281
+
282
+ function gitExecutable({ includeSystem = false } = {}) {
260
283
  const r = resolution();
261
- return r.passToClaude && r.git ? r.git : null;
284
+ if (!r.git) return null;
285
+ return (includeSystem || r.passToClaude) ? r.git : null;
262
286
  }
263
287
 
264
288
  function status() {
@@ -297,6 +321,7 @@ export function createGitBashManager({
297
321
  resolution,
298
322
  refresh,
299
323
  childEnv,
324
+ managedGitExecutable,
300
325
  gitExecutable,
301
326
  ensure,
302
327
  whenReady,
@@ -77,14 +77,27 @@ export function createGitStatusRunner({
77
77
  timeoutMs = 15000, debounceMs = 150, minIntervalMs = 2000, cacheMs = 30000, maxConcurrent = 2, maxRepos = 64,
78
78
  backoffMs = 30000, maxBackoffMs = 300000, uncoveredCacheMs = 2000, killGraceMs = 1500, taskkillMs = 1000,
79
79
  watch = true, watchFactory = createTreeWatcher, watchdog = spawnImpl === spawn, now = Date.now,
80
+ binaryResolver = null,
80
81
  } = {}) {
81
82
  const binaries = new Map();
83
+ let defaultBinaryResolver = typeof binaryResolver === 'function' ? binaryResolver : null;
82
84
  const entries = new Map(), monitors = createMonitorMemo(), queue = [], children = new Set();
83
85
  let active = 0, closed = false, guard = null, guardReady = null;
84
86
  const nullDevice = platform === 'win32' ? String.raw`\\.\nul` : devNull;
85
87
  const keyOf = root => platform === 'win32' ? root.toLowerCase() : root;
86
88
  const directKill = child => { if (children.has(child) && live(child)) try { child.kill('SIGKILL'); } catch { /* already gone */ } };
87
89
 
90
+ async function resolveBinary(binary) {
91
+ if (binary && binary !== 'git') return binary;
92
+ if (typeof defaultBinaryResolver === 'function') {
93
+ try {
94
+ const resolved = await defaultBinaryResolver();
95
+ if (resolved) return resolved;
96
+ } catch { /* fall back to 'git' */ }
97
+ }
98
+ return binary || 'git';
99
+ }
100
+
88
101
  function killTree(child, sync = false) {
89
102
  if (!children.has(child) || !live(child)) return Promise.resolve();
90
103
  if (platform !== 'win32') {
@@ -226,6 +239,7 @@ export function createGitStatusRunner({
226
239
  });
227
240
  }
228
241
  async function run(args, { cwd, binary = 'git', env = process.env, ...options } = {}) {
242
+ const resolvedBin = await resolveBinary(binary);
229
243
  const clean = { ...env };
230
244
  for (const name of REDIRECTING) delete clean[name];
231
245
  const safeEnv = gitReadEnv(clean);
@@ -233,11 +247,15 @@ export function createGitStatusRunner({
233
247
  if (readsIndex(args)) {
234
248
  monitor = monitors.get(cwd);
235
249
  if (monitor === undefined) {
236
- const probe = await execute(binary, ['--no-pager', '-c', `core.hooksPath=${nullDevice}`, 'config', '--type=bool', '--get', 'core.fsmonitor'], { ...options, timeoutMs: 3000, cwd, env: safeEnv });
250
+ const probe = await execute(resolvedBin, ['--no-pager', '-c', `core.hooksPath=${nullDevice}`, 'config', '--type=bool', '--get', 'core.fsmonitor'], { ...options, timeoutMs: 3000, cwd, env: safeEnv });
237
251
  monitor = monitors.set(cwd, probe.ok && String(probe.stdout).trim() === 'true');
238
252
  }
239
253
  }
240
- return execute(binary, gitReadArgs(args, { monitor, nullDevice }), { ...options, cwd, env: safeEnv });
254
+ return execute(resolvedBin, gitReadArgs(args, { monitor, nullDevice }), { ...options, cwd, env: safeEnv });
255
+ }
256
+ async function runRaw(args, options = {}) {
257
+ const resolvedBin = await resolveBinary(options.binary);
258
+ return execute(resolvedBin, args, { ...options, env: withGitFallback(options.env) });
241
259
  }
242
260
  function drop(key, entry) {
243
261
  entry.controller?.abort(); entry.watcher?.close(); entries.delete(key);
@@ -371,7 +389,17 @@ export function createGitStatusRunner({
371
389
  for (const child of children) void killTree(child, sync);
372
390
  if (guard?.connected) guard.disconnect();
373
391
  }
374
- return { read, run, runRaw: (args, options = {}) => execute(options.binary || 'git', args, { ...options, env: withGitFallback(options.env) }), ignored, invalidate, release, shutdown, stats: () => ({ active, queued: queue.length, children: children.size, repos: entries.size }) };
392
+ return {
393
+ read,
394
+ run,
395
+ runRaw,
396
+ setBinaryResolver: (fn) => { defaultBinaryResolver = typeof fn === 'function' ? fn : null; binaries.clear(); },
397
+ ignored,
398
+ invalidate,
399
+ release,
400
+ shutdown,
401
+ stats: () => ({ active, queued: queue.length, children: children.size, repos: entries.size }),
402
+ };
375
403
  }
376
404
 
377
405
  export function projectStatus(result, cwd, platform = process.platform) {
@@ -0,0 +1,162 @@
1
+ // ═══════════════════════════════════════════
2
+ // SynaBun Neural Interface — Async Loop Inventory Scanner
3
+ // ═══════════════════════════════════════════
4
+ // Scans LOOP_DIR (*.json) asynchronously using fs.promises and caches parsed
5
+ // loop files keyed by (mtimeMs, ctimeMs, ino, size) so unchanged files are
6
+ // neither re-read nor re-parsed on every periodic poll, while atomic
7
+ // same-name replacements with equal size and mtime still invalidate the cache.
8
+ // Dynamic fields (elapsedMinutes, stalledMinutes, stalledMs, terminalAlive,
9
+ // state) are recomputed live from the cached JSON on every scan.
10
+
11
+ import * as fsp from 'node:fs/promises';
12
+ import { resolve } from 'node:path';
13
+
14
+ export function isInventoryLoopFile(name) {
15
+ return typeof name === 'string'
16
+ && name.endsWith('.json')
17
+ && name !== '.gitkeep'
18
+ && !name.startsWith('pending-')
19
+ && name !== 'active-pointer.json';
20
+ }
21
+
22
+ /**
23
+ * Create an asynchronous, stat-identity-cached loop inventory scanner.
24
+ *
25
+ * @param {object} options
26
+ * @param {string | (() => string)} options.loopDir
27
+ * @param {(data: object) => boolean} [options.isLoopRuntimeAlive]
28
+ * @param {{ readdir: Function, stat: Function, readFile: Function }} [options.fsPromises]
29
+ * @param {() => number} [options.now]
30
+ */
31
+ export function createLoopInventoryScanner({
32
+ loopDir,
33
+ isLoopRuntimeAlive = () => false,
34
+ fsPromises = fsp,
35
+ now = Date.now,
36
+ } = {}) {
37
+ const fileCache = new Map(); // filename -> { mtimeMs, ctimeMs, ino, size, data }
38
+ let reads = 0;
39
+ let cacheHits = 0;
40
+
41
+ async function scan({ includeExtraFields = false, includeRaw = false } = {}) {
42
+ const result = includeRaw
43
+ ? { loops: [], staleCount: 0, rawEntries: [] }
44
+ : { loops: [], staleCount: 0 };
45
+ const dir = typeof loopDir === 'function' ? loopDir() : loopDir;
46
+ if (!dir) {
47
+ fileCache.clear();
48
+ return result;
49
+ }
50
+
51
+ let entries;
52
+ try {
53
+ entries = await fsPromises.readdir(dir);
54
+ } catch (err) {
55
+ if (err?.code === 'ENOENT') {
56
+ fileCache.clear();
57
+ return result;
58
+ }
59
+ throw err;
60
+ }
61
+
62
+ const files = entries.filter(isInventoryLoopFile);
63
+ const seen = new Set(files);
64
+ for (const key of fileCache.keys()) {
65
+ if (!seen.has(key)) fileCache.delete(key);
66
+ }
67
+
68
+ const currentMs = now();
69
+ for (const f of files) {
70
+ const filePath = resolve(dir, f);
71
+ let stat;
72
+ try {
73
+ stat = await fsPromises.stat(filePath);
74
+ } catch {
75
+ fileCache.delete(f);
76
+ continue;
77
+ }
78
+
79
+ const ctimeMs = stat.ctimeMs ?? null;
80
+ const ino = stat.ino ?? null;
81
+ let data;
82
+ const cached = fileCache.get(f);
83
+ if (
84
+ cached
85
+ && cached.mtimeMs === stat.mtimeMs
86
+ && cached.ctimeMs === ctimeMs
87
+ && cached.ino === ino
88
+ && cached.size === stat.size
89
+ ) {
90
+ data = cached.data;
91
+ cacheHits++;
92
+ } else {
93
+ try {
94
+ const raw = await fsPromises.readFile(filePath, 'utf-8');
95
+ data = JSON.parse(raw);
96
+ fileCache.set(f, { mtimeMs: stat.mtimeMs, ctimeMs, ino, size: stat.size, data });
97
+ reads++;
98
+ } catch {
99
+ fileCache.delete(f);
100
+ continue;
101
+ }
102
+ }
103
+
104
+ if (!data || typeof data !== 'object') continue;
105
+ const sessionId = f.replace('.json', '');
106
+ if (includeRaw) {
107
+ result.rawEntries.push({ file: f, filePath, sessionId, mtimeMs: stat.mtimeMs, stat, data });
108
+ }
109
+ const startedAtMs = data.startedAt ? new Date(data.startedAt).getTime() : 0;
110
+ const lastIterAtMs = data.lastIterationAt ? new Date(data.lastIterationAt).getTime() : startedAtMs;
111
+ const elapsedMs = startedAtMs ? currentMs - startedAtMs : 0;
112
+ const stalledMs = lastIterAtMs ? currentMs - lastIterAtMs : 0;
113
+ const terminalAlive = !!isLoopRuntimeAlive(data);
114
+ const iterDone = (data.currentIteration || 0) >= (data.totalIterations || 0) && (data.totalIterations || 0) > 0;
115
+ let state;
116
+ if (data.active === false) {
117
+ state = 'stale-inactive';
118
+ result.staleCount++;
119
+ } else if (data.terminalSessionId && !terminalAlive) {
120
+ state = data.runtimeType === 'native' ? 'orphaned-native' : 'orphaned-pty';
121
+ } else if (iterDone) {
122
+ state = 'finished';
123
+ } else {
124
+ state = 'active';
125
+ }
126
+
127
+ const item = {
128
+ sessionId,
129
+ terminalSessionId: data.terminalSessionId || null,
130
+ terminalAlive,
131
+ ...(includeExtraFields ? {
132
+ runId: data.runId || null,
133
+ profile: data.profile || null,
134
+ runtimeType: data.runtimeType || 'pty',
135
+ surface: data.surface || 'terminal',
136
+ } : {}),
137
+ task: typeof data.task === 'string' ? data.task.slice(0, 200) : '',
138
+ currentIteration: data.currentIteration || 0,
139
+ totalIterations: data.totalIterations || 0,
140
+ startedAt: data.startedAt || null,
141
+ lastIterationAt: data.lastIterationAt || null,
142
+ elapsedMinutes: Math.round(elapsedMs / 60000),
143
+ stalledMinutes: Math.round(stalledMs / 60000),
144
+ stalledMs,
145
+ state,
146
+ browserSessionId: data.browserSessionId || null,
147
+ browserTabId: data.browserTabId || null,
148
+ usesBrowser: !!data.usesBrowser,
149
+ };
150
+ result.loops.push(item);
151
+ }
152
+
153
+ result.loops.sort((a, b) => (b.startedAt || '').localeCompare(a.startedAt || ''));
154
+ return result;
155
+ }
156
+
157
+ return {
158
+ scan,
159
+ clearCache() { fileCache.clear(); },
160
+ stats() { return { reads, cacheHits, cachedFiles: fileCache.size }; },
161
+ };
162
+ }