synabun 2.4.5 → 2.4.6

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 (95) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +1 -1
  3. package/docs/whatsapp.md +17 -1
  4. package/hooks/claude-code/session-start.mjs +21 -18
  5. package/lib/claude-global-config.js +214 -0
  6. package/lib/client-config-repair.js +17 -3
  7. package/mcp-server/dist/index.d.ts.map +1 -1
  8. package/mcp-server/dist/index.js +6 -1
  9. package/mcp-server/dist/index.js.map +1 -1
  10. package/mcp-server/dist/services/tool-catalog.js +1 -1
  11. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  12. package/mcp-server/dist/tools/agents.d.ts +2 -0
  13. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  14. package/mcp-server/dist/tools/agents.js +11 -5
  15. package/mcp-server/dist/tools/agents.js.map +1 -1
  16. package/mcp-server/dist/tools/skill-tools.d.ts +24 -5
  17. package/mcp-server/dist/tools/skill-tools.d.ts.map +1 -1
  18. package/mcp-server/dist/tools/skill-tools.js +88 -8
  19. package/mcp-server/dist/tools/skill-tools.js.map +1 -1
  20. package/mcp-server/dist/tools/tool-groups.d.ts.map +1 -1
  21. package/mcp-server/dist/tools/tool-groups.js +19 -4
  22. package/mcp-server/dist/tools/tool-groups.js.map +1 -1
  23. package/mcp-server/package-lock.json +2 -2
  24. package/mcp-server/package.json +1 -1
  25. package/mcp-server/src/index.ts +6 -1
  26. package/mcp-server/src/services/tool-catalog.ts +1 -1
  27. package/mcp-server/src/tools/agents.ts +11 -5
  28. package/mcp-server/src/tools/skill-tools.ts +82 -9
  29. package/mcp-server/src/tools/tool-groups.ts +19 -4
  30. package/neural-interface/i18n/en.json +135 -10
  31. package/neural-interface/i18n/pt-BR.json +135 -10
  32. package/neural-interface/lib/antigravity/panel-bridge.js +7 -3
  33. package/neural-interface/lib/assistant-dispatch.js +15 -1
  34. package/neural-interface/lib/assistant-runtime.js +79 -8
  35. package/neural-interface/lib/assistant-user-context.js +7 -3
  36. package/neural-interface/lib/claude-agent-bridge.js +13 -2
  37. package/neural-interface/lib/codex-thread-history.js +144 -7
  38. package/neural-interface/lib/codex-worker-app-server.js +84 -30
  39. package/neural-interface/lib/db.js +26 -0
  40. package/neural-interface/lib/greeting/sources.js +7 -3
  41. package/neural-interface/lib/jsonl-lines.js +10 -11
  42. package/neural-interface/lib/line-buffer.js +88 -0
  43. package/neural-interface/lib/loop-stall.js +15 -1
  44. package/neural-interface/lib/memory-list-read.js +105 -0
  45. package/neural-interface/lib/memory-timers.js +4 -1
  46. package/neural-interface/lib/native-loop-runtime.js +7 -3
  47. package/neural-interface/lib/provider-panel-api-key-auth.js +33 -6
  48. package/neural-interface/lib/skills/api-v2.js +18 -3
  49. package/neural-interface/lib/skills/bundle.js +2 -2
  50. package/neural-interface/lib/skills/deploy.js +169 -34
  51. package/neural-interface/lib/skills/digest.js +57 -3
  52. package/neural-interface/lib/skills/health.js +55 -1
  53. package/neural-interface/lib/skills/known-bridge-digests.json +12 -0
  54. package/neural-interface/lib/skills/runtime-checks.js +7 -4
  55. package/neural-interface/lib/skills/scan-shell.js +56 -7
  56. package/neural-interface/lib/skills/scan.js +13 -12
  57. package/neural-interface/lib/skills/service.js +7 -2
  58. package/neural-interface/lib/skills/telemetry.js +2 -2
  59. package/neural-interface/lib/teams/README.md +12 -5
  60. package/neural-interface/lib/teams/api.js +15 -4
  61. package/neural-interface/lib/teams/index.js +2 -0
  62. package/neural-interface/lib/teams/landing.js +195 -75
  63. package/neural-interface/lib/teams/scheduler.js +31 -32
  64. package/neural-interface/lib/terminal-token-redaction.js +228 -58
  65. package/neural-interface/lib/terminal-tokens.js +18 -0
  66. package/neural-interface/lib/whatsapp/brain.js +21 -0
  67. package/neural-interface/lib/whatsapp/bridge.js +40 -4
  68. package/neural-interface/package-lock.json +2 -2
  69. package/neural-interface/package.json +1 -1
  70. package/neural-interface/public/index.html +117 -37
  71. package/neural-interface/public/shared/agents/studio/ax-api.js +11 -0
  72. package/neural-interface/public/shared/agents/studio/ax-create-view.js +1 -1
  73. package/neural-interface/public/shared/agents/studio/ax-icons.js +1 -0
  74. package/neural-interface/public/shared/agents/studio/ax-library-view.js +3 -2
  75. package/neural-interface/public/shared/agents/studio/ax-main.js +127 -41
  76. package/neural-interface/public/shared/agents/studio/ax-review-view.js +3 -2
  77. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +137 -39
  78. package/neural-interface/public/shared/agents/studio/ax-teams.js +219 -4
  79. package/neural-interface/public/shared/agents/studio/ax-ui.js +31 -0
  80. package/neural-interface/public/shared/agents/studio/ax-views.js +67 -69
  81. package/neural-interface/public/shared/agents/studio/ax-work-answer.js +86 -0
  82. package/neural-interface/public/shared/agents/studio/ax-work-view.js +305 -0
  83. package/neural-interface/public/shared/agents/studio/ax-work.css +74 -0
  84. package/neural-interface/public/shared/agents/studio/ax-work.js +300 -0
  85. package/neural-interface/public/shared/cdx/cdx-deferred.js +90 -0
  86. package/neural-interface/public/shared/cdx/cdx-render.js +18 -7
  87. package/neural-interface/public/shared/cdx/cdx-tabs.js +2 -1
  88. package/neural-interface/public/shared/loading-diagnostic-entry.js +16 -1
  89. package/neural-interface/public/shared/skills/studio/sx-operations-view.js +5 -0
  90. package/neural-interface/public/shared/skills/studio/sx-plan.js +42 -3
  91. package/neural-interface/public/shared/skills/studio/sx-publish-view.js +20 -4
  92. package/neural-interface/server.js +316 -252
  93. package/npm-shrinkwrap.json +2 -2
  94. package/package.json +2 -1
  95. package/skills/skill-forge/SKILL.md +7 -3
