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
@@ -16,6 +16,23 @@
16
16
  // be installed stays paused and is retried; pages, frames, dedicated workers and
17
17
  // targets already running still fail closed for the whole context, and a faulted
18
18
  // context re-arms with a fresh attachment (recoverBrowserNetworkGuard).
19
+ //
20
+ // One exception to "never closes a target" (2026-11-29). A target that was already
21
+ // running when this client attached and never answers (a worker in `while (true)`,
22
+ // a frozen renderer) can never be protected, so it failed every later attachment to
23
+ // the profile: on 2026-11-28 two nested workers of a TikTok Studio upload tab, left
24
+ // behind by a retired session, failed every scheduled launch on that MoreLogin
25
+ // profile for 40 hours. When such a target's top-level page is a tab SynaBun opened
26
+ // that no live session works in (`pageOwner` answers 'orphan'), that page is closed
27
+ // with the browser-level Target.closeTarget, which needs no answer from its renderer
28
+ // and ends its frames and workers, and arming goes on. Every other page (a live
29
+ // session's tab, the owner's own tab, one nobody can place) still fails closed; the
30
+ // error then names the page and the kind of target, so the owner can find the tab.
31
+ // Measured in Chromium 147 (tests/browser-network-guard-orphan.browser.mjs): a worker
32
+ // in `while (true) {}`, in a synchronous request or in Atomics.wait never answers a
33
+ // NEW client's Target.setAutoAttach, but answers at once while a client that turned
34
+ // auto-attach on before it hung is still attached. So the session that opened the tab
35
+ // never sees the fault; the first attachment after that session has gone does.
19
36
  import { connectGuardCdp } from './browser-guard-cdp.js';
20
37
  const guards = new WeakMap();
21
38
  const endpoints = new WeakMap();
@@ -32,13 +49,35 @@ const TIMING = {
32
49
  quarantineRetryMs: [1000, 5000, 15000, 60000], // the last delay repeats while the worker exists
33
50
  rearmBackoffMs: [2000, 5000, 15000, 30000, 60000], // after a failed re-arm; the last repeats
34
51
  recoverTimeoutMs: 10000, // the longest a caller waits for one re-arm
52
+ orphanCloseMs: 5000, // how long a closed orphan tab may take to leave the browser
53
+ };
54
+ // Whose a top-level page is, as `pageOwner` answers it. Only an 'orphan' is ever closed.
55
+ const PAGE_OWNER_WORDS = {
56
+ live: 'a live SynaBun session works in that tab',
57
+ foreign: 'SynaBun did not open that tab (it is the owner\'s own)',
58
+ orphan: 'SynaBun opened that tab for a session that has ended',
59
+ unknown: 'SynaBun cannot tell whose tab that is',
35
60
  };
