omnicell-router 0.7.0 → 0.8.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 (246) hide show
  1. package/backend/dist/cli/clients/activity.d.ts +35 -0
  2. package/backend/dist/cli/clients/activity.js +67 -0
  3. package/backend/dist/cli/clients/base.d.ts +13 -2
  4. package/backend/dist/cli/clients/claude.d.ts +2 -2
  5. package/backend/dist/cli/clients/codex.d.ts +2 -2
  6. package/backend/dist/cli/clients/core-adapters.d.ts +3 -4
  7. package/backend/dist/cli/clients/core-adapters.js +3 -4
  8. package/backend/dist/cli/clients/cursor-proxy.d.ts +88 -0
  9. package/backend/dist/cli/clients/cursor-proxy.js +421 -0
  10. package/backend/dist/cli/clients/dsh.d.ts +2 -2
  11. package/backend/dist/cli/clients/grok.d.ts +2 -2
  12. package/backend/dist/cli/clients/index.d.ts +8 -1
  13. package/backend/dist/cli/clients/index.js +55 -21
  14. package/backend/dist/cli/clients/kimi.d.ts +2 -2
  15. package/backend/dist/cli/clients/launcher.d.ts +8 -0
  16. package/backend/dist/cli/clients/model-meta.js +1 -1
  17. package/backend/dist/cli/clients/omp.d.ts +2 -2
  18. package/backend/dist/cli/clients/openclaw.d.ts +2 -2
  19. package/backend/dist/cli/clients/opencode-proxy.d.ts +11 -0
  20. package/backend/dist/cli/clients/opencode-proxy.js +351 -0
  21. package/backend/dist/cli/clients/opencode.d.ts +2 -2
  22. package/backend/dist/cli/clients/pi.d.ts +2 -2
  23. package/backend/dist/cli/clients/plugin-adapters.d.ts +3 -1
  24. package/backend/dist/cli/clients/plugin-adapters.js +6 -29
  25. package/backend/dist/cli/clients/qoder-proxy.d.ts +84 -0
  26. package/backend/dist/cli/clients/qoder-proxy.js +497 -0
  27. package/backend/dist/cli/clients/reserved.d.ts +2 -6
  28. package/backend/dist/cli/clients/reserved.js +2 -0
  29. package/backend/dist/cli/clients/workbuddy.d.ts +2 -2
  30. package/backend/dist/cli/index.js +60 -9
  31. package/backend/dist/cli/types.d.ts +29 -8
  32. package/backend/dist/compression/caveman-prompts.d.ts +1 -1
  33. package/backend/dist/config/comments-en.js +6 -12
  34. package/backend/dist/config/comments-zh.js +6 -12
  35. package/backend/dist/config/defaults.d.ts +56 -1
  36. package/backend/dist/config/defaults.js +68 -0
  37. package/backend/dist/config/index.d.ts +9 -2
  38. package/backend/dist/config/index.js +26 -3
  39. package/backend/dist/config/types.d.ts +55 -43
  40. package/backend/dist/forward-proxy/egress.d.ts +10 -2
  41. package/backend/dist/forward-proxy/egress.js +42 -4
  42. package/backend/dist/forward-proxy/ordered-relay.d.ts +29 -0
  43. package/backend/dist/forward-proxy/ordered-relay.js +46 -0
  44. package/backend/dist/forward-proxy/rules.d.ts +66 -19
  45. package/backend/dist/forward-proxy/rules.js +61 -14
  46. package/backend/dist/forward-proxy/server.js +226 -77
  47. package/backend/dist/forward-proxy/system-proxy.d.ts +42 -2
  48. package/backend/dist/forward-proxy/system-proxy.js +199 -22
  49. package/backend/dist/harness/common/market.d.ts +3 -3
  50. package/backend/dist/harness/host/adapters/amp.d.ts +1 -1
  51. package/backend/dist/harness/host/adapters/antigravity.d.ts +1 -1
  52. package/backend/dist/harness/host/adapters/claude.d.ts +1 -1
  53. package/backend/dist/harness/host/adapters/cline.d.ts +1 -1
  54. package/backend/dist/harness/host/adapters/codex.d.ts +1 -1
  55. package/backend/dist/harness/host/adapters/cursor.d.ts +1 -1
  56. package/backend/dist/harness/host/adapters/dsh.d.ts +2 -2
  57. package/backend/dist/harness/host/adapters/factory.d.ts +1 -1
  58. package/backend/dist/harness/host/adapters/gemini-cli.d.ts +1 -1
  59. package/backend/dist/harness/host/adapters/grok.d.ts +1 -1
  60. package/backend/dist/harness/host/adapters/kimi.d.ts +1 -1
  61. package/backend/dist/harness/host/adapters/omp.d.ts +1 -1
  62. package/backend/dist/harness/host/adapters/openclaw.d.ts +1 -1
  63. package/backend/dist/harness/host/adapters/opencode.d.ts +1 -1
  64. package/backend/dist/harness/host/adapters/pi.d.ts +1 -1
  65. package/backend/dist/harness/host/adapters/universal.d.ts +1 -1
  66. package/backend/dist/harness/host/adapters/windsurf.d.ts +1 -1
  67. package/backend/dist/harness/host/adapters/zed.d.ts +1 -1
  68. package/backend/dist/harness/skill/skills-sh.d.ts +1 -1
  69. package/backend/dist/harness/translation.js +64 -21
  70. package/backend/dist/harness/types.d.ts +1 -1
  71. package/backend/dist/harness/types.js +1 -1
  72. package/backend/dist/index.js +31 -18
  73. package/backend/dist/ir/adapters/anthropic-stream.d.ts +18 -0
  74. package/backend/dist/ir/adapters/anthropic-stream.js +247 -0
  75. package/backend/dist/ir/adapters/anthropic.d.ts +29 -0
  76. package/backend/dist/ir/adapters/anthropic.js +788 -0
  77. package/backend/dist/ir/adapters/chat.d.ts +15 -0
  78. package/backend/dist/ir/adapters/chat.js +602 -0
  79. package/backend/dist/ir/adapters/google-stream.d.ts +22 -0
  80. package/backend/dist/ir/adapters/google-stream.js +242 -0
  81. package/backend/dist/ir/adapters/google.d.ts +9 -0
  82. package/backend/dist/ir/adapters/google.js +317 -0
  83. package/backend/dist/ir/adapters/openai-responses-output.js +8 -5
  84. package/backend/dist/ir/adapters/openai-responses.d.ts +15 -0
  85. package/backend/dist/ir/adapters/openai-responses.js +26 -1
  86. package/backend/dist/ir/adapters/responses-output.d.ts +50 -0
  87. package/backend/dist/ir/adapters/responses-output.js +348 -0
  88. package/backend/dist/ir/adapters/responses-stream.d.ts +12 -0
  89. package/backend/dist/ir/adapters/responses-stream.js +178 -0
  90. package/backend/dist/ir/adapters/responses.d.ts +14 -0
  91. package/backend/dist/ir/adapters/responses.js +646 -0
  92. package/backend/dist/ir/errors.d.ts +2 -2
  93. package/backend/dist/ir/types.d.ts +2 -1
  94. package/backend/dist/metrics/request-cost.d.ts +11 -2
  95. package/backend/dist/metrics/request-cost.js +12 -3
  96. package/backend/dist/observability/request-identity.d.ts +1 -1
  97. package/backend/dist/observability/trace-id.d.ts +40 -0
  98. package/backend/dist/observability/trace-id.js +134 -0
  99. package/backend/dist/observability/upstream-events.d.ts +82 -60
  100. package/backend/dist/observability/upstream-events.js +142 -67
  101. package/backend/dist/opencode/catalog/types.d.ts +9 -0
  102. package/backend/dist/opencode/credentials/types.d.ts +2 -2
  103. package/backend/dist/opencode/probe.d.ts +24 -1
  104. package/backend/dist/opencode/probe.js +28 -4
  105. package/backend/dist/opencode/user-config.d.ts +5 -0
  106. package/backend/dist/pipeline/directives.d.ts +6 -2
  107. package/backend/dist/pipeline/directives.js +7 -3
  108. package/backend/dist/pipeline/orchestrator.d.ts +28 -27
  109. package/backend/dist/pipeline/orchestrator.js +220 -194
  110. package/backend/dist/pipeline/unresolved-model.d.ts +33 -0
  111. package/backend/dist/pipeline/unresolved-model.js +43 -0
  112. package/backend/dist/plugins/catalog-def.d.ts +143 -0
  113. package/backend/dist/plugins/catalog-def.js +177 -0
  114. package/backend/dist/plugins/gateways.d.ts +62 -3
  115. package/backend/dist/plugins/gateways.js +139 -2
  116. package/backend/dist/plugins/host.d.ts +42 -5
  117. package/backend/dist/plugins/host.js +454 -38
  118. package/backend/dist/plugins/manifest.d.ts +119 -10
  119. package/backend/dist/plugins/manifest.js +265 -14
  120. package/backend/dist/plugins/pack.js +26 -0
  121. package/backend/dist/plugins/types.d.ts +187 -21
  122. package/backend/dist/protocols/systemone/convert.d.ts +1 -0
  123. package/backend/dist/protocols/systemone/convert.js +6 -1
  124. package/backend/dist/protocols/systemone/decide.js +18 -8
  125. package/backend/dist/providers/anthropic-messages.d.ts +12 -0
  126. package/backend/dist/providers/anthropic-messages.js +53 -0
  127. package/backend/dist/providers/anthropic.d.ts +7 -8
  128. package/backend/dist/providers/anthropic.js +36 -324
  129. package/backend/dist/providers/base.d.ts +14 -2
  130. package/backend/dist/providers/boot-direct.js +68 -38
  131. package/backend/dist/providers/dispatch.d.ts +5 -19
  132. package/backend/dist/providers/dispatch.js +46 -58
  133. package/backend/dist/providers/executors/anthropic-messages.d.ts +1 -0
  134. package/backend/dist/providers/executors/anthropic-messages.js +3 -0
  135. package/backend/dist/providers/executors/dispatch.d.ts +16 -2
  136. package/backend/dist/providers/executors/dispatch.js +39 -9
  137. package/backend/dist/providers/executors/google-gemini.d.ts +1 -0
  138. package/backend/dist/providers/executors/google-gemini.js +3 -0
  139. package/backend/dist/providers/executors/http-stream.js +16 -3
  140. package/backend/dist/providers/executors/openai-chat.d.ts +1 -0
  141. package/backend/dist/providers/executors/openai-chat.js +3 -0
  142. package/backend/dist/providers/executors/openai-responses.d.ts +1 -0
  143. package/backend/dist/providers/executors/openai-responses.js +3 -0
  144. package/backend/dist/providers/executors/plugin-adapter.js +4 -4
  145. package/backend/dist/providers/google-gemini.d.ts +12 -0
  146. package/backend/dist/providers/google-gemini.js +50 -0
  147. package/backend/dist/providers/google.d.ts +7 -8
  148. package/backend/dist/providers/google.js +35 -308
  149. package/backend/dist/providers/http-json.d.ts +19 -0
  150. package/backend/dist/providers/http-json.js +104 -0
  151. package/backend/dist/providers/http-stream.d.ts +52 -0
  152. package/backend/dist/providers/http-stream.js +423 -0
  153. package/backend/dist/providers/member-match.d.ts +4 -5
  154. package/backend/dist/providers/member-match.js +4 -5
  155. package/backend/dist/providers/openai-chat.d.ts +13 -0
  156. package/backend/dist/providers/openai-chat.js +99 -0
  157. package/backend/dist/providers/openai-compatible.d.ts +7 -4
  158. package/backend/dist/providers/openai-compatible.js +71 -368
  159. package/backend/dist/providers/openai-responses.d.ts +12 -0
  160. package/backend/dist/providers/openai-responses.js +68 -0
  161. package/backend/dist/providers/opencode-proxy.d.ts +5 -5
  162. package/backend/dist/providers/opencode-proxy.js +49 -125
  163. package/backend/dist/providers/plugin-adapter.d.ts +9 -0
  164. package/backend/dist/providers/plugin-adapter.js +31 -0
  165. package/backend/dist/providers/registry.d.ts +49 -24
  166. package/backend/dist/providers/registry.js +97 -55
  167. package/backend/dist/providers/responses.d.ts +7 -28
  168. package/backend/dist/providers/responses.js +45 -253
  169. package/backend/dist/providers/tool-markup-leak.d.ts +41 -0
  170. package/backend/dist/providers/tool-markup-leak.js +57 -0
  171. package/backend/dist/providers/tool-markup-recovery.d.ts +27 -0
  172. package/backend/dist/providers/tool-markup-recovery.js +786 -0
  173. package/backend/dist/providers/virtual-meta.d.ts +21 -2
  174. package/backend/dist/providers/virtual-meta.js +49 -9
  175. package/backend/dist/proxy/asset-download.d.ts +54 -0
  176. package/backend/dist/proxy/asset-download.js +420 -0
  177. package/backend/dist/proxy/manual-node-spec.d.ts +16 -16
  178. package/backend/dist/proxy/mihomo-binary.d.ts +17 -2
  179. package/backend/dist/proxy/mihomo-binary.js +62 -51
  180. package/backend/dist/proxy/mihomo-client.js +15 -1
  181. package/backend/dist/proxy/mihomo-config.js +11 -2
  182. package/backend/dist/proxy/mihomo-geo.d.ts +87 -0
  183. package/backend/dist/proxy/mihomo-geo.js +213 -0
  184. package/backend/dist/proxy/mihomo-logs.d.ts +27 -0
  185. package/backend/dist/proxy/mihomo-logs.js +70 -0
  186. package/backend/dist/proxy/mihomo-pac.d.ts +11 -0
  187. package/backend/dist/proxy/mihomo-pac.js +15 -0
  188. package/backend/dist/proxy/mihomo-rules-import.d.ts +1 -1
  189. package/backend/dist/proxy/mihomo-rules-import.js +7 -7
  190. package/backend/dist/proxy/mihomo-sidecar.d.ts +17 -1
  191. package/backend/dist/proxy/mihomo-sidecar.js +148 -26
  192. package/backend/dist/quota/adapters/minimax.js +36 -13
  193. package/backend/dist/quota/cli-login.d.ts +8 -0
  194. package/backend/dist/quota/cli-login.js +18 -0
  195. package/backend/dist/quota/declarations.js +10 -0
  196. package/backend/dist/quota/dsl.js +18 -5
  197. package/backend/dist/quota/engine.d.ts +22 -1
  198. package/backend/dist/quota/engine.js +170 -29
  199. package/backend/dist/quota/prober.d.ts +5 -0
  200. package/backend/dist/quota/prober.js +11 -2
  201. package/backend/dist/quota/types.d.ts +87 -8
  202. package/backend/dist/quota/verdict.d.ts +35 -0
  203. package/backend/dist/quota/verdict.js +135 -0
  204. package/backend/dist/ratelimit/admission.d.ts +131 -0
  205. package/backend/dist/ratelimit/admission.js +233 -0
  206. package/backend/dist/ratelimit/rate-limiter.js +6 -0
  207. package/backend/dist/resilience/types.d.ts +2 -2
  208. package/backend/dist/router/layer2-decision.d.ts +1 -1
  209. package/backend/dist/router/layer2-decision.js +5 -8
  210. package/backend/dist/routes/console.js +248 -52
  211. package/backend/dist/routes/mihomo.d.ts +2 -0
  212. package/backend/dist/routes/mihomo.js +334 -29
  213. package/backend/dist/routes/responses.d.ts +87 -8
  214. package/backend/dist/routes/responses.js +314 -33
  215. package/backend/dist/server.js +34 -6
  216. package/backend/dist/session/session-manager.d.ts +6 -0
  217. package/backend/dist/session/session-manager.js +20 -9
  218. package/backend/dist/surfaces/chat-pipeline.d.ts +2 -2
  219. package/backend/dist/surfaces/chat-pipeline.js +17 -7
  220. package/backend/dist/surfaces/chat.js +15 -0
  221. package/backend/dist/surfaces/decision-pipeline.js +7 -10
  222. package/backend/dist/surfaces/direct-forward.d.ts +3 -0
  223. package/backend/dist/surfaces/direct-forward.js +206 -0
  224. package/backend/dist/surfaces/rate-limit-response.d.ts +17 -0
  225. package/backend/dist/surfaces/rate-limit-response.js +57 -0
  226. package/backend/dist/surfaces/types.d.ts +11 -0
  227. package/backend/dist/trace/tracker.d.ts +32 -1
  228. package/backend/dist/trace/tracker.js +29 -4
  229. package/backend/dist/types/router.d.ts +34 -12
  230. package/backend/dist/types/router.js +35 -6
  231. package/backend/dist/utils/chat-stream.d.ts +21 -8
  232. package/backend/dist/utils/chat-stream.js +46 -9
  233. package/backend/dist/utils/event-ring.d.ts +4 -0
  234. package/backend/dist/utils/event-ring.js +4 -0
  235. package/backend/dist/utils/popularity.js +29 -4
  236. package/backend/dist/utils/proxy.d.ts +7 -0
  237. package/backend/dist/utils/proxy.js +35 -10
  238. package/backend/dist/utils/retry-after.d.ts +21 -0
  239. package/backend/dist/utils/retry-after.js +36 -0
  240. package/bin/ocr.js +2 -2
  241. package/frontend/dist/assets/index-55VVwfFQ.js +1521 -0
  242. package/frontend/dist/assets/{index-CQSLGFTV.css → index-DxZ9MHKB.css} +1 -1
  243. package/frontend/dist/assets/workbuddy.color-DOMpQkxJ.svg +29 -0
  244. package/frontend/dist/index.html +2 -2
  245. package/package.json +1 -1
  246. package/frontend/dist/assets/index-CLvxJjp_.js +0 -1476
