synabun 2.2.1 → 2.2.2

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 (149) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +1 -1
  3. package/hooks/claude-code/pre-websearch.mjs +4 -1
  4. package/hooks/claude-code/prompt-submit.mjs +7 -0
  5. package/lib/release-scan.mjs +23 -10
  6. package/lib/virustotal.mjs +143 -39
  7. package/mcp-server/dist/http.d.ts +19 -0
  8. package/mcp-server/dist/http.d.ts.map +1 -1
  9. package/mcp-server/dist/http.js +55 -13
  10. package/mcp-server/dist/http.js.map +1 -1
  11. package/mcp-server/dist/index.d.ts.map +1 -1
  12. package/mcp-server/dist/index.js +14 -9
  13. package/mcp-server/dist/index.js.map +1 -1
  14. package/mcp-server/dist/services/browser-route-flow.d.ts +118 -0
  15. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -0
  16. package/mcp-server/dist/services/browser-route-flow.js +339 -0
  17. package/mcp-server/dist/services/browser-route-flow.js.map +1 -0
  18. package/mcp-server/dist/services/desktop-client.js +2 -2
  19. package/mcp-server/dist/services/desktop-client.js.map +1 -1
  20. package/mcp-server/dist/services/identity.d.ts +66 -3
  21. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  22. package/mcp-server/dist/services/identity.js +61 -4
  23. package/mcp-server/dist/services/identity.js.map +1 -1
  24. package/mcp-server/dist/services/neural-interface.d.ts +112 -1
  25. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  26. package/mcp-server/dist/services/neural-interface.js +555 -61
  27. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  28. package/mcp-server/dist/tools/bluesky.d.ts +20 -7
  29. package/mcp-server/dist/tools/bluesky.d.ts.map +1 -1
  30. package/mcp-server/dist/tools/bluesky.js +147 -45
  31. package/mcp-server/dist/tools/bluesky.js.map +1 -1
  32. package/mcp-server/dist/tools/browser-advanced.d.ts +11 -2
  33. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  34. package/mcp-server/dist/tools/browser-advanced.js +131 -18
  35. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  36. package/mcp-server/dist/tools/browser-cheatsheet.d.ts +2 -0
  37. package/mcp-server/dist/tools/browser-cheatsheet.d.ts.map +1 -1
  38. package/mcp-server/dist/tools/browser-cheatsheet.js +3 -0
  39. package/mcp-server/dist/tools/browser-cheatsheet.js.map +1 -1
  40. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  41. package/mcp-server/dist/tools/morelogin.js +4 -2
  42. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  43. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  44. package/mcp-server/dist/tools/youtube/helpers.d.ts +1 -0
  45. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  46. package/mcp-server/dist/tools/youtube/helpers.js +1 -1
  47. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  48. package/mcp-server/package-lock.json +2 -2
  49. package/mcp-server/package.json +1 -1
  50. package/mcp-server/src/http.ts +58 -12
  51. package/mcp-server/src/index.ts +15 -9
  52. package/mcp-server/src/services/browser-route-flow.ts +402 -0
  53. package/mcp-server/src/services/desktop-client.ts +2 -2
  54. package/mcp-server/src/services/identity.ts +80 -4
  55. package/mcp-server/src/services/neural-interface.ts +572 -70
  56. package/mcp-server/src/tools/bluesky.ts +164 -51
  57. package/mcp-server/src/tools/browser-advanced.ts +121 -17
  58. package/mcp-server/src/tools/browser-cheatsheet.ts +3 -0
  59. package/mcp-server/src/tools/morelogin.ts +4 -2
  60. package/mcp-server/src/tools/youtube/helpers.ts +2 -2
  61. package/neural-interface/i18n/en.json +24 -0
  62. package/neural-interface/i18n/pt-BR.json +24 -0
  63. package/neural-interface/lib/assistant-api.js +64 -23
  64. package/neural-interface/lib/assistant-catalog.js +20 -2
  65. package/neural-interface/lib/assistant-dispatch.js +27 -1
  66. package/neural-interface/lib/assistant-persona.js +1 -0
  67. package/neural-interface/lib/assistant-runtime.js +15 -1
  68. package/neural-interface/lib/assistant-tools.js +10 -1
  69. package/neural-interface/lib/browser-automation-routes.js +84 -0
  70. package/neural-interface/lib/browser-execution.js +16 -3
  71. package/neural-interface/lib/browser-owner.js +48 -0
  72. package/neural-interface/lib/browser-session-close.js +84 -0
  73. package/neural-interface/lib/browser-start-handoff.js +202 -0
  74. package/neural-interface/lib/browser-tool-policy.js +21 -4
  75. package/neural-interface/lib/browser-wedge-retire.js +64 -0
  76. package/neural-interface/lib/claude-agent-bridge.js +36 -1
  77. package/neural-interface/lib/claude-background-hold.js +239 -0
  78. package/neural-interface/lib/exec-loop-command.js +8 -0
  79. package/neural-interface/lib/http-guards.js +11 -6
  80. package/neural-interface/lib/loop-logger.js +6 -1
  81. package/neural-interface/lib/mcp-external-servers.js +37 -10
  82. package/neural-interface/lib/native-loop-providers.js +121 -10
  83. package/neural-interface/lib/native-loop-runtime.js +112 -11
  84. package/neural-interface/lib/owner-authority.js +113 -37
  85. package/neural-interface/lib/page-session.js +81 -23
  86. package/neural-interface/lib/peer-identity.js +263 -43
  87. package/neural-interface/lib/provider-panel-api-key-auth.js +7 -2
  88. package/neural-interface/lib/pty-host/core.js +36 -0
  89. package/neural-interface/lib/pty-host/protocol.js +2 -0
  90. package/neural-interface/lib/skills/api-v2.js +13 -2
  91. package/neural-interface/lib/skills/creation-api.js +3 -1
  92. package/neural-interface/lib/skills/evals-api.js +5 -1
  93. package/neural-interface/lib/social-write-pacing.js +151 -0
  94. package/neural-interface/lib/terminal-token-redaction.js +293 -0
  95. package/neural-interface/lib/terminal-tokens.js +359 -0
  96. package/neural-interface/lib/worker-mcp-channel.js +45 -10
  97. package/neural-interface/package-lock.json +2 -2
  98. package/neural-interface/package.json +1 -1
  99. package/neural-interface/public/shared/agy/agy-render.js +41 -1
  100. package/neural-interface/public/shared/agy/agy-styles.js +5 -0
  101. package/neural-interface/public/shared/api.js +1 -0
  102. package/neural-interface/public/shared/assistant/asst-computer.js +47 -2
  103. package/neural-interface/public/shared/assistant/asst-limit-wait.js +3 -1
  104. package/neural-interface/public/shared/assistant/asst-panel.js +7 -3
  105. package/neural-interface/public/shared/assistant/asst-render.js +10 -4
  106. package/neural-interface/public/shared/assistant/asst-styles.js +2 -1
  107. package/neural-interface/public/shared/cdx/cdx-render.js +73 -7
  108. package/neural-interface/public/shared/cdx/cdx-tabs.js +3 -3
  109. package/neural-interface/public/shared/cp/cp-agents.js +8 -0
  110. package/neural-interface/public/shared/cp/cp-permissions.js +6 -2
  111. package/neural-interface/public/shared/cp/cp-rehydrate.js +25 -1
  112. package/neural-interface/public/shared/cp/cp-tasks-model.js +33 -0
  113. package/neural-interface/public/shared/judgments-log-origins.js +29 -0
  114. package/neural-interface/public/shared/ocp-v2/ocp-v2-automation-ownership.js +23 -0
  115. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +13 -0
  116. package/neural-interface/public/shared/ocp-v2/ocp-v2-icons.js +3 -1
  117. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +4 -2
  118. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +6 -86
  119. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +5 -2
  120. package/neural-interface/public/shared/owner-access.js +134 -0
  121. package/neural-interface/public/shared/owner-authority-view.js +92 -0
  122. package/neural-interface/public/shared/page-session.js +143 -14
  123. package/neural-interface/public/shared/poll-backoff.js +59 -0
  124. package/neural-interface/public/shared/settings/settings-data.js +6 -1
  125. package/neural-interface/public/shared/settings/settings-kit.js +11 -3
  126. package/neural-interface/public/shared/settings/settings-shell.js +7 -0
  127. package/neural-interface/public/shared/shown-children.js +72 -0
  128. package/neural-interface/public/shared/static-bg-state.js +22 -0
  129. package/neural-interface/public/shared/styles.css +101 -7
  130. package/neural-interface/public/shared/synabun-tools.js +173 -0
  131. package/neural-interface/public/shared/tool-heartbeat.js +43 -0
  132. package/neural-interface/public/shared/tool-list-picker.js +3 -1
  133. package/neural-interface/public/shared/tool-list-view.js +23 -4
  134. package/neural-interface/public/shared/ui-automation-studio.js +8 -1
  135. package/neural-interface/public/shared/ui-claude-panel.js +159 -29
  136. package/neural-interface/public/shared/ui-judgments.js +37 -10
  137. package/neural-interface/public/shared/ui-navbar.js +6 -0
  138. package/neural-interface/public/shared/ui-owner-access.js +191 -0
  139. package/neural-interface/public/shared/ui-owner-authority.js +162 -0
  140. package/neural-interface/public/shared/ui-sessions.js +45 -16
  141. package/neural-interface/public/shared/ui-settings.js +86 -15
  142. package/neural-interface/public/shared/ui-terminal.js +15 -7
  143. package/neural-interface/public/shared/ui-tutorial-preview.js +4 -0
  144. package/neural-interface/public/shared/ui-update.js +3 -0
  145. package/neural-interface/public/shared/ui-whiteboard.js +4 -0
  146. package/neural-interface/public/shared/window-keys.js +38 -0
  147. package/neural-interface/server.js +1160 -205
  148. package/npm-shrinkwrap.json +2 -2
  149. package/package.json +1 -1
