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
@@ -6,10 +6,13 @@ let activeMonitor;
6
6
  // `last` alone named whatever marked most recently, and the 2 s capture and maintenance timers mark every second:
7
7
  // a multi-second recall or write wait that started before them was reported under their names
8
8
  // (docs/startup-freeze-and-agents-audit.md → Third pass). A stall line now also says what was still in flight
9
- // (beginActivity) and the slowest synchronous SQLite statement of the stalled interval (instrumentSqlite).
9
+ // (beginActivity) and the slowest synchronous work of the stalled interval (instrumentSqlite, timeBlockingWork,
10
+ // beginBlockingWork, noteBlockingWork). `markActivity` labels are kept strictly as context (`last:`), never
11
+ // timed via nextTick, so unrelated callbacks sharing a turn are never misattributed.
10
12
  const open = new Map();
11
13
  let openSeq = 0;
12
14
  let slowest = null;
15
+ const activeSyncSpans = []; // stack of open beginBlockingWork/timeBlockingWork spans on this thread
13
16
 
14
17
  export function markActivity(label) {
15
18
  activeMonitor?.mark(label);
@@ -33,16 +36,52 @@ export function noteBlockingWork(label, ms) {
33
36
  if (!slowest || ms > slowest.ms) slowest = { label, ms };
34
37
  }
35
38
 
39
+ /**
40
+ * Time a non-SQL synchronous section on this thread. Returns an `end()` callback that records its duration
41
+ * via `noteBlockingWork` when at or over `thresholdMs`. Also keeps the span visible while still running so
42
+ * a stall detected mid-section attributes it immediately.
43
+ */
44
+ export function beginBlockingWork(label, { thresholdMs = 50, mark = true } = {}) {
45
+ if (mark) markActivity(label);
46
+ const span = { label, started: performance.now(), thresholdMs, ended: false };
47
+ activeSyncSpans.push(span);
48
+ if (activeSyncSpans.length > 64) activeSyncSpans.shift();
49
+ return () => {
50
+ if (span.ended) return 0;
51
+ span.ended = true;
52
+ const idx = activeSyncSpans.lastIndexOf(span);
53
+ if (idx >= 0) activeSyncSpans.splice(idx, 1);
54
+ const ms = performance.now() - span.started;
55
+ if (ms >= thresholdMs) noteBlockingWork(label, ms);
56
+ return ms;
57
+ };
58
+ }
59
+
60
+ /** Run synchronous function `fn` under a named blocking-work timer (attributed on any stall line). */
61
+ export function timeBlockingWork(label, fn, options) {
62
+ const end = beginBlockingWork(label, options);
63
+ try { return fn(); } finally { end(); }
64
+ }
65
+
36
66
  function inFlight(now) {
37
67
  const list = [];
38
68
  for (const { label, at } of open.values()) { list.push(`${label} ${((now - at) / 1000).toFixed(1)} s`); if (list.length === 3) break; }
39
69
  return list.length ? `; in flight: ${list.join(', ')}${open.size > 3 ? ` +${open.size - 3}` : ''}` : '';
40
70
  }
41
71
 
72
+ function longestActiveSpan(now) {
73
+ let best = null;
74
+ for (const span of activeSyncSpans) {
75
+ const ms = now - span.started;
76
+ if (!best || ms > best.ms) best = { label: span.label, ms };
77
+ }
78
+ return best;
79
+ }
80
+
42
81
  let sqliteInstrumented = false;
43
82
  /**
44
- * Time every synchronous SQLite call on this thread (node:sqlite statements and exec) and keep the slowest of each
45
- * monitor interval at or over `thresholdMs`, with the start of its SQL. A few tens of nanoseconds per call.
83
+ * Time every synchronous SQLite call on this thread (node:sqlite statements, prepare and exec) and keep the slowest
84
+ * of each monitor interval at or over `thresholdMs`, with the start of its SQL. A few tens of nanoseconds per call.
46
85
  * Off with SYNABUN_LOOP_STALL_SQL=off. Only for the thread that runs the monitor: workers have their own classes.
47
86
  */
48
87
  export function instrumentSqlite({ thresholdMs = 50 } = {}) {
@@ -60,6 +99,16 @@ export function instrumentSqlite({ thresholdMs = 50 } = {}) {
60
99
  }
61
100
  };
62
101
  }
102
+ const prepare = DatabaseSync.prototype.prepare;
103
+ if (typeof prepare === 'function') {
104
+ DatabaseSync.prototype.prepare = function timedPrepare(sql, ...rest) {
105
+ const started = performance.now();
106
+ try { return prepare.call(this, sql, ...rest); } finally {
107
+ const ms = performance.now() - started;
108
+ if (ms >= thresholdMs) noteBlockingWork(`sql prepare ${describe(sql)}`, ms);
109
+ }
110
+ };
111
+ }
63
112
  const exec = DatabaseSync.prototype.exec;