@@ -8,16 +8,69 @@
8
8
  */
9
9
  import crypto from 'node:crypto';
10
10
  import net from 'node:net';
11
+ import tls from 'node:tls';
11
12
  import { parse, stringify } from 'yaml';
12
13
  import { loadConfig, mergeProxyConfig, sanitizeProxyConfig, saveConfig } from '../config/index.js';
14
+ import { osProxyBypasses, readOsProxyEndpoint } from '../forward-proxy/system-proxy.js';
13
15
  import { isManualNodeProtocol, manualNodeCatalog, sanitizeTypedNode } from '../proxy/manual-node-spec.js';
14
16
  import { installMihomoBinary } from '../proxy/mihomo-binary.js';
15
17
  import { MihomoClient, MihomoControllerError } from '../proxy/mihomo-client.js';
18
+ import { downloadMihomoGeoAssets, geoAssetsPresent, geoFetchForLeg, geoReport, rulesNeedGeo } from '../proxy/mihomo-geo.js';
19
+ import { clearMihomoCoreLogs, mihomoCoreLogs } from '../proxy/mihomo-logs.js';
16
20
  import { MANUAL_NODE_FORM_KEYS, manualNodeFields, manualNodeMapping, redactSubscriptionUrl } from '../proxy/mihomo-config.js';