@@ -23,11 +23,25 @@
23
23
  // • allowed: everything else — the owner's own browser (Safari's WebKit networking, Chrome's network service,
24
24
  // Firefox, Arc…), the SynaBun app's window, the owner's own terminal.
25
25
  //
26
- // No allowlist: nothing the owner uses has to be known for it to keep working. When the lookup itself cannot run
27
- // (netstat or ps missing, slow or unreadable, another platform) the answer is "unknown" and the caller keeps its
28
- // rules from before this module (the sandbox stays the boundary for workers): the owner is never locked out by a
29
- // failed lookup. A client socket that is no longer in the table when it is looked up (the client closed it before
30
- // its request was read) is refused: a browser waiting for its answer still holds its socket.
26
+ // No allowlist: nothing the owner uses has to be known for it to keep working. A client socket that is no longer in
27
+ // the table when it is looked up (the client closed it before its request was read) is refused: a browser waiting for
28
+ // its answer still holds its socket.
29
+ //
30
+ // When there is no answer, two cases are told apart (the verdict's `kind`, peerAuthority() reads it for every caller):
31
+ // • unsupported — the lookup does not run on this server: another platform than macOS, or SYNABUN_PEER_IDENTITY=off
32
+ // (the owner's explicit choice, logged at start). The callers keep their rules from before this module, so
33
+ // Windows and Linux work as they always did;
34
+ // • failed — the lookup should have run here (macOS) and could not: netstat or ps missing, denied (a server started
35
+ // inside a sandbox), slow past the cap, an output this parser does not read, a connection with no address, or an
36
+ // error in the lookup itself. That is no proof of who is asking, so the request gets no owner authority: no page
37
+ // secret, no brain credential, and the owner's writes, reads and sockets are answered 503 PEER_UNAVAILABLE (the
38
+ // app's pages and every other read still load). A failure that may pass (a timeout, a busy system) is tried once
39
+ // more at once and is kept on its connection for a moment only (NEGATIVE_TTL_MS), so an open tab recovers by
40
+ // itself; a client that left is never kept. The server probes netstat and ps once at start (probe()), keeps the
41
+ // state for GET /api/health (`ownerAuthority`: ok / degraded / unsupported / off), says the change in one loud log
42
+ // line, and the page shows a banner while it is degraded (public/shared/ui-owner-authority.js).
43
+ // Only a machine elsewhere on the network ('remote', below) still keeps the rules from before without a lookup: what to
44
+ // do about a LAN client is a separate decision (TODO(peer-identity-remote): decide the LAN policy).
31
45
  //
32
46
  // Cheap: one `netstat -anvl -p tcp` (~4 ms on macOS, one sysctl) per NEW connection, shared by every lookup that is
33
47
  // waiting when it starts; the process table (`ps`, ~20 ms) is read only for a process not seen in the last few
@@ -42,7 +56,9 @@
42
56
  // of a brain's environment (`ps -E` cannot be blocked between processes of one user) and sent through a relay is
43
57
  // dropped from the request, which then has no brain authority.
44
58
  //
45
- // macOS only (netstat's process:pid column, ps -E). Elsewhere every answer is "unknown" (the rules from before).
59
+ // macOS only (netstat's process:pid column, ps -E). Elsewhere every answer is "unknown, unsupported" (the rules from
60
+ // before). On macOS a credential whose check could not run (the lookup failed, or ps -E could not be read) is dropped
61
+ // too: nothing proves the brain sent it.
46
62
  // Parsers and the classifier are pure and unit-tested (tests/peer-identity.test.mjs); the reader takes an injected
47
63
  // `run` so tests drive it with fixed tables.
48
64
 
@@ -66,7 +82,11 @@ const LSOF = '/usr/sbin/lsof';
66
82
  export const lsofCwdArgs = (pid) => ['-a', '-p', String(pid), '-d', 'cwd', '-Fn'];
67
83
  const TABLE_TIMEOUT_MS = 1500;
68
84
  const PS_TIMEOUT_MS = 2000;
69
- const LOOKUP_CAP_MS = 2500;
85
+ /** The longest one attempt at a lookup may keep a request waiting (a failure that may pass gets one more attempt). */
86
+ export const LOOKUP_CAP_MS = 2500;
87
+ /** How long a failed lookup is kept on its connection: a burst of requests is not looked up again each, an open tab
88
+ * is soon. */
89
+ export const NEGATIVE_TTL_MS = 2000;
70
90
  const PS_SNAPSHOT_TTL_MS = 2000;
