synabun 2.2.2 → 2.3.0

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 (276) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +1 -1
  3. package/docs/whatsapp.md +52 -20
  4. package/lib/mcp-build.js +519 -0
  5. package/lib/mcp-dist.js +10 -4
  6. package/lib/server-supervisor.js +7 -1
  7. package/lib/virustotal.mjs +4 -2
  8. package/mcp-server/dist/http.d.ts +38 -0
  9. package/mcp-server/dist/http.d.ts.map +1 -1
  10. package/mcp-server/dist/http.js +75 -7
  11. package/mcp-server/dist/http.js.map +1 -1
  12. package/mcp-server/dist/services/browser-route-flow.d.ts +3 -2
  13. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -1
  14. package/mcp-server/dist/services/browser-route-flow.js +4 -3
  15. package/mcp-server/dist/services/browser-route-flow.js.map +1 -1
  16. package/mcp-server/dist/services/embedding-service.d.ts.map +1 -1
  17. package/mcp-server/dist/services/embedding-service.js +2 -1
  18. package/mcp-server/dist/services/embedding-service.js.map +1 -1
  19. package/mcp-server/dist/services/neural-interface.d.ts +21 -0
  20. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  21. package/mcp-server/dist/services/neural-interface.js +76 -4
  22. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  23. package/mcp-server/dist/services/tool-catalog.js +2 -2
  24. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  25. package/mcp-server/dist/tools/agents.d.ts +3 -2
  26. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  27. package/mcp-server/dist/tools/agents.js +6 -4
  28. package/mcp-server/dist/tools/agents.js.map +1 -1
  29. package/mcp-server/dist/tools/browser-advanced.d.ts +3 -1
  30. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  31. package/mcp-server/dist/tools/browser-advanced.js +30 -8
  32. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  33. package/mcp-server/dist/tools/browser-navigate.d.ts +3 -3
  34. package/mcp-server/dist/tools/browser-navigate.d.ts.map +1 -1
  35. package/mcp-server/dist/tools/browser-navigate.js +19 -16
  36. package/mcp-server/dist/tools/browser-navigate.js.map +1 -1
  37. package/mcp-server/dist/tools/browser-observe.d.ts +2 -1
  38. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  39. package/mcp-server/dist/tools/browser-observe.js +61 -20
  40. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  41. package/mcp-server/dist/tools/morelogin.d.ts +13 -3
  42. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  43. package/mcp-server/dist/tools/morelogin.js +81 -20
  44. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  45. package/mcp-server/dist/tools/youtube/upload.d.ts.map +1 -1
  46. package/mcp-server/dist/tools/youtube/upload.js +225 -88
  47. package/mcp-server/dist/tools/youtube/upload.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 +79 -7
  51. package/mcp-server/src/services/browser-route-flow.ts +4 -3
  52. package/mcp-server/src/services/embedding-service.ts +2 -1
  53. package/mcp-server/src/services/neural-interface.ts +77 -4
  54. package/mcp-server/src/services/tool-catalog.ts +2 -2
  55. package/mcp-server/src/tools/agents.ts +8 -4
  56. package/mcp-server/src/tools/browser-advanced.ts +29 -8
  57. package/mcp-server/src/tools/browser-navigate.ts +19 -16
  58. package/mcp-server/src/tools/browser-observe.ts +62 -20
  59. package/mcp-server/src/tools/morelogin.ts +81 -20
  60. package/mcp-server/src/tools/youtube/upload.ts +218 -99
  61. package/neural-interface/i18n/en.json +631 -123
  62. package/neural-interface/i18n/pt-BR.json +518 -10
  63. package/neural-interface/lib/assistant-api.js +26 -0
  64. package/neural-interface/lib/assistant-brains/claude.js +5 -0
  65. package/neural-interface/lib/assistant-catalog.js +114 -1
  66. package/neural-interface/lib/assistant-dispatch.js +71 -1
  67. package/neural-interface/lib/assistant-persona.js +14 -7
  68. package/neural-interface/lib/assistant-router.js +6 -4
  69. package/neural-interface/lib/assistant-runtime.js +3 -0
  70. package/neural-interface/lib/assistant-task-prompt.js +5 -0
  71. package/neural-interface/lib/automation-approval.js +249 -0
  72. package/neural-interface/lib/automation-browser-owner-access.js +82 -0
  73. package/neural-interface/lib/backup-service.js +16 -1
  74. package/neural-interface/lib/browser-background-tab.js +72 -3
  75. package/neural-interface/lib/browser-extraction.js +106 -45
  76. package/neural-interface/lib/browser-profile-choices.js +143 -0
  77. package/neural-interface/lib/browser-profiles.js +142 -0
  78. package/neural-interface/lib/browser-tab-recovery.js +153 -0
  79. package/neural-interface/lib/browser-tool-policy.js +2 -0
  80. package/neural-interface/lib/chromium-on-device-model.js +67 -0
  81. package/neural-interface/lib/claude-agent-bridge.js +7 -4
  82. package/neural-interface/lib/claude-model-catalog.js +12 -0
  83. package/neural-interface/lib/effort-levels.js +28 -2
  84. package/neural-interface/lib/local-profile-proxy.js +362 -0
  85. package/neural-interface/lib/local-profiles.js +929 -0
  86. package/neural-interface/lib/loop-logger.js +25 -4
  87. package/neural-interface/lib/maritaca/api.js +179 -0
  88. package/neural-interface/lib/maritaca/attachments.js +44 -0
  89. package/neural-interface/lib/maritaca/client.js +362 -0
  90. package/neural-interface/lib/maritaca/key-store.js +122 -0
  91. package/neural-interface/lib/maritaca/models.js +181 -0
  92. package/neural-interface/lib/maritaca/modes.js +39 -0
  93. package/neural-interface/lib/maritaca/opencode-proxy.js +236 -0
  94. package/neural-interface/lib/maritaca/opencode-stream.js +345 -0
  95. package/neural-interface/lib/maritaca/opencode.js +218 -0
  96. package/neural-interface/lib/maritaca/panel-bridge.js +273 -0
  97. package/neural-interface/lib/maritaca/sessions.js +198 -0
  98. package/neural-interface/lib/morelogin-agent-profiles.js +149 -0
  99. package/neural-interface/lib/morelogin.js +278 -14
  100. package/neural-interface/lib/native-loop-providers.js +3 -1
  101. package/neural-interface/lib/owner-authority.js +30 -12
  102. package/neural-interface/lib/page-session.js +43 -17
  103. package/neural-interface/lib/request-gate.js +2 -0
  104. package/neural-interface/lib/system-activity.js +1 -1
  105. package/neural-interface/lib/terminal-tokens.js +82 -5
  106. package/neural-interface/package-lock.json +3 -2
  107. package/neural-interface/package.json +2 -1
  108. package/neural-interface/public/assets/mascot/README.md +11 -0
  109. package/neural-interface/public/assets/mascot/ask.gif +0 -0
  110. package/neural-interface/public/assets/mascot/ask.png +0 -0
  111. package/neural-interface/public/assets/mascot/blocked.gif +0 -0
  112. package/neural-interface/public/assets/mascot/blocked.png +0 -0
  113. package/neural-interface/public/assets/mascot/budget.gif +0 -0
  114. package/neural-interface/public/assets/mascot/budget.png +0 -0
  115. package/neural-interface/public/assets/mascot/computer.gif +0 -0
  116. package/neural-interface/public/assets/mascot/computer.png +0 -0
  117. package/neural-interface/public/assets/mascot/edit.gif +0 -0
  118. package/neural-interface/public/assets/mascot/edit.png +0 -0
  119. package/neural-interface/public/assets/mascot/error.gif +0 -0
  120. package/neural-interface/public/assets/mascot/error.png +0 -0
  121. package/neural-interface/public/assets/mascot/hover-attention.gif +0 -0
  122. package/neural-interface/public/assets/mascot/hover-attention.png +0 -0
  123. package/neural-interface/public/assets/mascot/idle-hero.gif +0 -0
  124. package/neural-interface/public/assets/mascot/idle-hero.png +0 -0
  125. package/neural-interface/public/assets/mascot/idle.gif +0 -0
  126. package/neural-interface/public/assets/mascot/idle.png +0 -0
  127. package/neural-interface/public/assets/mascot/manifest.json +254 -0
  128. package/neural-interface/public/assets/mascot/mcp.gif +0 -0
  129. package/neural-interface/public/assets/mascot/mcp.png +0 -0
  130. package/neural-interface/public/assets/mascot/memory.gif +0 -0
  131. package/neural-interface/public/assets/mascot/memory.png +0 -0
  132. package/neural-interface/public/assets/mascot/offline.gif +0 -0
  133. package/neural-interface/public/assets/mascot/offline.png +0 -0
  134. package/neural-interface/public/assets/mascot/pick.gif +0 -0
  135. package/neural-interface/public/assets/mascot/pick.png +0 -0
  136. package/neural-interface/public/assets/mascot/plan.gif +0 -0
  137. package/neural-interface/public/assets/mascot/plan.png +0 -0
  138. package/neural-interface/public/assets/mascot/present.gif +0 -0
  139. package/neural-interface/public/assets/mascot/present.png +0 -0
  140. package/neural-interface/public/assets/mascot/project.gif +0 -0
  141. package/neural-interface/public/assets/mascot/project.png +0 -0
  142. package/neural-interface/public/assets/mascot/read.gif +0 -0
  143. package/neural-interface/public/assets/mascot/read.png +0 -0
  144. package/neural-interface/public/assets/mascot/runs.gif +0 -0
  145. package/neural-interface/public/assets/mascot/runs.png +0 -0
  146. package/neural-interface/public/assets/mascot/scenes/automation.gif +0 -0
  147. package/neural-interface/public/assets/mascot/scenes/automation.png +0 -0
  148. package/neural-interface/public/assets/mascot/scenes/browser.gif +0 -0
  149. package/neural-interface/public/assets/mascot/scenes/browser.png +0 -0
  150. package/neural-interface/public/assets/mascot/scenes/code.gif +0 -0
  151. package/neural-interface/public/assets/mascot/scenes/code.png +0 -0
  152. package/neural-interface/public/assets/mascot/scenes/complex.gif +0 -0
  153. package/neural-interface/public/assets/mascot/scenes/complex.png +0 -0
  154. package/neural-interface/public/assets/mascot/scenes/computer.gif +0 -0
  155. package/neural-interface/public/assets/mascot/scenes/computer.png +0 -0
  156. package/neural-interface/public/assets/mascot/scenes/design.gif +0 -0
  157. package/neural-interface/public/assets/mascot/scenes/design.png +0 -0
  158. package/neural-interface/public/assets/mascot/scenes/edit.gif +0 -0
  159. package/neural-interface/public/assets/mascot/scenes/edit.png +0 -0
  160. package/neural-interface/public/assets/mascot/scenes/generic.gif +0 -0
  161. package/neural-interface/public/assets/mascot/scenes/generic.png +0 -0
  162. package/neural-interface/public/assets/mascot/scenes/image_gen.gif +0 -0
  163. package/neural-interface/public/assets/mascot/scenes/image_gen.png +0 -0
  164. package/neural-interface/public/assets/mascot/scenes/manifest.json +173 -0
  165. package/neural-interface/public/assets/mascot/scenes/memory.gif +0 -0
  166. package/neural-interface/public/assets/mascot/scenes/memory.png +0 -0
  167. package/neural-interface/public/assets/mascot/scenes/quick.gif +0 -0
  168. package/neural-interface/public/assets/mascot/scenes/quick.png +0 -0
  169. package/neural-interface/public/assets/mascot/scenes/read.gif +0 -0
  170. package/neural-interface/public/assets/mascot/scenes/read.png +0 -0
  171. package/neural-interface/public/assets/mascot/scenes/research.gif +0 -0
  172. package/neural-interface/public/assets/mascot/scenes/research.png +0 -0
  173. package/neural-interface/public/assets/mascot/scenes/review.gif +0 -0
  174. package/neural-interface/public/assets/mascot/scenes/review.png +0 -0
  175. package/neural-interface/public/assets/mascot/scenes/search.gif +0 -0
  176. package/neural-interface/public/assets/mascot/scenes/search.png +0 -0
  177. package/neural-interface/public/assets/mascot/scenes/shell.gif +0 -0
  178. package/neural-interface/public/assets/mascot/scenes/shell.png +0 -0
  179. package/neural-interface/public/assets/mascot/scenes/thinking.gif +0 -0
  180. package/neural-interface/public/assets/mascot/scenes/thinking.png +0 -0
  181. package/neural-interface/public/assets/mascot/scenes/video_gen.gif +0 -0
  182. package/neural-interface/public/assets/mascot/scenes/video_gen.png +0 -0
  183. package/neural-interface/public/assets/mascot/scenes/web.gif +0 -0
  184. package/neural-interface/public/assets/mascot/scenes/web.png +0 -0
  185. package/neural-interface/public/assets/mascot/search.gif +0 -0
  186. package/neural-interface/public/assets/mascot/search.png +0 -0
  187. package/neural-interface/public/assets/mascot/shell.gif +0 -0
  188. package/neural-interface/public/assets/mascot/shell.png +0 -0
  189. package/neural-interface/public/assets/mascot/skill.gif +0 -0
  190. package/neural-interface/public/assets/mascot/skill.png +0 -0
  191. package/neural-interface/public/assets/mascot/sleep.gif +0 -0
  192. package/neural-interface/public/assets/mascot/sleep.png +0 -0
  193. package/neural-interface/public/assets/mascot/subagent.gif +0 -0
  194. package/neural-interface/public/assets/mascot/subagent.png +0 -0
  195. package/neural-interface/public/assets/mascot/success.gif +0 -0
  196. package/neural-interface/public/assets/mascot/success.png +0 -0
  197. package/neural-interface/public/assets/mascot/think.gif +0 -0
  198. package/neural-interface/public/assets/mascot/think.png +0 -0
  199. package/neural-interface/public/assets/mascot/wait.gif +0 -0
  200. package/neural-interface/public/assets/mascot/wait.png +0 -0
  201. package/neural-interface/public/assets/mascot/watch.gif +0 -0
  202. package/neural-interface/public/assets/mascot/watch.png +0 -0
  203. package/neural-interface/public/assets/mascot/web.gif +0 -0
  204. package/neural-interface/public/assets/mascot/web.png +0 -0
  205. package/neural-interface/public/onboarding.html +14 -1
  206. package/neural-interface/public/shared/agent-runtime-options.js +49 -8
  207. package/neural-interface/public/shared/agy/agy-panel.js +2 -2
  208. package/neural-interface/public/shared/api.js +4 -4
  209. package/neural-interface/public/shared/assistant/asst-ask-styles.js +8 -8
  210. package/neural-interface/public/shared/assistant/asst-ask.js +1 -1
  211. package/neural-interface/public/shared/assistant/asst-brain-picker.js +99 -9
  212. package/neural-interface/public/shared/assistant/asst-control.js +1 -1
  213. package/neural-interface/public/shared/assistant/asst-limit-wait.js +4 -4
  214. package/neural-interface/public/shared/assistant/asst-panel.js +6 -2
  215. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -4
  216. package/neural-interface/public/shared/assistant/asst-render.js +6 -6
  217. package/neural-interface/public/shared/assistant/asst-route-models.js +64 -4
  218. package/neural-interface/public/shared/assistant/asst-route.js +24 -7
  219. package/neural-interface/public/shared/assistant/asst-routes-editor.js +154 -39
  220. package/neural-interface/public/shared/assistant/asst-run-stage.js +3 -3
  221. package/neural-interface/public/shared/assistant/asst-scene-styles.js +8 -111
  222. package/neural-interface/public/shared/assistant/asst-scenes.js +46 -318
  223. package/neural-interface/public/shared/assistant/asst-sidepanel.js +2 -2
  224. package/neural-interface/public/shared/assistant/asst-state.js +72 -2
  225. package/neural-interface/public/shared/assistant/asst-styles.js +58 -14
  226. package/neural-interface/public/shared/automation-approval-view.js +75 -0
  227. package/neural-interface/public/shared/cdx/cdx-panel.js +2 -2
  228. package/neural-interface/public/shared/context-menu-model.js +2 -0
  229. package/neural-interface/public/shared/editor/editor-panel-logic.js +10 -0
  230. package/neural-interface/public/shared/editor/editor-panel.js +10 -2
  231. package/neural-interface/public/shared/html-shell.js +30 -22
  232. package/neural-interface/public/shared/morelogin-profile-choices.js +107 -0
  233. package/neural-interface/public/shared/morelogin-profile-field.js +186 -0
  234. package/neural-interface/public/shared/mtc/mtc-client.js +181 -0
  235. package/neural-interface/public/shared/mtc/mtc-compose.js +40 -0
  236. package/neural-interface/public/shared/mtc/mtc-copy.js +253 -0
  237. package/neural-interface/public/shared/mtc/mtc-logic.js +478 -0
  238. package/neural-interface/public/shared/mtc/mtc-panel.js +1354 -0
  239. package/neural-interface/public/shared/mtc/mtc-render.js +172 -0
  240. package/neural-interface/public/shared/mtc/mtc-styles.js +437 -0
  241. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +6 -2
  242. package/neural-interface/public/shared/provider-icons.js +3 -0
  243. package/neural-interface/public/shared/schedules-view.js +7 -0
  244. package/neural-interface/public/shared/server-back.js +50 -0
  245. package/neural-interface/public/shared/settings/settings-browser-owner-access.js +72 -0
  246. package/neural-interface/public/shared/settings/settings-data.js +1 -0
  247. package/neural-interface/public/shared/settings/settings-ia.js +3 -1
  248. package/neural-interface/public/shared/settings/settings-local-profiles.js +153 -0
  249. package/neural-interface/public/shared/settings/settings-maritaca-opencode.js +105 -0
  250. package/neural-interface/public/shared/sidepanel-session-status.js +16 -2
  251. package/neural-interface/public/shared/state.js +1 -1
  252. package/neural-interface/public/shared/styles.css +356 -157
  253. package/neural-interface/public/shared/synabun-mascot-assets.js +67 -0
  254. package/neural-interface/public/shared/synabun-mascot.js +136 -12
  255. package/neural-interface/public/shared/synabun-ticker.js +3 -0
  256. package/neural-interface/public/shared/topright-overflow-logic.js +1 -0
  257. package/neural-interface/public/shared/ui-automation-approval.js +188 -0
  258. package/neural-interface/public/shared/ui-automation-studio.js +130 -90
  259. package/neural-interface/public/shared/ui-claude-panel.js +50 -2
  260. package/neural-interface/public/shared/ui-maritaca-panel.js +15 -0
  261. package/neural-interface/public/shared/ui-navbar.js +17 -0
  262. package/neural-interface/public/shared/ui-panels.js +3 -1
  263. package/neural-interface/public/shared/ui-schedules-studio.js +118 -17
  264. package/neural-interface/public/shared/ui-scroll-follow.js +3 -0
  265. package/neural-interface/public/shared/ui-settings.js +590 -27
  266. package/neural-interface/public/shared/ui-sidepanel-session-entry.js +8 -2
  267. package/neural-interface/public/shared/ui-sidepanel-sessions.js +3 -3
  268. package/neural-interface/public/shared/ui-sidepanel-tray.js +24 -0
  269. package/neural-interface/public/shared/ui-sidepanel-windows.js +1 -1
  270. package/neural-interface/scripts/build-mascot-assets.mjs +30 -0
  271. package/neural-interface/server.js +1784 -195
  272. package/npm-shrinkwrap.json +5 -17
  273. package/package.json +5 -6
  274. package/postinstall.js +38 -39
  275. package/setup.js +33 -31
  276. package/skills/synabun/modules/changelog.md +14 -0
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Chromium's Optimization Guide downloads models into the profile it runs in: the on-device foundational
3
+ * model (Gemini Nano: `OptGuideOnDeviceModel/<version>/weights.bin`, about 4 GB) and the smaller prediction
4
+ * and hints models. SynaBun's automation browsers use none of them, and one such weights.bin, written into a
5
+ * SynaBun browser profile, once ended up in git. Every Chromium SynaBun launches itself gets these features
6
+ * turned off on its command line.
7
+ *
8
+ * Chromium reads one --disable-features: when the switch is given more than once, the last value replaces the
9
+ * others. So the list is merged into the one flag the arguments already carry (SynaBun's own, or one in the
10
+ * user's extra launch arguments), never added as a second flag. Under Playwright, SynaBun's arguments come after
11
+ * Playwright's defaults, so the merged flag is the one Chromium keeps.
12
+ *
13
+ * No imports: page-free and unit-tested (tests/chromium-on-device-model.test.mjs).
14
+ */
15
+
16
+ /** The Optimization Guide features that fetch or run downloaded models. */
17
+ export const ON_DEVICE_MODEL_FEATURES = Object.freeze([
18
+ 'OptimizationGuideModelDownloading',
19
+ 'OptimizationGuideOnDeviceModel',
20
+ 'OptimizationHintsFetching',
21
+ 'OptimizationTargetPrediction',
22
+ 'OptimizationHints',
23
+ ]);
24
+
25
+ // Chromium takes a switch after "--" or "-" (POSIX and Windows alike).
26
+ const DISABLE_FEATURES = /^--?disable-features(?:=([\s\S]*))?$/;
27
+
28
+ /** The feature names of one --disable-features value: comma-separated, surrounding quotes and blanks dropped. */
29
+ function featureNames(value) {
30
+ let text = String(value ?? '').trim();
31
+ const quoted = /^(["'])([\s\S]*)\1$/.exec(text);
32
+ if (quoted) text = quoted[2];
33
+ return text.split(',').map((name) => name.trim()).filter(Boolean);
34
+ }
35
+
36
+ /**
37
+ * `args` with exactly one --disable-features, at the place of the first one it had (or at the end), naming
38
+ * every feature any of its --disable-features named, in order, then `features`; each name once. The other
39
+ * arguments keep their order. `args` itself is not changed.
40
+ */
41
+ export function mergeDisabledFeatures(args, features = []) {
42
+ const list = Array.isArray(args) ? args : [];
43
+ const names = [];
44
+ const add = (name) => { if (!names.includes(name)) names.push(name); };
45
+ const out = [];
46
+ let at = -1;
47
+ for (const arg of list) {
48
+ const match = typeof arg === 'string' ? DISABLE_FEATURES.exec(arg) : null;
49
+ if (!match) { out.push(arg); continue; }
50
+ featureNames(match[1]).forEach(add);
51
+ if (at === -1) { at = out.length; out.push(null); }
52
+ }
53
+ for (const name of features) {
54
+ const clean = String(name ?? '').trim();
55
+ if (clean) add(clean);
56
+ }
57
+ if (!names.length) return at === -1 ? out : out.filter((_, i) => i !== at);
58
+ const flag = `--disable-features=${names.join(',')}`;
59
+ if (at === -1) out.push(flag);
60
+ else out[at] = flag;
61
+ return out;
62
+ }
63
+
64
+ /** `args` with the Optimization Guide's model features merged into its one --disable-features. */
65
+ export function withOnDeviceModelBlocked(args) {
66
+ return mergeDisabledFeatures(args, ON_DEVICE_MODEL_FEATURES);
67
+ }
@@ -27,7 +27,7 @@ import { detectProject as memoryProject } from '../../mcp-server/dist/config.js'
27
27
  // WS bound, so page-refresh reattach is the same object.
28
28
 
29
29
  import { query, startup } from '@anthropic-ai/claude-agent-sdk';
30
- import { CLAUDE_EFFORT_LEVELS } from './claude-model-catalog.js';
30
+ import { CLAUDE_EFFORT_LEVELS, CLAUDE_EFFORT_OFF, isThinkingOff } from './claude-model-catalog.js';
31
31
  import { CLAUDE_NOT_INSTALLED, resolveClaudeSdkExecutable } from './claude-executable.js';
32
32
  import { diagnoseLaunchFailure, isNativeBinaryLaunchFailure } from './native-binary-runtime.js';
33
33
  import { normalizePanelSession, startSignature, applyPanelSessionOptions, liveSettingsPatch, normalizeMcpServers, mergeTabMcpServers } from './claude-panel-session.js';
@@ -787,7 +787,8 @@ export class ClaudeSession {
787
787
  if (this.model) options.model = this.model;
788
788
  // Off is the user's pick, not the model's default: without it an
789
789
  // effortLevel in the user's settings would still apply.
790
- if (this.panel && this.effort === 'off') options.thinking = { type: 'disabled' };
790
+ // `none` is the Assistant's Off (route card, dispatch, brain turns): the same, for every session.
791
+ if ((this.panel && this.effort === 'off') || this.effort === CLAUDE_EFFORT_OFF) options.thinking = { type: 'disabled' };
791
792
  if (this.effort && CLAUDE_EFFORT_LEVELS.includes(this.effort)) {
792
793
  // Panel sessions use the typed option; every other caller keeps the flag it had.
793
794
  if (this.panel) options.effort = this.effort;
@@ -3044,9 +3045,11 @@ export class ClaudeSession {
3044
3045
 
3045
3046
  // Effort alone switches on the live CLI. A restart would cold-start the
3046
3047
  // session and kill any background agents it is running.
3047
- // (Off disables thinking, a start-up option: to or from it the session restarts.)
3048
+ // (Off disables thinking, a start-up option: to or from it the session restarts. Outside the panel
3049
+ // 'off' is Auto: a level back to the model's default switches live, `effortLevel: null`.)
3050
+ const thinkingOff = (value) => isThinkingOff(value, { panel: !!this.panel });
3048
3051
  if (this.q && effortChanged && !cwdChanged && !sessionChanged && !newChat
3049
- && prevEffort !== 'off' && effort !== 'off'
3052
+ && !thinkingOff(prevEffort) && !thinkingOff(effort)
3050
3053
  && typeof this.q.applyFlagSettings === 'function') {
3051
3054
  const effortLevel = CLAUDE_EFFORT_LEVELS.includes(effort) ? effort : null;
3052
3055
  this.q.applyFlagSettings({ effortLevel }).catch(err => log('applyFlagSettings(effort) failed:', err.message));
@@ -21,6 +21,18 @@ import { withPathEnv, getAugmentedPath } from './augmented-path.js';
21
21
  // and as the server-side allowlist at every spawn site.
22
22
  export const CLAUDE_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']);
23
23
 
24
+ // Off for an Assistant route / dispatch / brain turn (effort-levels.js EFFORT_OFF):
25
+ // no --effort, and the SDK's `thinking: { type: 'disabled' }`, over any effortLevel
26
+ // in the user's settings. (The Claude panel's own Think toggle says 'off'.)
27
+ export const CLAUDE_EFFORT_OFF = 'none';
28
+
29
+ /**
30
+ * An effort that starts the CLI with thinking disabled: `none` for every session, 'off' only in a
31
+ * panel session (its Think toggle). Elsewhere (the Assistant brain, loops) 'off' is Auto, the
32
+ * model's default, which a live process takes without a restart.
33
+ */
34
+ export function isThinkingOff(effort, { panel = true } = {}) { return effort === CLAUDE_EFFORT_OFF || (panel && effort === 'off'); }
35
+
24
36
  // Used only when discovery fails (CLI missing, spawn error, timeout). Kept
25
37
  // deliberately short — a stale fallback is less harmful than a stale primary,
26
38
  // because `source: 'fallback'` tells the UI the list is unverified.
@@ -73,7 +73,27 @@ export function modelEfforts(row) {
73
73
  return source ? sortEfforts(source) : null;
74
74
  }
75
75
 
76
- /** `effort` clamped into `levels`: kept, else the highest level below it, else the lowest. */
76
+ /**
77
+ * Off: thinking / reasoning disabled. One id across providers (Codex
78
+ * `model_reasoning_effort=none`, the OpenCode variant `none`, Claude Code
79
+ * `thinking: { type: 'disabled' }`). Only ever chosen, never reached by a
80
+ * correction: a level a model lacks never lands on Off.
81
+ */
82
+ export const EFFORT_OFF = 'none';
83
+
84
+ /**
85
+ * Can this provider/row run with thinking off? Codex and OpenCode only when the
86
+ * model lists `none`; Claude Code whenever the model thinks at all (the SDK
87
+ * disables thinking for any of them). Antigravity takes no such level.
88
+ */
89
+ export function supportsEffortOff(provider, row) {
90
+ const levels = modelEfforts(row);
91
+ if (provider === 'claude-code') return levels ? levels.some((id) => id.toLowerCase() !== EFFORT_OFF) : !!row;
92
+ if (provider === 'antigravity') return false;
93
+ return !!levels?.some((id) => id.toLowerCase() === EFFORT_OFF);
94
+ }
95
+
96
+ /** `effort` clamped into `levels`: kept, else the highest level below it, else the lowest (never Off). */
77
97
  export function clampEffort(effort, levels, { fallback = null } = {}) {
78
98
  const want = clean(effort);
79
99
  if (!want || !levels?.length) return null;
@@ -81,7 +101,9 @@ export function clampEffort(effort, levels, { fallback = null } = {}) {
81
101
  if (same) return same;
82
102
  const rank = effortRank(want);
83
103
  if (rank < 0) return fallback && levels.includes(fallback) ? fallback : null;
84
- const ranked = levels.filter((id) => effortRank(id) >= 0);
104
+ // Off is a choice, not a level to fall back on.
105
+ const ranked = levels.filter((id) => effortRank(id) >= 0 && id.toLowerCase() !== EFFORT_OFF);
106
+ if (!ranked.length) return levels.find((id) => id.toLowerCase() !== EFFORT_OFF) || null;
85
107
  const below = ranked.filter((id) => effortRank(id) < rank);
86
108
  if (below.length) return below[below.length - 1];
87
109
  return ranked[0] || levels[0];
@@ -97,6 +119,8 @@ function rowFor(catalog, provider, model) {
97
119
  /**
98
120
  * Check `effort` against the model's levels. → { effort, corrected: {from, to} | null }.
99
121
  * off/default/auto/empty → null (the model's own default). Supported → kept.
122
+ * `none` (Off: no thinking) is kept wherever supportsEffortOff says the model
123
+ * can run it, Claude Code's thinking models included.
100
124
  * Unsupported → the highest supported level below it, else the lowest
101
125
  * (minimal → low, ultra on a max-only model → max). A model with no levels →
102
126
  * null. Unknown model or unverified catalog → passed through unchanged: a value
@@ -109,6 +133,8 @@ export function normalizeEffort({ provider = null, model = null, effort = null,
109
133
  const row = rowFor(catalog, provider, model)?.row || null;
110
134
  const levels = modelEfforts(row);
111
135
  if (!levels) return { effort: raw, corrected: null };
136
+ // Off on a model that can switch its thinking off stays Off (Claude Code lists no `none`: see supportsEffortOff).
137
+ if (raw.toLowerCase() === EFFORT_OFF && supportsEffortOff(provider, row)) return { effort: EFFORT_OFF, corrected: null };
112
138
  const next = clampEffort(raw, levels, { fallback: row?.defaultEffort || null });
113
139
  return next === raw ? { effort: raw, corrected: null } : { effort: next, corrected: { from: raw, to: next } };
114
140
  }
@@ -0,0 +1,362 @@
1
+ /**
2
+ * The proxy relay of a local browser profile (lib/local-profiles.js), and the "check proxy" request.
3
+ *
4
+ * Chrome takes no proxy credentials on its command line and has no SOCKS5 login at all. So a local profile whose
5
+ * proxy has a username and a password gets one relay of its own on 127.0.0.1: Chrome is started with
6
+ * `--proxy-server=http://127.0.0.1:<port>`, and the relay sends what Chrome asks for (CONNECT and plain-HTTP requests)
7
+ * to the upstream proxy with the login: `Proxy-Authorization` for an HTTP or HTTPS proxy, the username/password
8
+ * handshake of RFC 1929 for SOCKS5. A proxy without a login needs none of this and goes straight to Chrome.
9
+ *
10
+ * It fails closed. The relay opens connections to the upstream proxy and to nothing else: when the upstream refuses
11
+ * or cannot be reached the request is answered 502, never sent directly. When the relay itself is down Chrome's proxy
12
+ * points at a dead port, so pages fail there too.
13
+ *
14
+ * The relay listens on loopback only and asks no login of its own (Chrome could not send one): whatever on this
15
+ * computer reaches its port goes out through the profile's proxy. A guarded worker's sandbox denies these ports
16
+ * (server.js workerBrowserControlPorts).
17
+ *
18
+ * Built-ins only. ESM, Node >= 22.
19
+ */
20
+ import http from 'node:http';
21
+ import https from 'node:https';
22
+ import net from 'node:net';
23
+ import tls from 'node:tls';
24
+
25
+ export const PROXY_TYPES = Object.freeze(['none', 'http', 'https', 'socks5']);
26
+ /** Where "check proxy" asks for the exit address. */
27
+ export const CHECK_PROXY_URL = 'https://api.ipify.org?format=json';
28
+ const CONNECT_TIMEOUT_MS = 20000;
29
+ const MAX_HEAD_BYTES = 64 * 1024;
30
+
31
+ function proxyError(code, message, extra = {}) {
32
+ return Object.assign(new Error(message), { code, ...extra });
33
+ }
34
+
35
+ /** Whether a profile's proxy needs the relay: a proxy with a login (a username; the password may be empty). */
36
+ export function proxyNeedsRelay(proxy) {
37
+ return !!proxy && proxy.type !== 'none' && PROXY_TYPES.includes(proxy.type) && !!proxy.host && !!proxy.username;
38
+ }
39
+
40
+ /** What Chrome is given as `--proxy-server` for a proxy without a login, or null for none. */
41
+ export function directProxyServer(proxy) {
42
+ if (!proxy || proxy.type === 'none' || !PROXY_TYPES.includes(proxy.type) || !proxy.host || !proxy.port) return null;
43
+ const host = proxy.host.includes(':') && !proxy.host.startsWith('[') ? `[${proxy.host}]` : proxy.host;
44
+ return `${proxy.type}://${host}:${proxy.port}`;
45
+ }
46
+
47
+ function onceConnected(socket, event, timeoutMs, what) {
48
+ return new Promise((resolveP, rejectP) => {
49
+ const done = (fn, value) => { clearTimeout(timer); socket.off('error', onError); socket.off(event, onOk); fn(value); };
50
+ const onOk = () => done(resolveP, socket);
51
+ const onError = (err) => done(rejectP, proxyError('PROXY_UNREACHABLE', `${what} could not be reached (${err?.code || err?.message || err})`));
52
+ const timer = setTimeout(() => { socket.destroy(); done(rejectP, proxyError('PROXY_TIMEOUT', `${what} did not answer in ${Math.round(timeoutMs / 1000)} s`)); }, timeoutMs);
53
+ timer.unref?.();
54
+ socket.once(event, onOk);
55
+ socket.once('error', onError);
56
+ });
57
+ }
58
+
59
+ /** Reads from `socket` until `enough(buffer)` says how many bytes the answer is; → { head, rest }. */
60
+ function readUntil(socket, enough, timeoutMs, what) {
61
+ return new Promise((resolveP, rejectP) => {
62
+ let buffer = Buffer.alloc(0);
63
+ const cleanup = () => { clearTimeout(timer); socket.off('data', onData); socket.off('error', onError); socket.off('close', onClose); };
64
+ const fail = (err) => { cleanup(); socket.destroy(); rejectP(err); };
65
+ const onData = (chunk) => {
66
+ buffer = Buffer.concat([buffer, chunk]);
67
+ let size;
68
+ try { size = enough(buffer); } catch (err) { return fail(err); }
69
+ if (size > 0) { cleanup(); socket.pause(); return resolveP({ head: buffer.subarray(0, size), rest: buffer.subarray(size) }); }
70
+ if (buffer.length > MAX_HEAD_BYTES) fail(proxyError('PROXY_PROTOCOL', `${what} sent an answer that is too long`));
71
+ };
72
+ const onError = (err) => fail(proxyError('PROXY_UNREACHABLE', `${what} closed the connection (${err?.code || err?.message || err})`));
73
+ const onClose = () => fail(proxyError('PROXY_UNREACHABLE', `${what} closed the connection`));
74
+ const timer = setTimeout(() => fail(proxyError('PROXY_TIMEOUT', `${what} did not answer in ${Math.round(timeoutMs / 1000)} s`)), timeoutMs);
75
+ timer.unref?.();
76
+ socket.on('data', onData);
77
+ socket.once('error', onError);
78
+ socket.once('close', onClose);
79
+ socket.resume();
80
+ });
81
+ }
82
+
83
+ function basicAuth(proxy) {
84
+ return `Basic ${Buffer.from(`${proxy.username}:${proxy.password || ''}`, 'utf8').toString('base64')}`;
85
+ }
86
+
87
+ async function connectToProxy(proxy, timeoutMs) {
88
+ const what = `The ${proxy.type.toUpperCase()} proxy ${proxy.host}:${proxy.port}`;
89
+ if (proxy.type === 'https') {
90
+ const socket = tls.connect({ host: proxy.host, port: Number(proxy.port), servername: net.isIP(proxy.host) ? undefined : proxy.host, ...(proxy.tls || {}) });
91
+ return onceConnected(socket, 'secureConnect', timeoutMs, what);
92
+ }
93
+ const socket = net.connect({ host: proxy.host, port: Number(proxy.port) });
94
+ return onceConnected(socket, 'connect', timeoutMs, what);
95
+ }
96
+
97
+ const SOCKS_REPLIES = {
98
+ 1: 'general failure', 2: 'connection not allowed', 3: 'network unreachable', 4: 'host unreachable',
99
+ 5: 'connection refused', 6: 'TTL expired', 7: 'command not supported', 8: 'address type not supported',
100
+ };
101
+
102
+ async function socks5Tunnel(socket, proxy, host, port, timeoutMs) {
103
+ const what = `The SOCKS5 proxy ${proxy.host}:${proxy.port}`;
104
+ const withLogin = !!proxy.username;
105
+ socket.write(Buffer.from(withLogin ? [5, 2, 0, 2] : [5, 1, 0]));
106
+ let answer = await readUntil(socket, (b) => (b.length >= 2 ? 2 : 0), timeoutMs, what);
107
+ if (answer.head[0] !== 5) throw proxyError('PROXY_PROTOCOL', `${what} did not answer as SOCKS5`);
108
+ if (answer.rest.length) socket.unshift(answer.rest);
109
+ const method = answer.head[1];
110
+ if (method === 2) {
111
+ if (!withLogin) throw proxyError('PROXY_AUTH', `${what} asks for a username and a password`);
112
+ const user = Buffer.from(String(proxy.username), 'utf8');
113
+ const pass = Buffer.from(String(proxy.password || ''), 'utf8');
114
+ if (user.length > 255 || pass.length > 255) throw proxyError('PROXY_AUTH', 'A SOCKS5 username or password is at most 255 bytes');
115
+ socket.write(Buffer.concat([Buffer.from([1, user.length]), user, Buffer.from([pass.length]), pass]));
116
+ answer = await readUntil(socket, (b) => (b.length >= 2 ? 2 : 0), timeoutMs, what);
117
+ if (answer.rest.length) socket.unshift(answer.rest);
118
+ if (answer.head[1] !== 0) throw proxyError('PROXY_AUTH', `${what} refused the username or the password`);
119
+ } else if (method !== 0) {
120
+ throw proxyError('PROXY_AUTH', `${what} accepts none of the ways SynaBun can sign in (no login, or a username and a password)`);
121
+ }
122
+ // The name goes to the proxy as a name: it is resolved there, never on this computer.
123
+ const name = Buffer.from(String(host).replace(/^\[|\]$/g, ''), 'utf8');
124
+ if (!name.length || name.length > 255) throw proxyError('PROXY_PROTOCOL', 'The host name is empty or longer than 255 bytes');
125
+ socket.write(Buffer.concat([Buffer.from([5, 1, 0, 3, name.length]), name, Buffer.from([(port >> 8) & 0xff, port & 0xff])]));
126
+ answer = await readUntil(socket, (b) => {
127
+ if (b.length < 5) return 0;
128
+ const size = b[3] === 1 ? 10 : b[3] === 4 ? 22 : b[3] === 3 ? 7 + b[4] : -1;
129
+ if (size < 0) throw proxyError('PROXY_PROTOCOL', `${what} sent an answer SynaBun does not read`);
130
+ return b.length >= size ? size : 0;
131
+ }, timeoutMs, what);
132
+ if (answer.head[1] !== 0) throw proxyError('PROXY_REFUSED', `${what} did not connect to ${host}:${port} (${SOCKS_REPLIES[answer.head[1]] || `code ${answer.head[1]}`})`);
133
+ if (answer.rest.length) socket.unshift(answer.rest);
134
+ return socket;
135
+ }
136
+
137
+ async function httpConnectTunnel(socket, proxy, host, port, timeoutMs) {
138
+ const what = `The ${proxy.type.toUpperCase()} proxy ${proxy.host}:${proxy.port}`;
139
+ const target = `${host}:${port}`;
140
+ socket.write(`CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n${proxy.username ? `Proxy-Authorization: ${basicAuth(proxy)}\r\n` : ''}\r\n`);
141
+ const answer = await readUntil(socket, (b) => { const at = b.indexOf('\r\n\r\n'); return at === -1 ? 0 : at + 4; }, timeoutMs, what);
142
+ const status = Number(/^HTTP\/\d\.\d (\d{3})/.exec(answer.head.toString('latin1'))?.[1]);
143
+ if (status === 407) throw proxyError('PROXY_AUTH', `${what} refused the username or the password (HTTP 407)`);
144
+ if (!(status >= 200 && status < 300)) throw proxyError('PROXY_REFUSED', `${what} did not connect to ${target} (HTTP ${status || 'answer not read'})`);
145
+ if (answer.rest.length) socket.unshift(answer.rest);
146
+ return socket;
147
+ }
148
+
149
+ /**
150
+ * A connection to `host:port` through `proxy` ({ type: 'http' | 'https' | 'socks5', host, port, username?, password? }).
151
+ * → the socket, ready for the caller's bytes. Throws PROXY_UNREACHABLE | PROXY_TIMEOUT | PROXY_AUTH | PROXY_REFUSED |
152
+ * PROXY_PROTOCOL; never opens a connection to anything but the proxy.
153
+ */
154
+ export async function openProxyTunnel(proxy, host, port, { timeoutMs = CONNECT_TIMEOUT_MS } = {}) {
155
+ if (!proxy || !['http', 'https', 'socks5'].includes(proxy.type) || !proxy.host || !proxy.port) {
156
+ throw proxyError('PROXY_REQUIRED', 'No proxy is set');
157
+ }
158
+ const portNumber = Number(port);
159
+ if (!Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) throw proxyError('PROXY_PROTOCOL', `Not a port: ${port}`);
160
+ const socket = await connectToProxy(proxy, timeoutMs);
161
+ try {
162
+ const tunnel = proxy.type === 'socks5'
163
+ ? await socks5Tunnel(socket, proxy, host, portNumber, timeoutMs)
164
+ : await httpConnectTunnel(socket, proxy, host, portNumber, timeoutMs);
165
+ tunnel.resume();
166
+ return tunnel;
167
+ } catch (err) {
168
+ socket.destroy();
169
+ throw err;
170
+ }
171
+ }
172
+
173
+ function splitHostPort(target, fallbackPort) {
174
+ const text = String(target || '');
175
+ const bracket = /^\[([^\]]+)\](?::(\d+))?$/.exec(text);
176
+ if (bracket) return { host: bracket[1], port: Number(bracket[2] || fallbackPort) };
177
+ const at = text.lastIndexOf(':');
178
+ if (at === -1) return { host: text, port: Number(fallbackPort) };
179
+ return { host: text.slice(0, at), port: Number(text.slice(at + 1)) };
180
+ }
181
+
182
+ const HOP_HEADERS = new Set(['proxy-connection', 'proxy-authorization', 'proxy-authenticate', 'connection', 'keep-alive', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
183
+ function forwardHeaders(raw) {
184
+ const out = {};
185
+ for (let i = 0; i + 1 < raw.length; i += 2) {
186
+ const name = raw[i];
187
+ const lower = name.toLowerCase();
188
+ if (HOP_HEADERS.has(lower) && lower !== 'transfer-encoding') continue;
189
+ if (out[name] === undefined) out[name] = raw[i + 1];
190
+ else out[name] = [].concat(out[name], raw[i + 1]);
191
+ }
192
+ return out;
193
+ }
194
+
195
+ /**
196
+ * One relay: a loopback HTTP proxy without a login in front of `upstream` (a proxy with one).
197
+ * listen(port?) → the port it listens on (a random free one for 0; a taken port rejects with EADDRINUSE)
198
+ * close() → stops listening and ends every connection through it
199
+ * port → the port while it listens, else null
200
+ * `counters`: { tunnels, requests, failures } for tests and the log.
201
+ */
202
+ export function createProxyRelay({ upstream, host = '127.0.0.1', log = () => {}, timeoutMs = CONNECT_TIMEOUT_MS } = {}) {
203
+ if (!upstream || !['http', 'https', 'socks5'].includes(upstream.type) || !upstream.host || !upstream.port) {
204
+ throw proxyError('PROXY_REQUIRED', 'A relay needs an upstream proxy (type, host and port)');
205
+ }
206
+ const sockets = new Set();
207
+ const counters = { tunnels: 0, requests: 0, failures: 0 };
208
+ let listeningPort = null;
209
+ const track = (socket) => { sockets.add(socket); socket.once('close', () => sockets.delete(socket)); return socket; };
210
+ const refuse = (socket, err) => {
211
+ counters.failures += 1;
212
+ log(`relay: ${err?.message || err}`);
213
+ const status = err?.code === 'PROXY_AUTH' ? '502 Proxy Login Refused' : '502 Bad Gateway';
214
+ try { socket.end(`HTTP/1.1 ${status}\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n${String(err?.message || 'The proxy could not be reached').slice(0, 400)}\n`); } catch { /* gone */ }
215
+ };
216
+
217
+ const server = http.createServer();
218
+ server.on('connection', track);
219
+
220
+ // CONNECT host:port — every https page, and Chrome's WebSockets.
221
+ server.on('connect', async (req, clientSocket, head) => {
222
+ clientSocket.on('error', () => {});
223
+ const { host: targetHost, port: targetPort } = splitHostPort(req.url, 443);
224
+ let tunnel;
225
+ try { tunnel = track(await openProxyTunnel(upstream, targetHost, targetPort, { timeoutMs })); }
226
+ catch (err) { return refuse(clientSocket, err); }
227
+ counters.tunnels += 1;
228
+ tunnel.on('error', () => clientSocket.destroy());
229
+ clientSocket.on('close', () => tunnel.destroy());
230
+ tunnel.on('close', () => clientSocket.destroy());
231
+ clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
232
+ if (head?.length) tunnel.write(head);
233
+ tunnel.pipe(clientSocket);
234
+ clientSocket.pipe(tunnel);
235
+ });
236
+
237
+ // A plain http:// request, asked of a proxy with its whole address.
238
+ server.on('request', (req, res) => {
239
+ let target;
240
+ try { target = new URL(req.url); } catch { target = null; }
241
+ if (!target || target.protocol !== 'http:') {
242
+ res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8', Connection: 'close' });
243
+ return res.end('This is the proxy relay of a SynaBun local profile: it takes a proxy request only.\n');
244
+ }
245
+ const fail = (err) => {
246
+ counters.failures += 1;
247
+ log(`relay: ${err?.message || err}`);
248
+ if (res.headersSent) return res.destroy();
249
+ res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8', Connection: 'close' });
250
+ res.end(`${String(err?.message || 'The proxy could not be reached').slice(0, 400)}\n`);
251
+ };
252
+ const headers = forwardHeaders(req.rawHeaders);
253
+ const answer = (upstreamRes) => {
254
+ counters.requests += 1;
255
+ res.writeHead(upstreamRes.statusCode || 502, upstreamRes.statusMessage, forwardHeaders(upstreamRes.rawHeaders));
256
+ upstreamRes.pipe(res);
257
+ };
258
+ let out;
259
+ if (upstream.type === 'socks5') {
260
+ // Through a connection the SOCKS5 proxy opened to the site: the request goes as the site expects it.
261
+ openProxyTunnel(upstream, target.hostname, Number(target.port || 80), { timeoutMs }).then((tunnel) => {
262
+ track(tunnel);
263
+ // No `agent` here: Node uses `createConnection` only for a request without one (with `agent: false` it
264
+ // would open a connection of its own, straight to the site).
265
+ out = http.request({ method: req.method, host: target.hostname, port: Number(target.port || 80), path: `${target.pathname}${target.search}`, headers, createConnection: () => tunnel }, answer);
266
+ out.on('error', fail);
267
+ req.pipe(out);
268
+ }, fail);
269
+ } else {
270
+ // To the HTTP(S) proxy as a proxy request, with the login.
271
+ const lib = upstream.type === 'https' ? https : http;
272
+ out = lib.request({
273
+ host: upstream.host, port: Number(upstream.port), method: req.method, path: target.href, agent: false,
274
+ headers: { ...headers, 'Proxy-Authorization': basicAuth(upstream) }, timeout: timeoutMs, ...(upstream.type === 'https' ? (upstream.tls || {}) : {}),
275
+ }, answer);
276
+ out.on('timeout', () => out.destroy(proxyError('PROXY_TIMEOUT', `The ${upstream.type.toUpperCase()} proxy ${upstream.host}:${upstream.port} did not answer`)));
277
+ out.on('error', (err) => fail(err?.code?.startsWith?.('PROXY_') ? err : proxyError('PROXY_UNREACHABLE', `The ${upstream.type.toUpperCase()} proxy ${upstream.host}:${upstream.port} could not be reached (${err?.code || err?.message || err})`)));
278
+ req.pipe(out);
279
+ }
280
+ res.on('close', () => { try { out?.destroy(); } catch { /* gone */ } });
281
+ });
282
+
283
+ server.on('clientError', (_err, socket) => { try { socket.destroy(); } catch { /* gone */ } });
284
+
285
+ return {
286
+ counters,
287
+ get port() { return listeningPort; },
288
+ listen(port = 0) {
289
+ return new Promise((resolveP, rejectP) => {
290
+ const onError = (err) => { server.off('listening', onListening); rejectP(err); };
291
+ const onListening = () => { server.off('error', onError); listeningPort = server.address().port; server.on('error', () => {}); resolveP(listeningPort); };
292
+ server.once('error', onError);
293
+ server.once('listening', onListening);
294
+ server.listen({ host, port: Number(port) || 0, exclusive: true });
295
+ });
296
+ },
297
+ close() {
298
+ return new Promise((resolveP) => {
299
+ const wasListening = listeningPort !== null;
300
+ listeningPort = null;
301
+ for (const socket of sockets) { try { socket.destroy(); } catch { /* gone */ } }
302
+ sockets.clear();
303
+ if (!wasListening) return resolveP();
304
+ server.close(() => resolveP());
305
+ server.closeAllConnections?.();
306
+ });
307
+ },
308
+ };
309
+ }
310
+
311
+ /**
312
+ * The address a site sees through `proxy`: GET `url` (CHECK_PROXY_URL) through it and read `{ ip }` from the answer.
313
+ * → { ok: true, ip, via: 'http' | 'https' | 'socks5' | 'direct', ms } or { ok: false, code, error }.
314
+ * Without a proxy (`type: 'none'`) the request goes out directly, and the answer says so (`via: 'direct'`).
315
+ * Never throws.
316
+ */
317
+ export async function checkProxy(proxy, { url = CHECK_PROXY_URL, timeoutMs = 15000, tlsOptions = {} } = {}) {
318
+ const started = Date.now();
319
+ let target;
320
+ try { target = new URL(url); } catch { return { ok: false, code: 'CHECK_URL', error: `Not an address: ${url}` }; }
321
+ const secure = target.protocol === 'https:';
322
+ const port = Number(target.port || (secure ? 443 : 80));
323
+ const direct = !proxy || proxy.type === 'none' || !proxy.host;
324
+ let socket = null;
325
+ try {
326
+ if (!direct) socket = await openProxyTunnel(proxy, target.hostname, port, { timeoutMs });
327
+ const body = await new Promise((resolveP, rejectP) => {
328
+ const lib = secure ? https : http;
329
+ const options = {
330
+ method: 'GET', host: target.hostname, port, path: `${target.pathname}${target.search}`, timeout: timeoutMs,
331
+ headers: { Accept: 'application/json', 'User-Agent': 'SynaBun', Connection: 'close' },
332
+ // Through the proxy: the request rides the tunnel and nothing else. No `agent` then: Node uses
333
+ // `createConnection` only for a request without one (with `agent: false` it would connect by itself, directly,
334
+ // and the check would show this computer's own address).
335
+ ...(socket ? {
336
+ createConnection: () => (secure
337
+ ? tls.connect({ socket, servername: net.isIP(target.hostname) ? undefined : target.hostname, ...tlsOptions })
338
+ : socket),
339
+ } : { agent: false, ...(secure ? tlsOptions : {}) }),
340
+ };
341
+ const req = lib.request(options, (res) => {
342
+ let text = '';
343
+ res.setEncoding('utf8');
344
+ res.on('data', (chunk) => { text += chunk; if (text.length > 16384) req.destroy(proxyError('CHECK_ANSWER', 'The answer is too long')); });
345
+ res.on('end', () => (res.statusCode >= 200 && res.statusCode < 300
346
+ ? resolveP(text)
347
+ : rejectP(proxyError('CHECK_ANSWER', `${target.hostname} answered HTTP ${res.statusCode}`))));
348
+ });
349
+ req.on('timeout', () => req.destroy(proxyError('PROXY_TIMEOUT', `${target.hostname} did not answer in ${Math.round(timeoutMs / 1000)} s`)));
350
+ req.on('error', (err) => rejectP(err?.code?.startsWith?.('PROXY_') || err?.code === 'CHECK_ANSWER' ? err : proxyError('CHECK_FAILED', `${target.hostname} could not be reached${direct ? '' : ' through the proxy'} (${err?.code || err?.message || err})`)));
351
+ req.end();
352
+ });
353
+ let ip = null;
354
+ try { ip = JSON.parse(body)?.ip; } catch { ip = body.trim(); }
355
+ if (typeof ip !== 'string' || !net.isIP(ip.trim())) return { ok: false, code: 'CHECK_ANSWER', error: `${target.hostname} did not answer with an address` };
356
+ return { ok: true, ip: ip.trim(), via: direct ? 'direct' : proxy.type, ms: Date.now() - started };
357
+ } catch (err) {
358
+ return { ok: false, code: err?.code || 'CHECK_FAILED', error: String(err?.message || err) };
359
+ } finally {
360
+ try { socket?.destroy(); } catch { /* gone */ }
361
+ }
362
+ }