one-model-router 0.0.10 → 0.0.11

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 (77) hide show
  1. package/LICENSE +21 -21
  2. package/package.json +1 -1
  3. package/src/admin.js +941 -941
  4. package/src/balances.js +61 -61
  5. package/src/boot.js +117 -117
  6. package/src/channels/buddy.js +2031 -2031
  7. package/src/channels/cline.js +753 -753
  8. package/src/channels/codearts.js +2051 -2051
  9. package/src/channels/comate.js +830 -830
  10. package/src/channels/doubaowork.js +1784 -1784
  11. package/src/channels/freebuff.js +1316 -1316
  12. package/src/channels/gemini.js +1721 -1721
  13. package/src/channels/index.js +270 -270
  14. package/src/channels/joycode.js +936 -936
  15. package/src/channels/kimi.js +572 -572
  16. package/src/channels/lobsterai.js +1226 -1226
  17. package/src/channels/loomy.js +1032 -1032
  18. package/src/channels/miaoshou.js +1396 -1396
  19. package/src/channels/mimo.js +474 -474
  20. package/src/channels/minimax.js +1451 -1451
  21. package/src/channels/qoder-wasm.js +434 -434
  22. package/src/channels/qoder.js +1619 -1619
  23. package/src/channels/raccoon.js +1842 -1842
  24. package/src/channels/tabbit.js +1457 -1457
  25. package/src/channels/trae.js +1405 -1405
  26. package/src/channels/zcode-global.js +35 -35
  27. package/src/channels/zcode.js +2085 -2085
  28. package/src/checkin.js +496 -496
  29. package/src/credits.js +464 -464
  30. package/src/crypto.js +132 -132
  31. package/src/free-models.js +683 -683
  32. package/src/gateway.js +596 -578
  33. package/src/health.js +86 -86
  34. package/src/model-key.js +35 -35
  35. package/src/paths.js +96 -96
  36. package/src/probe.js +318 -318
  37. package/src/providers/builtin.js +626 -626
  38. package/src/providers/index.js +483 -457
  39. package/src/providers/kilo.js +111 -111
  40. package/src/providers/last-good.js +69 -69
  41. package/src/providers/modelsdev.js +242 -242
  42. package/src/providers/openai-compat.js +312 -312
  43. package/src/providers/opencode/bun-fetch.js +226 -226
  44. package/src/providers/opencode/lane.js +186 -186
  45. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  46. package/src/providers/opencode/o2a/asset-source.js +43 -43
  47. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  48. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  49. package/src/providers/opencode/o2a/entry.js +17 -17
  50. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  51. package/src/providers/opencode/o2a/headers.js +133 -133
  52. package/src/providers/opencode/o2a/identity.js +148 -148
  53. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  54. package/src/providers/opencode/o2a/official-tools.js +110 -110
  55. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  56. package/src/providers/opencode/o2a/toolshape.js +418 -418
  57. package/src/providers/opencode/o2a/version.js +37 -37
  58. package/src/providers/opencode/upstream.js +403 -403
  59. package/src/providers/opencode/wire.js +496 -496
  60. package/src/providers/opencode.js +652 -652
  61. package/src/router.js +629 -629
  62. package/src/server.js +33 -33
  63. package/src/store.js +467 -467
  64. package/src/sync/index.js +1529 -1529
  65. package/src/sync/login-preload.cjs +52 -52
  66. package/src/sync/noise.js +141 -141
  67. package/src/sync/relay-http.js +176 -176
  68. package/src/sync/remote-host.js +818 -818
  69. package/src/sync/remote-http.js +112 -112
  70. package/src/sync/remote-login.js +657 -657
  71. package/src/sync/remote-pairing.js +204 -204
  72. package/src/sync/remote-protocol.js +321 -321
  73. package/src/sync/snapshot.js +211 -211
  74. package/src/util.js +334 -334
  75. package/web/app.js +3972 -3972
  76. package/web/index.html +32 -32
  77. package/web/style.css +971 -971