71
91
  // A process's parents and command line do not change while it lives (a parent that exits leaves it to launchd, which
72
92
  // only ever takes an agent or a browser out of the chain, never puts one in): kept half an hour, checked against
@@ -534,6 +554,65 @@ export function envHoldsCredential(env, credential) {
534
554
  }
535
555
  }
536
556
 
557
+ // ── Verdicts without an answer, and what a verdict means for the owner's authority ─
558
+
559
+ /** The lookup does not run on this server (another platform, SYNABUN_PEER_IDENTITY=off): the callers' rules from before. */
560
+ export function unsupportedPeerVerdict(reason = 'peer lookup is not available here') {
561
+ return { status: 'unknown', kind: 'unsupported', retryable: false, reason: String(reason) };
562
+ }
563
+ /** The lookup should have run here (macOS) and could not: no owner authority for the request (503 PEER_UNAVAILABLE). */
564
+ export function failedPeerVerdict(reason = 'the lookup failed', { retryable = false } = {}) {
565
+ return { status: 'unknown', kind: 'failed', retryable: retryable === true, reason: String(reason) };
566
+ }
567
+
568
+ const TRANSIENT_CODES = new Set(['ETIMEDOUT', 'EAGAIN', 'EMFILE', 'ENFILE', 'ENOMEM', 'EBUSY', 'EINTR']);
569
+ /**
570
+ * Whether a failure of netstat / ps may pass by itself: its own timeout ended it (execFile kills it and says
571
+ * `killed` / `signal`), or the system was short of something for a moment (no process slot, no file descriptor).
572
+ * A program that is missing (ENOENT), denied (EPERM, EACCES: a sandbox) or answers what cannot be read does not.
573
+ */
574
+ export function isTransientLookupError(error) {
575
+ if (!error || typeof error !== 'object') return false;
576
+ if (error.killed === true || (typeof error.signal === 'string' && error.signal)) return true;
577
+ return TRANSIENT_CODES.has(String(error.code || ''));
578
+ }
579
+ /** A short reason for a failed program ("timed out", "EPERM", "netstat named no processes…"). */
580
+ function failureText(error) {
581
+ if (error && typeof error === 'object' && (error.killed === true || (typeof error.signal === 'string' && error.signal))) return 'timed out';
582
+ return String(error?.code || error?.message || error || 'failed');
583
+ }
584
+
585
+ /**
586
+ * What a request's peer verdict means for the owner's authority: the one reading lib/page-session.js,
587
+ * lib/owner-authority.js and lib/assistant-api.js share. Pure, never throws.
588
+ * { decision: 'before' } never looked up, the lookup does not run here (unsupported: another platform or
589
+ * SYNABUN_PEER_IDENTITY=off), or a machine elsewhere on the network: the caller's rules
590
+ * from before decide
591
+ * { decision: 'allowed', self } the owner's own process (or this server itself)
592
+ * { decision: 'refused', code: 'PEER_REFUSED', kind, why, pid, name, gone } never the owner's authority (the caller
593
+ * still applies its own exceptions, such as an agent's own call)
594
+ * { decision: 'unavailable', code: 'PEER_UNAVAILABLE', retryable, reason } macOS, the lookup failed: no owner
595
+ * authority, and the caller answers 503 (a verdict of a shape this does not know is
596
+ * taken as this one: never the rules from before by accident)
597
+ */
598
+ export function peerAuthority(verdict) {
599
+ if (verdict === undefined || verdict === null) return { decision: 'before', reason: 'not looked up' };
600
+ if (typeof verdict !== 'object') return { decision: 'unavailable', code: 'PEER_UNAVAILABLE', retryable: false, reason: 'the lookup gave no answer' };
601
+ if (verdict.status === 'ok') {
602
+ if (!verdict.refuse) return { decision: 'allowed', self: verdict.self === true };
603
+ const r = verdict.refuse;
604
+ return { decision: 'refused', code: 'PEER_REFUSED', kind: String(r.kind || 'refused'), why: String(r.why || 'a process that may not act as the owner'), pid: r.pid ?? null, name: String(r.name || ''), gone: false };
605
+ }
606
+ if (verdict.status === 'gone') {
607
+ return { decision: 'refused', code: 'PEER_REFUSED', kind: 'gone', why: String(verdict.reason || 'the connection closed before its request was identified'), pid: verdict.pid ?? null, name: '', gone: true };
608
+ }
609
+ // TODO(peer-identity-remote): a client on another machine of the network keeps the rules from before; whether a LAN
610
+ // client may ever hold the page secret is a separate decision (isRemote() reads headers only).
611
+ if (verdict.status === 'remote') return { decision: 'before', reason: 'another machine' };
612
+ if (verdict.status === 'unknown' && verdict.kind === 'unsupported') return { decision: 'before', reason: String(verdict.reason || 'peer lookup is not available here') };
613
+ return { decision: 'unavailable', code: 'PEER_UNAVAILABLE', retryable: verdict.retryable === true, reason: String(verdict.reason || 'the lookup failed') };
614
+ }
615
+
537
616
  // ── The reader ───────────────────────────────────────────────────────────────
538
617
 