17
21
  import { fetchSubscriptionYaml, importRulesFromYaml, readCachedProviderYaml } from '../proxy/mihomo-rules-import.js';
18
22
  import { getMihomoStatus, mihomoWorkDir, reconcileMihomoSidecar, restartMihomoSidecar, startMihomoSidecar, stopMihomoSidecar, } from '../proxy/mihomo-sidecar.js';
19
- import { DEFAULT_MIHOMO_GROUP, DEFAULT_MIHOMO_MIXED_PORT, DEFAULT_MIHOMO_TEST_URL, MIHOMO_DELAY_TIMEOUT_MS, MIHOMO_NODE_PROBE_TIMEOUT_MS } from '../config/defaults.js';
23
+ import { DEFAULT_MIHOMO_GROUP, DEFAULT_MIHOMO_MIXED_PORT, DEFAULT_MIHOMO_TEST_URL, MIHOMO_CN_DIRECT_RULES, MIHOMO_DELAY_TIMEOUT_MS, MIHOMO_LAN_DIRECT_RULES, MIHOMO_NODE_PROBE_TIMEOUT_MS } from '../config/defaults.js';
20
24
  import { PAC_PATH, buildPacScript } from '../proxy/mihomo-pac.js';
25
+ /**
26
+ * Asset transfers the gateway is running right now, keyed by leg (`core`,
27
+ * `geo:machine`, `geo:node`). The console needs an explicit stop because a
28
+ * walk-away is INVISIBLE here: measured on Bun 1.3.14, a client that abandons a
29
+ * hijacked NDJSON response fires no `close` on the request, the response or the
30
+ * socket until the response ends, and a queued write callback never runs. So
31
+ * the only reliable stop signal is the console saying so (ADR-0022), and it has
32
+ * to reach the transfer it belongs to — never the other leg.
33
+ */
34
+ const liveTransfers = new Map();
35
+ /** NDJSON legs: one core install, one geo sync per egress leg. */
36
+ const CORE_LEG = 'core';
37
+ const geoTransferLeg = (leg) => `geo:${leg}`;
38
+ /**
39
+ * One resumable asset transfer wired to one NDJSON response: the signal the
40
+ * engine downloads under, a `send` that stops writing once the socket is gone,
41
+ * and `finish` to end the response and unregister the leg. The `close` listener
42
+ * stays as a safety net for runtimes that do report a disconnect; it must skip a
43
+ * normal end (`writableEnded`) and abort WITH a reason, so a stop surfaces as a
44
+ * cancelled outcome instead of the engine's reasonless AbortError.
45
+ */
46
+ function startAssetTransfer(raw, leg) {
47
+ let closed = false;
48
+ const abort = new AbortController();
49
+ liveTransfers.set(leg, abort);
50
+ raw.on('close', () => {
51
+ closed = true;
52
+ if (!raw.writableEnded)
53
+ abort.abort(new Error('client disconnected'));
54
+ });
55
+ return {
56
+ signal: abort.signal,
57
+ send: (evt) => {
58
+ if (closed)
59
+ return;
60
+ try {
61
+ raw.write(`${JSON.stringify(evt)}\n`);
62
+ }
63
+ catch {
64
+ closed = true;
65
+ }
66
+ },
67
+ finish: () => {
68
+ liveTransfers.delete(leg);
69
+ if (!raw.writableEnded)
70
+ raw.end();
71
+ },
72
+ };
73
+ }
21
74
  function currentProxy() {
22
75
  return loadConfig().proxy ?? {};
23
76
  }