package/src/store.js CHANGED
@@ -1,467 +1,467 @@
1
- /**
2
- * 配置存储:数据目录下的 JSON 文档,原子写入(tmp + rename),脏数据回落默认值。
3
- *
4
- * 数据目录默认落在用户 OS 应用目录(见 paths.js),仓库 data/ 只作历史迁移源;
5
- * 需要指到别处用环境变量 OMR_DATA_DIR 覆盖。
6
- *
7
- * 文档划分(各用一个独立文档,避免互相抹字段):
8
- * settings.json 网关与内置通道设置
9
- * providers.json 自定义 OpenAI 兼容提供商
10
- * groups.json 模型组
11
- * checkin.json 签到任务与运行状态
12
- */
13
-
14
- import { randomUUID } from 'node:crypto'
15
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
16
- import { join } from 'node:path'
17
- import { generateApiKey } from './util.js'
18
- import { sealDeep, openDeep } from './crypto.js'
19
- import { DATA_DIR } from './paths.js'
20
- import { BUILTIN_PROVIDERS, BUILTIN_IDS } from './providers/builtin.js'
21
-
22
- export { DATA_DIR }
23
-
24
- function docPath(name) {
25
- return join(DATA_DIR, name)
26
- }
27
-
28
- function readDoc(name, fallback) {
29
- const file = docPath(name)
30
- if (!existsSync(file)) return structuredClone(fallback)
31
- try {
32
- const raw = JSON.parse(readFileSync(file, 'utf8'))
33
- // 透明解密:凭据字段(apiKey/credential 等)在磁盘为密文,运行时为明文。
34
- return openDeep({ ...structuredClone(fallback), ...raw })
35
- } catch {
36
- return structuredClone(fallback)
37
- }
38
- }
39
-
40
- function writeDoc(name, value) {
41
- mkdirSync(DATA_DIR, { recursive: true })
42
- const file = docPath(name)
43
- const tmp = `${file}.tmp`
44
- // 透明加密:落盘前密封凭据字段,明文不落盘。
45
- writeFileSync(tmp, JSON.stringify(sealDeep(value), null, 2), 'utf8')
46
- renameSync(tmp, file)
47
- }
48
-
49
- // ── settings ────────────────────────────────────────────────────────────────
50
-
51
- const DEFAULT_SETTINGS = {
52
- gateway: {
53
- enabled: true,
54
- host: '127.0.0.1',
55
- port: 18682,
56
- apiKey: '',
57
- /** 上游单轮超时(毫秒)。 */
58
- turnTimeoutMs: 300000,
59
- /** 上游首字节超时(毫秒)。 */
60
- headerTimeoutMs: 60000,
61
- /** 流空闲超时(毫秒),每 chunk 重置。 */
62
- idleTimeoutMs: 120000,
63
- /** 组内单候选首字预算(毫秒):超过则放弃该候选换下一个(多候选组生效)。 */
64
- candidateTimeoutMs: 45000,
65
- /** 对冲间隔(毫秒):当前候选迟迟不出字时提前并行启动下一个;0 = 关闭对冲。 */
66
- hedgeDelayMs: 6000,
67
- /** 对冲最大并发候选数。 */
68
- hedgeMaxParallel: 2,
69
- },
70
- kilo: {
71
- enabled: true,
72
- baseUrl: 'https://api.kilo.ai/api/gateway',
73
- userAgent: 'OneModelRouter/1.0',
74
- },
75
- opencode: {
76
- enabled: true,
77
- /** 只填 Origin(路径由车道按模型分流);历史值 `…/zen/v1` 会被自动归一。 */
78
- baseUrl: 'https://opencode.ai',
79
- /** 留空 = 用车道常量 CLIENT_UA(v2 形状);填非 v2 形态也会被归一回落。 */
80
- userAgent: '',
81
- /** 身份槽:apiKey === 'public' 为匿名槽(只能用免费模型),其余为账号槽。 */
82
- slots: [
83
- { id: 'opencode-anon-default', label: '匿名通道', apiKey: 'public', enabled: true, proxy: '' },
84
- ],
85
- },
86
- checkin: {
87
- /** 渠道原生自动签到开关;只有显式 false 才算关闭(默认打开)。 */
88
- enabled: true,
89
- /** 启动后延迟执行(毫秒),等渠道凭据续期先稳住;0 = 立刻。 */
90
- delayMs: 15000,
91
- },
92
- probe: {
93
- /** 后台周期探测模型可用性。默认关闭。 */
94
- enabled: false,
95
- /** 探测间隔(分钟),最小 1。 */
96
- intervalMinutes: 15,
97
- /** 上次探测完成时间(毫秒时间戳),0 = 从未探测。重启后按此与间隔对比决定是否自动探测。 */
98
- lastProbeAt: 0,
99
- },
100
- freeModels: {
101
- /**
102
- * 小时扫描时把各渠道的「勾选清单」整体替换为本次拉取到的可用清单:
103
- * - 免费渠道(自定义提供商):完整可用清单;
104
- * - 转发渠道:完整可用清单,并同步刷新倍率表(channels.json 的 modelRates);
105
- * - 免密渠道(kilo / opencode):免费可用清单。
106
- * 默认开启;关掉后回到「只自动勾选免费模型、用户勾选的付费模型不动」的老行为
107
- * (免密渠道仍只保留免费清单)。
108
- * 渠道自身显式声明了 meta.syncSelection 的以声明为准(如 Cline 只保留免费池)。
109
- */
110
- autoSelectAvailable: true,
111
- },
112
- sync: {
113
- /** 多端同步。默认关闭;transport = remote(DSH Remote 零知识中继)| cloud(旧云 DB 回退,B4 删除)。 */
114
- enabled: false,
115
- /** 默认走新链路;cloud 仅在管理页显式选择时启用(B1–B3 回退,B4 删除)。 */
116
- transport: 'remote',
117
- // ── cloud(B1–B3 回退保留,B4 删除)──
118
- /** 云服务数据面 endpoint(publicConfig.endpoint)。 */
119
- endpoint: '',
120
- /** 云服务 publishableKey(publicConfig,公开值)。 */
121
- publishableKey: '',
122
- /** 设备专用 WorkBuddy 账号邮箱。 */
123
- email: '',
124
- /** 设备账号密码(键名 password —— 加密层按此密封落盘)。 */
125
- password: '',
126
- /** 云设备 ID(公开标识,omr-xxxx;与 remote 的 UUID 身份互不影响)。 */
127
- deviceId: '',
128
- /** 设备密钥(omr_relay RPC 级凭据,键名 apiKey —— 加密层按此密封落盘)。 */
129
- apiKey: '',
130
- // ── remote(DSH Remote Protocol v1)──
131
- /** 控制面 HTTP 根地址;relayUrl 为 WSS 连接地址。 */
132
- apiOrigin: 'https://dsh.r2049.cn',
133
- relayUrl: 'wss://dsh.r2049.cn/ws/v1/connect',
134
- /** 首次注册 Host 用的站点账号令牌:注册成功立即清空,绝不长期落盘、绝不下发手机。 */
135
- siteToken: '',
136
- /** Host 设备 ID(UUID,协议强制)。 */
137
- remoteDeviceId: '',
138
- /** Host X25519 静态公钥(公开,指纹供扫码核对)。 */
139
- identityPublicKey: '',
140
- /** Host X25519 静态私钥(键名命中 SENSITIVE_KEYS,密封落盘)。 */
141
- identityPrivateKey: '',
142
- /** Host 设备凭据(密封落盘;靠 /api/v1/auth/refresh 无限续期)。 */
143
- accessToken: '',
144
- refreshToken: '',
145
- accessTokenExpiresAt: 0,
146
- refreshTokenExpiresAt: 0,
147
- /** 已配对 Client 设备记录(含公钥与撤销用凭据,密封落盘;上限 16 台)。 */
148
- boundClients: [],
149
- },
150
- }
151
-
152
- export function loadSettings() {
153
- const settings = readDoc('settings.json', DEFAULT_SETTINGS)
154
- if (typeof settings.gateway.apiKey !== 'string' || settings.gateway.apiKey === '') {
155
- settings.gateway.apiKey = generateApiKey()
156
- writeDoc('settings.json', settings)
157
- }
158
- return settings
159
- }
160
-
161
- export function saveSettings(settings) {
162
- writeDoc('settings.json', settings)
163
- }
164
-
165
- // ── providers(内置免费渠道 + 用户自建 OpenAI 兼容)────────────────────────
166
-
167
- const DEFAULT_PROVIDERS = { custom: [] }
168
-
169
- /** 槽序列里是否有可用槽(启用且填了 key)——与 openai-compat.listSlots 的启用口径一致。 */
170
- function hasEnabledSlot(slots) {
171
- return (Array.isArray(slots) ? slots : []).some(
172
- slot => slot && slot.enabled !== false && typeof slot.apiKey === 'string' && slot.apiKey !== ''
173
- )
174
- }
175
-
176
- /**
177
- * 读取提供商:内置渠道(src/providers/builtin.js)与用户磁盘态合并后返回。
178
- *
179
- * 内置渠道的静态字段(id/name/baseUrl/models 目录/extraHeaders/free)永远来自代码;
180
- * 磁盘上只存在用户态(enabled / slots / 用户勾选的 models)。消费方都读
181
- * `loadProviders().custom`,因此在入口合并即让所有调用方零改动看到内置渠道。
182
- */
183
- export function loadProviders() {
184
- const doc = readDoc('providers.json', DEFAULT_PROVIDERS)
185
- const disk = Array.isArray(doc.custom) ? doc.custom : []
186
- const merged = []
187
- for (const builtin of BUILTIN_PROVIDERS) {
188
- const user = disk.find(p => p && p.id === builtin.id) ?? null
189
- const slots = Array.isArray(user?.slots) ? user.slots : []
190
- const apiKey = typeof user?.apiKey === 'string'
191
- ? user.apiKey
192
- : (typeof slots[0]?.apiKey === 'string' ? slots[0].apiKey : '')
193
- merged.push({
194
- id: builtin.id,
195
- name: builtin.name,
196
- baseUrl: builtin.baseUrl,
197
- // 用户显式选过(哪怕选成空数组)就以用户为准;否则回落内置全量目录
198
- models: user && Array.isArray(user.models) ? user.models : structuredClone(builtin.models),
199
- extraHeaders: user?.extraHeaders && typeof user.extraHeaders === 'object'
200
- ? user.extraHeaders
201
- : structuredClone(builtin.extraHeaders),
202
- free: builtin.free === true,
203
- apiKey,
204
- slots,
205
- // 没配可用槽的内置渠道默认停用(目录不产出、不会裸跑失败);
206
- // 加了启用槽且用户没显式关掉,就自动可用。
207
- enabled: (hasEnabledSlot(slots) || apiKey !== '') && user?.enabled !== false,
208
- builtin: true,
209
- })
210
- }
211
- // 用户自建(非内置)整项透传,排在内置渠道之后
212
- for (const provider of disk) {
213
- if (!provider || typeof provider.id !== 'string' || BUILTIN_IDS.has(provider.id)) continue
214
- merged.push(provider)
215
- }
216
- return { custom: merged }
217
- }
218
-
219
- /**
220
- * 写回提供商:内置渠道只持久化用户态(enabled / slots / 勾选 models),
221
- * 静态字段永远由代码提供,避免磁盘副本与代码漂移;用户自建 provider 仍整项存盘。
222
- */
223
- export function saveProviders(providers) {
224
- const persisted = []
225
- for (const provider of Array.isArray(providers?.custom) ? providers.custom : []) {
226
- if (!provider || typeof provider.id !== 'string' || provider.id === '') continue
227
- if (!BUILTIN_IDS.has(provider.id)) {
228
- persisted.push(provider)
229
- continue
230
- }
231
- const builtin = BUILTIN_PROVIDERS.find(b => b.id === provider.id)
232
- const models = Array.isArray(provider.models) ? provider.models : builtin.models
233
- const slots = Array.isArray(provider.slots) ? provider.slots : []
234
- const entry = {
235
- id: provider.id,
236
- // 入参未给 enabled 时按「有可用槽即启用」推导(调用方通常已显式给出)
237
- enabled: provider.enabled === undefined
238
- ? hasEnabledSlot(slots) || (typeof provider.apiKey === 'string' && provider.apiKey !== '')
239
- : provider.enabled === true,
240
- slots,
241
- }
242
- // 与内置全量一致时不落 models(读取时自动回落),否则记住用户的删改/勾选结果
243
- if (JSON.stringify(models) !== JSON.stringify(builtin.models)) entry.models = models
244
- persisted.push(entry)
245
- }
246
- writeDoc('providers.json', { custom: persisted })
247
- }
248
-
249
- // ── groups(模型组)─────────────────────────────────────────────────────────
250
-
251
- const DEFAULT_GROUPS = { groups: [] }
252
-
253
- export function loadGroups() {
254
- return readDoc('groups.json', DEFAULT_GROUPS)
255
- }
256
-
257
- export function saveGroups(groups) {
258
- writeDoc('groups.json', groups)
259
- }
260
-
261
- // ── checkin(任务 + 运行状态)───────────────────────────────────────────────
262
-
263
- const DEFAULT_CHECKIN = { auto: { lastDate: '', lastAt: 0, lastResult: '', channels: [], dismissedRunAt: 0 } }
264
-
265
- export function loadCheckin() {
266
- return readDoc('checkin.json', DEFAULT_CHECKIN)
267
- }
268
-
269
- export function saveCheckin(checkin) {
270
- writeDoc('checkin.json', checkin)
271
- }
272
-
273
- // ── free-models(各渠道免费模型小时快照,用于「今日新增」对比)──────────────
274
-
275
- const DEFAULT_FREE_MODELS = { lastRunAt: 0, channels: {} }
276
-
277
- export function loadFreeModels() {
278
- return readDoc('free-models.json', DEFAULT_FREE_MODELS)
279
- }
280
-
281
- export function saveFreeModels(doc) {
282
- writeDoc('free-models.json', doc)
283
- }
284
-
285
- // ── balances(转发渠道可用积分:小时扫描与手动查询共用的一份本地结果)──────
286
-
287
- const DEFAULT_BALANCES = { at: 0, result: {} }
288
-
289
- /** 读最近一次可用积分结果:{ at, result: { [channelId]: [{ accountId, nickname, balance, error? }] } }。 */
290
- export function loadBalances() {
291
- const doc = readDoc('balances.json', DEFAULT_BALANCES)
292
- return {
293
- at: Number(doc.at) || 0,
294
- result: doc.result && typeof doc.result === 'object' && !Array.isArray(doc.result) ? doc.result : {},
295
- }
296
- }
297
-
298
- export function saveBalances({ at = 0, result = {} } = {}) {
299
- writeDoc('balances.json', {
300
- at: Number(at) || 0,
301
- result: result && typeof result === 'object' && !Array.isArray(result) ? result : {},
302
- })
303
- }
304
-
305
- // ── channels(白嫖账号渠道:凭据 + 勾选清单,明文本地存储)──────────────────
306
-
307
- const DEFAULT_CHANNELS = { channels: {} }
308
-
309
- export function loadChannels() {
310
- return readDoc('channels.json', DEFAULT_CHANNELS)
311
- }
312
-
313
- export function saveChannels(channels) {
314
- writeDoc('channels.json', channels)
315
- }
316
-
317
- /**
318
- * 倍率表清洗:`{ <modelId>: { rate, rateOriginal? } }`。
319
- * 只保留数字倍率条目(上游没给倍率的模型不落盘),供卡片 chips 与目录展示。
320
- */
321
- function normalizeModelRates(raw) {
322
- const out = {}
323
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out
324
- for (const [id, meta] of Object.entries(raw)) {
325
- if (id === '' || !meta || typeof meta !== 'object') continue
326
- const rate = meta.rate
327
- if (typeof rate !== 'number' || !Number.isFinite(rate)) continue
328
- out[id] = typeof meta.rateOriginal === 'number' && Number.isFinite(meta.rateOriginal)
329
- ? { rate, rateOriginal: meta.rateOriginal }
330
- : { rate }
331
- }
332
- return out
333
- }
334
-
335
- /**
336
- * 上下文表清洗:`{ <modelId>: <contextWindow> }`。
337
- * 只保留正整数上下文(上游没给的不落盘),供目录「上下文」列在上游实时清单
338
- * 不带 context 字段时回退展示。
339
- */
340
- function normalizeModelContexts(raw) {
341
- const out = {}
342
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out
343
- for (const [id, ctx] of Object.entries(raw)) {
344
- if (id === '' || typeof ctx !== 'number' || !Number.isFinite(ctx) || ctx <= 0) continue
345
- out[id] = Math.trunc(ctx)
346
- }
347
- return out
348
- }
349
-
350
- /** 取某渠道的配置段(不存在时返回空壳,不落盘)。 */
351
- export function channelState(id) {
352
- const doc = loadChannels()
353
- if (!doc.channels[id] || typeof doc.channels[id] !== 'object') {
354
- return { enabled: false, models: [], modelRates: {}, modelContexts: {}, accounts: [] }
355
- }
356
- const seg = doc.channels[id]
357
- return {
358
- enabled: seg.enabled === true,
359
- models: Array.isArray(seg.models) ? seg.models.filter(m => typeof m === 'string') : [],
360
- modelRates: normalizeModelRates(seg.modelRates),
361
- modelContexts: normalizeModelContexts(seg.modelContexts),
362
- accounts: Array.isArray(seg.accounts) ? seg.accounts : [],
363
- }
364
- }
365
-
366
- /** 写回某渠道的配置段(整体替换该渠道段,保持原子写)。 */
367
- export function saveChannelState(id, state) {
368
- const doc = loadChannels()
369
- doc.channels[id] = {
370
- enabled: state.enabled === true,
371
- models: Array.isArray(state.models) ? state.models : [],
372
- modelRates: normalizeModelRates(state.modelRates),
373
- modelContexts: normalizeModelContexts(state.modelContexts),
374
- accounts: Array.isArray(state.accounts) ? state.accounts : [],
375
- }
376
- saveChannels(doc)
377
- }
378
-
379
- // ── Freebuff 安装标识(跨启动稳定的 UUID v4,非凭据)──────────────────────
380
-
381
- /**
382
- * Freebuff 桌面端身份头 `x-freebuff-install-id` 的取值来源。
383
- * 上游明确标注该头 "Not a credential":只用于把同一安装的请求归为同一安装,
384
- * 跨启动必须稳定 ⇒ 落盘持久化(data/freebuff-install.json,明文,不属加密键名)。
385
- */
386
- const DEFAULT_FREEBUFF_INSTALL = { installId: '' }
387
-
388
- const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
389
-
390
- /** 取本机的 Freebuff 安装标识(不存在或非法则生成并落盘)。 */
391
- export function loadFreebuffInstallId() {
392
- const doc = readDoc('freebuff-install.json', DEFAULT_FREEBUFF_INSTALL)
393
- const id = typeof doc.installId === 'string' ? doc.installId : ''
394
- if (UUID_V4_RE.test(id)) return id
395
- const fresh = randomUUID()
396
- writeDoc('freebuff-install.json', { installId: fresh })
397
- return fresh
398
- }
399
-
400
- // ── 最近请求持久化(先声明常量,runtime 初始化时要用到)────────────────────
401
-
402
- const RECENT_MAX = 500
403
- const DEFAULT_RECENT = { requests: [] }
404
-
405
- export function loadRecentRequests() {
406
- const doc = readDoc('recent-requests.json', DEFAULT_RECENT)
407
- return Array.isArray(doc.requests) ? doc.requests : []
408
- }
409
-
410
- export function saveRecentRequests(requests) {
411
- writeDoc('recent-requests.json', { requests })
412
- }
413
-
414
- /** 运行时健康/统计。最近请求落盘到 data/recent-requests.json,重启后保留最近 500 条。 */
415
- export const runtime = {
416
- startedAt: Date.now(),
417
- stats: { requests: 0, success: 0, failed: 0, fallbacks: 0 },
418
- recentRequests: loadRecentRequests(),
419
- }
420
-
421
- // 防抖落盘:请求频繁时合并写入,避免每条请求都刷盘。
422
- let recentFlushTimer = null
423
- function scheduleRecentFlush() {
424
- if (recentFlushTimer) return
425
- recentFlushTimer = setTimeout(() => {
426
- recentFlushTimer = null
427
- saveRecentRequests(runtime.recentRequests)
428
- }, 500)
429
- recentFlushTimer.unref?.()
430
- }
431
-
432
- /** 取消排定的落盘并立即写入(服务关闭时调用,避免丢最后几条)。 */
433
- export function flushRecentRequestsNow() {
434
- if (recentFlushTimer) {
435
- clearTimeout(recentFlushTimer)
436
- recentFlushTimer = null
437
- }
438
- saveRecentRequests(runtime.recentRequests)
439
- }
440
-
441
- // ── 事件总线(管理面 SSE 实时推送用)────────────────────────────────────────
442
- const eventListeners = new Set()
443
-
444
- /** 订阅运行时事件;返回取消订阅函数。事件:request / probe / probe-meta。 */
445
- export function onRuntimeEvent(fn) {
446
- eventListeners.add(fn)
447
- return () => eventListeners.delete(fn)
448
- }
449
-
450
- export function emitRuntimeEvent(type, payload) {
451
- for (const fn of eventListeners) {
452
- try { fn(type, payload) } catch { /* 单个订阅者异常不影响其余 */ }
453
- }
454
- }
455
-
456
- /** 真实网关请求完成时记账(探测/测试请求不走这里),并向管理面推送事件。 */
457
- export function recordRequest(entry) {
458
- runtime.stats.requests += 1
459
- if (entry.outcome === 'success') runtime.stats.success += 1
460
- else runtime.stats.failed += 1
461
- if (entry.fallbackFrom) runtime.stats.fallbacks += 1
462
- const row = { ...entry, at: Date.now() }
463
- runtime.recentRequests.unshift(row)
464
- if (runtime.recentRequests.length > RECENT_MAX) runtime.recentRequests.length = RECENT_MAX
465
- scheduleRecentFlush()
466
- emitRuntimeEvent('request', { stats: runtime.stats, request: row })
467
- }
1
+ /**
2
+ * 配置存储:数据目录下的 JSON 文档,原子写入(tmp + rename),脏数据回落默认值。
3
+ *
4
+ * 数据目录默认落在用户 OS 应用目录(见 paths.js),仓库 data/ 只作历史迁移源;
5
+ * 需要指到别处用环境变量 OMR_DATA_DIR 覆盖。
6
+ *
7
+ * 文档划分(各用一个独立文档,避免互相抹字段):
8
+ * settings.json 网关与内置通道设置
9
+ * providers.json 自定义 OpenAI 兼容提供商
10
+ * groups.json 模型组
11
+ * checkin.json 签到任务与运行状态
12
+ */
13
+
14
+ import { randomUUID } from 'node:crypto'
15
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
16
+ import { join } from 'node:path'
17
+ import { generateApiKey } from './util.js'
18
+ import { sealDeep, openDeep } from './crypto.js'
19
+ import { DATA_DIR } from './paths.js'
20
+ import { BUILTIN_PROVIDERS, BUILTIN_IDS } from './providers/builtin.js'
21
+
22
+ export { DATA_DIR }
23
+
24
+ function docPath(name) {
25
+ return join(DATA_DIR, name)
26
+ }
27
+
28
+ function readDoc(name, fallback) {
29
+ const file = docPath(name)
30
+ if (!existsSync(file)) return structuredClone(fallback)
31
+ try {
32
+ const raw = JSON.parse(readFileSync(file, 'utf8'))
33
+ // 透明解密:凭据字段(apiKey/credential 等)在磁盘为密文,运行时为明文。
34
+ return openDeep({ ...structuredClone(fallback), ...raw })
35
+ } catch {
36
+ return structuredClone(fallback)
37
+ }
38
+ }
39
+
40
+ function writeDoc(name, value) {
41
+ mkdirSync(DATA_DIR, { recursive: true })
42
+ const file = docPath(name)
43
+ const tmp = `${file}.tmp`
44
+ // 透明加密:落盘前密封凭据字段,明文不落盘。
45
+ writeFileSync(tmp, JSON.stringify(sealDeep(value), null, 2), 'utf8')
46
+ renameSync(tmp, file)
47
+ }
48
+
49
+ // ── settings ────────────────────────────────────────────────────────────────
50
+
51
+ const DEFAULT_SETTINGS = {
52
+ gateway: {
53
+ enabled: true,
54
+ host: '127.0.0.1',
55
+ port: 18682,
56
+ apiKey: '',
57
+ /** 上游单轮超时(毫秒)。 */
58
+ turnTimeoutMs: 300000,
59
+ /** 上游首字节超时(毫秒)。 */
60
+ headerTimeoutMs: 60000,
61
+ /** 流空闲超时(毫秒),每 chunk 重置。 */
62
+ idleTimeoutMs: 120000,
63
+ /** 组内单候选首字预算(毫秒):超过则放弃该候选换下一个(多候选组生效)。 */
64
+ candidateTimeoutMs: 45000,
65
+ /** 对冲间隔(毫秒):当前候选迟迟不出字时提前并行启动下一个;0 = 关闭对冲。 */
66
+ hedgeDelayMs: 6000,
67
+ /** 对冲最大并发候选数。 */
68
+ hedgeMaxParallel: 2,
69
+ },
70
+ kilo: {
71
+ enabled: true,
72
+ baseUrl: 'https://api.kilo.ai/api/gateway',
73
+ userAgent: 'OneModelRouter/1.0',
74
+ },
75
+ opencode: {
76
+ enabled: true,
77
+ /** 只填 Origin(路径由车道按模型分流);历史值 `…/zen/v1` 会被自动归一。 */
78
+ baseUrl: 'https://opencode.ai',
79
+ /** 留空 = 用车道常量 CLIENT_UA(v2 形状);填非 v2 形态也会被归一回落。 */
80
+ userAgent: '',
81
+ /** 身份槽:apiKey === 'public' 为匿名槽(只能用免费模型),其余为账号槽。 */
82
+ slots: [
83
+ { id: 'opencode-anon-default', label: '匿名通道', apiKey: 'public', enabled: true, proxy: '' },
84
+ ],
85
+ },
86
+ checkin: {
87
+ /** 渠道原生自动签到开关;只有显式 false 才算关闭(默认打开)。 */
88
+ enabled: true,
89
+ /** 启动后延迟执行(毫秒),等渠道凭据续期先稳住;0 = 立刻。 */
90
+ delayMs: 15000,
91
+ },
92
+ probe: {
93
+ /** 后台周期探测模型可用性。默认关闭。 */
94
+ enabled: false,
95
+ /** 探测间隔(分钟),最小 1。 */
96
+ intervalMinutes: 15,
97
+ /** 上次探测完成时间(毫秒时间戳),0 = 从未探测。重启后按此与间隔对比决定是否自动探测。 */
98
+ lastProbeAt: 0,
99
+ },
100
+ freeModels: {
101
+ /**
102
+ * 小时扫描时把各渠道的「勾选清单」整体替换为本次拉取到的可用清单:
103
+ * - 免费渠道(自定义提供商):完整可用清单;
104
+ * - 转发渠道:完整可用清单,并同步刷新倍率表(channels.json 的 modelRates);
105
+ * - 免密渠道(kilo / opencode):免费可用清单。
106
+ * 默认开启;关掉后回到「只自动勾选免费模型、用户勾选的付费模型不动」的老行为
107
+ * (免密渠道仍只保留免费清单)。
108
+ * 渠道自身显式声明了 meta.syncSelection 的以声明为准(如 Cline 只保留免费池)。
109
+ */
110
+ autoSelectAvailable: true,
111
+ },
112
+ sync: {
113
+ /** 多端同步。默认关闭;transport = remote(DSH Remote 零知识中继)| cloud(旧云 DB 回退,B4 删除)。 */
114
+ enabled: false,
115
+ /** 默认走新链路;cloud 仅在管理页显式选择时启用(B1–B3 回退,B4 删除)。 */
116
+ transport: 'remote',
117
+ // ── cloud(B1–B3 回退保留,B4 删除)──
118
+ /** 云服务数据面 endpoint(publicConfig.endpoint)。 */
119
+ endpoint: '',
120
+ /** 云服务 publishableKey(publicConfig,公开值)。 */
121
+ publishableKey: '',
122
+ /** 设备专用 WorkBuddy 账号邮箱。 */
123
+ email: '',
124
+ /** 设备账号密码(键名 password —— 加密层按此密封落盘)。 */
125
+ password: '',
126
+ /** 云设备 ID(公开标识,omr-xxxx;与 remote 的 UUID 身份互不影响)。 */
127
+ deviceId: '',
128
+ /** 设备密钥(omr_relay RPC 级凭据,键名 apiKey —— 加密层按此密封落盘)。 */
129
+ apiKey: '',
130
+ // ── remote(DSH Remote Protocol v1)──
131
+ /** 控制面 HTTP 根地址;relayUrl 为 WSS 连接地址。 */
132
+ apiOrigin: 'https://dsh.r2049.cn',
133
+ relayUrl: 'wss://dsh.r2049.cn/ws/v1/connect',
134
+ /** 首次注册 Host 用的站点账号令牌:注册成功立即清空,绝不长期落盘、绝不下发手机。 */
135
+ siteToken: '',
136
+ /** Host 设备 ID(UUID,协议强制)。 */
137
+ remoteDeviceId: '',
138
+ /** Host X25519 静态公钥(公开,指纹供扫码核对)。 */
139
+ identityPublicKey: '',
140
+ /** Host X25519 静态私钥(键名命中 SENSITIVE_KEYS,密封落盘)。 */
141
+ identityPrivateKey: '',
142
+ /** Host 设备凭据(密封落盘;靠 /api/v1/auth/refresh 无限续期)。 */
143
+ accessToken: '',
144
+ refreshToken: '',
145
+ accessTokenExpiresAt: 0,
146
+ refreshTokenExpiresAt: 0,
147
+ /** 已配对 Client 设备记录(含公钥与撤销用凭据,密封落盘;上限 16 台)。 */
148
+ boundClients: [],
149
+ },
150
+ }
151
+
152
+ export function loadSettings() {
153
+ const settings = readDoc('settings.json', DEFAULT_SETTINGS)
154
+ if (typeof settings.gateway.apiKey !== 'string' || settings.gateway.apiKey === '') {
155
+ settings.gateway.apiKey = generateApiKey()
156
+ writeDoc('settings.json', settings)
157
+ }
158
+ return settings
159
+ }
160
+
161
+ export function saveSettings(settings) {
162
+ writeDoc('settings.json', settings)
163
+ }
164
+
165
+ // ── providers(内置免费渠道 + 用户自建 OpenAI 兼容)────────────────────────
166
+
167
+ const DEFAULT_PROVIDERS = { custom: [] }
168
+
169
+ /** 槽序列里是否有可用槽(启用且填了 key)——与 openai-compat.listSlots 的启用口径一致。 */
170
+ function hasEnabledSlot(slots) {
171
+ return (Array.isArray(slots) ? slots : []).some(
172
+ slot => slot && slot.enabled !== false && typeof slot.apiKey === 'string' && slot.apiKey !== ''
173
+ )
174
+ }
175
+
176
+ /**
177
+ * 读取提供商:内置渠道(src/providers/builtin.js)与用户磁盘态合并后返回。
178
+ *
179
+ * 内置渠道的静态字段(id/name/baseUrl/models 目录/extraHeaders/free)永远来自代码;
180
+ * 磁盘上只存在用户态(enabled / slots / 用户勾选的 models)。消费方都读
181
+ * `loadProviders().custom`,因此在入口合并即让所有调用方零改动看到内置渠道。
182
+ */
183
+ export function loadProviders() {
184
+ const doc = readDoc('providers.json', DEFAULT_PROVIDERS)
185
+ const disk = Array.isArray(doc.custom) ? doc.custom : []
186
+ const merged = []
187
+ for (const builtin of BUILTIN_PROVIDERS) {
188
+ const user = disk.find(p => p && p.id === builtin.id) ?? null
189
+ const slots = Array.isArray(user?.slots) ? user.slots : []
190
+ const apiKey = typeof user?.apiKey === 'string'
191
+ ? user.apiKey
192
+ : (typeof slots[0]?.apiKey === 'string' ? slots[0].apiKey : '')
193
+ merged.push({
194
+ id: builtin.id,
195
+ name: builtin.name,
196
+ baseUrl: builtin.baseUrl,
197
+ // 用户显式选过(哪怕选成空数组)就以用户为准;否则回落内置全量目录
198
+ models: user && Array.isArray(user.models) ? user.models : structuredClone(builtin.models),
199
+ extraHeaders: user?.extraHeaders && typeof user.extraHeaders === 'object'
200
+ ? user.extraHeaders
201
+ : structuredClone(builtin.extraHeaders),
202
+ free: builtin.free === true,
203
+ apiKey,
204
+ slots,
205
+ // 没配可用槽的内置渠道默认停用(目录不产出、不会裸跑失败);
206
+ // 加了启用槽且用户没显式关掉,就自动可用。
207
+ enabled: (hasEnabledSlot(slots) || apiKey !== '') && user?.enabled !== false,
208
+ builtin: true,
209
+ })
210
+ }
211
+ // 用户自建(非内置)整项透传,排在内置渠道之后
212
+ for (const provider of disk) {
213
+ if (!provider || typeof provider.id !== 'string' || BUILTIN_IDS.has(provider.id)) continue
214
+ merged.push(provider)
215
+ }
216
+ return { custom: merged }
217
+ }
218
+
219
+ /**
220
+ * 写回提供商:内置渠道只持久化用户态(enabled / slots / 勾选 models),
221
+ * 静态字段永远由代码提供,避免磁盘副本与代码漂移;用户自建 provider 仍整项存盘。
222
+ */
223
+ export function saveProviders(providers) {
224
+ const persisted = []
225
+ for (const provider of Array.isArray(providers?.custom) ? providers.custom : []) {
226
+ if (!provider || typeof provider.id !== 'string' || provider.id === '') continue
227
+ if (!BUILTIN_IDS.has(provider.id)) {
228
+ persisted.push(provider)
229
+ continue
230
+ }
231
+ const builtin = BUILTIN_PROVIDERS.find(b => b.id === provider.id)
232
+ const models = Array.isArray(provider.models) ? provider.models : builtin.models
233
+ const slots = Array.isArray(provider.slots) ? provider.slots : []
234
+ const entry = {
235
+ id: provider.id,
236
+ // 入参未给 enabled 时按「有可用槽即启用」推导(调用方通常已显式给出)
237
+ enabled: provider.enabled === undefined
238
+ ? hasEnabledSlot(slots) || (typeof provider.apiKey === 'string' && provider.apiKey !== '')
239
+ : provider.enabled === true,
240
+ slots,
241
+ }
242
+ // 与内置全量一致时不落 models(读取时自动回落),否则记住用户的删改/勾选结果
243
+ if (JSON.stringify(models) !== JSON.stringify(builtin.models)) entry.models = models
244
+ persisted.push(entry)
245
+ }
246
+ writeDoc('providers.json', { custom: persisted })
247
+ }
248
+
249
+ // ── groups(模型组)─────────────────────────────────────────────────────────
250
+
251
+ const DEFAULT_GROUPS = { groups: [] }
252
+
253
+ export function loadGroups() {
254
+ return readDoc('groups.json', DEFAULT_GROUPS)
255
+ }
256
+
257
+ export function saveGroups(groups) {
258
+ writeDoc('groups.json', groups)
259
+ }
260
+
261
+ // ── checkin(任务 + 运行状态)───────────────────────────────────────────────
262
+
263
+ const DEFAULT_CHECKIN = { auto: { lastDate: '', lastAt: 0, lastResult: '', channels: [], dismissedRunAt: 0 } }
264
+
265
+ export function loadCheckin() {
266
+ return readDoc('checkin.json', DEFAULT_CHECKIN)
267
+ }
268
+
269
+ export function saveCheckin(checkin) {
270
+ writeDoc('checkin.json', checkin)
271
+ }
272
+
273
+ // ── free-models(各渠道免费模型小时快照,用于「今日新增」对比)──────────────
274
+
275
+ const DEFAULT_FREE_MODELS = { lastRunAt: 0, channels: {} }
276
+
277
+ export function loadFreeModels() {
278
+ return readDoc('free-models.json', DEFAULT_FREE_MODELS)
279
+ }
280
+
281
+ export function saveFreeModels(doc) {
282
+ writeDoc('free-models.json', doc)
283
+ }
284
+
285
+ // ── balances(转发渠道可用积分:小时扫描与手动查询共用的一份本地结果)──────
286
+
287
+ const DEFAULT_BALANCES = { at: 0, result: {} }
288
+
289
+ /** 读最近一次可用积分结果:{ at, result: { [channelId]: [{ accountId, nickname, balance, error? }] } }。 */
290
+ export function loadBalances() {
291
+ const doc = readDoc('balances.json', DEFAULT_BALANCES)
292
+ return {
293
+ at: Number(doc.at) || 0,
294
+ result: doc.result && typeof doc.result === 'object' && !Array.isArray(doc.result) ? doc.result : {},
295
+ }
296
+ }
297
+
298
+ export function saveBalances({ at = 0, result = {} } = {}) {
299
+ writeDoc('balances.json', {
300
+ at: Number(at) || 0,
301
+ result: result && typeof result === 'object' && !Array.isArray(result) ? result : {},
302
+ })
303
+ }
304
+
305
+ // ── channels(白嫖账号渠道:凭据 + 勾选清单,明文本地存储)──────────────────
306
+
307
+ const DEFAULT_CHANNELS = { channels: {} }
308
+
309
+ export function loadChannels() {
310
+ return readDoc('channels.json', DEFAULT_CHANNELS)
311
+ }
312
+
313
+ export function saveChannels(channels) {
314
+ writeDoc('channels.json', channels)
315
+ }
316
+
317
+ /**
318
+ * 倍率表清洗:`{ <modelId>: { rate, rateOriginal? } }`。
319
+ * 只保留数字倍率条目(上游没给倍率的模型不落盘),供卡片 chips 与目录展示。
320
+ */
321
+ function normalizeModelRates(raw) {
322
+ const out = {}
323
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out
324
+ for (const [id, meta] of Object.entries(raw)) {
325
+ if (id === '' || !meta || typeof meta !== 'object') continue
326
+ const rate = meta.rate
327
+ if (typeof rate !== 'number' || !Number.isFinite(rate)) continue
328
+ out[id] = typeof meta.rateOriginal === 'number' && Number.isFinite(meta.rateOriginal)
329
+ ? { rate, rateOriginal: meta.rateOriginal }
330
+ : { rate }
331
+ }
332
+ return out
333
+ }
334
+
335
+ /**
336
+ * 上下文表清洗:`{ <modelId>: <contextWindow> }`。
337
+ * 只保留正整数上下文(上游没给的不落盘),供目录「上下文」列在上游实时清单
338
+ * 不带 context 字段时回退展示。
339
+ */
340
+ function normalizeModelContexts(raw) {
341
+ const out = {}
342
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out
343
+ for (const [id, ctx] of Object.entries(raw)) {
344
+ if (id === '' || typeof ctx !== 'number' || !Number.isFinite(ctx) || ctx <= 0) continue
345
+ out[id] = Math.trunc(ctx)
346
+ }
347
+ return out
348
+ }
349
+
350
+ /** 取某渠道的配置段(不存在时返回空壳,不落盘)。 */
351
+ export function channelState(id) {
352
+ const doc = loadChannels()
353
+ if (!doc.channels[id] || typeof doc.channels[id] !== 'object') {
354
+ return { enabled: false, models: [], modelRates: {}, modelContexts: {}, accounts: [] }
355
+ }
356
+ const seg = doc.channels[id]
357
+ return {
358
+ enabled: seg.enabled === true,
359
+ models: Array.isArray(seg.models) ? seg.models.filter(m => typeof m === 'string') : [],
360
+ modelRates: normalizeModelRates(seg.modelRates),
361
+ modelContexts: normalizeModelContexts(seg.modelContexts),
362
+ accounts: Array.isArray(seg.accounts) ? seg.accounts : [],
363
+ }
364
+ }
365
+
366
+ /** 写回某渠道的配置段(整体替换该渠道段,保持原子写)。 */
367
+ export function saveChannelState(id, state) {
368
+ const doc = loadChannels()
369
+ doc.channels[id] = {
370
+ enabled: state.enabled === true,
371
+ models: Array.isArray(state.models) ? state.models : [],
372
+ modelRates: normalizeModelRates(state.modelRates),
373
+ modelContexts: normalizeModelContexts(state.modelContexts),
374
+ accounts: Array.isArray(state.accounts) ? state.accounts : [],
375
+ }
376
+ saveChannels(doc)
377
+ }
378
+
379
+ // ── Freebuff 安装标识(跨启动稳定的 UUID v4,非凭据)──────────────────────
380
+
381
+ /**
382
+ * Freebuff 桌面端身份头 `x-freebuff-install-id` 的取值来源。
383
+ * 上游明确标注该头 "Not a credential":只用于把同一安装的请求归为同一安装,
384
+ * 跨启动必须稳定 ⇒ 落盘持久化(data/freebuff-install.json,明文,不属加密键名)。
385
+ */
386
+ const DEFAULT_FREEBUFF_INSTALL = { installId: '' }
387
+
388
+ const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
389
+
390
+ /** 取本机的 Freebuff 安装标识(不存在或非法则生成并落盘)。 */
391
+ export function loadFreebuffInstallId() {
392
+ const doc = readDoc('freebuff-install.json', DEFAULT_FREEBUFF_INSTALL)
393
+ const id = typeof doc.installId === 'string' ? doc.installId : ''
394
+ if (UUID_V4_RE.test(id)) return id
395
+ const fresh = randomUUID()
396
+ writeDoc('freebuff-install.json', { installId: fresh })
397
+ return fresh
398
+ }
399
+
400
+ // ── 最近请求持久化(先声明常量,runtime 初始化时要用到)────────────────────
401
+
402
+ const RECENT_MAX = 500
403
+ const DEFAULT_RECENT = { requests: [] }
404
+
405
+ export function loadRecentRequests() {
406
+ const doc = readDoc('recent-requests.json', DEFAULT_RECENT)
407
+ return Array.isArray(doc.requests) ? doc.requests : []
408
+ }
409
+
410
+ export function saveRecentRequests(requests) {
411
+ writeDoc('recent-requests.json', { requests })
412
+ }
413
+
414
+ /** 运行时健康/统计。最近请求落盘到 data/recent-requests.json,重启后保留最近 500 条。 */
415
+ export const runtime = {
416
+ startedAt: Date.now(),
417
+ stats: { requests: 0, success: 0, failed: 0, fallbacks: 0 },
418
+ recentRequests: loadRecentRequests(),
419
+ }
420
+
421
+ // 防抖落盘:请求频繁时合并写入,避免每条请求都刷盘。
422
+ let recentFlushTimer = null
423
+ function scheduleRecentFlush() {
424
+ if (recentFlushTimer) return
425
+ recentFlushTimer = setTimeout(() => {
426
+ recentFlushTimer = null
427
+ saveRecentRequests(runtime.recentRequests)
428
+ }, 500)
429
+ recentFlushTimer.unref?.()
430
+ }
431
+
432
+ /** 取消排定的落盘并立即写入(服务关闭时调用,避免丢最后几条)。 */
433
+ export function flushRecentRequestsNow() {
434
+ if (recentFlushTimer) {
435
+ clearTimeout(recentFlushTimer)
436
+ recentFlushTimer = null
437
+ }
438
+ saveRecentRequests(runtime.recentRequests)
439
+ }
440
+
441
+ // ── 事件总线(管理面 SSE 实时推送用)────────────────────────────────────────
442
+ const eventListeners = new Set()
443
+
444
+ /** 订阅运行时事件;返回取消订阅函数。事件:request / probe / probe-meta。 */
445
+ export function onRuntimeEvent(fn) {
446
+ eventListeners.add(fn)
447
+ return () => eventListeners.delete(fn)
448
+ }
449
+
450
+ export function emitRuntimeEvent(type, payload) {
451
+ for (const fn of eventListeners) {
452
+ try { fn(type, payload) } catch { /* 单个订阅者异常不影响其余 */ }
453
+ }
454
+ }
455
+
456
+ /** 真实网关请求完成时记账(探测/测试请求不走这里),并向管理面推送事件。 */
457
+ export function recordRequest(entry) {
458
+ runtime.stats.requests += 1
459
+ if (entry.outcome === 'success') runtime.stats.success += 1
460
+ else runtime.stats.failed += 1
461
+ if (entry.fallbackFrom) runtime.stats.fallbacks += 1
462
+ const row = { ...entry, at: Date.now() }
463
+ runtime.recentRequests.unshift(row)
464
+ if (runtime.recentRequests.length > RECENT_MAX) runtime.recentRequests.length = RECENT_MAX
465
+ scheduleRecentFlush()
466
+ emitRuntimeEvent('request', { stats: runtime.stats, request: row })
467
+ }