539
618
  function defaultRun(file, args, { timeout }) {
@@ -556,7 +635,7 @@ function thisMachineAddresses() {
556
635
 
557
636
  /**
558
637
  * @param {object} [o]
559
- * @param {string} [o.platform] process.platform; only darwin is looked up (everything else is "unknown").
638
+ * @param {string} [o.platform] process.platform; only darwin is looked up (everything else is "unknown, unsupported").
560
639
  * @param {number} [o.selfPid] this server's pid (its own in-process calls are trusted).
561
640
  * @param {(file:string, args:string[], opts:{timeout:number}) => Promise<string>} [o.run] runs a program (execFile-shaped).
562
641
  * @param {() => Set<string>} [o.localAddresses] this computer's addresses (normalized).
@@ -566,12 +645,20 @@ function thisMachineAddresses() {
566
645
  * @param {string[]} [o.synabunRoots] this server's install (the folder holding mcp-server/): its MCP server over HTTP
567
646
  * is told apart from other listening programs (isSynabunMcpServer). None: it is refused as a listener, as any relay.
568
647
  * @param {(path:string) => string} [o.realpath] fs.realpathSync (tests inject one).
648
+ * @param {number} [o.lookupCapMs] the cap of one attempt (LOOKUP_CAP_MS; tests shorten it).
649
+ * @param {number} [o.negativeTtlMs] how long a failed lookup is kept on its connection (NEGATIVE_TTL_MS).
569
650
  */
570
- export function createPeerIdentity({ platform = process.platform, selfPid = process.pid, run = defaultRun, localAddresses = null, log = () => {}, now = Date.now, disabled = false, synabunRoots = [], realpath = realpathSync, debugClient = null } = {}) {
651
+ export function createPeerIdentity({ platform = process.platform, selfPid = process.pid, run = defaultRun, localAddresses = null, log = () => {}, now = Date.now, disabled = false, synabunRoots = [], realpath = realpathSync, debugClient = null, lookupCapMs = LOOKUP_CAP_MS, negativeTtlMs = NEGATIVE_TTL_MS } = {}) {
571
652
  const supported = platform === 'darwin' && !disabled;
653
+ const capMs = Number.isFinite(lookupCapMs) && lookupCapMs > 0 ? lookupCapMs : LOOKUP_CAP_MS;
654
+ const ttlMs = Number.isFinite(negativeTtlMs) && negativeTtlMs >= 0 ? negativeTtlMs : NEGATIVE_TTL_MS;
572
655
  const debugPolicy = debugClient?.enabled ? { enabled: true, port: Number.isInteger(debugClient.port) ? debugClient.port : null } : null;
573
656
  if (debugPolicy) { try { log(`[peer-identity] WARNING: SYNABUN_ALLOW_DEBUG_CLIENT is set: a loopback client started with --remote-debugging-port${debugPolicy.port ? `=${debugPolicy.port}` : ''} is taken as the owner (local profiling only; unset it when done)`); } catch { /* logger */ } }
574
- if (disabled) { try { log('[peer-identity] off (SYNABUN_PEER_IDENTITY=off): the page secret\'s rules from before apply, with no peer lookup'); } catch { /* logger */ } }
657
+ if (disabled) { try { log('[peer-identity] off (SYNABUN_PEER_IDENTITY=off, the owner\'s explicit choice): no peer lookup; the page secret, the owner\'s routes and the brain credential keep their rules from before (a local process that fetches a page gets the secret)'); } catch { /* logger */ } }
658
+ /** "Not looked up here" for this server: off, or another platform. */
659
+ const unsupportedReason = disabled ? 'SYNABUN_PEER_IDENTITY=off' : `peer lookup is not available on ${platform}`;
660
+ /** No answer: a failure where the lookup runs (macOS), the rules from before anywhere else. */
661
+ const noAnswer = (reason, { retryable = false } = {}) => (supported ? failedPeerVerdict(reason, { retryable }) : unsupportedPeerVerdict(unsupportedReason));
575
662
  const bySocket = new WeakMap();
576
663
  const chains = new Map(); // pid → { at, ucomm, chain }
577
664
  const envs = new Map(); // `${pid}\0${credential}` → { at, holds }
@@ -584,7 +671,7 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
584
671
  return typeof real === 'string' && real !== written ? [written, real] : [written];
585
672
  }))];
586
673
  const logged = new Map(); // key → last time
587
- const stats = { lookups: 0, tableReads: 0, psReads: 0, envReads: 0, refused: 0, unknown: 0, gone: 0, totalMs: 0, maxMs: 0 };
674
+ const stats = { lookups: 0, tableReads: 0, psReads: 0, envReads: 0, refused: 0, unknown: 0, failed: 0, retries: 0, gone: 0, totalMs: 0, maxMs: 0 };
588
675
  let addrCache = null;
589
676
  let addrAt = 0;
590
677
 
@@ -595,6 +682,81 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
595
682
  if (logged.size > 500) logged.delete(logged.keys().next().value);
596
683
  try { log(line); } catch { /* a logger's own failure */ }
597
684
  };
685
+ const say = (line) => { try { log(line); } catch { /* a logger's own failure */ } };
686
+
687
+ // ── The state of the owner's authority (GET /api/health `ownerAuthority`, the page's banner) ──
688
+ // off / unsupported never change. On macOS it is ok until the start probe or a lookup fails (degraded, with the
689
+ // reason), and ok again after a whole lookup works (one that read the process table, not just this server's own
690
+ // call, which needs netstat only). Each change is said once, loudly; a lookup that keeps failing is not said again.
691
+ const iso = (ms) => { try { return new Date(ms).toISOString(); } catch { return null; } };
692
+ let authority = disabled
693
+ ? { state: 'off', reason: 'SYNABUN_PEER_IDENTITY=off', retryable: false, since: iso(now()) }
694
+ : !supported
695
+ ? { state: 'unsupported', reason: unsupportedReason, retryable: false, since: iso(now()) }
696
+ : { state: 'ok', reason: null, retryable: false, since: iso(now()) };
697
+ let probed = null; // the start probe's promise
698
+ function degrade(reason, { retryable = false, source = 'lookup' } = {}) {
699
+ if (!supported) return;
700
+ const text = String(reason || 'the lookup failed');
701
+ if (authority.state === 'degraded') {
702
+ // The same outage, said once. Its reason stays what it was (the page's banner is dismissed by it), unless a cause
703
+ // that does not pass by itself follows one that might (a denial after a timeout): that one is the news.
704
+ if (authority.reason !== text) {
705
+ if (authority.retryable && !retryable) authority = { ...authority, reason: text, retryable: false };
706
+ note(`degraded:${text}`, `[peer-identity] still degraded: ${text}`);
707
+ }
708
+ return;
709
+ }
710
+ authority = { state: 'degraded', reason: text, retryable, since: iso(now()) };
711
+ say(`[peer-identity] DEGRADED (${source}): SynaBun cannot tell which local program is calling it (${text}). Until a lookup works again it hands out no page secret, takes no brain credential and answers the owner's writes, reads and sockets 503 PEER_UNAVAILABLE; pages and other reads still load. If this persists, start SynaBun outside any sandbox, or set SYNABUN_PEER_IDENTITY=off in ~/.synabun/.env and restart (the rules from before, without this protection).`);
712
+ }
713
+ function restore(source = 'lookup') {
714
+ if (!supported || authority.state === 'ok') return;
715
+ const was = authority.reason;
716
+ authority = { state: 'ok', reason: null, retryable: false, since: iso(now()) };
717
+ say(`[peer-identity] owner authority restored (${source}): local programs are identified again${was ? ` (it was: ${was})` : ''}`);
718
+ }
719
+ /** What a lookup said about the lookup itself: a whole answer restores, a failure degrades (one about a single
720
+ * connection — it has no address any more — says nothing about the tools). */
721
+ function noteOutcome(verdict) {
722
+ if (!supported || !verdict || typeof verdict !== 'object') return;
723
+ if (verdict.status === 'unknown' && verdict.kind === 'failed') { if (!verdict.connection) degrade(verdict.reason, { retryable: verdict.retryable === true }); }
724
+ else if (verdict.status === 'ok' && !verdict.self) restore();
725
+ }
726
+ /** The state for GET /api/health: { state: 'ok'|'degraded'|'unsupported'|'off', reason, retryable, since }. */
727
+ function authorityState() {
728
+ return { state: authority.state, reason: authority.reason, retryable: authority.retryable === true, since: authority.since };
729
+ }
730
+ /**
731
+ * The start probe (server.js runs it once, at start): netstat and ps, as a lookup runs them. A failure is the
732
+ * degraded state at once, with its reason in the log and in GET /api/health, before any owner's request meets it.
733
+ * Off macOS (or off) there is nothing to probe. Never rejects; asked twice, it runs once.
734
+ */
735
+ function probe() {
736
+ if (!supported) return Promise.resolve(authorityState());
737
+ if (probed) return probed;
738
+ probed = (async () => {
739
+ const failures = [];
740
+ let retryable = false;
741
+ try {
742
+ const table = parseNetstatTcp(await run(NETSTAT, NETSTAT_ARGS, { timeout: TABLE_TIMEOUT_MS }));
743
+ if (!table.rows.length) failures.push('netstat listed no TCP sockets');
744
+ else if (!table.rows.some((r) => r.pid > 0)) failures.push('netstat named no processes (an unknown output layout)');
745
+ } catch (error) { failures.push(`netstat: ${failureText(error)}`); retryable = retryable || isTransientLookupError(error); }
746
+ try {
747
+ const parents = parsePsParents(await run(PS, ['-Ao', 'pid=,ppid=,ucomm='], { timeout: PS_TIMEOUT_MS }));
748
+ if (!parents.size) failures.push('ps listed no processes');
749
+ else if (!parents.has(selfPid)) failures.push('ps did not list this server');
750
+ } catch (error) { failures.push(`ps: ${failureText(error)}`); retryable = retryable || isTransientLookupError(error); }
751
+ if (failures.length) degrade(failures.join('; '), { retryable, source: 'start probe' });
752
+ else {
753
+ say('[peer-identity] start probe: netstat and ps answer; the owner\'s authority is checked against the calling process');
754
+ restore('start probe');
755
+ }
756
+ return authorityState();
757
+ })().catch((error) => { degrade(`the probe failed (${error?.message || error})`, { source: 'start probe' }); return authorityState(); });
758
+ return probed;
759
+ }
598
760
  const isThisMachine = (addr) => {
599
761
  if (typeof localAddresses === 'function') { try { return localAddresses().has(addr); } catch { return false; } }
600
762
  if (!addrCache || now() - addrAt > LOCAL_ADDR_TTL_MS) { addrCache = thisMachineAddresses(); addrAt = now(); }
@@ -707,16 +869,18 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
707
869
  const remotePort = Number(socket?.remotePort);
708
870
  const local = normalizeAddress(socket?.localAddress);
709
871
  const localPort = Number(socket?.localPort);
710
- if (!remote || !remotePort || !localPort) return { status: 'unknown', reason: 'the connection has no address' };
872
+ // (on macOS: no proof of who is asking, about this one connection — it says nothing about the tools)
873
+ if (!remote || !remotePort || !localPort) return { ...noAnswer('the connection has no address'), connection: true };
874
+ // TODO(peer-identity-remote): another machine of the network is not looked up and keeps the rules from before.
711
875
  if (!isThisMachine(remote)) return { status: 'remote' };
712
- if (!supported) return { status: 'unknown', reason: `peer lookup is not available on ${platform}` };
876
+ if (!supported) return unsupportedPeerVerdict(unsupportedReason);
713
877
  let table;
714
- try { table = await tcpTable(); } catch (error) { return { status: 'unknown', reason: `netstat: ${error?.code || error?.message || error}` }; }
878
+ try { table = await tcpTable(); } catch (error) { return failedPeerVerdict(`netstat: ${failureText(error)}`, { retryable: isTransientLookupError(error) }); }
715
879
  const row = table.rows.find((r) => r.local.port === remotePort && r.local.addr === remote && r.foreign.port === localPort && (r.foreign.addr === local || !local));
716
880
  if (!row || !row.pid) return { status: 'gone', reason: 'the connection closed before its request was identified', ms: now() - started };
717
881
  if (row.pid === selfPid) return { status: 'ok', self: true, pid: row.pid, name: row.name, chain: [], refuse: null, ms: now() - started };
718
882
  let chain;
719
- try { chain = await chainOf(row.pid, row.name, table.startedAt); } catch (error) { return { status: 'unknown', reason: `ps: ${error?.code || error?.message || error}`, pid: row.pid }; }
883
+ try { chain = await chainOf(row.pid, row.name, table.startedAt); } catch (error) { return { ...failedPeerVerdict(`ps: ${failureText(error)}`, { retryable: isTransientLookupError(error) }), pid: row.pid }; }
720
884
  // The process table was read and the client is not in it: it sent its request and exited without waiting for the
721
885
  // answer (a one-shot relay). A browser or a brain waits for its answer; this is treated like a closed socket.
722
886
  if (!chain || !chain.length) return { status: 'gone', reason: 'the client process exited before it was identified', pid: row.pid, ms: now() - started };
@@ -727,18 +891,43 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
727
891
  return { status: 'ok', self: verdict.self, pid: row.pid, name: row.name || chain[0].ucomm, chain, refuse: verdict.refuse, ms: now() - started };
728
892
  }