@@ -43,6 +96,7 @@ function normalizeDraft(body, id) {
43
96
  name: typeof body?.name === 'string' ? body.name : '',
44
97
  url: typeof body?.url === 'string' ? body.url : '',
45
98
  interval: typeof body?.interval === 'number' ? body.interval : undefined,
99
+ ...(typeof body?.proxy === 'string' ? { proxy: body.proxy } : {}),
46
100
  enabled: body?.enabled !== false,
47
101
  };
48
102
  }
@@ -143,6 +197,15 @@ export function registerMihomoRoutes(app) {
143
197
  }
144
198
  return { status: 'ok', ...status, routingMode: configured, liveRoutingMode: live };
145
199
  });
200
+ // The core's own output, captured from the process this gateway spawned.
201
+ // Memory-only and deliberately independent of the controller: a core that
202
+ // just died still has its last lines here. An adopted core was not spawned
203
+ // by this process, so it contributes nothing.
204
+ app.get('/api/admin/proxy/mihomo/logs', async () => ({ status: 'ok', lines: mihomoCoreLogs() }));
205
+ app.delete('/api/admin/proxy/mihomo/logs', async () => {
206
+ clearMihomoCoreLogs();
207
+ return { status: 'ok' };
208
+ });
146
209
  // Outbound mode (rule / global / direct) — the deliberate kill switch next to
147
210
  // "stop the core": direct keeps subscriptions updating and the controller
148
211
  // alive while traffic bypasses the tunnel. Persisted for the next start AND
@@ -217,24 +280,12 @@ export function registerMihomoRoutes(app) {
217
280
  reply.hijack();
218
281
  const raw = reply.raw;
219
282
  raw.writeHead(200, { 'content-type': 'application/x-ndjson; charset=utf-8', 'cache-control': 'no-store' });
220
- let closed = false;
221
- raw.on('close', () => {
222
- closed = true;
223
- });
224
- const send = (evt) => {
225
- if (closed)
226
- return;
227
- try {
228
- raw.write(`${JSON.stringify(evt)}\n`);
229
- }
230
- catch {
231
- closed = true;
232
- }
233
- };
283
+ const t = startAssetTransfer(raw, CORE_LEG);
234
284
  let lastSent = 0;
235
285
  try {
236
286
  const result = await installMihomoBinary({
237
287
  version,
288
+ signal: t.signal,
238
289
  // Coalesce byte ticks: one event per 100ms is plenty for a progress bar
239
290
  // and keeps a fast link from flooding the socket.
240
291
  onProgress: (downloaded, total) => {
@@ -242,16 +293,36 @@ export function registerMihomoRoutes(app) {
242
293
  if (now - lastSent < 100 && downloaded !== total)
243
294
  return;
244
295
  lastSent = now;
245
- send({ type: 'progress', downloaded, total });
296
+ t.send({ type: 'progress', downloaded, total });
246
297
  },
247
298
  });
248
- send({ type: 'result', status: result.ok ? 'ok' : 'error', ...result });
299
+ t.send({ type: 'result', status: result.ok ? 'ok' : 'error', ...result });
249
300
  }
250
301
  catch (err) {
302
+ // An abort (disconnect, or shutdown mid-transfer) is a cancelled download,
303
+ // not a mystery: the `.part` and its sidecar stay on disk, so the next
304
+ // click resumes. Reporting it as `download-aborted` keeps the console on
305
+ // the resume copy instead of leaking the engine's abort wording.
306
+ const aborted = t.signal.aborted;
251
307
  const message = err instanceof Error ? err.message : String(err);
252
- send({ type: 'result', status: 'error', ok: false, code: 'install-failed', error: message });
308
+ t.send({ type: 'result', status: 'error', ok: false, code: aborted ? 'download-aborted' : 'install-failed', error: aborted ? 'download cancelled' : message });
253
309
  }
254
- raw.end();
310
+ t.finish();
311
+ });
312
+ // Stop a transfer the operator walked away from. The console calls this when
313
+ // it cancels or leaves the page (keepalive fetch) — see `liveTransfers` for
314
+ // why a disconnect cannot be detected from the socket here. The abort carries
315
+ // a reason so the engine reports `download-aborted`, and the `.part` plus its
316
+ // sidecar stay on disk: the next click resumes from the bytes it has.
317
+ app.post('/api/admin/proxy/mihomo/transfers/cancel', async (req) => {
318
+ const leg = typeof req.body?.leg === 'string'
319
+ ? req.body.leg
320
+ : '';
321
+ const controller = liveTransfers.get(leg);
322
+ if (!controller)
323
+ return { status: 'ok', cancelled: false };
324
+ controller.abort(new Error('cancelled by the console'));
325
+ return { status: 'ok', cancelled: true };
255
326
  });
