synabun 2.2.0 → 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 (166) hide show
  1. package/CHANGELOG.md +45 -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 +27 -0
  62. package/neural-interface/i18n/pt-BR.json +27 -0
  63. package/neural-interface/lib/assistant-api.js +64 -23
  64. package/neural-interface/lib/assistant-brains/codex.js +6 -1
  65. package/neural-interface/lib/assistant-catalog.js +20 -2
  66. package/neural-interface/lib/assistant-dispatch.js +31 -2
  67. package/neural-interface/lib/assistant-persona.js +1 -0
  68. package/neural-interface/lib/assistant-runtime.js +15 -1
  69. package/neural-interface/lib/assistant-tools.js +10 -1
  70. package/neural-interface/lib/browser-automation-routes.js +84 -0
  71. package/neural-interface/lib/browser-execution.js +16 -3
  72. package/neural-interface/lib/browser-owner.js +48 -0
  73. package/neural-interface/lib/browser-session-close.js +84 -0
  74. package/neural-interface/lib/browser-start-handoff.js +202 -0
  75. package/neural-interface/lib/browser-tool-policy.js +21 -4
  76. package/neural-interface/lib/browser-wedge-retire.js +64 -0
  77. package/neural-interface/lib/claude-agent-bridge.js +36 -1
  78. package/neural-interface/lib/claude-background-hold.js +239 -0
  79. package/neural-interface/lib/exec-loop-command.js +8 -0
  80. package/neural-interface/lib/http-guards.js +11 -6
  81. package/neural-interface/lib/loop-logger.js +6 -1
  82. package/neural-interface/lib/mcp-external-servers.js +64 -13
  83. package/neural-interface/lib/native-loop-providers.js +122 -10
  84. package/neural-interface/lib/native-loop-runtime.js +112 -11
  85. package/neural-interface/lib/opencode-native-boundary.js +155 -21
  86. package/neural-interface/lib/owner-authority.js +113 -37
  87. package/neural-interface/lib/page-session.js +81 -23
  88. package/neural-interface/lib/peer-identity.js +311 -47
  89. package/neural-interface/lib/provider-panel-api-key-auth.js +7 -2
  90. package/neural-interface/lib/pty-host/core.js +36 -0
  91. package/neural-interface/lib/pty-host/protocol.js +2 -0
  92. package/neural-interface/lib/skills/api-v2.js +13 -2
  93. package/neural-interface/lib/skills/creation-api.js +3 -1
  94. package/neural-interface/lib/skills/evals-api.js +5 -1
  95. package/neural-interface/lib/social-write-pacing.js +151 -0
  96. package/neural-interface/lib/terminal-token-redaction.js +293 -0
  97. package/neural-interface/lib/terminal-tokens.js +359 -0
  98. package/neural-interface/lib/worker-mcp-channel.js +45 -10
  99. package/neural-interface/package-lock.json +2 -2
  100. package/neural-interface/package.json +1 -1
  101. package/neural-interface/public/shared/agy/agy-render.js +41 -1
  102. package/neural-interface/public/shared/agy/agy-styles.js +5 -0
  103. package/neural-interface/public/shared/api.js +1 -0
  104. package/neural-interface/public/shared/assistant/asst-api.js +14 -2
  105. package/neural-interface/public/shared/assistant/asst-computer.js +73 -4
  106. package/neural-interface/public/shared/assistant/asst-limit-wait.js +3 -1
  107. package/neural-interface/public/shared/assistant/asst-motion-gate.js +80 -0
  108. package/neural-interface/public/shared/assistant/asst-panel.js +8 -4
  109. package/neural-interface/public/shared/assistant/asst-render.js +72 -11
  110. package/neural-interface/public/shared/assistant/asst-scene-styles.js +55 -23
  111. package/neural-interface/public/shared/assistant/asst-scenes.js +225 -79
  112. package/neural-interface/public/shared/assistant/asst-sidepanel-styles.js +4 -4
  113. package/neural-interface/public/shared/assistant/asst-style-cache.js +44 -0
  114. package/neural-interface/public/shared/assistant/asst-styles.js +26 -5
  115. package/neural-interface/public/shared/cdx/cdx-render.js +73 -7
  116. package/neural-interface/public/shared/cdx/cdx-tabs.js +3 -3
  117. package/neural-interface/public/shared/cp/cp-agents.js +8 -0
  118. package/neural-interface/public/shared/cp/cp-permissions.js +18 -2
  119. package/neural-interface/public/shared/cp/cp-rehydrate.js +25 -1
  120. package/neural-interface/public/shared/cp/cp-tasks-model.js +33 -0
  121. package/neural-interface/public/shared/judgments-log-origins.js +29 -0
  122. package/neural-interface/public/shared/loading-teardown.js +34 -0
  123. package/neural-interface/public/shared/ocp-v2/ocp-v2-automation-ownership.js +23 -0
  124. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +6 -1
  125. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +13 -0
  126. package/neural-interface/public/shared/ocp-v2/ocp-v2-icons.js +3 -1
  127. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +5 -2
  128. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +16 -86
  129. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +6 -0
  130. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +88 -72
  131. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +5 -2
  132. package/neural-interface/public/shared/owner-access.js +134 -0
  133. package/neural-interface/public/shared/owner-authority-view.js +92 -0
  134. package/neural-interface/public/shared/page-session.js +143 -14
  135. package/neural-interface/public/shared/poll-backoff.js +59 -0
  136. package/neural-interface/public/shared/settings/settings-data.js +6 -1
  137. package/neural-interface/public/shared/settings/settings-kit.js +11 -3
  138. package/neural-interface/public/shared/settings/settings-shell.js +7 -0
  139. package/neural-interface/public/shared/shown-children.js +72 -0
  140. package/neural-interface/public/shared/static-bg-state.js +22 -0
  141. package/neural-interface/public/shared/storage-retry.js +47 -0
  142. package/neural-interface/public/shared/storage.js +25 -4
  143. package/neural-interface/public/shared/styles.css +109 -8
  144. package/neural-interface/public/shared/synabun-mascot.js +27 -8
  145. package/neural-interface/public/shared/synabun-ticker.js +147 -12
  146. package/neural-interface/public/shared/synabun-tools.js +173 -0
  147. package/neural-interface/public/shared/tool-heartbeat.js +43 -0
  148. package/neural-interface/public/shared/tool-list-picker.js +3 -1
  149. package/neural-interface/public/shared/tool-list-view.js +23 -4
  150. package/neural-interface/public/shared/ui-automation-studio.js +8 -1
  151. package/neural-interface/public/shared/ui-claude-panel.js +238 -90
  152. package/neural-interface/public/shared/ui-judgments.js +37 -10
  153. package/neural-interface/public/shared/ui-loading.js +5 -4
  154. package/neural-interface/public/shared/ui-navbar.js +6 -0
  155. package/neural-interface/public/shared/ui-owner-access.js +191 -0
  156. package/neural-interface/public/shared/ui-owner-authority.js +162 -0
  157. package/neural-interface/public/shared/ui-sessions.js +45 -16
  158. package/neural-interface/public/shared/ui-settings.js +86 -15
  159. package/neural-interface/public/shared/ui-terminal.js +15 -7
  160. package/neural-interface/public/shared/ui-tutorial-preview.js +4 -0
  161. package/neural-interface/public/shared/ui-update.js +3 -0
  162. package/neural-interface/public/shared/ui-whiteboard.js +4 -0
  163. package/neural-interface/public/shared/window-keys.js +38 -0
  164. package/neural-interface/server.js +1240 -238
  165. package/npm-shrinkwrap.json +2 -2
  166. package/package.json +1 -1
