synabun 2.4.4 → 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 (129) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +5 -4
  4. package/docs/whatsapp.md +19 -3
  5. package/hooks/claude-code/session-start.mjs +21 -18
  6. package/lib/claude-global-config.js +214 -0
  7. package/lib/client-config-repair.js +17 -3
  8. package/mcp-server/dist/index.d.ts.map +1 -1
  9. package/mcp-server/dist/index.js +6 -1
  10. package/mcp-server/dist/index.js.map +1 -1
  11. package/mcp-server/dist/services/neural-interface.d.ts +1 -0
  12. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  13. package/mcp-server/dist/services/neural-interface.js +1 -0
  14. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  15. package/mcp-server/dist/services/tool-catalog.js +1 -1
  16. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  17. package/mcp-server/dist/tools/agents.d.ts +18 -3
  18. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  19. package/mcp-server/dist/tools/agents.js +85 -16
  20. package/mcp-server/dist/tools/agents.js.map +1 -1
  21. package/mcp-server/dist/tools/skill-tools.d.ts +24 -5
  22. package/mcp-server/dist/tools/skill-tools.d.ts.map +1 -1
  23. package/mcp-server/dist/tools/skill-tools.js +88 -8
  24. package/mcp-server/dist/tools/skill-tools.js.map +1 -1
  25. package/mcp-server/dist/tools/tool-groups.d.ts.map +1 -1
  26. package/mcp-server/dist/tools/tool-groups.js +19 -4
  27. package/mcp-server/dist/tools/tool-groups.js.map +1 -1
  28. package/mcp-server/package-lock.json +2 -2
  29. package/mcp-server/package.json +1 -1
  30. package/mcp-server/src/index.ts +6 -1
  31. package/mcp-server/src/services/neural-interface.ts +2 -1
  32. package/mcp-server/src/services/tool-catalog.ts +1 -1
  33. package/mcp-server/src/tools/agents.ts +78 -16
  34. package/mcp-server/src/tools/skill-tools.ts +82 -9
  35. package/mcp-server/src/tools/tool-groups.ts +19 -4
  36. package/neural-interface/i18n/en.json +484 -19
  37. package/neural-interface/i18n/pt-BR.json +484 -19
  38. package/neural-interface/lib/agents-studio-api.js +7 -2
  39. package/neural-interface/lib/antigravity/home.js +43 -8
  40. package/neural-interface/lib/antigravity/panel-bridge.js +7 -3
  41. package/neural-interface/lib/antigravity/tool-call.js +14 -0
  42. package/neural-interface/lib/assistant-brains/antigravity.js +4 -2
  43. package/neural-interface/lib/assistant-dispatch.js +15 -1
  44. package/neural-interface/lib/assistant-persona.js +8 -3
  45. package/neural-interface/lib/assistant-route-gate.js +11 -2
  46. package/neural-interface/lib/assistant-runtime.js +95 -13
  47. package/neural-interface/lib/assistant-spilled-output.js +53 -0
  48. package/neural-interface/lib/assistant-user-context.js +7 -3
  49. package/neural-interface/lib/browser-default.js +22 -2
  50. package/neural-interface/lib/browser-extension-bridge.js +50 -3
  51. package/neural-interface/lib/browser-extension-pin.json +7 -7
  52. package/neural-interface/lib/browser-extension-protocol.js +30 -1
  53. package/neural-interface/lib/browser-extension-setup.js +204 -36
  54. package/neural-interface/lib/claude-agent-bridge.js +13 -2
  55. package/neural-interface/lib/codex-thread-history.js +144 -7
  56. package/neural-interface/lib/codex-worker-app-server.js +84 -30
  57. package/neural-interface/lib/db.js +26 -0
  58. package/neural-interface/lib/greeting/sources.js +7 -3
  59. package/neural-interface/lib/jsonl-lines.js +10 -11
  60. package/neural-interface/lib/line-buffer.js +88 -0
  61. package/neural-interface/lib/loop-stall.js +15 -1
  62. package/neural-interface/lib/memory-list-read.js +105 -0
  63. package/neural-interface/lib/memory-timers.js +4 -1
  64. package/neural-interface/lib/native-loop-runtime.js +7 -3
  65. package/neural-interface/lib/provider-panel-api-key-auth.js +33 -6
  66. package/neural-interface/lib/remote-policy.js +24 -7
  67. package/neural-interface/lib/skills/api-v2.js +18 -3
  68. package/neural-interface/lib/skills/bundle.js +2 -2
  69. package/neural-interface/lib/skills/deploy.js +169 -34
  70. package/neural-interface/lib/skills/digest.js +57 -3
  71. package/neural-interface/lib/skills/health.js +55 -1
  72. package/neural-interface/lib/skills/known-bridge-digests.json +12 -0
  73. package/neural-interface/lib/skills/runtime-checks.js +7 -4
  74. package/neural-interface/lib/skills/scan-shell.js +56 -7
  75. package/neural-interface/lib/skills/scan.js +13 -12
  76. package/neural-interface/lib/skills/service.js +7 -2
  77. package/neural-interface/lib/skills/telemetry.js +2 -2
  78. package/neural-interface/lib/teams/README.md +34 -6
  79. package/neural-interface/lib/teams/api.js +94 -10
  80. package/neural-interface/lib/teams/index.js +4 -0
  81. package/neural-interface/lib/teams/landing.js +195 -75
  82. package/neural-interface/lib/teams/recovery.js +68 -0
  83. package/neural-interface/lib/teams/scheduler.js +380 -61
  84. package/neural-interface/lib/teams/worktrees.js +123 -30
  85. package/neural-interface/lib/terminal-token-redaction.js +228 -58
  86. package/neural-interface/lib/terminal-tokens.js +18 -0
  87. package/neural-interface/lib/whatsapp/brain.js +21 -0
  88. package/neural-interface/lib/whatsapp/bridge.js +40 -4
  89. package/neural-interface/package-lock.json +2 -2
  90. package/neural-interface/package.json +1 -1
  91. package/neural-interface/public/extension-setup.html +6 -2
  92. package/neural-interface/public/index.html +117 -37
  93. package/neural-interface/public/shared/agents/studio/ax-api.js +27 -0
  94. package/neural-interface/public/shared/agents/studio/ax-create-view.js +1 -1
  95. package/neural-interface/public/shared/agents/studio/ax-icons.js +1 -0
  96. package/neural-interface/public/shared/agents/studio/ax-library-view.js +3 -2
  97. package/neural-interface/public/shared/agents/studio/ax-main.js +127 -41
  98. package/neural-interface/public/shared/agents/studio/ax-review-view.js +3 -2
  99. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +436 -33
  100. package/neural-interface/public/shared/agents/studio/ax-teams.js +357 -10
  101. package/neural-interface/public/shared/agents/studio/ax-ui.js +31 -0
  102. package/neural-interface/public/shared/agents/studio/ax-views.js +67 -69
  103. package/neural-interface/public/shared/agents/studio/ax-work-answer.js +86 -0
  104. package/neural-interface/public/shared/agents/studio/ax-work-view.js +305 -0
  105. package/neural-interface/public/shared/agents/studio/ax-work.css +74 -0
  106. package/neural-interface/public/shared/agents/studio/ax-work.js +300 -0
  107. package/neural-interface/public/shared/browser-extension-updates.js +3 -1
  108. package/neural-interface/public/shared/cdx/cdx-deferred.js +90 -0
  109. package/neural-interface/public/shared/cdx/cdx-render.js +18 -7
  110. package/neural-interface/public/shared/cdx/cdx-tabs.js +2 -1
  111. package/neural-interface/public/shared/extension-setup/es-page.js +23 -4
  112. package/neural-interface/public/shared/extension-setup/es-view.js +51 -11
  113. package/neural-interface/public/shared/extension-update-view.js +1 -1
  114. package/neural-interface/public/shared/loading-diagnostic-entry.js +16 -1
  115. package/neural-interface/public/shared/settings/settings-ai-browser.js +23 -3
  116. package/neural-interface/public/shared/settings/settings-browser-extension.js +575 -197
  117. package/neural-interface/public/shared/settings/settings-extension-diagrams.js +116 -0
  118. package/neural-interface/public/shared/settings/settings-extension-guide.js +222 -0
  119. package/neural-interface/public/shared/settings/settings-ia.js +2 -2
  120. package/neural-interface/public/shared/settings/settings-shell.js +5 -0
  121. package/neural-interface/public/shared/skills/studio/sx-operations-view.js +5 -0
  122. package/neural-interface/public/shared/skills/studio/sx-plan.js +42 -3
  123. package/neural-interface/public/shared/skills/studio/sx-publish-view.js +20 -4
  124. package/neural-interface/public/shared/styles.css +196 -13
  125. package/neural-interface/public/shared/ui-settings.js +48 -11
  126. package/neural-interface/server.js +336 -253
  127. package/npm-shrinkwrap.json +2 -2
  128. package/package.json +2 -1
  129. package/skills/skill-forge/SKILL.md +7 -3