256
327
  // The rule table the RUNNING core reports: the console shows what is in
257
328
  // effect instead of what the generated config was supposed to say. A dead
@@ -268,6 +339,82 @@ export function registerMihomoRoutes(app) {
268
339
  return reply.status(409).send({ status: 'error', code: 'not-running', message: 'Clash core is not running' });
269
340
  }
270
341
  });
342
+ // The two direct presets the console offers. Served from the backend so the
343
+ // rule rows have ONE declaration (a frontend copy would be a drift twin of
344
+ // the seeded defaults) and the console never hardcodes a payload.
345
+ app.get('/api/admin/proxy/mihomo/rules/presets', async () => ({
346
+ status: 'ok',
347
+ defaults: MIHOMO_LAN_DIRECT_RULES,
348
+ cn: MIHOMO_CN_DIRECT_RULES,
349
+ }));
350
+ // State of the geo databases GEOIP/GEOSITE rules are evaluated against.
351
+ // Sizes only — no content, no path beyond the file names mihomo owns.
352
+ app.get('/api/admin/proxy/mihomo/geo', async () => ({
353
+ status: 'ok',
354
+ ...geoReport(mihomoWorkDir()),
355
+ }));
356
+ // Explicit geo-data install. NDJSON for the same reason as the binary
357
+ // download: two files, ~12 MB together, and a silent multi-second request is
358
+ // indistinguishable from a hang. `progress` events carry the asset key and
359
+ // byte counts, then exactly one `result`.
360
+ //
361
+ // `leg` names the egress (ADR-0022): `machine` (the default) is the
362
+ // machine's own network — OS system proxy when one is enabled, bypass list
363
+ // honoured, direct otherwise — and `node` goes through the core's mixed
364
+ // port, i.e. the selected node. The node leg refuses while the core is down;
365
+ // the machine leg never needs the core.
366
+ app.post('/api/admin/proxy/mihomo/geo', async (req, reply) => {
367
+ const body = (req.body ?? {});
368
+ const leg = body.leg === undefined ? 'machine' : body.leg === 'machine' || body.leg === 'node' ? body.leg : null;
369
+ if (leg === null) {
370
+ return reply.status(400).send({ status: 'error', message: 'leg must be machine or node' });
371
+ }
372
+ const refresh = body.refresh === true;
373
+ reply.hijack();
374
+ const raw = reply.raw;
375
+ raw.writeHead(200, { 'content-type': 'application/x-ndjson; charset=utf-8', 'cache-control': 'no-store' });
376
+ const t = startAssetTransfer(raw, geoTransferLeg(leg));
377
+ let lastSent = 0;
378
+ try {
379
+ const dir = mihomoWorkDir();
380
+ let fetchImpl;
381
+ if (leg === 'node' && (refresh || !geoAssetsPresent(dir))) {
382
+ // The node leg is the core's own exit; a configured controller is not
383
+ // proof the mixed port is listening, so ask the live status.
384
+ const status = await getMihomoStatus();
385
+ if (!status.running) {
386
+ t.send({ type: 'result', status: 'error', ok: false, code: 'not-running', present: false, files: geoReport(dir).files });
387
+ t.finish();
388
+ return;
389
+ }
390
+ fetchImpl = await geoFetchForLeg('node', { mixedPort: currentProxy().mihomo?.mixedPort ?? DEFAULT_MIHOMO_MIXED_PORT });
391
+ }
392
+ else if (leg === 'machine') {
393
+ fetchImpl = await geoFetchForLeg('machine', { osProxyReader });
394
+ }
395
+ const result = await downloadMihomoGeoAssets(dir, {
396
+ fetchImpl,
397
+ refresh,
398
+ signal: t.signal,
399
+ // One event per 100ms is plenty for a progress bar and keeps a fast
400
+ // link from flooding the socket.
401
+ onProgress: (file, downloaded, total) => {
402
+ const now = Date.now();
403
+ if (now - lastSent < 100 && downloaded !== total)
404
+ return;
405
+ lastSent = now;
406
+ t.send({ type: 'progress', file, downloaded, total });
407
+ },
408
+ });
409
+ t.send({ type: 'result', status: result.ok ? 'ok' : 'error', ...result });
410
+ }
411
+ catch (err) {
412
+ const aborted = t.signal.aborted;
413
+ const message = err instanceof Error ? err.message : String(err);
414
+ t.send({ type: 'result', status: 'error', ok: false, code: aborted ? 'download-aborted' : 'geo-download-failed', error: aborted ? 'download cancelled' : message, present: geoAssetsPresent(mihomoWorkDir()), files: geoReport(mihomoWorkDir()).files });
415
+ }
416
+ t.finish();
417
+ });
271
418
  // Operator-authored rules. The body is the WHOLE ordered list: this is a rule
272
419
  // TABLE, so a patch-style merge would silently reorder or resurrect rows the
273
420
  // operator deleted. Sanitizing happens on the config boundary (whitelisted
@@ -280,6 +427,17 @@ export function registerMihomoRoutes(app) {
280
427
  }
281
428
  const proxy = currentProxy();
282
429
  const merged = mergeProxyConfig(proxy, { mihomo: { rules: body.rules } });
430
+ // A GEOIP/GEOSITE row without its geo databases would kill the core at the
431
+ // next start (mihomo parses the data before it listens). Refuse to SAVE it:
432
+ // persisting first and failing the reconcile would leave the file and the
433
+ // process disagreement in place for every later boot.
434
+ if (rulesNeedGeo(merged.mihomo?.rules) && !geoAssetsPresent(mihomoWorkDir())) {
435
+ return reply.status(400).send({
436
+ status: 'error',
437
+ code: 'geo-missing',
438
+ message: 'GEOIP/GEOSITE rules need the geo databases — download them in the Clash panel first',
439
+ });
440
+ }
283
441
  const result = persistProxy(merged);