@@ -0,0 +1,239 @@
1
+ // ── A Claude Code turn that waits for its own background work (DOM-free) ──
2
+ //
3
+ // An unattended run (a native loop iteration, a dispatched worker turn) drives one streaming Agent SDK query and
4
+ // counted the iteration over at the first `result`. A turn that ends while a background shell or a Monitor it
5
+ // started still runs is not over: the CLI comes back by itself when that work settles (a `task_notification`
6
+ // queued to the idle session starts a new turn, beginning with a `system/init`), and the work continues there.
7
+ // Ending the iteration at the first result disposed the query, the CLI killed the waits, and the run stopped
8
+ // mid-task while its panel showed the waits "running" forever (a Bluesky schedule waiting out a pacing gap).
9
+ //
10
+ // This module decides, from the SDK's own events, when such a turn is really over:
11
+ // - a result with none of the session's background tasks live (and none just reported that would start another
12
+ // turn) ends it at once, exactly as before;
13
+ // - a result while tasks are live is held: later results join it (cost and usage summed, the last text wins);
14
+ // - when the tasks drain and the CLI does not come back within `resumeGraceMs`, the host pushes one continuation
15
+ // prompt (`nudge`);
16
+ // - `idleMs` without any event from the CLI, or the run's own deadline, ends the hold with the last result.
17
+ //
18
+ // The host (lib/native-loop-providers.js) feeds every SDK message to `onEvent` and asks `onResult` what to do
19
+ // with each result of the active turn. Clock and timers are injected, so the tests run it on a fake clock.
20
+
21
+ export const BACKGROUND_HOLD_DEFAULTS = Object.freeze({
22
+ // How long a held turn waits with no event at all from the CLI (a background task that never ends, a CLI that
23
+ // never comes back) before the iteration ends with the last result. Pacing gaps are a few minutes at most.
24
+ idleMs: 10 * 60_000,
25
+ // After the last background task ended: how long the CLI has to start its own turn before the host nudges it.
26
+ resumeGraceMs: 15_000,
27
+ // A task reported during the turn that just ended may still start a turn of its own: this long is waited for it.
28
+ followGraceMs: 4_000,
29
+ });
30
+
31
+ const RESULT_BLOCK_RE = /^#{1,3}\s*Result\b/m;
32
+
33
+ /** A dispatched worker that wrote its ## Result block has said it is done: its turn is never held. */
34
+ export function resultDeclaresDone(text) {
35
+ return RESULT_BLOCK_RE.test(String(text || ''));
36
+ }
37
+
38
+ const NUMERIC_USAGE_KEYS = ['input_tokens', 'output_tokens', 'cache_creation_input_tokens', 'cache_read_input_tokens'];
39
+
40
+ /** The usage of two results of one held turn, added up (unknown fields: the later one's). */
41
+ export function addUsage(a, b) {
42
+ if (!a) return b || null;
43
+ if (!b) return a;
44
+ const out = { ...a, ...b };
45
+ for (const key of NUMERIC_USAGE_KEYS) {
46
+ const x = Number(a[key]) || 0;
47
+ const y = Number(b[key]) || 0;
48
+ if (x || y) out[key] = x + y;
49
+ }
50
+ return out;
51
+ }
52
+
53
+ /** The live background tasks of one CLI session, from its level signal and its bookends. */
54
+ export function createBackgroundTasks() {
55
+ const live = new Map(); // task_id → { id, type, description, ambient }
56
+ const started = new Map(); // task_id → tool_use_id (set when a tool call of the model started it)
57
+ const excused = new Set(); // tasks a hold already gave up on (never ending): they hold no later turn
58
+ let notifiedAt = 0; // last task_notification (ms, host clock)
59
+ return {
60
+ /** @returns true when the event was a task event */
61
+ apply(event, now) {
62
+ if (event?.type !== 'system') return false;
63
+ switch (event.subtype) {
64
+ case 'background_tasks_changed': {
65
+ live.clear();
66
+ for (const task of Array.isArray(event.tasks) ? event.tasks : []) {
67
+ if (!task?.task_id) continue;
68
+ const id = String(task.task_id);
69
+ live.set(id, { id, type: String(task.task_type || ''), description: String(task.description || ''), ambient: task.ambient === true });
70
+ }
71
+ return true;
72
+ }
73
+ case 'task_started':
74
+ if (event.task_id) started.set(String(event.task_id), event.tool_use_id ? String(event.tool_use_id) : '');
75
+ return true;
76
+ case 'task_notification':
77
+ if (event.task_id) live.delete(String(event.task_id));
78
+ notifiedAt = now;
79
+ return true;
80
+ case 'task_updated': {
81
+ const status = event.patch?.status;
82
+ if (event.task_id && ['completed', 'failed', 'killed', 'stopped'].includes(status)) live.delete(String(event.task_id));
83
+ return true;
84
+ }
85
+ default:
86
+ return false;
87
+ }
88
+ },
89
+ /**
90
+ * What a turn waits for: every live task, except ambient housekeeping nothing of the model started
91
+ * (a watcher the CLI runs by itself would otherwise hold every turn to its limit).
92
+ */
93
+ holdable() {
94
+ return [...live.values()].filter((task) => !excused.has(task.id) && (!task.ambient || !!started.get(task.id)));
95
+ },
96
+ /** A hold ended without these tasks (idle, deadline): a later turn does not wait for them again. */
97
+ excuse(list) { for (const task of Array.isArray(list) ? list : []) if (task?.id) excused.add(String(task.id)); },
98
+ live: () => [...live.values()],
99
+ notifiedAt: () => notifiedAt,
100
+ /** The CLI process is gone: nothing of it runs any more. */
101
+ clear() { live.clear(); started.clear(); excused.clear(); },
102
+ };
103
+ }
104
+
105
+ /**
106
+ * One turn's hold. `onResult(event, value)` is called for each result of the active turn and answers 'resolve'
107
+ * (the turn is over: resolve it with `value()`) or 'hold' (keep waiting). Every other SDK message goes to
108
+ * `onEvent`. `onRelease(reason)` is the host's: called when the hold ends by itself ('drained': the CLI did not
109
+ * come back after its work ended, 'idle_timeout', 'deadline'); `nudge()` is the host's too: push one continuation
110
+ * prompt, answer whether it was sent. `shouldHold(value)` says whether a result may wait at all (a dispatched
111
+ * worker that wrote its ## Result block is done).
112
+ */
113
+ export function createTurnHold({
114
+ tasks,
115
+ now = Date.now,
116
+ setTimer = (fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return t; },
117
+ clearTimer = (t) => clearTimeout(t),
118
+ idleMs = BACKGROUND_HOLD_DEFAULTS.idleMs,
119
+ resumeGraceMs = BACKGROUND_HOLD_DEFAULTS.resumeGraceMs,
120
+ followGraceMs = BACKGROUND_HOLD_DEFAULTS.followGraceMs,
121
+ deadlineAt = null,
122
+ shouldHold = () => true,
123
+ onRelease = () => {},
124
+ nudge = () => false,
125
+ onState = () => {},
126
+ } = {}) {
127
+ let value = null; // the turn's result so far (several results merged while held)
128
+ let holding = false;
129
+ let inTurn = true; // the CLI is in a turn of this hold (the host's prompt, or one it started itself)
130
+ let turnStartedAt = now();
131
+ let drainedWhileIdle = false; // the work it waited for ended after its last result, and no turn started since
132
+ let nudged = false;
133
+ let done = false;
134
+ let idleTimer = null;
135
+ let graceTimer = null;
136
+ let deadlineTimer = null;
137
+
138
+ const clearAll = () => {
139
+ clearTimer(idleTimer); idleTimer = null;
140
+ clearTimer(graceTimer); graceTimer = null;
141
+ clearTimer(deadlineTimer); deadlineTimer = null;
142
+ };
143
+ const finish = () => { done = true; holding = false; clearAll(); return 'resolve'; };
144
+ const release = (reason) => {
145
+ if (done || !holding) return;
146
+ const live = tasks.holdable();
147
+ finish();
148
+ onState({ state: 'released', reason, tasks: live });
149
+ onRelease(reason, live);
150
+ };
151
+ const armIdle = () => {
152
+ clearTimer(idleTimer);
153
+ idleTimer = setTimer(() => release('idle_timeout'), Math.max(1, idleMs));
154
+ };
155
+ const armDeadline = () => {
156
+ if (deadlineTimer || !(Number(deadlineAt) > 0)) return;
157
+ deadlineTimer = setTimer(() => release('deadline'), Math.max(1, Number(deadlineAt) - now()));
158
+ };
159
+ /** Between turns with nothing holdable live: the CLI should come back by itself; nudge it once if it does not. */
160
+ const armGrace = () => {
161
+ clearTimer(graceTimer);
162
+ graceTimer = null;
163
+ if (done || !holding || inTurn || tasks.holdable().length) return;
164
+ const waitMs = drainedWhileIdle ? resumeGraceMs : Math.min(followGraceMs, resumeGraceMs);
165
+ graceTimer = setTimer(() => {
166
+ graceTimer = null;
167
+ if (done || inTurn || tasks.holdable().length) return;
168
+ if (drainedWhileIdle && !nudged && nudge()) {
169
+ nudged = true;
170
+ inTurn = true;
171
+ drainedWhileIdle = false;
172
+ turnStartedAt = now();
173
+ onState({ state: 'nudged', tasks: [] });
174
+ return;
175
+ }
176
+ release('drained');
177
+ }, Math.max(1, waitMs));
178
+ };
179
+
180
+ return {
181
+ get held() { return holding && !done; },
182
+ get done() { return done; },
183
+ /** Any SDK message that is not a result of this turn (task events included: the host applied them first). */
184
+ onEvent(event) {
185
+ if (done) return;
186
+ if (holding) armIdle();
187
+ // Every turn the CLI starts by itself begins with system/init.
188
+ if (event?.type === 'system' && event.subtype === 'init') {
189
+ if (holding && !inTurn) {
190
+ inTurn = true;
191
+ drainedWhileIdle = false;
192
+ turnStartedAt = now();
193
+ clearTimer(graceTimer); graceTimer = null;
194
+ onState({ state: 'resumed', tasks: tasks.holdable() });
195
+ }
196
+ return;
197
+ }
198
+ if (!holding || inTurn) return;
199
+ if (!tasks.holdable().length && !graceTimer) {
200
+ drainedWhileIdle = true;
201
+ armGrace();
202
+ }
203
+ },
204
+ /** A result of this turn. `turnValue` is what the turn resolves with if this is its last result. */
205
+ onResult(event, turnValue) {
206
+ if (done) return 'resolve';
207
+ inTurn = false;
208
+ value = mergeTurnValues(value, turnValue);
209
+ const more = Number(event?.queued_turn_count) > 0;
210
+ const live = tasks.holdable();
211
+ // A task that reported during this turn may start a turn of its own (the CLI queues it): a short wait.
212
+ const reportedInTurn = tasks.notifiedAt() > turnStartedAt;
213
+ if (!more && !live.length && !reportedInTurn) return finish();
214
+ if (!shouldHold(value)) return finish();
215
+ holding = true;
216
+ drainedWhileIdle = false;
217
+ if (live.length) onState({ state: 'holding', tasks: live });
218
+ armIdle();
219
+ armDeadline();
220
+ armGrace();
221
+ return 'hold';
222
+ },
223
+ value: () => value,
224
+ cancel() { if (!done) finish(); },
225
+ };
226
+ }
227
+
228
+ /** Two results of one held turn: the later one's text and event, the charges added up. */
229
+ export function mergeTurnValues(earlier, later) {
230
+ if (!earlier) return later;
231
+ if (!later) return earlier;
232
+ const cost = (Number(earlier.costUsd) || 0) + (Number(later.costUsd) || 0);
233
+ return {
234
+ ...later,
235
+ costUsd: Number(cost.toFixed(8)),
236
+ usage: addUsage(earlier.usage, later.usage),
237
+ heldResults: (Number(earlier.heldResults) || 1) + 1,
238
+ };
239
+ }
@@ -85,6 +85,9 @@ export function buildExecInvocation({
85
85
  model,
86
86
  effort,
87
87
  mcpEnvOverrides = [],
88
+ // Codex: variables its SynaBun MCP server takes from the loop's environment by name (`env_vars`): a secret is never
89
+ // a `-c` value, because a command line is readable by every account of the computer (the run's terminal token).
90
+ mcpEnvVars = [],
88
91
  // Codex: launch overrides as `-c` words (the Windows sandbox of the Admin sandbox setting).
89
92
  codexConfigArgs = [],
90
93
  platform = process.platform,
@@ -103,6 +106,11 @@ export function buildExecInvocation({
103
106
  for (const [key, value] of mcpEnvOverrides) {
104
107
  args.push('-c', `mcp_servers.SynaBun.env.${key}=${codexConfigString(value)}`);
105
108
  }
109
+ const forwarded = [...new Set((Array.isArray(mcpEnvVars) ? mcpEnvVars : []).map(String))];
110
+ for (const name of forwarded) {
111
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error(`Invalid environment variable name: ${name}`);
112
+ }
113
+ if (forwarded.length) args.push('-c', `mcp_servers.SynaBun.env_vars=[${forwarded.map(codexConfigString).join(',')}]`);
106
114
  const normalizedEffort = codexReasoningEffort(effort);
107
115
  if (normalizedEffort) args.push('-c', `model_reasoning_effort=${codexConfigString(normalizedEffort)}`);
108
116
  if (model) args.push('--model', String(model));
@@ -25,7 +25,7 @@
25
25
  // isAllowedWebSocketOrigin(req, {port, allowedOrigins}) a browser's Origin must be this server, under one of its own names
26
26
  // isAllowedHost(host, {allowedHosts, machineName}) is this Host one of our names, one DNS rebinding cannot borrow?
27
27
  // hostNameOf(host) the name a Host header holds, as the rule compares it
28
- // refuseUpgrade(socket, status) answer the upgrade with an HTTP error, close
28
+ // refuseUpgrade(socket, status, message?, headers?) answer the upgrade with an HTTP error, close
29
29
  //
30
30
  // isOwnerOrigin(origin, {port, ownNames, addresses}) a page of this server at its port, under loopback or one
31
31
  // of this computer's names and addresses (tunnel start / stop)
@@ -51,8 +51,9 @@ import { machineNames as thisMachine } from './machine-names.js';
51
51
  /** Headers that mean a proxy or tunnel forwarded the request (lower-case). */
52
52
  export const PROXY_HEADERS = Object.freeze(['cf-connecting-ip', 'cf-ray', 'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto', 'forwarded', 'x-real-ip', 'via']);
53
53
 
54
- /** Headers that mark a request as an agent's rather than the user's (lower-case). */
55
- export const AGENT_HEADERS = Object.freeze(['x-synabun-desktop-grant', 'x-synabun-terminal', 'x-synabun-role', 'x-synabun-assistant']);
54
+ /** Headers that mark a request as an agent's rather than the user's (lower-case). A run's terminal token
55
+ * (lib/terminal-tokens.js) is one: only a run's own MCP server sends it, never the owner's page. */
56
+ export const AGENT_HEADERS = Object.freeze(['x-synabun-desktop-grant', 'x-synabun-terminal', 'x-synabun-role', 'x-synabun-assistant', 'x-synabun-terminal-token']);
56
57
 
57
58
  const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
58
59
  // RFC 3986 dec-octet: 0-255, no leading zeros (Node never reports them).
@@ -453,16 +454,20 @@ export function ownerRouteGuard({
453
454
  return ownerRoute;
454
455
  }
455
456
 
456
- /** Answer a WebSocket upgrade with a plain HTTP error (default 403) and close the socket. */
457
- export function refuseUpgrade(socket, status = 403, message = status === 403 ? 'Forbidden' : 'Bad Request') {
457
+ /** Answer a WebSocket upgrade with a plain HTTP error (default 403) and close the socket. `headers`: a few more
458
+ * (Retry-After for a 503); a name or value with a line break or a colon in the name is left out. */
459
+ export function refuseUpgrade(socket, status = 403, message = status === 403 ? 'Forbidden' : 'Bad Request', headers = {}) {
458
460
  if (!socket) return;
459
461
  // Node drops its own 'error' listener from an upgrade socket: without one, a
460
462
  // peer reset while the answer is written would be an uncaught exception.
461
463
  socket.on?.('error', () => { try { socket.destroy(); } catch {} });
462
464
  if (!socket.writable) { try { socket.destroy(); } catch {} return; }
465
+ const extra = Object.entries(headers && typeof headers === 'object' ? headers : {})
466
+ .filter(([name, value]) => /^[A-Za-z0-9-]+$/.test(name) && !/[\r\n]/.test(String(value)))
467
+ .map(([name, value]) => `${name}: ${String(value)}\r\n`).join('');
463
468
  try {
464
469
  socket.once('finish', () => socket.destroy());
465
- socket.end(`HTTP/1.1 ${status} ${message}\r\nConnection: close\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: ${Buffer.byteLength(message)}\r\n\r\n${message}`);
470
+ socket.end(`HTTP/1.1 ${status} ${message}\r\nConnection: close\r\n${extra}Content-Type: text/plain; charset=utf-8\r\nContent-Length: ${Buffer.byteLength(message)}\r\n\r\n${message}`);
466
471
  } catch {
467
472
  try { socket.destroy(); } catch {}
468
473
  }
@@ -12,6 +12,7 @@ import { existsSync, mkdirSync, readdirSync, statSync, unlinkSync } from 'node:f
12
12
  import { appendFile } from 'node:fs/promises';
13
13
  import { resolve, join } from 'node:path';
14
14
  import { getDataHome } from '../../lib/paths.js';
15
+ import { redactTerminalSecrets, scrubTokenText } from './terminal-token-redaction.js';
15
16
 
16
17
  const DATA_HOME = getDataHome();
17
18
  const LOG_DIR = resolve(DATA_HOME, 'data', 'logs');
@@ -86,7 +87,11 @@ function _appendOrdered(path, line, terminalSessionId) {
86
87
 
87
88
  export function loopLog(terminalSessionId, tag, msg, meta = undefined) {
88
89
  const ts = new Date().toISOString();
89
- const safeMeta = (meta && Object.keys(meta).length > 0) ? safeJson(meta) : '';
90
+ // A run's secrets never reach a log line, the file under data/logs or the console (lib/terminal-token-redaction.js):
91
+ // a message or its data may quote what an agent printed or a provider threw, a token included (review 972afb74,
92
+ // finding 5). The JSON is scrubbed again as text, for a value it holds in a form the object walk does not open.
93
+ const safeMeta = (meta && Object.keys(meta).length > 0) ? scrubTokenText(safeJson(redactTerminalSecrets(meta))) : '';
94
+ msg = scrubTokenText(typeof msg === 'string' ? msg : String(msg ?? ''));
90
95
  const line = `${ts} | ${tag} | ${msg}${safeMeta ? ' | ' + safeMeta : ''}\n`;
91
96
 
92
97
  // Console mirror
@@ -14,22 +14,24 @@ export const EXTERNAL_SERVER_LIMITATIONS = Object.freeze({ codex: 'Plugin-provid
14
14
  /** Where Antigravity keeps its MCP servers: { mcpServers: { name: { command, args, env, disabled } | { serverUrl, headers, disabled } } }. */
15
15
  export function antigravityMcpConfigPath(home = homedir()) { return join(home, '.gemini', 'config', 'mcp_config.json'); }
16
16
  export const externalServerName = name => typeof name === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(name) && external(name);
17
+ // `reason` and `errno` say what went wrong without the path or a byte of the file; they reach the page.
18
+ const discoveryFailure = (message, reason, errno = null) => Object.assign(new Error(message), { code: 'MCP_DISCOVERY_FAILED', reason, ...(errno ? { errno } : {}) });
17
19
  function read(path, fallback = null) {
18
20
  try { return readFileSync(path, 'utf8'); }
19
- catch (error) { if (error.code === 'ENOENT') return fallback; throw Object.assign(new Error('Could not read an MCP configuration source'), { code: 'MCP_DISCOVERY_FAILED' }); }
21
+ catch (error) { if (error.code === 'ENOENT') return fallback; throw discoveryFailure('Could not read an MCP configuration source', 'unreadable', typeof error.code === 'string' && /^E[A-Z]+$/.test(error.code) ? error.code : null); }
20
22
  }
21
23
  function document(path) {
22
24
  const text = read(path);
23
25
  if (text === null) return {};
24
26
  try { return object(parseJsonc(text)); }
25
- catch { throw Object.assign(new Error('Could not parse an MCP configuration source'), { code: 'MCP_DISCOVERY_FAILED' }); }
27
+ catch { throw discoveryFailure('Could not parse an MCP configuration source', 'unparseable'); }
26
28
  }
27
29
  /** Names/kinds/enabled only: Codex keeps definitions and secrets in its own TOML. Quoted dotted names stay whole. */
28
30
  export function parseCodexMcpServers(text = '') {
29
31
  // Structural TOML reader: supports tables, dotted/quoted keys and inline maps without copying definitions.
30
32
  const tokens = []; let at = 0;
31
33
  const input = String(text);
32
- const fail = () => Object.assign(new Error('Could not parse Codex MCP configuration'), { code: 'MCP_DISCOVERY_FAILED' });
34
+ const fail = () => discoveryFailure('Could not parse Codex MCP configuration', 'unparseable');
33
35
  while (at < input.length) {
34
36
  const ch = input[at];
35
37
  if (ch === '#') { while (at < input.length && input[at] !== '\n') at++; continue; }
@@ -168,7 +170,7 @@ export function externalServerInventory({ provider, cwd = process.cwd(), codexHo
168
170
  let base = opencodeConfig;
169
171
  if (base == null) {
170
172
  const docs = readOpencodeConfigDocuments(configDir);
171
- if (docs.some(row => row.error)) throw Object.assign(new Error('Could not parse an MCP configuration source'), { code: 'MCP_DISCOVERY_FAILED' });
173
+ if (docs.some(row => row.error)) throw discoveryFailure('Could not parse an MCP configuration source', 'unparseable');
172
174
  base = mergedOpencodeConfig(docs);
173
175
  }
174
176
  for (const [name, entry] of Object.entries(mcpServersOf(base))) add(name, entry, 'user');
@@ -254,13 +256,38 @@ export function selectExternalServers(tools, inventory) {
254
256
  if (problems.length) throw Object.assign(new Error(problems.map(problem => problem.hint).join(' ')), { code: 'TOOLS_INVALID', status: 400, problems });
255
257
  return { names: [...selected].sort(), disabled: inventory.servers.filter(row => !selected.has(row.name)).map(row => row.name) };
256
258
  }
257
- export function externalCatalog(options = {}) {
258
- const rows = new Map();
259
- for (const provider of ['codex', 'opencode', 'claude-code', 'antigravity']) for (const row of discoverExternalServers({ ...options, provider })) {
260
- if (!rows.has(row.name)) rows.set(row.name, { ref: `mcp:${row.name}`, label: row.name, selectable: row.selectable, providers: { codex: 'absent', opencode: 'absent', 'claude-code': 'absent', antigravity: 'absent' }, blocked: row.blocked });
261
- rows.get(row.name).providers[provider] = row.blocked ? 'blocked' : row.deliverable ? 'deliverable' : 'unavailable';
259
+ export const EXTERNAL_CATALOG_PROVIDERS = Object.freeze(['codex', 'opencode', 'claude-code', 'antigravity']);
260
+ /** The public form of a provider whose configuration could not be read: no path, no file content. */
261
+ export function externalDiscoveryError(provider, error) {
262
+ return { provider, code: 'MCP_DISCOVERY_FAILED', reason: error?.reason === 'unparseable' ? 'unparseable' : 'unreadable', ...(error?.errno ? { errno: error.errno } : {}) };
263
+ }
264
+ /**
265
+ * Names-only catalog over every provider, with the providers that could not be read beside it.
266
+ * A provider in `errors` is `unknown` on every row, never `absent` or `deliverable`: nothing may read it
267
+ * as "no servers there". `strict` rethrows the first discovery failure (what every validation and grant
268
+ * path needs); any other error always propagates.
269
+ */
270
+ export function externalCatalogReport(options = {}, { strict = false } = {}) {
271
+ const rows = new Map(), errors = [];
272
+ for (const provider of EXTERNAL_CATALOG_PROVIDERS) {
273
+ let servers;
274
+ try { servers = discoverExternalServers({ ...options, provider }); }
275
+ catch (error) { if (strict || error?.code !== 'MCP_DISCOVERY_FAILED') throw error; errors.push(externalDiscoveryError(provider, error)); continue; }
276
+ for (const row of servers) {
277
+ if (!rows.has(row.name)) rows.set(row.name, { ref: `mcp:${row.name}`, label: row.name, selectable: row.selectable, providers: { codex: 'absent', opencode: 'absent', 'claude-code': 'absent', antigravity: 'absent' }, blocked: row.blocked });
278
+ rows.get(row.name).providers[provider] = row.blocked ? 'blocked' : row.deliverable ? 'deliverable' : 'unavailable';
279
+ }
262
280
  }
263
- return [...rows.values()].sort((a, b) => a.ref.localeCompare(b.ref));
281
+ for (const { provider } of errors) for (const row of rows.values()) row.providers[provider] = 'unknown';
282
+ return { servers: [...rows.values()].sort((a, b) => a.ref.localeCompare(b.ref)), errors };
283
+ }
284
+ /** Strict: one unreadable provider fails the whole catalog (validation and worker paths). */
285
+ export function externalCatalog(options = {}) { return externalCatalogReport(options, { strict: true }).servers; }
286
+ /** One row's availability for a provider when the catalogs of several folders are merged. */
287
+ export function mergeExternalAvailability(previous, next) {
288
+ if (next === 'deliverable' || previous === 'absent') return next;
289
+ if (previous === 'unknown' && next !== 'absent') return next;
290
+ return previous;
264
291
  }
265
292
  /** Complete validated disabled entries, proved on 2.1.4. No owner env/header/URL payload in the disabled copy. */
266
293
  export function scopeOpenCodeServers(config, tools, inventory, { node = process.execPath } = {}) {
@@ -319,14 +346,38 @@ export async function waitForClaudeMcpScope(q, names, { timeoutMs = 30000 } = {}
319
346
  }
320
347
  throw Object.assign(new Error('Claude MCP scope could not be enforced before the first turn'), { code: 'MCP_SCOPE_UNENFORCED' });
321
348
  }
349
+ /** Values shorter than this are never redacted: a short or common word would be erased from ordinary output. */
350
+ export const MIN_MCP_SECRET_LENGTH = 8;
322
351
  export function redactMcpValues(value, values) {
323
- if (typeof value === 'string') { for (const secret of [...new Set(values)].filter(Boolean).sort((a, b) => b.length - a.length)) value = value.split(secret).join('[MCP value]'); return value; }
352
+ if (typeof value === 'string') { for (const secret of [...new Set(values)].filter(item => typeof item === 'string' && item.length >= MIN_MCP_SECRET_LENGTH).sort((a, b) => b.length - a.length)) value = value.split(secret).join('[MCP value]'); return value; }
324
353
  if (Array.isArray(value)) return value.map(item => redactMcpValues(item, values));
325
354
  if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redactMcpValues(item, values)]));
326
355
  return value;
327
356
  }
328
357
 
329
- export function mcpDefinitionValues(servers) {
358
+ const SECRET_QUERY_NAME = /token|key|secret|auth|pass|pwd|sig|credential|session|code/i;
359
+ /** The secrets a URL carries (userinfo, credential-named query values), never the URL itself. */
360
+ export function urlSecretValues(url) {
361
+ if (typeof url !== 'string' || !url) return [];
362
+ let parsed; try { parsed = new URL(url); } catch { return []; }
363
+ const out = [];
364
+ for (const part of [parsed.username, parsed.password]) if (part) { out.push(part); try { out.push(decodeURIComponent(part)); } catch {} }
365
+ for (const [name, value] of parsed.searchParams) if (value && SECRET_QUERY_NAME.test(name)) { out.push(value); out.push(encodeURIComponent(value)); }
366
+ return out;
367
+ }
368
+
369
+ /**
370
+ * The real secrets of MCP server definitions: env / environment and header values, authToken, oauth strings
371
+ * and the secrets inside a URL. Never command, args, cwd, type or a whole URL, and never SynaBun's own entry
372
+ * (its headers name the project, terminal and role: ordinary words). `${VAR}` / `{env:VAR}` references are
373
+ * expanded through `env` when given. Values under MIN_MCP_SECRET_LENGTH are dropped.
374
+ */
375
+ export function mcpSecretValues(servers, { env = null, exclude = ['SynaBun'] } = {}) {
330
376
  const strings = value => typeof value === 'string' ? [value] : Array.isArray(value) ? value.flatMap(strings) : value && typeof value === 'object' ? Object.values(value).flatMap(strings) : [];
331
- return [...new Set(Object.values(servers || {}).flatMap(entry => ['command', 'args', 'cwd', 'env', 'environment', 'headers', 'url', 'oauth', 'headersHelper', 'authToken'].flatMap(field => strings(entry[field]))))].filter(Boolean);
377
+ const expand = value => env ? value.replace(/\{env:([A-Za-z_][A-Za-z0-9_]*)\}|\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (whole, a, b) => env[a || b] ?? whole) : value;
378
+ const values = Object.entries(servers || {}).filter(([name]) => !exclude.includes(name)).flatMap(([, entry]) => entry && typeof entry === 'object' ? [
379
+ ...['env', 'environment', 'headers', 'oauth', 'authToken'].flatMap(field => strings(entry[field])).flatMap(value => { const bare = /^(?:Bearer|Basic|Token|Bot)\s+(\S.*)$/i.exec(value); return bare ? [value, bare[1]] : [value]; }),
380
+ ...urlSecretValues(entry.url),
381
+ ] : []).map(expand);
382
+ return [...new Set(values)].filter(value => value.length >= MIN_MCP_SECRET_LENGTH);
332
383
  }