synabun 2.4.5 → 2.4.7

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 (108) hide show
  1. package/CHANGELOG.md +38 -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 +153 -10
  31. package/neural-interface/i18n/pt-BR.json +153 -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/browser-background-tab.js +12 -0
  37. package/neural-interface/lib/browser-guard-cdp.js +2 -1
  38. package/neural-interface/lib/browser-network-guard.js +140 -3
  39. package/neural-interface/lib/browser-own-targets.js +350 -0
  40. package/neural-interface/lib/claude-agent-bridge.js +13 -2
  41. package/neural-interface/lib/codex-thread-history.js +144 -7
  42. package/neural-interface/lib/codex-worker-app-server.js +84 -30
  43. package/neural-interface/lib/db.js +26 -0
  44. package/neural-interface/lib/greeting/sources.js +7 -3
  45. package/neural-interface/lib/jsonl-lines.js +10 -11
  46. package/neural-interface/lib/launch-block-api.js +86 -0
  47. package/neural-interface/lib/line-buffer.js +88 -0
  48. package/neural-interface/lib/loop-stall.js +15 -1
  49. package/neural-interface/lib/memory-list-read.js +105 -0
  50. package/neural-interface/lib/memory-timers.js +4 -1
  51. package/neural-interface/lib/morelogin-launch-recovery.js +506 -0
  52. package/neural-interface/lib/morelogin-profile-failures.js +48 -1
  53. package/neural-interface/lib/morelogin.js +16 -2
  54. package/neural-interface/lib/native-loop-runtime.js +7 -3
  55. package/neural-interface/lib/provider-panel-api-key-auth.js +33 -6
  56. package/neural-interface/lib/skills/api-v2.js +18 -3
  57. package/neural-interface/lib/skills/bundle.js +2 -2
  58. package/neural-interface/lib/skills/deploy.js +169 -34
  59. package/neural-interface/lib/skills/digest.js +57 -3
  60. package/neural-interface/lib/skills/health.js +55 -1
  61. package/neural-interface/lib/skills/known-bridge-digests.json +12 -0
  62. package/neural-interface/lib/skills/runtime-checks.js +7 -4
  63. package/neural-interface/lib/skills/scan-shell.js +56 -7
  64. package/neural-interface/lib/skills/scan.js +13 -12
  65. package/neural-interface/lib/skills/service.js +7 -2
  66. package/neural-interface/lib/skills/telemetry.js +2 -2
  67. package/neural-interface/lib/teams/README.md +12 -5
  68. package/neural-interface/lib/teams/api.js +15 -4
  69. package/neural-interface/lib/teams/index.js +2 -0
  70. package/neural-interface/lib/teams/landing.js +195 -75
  71. package/neural-interface/lib/teams/scheduler.js +31 -32
  72. package/neural-interface/lib/terminal-token-redaction.js +228 -58
  73. package/neural-interface/lib/terminal-tokens.js +18 -0
  74. package/neural-interface/lib/whatsapp/brain.js +21 -0
  75. package/neural-interface/lib/whatsapp/bridge.js +40 -4
  76. package/neural-interface/package-lock.json +2 -2
  77. package/neural-interface/package.json +1 -1
  78. package/neural-interface/public/index.html +117 -37
  79. package/neural-interface/public/shared/agents/studio/ax-api.js +11 -0
  80. package/neural-interface/public/shared/agents/studio/ax-create-view.js +1 -1
  81. package/neural-interface/public/shared/agents/studio/ax-icons.js +1 -0
  82. package/neural-interface/public/shared/agents/studio/ax-library-view.js +3 -2
  83. package/neural-interface/public/shared/agents/studio/ax-main.js +127 -41
  84. package/neural-interface/public/shared/agents/studio/ax-review-view.js +3 -2
  85. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +137 -39
  86. package/neural-interface/public/shared/agents/studio/ax-teams.js +219 -4
  87. package/neural-interface/public/shared/agents/studio/ax-ui.js +31 -0
  88. package/neural-interface/public/shared/agents/studio/ax-views.js +67 -69
  89. package/neural-interface/public/shared/agents/studio/ax-work-answer.js +86 -0
  90. package/neural-interface/public/shared/agents/studio/ax-work-view.js +305 -0
  91. package/neural-interface/public/shared/agents/studio/ax-work.css +74 -0
  92. package/neural-interface/public/shared/agents/studio/ax-work.js +300 -0
  93. package/neural-interface/public/shared/cdx/cdx-deferred.js +90 -0
  94. package/neural-interface/public/shared/cdx/cdx-render.js +18 -7
  95. package/neural-interface/public/shared/cdx/cdx-tabs.js +2 -1
  96. package/neural-interface/public/shared/launch-block-view.js +124 -0
  97. package/neural-interface/public/shared/loading-diagnostic-entry.js +16 -1
  98. package/neural-interface/public/shared/skills/studio/sx-operations-view.js +5 -0
  99. package/neural-interface/public/shared/skills/studio/sx-plan.js +42 -3
  100. package/neural-interface/public/shared/skills/studio/sx-publish-view.js +20 -4
  101. package/neural-interface/public/shared/styles.css +17 -0
  102. package/neural-interface/public/shared/ui-launch-block-notice.js +155 -0
  103. package/neural-interface/public/shared/ui-navbar.js +11 -0
  104. package/neural-interface/public/shared/ui-sync.js +2 -0
  105. package/neural-interface/server.js +745 -270
  106. package/npm-shrinkwrap.json +2 -2
  107. package/package.json +2 -1
  108. package/skills/skill-forge/SKILL.md +7 -3
@@ -51,7 +51,12 @@ 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';
56
+ import { createOwnTargetRegistry, createOwnTabCloseWatch, ownTargetProfileKey, closeOwnTargets } from './lib/browser-own-targets.js';
57
+ import { createLaunchRecovery } from './lib/morelogin-launch-recovery.js';
58
+ import { createLaunchBlockApi, launchBlockNoticeOf } from './lib/launch-block-api.js';
59
+ import { connectGuardCdp } from './lib/browser-guard-cdp.js';
55
60
  import { createSocialWritePacer, socialPaceAccountKey, socialPaceRequest, socialPacingBlock, SOCIAL_PACE_LIMITS, SOCIAL_WRITE_GAPS } from './lib/social-write-pacing.js';
56
61
  import { describeLocatorMatches, healLocatorByText, validNthMatch, captureTargetIdentity, matchesTargetIdentity } from './lib/browser-targets.js';
57
62
  import { getInteractiveHints, collectSemanticContext, buildAssist, describeTargetFacts, verifyHealTarget, createAssistContextStore } from './lib/browser-semantic-context.js';
@@ -65,7 +70,7 @@ import { runBrowserExtraction, readBrowserContentHtml } from './lib/browser-extr
65
70
  import { attachConsoleBuffer, readConsoleBuffer, parseConsoleSince } from './lib/browser-console.js';
66
71
  import { resolveBrowserLanguage, validateBrowserLanguageConfig } from './lib/browser-language.js';
67
72
  import { parseScreenshotOptions, captureScreenshot, screenshotPathRefusal, defaultScreenshotPath, writeScreenshotFile } from './lib/browser-screenshot.js';
68
- import { openBackgroundPageStrict, backgroundTabsEnabled, newContextWithId, selectedTabReading } from './lib/browser-background-tab.js';
73
+ import { openBackgroundPageStrict, backgroundTabsEnabled, newContextWithId, selectedTabReading, pageTargetId } from './lib/browser-background-tab.js';
69
74
  import { withMemoryWrite } from '../mcp-server/dist/services/sqlite-write.js';
70
75
  import { memoryRevision } from '../mcp-server/dist/services/memory-maintenance.js';
71
76
  import { startGatedMemoryMaintenance, stopGatedMemoryMaintenance } from './lib/memory-timers.js';
@@ -143,6 +148,7 @@ import { createRequire } from 'module';
143
148
  import { Readable } from 'stream';
144
149
  import { createConnection as netConnect } from 'net';
145
150
  import { DatabaseSync } from 'node:sqlite';
151
+ import { StringDecoder } from 'node:string_decoder';
146
152
  import { WebSocketServer } from 'ws';
147
153
  import { Agent as UndiciAgent, fetch as undiciFetch } from 'undici';
148
154
  import os from 'node:os';
@@ -366,7 +372,7 @@ import {
366
372
  retireCodexChildProcess,
367
373
  shouldReleaseCodexWriter,
368
374
  } from './lib/codex-writer-lifecycle.js';