@@ -51,6 +51,7 @@ import { createProfileFailureStore, namesFailedProfile, profileSwitchBarError, p
51
51
  import { scheduleReview, templateReview, sameDigest, scheduleMarked, templateMarked, clearScheduleMark, clearTemplateMark, markRecordsUnreviewed, REVIEW_CHANGED, UNREVIEWED_SOURCES } from './lib/automation-approval.js';
52
52
  import { AGENT_PROFILES_KEY, PROFILE_NOT_ALLOWED, normalizeAgentProfiles, agentProfileAllowed, withAgentProfile, profileNotAllowedError, pinUseRefusal, scheduleProfileAuthority, scheduleProfileRefusalText, describeProfile, profileKindLabel } from './lib/morelogin-agent-profiles.js';
53
53
  import { createTerminalTokenRegistry, TERMINAL_TOKEN_ENV, TERMINAL_TOKEN_HEADER, BRAIN_CREDENTIAL_HEADER, redactTerminalSecrets, logIdOf } from './lib/terminal-tokens.js';
54
+ import { knownSecretCount } from './lib/terminal-token-redaction.js';
54
55
  import { decideFailedTabRecovery } from './lib/browser-wedge-retire.js';
55
56
  import { createSocialWritePacer, socialPaceAccountKey, socialPaceRequest, socialPacingBlock, SOCIAL_PACE_LIMITS, SOCIAL_WRITE_GAPS } from './lib/social-write-pacing.js';
56
57
  import { describeLocatorMatches, healLocatorByText, validNthMatch, captureTargetIdentity, matchesTargetIdentity } from './lib/browser-targets.js';
@@ -143,6 +144,7 @@ import { createRequire } from 'module';
143
144
  import { Readable } from 'stream';
144
145
  import { createConnection as netConnect } from 'net';
145
146
  import { DatabaseSync } from 'node:sqlite';
147
+ import { StringDecoder } from 'node:string_decoder';
146
148
  import { WebSocketServer } from 'ws';
147
149
  import { Agent as UndiciAgent, fetch as undiciFetch } from 'undici';
148
150
  import os from 'node:os';
@@ -366,7 +368,7 @@ import {
366
368
  retireCodexChildProcess,
367
369
  shouldReleaseCodexWriter,
368
370
  } from './lib/codex-writer-lifecycle.js';
369
- import { hydrateCodexThreadHistory, revertCodexThreadHistory } from './lib/codex-thread-history.js';
371
+ import { deferCodexInlineImage, hydrateCodexThreadHistory, readCodexThreadItem, revertCodexThreadHistory } from './lib/codex-thread-history.js';
370
372
  import {
371
373
  buildCodexConfigEdits,
372
374
  buildCodexMcpServerApprovalEdit,
@@ -468,6 +470,7 @@ import { checkRuntimeDependencies, fallbackInstallArgs, fallbackInstallEnv, find
468
470
  import { buildMcpServerSafelyAsync, mcpBuildNeeded, mcpDistWhole } from '../lib/mcp-build.js';
469
471
  import { STOP_MARKER_NAME, STOP_TOKEN_ENV, stopAnnouncement, writeStopMarker } from '../lib/server-exit.js';
470
472
  import { redactDeep, redactSecrets } from '../lib/log-redact.js';
473
+ import { claudeGlobalConfigRefusal, updateClaudeGlobalConfig } from '../lib/claude-global-config.js';
471
474
  import { applyPackagedChildPath, durableEntry, mcpStdioCommand, npmGlobalBinFor, packagedNpmPrefix, packagedPathFolders, packagedRuntime } from '../lib/packaged-runtime.js';
472
475
  import { dataHomeId } from '../lib/desktop-app.js';
473
476
  import { pruneExternalTools } from '../lib/external-tools.js';
@@ -478,7 +481,7 @@ import { parseMemoryPage, pageEtagPart, describePage, isLastPage } from './lib/m
478
481
  import {
479
482
  getDb, closeDb, getDbPath, getEmbedding, getEmbeddingBatch, getEmbeddingDims, warmupEmbeddings,
480
483
  encodeVector, decodeVector, cosineSimilarity,
481
- searchMemories as dbSearchMemories, getAllMemories, getMemoriesPage, getAllMemoriesWithVectors,
484
+ searchMemories as dbSearchMemories, getAllMemories, readAllMemories, readMemoriesPage, getAllMemoriesWithVectors,
482
485
  getMemoryById, getMemoryWithVector, updateMemoryPayload,
483
486
  softDeleteMemory, hardDeleteMemory, restoreMemory as dbRestoreMemory,
484
487
  getTrashedMemories, purgeTrash, countMemories, getMemoryStats,
@@ -491,7 +494,8 @@ import {
491
494
  getFbActionBudget, getFbEngagementTier, FB_ACTION_TYPES,
492
495
  } from './lib/db.js';
493
496
  import { drainSessionJobs, runSessionJob, setSessionJobStoreGate } from './lib/session-cache-worker.js';
494
- import { beginActivity, instrumentSqlite, markActivity, startLoopStallMonitor } from './lib/loop-stall.js';
497
+ import { beginActivity, beginBlockingWork, instrumentSqlite, markActivity, sizedLabel, startLoopStallMonitor, timeBlockingWork } from './lib/loop-stall.js';
498
+ import { createLineBuffer } from './lib/line-buffer.js';
495
499
  import { createHealthCount } from './lib/health-count.js';
496
500
  import { createRecallImpact } from './lib/recall-impact.js';
497
501
  import { installMemoryStoreGate, isMemoryStoreRefusal, noteMemoryStoreRefusal } from './lib/memory-store-gate.js';
@@ -500,7 +504,9 @@ import { installMemoryStoreGate, isMemoryStoreRefusal, noteMemoryStoreRefusal }
500
504
  const memoryStoreGate = installMemoryStoreGate();
501
505
  setSessionJobStoreGate(() => (memoryStoreGate.open() ? null : memoryStoreGate.forJobs()));
502
506
 
503
- startLoopStallMonitor();
507
+ // A stall of 3 s or more also says how many secrets the scrubbers look for: their cost once grew with that number
508
+ // (lib/terminal-token-redaction.js), and a count that only grows is a leak worth seeing in the same line.
509
+ startLoopStallMonitor({ detail: () => `known secrets ${knownSecretCount()}` });
504
510
  // A stall line names the slowest synchronous SQLite statement it held (off: SYNABUN_LOOP_STALL_SQL=off).
505
511
  instrumentSqlite();
506
512
  import {
@@ -1141,10 +1147,20 @@ app.get(['/', '/index.html', '/index2d.html'], (req, res, next) => {
1141
1147
  if (target !== req.originalUrl) return res.redirect(target);
1142
1148
  next();
1143
1149
  });
1150
+ // Scripts and styles are kept by the browser and asked about on every load (`no-cache` + a validator). A page is
1151
+ // never kept (`no-store`, and always answered whole, never 304: a 304 would keep the browser's copy). A kept page is
1152
+ // what a browser shows for a history-style load while the server is away: on 2026-11-28 the owner's Safari web app
1153
+ // reopened a copy of index.html from before a fix, ran it without its server, and the module loads that failed there
1154
+ // stayed failed in WebKit's memory for the pages loaded after it. Without a copy that load reaches the service
1155
+ // worker's offline page, which has the Start Server button.
1144
1156
  app.use(express.static(join(__dirname, 'public'), {
1145
1157
  etag: true,
1146
1158
  lastModified: true,
1147
- setHeaders: (res) => res.setHeader('Cache-Control', 'no-cache'),
1159
+ setHeaders: (res, path) => {
1160
+ if (!/\.html?$/i.test(path)) { res.setHeader('Cache-Control', 'no-cache'); return; }
1161
+ res.setHeader('Cache-Control', 'no-store');
1162
+ if (res.req) { delete res.req.headers['if-none-match']; delete res.req.headers['if-modified-since']; }
1163
+ },
1148
1164
  }));
1149
1165
 
1150
1166
  // --- Helpers ---
@@ -1527,10 +1543,10 @@ app.get('/api/memories', async (req, res) => {
1527
1543
  // so before a row is read (lib/memory-list-stamp.js). 32 MB were read, built and serialised on every
1528
1544
  // load only to find out, from the finished body, that nothing had changed.
1529
1545
  let listVersion = null;
1546
+ let listStamp = null;
1530
1547
  if (!includeLinks) {
1531
1548
  const ocBridgeNow = loadBridgeConfig('openclaw');
1532
1549
  if (_openclawNodes !== _openclawNodesSeen) { _openclawNodesSeen = _openclawNodes; _openclawNodesRev += 1; }
1533
- let listStamp = null;
1534
1550
  try { listStamp = memoryListStamp(getDb()); } catch { /* no stamp: the full answer, as before */ }
1535
1551
  const listParts = [
1536
1552
  listStamp, slim ? 'graph' : 'full', SLIM_CONTENT_CHARS,
@@ -1548,9 +1564,11 @@ app.get('/api/memories', async (req, res) => {
1548
1564
 
1549
1565
  const cachedLinks = includeLinks ? getValidLinkCache() : null;
1550
1566
  const needVectors = includeLinks && !cachedLinks;
1551
- // A page reads its own rows only (and how many there are); the whole list reads them all.
1552
- const pageRead = page ? getMemoriesPage(page) : null;
1553
- const allPoints = pageRead ? pageRead.rows : (needVectors ? getAllMemoriesWithVectors() : getAllMemories());
1567
+ // A page reads its own rows only (and how many there are); the whole list reads them all. Both are read off this
1568
+ // thread (lib/memory-list-read.js): on a busy store one page held it for seconds, right when the page that asked
1569
+ // also wants its modules. Only the vectors for a link computation are still read here.
1570
+ const pageRead = page ? await readMemoriesPage(page, { stamp: listStamp }) : null;
1571
+ const allPoints = pageRead ? pageRead.rows : (needVectors ? getAllMemoriesWithVectors() : await readAllMemories({ stamp: listStamp }));
1554
1572
 
1555
1573
  // Build nodes
1556
1574
  const nodes = allPoints.map(p => ({
@@ -4699,6 +4717,10 @@ function codexAccountInUse(accountId, { except = null } = {}) {
4699
4717
  return '';
4700
4718
  }
4701
4719
 
4720
+ // How a thread's history is read for a page (lib/codex-thread-history.js hydrateCodexThreadHistory): generated
4721
+ // images' inline data is left out of each item as its page arrives, and fetched when the item is opened.
4722
+ const CODEX_HISTORY_FOR_PAGE = Object.freeze({ transformItem: deferCodexInlineImage });
4723
+
4702
4724
  function handleCodexSkinWebSocket(ws) {
4703
4725
  // In API-key mode with a key SynaBun holds, the app-server starts with an ephemeral
4704
4726
  // credential store and this key is its first request over stdin (lib/codex-accounts.js).
@@ -4723,7 +4745,10 @@ CRITICAL — When you need clarification during planning:
4723
4745
  6. The sidepanel will ask the user whether to Edit plan, Compact context, or Continue with implementation.`,
4724
4746
  ];
4725
4747
  let child = null;
4726
- let childStdoutBuf = '';
4748
+ // The app-server's stdout, cut into lines in time linear in what arrives (lib/line-buffer.js).
4749
+ const childStdoutLines = createLineBuffer({
4750
+ onOverflow: (chars) => console.warn(`[codex-skin] Dropped an app-server line of over ${Math.round(chars / 1048576)} MB (longer than a string can be)`),
4751
+ });
4727
4752
  let initialized = false;
4728
4753
  let bootPromise = null;
4729
4754
  let nextRequestId = 1;
@@ -4960,7 +4985,7 @@ CRITICAL — When you need clarification during planning:
4960
4985
  try { clearTimeout(entry.timer); entry.reject(new Error('Codex account sign-in changed')); } catch {}
4961
4986
  }
4962
4987
  pending.clear();
4963
- childStdoutBuf = '';
4988
+ childStdoutLines.clear();
4964
4989
  unregisterCodexToolsRuntime();
4965
4990
  child = null;
4966
4991
  childCredential = null;
@@ -5668,13 +5693,28 @@ CRITICAL — When you need clarification during planning:
5668
5693
  const readResult = await request('thread/read', getDefaultReadParams(threadId), 15000);
5669
5694
  const thread = extractCodexThread(readResult);
5670
5695
  if (!thread) return null;
5671
- const history = await hydrateCodexThreadHistory(request, thread.id || threadId);
5696
+ // Read in pages sized by what they weigh, and a generated image's inline data is left out as each page arrives
5697
+ // (lib/codex-thread-history.js): the page asks for it when its item is opened (thread_item_payload). A thread of
5698
+ // generated images used to come back as one reply of 171 MB, parsed, redacted and sent on in one go.
5699
+ const history = await hydrateCodexThreadHistory(request, thread.id || threadId, CODEX_HISTORY_FOR_PAGE);
5672
5700
  if (history.source === 'turns-full-fallback') {
5673
5701
  console.log(`[codex-history] thread/items/list unavailable; restored full turns thread=${thread.id || threadId}`);
5674
5702
  }
5675
5703
  return { ...thread, turns: history.turns };
5676
5704
  }
5677
5705
 
5706
+ // One item of the thread this tab shows, whole: the data a history left out of it (a generated image).
5707
+ async function readThreadItemPayload(msg) {
5708
+ const threadId = String(msg.threadId || '');
5709
+ const shown = [displayedThreadId, activeThreadId].filter(Boolean).map(String);
5710
+ if (!threadId || !shown.includes(threadId)) throw new Error('This item belongs to another thread.');
5711
+ if (typeof msg.turnId !== 'string' || !msg.turnId || typeof msg.itemId !== 'string' || !msg.itemId) throw new Error('A turn and an item are required.');
5712
+ await ensureInitialized();
5713
+ const item = await readCodexThreadItem(request, threadId, msg.turnId, msg.itemId);
5714
+ if (!item) throw new Error('Codex no longer has this item.');
5715
+ return sanitizeCodexHistoryItem(item);
5716
+ }
5717
+
5678
5718
  function tryParseJson(value) {
5679
5719
  if (typeof value !== 'string') return value;
5680
5720
  const trimmed = value.trim();
@@ -6069,12 +6109,20 @@ CRITICAL — When you need clarification during planning:
6069
6109
  if (!codexTerminalToken) delete env[TERMINAL_TOKEN_ENV];
6070
6110
  delete env.FORCE_COLOR;
6071
6111
  delete env.CLICOLOR_FORCE;
6072
- const proc = spawn(shellCommand(codexBin, useShell, { isFile: existsSync }), args, {
6073
- cwd: PACKAGE_ROOT,
6074
- env,
6075
- stdio: ['pipe', 'pipe', 'pipe'],
6076
- shell: useShell,
6077
- });
6112
+ let proc;
6113
+ try {
6114
+ proc = spawn(shellCommand(codexBin, useShell, { isFile: existsSync }), args, {
6115
+ cwd: PACKAGE_ROOT,
6116
+ env,
6117
+ stdio: ['pipe', 'pipe', 'pipe'],
6118
+ shell: useShell,
6119
+ });
6120
+ } catch (error) {
6121
+ // No process, so no 'close' that would end its proof: the token minted for it above is revoked here (the
6122
+ // scrubbers forget it), or every failed start would leave one known secret behind for as long as the server runs.
6123
+ _terminalTokens.revoke(codexMcpRuntimeId);
6124
+ throw error;
6125
+ }
6078
6126
  child = proc;
6079
6127
  childApiKeyLogin = launch.apiKey || null;
6080
6128
  childUsesHeldKey = !!launch.apiKey;
@@ -6086,197 +6134,201 @@ CRITICAL — When you need clarification during planning:
6086
6134
  registerCodexToolsRuntime();
6087
6135
  console.log(`[codex-skin] Spawned app-server pid ${proc.pid || '?'} account=${activeAccountId} mode=${launch.mode || 'none'} windowsSandbox=${launch.windowsSandbox} runtime=${codexMcpRuntimeId} CODEX_HOME=${activeCodexHome}`);
6088
6136
  proc.stdout.setEncoding('utf-8');
6089
- proc.stdout.on('data', (chunk) => {
6090
- if (child !== proc) return; // stale process from a previous account
6091
- childStdoutBuf += chunk;
6092
- const lines = childStdoutBuf.split('\n');
6093
- childStdoutBuf = lines.pop() || '';
6094
- for (const rawLine of lines) {
6095
- const line = rawLine.trim();
6096
- if (!line) continue;
6097
- let msg;
6098
- try {
6099
- msg = redactProviderSecrets(JSON.parse(line));
6100
- } catch (err) {
6101
- console.warn('[codex-skin] Invalid JSON from app-server');
6102
- continue;
6103
- }
6137
+ // One line of the app-server's stdout: a JSON-RPC reply, request or notification. Parsed, redacted and handed
6138
+ // on here, on the server's own thread: timed by name where it is called (below), so a stall names it.
6139
+ const handleStdoutLine = (line) => {
6140
+ let msg;
6141
+ try {
6142
+ msg = redactProviderSecrets(JSON.parse(line));
6143
+ } catch (err) {
6144
+ console.warn('[codex-skin] Invalid JSON from app-server');
6145
+ return;
6146
+ }
6104
6147
 
6105
- if (msg.id !== undefined && !msg.method) {
6106
- const entry = clearPendingRequest(msg.id);
6107
- if (!entry) continue;
6108
- if (msg.error) {
6109
- const err = new Error(msg.error.message || `Codex request ${msg.id} failed`);
6110
- err.code = msg.error.code;
6111
- err.data = msg.error.data;
6112
- const unsupported = isCodexUnsupportedMethod(err);
6113
- const capabilityChanged = codexCapabilities.observe(entry.method, err);
6114
- if (capabilityChanged && unsupported) {
6115
- sendToClient({ type: 'capabilities', ...codexCapabilitySnapshot() });
6116
- }
6117
- entry.reject(err);
6118
- } else {
6119
- codexCapabilities.observe(entry.method);
6120
- entry.resolve(msg.result);
6148
+ if (msg.id !== undefined && !msg.method) {
6149
+ const entry = clearPendingRequest(msg.id);
6150
+ if (!entry) return;
6151
+ if (msg.error) {
6152
+ const err = new Error(msg.error.message || `Codex request ${msg.id} failed`);
6153
+ err.code = msg.error.code;
6154
+ err.data = msg.error.data;
6155
+ const unsupported = isCodexUnsupportedMethod(err);
6156
+ const capabilityChanged = codexCapabilities.observe(entry.method, err);
6157
+ if (capabilityChanged && unsupported) {
6158
+ sendToClient({ type: 'capabilities', ...codexCapabilitySnapshot() });
6121
6159
  }
6122
- continue;
6160
+ entry.reject(err);
6161
+ } else {
6162
+ codexCapabilities.observe(entry.method);
6163
+ entry.resolve(msg.result);
6123
6164
  }
6165
+ return;
6166
+ }
6124
6167
 
6125
- if (msg.id !== undefined && msg.method) {
6126
- const requestId = msg.id;
6127
- const automatic = automaticCodexServerReply(msg.method, msg.params, Date.now(), { userVerification: supportsUserVerification && codexRole !== 'assistant' && ws.readyState === 1 });
6128
- if (automatic) {
6129
- try { writeRpc({ jsonrpc: '2.0', id: requestId, ...automatic }); } catch {}
6130
- if (automatic.error) sendToClient({
6131
- type: 'server_request', requestId, method: msg.method, params: codexVerificationCardParams(msg.params || {}), resolved: true,
6132
- threadId: msg.params?.threadId || activeThreadId || null,
6133
- turnId: msg.params?.turnId || activeTurnId || null,
6134
- });
6135
- continue;
6136
- }
6168
+ if (msg.id !== undefined && msg.method) {
6169
+ const requestId = msg.id;
6170
+ const automatic = automaticCodexServerReply(msg.method, msg.params, Date.now(), { userVerification: supportsUserVerification && codexRole !== 'assistant' && ws.readyState === 1 });
6171
+ if (automatic) {
6172
+ try { writeRpc({ jsonrpc: '2.0', id: requestId, ...automatic }); } catch {}
6173
+ if (automatic.error) sendToClient({
6174
+ type: 'server_request', requestId, method: msg.method, params: codexVerificationCardParams(msg.params || {}), resolved: true,
6175
+ threadId: msg.params?.threadId || activeThreadId || null,
6176
+ turnId: msg.params?.turnId || activeTurnId || null,
6177
+ });
6178
+ return;
6179
+ }
6137
6180
 
6138
- // Auto-accept MCP tool approvals under this turn's mode, independently
6139
- // of Claude's settings. Native Codex can omit tool_name altogether.
6140
- // Assistant requests always reach the brain: it applies the current
6141
- // mode and the plan/read-only policy before answering automatically.
6142
- if (msg.method === 'mcpServer/elicitation/request'
6143
- && codexRole !== 'assistant'
6144
- && shouldAutoAcceptCodexMcpToolApproval(msg.params, { autoAccept: activeTurnAutoAccept })
6145
- && serverRequestThreadIsOwned(msg.params?.threadId || activeThreadId)) {
6146
- try { writeRpc({ jsonrpc: '2.0', id: requestId, result: { action: 'accept', content: {}, _meta: {} } }); } catch {}
6147
- continue;
6148
- }
6181
+ // Auto-accept MCP tool approvals under this turn's mode, independently
6182
+ // of Claude's settings. Native Codex can omit tool_name altogether.
6183
+ // Assistant requests always reach the brain: it applies the current
6184
+ // mode and the plan/read-only policy before answering automatically.
6185
+ if (msg.method === 'mcpServer/elicitation/request'
6186
+ && codexRole !== 'assistant'
6187
+ && shouldAutoAcceptCodexMcpToolApproval(msg.params, { autoAccept: activeTurnAutoAccept })
6188
+ && serverRequestThreadIsOwned(msg.params?.threadId || activeThreadId)) {
6189
+ try { writeRpc({ jsonrpc: '2.0', id: requestId, result: { action: 'accept', content: {}, _meta: {} } }); } catch {}
6190
+ return;
6191
+ }
6149
6192
 
6150
- const requestParams = msg.params || {};
6151
- const requestInfo = {
6152
- // The JSON-RPC id exactly as the app-server sent it (a number): the
6153
- // reply must carry the same value, and clients may echo it as a string.
6154
- rpcId: requestId,
6155
- method: msg.method,
6156
- params: codexVerificationCardParams(requestParams),
6157
- threadId: requestParams.threadId || activeThreadId || null,
6158
- turnId: requestParams.turnId || activeTurnId || null,
6159
- toolCallId: requestParams.toolCallId || requestParams.callId || requestParams.itemId || null,
6160
- };
6161
- if (!serverRequestThreadIsOwned(requestInfo.threadId)) {
6162
- recordCodexIsolationDecision('foreign_server_request');
6163
- try {
6164
- writeRpc({
6165
- jsonrpc: '2.0',
6166
- id: requestId,
6167
- error: { code: -32001, message: 'Request does not belong to this Codex sidepanel thread.' },
6168
- });
6169
- } catch {}
6170
- continue;
6171
- }
6172
- const correlation = requestCorrelation(requestId, requestInfo);
6173
- const registered = runCodexJournalOperation('register', correlation, () => (
6174
- codexRequestJournal.register(correlation, { method: msg.method })
6175
- ));
6176
- if (!registered.ok) {
6177
- const code = registered.error.code;
6178
- const message = code === 'ENOSPC'
6179
- ? 'SynaBun cannot persist this Codex request because the disk is full. Free disk space and retry.'
6180
- : 'SynaBun cannot persist this Codex request. Resolve the storage error and retry.';
6181
- sendRpcError(requestId, message, -32070, {
6182
- code,
6183
- retryable: true,
6193
+ const requestParams = msg.params || {};
6194
+ const requestInfo = {
6195
+ // The JSON-RPC id exactly as the app-server sent it (a number): the
6196
+ // reply must carry the same value, and clients may echo it as a string.
6197
+ rpcId: requestId,
6198
+ method: msg.method,
6199
+ params: codexVerificationCardParams(requestParams),
6200
+ threadId: requestParams.threadId || activeThreadId || null,
6201
+ turnId: requestParams.turnId || activeTurnId || null,
6202
+ toolCallId: requestParams.toolCallId || requestParams.callId || requestParams.itemId || null,
6203
+ };
6204
+ if (!serverRequestThreadIsOwned(requestInfo.threadId)) {
6205
+ recordCodexIsolationDecision('foreign_server_request');
6206
+ try {
6207
+ writeRpc({
6208
+ jsonrpc: '2.0',
6209
+ id: requestId,
6210
+ error: { code: -32001, message: 'Request does not belong to this Codex sidepanel thread.' },
6184
6211
  });
6185
- continue;
6186
- }
6187
- if (requestParams.mode === 'openai/userVerification') requestInfo.verification = new CodexVerificationOperation();
6188
- pendingServerRequests.set(String(requestId), requestInfo);
6189
- logRequestLifecycle('render', correlation, {
6190
- method: msg.method,
6191
- });
6192
- sendToClient({
6193
- type: 'server_request',
6194
- requestId,
6195
- method: msg.method,
6196
- params: codexVerificationCardParams(requestParams),
6197
- threadId: requestParams.threadId || activeThreadId || null,
6198
- turnId: requestParams.turnId || activeTurnId || null,
6212
+ } catch {}
6213
+ return;
6214
+ }
6215
+ const correlation = requestCorrelation(requestId, requestInfo);
6216
+ const registered = runCodexJournalOperation('register', correlation, () => (
6217
+ codexRequestJournal.register(correlation, { method: msg.method })
6218
+ ));
6219
+ if (!registered.ok) {
6220
+ const code = registered.error.code;
6221
+ const message = code === 'ENOSPC'
6222
+ ? 'SynaBun cannot persist this Codex request because the disk is full. Free disk space and retry.'
6223
+ : 'SynaBun cannot persist this Codex request. Resolve the storage error and retry.';
6224
+ sendRpcError(requestId, message, -32070, {
6225
+ code,
6226
+ retryable: true,
6199
6227
  });
6200
- continue;
6228
+ return;
6201
6229
  }
6230
+ if (requestParams.mode === 'openai/userVerification') requestInfo.verification = new CodexVerificationOperation();
6231
+ pendingServerRequests.set(String(requestId), requestInfo);
6232
+ logRequestLifecycle('render', correlation, {
6233
+ method: msg.method,
6234
+ });
6235
+ sendToClient({
6236
+ type: 'server_request',
6237
+ requestId,
6238
+ method: msg.method,
6239
+ params: codexVerificationCardParams(requestParams),
6240
+ threadId: requestParams.threadId || activeThreadId || null,
6241
+ turnId: requestParams.turnId || activeTurnId || null,
6242
+ });
6243
+ return;
6244
+ }
6202
6245
 
6203
- if (msg.method) {
6204
- const method = msg.method;
6205
- const params = msg.params || {};
6206
- if (method === 'account/rateLimits/updated') _assistantAccountUsage?.note('codex', activeAccountId, params);
6207
- if (method === 'account/login/completed') void panelAuth.complete(params);
6208
- if (method === 'account/updated' && params.authMode === null && !panelAuth.active()) panelAuth.reset();
6209
- const scopedThreadId = notificationThreadId(method, params);
6210
- const scopedTurnId = notificationTurnId(method, params);
6211
- const expectedThreadId = displayedThreadId;
6212
- const expectedTurnId = activeTurnId;
6213
- rememberCodexNotificationOwnership(params, scopedThreadId, scopedTurnId);
6214
- const rejectionReason = codexNotificationRejectionReason(
6215
- method,
6216
- scopedThreadId,
6217
- scopedTurnId,
6218
- expectedThreadId,
6219
- expectedTurnId,
6220
- );
6221
- if (method === 'thread/started' && params.thread?.id) {
6222
- rememberThreadSubscription(params.thread);
6223
- } else if (method === 'turn/started' && params.turn?.id
6224
- && (!scopedThreadId || !activeThreadId || scopedThreadId === String(activeThreadId))) {
6225
- activeTurnId = params.turn.id;
6226
- } else if (method === 'turn/completed'
6227
- && (!scopedThreadId || !activeThreadId || scopedThreadId === String(activeThreadId))
6228
- && (!activeTurnId || !scopedTurnId || scopedTurnId === String(activeTurnId))) {
6229
- finishPendingServerRequests(params.turn?.error ? 'turn_canceled' : 'dismissed', params.turn?.error?.message || '');
6246
+ if (msg.method) {
6247
+ const method = msg.method;
6248
+ const params = msg.params || {};
6249
+ if (method === 'account/rateLimits/updated') _assistantAccountUsage?.note('codex', activeAccountId, params);
6250
+ if (method === 'account/login/completed') void panelAuth.complete(params);
6251
+ if (method === 'account/updated' && params.authMode === null && !panelAuth.active()) panelAuth.reset();
6252
+ const scopedThreadId = notificationThreadId(method, params);
6253
+ const scopedTurnId = notificationTurnId(method, params);
6254
+ const expectedThreadId = displayedThreadId;
6255
+ const expectedTurnId = activeTurnId;
6256
+ rememberCodexNotificationOwnership(params, scopedThreadId, scopedTurnId);
6257
+ const rejectionReason = codexNotificationRejectionReason(
6258
+ method,
6259
+ scopedThreadId,
6260
+ scopedTurnId,
6261
+ expectedThreadId,
6262
+ expectedTurnId,
6263
+ );
6264
+ if (method === 'thread/started' && params.thread?.id) {
6265
+ rememberThreadSubscription(params.thread);
6266
+ } else if (method === 'turn/started' && params.turn?.id
6267
+ && (!scopedThreadId || !activeThreadId || scopedThreadId === String(activeThreadId))) {
6268
+ activeTurnId = params.turn.id;
6269
+ } else if (method === 'turn/completed'
6270
+ && (!scopedThreadId || !activeThreadId || scopedThreadId === String(activeThreadId))
6271
+ && (!activeTurnId || !scopedTurnId || scopedTurnId === String(activeTurnId))) {
6272
+ finishPendingServerRequests(params.turn?.error ? 'turn_canceled' : 'dismissed', params.turn?.error?.message || '');
6273
+ activeTurnId = null;
6274
+ activeTurnAutoAccept = false;
6275
+ lastTurnLocalImages = [];
6276
+ } else if (method === 'thread/closed' && params.threadId) {
6277
+ const closedThreadId = String(params.threadId);
6278
+ subscribedThreadIds.delete(closedThreadId);
6279
+ threadOwnerRoots.delete(closedThreadId);
6280
+ if (closedThreadId === String(activeThreadId || '')) {
6281
+ activeThreadId = null;
6282
+ appBoundary.invalidate();
6230
6283
  activeTurnId = null;
6231
6284
  activeTurnAutoAccept = false;
6232
- lastTurnLocalImages = [];
6233
- } else if (method === 'thread/closed' && params.threadId) {
6234
- const closedThreadId = String(params.threadId);
6235
- subscribedThreadIds.delete(closedThreadId);
6236
- threadOwnerRoots.delete(closedThreadId);
6237
- if (closedThreadId === String(activeThreadId || '')) {
6238
- activeThreadId = null;
6239
- appBoundary.invalidate();
6240
- activeTurnId = null;
6241
- activeTurnAutoAccept = false;
6242
- activeThreadRuntimeFingerprint = null;
6243
- }
6244
- if (closedThreadId === String(displayedThreadId || '')) displayedThreadId = null;
6285
+ activeThreadRuntimeFingerprint = null;
6245
6286
  }
6246
- if (method === 'serverRequest/resolved' && params.requestId != null) {
6247
- const resolvedRequest = pendingServerRequests.get(String(params.requestId));
6248
- if (resolvedRequest?.verification) {
6249
- params.status = 'cancelled';
6250
- const settled = resolvedRequest.verification.finish('cancel');
6251
- if (settled?.cancelId != null) void request('userVerification/cancel', { requestId: settled.cancelId }, 10000).catch(() => {});
6252
- }
6253
- if (resolvedRequest) {
6254
- const correlation = requestCorrelation(params.requestId, resolvedRequest);
6255
- runCodexJournalOperation('finish', correlation, () => (
6256
- codexRequestJournal.finish(
6257
- correlation,
6258
- 'dismissed',
6259
- 'Resolved without a submitted sidepanel answer',
6260
- )
6261
- ));
6262
- }
6263
- pendingServerRequests.delete(String(params.requestId));
6264
- }
6265
- const sanitizedParams = sanitizeCodexNotifyParams(method, params);
6266
- if (method === 'configWarning') {
6267
- console.warn('[codex-config] app-server warning:', JSON.stringify(sanitizedParams));
6287
+ if (closedThreadId === String(displayedThreadId || '')) displayedThreadId = null;
6288
+ }
6289
+ if (method === 'serverRequest/resolved' && params.requestId != null) {
6290
+ const resolvedRequest = pendingServerRequests.get(String(params.requestId));
6291
+ if (resolvedRequest?.verification) {
6292
+ params.status = 'cancelled';
6293
+ const settled = resolvedRequest.verification.finish('cancel');
6294
+ if (settled?.cancelId != null) void request('userVerification/cancel', { requestId: settled.cancelId }, 10000).catch(() => {});
6268
6295
  }
6269
- recordCodexIsolationDecision(rejectionReason);
6270
- if (!rejectionReason) {
6271
- sendToClient({
6272
- type: 'notify',
6273
- method,
6274
- params: sanitizedParams,
6275
- threadId: scopedThreadId,
6276
- turnId: scopedTurnId,
6277
- });
6296
+ if (resolvedRequest) {
6297
+ const correlation = requestCorrelation(params.requestId, resolvedRequest);
6298
+ runCodexJournalOperation('finish', correlation, () => (
6299
+ codexRequestJournal.finish(
6300
+ correlation,
6301
+ 'dismissed',
6302
+ 'Resolved without a submitted sidepanel answer',
6303
+ )
6304
+ ));
6278
6305
  }
6306
+ pendingServerRequests.delete(String(params.requestId));
6307
+ }
6308
+ const sanitizedParams = sanitizeCodexNotifyParams(method, params);
6309
+ if (method === 'configWarning') {
6310
+ console.warn('[codex-config] app-server warning:', JSON.stringify(sanitizedParams));
6279
6311
  }
6312
+ recordCodexIsolationDecision(rejectionReason);
6313
+ if (!rejectionReason) {
6314
+ sendToClient({
6315
+ type: 'notify',
6316
+ method,
6317
+ params: sanitizedParams,
6318
+ threadId: scopedThreadId,
6319
+ turnId: scopedTurnId,
6320
+ });
6321
+ }
6322
+ }
6323
+ };
6324
+ proc.stdout.on('data', (chunk) => {
6325
+ if (child !== proc) return; // stale process from a previous account
6326
+ // Each chunk is searched once and a long line joined once (lib/line-buffer.js): a reply of one 171 MB line
6327
+ // used to be copied and searched again from its start for every 64 KiB of it.
6328
+ for (const rawLine of childStdoutLines.push(chunk)) {
6329
+ const line = rawLine.trim();
6330
+ if (!line) continue;
6331
+ timeBlockingWork(sizedLabel('codex:stdout-line', line.length), () => handleStdoutLine(line));
6280
6332
  }
6281
6333
  });
6282
6334
  // A write that reaches an app-server as it exits fails on the pipe (EPIPE)
@@ -6312,10 +6364,8 @@ CRITICAL — When you need clarification during planning:
6312
6364
  activeTurnId = null;
6313
6365
  activeTurnAutoAccept = false;
6314
6366
  activeThreadRuntimeFingerprint = null;
6315
- if (childStdoutBuf.trim()) {
6316
- console.log('[codex-skin] trailing stdout:', childStdoutBuf.trim().slice(0, 200));
6317
- }
6318
- childStdoutBuf = '';
6367
+ const trailingStdout = childStdoutLines.end().trim();
6368
+ if (trailingStdout) console.log('[codex-skin] trailing stdout:', trailingStdout.slice(0, 200));
6319
6369
  for (const [id, entry] of pending.entries()) {
6320
6370
  clearTimeout(entry.timer);
6321
6371
  entry.reject(new Error(`Codex app-server exited before responding to request ${id}`));
@@ -6426,7 +6476,7 @@ CRITICAL — When you need clarification during planning:
6426
6476
  try { clearTimeout(entry.timer); entry.reject(new Error(reason)); } catch {}
6427
6477
  }
6428
6478
  pending.clear();
6429
- childStdoutBuf = '';
6479
+ childStdoutLines.clear();
6430
6480
  unregisterCodexToolsRuntime();
6431
6481
  child = null;
6432
6482
  if (old) {
@@ -6478,7 +6528,7 @@ CRITICAL — When you need clarification during planning:
6478
6528
  }
6479
6529
  pending.clear();
6480
6530
  pendingServerRequests.clear();
6481
- childStdoutBuf = ''; // drop any partial line from the outgoing process
6531
+ childStdoutLines.clear(); // drop any partial line from the outgoing process
6482
6532
  unregisterCodexToolsRuntime();
6483
6533
  child = null; // detach so old.on('close') sees child !== old and bails
6484
6534
  if (old) {
@@ -7204,6 +7254,15 @@ CRITICAL — When you need clarification during planning:
7204
7254
  withWriterOperation: withCodexWriterOperation,
7205
7255
  beforeRequest: beforeCodexCompatRequest, afterRequest: afterCodexCompatRequest,
7206
7256
  })) return;
7257
+ if (msg.type === 'thread_item_payload') {
7258
+ try {
7259
+ const item = await readThreadItemPayload(msg);
7260
+ sendToClient({ type: 'thread_item_payload', requestId: msg.requestId || null, threadId: String(msg.threadId), turnId: msg.turnId, itemId: msg.itemId, item });
7261
+ } catch (err) {
7262
+ sendToClient({ type: 'error', requestId: msg.requestId || null, ...classifyCodexRpcError(err), message: `Could not load this item's data. ${err.message}` });
7263
+ }
7264
+ return;
7265
+ }
7207
7266
  if (msg.type === 'thread_list') {
7208
7267
  try {
7209
7268
  const result = await listThreads({
@@ -7725,7 +7784,7 @@ CRITICAL — When you need clarification during planning:
7725
7784
  let result;
7726
7785
  try {
7727
7786
  result = await withCodexWriterOperation('thread_revert', () => revertCodexThreadHistory(request, threadId, {
7728
- numTurns: msg.numTurns ?? 1, beforeTurnId: msg.beforeTurnId,
7787
+ numTurns: msg.numTurns ?? 1, beforeTurnId: msg.beforeTurnId, history: CODEX_HISTORY_FOR_PAGE,
7729
7788
  }));
7730
7789
  } finally { appBoundary.invalidate(); }
7731
7790
  sendToClient({ type: 'thread_rolled_back', requestId: msg.requestId || null, thread: sanitizeCodexThreadForClient(result?.thread || result || null) });
@@ -8283,7 +8342,7 @@ async function queryCodexAppServerModels(codexHome = CODEX_DEFAULT_HOME, launch
8283
8342
  shell: useShell,
8284
8343
  });
8285
8344
  let nextId = 1;
8286
- let stdoutBuf = '';
8345
+ const stdoutLines = createLineBuffer();
8287
8346
  let stderrBuf = '';
8288
8347
  const pending = new Map();
8289
8348
  const cleanup = () => {
@@ -8331,10 +8390,7 @@ async function queryCodexAppServerModels(codexHome = CODEX_DEFAULT_HOME, launch
8331
8390
  }
8332
8391
  });
8333
8392
  child.stdout.on('data', (chunk) => {
8334
- stdoutBuf += chunk;
8335
- const lines = stdoutBuf.split('\n');
8336
- stdoutBuf = lines.pop() || '';
8337
- for (const rawLine of lines) {
8393
+ for (const rawLine of stdoutLines.push(chunk)) {
8338
8394
  const line = rawLine.trim();
8339
8395
  if (!line) continue;
8340
8396
  let msg;
@@ -8713,7 +8769,8 @@ function broadcastToOpencodeV2Clients(data, { nativeRunId = null } = {}) {
8713
8769
  : data;
8714
8770
  // An OpenCode panel's, brain's or run's output never carries a SynaBun run secret an agent printed (its serve's
8715
8771
  // environment holds the panel's token or the brain's credential): lib/terminal-token-redaction.js.
8716
- const payload = JSON.stringify(redactTerminalSecrets(wireData));
8772
+ // The scrub and the serialisation of one event, on the server's own thread: timed by name, so a stall names it.
8773
+ const payload = timeBlockingWork('opencode:event', () => JSON.stringify(redactTerminalSecrets(wireData)));
8717
8774
  for (const ws of _ocpV2WsClients) {
8718
8775
  if (nativeRun && !opencodeV2ClientOwnsRun(ws, nativeRun)) continue;
8719
8776
  if (ws.readyState === 1) {
@@ -18126,16 +18183,17 @@ function spawnAgentProcess(agent, prompt, extraEnv = {}) {
18126
18183
 
18127
18184
  agent.process = child;
18128
18185
  agent._lineBuffer = '';
18186
+ // The CLI's stdout cut into lines in time linear in what arrives (lib/line-buffer.js); bytes cut in the middle
18187
+ // of a character are completed by the decoder.
18188
+ const stdoutLines = createLineBuffer();
18189
+ const stdoutDecoder = new StringDecoder('utf8');
18129
18190
  let stderrBuf = '';
18130
18191
  let stderrLineBuffer = '';
18131
18192
 
18132
18193
  child.stdout.on('data', (chunk) => {
18133
- agent._lineBuffer += chunk.toString();
18134
- const lines = agent._lineBuffer.split('\n');
18135
- agent._lineBuffer = lines.pop();
18136
-
18137
- for (const line of lines) {
18194
+ for (const line of stdoutLines.push(typeof chunk === 'string' ? chunk : stdoutDecoder.write(chunk))) {
18138
18195
  if (!line.trim()) continue;
18196
+ const endLineWork = beginBlockingWork(sizedLabel('agent:stdout-line', line.length));
18139
18197
  try {
18140
18198
  const event = redactMcpValues(JSON.parse(line), mcpValues);
18141
18199
  agent.output.push(event);
@@ -18156,7 +18214,7 @@ function spawnAgentProcess(agent, prompt, extraEnv = {}) {
18156
18214
  if (event.total_cost_usd != null) agent.costUsd = event.total_cost_usd;
18157
18215
  }
18158
18216
  broadcastSync({ type: 'agent:output', agentId: agent.id, event });
18159
- } catch { /* partial JSON */ }
18217
+ } catch { /* partial JSON */ } finally { endLineWork(); }
18160
18218
  }
18161
18219
  });
18162
18220
 
@@ -18182,9 +18240,10 @@ function spawnAgentProcess(agent, prompt, extraEnv = {}) {
18182
18240
  });
18183
18241
 
18184
18242
  child.on('close', (code) => {
18185
- if (agent._lineBuffer.trim()) {
18243
+ const lastLine = stdoutLines.push(stdoutDecoder.end()).join('\n') + stdoutLines.end();
18244
+ if (lastLine.trim()) {
18186
18245
  try {
18187
- const event = redactMcpValues(JSON.parse(agent._lineBuffer), mcpValues);
18246
+ const event = redactMcpValues(JSON.parse(lastLine), mcpValues);
18188
18247
  agent.output.push(event);
18189
18248
  if (event.type === 'result') {
18190
18249
  if (event.cost_usd != null) agent.costUsd = (agent.costUsd || 0) + event.cost_usd;
@@ -21454,16 +21513,15 @@ function writeAntigravityMcpConfig(data) {
21454
21513
  function _writeMoreLoginMcpToAgents(entry) {
21455
21514
  const targets = [];
21456
21515
  const home = getHomePath();
21457
- try { // Claude Code (~/.claude.json)
21516
+ try { // Claude Code (~/.claude.json, its own file: only through lib/claude-global-config.js)
21458
21517
  const p = join(home, '.claude.json');
21459
21518
  if (existsSync(p)) {
21460
- const data = JSON.parse(readFileSync(p, 'utf8') || '{}');
21461
- if (!data.mcpServers) data.mcpServers = {};
21462
- data.mcpServers[MORELOGIN_MCP_KEY] = entry.url
21519
+ const moreLoginEntry = entry.url
21463
21520
  ? { type: entry.type || 'http', url: entry.url }
21464
21521
  : { command: entry.command, args: entry.args || [], ...(entry.env ? { env: entry.env } : {}) };
21465
- writeFileSync(p, JSON.stringify(data, null, 2), 'utf8');
21466
- targets.push('Claude Code');
21522
+ const written = updateClaudeGlobalConfig(p, (data) => ({ ...data, mcpServers: { ...(data.mcpServers && typeof data.mcpServers === 'object' ? data.mcpServers : {}), [MORELOGIN_MCP_KEY]: moreLoginEntry } }));
21523
+ if (written.ok) targets.push('Claude Code');
21524
+ else console.warn('[morelogin] Claude register skipped:', claudeGlobalConfigRefusal(written.reason));
21467
21525
  }
21468
21526
  } catch (e) { console.warn('[morelogin] Claude register failed:', e.message); }
21469
21527
  try { // Antigravity (~/.gemini/config/mcp_config.json, the CLI's and the app's): only where Antigravity has run
@@ -21504,12 +21562,16 @@ function _removeMoreLoginMcpFromAgents() {
21504
21562
  try {
21505
21563
  const p = join(home, '.claude.json');
21506
21564
  if (existsSync(p)) {
21507
- const data = JSON.parse(readFileSync(p, 'utf8') || '{}');
21508
- if (data.mcpServers && data.mcpServers[MORELOGIN_MCP_KEY]) {
21509
- delete data.mcpServers[MORELOGIN_MCP_KEY];
21510
- writeFileSync(p, JSON.stringify(data, null, 2), 'utf8');
21511
- targets.push('Claude Code');
21512
- }
21565
+ let had = false;
21566
+ const written = updateClaudeGlobalConfig(p, (data) => {
21567
+ if (!data.mcpServers || typeof data.mcpServers !== 'object' || !data.mcpServers[MORELOGIN_MCP_KEY]) return null;
21568
+ had = true;
21569
+ const mcpServers = { ...data.mcpServers };
21570
+ delete mcpServers[MORELOGIN_MCP_KEY];
21571
+ return { ...data, mcpServers };
21572
+ });
21573
+ if (written.ok && had) targets.push('Claude Code');
21574
+ else if (!written.ok) console.warn('[morelogin] Claude unregister skipped:', claudeGlobalConfigRefusal(written.reason));
21513
21575
  }
21514
21576
  } catch {}
21515
21577
  try {
@@ -24659,10 +24721,10 @@ app.post('/api/claude-code/mcp', (req, res) => {
24659
24721
  const claudeJsonPath = join(home, '.claude.json');
24660
24722
  const mcpUrl = `http://localhost:${PORT}/mcp`;
24661
24723
 
24662
- let data = {};
24663
- try { data = JSON.parse(readFileSync(claudeJsonPath, 'utf-8')); } catch {}
24664
- data = mergeClaudeMcpConfig(data, mcpUrl);
24665
- writeFileSync(claudeJsonPath, JSON.stringify(data, null, 2), 'utf-8');
24724
+ // Claude Code's own file (the sign-in's record, the flag that says where its login lives): a file it cannot read
24725
+ // as JSON is never replaced (lib/claude-global-config.js).
24726
+ const written = updateClaudeGlobalConfig(claudeJsonPath, (data) => mergeClaudeMcpConfig(data, mcpUrl), { create: true });
24727
+ if (!written.ok) return res.status(409).json({ ok: false, code: 'CLAUDE_CONFIG_UNSAFE', reason: written.reason, error: claudeGlobalConfigRefusal(written.reason) });
24666
24728
 
24667
24729
  // Force-allow the 7 SynaBun memory tools so CLI/PTY sessions skip per-call
24668
24730
  // permission prompts. Writes to ~/.claude/settings.json if present, otherwise
@@ -24683,12 +24745,15 @@ app.delete('/api/claude-code/mcp', (req, res) => {
24683
24745
  const home = process.env.USERPROFILE || process.env.HOME || '';
24684
24746
  const claudeJsonPath = join(home, '.claude.json');
24685
24747
  if (!existsSync(claudeJsonPath)) return res.json({ ok: true, rules: syncRulesWithMcp('claude', 'remove') });
24686
- const data = JSON.parse(readFileSync(claudeJsonPath, 'utf-8'));
24687
- if (data.mcpServers && data.mcpServers.SynaBun) {
24688
- delete data.mcpServers.SynaBun;
24689
- if (Object.keys(data.mcpServers).length === 0) delete data.mcpServers;
24690
- writeFileSync(claudeJsonPath, JSON.stringify(data, null, 2), 'utf-8');
24691
- }
24748
+ const written = updateClaudeGlobalConfig(claudeJsonPath, (data) => {
24749
+ if (!data.mcpServers || typeof data.mcpServers !== 'object' || !data.mcpServers.SynaBun) return null;
24750
+ const mcpServers = { ...data.mcpServers };
24751
+ delete mcpServers.SynaBun;
24752
+ const next = { ...data, mcpServers };
24753
+ if (Object.keys(mcpServers).length === 0) delete next.mcpServers;
24754
+ return next;
24755
+ });
24756
+ if (!written.ok && written.reason !== 'missing') return res.status(409).json({ ok: false, code: 'CLAUDE_CONFIG_UNSAFE', reason: written.reason, error: claudeGlobalConfigRefusal(written.reason) });
24692
24757
  res.json({ ok: true, message: 'SynaBun MCP removed from Claude.', rules: syncRulesWithMcp('claude', 'remove') });
24693
24758
  } catch (err) {
24694
24759
  res.status(500).json({ error: err.message });
@@ -28235,12 +28300,9 @@ async function internalMcpSync({ name, config, platforms }) {
28235
28300
  try {
28236
28301
  if (p === 'claudeCode') {
28237
28302
  const claudeJsonPath = join(home, '.claude.json');
28238
- let data = {};
28239
- try { data = JSON.parse(readFileSync(claudeJsonPath, 'utf-8')); } catch {}
28240
- if (!data.mcpServers) data.mcpServers = {};
28241
- data.mcpServers[name] = buildClaudeMcpEntry(config);
28242
- writeFileSync(claudeJsonPath, JSON.stringify(data, null, 2), 'utf-8');
28243
- results.claudeCode = 'ok';
28303
+ const claudeEntry = buildClaudeMcpEntry(config);
28304
+ const written = updateClaudeGlobalConfig(claudeJsonPath, (data) => ({ ...data, mcpServers: { ...(data.mcpServers && typeof data.mcpServers === 'object' ? data.mcpServers : {}), [name]: claudeEntry } }), { create: true });
28305
+ results.claudeCode = written.ok ? 'ok' : `error: ${claudeGlobalConfigRefusal(written.reason)}`;
28244
28306
  } else if (p === 'opencode') {
28245
28307
  persistMcpToOpencodeConfig(name, config);
28246
28308
  results.opencode = 'ok';
@@ -28291,15 +28353,15 @@ app.delete('/api/mcp/sync', (req, res) => {
28291
28353
  try {
28292
28354
  if (p === 'claudeCode') {
28293
28355
  const claudeJsonPath = join(home, '.claude.json');
28294
- if (existsSync(claudeJsonPath)) {
28295
- const data = JSON.parse(readFileSync(claudeJsonPath, 'utf-8'));
28296
- if (data.mcpServers?.[name]) {
28297
- delete data.mcpServers[name];
28298
- if (Object.keys(data.mcpServers).length === 0) delete data.mcpServers;
28299
- writeFileSync(claudeJsonPath, JSON.stringify(data, null, 2), 'utf-8');
28300
- }
28301
- }
28302
- results.claudeCode = 'ok';
28356
+ const written = updateClaudeGlobalConfig(claudeJsonPath, (data) => {
28357
+ if (!data.mcpServers || typeof data.mcpServers !== 'object' || !data.mcpServers[name]) return null;
28358
+ const mcpServers = { ...data.mcpServers };
28359
+ delete mcpServers[name];
28360
+ const next = { ...data, mcpServers };
28361
+ if (Object.keys(mcpServers).length === 0) delete next.mcpServers;
28362
+ return next;
28363
+ });
28364
+ results.claudeCode = written.ok || written.reason === 'missing' ? 'ok' : `error: ${claudeGlobalConfigRefusal(written.reason)}`;
28303
28365
 
28304
28366
  } else if (p === 'opencode') {
28305
28367
  if (mcpServersOf(readOpencodeConfigDocument(getOpencodeConfigPath()).config)[name]) {
@@ -28750,7 +28812,9 @@ app.get('/api/diagnostics/event-loop', async (req, res) => {
28750
28812
  let ptyHost;
28751
28813
  try { ptyHost = await terminalHost.stats({ reset }); }
28752
28814
  catch (err) { ptyHost = { error: err.message, mode: terminalHost.mode, restarts: terminalHost.restarts }; }
28753
- res.json({ ok: true, main, ptyHost });
28815
+ // How many secrets the scrubbers look for (lib/terminal-token-redaction.js) and what holds a live proof, by kind and
28816
+ // by the family of its id: numbers only, never an id or a value. A count that only grows is a leak.
28817
+ res.json({ ok: true, main, ptyHost, knownSecrets: knownSecretCount(), terminalTokens: { ..._terminalTokens.stats(), ..._terminalTokens.breakdown() } });
28754
28818
  });
28755
28819
 
28756
28820
  // ── CLI Config (custom CLI paths for terminal profiles) ──
@@ -37787,7 +37851,26 @@ app.post('/api/browser/extension/reload', ownerReloadHandler({ update: extension
37787
37851
  const sendSetup = (res, run) => Promise.resolve().then(run).then(value => res.json({ ok: true, ...value }),
37788
37852
  error => res.status(400).json(extensionSetupError(error) || extensionSafeError(error)));
37789
37853
  app.get('/api/browser/extension/setup/status', (_req, res) => sendSetup(res, () => extensionSetup.status()));
37790
- app.post('/api/browser/extension/setup/start', (req, res) => sendSetup(res, () => extensionSetup.start({ browserId: typeof req.body?.browser === 'string' ? req.body.browser : undefined })));
37854
+ // The Settings guide's list of browsers (names and extensions addresses from the catalog, never a program or a path).
37855
+ // A look starts plutil or reg, so one is reused for 30 s; ?refresh=1 looks again.
37856
+ app.get('/api/browser/extension/setup/browsers', (req, res) => sendSetup(res, () => extensionSetup.browsers({ refresh: req.query?.refresh === '1' })));
37857
+ // `present: 'none'` (the Settings guide): the folder and the pairing session, nothing opened or shown.
37858
+ app.post('/api/browser/extension/setup/start', (req, res) => sendSetup(res, () => extensionSetup.start({ browserId: typeof req.body?.browser === 'string' ? req.body.browser : undefined, present: req.body?.present })));
37859
+ // The routes that start a browser for the guide (its extensions page, the companion page) and the capabilities check
37860
+ // are asked by SynaBun Settings only: besides the guard above, refused from an extension's own origin, from a request
37861
+ // the browser does not mark same-origin, and without the app's X-SynaBun-UI header (as reload/confirm). The body
37862
+ // names an installed browser by its id and nothing else; the program and the address come from the detected install
37863
+ // and the catalog (lib/browser-default.js extensionsPagePlan / launchPlan).
37864
+ const extensionSettingsOnly = (req, res, next) => {
37865
+ const origin = String(req.headers.origin || ''), site = req.headers['sec-fetch-site'];
37866
+ if (/^[a-z-]*extension:/i.test(origin) || (site !== undefined && site !== 'same-origin') || req.headers['x-synabun-ui'] !== '1') return res.status(403).json({ code: 'OWNER_ROUTE', error: 'Only the owner\'s SynaBun Settings can do this.' });
37867
+ next();
37868
+ };
37869
+ app.post('/api/browser/extension/setup/open-extensions', extensionSettingsOnly, (req, res) => sendSetup(res, () => extensionSetup.openExtensions(req.body)));
37870
+ app.post('/api/browser/extension/setup/focus', extensionSettingsOnly, (req, res) => sendSetup(res, () => extensionSetup.focus(req.body)));
37871
+ // What the paired extension can do now (the bridge's probe, 4 s at most); `capabilities` of GET /api/browser/extension
37872
+ // is the bridge's last report (its status, spread there whole).
37873
+ app.post('/api/browser/extension/capabilities/check', extensionSettingsOnly, (req, res) => sendSetup(res, () => extensionSetup.capabilities(req.body)));
37791
37874
  app.post('/api/browser/extension/setup/ticket', (_req, res) => { res.setHeader('Cache-Control', 'no-store'); return sendSetup(res, () => extensionSetup.ticket()); });
37792
37875
  app.post('/api/browser/extension/setup/cancel', (_req, res) => sendSetup(res, () => extensionSetup.cancel()));
37793
37876
  app.post('/api/browser/extension/setup/reveal', (_req, res) => sendSetup(res, () => extensionSetup.reveal()));