61
+ /** A page address as an error and a log name it: no query and no fragment (they can carry tokens). */
62
+ export function guardPageLabel(url) {
63
+ const text = typeof url === 'string' ? url : '';
64
+ try {
65
+ const parsed = new URL(text);
66
+ return (/^https?:$/.test(parsed.protocol) ? `${parsed.origin}${parsed.pathname}` : `${parsed.protocol}${parsed.pathname}`).slice(0, 200);
67
+ } catch { return text ? text.split(/[?#]/)[0].slice(0, 200) : 'an unnamed page'; }
68
+ }
36
69
  export const NETWORK_GUARD_FAULT_EVENT = 'synabun-network-guard-fault';
37
70
  export const NETWORK_GUARD_RECOVERED_EVENT = 'synabun-network-guard-recovered';
38
71
 
39
- /** Register only externally owned Chromium contexts with an existing endpoint. */
40
- export function registerBrowserNetworkEndpoint(context, endpoint, { connect = connectGuardCdp, timing } = {}) {
41
- endpoints.set(context, { endpoint, connect, timing: { ...TIMING, ...timing } });
72
+ /**
73
+ * Register only externally owned Chromium contexts with an existing endpoint.
74
+ * `pageOwner(targetInfo)` says whose a top-level page is: 'orphan' (a tab SynaBun opened that no live session works
75
+ * in), 'live' (a live session's tab), 'foreign' (not SynaBun's: the owner's own tab) or 'unknown'; sync or async.
76
+ * Without it every page is 'unknown' and nothing is ever closed. `onOrphanClosed(targetInfo)` is told of each orphan
77
+ * tab the guard closed.
78
+ */
79
+ export function registerBrowserNetworkEndpoint(context, endpoint, { connect = connectGuardCdp, timing, pageOwner = null, onOrphanClosed = null } = {}) {
80
+ endpoints.set(context, { endpoint, connect, timing: { ...TIMING, ...timing }, pageOwner, onOrphanClosed });
42
81
  }
43
82
 
44
83
  export function usesNativeBrowserNetworkGuard(context) { return endpoints.has(context); }
@@ -50,6 +89,8 @@ class GuardLink {
50
89
  this.children = new Map();
51
90
  this.installing = new Set();
52
91
  this.timers = new Set();
92
+ this.reclaims = new Map(); // page targetId → the one attempt of this link to close that orphan page
93
+ this.destroyed = new Set(); // targetIds the browser reported destroyed (Target.targetDestroyed) on this link
53
94
  this.fault = null;
54
95
  this.closed = false;
55
96
  }
@@ -154,6 +195,92 @@ class GuardLink {
154
195
  this.resume(child);
155
196
  });
156
197
  }
198
+ /** The top-level page a target lives in (itself, for a page), or null: a service or shared worker has none. */
199
+ topPage(child) {
200
+ let node = child;
201
+ while (node?.parent && node.parent !== this.root) node = node.parent;
202
+ return node?.target?.type === 'page' && node.parent === this.root ? node : null;
203
+ }
204
+ /**
205
+ * A target that was already running and whose protection nobody answered: whose page it is in, and that page
206
+ * closed when it is an orphan. One attempt per page for this link, shared by every target under it (a frozen tab
207
+ * can hold dozens of workers). → { closed, owner, page: { targetId, url, type } | null }. Never rejects.
208
+ */
209
+ reclaim(child) {
210
+ const page = this.topPage(child);
211
+ if (!page) return Promise.resolve({ closed: false, owner: 'unknown', page: null });
212
+ const targetId = page.target.targetId;
213
+ if (!this.reclaims.has(targetId)) {
214
+ this.reclaims.set(targetId, this.closeOrphan(page).catch(() => ({ closed: false, owner: 'unknown', page: { targetId, url: page.target.url || '', type: 'page' } })));
215
+ }
216
+ return this.reclaims.get(targetId);
217
+ }
218
+ async closeOrphan(page) {
219
+ const targetId = page.target.targetId;
220
+ // Asked of the browser, not of the page: it answers for a frozen renderer too, and with the address of now.
221
+ let info = page.target;
222
+ try { info = (await this.root.send('Target.getTargetInfo', { targetId })).targetInfo || info; } catch { /* as attached */ }
223
+ const { pageOwner, onOrphanClosed } = endpoints.get(this.guard.context) || {};
224
+ let owner = 'unknown';
225
+ try {
226
+ const said = typeof pageOwner === 'function' ? await pageOwner({ ...info }) : null;
227
+ if (said === 'orphan' || said === 'live' || said === 'foreign') owner = said;
228
+ } catch { owner = 'unknown'; }
229
+ const out = { closed: false, owner, page: { targetId, url: info.url || '', type: info.type || 'page' } };
230
+ if (owner !== 'orphan' || this.closed) return out;
231
+ console.warn(`[browser-network-guard] closing the orphan tab ${guardPageLabel(info.url)} (target ${targetId}): a target in it does not answer, SynaBun opened it and no live session works in it`);
232
+ try { await this.root.send('Target.closeTarget', { targetId }); }
233
+ catch (error) {
234
+ if (!gone(error) && !/No target with given id/i.test(error.protocolMessage || error.message)) {
235
+ console.error(`[browser-network-guard] the orphan tab ${guardPageLabel(info.url)} (target ${targetId}) could not be closed: ${error.message}`);
236
+ return out;
237
+ }
238
+ }
239
+ // Closed when the browser says so: Target.targetDestroyed seen for it, or Target.getTargetInfo no longer knows it.
240
+ // The detach of the page's own session (Target.detachedFromTarget) comes with a close too, often first, but a
241
+ // session also detaches for other reasons while its tab runs on (and its worker with it): a detach alone is no
242
+ // close, it only makes the browser be asked at once. Each question is bounded by what is left of orphanCloseMs, so
243
+ // a browser that does not answer cannot hold the arming up; past it the page is not closed and arming fails closed.
244
+ const until = Date.now() + this.guard.timing.orphanCloseMs;
245
+ for (;;) {
246
+ if (this.closed) return out;
247
+ let left = this.destroyed.has(targetId);
248
+ if (!left) {
249
+ const wait = Math.max(1, until - Date.now());
250
+ let timer;
251
+ const unanswered = new Promise(resolve => { timer = setTimeout(() => resolve('unanswered'), wait); timer.unref?.(); });
252
+ const asked = this.root.send('Target.getTargetInfo', { targetId }).then(
253
+ reply => (reply?.targetInfo ? 'open' : 'gone'),
254
+ probe => (/No target with given id/i.test(probe.protocolMessage || probe.message) ? 'gone' : 'unanswered'),
255
+ );
256
+ const said = await Promise.race([asked, unanswered]).finally(() => clearTimeout(timer));
257
+ left = said === 'gone' || this.destroyed.has(targetId);
258
+ }
259
+ if (left) break;
260
+ if (Date.now() >= until) {
261
+ console.error(`[browser-network-guard] the orphan tab ${guardPageLabel(info.url)} (target ${targetId}) is still open ${this.guard.timing.orphanCloseMs} ms after it was closed`);
262
+ return out;
263
+ }
264
+ await new Promise(resolve => { const timer = setTimeout(resolve, 50); timer.unref?.(); });
265
+ }
266
+ out.closed = true;
267
+ console.warn(`[browser-network-guard] closed the orphan tab ${guardPageLabel(info.url)} (target ${targetId}); arming goes on`);
268
+ try { onOrphanClosed?.({ ...info }); } catch { /* the registry's own business */ }
269
+ return out;
270
+ }
271
+ /** The fail-closed error of a running target nobody answered for, naming its page and what kind of target it is. */
272
+ named(error, child, outcome) {
273
+ // A worker fails with its parent's own error when the parent could not be configured: named once, as the parent's.
274
+ if (error.pageOwner) return error;
275
+ const where = outcome.page;
276
+ const label = where ? guardPageLabel(where.url) : null;
277
+ const kind = child.target.type === 'page' ? 'the page itself' : `a ${child.target.type} in it`;
278
+ error.message = where
279
+ ? `${error.message}. The target that does not answer is in the tab ${label} (${kind}); ${PAGE_OWNER_WORDS[outcome.owner]}${outcome.owner === 'orphan' ? ' and could not close it' : ', so SynaBun did not close it'}`
280
+ : `${error.message}. The target that does not answer is a ${child.target.type}${child.target.url ? ` of ${guardPageLabel(child.target.url)}` : ''} with no tab of its own to close`;
281
+ Object.assign(error, { pageOwner: outcome.owner, ...(where ? { pageUrl: label, pageTargetId: where.targetId } : {}) });
282
+ return error;
283
+ }
157
284
  async ownsDocument(frameId) {
158
285
  try {
159
286
  const { targetInfo } = await this.root.send('Target.getTargetInfo', { targetId: frameId });
@@ -204,6 +331,9 @@ class GuardLink {
204
331
  } else if (method === 'Target.detachedFromTarget') {
205
332
  this.children.get(event.sessionId)?.close();
206
333
  this.children.delete(event.sessionId);
334
+ } else if (method === 'Target.targetDestroyed') {
335
+ // Only an orphan close waits for this (closeOrphan); kept for the pages it asked about, so it stays small.
336
+ if (event?.targetId && this.reclaims.has(event.targetId)) this.destroyed.add(event.targetId);
207
337
  } else if (method === 'Fetch.requestPaused') {
208
338
  if (!parent) return; // event queued before this target's detach arrived
209
339
  void this.request(parent, event).catch(error => {
@@ -234,6 +364,13 @@ class GuardLink {
234
364
  } catch (error) {
235
365
  if (await this.vanished(child, error)) return;
236
366
  if (waiting && OWN_FETCH_WORKERS.has(child.target.type)) { this.quarantine(child, error); return; }
367
+ // A target that already ran and never answered: no retry protects it. When its page is an orphan tab of
368
+ // SynaBun's, the page is closed (its workers and frames end with it) and arming goes on.
369
+ if (!waiting && error?.timedOut) {
370
+ const outcome = await this.reclaim(child);
371
+ if (outcome.closed || this.closed) return;
372
+ throw this.named(error, child, outcome);
373
+ }
237
374
  // Pages, frames, dedicated workers and anything already running fail closed.
238
375
  throw error;
239
376
  }
@@ -0,0 +1,350 @@
1
+ // ── The tabs SynaBun opened in a browser the user owns, by DevTools target id ──
2
+ //
3
+ // In a MoreLogin profile (or the user's Chrome over CDP) the browser outlives every SynaBun session: closing a
4
+ // session only disconnects, and each tab stays. A tab SynaBun opened is its own to close; every other tab is the
5
+ // owner's and is never touched. server.js knew its own tabs by their Playwright page (synabunOpenedPages), which
6
+ // is gone the moment the session's connection is: on 2026-11-28 a session was retired because nothing in it
7
+ // answered, its frozen TikTok Studio tab stayed in MoreLogin profile P-1, and nothing could tell later that the tab
8
+ // was SynaBun's. Every scheduled launch on that profile then failed for 40 hours on that tab's workers
9
+ // (lib/browser-network-guard.js).
10
+ //
11
+ // This registry keeps the DevTools target id of every tab SynaBun opens, per profile, in memory and in
12
+ // DATA_HOME/data/browser-own-targets.json (a tab outlives a server restart too). A target id is the browser's own
13
+ // name for a tab and lasts as long as that browser runs; a profile that was stopped and started gives every tab a
14
+ // new one, so a tab the browser restored is never mistaken for SynaBun's. Two things read it:
15
+ // - the network guard, for a page whose target never answers (`classify`): 'orphan' (SynaBun's tab, no live
16
+ // session works in it: closed), 'live' (a live session's tab: left alone) or 'foreign' (not SynaBun's: left
17
+ // alone);
18
+ // - the retirement of a session that stopped answering (`closeOwnTargets`), which closes the session's own tabs
19
+ // with the browser-level Target.closeTarget, the one close a frozen renderer cannot hold up.
20
+ // Nothing here ever closes a target that is not recorded as SynaBun's.
21
+ //
22
+ // An entry goes when its tab is seen gone: SynaBun closed it, or its page reported its close, and the browser no
23
+ // longer lists its target (`createOwnTabCloseWatch`); the guard closed it as an orphan; a new attachment finds it gone
24
+ // (`prune`). A close event alone never forgets an entry: a page also reports a close when the connection to its
25
+ // browser ends, and its tab stays open. The file is written behind (`OWN_TARGETS_WRITE_DELAY_MS`) and flushed at a
26
+ // stop: what a crash loses is an entry (that tab is then the owner's as far as SynaBun can tell, the safe side),
27
+ // never a wrong one.
28
+
29
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
30
+ import { dirname } from 'node:path';
31
+
32
+ /** Entries kept at most (the oldest go first: such a tab is then the owner's as far as SynaBun can tell). */
33
+ export const OWN_TARGETS_MAX = 1000;
34
+ /** An entry older than this is dropped: no browser keeps a target that long without a restart of the profile. */
35
+ export const OWN_TARGET_MAX_AGE_MS = 7 * 24 * 60 * 60_000;
36
+ /** A tab opened this recently counts as in use: it may not be in its session's registry yet. */
37
+ export const OWN_TARGET_SETUP_GRACE_MS = 2 * 60_000;
38
+ /** How long a change waits before the file is written: tabs opened together are one write, not one each. */
39
+ export const OWN_TARGETS_WRITE_DELAY_MS = 250;
40
+ /** When a recorded tab's page closed, the browser is asked after these delays whether its target is gone. */
41
+ export const OWN_TAB_CLOSE_CHECKS_MS = Object.freeze([250, 1_000, 5_000]);
42
+
43
+ const ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
44
+ const KEY_RE = /^[A-Za-z0-9_:.-]{1,160}$/;
45
+
46
+ /** The registry key of a browser: a MoreLogin (or local) profile by its id, else the one attached Chrome. */
47
+ export function ownTargetProfileKey({ profileMode = null, envId = null } = {}) {
48
+ if (envId !== null && envId !== undefined && String(envId)) return `ml:${String(envId)}`;
49
+ return profileMode === 'cdp' ? 'cdp' : null;
50
+ }
51
+
52
+ /**
53
+ * @param {object} [opts]
54
+ * @param {string|null} [opts.file] where the registry is kept (none: memory only)
55
+ * @param {(page: object) => boolean} [opts.inUse] whether a live session works in this Playwright page now
56
+ */
57
+ export function createOwnTargetRegistry({ file = null, now = Date.now, log = () => {}, inUse = () => false, max = OWN_TARGETS_MAX, maxAgeMs = OWN_TARGET_MAX_AGE_MS, setupGraceMs = OWN_TARGET_SETUP_GRACE_MS, writeDelayMs = OWN_TARGETS_WRITE_DELAY_MS } = {}) {
58
+ /** targetId → { profile, at }, oldest first. */
59
+ let rows = null;
60
+ /** The pages this process opened: targetId → page, and back. */
61
+ const pages = new Map();
62
+ const ids = new WeakMap();
63
+
64
+ const fresh = (row) => row && Number.isFinite(Number(row.at)) && now() - Number(row.at) < maxAgeMs;
65
+
66
+ function read() {
67
+ const out = new Map();
68
+ try {
69
+ if (!file || !existsSync(file)) return out;
70
+ const data = JSON.parse(readFileSync(file, 'utf-8'));
71
+ const list = data && typeof data === 'object' && data.targets && typeof data.targets === 'object' ? Object.entries(data.targets) : [];
72
+ for (const [id, row] of list.filter(([id, row]) => ID_RE.test(id) && fresh(row) && KEY_RE.test(String(row.profile || ''))).sort((a, b) => Number(a[1].at) - Number(b[1].at))) {
73
+ out.set(id, { profile: String(row.profile), at: Number(row.at) });
74
+ }
75
+ } catch (error) {
76
+ log(`the tabs SynaBun opened could not be read (${error?.message || error}): none is known as its own, so none is closed`);
77
+ }
78
+ return out;
79
+ }
80
+
81
+ // Written behind: one write for the changes of `writeDelayMs`, through a temporary file and a rename (a reader never
82
+ // sees half a file). The file is always the registry as it was at one moment, so a crash before a write loses the
83
+ // latest entries (safe: such a tab is never closed by its id) and never adds one.
84
+ let writeTimer = null;
85
+ function writeNow() {
86
+ if (writeTimer) { clearTimeout(writeTimer); writeTimer = null; }
87
+ if (!file || !rows) return;
88
+ const temp = `${file}.${process.pid}.tmp`;
89
+ try {
90
+ mkdirSync(dirname(file), { recursive: true });
91
+ writeFileSync(temp, JSON.stringify({ version: 1, targets: Object.fromEntries(rows) }), { mode: 0o600 });
92
+ renameSync(temp, file);
93
+ } catch (error) {
94
+ try { rmSync(temp, { force: true }); } catch { /* nothing to clean */ }
95
+ log(`a tab SynaBun opened was not saved (${error?.message || error}): it is known as its own until the server restarts`);
96
+ }
97
+ }
98
+ function write() {
99
+ if (!file) return;
100
+ if (!(writeDelayMs > 0)) { writeNow(); return; }
101
+ if (writeTimer) return;
102
+ writeTimer = setTimeout(writeNow, writeDelayMs);
103
+ writeTimer.unref?.();
104
+ }
105
+
106
+ const loaded = () => (rows ||= read());
107
+ const drop = (id) => { const page = pages.get(id); pages.delete(id); if (page) ids.delete(page); return loaded().delete(id); };
108
+
109
+ return {
110
+ /** SynaBun opened the tab `targetId` in the browser `profileKey` (its Playwright `page`, when this process has it). */
111
+ note(profileKey, targetId, { page = null } = {}) {
112
+ const key = String(profileKey || '');
113
+ const id = String(targetId || '');
114
+ if (!KEY_RE.test(key) || !ID_RE.test(id)) return false;
115
+ const map = loaded();
116
+ map.delete(id); // newest last
117
+ map.set(id, { profile: key, at: now() });
118
+ while (map.size > max) drop(map.keys().next().value);
119
+ if (page && typeof page === 'object') { pages.set(id, page); ids.set(page, id); }
120
+ write();
121
+ return true;
122
+ },
123
+ /** The target id noted for a page this process opened, or null. */
124
+ targetIdOf(page) {
125
+ return (page && typeof page === 'object' && ids.get(page)) || null;
126
+ },
127
+ /** Whether `targetId` is recorded as a tab SynaBun opened in `profileKey`. */
128
+ owns(profileKey, targetId) {
129
+ const row = loaded().get(String(targetId || ''));
130
+ return !!row && fresh(row) && row.profile === String(profileKey || '');
131
+ },
132
+ /**
133
+ * Whose the tab is: 'foreign' (not recorded as SynaBun's in this browser), 'live' (a live session works in its
134
+ * page, or it was opened moments ago and may not be registered yet) or 'orphan' (SynaBun's, and nothing works in
135
+ * it: its session was retired, or it is left from before a restart of the server).
136
+ */
137
+ classify(profileKey, targetId) {
138
+ const id = String(targetId || '');
139
+ const row = loaded().get(id);
140
+ if (!row || !fresh(row) || row.profile !== String(profileKey || '')) return 'foreign';
141
+ const page = pages.get(id);
142
+ if (!page) return 'orphan';
143
+ let used = false;
144
+ try { used = inUse(page) === true; } catch { used = true; } // a doubt keeps the tab
145
+ return used || now() - row.at < setupGraceMs ? 'live' : 'orphan';
146
+ },
147
+ /** The tab is gone (closed, and seen closed): forgotten. Returns whether it was known. */
148
+ forget(targetId) {
149
+ const known = drop(String(targetId || ''));
150
+ if (known) write();
151
+ return known;
152
+ },
153
+ /**
154
+ * The browser `profileKey` holds exactly the targets `present` now: entries of that browser it no longer has
155
+ * are dropped (the profile was restarted, or the tabs were closed). Returns how many went.
156
+ */
157
+ prune(profileKey, present) {
158
+ const key = String(profileKey || '');
159
+ const have = new Set([...(present || [])].map(String));
160
+ let gone = 0;
161
+ for (const [id, row] of [...loaded()]) {
162
+ if (row.profile === key && !have.has(id)) { drop(id); gone += 1; }
163
+ }
164
+ if (gone) write();
165
+ return gone;
166
+ },
167
+ /** Every tab recorded for `profileKey`: [targetId], oldest first. */
168
+ list(profileKey) {
169
+ const key = String(profileKey || '');
170
+ return [...loaded()].filter(([, row]) => row.profile === key && fresh(row)).map(([id]) => id);
171
+ },
172
+ /** A write that is still waiting is done now (the server stops). Never throws. */
173
+ flush() {
174
+ if (writeTimer) writeNow();
175
+ },
176
+ /** Whether a write is waiting (tests). */
177
+ get writePending() { return writeTimer !== null; },
178
+ };
179
+ }
180
+
181
+ /**
182
+ * Forgets a recorded tab once it is seen gone. `seen(profileKey, targetId, browser)` is called when SynaBun closed the
183
+ * tab, or its page reported its close; `list(browser)` asks that browser, over the session's own connection (so it is
184
+ * the browser the tab was opened in), which targets it has now, and answers null when it cannot be asked (the
185
+ * connection ended, it did not answer). An entry is forgotten only when the browser answered and no longer lists the
186
+ * target: a page reports a close too when the connection to its browser ends, and the tab is then still open. A target
187
+ * still listed is asked about again after each delay of `checksMs`, then kept (the next attachment to that browser
188
+ * prunes what is gone). The checks of one browser are made together. Never throws.
189
+ */
190
+ export function createOwnTabCloseWatch({ registry, list, checksMs = OWN_TAB_CLOSE_CHECKS_MS, log = () => {} } = {}) {
191
+ if (!registry || typeof list !== 'function') throw new Error('createOwnTabCloseWatch needs the registry and a way to list the targets of a browser');
192
+ /** browser → { ids: Map<targetId, { key, step }>, timer } */
193
+ const waiting = new Map();
194
+ const delays = (Array.isArray(checksMs) && checksMs.length ? checksMs : OWN_TAB_CLOSE_CHECKS_MS).map((ms) => Math.max(0, Number(ms) || 0));
195
+
196
+ function schedule(browser, batch) {
197
+ if (batch.timer) return;
198
+ const next = Math.min(...[...batch.ids.values()].map((entry) => delays[Math.min(entry.step, delays.length - 1)]));
199
+ batch.timer = setTimeout(() => { batch.timer = null; void check(browser); }, next);
200
+ batch.timer.unref?.();
201
+ }
202
+
203
+ async function check(browser) {
204
+ const batch = waiting.get(browser);
205
+ if (!batch) return 0;
206
+ if (batch.timer) { clearTimeout(batch.timer); batch.timer = null; }
207
+ waiting.delete(browser);
208
+ let present = null;
209
+ try { present = await list(browser); } catch { present = null; }
210
+ // The browser could not be asked: nothing is known to be gone, so nothing is forgotten.
211
+ if (!Array.isArray(present)) return 0;
212
+ const have = new Set(present.map(String));
213
+ let gone = 0;
214
+ const again = new Map();
215
+ for (const [id, entry] of batch.ids) {
216
+ if (!registry.owns(entry.key, id)) continue; // forgotten meanwhile
217
+ if (!have.has(id)) { if (registry.forget(id)) gone += 1; continue; }
218
+ if (entry.step + 1 < delays.length) again.set(id, { key: entry.key, step: entry.step + 1 });
219
+ else log(`tab ${id} reported its close and its browser still lists it: it stays known as SynaBun's`);
220
+ }
221
+ if (again.size) {
222
+ const merged = waiting.get(browser) || { ids: new Map(), timer: null };
223
+ for (const [id, entry] of again) if (!merged.ids.has(id)) merged.ids.set(id, entry);
224
+ waiting.set(browser, merged);
225
+ schedule(browser, merged);
226
+ }
227
+ return gone;
228
+ }
229
+
230
+ return {
231
+ /** The tab `targetId` of `profileKey` was closed, or its page said so: checked against `browser` shortly. */
232
+ seen(profileKey, targetId, browser) {
233
+ const key = String(profileKey || '');
234
+ const id = String(targetId || '');
235
+ if (!browser || !key || !id || !registry.owns(key, id)) return false;
236
+ const batch = waiting.get(browser) || { ids: new Map(), timer: null };
237
+ if (!batch.ids.has(id)) batch.ids.set(id, { key, step: 0 });
238
+ waiting.set(browser, batch);
239
+ schedule(browser, batch);
240
+ return true;
241
+ },
242
+ /** Check `browser`'s closed tabs now (before its connection ends). → how many were forgotten. */
243
+ confirm(browser) {
244
+ return waiting.has(browser) ? check(browser) : Promise.resolve(0);
245
+ },
246
+ /** How many closed tabs wait for their check (tests). */
247
+ pending() { return [...waiting.values()].reduce((sum, batch) => sum + batch.ids.size, 0); },
248
+ };
249
+ }
250
+
251
+ // The browser's own pages that do not count as a tab that keeps its window open: extension and DevTools pages and
252
+ // the browser's own UI (server.js otherOpenPageCount reads the same way).
253
+ const windowTab = (target) => target?.type === 'page' && !target.subtype
254
+ && !/^(?:chrome-extension|devtools):|^chrome(?:-untrusted)?:\/\/[^/]*\.top-chrome\b/i.test(target.url || '');
255
+
256
+ const within = (promise, ms, what) => {
257
+ let timer;
258
+ return Promise.race([
259
+ Promise.resolve(promise),
260
+ new Promise((_, fail) => { timer = setTimeout(() => fail(new Error(`${what} timed out`)), ms); timer.unref?.(); }),
261
+ ]).finally(() => clearTimeout(timer));
262
+ };
263
+
264
+ /**
265
+ * Close the tabs `targetIds` of one browser with the browser-level Target.closeTarget (it asks nothing of a tab's
266
+ * renderer, so a frozen tab closes too). `openers`: ways to a browser-level CDP client ({ send(method, params),
267
+ * detach() }), tried in order until one lists the browser's targets; a session that stopped answering is given a
268
+ * fresh connection first and its own second.
269
+ *
270
+ * The browser keeps a window: when the tabs to close are its only ones, an empty tab is opened first (in the
271
+ * background); when that fails, the last of them stays open and is reported as `kept`. A tab the browser no longer
272
+ * has counts as closed, but only on the word of a browser shown to be the one the tabs were opened in: an opener
273
+ * marked `{ open, sameBrowser: true }` (the session's own connection), or one whose browser lists at least one of
274
+ * `targetIds` or of `known` (other tabs recorded for that browser). A DevTools port can belong to another browser
275
+ * by now (the profile was restarted on another port, another program took it): there SynaBun's ids are all absent,
276
+ * and that says nothing. Such an opener is passed over, and when no opener can be trusted the ids are reported as
277
+ * `unverified`, neither closed nor forgotten. Bounded (`timeoutMs` per step) and never throws.
278
+ * → { closed: [id], pending: [id] (asked, not seen gone), unverified: [id] (no browser shown to be theirs answered),
279
+ * kept: id|null, placeholder: id|null, via: index|null, error }
280
+ */
281
+ export async function closeOwnTargets(openers, targetIds, { timeoutMs = 3000, keepWindow = true, known = [], log = () => {} } = {}) {
282
+ const wanted = [...new Set((targetIds || []).map(String).filter((id) => ID_RE.test(id)))];
283
+ const out = { closed: [], pending: [], unverified: [], kept: null, placeholder: null, via: null, error: null };
284
+ if (wanted.length === 0) return out;
285
+ const evidence = new Set([...wanted, ...(known || []).map(String)]);
286
+ const list = async (cdp) => (await within(cdp.send('Target.getTargets'), timeoutMs, 'listing the tabs of the browser')).targetInfos || [];
287
+ let untrusted = false;
288
+ for (const [index, opener] of (openers || []).entries()) {
289
+ const open = typeof opener === 'function' ? opener : opener?.open;
290
+ const sameBrowser = typeof opener === 'object' && opener?.sameBrowser === true;
291
+ if (typeof open !== 'function') continue;
292
+ let cdp = null;
293
+ try {
294
+ let late = null;
295
+ const opening = Promise.resolve().then(open);
296
+ opening.then((client) => { if (late) Promise.resolve().then(() => client?.detach?.()).catch(() => {}); }, () => {});
297
+ try { cdp = await within(opening, timeoutMs, 'connecting to the browser'); } catch (error) { late = true; throw error; }
298
+ if (!cdp || typeof cdp.send !== 'function') throw new Error('no browser-level connection');
299
+ const before = await list(cdp);
300
+ const present = new Set(before.map((target) => target.targetId));
301
+ if (!sameBrowser && ![...evidence].some((id) => present.has(id))) {
302
+ // None of SynaBun's tabs of this browser is there: another browser answers, or every one is gone. In doubt the
303
+ // entries stay (a new attachment to the profile prunes them on its own connection).
304
+ untrusted = true;
305
+ log(`the browser reached by connection ${index + 1} lists none of the ${evidence.size} tab(s) SynaBun recorded for it: it may be another browser, so nothing is taken as closed on its word`);
306
+ continue;
307
+ }
308
+ out.via = index;
309
+ const stillOpen = wanted.filter((id) => present.has(id));
310
+ out.closed.push(...wanted.filter((id) => !present.has(id)));
311
+ let closing = stillOpen;
312
+ if (keepWindow && stillOpen.length && before.filter((target) => windowTab(target) && !stillOpen.includes(target.targetId)).length === 0) {
313
+ try {
314
+ const made = await within(cdp.send('Target.createTarget', { url: 'about:blank', background: true }), timeoutMs, 'opening an empty tab');
315
+ out.placeholder = made?.targetId || null;
316
+ } catch (error) { log(`no empty tab could be opened to keep the window (${error?.message || error})`); }
317
+ if (!out.placeholder) { out.kept = stillOpen.at(-1); closing = stillOpen.slice(0, -1); }
318
+ }
319
+ await Promise.all(closing.map((targetId) => within(cdp.send('Target.closeTarget', { targetId }), timeoutMs, 'closing a tab').catch((error) => {
320
+ if (!/No target with given id/i.test(error?.protocolMessage || error?.message || '')) log(`tab ${targetId} was not confirmed closed (${error?.message || error})`);
321
+ })));
322
+ // Gone when the browser no longer lists it: a close is asynchronous, and a frozen tab takes a moment.
323
+ let left = closing;
324
+ const until = Date.now() + timeoutMs;
325
+ while (left.length) {
326
+ let after = null;
327
+ try { after = new Set((await list(cdp)).map((target) => target.targetId)); } catch { break; }
328
+ left = left.filter((id) => after.has(id));
329
+ if (!left.length || Date.now() >= until) break;
330
+ await new Promise((resolve) => { const timer = setTimeout(resolve, 100); timer.unref?.(); });
331
+ }
332
+ out.closed.push(...closing.filter((id) => !left.includes(id)));
333
+ out.pending = left;
334
+ out.error = null;
335
+ return out;
336
+ } catch (error) {
337
+ out.error = error?.message || String(error);
338
+ if (out.via !== null) { out.pending = wanted.filter((id) => !out.closed.includes(id) && id !== out.kept); return out; }
339
+ } finally {
340
+ if (cdp) Promise.resolve().then(() => cdp.detach?.()).catch(() => {});
341
+ }
342
+ }
343
+ if (untrusted) {
344
+ out.unverified = wanted;
345
+ out.error = 'no browser that answered could be shown to be the one these tabs were opened in';
346
+ return out;
347
+ }
348
+ out.pending = wanted;
349
+ return out;
350
+ }
@@ -1,4 +1,5 @@
1
1
  import { redactProviderSecrets } from './provider-panel-api-key-auth.js';
2
+ import { timeBlockingWork } from './loop-stall.js';
2
3
  import { applyClaudeLaunchEnv, CLAUDE_CREDENTIAL_ENV } from './claude-accounts.js';
3
4
  import { claudeStallSeconds } from './claude-stall-policy.js';
4
5
  import { detectProject as memoryProject } from '../../mcp-server/dist/config.js';
@@ -769,6 +770,10 @@ export class ClaudeSession {
769
770
  try { token = deps.terminalTokens.rotate(this.synabunOwnerKey) || null; } catch { token = null; }
770
771
  if (token) {
771
772
  this._terminalToken = token;
773
+ // The registry holds a proof for this tab from now on, whatever a later start does (one without the SynaBun
774
+ // server resets _terminalToken above and mints nothing): destroy() revokes by this, so that proof never
775
+ // outlives the tab as a secret the scrubbers keep looking for.
776
+ this._terminalTokenIssued = true;
772
777
  options.mcpServers.SynaBun.headers[TERMINAL_TOKEN_HEADER_NAME] = `\${${TERMINAL_TOKEN_ENV_NAME}}`;
773
778
  options.env = { ...options.env, [TERMINAL_TOKEN_ENV_NAME]: token };
774
779
  }
@@ -922,7 +927,9 @@ export class ClaudeSession {
922
927
  // client — its late results would corrupt the new query's turn accounting.
923
928
  if (this.q !== q) break;
924
929
  this.lastEventTime = Date.now();
925
- try { this._translate(m); } catch (err) { log('translate error:', err.message); }
930
+ // One SDK message translated, redacted and sent on, on the server's own thread: timed by name, so a stall
931
+ // of the event loop names it (lib/loop-stall.js).
932
+ try { timeBlockingWork('claude:sdk-message', () => this._translate(m)); } catch (err) { log('translate error:', err.message); }
926
933
  }
927
934
  // Generator ended (input closed / process exit). If a turn was in flight
928
935
  // and this wasn't a deliberate teardown, surface it.
@@ -3360,7 +3367,11 @@ export class ClaudeSession {
3360
3367
  // grace-reap once no owners remain. Best-effort, in-process on the NI side.
3361
3368
  try { deps.releaseBrowserOwner?.(this.synabunOwnerKey); } catch {}
3362
3369
  // The tab's terminal token ends with its session (nothing may act as it from now on).
3363
- if (this.panel && this._terminalToken) { try { deps.terminalTokens?.revoke?.(this.synabunOwnerKey); } catch {} this._terminalToken = null; }
3370
+ if (this.panel && (this._terminalToken || this._terminalTokenIssued)) {
3371
+ try { deps.terminalTokens?.revoke?.(this.synabunOwnerKey); } catch {}
3372
+ this._terminalToken = null;
3373
+ this._terminalTokenIssued = false;
3374
+ }
3364
3375
  _allSessions.delete(this);
3365
3376
  }
3366
3377
  }