369
- import { hydrateCodexThreadHistory, revertCodexThreadHistory } from './lib/codex-thread-history.js';
375
+ import { deferCodexInlineImage, hydrateCodexThreadHistory, readCodexThreadItem, revertCodexThreadHistory } from './lib/codex-thread-history.js';
370
376
  import {
371
377
  buildCodexConfigEdits,
372
378
  buildCodexMcpServerApprovalEdit,
@@ -468,6 +474,7 @@ import { checkRuntimeDependencies, fallbackInstallArgs, fallbackInstallEnv, find
468
474
  import { buildMcpServerSafelyAsync, mcpBuildNeeded, mcpDistWhole } from '../lib/mcp-build.js';
469
475
  import { STOP_MARKER_NAME, STOP_TOKEN_ENV, stopAnnouncement, writeStopMarker } from '../lib/server-exit.js';
470
476
  import { redactDeep, redactSecrets } from '../lib/log-redact.js';
477
+ import { claudeGlobalConfigRefusal, updateClaudeGlobalConfig } from '../lib/claude-global-config.js';
471
478
  import { applyPackagedChildPath, durableEntry, mcpStdioCommand, npmGlobalBinFor, packagedNpmPrefix, packagedPathFolders, packagedRuntime } from '../lib/packaged-runtime.js';
472
479
  import { dataHomeId } from '../lib/desktop-app.js';
473
480
  import { pruneExternalTools } from '../lib/external-tools.js';
@@ -478,7 +485,7 @@ import { parseMemoryPage, pageEtagPart, describePage, isLastPage } from './lib/m
478
485
  import {
479
486
  getDb, closeDb, getDbPath, getEmbedding, getEmbeddingBatch, getEmbeddingDims, warmupEmbeddings,
480
487
  encodeVector, decodeVector, cosineSimilarity,
481
- searchMemories as dbSearchMemories, getAllMemories, getMemoriesPage, getAllMemoriesWithVectors,
488
+ searchMemories as dbSearchMemories, getAllMemories, readAllMemories, readMemoriesPage, getAllMemoriesWithVectors,
482
489
  getMemoryById, getMemoryWithVector, updateMemoryPayload,
483
490
  softDeleteMemory, hardDeleteMemory, restoreMemory as dbRestoreMemory,
484
491
  getTrashedMemories, purgeTrash, countMemories, getMemoryStats,
@@ -491,7 +498,8 @@ import {
491
498
  getFbActionBudget, getFbEngagementTier, FB_ACTION_TYPES,
492
499
  } from './lib/db.js';
493
500
  import { drainSessionJobs, runSessionJob, setSessionJobStoreGate } from './lib/session-cache-worker.js';
494
- import { beginActivity, instrumentSqlite, markActivity, startLoopStallMonitor } from './lib/loop-stall.js';
501
+ import { beginActivity, beginBlockingWork, instrumentSqlite, markActivity, sizedLabel, startLoopStallMonitor, timeBlockingWork } from './lib/loop-stall.js';
502
+ import { createLineBuffer } from './lib/line-buffer.js';
495
503
  import { createHealthCount } from './lib/health-count.js';
496
504
  import { createRecallImpact } from './lib/recall-impact.js';
497
505
  import { installMemoryStoreGate, isMemoryStoreRefusal, noteMemoryStoreRefusal } from './lib/memory-store-gate.js';
@@ -500,7 +508,9 @@ import { installMemoryStoreGate, isMemoryStoreRefusal, noteMemoryStoreRefusal }
500
508
  const memoryStoreGate = installMemoryStoreGate();
501
509
  setSessionJobStoreGate(() => (memoryStoreGate.open() ? null : memoryStoreGate.forJobs()));
502
510
 
503
- startLoopStallMonitor();
511
+ // A stall of 3 s or more also says how many secrets the scrubbers look for: their cost once grew with that number
512
+ // (lib/terminal-token-redaction.js), and a count that only grows is a leak worth seeing in the same line.
513
+ startLoopStallMonitor({ detail: () => `known secrets ${knownSecretCount()}` });
504
514
  // A stall line names the slowest synchronous SQLite statement it held (off: SYNABUN_LOOP_STALL_SQL=off).
505
515
  instrumentSqlite();
506
516
  import {
@@ -1141,10 +1151,20 @@ app.get(['/', '/index.html', '/index2d.html'], (req, res, next) => {
1141
1151
  if (target !== req.originalUrl) return res.redirect(target);
1142
1152
  next();
1143
1153
  });
1154
+ // Scripts and styles are kept by the browser and asked about on every load (`no-cache` + a validator). A page is
1155
+ // never kept (`no-store`, and always answered whole, never 304: a 304 would keep the browser's copy). A kept page is
1156
+ // what a browser shows for a history-style load while the server is away: on 2026-11-28 the owner's Safari web app
1157
+ // reopened a copy of index.html from before a fix, ran it without its server, and the module loads that failed there
1158
+ // stayed failed in WebKit's memory for the pages loaded after it. Without a copy that load reaches the service
1159
+ // worker's offline page, which has the Start Server button.
1144
1160
  app.use(express.static(join(__dirname, 'public'), {
1145
1161
  etag: true,
1146
1162
  lastModified: true,
1147
- setHeaders: (res) => res.setHeader('Cache-Control', 'no-cache'),
1163
+ setHeaders: (res, path) => {
1164
+ if (!/\.html?$/i.test(path)) { res.setHeader('Cache-Control', 'no-cache'); return; }
1165
+ res.setHeader('Cache-Control', 'no-store');
1166
+ if (res.req) { delete res.req.headers['if-none-match']; delete res.req.headers['if-modified-since']; }
1167
+ },
1148
1168
  }));
1149
1169
 
1150
1170
  // --- Helpers ---
@@ -1527,10 +1547,10 @@ app.get('/api/memories', async (req, res) => {
1527
1547
  // so before a row is read (lib/memory-list-stamp.js). 32 MB were read, built and serialised on every
1528
1548
  // load only to find out, from the finished body, that nothing had changed.
1529
1549
  let listVersion = null;
1550
+ let listStamp = null;
1530
1551
  if (!includeLinks) {
1531
1552
  const ocBridgeNow = loadBridgeConfig('openclaw');
1532
1553
  if (_openclawNodes !== _openclawNodesSeen) { _openclawNodesSeen = _openclawNodes; _openclawNodesRev += 1; }
1533
- let listStamp = null;
1534
1554
  try { listStamp = memoryListStamp(getDb()); } catch { /* no stamp: the full answer, as before */ }
1535
1555
  const listParts = [
1536
1556
  listStamp, slim ? 'graph' : 'full', SLIM_CONTENT_CHARS,
@@ -1548,9 +1568,11 @@ app.get('/api/memories', async (req, res) => {
1548
1568
 
1549
1569
  const cachedLinks = includeLinks ? getValidLinkCache() : null;
1550
1570
  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());
1571
+ // A page reads its own rows only (and how many there are); the whole list reads them all. Both are read off this
1572
+ // thread (lib/memory-list-read.js): on a busy store one page held it for seconds, right when the page that asked
1573
+ // also wants its modules. Only the vectors for a link computation are still read here.
1574
+ const pageRead = page ? await readMemoriesPage(page, { stamp: listStamp }) : null;
1575
+ const allPoints = pageRead ? pageRead.rows : (needVectors ? getAllMemoriesWithVectors() : await readAllMemories({ stamp: listStamp }));
1554
1576
 
1555
1577
  // Build nodes
1556
1578
  const nodes = allPoints.map(p => ({
@@ -4699,6 +4721,10 @@ function codexAccountInUse(accountId, { except = null } = {}) {
4699
4721
  return '';
4700
4722
  }
4701
4723
 
4724
+ // How a thread's history is read for a page (lib/codex-thread-history.js hydrateCodexThreadHistory): generated
4725
+ // images' inline data is left out of each item as its page arrives, and fetched when the item is opened.
4726
+ const CODEX_HISTORY_FOR_PAGE = Object.freeze({ transformItem: deferCodexInlineImage });
4727
+
4702
4728
  function handleCodexSkinWebSocket(ws) {
4703
4729
  // In API-key mode with a key SynaBun holds, the app-server starts with an ephemeral
4704
4730
  // credential store and this key is its first request over stdin (lib/codex-accounts.js).
@@ -4723,7 +4749,10 @@ CRITICAL — When you need clarification during planning:
4723
4749
  6. The sidepanel will ask the user whether to Edit plan, Compact context, or Continue with implementation.`,
4724
4750
  ];
4725
4751
  let child = null;
4726
- let childStdoutBuf = '';
4752
+ // The app-server's stdout, cut into lines in time linear in what arrives (lib/line-buffer.js).
4753
+ const childStdoutLines = createLineBuffer({
4754
+ onOverflow: (chars) => console.warn(`[codex-skin] Dropped an app-server line of over ${Math.round(chars / 1048576)} MB (longer than a string can be)`),
4755
+ });
4727
4756
  let initialized = false;
4728
4757
  let bootPromise = null;
4729
4758
  let nextRequestId = 1;
@@ -4960,7 +4989,7 @@ CRITICAL — When you need clarification during planning:
4960
4989
  try { clearTimeout(entry.timer); entry.reject(new Error('Codex account sign-in changed')); } catch {}
4961
4990
  }
4962
4991
  pending.clear();
4963
- childStdoutBuf = '';
4992
+ childStdoutLines.clear();
4964
4993
  unregisterCodexToolsRuntime();
4965
4994
  child = null;
4966
4995
  childCredential = null;
@@ -5668,13 +5697,28 @@ CRITICAL — When you need clarification during planning:
5668
5697
  const readResult = await request('thread/read', getDefaultReadParams(threadId), 15000);
5669
5698
  const thread = extractCodexThread(readResult);
5670
5699
  if (!thread) return null;
5671
- const history = await hydrateCodexThreadHistory(request, thread.id || threadId);
5700
+ // Read in pages sized by what they weigh, and a generated image's inline data is left out as each page arrives
5701
+ // (lib/codex-thread-history.js): the page asks for it when its item is opened (thread_item_payload). A thread of
5702
+ // generated images used to come back as one reply of 171 MB, parsed, redacted and sent on in one go.
5703
+ const history = await hydrateCodexThreadHistory(request, thread.id || threadId, CODEX_HISTORY_FOR_PAGE);
5672
5704
  if (history.source === 'turns-full-fallback') {
5673
5705
  console.log(`[codex-history] thread/items/list unavailable; restored full turns thread=${thread.id || threadId}`);
5674
5706
  }
5675
5707
  return { ...thread, turns: history.turns };
5676
5708
  }
5677
5709
 
5710
+ // One item of the thread this tab shows, whole: the data a history left out of it (a generated image).
5711
+ async function readThreadItemPayload(msg) {
5712
+ const threadId = String(msg.threadId || '');
5713
+ const shown = [displayedThreadId, activeThreadId].filter(Boolean).map(String);
5714
+ if (!threadId || !shown.includes(threadId)) throw new Error('This item belongs to another thread.');
5715
+ if (typeof msg.turnId !== 'string' || !msg.turnId || typeof msg.itemId !== 'string' || !msg.itemId) throw new Error('A turn and an item are required.');
5716
+ await ensureInitialized();
5717
+ const item = await readCodexThreadItem(request, threadId, msg.turnId, msg.itemId);
5718
+ if (!item) throw new Error('Codex no longer has this item.');
5719
+ return sanitizeCodexHistoryItem(item);
5720
+ }
5721
+
5678
5722
  function tryParseJson(value) {
5679
5723
  if (typeof value !== 'string') return value;
5680
5724
  const trimmed = value.trim();
@@ -6069,12 +6113,20 @@ CRITICAL — When you need clarification during planning:
6069
6113
  if (!codexTerminalToken) delete env[TERMINAL_TOKEN_ENV];
6070
6114
  delete env.FORCE_COLOR;
6071
6115
  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
- });
6116
+ let proc;
6117
+ try {
6118
+ proc = spawn(shellCommand(codexBin, useShell, { isFile: existsSync }), args, {
6119
+ cwd: PACKAGE_ROOT,
6120
+ env,
6121
+ stdio: ['pipe', 'pipe', 'pipe'],
6122
+ shell: useShell,
6123
+ });
6124
+ } catch (error) {
6125
+ // No process, so no 'close' that would end its proof: the token minted for it above is revoked here (the
6126
+ // scrubbers forget it), or every failed start would leave one known secret behind for as long as the server runs.
6127
+ _terminalTokens.revoke(codexMcpRuntimeId);
6128
+ throw error;
6129
+ }
6078
6130
  child = proc;
6079
6131
  childApiKeyLogin = launch.apiKey || null;
6080
6132
  childUsesHeldKey = !!launch.apiKey;
@@ -6086,198 +6138,202 @@ CRITICAL — When you need clarification during planning:
6086
6138
  registerCodexToolsRuntime();
6087
6139
  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
6140
  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
- }
6141
+ // One line of the app-server's stdout: a JSON-RPC reply, request or notification. Parsed, redacted and handed
6142
+ // on here, on the server's own thread: timed by name where it is called (below), so a stall names it.
6143
+ const handleStdoutLine = (line) => {
6144
+ let msg;
6145
+ try {
6146
+ msg = redactProviderSecrets(JSON.parse(line));
6147
+ } catch (err) {
6148
+ console.warn('[codex-skin] Invalid JSON from app-server');
6149
+ return;
6150
+ }
6104
6151
 
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);
6152
+ if (msg.id !== undefined && !msg.method) {
6153
+ const entry = clearPendingRequest(msg.id);
6154
+ if (!entry) return;
6155
+ if (msg.error) {
6156
+ const err = new Error(msg.error.message || `Codex request ${msg.id} failed`);
6157
+ err.code = msg.error.code;
6158
+ err.data = msg.error.data;
6159
+ const unsupported = isCodexUnsupportedMethod(err);
6160
+ const capabilityChanged = codexCapabilities.observe(entry.method, err);
6161
+ if (capabilityChanged && unsupported) {
6162
+ sendToClient({ type: 'capabilities', ...codexCapabilitySnapshot() });
6121
6163
  }
6122
- continue;
6164
+ entry.reject(err);
6165
+ } else {
6166
+ codexCapabilities.observe(entry.method);
6167
+ entry.resolve(msg.result);
6123
6168
  }
6169
+ return;
6170
+ }
6124
6171
 
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
- }
6172
+ if (msg.id !== undefined && msg.method) {
6173
+ const requestId = msg.id;
6174
+ const automatic = automaticCodexServerReply(msg.method, msg.params, Date.now(), { userVerification: supportsUserVerification && codexRole !== 'assistant' && ws.readyState === 1 });
6175
+ if (automatic) {
6176
+ try { writeRpc({ jsonrpc: '2.0', id: requestId, ...automatic }); } catch {}
6177
+ if (automatic.error) sendToClient({
6178
+ type: 'server_request', requestId, method: msg.method, params: codexVerificationCardParams(msg.params || {}), resolved: true,
6179
+ threadId: msg.params?.threadId || activeThreadId || null,
6180
+ turnId: msg.params?.turnId || activeTurnId || null,
6181
+ });
6182
+ return;
6183
+ }
6137
6184
 
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
- }
6185
+ // Auto-accept MCP tool approvals under this turn's mode, independently
6186
+ // of Claude's settings. Native Codex can omit tool_name altogether.
6187
+ // Assistant requests always reach the brain: it applies the current
6188
+ // mode and the plan/read-only policy before answering automatically.
6189
+ if (msg.method === 'mcpServer/elicitation/request'
6190
+ && codexRole !== 'assistant'
6191
+ && shouldAutoAcceptCodexMcpToolApproval(msg.params, { autoAccept: activeTurnAutoAccept })
6192
+ && serverRequestThreadIsOwned(msg.params?.threadId || activeThreadId)) {
6193
+ try { writeRpc({ jsonrpc: '2.0', id: requestId, result: { action: 'accept', content: {}, _meta: {} } }); } catch {}
6194
+ return;
6195
+ }
6149
6196
 
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,
6197
+ const requestParams = msg.params || {};
6198
+ const requestInfo = {
6199
+ // The JSON-RPC id exactly as the app-server sent it (a number): the
6200
+ // reply must carry the same value, and clients may echo it as a string.
6201
+ rpcId: requestId,
6202
+ method: msg.method,
6203
+ params: codexVerificationCardParams(requestParams),
6204
+ threadId: requestParams.threadId || activeThreadId || null,
6205
+ turnId: requestParams.turnId || activeTurnId || null,
6206
+ toolCallId: requestParams.toolCallId || requestParams.callId || requestParams.itemId || null,
6207
+ };
6208
+ if (!serverRequestThreadIsOwned(requestInfo.threadId)) {
6209
+ recordCodexIsolationDecision('foreign_server_request');
6210
+ try {
6211
+ writeRpc({
6212
+ jsonrpc: '2.0',
6213
+ id: requestId,
6214
+ error: { code: -32001, message: 'Request does not belong to this Codex sidepanel thread.' },
6184
6215
  });
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,
6216
+ } catch {}
6217
+ return;
6218
+ }
6219
+ const correlation = requestCorrelation(requestId, requestInfo);
6220
+ const registered = runCodexJournalOperation('register', correlation, () => (
6221
+ codexRequestJournal.register(correlation, { method: msg.method })
6222
+ ));
6223
+ if (!registered.ok) {
6224
+ const code = registered.error.code;
6225
+ const message = code === 'ENOSPC'
6226
+ ? 'SynaBun cannot persist this Codex request because the disk is full. Free disk space and retry.'
6227
+ : 'SynaBun cannot persist this Codex request. Resolve the storage error and retry.';
6228
+ sendRpcError(requestId, message, -32070, {
6229
+ code,
6230
+ retryable: true,
6199
6231
  });
6200
- continue;
6232
+ return;
6201
6233
  }
6234
+ if (requestParams.mode === 'openai/userVerification') requestInfo.verification = new CodexVerificationOperation();
6235
+ pendingServerRequests.set(String(requestId), requestInfo);
6236
+ logRequestLifecycle('render', correlation, {
6237
+ method: msg.method,
6238
+ });
6239
+ sendToClient({
6240
+ type: 'server_request',
6241
+ requestId,
6242
+ method: msg.method,
6243
+ params: codexVerificationCardParams(requestParams),
6244
+ threadId: requestParams.threadId || activeThreadId || null,
6245
+ turnId: requestParams.turnId || activeTurnId || null,
6246
+ });
6247
+ return;
6248
+ }
6202
6249
 
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 || '');
6250
+ if (msg.method) {
6251
+ const method = msg.method;
6252
+ const params = msg.params || {};
6253
+ if (method === 'account/rateLimits/updated') _assistantAccountUsage?.note('codex', activeAccountId, params);
6254
+ if (method === 'account/login/completed') void panelAuth.complete(params);
6255
+ if (method === 'account/updated' && params.authMode === null && !panelAuth.active()) panelAuth.reset();
6256
+ const scopedThreadId = notificationThreadId(method, params);
6257
+ const scopedTurnId = notificationTurnId(method, params);
6258
+ const expectedThreadId = displayedThreadId;
6259
+ const expectedTurnId = activeTurnId;
6260
+ rememberCodexNotificationOwnership(params, scopedThreadId, scopedTurnId);
6261
+ const rejectionReason = codexNotificationRejectionReason(
6262
+ method,
6263
+ scopedThreadId,
6264
+ scopedTurnId,
6265
+ expectedThreadId,
6266
+ expectedTurnId,
6267
+ );
6268
+ if (method === 'thread/started' && params.thread?.id) {
6269
+ rememberThreadSubscription(params.thread);
6270
+ } else if (method === 'turn/started' && params.turn?.id
6271
+ && (!scopedThreadId || !activeThreadId || scopedThreadId === String(activeThreadId))) {
6272
+ activeTurnId = params.turn.id;
6273
+ } else if (method === 'turn/completed'
6274
+ && (!scopedThreadId || !activeThreadId || scopedThreadId === String(activeThreadId))
6275
+ && (!activeTurnId || !scopedTurnId || scopedTurnId === String(activeTurnId))) {
6276
+ finishPendingServerRequests(params.turn?.error ? 'turn_canceled' : 'dismissed', params.turn?.error?.message || '');
6277
+ activeTurnId = null;
6278
+ activeTurnAutoAccept = false;
6279
+ lastTurnLocalImages = [];
6280
+ } else if (method === 'thread/closed' && params.threadId) {
6281
+ const closedThreadId = String(params.threadId);
6282
+ subscribedThreadIds.delete(closedThreadId);
6283
+ threadOwnerRoots.delete(closedThreadId);
6284
+ if (closedThreadId === String(activeThreadId || '')) {
6285
+ activeThreadId = null;
6286
+ appBoundary.invalidate();
6230
6287
  activeTurnId = null;
6231
6288
  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;
6289
+ activeThreadRuntimeFingerprint = null;
6245
6290
  }
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));
6291
+ if (closedThreadId === String(displayedThreadId || '')) displayedThreadId = null;
6292
+ }
6293
+ if (method === 'serverRequest/resolved' && params.requestId != null) {
6294
+ const resolvedRequest = pendingServerRequests.get(String(params.requestId));
6295
+ if (resolvedRequest?.verification) {
6296
+ params.status = 'cancelled';
6297
+ const settled = resolvedRequest.verification.finish('cancel');
6298
+ if (settled?.cancelId != null) void request('userVerification/cancel', { requestId: settled.cancelId }, 10000).catch(() => {});
6268
6299
  }
6269
- recordCodexIsolationDecision(rejectionReason);
6270
- if (!rejectionReason) {
6271
- sendToClient({
6272
- type: 'notify',
6273
- method,
6274
- params: sanitizedParams,
6275
- threadId: scopedThreadId,
6276
- turnId: scopedTurnId,
6277
- });
6300
+ if (resolvedRequest) {
6301
+ const correlation = requestCorrelation(params.requestId, resolvedRequest);
6302
+ runCodexJournalOperation('finish', correlation, () => (
6303
+ codexRequestJournal.finish(
6304
+ correlation,
6305
+ 'dismissed',
6306
+ 'Resolved without a submitted sidepanel answer',
6307
+ )
6308
+ ));
6278
6309
  }
6310
+ pendingServerRequests.delete(String(params.requestId));
6311
+ }
6312
+ const sanitizedParams = sanitizeCodexNotifyParams(method, params);
6313
+ if (method === 'configWarning') {
6314
+ console.warn('[codex-config] app-server warning:', JSON.stringify(sanitizedParams));
6315
+ }
6316
+ recordCodexIsolationDecision(rejectionReason);
6317
+ if (!rejectionReason) {
6318
+ sendToClient({
6319
+ type: 'notify',
6320
+ method,
6321
+ params: sanitizedParams,
6322
+ threadId: scopedThreadId,
6323
+ turnId: scopedTurnId,
6324
+ });
6279
6325
  }
6280
6326
  }
6327
+ };
6328
+ proc.stdout.on('data', (chunk) => {
6329
+ if (child !== proc) return; // stale process from a previous account
6330
+ // Each chunk is searched once and a long line joined once (lib/line-buffer.js): a reply of one 171 MB line
6331
+ // used to be copied and searched again from its start for every 64 KiB of it.
6332
+ for (const rawLine of childStdoutLines.push(chunk)) {
6333
+ const line = rawLine.trim();
6334
+ if (!line) continue;
6335
+ timeBlockingWork(sizedLabel('codex:stdout-line', line.length), () => handleStdoutLine(line));
6336
+ }
6281
6337
  });
6282
6338
  // A write that reaches an app-server as it exits fails on the pipe (EPIPE)
6283
6339
  // after write() returned; unhandled, that error ended the whole server.
@@ -6312,10 +6368,8 @@ CRITICAL — When you need clarification during planning:
6312
6368
  activeTurnId = null;
6313
6369
  activeTurnAutoAccept = false;
6314
6370
  activeThreadRuntimeFingerprint = null;
6315
- if (childStdoutBuf.trim()) {
6316
- console.log('[codex-skin] trailing stdout:', childStdoutBuf.trim().slice(0, 200));
6317
- }
6318
- childStdoutBuf = '';
6371
+ const trailingStdout = childStdoutLines.end().trim();
6372
+ if (trailingStdout) console.log('[codex-skin] trailing stdout:', trailingStdout.slice(0, 200));
6319
6373
  for (const [id, entry] of pending.entries()) {
6320
6374
  clearTimeout(entry.timer);
6321
6375
  entry.reject(new Error(`Codex app-server exited before responding to request ${id}`));
@@ -6426,7 +6480,7 @@ CRITICAL — When you need clarification during planning:
6426
6480
  try { clearTimeout(entry.timer); entry.reject(new Error(reason)); } catch {}
6427
6481
  }
6428
6482
  pending.clear();
6429
- childStdoutBuf = '';
6483
+ childStdoutLines.clear();
6430
6484
  unregisterCodexToolsRuntime();
6431
6485
  child = null;
6432
6486
  if (old) {
@@ -6478,7 +6532,7 @@ CRITICAL — When you need clarification during planning:
6478
6532
  }
6479
6533
  pending.clear();
6480
6534
  pendingServerRequests.clear();
6481
- childStdoutBuf = ''; // drop any partial line from the outgoing process
6535
+ childStdoutLines.clear(); // drop any partial line from the outgoing process
6482
6536
  unregisterCodexToolsRuntime();
6483
6537
  child = null; // detach so old.on('close') sees child !== old and bails
6484
6538
  if (old) {
@@ -7204,6 +7258,15 @@ CRITICAL — When you need clarification during planning:
7204
7258
  withWriterOperation: withCodexWriterOperation,
7205
7259
  beforeRequest: beforeCodexCompatRequest, afterRequest: afterCodexCompatRequest,
7206
7260
  })) return;
7261
+ if (msg.type === 'thread_item_payload') {
7262
+ try {
7263
+ const item = await readThreadItemPayload(msg);
7264
+ sendToClient({ type: 'thread_item_payload', requestId: msg.requestId || null, threadId: String(msg.threadId), turnId: msg.turnId, itemId: msg.itemId, item });
7265
+ } catch (err) {
7266
+ sendToClient({ type: 'error', requestId: msg.requestId || null, ...classifyCodexRpcError(err), message: `Could not load this item's data. ${err.message}` });
7267
+ }
7268
+ return;
7269
+ }
7207
7270
  if (msg.type === 'thread_list') {
7208
7271
  try {
7209
7272
  const result = await listThreads({
@@ -7725,7 +7788,7 @@ CRITICAL — When you need clarification during planning:
7725
7788
  let result;
7726
7789
  try {
7727
7790
  result = await withCodexWriterOperation('thread_revert', () => revertCodexThreadHistory(request, threadId, {
7728
- numTurns: msg.numTurns ?? 1, beforeTurnId: msg.beforeTurnId,
7791
+ numTurns: msg.numTurns ?? 1, beforeTurnId: msg.beforeTurnId, history: CODEX_HISTORY_FOR_PAGE,
7729
7792
  }));
7730
7793
  } finally { appBoundary.invalidate(); }
7731
7794
  sendToClient({ type: 'thread_rolled_back', requestId: msg.requestId || null, thread: sanitizeCodexThreadForClient(result?.thread || result || null) });
@@ -8283,7 +8346,7 @@ async function queryCodexAppServerModels(codexHome = CODEX_DEFAULT_HOME, launch
8283
8346
  shell: useShell,
8284
8347
  });
8285
8348
  let nextId = 1;
8286
- let stdoutBuf = '';
8349
+ const stdoutLines = createLineBuffer();
8287
8350
  let stderrBuf = '';
8288
8351
  const pending = new Map();
8289
8352
  const cleanup = () => {
@@ -8331,10 +8394,7 @@ async function queryCodexAppServerModels(codexHome = CODEX_DEFAULT_HOME, launch
8331
8394
  }
8332
8395
  });
8333
8396
  child.stdout.on('data', (chunk) => {
8334
- stdoutBuf += chunk;
8335
- const lines = stdoutBuf.split('\n');
8336
- stdoutBuf = lines.pop() || '';
8337
- for (const rawLine of lines) {
8397
+ for (const rawLine of stdoutLines.push(chunk)) {
8338
8398
  const line = rawLine.trim();
8339
8399
  if (!line) continue;
8340
8400
  let msg;
@@ -8713,7 +8773,8 @@ function broadcastToOpencodeV2Clients(data, { nativeRunId = null } = {}) {
8713
8773
  : data;
8714
8774
  // An OpenCode panel's, brain's or run's output never carries a SynaBun run secret an agent printed (its serve's
8715
8775
  // environment holds the panel's token or the brain's credential): lib/terminal-token-redaction.js.
8716
- const payload = JSON.stringify(redactTerminalSecrets(wireData));
8776
+ // The scrub and the serialisation of one event, on the server's own thread: timed by name, so a stall names it.
8777
+ const payload = timeBlockingWork('opencode:event', () => JSON.stringify(redactTerminalSecrets(wireData)));
8717
8778
  for (const ws of _ocpV2WsClients) {
8718
8779
  if (nativeRun && !opencodeV2ClientOwnsRun(ws, nativeRun)) continue;
8719
8780
  if (ws.readyState === 1) {
@@ -16482,7 +16543,9 @@ async function launchScheduledLoop(schedule) {
16482
16543
  if (scheduledUsesBrowser) {
16483
16544
  // Same serialized shared-browser + dedicated-tab acquisition as manual loops. A new firing may start a profile
16484
16545
  // closed outside SynaBun (lib/morelogin-outside-close.js): that is what the schedule is for.
16485
- const acq = await acquireLoopBrowserAndTab({ terminalSessionId, logTag: 'schedule:browser', scheduledFiring: true });
16546
+ // `launch`: what the owner's notice names when launches keep failing on the profile (lib/morelogin-launch-recovery.js).
16547
+ const acq = await acquireLoopBrowserAndTab({ terminalSessionId, logTag: 'schedule:browser', scheduledFiring: true,
16548
+ launch: group?.name ? `${schedule.name} (${group.name})` : schedule.name });
16486
16549
  if (acq.error) {
16487
16550
  throw new Error(acq.error);
16488
16551
  }
@@ -18126,16 +18189,17 @@ function spawnAgentProcess(agent, prompt, extraEnv = {}) {
18126
18189
 
18127
18190
  agent.process = child;
18128
18191
  agent._lineBuffer = '';
18192
+ // The CLI's stdout cut into lines in time linear in what arrives (lib/line-buffer.js); bytes cut in the middle
18193
+ // of a character are completed by the decoder.
18194
+ const stdoutLines = createLineBuffer();
18195
+ const stdoutDecoder = new StringDecoder('utf8');
18129
18196
  let stderrBuf = '';
18130
18197
  let stderrLineBuffer = '';
18131
18198
 
18132
18199
  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) {
18200
+ for (const line of stdoutLines.push(typeof chunk === 'string' ? chunk : stdoutDecoder.write(chunk))) {
18138
18201
  if (!line.trim()) continue;
18202
+ const endLineWork = beginBlockingWork(sizedLabel('agent:stdout-line', line.length));
18139
18203
  try {
18140
18204
  const event = redactMcpValues(JSON.parse(line), mcpValues);
18141
18205
  agent.output.push(event);
@@ -18156,7 +18220,7 @@ function spawnAgentProcess(agent, prompt, extraEnv = {}) {
18156
18220
  if (event.total_cost_usd != null) agent.costUsd = event.total_cost_usd;
18157
18221
  }
18158
18222
  broadcastSync({ type: 'agent:output', agentId: agent.id, event });
18159
- } catch { /* partial JSON */ }
18223
+ } catch { /* partial JSON */ } finally { endLineWork(); }
18160
18224
  }
18161
18225
  });
18162
18226
 
@@ -18182,9 +18246,10 @@ function spawnAgentProcess(agent, prompt, extraEnv = {}) {
18182
18246
  });
18183
18247
 
18184
18248
  child.on('close', (code) => {
18185
- if (agent._lineBuffer.trim()) {
18249
+ const lastLine = stdoutLines.push(stdoutDecoder.end()).join('\n') + stdoutLines.end();
18250
+ if (lastLine.trim()) {
18186
18251
  try {
18187
- const event = redactMcpValues(JSON.parse(agent._lineBuffer), mcpValues);
18252
+ const event = redactMcpValues(JSON.parse(lastLine), mcpValues);
18188
18253
  agent.output.push(event);
18189
18254
  if (event.type === 'result') {
18190
18255
  if (event.cost_usd != null) agent.costUsd = (agent.costUsd || 0) + event.cost_usd;
@@ -21235,6 +21300,96 @@ const _runProfileFailures = createProfileFailureStore({
21235
21300
  log: (line) => console.warn(`[morelogin] ${line}`),
21236
21301
  });
21237
21302
 
21303
+ // ── A launch that fails on its profile's browser: one restart, one retry, one notice (lib/morelogin-launch-recovery.js) ──
21304
+ // The server's own recovery for the run it is launching (acquireWithProfileRecovery), never an agent's tool: what an
21305
+ // agent may stop or start is unchanged (POST /api/morelogin/stop, /start). Outcomes go to the profile's row of
21306
+ // morelogin-profile-failures.json and to this log; the owner's pages are told once per streak (`schedule:launch-blocked`,
21307
+ // GET /api/system/launch-blocks).
21308
+ /**
21309
+ * The automations other than `ownerKey` that work in profile `envId` now: the owners of a tab or a hold in a live
21310
+ * session on it (lib/browser-session-close.js otherSessionOwners), and the runs that started it themselves and are
21311
+ * still running. While there is one, the profile is not restarted under it. A starter the server no longer knows as
21312
+ * a running run (it ended, or it was a session that left) holds nothing: its entry stays until the profile is stopped,
21313
+ * and must not keep the profile from ever being restarted.
21314
+ */
21315
+ function otherProfileHolders(envId, ownerKey) {
21316
+ const others = new Set();
21317
+ for (const session of browserSessions.values()) {
21318
+ if (!sessionServesMoreLoginEnv(session, envId)) continue;
21319
+ for (const owner of otherSessionOwners(session, ownerKey)) others.add(owner);
21320
+ }
21321
+ for (const starter of _moreLoginStartedBy.get(String(envId)) || []) {
21322
+ if (starter !== ownerKey && automationRunState(browserOwnerId(starter) || starter, { files: true }) === 'live') others.add(starter);
21323
+ }
21324
+ return [...others];
21325
+ }
21326
+ /**
21327
+ * The sessions of profile `envId` that the owner has open in SynaBun: a page watches them (`clients`: a Browser panel,
21328
+ * a terminal's browser card) and no automation other than `ownerKey` works in them. A session the owner opened from the
21329
+ * page has no owner key, so otherProfileHolders never sees it; a restart would close the tabs the owner works in
21330
+ * (review of 2026-11-29, finding 1). closeUnclaimedBrowserStart reads a watched session as in use the same way. Such a
21331
+ * session is never restarted under the owner, and nothing of it is closed on the way to that refusal: the release of a
21332
+ * session that opens no tab (acquireSharedBrowserTab `release`) runs only after the recovery decided to restart.
21333
+ */
21334
+ function ownerPageSessionsOn(envId, ownerKey) {
21335
+ const watched = [];
21336
+ for (const [id, session] of browserSessions) {
21337
+ if (!sessionServesMoreLoginEnv(session, envId)) continue;
21338
+ if ((session.clients?.size || 0) > 0 && otherSessionOwners(session, ownerKey).length === 0) watched.push(id);
21339
+ }
21340
+ return watched;
21341
+ }
21342
+ const _launchRecovery = createLaunchRecovery({
21343
+ store: _runProfileFailures,
21344
+ holders: otherProfileHolders,
21345
+ ownerSessions: ownerPageSessionsOn,
21346
+ // SynaBun's own tabs in the profile are closed right before the stop: MoreLogin would reopen a frozen one.
21347
+ closeOwnTabs: (envId) => closeRecordedTabsBeforeRestart(envId),
21348
+ startLimit: (envId) => moreLogin.listStartCooldowns().find((held) => String(held.envId) === String(envId)) || null,
21349
+ closedOutside: (envId) => moreLogin.outsideCloseFor(String(envId)),
21350
+ running: async (envId) => !!moreLogin.runningDebugPort(await moreLogin.profileStatus(envId, { ..._moreLoginOpts(), timeout: 3000 })),
21351
+ stop: (envId) => moreLogin.stopProfile(envId, _moreLoginOpts()),
21352
+ // A new scheduled firing may start a profile closed outside SynaBun (lib/morelogin-outside-close.js); nothing else may.
21353
+ start: (envId, { scheduled = false } = {}) => moreLogin.startProfile(envId, { ..._moreLoginOpts(), requireCdp: true, profileLabel: moreLoginProfileLabel,
21354
+ ...(scheduled ? { allowAfterOutsideClose: 'schedule' } : {}) }),
21355
+ // SynaBun's own stop: no session there reads it as a close by someone else, and nobody "started" what is restarted.
21356
+ stopping: (envId) => { _moreLoginStoppedBySynaBun.set(String(envId), Date.now()); _moreLoginStartedBy.delete(String(envId)); },
21357
+ describe: (envId, name) => describeProfile(String(envId), name || _moreLoginEnvNames.get(String(envId)) || null),
21358
+ // `schedule:` messages go to the owner's pages only (broadcastSync keeps them from invite guests).
21359
+ announce: (notices) => broadcastSync({ type: 'schedule:launch-blocked', notices: notices.map(launchBlockNoticeOf).filter(Boolean) }),
21360
+ log: (line) => console.warn(`[morelogin] launch recovery: ${line}`),
21361
+ newId: () => randomBytes(8).toString('hex'),
21362
+ });
21363
+ /**
21364
+ * An attachment to profile `envId` from outside its acquisition queue (createBrowserSession: an agent's
21365
+ * browser_session create, POST /api/browser/sessions, the owner's page) while the launch recovery restarts it: it waits
21366
+ * for the restart (RESTART_ATTACH_WAIT_MS at most) and goes on, or is refused with MORELOGIN_PROFILE_RESTARTING. The
21367
+ * recovery's own retry comes after the restart and never waits here. Review of e8937e79, N1.
21368
+ */
21369
+ async function waitOutProfileRestart(envId) {
21370
+ const id = envId === null || envId === undefined ? '' : String(envId);
21371
+ if (!id || !_launchRecovery.restarting?.(id)) return;
21372
+ console.warn(`[morelogin] ${describeProfile(id, _moreLoginEnvNames.get(id) || null)} is being restarted by SynaBun: an attachment to it waits for the restart`);
21373
+ const started = Date.now();
21374
+ if (await _launchRecovery.whenRestarted(id)) return;
21375
+ throw _launchRecovery.restartingError(id, { name: _moreLoginEnvNames.get(id) || null, waitedMs: Date.now() - started });
21376
+ }
21377
+ /** A new tab in a session of a profile the launch recovery restarts is refused at once: the stop ends that session. */
21378
+ function profileRestartRefusal(session) {
21379
+ const id = session?._profileMode === 'morelogin' && session._mlEnvId ? String(session._mlEnvId) : '';
21380
+ return id && _launchRecovery.restarting?.(id) ? _launchRecovery.restartingError(id, { name: _moreLoginEnvNames.get(id) || null }) : null;
21381
+ }
21382
+
21383
+ // The notice the owner's pages show when launches keep failing on a profile (lib/launch-block-api.js,
21384
+ // public/shared/ui-launch-block-notice.js): asked when a page loads and when its sync socket connects.
21385
+ app.use('/api/system/launch-blocks', createLaunchBlockApi({
21386
+ recovery: () => _launchRecovery,
21387
+ guard: ownerRouteGuard({ isGuestRequest, port: PORT, allowedOrigins: publicWebOrigins, refuseCrossSite: true, ownOriginsOnly: true, requireOrigin: true }),
21388
+ // The dismissal carries this boot's page secret, as the crash notice's does (lib/page-session.js).
21389
+ pageSession: _pageSession,
21390
+ log: (line) => console.log(line),
21391
+ }));
21392
+
21238
21393
  /**
21239
21394
  * The owners of the saved choices are retired when the server starts (called once, as it starts listening, before any
21240
21395
  * request is answered): their ids are refused until their owner registers again (a side panel's new token, a brain's
@@ -21454,16 +21609,15 @@ function writeAntigravityMcpConfig(data) {
21454
21609
  function _writeMoreLoginMcpToAgents(entry) {
21455
21610
  const targets = [];
21456
21611
  const home = getHomePath();
21457
- try { // Claude Code (~/.claude.json)
21612
+ try { // Claude Code (~/.claude.json, its own file: only through lib/claude-global-config.js)
21458
21613
  const p = join(home, '.claude.json');
21459
21614
  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
21615
+ const moreLoginEntry = entry.url
21463
21616
  ? { type: entry.type || 'http', url: entry.url }
21464
21617
  : { 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');
21618
+ const written = updateClaudeGlobalConfig(p, (data) => ({ ...data, mcpServers: { ...(data.mcpServers && typeof data.mcpServers === 'object' ? data.mcpServers : {}), [MORELOGIN_MCP_KEY]: moreLoginEntry } }));
21619
+ if (written.ok) targets.push('Claude Code');
21620
+ else console.warn('[morelogin] Claude register skipped:', claudeGlobalConfigRefusal(written.reason));
21467
21621
  }
21468
21622
  } catch (e) { console.warn('[morelogin] Claude register failed:', e.message); }
21469
21623
  try { // Antigravity (~/.gemini/config/mcp_config.json, the CLI's and the app's): only where Antigravity has run
@@ -21504,12 +21658,16 @@ function _removeMoreLoginMcpFromAgents() {
21504
21658
  try {
21505
21659
  const p = join(home, '.claude.json');
21506
21660
  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
- }
21661
+ let had = false;
21662
+ const written = updateClaudeGlobalConfig(p, (data) => {
21663
+ if (!data.mcpServers || typeof data.mcpServers !== 'object' || !data.mcpServers[MORELOGIN_MCP_KEY]) return null;
21664
+ had = true;
21665
+ const mcpServers = { ...data.mcpServers };
21666
+ delete mcpServers[MORELOGIN_MCP_KEY];
21667
+ return { ...data, mcpServers };
21668
+ });
21669
+ if (written.ok && had) targets.push('Claude Code');
21670
+ else if (!written.ok) console.warn('[morelogin] Claude unregister skipped:', claudeGlobalConfigRefusal(written.reason));
21513
21671
  }
21514
21672
  } catch {}
21515
21673
  try {
@@ -24659,10 +24817,10 @@ app.post('/api/claude-code/mcp', (req, res) => {
24659
24817
  const claudeJsonPath = join(home, '.claude.json');
24660
24818
  const mcpUrl = `http://localhost:${PORT}/mcp`;
24661
24819
 
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');
24820
+ // Claude Code's own file (the sign-in's record, the flag that says where its login lives): a file it cannot read
24821
+ // as JSON is never replaced (lib/claude-global-config.js).
24822
+ const written = updateClaudeGlobalConfig(claudeJsonPath, (data) => mergeClaudeMcpConfig(data, mcpUrl), { create: true });
24823
+ if (!written.ok) return res.status(409).json({ ok: false, code: 'CLAUDE_CONFIG_UNSAFE', reason: written.reason, error: claudeGlobalConfigRefusal(written.reason) });
24666
24824
 
24667
24825
  // Force-allow the 7 SynaBun memory tools so CLI/PTY sessions skip per-call
24668
24826
  // permission prompts. Writes to ~/.claude/settings.json if present, otherwise
@@ -24683,12 +24841,15 @@ app.delete('/api/claude-code/mcp', (req, res) => {
24683
24841
  const home = process.env.USERPROFILE || process.env.HOME || '';
24684
24842
  const claudeJsonPath = join(home, '.claude.json');
24685
24843
  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
- }
24844
+ const written = updateClaudeGlobalConfig(claudeJsonPath, (data) => {
24845
+ if (!data.mcpServers || typeof data.mcpServers !== 'object' || !data.mcpServers.SynaBun) return null;
24846
+ const mcpServers = { ...data.mcpServers };
24847
+ delete mcpServers.SynaBun;
24848
+ const next = { ...data, mcpServers };
24849
+ if (Object.keys(mcpServers).length === 0) delete next.mcpServers;
24850
+ return next;
24851
+ });
24852
+ 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
24853
  res.json({ ok: true, message: 'SynaBun MCP removed from Claude.', rules: syncRulesWithMcp('claude', 'remove') });
24693
24854
  } catch (err) {
24694
24855
  res.status(500).json({ error: err.message });
@@ -28235,12 +28396,9 @@ async function internalMcpSync({ name, config, platforms }) {
28235
28396
  try {
28236
28397
  if (p === 'claudeCode') {
28237
28398
  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';
28399
+ const claudeEntry = buildClaudeMcpEntry(config);
28400
+ const written = updateClaudeGlobalConfig(claudeJsonPath, (data) => ({ ...data, mcpServers: { ...(data.mcpServers && typeof data.mcpServers === 'object' ? data.mcpServers : {}), [name]: claudeEntry } }), { create: true });
28401
+ results.claudeCode = written.ok ? 'ok' : `error: ${claudeGlobalConfigRefusal(written.reason)}`;
28244
28402
  } else if (p === 'opencode') {
28245
28403
  persistMcpToOpencodeConfig(name, config);
28246
28404
  results.opencode = 'ok';
@@ -28291,15 +28449,15 @@ app.delete('/api/mcp/sync', (req, res) => {
28291
28449
  try {
28292
28450
  if (p === 'claudeCode') {
28293
28451
  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';
28452
+ const written = updateClaudeGlobalConfig(claudeJsonPath, (data) => {
28453
+ if (!data.mcpServers || typeof data.mcpServers !== 'object' || !data.mcpServers[name]) return null;
28454
+ const mcpServers = { ...data.mcpServers };
28455
+ delete mcpServers[name];
28456
+ const next = { ...data, mcpServers };
28457
+ if (Object.keys(mcpServers).length === 0) delete next.mcpServers;
28458
+ return next;
28459
+ });
28460
+ results.claudeCode = written.ok || written.reason === 'missing' ? 'ok' : `error: ${claudeGlobalConfigRefusal(written.reason)}`;
28303
28461
 
28304
28462
  } else if (p === 'opencode') {
28305
28463
  if (mcpServersOf(readOpencodeConfigDocument(getOpencodeConfigPath()).config)[name]) {
@@ -28750,7 +28908,9 @@ app.get('/api/diagnostics/event-loop', async (req, res) => {
28750
28908
  let ptyHost;
28751
28909
  try { ptyHost = await terminalHost.stats({ reset }); }
28752
28910
  catch (err) { ptyHost = { error: err.message, mode: terminalHost.mode, restarts: terminalHost.restarts }; }
28753
- res.json({ ok: true, main, ptyHost });
28911
+ // How many secrets the scrubbers look for (lib/terminal-token-redaction.js) and what holds a live proof, by kind and
28912
+ // by the family of its id: numbers only, never an id or a value. A count that only grows is a leak.
28913
+ res.json({ ok: true, main, ptyHost, knownSecrets: knownSecretCount(), terminalTokens: { ..._terminalTokens.stats(), ..._terminalTokens.breakdown() } });
28754
28914
  });
28755
28915
 
28756
28916
  // ── CLI Config (custom CLI paths for terminal profiles) ──
@@ -33894,7 +34054,7 @@ async function findReusableBrowserSession(opts = {}) {
33894
34054
  return { id, session };
33895
34055
  } catch (error) {
33896
34056
  console.warn(`[browser] Existing session ${id} context is dead — destroying (${error.message})`);
33897
- await destroyBrowserSession(id).catch(() => {});
34057
+ await destroyBrowserSession(id, { retireOwnTabs: true }).catch(() => {});
33898
34058
  }
33899
34059
  }
33900
34060
  return null;
@@ -33983,17 +34143,20 @@ function loopBrowserLockKey(ownerKey, requestedBrowserSessionId, cfg) {
33983
34143
  *
33984
34144
  * Returns { browserSessionId, browserTabId } on success, or { error } on failure.
33985
34145
  */
33986
- async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, ownerKey, ownerType = 'loop', logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false }) {
34146
+ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, ownerKey, ownerType = 'loop', logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false, launch = null }) {
33987
34147
  if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(ownerKey)) {
33988
34148
  // takeOverTab: one of the owner's open tabs in the everyday browser (full control), named by browser_session create.
33989
34149
  try { return await extensionAdapter.acquire(ownerKey, ownerType, { adopt: takeOverTab || undefined }); }
33990
34150
  catch (error) { return extensionAdapter.describeError(error); }
33991
34151
  }
33992
34152
  const lockKey = loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig());
33993
- const acquired = await withLoopBrowserLock(lockKey, async () => {
34153
+ const acquired = await withLoopBrowserLock(lockKey, () => {
33994
34154
  // The browser this owner gets changed while it waited (the owner's settings, a requested session that went away):
33995
34155
  // it queues again for the right one, outside this turn.
33996
34156
  if (loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig()) !== lockKey) return { requeue: true };
34157
+ // One attempt: strategies 0 to 2 and the owner's tab. A failure on the profile's own browser carries `_launch`
34158
+ // (the profile and what failed), which acquireWithProfileRecovery reads to restart the profile and try once more.
34159
+ const attempt = async ({ onlyEnvId = null } = {}) => {
33997
34160
  let browserSessionId = null;
33998
34161
  let browserTabId = null;
33999
34162
  const ownerProp = ownerType === 'interactive' ? '_interactiveOwned' : '_loopOwned';
@@ -34013,6 +34176,19 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
34013
34176
  loopLog(ownerKey, logTag, 'ABORT: the run\'s MoreLogin profile is not on the owner\'s list of profiles agents may choose', { envId: pin.envId });
34014
34177
  return { error: pinRefused.error, code: pinRefused.code };
34015
34178
  }
34179
+ // The retry after a restart (acquireWithProfileRecovery `onlyEnvId`) runs in the profile that was restarted and in
34180
+ // no other: when the owner moved the run, or changed the default profile, during the restart, it is not tried again
34181
+ // at all (never another profile), and the launch that failed stays counted on the profile it ran on.
34182
+ if (onlyEnvId) {
34183
+ const runsOn = pin ? String(pin.envId) : (moreLoginDefault && moreLoginDefaultEnvId(policyCfg) ? String(moreLoginDefaultEnvId(policyCfg)) : null);
34184
+ if (runsOn !== String(onlyEnvId)) {
34185
+ loopLog(ownerKey, logTag, 'ABORT: the run\'s profile changed during the restart: the launch is not tried again in another profile', { restarted: String(onlyEnvId), now: runsOn });
34186
+ return {
34187
+ error: `The run's browser profile changed while SynaBun restarted ${describeProfile(String(onlyEnvId), _moreLoginEnvNames.get(String(onlyEnvId)) || null)} for it${runsOn ? ` (it is ${describeProfile(runsOn, _moreLoginEnvNames.get(runsOn) || null)} now)` : ''}: the launch was not tried again, because a retry runs only in the profile that was restarted. Its next launch runs in its profile as it is now.`,
34188
+ code: 'PROFILE_CHANGED_DURING_RESTART', _launch: { envId: String(onlyEnvId), profileChanged: true },
34189
+ };
34190
+ }
34191
+ }
34016
34192
  if (requestedBrowserSessionId) {
34017
34193
  const requested = browserSessions.get(requestedBrowserSessionId);
34018
34194
  const unfit = requested && !sessionServesRun(requested, policyCfg, ownerKey);
@@ -34028,7 +34204,10 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
34028
34204
  loopLog(ownerKey, logTag, 'strategy 0: pinned to requested browser', { browserSessionId });
34029
34205
  } catch (err) {
34030
34206
  loopLog(ownerKey, logTag, 'strategy 0 failed: requested browser unhealthy — destroying', { requestedBrowserSessionId, err: err.message });
34031
- await destroyBrowserSession(requestedBrowserSessionId).catch(() => {});
34207
+ // Only its current tab was asked: other runs' tabs may still be working (an upload under way), so only this
34208
+ // caller's tabs and the ones nobody owns are closed (retireFor); the others stay open, as before 2026-11-29
34209
+ // (review of 2026-11-29, finding 3).
34210
+ await destroyBrowserSession(requestedBrowserSessionId, { retireOwnTabs: true, retireFor: ownerKey }).catch(() => {});
34032
34211
  }
34033
34212
  } else {
34034
34213
  loopLog(ownerKey, logTag, 'strategy 0 skipped: requested browser not in registry', { requestedBrowserSessionId });
@@ -34091,8 +34270,11 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
34091
34270
  // it may not move to another profile (POST /api/morelogin/use answers 409 PROFILE_FAILED_NO_SWITCH) until that
34092
34271
  // profile connects again for it (below), the owner moves it, or it ends (lib/morelogin-profile-failures.js).
34093
34272
  let profileAdvice = '';
34273
+ // What acquireWithProfileRecovery reads: the profile that failed and how.
34274
+ let _launch = null;
34094
34275
  if (createError) {
34095
34276
  const own = pin || (moreLoginDefault && moreLoginDefaultEnvId(policyCfg) ? { envId: String(moreLoginDefaultEnvId(policyCfg)), name: null } : null);
34277
+ if (own) _launch = { envId: String(own.envId), name: own.name || _moreLoginEnvNames.get(String(own.envId)) || null, failure: createError };
34096
34278
  noteRunProfileFailure(ownerKey, own, createError);
34097
34279
  if (own && !createError.code) {
34098
34280
  profileAdvice = await stoppedProfileAdvice(own.envId, own.name || _moreLoginEnvNames.get(own.envId),
@@ -34124,6 +34306,7 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
34124
34306
  ...(createError?.code ? { code: createError.code, offenders: createError.offenders } : {}),
34125
34307
  ...(createError?.needsUser ? { needsUser: true } : {}),
34126
34308
  ...(createError?.resetAt ? { resetAt: createError.resetAt } : {}),
34309
+ ...(_launch ? { _launch } : {}),
34127
34310
  };
34128
34311
  }
34129
34312
 
@@ -34188,7 +34371,14 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
34188
34371
  } catch (err) {
34189
34372
  claimedSession?.[ownerProp]?.delete(ownerKey);
34190
34373
  loopLog(ownerKey, logTag, 'ABORT: could not create tab', { err: err.message, browserSessionId });
34191
- return { error: `Could not create a new browser tab: ${err.message}` };
34374
+ // A profile's browser that opens no tab: the recovery may restart it, after this session (which nobody else
34375
+ // works in then) has let go of it.
34376
+ const tabless = claimedSession._profileMode === 'morelogin' && claimedSession._mlEnvId ? {
34377
+ envId: String(claimedSession._mlEnvId), name: pin?.name || _moreLoginEnvNames.get(String(claimedSession._mlEnvId)) || null,
34378
+ failure: { error: err.message, ...(err.code ? { code: err.code } : {}) },
34379
+ release: () => destroyBrowserSession(browserSessionId, { retireOwnTabs: true }),
34380
+ } : null;
34381
+ return { error: `Could not create a new browser tab: ${err.message}`, ...(tabless ? { _launch: tabless } : {}) };
34192
34382
  }
34193
34383
 
34194
34384
  // Record ownerKey → tabId so getTargetPage() can route a tab-less call from this
@@ -34220,9 +34410,65 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
34220
34410
 
34221
34411
  // Connected to its profile: a failure of that profile noted earlier in this run is over (it may switch again).
34222
34412
  if (claimedSession._mlEnvId) noteRunProfileConnected(ownerKey, claimedSession._mlEnvId);
34223
- return { browserSessionId, browserTabId };
34413
+ return { browserSessionId, browserTabId, ...(claimedSession._mlEnvId ? { _launch: { envId: String(claimedSession._mlEnvId) } } : {}) };
34414
+ };
34415
+ return acquireWithProfileRecovery({ attempt, ownerKey, ownerType, logTag, scheduledFiring, launch, lockKey });
34224
34416
  });
34225
- return acquired?.requeue ? acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey, ownerType, logTag, scheduledFiring }) : acquired;
34417
+ return acquired?.requeue ? acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey, ownerType, logTag, scheduledFiring, launch }) : acquired;
34418
+ }
34419
+
34420
+ /**
34421
+ * One acquisition of a run's browser tab with the profile's own recovery (lib/morelogin-launch-recovery.js), inside
34422
+ * the profile's acquisition queue. `attempt()` is the acquisition itself; what it answers carries `_launch` (never
34423
+ * returned): the profile it ran in ({ envId }), and for a failure on that profile's browser also its name, what
34424
+ * failed (`failure`) and what must let go of the browser before a restart (`release`).
34425
+ *
34426
+ * A loop's acquisition (a scheduled launch, a loop launch, a run's recovery or create) that failed because the
34427
+ * network guard timed out or the profile's browser does not answer: the profile is stopped and started through
34428
+ * MoreLogin's local API (a local profile through its launcher) and the acquisition is tried ONCE more, unless another
34429
+ * automation holds a tab there, MoreLogin holds its start, or it was restarted recently; then the run fails with that
34430
+ * reason. A second failure fails the run. Never another profile, never Chrome, never the extension: both attempts are
34431
+ * the same acquisition, for the same profile. Every failed launch on a profile counts towards the owner's one notice;
34432
+ * a launch that works ends the count.
34433
+ */
34434
+ async function acquireWithProfileRecovery({ attempt, ownerKey, ownerType = 'loop', logTag = 'launch:browser', scheduledFiring = false, launch = null, lockKey = null }) {
34435
+ const bare = (result) => { if (result && typeof result === 'object') delete result._launch; return result; };
34436
+ let result = await attempt();
34437
+ let info = result?._launch || null;
34438
+ if (!result || result.requeue || !info?.envId) return bare(result);
34439
+ // The restart and the retry happen in the queue of the profile that failed (or the whole registry's): a failure of
34440
+ // another profile than the one whose queue this acquisition holds is never restarted from here.
34441
+ const inItsQueue = lockKey === null || lockKey === `ml:${info.envId}`;
34442
+ if (ownerType === 'loop' && result.error && info.failure && inItsQueue) {
34443
+ const recovery = await _launchRecovery.attempt({ ownerKey, envId: info.envId, name: info.name || null, failure: info.failure, scheduled: scheduledFiring === true, beforeStop: info.release || null });
34444
+ if (recovery.restarted) {
34445
+ loopLog(ownerKey, logTag, 'the profile was restarted to clear the failure: trying the acquisition once more', { envId: info.envId, kind: recovery.kind });
34446
+ // Only in the profile that was restarted (`onlyEnvId`): the owner may have changed the run's profile meanwhile.
34447
+ const retried = await attempt({ onlyEnvId: info.envId });
34448
+ if (!retried || retried.requeue) return bare(retried);
34449
+ if (retried._launch?.profileChanged) {
34450
+ // Not tried: the restart's own outcome stays as it is, and the failed launch counts on the profile it ran on.
34451
+ result.error = `${result.error} ${retried.error}`;
34452
+ result.code = retried.code;
34453
+ loopLog(ownerKey, logTag, 'the run\'s profile changed during the restart: no retry, the run fails', { envId: info.envId });
34454
+ } else {
34455
+ // Where the retry ran (its session's profile, which the attempt holds to `onlyEnvId`).
34456
+ const ranOn = retried._launch?.envId ? String(retried._launch.envId) : info.envId;
34457
+ const sentence = _launchRecovery.settled({ envId: info.envId, name: info.name || null, ownerKey, ok: !retried.error && ranOn === info.envId, error: retried._launch?.failure?.error || retried.error || null });
34458
+ if (retried.error && sentence) retried.error = `${retried.error} ${sentence}`;
34459
+ loopLog(ownerKey, logTag, retried.error ? 'the acquisition failed again after the restart: the run fails (no second restart)' : 'the acquisition works after the restart', { envId: ranOn });
34460
+ result = retried;
34461
+ info = { ...info, ...(retried._launch || {}), envId: ranOn };
34462
+ }
34463
+ } else if (recovery.kind) {
34464
+ loopLog(ownerKey, logTag, `the profile was not restarted (${recovery.reason})`, { envId: info.envId, kind: recovery.kind });
34465
+ if (recovery.sentence) result.error = `${result.error} ${recovery.sentence}`;
34466
+ if (recovery.needsUser) result.needsUser = true;
34467
+ }
34468
+ }
34469
+ if (!result.error) _launchRecovery.launchSucceeded(info.envId);
34470
+ else if (ownerType === 'loop' && info.failure) _launchRecovery.launchFailed({ envId: info.envId, name: info.name || null, failure: info.failure, launch });
34471
+ return bare(result);
34226
34472
  }
34227
34473
 
34228
34474
  /**
@@ -34266,8 +34512,8 @@ function moreLoginProfileLabel(envId, name = null) {
34266
34512
  * Backward-compatible loop wrapper around acquireSharedBrowserTab. Existing callers
34267
34513
  * pass { terminalSessionId } and expect loop-owned semantics.
34268
34514
  */
34269
- async function acquireLoopBrowserAndTab({ requestedBrowserSessionId = null, terminalSessionId, logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false }) {
34270
- return acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey: terminalSessionId, ownerType: 'loop', logTag, takeOverTab, scheduledFiring });
34515
+ async function acquireLoopBrowserAndTab({ requestedBrowserSessionId = null, terminalSessionId, logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false, launch = null }) {
34516
+ return acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey: terminalSessionId, ownerType: 'loop', logTag, takeOverTab, scheduledFiring, launch });
34271
34517
  }
34272
34518
 
34273
34519
  /**
@@ -36073,6 +36319,9 @@ async function createBrowserSession(options = {}) {
36073
36319
  const def = await moreLogin.ensureDefaultProfile(mlOpts);
36074
36320
  envId = def.id;
36075
36321
  }
36322
+ // SynaBun is restarting this profile to clear a launch that failed on it: its stop would cut this attachment
36323
+ // off. It waits for the restart, then goes on (or is refused with MORELOGIN_PROFILE_RESTARTING).
36324
+ await waitOutProfileRestart(envId);
36076
36325
  // requireCdp: a Firefox-type profile has no DevTools endpoint and is refused, before it is started when
36077
36326
  // MoreLogin says what it is up front.
36078
36327
  nativePreflightProfiles.add(String(envId));
@@ -36104,6 +36353,9 @@ async function createBrowserSession(options = {}) {
36104
36353
  attached = await moreLogin.attachProfileBrowser(
36105
36354
  chromium, endpoint,
36106
36355
  (cdpBrowser, cdpContext) => newSessionPage({ browser: cdpBrowser, context: cdpContext, _profileMode: 'morelogin' }),
36356
+ // Whose a tab is, for a page of this profile that never answers the network guard (an orphan tab of
36357
+ // SynaBun's is closed, every other one fails the session closed).
36358
+ ownTargetGuardOptions(envId),
36107
36359
  ); // fresh tab in the real profile; never substitute an incognito context
36108
36360
  } catch (attachError) {
36109
36361
  // MoreLogin lists the profile running, but its browser holds no profile (its window was closed and the
@@ -36118,6 +36370,8 @@ async function createBrowserSession(options = {}) {
36118
36370
  }
36119
36371
  }
36120
36372
  const { browser: cdpBrowser, context: cdpContext, page: cdpPage } = attached;
36373
+ // This first tab is SynaBun's own in that profile's browser, known by its target id from now on.
36374
+ await adoptProfileBrowser(envId, cdpBrowser, cdpContext, cdpPage);
36121
36375
  // A local profile's timezone on this first tab (every later tab gets it in newSessionPage, from the session).
36122
36376
  if (_localProfileInfo?.timezone) await applyPageTimezone(cdpContext, cdpPage, _localProfileInfo.timezone);
36123
36377
 
@@ -36820,6 +37074,8 @@ async function newSessionPage(session, { timeoutMs } = {}) {
36820
37074
  page = await session.context.newPage();
36821
37075
  }
36822
37076
  synabunOpenedPages.add(page);
37077
+ // Its DevTools target id is kept too, for a browser that outlives the session (noteOwnTab).
37078
+ await noteOwnTab(session, page);
36823
37079
  // A local profile's timezone (lib/local-profiles.js). Its Chrome is started with TZ, which Chrome on Windows does
36824
37080
  // not read: the tabs SynaBun opens there are told over DevTools too. The CDP session stays with the page (the
36825
37081
  // override ends when it detaches). Best effort: a tab without it still has the timezone of the profile's start.
@@ -36849,6 +37105,9 @@ const synabunOpenedPages = new WeakSet();
36849
37105
  * Returns { tabId, url, title }.
36850
37106
  */
36851
37107
  async function createSessionTab(session, sessionId, url = 'about:blank') {
37108
+ // A session of a profile SynaBun is restarting ends with the stop: no new tab is opened in it meanwhile.
37109
+ const restarting = profileRestartRefusal(session);
37110
+ if (restarting) throw restarting;
36852
37111
  const tabId = randomBytes(4).toString('hex');
36853
37112
  const activeEntry = session.tabs?.get(session.activeTabId);
36854
37113
  const shouldAdoptAsActive = !activeEntry || activeEntry.page?.isClosed?.();
@@ -37011,8 +37270,13 @@ async function recoverSessionTabPage(session, sessionId, tabId, reason = 'page b
37011
37270
  console.warn(`[browser] Failed during ${recoveryStage} for tab ${tabId} in session ${sessionId}: ${error.message}`);
37012
37271
  // One slow tab does not end the other runs' tabs (lib/browser-wedge-retire.js): while the session's other
37013
37272
  // tabs still answer, only this tab is retired; its owner's next call gets "Tab not found" and a new tab.
37273
+ // Its tabs are closed with the session only when that probe found nothing in it that answers: a session retired
37274
+ // without the probe (the tab changed meanwhile) or after a probe that found tabs answering only disconnects, as
37275
+ // before 2026-11-29, so another run's working tab is never closed (review of 2026-11-29).
37276
+ let nothingAnswers = false;
37014
37277
  if (!session._invalidating && browserSessions.get(sessionId) === session && session.tabs.get(tabId)?.page === oldPage) {
37015
37278
  const verdict = await decideFailedTabRecovery(session, tabId);
37279
+ nothingAnswers = verdict.action === 'retire-session';
37016
37280
  if (verdict.action === 'retire-tab' && !session._invalidating && browserSessions.get(sessionId) === session
37017
37281
  && session.tabs.get(tabId)?.page === oldPage) {
37018
37282
  unrouteScreenshotTab(session, sessionId, tabId, oldPage);
@@ -37032,7 +37296,9 @@ async function recoverSessionTabPage(session, sessionId, tabId, reason = 'page b
37032
37296
  // destroyBrowserSession removes the registry entry synchronously before
37033
37297
  // its first await. The next pinned MCP call will therefore use the
37034
37298
  // existing /api/loop/recover-browser path instead of reusing this context.
37035
- void destroyBrowserSession(sessionId).catch((destroyError) => {
37299
+ // Its own tabs go with it when nothing in it answers (retireOwnTabs): a tab that froze is closed, not left in
37300
+ // the browser.
37301
+ void destroyBrowserSession(sessionId, { retireOwnTabs: nothingAnswers }).catch((destroyError) => {
37036
37302
  console.warn(`[browser] Failed to retire invalidated session ${sessionId}: ${destroyError.message}`);
37037
37303
  });
37038
37304
  }
@@ -37207,6 +37473,8 @@ async function closeSessionTab(session, sessionId, tabId) {
37207
37473
 
37208
37474
  // Close the page, whatever the switch did: the tab has left the registry already
37209
37475
  try { await tabEntry.page.close(); } catch {}
37476
+ // A tab SynaBun recorded as its own leaves that record once its browser no longer lists it (noteOwnTabClosed).
37477
+ noteOwnTabClosed(session, tabEntry.page);
37210
37478
  console.log(`[browser] Tab ${tabId} closed in session ${sessionId} (remaining: ${session.tabs.size})`);
37211
37479
  if (switchError) throw switchError;
37212
37480
  }
@@ -37218,10 +37486,18 @@ async function closeSessionTab(session, sessionId, tabId) {
37218
37486
  * their Chrome over CDP) the tabs SynaBun opened for the session are closed
37219
37487
  * before the disconnect, `closingPage` (a last tab that has left the registry
37220
37488
  * already) included. Every other connect mode closes its whole browser anyway
37221
- * and is unchanged, and so is every other teardown (a dead or invalidated
37222
- * session, an idle or grace reap).
37489
+ * and is unchanged, and so is every other teardown (an idle or grace reap).
37490
+ * `retireOwnTabs` marks a session retired because it stopped answering (a
37491
+ * wedged tab whose session has nothing left that answers, a requested or
37492
+ * reusable session found dead): in a browser the user owns its own tabs are
37493
+ * closed by their DevTools target id, over a browser-level connection
37494
+ * (retireSessionOwnTabs), so a frozen tab is not left behind for the next
37495
+ * launch on that browser to trip over. `retireFor` (an owner key, or null for
37496
+ * the owner's page) narrows that to the tabs of that owner and the ones nobody
37497
+ * owns, for a retirement decided on one tab alone: another run's tabs stay
37498
+ * open, as they did before 2026-11-29 (retireSessionOwnTabs).
37223
37499
  */
37224
- async function destroyBrowserSession(sessionId, { closeOwnTabs = false, closingPage = null } = {}) {
37500
+ async function destroyBrowserSession(sessionId, { closeOwnTabs = false, closingPage = null, retireOwnTabs = false, retireFor = undefined } = {}) {
37225
37501
  const session = browserSessions.get(sessionId);
37226
37502
  if (session?._profileMode === 'extension') return extensionAdapter.destroy(sessionId);
37227
37503
  if (!session) return;
@@ -37233,7 +37509,10 @@ async function destroyBrowserSession(sessionId, { closeOwnTabs = false, closingP
37233
37509
  engagementScheduler.clear(sessionId);
37234
37510
  // From here on the tabs this close takes leave quietly: their close handlers switch to no
37235
37511
  // other tab and announce nothing, and a call that fails on one of them opens no replacement.
37236
- if (closeOwnTabs && (session._profileMode === 'cdp' || session._profileMode === 'morelogin') && !session._chromeProcess) {
37512
+ const userOwnedBrowser = (session._profileMode === 'cdp' || session._profileMode === 'morelogin') && !session._chromeProcess;
37513
+ // A retired session's own tabs are closed by target id (below); they leave as quietly as an explicit close's.
37514
+ const retiring = !closeOwnTabs && retireOwnTabs && userOwnedBrowser;
37515
+ if ((closeOwnTabs || retiring) && userOwnedBrowser) {
37237
37516
  session._tearingDown = true;
37238
37517
  }
37239
37518
 
@@ -37261,7 +37540,8 @@ async function destroyBrowserSession(sessionId, { closeOwnTabs = false, closingP
37261
37540
  // transport; it does not terminate the externally-owned Chromium process, and
37262
37541
  // every tab stays open (MoreLogin reopens them all at the profile's next start).
37263
37542
  // An explicit close therefore first closes the tabs SynaBun opened for the session.
37264
- if (session._tearingDown) await closeOwnTabsBeforeDisconnect(session, sessionId, closingPage);
37543
+ if (retiring) await retireSessionOwnTabs(session, sessionId, retireFor === undefined ? {} : { forOwner: retireFor });
37544
+ else if (session._tearingDown) await closeOwnTabsBeforeDisconnect(session, sessionId, closingPage);
37265
37545
  try { await session.browser.close(); } catch {}
37266
37546
  } else if (session._chromeProcess) {
37267
37547
  // Spawned Chrome process: disconnect Playwright, then kill Chrome
@@ -37335,8 +37615,14 @@ function closeOwnTabsBeforeDisconnect(session, sessionId, closingPage = null) {
37335
37615
  3_000,
37336
37616
  page === keep ? 'Emptying the last tab of the browser' : 'Closing a tab SynaBun opened',
37337
37617
  ).catch(() => {})));
37338
- const closed = own.filter((page) => page !== keep && page.isClosed?.()).length;
37618
+ const closedPages = own.filter((page) => page !== keep && page.isClosed?.());
37619
+ const closed = closedPages.length;
37339
37620
  const open = own.length - closed - (keep ? 1 : 0);
37621
+ // The records of the closed ones go now, while this connection can still ask the browser (bounded; what it
37622
+ // cannot confirm stays until the next attachment to that browser prunes it).
37623
+ if (closedPages.map((page) => noteOwnTabClosed(session, page)).some(Boolean)) {
37624
+ await withBrowserOperationDeadline(_ownTabCloses.confirm(ownTabBrowserOf(session, closedPages[0])), 2_500, 'Confirming the closed tabs').catch(() => {});
37625
+ }
37340
37626
  console.log(`[browser] Closed ${closed} tab(s) SynaBun opened in session ${sessionId} before disconnecting`
37341
37627
  + `${keep ? '; the last page of the browser was emptied (about:blank) instead' : ''}`
37342
37628
  + `${open ? `; ${open} not confirmed closed, may still be open` : ''}`);
@@ -37378,6 +37664,192 @@ async function otherOpenPageCount(session, own) {
37378
37664
  }
37379
37665
  }
37380
37666
 
37667
+ // ── The tabs SynaBun opened (synabunOpenedPages), by DevTools target id (lib/browser-own-targets.js) ──
37668
+ // For a browser that outlives its session. A Playwright page is gone with its session's connection; the tab is not.
37669
+ // The target id is what tells later, on a new connection or after a restart of the server, that a tab is SynaBun's
37670
+ // own: the network guard closes such a tab when it froze and no live session works in it (ownTargetGuardOptions), and
37671
+ // a session retired because it stopped answering closes its own tabs by it (retireSessionOwnTabs). Never a tab that
37672
+ // is not in here.
37673
+ const _ownTargets = createOwnTargetRegistry({
37674
+ file: resolve(LOOP_DATA_DIR, 'browser-own-targets.json'),
37675
+ log: (line) => console.warn(`[browser] ${line}`),
37676
+ // In use: a tab of a session that is still registered (a retired session left the registry before anything else).
37677
+ inUse: (page) => {
37678
+ for (const session of browserSessions.values()) {
37679
+ for (const entry of session.tabs?.values?.() || []) if (entry?.page === page) return true;
37680
+ }
37681
+ return false;
37682
+ },
37683
+ });
37684
+
37685
+ /**
37686
+ * Records the tab `page` as SynaBun's own in the browser `session` drives (a MoreLogin or local profile by its id,
37687
+ * the attached Chrome), by its DevTools target id. Best effort and bounded: a tab whose id could not be read is
37688
+ * never closed by its id later. Launched browsers end with their session and are not recorded.
37689
+ */
37690
+ async function noteOwnTab(session, page) {
37691
+ const key = ownTargetProfileKey({ profileMode: session?._profileMode, envId: session?._mlEnvId });
37692
+ if (!key || !page) return null;
37693
+ try {
37694
+ const targetId = await pageTargetId(session.context, page);
37695
+ if (targetId) {
37696
+ _ownTargets.note(key, targetId, { page });
37697
+ // Closed by anyone (the owner, the page itself, a close of SynaBun's): forgotten once its browser no longer lists
37698
+ // it. The page's close event alone is not enough: it also comes when the connection to the browser ends.
37699
+ const browser = ownTabBrowserOf(session, page);
37700
+ if (typeof page.once === 'function') page.once('close', () => { _ownTabCloses.seen(key, targetId, browser); });
37701
+ }
37702
+ return targetId || null;
37703
+ } catch { return null; }
37704
+ }
37705
+
37706
+ /** The Playwright browser a session's tab lives in: the connection its close is checked over. */
37707
+ function ownTabBrowserOf(session, page) {
37708
+ try { return session?.browser || session?.context?.browser?.() || page?.context?.()?.browser?.() || null; } catch { return null; }
37709
+ }
37710
+
37711
+ /**
37712
+ * The targets the browser `browser` has now, asked over its own Playwright connection (it is the browser the tab was
37713
+ * opened in), or null when it cannot be asked: disconnected, or no answer within `timeoutMs` per step.
37714
+ */
37715
+ async function listBrowserTargetIds(browser, { timeoutMs = 2_000 } = {}) {
37716
+ if (!browser || typeof browser.newBrowserCDPSession !== 'function' || browser.isConnected?.() === false) return null;
37717
+ let cdp = null;
37718
+ try {
37719
+ cdp = await withBrowserOperationDeadline(browser.newBrowserCDPSession(), timeoutMs, 'Opening a browser CDP session', { onLateResolve: (late) => late?.detach?.() });
37720
+ const { targetInfos = [] } = await withBrowserOperationDeadline(cdp.send('Target.getTargets'), timeoutMs, 'Listing the tabs of the browser');
37721
+ return targetInfos.map((target) => target.targetId);
37722
+ } catch { return null; } finally { if (cdp) cdp.detach().catch(() => {}); }
37723
+ }
37724
+
37725
+ // A recorded tab that was closed leaves the registry once its browser confirms it (lib/browser-own-targets.js
37726
+ // createOwnTabCloseWatch). A MoreLogin session is never reaped for idleness and lives for hours while loops open and
37727
+ // close tabs in it: without this, each closed tab stayed in browser-own-targets.json and in the page map until the
37728
+ // next new attachment to the profile, and a restart's close asked for tabs long gone.
37729
+ const _ownTabCloses = createOwnTabCloseWatch({
37730
+ registry: _ownTargets,
37731
+ list: (browser) => listBrowserTargetIds(browser),
37732
+ log: (line) => console.warn(`[browser] ${line}`),
37733
+ });
37734
+
37735
+ /** SynaBun closed the tab `page` of `session`: its entry goes once the browser no longer lists it. */
37736
+ function noteOwnTabClosed(session, page) {
37737
+ const key = ownTargetProfileKey({ profileMode: session?._profileMode, envId: session?._mlEnvId });
37738
+ const targetId = key && page ? _ownTargets.targetIdOf(page) : null;
37739
+ return targetId ? _ownTabCloses.seen(key, targetId, ownTabBrowserOf(session, page)) : false;
37740
+ }
37741
+
37742
+ /**
37743
+ * What the network guard of profile `envId` is told about a page whose target never answers
37744
+ * (lib/browser-network-guard.js registerBrowserNetworkEndpoint): whose tab it is, and that an orphan was closed.
37745
+ */
37746
+ function ownTargetGuardOptions(envId) {
37747
+ const key = ownTargetProfileKey({ profileMode: 'morelogin', envId });
37748
+ return {
37749
+ pageOwner: (targetInfo) => _ownTargets.classify(key, targetInfo?.targetId),
37750
+ onOrphanClosed: (targetInfo) => {
37751
+ _ownTargets.forget(targetInfo?.targetId);
37752
+ console.warn(`[browser] ${describeProfile(String(envId), _moreLoginEnvNames.get(String(envId)) || null)}: closed a frozen tab SynaBun had opened for a session that ended (target ${targetInfo?.targetId}); the profile's network protection could not be installed while it was open`);
37753
+ },
37754
+ };
37755
+ }
37756
+
37757
+ /**
37758
+ * SynaBun attached to the browser of profile `envId`: its first tab there is recorded as its own, and the tabs
37759
+ * recorded for that profile that its browser no longer has are forgotten (the profile was restarted since, or they
37760
+ * were closed). The second part runs on its own and never holds the session up.
37761
+ */
37762
+ async function adoptProfileBrowser(envId, browser, context, page) {
37763
+ const key = ownTargetProfileKey({ profileMode: 'morelogin', envId });
37764
+ await noteOwnTab({ context, _profileMode: 'morelogin', _mlEnvId: String(envId) }, page);
37765
+ void (async () => {
37766
+ let cdp = null;
37767
+ try {
37768
+ cdp = await withBrowserOperationDeadline(browser.newBrowserCDPSession(), 2_000, 'Opening a browser CDP session', { onLateResolve: (late) => late?.detach?.() });
37769
+ const { targetInfos = [] } = await withBrowserOperationDeadline(cdp.send('Target.getTargets'), 2_000, 'Listing the tabs of the browser');
37770
+ _ownTargets.prune(key, targetInfos.map((target) => target.targetId));
37771
+ } catch { /* kept until they expire */ } finally { if (cdp) cdp.detach().catch(() => {}); }
37772
+ })();
37773
+ }
37774
+
37775
+ /**
37776
+ * A session that is retired because it stopped answering (its browser stays open: a MoreLogin profile, the user's
37777
+ * Chrome): the tabs SynaBun opened for it are closed with the browser-level Target.closeTarget, which a frozen tab
37778
+ * cannot hold up, over a fresh connection first (the session's own may be what is stuck). Before 2026-11-29 such a
37779
+ * session only disconnected and its tabs stayed; a frozen one then failed every later launch on the profile. Only
37780
+ * tabs recorded as SynaBun's own, never the owner's; the browser keeps a window (closeOwnTargets). Bounded, never throws.
37781
+ */
37782
+ async function retireSessionOwnTabs(session, sessionId, { forOwner } = {}) {
37783
+ try {
37784
+ const key = ownTargetProfileKey({ profileMode: session._profileMode, envId: session._mlEnvId });
37785
+ if (!key) return null;
37786
+ // `forOwner` (a key, or null for the owner's page): a retirement decided on one tab alone closes only that caller's
37787
+ // tabs and the ones nobody owns, never another run's, which may still be working (review of 2026-11-29, finding 3).
37788
+ // An unowned tab of a session a page watches is the owner's working tab: it stays too.
37789
+ const owned = new Map();
37790
+ for (const [owner, tabId] of session._tabOwners || []) owned.set(tabId, [...(owned.get(tabId) || []), owner]);
37791
+ const closable = ([tabId]) => {
37792
+ if (forOwner === undefined) return true;
37793
+ const owners = owned.get(tabId) || [];
37794
+ if (owners.length === 0) return (session.clients?.size || 0) === 0;
37795
+ return owners.every((owner) => owner === forOwner);
37796
+ };
37797
+ const entries = [...(session.tabs?.entries() || [])].filter(closable);
37798
+ const pages = [...new Set(entries.map(([, entry]) => entry?.page))].filter((page) => page && synabunOpenedPages.has(page));
37799
+ const targetIds = pages.map((page) => _ownTargets.targetIdOf(page)).filter((id) => id && _ownTargets.owns(key, id));
37800
+ if (targetIds.length === 0) return null;
37801
+ const openers = [];
37802
+ // The port the session remembered may belong to another browser by now: what that one lists is trusted only when
37803
+ // it holds a tab recorded for this profile (closeOwnTargets `known`). The session's own connection is that browser.
37804
+ if (session._mlDebugPort) openers.push(() => connectGuardCdp(`http://127.0.0.1:${session._mlDebugPort}`, { timeoutMs: 3_000 }));
37805
+ openers.push({ open: () => session.browser.newBrowserCDPSession(), sameBrowser: true });
37806
+ const result = await closeOwnTargets(openers, targetIds, { known: _ownTargets.list(key), log: (line) => console.warn(`[browser] retiring session ${sessionId}: ${line}`) });
37807
+ for (const id of result.closed) _ownTargets.forget(id);
37808
+ // The empty tab that keeps the window is SynaBun's too: nothing works in it.
37809
+ if (result.placeholder) _ownTargets.note(key, result.placeholder);
37810
+ console.warn(`[browser] Retired session ${sessionId}: closed ${result.closed.length} of the ${targetIds.length} tab(s) SynaBun had opened in it`
37811
+ + `${result.placeholder ? '; an empty tab was opened first so the browser keeps its window' : ''}`
37812
+ + `${result.kept ? '; one stays open so the browser keeps its window' : ''}`
37813
+ + `${result.pending.length ? `; ${result.pending.length} not seen closed (the next launch on this browser closes a frozen one)` : ''}`
37814
+ + `${result.unverified?.length ? `; ${result.unverified.length} kept as SynaBun's: no browser that answered could be shown to be theirs` : ''}`
37815
+ + `${result.via === null && !result.unverified?.length ? `; the browser could not be reached (${result.error || 'no connection'})` : ''}`);
37816
+ return result;
37817
+ } catch (error) {
37818
+ console.warn(`[browser] Closing the tabs of retired session ${sessionId} failed: ${error.message}`);
37819
+ return null;
37820
+ }
37821
+ }
37822
+
37823
+ /**
37824
+ * The launch recovery restarts profile `envId` (lib/morelogin-launch-recovery.js `closeOwnTabs`): right before the
37825
+ * stop, every tab recorded as SynaBun's own in that profile is closed with the browser-level Target.closeTarget over
37826
+ * the profile's DevTools port. MoreLogin reopens a profile's tabs at its next start, under new target ids that nothing
37827
+ * knows as SynaBun's, so a frozen tab left open at the stop came straight back (review of 2026-11-29, finding 2). It
37828
+ * runs only after the recovery found no other automation and no page of the owner's in the profile; only recorded
37829
+ * tabs, never the owner's. The browser keeps a window (closeOwnTargets opens an empty tab first when SynaBun's are
37830
+ * its only ones): a browser left with no window closes itself on Windows, before SynaBun's stop is marked as its own,
37831
+ * and could be read as a close outside SynaBun. Bounded per step; the recovery bounds the whole and never waits on it.
37832
+ */
37833
+ async function closeRecordedTabsBeforeRestart(envId) {
37834
+ const key = ownTargetProfileKey({ profileMode: 'morelogin', envId });
37835
+ const targetIds = key ? _ownTargets.list(key) : [];
37836
+ if (targetIds.length === 0) return { asked: 0, closed: [], pending: [], kept: null, placeholder: null, error: null };
37837
+ let port = null;
37838
+ try { port = moreLogin.runningDebugPort(await moreLogin.profileStatus(envId, { ..._moreLoginOpts(), timeout: 3000 })); } catch { port = null; }
37839
+ if (!port) {
37840
+ for (const session of browserSessions.values()) if (sessionServesMoreLoginEnv(session, envId) && session._mlDebugPort) { port = session._mlDebugPort; break; }
37841
+ }
37842
+ if (!port) return { asked: targetIds.length, closed: [], pending: targetIds, kept: null, placeholder: null, error: 'the profile\'s DevTools port is not known' };
37843
+ // Only on the word of a browser that holds one of the tabs recorded there (closeOwnTargets `known`): a port that
37844
+ // belongs to another browser by now lists none of them, and nothing is then taken as closed or forgotten.
37845
+ const result = await closeOwnTargets([() => connectGuardCdp(`http://127.0.0.1:${port}`, { timeoutMs: 2_000 })], targetIds, {
37846
+ timeoutMs: 2_000, known: targetIds, log: (line) => console.warn(`[morelogin] launch recovery: ${describeProfile(String(envId), _moreLoginEnvNames.get(String(envId)) || null)}: ${line}`),
37847
+ });
37848
+ for (const id of result.closed) _ownTargets.forget(id);
37849
+ if (result.placeholder) _ownTargets.note(key, result.placeholder);
37850
+ return { asked: targetIds.length, ...result };
37851
+ }
37852
+
37381
37853
  // ── Who a browser request is (lib/terminal-tokens.js) ──
37382
37854
  // A run's X-Synabun-Terminal counts only with that run's terminal token (X-Synabun-Terminal-Token): a request that
37383
37855
  // names a run SynaBun gave a token to without it, with another one, or after the run ended is refused before any
@@ -41417,6 +41889,9 @@ process.on('exit', () => {
41417
41889
  try { flushWhiteboardSync(); } catch {}
41418
41890
  try { flushCostDataSync(); } catch {}
41419
41891
  try { memoryMap.flushSync(); } catch {}
41892
+ // The tabs SynaBun opened, by target id (lib/browser-own-targets.js): written behind, so a write still waiting is
41893
+ // done now. A crash that skips this loses only entries, never adds a wrong one.
41894
+ try { _ownTargets.flush(); } catch {}
41420
41895
  // The Assistant's session records (a rename among them): this handler runs before the Assistant's own
41421
41896
  // exit handler, which the SIGKILL below never lets run.
41422
41897
  try { _assistantRuntime?.flushIndex?.(); } catch {}