@morgan9668/dsh-llm-gateway 1.2.0 → 1.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.
package/index.js CHANGED
@@ -14,6 +14,13 @@ import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
14
14
  import { homedir } from 'node:os';
15
15
  import { join } from 'node:path';
16
16
 
17
+ import { createNoticeHub } from './src/notify/hub.js';
18
+ import { createNotifier } from './src/notify/index.js';
19
+ import { normalizeNotify, normalizeInApp } from './src/notify/config.js';
20
+ import { reasonKindOf } from './src/notify/render.js';
21
+ import { createConfigStore } from './src/notify/store.js';
22
+ import { createStreamCollector, summarizeCollected, tapStream } from './src/notify/stream-tap.js';
23
+
17
24
  export const name = 'dsh-llm-gateway';
18
25
  // `attachments` 用于把工具返回的内联图片落成真实附件,让模型能看到图;
19
26
  // 没有该服务时退化为占位文本(见 imagePlaceholder)。
@@ -22,11 +29,19 @@ export const inject = ['llm', 'attachments'];
22
29
  const DEFAULTS = {
23
30
  host: '127.0.0.1',
24
31
  port: 8392,
25
- // 认证默认**开启**。空串不再表示「不鉴权」,而是「用自动生成的密钥」——
26
- // 见 resolveApiKey。空串放行意味着本机任何进程都能白用你已配好的模型额度,
27
- // 这是市场审核明确要求整改的一条。
32
+ // 认证默认**关闭**,保持向后兼容:空串就是「不校验 token」。
33
+ //
34
+ // 之所以不默认开启:现成的客户端(Codex、SDK、脚本)都是零配置直连的,
35
+ // 一旦默认要求 token,它们会在升级后立刻 401,而用户不一定知道去哪找密钥。
36
+ // 默认开启的安全收益有限——网关本来就只绑回环,外加下面 Host/Origin 两道
37
+ // 校验,已经挡住了真正危险的场景(浏览器里的跨站页面、DNS rebinding)。
38
+ //
39
+ // 需要更强隔离时:把 requireAuth 设为 true,密钥会自动生成到 apiKeyFile
40
+ // (600 权限),或者直接把 apiKey 填成想要的值。
28
41
  apiKey: '',
29
- // 自动生成的密钥落盘位置。首次启动写入,之后复用。
42
+ // 为 true 时强制校验 bearer token;apiKey 为空则自动生成并落盘。
43
+ requireAuth: false,
44
+ // 自动生成的密钥落盘位置。requireAuth 打开时才使用。
30
45
  apiKeyFile: '',
31
46
  // 允许的 Host 头。默认只接受回环地址的几种写法,挡掉 DNS rebinding。
32
47
  allowedHosts: [],
@@ -137,6 +152,7 @@ function normalizeConfig(raw) {
137
152
  if (typeof raw.host === 'string' && raw.host !== '') config.host = raw.host;
138
153
  if (Number.isInteger(raw.port) && raw.port > 0 && raw.port < 65536) config.port = raw.port;
139
154
  if (typeof raw.apiKey === 'string') config.apiKey = raw.apiKey;
155
+ if (typeof raw.requireAuth === 'boolean') config.requireAuth = raw.requireAuth;
140
156
  if (typeof raw.apiKeyFile === 'string') config.apiKeyFile = raw.apiKeyFile;
141
157
  if (Array.isArray(raw.allowedHosts)) {
142
158
  config.allowedHosts = raw.allowedHosts.filter((h) => typeof h === 'string' && h !== '');
@@ -177,6 +193,8 @@ function defaultAllowedHosts(host, port) {
177
193
  */
178
194
  function resolveApiKey(config) {
179
195
  if (config.apiKey !== '') return { key: config.apiKey, filePath: undefined, generated: false };
196
+ // 既没填 apiKey 也没要求认证:不校验。调用方据此跳过 token 比对。
197
+ if (config.requireAuth !== true) return { key: '', filePath: undefined, generated: false };
180
198
  const filePath = config.apiKeyFile !== ''
181
199
  ? config.apiKeyFile
182
200
  : join(homedir(), '.dsh', 'dsh-llm-gateway.key');
@@ -574,6 +592,87 @@ function uuid() {
574
592
  return randomUUID();
575
593
  }
576
594
 
595
+ /* ------------------------------------------------------------------ *
596
+ * 会话事件的只读小工具
597
+ * ------------------------------------------------------------------ */
598
+
599
+ /**
600
+ * 从事件里取它自己的时间戳。
601
+ *
602
+ * DSH 提交的每条会话事件都带 `time`(毫秒)。这个值有两条硬性好处:
603
+ * · 不受插件重启影响 —— 每次 reconcile 都会重新 apply,内存里记的
604
+ * 「回合开始时刻」随之清零;
605
+ * · 与日志里其它事件同一个时钟,算出来的差值和 DSH 自己显示的一致。
606
+ */
607
+ function eventTime(event, fallback) {
608
+ const time = event?.time;
609
+ return typeof time === 'number' && Number.isFinite(time) && time > 0 ? time : fallback;
610
+ }
611
+
612
+ /**
613
+ * 从会话事件日志里算某一回合的耗时。
614
+ *
615
+ * 取**同一 turn 号**的 turn/start 与 turn/end 两条事件的时间差。这是跨插件
616
+ * 重启唯一可靠的算法:内存里的 Map 一重新 apply 就空了,而日志还在。
617
+ * 找不到配对、时间戳缺失、或差值为负时返回 undefined——交给调用方决定怎么
618
+ * 降级,而不是在这里编一个数字出来。
619
+ */
620
+ function turnDurationFromEvents(events, turn) {
621
+ if (!Array.isArray(events) || events.length === 0) return undefined;
622
+ if (!Number.isInteger(turn) || turn < 0) return undefined;
623
+
624
+ let startTime;
625
+ let endTime;
626
+ // 反向扫:同一个 turn 号在日志里只应出现一次起止,从新往旧找最快命中。
627
+ for (let i = events.length - 1; i >= 0; i -= 1) {
628
+ const event = events[i];
629
+ if (event?.data?.turn !== turn) continue;
630
+ if (event.type === 'turn/end' && endTime === undefined) {
631
+ const time = event?.time;
632
+ if (typeof time === 'number' && Number.isFinite(time)) endTime = time;
633
+ } else if (event.type === 'turn/start' && startTime === undefined) {
634
+ const time = event?.time;
635
+ if (typeof time === 'number' && Number.isFinite(time)) startTime = time;
636
+ }
637
+ if (startTime !== undefined && endTime !== undefined) break;
638
+ }
639
+
640
+ if (startTime === undefined || endTime === undefined) return undefined;
641
+ const duration = endTime - startTime;
642
+ return duration >= 0 ? duration : undefined;
643
+ }
644
+
645
+ /**
646
+ * 读会话的完整事件日志(旧 → 新)。
647
+ *
648
+ * 真正的读法是 `snapshotEvents(fromSeq?, toSeqExclusive?)`;更早的 harness
649
+ * 只有 `events` getter,两条都要试,否则在新版上会静默拿到 undefined。
650
+ * 任何读取失败都退化成空数组:内容降级可以接受,把异常抛给 harness 不行。
651
+ */
652
+ function sessionEvents(session) {
653
+ try {
654
+ if (typeof session?.snapshotEvents === 'function') {
655
+ const snapshot = session.snapshotEvents();
656
+ if (Array.isArray(snapshot)) return snapshot;
657
+ }
658
+ if (Array.isArray(session?.events)) return session.events;
659
+ } catch {
660
+ /* 落到空日志 */
661
+ }
662
+ return [];
663
+ }
664
+
665
+ /** 会话当前用的模型,形如 `provider/model`;读不到就留空。 */
666
+ function modelLabelOf(session) {
667
+ try {
668
+ const selection = session?.requestHeader?.()?.config;
669
+ if (selection?.provider && selection?.model) return `${selection.provider}/${selection.model}`;
670
+ } catch {
671
+ /* 调用方折叠失败就退回空串 */
672
+ }
673
+ return '';
674
+ }
675
+
577
676
  /* ------------------------------------------------------------------ *
578
677
  * Request conversion: both Wire protocols -> DSH GenerateOptions.messages
579
678
  * ------------------------------------------------------------------ */
@@ -1686,9 +1785,57 @@ export function apply(ctx, rawConfig) {
1686
1785
  if (apiKeyGenerated) {
1687
1786
  log(`已生成新的 API 密钥并写入 ${apiKeyFile ?? '(仅本次进程)'};客户端请用 Authorization: Bearer <该文件内容>`);
1688
1787
  }
1689
- log(`认证已启用;允许的 Host:${allowedHosts.join(', ')}`);
1788
+ if (apiKey === '') {
1789
+ log(`认证未启用(只绑回环 + Host/Origin 校验);需要时设 requireAuth: true 或填 apiKey`);
1790
+ } else {
1791
+ log('认证已启用');
1792
+ }
1793
+ log(`允许的 Host:${allowedHosts.join(', ')}`);
1690
1794
  if (allowedOrigins.length > 0) log(`允许的 Origin:${allowedOrigins.join(', ')}`);
1691
1795
 
1796
+ /* ---------------------------------------------------------------- *
1797
+ * 任务完成通知
1798
+ *
1799
+ * 两块触发源共享同一套渠道、排版与闪动:
1800
+ * · 网关请求 —— 本文件里的 handle() 每打完一个请求记一笔(外部客户端);
1801
+ * · DSH 会话 —— 下面的 session/event 监听(本机 agent 的回合)。
1802
+ *
1803
+ * 配置存自己的文件(见 src/notify/store.js):写 config 会触发 reconcile,
1804
+ * 也就是 server.close() 重启,正在跑的客户端请求会被掐断。设置页改一个
1805
+ * 勾选框就断掉 Codex 的任务,那不可接受。
1806
+ * ---------------------------------------------------------------- */
1807
+ const notifyHub = createNoticeHub({ log });
1808
+ ctx.effect?.(() => () => notifyHub.dispose(), 'dsh-llm-gateway: notify hub');
1809
+
1810
+ const notifyStore = createConfigStore({
1811
+ // 与密钥文件同一个目录,都是 ~/.dsh 下的本机文件。
1812
+ filePath: join(homedir(), '.dsh', 'dsh-llm-gateway.notify.json'),
1813
+ // patch 里的兜底配置在 `notify:` 下面。**不**回落到整个 rawConfig:
1814
+ // 那样一来网关自己的 host/port/apiKey 会被当成通知字段,而 `enabled`
1815
+ // 这类字段在同名不同义时更难查。
1816
+ readPatchConfig: () => rawConfig?.notify ?? {},
1817
+ log,
1818
+ });
1819
+ const notifier = createNotifier({
1820
+ readConfig: () => notifyStore.read(),
1821
+ log,
1822
+ hub: notifyHub,
1823
+ });
1824
+
1825
+ {
1826
+ const notifyConfig = notifier.currentConfig();
1827
+ if (!notifyConfig.enabled) {
1828
+ log('通知:已禁用(notify.enabled: false)');
1829
+ } else {
1830
+ const ready = notifier.readyChannels();
1831
+ log(ready.length === 0
1832
+ ? '通知:已启用但没有任何可用渠道;在网关设置页填 Webhook 后即可发送'
1833
+ : `通知:已启用,可用渠道 ${ready.join('、')}`);
1834
+ log(`通知触发源:网关请求 ${notifyConfig.sources.gateway ? '开' : '关'}、`
1835
+ + `DSH 会话 ${notifyConfig.sources.session ? '开' : '关'}`);
1836
+ }
1837
+ }
1838
+
1692
1839
  let cache = [];
1693
1840
  let cacheAt = 0;
1694
1841
  let inflight = null;
@@ -1861,6 +2008,8 @@ export function apply(ctx, rawConfig) {
1861
2008
  * 远程可达的端点上那是可测量的时间侧信道。
1862
2009
  */
1863
2010
  function authorized(request) {
2011
+ // apiKey 为空 = 未启用认证(requireAuth 关闭且没填 key)。
2012
+ if (apiKey === '') return true;
1864
2013
  const header = request.headers.get('authorization') ?? '';
1865
2014
  const prefix = 'Bearer ';
1866
2015
  if (!header.startsWith(prefix)) return false;
@@ -1894,6 +2043,88 @@ export function apply(ctx, rawConfig) {
1894
2043
  return allowedOrigins.includes(origin.toLowerCase());
1895
2044
  }
1896
2045
 
2046
+ /* ---------------------------------------------------------------- *
2047
+ * 网关请求 → 通知
2048
+ * ---------------------------------------------------------------- */
2049
+
2050
+ /**
2051
+ * 从 User-Agent 里认出「谁在调我」。
2052
+ *
2053
+ * 只取第一段(`codex_cli_rs/0.31.0` → `codex_cli_rs`),完整 UA 太长,
2054
+ * 塞进群消息的标题里会把真正有用的模型名挤掉。认不出就留空,
2055
+ * 通知里那一截自然消失,不写「未知客户端」这种废话。
2056
+ */
2057
+ function clientLabelOf(request) {
2058
+ const raw = request.headers.get('user-agent') ?? '';
2059
+ if (raw.trim() === '') return '';
2060
+ const first = raw.split(/[\s/]+/)[0] ?? '';
2061
+ return first.slice(0, 40);
2062
+ }
2063
+
2064
+ /** 一次请求在通知里需要的固定信息。 */
2065
+ /**
2066
+ * 一次请求在通知里需要的固定信息。
2067
+ *
2068
+ * `startedAt` 必须在这里取,而不是在 `noteGateway` 里:那个函数在请求
2069
+ * **收尾**时调用,单请求任务的首尾时刻会相同,算出来的耗时恒为 0。
2070
+ * 这是个真实踩过的坑——通知里写过「耗时 0 毫秒」。
2071
+ */
2072
+ function noteContext(request, route, protocol, startedAt = Date.now()) {
2073
+ return {
2074
+ clientLabel: clientLabelOf(request),
2075
+ modelLabel: typeof route?.publicId === 'string' ? route.publicId : '',
2076
+ protocol,
2077
+ startedAt,
2078
+ };
2079
+ }
2080
+
2081
+ /**
2082
+ * 把一次请求的结局交给通知调度器。
2083
+ *
2084
+ * 数据源两种形状,字段名不同,在这里抹平而不是让两条路径各写一份调用:
2085
+ * · 流式路径 —— `createStreamCollector()`:`toolCalls` 是数字,
2086
+ * `usage` 是 DSH 形状,要经 `summarizeCollected` 换算;
2087
+ * · 非流式路径 —— `collectStream()`:`toolCalls` 是数组,
2088
+ * `usage` 已经是 OpenAI 形状。
2089
+ *
2090
+ * 判据是 `toolCalls` 是不是数组——这比「有没有 usage」可靠:非流式路径在
2091
+ * 上游不给 usage 时 `usage` 是 undefined,用 usage 判断会把它错认成流式。
2092
+ *
2093
+ * 绝不抛错:通知坏了不该让一个已经成功的请求变成 500。
2094
+ */
2095
+ function noteGateway(collected, base, extra = {}) {
2096
+ try {
2097
+ const fromCollectStream = Array.isArray(collected?.toolCalls);
2098
+ notifier.recordGatewayRequest({
2099
+ ...base,
2100
+ reasonKind: reasonKindOf(collected?.finish),
2101
+ failureMessage: extra.failureMessage ?? '',
2102
+ usage: fromCollectStream
2103
+ ? usageFromWireValue(collected?.usage)
2104
+ : summarizeCollected(collected, usageToOpenAI).usage,
2105
+ reply: typeof collected?.text === 'string' ? collected.text : '',
2106
+ toolCallCount: fromCollectStream ? collected.toolCalls.length : (collected?.toolCalls ?? 0),
2107
+ });
2108
+ } catch (error) {
2109
+ log(`记录网关通知失败:${error?.message ?? error}`);
2110
+ }
2111
+ }
2112
+
2113
+ /** 把 OpenAI 形状的 usage(非流式路径的产物)收成渲染层形状。 */
2114
+ function usageFromWireValue(usage) {
2115
+ if (usage === undefined || usage === null) return undefined;
2116
+ return {
2117
+ available: true,
2118
+ inputTokens: usage.prompt_tokens ?? 0,
2119
+ outputTokens: usage.completion_tokens ?? 0,
2120
+ totalTokens: usage.total_tokens ?? (usage.prompt_tokens ?? 0) + (usage.completion_tokens ?? 0),
2121
+ cachedReadTokens: usage.prompt_tokens_details?.cached_tokens
2122
+ ?? usage.prompt_cache_hit_tokens
2123
+ ?? 0,
2124
+ missing: [],
2125
+ };
2126
+ }
2127
+
1897
2128
  async function handle(request) {
1898
2129
  // `request` is a Web Request (absolute url) built in createServer below.
1899
2130
  const url = new URL(request.url);
@@ -1945,6 +2176,9 @@ export function apply(ctx, rawConfig) {
1945
2176
  }
1946
2177
 
1947
2178
  if (request.method === 'POST' && path === '/v1/chat/completions') {
2179
+ // 耗时从这个请求进网关那一刻算起,不是从「结果出来」算起:
2180
+ // 后者让单请求任务的耗时恒为 0(见 noteContext 的说明)。
2181
+ const startedAt = Date.now();
1948
2182
  const body = await readJson(request, config.maxBodyBytes);
1949
2183
  let messages = chatMessagesToDsh(body.messages, { provider: 'gateway', model: body.model });
1950
2184
  messages = await materializeImages(messages, {
@@ -1955,9 +2189,13 @@ export function apply(ctx, rawConfig) {
1955
2189
  });
1956
2190
  if (messages.length === 0) throw new HttpError(400, 'messages must not be empty');
1957
2191
  const { route, options } = await buildOptions(body, messages, requestedEffortOf(body));
2192
+ const noteBase = noteContext(request, route, 'Chat Completions', startedAt);
1958
2193
 
1959
2194
  if (body.stream === true) {
1960
2195
  const encoder = new TextEncoder();
2196
+ // 旁路采集:把 chunk 原样转给 handleChatStream,同时记下正文与用量。
2197
+ // tapStream 不改变任何 chunk,网关对客户端的行为与没开通知时完全一致。
2198
+ const collector = createStreamCollector();
1961
2199
  const stream = new ReadableStream({
1962
2200
  start(controller) {
1963
2201
  const sink = {
@@ -1966,16 +2204,22 @@ export function apply(ctx, rawConfig) {
1966
2204
  },
1967
2205
  };
1968
2206
  (async () => {
2207
+ // 一个请求只记一次通知:catch 里记了失败原因,finally 就不要
2208
+ // 再用默认值覆盖一遍(那会把「上游报错」写成「任务完成」)。
2209
+ let noted = false;
1969
2210
  try {
1970
- await handleChatStream(body.model, ctx.llm.stream(options), sink);
2211
+ await handleChatStream(body.model, tapStream(ctx.llm.stream(options), collector), sink);
1971
2212
  } catch (error) {
1972
2213
  const failure = failureOf(error?.reason) ?? { message: String(error) };
1973
2214
  sink.write(sseChunk({
1974
2215
  error: { message: failure.message ?? String(error), type: 'api_error' },
1975
2216
  }));
1976
2217
  sink.write('data: [DONE]\n\n');
2218
+ noteGateway(collector, noteBase, { failureMessage: failure.message ?? String(error) });
2219
+ noted = true;
1977
2220
  } finally {
1978
2221
  try { controller.close(); } catch { /* already closed */ }
2222
+ if (!noted) noteGateway(collector, noteBase);
1979
2223
  }
1980
2224
  })();
1981
2225
  },
@@ -1993,16 +2237,20 @@ export function apply(ctx, rawConfig) {
1993
2237
  && collected.reasoning.trim() !== ''
1994
2238
  && collected.finish?.reason?.kind !== 'max-tokens';
1995
2239
  if (reasoningOnly) {
2240
+ noteGateway(collected, noteBase, { failureMessage: 'upstream returned reasoning without output text' });
1996
2241
  throw new HttpError(502, 'upstream returned reasoning without output text; retry', 'empty_reasoning_only');
1997
2242
  }
1998
2243
  if (failure !== undefined && collected.text === '' && collected.toolCalls.length === 0) {
1999
2244
  const classified = classifiedError(failure);
2245
+ noteGateway(collected, noteBase, { failureMessage: failure.message ?? 'upstream failed' });
2000
2246
  throw new HttpError(classified.status, classified.body.message, classified.body.type, classified.headers);
2001
2247
  }
2248
+ noteGateway(collected, noteBase);
2002
2249
  return json(chatCompletionNonStream(body.model, collected));
2003
2250
  }
2004
2251
 
2005
2252
  if (request.method === 'POST' && path === '/v1/responses') {
2253
+ const startedAt = Date.now();
2006
2254
  const body = await readJson(request, config.maxBodyBytes);
2007
2255
  let messages = responsesToDsh(body, { provider: 'gateway', model: body.model });
2008
2256
  messages = await materializeImages(messages, {
@@ -2018,9 +2266,11 @@ export function apply(ctx, rawConfig) {
2018
2266
  max_tokens: body.max_output_tokens,
2019
2267
  };
2020
2268
  const { route, options } = await buildOptions(bodyForOptions, messages, requestedEffortOf(body));
2269
+ const noteBase = noteContext(request, route, 'Responses', startedAt);
2021
2270
 
2022
2271
  if (body.stream === true) {
2023
2272
  const encoder = new TextEncoder();
2273
+ const collector = createStreamCollector();
2024
2274
  const stream = new ReadableStream({
2025
2275
  start(controller) {
2026
2276
  const sink = {
@@ -2029,8 +2279,9 @@ export function apply(ctx, rawConfig) {
2029
2279
  },
2030
2280
  };
2031
2281
  (async () => {
2282
+ let noted = false;
2032
2283
  try {
2033
- await handleResponsesStream(body.model, ctx.llm.stream(options), sink);
2284
+ await handleResponsesStream(body.model, tapStream(ctx.llm.stream(options), collector), sink);
2034
2285
  } catch (error) {
2035
2286
  sink.write(sseEvent('response.failed', {
2036
2287
  response: {
@@ -2041,8 +2292,11 @@ export function apply(ctx, rawConfig) {
2041
2292
  error: { message: String(error), code: 'upstream_error' },
2042
2293
  },
2043
2294
  }));
2295
+ noteGateway(collector, noteBase, { failureMessage: String(error) });
2296
+ noted = true;
2044
2297
  } finally {
2045
2298
  try { controller.close(); } catch { /* already closed */ }
2299
+ if (!noted) noteGateway(collector, noteBase);
2046
2300
  }
2047
2301
  })();
2048
2302
  },
@@ -2060,18 +2314,207 @@ export function apply(ctx, rawConfig) {
2060
2314
  && collected.reasoning.trim() !== ''
2061
2315
  && collected.finish?.reason?.kind !== 'max-tokens';
2062
2316
  if (reasoningOnly) {
2317
+ noteGateway(collected, noteBase, { failureMessage: 'upstream returned reasoning without output text' });
2063
2318
  throw new HttpError(502, 'upstream returned reasoning without output text; retry', 'empty_reasoning_only');
2064
2319
  }
2065
2320
  if (failure !== undefined && collected.text === '' && collected.toolCalls.length === 0) {
2066
2321
  const classified = classifiedError(failure);
2322
+ noteGateway(collected, noteBase, { failureMessage: failure.message ?? 'upstream failed' });
2067
2323
  throw new HttpError(classified.status, classified.body.message, classified.body.type, classified.headers);
2068
2324
  }
2325
+ noteGateway(collected, noteBase);
2069
2326
  return json(responsesNonStream(body.model, collected));
2070
2327
  }
2071
2328
 
2072
2329
  throw new HttpError(404, `no route for ${request.method} ${path}`, 'not_found_error');
2073
2330
  }
2074
2331
 
2332
+ /* ---------------------------------------------------------------- *
2333
+ * 设置页的同源 API
2334
+ *
2335
+ * 走 DSH 自己的 webServer,而不是网关监听的 8392:设置页是浏览器里的页面,
2336
+ * 它和宿主同源;把配置接口挂到 8392 上等于让任何能访问网关的客户端改配置。
2337
+ *
2338
+ * 用 ctx.inject 而不是 apply 时 `ctx.get('webServer')` 一次:真实 web 组合里
2339
+ * 插件先加载、浏览器半身后发布该服务,一次性取会拿到 undefined,路由永远
2340
+ * 注册不上,设置页就变成一个永远转圈的壳。
2341
+ *
2342
+ * 四条路由都用**精确路径**,不用前缀:web server 按最长前缀匹配,一个吃掉
2343
+ * `/api/llm-gateway` 的前缀会顺手接管它下面所有未来的路径,排查成本远高于
2344
+ * 多写三行。
2345
+ * ---------------------------------------------------------------- */
2346
+ const API_PREFIX = '/api/llm-gateway';
2347
+
2348
+ const readBody = async (request) => {
2349
+ const chunks = [];
2350
+ if (typeof request?.[Symbol.asyncIterator] === 'function') {
2351
+ for await (const chunk of request) chunks.push(chunk);
2352
+ }
2353
+ const text = Buffer.concat(chunks).toString('utf8');
2354
+ if (text.trim() === '') return {};
2355
+ return JSON.parse(text);
2356
+ };
2357
+
2358
+ const sendJson = (response, status, payload) => {
2359
+ response.writeHead(status, {
2360
+ 'content-type': 'application/json; charset=utf-8',
2361
+ 'cache-control': 'no-store',
2362
+ });
2363
+ response.end(JSON.stringify(payload));
2364
+ };
2365
+
2366
+ /** 网关自身的只读状态:设置页顶部那一行用它,用户据此确认网关在工作。 */
2367
+ const gatewayStatus = () => ({
2368
+ host: config.host,
2369
+ port: config.port,
2370
+ listening: server.listening,
2371
+ models: cache.length,
2372
+ // 认证开着时不说密钥内容,只说「开了」——设置页在浏览器里,
2373
+ // 把密钥回显出去等于把它写进 DOM 和截图。
2374
+ auth: apiKey !== '',
2375
+ });
2376
+
2377
+ ctx.inject?.(['webServer'], (scoped) => {
2378
+ const web = scoped.webServer;
2379
+ if (web === undefined || typeof web.register !== 'function') return;
2380
+
2381
+ const register = (path, handler) => {
2382
+ try {
2383
+ scoped.effect(
2384
+ () => web.register({
2385
+ kind: 'exact',
2386
+ path,
2387
+ handler: (request, response) => {
2388
+ void (async () => {
2389
+ try {
2390
+ await handler(request, response);
2391
+ } catch (error) {
2392
+ sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
2393
+ }
2394
+ })();
2395
+ },
2396
+ }),
2397
+ `dsh-llm-gateway: ${path}`,
2398
+ );
2399
+ } catch (error) {
2400
+ log(`路由 ${path} 注册失败:${error instanceof Error ? error.message : String(error)}`);
2401
+ }
2402
+ };
2403
+
2404
+ /**
2405
+ * 配置读写,一条路由。
2406
+ *
2407
+ * **必须是一条。** 曾经拆成两条同路径的 register:web server 按
2408
+ * (kind, path) 去重,先注册的 GET 处理器把 POST 也吞了,客户端勾选框拿回
2409
+ * 「当前配置」而不是「已保存」,JSON 立刻弹回,而 HTTP 状态还是 200。
2410
+ */
2411
+ register(`${API_PREFIX}/settings`, async (request, response) => {
2412
+ if (request.method === 'POST') {
2413
+ const body = await readBody(request);
2414
+ const { config: next, saved, detail } = notifyStore.setPath(body.path, body.value);
2415
+ log(`通知设置已更新:${Array.isArray(body.path) ? body.path.join('.') : '?'}`
2416
+ + `${saved ? '' : `(仅内存,写盘失败:${detail})`}`);
2417
+ sendJson(response, saved ? 200 : 500, {
2418
+ ok: saved,
2419
+ saved,
2420
+ ...(saved ? {} : { error: detail ?? '配置写入失败' }),
2421
+ settings: normalizeNotify(next),
2422
+ status: gatewayStatus(),
2423
+ });
2424
+ return;
2425
+ }
2426
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
2427
+ sendJson(response, 405, { error: '只接受 GET / POST' });
2428
+ return;
2429
+ }
2430
+ sendJson(response, 200, {
2431
+ ok: true,
2432
+ settings: notifier.currentConfig(),
2433
+ status: gatewayStatus(),
2434
+ viewers: notifier.viewers,
2435
+ });
2436
+ });
2437
+
2438
+ /**
2439
+ * 闪动事件流(SSE)。
2440
+ *
2441
+ * 不走 register 包装:那个包装吞返回值,而这里要的是接管响应并一直开着。
2442
+ * 也不包 try/catch 上报——流已经写出去了,再补一个 500 只会在客户端留下
2443
+ * 半截帧。
2444
+ */
2445
+ try {
2446
+ scoped.effect(
2447
+ () => web.register({
2448
+ kind: 'exact',
2449
+ path: `${API_PREFIX}/events`,
2450
+ handler: (request, response) => {
2451
+ if (request.method === 'OPTIONS') {
2452
+ response.writeHead(204, { allow: 'GET, HEAD, OPTIONS', 'cache-control': 'no-store' });
2453
+ response.end();
2454
+ return;
2455
+ }
2456
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
2457
+ sendJson(response, 405, { error: '只接受 GET' });
2458
+ return;
2459
+ }
2460
+ notifyHub.attach(request, response, {
2461
+ settings: notifier.currentConfig().inApp,
2462
+ viewers: notifyHub.size + 1,
2463
+ });
2464
+ },
2465
+ }),
2466
+ 'dsh-llm-gateway: notify events',
2467
+ );
2468
+ } catch (error) {
2469
+ log(`通知流路由注册失败:${error instanceof Error ? error.message : String(error)}`);
2470
+ }
2471
+
2472
+ /** 发送测试通知:验证 Webhook 通不通。 */
2473
+ register(`${API_PREFIX}/test`, async (request, response) => {
2474
+ if (request.method === 'OPTIONS') {
2475
+ response.writeHead(204, { allow: 'POST, OPTIONS', 'cache-control': 'no-store' });
2476
+ response.end();
2477
+ return;
2478
+ }
2479
+ if (request.method !== 'POST') {
2480
+ sendJson(response, 405, { error: '只接受 POST' });
2481
+ return;
2482
+ }
2483
+ let results = [];
2484
+ try {
2485
+ results = await notifier.sendTest();
2486
+ } catch (error) {
2487
+ results = [{ ok: false, channel: 'host', detail: error instanceof Error ? error.message : String(error) }];
2488
+ }
2489
+ sendJson(response, 200, { ok: results.length > 0 && results.every((entry) => entry.ok), results });
2490
+ });
2491
+
2492
+ /**
2493
+ * 闪一下给用户看:设置页验证「次数 / 时长 / 颜色」。
2494
+ *
2495
+ * 它和真实触发走同一个 emitFlash,所以预览看到的就是真效果;但它**不看**
2496
+ * inApp.enabled——用户正站在设置页点「预览」,取消勾选后还想看一眼再决定,
2497
+ * 拦下来只会让人以为按钮坏了。送达 0 个页面时如实回报 0。
2498
+ */
2499
+ register(`${API_PREFIX}/flash`, async (request, response) => {
2500
+ if (request.method === 'OPTIONS') {
2501
+ response.writeHead(204, { allow: 'POST, OPTIONS', 'cache-control': 'no-store' });
2502
+ response.end();
2503
+ return;
2504
+ }
2505
+ if (request.method !== 'POST') {
2506
+ sendJson(response, 405, { error: '只接受 POST' });
2507
+ return;
2508
+ }
2509
+ const body = await readBody(request);
2510
+ const preview = normalizeInApp({ ...notifier.currentConfig().inApp, ...(body?.inApp ?? {}), enabled: true });
2511
+ const delivered = notifier.emitFlash({ inApp: preview });
2512
+ sendJson(response, 200, { ok: delivered > 0, viewers: delivered, settings: preview });
2513
+ });
2514
+
2515
+ log(`设置 API 已挂载:${API_PREFIX}`);
2516
+ });
2517
+
2075
2518
  const server = http.createServer(async (request, response) => {
2076
2519
  let result;
2077
2520
  try {
@@ -2145,6 +2588,95 @@ export function apply(ctx, rawConfig) {
2145
2588
  server.listen(config.port, config.host, () => {
2146
2589
  log(`listening on http://${config.host}:${config.port}`);
2147
2590
  });
2148
- return () => server.close();
2591
+ // 关服之前先把还没到期的聚合槽发出去:用户可能刚收到一个任务的结果,
2592
+ // 插件正好在这一刻被 reconcile(改配置、重载)。默默丢掉那条通知比
2593
+ // 晚发几毫秒糟得多。
2594
+ //
2595
+ // 用 void 而不是 await:effect 的清理函数是同步契约,返回 Promise 会被
2596
+ // 当成「清理未完成」而拖住下一次挂载。发送本身是 fire-and-forget。
2597
+ return () => {
2598
+ void notifier.flush().catch((error) => log(`通知冲刷失败:${error?.message ?? error}`));
2599
+ notifier.dispose();
2600
+ server.close();
2601
+ };
2149
2602
  });
2603
+
2604
+ /* ---------------------------------------------------------------- *
2605
+ * DSH 会话回合 → 通知
2606
+ *
2607
+ * 第二个触发源。它和网关请求那条完全独立:网关收到的是外部客户端的一次
2608
+ * 请求,这里是本机 agent 的一个回合。两边共用一个渠道配置,所以设置页
2609
+ * 里的「触发源」两个勾选框可以分别关掉。
2610
+ *
2611
+ * 事件本身由 DSH 提交(post-commit),插件只是读:任何计算都不改会话状态,
2612
+ * 也不向会话里写东西。
2613
+ * ---------------------------------------------------------------- */
2614
+ if (typeof ctx.on === 'function') {
2615
+ /** 每个会话的回合开始时刻与 turn 号,用于算耗时。 */
2616
+ const turnStarts = new Map();
2617
+ /** 已发送过的回合指纹,避免同一条重复推送。 */
2618
+ const delivered = new Set();
2619
+
2620
+ ctx.effect(() => {
2621
+ const off = ctx.on('session/event', (session, event) => {
2622
+ try {
2623
+ if (event?.type === 'turn/start') {
2624
+ turnStarts.set(session?.id, {
2625
+ // 记事件自带的 `time`(DSH 提交日志时打的时间戳),而不是
2626
+ // Date.now():后者只是「插件看到这条事件的那一刻」,插件在回合
2627
+ // 中途被 reconcile 重启过,这个值就丢了。
2628
+ at: eventTime(event, Date.now()),
2629
+ turn: event?.data?.turn,
2630
+ });
2631
+ return;
2632
+ }
2633
+ if (event?.type !== 'turn/end') return;
2634
+
2635
+ const notifyConfig = notifier.currentConfig();
2636
+ if (!notifyConfig.enabled || !notifyConfig.sources.session) return;
2637
+
2638
+ const depth = session?.header?.delegationDepth ?? 0;
2639
+ if (!notifyConfig.notifySubagents && depth > 0) return;
2640
+
2641
+ const reasonKind = event?.data?.reason?.kind;
2642
+ if (!notifyConfig.reasons.includes(reasonKind)) return;
2643
+
2644
+ const key = `${session?.id}\u0000${event?.data?.turn ?? ''}\u0000${reasonKind}`;
2645
+ if (delivered.has(key)) return;
2646
+ delivered.add(key);
2647
+ // 上限保护:长会话不无限增长。
2648
+ if (delivered.size > 512) {
2649
+ const oldest = delivered.values().next().value;
2650
+ delivered.delete(oldest);
2651
+ }
2652
+
2653
+ const started = turnStarts.get(session?.id);
2654
+ const turn = started?.turn ?? event?.data?.turn;
2655
+ turnStarts.delete(session?.id);
2656
+
2657
+ // 事件日志是唯一可靠的耗时来源:内存里的 turnStarts 只在插件实例
2658
+ // 活着时有效,而插件每次改配置都会被 reconcile 重启一次。
2659
+ const events = sessionEvents(session);
2660
+ const durationMs = turnDurationFromEvents(events, turn)
2661
+ ?? (started?.at ? eventTime(event, Date.now()) - started.at : Number.NaN);
2662
+
2663
+ // fire-and-forget:通知失败不该让 agent 的收尾变慢或报错。
2664
+ void notifier.notifySession({
2665
+ session,
2666
+ events,
2667
+ reasonKind,
2668
+ durationMs,
2669
+ turn,
2670
+ modelLabel: modelLabelOf(session),
2671
+ }).catch((error) => log(`会话通知发送失败:${error?.message ?? error}`));
2672
+ } catch (error) {
2673
+ log(`会话通知处理失败:${error?.message ?? error}`);
2674
+ }
2675
+ });
2676
+ return () => {
2677
+ off?.();
2678
+ turnStarts.clear();
2679
+ };
2680
+ }, 'dsh-llm-gateway: session notify');
2681
+ }
2150
2682
  }