284
442
  if (!result.success)
285
443
  return reply.status(400).send({ status: 'error', message: result.error || 'save failed' });
@@ -813,21 +971,39 @@ export function registerMihomoRoutes(app) {
813
971
  return reply.status(502).send(controllerFailure(err));
814
972
  }
815
973
  });
816
- // Reachability is not latency. This endpoint answers only "can the
817
- // configured URL be fetched THROUGH the proxy": mihomo runs its delay test
818
- // on the group's currently selected node. The add-node dialog's "test
819
- // connection" is the opposite by design — a direct TCP probe of the node's
820
- // server:port with no proxy.
974
+ // Reachability is not latency. This endpoint answers "can the configured URL
975
+ // be fetched" over ONE of two legs, chosen by `mode` (default `tunnel`):
976
+ // - `tunnel` — mihomo's delay test on the group's currently selected node;
977
+ // - `machine` — the machine's own egress: what any other application on
978
+ // this box would do. Goes through the OS system proxy when one is enabled
979
+ // (respecting its bypass list) and connects directly otherwise. It needs
980
+ // no running core and never uses `proxiedFetch` (whose `proxy.enabled`
981
+ // policy would silently re-route the leg). The shell's HTTP_PROXY /
982
+ // HTTPS_PROXY are IGNORED: they describe how this gateway was launched,
983
+ // not what the machine is configured to use. See `probeUrlMachine` for
984
+ // why it cannot use an HTTP client stack at all.
985
+ // The add-node dialog's "test connection" is the opposite by design — a
986
+ // direct TCP probe of the node's server:port with no proxy.
821
987
  app.post('/api/admin/proxy/mihomo/test-url', async (req, reply) => {
822
988
  const proxy = currentProxy();
823
- const client = clientOrNull(proxy);
824
- if (!client)
825
- return reply.status(409).send({ status: 'error', code: 'not-running', message: 'Clash core is not running' });
826
989
  const body = (req.body ?? {});
990
+ const mode = body.mode === undefined ? 'tunnel' : body.mode === 'tunnel' || body.mode === 'machine' ? body.mode : null;
991
+ if (mode === null)
992
+ return reply.status(400).send({ status: 'error', message: 'invalid mode' });
827
993
  const requested = parseRequestTestUrl(body.url);
828
994
  if (requested === null)
829
995
  return reply.status(400).send({ status: 'error', message: 'invalid test URL' });
830
996
  const url = requested || proxy.mihomo?.testUrl || DEFAULT_MIHOMO_TEST_URL;
997
+ if (mode === 'machine') {
998
+ const outcome = await probeUrlMachine(url, requestedDelayTimeout(body.timeoutMs), await osProxyReader());
999
+ const route = { status: 'ok', mode, via: outcome.via, ...(outcome.proxy ? { proxy: outcome.proxy } : {}) };
1000
+ return outcome.ms !== undefined
1001
+ ? { ...route, reachable: true, url, ms: outcome.ms }
1002
+ : { ...route, reachable: false, url, error: outcome.error };
1003
+ }
1004
+ const client = clientOrNull(proxy);
1005
+ if (!client)
1006
+ return reply.status(409).send({ status: 'error', code: 'not-running', message: 'Clash core is not running' });
831
1007
  // The console shows the RUNNING core's group; a group edited but not yet
832
1008
  // applied exists only in config, so the request may name the live one.
833
1009
  const requestedGroup = typeof body.group === 'string' ? body.group.trim() : '';
@@ -846,7 +1022,7 @@ export function registerMihomoRoutes(app) {
846
1022
  }
847
1023
  try {
848
1024
  const ms = await client.delay(node, requestedDelayTimeout(body.timeoutMs), url);
849
- return { status: 'ok', reachable: true, url, node, ms };
1025
+ return { status: 'ok', mode, reachable: true, url, node, ms };
850
1026
  }
851
1027
  catch (err) {
852
1028
  // Give the console something actionable: a timeout stays a stable code
@@ -855,10 +1031,139 @@ export function registerMihomoRoutes(app) {
855
1031
  const failure = err instanceof MihomoControllerError
856
1032
  ? (err.code === 'delay-missing' || err.code === 'timeout' ? 'timeout' : err.message)
857
1033
  : 'error';
858
- return { status: 'ok', reachable: false, url, node, error: failure };
1034
+ return { status: 'ok', mode, reachable: false, url, node, error: failure };
859
1035
  }
860
1036
  });
861
1037
  }