729
893
 
730
- /** The peer of a request's connection, looked up once per connection (keep-alive requests share it). Never rejects. */
894
+ /** One attempt, capped: the request never waits past `capMs` for it (the programs it started end by their own timeouts). */
895
+ function attempt(socket) {
896
+ let timer = null;
897
+ const cap = new Promise((resolve) => { timer = setTimeout(() => resolve(noAnswer(`the lookup took over ${capMs} ms`, { retryable: true })), capMs); timer.unref?.(); });
898
+ const work = Promise.resolve().then(() => identify(socket)).catch((error) => noAnswer(`the lookup failed (${error?.message || error})`));
899
+ return Promise.race([work, cap]).finally(() => clearTimeout(timer));
900
+ }
901
+ /** A lookup, and once more at once when its failure may pass (a timeout, a busy system). */
902
+ async function settle(socket) {
903
+ const first = await attempt(socket);
904
+ if (!(first.status === 'unknown' && first.kind === 'failed' && first.retryable && !first.connection)) return first;
905
+ stats.retries++;
906
+ const second = await attempt(socket);
907
+ return second.status === 'unknown' && second.kind === 'failed' ? { ...second, retried: true } : second;
908
+ }
909
+ /**
910
+ * The peer of a request's connection, looked up once per connection (keep-alive requests share it). Never rejects.
911
+ * Kept on the connection: an answer (ok, another machine, not looked up here) for its lifetime; a failed lookup for
912
+ * `ttlMs` only (a burst of requests shares it, the next one after that looks again, so an open tab recovers once the
913
+ * lookup works); a client that left never (gone: the next request on it is looked up afresh).
914
+ */
731
915
  function lookup(req) {
732
916
  const socket = req?.socket || req?.connection || null;
733
- if (!socket || typeof socket !== 'object') return Promise.resolve({ status: 'unknown', reason: 'no connection' });
734
- let p = bySocket.get(socket);
735
- if (!p) {
736
- let timer = null;
737
- const cap = new Promise((resolve) => { timer = setTimeout(() => resolve({ status: 'unknown', reason: `the lookup took over ${LOOKUP_CAP_MS} ms` }), LOOKUP_CAP_MS); timer.unref?.(); });
738
- p = Promise.race([identify(socket).catch((error) => ({ status: 'unknown', reason: error?.message || String(error) })), cap]).finally(() => clearTimeout(timer));
739
- bySocket.set(socket, p);
740
- }
741
- return p;
917
+ if (!socket || typeof socket !== 'object') return Promise.resolve({ ...noAnswer('no connection'), connection: true });
918
+ const kept = bySocket.get(socket);
919
+ if (kept && (kept.pending || kept.until > now())) return kept.promise;
920
+ const entry = { pending: true, until: 0, promise: null };
921
+ entry.promise = settle(socket).then((verdict) => {
922
+ entry.pending = false;
923
+ noteOutcome(verdict);
924
+ const failed = verdict.status === 'unknown' && verdict.kind === 'failed';
925
+ entry.until = verdict.status === 'gone' ? 0 : failed ? now() + ttlMs : Infinity;
926
+ if (!(entry.until > now()) && bySocket.get(socket) === entry) bySocket.delete(socket);
927
+ return verdict;
928
+ });
929
+ bySocket.set(socket, entry);
930
+ return entry.promise;
742
931
  }