64
113
  DatabaseSync.prototype.exec = function timedExec(sql) {
65
114
  const started = performance.now();
@@ -81,6 +130,7 @@ export function instrumentSqlite({ thresholdMs = 50 } = {}) {
81
130
  // line ends with what the limit kept back since the line before it: how many stalls, their sum and the worst.
82
131
  export function startLoopStallMonitor({
83
132
  thresholdMs = 500, intervalMs = 100, resolution = 20, rateLimitMs = 30_000, longMs = 3000,
133
+ unattributedMs = 10_000,
84
134
  log = console.warn,
85
135
  } = {}) {
86
136
  if (activeMonitor) return activeMonitor;
@@ -93,6 +143,24 @@ export function startLoopStallMonitor({
93
143
  // One stall is seen twice (by the mark that follows it and by the delayed tick): `seenUntil` counts it once.
94
144
  let seenUntil = -Infinity;
95
145
 
146
+ function pickAttribution(now, blocked) {
147
+ const activeSpan = longestActiveSpan(now);
148
+ const specific = !slowest ? activeSpan
149
+ : !activeSpan ? slowest
150
+ : activeSpan.ms > slowest.ms ? activeSpan : slowest;
151
+ const minReport = Math.min(blocked / 4, 100);
152
+ if (specific && specific.ms >= minReport) {
153
+ return `; longest sync: ${specific.label} ${Math.round(specific.ms)} ms`;
154
+ }
155
+ // Never leave a >10 s stall completely unattributed: report whatever timed section ran, or explicitly
156
+ // state it was unattributed (e.g., V8 GC pause, OS sleep, or untagged native/JS work) after `activity`.
157
+ if (blocked >= unattributedMs) {
158
+ if (specific && specific.ms > 0) return `; longest sync: ${specific.label} ${Math.round(specific.ms)} ms`;
159
+ return `; longest sync: unattributed (after ${activity})`;
160
+ }
161
+ return '';
162
+ }
163
+
96
164
  function check(now, histogram = 0) {
97
165
  const blocked = Math.max(now - lastTick - intervalMs, histogram);
98
166
  if (blocked < thresholdMs) return;
@@ -107,7 +175,7 @@ export function startLoopStallMonitor({
107
175
  if (limited && now - blocked < seenUntil) return; // this long stall already has its line
108
176
  lastReport = now;
109
177
  seenUntil = now;
110
- const work = slowest && slowest.ms >= Math.min(blocked / 4, 100) ? `; longest sync: ${slowest.label} ${Math.round(slowest.ms)} ms` : '';
178
+ const work = pickAttribution(now, blocked);
111
179
  slowest = null;
112
180
  const more = held.count
113
181
  ? `; ${held.count} more ${held.count === 1 ? 'stall' : 'stalls'} since the last line, ${Math.round(held.ms)} ms in all, worst ${Math.round(held.worst)} ms`
@@ -132,6 +200,8 @@ export function startLoopStallMonitor({
132
200
  stop() {
133
201
  clearInterval(timer);
134
202
  delay.disable();
203
+ slowest = null;
204
+ activeSyncSpans.length = 0;
135
205
  if (activeMonitor === this) activeMonitor = undefined;
136
206
  },
137
207
  };
@@ -1,4 +1,6 @@
1
1
  import { runSessionJob } from './session-cache-worker.js';
2
+ import { captureStartOffset, fileIdentityOf, mtimeIsoOf } from './session-capture-gate.js';
3
+ import { statSync } from 'node:fs';
2
4
  import { open } from 'node:fs/promises';
3
5
  import { getDb } from '../../mcp-server/dist/services/sqlite.js';
4
6
  import { detectProject } from '../../mcp-server/dist/config.js';
@@ -6,40 +8,109 @@ import { normalizeMemoryEvents, ingestMemoryEvents, CAPTURE_TRANSACTION_MS, CAPT
6
8
  import { maintenancePaused } from './memory-timers.js';
7
9
 
8
10
  /** The hosts whose transcripts are captured from a file (OpenCode's rows are taken in session-cache-builder.js). */
9
- export const CAPTURE_HOSTS=Object.freeze(['claude-code','codex','antigravity']);
11
+ export const CAPTURE_HOSTS = Object.freeze(['claude-code', 'codex', 'antigravity']);
10
12
 
11
- /**
12
- * `size`: the transcript's size now, when the caller knows it. A file already read to that size is left as it is
13
- * (a pass over every Antigravity conversation would otherwise mark each one pending again).
14
- */
15
- export function queueMemoryCapture({host,sessionId,filePath,project,cwd,size=null}) {
16
- if(!filePath || !sessionId || !CAPTURE_HOSTS.includes(host))return;
17
- if(size!=null) {
18
- const row=getDb().prepare('SELECT file_path,byte_offset,status,cwd FROM memory_capture_files WHERE host=? AND session_id=?').get(host,sessionId);
19
- if(row && row.status==='complete' && row.file_path===filePath && Number(row.byte_offset)===Number(size) && (row.cwd || null)===(cwd || null))return;
13
+ const migratedDbs = new WeakSet();
14
+ const CAPTURE_EXTRA_COLUMNS = Object.freeze([
15
+ ['file_size', 'INTEGER'],
16
+ ['file_mtime', 'TEXT'],
17
+ ['file_identity', 'TEXT'],
18
+ ]);
19
+
20
+ function ensureCaptureMetadataColumns(d) {
21
+ if (migratedDbs.has(d)) return;
22
+ for (const [name, type] of CAPTURE_EXTRA_COLUMNS) {
23
+ const hasColumn = () => d.prepare('PRAGMA table_info(memory_capture_files)').all().some(c => c.name === name);
24
+ if (!hasColumn()) {
25
+ try { d.exec(`ALTER TABLE memory_capture_files ADD COLUMN ${name} ${type}`); }
26
+ catch (err) { if (!hasColumn()) throw err; }
27
+ }
20
28
  }
21
- // An Antigravity conversation whose folder agy named only later is read again from its start: its events take the
22
- // project (each step keeps its source id, so nothing is stored twice).
23
- getDb().prepare(`INSERT INTO memory_capture_files(host,session_id,file_path,project,cwd) VALUES(?,?,?,?,?)
24
- ON CONFLICT(host,session_id) DO UPDATE SET file_path=excluded.file_path,project=excluded.project,cwd=excluded.cwd,status='pending',error=NULL,
25
- byte_offset=CASE WHEN excluded.host='antigravity' AND memory_capture_files.cwd IS NOT excluded.cwd THEN 0 ELSE memory_capture_files.byte_offset END`)
26
- .run(host,sessionId,filePath,cwd ? detectProject(cwd) : project || 'global',cwd || null);
29
+ migratedDbs.add(d);
27
30
  }
28
31
 
29
- let running=false;
30
- let timer=null;
32
+ function readStatBestEffort(filePath, providedStat) {
33
+ if (providedStat && providedStat.size != null && (providedStat.dev != null || providedStat.ino != null || providedStat.mtimeNs != null)) {
34
+ return providedStat;
35
+ }
36
+ try {
37
+ return statSync(filePath, { bigint: true });
38
+ } catch {
39
+ return providedStat || null;
40
+ }
41
+ }
42
+
43
+ // Compare the actual checkpoint in SQL on every transition: a scan or worker
44
+ // that yielded to another capture cannot overwrite its newer offset or status.
45
+ const checkpointWhere = `host = ? AND session_id = ? AND status = ? AND byte_offset = ?
46
+ AND file_path = ? AND cwd IS ? AND file_size IS ? AND file_mtime IS ? AND file_identity IS ?`;
47
+ function checkpointKey(row) {
48
+ return [row.host, row.session_id, row.status, row.byte_offset, row.file_path, row.cwd,
49
+ row.file_size, row.file_mtime, row.file_identity];
50
+ }
51
+
52
+ export function queueMemoryCapture({ host, sessionId, filePath, project, cwd, size = null, stat = null,
53
+ fileMtime = null, fileIdentity = null }) {
54
+ if (!filePath || !sessionId || !CAPTURE_HOSTS.includes(host)) return;
55
+ const d = getDb();
56
+ ensureCaptureMetadataColumns(d);
57
+ const read = d.prepare('SELECT * FROM memory_capture_files WHERE host = ? AND session_id = ?');
58
+ const projectName = () => cwd ? detectProject(cwd) : project || 'global';
59
+ // A worker can finish between the read and the update. Re-evaluate that checkpoint.
60
+ for (;;) {
61
+ const row = read.get(host, sessionId);
62
+ const st = readStatBestEffort(filePath, stat);
63
+ const currentSize = st ? Number(st.size) : size;
64
+ const mtime = mtimeIsoOf(st) ?? fileMtime;
65
+ const identity = fileIdentityOf(st) ?? fileIdentity;
66
+ if (!row) {
67
+ const added = d.prepare(`INSERT INTO memory_capture_files
68
+ (host, session_id, file_path, project, cwd, byte_offset, status, file_size, file_mtime, file_identity)
69
+ VALUES (?, ?, ?, ?, ?, 0, 'pending', ?, ?, ?) ON CONFLICT(host, session_id) DO NOTHING`)
70
+ .run(host, sessionId, filePath, projectName(), cwd || null, currentSize, mtime, identity);
71
+ if (added.changes) return;
72
+ stat = null;
73
+ continue;
74
+ }
75
+
76
+ const sameCwd = (host !== 'antigravity' && !cwd) || row.cwd === (cwd || null);
77
+ const sameSource = row.file_path === filePath && (host !== 'antigravity' || sameCwd);
78
+ const offset = sameSource ? captureStartOffset(row, currentSize, identity, mtime) : 0;
79
+ const complete = row.status === 'complete' && sameSource && sameCwd && offset === currentSize;
80
+ const status = complete ? 'complete' : 'pending';
81
+ // If the stat failed, preserve the known checkpoint for the worker's next open.
82
+ const nextSize = currentSize ?? (sameSource ? row.file_size : null);
83
+ const nextMtime = mtime ?? (sameSource ? row.file_mtime : null);
84
+ const nextIdentity = identity ?? (sameSource ? row.file_identity : null);
85
+ const nextCwd = sameCwd && sameSource ? row.cwd : cwd || null;
86
+ if (sameSource && sameCwd && status === row.status && offset === row.byte_offset
87
+ && row.file_size === nextSize && row.file_mtime === nextMtime && row.file_identity === nextIdentity
88
+ && (complete || row.project === projectName())) return;
89
+
90
+ const changed = d.prepare(`UPDATE memory_capture_files SET file_path = ?, project = ?, cwd = ?,
91
+ status = ?, error = NULL, byte_offset = ?, file_size = ?, file_mtime = ?, file_identity = ?
92
+ WHERE ${checkpointWhere}`).run(filePath, complete ? row.project : projectName(), nextCwd,
93
+ status, offset, nextSize, nextMtime, nextIdentity, ...checkpointKey(row));
94
+ if (changed.changes) return;
95
+ stat = null; // Resample if a worker committed a newer checkpoint.
96
+ }
97
+ }
98
+
99
+ let running = false;
100
+ let timer = null;
31
101
  export async function captureMemoryFileBatch(target, { reportProgress = false } = {}) {
32
- if(running)return {busy:true};
33
- running=true;
102
+ if (running) return { busy: true };
103
+ running = true;
34
104
  try {
35
105
  return await runSessionJob('capture', { target, reportProgress });
36
106
  } finally {
37
- running=false;
107
+ running = false;
38
108
  }
39
109
  }
40
110
 
41
111
  export async function capturePendingFile(target, { reportProgress, warmLookup } = {}) {
42
112
  const d = getDb();
113
+ ensureCaptureMetadataColumns(d);
43
114
  if (maintenancePaused(d)) return { paused: true };
44
115
  const select = target
45
116
  ? d.prepare('SELECT * FROM memory_capture_files WHERE host=? AND session_id=?')
@@ -62,66 +133,86 @@ export async function capturePendingFile(target, { reportProgress, warmLookup }
62
133
  async function readCaptureFile(d, job) {
63
134
  let file;
64
135
  try {
65
- file=await open(job.file_path,'r');
66
- const stat=await file.stat();
67
- const offset=stat.size<job.byte_offset ? 0 : job.byte_offset;
136
+ file = await open(job.file_path, 'r');
137
+ const stat = await file.stat({ bigint: true });
138
+ const fileSize = Number(stat.size);
139
+ const identity = fileIdentityOf(stat);
140
+ const mtime = mtimeIsoOf(stat);
141
+ const offset = captureStartOffset(job, fileSize, identity, mtime);
142
+ const saveCheckpoint = (end) => d.prepare(`
143
+ UPDATE memory_capture_files SET byte_offset = ?, status = ?, error = NULL,
144
+ file_size = ?, file_mtime = ?, file_identity = ? WHERE ${checkpointWhere}
145
+ `).run(end, end >= fileSize ? 'complete' : 'pending', fileSize, mtime, identity, ...checkpointKey(job));
146
+
68
147
  // Bounded file reads keep large transcripts off the UI request path.
69
- let buffer=Buffer.alloc(256*1024);
70
- let {bytesRead}=await file.read(buffer,0,buffer.length,offset);
71
- if(!bytesRead){d.prepare("UPDATE memory_capture_files SET status='complete' WHERE host=? AND session_id=?").run(job.host,job.session_id);return;}
72
- while(buffer.subarray(0,bytesRead).lastIndexOf(10)<0 && bytesRead===buffer.length && buffer.length<8*1024*1024) {
73
- buffer=Buffer.alloc(buffer.length*2);
74
- ({bytesRead}=await file.read(buffer,0,buffer.length,offset));
148
+ let buffer = Buffer.alloc(256 * 1024);
149
+ let { bytesRead } = await file.read(buffer, 0, buffer.length, offset);
150
+ if (!bytesRead) {
151
+ saveCheckpoint(offset);
152
+ return;
153
+ }
154
+ while (buffer.subarray(0, bytesRead).lastIndexOf(10) < 0 && bytesRead === buffer.length && buffer.length < 8 * 1024 * 1024) {
155
+ buffer = Buffer.alloc(buffer.length * 2);
156
+ ({ bytesRead } = await file.read(buffer, 0, buffer.length, offset));
75
157
  }
76
- const bytes=buffer.subarray(0,bytesRead);
77
- const newline=bytes.lastIndexOf(10);
78
- let consumed=newline+1;
79
- if(newline<0) {
80
- if(bytesRead===buffer.length)throw new Error('Transcript record exceeds 8 MiB; original source retained.');
158
+ const bytes = buffer.subarray(0, bytesRead);
159
+ const newline = bytes.lastIndexOf(10);
160
+ let consumed = newline + 1;
161
+ if (newline < 0) {
162
+ if (bytesRead === buffer.length) throw new Error('Transcript record exceeds 8 MiB; original source retained.');
81
163
  // A valid final JSON record need not end in a newline. Incomplete tails
82
164
  // remain pending until the writer finishes them.
83
- try{JSON.parse(bytes.toString('utf8'));consumed=bytesRead;}catch{return;}
165
+ try { JSON.parse(bytes.toString('utf8')); consumed = bytesRead; } catch { return; }
84
166
  }
85
- const records=[];
86
- let position=offset;
87
- for(const line of bytes.subarray(0,consumed).toString('utf8').split('\n')) {
88
- if(line.trim()) {try {const record=JSON.parse(line);records.push({...record,id:record.id || record.uuid || `byte:${position}`});}catch{}}
89
- position+=Buffer.byteLength(line)+1;
167
+ const records = [];
168
+ let position = offset;
169
+ for (const line of bytes.subarray(0, consumed).toString('utf8').split('\n')) {
170
+ if (line.trim()) {
171
+ try {
172
+ const record = JSON.parse(line);
173
+ records.push({ ...record, id: record.id || record.uuid || `byte:${position}` });
174
+ } catch {}
175
+ }
176
+ position += Buffer.byteLength(line) + 1;
90
177
  }
91
- const sourceCwd=job.cwd || records.find(r=>r.cwd)?.cwd || records.find(r=>r.type==='session_meta')?.payload?.cwd;
92
- const project=sourceCwd ? detectProject(sourceCwd) : job.project;
93
- const events=normalizeMemoryEvents(job.host,records,{session_id:job.session_id,project,cwd:sourceCwd});
94
- if(maintenancePaused())return;
178
+ const sourceCwd = job.cwd || records.find(r => r.cwd)?.cwd || records.find(r => r.type === 'session_meta')?.payload?.cwd;
179
+ const project = sourceCwd ? detectProject(sourceCwd) : job.project;
180
+ const events = normalizeMemoryEvents(job.host, records, { session_id: job.session_id, project, cwd: sourceCwd });
181
+ if (maintenancePaused()) return;
95
182
  // Short transactions with the write lock left free between them (memory-sessions.ts CAPTURE_*): the server's
96
183
  // own writes wait for this lock on its event loop.
97
- for (let offset = 0; offset < events.length;) {
184
+ for (let i = 0; i < events.length;) {
98
185
  if (maintenancePaused()) return; // replay from the previous checkpoint on resume
99
- const batch = ingestMemoryEvents(events.slice(offset, offset + 25), { maxTransactionMs: CAPTURE_TRANSACTION_MS });
100
- offset += Math.max(1, batch.consumed);
101
- if (batch.indexed && offset < events.length) await new Promise(done => setTimeout(done, CAPTURE_PAUSE_MS));
186
+ const batch = ingestMemoryEvents(events.slice(i, i + 25), { maxTransactionMs: CAPTURE_TRANSACTION_MS });
187
+ i += Math.max(1, batch.consumed);
188
+ if (batch.indexed && i < events.length) await new Promise(done => setTimeout(done, CAPTURE_PAUSE_MS));
102
189
  }
103
190
  // Replaying after a crash between intake and checkpoint is idempotent.
104
- d.prepare("UPDATE memory_capture_files SET byte_offset=?,status=?,error=NULL WHERE host=? AND session_id=?")
105
- .run(offset+consumed,offset+consumed>=stat.size ? 'complete':'pending',job.host,job.session_id);
106
- }catch(error){d.prepare("UPDATE memory_capture_files SET status='failed',error=? WHERE host=? AND session_id=?").run(error.message,job.host,job.session_id);}
107
- finally{await file?.close();}
191
+ saveCheckpoint(offset + consumed);
192
+ } catch (error) {
193
+ d.prepare(`UPDATE memory_capture_files SET status='failed', error=? WHERE ${checkpointWhere}`)
194
+ .run(error.message, ...checkpointKey(job));
195
+ } finally {
196
+ await file?.close();
197
+ }
108
198
  }
109
- let startTimer=null;
199
+
200
+ let startTimer = null;
110
201
  // offsetMs keeps this tick out of phase with the 2 s maintenance timer so the
111
202
  // two never stack on the same event-loop turn.
112
- export function startMemoryCapture({offsetMs=1000,intervalMs=2000}={}) {
113
- if(timer||startTimer)return;
114
- const tick=()=>captureMemoryFileBatch().catch(error=>console.error('[memory capture]',error.message));
115
- startTimer=setTimeout(()=>{
116
- startTimer=null;
117
- timer=setInterval(tick,intervalMs);
203
+ export function startMemoryCapture({ offsetMs = 1000, intervalMs = 2000 } = {}) {
204
+ if (timer || startTimer) return;
205
+ const tick = () => captureMemoryFileBatch().catch(error => console.error('[memory capture]', error.message));
206
+ startTimer = setTimeout(() => {
207
+ startTimer = null;
208
+ timer = setInterval(tick, intervalMs);
118
209
  timer.unref();
119
- },offsetMs);
210
+ }, offsetMs);
120
211
  startTimer.unref();
121
212
  }
122
- export function stopMemoryCapture(){
123
- if(startTimer)clearTimeout(startTimer);
124
- if(timer)clearInterval(timer);
125
- startTimer=null;
126
- timer=null;
213
+ export function stopMemoryCapture() {
214
+ if (startTimer) clearTimeout(startTimer);
215
+ if (timer) clearInterval(timer);
216
+ startTimer = null;
217
+ timer = null;
127
218
  }
@@ -709,6 +709,12 @@ export async function createClaudeNativeLoopAdapter(options = {}) {
709
709
  let alive = true;
710
710
  let sessionId = null;
711
711
  let activeTurn = null;
712
+ // Results the CLI still owes for turns a steer cut (abort('steered')): each interrupted prompt ends with one result
713
+ // of its own, which must not settle the turn sent after it.
714
+ let staleResults = 0;
715
+ // A turn still waiting to start (the MCP scope check) has no prompt at the CLI yet: an abort then ends it before
716
+ // the prompt goes ({ reason } while it waits, read once runTurn may send).
717
+ let startingTurn = null;
712
718
  // The session's live background tasks (shells, Monitors, agents): what a turn of this run waits for.
713
719
  const bgTasks = createBackgroundTasks();
714
720
  const holdLimits = backgroundHold && typeof backgroundHold === 'object' ? { ...BACKGROUND_HOLD_DEFAULTS, ...backgroundHold } : BACKGROUND_HOLD_DEFAULTS;
@@ -1087,6 +1093,7 @@ export async function createClaudeNativeLoopAdapter(options = {}) {
1087
1093
  }
1088
1094
  emitEvent(event);
1089
1095
  bgTasks.apply(event, Date.now());
1096
+ if (event?.type === 'result' && staleResults > 0) { staleResults -= 1; continue; }
1090
1097
  if (event?.type === 'result' && activeTurn) {
1091
1098
  const turn = activeTurn;
1092
1099
  const cost = turnCost(event);
@@ -1158,24 +1165,50 @@ export async function createClaudeNativeLoopAdapter(options = {}) {
1158
1165
  });
1159
1166
  });
1160
1167
 
1168
+ // The MCP scope check (only the servers this run may use are connected) before a prompt goes to the CLI. A CLI that
1169
+ // exited at once fails it too, with the CLI's own reason when it gave one.
1170
+ const scopeCheck = async () => {
1171
+ if (held) return;
1172
+ try { await waitForClaudeMcpScope(q, externalScopeNames); }
1173
+ catch {
1174
+ input.close(); q.close?.(); await endProcess();
1175
+ // A CLI that ended by itself said why: a resumed session with nothing saved is that, not an MCP problem.
1176
+ const ended = await Promise.race([pump.then(() => null, (error) => error), new Promise((done) => { const timer = setTimeout(done, 1000, null); timer.unref?.(); })]);
1177
+ const noConversation = /No conversation found with session ID[^\n]*/i.exec(`${ended?.message || ''}\n${stderrTail}`);
1178
+ if (noConversation) throw new Error(`Claude Code returned an error result: ${noConversation[0].trim()}`);
1179
+ throw Object.assign(new Error('Claude MCP scope could not be enforced before the first turn'), { code: 'MCP_SCOPE_UNENFORCED' });
1180
+ }
1181
+ };
1182
+ // ready()'s check, which the first turn takes instead of checking again (every later turn checks as before).
1183
+ let readyCheck = null;
1184
+
1161
1185
  return {
1162
1186
  identity: () => ({ providerSessionId: sessionId }),
1163
1187
  isAlive: () => alive,
1188
+ // Review round 3, I1c-b: the runtime awaits this inside its startup window before it reports the run started
1189
+ // (NativeLoopRuntime._bootstrap), as the Codex, OpenCode and Antigravity factories finish their own startup before
1190
+ // they return. Without it a Claude worker read as started before its CLI had proved it runs with its MCP scope,
1191
+ // and a boot failure came only with the first turn, after the dispatcher had committed its single route.
1192
+ ready() {
1193
+ if (!readyCheck) { readyCheck = scopeCheck(); readyCheck.catch(() => {}); }
1194
+ return readyCheck;
1195
+ },
1164
1196
  // The CLI's process while it runs ({ pid }), else null.
1165
1197
  processInfo: () => (child?.pid && !processEnded() ? { pid: child.pid } : null),
1166
1198
  describe: () => ({ provider: 'claude-code', permissionPolicy, capability, askMode, ...(held ? { confinement: held.kind, root: held.root, ...(evaluated ? { role: evaluated.role, skills: [...evalOptions.skills], plugins: evalOptions.plugins.map((plugin) => plugin.path) } : {}) } : {}), ...(guard ? { guard: { mode: guard.mode, capability: guard.capability, writable: [...guard.writable] } } : {}) }),
1167
1199
  async runTurn(prompt, meta = {}) {
1168
- if (!held) {
1169
- try { await waitForClaudeMcpScope(q, externalScopeNames); }
1170
- catch {
1171
- input.close(); q.close?.(); await endProcess();
1172
- // A CLI that ended by itself said why: a resumed session with nothing saved is that, not an MCP problem.
1173
- const ended = await Promise.race([pump.then(() => null, (error) => error), new Promise((done) => { const timer = setTimeout(done, 1000, null); timer.unref?.(); })]);
1174
- const noConversation = /No conversation found with session ID[^\n]*/i.exec(`${ended?.message || ''}\n${stderrTail}`);
1175
- if (noConversation) throw new Error(`Claude Code returned an error result: ${noConversation[0].trim()}`);
1176
- throw Object.assign(new Error('Claude MCP scope could not be enforced before the first turn'), { code: 'MCP_SCOPE_UNENFORCED' });
1177
- }
1200
+ const starting = { reason: null };
1201
+ startingTurn = starting;
1202
+ const check = readyCheck || scopeCheck();
1203
+ readyCheck = null;
1204
+ try { await check; }
1205
+ catch (error) {
1206
+ if (startingTurn === starting) startingTurn = null;
1207
+ throw error;
1178
1208
  }
1209
+ if (startingTurn === starting) startingTurn = null;
1210
+ // Aborted while it waited to start: the prompt never went to the CLI (no result is owed for it).
1211
+ if (starting.reason) throw Object.assign(asAbortError(starting.reason), { notSent: true });
1179
1212
  if (!alive) return Promise.reject(new Error('Claude native loop is closed'));
1180
1213
  if (activeTurn) return Promise.reject(new Error('Claude native loop already has an active turn'));
1181
1214
  onEvent({
@@ -1201,10 +1234,13 @@ export async function createClaudeNativeLoopAdapter(options = {}) {
1201
1234
  });
1202
1235
  },
1203
1236
  async abort(reason = 'aborted') {
1237
+ if (startingTurn && !activeTurn) { startingTurn.reason = reason; return true; }
1204
1238
  if (activeTurn) {
1205
1239
  const turn = activeTurn; activeTurn = null;
1206
1240
  turn.hold?.cancel();
1207
1241
  turn.reject(asAbortError(reason));
1242
+ // A steer keeps the session for the next prompt: the cut prompt's own result is not that one's.
1243
+ if (reason === 'steered' && alive) staleResults += 1;
1208
1244
  }
1209
1245
  if (!alive) return true;
1210
1246
  try {
@@ -1338,6 +1374,12 @@ export async function createOpenCodeNativeLoopAdapter(options = {}) {
1338
1374
  let alive = true;
1339
1375
  let activeAbort = null;
1340
1376
  let activeTurn = null;
1377
+ // The serve's end of a turn a steer cut, still owed ({ until, error }): see the event handler.
1378
+ let steerEcho = null;
1379
+ const isAbortEcho = (event) => {
1380
+ const error = event?.error || event?.info?.error || event?.data?.error || {};
1381
+ return /abort/i.test(String(error?.name || '')) || /turn was stopped/i.test(String(error?.data?.message || error?.message || ''));
1382
+ };
1341
1383
  const eventSource = client.onEvent ? client : client.event;
1342
1384
  let sessionId = null;
1343
1385
  // Assistant text assembled from the SSE stream (message.updated gives roles,
@@ -1501,6 +1543,20 @@ export async function createOpenCodeNativeLoopAdapter(options = {}) {
1501
1543
  // synchronous fetch open and misclassifying a long, healthy turn as
1502
1544
  // `native:iteration-error | fetch failed`.
1503
1545
  const ownsTurnEvent = !!sid && sid === sessionId;
1546
+ // A steer's abort (abort('steered')) ends the cut turn at the serve with "The turn was stopped (user)" and an
1547
+ // idle, which can arrive after the steer's own turn was sent: they are that cut turn's end, never this one's.
1548
+ if (ownsTurnEvent && steerEcho && Date.now() > steerEcho.until) steerEcho = null;
1549
+ if (ownsTurnEvent && steerEcho && /^session[.:]error$/i.test(eventType) && isAbortEcho(event)) {
1550
+ steerEcho.error = true;
1551
+ steerEcho.until = Math.min(steerEcho.until, Date.now() + 2000);
1552
+ onEvent({ provider: 'opencode', runId, eventType, event, steerEcho: true });
1553
+ return;
1554
+ }
1555
+ if (ownsTurnEvent && steerEcho?.error && /^session[.:]idle$/i.test(eventType)) {
1556
+ steerEcho = null;
1557
+ onEvent({ provider: 'opencode', runId, eventType, event, steerEcho: true });
1558
+ return;
1559
+ }
1504
1560
  if (ownsTurnEvent && /^session[.:]idle$/i.test(eventType)) finishTurnWithText();
1505
1561
  if (ownsTurnEvent && /^session[.:]error$/i.test(eventType)) {
1506
1562
  const detail = providerErrorMessage(
@@ -1568,7 +1624,7 @@ export async function createOpenCodeNativeLoopAdapter(options = {}) {
1568
1624
  activeAbort = controller;
1569
1625
  const checkReady = async () => {
1570
1626
  await client.waitUntilConnected?.(10_000);
1571
- if (!alive || controller.signal.aborted) throw asAbortError('aborted');
1627
+ if (!alive || controller.signal.aborted) throw Object.assign(asAbortError('aborted'), { notSent: true });
1572
1628
  const ready = await waitForSynabunTools(client, {
1573
1629
  ...(options.mcpWait || {}), directory: cwd || undefined,
1574
1630
  expected: options.synabunExpected !== false && !held, signal: controller.signal,
@@ -1579,7 +1635,7 @@ export async function createOpenCodeNativeLoopAdapter(options = {}) {
1579
1635
  onEvent({ provider: 'opencode', runId, eventType: 'synabun.mcp.status', event: { sessionID: sessionId, text } });
1580
1636
  },
1581
1637
  });
1582
- if (!ready || controller.signal.aborted || !alive) throw asAbortError('aborted');
1638
+ if (!ready || controller.signal.aborted || !alive) throw Object.assign(asAbortError('aborted'), { notSent: true });
1583
1639
  };
1584
1640
  const request = {
1585
1641
  sessionID: sessionId,
@@ -1653,6 +1709,9 @@ export async function createOpenCodeNativeLoopAdapter(options = {}) {
1653
1709
  }
1654
1710
  },
1655
1711
  async abort(reason = 'aborted') {
1712
+ // Only a turn the serve already has ends there with an echo (a prompt not sent yet has nothing to stop).
1713
+ const sentTurn = !!activeTurn && (activeTurn.mode === 'sync' || activeTurn.sent);
1714
+ steerEcho = reason === 'steered' && sentTurn ? { until: Date.now() + 10_000, error: false } : null;
1656
1715
  if (activeAbort) activeAbort.abort(asAbortError(reason));
1657
1716
  settleActiveTurn(asAbortError(reason));
1658
1717
  try {
@@ -1661,7 +1720,8 @@ export async function createOpenCodeNativeLoopAdapter(options = {}) {
1661
1720
  // background, and its end wakes no model turn in a session nobody owns any more.
1662
1721
  // What it gave up on goes back to the runtime (lib/native-loop-runtime.js stop), which keeps it on the run:
1663
1722
  // its result, its tab and the brain then say that the command may still be running (review 29cd51fe).
1664
- const answer = await settleWithin(client.session.abort({ sessionID: sessionId, directory: cwd || undefined, force: true }));
1723
+ // A steer cuts the turn only: the session goes on, so a command in the background is left to it (no force).
1724
+ const answer = await settleWithin(client.session.abort({ sessionID: sessionId, directory: cwd || undefined, ...(reason === 'steered' ? {} : { force: true }) }));
1665
1725
  const abandoned = Array.isArray(answer?.data?.abandoned) ? answer.data.abandoned : [];
1666
1726
  if (abandoned.length) {
1667
1727
  return { stopped: true, abandoned: abandoned.map((shell) => ({ id: String(shell?.id || ''), command: String(shell?.command || '').slice(0, 200) })) };
@@ -626,6 +626,9 @@ export class NativeLoopRuntime {
626
626
  await cleanupCandidate(adapter, 'invalid_adapter');
627
627
  throw new Error(`${state.profile} native provider did not return a runnable adapter`);
628
628
  }
629
+ // An adapter whose factory returns before its provider proved it runs (Claude Code: the CLI and its MCP scope)
630
+ // finishes its startup here, inside the same startup window and cancellation, before the run reads as started.
631
+ if (typeof adapter.ready === 'function') await Promise.race([adapter.ready(), startupTimeout, startupCancelled]);
629
632
  if (record.status !== 'starting' || record.stopping) {
630
633
  await cleanupCandidate(adapter, record.stoppedReason || 'startup_cancelled');
631
634
  const cancelled = new Error(`${state.profile} native loop was stopped during provider startup`);
@@ -228,12 +228,14 @@ async function readJson(res) {
228
228
  * 'error' something answered, but not OpenCode 2's API
229
229
  * Never throws.
230
230
  */
231
- export async function checkOpencodeServer({ port, password = null, fetchImpl = globalThis.fetch, timeoutMs = 2000, host = '127.0.0.1' } = {}) {
231
+ export async function checkOpencodeServer({ port, password = null, fetchImpl = globalThis.fetch, timeoutMs = 2000, host = '127.0.0.1', signal = null } = {}) {
232
232
  let res;
233
233
  try {
234
+ const timeout = AbortSignal.timeout(timeoutMs);
235
+ const reqSignal = signal ? AbortSignal.any([timeout, signal]) : timeout;
234
236
  res = await fetchImpl(`http://${host}:${port}/api/info`, {
235
237
  headers: { accept: 'application/json', ...(password ? { authorization: basicAuthHeader(password) } : {}) },
236
- signal: AbortSignal.timeout(timeoutMs),
238
+ signal: reqSignal,
237
239
  });
238
240
  } catch (error) {
239
241
  return { ok: false, version: null, state: 'down', error: String(error?.message || error) };