1038
+ /**
1039
+ * The machine leg's egress resolver. Defaults to the OS system-proxy reader;
1040
+ * tests redirect it because a CI box's own OS settings are not the fixture.
1041
+ */
1042
+ let osProxyReader = readOsProxyEndpoint;
1043
+ export function setUrlProbeOsProxyReaderForTests(reader) {
1044
+ osProxyReader = reader ?? readOsProxyEndpoint;
1045
+ }
1046
+ /**
1047
+ * The `machine` leg of the endpoint check: one request sent the way the
1048
+ * machine's other applications send theirs — through the OS system proxy when
1049
+ * one is enabled, straight out when none is.
1050
+ *
1051
+ * It speaks HTTP/1.1 over a raw `net`/`tls` socket rather than an HTTP client
1052
+ * because on this runtime BOTH `fetch` and `node:http`/`node:https` consult
1053
+ * `HTTP_PROXY`/`HTTPS_PROXY` from the environment (verified: a dead env proxy
1054
+ * fails them all, even `fetch(url, { proxy: '' })`), and those variables
1055
+ * describe how the gateway process was launched — not the machine. A raw
1056
+ * socket lets this leg follow the OS setting and nothing else.
1057
+ *
1058
+ * Resolves on the response head (reachability, not latency grading) and never
1059
+ * throws — the route reports `{ ms }` or `{ error }`.
1060
+ */
1061
+ function probeUrlMachine(url, timeoutMs, osProxy) {
1062
+ const parsed = new URL(url);
1063
+ const secure = parsed.protocol === 'https:';
1064
+ // `URL.hostname` keeps IPv6 brackets; sockets want the bare address, and an
1065
+ // address must never be sent as SNI (TLS libraries reject IP servernames).
1066
+ const host = parsed.hostname.replace(/^\[|\]$/g, '');
1067
+ const port = Number(parsed.port) || (secure ? 443 : 80);
1068
+ const path = `${parsed.pathname || '/'}${parsed.search}`;
1069
+ const proxied = osProxy && !osProxyBypasses(host, osProxy.bypass) ? splitProxyEndpoint(osProxy.server) : undefined;
1070
+ const via = proxied ? 'system-proxy' : 'direct';
1071
+ return new Promise((resolve) => {
1072
+ const started = performance.now();
1073
+ let settled = false;
1074
+ let guard;
1075
+ let socket;
1076
+ const finish = (outcome) => {
1077
+ if (settled)
1078
+ return;
1079
+ settled = true;
1080
+ if (guard)
1081
+ clearTimeout(guard);
1082
+ socket?.destroy();
1083
+ resolve({ ...outcome, via, ...(proxied ? { proxy: `${proxied.host}:${proxied.port}` } : {}) });
1084
+ };
1085
+ const elapsed = () => Math.round(performance.now() - started);
1086
+ guard = setTimeout(() => finish({ error: 'timeout' }), timeoutMs);
1087
+ const servername = net.isIP(host) !== 0 ? undefined : host;
1088
+ const dial = proxied ?? { host, port };
1089
+ socket = net.connect({ host: dial.host, port: dial.port });
1090
+ socket.on('error', (err) => finish({ error: err.code || 'error' }));
1091
+ socket.on('close', () => finish({ error: 'eof' }));
1092
+ const headers = 'User-Agent: OmniCellRouter/endpoint-probe\r\nAccept: */*\r\nConnection: close\r\n';
1093
+ const originRequest = `GET ${path} HTTP/1.1\r\nHost: ${parsed.host}\r\n${headers}\r\n`;
1094
+ // Through a proxy an http:// target uses the absolute form; https:// must
1095
+ // first open a CONNECT tunnel and then speak TLS on it.
1096
+ const proxyAuth = proxied?.auth ? `Proxy-Authorization: ${proxied.auth}\r\n` : '';
1097
+ const absoluteRequest = `GET ${parsed.protocol}//${parsed.host}${path} HTTP/1.1\r\nHost: ${parsed.host}\r\n${proxyAuth}${headers}\r\n`;
1098
+ /** The final leg on the wire: TLS once secure, plain otherwise. */
1099
+ const sendOverTls = (transport) => {
1100
+ const tlsSocket = tls.connect({ socket: transport, servername });
1101
+ socket = tlsSocket;
1102
+ tlsSocket.on('error', (err) => finish({ error: err.code || 'error' }));
1103
+ tlsSocket.once('secureConnect', () => tlsSocket.write(originRequest));
1104
+ tlsSocket.once('data', () => finish({ ms: elapsed() }));
1105
+ };
1106
+ socket.once('connect', () => {
1107
+ if (!proxied) {
1108
+ if (secure)
1109
+ sendOverTls(socket);
1110
+ else {
1111
+ socket.write(originRequest);
1112
+ socket.once('data', () => finish({ ms: elapsed() }));
1113
+ }
1114
+ return;
1115
+ }
1116
+ if (!secure) {
1117
+ socket.write(absoluteRequest);
1118
+ socket.once('data', () => finish({ ms: elapsed() }));
1119
+ return;
1120
+ }
1121
+ socket.write(`CONNECT ${parsed.hostname}:${port} HTTP/1.1\r\nHost: ${parsed.hostname}:${port}\r\n${proxyAuth}\r\n`);
1122
+ let buffered = Buffer.alloc(0);
1123
+ const onData = (chunk) => {
1124
+ buffered = Buffer.concat([buffered, chunk]);
1125
+ const end = buffered.indexOf('\r\n\r\n');
1126
+ if (end < 0)
1127
+ return;
1128
+ socket.off('data', onData);
1129
+ const code = Number(/^HTTP\/1\.[01] (\d{3})/.exec(buffered.subarray(0, end).toString('latin1'))?.[1] ?? 0);
1130
+ // A proxy that refuses the tunnel is the answer, not a transport error.
1131
+ if (code !== 200) {
1132
+ finish({ error: `proxy-${code || 'error'}` });
1133
+ return;
1134
+ }
1135
+ sendOverTls(socket);
1136
+ };
1137
+ socket.on('data', onData);
1138
+ });
1139
+ });
1140
+ }
1141
+ /** `user:pass@host:port` (WinINET stores auth this way) → dial coordinates. */
1142
+ function splitProxyEndpoint(server) {
1143
+ let rest = server.trim();
1144
+ let auth;
1145
+ const at = rest.lastIndexOf('@');
1146
+ if (at >= 0) {
1147
+ const userinfo = rest.slice(0, at).split(':').map((part) => {
1148
+ try {
1149
+ return decodeURIComponent(part);
1150
+ }
1151
+ catch {
1152
+ return part;
1153
+ }
1154
+ }).join(':');
1155
+ rest = rest.slice(at + 1);
1156
+ auth = `Basic ${Buffer.from(userinfo).toString('base64')}`;
1157
+ }
1158
+ const v6 = /^\[([^\]]+)\](?::(\d+))?$/.exec(rest);
1159
+ if (v6)
1160
+ return { host: v6[1], port: Number(v6[2]) || 80, auth };
1161
+ const colon = rest.lastIndexOf(':');
1162
+ if (colon > 0 && /^\d+$/.test(rest.slice(colon + 1))) {
1163
+ return { host: rest.slice(0, colon), port: Number(rest.slice(colon + 1)), auth };
1164
+ }
1165
+ return { host: rest, port: 80, auth };
1166
+ }
862
1167
  function controllerFailure(err) {
863
1168
  if (err instanceof MihomoControllerError) {
864
1169
  // "Unreachable" IS the down-core case once the secret exists: answer with
@@ -20,11 +20,16 @@ import type { ReasoningEffort } from '../types/router.js';
20
20
  * - a previous_response_id that is unknown/expired fails LOUDLY with 400
21
21
  * (never silently opens a new session).
22
22
  *
23
- * `reasoning` input items are intentionally skipped: chat-completions
24
- * upstreams cannot consume them (note: `reasoning` is the OpenAI Responses API
25
- * item type name, kept verbatim — not the internal tier name). Unknown item
26
- * types fail with 400 rather
27
- * than being silently dropped (fail-visible over silent data loss).
23
+ * `reasoning` items round-trip the assistant's thinking text. Chat upstreams
24
+ * have no reasoning item, so the text rides `reasoning_content` (the
25
+ * OpenAI-compatible `interleaved.field` convention); thinking-mode upstreams
26
+ * (DeepSeek) reject a follow-up turn whose assistant tool calls do not carry
27
+ * it. Outbound: a served assistant message with `reasoning_content` becomes a
28
+ * `reasoning` item whose `summary` parts carry the text. Inbound: a
29
+ * `reasoning` item's text is attached to the assistant message of its turn
30
+ * (before it, the normal order, or the one it follows on the relayed leg).
31
+ * Unknown item types fail with 400 rather than being silently dropped
32
+ * (fail-visible over silent data loss).
28
33
  *
29
34
  * Streaming (`stream: true`) synthesizes the Responses SSE event sequence
30
35
  * from the fully-buffered gateway response — same architecture as the
@@ -67,7 +72,14 @@ export interface ResponsesRequest {
67
72
  instructions?: string;
68
73
  previous_response_id?: string;
69
74
  stream?: boolean;
70
- /** Accepted for compatibility; the gateway always keeps state (local, bounded). */
75
+ /**
76
+ * OpenAI retention flag, HONORED (default true): `store:false` means this
77
+ * response is not retained by the gateway's chain store, so a later
78
+ * `previous_response_id` naming it resolves to nothing (the documented
79
+ * resend-full-input 400) — the same rule that makes chaining impossible
80
+ * without server-side state upstream. Request capture is a separate,
81
+ * operator-controlled plane and is NOT affected by this flag.
82
+ */
71
83
  store?: boolean;
72
84
  user?: string;
73
85
  temperature?: number;
@@ -80,7 +92,30 @@ export interface ResponsesRequest {
80
92
  effort?: Exclude<ReasoningEffort, 'max'>;
81
93
  max_tokens?: number;
82
94
  };
95
+ /**
96
+ * Conversations API handle. NOT implemented: rejected fail-visible, because
97
+ * silently ignoring it leaves a client convinced the session continued while
98
+ * every turn starts from empty history.
99
+ */
100
+ conversation?: unknown;
101
+ /** Async execution + polling endpoints. NOT implemented: `true` is rejected. */
102
+ background?: boolean;
103
+ /** `auto` (server-side context trimming). NOT implemented: `auto` is rejected. */
104
+ truncation?: 'auto' | 'disabled';
105
+ /** Structured outputs. `format.type !== 'text'` is rejected (no mapping on this gateway). */
106
+ text?: {
107
+ format?: {
108
+ type?: string;
109
+ };
110
+ };
83
111
  }
112
+ /**
113
+ * The wire parameters this gateway does NOT implement but which change what
114
+ * the client believes it got. Ignoring them is the one behavior a standard
115
+ * client cannot detect, so each is rejected with `unsupported_parameter`
116
+ * instead (fail-visible over silent divergence).
117
+ */
118
+ export declare function unsupportedResponsesParameter(req: ResponsesRequest): string | null;
84
119
  /**
85
120
  * Responses-wire tools are FLAT (`{type:'function', name, description, parameters}`);
86
121
  * chat-completions tools are NESTED (`{type:'function', function:{...}}`). The
@@ -99,7 +134,51 @@ export declare function chatToolsToResponses(tools: Tool[]): Record<string, unkn
99
134
  */
100
135
  export declare function responsesToolChoiceToChat(raw: unknown): ChatCompletionRequest['tool_choice'];
101
136
  export declare function inputItemsToMessages(input: string | ResponsesInputItem[]): ChatMessage[];
102
- export declare function chatToResponseObject(chatResp: ChatCompletionResponse, respId: string, model: string): Record<string, unknown>;
137
+ export declare function chatToResponseObject(chatResp: ChatCompletionResponse, respId: string, model: string,
138
+ /** Pre-minted on the relayed leg so `response.created` and `response.completed` share one item id. */
139
+ messageId?: string,
140
+ /**
141
+ * The client's EFFECTIVE `store` flag (default true, OpenAI parity). The
142
+ * gateway honors it: `store:false` means the response is not retained, so it
143
+ * can never be a `previous_response_id` parent — and the response object
144
+ * says so instead of pretending a chain exists.
145
+ */
146
+ store?: boolean): Record<string, unknown>;
147
+ /**
148
+ * Per-response SSE sequence counter. OpenAI Responses streaming events carry a
149
+ * monotonically increasing `sequence_number`. Strict consumers declare it
150
+ * REQUIRED on EVERY event — including their catch-all `Unknown` variant.
151
+ * JetBrains Junie (4020.10) drops unnumbered events silently, so a missing
152
+ * number on `response.completed` makes it throw `LlmStreamTruncatedException`
153
+ * ("streaming response ended before a terminal response.* event") and surface
154
+ * "A network error interrupted the request to the model provider".
155
+ *
156
+ * One counter is shared by the relayed leg's opening prefix, every live
157
+ * `response.output_text.delta`, and the closing half. The buffered leg owns a
158
+ * fresh counter and numbers its synthesized sequence the same way.
159
+ */
160
+ export interface ResponsesStreamSequence {
161
+ value: number;
162
+ }
163
+ export declare function newResponseStreamSequence(): ResponsesStreamSequence;
164
+ /** One `event:/data:` frame — the exact shape every Responses SSE consumer reads. */
165
+ export declare function responsesEventFrame(payload: Record<string, unknown>): string;
166
+ /** Id for the assistant message item; minted at parse time on the relayed leg. */
167
+ export declare function newResponseMessageId(): string;
168
+ /**
169
+ * Frames emitted ONCE before the first upstream chunk of a relayed turn.
170
+ * `output_item.added` / `content_part.added` pin the item_id that every later
171
+ * `response.output_text.delta` must carry, so they cannot wait for the result.
172
+ */
173
+ export declare function responsesStreamPrefix(respId: string, model: string, messageId: string, seq?: ResponsesStreamSequence, store?: boolean): string[];
174
+ /** ONE upstream chat delta -> ONE Responses text delta frame. */
175
+ export declare function responsesDeltaFrame(messageId: string, delta: string, seq: ResponsesStreamSequence): string;
103
176
  /** Synthesized Responses SSE event sequence for one buffered completion. */
104
- export declare function chatToStreamEvents(chatResp: ChatCompletionResponse, respId: string, model: string): string[];
177
+ export declare function chatToStreamEvents(chatResp: ChatCompletionResponse, respId: string, model: string, messageId?: string, seq?: ResponsesStreamSequence, store?: boolean): string[];
178
+ /**
179
+ * Closing half of a relayed turn. Shares the SAME sequence counter as the
180
+ * prefix and the live deltas so `sequence_number` stays strictly increasing
181
+ * across the entire connection.
182
+ */
183
+ export declare function responsesStreamSuffix(chatResp: ChatCompletionResponse, respId: string, model: string, messageId: string, seq: ResponsesStreamSequence, store?: boolean): string[];
105
184
  export {};