743
932
 
744
933
  /** Whether some process in `chain` (the peer up to this server) holds the credential in its own environment. */
@@ -770,21 +959,36 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
770
959
 
771
960
  /**
772
961
  * Express middleware: looks the peer up when `needs(req)` says the request asks for, or carries, the owner's
773
- * authority, and keeps the verdict on the request (refusal() reads it). A brain credential from a peer outside the
774
- * brain's own process tree is removed from the request. Never fails a request: a lookup that cannot run leaves the
775
- * rules from before in force.
962
+ * authority, and keeps the verdict on the request (peerAuthority() reads it). A brain credential from a peer outside
963
+ * the brain's own process tree is removed from the request. It never answers a request itself: on another platform
964
+ * (or off) a lookup that cannot run leaves the rules from before in force; on macOS it leaves a failed verdict, which
965
+ * the owner gate and the page secret answer with 503 PEER_UNAVAILABLE.
776
966
  */
777
967
  function middleware({ needs = () => false } = {}) {
778
968
  // Express 4 does not catch a rejected promise: the decision is made apart from next(), which is called exactly
779
- // once whatever happens in it (an unexpected error leaves the rules from before, and is said once).
969
+ // once whatever happens in it.
780
970
  return function peerIdentity(req, res, next) {
781
971
  if (disabled) return next();
782
972
  let wanted = false;
783
- try { wanted = needs(req) === true; } catch { wanted = false; }
973
+ // A needs() that throws cannot say the request asks for nothing: where the lookup runs, it is looked up.
974
+ try { wanted = needs(req) === true; } catch { wanted = supported; }
784
975
  const credential = typeof req.headers?.[BRAIN_HEADER] === 'string' ? req.headers[BRAIN_HEADER].trim() : null;
785
976
  if (!wanted && !credential) return next();
786
977
  decide(req, wanted, credential).then(() => next(), (error) => {
787
- note(`error:${error?.message}`, `[peer-identity] the lookup failed (${error?.message || error}); the page secret's rules from before apply`);
978
+ try {
979
+ if (supported) {
980
+ // Never the rules from before by accident: on macOS a decision that broke is a lookup that failed, with no
981
+ // owner authority and no brain credential for this request. (A request that cannot even hold the verdict
982
+ // is left without one, which the callers of a server whose lookup runs take as a failed lookup too.)
983
+ const verdict = failedPeerVerdict(`the lookup failed (${error?.message || error})`);
984
+ if (req.headers && credential) delete req.headers[BRAIN_HEADER];
985
+ noteOutcome(verdict);
986
+ note(`error:${error?.message}`, `[peer-identity] the lookup failed (${error?.message || error}): no owner authority for this request (503 PEER_UNAVAILABLE)`);
987
+ req[PEER_VERDICT] = verdict;
988
+ } else {
989
+ note(`error:${error?.message}`, `[peer-identity] the lookup failed (${error?.message || error}); the page secret's rules from before apply`);
990
+ }
991
+ } catch { /* a request that cannot be written to: see above */ }
788
992
  next();
789
993
  });
790
994
  };
@@ -793,44 +997,60 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
793
997
  async function decide(req, wanted, credential) {
794
998
  const t0 = now();
795
999
  let peer;
796
- try { peer = await lookup(req); } catch (error) { peer = { status: 'unknown', reason: error?.message || String(error) }; }
1000
+ try { peer = await lookup(req); } catch (error) { peer = noAnswer(`the lookup failed (${error?.message || error})`); }
1001
+ if (!peer || typeof peer !== 'object') peer = noAnswer('the lookup gave no answer');
797
1002
  const ms = now() - t0;
798
1003
  stats.lookups++; stats.totalMs += ms; if (ms > stats.maxMs) stats.maxMs = ms;
799
1004
  req[PEER_VERDICT] = peer;
800
- if (peer.status === 'unknown') { stats.unknown++; note(`unknown:${peer.reason}`, `[peer-identity] could not tell who is asking (${peer.reason}); the page secret's rules from before apply`); }
1005
+ if (peer.status === 'unknown') {
1006
+ stats.unknown++;
1007
+ if (peer.kind === 'failed') {
1008
+ stats.failed++;
1009
+ note(`failed:${peer.reason}`, `[peer-identity] could not tell who is asking (${peer.reason}${peer.retried ? ', tried twice' : ''}): no page secret, owner authority or brain credential for it (503 PEER_UNAVAILABLE)`);
1010
+ } else note(`unknown:${peer.reason}`, `[peer-identity] could not tell who is asking (${peer.reason}); the page secret's rules from before apply`);
1011
+ }
801
1012
  if (peer.status === 'gone') { stats.gone++; note(`gone`, `[peer-identity] ${peer.reason || 'a connection closed before its request was identified'}: no owner authority for it`); }
802
1013
  if (peer.status === 'ok' && peer.refuse && wanted) {
803
1014
  stats.refused++;
804
1015
  note(`refuse:${peer.refuse.pid}:${peer.refuse.kind}`, `[peer-identity] no page secret / owner authority for pid ${peer.refuse.pid} (${peer.refuse.name}): ${peer.refuse.why}`);
805
1016
  }
806
1017
  if (!credential) return;
1018
+ // Kept: from this server itself, from the brain's own tree (it holds the credential in its environment), or where
1019
+ // no lookup runs (another platform: the credential alone, as before). Dropped: from anywhere else, from a client
1020
+ // that left, and on macOS whenever its check could not run (the lookup failed, or ps -E could not be read).
807
1021
  let keep = true;
808
1022
  if (peer.status === 'gone') keep = false;
1023
+ else if (peer.status === 'unknown' && peer.kind === 'failed') keep = false;
809
1024
  else if (peer.status === 'ok' && !peer.self) {
810
1025
  try { keep = await chainHoldsCredential(peer.chain || [], credential); } catch (error) {
811
- keep = true; // the environment could not be read: the rules from before (the credential alone)
812
- note(`env:${error?.code || error?.message}`, `[peer-identity] could not read a brain's environment (${error?.code || error?.message || error}); the brain credential is taken as before`);
1026
+ keep = false;
1027
+ // The whole request then has no proven caller: answered 503 (retryable when ps -E only timed out).
1028
+ const failed = { ...failedPeerVerdict(`ps -E: ${failureText(error)}`, { retryable: isTransientLookupError(error) }), pid: peer.pid };
1029
+ req[PEER_VERDICT] = failed;
1030
+ noteOutcome(failed);
1031
+ note(`env:${error?.code || error?.message}`, `[peer-identity] could not read a brain's environment (${failureText(error)}): the brain credential was dropped and the request has no owner authority (503 PEER_UNAVAILABLE)`);
813
1032
  }
814
1033
  }
815
1034
  if (!keep) {
816
1035
  delete req.headers[BRAIN_HEADER];
817
- note(`brain:${peer.pid || 'gone'}`, `[peer-identity] a brain credential came from pid ${peer.pid || '?'} (${peer.name || 'closed connection'}), outside the brain's own process tree: it was dropped from the request`);
1036
+ const why = peer.status === 'unknown' ? `its check could not run (${peer.reason})` : 'outside the brain\'s own process tree';
1037
+ note(`brain:${peer.pid || peer.status}`, `[peer-identity] a brain credential came from pid ${peer.pid || '?'} (${peer.name || (peer.status === 'gone' ? 'closed connection' : 'not identified')}), ${why}: it was dropped from the request`);
818
1038
  }
819
1039
  }
820
1040
 
821
1041
  /**
822
- * Why this request may not hold or use the owner's page secret (a short sentence), or null. Null as well when the
823
- * peer could not be identified or was never looked up: the caller's rules from before decide.
1042
+ * Why this request may not hold or use the owner's page secret (a short sentence), or null: a refused peer, a client
1043
+ * that left, and on macOS a lookup that failed (no proof of who is asking). Null when the peer is allowed, was never
1044
+ * looked up, or is not looked up here (another platform, off, another machine): the caller's rules from before.
824
1045
  */
825
1046
  function refusal(req) {
826
- const peer = req?.[PEER_VERDICT];
827
- if (!peer) return null;
828
- if (peer.status === 'gone') return peer.reason || 'the connection closed before its request was identified';
829
- if (peer.status === 'ok' && peer.refuse) return `${peer.refuse.why}: pid ${peer.refuse.pid} (${peer.refuse.name})`;
1047
+ const auth = peerAuthority(req?.[PEER_VERDICT]);
1048
+ if (auth.decision === 'refused') return auth.gone ? auth.why : `${auth.why}: pid ${auth.pid} (${auth.name})`;
1049
+ if (auth.decision === 'unavailable') return `a request SynaBun could not identify (${auth.reason})`;
830
1050
  return null;
831
1051
  }
832
1052
 
833
- return { supported, lookup, middleware, refusal, chainHoldsCredential, stats: () => ({ ...stats, avgMs: stats.lookups ? Math.round((stats.totalMs / stats.lookups) * 10) / 10 : 0 }) };
1053
+ return { supported, lookup, middleware, refusal, chainHoldsCredential, probe, authorityState, stats: () => ({ ...stats, avgMs: stats.lookups ? Math.round((stats.totalMs / stats.lookups) * 10) / 10 : 0 }) };
834
1054
  }