@@ -4,6 +4,67 @@ const CODEX_HISTORY_PAGE_TIMEOUT_MS = 15000;
4
4
  const CODEX_TURN_PAGE_SIZE = 100;
5
5
  const CODEX_ITEM_PAGE_SIZE = 500;
6
6
 
7
+ // ── Pages sized by what they weigh ──
8
+ // A page of items is one JSON-RPC reply: one line of the app-server's stdout, parsed and redacted in one go on the
9
+ // server's own thread. Asked for 500 items at a time, a thread of generated images answered with all of it at once
10
+ // (2026-11-29: 408 items, 171 MB, one line), and the server answered nobody for the time that took. The app-server
11
+ // has no way to leave image data out of an item, so the lever is the page: the first page asks for few items, and
12
+ // every next one for as many as fit the weight the last page showed (never more than CODEX_ITEM_PAGE_SIZE, and at
13
+ // most four times the last page). A thread of small items is read in pages of 500 again after two steps.
14
+ /** How many items the first page of a thread asks for. */
15
+ export const CODEX_ITEM_FIRST_PAGE = 32;
16
+ /** How many turns with their items the first page of the older, turn-by-turn reading asks for. */
17
+ export const CODEX_FULL_TURN_FIRST_PAGE = 8;
18
+ /** What a page should weigh at most, in characters of its strings (about its size as JSON). */
19
+ export const CODEX_PAGE_TARGET_CHARS = 16 * 1024 * 1024;
20
+
21
+ // ── Inline generated images, as references ──
22
+ /** A generated image's inline data of this many characters or more is handed on as a reference, not as text. */
23
+ export const CODEX_INLINE_IMAGE_MIN_CHARS = 64 * 1024;
24
+ /** The mark an item carries for what was left out of it: `{ turnId, fields: { result: { chars, head } } }`. */
25
+ export const CODEX_DEFERRED_KEY = '_synabunDeferred';
26
+ /** How much of the beginning stays in the mark: what a card's head showed of the data (one short line). */
27
+ const CODEX_DEFERRED_HEAD_CHARS = 160;
28
+
29
+ /** The characters in every string of `value`, at any depth: what it weighs, about, as JSON. */
30
+ export function approximateChars(value) {
31
+ let chars = 0;
32
+ const stack = [value];
33
+ let nodes = 0;
34
+ while (stack.length && nodes++ < 2_000_000) {
35
+ const item = stack.pop();
36
+ if (typeof item === 'string') chars += item.length;
37
+ else if (Array.isArray(item)) for (let i = 0; i < item.length; i++) stack.push(item[i]);
38
+ else if (item && typeof item === 'object') for (const key in item) stack.push(item[key]);
39
+ }
40
+ return chars;
41
+ }
42
+
43
+ /** How many entries the next page asks for, after a page of `count` entries that weighed `chars`. */
44
+ export function nextPageLimit(limit, count, chars, { max, target = CODEX_PAGE_TARGET_CHARS } = {}) {
45
+ if (!(count > 0)) return Math.min(max, limit);
46
+ const perEntry = Math.max(1, chars / count);
47
+ return Math.max(1, Math.min(max, limit * 4, Math.floor(target / perEntry)));
48
+ }
49
+
50
+ /**
51
+ * `item` as the page gets it: a generated image's inline data (megabytes of base64 in `result`) is left out and
52
+ * marked, with the turn it belongs to, so the page can ask for it when somebody opens the item
53
+ * (readCodexThreadItem). Everything else of the item, and every other item, is handed on as it is.
54
+ */
55
+ export function deferCodexInlineImage(item, turnId) {
56
+ if (!item || typeof item !== 'object' || item.type !== 'imageGeneration') return item;
57
+ if (typeof item.result !== 'string' || item.result.length < CODEX_INLINE_IMAGE_MIN_CHARS) return item;
58
+ return {
59
+ ...item,
60
+ result: '',
61
+ [CODEX_DEFERRED_KEY]: {
62
+ turnId: turnId == null ? null : String(turnId),
63
+ fields: { result: { chars: item.result.length, head: item.result.slice(0, CODEX_DEFERRED_HEAD_CHARS) } },
64
+ },
65
+ };
66
+ }
67
+
7
68
  function codexErrorText(error) {
8
69
  if (!error) return '';
9
70
  const parts = [
@@ -32,20 +93,31 @@ export function isCodexHistoryUnavailableBeforeFirstTurn(error) {
32
93
  return /(?:not materialized yet|unavailable before first user message)/i.test(codexErrorText(error));
33
94
  }
34
95
 
96
+ /**
97
+ * Every page of `method`, in order. `adaptive: { first, max, target }`: the first page asks for `first` entries and
98
+ * each next one for what the last page's weight allows (nextPageLimit); without it every page asks for
99
+ * `baseParams.limit`. `each(entry)`: what is kept of an entry (it may return a lighter one).
100
+ */
35
101
  async function paginateCodexHistory(request, method, baseParams, {
36
102
  timeoutMs = CODEX_HISTORY_PAGE_TIMEOUT_MS,
103
+ adaptive = null,
104
+ each = null,
37
105
  } = {}) {
38
106
  const data = [];
39
107
  const seenCursors = new Set();
40
108
  let cursor = null;
109
+ let limit = adaptive ? Math.max(1, Math.min(adaptive.max, adaptive.first)) : baseParams.limit;
41
110
 
42
111
  do {
43
- const params = cursor == null ? baseParams : { ...baseParams, cursor };
112
+ const params = { ...baseParams, limit };
113
+ if (cursor != null) params.cursor = cursor;
44
114
  const result = await request(method, params, timeoutMs);
45
115
  if (!Array.isArray(result?.data)) {
46
116
  throw historyProtocolError(`${method} returned an invalid page`);
47
117
  }
48
- data.push(...result.data);
118
+ if (adaptive) limit = nextPageLimit(limit, result.data.length, approximateChars(result.data), adaptive);
119
+ if (each) for (const entry of result.data) data.push(each(entry));
120
+ else data.push(...result.data);
49
121
 
50
122
  const nextCursor = result.nextCursor ?? null;
51
123
  if (nextCursor == null) break;
@@ -62,21 +134,39 @@ async function paginateCodexHistory(request, method, baseParams, {
62
134
  return data;
63
135
  }
64
136
 
137
+ /** The item of an entry or of a turn passed through `transformItem` (hydrateCodexThreadHistory's option). */
138
+ const transformed = (transformItem, item, turnId) => (typeof transformItem === 'function' && item && typeof item === 'object' ? transformItem(item, turnId) : item);
139
+
65
140
  async function listCodexTurns(request, threadId, itemsView, options) {
141
+ const full = itemsView === 'full';
66
142
  return paginateCodexHistory(request, 'thread/turns/list', {
67
143
  threadId,
68
144
  limit: options.turnPageSize ?? CODEX_TURN_PAGE_SIZE,
69
145
  sortDirection: 'asc',
70
146
  itemsView,
71
- }, options);
147
+ }, {
148
+ timeoutMs: options.timeoutMs,
149
+ // Turns with their items weigh what their items weigh: sized like item pages. Turns alone are small.
150
+ adaptive: full ? { first: Math.min(options.turnPageSize ?? CODEX_TURN_PAGE_SIZE, options.firstFullTurnPage ?? CODEX_FULL_TURN_FIRST_PAGE), max: options.turnPageSize ?? CODEX_TURN_PAGE_SIZE, target: options.pageTargetChars } : null,
151
+ each: full && typeof options.transformItem === 'function'
152
+ ? (turn) => (turn && Array.isArray(turn.items) ? { ...turn, items: turn.items.map((item) => transformed(options.transformItem, item, turn.id)) } : turn)
153
+ : null,
154
+ });
72
155
  }
73
156
 
74
157
  async function listCodexItems(request, threadId, options) {
158
+ const max = options.itemPageSize ?? CODEX_ITEM_PAGE_SIZE;
75
159
  return paginateCodexHistory(request, 'thread/items/list', {
76
160
  threadId,
77
- limit: options.itemPageSize ?? CODEX_ITEM_PAGE_SIZE,
161
+ limit: max,
78
162
  sortDirection: 'asc',
79
- }, options);
163
+ }, {
164
+ timeoutMs: options.timeoutMs,
165
+ adaptive: { first: Math.min(max, options.firstItemPage ?? CODEX_ITEM_FIRST_PAGE), max, target: options.pageTargetChars },
166
+ each: typeof options.transformItem === 'function'
167
+ ? (entry) => (entry && entry.item && typeof entry.item === 'object' ? { ...entry, item: transformed(options.transformItem, entry.item, entry.turnId) } : entry)
168
+ : null,
169
+ });
80
170
  }
81
171
 
82
172
  function mergeCodexItemsIntoTurns(turns, itemEntries) {
@@ -113,6 +203,12 @@ function mergeCodexItemsIntoTurns(turns, itemEntries) {
113
203
  return hydratedTurns;
114
204
  }
115
205
 
206
+ /**
207
+ * A thread's turns with their items, read in pages. `options.transformItem(item, turnId)`: what is kept of each item
208
+ * as its page arrives (the server passes deferCodexInlineImage, so a page's megabytes of image data are let go
209
+ * before the next page is asked for); `firstItemPage`, `itemPageSize`, `turnPageSize`, `pageTargetChars`,
210
+ * `timeoutMs`: the paging (the defaults are the constants above).
211
+ */
116
212
  export async function hydrateCodexThreadHistory(request, threadId, options = {}) {
117
213
  if (typeof request !== 'function') throw new TypeError('request must be a function');
118
214
  const targetThreadId = String(threadId || '');
@@ -143,8 +239,49 @@ export async function hydrateCodexThreadHistory(request, threadId, options = {})
143
239
  }
144
240
  }
145
241
 
242
+ /**
243
+ * One item of a thread, whole: what the page asks for when somebody opens an item whose image data was left out
244
+ * (deferCodexInlineImage). `thread/items/read` gives it directly; a Codex without that method is asked for the
245
+ * turn's items in pages (sized by weight, like the history) until the item comes by. null when the thread has no
246
+ * such item in that turn.
247
+ */
248
+ export async function readCodexThreadItem(request, threadId, turnId, itemId, options = {}) {
249
+ if (typeof request !== 'function') throw new TypeError('request must be a function');
250
+ const thread = String(threadId || '');
251
+ const turn = String(turnId || '');
252
+ const target = String(itemId || '');
253
+ if (!thread || !turn || !target) throw new Error('A thread, a turn and an item are required.');
254
+ const timeoutMs = options.timeoutMs ?? CODEX_HISTORY_PAGE_TIMEOUT_MS;
255
+ const itemOf = (entry) => (entry?.item && typeof entry.item === 'object' ? entry.item : entry);
256
+ try {
257
+ const result = await request('thread/items/read', { threadId: thread, turnId: turn, itemIds: [target] }, timeoutMs);
258
+ const found = (Array.isArray(result?.data) ? result.data : []).map(itemOf).find((item) => String(item?.id ?? '') === target);
259
+ return found || null;
260
+ } catch (error) {
261
+ if (!isCodexItemsPaginationUnsupported(error)) throw error;
262
+ }
263
+ const max = options.itemPageSize ?? CODEX_ITEM_PAGE_SIZE;
264
+ let limit = Math.min(max, options.firstItemPage ?? CODEX_ITEM_FIRST_PAGE);
265
+ let cursor = null;
266
+ const seenCursors = new Set();
267
+ for (;;) {
268
+ const params = { threadId: thread, turnId: turn, limit, sortDirection: 'asc' };
269
+ if (cursor != null) params.cursor = cursor;
270
+ const result = await request('thread/items/list', params, timeoutMs);
271
+ if (!Array.isArray(result?.data)) throw historyProtocolError('thread/items/list returned an invalid page');
272
+ const found = result.data.map(itemOf).find((item) => String(item?.id ?? '') === target);
273
+ if (found) return found;
274
+ const nextCursor = result.nextCursor ?? null;
275
+ if (nextCursor == null) return null;
276
+ if (typeof nextCursor !== 'string' || !nextCursor || seenCursors.has(nextCursor)) throw historyProtocolError('thread/items/list returned an invalid nextCursor');
277
+ seenCursors.add(nextCursor);
278
+ cursor = nextCursor;
279
+ limit = nextPageLimit(limit, result.data.length, approximateChars(result.data), { max, target: options.pageTargetChars });
280
+ }
281
+ }
282
+
146
283
  /** 0.160 removed rollback; revert excludes a named turn and all later turns. */
147
- export async function revertCodexThreadHistory(request, threadId, { numTurns = 1, beforeTurnId } = {}) {
284
+ export async function revertCodexThreadHistory(request, threadId, { numTurns = 1, beforeTurnId, history: historyOptions = {} } = {}) {
148
285
  if (!threadId) throw new Error('No thread provided');
149
286
  if (!Number.isSafeInteger(numTurns) || numTurns < 1) throw new Error('Turn count must be a positive integer.');
150
287
  const turns = beforeTurnId ? null : await listCodexTurns(request, threadId, 'notLoaded', {});
@@ -160,6 +297,6 @@ export async function revertCodexThreadHistory(request, threadId, { numTurns = 1
160
297
  if (!count) throw error;
161
298
  return request('thread/rollback', { threadId, numTurns: count }, CODEX_HISTORY_PAGE_TIMEOUT_MS);
162
299
  }
163
- const history = await hydrateCodexThreadHistory(request, threadId);
300
+ const history = await hydrateCodexThreadHistory(request, threadId, historyOptions);
164
301
  return { ...result, thread: { ...result.thread, turns: history.turns } };
165
302
  }
@@ -2,6 +2,8 @@
2
2
  // worker's event/usage contract while thread/resume reopens its durable thread.
3
3
  import { spawn, execFileSync } from 'node:child_process';
4
4
  import { StringDecoder } from 'node:string_decoder';
5
+ import { createLineBuffer } from './line-buffer.js';
6
+ import { sizedLabel, timeBlockingWork } from './loop-stall.js';
5
7
 
6
8
  const toml = (v) => Array.isArray(v) ? `[${v.map(toml).join(',')}]`
7
9
  : v && typeof v === 'object' ? `{${Object.entries(v).filter(([, x]) => x != null).map(([k, x]) => `${JSON.stringify(k)}=${toml(x)}`).join(',')}}`
@@ -26,8 +28,17 @@ export function codexWorkerConfigOverrides(config) {
26
28
  return overrides;
27
29
  }
28
30
 
31
+ // How long the next turn waits for a turn this client interrupted to end at the app-server (turn/completed).
32
+ export const CODEX_INTERRUPT_SETTLE_MS = 10_000;
33
+
34
+ /** The turn a notification belongs to (item/*, turn/*), or null. */
35
+ function notificationTurnId(params) {
36
+ const id = params?.turnId || params?.turn?.id || params?.item?.turnId || null;
37
+ return id ? String(id) : null;
38
+ }
39
+
29
40
  export class CodexWorkerAppServer {
30
- constructor({ codexPathOverride, env, config = {}, configArgs = [], apiKey, signal, onProcess = () => {}, onRequest = null, permissionPolicy = 'auto' }) {
41
+ constructor({ codexPathOverride, env, config = {}, configArgs = [], apiKey, signal, onProcess = () => {}, onRequest = null, permissionPolicy = 'auto', interruptSettleMs = CODEX_INTERRUPT_SETTLE_MS }) {
31
42
  this.onRequest = onRequest;
32
43
  this.approvalPolicy = permissionPolicy === 'ask' ? 'untrusted' : 'never';
33
44
  this.requestAbort = new AbortController();
@@ -37,6 +48,13 @@ export class CodexWorkerAppServer {
37
48
  this.seq = 0;
38
49
  this.listener = null;
39
50
  this.failure = null;
51
+ // Turns this client interrupted (a steer, a stop): the app-server ends such a turn a moment after turn/interrupt
52
+ // (its tool call is cut first) with turn/completed { status: 'interrupted' }. Those last notifications belong to
53
+ // that turn and never reach the turn that follows it on the same thread, which would read them as its own end.
54
+ this.interruptedTurns = new Set();
55
+ // turnId → the wait for that end; the next turn/start goes only after it (bounded by interruptSettleMs).
56
+ this.interrupts = new Map();
57
+ this.interruptSettleMs = Math.max(0, Number(interruptSettleMs) || 0);
40
58
  const args = [...configArgs];
41
59
  for (const override of codexWorkerConfigOverrides(config)) args.push('-c', override);
42
60
  // Run identity in the command line permits conservative orphan identification.
@@ -44,34 +62,43 @@ export class CodexWorkerAppServer {
44
62
  this.proc = spawn(codexPathOverride, args, { env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
45
63
  this.exited = new Promise((r) => this.proc.once('close', r));
46
64
  onProcess({ pid: this.proc.pid, startedAt: new Date().toISOString() });
47
- let buffer = '';
65
+ // stdout cut into lines in time linear in what arrives (lib/line-buffer.js: a chunk is searched once, a long line
66
+ // joined once), and each line's parse and dispatch timed by name, so a stall of the server's thread names it.
67
+ const lines = createLineBuffer();
48
68
  const decoder = new StringDecoder('utf8');
49
- this.proc.stdout.on('data', (chunk) => {
50
- buffer += decoder.write(chunk);
51
- let end;
52
- while ((end = buffer.indexOf('\n')) >= 0) {
53
- const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
54
- let msg; try { msg = JSON.parse(line); } catch { continue; }
55
- if (msg.id != null && !msg.method) {
56
- const p = this.pending.get(msg.id); if (!p) continue;
57
- this.pending.delete(msg.id); clearTimeout(p.timer);
58
- msg.error ? p.reject(new Error(msg.error.message || 'Codex RPC failed')) : p.resolve(msg.result);
59
- } else if (msg.id != null) {
60
- const controller = new AbortController();
61
- this.incoming.set(msg.id, controller);
62
- Promise.resolve().then(() => {
63
- if (!this.onRequest) throw new Error('Worker has no interactive request handler');
64
- return this.onRequest(msg, controller.signal);
65
- }).then((reply) => {
66
- if (!this.failure && !controller.signal.aborted) this.write({ id: msg.id, ...reply });
67
- }, (error) => {
68
- if (!this.failure && !controller.signal.aborted) this.write({ id: msg.id, error: { code: -32000, message: error.message } });
69
- }).finally(() => this.incoming.delete(msg.id));
70
- } else {
71
- if (msg.method === 'serverRequest/resolved') this.incoming.get(msg.params?.requestId)?.abort();
72
- if (msg.method === 'turn/completed') { for (const pending of this.incoming.values()) pending.abort(); this.incoming.clear(); }
73
- this.listener?.(msg);
69
+ const handleLine = (line) => {
70
+ let msg; try { msg = JSON.parse(line); } catch { return; }
71
+ if (msg.id != null && !msg.method) {
72
+ const p = this.pending.get(msg.id); if (!p) return;
73
+ this.pending.delete(msg.id); clearTimeout(p.timer);
74
+ msg.error ? p.reject(new Error(msg.error.message || 'Codex RPC failed')) : p.resolve(msg.result);
75
+ } else if (msg.id != null) {
76
+ const controller = new AbortController();
77
+ this.incoming.set(msg.id, controller);
78
+ Promise.resolve().then(() => {
79
+ if (!this.onRequest) throw new Error('Worker has no interactive request handler');
80
+ return this.onRequest(msg, controller.signal);
81
+ }).then((reply) => {
82
+ if (!this.failure && !controller.signal.aborted) this.write({ id: msg.id, ...reply });
83
+ }, (error) => {
84
+ if (!this.failure && !controller.signal.aborted) this.write({ id: msg.id, error: { code: -32000, message: error.message } });
85
+ }).finally(() => this.incoming.delete(msg.id));
86
+ } else {
87
+ // The last words of a turn this client interrupted: its end settles the wait for it, nothing else sees them
88
+ // (not the turn that runs now, nor that turn's pending requests).
89
+ const turnOf = notificationTurnId(msg.params);
90
+ if (turnOf && this.interruptedTurns.has(turnOf)) {
91
+ if (msg.method === 'turn/completed') this.interrupts.get(turnOf)?.finish();
92
+ return;
74
93
  }
94
+ if (msg.method === 'serverRequest/resolved') this.incoming.get(msg.params?.requestId)?.abort();
95
+ if (msg.method === 'turn/completed') { for (const pending of this.incoming.values()) pending.abort(); this.incoming.clear(); }
96
+ this.listener?.(msg);
97
+ }
98
+ };
99
+ this.proc.stdout.on('data', (chunk) => {
100
+ for (const line of lines.push(decoder.write(chunk))) {
101
+ timeBlockingWork(sizedLabel('codex-worker:stdout-line', line.length), () => handleLine(line));
75
102
  }
76
103
  });
77
104
  // Drain stderr without exposing credentials/config to the worker transcript.
@@ -96,8 +123,30 @@ export class CodexWorkerAppServer {
96
123
  this.requestAbort.abort();
97
124
  for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(error); }
98
125
  this.pending.clear();
126
+ for (const wait of [...this.interrupts.values()]) wait.finish();
99
127
  this.listener?.({ method: 'synabun/exit', error });
100
128
  }
129
+ /**
130
+ * Interrupt a turn in flight, once. From now on its notifications are its own (see the reader), and the next turn
131
+ * of the thread waits (settledInterrupts) until it ended: its turn/completed, a refused interrupt (the turn was not
132
+ * running any more), the process's exit, or interruptSettleMs.
133
+ */
134
+ interruptTurn(threadId, turnId) {
135
+ const key = String(turnId);
136
+ if (this.interruptedTurns.has(key)) return;
137
+ this.interruptedTurns.add(key);
138
+ if (this.interruptedTurns.size > 100) this.interruptedTurns.delete(this.interruptedTurns.values().next().value);
139
+ let settle;
140
+ const wait = { done: new Promise((resolve) => { settle = resolve; }), timer: null };
141
+ wait.finish = () => { clearTimeout(wait.timer); if (this.interrupts.get(key) === wait) this.interrupts.delete(key); settle(); };
142
+ wait.timer = setTimeout(wait.finish, this.interruptSettleMs);
143
+ wait.timer.unref?.();
144
+ this.interrupts.set(key, wait);
145
+ if (this.failure) { wait.finish(); return; }
146
+ this.rpc('turn/interrupt', { threadId, turnId }).catch(wait.finish);
147
+ }
148
+ /** Every interrupted turn has ended (or stopped being waited for). */
149
+ settledInterrupts() { return Promise.all([...this.interrupts.values()].map((wait) => wait.done)); }
101
150
  rpc(method, params) {
102
151
  if (this.failure) return Promise.reject(this.failure);
103
152
  return new Promise((resolve, reject) => {
@@ -129,15 +178,20 @@ export class CodexWorkerAppServer {
129
178
  get id() { return id; }, ready: () => ready,
130
179
  async runStreamed(prompt, { signal, outputSchema } = {}) {
131
180
  await ready;
132
- const queue = []; const text = new Map(); let wake; let done = false; let failure; let turnId;
181
+ // A turn this client interrupted (a steer cuts a turn and sends the next at once) ends first at the app-server.
182
+ await owner.settledInterrupts();
183
+ const queue = []; const text = new Map(); let wake; let done = false; let failure; let turnId; let ended = false;
133
184
  const push = (event) => { queue.push(event); wake?.(); };
134
185
  const abort = () => {
135
186
  failure = Object.assign(new Error('Codex turn aborted'), { name: 'AbortError' }); done = true; wake?.();
136
- if (turnId) owner.rpc('turn/interrupt', { threadId: id, turnId }).catch(() => {});
187
+ if (turnId && !ended) owner.interruptTurn(id, turnId);
137
188
  };
138
189
  owner.listener = (msg) => {
139
190
  const p = msg.params || {};
140
191
  if (p.threadId && p.threadId !== id) return;
192
+ // One turn's notifications only: another turn's (an earlier one) never ends or feeds this one.
193
+ const turnOf = notificationTurnId(p);
194
+ if (turnOf && turnId && turnOf !== String(turnId)) return;
141
195
  if (msg.method === 'synabun/exit') { failure = msg.error; done = true; wake?.(); }
142
196
  if (msg.method === 'item/agentMessage/delta') {
143
197
  const value = (text.get(p.itemId) || '') + (p.delta || '');
@@ -153,7 +207,7 @@ export class CodexWorkerAppServer {
153
207
  if (p.turn?.status === 'failed') push({ type: 'turn.failed', error: p.turn.error || { message: 'Codex turn failed' } });
154
208
  else if (p.turn?.status === 'interrupted') failure = Object.assign(new Error('Codex turn interrupted'), { name: 'AbortError' });
155
209
  else push({ type: 'turn.completed' }); // rollout meter is authoritative across resumes
156
- done = true; wake?.();
210
+ ended = true; done = true; wake?.();
157
211
  }
158
212
  };
159
213
  signal?.addEventListener('abort', abort, { once: true });
@@ -10,6 +10,7 @@ import { resolve, dirname } from 'path';
10
10
  import { existsSync, mkdirSync } from 'fs';
11
11
  import { getDb as sharedDb, closeDatabase, memoryVectors, chunkVectors, searchMemories as sharedSearch, searchSessionChunks as sharedSessionSearch, updatePayload as sharedUpdate, deleteMemory as sharedDelete } from '../../mcp-server/dist/services/sqlite.js';
12
12
  import { readRows } from '../../mcp-server/dist/services/retrieval-reader.js';
13
+ import { createMemoryListReader } from './memory-list-read.js';
13
14
  import { generateEmbedding, generateEmbeddingBatch, warmupEmbeddings, EMBEDDING_MODEL, EMBEDDING_DIMENSIONS } from '../../mcp-server/dist/services/local-embeddings.js';
14
15
  export { memoryVectors, chunkVectors, warmupEmbeddings, EMBEDDING_MODEL };
15
16
  export const EMBEDDING_DIMS = EMBEDDING_DIMENSIONS;
@@ -130,6 +131,7 @@ export function closeDb() {
130
131
  }
131
132
  memoryVectors.invalidate();
132
133
  chunkVectors.invalidate();
134
+ memoryList.forget();
133
135
  }
134
136
 
135
137
  // --- In-memory vector caches (see vector-cache.js for coherence model) ---
@@ -596,6 +598,30 @@ export function getMemoriesPage({ offset = 0, limit } = {}) {
596
598
  return { rows: rows.map((row) => ({ id: row.id, ...rowToPayload(row) })), total };
597
599
  }
598
600
 
601
+ // The same two answers for the route that serves the page's list, read on the retrieval reader's thread and far
602
+ // cheaper a page (lib/memory-list-read.js): the two functions above held the server's only thread for 0.6-7.7 s a
603
+ // page on the owner's store while it was busy. Async; when the reader cannot serve a read it runs on this connection.
604
+ const memoryList = createMemoryListReader({
605
+ read: (sql, params = []) => { getDb(); return readRows(sql, params); }, // the store's refusal while it is closed or migrating first
606
+ toMemory: (row) => ({ id: row.id, ...rowToPayload(row) }),
607
+ });
608
+
609
+ /**
610
+ * getMemoriesPage(), off the server's thread. `stamp` is the list's stamp (lib/memory-list-stamp.js) when the caller
611
+ * has it: the pages of one unchanged list then share one read of the order.
612
+ * @param {{ offset?: number, limit: number }} page
613
+ * @param {{ stamp?: string | null }} [options]
614
+ * @returns {Promise<{ rows: Array<object>, total: number }>}
615
+ */
616
+ export function readMemoriesPage(page, options) {
617
+ return memoryList.page(page, options);
618
+ }
619
+
620
+ /** getAllMemories() (live memories, no vectors), off the server's thread. */
621
+ export function readAllMemories(options) {
622
+ return memoryList.all(options);
623
+ }
624
+
599
625
  /**
600
626
  * Get all memories with vectors for link computation.
601
627
  */
@@ -114,11 +114,15 @@ export function createGreetingSources({
114
114
  return out.sort((a, b) => (ms(b.endedAt) ?? 0) - (ms(a.endedAt) ?? 0)).slice(0, FACTS.threads);
115
115
  }
116
116
 
117
+ // Three reads below say `+trashed_at IS NULL` and `+lower(project) = lower(?)`: the plus keeps SQLite, which has no
118
+ // statistics here, from choosing the index of a whole project or of every live memory (13-21,000 rows read whole,
119
+ // 26-29 ms on an idle machine and up to 1.6 s on a busy one, on the server's thread). The category's index or the
120
+ // creation time's is used instead: the same rows in about a millisecond.
117
121
  function summaryRows(project) {
118
122
  const categories = [...new Set(safe(() => sessionCategories(), ['conversations']).map(String).filter((name) => name && name !== CATEGORIES.threads))];
119
123
  if (!categories.length) return [];
120
124
  const rows = safe(() => getDb().prepare(`SELECT id, content, created_at FROM memories
121
- WHERE trashed_at IS NULL AND category IN (${marks(categories.length)}) AND lower(project) = lower(?) ORDER BY created_at DESC LIMIT ?`).all(...categories, project, FACTS.sessions * 3), []);
125
+ WHERE +trashed_at IS NULL AND category IN (${marks(categories.length)}) AND +lower(project) = lower(?) ORDER BY created_at DESC LIMIT ?`).all(...categories, project, FACTS.sessions * 3), []);
122
126
  const out = [];
123
127
  for (const row of rows) {
124
128
  const parsed = parseSessionSummary(row.content);
@@ -134,7 +138,7 @@ export function createGreetingSources({
134
138
  if (from == null) return [];
135
139
  const skip = [...new Set([CATEGORIES.threads, CATEGORIES.knowledge, CATEGORIES.knowledgeParent, ...exclude])];
136
140
  const rows = safe(() => getDb().prepare(`SELECT id, content, category, importance, created_at FROM memories
137
- WHERE trashed_at IS NULL AND lower(project) = lower(?) AND importance >= ? AND created_at >= ? AND created_at <= ?
141
+ WHERE +trashed_at IS NULL AND +lower(project) = lower(?) AND importance >= ? AND created_at >= ? AND created_at <= ?
138
142
  AND category NOT IN (${marks(skip.length)}) ORDER BY importance DESC, created_at DESC LIMIT ?`)
139
143
  .all(project, FACTS.memoryImportance, new Date(from).toISOString(), new Date(to).toISOString(), ...skip, FACTS.memories), []);
140
144
  return rows.map((row) => ({ id: String(row.id), title: firstLine(row.content).replace(/^#+\s*/, ''), excerpt: String(row.content || '').replace(/^#+\s*/gm, ''), category: row.category, importance: row.importance, at: row.created_at }));
@@ -242,7 +246,7 @@ export function createGreetingSources({
242
246
  function recentProjects({ limit = 6 } = {}) {
243
247
  const categories = [...new Set([CATEGORIES.threads, ...safe(() => sessionCategories(), ['conversations'])])];
244
248
  const rows = safe(() => getDb().prepare(`SELECT lower(project) AS project, MAX(updated_at) AS at FROM memories
245
- WHERE trashed_at IS NULL AND category IN (${marks(categories.length)}) GROUP BY lower(project) ORDER BY at DESC LIMIT ?`).all(...categories, limit), []);
249
+ WHERE +trashed_at IS NULL AND category IN (${marks(categories.length)}) GROUP BY lower(project) ORDER BY at DESC LIMIT ?`).all(...categories, limit), []);
246
250
  return rows.map((row) => String(row.project || 'global')).filter(Boolean);
247
251
  }
248
252
 
@@ -11,25 +11,24 @@
11
11
  // "Failed to parse item"; the session-history endpoint silently dropped such
12
12
  // transcript lines.
13
13
 
14
+ import { createLineBuffer } from './line-buffer.js';
15
+
14
16
  /**
15
17
  * Lines of a text stream (or any async iterable of string chunks), split on
16
18
  * "\n" only; a trailing "\r" is removed. The last line is yielded even without
17
19
  * a final newline.
18
20
  */
19
21
  export async function* jsonlLines(chunks) {
20
- let buffer = '';
22
+ // Each chunk is searched once and an unfinished line joined once (lib/line-buffer.js): a rollout line of several
23
+ // megabytes (an inline image) used to be searched again from its start for every chunk of it.
24
+ const buffer = createLineBuffer({ stripCr: true });
21
25
  for await (const chunk of chunks) {
22
- buffer += typeof chunk === 'string' ? chunk : String(chunk);
23
- let start = 0;
24
- let index;
25
- while ((index = buffer.indexOf('\n', start)) !== -1) {
26
- const line = buffer.slice(start, index);
27
- start = index + 1;
28
- yield line.endsWith('\r') ? line.slice(0, -1) : line;
29
- }
30
- buffer = buffer.slice(start);
26
+ for (const line of buffer.push(typeof chunk === 'string' ? chunk : String(chunk))) yield line;
31
27
  }
32
- if (buffer) yield buffer.endsWith('\r') ? buffer.slice(0, -1) : buffer;
28
+ // The last line, without a newline: yielded whenever something is left (a lone "\r" yields '', as it always did).
29
+ const left = buffer.pendingChars() > 0;
30
+ const rest = buffer.end();
31
+ if (left) yield rest;
33
32
  }
34
33
 
35
34
  function isRecord(text) {
@@ -0,0 +1,88 @@
1
+ // ── Lines out of a stream of chunks, in time linear in what arrives ──
2
+ //
3
+ // A child's stdout (a Codex app-server's JSON-RPC, a CLI's stream of JSON events) was read with
4
+ // buffer += chunk; lines = buffer.split('\n'); buffer = lines.pop();
5
+ // which looks at the whole unfinished line again for every chunk: a reply of one 171 MB line arrives in some 2,600
6
+ // chunks of 64 KiB, and each of them copied and searched everything before it (quadratic: about 220 GB moved for
7
+ // that one line). Here a chunk is searched once, from its own start, and the pieces of an unfinished line are kept
8
+ // as they came and joined once, when its newline arrives.
9
+ //
10
+ // Lines end at "\n" only. A "\r" before it stays in the line (callers trim it, or pass `stripCr`), also when a pipe
11
+ // cut the "\r\n" in two. Nothing here depends on the platform: chunk sizes differ by OS, the result does not.
12
+ import { constants } from 'node:buffer';
13
+
14
+ /** The longest line kept: V8 cannot make a longer string (about 512 MB), and joining one would throw. */
15
+ export const MAX_LINE_CHARS = constants.MAX_STRING_LENGTH - 1024;
16
+
17
+ /**
18
+ * @param {{ stripCr?: boolean, maxLineChars?: number, onOverflow?: (chars: number) => void }} [options]
19
+ * `stripCr`: remove one "\r" at the end of each line. `maxLineChars`: a line longer than this is dropped whole
20
+ * (`onOverflow` is told once per dropped line, with how many characters had arrived by then).
21
+ * @returns {{ push(chunk: string): string[], end(): string, clear(): void, pendingChars(): number }}
22
+ * push(): the lines `chunk` completed, in order (often none). end(): the unfinished last line ('' when there is
23
+ * none), and the buffer is empty afterwards. clear(): drop what is held (the child was replaced).
24
+ */
25
+ export function createLineBuffer({ stripCr = false, maxLineChars = MAX_LINE_CHARS, onOverflow = null } = {}) {
26
+ let parts = []; // the pieces of the unfinished line, as they arrived
27
+ let held = 0; // their length together
28
+ let dropping = false; // the unfinished line is over the limit: nothing of it is kept until its newline
29
+
30
+ const finish = (line) => (stripCr && line.endsWith('\r') ? line.slice(0, -1) : line);
31
+
32
+ /** Keep `piece` of the unfinished line, or start dropping the line when it grows past the limit. */
33
+ function hold(piece) {
34
+ if (dropping || !piece) return;
35
+ if (held + piece.length > maxLineChars) {
36
+ const chars = held + piece.length;
37
+ parts = [];
38
+ held = 0;
39
+ dropping = true;
40
+ if (typeof onOverflow === 'function') { try { onOverflow(chars); } catch { /* the caller's own failure */ } }
41
+ return;
42
+ }
43
+ parts.push(piece);
44
+ held += piece.length;
45
+ }
46
+
47
+ function push(chunk) {
48
+ const text = typeof chunk === 'string' ? chunk : String(chunk ?? '');
49
+ const lines = [];
50
+ let start = 0;
51
+ for (let at = text.indexOf('\n'); at !== -1; at = text.indexOf('\n', start)) {
52
+ const piece = text.slice(start, at);
53
+ start = at + 1;
54
+ if (dropping) { dropping = false; continue; } // the end of a line that was too long
55
+ if (held + piece.length > maxLineChars) {
56
+ if (typeof onOverflow === 'function') { try { onOverflow(held + piece.length); } catch { /* the caller's own failure */ } }
57
+ parts = [];
58
+ held = 0;
59
+ continue;
60
+ }
61
+ if (parts.length) {
62
+ parts.push(piece);
63
+ lines.push(finish(parts.join('')));
64
+ parts = [];
65
+ held = 0;
66
+ } else {
67
+ lines.push(finish(piece));
68
+ }
69
+ }
70
+ if (start < text.length) hold(start === 0 ? text : text.slice(start));
71
+ return lines;
72
+ }
73
+
74
+ function end() {
75
+ const rest = dropping ? '' : parts.join('');
76
+ parts = [];
77
+ held = 0;
78
+ dropping = false;
79
+ return finish(rest);
80
+ }
81
+
82
+ return {
83
+ push,
84
+ end,
85
+ clear() { parts = []; held = 0; dropping = false; },
86
+ pendingChars: () => held,
87
+ };
88
+ }
@@ -63,6 +63,14 @@ export function timeBlockingWork(label, fn, options) {
63
63
  try { return fn(); } finally { end(); }
64
64
  }
65
65
 
66
+ /**
67
+ * `label` with the size of what is being worked on, once that is a megabyte or more (`codex:stdout-line 171.0 MB`):
68
+ * a stall under such a label says at once that one large payload held the thread. Smaller work keeps the bare label.
69
+ */
70
+ export function sizedLabel(label, chars) {
71
+ return chars >= 1048576 ? `${label} ${(chars / 1048576).toFixed(1)} MB` : label;
72
+ }
73
+
66
74
  function inFlight(now) {
67
75
  const list = [];
68
76
  for (const { label, at } of open.values()) { list.push(`${label} ${((now - at) / 1000).toFixed(1)} s`); if (list.length === 3) break; }
@@ -132,6 +140,7 @@ export function startLoopStallMonitor({
132
140
  thresholdMs = 500, intervalMs = 100, resolution = 20, rateLimitMs = 30_000, longMs = 3000,
133
141
  unattributedMs = 10_000,
134
142
  log = console.warn,
143
+ detail = null,
135
144
  } = {}) {
136
145
  if (activeMonitor) return activeMonitor;
137
146
  const delay = monitorEventLoopDelay({ resolution });
@@ -181,7 +190,12 @@ export function startLoopStallMonitor({
181
190
  ? `; ${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`
182
191
  : '';
183
192
  held = { count: 0, ms: 0, worst: 0 };
184
- log(`[loop-stall] ${new Date().toISOString()} blocked ${Math.round(blocked)} ms (last: ${activity}${inFlight(now)}${work})${more}`);
193
+ // A long stall also says what the host adds (`detail`; the server: how many secrets its scrubbers look for).
194
+ let extra = '';
195
+ if (blocked >= longMs && typeof detail === 'function') {
196
+ try { const text = detail(); if (text) extra = `; ${text}`; } catch { /* the line goes out without it */ }
197
+ }
198
+ log(`[loop-stall] ${new Date().toISOString()} blocked ${Math.round(blocked)} ms (last: ${activity}${inFlight(now)}${work}${extra})${more}`);
185
199
  }
186
200
 
187
201
  const timer = setInterval(() => {