835
1055
 
836
1056
  /** Exposed for tests: whether an address is a literal IP (4 or 6). */
@@ -1,3 +1,5 @@
1
+ import { scrubTokenText } from './terminal-token-redaction.js';
2
+
1
3
  const API_KEY_ERRORS = {
2
4
  invalid_key: { status: 400, message: "That doesn't look like an API key for this provider." },
3
5
  oauth_token: { status: 400, message: "That's a Claude sign-in token. Use Sign in with Claude." },
@@ -27,9 +29,12 @@ export function validateProviderApiKey(provider, key) {
27
29
  return key;
28
30
  }
29
31
 
30
- // Defense in depth for native diagnostics/events. Never forward credential fields.
32
+ // Defense in depth for native diagnostics/events. Never forward credential fields. SynaBun's own run secrets go too
33
+ // (a terminal token, a brain's launch credential: lib/terminal-token-redaction.js), first, so a provider-key pattern
34
+ // inside one never leaves a piece of it: the Claude Code panel's and brain's events and the Codex panel's messages
35
+ // (and its app-server's output) pass here.
31
36
  export function redactProviderSecrets(value) {
32
- if (typeof value === 'string') return value.replace(/sk-[A-Za-z0-9_-]{16,}/g, '[redacted]');
37
+ if (typeof value === 'string') return scrubTokenText(value).replace(/sk-[A-Za-z0-9_-]{16,}/g, '[redacted]');
33
38
  if (Array.isArray(value)) return value.map(redactProviderSecrets);
34
39
  if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value)
35
40
  .filter(([key]) => !/^(api_?key|access_?token|refresh_?token|id_?token|authorization)$/i.test(key))
@@ -20,6 +20,7 @@ import { EV, OP, HOST_DEFAULTS } from './protocol.js';
20
20
  import { createEventLoopMonitor } from '../event-loop-monitor.js';
21
21
  import { withPathEnv } from '../augmented-path.js';
22
22
  import { killOwnedPty } from './lifetime.js';
23
+ import { createTokenStreamRedactor } from '../terminal-token-redaction.js';
23
24
 
24
25
  const IS_WIN = process.platform === 'win32';
25
26
  const IS_LINUX = process.platform === 'linux';
@@ -129,6 +130,12 @@ export function createPtyHostCore({ send, config = {}, pty: injectedPty = null }
129
130
  profile: spec.profile || null,
130
131
  loopOwned: !!spec.loopOwned,
131
132
  tap: !!spec.tap,
133
+ // A session whose environment holds a run's terminal token (a loop's PTY): what it prints is scrubbed of
134
+ // token-shaped values before anything gets it (clients, the snapshot model, the tap to the main process), so an
135
+ // agent that runs `env` writes no live token to a loop's log, a link's capture or a reconnect snapshot.
136
+ // The exact tokens in its environment are handed to it too, so their base64 and hex are masked as well.
137
+ redactor: spec.redactTokens ? createTokenStreamRedactor({ secrets: [spec.env?.SYNABUN_TERMINAL_TOKEN, spec.env?.SYNABUN_BRAIN_TOKEN].filter((v) => typeof v === 'string') }) : null,
138
+ redactTimer: null,
132
139
  clients: new Set(),
133
140
  outputBytes: 0,
134
141
  coalesce: '',
@@ -157,6 +164,11 @@ export function createPtyHostCore({ send, config = {}, pty: injectedPty = null }
157
164
  // ── Output path ──
158
165
  function onPtyData(s, data) {
159
166
  if (s.exited) return;
167
+ if (s.redactor) {
168
+ data = s.redactor.push(data);
169
+ holdRedactedTail(s);
170
+ if (!data) return;
171
+ }
160
172
  s.coalesce += data;
161
173
  if (s.coalesce.length >= cfg.coalesceBurstBytes) { flush(s); return; }
162
174
  if (!s.flushScheduled) {
@@ -165,6 +177,23 @@ export function createPtyHostCore({ send, config = {}, pty: injectedPty = null }
165
177
  }
166
178
  }
167
179
 
180
+ // The end of a chunk that could be a token's beginning waits for the next chunk; when none comes within
181
+ // redactHoldMs it goes out (a held token beginning masked), and what continues it later is masked when it comes:
182
+ // the redactor remembers the characters it passed on, so no wait between pieces lets a whole token through.
183
+ function holdRedactedTail(s) {
184
+ if (s.redactTimer) { clearTimeout(s.redactTimer); s.redactTimer = null; }
185
+ if (!s.redactor?.pending()) return;
186
+ s.redactTimer = setTimeout(() => {
187
+ s.redactTimer = null;
188
+ if (s.exited || !s.redactor?.pending()) return;
189
+ const rest = s.redactor.flush();
190
+ if (!rest) return;
191
+ s.coalesce += rest;
192
+ flush(s);
193
+ }, cfg.redactHoldMs);
194
+ s.redactTimer.unref?.();
195
+ }
196
+
168
197
  function flush(s) {
169
198
  s.flushScheduled = false;
170
199
  if (!s.coalesce) return;
@@ -479,6 +508,12 @@ export function createPtyHostCore({ send, config = {}, pty: injectedPty = null }
479
508
  counters.exits++;
480
509
  if (s.pausedWatch) { clearInterval(s.pausedWatch); s.pausedWatch = null; }
481
510
  s.ptyPaused = false;
511
+ // What the scrubber still holds is the end of the output.
512
+ if (s.redactor) {
513
+ if (s.redactTimer) { clearTimeout(s.redactTimer); s.redactTimer = null; }
514
+ const rest = s.redactor.flush();
515
+ if (rest) s.coalesce += rest;
516
+ }
482
517
  // Final bytes first — to clients, the model and the tap — then the exit.
483
518
  flush(s);
484
519
  s.exited = true;
@@ -498,6 +533,7 @@ export function createPtyHostCore({ send, config = {}, pty: injectedPty = null }
498
533
  if (s.graceTimer) { clearTimeout(s.graceTimer); s.graceTimer = null; }
499
534
  if (s.resize.timer) { clearTimeout(s.resize.timer); s.resize.timer = null; }
500
535
  if (s.tapTimer) { clearTimeout(s.tapTimer); s.tapTimer = null; }
536
+ if (s.redactTimer) { clearTimeout(s.redactTimer); s.redactTimer = null; }
501
537
  for (const c of s.clients) clearLagState(c);
502
538
  for (const f of s.tempFiles.splice(0)) unlink(f).catch(() => {});
503
539
  try { s.model.dispose(); } catch {}
@@ -70,6 +70,8 @@ export const HOST_DEFAULTS = Object.freeze({
70
70
  pingMs: 30000,
71
71
  // Output tap to the main process (loop drivers, live links).
72
72
  tapBatchMs: 25,
73
+ // A token-scrubbed session (a loop's PTY): how long the end of a chunk that could begin a token waits for the next.
74
+ redactHoldMs: 30,
73
75
  tapBatchBytes: 64 * 1024,
74
76
  });
75
77
 
@@ -93,7 +93,17 @@ function fail(res, err) {
93
93
  * @param {Function} [o.ownerGuard] lib/http-guards.js ownerRouteGuard(…) of this server (Host, Origin, guests)
94
94
  * @param {(req) => string|null} [o.assistantOf] the Assistant session a request's brain credential belongs to (principalOf)
95
95
  */
96
- export function registerSkillsV2Routes(app, { service, isGuestRequest = null, ownerGuard = null, assistantOf = null, pageSession = null } = {}) {
96
+ export function registerSkillsV2Routes(app, { service, isGuestRequest = null, ownerGuard = null, assistantOf = null, pageSession = null, terminalRefusal = null } = {}) {
97
+ // An agent's X-Synabun-Terminal names its author: it counts only with the run's (or the brain's) proof, else the
98
+ // request is refused (server.js browserCaller: 403 TERMINAL_TOKEN_REQUIRED / _INVALID), so one agent never passes
99
+ // for another (a review's withdrawal). `terminalRefusal(req)` → { status, code, error } or null.
100
+ const refusedPin = (req, res) => {
101
+ let refused = null;
102
+ try { refused = typeof terminalRefusal === 'function' ? terminalRefusal(req) : null; } catch { refused = { status: 403, code: 'TERMINAL_TOKEN_INVALID', error: 'The run this request names could not be checked.' }; }
103
+ if (!refused) return false;
104
+ sendGuardError(res, Number(refused.status) || 403, String(refused.code || 'TERMINAL_TOKEN_INVALID'), String(refused.error || 'This request names a run it cannot prove it is.'));
105
+ return true;
106
+ };
97
107
  const idem = new Map();
98
108
 
99
109
  const json = (req, res, next) => {
@@ -106,8 +116,9 @@ export function registerSkillsV2Routes(app, { service, isGuestRequest = null, ow
106
116
  next();
107
117
  };
108
118
  // A read of the owner's page hands it the page secret (lib/page-session.js), which its writes then carry.
109
- const reader = (req, res, next) => { req.principal = principalOf(req, isGuestRequest, assistantOf); if (req.principal.kind === 'owner') pageSession?.attach?.(res); next(); };
119
+ const reader = (req, res, next) => { if (refusedPin(req, res)) return; req.principal = principalOf(req, isGuestRequest, assistantOf); if (req.principal.kind === 'owner') pageSession?.attach?.(res); next(); };
110
120
  const writer = (req, res, next) => {
121
+ if (refusedPin(req, res)) return;
111
122
  req.principal = principalOf(req, isGuestRequest, assistantOf);
112
123
  if (req.principal.kind === 'guest') return sendGuardError(res, 403, 'GUEST_FORBIDDEN', 'Available to the owner only.');
113
124
  next();
@@ -40,7 +40,7 @@ function fail(res, err) {
40
40
  * @param {object} o.service lib/skills/service.js (the bundled skill-forge for GET /guide)
41
41
  * @param {(req) => boolean} [o.isGuestRequest]
42
42
  * @param {Function} [o.ownerGuard] lib/http-guards.js ownerRouteGuard(…) of this server
43
- * @param {(req) => ({ kind: 'assistant', assistantSessionId: string } | { kind: 'worker' } | null)} [o.assistantCaller]
43
+ * @param {(req) => ({ kind: 'assistant', assistantSessionId: string } | { kind: 'worker' } | { kind: 'refused', code, error, status } | null)} [o.assistantCaller]
44
44
  * who an agent request is: an Assistant brain (the session its credential belongs to), a dispatched worker, or nobody
45
45
  * @param {() => object} [o.options] what can run now: { conversation: string[] (providers), url: boolean, urlReason,
46
46
  * repo: { path, label }[], memory: boolean, import: boolean, defaultTarget, drafting: { available, reason, providers } }
@@ -80,6 +80,8 @@ export function registerSkillCreationRoutes(app, { creations, service, isGuestRe
80
80
  // a dispatched worker.
81
81
  let who = null;
82
82
  try { who = typeof assistantCaller === 'function' ? assistantCaller(req) : null; } catch { who = null; }
83
+ // A request that names a run or a brain it cannot prove it is (server.js browserCaller: no terminal token, another's).
84
+ if (who?.kind === 'refused') return sendGuardError(res, Number(who.status) || 403, typeof who.code === 'string' ? who.code : 'TERMINAL_TOKEN_INVALID', typeof who.error === 'string' ? who.error : 'This request names a run it cannot prove it is.');
83
85
  if (who?.kind === 'worker') return sendGuardError(res, 403, 'WORKERS_NOT_PERMITTED', 'Dispatched workers cannot create skills: the Assistant or the owner does.');
84
86
  if (who?.kind !== 'assistant' || typeof who.assistantSessionId !== 'string' || !who.assistantSessionId) {
85
87
  return sendGuardError(res, 403, 'ASSISTANT_CREDENTIAL_REQUIRED', 'Drafting skills with AI is the owner\'s (Skills Studio) and the SynaBun Assistant\'s own brain\'s (its launch credential): a role header is not enough.');