engine7 7.1.147 → 7.1.149

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.
@@ -1,5 +1,3128 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/auth/protocol.ts
12
+ function brokerBase(value) {
13
+ const url = new URL(value);
14
+ if (url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))) throw new AuthError("invalid_broker_url");
15
+ if (!url.pathname.endsWith("/")) url.pathname += "/";
16
+ return url;
17
+ }
18
+ var AuthError;
19
+ var init_protocol = __esm({
20
+ "src/auth/protocol.ts"() {
21
+ "use strict";
22
+ AuthError = class extends Error {
23
+ constructor(code) {
24
+ super(code);
25
+ this.code = code;
26
+ this.name = "AuthError";
27
+ }
28
+ };
29
+ }
30
+ });
31
+
32
+ // src/auth/capabilities.ts
33
+ var init_capabilities = __esm({
34
+ "src/auth/capabilities.ts"() {
35
+ "use strict";
36
+ init_protocol();
37
+ }
38
+ });
39
+
40
+ // src/auth/client.ts
41
+ var DEFAULT_AUTH_BROKER, LEGACY_AUTH_BROKERS, OFFICIAL_AUTH_BROKERS;
42
+ var init_client = __esm({
43
+ "src/auth/client.ts"() {
44
+ "use strict";
45
+ init_capabilities();
46
+ init_protocol();
47
+ DEFAULT_AUTH_BROKER = "https://auth.engine7.ai/auth/";
48
+ LEGACY_AUTH_BROKERS = ["https://www.twinsun.top/auth/"];
49
+ OFFICIAL_AUTH_BROKERS = /* @__PURE__ */ new Set([DEFAULT_AUTH_BROKER, ...LEGACY_AUTH_BROKERS]);
50
+ }
51
+ });
52
+
53
+ // src/auth/config.ts
54
+ function authConfig(raw) {
55
+ const value = raw;
56
+ const brokerUrl = brokerBase(value?.brokerUrl === void 0 ? DEFAULT_AUTH_BROKER : String(value.brokerUrl)).toString();
57
+ const rawProxy = typeof value?.gmailProxy === "string" ? value.gmailProxy.trim() : "";
58
+ return rawProxy ? { brokerUrl, gmailProxy: rawProxy } : { brokerUrl };
59
+ }
60
+ var init_config = __esm({
61
+ "src/auth/config.ts"() {
62
+ "use strict";
63
+ init_protocol();
64
+ init_client();
65
+ }
66
+ });
67
+
68
+ // src/config/display.ts
69
+ function loadDisplayConfig(raw) {
70
+ if (!raw) return { ...DEFAULT_DISPLAY };
71
+ return {
72
+ toolOutputMode: raw.toolOutputMode === "collapsed" ? "collapsed" : "expanded",
73
+ thinking: {
74
+ ...DEFAULT_DISPLAY.thinking,
75
+ ...raw.thinking || {}
76
+ },
77
+ toolUse: {
78
+ ...DEFAULT_DISPLAY.toolUse,
79
+ ...raw.toolUse || {}
80
+ },
81
+ toolResult: {
82
+ ...DEFAULT_DISPLAY.toolResult,
83
+ ...raw.toolResult || {}
84
+ },
85
+ reactions: {
86
+ ...DEFAULT_DISPLAY.reactions,
87
+ ...raw.reactions || {}
88
+ },
89
+ preview: {
90
+ ...DEFAULT_DISPLAY.preview,
91
+ ...raw.preview || {}
92
+ },
93
+ bubbleSplit: {
94
+ ...DEFAULT_DISPLAY.bubbleSplit,
95
+ ...raw.bubbleSplit || {}
96
+ },
97
+ typing: {
98
+ ...DEFAULT_DISPLAY.typing,
99
+ ...raw.typing || {}
100
+ }
101
+ };
102
+ }
103
+ var DEFAULT_DISPLAY;
104
+ var init_display = __esm({
105
+ "src/config/display.ts"() {
106
+ "use strict";
107
+ DEFAULT_DISPLAY = {
108
+ toolOutputMode: "expanded",
109
+ thinking: { enabled: true, emoji: "\u{1F4AD}", maxLen: 300 },
110
+ // 0930 翀哥:displayMode 默认 raw→summary——raw 把原始参数 JSON 全糊进聊天,太占地方。
111
+ toolUse: { enabled: true, emoji: "\u{1F527}", displayMode: "summary", bashDisplayMode: "description", displayLimits: { write: 200 } },
112
+ toolResult: { enabled: true, emoji: "\u{1F4E4}" },
113
+ reactions: { enabled: true, start: "\u{1F440}", done: "\u2705", error: "\u274C" },
114
+ preview: { agentName: "Agent" },
115
+ bubbleSplit: { emotion: true, work: false },
116
+ typing: { enabled: true }
117
+ };
118
+ }
119
+ });
120
+
121
+ // src/config/writer.ts
122
+ import fs from "node:fs";
123
+ import path from "node:path";
124
+ function isNormalized(text) {
125
+ if (text === "") return true;
126
+ if (text.includes("\r")) return false;
127
+ let minIndent = Infinity;
128
+ for (const line of text.split("\n")) {
129
+ const m = /^( +)\S/.exec(line);
130
+ if (!m) continue;
131
+ const width = m[1].length;
132
+ if (width % 2 !== 0) return false;
133
+ if (width < minIndent) minIndent = width;
134
+ }
135
+ return minIndent === 2 || minIndent === Infinity;
136
+ }
137
+ function rotateBaks(filePath) {
138
+ const dir = path.dirname(filePath);
139
+ const base = path.basename(filePath);
140
+ const baks = fs.readdirSync(dir).filter((n) => n.startsWith(base + ".bak-")).sort();
141
+ while (baks.length >= KEEP_BAKS) {
142
+ const victim = baks.shift();
143
+ try {
144
+ fs.unlinkSync(path.join(dir, victim));
145
+ } catch {
146
+ }
147
+ }
148
+ }
149
+ function sleepSync(ms) {
150
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
151
+ }
152
+ function errCode(err) {
153
+ return err?.code ?? "";
154
+ }
155
+ function writeFailure(filePath, primary, extra) {
156
+ const code = errCode(primary);
157
+ const reason = RETRYABLE_CODES.has(code) ? `\u76EE\u6807\u6587\u4EF6\u88AB\u5360\u7528\u6216\u4E0D\u53EF\u5199\uFF08${code}\uFF09\u2014\u2014\u8BF7\u5173\u95ED\u6B63\u5728\u4F7F\u7528\u5B83\u7684\u7A0B\u5E8F\uFF08\u7F16\u8F91\u5668\u3001\u6740\u6BD2\u3001\u540C\u6B65\u76D8\u7B49\uFF09\u540E\u91CD\u8BD5` : `\u5199\u5165\u5931\u8D25${code ? `\uFF08${code}\uFF09` : ""}\uFF1A${primary?.message ?? String(primary)}`;
158
+ return new ConfigWriteError(`\u65E0\u6CD5\u5199\u5165 ${filePath}\uFF1A${reason}${extra ? `\uFF1B${extra}` : ""}`, code, primary);
159
+ }
160
+ function renameWithRetry(from, to) {
161
+ for (let attempt = 1; ; attempt++) {
162
+ try {
163
+ fs.renameSync(from, to);
164
+ return;
165
+ } catch (err) {
166
+ if (attempt >= RENAME_ATTEMPTS || !RETRYABLE_CODES.has(errCode(err))) throw err;
167
+ sleepSync(RENAME_RETRY_MS);
168
+ }
169
+ }
170
+ }
171
+ function commitFile(tmp, filePath) {
172
+ try {
173
+ renameWithRetry(tmp, filePath);
174
+ return;
175
+ } catch (primaryErr) {
176
+ const old = `${filePath}.old`;
177
+ try {
178
+ fs.renameSync(filePath, old);
179
+ } catch (err) {
180
+ throw writeFailure(filePath, primaryErr, `\u6539\u540D .old \u5907\u4EFD\u4E5F\u5931\u8D25\uFF08${errCode(err) || "\u672A\u77E5"}\uFF09`);
181
+ }
182
+ try {
183
+ fs.renameSync(tmp, filePath);
184
+ } catch (err) {
185
+ try {
186
+ fs.renameSync(old, filePath);
187
+ } catch {
188
+ throw writeFailure(filePath, primaryErr, `\u65B0\u5185\u5BB9\u843D\u76D8\u4E0E\u56DE\u6EDA\u90FD\u5931\u8D25\uFF0C\u65E7\u5185\u5BB9\u7559\u5728 ${old}`);
189
+ }
190
+ throw writeFailure(filePath, primaryErr, `\u6362\u540D\u843D\u76D8\u5931\u8D25\uFF08${errCode(err) || "\u672A\u77E5"}\uFF09`);
191
+ }
192
+ try {
193
+ fs.unlinkSync(old);
194
+ } catch {
195
+ }
196
+ }
197
+ }
198
+ function writeConfigAtomic(filePath, obj) {
199
+ const existed = fs.existsSync(filePath);
200
+ let prevText = "";
201
+ let fileMode;
202
+ if (existed) {
203
+ try {
204
+ prevText = fs.readFileSync(filePath, "utf-8");
205
+ fileMode = fs.statSync(filePath).mode & 511;
206
+ } catch (err) {
207
+ throw writeFailure(filePath, err);
208
+ }
209
+ }
210
+ const normalized = !existed || !isNormalized(prevText);
211
+ if (prevText) {
212
+ try {
213
+ fs.copyFileSync(filePath, `${filePath}.bak-${Date.now()}`);
214
+ } catch {
215
+ }
216
+ rotateBaks(filePath);
217
+ }
218
+ const content = JSON.stringify(obj, null, 2) + "\n";
219
+ const tmp = path.join(path.dirname(filePath), `.${path.basename(filePath)}.tmp-${process.pid}`);
220
+ try {
221
+ const fd = fs.openSync(tmp, "w", fileMode);
222
+ try {
223
+ if (fileMode !== void 0) fs.fchmodSync(fd, fileMode);
224
+ fs.writeFileSync(fd, content, "utf-8");
225
+ fs.fsyncSync(fd);
226
+ } finally {
227
+ fs.closeSync(fd);
228
+ }
229
+ commitFile(tmp, filePath);
230
+ } catch (err) {
231
+ throw err instanceof ConfigWriteError ? err : writeFailure(filePath, err);
232
+ } finally {
233
+ try {
234
+ fs.unlinkSync(tmp);
235
+ } catch {
236
+ }
237
+ }
238
+ return { normalized };
239
+ }
240
+ var KEEP_BAKS, RENAME_ATTEMPTS, RENAME_RETRY_MS, RETRYABLE_CODES, ConfigWriteError;
241
+ var init_writer = __esm({
242
+ "src/config/writer.ts"() {
243
+ "use strict";
244
+ KEEP_BAKS = 3;
245
+ RENAME_ATTEMPTS = 5;
246
+ RENAME_RETRY_MS = 50;
247
+ RETRYABLE_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES"]);
248
+ ConfigWriteError = class extends Error {
249
+ code;
250
+ constructor(message, code, cause) {
251
+ super(message, { cause });
252
+ this.name = "ConfigWriteError";
253
+ this.code = code;
254
+ }
255
+ };
256
+ }
257
+ });
258
+
259
+ // src/config/live.ts
260
+ function markSelfWrite() {
261
+ selfWrite.pending = true;
262
+ }
263
+ var LiveConfigClass, liveConfig, selfWrite;
264
+ var init_live = __esm({
265
+ "src/config/live.ts"() {
266
+ "use strict";
267
+ init_writer();
268
+ LiveConfigClass = class {
269
+ current = null;
270
+ /** 启动时注入(替代 registry.config = config) */
271
+ init(config) {
272
+ this.current = config;
273
+ }
274
+ /** 取整个 config 对象(只读引用,不要缓存) */
275
+ all() {
276
+ if (!this.current) {
277
+ throw new Error("[liveConfig] not initialized \u2014 call liveConfig.init() first");
278
+ }
279
+ return this.current;
280
+ }
281
+ /** 安全取子段('services.voice-chat.start' → current.services.voice-chat.start) */
282
+ get(dotPath) {
283
+ if (!this.current) return void 0;
284
+ return dotPath.split(".").reduce((acc, key) => {
285
+ if (acc == null) return void 0;
286
+ if (key === "__proto__" || key === "constructor" || key === "prototype") return void 0;
287
+ return acc[key];
288
+ }, this.current);
289
+ }
290
+ /** reload 时原地更新(Object.assign 保持引用不变)
291
+ * ⚠️ 0908 立法(浅层 assign 陷阱,见 docs/hot-reload-architecture.md):
292
+ * 这是**浅层** assign——顶层 key 被整体换新引用,构造期捕获嵌套子对象
293
+ * (如 config.cron、deps.everosCfg、adapter 的 config 段)的模块 reload 后
294
+ * 拿着的是旧对象。两条出路:(a) 使用时 liveConfig.get() 现读;(b) 注册为
295
+ * reloadOrchestrator entry,key 变化驱动 stop→start 重建。禁止新增"构造期
296
+ * 固化嵌套 config 引用"的代码。(不做 deep-merge:会破坏"删 key"语义。) */
297
+ assign(newConfig) {
298
+ if (!this.current) {
299
+ this.current = newConfig;
300
+ return;
301
+ }
302
+ Object.assign(this.current, newConfig);
303
+ }
304
+ /** 改活树上的值;文件承载路径同步持久化(read-modify-write 回 config 文件) */
305
+ /**
306
+ * 改活树 + 落盘。
307
+ *
308
+ * 返回值 = **落盘**是否成功(活树无论成败都已同步——它是先改的)。绝大多数调用点照旧
309
+ * `void liveConfig.set(...)` 不理它;但**要打成功日志的调用点必须 await 这个布尔值**。
310
+ *
311
+ * 为什么把这个信号交出去(1001 审查捞回):本方法本来是 fire-and-forget,落盘失败只在
312
+ * `persistToFile` 里 warn 一行;而启动早段的调用点(两个免费档 fixup)紧接着打了句
313
+ * "免费档补齐 xxx" 的成功日志 ⇒ 配置**没写进文件**却被读成"写好了":进程内生效、托盘
314
+ * 读文件还是旧值、下次启动重放同一句——正是本仓最恨的假信号。
315
+ */
316
+ async set(dotPath, val, options) {
317
+ if (!this.current) throw new Error("[liveConfig] not initialized \u2014 call liveConfig.init() first");
318
+ const keys = dotPath.split(".");
319
+ const dangerous = keys.find((k) => k === "__proto__" || k === "constructor" || k === "prototype");
320
+ if (dangerous) throw new Error(`[liveConfig] set: \u8DEF\u5F84\u6BB5\u300C${dangerous}\u300D\u662F\u4FDD\u7559\u540D\uFF0C\u62D2\u7EDD\u5199\u5165\uFF08${dotPath}\uFF09`);
321
+ let obj = this.current;
322
+ for (let i = 0; i < keys.length - 1; i++) {
323
+ if (obj[keys[i]] == null) obj[keys[i]] = {};
324
+ obj = obj[keys[i]];
325
+ }
326
+ obj[keys[keys.length - 1]] = val;
327
+ return this.persistToFile(dotPath, val, options?.atomic === true);
328
+ }
329
+ /** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
330
+ async persistToFile(dotPath, val, atomic = false) {
331
+ const fs3 = await import("node:fs");
332
+ const cfgPath = this.current?._configFilePath;
333
+ if (!cfgPath || !fs3.existsSync(cfgPath)) {
334
+ console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
335
+ return false;
336
+ }
337
+ try {
338
+ const raw = JSON.parse(fs3.readFileSync(cfgPath, "utf-8"));
339
+ const keys = dotPath.split(".");
340
+ let o = raw;
341
+ for (let i = 0; i < keys.length - 1; i++) {
342
+ if (o[keys[i]] == null) o[keys[i]] = {};
343
+ o = o[keys[i]];
344
+ }
345
+ o[keys[keys.length - 1]] = val;
346
+ if (atomic) {
347
+ writeConfigAtomic(cfgPath, raw);
348
+ } else fs3.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
349
+ const lastKey = keys[keys.length - 1].toLowerCase();
350
+ const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
351
+ const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
352
+ console.log(`[liveConfig] persisted ${dotPath} = ${shown} to ${cfgPath}`);
353
+ markSelfWrite();
354
+ return true;
355
+ } catch (e) {
356
+ console.warn(`[liveConfig] persist failed (${dotPath}): ${e.message}`);
357
+ return false;
358
+ }
359
+ }
360
+ /** 是否已初始化 */
361
+ isReady() {
362
+ return this.current !== null;
363
+ }
364
+ };
365
+ liveConfig = new LiveConfigClass();
366
+ selfWrite = { pending: false };
367
+ }
368
+ });
369
+
370
+ // src/config/features.ts
371
+ var FEATURE_DEFAULTS;
372
+ var init_features = __esm({
373
+ "src/config/features.ts"() {
374
+ "use strict";
375
+ init_live();
376
+ FEATURE_DEFAULTS = {
377
+ filesystem: true,
378
+ shell: true,
379
+ memory: true,
380
+ "topic-extract": true,
381
+ "topic-recall": true,
382
+ "session-memory": true,
383
+ todo: true,
384
+ cron: false,
385
+ voice: false,
386
+ selfie: false,
387
+ eyes: false,
388
+ calendar: false,
389
+ webSearch: true,
390
+ webFetch: true,
391
+ installer: true,
392
+ agentTeams: true,
393
+ autoDream: true,
394
+ /** 1122:cc_ask/cc_progress 默认开(存量配置 loader 就地补全);边缘功能,垫底 */
395
+ "cc-driver": true,
396
+ processOutput: "verbose",
397
+ interrupt: "command",
398
+ /** 1105:主 query 运行中用户消息的处理——'steer'(默认,注入当前 query)| 'queue'(旧行为,排队) */
399
+ busyPolicy: "steer",
400
+ debounceMs: 5e3
401
+ };
402
+ }
403
+ });
404
+
405
+ // src/time/wall-parts.ts
406
+ var init_wall_parts = __esm({
407
+ "src/time/wall-parts.ts"() {
408
+ "use strict";
409
+ }
410
+ });
411
+
412
+ // src/time/clock.ts
413
+ function detectHostTimezone() {
414
+ try {
415
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
416
+ } catch {
417
+ return "UTC";
418
+ }
419
+ }
420
+ var init_clock = __esm({
421
+ "src/time/clock.ts"() {
422
+ "use strict";
423
+ init_live();
424
+ init_wall_parts();
425
+ }
426
+ });
427
+
428
+ // src/config/loader.ts
429
+ var loader_exports = {};
430
+ __export(loader_exports, {
431
+ configSummary: () => configSummary,
432
+ isUnresolvedEnvRef: () => isUnresolvedEnvRef,
433
+ loadConfig: () => loadConfig,
434
+ makeEnvResolver: () => makeEnvResolver,
435
+ parseModelRef: () => parseModelRef,
436
+ resolveTimezone: () => resolveTimezone,
437
+ takeLoadWarnings: () => takeLoadWarnings
438
+ });
439
+ import * as fs2 from "node:fs";
440
+ import * as path2 from "node:path";
441
+ function parseModelRef(ref) {
442
+ const idx = ref.indexOf("/");
443
+ if (idx <= 0 || idx === ref.length - 1) {
444
+ throw new Error(`Invalid model reference: "${ref}". Expected format: "provider/model"`);
445
+ }
446
+ return { providerId: ref.slice(0, idx), modelId: ref.slice(idx + 1) };
447
+ }
448
+ function takeLoadWarnings() {
449
+ loadWarningsFlushed = true;
450
+ const out = loadWarnings.slice();
451
+ loadWarnings.length = 0;
452
+ return out;
453
+ }
454
+ function warnAtLoad(msg) {
455
+ if (!loadWarningsFlushed) loadWarnings.push(msg);
456
+ console.warn(msg);
457
+ }
458
+ function resolveTimezone(raw) {
459
+ const fallback = () => {
460
+ try {
461
+ return detectHostTimezone();
462
+ } catch {
463
+ return "UTC";
464
+ }
465
+ };
466
+ const v = raw?.timezone;
467
+ if (typeof v !== "string" || !v) return fallback();
468
+ try {
469
+ new Intl.DateTimeFormat("en-US", { timeZone: v });
470
+ return v;
471
+ } catch {
472
+ warnAtLoad(`[config] timezone "${v}" \u4E0D\u662F\u5408\u6CD5 IANA \u65F6\u533A\u540D\uFF0C\u9000\u56DE\u672C\u673A\u63A2\u6D4B`);
473
+ return fallback();
474
+ }
475
+ }
476
+ function makeEnvResolver(missingEnvKeys) {
477
+ return function resolveEnv(node) {
478
+ if (typeof node === "string") {
479
+ const m = ENV_REF_RE.exec(node);
480
+ if (m) {
481
+ if (process.env[m[1]] !== void 0) return process.env[m[1]];
482
+ if (missingEnvKeys && node.startsWith("env:")) missingEnvKeys.add(m[1]);
483
+ }
484
+ return node;
485
+ }
486
+ if (Array.isArray(node)) return node.map(resolveEnv);
487
+ if (node && typeof node === "object") {
488
+ for (const k of Object.keys(node)) node[k] = resolveEnv(node[k]);
489
+ }
490
+ return node;
491
+ };
492
+ }
493
+ function isUnresolvedEnvRef(value) {
494
+ return typeof value === "string" && ENV_REF_RE.test(value);
495
+ }
496
+ function loadConfig(configPath) {
497
+ const resolvedPath = path2.resolve(
498
+ configPath || process.env.ENGINE_CONFIG || "engine-config.json"
499
+ );
500
+ if (!fs2.existsSync(resolvedPath)) {
501
+ throw new Error(`Config file not found: ${resolvedPath}`);
502
+ }
503
+ const raw = JSON.parse(fs2.readFileSync(resolvedPath, "utf-8"));
504
+ const missingEnvKeys = /* @__PURE__ */ new Set();
505
+ const resolveEnv = makeEnvResolver(missingEnvKeys);
506
+ resolveEnv(raw);
507
+ if (missingEnvKeys.size > 0) {
508
+ warnAtLoad(
509
+ `[config] \u73AF\u5883\u53D8\u91CF\u672A\u8BBE\u7F6E\uFF1A${[...missingEnvKeys].join(", ")}\uFF08config \u91CC\u7528 env: \u5F15\u7528\u4E86\u5B83\u4EEC\uFF09\u2014\u2014\u7528\u5230\u5BF9\u5E94 provider / tool \u65F6\u4F1A\u5931\u8D25\u3002`
510
+ );
511
+ }
512
+ const envOverrides = [];
513
+ if (process.env.ENGINE_CONFIG) envOverrides.push(`ENGINE_CONFIG=${process.env.ENGINE_CONFIG}`);
514
+ if (process.env.ENGINE_MODEL) envOverrides.push(`ENGINE_MODEL=${process.env.ENGINE_MODEL}`);
515
+ if (process.env.ENGINE_STATE_DIR) envOverrides.push(`ENGINE_STATE_DIR=${process.env.ENGINE_STATE_DIR}`);
516
+ if (process.env.ENGINE_WORKSPACE) envOverrides.push(`ENGINE_WORKSPACE=${process.env.ENGINE_WORKSPACE}`);
517
+ if (process.env.ENGINE_AGENT) envOverrides.push(`ENGINE_AGENT=${process.env.ENGINE_AGENT}`);
518
+ if (envOverrides.length > 0) {
519
+ if (!envOverridesLogged) {
520
+ envOverridesLogged = true;
521
+ console.log(`[config] ENV overrides: ${envOverrides.join(", ")}`);
522
+ }
523
+ }
524
+ const providers = {};
525
+ for (const [id, p] of Object.entries(raw.models?.providers || {})) {
526
+ const pv = p;
527
+ if (typeof pv?.apiKey === "string") {
528
+ const m = pv.apiKey.match(/^(?:env:|{{\s*)?([A-Z][A-Z0-9_]*)(?:\s*}})?$/);
529
+ if (m && process.env[m[1]] !== void 0) {
530
+ pv.apiKey = process.env[m[1]];
531
+ }
532
+ }
533
+ providers[id] = {
534
+ id,
535
+ ...pv
536
+ };
537
+ }
538
+ const agentDefaults = raw.agents?.defaults || {};
539
+ let defaultFallbackModel;
540
+ if (Object.keys(providers).length > 0) {
541
+ const firstProviderId = Object.keys(providers)[0];
542
+ const firstProvider = providers[firstProviderId];
543
+ if (firstProvider?.models?.length) {
544
+ defaultFallbackModel = `${firstProviderId}/${firstProvider.models[0].id}`;
545
+ }
546
+ }
547
+ const modelRef = process.env.ENGINE_MODEL || agentDefaults.model?.primary || defaultFallbackModel || Object.keys(providers)[0];
548
+ const modelAliases = {};
549
+ if (agentDefaults.models) {
550
+ for (const [ref, spec] of Object.entries(agentDefaults.models)) {
551
+ const alias = spec?.alias;
552
+ if (alias && typeof alias === "string") {
553
+ modelAliases[alias] = ref;
554
+ }
555
+ }
556
+ }
557
+ const { providerId: providerId2, modelId } = parseModelRef(modelRef);
558
+ const provider = providers[providerId2];
559
+ if (!provider) {
560
+ throw new Error(`Provider "${providerId2}" not found in config. Available: ${Object.keys(providers).join(", ")}`);
561
+ }
562
+ const fallbacks = Array.isArray(agentDefaults.model?.fallbacks) ? agentDefaults.model.fallbacks : void 0;
563
+ let visionModel = null;
564
+ const visionRef = agentDefaults.model?.vision;
565
+ if (visionRef) {
566
+ const parsed = parseModelRef(visionRef);
567
+ if (providers[parsed.providerId]) {
568
+ visionModel = parsed;
569
+ } else {
570
+ warnAtLoad(`[config] Vision provider "${parsed.providerId}" not found, vision routing disabled`);
571
+ }
572
+ }
573
+ let videoModel = null;
574
+ const videoRef = agentDefaults.model?.video;
575
+ if (videoRef) {
576
+ const parsed = parseModelRef(videoRef);
577
+ if (providers[parsed.providerId]) {
578
+ videoModel = parsed;
579
+ } else {
580
+ warnAtLoad(`[config] Video provider "${parsed.providerId}" not found, video routing disabled (ref: ${videoRef})`);
581
+ }
582
+ }
583
+ let visionFallbacks = [];
584
+ const visionFbRefs = agentDefaults.model?.visionFallbacks;
585
+ if (visionFbRefs) {
586
+ for (const ref of visionFbRefs) {
587
+ const parsed = parseModelRef(ref);
588
+ if (providers[parsed.providerId]) {
589
+ visionFallbacks.push(parsed);
590
+ } else {
591
+ warnAtLoad(`[config] Vision fallback provider "${parsed.providerId}" not found, skipping ${ref}`);
592
+ }
593
+ }
594
+ }
595
+ const stateDir = raw.stateDir || process.env.ENGINE_STATE_DIR || path2.resolve(".engine");
596
+ const workspace = process.env.ENGINE_WORKSPACE || agentDefaults.workspace || path2.join(stateDir, "workspace");
597
+ const mediaDir = raw.mediaDir || path2.join(stateDir, "media", "inbound");
598
+ if (!agentDefaults.features) agentDefaults.features = {};
599
+ for (const [k, v] of Object.entries(FEATURE_DEFAULTS)) {
600
+ if (agentDefaults.features[k] === void 0) {
601
+ ;
602
+ agentDefaults.features[k] = v;
603
+ }
604
+ }
605
+ const profile = {
606
+ id: process.env.ENGINE_AGENT || "default",
607
+ name: agentDefaults.name || "AI Assistant",
608
+ model: modelRef,
609
+ workspace,
610
+ soul: agentDefaults.soul,
611
+ agents: agentDefaults.agents,
612
+ features: agentDefaults.features,
613
+ // canonical:profile.features 即 agents.defaults.features(同一对象,过渡兼容)
614
+ channels: agentDefaults.channels || [],
615
+ extensions: agentDefaults.extensions,
616
+ maxTurns: agentDefaults.maxTurns,
617
+ // ⚠️ **默认 true**(0928 翀哥拍板):开源项目,功能不按 license 分档。
618
+ // 要收起来才显式配 `agents.defaults.devMode: false`。
619
+ // 反过来写(=== true)时,任何没手配这一格的配置都会静默落进"基础引擎模式"。
620
+ devMode: agentDefaults.devMode !== false
621
+ };
622
+ const rawSession = raw.session || {};
623
+ const sessionScope = Object.keys(rawSession).length > 0 ? { ...rawSession } : void 0;
624
+ const rawHeartbeat = raw.heartbeat || {};
625
+ const heartbeat = rawHeartbeat.enabled ? {
626
+ ...rawHeartbeat,
627
+ enabled: true
628
+ } : void 0;
629
+ const rawInnerVoice = raw.innerVoice || {};
630
+ const innerVoice = rawInnerVoice.enabled ? {
631
+ ...rawInnerVoice,
632
+ enabled: true
633
+ } : void 0;
634
+ const resolvedTimezone = resolveTimezone(raw);
635
+ const rawCron = raw.cron || {};
636
+ const cron = rawCron.enabled ? {
637
+ ...rawCron,
638
+ enabled: true,
639
+ // ★ 这里原来写死 'Asia/Shanghai'。而 cron/tasks.ts 建任务时是
640
+ // `params.timezone || params.defaultTimezone || 'Asia/Shanghai'` ——
641
+ // defaultTimezone 恒有值 ⇒ 兜底永远轮不到 ⇒ **工具建的每个任务都被
642
+ // 显式写死北京时区存进 tasks.json**,顶层 timezone 配置形同虚设
643
+ // (马耳他用户说"每天 9 点",会在当地凌晨 3 点触发)。
644
+ // 改为跟随引擎时区;per-task 的显式 timezone 仍然优先。
645
+ defaultTimezone: rawCron.defaultTimezone || resolvedTimezone,
646
+ tickIntervalMs: rawCron.tickIntervalMs || 1e4,
647
+ maxConsecutiveFailures: rawCron.maxConsecutiveFailures || 5,
648
+ retry: {
649
+ maxAttempts: rawCron.retry?.maxAttempts ?? 2,
650
+ delayMs: rawCron.retry?.delayMs ?? 3e4
651
+ },
652
+ missedTaskGraceMs: rawCron.missedTaskGraceMs || 3e5,
653
+ maxTasks: rawCron.maxTasks || 100
654
+ } : void 0;
655
+ return {
656
+ ...raw,
657
+ // 先展开 raw:未显式处理的字段(如 webhook)自动进来,避免每次加 config 都要手动挑;下面显式字段覆盖 raw(解析值优先)
658
+ timezone: resolvedTimezone,
659
+ provider,
660
+ providers,
661
+ // 所有 provider 配置字典(供 memory/provider 动态切换用)
662
+ modelAliases: Object.keys(modelAliases).length > 0 ? modelAliases : void 0,
663
+ model: modelId,
664
+ fallbacks,
665
+ visionModel,
666
+ visionFallbacks,
667
+ videoModel,
668
+ workspace,
669
+ stateDir,
670
+ mediaDir,
671
+ profile,
672
+ display: loadDisplayConfig(raw.display),
673
+ channels: raw.channels || {},
674
+ tools: raw.tools || {},
675
+ auth: authConfig(raw.auth),
676
+ toolSearch: raw.toolSearch,
677
+ memoryIndex: agentDefaults.memorySearch,
678
+ session: sessionScope,
679
+ heartbeat,
680
+ nudge: raw.nudge,
681
+ innerVoice,
682
+ cron,
683
+ skills: agentDefaults.skills,
684
+ prompt: raw.prompt,
685
+ agentTeams: raw.agentTeams,
686
+ hooks: raw.hooks,
687
+ visualization: raw.visualization?.enabled ? raw.visualization : void 0,
688
+ mcpServers: raw.mcpServers || {},
689
+ topics: raw.topics,
690
+ sandbox: raw.sandbox,
691
+ api: raw.api,
692
+ voiceChat: raw.voiceChat,
693
+ services: raw.services,
694
+ commands: raw.commands,
695
+ compaction: raw.compaction,
696
+ everos: raw.everos,
697
+ // 保留原始 agents 段,供 liveConfig.get('agents.defaults.*') 读取(如 privateTools 开关)
698
+ agents: raw.agents,
699
+ _configFilePath: resolvedPath
700
+ };
701
+ }
702
+ function configSummary(config) {
703
+ const lines = [
704
+ `Provider: ${config.provider.id} (${config.provider.api})`,
705
+ `Model: ${config.model}`,
706
+ `Base URL: ${config.provider.baseUrl}`,
707
+ `Workspace: ${config.workspace}`,
708
+ `Agent: ${config.profile.id}`
709
+ ];
710
+ const enabled = [];
711
+ const disabled = [];
712
+ for (const [k, v] of Object.entries(config.profile.features)) {
713
+ if (k === "processOutput" || k === "interrupt" || k === "debounceMs") continue;
714
+ if (v) enabled.push(k);
715
+ else disabled.push(k);
716
+ }
717
+ if (enabled.length) lines.push(`Features: ${enabled.join(", ")}`);
718
+ if (disabled.length) lines.push(`Disabled: ${disabled.join(", ")}`);
719
+ lines.push(`Output: ${config.profile.features.processOutput}`);
720
+ lines.push(`Interrupt: ${config.profile.features.interrupt}`);
721
+ return lines.join("\n");
722
+ }
723
+ var loadWarnings, loadWarningsFlushed, ENV_REF_RE, envOverridesLogged;
724
+ var init_loader = __esm({
725
+ "src/config/loader.ts"() {
726
+ "use strict";
727
+ init_config();
728
+ init_display();
729
+ init_features();
730
+ init_clock();
731
+ loadWarnings = [];
732
+ loadWarningsFlushed = false;
733
+ ENV_REF_RE = /^(?:env:|{{\s*)(?=[A-Z0-9_]*[A-Z])([A-Z0-9_]+)(?:\s*}})?$/;
734
+ envOverridesLogged = false;
735
+ }
736
+ });
737
+
738
+ // src/config/tts-providers.ts
739
+ var TTS_PROVIDERS;
740
+ var init_tts_providers = __esm({
741
+ "src/config/tts-providers.ts"() {
742
+ "use strict";
743
+ TTS_PROVIDERS = [
744
+ // relay:走 7yi 中转站的 /v1/audio/speech。
745
+ // 后三个 billing* 键也在这支读——选池要用;漏了的话托盘切 provider 会把它们清掉。
746
+ //
747
+ // ⚠️ `voiceTier` 与 `fallback` 都在这一支读,且**都由引擎侧读、托盘没有输入框**
748
+ // (见 config-editors.ts 的 VOICE_FORM_KEYS —— 托盘只建它有框的那几格)。
749
+ // 它们出现在这里**不是为了给用户编辑**,而是为了让托盘的保存路径**别把它们删掉**:
750
+ // mergeMyVoice 的 `keep` 来自这份清单(它决定"这一版 provider 会读哪些键"),
751
+ // 而不在 keep 里的键会被整份替换下去 —— 漏了 `voiceTier` 就是"托盘一保存,
752
+ // 计价档位静默消失"。这是本清单**唯一**的第二个用途,别把这两个键当成多余的。
753
+ // · voiceTier → providers.ts:39 算 tier(route 用它选池、usage 用它记账;
754
+ // spec §4.4 留的克隆音色计费钩子,今天没有生产者)
755
+ // · fallback → my-voice.ts 主路径的回退链(spec §4.1,默认 ['edge'])
756
+ { id: "relay", requiredKeys: [
757
+ "pythonPath",
758
+ "relayProviderId",
759
+ "relayModel",
760
+ "voice",
761
+ "billingProviderId",
762
+ "billingModel",
763
+ "billingMode",
764
+ "voiceTier",
765
+ "fallback"
766
+ ] },
767
+ { id: "cosyvoice", requiredKeys: ["pythonPath", "apiKey", "model", "voice", "workspaceId", "instruction"] },
768
+ // gptsovits:四个 gptsovits* 键是 Task 9 从硬编码改过来的(原来是 GPTSOVITS_API / REF_WAV /
769
+ // REF_TEXT 写死在 my-voice.ts:303-306,那个 REF_WAV 是翀哥 Linux 机器上的路径,所有用户都会去找它)
770
+ { id: "gptsovits", requiredKeys: [
771
+ "pythonPath",
772
+ "gptsovitsUrl",
773
+ "gptsovitsRefWav",
774
+ "gptsovitsRefText",
775
+ "gptsovitsRefLang"
776
+ ] },
777
+ { id: "qwen3-3060", requiredKeys: ["pythonPath", "url", "voice", "lang"] },
778
+ { id: "edge", requiredKeys: ["pythonPath"] }
779
+ ];
780
+ }
781
+ });
782
+
783
+ // src/config/tts-voices.ts
784
+ var RELAY_VOICES;
785
+ var init_tts_voices = __esm({
786
+ "src/config/tts-voices.ts"() {
787
+ "use strict";
788
+ RELAY_VOICES = [
789
+ // 女声三支(默认音色排第一 —— 下拉的默认选中项就是第一项)
790
+ "Chinese (Mandarin)_Warm_Girl",
791
+ // 温暖女孩(= DEFAULT_FREE_VOICE,生产已验证)
792
+ "Chinese (Mandarin)_Crisp_Girl",
793
+ // 清脆女孩
794
+ "Chinese (Mandarin)_Soft_Girl",
795
+ // 轻柔女孩
796
+ // 男声三支(翀哥 0927:女生想要男音,之前没得选)
797
+ "Chinese (Mandarin)_Gentle_Youth",
798
+ // 温润青年
799
+ "Chinese (Mandarin)_Unrestrained_Young_Man",
800
+ // 不羁青年
801
+ "Chinese (Mandarin)_Southern_Young_Man"
802
+ // 南方青年
803
+ ];
804
+ }
805
+ });
806
+
807
+ // src/config/registry.ts
808
+ function modelRefListError(v) {
809
+ if (!Array.isArray(v)) return '\u964D\u7EA7\u94FE\u8981\u662F\u6570\u7EC4\uFF0C\u6BCF\u4E2A\u5143\u7D20\u5F62\u5982 "provider/model"';
810
+ for (const item of v) {
811
+ if (typeof item !== "string" || item.trim() === "") {
812
+ return `\u964D\u7EA7\u94FE\u7684\u6BCF\u4E2A\u5143\u7D20\u8981\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u6536\u5230 ${JSON.stringify(item)}\uFF09`;
813
+ }
814
+ const slash = item.indexOf("/");
815
+ if (slash <= 0 || slash === item.length - 1) {
816
+ return `"${item}" \u4E0D\u662F provider/model\u2014\u2014'/' \u524D\u8981\u662F provider\u3001'/' \u540E\u8981\u662F\u578B\u53F7\uFF0C\u4E24\u4FA7\u90FD\u4E0D\u80FD\u4E3A\u7A7A`;
817
+ }
818
+ }
819
+ return null;
820
+ }
821
+ function getField(path4) {
822
+ return FIELDS.find((f) => f.path === path4);
823
+ }
824
+ var VALID_PERSONAS, FIELDS;
825
+ var init_registry = __esm({
826
+ "src/config/registry.ts"() {
827
+ "use strict";
828
+ init_protocol();
829
+ init_tts_providers();
830
+ init_tts_voices();
831
+ VALID_PERSONAS = ["assistant", "companion", "butler", "friend"];
832
+ FIELDS = [
833
+ { path: "discovery.enabled", type: "boolean", group: "general", label: "\u81EA\u52A8\u5206\u4EAB\u52A8\u6001\u4E0E\u70B9\u5B50", effect: "hot" },
834
+ { path: "discovery.intervalMs", type: "number", group: "general", label: "\u53D1\u73B0\u9009\u6750\u95F4\u9694\uFF08\u6BEB\u79D2\uFF09", effect: "hot", validate: (v) => typeof v === "number" && Number.isFinite(v) && v >= 6e5 && v <= 6048e5 ? null : "\u95F4\u9694\u9700\u4E3A10\u5206\u949F\u81F37\u5929" },
835
+ { path: "discovery.maxPostsPerDay", type: "number", group: "general", label: "\u6BCF\u65E5\u52A8\u6001\u4E0E\u70B9\u5B50\u5408\u8BA1\u4E0A\u9650", effect: "hot", validate: (v) => Number.isSafeInteger(v) && Number(v) >= 1 && Number(v) <= 24 ? null : "\u6BCF\u65E5\u4E0A\u9650\u9700\u4E3A1\u81F324" },
836
+ { path: "discovery.model", type: "string", group: "model", label: "\u53D1\u73B0\u9009\u6750\u6A21\u578B", effect: "hot" },
837
+ // === general:环境与目录 ===
838
+ {
839
+ path: "timezone",
840
+ type: "string",
841
+ group: "general",
842
+ label: "\u65F6\u533A",
843
+ effect: "hot"
844
+ },
845
+ { path: "stateDir", type: "path", group: "general", label: "\u72B6\u6001\u76EE\u5F55", effect: "restart" },
846
+ { path: "mediaDir", type: "path", group: "general", label: "\u5165\u7AD9\u5A92\u4F53\u76EE\u5F55", effect: "restart" },
847
+ { path: "agents.defaults.workspace", type: "path", group: "general", label: "\u5DE5\u4F5C\u533A\u76EE\u5F55", effect: "restart" },
848
+ // === identity:名字与人设 ===
849
+ {
850
+ // 没有 migration 触发器:display.preview.agentName 的同步是**纯内存联动**,
851
+ // 实现收在 cli-config.ts 的写入点里(一次落盘)。原先还声明过一个 'agent-name'
852
+ // 触发器,它只"报告"要同步却什么都不写——两个实现两套判据(迁移那边连
853
+ // preview.agentName 为 undefined 都算改),已删(C6)。
854
+ path: "agents.defaults.name",
855
+ type: "string",
856
+ group: "identity",
857
+ label: "\u52A9\u624B\u540D\u5B57",
858
+ effect: "hot"
859
+ },
860
+ {
861
+ path: "agents.defaults.persona",
862
+ type: "enum",
863
+ group: "identity",
864
+ label: "\u4EBA\u8BBE",
865
+ effect: "hot",
866
+ options: VALID_PERSONAS,
867
+ migration: "persona-switch",
868
+ validate: (v) => VALID_PERSONAS.includes(String(v)) ? null : `\u4EBA\u8BBE\u53EA\u80FD\u662F ${VALID_PERSONAS.join(" / ")}`
869
+ },
870
+ // === model:模型服务与本机 API ===
871
+ {
872
+ path: "agents.defaults.model.primary",
873
+ type: "string",
874
+ group: "model",
875
+ label: "\u4E3B\u6A21\u578B",
876
+ effect: "hot"
877
+ },
878
+ {
879
+ // 降级链。type 用 json 不是"新造一个数组类型"——FieldType 枚举里没有数组,
880
+ // 同类先例是 prompt.staticFiles(同为 string[],也标 json)。
881
+ path: "agents.defaults.model.fallbacks",
882
+ type: "json",
883
+ group: "model",
884
+ label: "\u964D\u7EA7\u94FE",
885
+ // hot —— 有实证,不是"看着像运行时读的":
886
+ // reload.ts:86 / :103 的 provider 重建 key **逐字含 fallbacks**,只改这一格也必然
887
+ // old !== new → buildProviderChain(newConfig) 用 newConfig.fallbacks 重建
888
+ // FallbackProvider(startup/providers.ts:47,54)→ deps.engine.setProvider
889
+ // (reload.ts:133 → core/query.ts:190),并经 onProviderSwapped 换掉闭包里的 provider
890
+ // (message-pipeline.ts:124-125)。loader 的读点:loader.ts:557-558。
891
+ effect: "hot",
892
+ validate: (v) => modelRefListError(v)
893
+ },
894
+ {
895
+ path: "agents.defaults.model.vision",
896
+ type: "string",
897
+ group: "model",
898
+ label: "\u89C6\u89C9\u6A21\u578B",
899
+ effect: "hot"
900
+ },
901
+ {
902
+ // 视觉降级链(vision 引用不可用时的备用型号)。与上面同形状、同校验。
903
+ // hot 实证:reload.ts:88 / :105 同样把它算进 provider key,变更即重建 vision 链
904
+ // (startup/providers.ts:86-97 → reload.ts:145-157 的 deps.setVisionProvider)。
905
+ path: "agents.defaults.model.visionFallbacks",
906
+ type: "json",
907
+ group: "model",
908
+ label: "\u89C6\u89C9\u964D\u7EA7\u94FE",
909
+ effect: "hot",
910
+ validate: (v) => modelRefListError(v)
911
+ },
912
+ {
913
+ path: "models.providers",
914
+ type: "json",
915
+ group: "model",
916
+ label: "\u6A21\u578B\u670D\u52A1",
917
+ effect: "hot"
918
+ },
919
+ {
920
+ path: "tools.tavily.apiKey",
921
+ type: "secret",
922
+ group: "model",
923
+ label: "Tavily Key",
924
+ effect: "hot"
925
+ },
926
+ {
927
+ path: "tools.my_eyes.model",
928
+ type: "string",
929
+ group: "model",
930
+ label: "\u770B\u56FE\u6A21\u578B",
931
+ effect: "hot"
932
+ },
933
+ {
934
+ path: "tools.webSearch.provider",
935
+ type: "string",
936
+ group: "model",
937
+ label: "\u641C\u7D22\u540E\u7AEF",
938
+ effect: "hot",
939
+ // tavily(默认,链接列表,~2s)|doubao(豆包联网搜索,综合答案,13-20s,按次计费)。
940
+ // knownValues 给托盘「搜索设置」面板做下拉(1010 翀哥拍板:不让用户手打裸值)
941
+ knownValues: ["tavily", "doubao"],
942
+ validate: (v) => v === "tavily" || v === "doubao" ? null : "\u53EA\u80FD\u662F tavily \u6216 doubao"
943
+ },
944
+ {
945
+ path: "tools.webSearch.doubaoModel",
946
+ type: "string",
947
+ group: "model",
948
+ label: "\u8C46\u5305\u641C\u7D22\u6A21\u578B",
949
+ effect: "hot",
950
+ // 复合串 provider/model(模型引用统一口径):provider 指向 OpenAI-compat 的
951
+ // providers 条目(7yi 中转的 doubao-web-search 或方舟直连)
952
+ validate: (v) => !v || String(v).includes("/") ? null : "\u683C\u5F0F\uFF1Aprovider/model\uFF08provider \u662F providers \u91CC\u7684 key\uFF09"
953
+ },
954
+ // 1019 妹妹评审二轮 #9:api.* 是本机服务/集成面,从 'model' 组独立成 'api' 组。
955
+ {
956
+ path: "api.port",
957
+ type: "number",
958
+ group: "api",
959
+ label: "\u672C\u673A API \u7AEF\u53E3",
960
+ effect: "restart",
961
+ // v 可能是字符串(JSON 里的 "17000"、`config set api.port 17000` 的 argv)——先 Number()
962
+ // 再判。别写成 Number.isInteger(v):那对字符串永远 false,会把合法端口判死。
963
+ validate: (v) => {
964
+ const n = Number(v);
965
+ return Number.isInteger(n) && n > 0 && n < 65536 ? null : "\u7AEF\u53E3\u8981\u662F 1~65535 \u7684\u6574\u6570";
966
+ }
967
+ },
968
+ // 1019 豆包助理桥:init 时把桥 skill 落进豆包 .user_skills(用户在豆包里说「让助理帮我…」
969
+ // 就能用到本引擎)。restart 而非 hot:桥只随 init 落盘,改开关后要重跑 init(或手动拷)才生效;
970
+ // 运行时侧 webhook.requireToken 会对 doubaoBridge=false 的桥请求 403(关桥立即生效)。
971
+ {
972
+ path: "api.doubaoBridge",
973
+ type: "boolean",
974
+ group: "api",
975
+ label: "\u8C46\u5305\u52A9\u7406\u6865",
976
+ effect: "restart"
977
+ },
978
+ {
979
+ path: "api.bridge_token",
980
+ type: "secret",
981
+ group: "api",
982
+ label: "\u6865\u5171\u4EAB\u4EE4\u724C",
983
+ effect: "restart"
984
+ },
985
+ // 1019 妹妹评审二轮 #1/#2:webhook 门与鉴权。enabled 此前 init 从不设置(桥 DOA 根因);
986
+ // requireToken=true 时 /api/webhook 必须带匹配 api.bridge_token 的 bridgeToken(老装机
987
+ // 无此键=不校验,既有调用方零破坏)。两格都是逐请求现读 → hot。
988
+ {
989
+ path: "webhook.enabled",
990
+ type: "boolean",
991
+ group: "api",
992
+ label: "Webhook \u6CE8\u5165\u5165\u53E3",
993
+ effect: "hot"
994
+ },
995
+ {
996
+ path: "webhook.requireToken",
997
+ type: "boolean",
998
+ group: "api",
999
+ label: "Webhook \u9274\u6743\uFF08\u6865\u4EE4\u724C\uFF09",
1000
+ effect: "hot"
1001
+ },
1002
+ // === channel:通道接入 ===
1003
+ // 开关 / 策略类走 channels reload entry(engine-startup.ts:750)→ hot;
1004
+ // token / appSecret 走 channel-reconnect:**config 里存的是 env: 引用**,set 值的
1005
+ // 时候写的 .env、config 那格一个字节不变 ⇒ watcher 不触发,长连接不会自己换新凭证。
1006
+ // (0926 T12 起通道凭据与 provider apiKey 同机制,不再有"明文写 config"的例外。)
1007
+ {
1008
+ path: "channels.discord.enabled",
1009
+ type: "boolean",
1010
+ group: "channel",
1011
+ label: "\u542F\u7528 Discord",
1012
+ effect: "hot"
1013
+ },
1014
+ {
1015
+ path: "channels.discord.accounts.default.token",
1016
+ type: "secret",
1017
+ group: "channel",
1018
+ label: "Discord \u673A\u5668\u4EBA\u4EE4\u724C",
1019
+ effect: "channel-reconnect",
1020
+ envKey: "DISCORD_BOT_TOKEN"
1021
+ },
1022
+ {
1023
+ path: "channels.discord.dmPolicy",
1024
+ type: "enum",
1025
+ group: "channel",
1026
+ label: "Discord \u79C1\u804A\u7B56\u7565",
1027
+ effect: "hot",
1028
+ options: ["pairing", "open"]
1029
+ },
1030
+ {
1031
+ path: "channels.discord.groupPolicy",
1032
+ type: "enum",
1033
+ group: "channel",
1034
+ label: "Discord \u7FA4\u804A\u7B56\u7565",
1035
+ effect: "hot",
1036
+ options: ["open", "mention-only"]
1037
+ },
1038
+ {
1039
+ path: "channels.discord.replyToMode",
1040
+ type: "enum",
1041
+ group: "channel",
1042
+ label: "Discord \u56DE\u590D\u65B9\u5F0F",
1043
+ effect: "hot",
1044
+ options: ["off", "all"]
1045
+ },
1046
+ {
1047
+ path: "channels.feishu.enabled",
1048
+ type: "boolean",
1049
+ group: "channel",
1050
+ label: "\u542F\u7528\u98DE\u4E66",
1051
+ effect: "hot"
1052
+ },
1053
+ {
1054
+ path: "channels.feishu.appId",
1055
+ type: "string",
1056
+ group: "channel",
1057
+ label: "\u98DE\u4E66 App ID",
1058
+ effect: "hot"
1059
+ },
1060
+ {
1061
+ path: "channels.feishu.appSecret",
1062
+ type: "secret",
1063
+ group: "channel",
1064
+ label: "\u98DE\u4E66 App Secret",
1065
+ effect: "channel-reconnect",
1066
+ envKey: "FEISHU_APP_SECRET"
1067
+ },
1068
+ {
1069
+ path: "channels.feishu.connectionMode",
1070
+ type: "enum",
1071
+ group: "channel",
1072
+ label: "\u98DE\u4E66\u8FDE\u63A5\u65B9\u5F0F",
1073
+ effect: "hot",
1074
+ options: ["websocket", "webhook"]
1075
+ },
1076
+ {
1077
+ path: "channels.feishu.dmPolicy",
1078
+ type: "enum",
1079
+ group: "channel",
1080
+ label: "\u98DE\u4E66\u79C1\u804A\u7B56\u7565",
1081
+ effect: "hot",
1082
+ options: ["pairing", "open"]
1083
+ },
1084
+ {
1085
+ path: "channels.feishu.groupPolicy",
1086
+ type: "enum",
1087
+ group: "channel",
1088
+ label: "\u98DE\u4E66\u7FA4\u804A\u7B56\u7565",
1089
+ effect: "hot",
1090
+ options: ["mention-only", "open"]
1091
+ },
1092
+ {
1093
+ path: "channels.feishu.interactive",
1094
+ type: "boolean",
1095
+ group: "channel",
1096
+ label: "\u98DE\u4E66\u4EA4\u4E92\u5361\u7247",
1097
+ effect: "hot"
1098
+ },
1099
+ // 1029 onboarding:装机扫码注册时采集的主人 open_id(cli-init configureFeishu 的
1100
+ // result.openId)。只被 onboarding 子系统读(src/onboarding/)——主动欢迎的投递目标。
1101
+ // hot:不参与飞书长连接身份,改了不影响 adapter。
1102
+ {
1103
+ path: "channels.feishu.ownerOpenId",
1104
+ type: "string",
1105
+ group: "channel",
1106
+ label: "\u98DE\u4E66\u4E3B\u4EBA Open ID\uFF08\u4E3B\u52A8\u6B22\u8FCE\u7528\uFF09",
1107
+ effect: "hot"
1108
+ },
1109
+ // ⚠️ wechat 整段以前**不在注册表里**:init 与 reconfig 明文写它的 token,
1110
+ // 托盘既看不到也改不动(`set` 直接报"不在字段清单里"),而 `config get` 靠
1111
+ // maskCredentials 的路径模式兜着才没把活 token 打出去。T12 一并补齐。
1112
+ // 字段集对齐 init/reconfig 实际写出的那个块(cli-reconfig.ts:175)——漏一个
1113
+ // 托盘就回写不出完整的 wechat 段(读到的缺了、写回去的更缺)。
1114
+ {
1115
+ path: "channels.wechat.enabled",
1116
+ type: "boolean",
1117
+ group: "channel",
1118
+ label: "\u542F\u7528\u5FAE\u4FE1",
1119
+ effect: "hot"
1120
+ },
1121
+ {
1122
+ path: "channels.wechat.token",
1123
+ type: "secret",
1124
+ group: "channel",
1125
+ label: "\u5FAE\u4FE1\u4EE4\u724C",
1126
+ effect: "channel-reconnect",
1127
+ envKey: "WECHAT_TOKEN"
1128
+ },
1129
+ // accountId 不是密文,但它是**这条连接的身份**(换账号 = 换一条登录),
1130
+ // 与 token 同类:config 生效了、长连接仍不会自己换。
1131
+ {
1132
+ path: "channels.wechat.accountId",
1133
+ type: "string",
1134
+ group: "channel",
1135
+ label: "\u5FAE\u4FE1\u8D26\u53F7",
1136
+ effect: "channel-reconnect"
1137
+ },
1138
+ {
1139
+ path: "channels.wechat.dmPolicy",
1140
+ type: "enum",
1141
+ group: "channel",
1142
+ label: "\u5FAE\u4FE1\u79C1\u804A\u7B56\u7565",
1143
+ effect: "hot",
1144
+ options: ["pairing", "open", "disabled", "allowlist"]
1145
+ },
1146
+ {
1147
+ path: "channels.wechat.group.policy",
1148
+ type: "enum",
1149
+ group: "channel",
1150
+ label: "\u5FAE\u4FE1\u7FA4\u804A\u7B56\u7565",
1151
+ effect: "hot",
1152
+ options: ["disabled", "allowlist", "open"]
1153
+ },
1154
+ // 1029 onboarding:QR 扫码确认回包里的 ilink_user_id(= 扫码用户本人,实证与
1155
+ // getupdates 的 from_user_id 同 id)。cli-init configureWechat 从凭证写入。
1156
+ // 只被 onboarding 子系统读——主动欢迎的投递目标;hot 同 ownerOpenId。
1157
+ {
1158
+ path: "channels.wechat.userId",
1159
+ type: "string",
1160
+ group: "channel",
1161
+ label: "\u5FAE\u4FE1\u4E3B\u4EBA\u8D26\u53F7\uFF08iLink \u7528\u6237 id\uFF0C\u4E3B\u52A8\u6B22\u8FCE\u7528\uFF09",
1162
+ effect: "hot"
1163
+ },
1164
+ // telegram(1002 阶段一):先只声明凭据这一格——init / channel-secrets 迁移 /
1165
+ // `config set` 三处都靠 envKey 认名字(cli-init-config 的 secretRef / 迁移的 envNameFor)。
1166
+ {
1167
+ path: "channels.telegram.token",
1168
+ type: "secret",
1169
+ group: "channel",
1170
+ label: "Telegram \u673A\u5668\u4EBA\u4EE4\u724C",
1171
+ effect: "channel-reconnect",
1172
+ envKey: "TELEGRAM_BOT_TOKEN"
1173
+ },
1174
+ // dingtalk(1004):凭据 = 开发者后台应用凭证(AppKey/AppSecret)。gating 参数 hot =
1175
+ // channels reload entry 整块 diff 重建 adapter,变更即生效(whatsapp 注释同款口径)。
1176
+ {
1177
+ path: "channels.dingtalk.enabled",
1178
+ type: "boolean",
1179
+ group: "channel",
1180
+ label: "\u542F\u7528\u9489\u9489",
1181
+ effect: "hot"
1182
+ },
1183
+ {
1184
+ path: "channels.dingtalk.clientId",
1185
+ type: "string",
1186
+ group: "channel",
1187
+ label: "\u9489\u9489 Client ID\uFF08AppKey\uFF09",
1188
+ effect: "channel-reconnect"
1189
+ },
1190
+ {
1191
+ path: "channels.dingtalk.clientSecret",
1192
+ type: "secret",
1193
+ group: "channel",
1194
+ label: "\u9489\u9489 Client Secret",
1195
+ effect: "channel-reconnect",
1196
+ envKey: "DINGTALK_CLIENT_SECRET"
1197
+ },
1198
+ {
1199
+ path: "channels.dingtalk.groupPolicy",
1200
+ type: "enum",
1201
+ group: "channel",
1202
+ label: "\u9489\u9489\u7FA4\u804A\u7B56\u7565",
1203
+ effect: "hot",
1204
+ options: ["mention-only", "open"]
1205
+ },
1206
+ {
1207
+ path: "channels.dingtalk.allowedUsers",
1208
+ type: "json",
1209
+ group: "channel",
1210
+ label: "\u9489\u9489\u79C1\u804A\u767D\u540D\u5355\uFF08staffId/senderId\uFF09",
1211
+ effect: "hot"
1212
+ },
1213
+ {
1214
+ path: "channels.dingtalk.allowedChats",
1215
+ type: "json",
1216
+ group: "channel",
1217
+ label: "\u9489\u9489\u7FA4\u767D\u540D\u5355\uFF08conversationId\uFF09",
1218
+ effect: "hot"
1219
+ },
1220
+ // wecom(1004):凭据 = 企微后台智能机器人(API 模式 → 长连接)的 BotID/Secret。
1221
+ // 群语义免配(平台只投递 @ 机器人的群消息);displayName 是群 @ 前缀剥离的比对基准。
1222
+ {
1223
+ path: "channels.wecom.enabled",
1224
+ type: "boolean",
1225
+ group: "channel",
1226
+ label: "\u542F\u7528\u4F01\u4E1A\u5FAE\u4FE1",
1227
+ effect: "hot"
1228
+ },
1229
+ {
1230
+ path: "channels.wecom.botId",
1231
+ type: "string",
1232
+ group: "channel",
1233
+ label: "\u4F01\u5FAE\u673A\u5668\u4EBA BotID",
1234
+ effect: "channel-reconnect"
1235
+ },
1236
+ {
1237
+ path: "channels.wecom.secret",
1238
+ type: "secret",
1239
+ group: "channel",
1240
+ label: "\u4F01\u5FAE\u673A\u5668\u4EBA Secret\uFF08\u957F\u8FDE\u63A5\u4E13\u7528\uFF09",
1241
+ effect: "channel-reconnect",
1242
+ envKey: "WECOM_BOT_SECRET"
1243
+ },
1244
+ {
1245
+ path: "channels.wecom.displayName",
1246
+ type: "string",
1247
+ group: "channel",
1248
+ label: "\u4F01\u5FAE\u673A\u5668\u4EBA\u663E\u793A\u540D\uFF08\u7FA4 @ \u524D\u7F00\u5265\u79BB\u7528\uFF09",
1249
+ effect: "hot"
1250
+ },
1251
+ {
1252
+ path: "channels.wecom.allowedUsers",
1253
+ type: "json",
1254
+ group: "channel",
1255
+ label: "\u4F01\u5FAE\u79C1\u804A\u767D\u540D\u5355\uFF08userid\uFF09",
1256
+ effect: "hot"
1257
+ },
1258
+ {
1259
+ path: "channels.wecom.allowedChats",
1260
+ type: "json",
1261
+ group: "channel",
1262
+ label: "\u4F01\u5FAE\u7FA4\u767D\u540D\u5355\uFF08chatid\uFF09",
1263
+ effect: "hot"
1264
+ },
1265
+ {
1266
+ path: "channels.wecom.textFormat",
1267
+ type: "enum",
1268
+ group: "channel",
1269
+ label: "\u4F01\u5FAE\u6D88\u606F\u683C\u5F0F\uFF08\u4E2A\u4EBA\u5FAE\u4FE1\u4E92\u901A\u9009 text\uFF09",
1270
+ effect: "hot",
1271
+ options: ["markdown", "text"]
1272
+ },
1273
+ {
1274
+ path: "channels.wecom.mergeWindowMs",
1275
+ type: "number",
1276
+ group: "channel",
1277
+ label: "\u4F01\u5FAE\u957F\u6D88\u606F\u5408\u5E76\u7A97\u53E3\uFF08ms\uFF09",
1278
+ effect: "hot"
1279
+ },
1280
+ // whatsapp(1003 Task 9):扫码制通道——**没有凭据格**。配对凭证是扫码得来的设备身份,
1281
+ // 落 stateDir/whatsapp-auth,从不经 config/secrets ⇒ channel-secrets 迁移无需 whatsapp 路径。
1282
+ // 连接态也不走这里(扫码进度看 /api/whatsapp/qr 与 /api/whatsapp/status),面板上声明这三格
1283
+ // 是让通道开关/DM 闸门可见可改。三格全部 hot:channels reload entry 按整块 diff 重建 adapter
1284
+ // (manager.reconcileFromConfig),任何一格变更都会拆旧建新,写完即生效。
1285
+ {
1286
+ path: "channels.whatsapp.enabled",
1287
+ type: "boolean",
1288
+ group: "channel",
1289
+ label: "\u542F\u7528 WhatsApp",
1290
+ effect: "hot"
1291
+ },
1292
+ {
1293
+ path: "channels.whatsapp.dmPolicy",
1294
+ type: "enum",
1295
+ group: "channel",
1296
+ label: "WhatsApp \u79C1\u804A\u7B56\u7565",
1297
+ effect: "hot",
1298
+ options: ["allowlist", "open", "disabled"]
1299
+ },
1300
+ {
1301
+ path: "channels.whatsapp.allowFrom",
1302
+ type: "json",
1303
+ group: "channel",
1304
+ label: "WhatsApp \u767D\u540D\u5355\uFF08E.164 \u53F7\u7801\uFF09",
1305
+ effect: "hot"
1306
+ },
1307
+ // ⚠️ allowFrom 的条目是 **E.164 号码**('+852…')。不是 @lid/jid——@lid 条目会
1308
+ // fail-closed 不匹配(adapter 的 allowFromMatch 两侧归一到 '+digits' 再比),label
1309
+ // 与文档都别写"或 jid",免得用户填了 @lid 还以为在白名单里。
1310
+ {
1311
+ path: "channels.emotion.enabled",
1312
+ type: "boolean",
1313
+ group: "channel",
1314
+ label: "\u60C5\u611F\u6A21\u5F0F",
1315
+ effect: "hot"
1316
+ },
1317
+ {
1318
+ path: "channels.emotion.tools",
1319
+ type: "json",
1320
+ group: "channel",
1321
+ label: "\u60C5\u611F\u6A21\u5F0F\u53EF\u7528\u5DE5\u5177",
1322
+ effect: "hot"
1323
+ },
1324
+ {
1325
+ path: "channels.emotion.liveSystemPrompt.files",
1326
+ type: "json",
1327
+ group: "channel",
1328
+ label: "\u60C5\u611F\u6A21\u5F0F\u52A0\u8F7D\u7684\u6587\u4EF6",
1329
+ effect: "hot"
1330
+ },
1331
+ // === display:渲染层 ===
1332
+ {
1333
+ path: "display.toolOutputMode",
1334
+ type: "enum",
1335
+ group: "display",
1336
+ label: "\u5DE5\u5177\u8F93\u51FA\u65B9\u5F0F",
1337
+ effect: "hot",
1338
+ options: ["expanded", "collapsed"]
1339
+ },
1340
+ {
1341
+ path: "display.thinking.enabled",
1342
+ type: "boolean",
1343
+ group: "display",
1344
+ label: "\u663E\u793A\u601D\u8003\u8FC7\u7A0B",
1345
+ effect: "hot"
1346
+ },
1347
+ {
1348
+ path: "display.thinking.emoji",
1349
+ type: "string",
1350
+ group: "display",
1351
+ label: "\u601D\u8003\u8868\u60C5",
1352
+ effect: "hot"
1353
+ },
1354
+ {
1355
+ path: "display.thinking.maxLen",
1356
+ type: "number",
1357
+ group: "display",
1358
+ label: "\u601D\u8003\u622A\u65AD\u957F\u5EA6",
1359
+ effect: "hot"
1360
+ },
1361
+ {
1362
+ path: "display.toolUse.enabled",
1363
+ type: "boolean",
1364
+ group: "display",
1365
+ label: "\u663E\u793A\u5DE5\u5177\u8C03\u7528",
1366
+ effect: "hot"
1367
+ },
1368
+ {
1369
+ path: "display.toolUse.emoji",
1370
+ type: "string",
1371
+ group: "display",
1372
+ label: "\u5DE5\u5177\u8C03\u7528\u8868\u60C5",
1373
+ effect: "hot"
1374
+ },
1375
+ {
1376
+ path: "display.toolUse.displayMode",
1377
+ type: "enum",
1378
+ group: "display",
1379
+ label: "\u5DE5\u5177\u53C2\u6570\u663E\u793A",
1380
+ effect: "hot",
1381
+ options: ["raw", "summary"]
1382
+ },
1383
+ {
1384
+ path: "display.toolUse.bashDisplayMode",
1385
+ type: "enum",
1386
+ group: "display",
1387
+ label: "\u547D\u4EE4\u663E\u793A\u65B9\u5F0F",
1388
+ effect: "hot",
1389
+ options: ["description", "both"]
1390
+ },
1391
+ {
1392
+ path: "display.toolResult.enabled",
1393
+ type: "boolean",
1394
+ group: "display",
1395
+ label: "\u663E\u793A\u5DE5\u5177\u7ED3\u679C",
1396
+ effect: "hot"
1397
+ },
1398
+ {
1399
+ path: "display.reactions.enabled",
1400
+ type: "boolean",
1401
+ group: "display",
1402
+ label: "\u6D88\u606F\u8868\u60C5\u56DE\u5E94",
1403
+ effect: "hot"
1404
+ },
1405
+ {
1406
+ path: "display.reactions.start",
1407
+ type: "string",
1408
+ group: "display",
1409
+ label: "\u5F00\u59CB\u5904\u7406\u7684\u8868\u60C5",
1410
+ effect: "hot"
1411
+ },
1412
+ {
1413
+ path: "display.reactions.done",
1414
+ type: "string",
1415
+ group: "display",
1416
+ label: "\u5B8C\u6210\u7684\u8868\u60C5",
1417
+ effect: "hot"
1418
+ },
1419
+ {
1420
+ path: "display.reactions.error",
1421
+ type: "string",
1422
+ group: "display",
1423
+ label: "\u51FA\u9519\u7684\u8868\u60C5",
1424
+ effect: "hot"
1425
+ },
1426
+ {
1427
+ path: "display.preview.agentName",
1428
+ type: "string",
1429
+ group: "display",
1430
+ label: "\u9884\u89C8\u91CC\u7684\u540D\u5B57",
1431
+ effect: "hot"
1432
+ },
1433
+ {
1434
+ path: "display.preview.delayMs",
1435
+ type: "number",
1436
+ group: "display",
1437
+ label: "\u60C5\u611F\u8F6E\u9759\u9ED8\u9608\u503C(\u8D85\u65F6\u4EAE\u5361)",
1438
+ effect: "hot"
1439
+ },
1440
+ {
1441
+ path: "display.preview.emotionWaitText",
1442
+ type: "string",
1443
+ group: "display",
1444
+ label: "\u79C1\u804A\u6162\u67E5\u8BE2\u65F6\u81EA\u9009\u7684\u4E00\u53E5\u8BDD",
1445
+ effect: "hot"
1446
+ },
1447
+ {
1448
+ path: "display.typing.enabled",
1449
+ type: "boolean",
1450
+ group: "display",
1451
+ label: "\u6B63\u5728\u8F93\u5165\u63D0\u793A",
1452
+ effect: "hot"
1453
+ },
1454
+ // === session:会话范围 ===
1455
+ // ⚠️ 整段是 restart,不是 hot:SessionManager 在**构造期**整体捕获子对象
1456
+ // (session-manager.ts:92 `this.scopeConfig = config.scopeConfig`,由
1457
+ // engine-startup.ts:284 灌入),而 liveConfig.assign 是浅层 assign(live.ts:30-38
1458
+ // 的立法注释)——reload 之后 scopeConfig 是个**陈旧对象**,全仓没有第二处更新它。
1459
+ // 读点:session-manager.ts:167-168(resolvePlatformKey)。附带的连带读点:
1460
+ // heartbeat.ts:48 / nudge/plugin.ts:96 的 shouldEnable 都拿这个被捕获的 sessions 对象问
1461
+ // 「dmScope 是不是 main」。
1462
+ {
1463
+ path: "session.dmScope",
1464
+ type: "enum",
1465
+ group: "session",
1466
+ label: "\u79C1\u804A\u4F1A\u8BDD\u8303\u56F4",
1467
+ effect: "restart",
1468
+ options: ["per-user", "main"]
1469
+ },
1470
+ {
1471
+ path: "session.groupScope",
1472
+ type: "enum",
1473
+ group: "session",
1474
+ label: "\u7FA4\u804A\u4F1A\u8BDD\u8303\u56F4",
1475
+ effect: "restart",
1476
+ options: ["per-user", "main"]
1477
+ },
1478
+ // === sandbox:文件访问限制 ===
1479
+ {
1480
+ path: "sandbox.mode",
1481
+ type: "enum",
1482
+ group: "sandbox",
1483
+ label: "\u6C99\u7BB1\u6A21\u5F0F",
1484
+ effect: "restart",
1485
+ options: ["off", "on"]
1486
+ },
1487
+ // === feature:功能开关 ===
1488
+ // features.* 不是一类,按**实际语义**拆(翀哥 0925 裁决)。判据来自代码,不是印象:
1489
+ // restart —— 在 tools/features.ts 的 builtInFeatures 里有 setup(),且那个 setup 真的
1490
+ // import/注册工具;setupFeatures() 只在 engine-startup.ts:189 跑**一次**,
1491
+ // 运行时翻转不会卸载已注册的工具(reload orchestrator 里没有 tools/features entry)。
1492
+ // hot —— getFeature()(config/features.ts:31 → liveConfig)在**每次调用**时现读,
1493
+ // 全仓读点只有 4 个 feature 键:topic-extract / topic-recall / autoDream / session-memory
1494
+ // (另加 commands/misc.ts:97 的 /features 展示)。
1495
+ // ⚠️ agentTeams 两边都沾:setup() 注册了 team 工具(→ 卸载要重启),
1496
+ // 同时 isAgentSwarmsEnabled 每次现读(→ 行为闸立即生效)。按「不重启会发生什么」定 restart。
1497
+ // **没有被收进清单的 feature 键**(零读者,写进托盘就是让人改一个没用的值):
1498
+ // memory —— builtInFeatures 的 setup 是空实现,memory_search 由
1499
+ // bootstrap.ts:144 的 registerMemoryTools() 无条件注册;无 getFeature 读点
1500
+ // topics —— 无 setup、无任何读者
1501
+ // processOutput / interrupt / debounceMs —— resolveRequiredTools 里被显式 continue 跳过,
1502
+ // 全仓只有 loader 的 banner 打印读过它们,没有行为消费者
1503
+ // voice / selfie / eyes / calendar —— 对应工具由 engine-startup.ts:65-67 无条件 side-effect
1504
+ // import 注册,这几个 flag 没有任何读者
1505
+ // 🔵 **这 14 项是「内部字段」**(翀哥 0927:「其他里面的 功能开关 隐藏」;同日又拍
1506
+ // 「但是你这个也不用删了,可以隐藏,我们内部自己可以用以后,可以出个调试版内部版」)
1507
+ // —— 声明**都还在**,只是带 `internal: true`、默认不进 `config schema` 的输出
1508
+ // (口径见 ConfigField.internal 与 listSchemaFields())。内部模式下托盘照常拿到它们。
1509
+ // 上面那段分类依据仍然成立、仍然有用(谁有读者、谁是 restart)——内部模式里
1510
+ // effect 照样驱动"要不要提示重启"。
1511
+ //
1512
+ // ⚠️ **其中两个不是能力开关,放出来之前请想一下**:
1513
+ // innerVoice.enabled —— 内心戏;proactive.enabled —— 主动消息
1514
+ // 小柯 review(Q1 第 4 条)点名过:「proactive 开关(主动消息,隐私敏感,
1515
+ // 用户必须能一刀关)」。它们现在只在内部模式下可见 ⇒ **普通用户仍然没有**
1516
+ // 让助手别主动找他的开关(只能让助手自己去改 config,或者手动编辑)。
1517
+ // 哪天真要面向用户放回清单,**优先放的是这两个**,而不是那 12 个能力开关
1518
+ // (那些"小白"确实不该碰:关掉联网、关掉命令执行,助手当场残废,而用户不知道为什么)。
1519
+ {
1520
+ path: "agents.defaults.features.filesystem",
1521
+ type: "boolean",
1522
+ group: "feature",
1523
+ label: "\u6587\u4EF6\u8BFB\u5199",
1524
+ effect: "restart",
1525
+ internal: true
1526
+ },
1527
+ {
1528
+ path: "agents.defaults.features.shell",
1529
+ type: "boolean",
1530
+ group: "feature",
1531
+ label: "\u547D\u4EE4\u6267\u884C",
1532
+ effect: "restart",
1533
+ internal: true
1534
+ },
1535
+ {
1536
+ path: "agents.defaults.features.webSearch",
1537
+ type: "boolean",
1538
+ group: "feature",
1539
+ label: "\u8054\u7F51\u641C\u7D22",
1540
+ effect: "restart",
1541
+ internal: true
1542
+ },
1543
+ {
1544
+ path: "agents.defaults.features.webFetch",
1545
+ type: "boolean",
1546
+ group: "feature",
1547
+ label: "\u7F51\u9875\u6293\u53D6",
1548
+ effect: "restart",
1549
+ internal: true
1550
+ },
1551
+ {
1552
+ path: "agents.defaults.features.installer",
1553
+ type: "boolean",
1554
+ group: "feature",
1555
+ label: "\u6280\u80FD/MCP \u5B89\u88C5",
1556
+ effect: "restart",
1557
+ internal: true
1558
+ },
1559
+ {
1560
+ path: "agents.defaults.features.cron",
1561
+ type: "boolean",
1562
+ group: "feature",
1563
+ label: "\u5B9A\u65F6\u4EFB\u52A1",
1564
+ effect: "restart",
1565
+ internal: true
1566
+ },
1567
+ {
1568
+ path: "agents.defaults.features.agent",
1569
+ type: "boolean",
1570
+ group: "feature",
1571
+ label: "\u5B50 Agent",
1572
+ effect: "restart",
1573
+ internal: true
1574
+ },
1575
+ {
1576
+ path: "agents.defaults.features.agentTeams",
1577
+ type: "boolean",
1578
+ group: "feature",
1579
+ label: "Agent \u56E2\u961F",
1580
+ effect: "restart",
1581
+ internal: true
1582
+ },
1583
+ {
1584
+ path: "agents.defaults.features.todo",
1585
+ type: "boolean",
1586
+ group: "feature",
1587
+ label: "\u4EFB\u52A1\u5217\u8868",
1588
+ effect: "restart",
1589
+ internal: true
1590
+ },
1591
+ {
1592
+ path: "agents.defaults.features.topic-extract",
1593
+ type: "boolean",
1594
+ group: "feature",
1595
+ label: "\u8BDD\u9898\u63D0\u53D6",
1596
+ effect: "hot",
1597
+ internal: true
1598
+ },
1599
+ {
1600
+ path: "agents.defaults.features.topic-recall",
1601
+ type: "boolean",
1602
+ group: "feature",
1603
+ label: "\u8BDD\u9898\u53EC\u56DE",
1604
+ effect: "hot",
1605
+ internal: true
1606
+ },
1607
+ {
1608
+ path: "agents.defaults.features.autoDream",
1609
+ type: "boolean",
1610
+ group: "feature",
1611
+ label: "\u8BB0\u5FC6\u6574\u5408",
1612
+ effect: "hot",
1613
+ internal: true
1614
+ },
1615
+ {
1616
+ path: "agents.defaults.features.session-memory",
1617
+ type: "boolean",
1618
+ group: "feature",
1619
+ label: "\u4F1A\u8BDD\u7B14\u8BB0",
1620
+ effect: "hot",
1621
+ internal: true
1622
+ },
1623
+ {
1624
+ path: "innerVoice.enabled",
1625
+ type: "boolean",
1626
+ group: "feature",
1627
+ label: "\u5185\u5FC3\u620F",
1628
+ effect: "hot",
1629
+ internal: true
1630
+ },
1631
+ {
1632
+ path: "innerVoice.serviceSuggestions.enabled",
1633
+ type: "boolean",
1634
+ group: "feature",
1635
+ label: "\u4E3B\u52A8\u5E2E\u5FD9\u5EFA\u8BAE",
1636
+ effect: "hot",
1637
+ internal: true
1638
+ },
1639
+ {
1640
+ path: "innerVoice.serviceSuggestions.delivery",
1641
+ type: "json",
1642
+ group: "feature",
1643
+ label: "\u4E3B\u52A8\u5E2E\u5FD9\u6295\u9012\u901A\u9053",
1644
+ effect: "hot",
1645
+ internal: true,
1646
+ validate: (value) => {
1647
+ if (value == null) return null;
1648
+ if (typeof value !== "object" || !("channel" in value) || !("target" in value)) return "\u987B\u63D0\u4F9Bchannel\u548Ctarget";
1649
+ return typeof value.channel === "string" && value.channel.trim() && typeof value.target === "string" && value.target.trim() ? null : "\u987B\u63D0\u4F9Bchannel\u548Ctarget";
1650
+ }
1651
+ },
1652
+ {
1653
+ path: "innerVoice.maxTokens",
1654
+ type: "number",
1655
+ group: "feature",
1656
+ label: "\u5FF5\u5934\u8F93\u51FA\u9884\u7B97",
1657
+ effect: "hot",
1658
+ internal: true,
1659
+ validate: (value) => Number.isSafeInteger(value) && value > 0 ? null : "\u987B\u4E3A\u6B63\u6574\u6570"
1660
+ },
1661
+ {
1662
+ path: "proactive.enabled",
1663
+ type: "boolean",
1664
+ group: "feature",
1665
+ label: "\u4E3B\u52A8\u6D88\u606F",
1666
+ effect: "hot",
1667
+ internal: true
1668
+ },
1669
+ {
1670
+ path: "mem7.turnReadBudgetMs",
1671
+ type: "number",
1672
+ group: "feature",
1673
+ label: "\u6BCF\u8F6E\u8BB0\u5FC6\u8BFB\u53D6\u65F6\u95F4\u4E0A\u9650",
1674
+ effect: "hot",
1675
+ internal: true,
1676
+ validate: (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= 5e3 ? null : "\u6BCF\u8F6E\u8BB0\u5FC6\u8BFB\u53D6\u65F6\u95F4\u987B\u4E3A 1\u20135000 \u6BEB\u79D2"
1677
+ },
1678
+ {
1679
+ path: "mem7.turnReadMaxSteps",
1680
+ type: "number",
1681
+ group: "feature",
1682
+ label: "\u6BCF\u8F6E\u8BB0\u5FC6\u8BFB\u53D6\u64CD\u4F5C\u4E0A\u9650",
1683
+ effect: "hot",
1684
+ internal: true,
1685
+ // 上限必须 ≥ 代码默认值 250_000(1012 抬默认时漏了这里,导致托盘/CLI 拒收代码自己的默认值)
1686
+ validate: (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= 5e5 ? null : "\u6BCF\u8F6E\u8BB0\u5FC6\u8BFB\u53D6\u64CD\u4F5C\u987B\u4E3A 1\u2013500000 \u6B21"
1687
+ },
1688
+ {
1689
+ path: "mem7.graphReasoning",
1690
+ type: "boolean",
1691
+ group: "feature",
1692
+ label: "\u6BCF\u4E8B\u4EF6\u56FE\u63A8\u7406",
1693
+ effect: "hot",
1694
+ internal: true,
1695
+ // 1015 默认关:everos 从不逐事件推理,实测计划多数无效纯烧钱。true 重开(episode 级批次设计另议)
1696
+ validate: (value) => typeof value === "boolean" ? null : "\u987B\u4E3A\u5E03\u5C14\u503C"
1697
+ },
1698
+ {
1699
+ path: "mem7.projection",
1700
+ type: "boolean",
1701
+ group: "feature",
1702
+ label: "\u8BB0\u5FC6\u53D8\u66F4\u6295\u9012\u8FDB\u56FE",
1703
+ effect: "hot",
1704
+ internal: true,
1705
+ // 默认开:有界投递接通 mem7 → proactive。false 暂停,保留 outbox 水位供恢复续传。
1706
+ validate: (value) => typeof value === "boolean" ? null : "\u987B\u4E3A\u5E03\u5C14\u503C"
1707
+ },
1708
+ {
1709
+ path: "mem7.relationshipCognition",
1710
+ type: "boolean",
1711
+ group: "feature",
1712
+ label: "\u4EBA\u7269\u5173\u7CFB\u8BA4\u77E5",
1713
+ effect: "hot",
1714
+ internal: true,
1715
+ // 默认开。false = 跳过 cognition 相位(它是关系通知的唯一供料源,停了通知会随存量清完而静默)
1716
+ validate: (value) => typeof value === "boolean" ? null : "\u987B\u4E3A\u5E03\u5C14\u503C"
1717
+ },
1718
+ {
1719
+ path: "mem7.relationships",
1720
+ type: "json",
1721
+ group: "feature",
1722
+ label: "\u4EBA\u7269\u5173\u7CFB\u8BFB\u53D6\u9884\u7B97",
1723
+ effect: "hot",
1724
+ internal: true,
1725
+ validate: (value) => {
1726
+ if (!value || typeof value !== "object" || Array.isArray(value)) return "\u4EBA\u7269\u5173\u7CFB\u9884\u7B97\u5FC5\u987B\u662F\u5BF9\u8C61";
1727
+ const bounds = { maxHops: [0, 8], maxNodes: [1, 1e3], maxTokens: [512, 64e3], maxExplorations: [0, 2], maxActive: [1, 1e3] };
1728
+ for (const [key, range] of Object.entries(bounds)) {
1729
+ const number = value[key];
1730
+ if (number !== void 0 && (typeof number !== "number" || !Number.isSafeInteger(number) || number < range[0] || number > range[1])) {
1731
+ return `${key} \u5FC5\u987B\u662F ${range[0]} \u5230 ${range[1]} \u7684\u6574\u6570`;
1732
+ }
1733
+ }
1734
+ return null;
1735
+ }
1736
+ },
1737
+ // === prompt:系统提示词组装 ===
1738
+ // 🔵 三项都是**内部字段**(翀哥 0927:「提示词 隐藏」+「隐藏就行」)。
1739
+ // 为什么不给普通用户:`staticFiles`(静态文件清单)与 `order`(注入顺序)是**引擎内部的
1740
+ // 提示词管线**,改错会直接把提示词拼坏;`mode`(standard/custom)听着无害,
1741
+ // 但没有配套的编辑 custom 提示词的 UI,用户切过去只会看到行为变了却无从下手。
1742
+ // 目标用户是"装完就用"的人 ⇒ 普通模式不给,内部模式照常。
1743
+ //
1744
+ // 三项一律 hot —— 实证不是"看着像运行时读的":createPromptGetters 的 getSystemStable
1745
+ // 每次请求都 `liveConfig.get('prompt')`(startup/prompt-config.ts:51),指纹里带着
1746
+ // mode / order / staticFiles 及各文件 mtime,变了才重建(:52-70)。
1747
+ {
1748
+ path: "prompt.mode",
1749
+ type: "enum",
1750
+ group: "prompt",
1751
+ label: "\u63D0\u793A\u8BCD\u6A21\u5F0F",
1752
+ effect: "hot",
1753
+ options: ["standard", "custom"],
1754
+ internal: true
1755
+ },
1756
+ {
1757
+ path: "prompt.staticFiles",
1758
+ type: "json",
1759
+ group: "prompt",
1760
+ label: "\u9759\u6001\u6587\u4EF6\u6E05\u5355",
1761
+ effect: "hot",
1762
+ internal: true
1763
+ },
1764
+ {
1765
+ path: "prompt.order",
1766
+ type: "json",
1767
+ group: "prompt",
1768
+ label: "\u6CE8\u5165\u987A\u5E8F",
1769
+ effect: "hot",
1770
+ internal: true
1771
+ },
1772
+ {
1773
+ path: "prompt.rules.enabled",
1774
+ type: "boolean",
1775
+ group: "prompt",
1776
+ label: "\u52A0\u8F7D\u901A\u7528\u89C4\u5219",
1777
+ effect: "hot",
1778
+ internal: true
1779
+ },
1780
+ // === compaction:上下文压缩 ===
1781
+ // 🔵 八项都是**内部字段**(翀哥 0927:「compaction 不要给用户配也不要展示给用户,
1782
+ // 安装器搞的都是小白」+「隐藏就行」)。理由:这八项是 token 调参(bufferTokens /
1783
+ // maxOutputTokens / minReductionRatio)、内部字段名清单(ruleBased.essentialFields)、
1784
+ // 字节阈值(forceFlushTranscriptBytes)—— 目标用户是「装完就用」的人,
1785
+ // **没有依据填这些**,而填错的后果(压缩不触发、或压缩过狠把历史丢了)又是不可见的。
1786
+ //
1787
+ // 除 memoryFlush.* 外都是 hot:createCompactGetters 的 getCompactConfig 每次调用
1788
+ // 现读 liveConfig.get('compaction')(startup/prompt-config.ts 的 getCompactConfig),
1789
+ // 引擎每 turn 刷新(core/query.ts:312-316)⇒ enabled / bufferTokens / maxOutputTokens /
1790
+ // minReductionRatio / ruleBased.* 都实时生效。
1791
+ {
1792
+ path: "compaction.enabled",
1793
+ type: "boolean",
1794
+ group: "compaction",
1795
+ label: "\u81EA\u52A8\u538B\u7F29",
1796
+ effect: "hot",
1797
+ internal: true
1798
+ },
1799
+ {
1800
+ path: "compaction.background",
1801
+ type: "boolean",
1802
+ group: "compaction",
1803
+ label: "\u540E\u53F0\u538B\u7F29",
1804
+ effect: "hot",
1805
+ internal: true
1806
+ },
1807
+ {
1808
+ path: "compaction.keepRecentTokens",
1809
+ type: "number",
1810
+ group: "compaction",
1811
+ label: "\u8FD1\u671F\u4E0A\u4E0B\u6587\u4FDD\u7559",
1812
+ effect: "hot",
1813
+ internal: true
1814
+ },
1815
+ {
1816
+ path: "compaction.bufferTokens",
1817
+ type: "number",
1818
+ group: "compaction",
1819
+ label: "\u538B\u7F29\u7F13\u51B2 token",
1820
+ effect: "hot",
1821
+ internal: true
1822
+ },
1823
+ {
1824
+ path: "compaction.maxOutputTokens",
1825
+ type: "number",
1826
+ group: "compaction",
1827
+ label: "\u538B\u7F29\u8F93\u51FA\u4E0A\u9650",
1828
+ effect: "hot",
1829
+ internal: true
1830
+ },
1831
+ {
1832
+ path: "compaction.minReductionRatio",
1833
+ type: "number",
1834
+ group: "compaction",
1835
+ label: "\u6700\u5C0F\u538B\u7F29\u6BD4",
1836
+ effect: "hot",
1837
+ internal: true
1838
+ },
1839
+ {
1840
+ path: "compaction.ruleBased.enabled",
1841
+ type: "boolean",
1842
+ group: "compaction",
1843
+ label: "\u89C4\u5219\u538B\u7F29",
1844
+ effect: "hot",
1845
+ internal: true
1846
+ },
1847
+ {
1848
+ path: "compaction.ruleBased.essentialFields",
1849
+ type: "json",
1850
+ group: "compaction",
1851
+ label: "\u89C4\u5219\u538B\u7F29\u4FDD\u7559\u5B57\u6BB5",
1852
+ effect: "hot",
1853
+ internal: true
1854
+ },
1855
+ // ⚠️ memoryFlush 这两格是 restart,尽管它们在同一段里(0927 复核过一次,别再标错):
1856
+ // 启动期就被解成**裸值**塞进 SessionManager 的构造参数(startup/prompt-config.ts:105-108 解
1857
+ // → engine-startup.ts:233 解构 → :286-287 注入 archiveThreshold / memoryFlushEnabled),
1858
+ // 此后只在 session-manager.ts:244,247 的 `this.config.*` 读**那份快照**——
1859
+ // getCompactConfig 那条实时链路不覆盖它们(它的 cfg 里 forceFlushTranscriptBytes
1860
+ // 取的是闭包变量、不是 liveConfig)。标 hot 的后果是托盘写完后 needsRestart 为空
1861
+ // ⇒ 静默不生效。
1862
+ {
1863
+ path: "compaction.memoryFlush.enabled",
1864
+ type: "boolean",
1865
+ group: "compaction",
1866
+ label: "\u5386\u53F2\u5F52\u6863",
1867
+ effect: "restart",
1868
+ internal: true
1869
+ },
1870
+ {
1871
+ path: "compaction.memoryFlush.forceFlushTranscriptBytes",
1872
+ type: "string",
1873
+ group: "compaction",
1874
+ label: "\u5F52\u6863\u9608\u503C",
1875
+ effect: "restart",
1876
+ internal: true
1877
+ },
1878
+ // === skills:技能目录 ===
1879
+ {
1880
+ path: "skills.enabled",
1881
+ type: "boolean",
1882
+ group: "skills",
1883
+ label: "\u542F\u7528\u6280\u80FD",
1884
+ effect: "restart"
1885
+ },
1886
+ {
1887
+ path: "skills.path",
1888
+ type: "path",
1889
+ group: "skills",
1890
+ label: "\u6280\u80FD\u76EE\u5F55",
1891
+ effect: "restart"
1892
+ },
1893
+ // === face:静态自拍 ===
1894
+ {
1895
+ path: "tools.my_selfie",
1896
+ type: "json",
1897
+ group: "face",
1898
+ label: "\u81EA\u62CD\u5F62\u8C61",
1899
+ effect: "hot",
1900
+ migration: "portrait"
1901
+ },
1902
+ // === email:邮箱托管(1010 预装邮件 skill;凭证只落本机 config 文件——skill 每次
1903
+ // 直读文件、引擎不消费,故 hot;.env 是妹妹存量兼容路径,托盘不感知)===
1904
+ {
1905
+ path: "auth.brokerUrl",
1906
+ type: "string",
1907
+ group: "api",
1908
+ label: "\u670D\u52A1\u6388\u6743\u5165\u53E3",
1909
+ effect: "hot",
1910
+ validate: (value) => {
1911
+ try {
1912
+ brokerBase(String(value));
1913
+ return null;
1914
+ } catch {
1915
+ return "\u987B\u4E3A HTTPS \u6388\u6743\u5165\u53E3";
1916
+ }
1917
+ }
1918
+ },
1919
+ // 1119:引擎侧 Gmail 读信的 scoped 代理出口(只作用于 GmailClient→gmail.googleapis.com,
1920
+ // broker 不走它)。Mac 直连被墙的机器配本机代理即可;不配=维持直连行为。
1921
+ { path: "auth.gmailProxy", type: "string", group: "api", label: "Gmail \u51FA\u53E3\u4EE3\u7406", effect: "hot" },
1922
+ {
1923
+ path: "tools.email",
1924
+ type: "json",
1925
+ group: "email",
1926
+ label: "\u90AE\u7BB1\u6258\u7BA1",
1927
+ effect: "hot",
1928
+ knownValues: {
1929
+ // 分级闸三档(设计 docs/superpowers/specs/2026-10-10-installer-email-skill-design.md §3.2)
1930
+ sendPolicy: ["tiered", "confirm-all", "auto"]
1931
+ }
1932
+ },
1933
+ // === voice:声音(两条独立链路,别混:tools.my_voice = 发语音条;
1934
+ // voiceChat.* = 实时语音对话,进程不归引擎管 → external-service)===
1935
+ {
1936
+ path: "tools.my_voice",
1937
+ type: "json",
1938
+ group: "voice",
1939
+ label: "\u6211\u7684\u58F0\u97F3",
1940
+ effect: "hot",
1941
+ migration: "voice-config",
1942
+ knownValues: {
1943
+ // ⚠️ **派生,不是并列的第二份清单**——手写数组 = 同一清单两处定义,
1944
+ // 加第六支时漏改一处就是「引擎加了、托盘下拉里没有」,不报错也看不见。
1945
+ provider: TTS_PROVIDERS.map((p) => p.id),
1946
+ // 这份是**纯配置枚举、没有实体表**,手写合理 —— 但此处是它的唯一源。
1947
+ billingMode: ["off", "custom-only", "all"]
1948
+ },
1949
+ knownValuesByProvider: {
1950
+ // ⚠️ **派生,不是并列的第二份清单** —— 与上面 knownValues.provider 同一条纪律。
1951
+ // 手写数组 = 同一清单两处定义,加音色时漏改一处就是「引擎加了、下拉里没有」。
1952
+ voice: { relay: [...RELAY_VOICES] }
1953
+ },
1954
+ valueKeys: {
1955
+ // 每个 provider 读哪些子键 —— 托盘靠它决定行显隐与切换清理,
1956
+ // 同样**派生**(托盘看不到 TTS_PROVIDERS,这份数据只能经 schema 出去)
1957
+ provider: Object.fromEntries(TTS_PROVIDERS.map((p) => [p.id, [...p.requiredKeys]]))
1958
+ }
1959
+ },
1960
+ // 🔵 `voiceChat.*` 那四格是**内部字段**。翀哥 0927:「voiceChat 隐藏,以后售卖的时候
1961
+ // 再说。你内部可以留位。」+「隐藏就行」。
1962
+ //
1963
+ // 以前把它们声明给所有用户时,托盘只能**只读展示** + 写一句「归后续版本」—— 对用户是
1964
+ // 纯噪音(半屏不可操作的东西 + 一个他调不了的端口)。以后真做「实时语音对话」这个售卖点,
1965
+ // **连 UI 一起设计**,别只把这几格摆出来。
1966
+ //
1967
+ // ⚠️ effect 一律 `external-service`(0927 复核):那个 Python 进程不归引擎管
1968
+ // (optional/voice-chat/plugin.ts 头注:spawnPython 0925 已删,引擎手里没有那个进程的
1969
+ // 句柄)。`pythonPort` 唯一的读者是 commands/stop.ts:44-47,而且读的是 `deps.config`
1970
+ // 那份**启动快照**——就算标 restart 也修不出"引擎自己能让它生效"这件事,改端口要动的是
1971
+ // 那个服务自己的配置。**别标 hot / restart**:那会给出误导性的重启提示。
1972
+ {
1973
+ path: "voiceChat.pythonPort",
1974
+ type: "number",
1975
+ group: "voice",
1976
+ label: "\u8BED\u97F3\u670D\u52A1\u7AEF\u53E3",
1977
+ effect: "external-service",
1978
+ internal: true
1979
+ },
1980
+ {
1981
+ path: "voiceChat.tts",
1982
+ type: "json",
1983
+ group: "voice",
1984
+ label: "\u5B9E\u65F6\u8BED\u97F3\u5408\u6210",
1985
+ effect: "external-service",
1986
+ internal: true
1987
+ },
1988
+ {
1989
+ path: "voiceChat.local",
1990
+ type: "json",
1991
+ group: "voice",
1992
+ label: "\u672C\u5730\u8BED\u97F3\u670D\u52A1",
1993
+ effect: "external-service",
1994
+ internal: true
1995
+ },
1996
+ {
1997
+ path: "voiceChat.avatar",
1998
+ type: "json",
1999
+ group: "voice",
2000
+ label: "\u6570\u5B57\u4EBA\u5F62\u8C61",
2001
+ effect: "external-service",
2002
+ internal: true
2003
+ },
2004
+ // === onboarding:装机主动欢迎 + 每日小功能推送(1029)===
2005
+ // 读点全在 src/onboarding/plugin.ts:每次检查都 liveConfig.get() 现读,且子系统注册了
2006
+ // reloadOrchestrator entry(startup/subsystems.ts)按切片重建 ⇒ 全部 hot。
2007
+ // 为什么放出来不 internal:这是"助理主动给用户发消息"的一类(和 proactive 同隐私敏感级),
2008
+ // 用户必须能一刀关(见上面 feature 段小柯 review 的同类口径)——藏起来就没有退出口了。
2009
+ {
2010
+ path: "onboarding.welcome.enabled",
2011
+ type: "boolean",
2012
+ group: "onboarding",
2013
+ label: "\u65B0\u7528\u6237\u4E3B\u52A8\u6B22\u8FCE",
2014
+ effect: "hot"
2015
+ },
2016
+ {
2017
+ path: "onboarding.tips.enabled",
2018
+ type: "boolean",
2019
+ group: "onboarding",
2020
+ label: "\u6BCF\u65E5\u5C0F\u529F\u80FD\u63A8\u9001",
2021
+ effect: "hot"
2022
+ },
2023
+ {
2024
+ path: "onboarding.tips.days",
2025
+ type: "number",
2026
+ group: "onboarding",
2027
+ label: "\u5C0F\u529F\u80FD\u63A8\u9001\u5929\u6570",
2028
+ effect: "hot"
2029
+ },
2030
+ {
2031
+ path: "onboarding.quietStartHour",
2032
+ type: "number",
2033
+ group: "onboarding",
2034
+ label: "\u514D\u6253\u6270\u5F00\u59CB\uFF08\u70B9\uFF0C\u9ED8\u8BA4 21\uFF09",
2035
+ effect: "hot"
2036
+ },
2037
+ {
2038
+ path: "onboarding.quietEndHour",
2039
+ type: "number",
2040
+ group: "onboarding",
2041
+ label: "\u514D\u6253\u6270\u7ED3\u675F\uFF08\u70B9\uFF0C\u9ED8\u8BA4 9\uFF09",
2042
+ effect: "hot"
2043
+ }
2044
+ ];
2045
+ }
2046
+ });
2047
+
2048
+ // src/config/emotion-tools.defaults.json
2049
+ var emotion_tools_defaults_default;
2050
+ var init_emotion_tools_defaults = __esm({
2051
+ "src/config/emotion-tools.defaults.json"() {
2052
+ emotion_tools_defaults_default = [
2053
+ "msg_send",
2054
+ "media_send",
2055
+ "my_voice",
2056
+ "my_selfie",
2057
+ "my_eyes",
2058
+ "chat_history",
2059
+ "chan7_suggest",
2060
+ "chan7_discovery",
2061
+ "tracking_goal",
2062
+ "device_data",
2063
+ "read",
2064
+ "edit",
2065
+ "write",
2066
+ "glob",
2067
+ "grep",
2068
+ "calendar",
2069
+ "web_search",
2070
+ "web_fetch",
2071
+ "exec",
2072
+ "memory_search",
2073
+ "memory_get",
2074
+ "memory_write",
2075
+ "memory_correct",
2076
+ "memory_delete",
2077
+ "memory_status",
2078
+ "memory_retry",
2079
+ "memory_entity_confirm",
2080
+ "memory_identity_resolve",
2081
+ "memory_identity_redirect",
2082
+ "memory_people_update",
2083
+ "Skill",
2084
+ "load_missing_tools"
2085
+ ];
2086
+ }
2087
+ });
2088
+
2089
+ // src/config/emotion-tools.ts
2090
+ function defaultEmotionTools() {
2091
+ return [...emotion_tools_defaults_default];
2092
+ }
2093
+ var init_emotion_tools = __esm({
2094
+ "src/config/emotion-tools.ts"() {
2095
+ "use strict";
2096
+ init_emotion_tools_defaults();
2097
+ }
2098
+ });
2099
+
2100
+ // src/config/context-window-policy.ts
2101
+ var DEFAULT_CONTEXT_WINDOW, CONTEXT_WINDOW_MIGRATION_VERSION;
2102
+ var init_context_window_policy = __esm({
2103
+ "src/config/context-window-policy.ts"() {
2104
+ "use strict";
2105
+ DEFAULT_CONTEXT_WINDOW = 35e4;
2106
+ CONTEXT_WINDOW_MIGRATION_VERSION = 2;
2107
+ }
2108
+ });
2109
+
2110
+ // src/cli-init-config.ts
2111
+ var cli_init_config_exports = {};
2112
+ __export(cli_init_config_exports, {
2113
+ DEFAULT_FREE_VOICE: () => DEFAULT_FREE_VOICE,
2114
+ DEFAULT_PRIMARY_MODEL: () => DEFAULT_PRIMARY_MODEL,
2115
+ EXTRACT_COOLDOWN_MINUTES: () => EXTRACT_COOLDOWN_MINUTES,
2116
+ FREE_TIER_EMB_MODEL: () => FREE_TIER_EMB_MODEL,
2117
+ FREE_TIER_EMB_REF: () => FREE_TIER_EMB_REF,
2118
+ FREE_TIER_FAST_MODEL: () => FREE_TIER_FAST_MODEL,
2119
+ FREE_TIER_FAST_REF: () => FREE_TIER_FAST_REF,
2120
+ FREE_TIER_NORT_MODEL: () => FREE_TIER_NORT_MODEL,
2121
+ FREE_TIER_NORT_REF: () => FREE_TIER_NORT_REF,
2122
+ FREE_TIER_PROVIDER_ID: () => FREE_TIER_PROVIDER_ID,
2123
+ FREE_TIER_RELAY_URL: () => FREE_TIER_RELAY_URL,
2124
+ LEGACY_FREE_TIER_RELAY_URL: () => LEGACY_FREE_TIER_RELAY_URL,
2125
+ MEM7_RERANK_REF: () => MEM7_RERANK_REF,
2126
+ MODEL_CHOICES: () => MODEL_CHOICES,
2127
+ PLAYWRIGHT_MCP_ENTRY: () => PLAYWRIGHT_MCP_ENTRY,
2128
+ PROVIDER_DEFS: () => PROVIDER_DEFS,
2129
+ SCHEMA_VERSION: () => SCHEMA_VERSION,
2130
+ TEMPLATE_VALUES: () => TEMPLATE_VALUES,
2131
+ VISION_CAPABLE: () => VISION_CAPABLE,
2132
+ envKeyOf: () => envKeyOf,
2133
+ freeTierVoiceConfig: () => freeTierVoiceConfig,
2134
+ generateConfig: () => generateConfig,
2135
+ generateProviderConfig: () => generateProviderConfig,
2136
+ isFreeTier: () => isFreeTier,
2137
+ mem7ServiceDefaults: () => mem7ServiceDefaults,
2138
+ menuProviderOf: () => menuProviderOf,
2139
+ renderConfigTemplate: () => renderConfigTemplate,
2140
+ resolveProviderTarget: () => resolveProviderTarget,
2141
+ resolveRelayUrl: () => resolveRelayUrl,
2142
+ resolveVideoModel: () => resolveVideoModel,
2143
+ resolveVisionModel: () => resolveVisionModel,
2144
+ secretRef: () => secretRef,
2145
+ videoOf: () => videoOf,
2146
+ visionOf: () => visionOf
2147
+ });
2148
+ import * as path3 from "node:path";
2149
+ function envKeyOf(dotPath) {
2150
+ const k = getField(dotPath)?.envKey;
2151
+ if (!k) throw new Error(`[init] \u6CE8\u518C\u8868\u6CA1\u7ED9 ${dotPath} \u58F0\u660E envKey\u2014\u2014\u51ED\u636E\u5199\u4E0D\u8FDB secrets`);
2152
+ return k;
2153
+ }
2154
+ function secretRef(envKey, value) {
2155
+ const v = (value || "").trim();
2156
+ if (!v) return "";
2157
+ if (/^(?:env:|{{\s*)[A-Z0-9_]+(?:\s*}})?$/.test(v)) return v;
2158
+ return `env:${envKey}`;
2159
+ }
2160
+ function isFreeTier(v) {
2161
+ return v.freeTier === true || v.primaryProvider === "7yi";
2162
+ }
2163
+ function mem7ServiceDefaults(mem7, legacyRerank) {
2164
+ if (mem7?.enabled === false) return {};
2165
+ return {
2166
+ ...mem7?.embedding == null ? { embedding: { model: FREE_TIER_EMB_REF } } : {},
2167
+ ...mem7?.rerank == null && legacyRerank == null ? { rerank: { model: MEM7_RERANK_REF } } : {}
2168
+ };
2169
+ }
2170
+ function freeTierVoiceConfig(existing) {
2171
+ const mv = existing && typeof existing === "object" ? existing : {};
2172
+ return {
2173
+ ...mv,
2174
+ provider: "relay",
2175
+ relayProviderId: FREE_TIER_PROVIDER_ID,
2176
+ relayModel: "engine7-tts",
2177
+ voice: mv.voice || DEFAULT_FREE_VOICE
2178
+ };
2179
+ }
2180
+ function resolveRelayUrl(relayArg, env = process.env) {
2181
+ return (relayArg || "").trim() || (env.E7_RELAY_URL || "").trim() || FREE_TIER_RELAY_URL;
2182
+ }
2183
+ function modelIdOf(ref) {
2184
+ const i = ref.indexOf("/");
2185
+ return i >= 0 ? ref.slice(i + 1) : ref;
2186
+ }
2187
+ function menuProviderOf(providerId2) {
2188
+ return PROVIDER_DEFS[providerId2] ? providerId2 : "custom";
2189
+ }
2190
+ function resolveProviderTarget(input) {
2191
+ const isCustom = !PROVIDER_DEFS[input.menuProvider];
2192
+ const providerId2 = isCustom ? (input.customProviderId || "").trim() || "custom" : input.menuProvider;
2193
+ const rawRef = (input.modelRef || "").trim();
2194
+ const modelId = (rawRef.includes("/") ? modelIdOf(rawRef) : rawRef) || (input.modelId || "").trim();
2195
+ return { providerId: providerId2, modelId, modelRef: modelId ? `${providerId2}/${modelId}` : "" };
2196
+ }
2197
+ function visionOf(ref, catalog) {
2198
+ const hit = catalog?.find((m) => m.id === modelIdOf(ref));
2199
+ if (hit && typeof hit.vision === "boolean") return hit.vision;
2200
+ return VISION_CAPABLE[ref];
2201
+ }
2202
+ function builtinVisionModels(providerId2) {
2203
+ const def = PROVIDER_DEFS[providerId2];
2204
+ if (!def) return [];
2205
+ return def.models.filter((m) => (m.input || []).includes("image")).map((m) => `${providerId2}/${m.id}`);
2206
+ }
2207
+ function resolveVisionModel(providerId2, primaryModel, catalog) {
2208
+ if (visionOf(primaryModel, catalog) !== false) return primaryModel;
2209
+ const candidates = catalog?.length ? catalog.filter((m) => m.vision === true).map((m) => `${providerId2}/${m.id}`) : builtinVisionModels(providerId2);
2210
+ return candidates[0] || "";
2211
+ }
2212
+ function videoOf(ref, catalog) {
2213
+ const hit = catalog?.find((m) => m.id === modelIdOf(ref));
2214
+ if (hit && typeof hit.video === "boolean") return hit.video;
2215
+ const builtin = builtinModelOf(ref);
2216
+ if (builtin && Array.isArray(builtin.input)) return builtin.input.includes("video");
2217
+ return void 0;
2218
+ }
2219
+ function builtinModelOf(ref) {
2220
+ const def = PROVIDER_DEFS[ref.split("/")[0]];
2221
+ if (!def) return void 0;
2222
+ return def.models.find((m) => m.id === modelIdOf(ref));
2223
+ }
2224
+ function resolveVideoModel(providerId2, primaryModel, catalog) {
2225
+ if (videoOf(primaryModel, catalog) !== false) return primaryModel;
2226
+ const candidates = catalog?.length ? catalog.filter((m) => m.video === true).map((m) => `${providerId2}/${m.id}`) : (PROVIDER_DEFS[providerId2]?.models || []).filter((m) => (m.input || []).includes("video")).map((m) => `${providerId2}/${m.id}`);
2227
+ return candidates[0] || "";
2228
+ }
2229
+ function renderConfigTemplate() {
2230
+ return JSON.stringify(generateConfig(TEMPLATE_VALUES), null, 2) + "\n";
2231
+ }
2232
+ function generateProviderConfig(v) {
2233
+ if (!PROVIDER_DEFS[v.primaryProvider]) {
2234
+ const models = v.existingModels?.length ? [...v.existingModels] : [];
2235
+ const customModelId = v.customModelId || models[0]?.id || modelIdOf(v.primaryModel);
2236
+ if (!customModelId) {
2237
+ throw new Error(
2238
+ `\u81EA\u5B9A\u4E49 provider "${v.primaryProvider}" \u6CA1\u6709\u6A21\u578B id\u2014\u2014init \u751F\u6210\u4E0D\u51FA\u53EF\u7528\u7684 config\u3002\u8BF7\u5728\u5411\u5BFC\u91CC\u586B\u300C\u6A21\u578B ID\u300D\uFF0C\u6216\u8865\u4E0A configs/main7.json \u91CC models.providers.${v.primaryProvider}.models[0].id\u3002`
2239
+ );
2240
+ }
2241
+ if (models.length && !models.some((m) => m?.id === customModelId)) {
2242
+ models.unshift({ id: customModelId, name: customModelId, reasoning: false, input: CUSTOM_DEFAULT_INPUT, contextWindow: 2e5, maxTokens: 8192 });
2243
+ }
2244
+ return {
2245
+ baseUrl: (v.customBaseUrl || "").trim(),
2246
+ api: v.customApi,
2247
+ apiKey: "env:" + v.primaryProvider.toUpperCase().replace(/[^A-Z0-9_]/g, "_") + "_API_KEY",
2248
+ models: models.length ? models : [
2249
+ { id: customModelId, name: customModelId, reasoning: false, input: CUSTOM_DEFAULT_INPUT, contextWindow: 2e5, maxTokens: 8192 }
2250
+ ]
2251
+ };
2252
+ }
2253
+ if (PROVIDER_DEFS[v.primaryProvider]) {
2254
+ const def = { ...PROVIDER_DEFS[v.primaryProvider] };
2255
+ if (v.primaryProvider === "zhipu" && v.zhipuPlan === "token") {
2256
+ def.baseUrl = "https://open.bigmodel.cn/api/paas/v4";
2257
+ }
2258
+ if (v.primaryProvider === "dashscope" && v.dashscopePlan === "token") {
2259
+ def.baseUrl = "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1";
2260
+ }
2261
+ if (v.primaryProvider === "7yi" && (v.customBaseUrl || "").trim()) {
2262
+ def.baseUrl = v.customBaseUrl.trim();
2263
+ }
2264
+ if (v.providerModels && v.providerModels.length > 0) {
2265
+ def.models = v.providerModels.map((m) => ({
2266
+ id: m.id,
2267
+ name: m.name || m.id,
2268
+ reasoning: m.reasoning ?? true,
2269
+ // 没标 vision 的条目按「不支持」写 input(目录是权威),但 visionOf 那边对
2270
+ // 「没标」仍按未知处理——若用户手输的型号恰好是主模型,vision 仍会宽复用它
2271
+ input: ["text", ...m.vision ? ["image"] : [], ...m.video ? ["video"] : []],
2272
+ contextWindow: m.contextWindow ?? 2e5,
2273
+ maxTokens: m.maxTokens ?? 8192
2274
+ }));
2275
+ }
2276
+ const primaryModelId = modelIdOf(v.primaryModel);
2277
+ if (primaryModelId && !def.models.some((m) => m?.id === primaryModelId)) {
2278
+ const old = (v.existingModels || []).find((m) => m?.id === primaryModelId);
2279
+ def.models = [...def.models, old || { id: primaryModelId, name: primaryModelId }];
2280
+ }
2281
+ return {
2282
+ ...def,
2283
+ apiKey: "env:" + v.primaryProvider.toUpperCase().replace(/[^A-Z0-9_]/g, "_") + "_API_KEY",
2284
+ ...def.baseUrl ? { baseUrl: def.baseUrl.trim() } : {}
2285
+ };
2286
+ }
2287
+ throw new Error("\u65E0\u6CD5\u751F\u6210\u6240\u9009\u6A21\u578B\u670D\u52A1");
2288
+ }
2289
+ function generateConfig(v) {
2290
+ const workspace = path3.join(v.stateDir, "workspace").replace(/\\/g, "/");
2291
+ const config = {
2292
+ schemaVersion: SCHEMA_VERSION,
2293
+ // 全引擎统一时区(design §3.1)。真实 init 走 getDefaultValues() 探测本机,
2294
+ // 模板走 {{TIMEZONE}} 占位符。
2295
+ timezone: v.timezone,
2296
+ stateDir: v.stateDir.replace(/\\/g, "/"),
2297
+ mediaDir: `${v.stateDir.replace(/\\/g, "/")}/media/inbound`,
2298
+ models: {
2299
+ providers: {}
2300
+ },
2301
+ // 0917:my_eyes(看图工具)读的是 tools.my_eyes.model,不是 tools.vision——
2302
+ // 后者是模板里遗留的死键(全仓零读者),已删。visionModel 解析不出就不写这个块。
2303
+ //
2304
+ // 1001 发语音条(§7.4):免费档必须把这块写全。此前唯一会写 `tools.my_voice` 的是
2305
+ // `applyFreeTier`,而它只从「切换到免费档」那张卡触发——配置已经是免费档时卡片不显示
2306
+ // ⇒ **新装机永远没有这块**:托盘「合成引擎」显示 edge-tts(面板在 provider 缺失时
2307
+ // 默认选它),引擎 `pickProvider` 也落 edge,而 edge 要本机 Python + `edge_tts`
2308
+ // (安装包一个都不带)⇒ 用户第一次说"发条语音"就报错。郭叔 1001 装机实测撞到。
2309
+ // 形状走 `freeTierVoiceConfig()`(唯一源,与 applyFreeTier / 启动补齐同一份)。
2310
+ tools: {
2311
+ ...v.tavilyKey ? { tavily: { apiKey: v.tavilyKey } } : {},
2312
+ ...v.visionModel ? { my_eyes: { model: v.visionModel } } : {},
2313
+ // ⚠️ 判据是 **provider 真的是 7yi**,不是 `isFreeTier(v)`:后者会因 `freeTier:true`
2314
+ // 单独为真(answers 手写坏组合时),而那种 config 里**根本没有 7yi provider 块**,
2315
+ // 写进去就是个悬空引用(第一次发语音报"免费池未配置",把用户指向错误的排查方向)。
2316
+ // 与下面 vision/video 的收口闸同一条纪律:**引用必须落在本次真实写出的 provider 里**。
2317
+ ...v.primaryProvider === FREE_TIER_PROVIDER_ID ? { my_voice: freeTierVoiceConfig() } : {},
2318
+ // 自拍(§4.3):免费档必须显式写 provider:'relay'。不写的话 getProvider()
2319
+ // 会落回默认值 'fal',而免费装机没有 fal key——第一次自拍就失败。
2320
+ // 非免费档只在用户真给了形象时才写这个块,且不替他决定 provider。
2321
+ ...isFreeTier(v) || v.selfiePhotoRelPath || v.selfiePortraitDesc ? {
2322
+ my_selfie: {
2323
+ ...isFreeTier(v) ? { provider: "relay" } : {},
2324
+ ...v.selfiePhotoRelPath ? { references: [{ name: "portrait", path: v.selfiePhotoRelPath }] } : {},
2325
+ // 只在没有照片时才写描述——两个都给的话以照片为准,写进去会让人以为
2326
+ // 描述也生效了(冷启读的就是这个键)
2327
+ ...!v.selfiePhotoRelPath && v.selfiePortraitDesc ? { portraitDesc: v.selfiePortraitDesc } : {}
2328
+ }
2329
+ } : {}
2330
+ },
2331
+ session: { dmScope: "main", groupScope: "main" },
2332
+ // 1116 翀哥令:助理必须自带浏览器自动化("连个浏览器自动化都不给那还叫助理么")。
2333
+ // 1126:@playwright/mcp 随引擎进 node_modules,MCP 启动时直接用引擎自己的 node 跑包里的 cli
2334
+ // (src/mcp/bundled-npx.ts),不找 npx、不联网——桌面 App 里没有 npx,走 npx 会 ENOENT。
2335
+ // 浏览器用系统 Chrome 不另下 Chromium。档案目录各机独立,登一次持久。
2336
+ mcpServers: {
2337
+ playwright: { ...PLAYWRIGHT_MCP_ENTRY, args: [...PLAYWRIGHT_MCP_ENTRY.args] }
2338
+ },
2339
+ sandbox: { mode: "off" },
2340
+ display: {
2341
+ // 1126 翀哥令:新装机默认折叠——工具过程并成一张过程卡逐步更新,不逐步刷消息。
2342
+ // 只写进新装机配置;存量装机没写这一项的仍是展开(loadDisplayConfig 兜底),要改走托盘配置面板。
2343
+ toolOutputMode: "collapsed",
2344
+ thinking: { enabled: false, emoji: "\u{1F4AD}", maxLen: 300 },
2345
+ // 0930 翀哥:默认改 summary/description(原来 raw/both 把工具参数和命令原文全糊进
2346
+ // 聊天,占地方)。已有装机的配置不受影响——要改走托盘配置面板。
2347
+ toolUse: { enabled: true, emoji: "\u{1F527}", displayMode: "summary", bashDisplayMode: "description" },
2348
+ toolResult: { enabled: false },
2349
+ reactions: { enabled: true, start: "\u{1F440}", done: "\u2705", error: "\u274C" },
2350
+ // 1125:不再写 preview.enabled——全仓零读者(预览开关读的是 channels.<通道>.dm/group.previewEnabled),
2351
+ // 写进配置只会让人以为改它有用。真正的开关见 message-pipeline 的 previewEnabled。
2352
+ preview: { agentName: v.agentName, color: "orange" },
2353
+ typing: { enabled: true }
2354
+ },
2355
+ agents: {
2356
+ defaults: {
2357
+ workspace,
2358
+ name: v.agentName,
2359
+ // 人设落 config 是为了**复跑能读回来**(loadExistingValues)。引擎运行时不读它
2360
+ // ——SOUL.md 已经按人设渲染好了。不写的话复跑 init 会退回 'assistant',
2361
+ // 而 execute() 用模板重写 SOUL.md,用户选的"情感陪伴"重装一次就变回通用助手。
2362
+ persona: v.persona,
2363
+ model: {
2364
+ primary: v.primaryModel,
2365
+ // 条件写入:vision 引用解析不出时省略键(loader 按 if (visionRef) 处理缺失)
2366
+ ...v.visionModel ? { vision: v.visionModel } : {},
2367
+ // 条件写入:video 解析不出时省略键(loader 按 if (videoRef) 处理缺失)
2368
+ ...v.videoModel ? { video: v.videoModel } : {}
2369
+ },
2370
+ features: {
2371
+ filesystem: true,
2372
+ // cc-driver(1104):cc_ask 使唤桌面 CC / cc_progress 旁观——cc-run scope 配套
2373
+ "cc-driver": true,
2374
+ shell: true,
2375
+ webSearch: true,
2376
+ webFetch: true,
2377
+ installer: true,
2378
+ memory: true,
2379
+ topics: true,
2380
+ "topic-extract": true,
2381
+ "topic-recall": true,
2382
+ cron: true,
2383
+ agent: true,
2384
+ agentTeams: true,
2385
+ processOutput: "minimal",
2386
+ interrupt: "command",
2387
+ debounceMs: 5e3,
2388
+ // 免费档的装机目标是「能对话、能看图、能自拍」,这两个 flag 默认 false
2389
+ // (src/config/features.ts)。显式打开,它们是声明这两件事的地方。
2390
+ ...isFreeTier(v) ? { selfie: true, eyes: true } : {}
2391
+ }
2392
+ }
2393
+ },
2394
+ // 1004 翀哥拍板:extract 带 15 分钟冷却闸。不配的话默认 0=每轮 query 都跑
2395
+ // side-model 提取——token 大量消耗且小批次提取质量差(与 mem7 3x 产量根因同源:
2396
+ // 小 cell 口径)。冷却内跳过的窗口由水位线兜底,消息不丢。
2397
+ // 1006:extract 指到 nort 车道(后台提取没人等,不该占主链快档)。
2398
+ // 1025:清洗独立 topics.clean.model 指快档(FREE_TIER_FAST_REF 头注)。
2399
+ // ⚠️ 只对免费档写 model——它引用 `7yi` provider,而非免费档本次**并不写**那个
2400
+ // provider 块(同 my_voice 那条纪律:引用必须落在本次真实写出的 provider 里)。
2401
+ // intervalMinutes 与档位无关,一律写:新装机都带冷却闸(1004 拍板)。
2402
+ topics: {
2403
+ extract: {
2404
+ intervalMinutes: EXTRACT_COOLDOWN_MINUTES,
2405
+ ...isFreeTier(v) ? { model: FREE_TIER_NORT_REF } : {}
2406
+ },
2407
+ // 存量清洗(升级管线)用快档——一批 16 页在 nort 要 ~11 分钟,快档秒级。
2408
+ ...isFreeTier(v) ? { clean: { model: FREE_TIER_FAST_REF } } : {}
2409
+ },
2410
+ // 1026 翀哥拍板:免费档默认带 mem7 向量通道——provision 时代不写这格,免费装机
2411
+ // topics 导入全零向量、语义检索空转(testengine2 实弹 51/51 零向量)。只在免费档写
2412
+ // embedding(引用必须落在本次真实写出的 7yi provider 里,同 topics.model 纪律)。
2413
+ // 🔴 1102 补 enabled 本体(翀哥拍板"新装默认开"):引擎严格判 `=== true` 且全仓无
2414
+ // 默认填充——下面那条"enabled 不写(引擎默认开)"的旧注释从未成立,1026 起新装机
2415
+ // 的 mem7 实际是静默关闭的(装机日志三次 WARN memory 工具不可用,1102 实证)。
2416
+ ...isFreeTier(v) ? { mem7: { enabled: true, ...mem7ServiceDefaults(void 0) } } : {},
2417
+ channels: {
2418
+ // ⚠️ 三个凭据格写的是 `env:` 引用,**不是明文**(T12,0926)。值落
2419
+ // ~/.engine7-secrets/<cfg>.env(0600),由 cli-init 在 config 落盘后写入。
2420
+ // 在这之前 init 是明文直写这三格,与「config 不明文存 key」的既定机制并存——
2421
+ // 而注册表把这三格标成 type:'secret',于是配置面板对它们 set 结构上不可能生效
2422
+ // (写 .env、引擎读 config 字面量),用户陷入「写入→ok→显示未配置→重填」。
2423
+ // 统一成一套机制不是安全考量(两边都是明文),是不再留例外。
2424
+ discord: {
2425
+ enabled: v.discordEnabled,
2426
+ dmPolicy: "pairing",
2427
+ groupPolicy: "open",
2428
+ accounts: { default: { token: secretRef(envKeyOf("channels.discord.accounts.default.token"), v.discordToken) } },
2429
+ replyToMode: "all"
2430
+ },
2431
+ // telegram(1002 阶段一):块恒写出,enabled 走 values(init 两条装配路径都给 false)。
2432
+ // 令牌格与 discord/feishu 同一套机制——config 存 env: 引用、明文落 secrets;
2433
+ // 空串保持空串(secretRef 的既定行为),不写一个指向不存在变量的引用。
2434
+ telegram: {
2435
+ enabled: v.telegramEnabled,
2436
+ token: secretRef(envKeyOf("channels.telegram.token"), v.telegramToken),
2437
+ dmPolicy: "open",
2438
+ groupPolicy: "mention-only",
2439
+ allowFrom: []
2440
+ },
2441
+ // whatsapp(1003 Task 9):块恒写出,enabled 走 values(init 两条装配路径都给 false)。
2442
+ // 扫码制**没有凭据格**——配对凭证落 stateDir/whatsapp-auth,config/secrets 都不经手。
2443
+ // allowFrom 条目是 **E.164 号码**('+852…';不是 @lid/jid——@lid 条目 fail-closed 不匹配)。
2444
+ whatsapp: {
2445
+ enabled: v.whatsappEnabled,
2446
+ dmPolicy: "allowlist",
2447
+ allowFrom: [],
2448
+ replyToMode: "off",
2449
+ sendReadReceipts: false,
2450
+ selfChatPrefix: true,
2451
+ groupDigest: { enabled: true, patrolIntervalMin: 60, maxLinesPerGroup: 500 }
2452
+ },
2453
+ feishu: {
2454
+ enabled: v.feishuEnabled,
2455
+ appId: v.feishuAppId,
2456
+ appSecret: secretRef(envKeyOf("channels.feishu.appSecret"), v.feishuAppSecret),
2457
+ connectionMode: "websocket",
2458
+ dmPolicy: "pairing",
2459
+ // 1011 翀哥:群默认 mention-only——@才回应(引擎 adapter 同款默认)。此前脚手架写
2460
+ // 'open' = 装机用户的机器人在群里每条都接话;免 @ 的群走 group.openGroups 局部豁免。
2461
+ groupPolicy: "mention-only",
2462
+ // 1029 onboarding:装机扫码注册人的 open_id——主动欢迎投递目标(手输路径可为空)
2463
+ ...v.feishuOpenId ? { ownerOpenId: v.feishuOpenId } : {}
2464
+ },
2465
+ ...v.wechatEnabled && v.wechatToken ? {
2466
+ wechat: {
2467
+ enabled: true,
2468
+ token: secretRef(envKeyOf("channels.wechat.token"), v.wechatToken),
2469
+ accountId: v.wechatAccountId,
2470
+ // 1029 onboarding:扫码用户本人的 iLink id——主动欢迎投递目标
2471
+ ...v.wechatUserId ? { userId: v.wechatUserId } : {},
2472
+ dmPolicy: "pairing",
2473
+ group: { policy: "disabled" }
2474
+ }
2475
+ } : {},
2476
+ // 0920 翀哥拍板:emotion 通道默认开启(含 liveSystemPrompt 加载 EMOTION.md)
2477
+ // 即使没装 EMOTION.md,buildLightStablePrompt 也会硬编码"想 TA 就发"那段兜底
2478
+ //
2479
+ // T11:files 里写的是**逻辑名**,别改成 `personas/<persona>/EMOTION.md`。init 知道
2480
+ // 本次选的 persona,顺手把路径烤进 config 看着更直白,但那样会静默坏:切换 persona
2481
+ // 只改 agents.defaults.persona,这里的路径仍指着旧人设目录(读错人设的 EMOTION.md)。
2482
+ // 名字交给读取点按当前 persona 现解析——config/persona-files.ts(新路径优先,回退旧路径)。
2483
+ emotion: {
2484
+ enabled: true,
2485
+ tools: defaultEmotionTools(),
2486
+ liveSystemPrompt: {
2487
+ files: ["SOUL.md", "EMOTION.md"]
2488
+ }
2489
+ },
2490
+ // cc-driver(1103):把某个私聊绑成"桌面 Claude Code 终端"——消息直驱本机
2491
+ // claude CLI,与控制台共享 session/记忆。块恒写出、默认关:用户在私聊里发
2492
+ // /cc-bind <项目绝对路径> 即自动开启并绑定(无需手改配置),/cc-unbind 解绑。
2493
+ // 前提:本机已装 claude CLI 并登录。
2494
+ ccDriver: {
2495
+ enabled: false,
2496
+ bindings: []
2497
+ }
2498
+ },
2499
+ // cc-run 会话范围:per-session=每次独立会话(缺省,与 cc-run 代码缺省 project 一致——
2500
+ // 1113 spec 要求两处缺省统一,1127 补齐);main=接续该 agent 最近的主对话,须显式选。
2501
+ ccRun: { scope: v.ccRunScope ?? "per-session" },
2502
+ api: { port: v.apiPort },
2503
+ // 0909 npm 包默认开:inner-voice + proactive 是开箱即用的核心体验
2504
+ // (不写 model → 都兜底主模型;proactive 领域/persona 可用 workspace/prompts/ 覆盖)
2505
+ innerVoice: { enabled: true, ...isFreeTier(v) ? { model: FREE_TIER_NORT_REF } : {} },
2506
+ proactive: { enabled: true },
2507
+ prompt: {
2508
+ rules: { enabled: true },
2509
+ mode: "custom",
2510
+ staticFiles: ["AGENTS.md", "USER.md", "MEMORY.md", "memory/distill-output.md", "memory/distill-emotion.md"],
2511
+ order: ["soul", "AGENTS.md", "prompts/contacts.md", "using-tools", "USER.md", "MEMORY.md", "memory/distill-output.md", "memory/distill-emotion.md", "auto-memory-instructions"]
2512
+ },
2513
+ compaction: {
2514
+ enabled: true,
2515
+ contextWindow: DEFAULT_CONTEXT_WINDOW,
2516
+ contextWindowMigrationVersion: CONTEXT_WINDOW_MIGRATION_VERSION,
2517
+ background: true,
2518
+ keepRecentTokens: 2e4,
2519
+ bufferTokens: 23e3,
2520
+ maxOutputTokens: 16384,
2521
+ minReductionRatio: 0.3,
2522
+ ruleBased: { enabled: true, essentialFields: [] },
2523
+ memoryFlush: { enabled: true, forceFlushTranscriptBytes: "2.0mb" }
2524
+ },
2525
+ skills: {
2526
+ enabled: true,
2527
+ path: "skills"
2528
+ }
2529
+ };
2530
+ config.models.providers[v.primaryProvider] = generateProviderConfig(v);
2531
+ const providerKeys = Object.keys(config.models.providers);
2532
+ if (providerKeys.length === 0) {
2533
+ throw new Error("\u6CA1\u6709\u751F\u6210\u4EFB\u4F55 provider\u2014\u2014\u68C0\u67E5 init \u7684 provider \u9009\u62E9\u4E0E\u6A21\u578B ID\u3002");
2534
+ }
2535
+ const primaryRef = String(config.agents.defaults.model.primary);
2536
+ const primaryProviderId = primaryRef.split("/")[0];
2537
+ if (!config.models.providers[primaryProviderId]) {
2538
+ throw new Error(
2539
+ `\u751F\u6210\u7684 config \u4E0D\u81EA\u6D3D\uFF1Aagents.defaults.model.primary = "${primaryRef}"\uFF0C\u4F46 models.providers \u91CC\u53EA\u6709 ${providerKeys.join(", ")}\u2014\u2014\u5F15\u64CE\u542F\u52A8\u4F1A\u76F4\u63A5\u629B Provider not found\u3002\u8FD9\u662F init \u7684 bug\uFF0C\u8BF7\u8FDE\u540C\u8FD9\u6761\u6D88\u606F\u4E00\u8D77\u53CD\u9988\u3002`
2540
+ );
2541
+ }
2542
+ const primaryModelId = primaryRef.split("/").slice(1).join("/");
2543
+ const listed = config.models.providers[primaryProviderId].models || [];
2544
+ if (primaryModelId && !listed.some((m) => m?.id === primaryModelId)) {
2545
+ throw new Error(
2546
+ `\u751F\u6210\u7684 config \u4E0D\u81EA\u6D3D\uFF1A\u4E3B\u6A21\u578B "${primaryRef}" \u4E0D\u5728 ${primaryProviderId} \u7684\u6A21\u578B\u8868\u91CC\uFF08\u8868\u91CC\u662F ${listed.map((m) => m?.id).join(", ") || "\u7A7A"}\uFF09\u3002\u8FD9\u662F init \u7684 bug\uFF0C\u8BF7\u8FDE\u540C\u8FD9\u6761\u6D88\u606F\u4E00\u8D77\u53CD\u9988\u3002`
2547
+ );
2548
+ }
2549
+ if (v.visionModel) {
2550
+ const visionProvider = v.visionModel.split("/")[0];
2551
+ if (!config.models.providers[visionProvider]) {
2552
+ console.warn(
2553
+ `[config] \u5FFD\u7565 vision \u5F15\u7528 "${v.visionModel}"\uFF1Aprovider "${visionProvider}" \u4E0D\u5728\u672C\u6B21\u751F\u6210\u7684 providers\uFF08${Object.keys(config.models.providers).join(", ") || "\u7A7A"}\uFF09\u91CC\u2014\u2014\u5199\u8FDB\u53BB\u4F1A\u8BA9 loader \u89E3\u6790\u5931\u8D25\u3001\u5165\u7AD9\u56FE\u7247\u88AB\u9759\u9ED8\u4E22\u5F03\u3002\u56FE\u7247\u8BC6\u522B\u672C\u6B21\u5173\u95ED\u3002`
2554
+ );
2555
+ delete config.agents.defaults.model.vision;
2556
+ delete config.tools.my_eyes;
2557
+ }
2558
+ }
2559
+ if (v.videoModel) {
2560
+ const videoProvider = v.videoModel.split("/")[0];
2561
+ if (!config.models.providers[videoProvider]) {
2562
+ console.warn(
2563
+ `[config] \u5FFD\u7565 video \u5F15\u7528 "${v.videoModel}"\uFF1Aprovider "${videoProvider}" \u4E0D\u5728\u672C\u6B21\u751F\u6210\u7684 providers\uFF08${Object.keys(config.models.providers).join(", ") || "\u7A7A"}\uFF09\u91CC\u2014\u2014\u89C6\u9891\u7406\u89E3\u672C\u6B21\u6309\u672A\u914D\u7F6E\u5904\u7406\uFF08\u6D88\u606F\u8D70\u9ED8\u8BA4\u6A21\u578B\uFF0C\u89C6\u9891\u5757\u4F1A\u88AB\u5265\u79BB\uFF09\u3002`
2564
+ );
2565
+ delete config.agents.defaults.model.video;
2566
+ }
2567
+ }
2568
+ return config;
2569
+ }
2570
+ var SCHEMA_VERSION, FREE_TIER_RELAY_URL, LEGACY_FREE_TIER_RELAY_URL, FREE_TIER_PROVIDER_ID, FREE_TIER_NORT_MODEL, FREE_TIER_NORT_REF, FREE_TIER_FAST_MODEL, FREE_TIER_FAST_REF, FREE_TIER_EMB_MODEL, FREE_TIER_EMB_REF, MEM7_RERANK_REF, EXTRACT_COOLDOWN_MINUTES, PLAYWRIGHT_MCP_ENTRY, DEFAULT_FREE_VOICE, DEFAULT_PRIMARY_MODEL, VISION_CAPABLE, PROVIDER_DEFS, MODEL_CHOICES, CUSTOM_DEFAULT_INPUT, TEMPLATE_VALUES;
2571
+ var init_cli_init_config = __esm({
2572
+ "src/cli-init-config.ts"() {
2573
+ "use strict";
2574
+ init_registry();
2575
+ init_emotion_tools();
2576
+ init_context_window_policy();
2577
+ SCHEMA_VERSION = 1;
2578
+ FREE_TIER_RELAY_URL = "https://7yi.engine7.ai";
2579
+ LEGACY_FREE_TIER_RELAY_URL = "https://www.twinsun.top:8866";
2580
+ FREE_TIER_PROVIDER_ID = "7yi";
2581
+ FREE_TIER_NORT_MODEL = "engine7-free-nort";
2582
+ FREE_TIER_NORT_REF = `${FREE_TIER_PROVIDER_ID}/${FREE_TIER_NORT_MODEL}`;
2583
+ FREE_TIER_FAST_MODEL = "engine7-free";
2584
+ FREE_TIER_FAST_REF = `${FREE_TIER_PROVIDER_ID}/${FREE_TIER_FAST_MODEL}`;
2585
+ FREE_TIER_EMB_MODEL = "engine7-emb";
2586
+ FREE_TIER_EMB_REF = `${FREE_TIER_PROVIDER_ID}/${FREE_TIER_EMB_MODEL}`;
2587
+ MEM7_RERANK_REF = `${FREE_TIER_PROVIDER_ID}/engine7-rerank`;
2588
+ EXTRACT_COOLDOWN_MINUTES = 15;
2589
+ PLAYWRIGHT_MCP_ENTRY = {
2590
+ enabled: true,
2591
+ command: "npx",
2592
+ args: ["-y", "@playwright/mcp@latest"]
2593
+ };
2594
+ DEFAULT_FREE_VOICE = "Chinese (Mandarin)_Warm_Girl";
2595
+ DEFAULT_PRIMARY_MODEL = {
2596
+ dashscope: "dashscope/qwen3.8-max",
2597
+ minimax: "minimax/MiniMax-M3",
2598
+ zhipu: "zhipu/glm-5.3",
2599
+ deepseek: "deepseek/deepseek-v4-pro",
2600
+ "7yi": "7yi/engine7-free"
2601
+ };
2602
+ VISION_CAPABLE = {
2603
+ // 0917:原先标 true,但同一个文件里 qwen3.8-max 的 input 是 ['text'],安装器目录
2604
+ // 也明确标 vision=false(只有 Flash 叫"多模态")。矛盾直接导致**默认 CLI 装机路径**
2605
+ // 重演 P0-2 的症状:vision 复用主模型 → 该型号 modelInputs=['text'] → 引擎把历史和
2606
+ // 当前消息里的图全剥成 "[image]"。改成 false 后 resolveVisionModel 会落到
2607
+ // qwen3.8-flash(input 真含 image)。
2608
+ "dashscope/qwen3.8-max": false,
2609
+ "dashscope/qwen3.8-flash": true,
2610
+ "minimax/MiniMax-M3": true,
2611
+ // 0918 移除 'minimax/MiniMax-M2.7'(内置表同时去掉该型号)
2612
+ "zhipu/glm-5v-turbo": true,
2613
+ "zhipu/glm-5.3": false,
2614
+ // 0917:DeepSeek 全线按支持图片处理。依据(官方更新日志 + Vision 文档):
2615
+ // - `deepseek-flash`(V4.1 Flash)原生多模态,官方 Vision 文档明确收图
2616
+ // https://api-docs.deepseek.com/guides/vision
2617
+ // - `deepseek-v4-flash` / `deepseek-v4-flash-vision-exp`:退役名,请求由 V4.1 Flash
2618
+ // 承接(临时兼容路由,官方未给移除日期)→ 同样收图
2619
+ // - `deepseek-v4-pro`:官方旗舰已停,9/14 起请求同样由 V4.1 Flash 承接;新的
2620
+ // deepseek-pro 发布后大概率也走多模态(flash 都支持了,pro 不会倒退)
2621
+ // 原先两个都标 false:v4-pro 标 false 会让今天用它的 agent **静默丢图**,
2622
+ // deepseek-flash 标 false 还会触发 P0-2 的幽灵引用兜底。
2623
+ // 声明多一分的代价是上游响亮报错,少一分的代价是无声丢图——选前者。
2624
+ "deepseek/deepseek-flash": true,
2625
+ "deepseek/deepseek-v4-flash": true,
2626
+ "deepseek/deepseek-v4-pro": true,
2627
+ // 免费档(0919):engine7-free 只收文本,engine7-vis-free 才带 image。
2628
+ // 标错会让主模型被当成能看图 → 图发给一个 input=['text'] 的型号 → 静默丢图。
2629
+ "7yi/engine7-free": false,
2630
+ // 1006:nort 车道纯文本(吃它的三个字段——extract / innerVoice / cron——都不带图)。
2631
+ // 标 true 会让图片被路由到一个 input=['text'] 的型号 → 静默丢图。
2632
+ "7yi/engine7-free-nort": false,
2633
+ "7yi/engine7-vis-free": true,
2634
+ // 0930:engine7-video 声明收图(图+视频同发不剥图,见 PROVIDER_DEFS['7yi'] 注释)。
2635
+ // 本表与内置表 input 必须一致——「能力表与模型表互不矛盾」那条测试盯的就是这个。
2636
+ "7yi/engine7-video": true
2637
+ };
2638
+ PROVIDER_DEFS = {
2639
+ dashscope: {
2640
+ // 双通道(0916):按量付费(sk-)走 compatible-mode;Token Plan 订阅(sk-sp-)走专属域名,
2641
+ // 两边密钥/端点不可互换——用错就"订阅了还按量计费"。计划选择见 dashscopePlan。
2642
+ baseUrl: "https://dashscope.aliyuncs.com/compatible-mode/v1",
2643
+ api: "openai-completions",
2644
+ models: [
2645
+ { id: "qwen3.8-max", name: "Qwen 3.8 Max", reasoning: true, input: ["text"], contextWindow: 1e6, maxTokens: 65536 },
2646
+ { id: "qwen3.8-flash", name: "Qwen 3.8 Flash\uFF08\u591A\u6A21\u6001\uFF09", reasoning: true, input: ["text", "image"], contextWindow: 1e6, maxTokens: 65536 }
2647
+ ]
2648
+ },
2649
+ minimax: {
2650
+ baseUrl: "https://api.minimaxi.com/anthropic",
2651
+ api: "anthropic",
2652
+ models: [
2653
+ // 0918 去掉 MiniMax-M2.7:有 M3 之后没人用了(翀哥)
2654
+ { id: "MiniMax-M3", name: "MiniMax M3", reasoning: true, input: ["text", "image", "video"], contextWindow: 1e6, maxTokens: 64e3 }
2655
+ // 0930 补 video:anthropic 端点收 type="video" block(小雯真机验通 + 直连复核 M3.1)
2656
+ ]
2657
+ },
2658
+ zhipu: {
2659
+ baseUrl: "https://open.bigmodel.cn/api/coding/paas/v4",
2660
+ api: "openai-completions",
2661
+ models: [
2662
+ { id: "glm-5.3", name: "GLM-5.3 (\u6700\u65B0\u4E3B\u529B)", reasoning: true, input: ["text"], contextWindow: 1e6, maxTokens: 128e3 },
2663
+ { id: "glm-5v-turbo", name: "GLM-5V-Turbo (\u89C6\u89C9)", reasoning: true, input: ["text", "image"], contextWindow: 2e5, maxTokens: 128e3 }
2664
+ ]
2665
+ },
2666
+ deepseek: {
2667
+ baseUrl: "https://api.deepseek.com/anthropic",
2668
+ api: "anthropic",
2669
+ thinking: { enabled: true, budgetTokens: 8192 },
2670
+ // 0923:官方 anthropic 端点 thinking 模式下,历史里"带 tool_use 却没 thinking 块"的 assistant 轮
2671
+ // 会让下一次请求 400 must be passed back。这种轮是引擎自己造的——空响应重试会发
2672
+ // thinking:{type:'disabled'}(见 query.ts)。开了这个开关就给它补占位块、并让无签名的
2673
+ // thinking 也回传。实测矩阵见 anthropic-provider.ts 的 AnthropicProviderConfig。
2674
+ requireThinkingBlocks: true,
2675
+ models: [
2676
+ // 0916 改名:deepseek-v4-flash → deepseek-flash(旧名仍可调,请求由 V4.1 Flash 承接)
2677
+ // 0917 补 image:V4.1 Flash 原生多模态(见 VISION_CAPABLE 注释)
2678
+ { id: "deepseek-flash", name: "DeepSeek Flash", reasoning: true, input: ["text", "image"], contextWindow: 1e6, maxTokens: 384e3 },
2679
+ // 0917 补 image:官方旗舰已停、9/14 起请求由 V4.1 Flash 承接,实际收图
2680
+ { id: "deepseek-v4-pro", name: "DeepSeek V4 Pro", reasoning: true, input: ["text", "image"], contextWindow: 1e6, maxTokens: 384e3 }
2681
+ ]
2682
+ },
2683
+ "7yi": {
2684
+ // 引擎免费档的中转站。baseUrl 是兜底值——真正的权威值来自领号响应
2685
+ // (服务端按请求 Host 自报地址),由安装器作为 customBaseUrl 下发。
2686
+ // 这样挪机器、换域名只改服务端,不用重发安装包。
2687
+ //
2688
+ // ⚠️ 0921 修:这里原本写的是 `https://www.twinsun.top/v1`(443),而 **443 上不是
2689
+ // 中转站**(实测回的是另一个服务的 FastAPI 404)。安装器那条路每次都会下发
2690
+ // customBaseUrl 把它盖掉,所以正式装机撞不到;但**终端向导选 7yi 时不问 baseUrl**,
2691
+ // 直接落到这个兜底值——于是命令行用户拿到的是「号领到了、引擎起来了、一发消息就废」。
2692
+ // 用常量拼,别再手写一遍(漏端口就是这个坑)。
2693
+ baseUrl: `${FREE_TIER_RELAY_URL}/v1`,
2694
+ api: "anthropic",
2695
+ models: [
2696
+ // 1111:免费主档的新装默认从500k收窄到350k,减少在线历史增长。
2697
+ // 按默认压缩配置:350000 - 16384输出预留 - 23000缓冲 - 固定开销H。
2698
+ // H为40000时,历史估算触发点270616(约77.3%);不是固定比例或usage实报。
2699
+ //
2700
+ // 病例史(改这个值前必读):
2701
+ // - 0919(声明 1M 的代价):阈值 906137 高到永不触发,上下文滚到 191080 仍不压缩,
2702
+ // 191k 的请求把 SenseNova 的 TPM 打爆(429 inference exceeds tpm/rpm limit),
2703
+ // 整条链退到付费的 MiniMax。当时据此取过 150000(实测成功线 114K)。
2704
+ // - 0922(声明 150k 的代价,反向):把 7yi 只当 vision 旁路的部署(小柯)里,
2705
+ // vision 引擎按 150k 算出阈值 49071,对共享 session 的 50 万 token(1M 主模型
2706
+ // glm-5.3 的正常水位)连触 3 次 compact,47 万历史被 ruleCompact 折叠、不可逆。
2707
+ // → 7yi仅当vision旁路时,部署模型表须与共享session的主模型预算协调;
2708
+ // 本条350k用于"7yi当主模型"的新装默认,不覆盖已有模型表或显式窗口配置。
2709
+ { id: "engine7-free", name: "Engine7 \u514D\u8D39\uFF08\u6587\u672C\uFF09", reasoning: true, input: ["text"], contextWindow: 35e4, maxTokens: 64e3 },
2710
+ // 1006:后台非实时车道(topics.extract / innerVoice / cron 三个字段指它)。
2711
+ // 中转站侧是独立链:sensenova-6.8-flash-lite(#13, pri 20) → MiniMax-M3.1 兜底(#20, pri 10),
2712
+ // 与主链共用 #20 兜底但主链已摘掉 6.8-lite(那是 P90 120 秒的档)。
2713
+ // contextWindow 与 engine7-free 对齐350000:同一批上游、同一条用途,
2714
+ // 分开取值只会多一个漂移点(compaction 阈值按声明值算)。
2715
+ // ⚠️ 这里必须注册:`cron.model` 那条路走 createModelDeps(engine-startup.ts),
2716
+ // 模型 id 不在 models[] 里会 warn 后返回 null,cron 整个静默 no-op。
2717
+ { id: "engine7-free-nort", name: "Engine7 \u514D\u8D39\uFF08\u540E\u53F0\uFF09", reasoning: true, input: ["text"], contextWindow: 35e4, maxTokens: 64e3 },
2718
+ // input 带 image:实测 Claude 格式的图片块经 /v1/messages 能被上游正确识别
2719
+ { id: "engine7-vis-free", name: "Engine7 \u514D\u8D39\uFF08\u89C6\u89C9\uFF09", reasoning: true, input: ["text", "image"], contextWindow: 35e4, maxTokens: 64e3 },
2720
+ // 0930 视频理解:后端映射 MiniMax-M3.1-Flash(#20,直连实测收 video block;1023 上游去掉 -Preview)。
2721
+ // input 带 image:图+视频同发时消息路由到视频模型,handle-query 按 modelInputs 剥块
2722
+ // ——不带 image 就是"同发丢图"(547fd1ac 修过的形状);M3.1 本身收图,声明与事实一致。
2723
+ { id: "engine7-video", name: "Engine7 \u89C6\u9891", reasoning: true, input: ["text", "image", "video"], contextWindow: 35e4, maxTokens: 64e3 }
2724
+ // 注意:engine7-img-free 不在这里。它在 chat 端点是 404(不是 chat 模型),
2725
+ // 生图由 my_selfie 自己拼 /v1/images/edits,relayModel 默认值已经是它。
2726
+ ]
2727
+ }
2728
+ };
2729
+ MODEL_CHOICES = Object.fromEntries(
2730
+ Object.entries(PROVIDER_DEFS).map(([pid, def]) => [
2731
+ pid,
2732
+ def.models.map((m) => `${pid}/${m.id}`)
2733
+ ])
2734
+ );
2735
+ CUSTOM_DEFAULT_INPUT = ["text", "image"];
2736
+ TEMPLATE_VALUES = {
2737
+ stateDir: "{{STATE_DIR}}",
2738
+ timezone: "{{TIMEZONE}}",
2739
+ agentName: "{{AGENT_NAME}}",
2740
+ persona: "assistant",
2741
+ chatMode: "auto",
2742
+ primaryProvider: "dashscope",
2743
+ zhipuPlan: "",
2744
+ dashscopePlan: "",
2745
+ providerModels: null,
2746
+ // 走内置模型表,模板里展示内置形状
2747
+ primaryApiKey: "",
2748
+ // generateConfig 只写 env: 占位符,明文不落 config
2749
+ primaryModel: "dashscope/qwen3.8-max",
2750
+ // 派生而非手写:qwen3.8-max 不支持图片,vision 落到 flash。手写就会再制造一次
2751
+ // "vision 指向一个 input 里没有 image 的型号"(见 VISION_CAPABLE 注释)。
2752
+ visionModel: resolveVisionModel("dashscope", "dashscope/qwen3.8-max"),
2753
+ // 派生:dashscope 目录里没有 input 含 video 的型号 → 空串 → 模板不写 video 键
2754
+ videoModel: resolveVideoModel("dashscope", "dashscope/qwen3.8-max"),
2755
+ discordEnabled: false,
2756
+ discordToken: "",
2757
+ discordUserId: "",
2758
+ feishuEnabled: true,
2759
+ feishuAppId: "{{FEISHU_APP_ID}}",
2760
+ // env: 而不是 {{}}——**这一格真实 init 写的就是个引用**(上面 generateConfig 的渠道块),
2761
+ // 写法对齐才能让人看懂"真值在 secrets 里"。`{{}}` 在本模板里的含义是"你来填"
2762
+ // ({{STATE_DIR}} / {{AGENT_NAME}} / appId),凭据格不是那个意思,也永远不会被替换。
2763
+ feishuAppSecret: "env:FEISHU_APP_SECRET",
2764
+ feishuOpenId: "",
2765
+ wechatEnabled: false,
2766
+ // 微信块是条件写入的,模板只展示通用形状
2767
+ wechatToken: "",
2768
+ wechatAccountId: "",
2769
+ wechatUserId: "",
2770
+ // telegram 块恒写出(与 discord/feishu 同款),enabled 恒 false:模板展示的是通用形状,
2771
+ // 令牌由装机后经托盘/`config set`/存量迁移进 secrets(TELEGRAM_BOT_TOKEN)
2772
+ telegramEnabled: false,
2773
+ telegramToken: "",
2774
+ // whatsapp 块恒写出(1003 Task 9,与 telegram 同款),enabled 恒 false:扫码制没有令牌格,
2775
+ // 白名单/策略用 generateConfig 里的固定默认值(模板展示通用形状)
2776
+ whatsappEnabled: false,
2777
+ customBaseUrl: "",
2778
+ customModelId: "",
2779
+ customApi: "anthropic",
2780
+ customProviderId: "",
2781
+ // 用 env: 而不是 {{}}:{{}} 是脚手架占位符({{STATE_DIR}} 那种,由工具替换),
2782
+ // 而这一格真实 init 写的就是个 key。写成 {{TAVILY_API_KEY}} 会误导人以为有人会替换它。
2783
+ // env:TAVILY_API_KEY 是引擎真认的形式(loader 会解析),照抄也能跑通。
2784
+ tavilyKey: "env:TAVILY_API_KEY",
2785
+ apiPort: 16990
2786
+ };
2787
+ }
2788
+ });
2789
+
2790
+ // src/config/secrets-env.ts
2791
+ var secrets_env_exports = {};
2792
+ __export(secrets_env_exports, {
2793
+ engineStateDirOfConfig: () => engineStateDirOfConfig,
2794
+ loadSecretsEnv: () => loadSecretsEnv,
2795
+ loadSecretsEnvForConfig: () => loadSecretsEnvForConfig,
2796
+ readSecretsEnv: () => readSecretsEnv,
2797
+ resolveConfigIdentity: () => resolveConfigIdentity,
2798
+ secretsCandidates: () => secretsCandidates,
2799
+ secretsHome: () => secretsHome,
2800
+ stateKey: () => stateKey,
2801
+ writeSecretsValue: () => writeSecretsValue
2802
+ });
2803
+ import { createHash as createHash2 } from "node:crypto";
2804
+ import { chmodSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
2805
+ import { basename, dirname as dirname2, join as join4, normalize, resolve as resolve2 } from "node:path";
2806
+ function secretsHome() {
2807
+ return process.env.HOME || process.env.USERPROFILE || ".";
2808
+ }
2809
+ function normalizeStateDir(stateDir) {
2810
+ return normalize(stateDir).split("\\").join("/").replace(/\/+$/, "").toLowerCase();
2811
+ }
2812
+ function stateKey(stateDir) {
2813
+ return createHash2("sha256").update(normalizeStateDir(stateDir)).digest("hex").slice(0, 8);
2814
+ }
2815
+ function isDefaultStateDir(stateDir) {
2816
+ return normalizeStateDir(stateDir) === normalizeStateDir(join4(secretsHome(), ".engine7"));
2817
+ }
2818
+ function secretsCandidates(stateDir, configName) {
2819
+ const shared = join4(secretsHome(), ".engine7-secrets", `${configName}.env`);
2820
+ const inState = [
2821
+ join4(stateDir, "configs", `.env.${configName}`),
2822
+ join4(stateDir, "configs", ".env")
2823
+ ];
2824
+ if (isDefaultStateDir(stateDir)) return [shared, ...inState];
2825
+ return [
2826
+ join4(secretsHome(), ".engine7-secrets", `${configName}-${stateKey(stateDir)}.env`),
2827
+ shared,
2828
+ ...inState
2829
+ ];
2830
+ }
2831
+ function readSecretsEntries(stateDir, configName) {
2832
+ for (const p of secretsCandidates(stateDir, configName)) {
2833
+ if (!existsSync3(p)) continue;
2834
+ const entries = [];
2835
+ for (const line of readFileSync3(p, "utf-8").split("\n")) {
2836
+ const t = line.trim();
2837
+ if (!t || t.startsWith("#")) continue;
2838
+ const eq = t.indexOf("=");
2839
+ if (eq <= 0) continue;
2840
+ const k = t.slice(0, eq).trim();
2841
+ const v = t.slice(eq + 1).trim();
2842
+ if (k) entries.push([k, v]);
2843
+ }
2844
+ return { path: p, entries };
2845
+ }
2846
+ return null;
2847
+ }
2848
+ function readSecretsEnv(stateDir, configName) {
2849
+ const selected = readSecretsEntries(stateDir, configName);
2850
+ return selected ? { path: selected.path, values: Object.fromEntries(selected.entries) } : null;
2851
+ }
2852
+ function loadSecretsEnv(stateDir, configName, options = {}) {
2853
+ const selected = readSecretsEntries(stateDir, configName);
2854
+ if (!selected) return null;
2855
+ for (const [key, value] of selected.entries) {
2856
+ const current = process.env[key];
2857
+ if (options.overwrite || current === void 0 || current === "") process.env[key] = value;
2858
+ }
2859
+ return selected.path;
2860
+ }
2861
+ function resolveConfigIdentity(configPath) {
2862
+ const abs = resolve2(configPath);
2863
+ const cfgName = basename(abs, ".json");
2864
+ const cfgDir = dirname2(abs);
2865
+ const stateDir = basename(cfgDir) === "configs" ? dirname2(cfgDir) : cfgDir;
2866
+ return { stateDir, configName: cfgName };
2867
+ }
2868
+ function engineStateDirOfConfig(configPath, env = process.env) {
2869
+ let raw;
2870
+ try {
2871
+ raw = JSON.parse(readFileSync3(configPath, "utf-8"));
2872
+ } catch {
2873
+ return null;
2874
+ }
2875
+ if (typeof raw?.stateDir === "string" && raw.stateDir.trim()) return raw.stateDir.trim();
2876
+ const fromEnv = env.ENGINE_STATE_DIR;
2877
+ if (fromEnv && fromEnv.trim()) return fromEnv.trim();
2878
+ if (basename(dirname2(configPath)) !== "configs") return null;
2879
+ return resolveConfigIdentity(configPath).stateDir;
2880
+ }
2881
+ function loadSecretsEnvForConfig(configPath, options = {}) {
2882
+ const { stateDir, configName } = resolveConfigIdentity(configPath);
2883
+ return loadSecretsEnv(stateDir, configName, options);
2884
+ }
2885
+ function writeSecretsValue(configPath, envKey, value) {
2886
+ const { stateDir, configName } = resolveConfigIdentity(configPath);
2887
+ const dir = join4(secretsHome(), ".engine7-secrets");
2888
+ mkdirSync2(dir, { recursive: true });
2889
+ const file = secretsCandidates(stateDir, configName)[0];
2890
+ const seedFrom = existsSync3(file) ? file : secretsCandidates(stateDir, configName).find((p) => existsSync3(p)) ?? null;
2891
+ const lines = [];
2892
+ if (seedFrom) {
2893
+ for (const line of readFileSync3(seedFrom, "utf8").split(/\r?\n/)) {
2894
+ if (new RegExp(`^\\s*${envKey}\\s*=`).test(line)) continue;
2895
+ lines.push(line);
2896
+ }
2897
+ }
2898
+ while (lines.length && lines[lines.length - 1] === "") lines.pop();
2899
+ lines.push(`${envKey}=${value}`);
2900
+ writeFileSync2(file, lines.join("\n") + "\n", { mode: 384 });
2901
+ try {
2902
+ chmodSync(file, 384);
2903
+ } catch {
2904
+ }
2905
+ return file;
2906
+ }
2907
+ var init_secrets_env = __esm({
2908
+ "src/config/secrets-env.ts"() {
2909
+ "use strict";
2910
+ }
2911
+ });
2912
+
2913
+ // src/travel/oss-broker.ts
2914
+ var oss_broker_exports = {};
2915
+ __export(oss_broker_exports, {
2916
+ brokerOssConfig: () => brokerOssConfig,
2917
+ clearOssRequests: () => clearOssRequests,
2918
+ prepareOssRequests: () => prepareOssRequests,
2919
+ settleOssBroker: () => settleOssBroker,
2920
+ signedOssRequest: () => signedOssRequest,
2921
+ withOssBatches: () => withOssBatches
2922
+ });
2923
+ import { randomBytes } from "node:crypto";
2924
+ import { readFileSync as readFileSync4 } from "node:fs";
2925
+ function clearOssRequests(config) {
2926
+ cache.delete(config);
2927
+ }
2928
+ function validateAuthorization(config, value, operations) {
2929
+ if (!value || !Number.isSafeInteger(value.expiresAt) || value.expiresAt > Date.now() / 1e3 + 960 || !Array.isArray(value.objects) || value.objects.length !== operations.length) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
2930
+ if (!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(value.bucket) || !/^oss-[a-z0-9-]+(?:-internal)?\.aliyuncs\.com$/.test(value.endpoint) && !/^http:\/\/127\.0\.0\.1:\d+$/.test(value.endpoint)) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
2931
+ if (config.bucket && config.bucket !== value.bucket || config.endpoint && config.endpoint !== value.endpoint) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
2932
+ let tokenId = config.broker.tokenId;
2933
+ for (let i = 0; i < operations.length; i++) {
2934
+ const expected = operations[i], actual = value.objects[i], url = new URL(actual.url);
2935
+ const local = value.endpoint.startsWith("http://127.0.0.1:");
2936
+ const host = local ? new URL(value.endpoint).host : `${value.bucket}.${value.endpoint}`;
2937
+ const root = (local ? "/" + value.bucket : "") + "/chunks/7yi/";
2938
+ const [owner, transferId, ...key] = url.pathname.slice(root.length).split("/");
2939
+ if (!url.pathname.startsWith(root) || !owner || !/^[1-9][0-9]{0,18}$/.test(owner) || transferId !== config.broker.transferId || key.join("/") !== expected.key || tokenId && owner !== tokenId) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
2940
+ tokenId = owner;
2941
+ if (actual.method !== expected.method || actual.key !== expected.key || url.host !== host || url.protocol !== (local ? "http:" : "https:") || url.username || url.password || url.hash || !actual.headers || Object.keys(actual.headers).some((k) => !["Content-MD5", "Content-Type"].includes(k))) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
2942
+ if (expected.method === "PUT" && (actual.headers["Content-MD5"] !== expected.contentMD5 || actual.headers["Content-Type"] !== expected.contentType)) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
2943
+ }
2944
+ config.broker.tokenId = tokenId;
2945
+ }
2946
+ async function authorizeHttp(config, operations) {
2947
+ const broker = config.broker;
2948
+ let result;
2949
+ try {
2950
+ const internal = broker.internal ?? config.endpoint.includes("-internal.");
2951
+ const body = { transferId: broker.transferId, internal, ...broker.region !== void 0 ? { region: broker.region } : {}, ...config.bucket ? { bucket: config.bucket } : {}, objects: operations };
2952
+ const response = await fetch(broker.url, { method: "POST", redirect: "error", headers: { Authorization: "Bearer " + broker.apiKey, "Content-Type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(2e4) });
2953
+ if (!response.ok) {
2954
+ await response.body?.cancel();
2955
+ throw Error(`TRAVEL_OSS_AUTHORIZATION_HTTP_${response.status}`);
2956
+ }
2957
+ result = await response.json();
2958
+ validateAuthorization(config, result, operations);
2959
+ } catch (error) {
2960
+ if (error instanceof Error && /^TRAVEL_OSS_AUTHORIZATION_HTTP_[0-9]{3}$/.test(error.message)) throw error;
2961
+ throw Error("TRAVEL_OSS_AUTHORIZATION_FAILED");
2962
+ }
2963
+ return result;
2964
+ }
2965
+ async function settleOssBroker(config) {
2966
+ if (!config.broker) return config;
2967
+ const result = await authorizeHttp(config, []);
2968
+ if (!config.bucket) config.bucket = result.bucket;
2969
+ if (!config.endpoint) config.endpoint = result.endpoint;
2970
+ if (config.broker && result.region !== void 0) config.broker.bucketRegion = result.region;
2971
+ return config;
2972
+ }
2973
+ async function authorize(config, operations, background = false) {
2974
+ const broker = config.broker;
2975
+ let queue = signingQueues.get(broker);
2976
+ if (!queue) {
2977
+ queue = { tail: Promise.resolve(), last: 0 };
2978
+ signingQueues.set(broker, queue);
2979
+ }
2980
+ const current = queue;
2981
+ const result = current.tail.catch(() => {
2982
+ }).then(async () => {
2983
+ const wait = 1e3 - (Date.now() - current.last);
2984
+ if (wait > 0) await new Promise((resolve4) => {
2985
+ const timer = setTimeout(resolve4, wait);
2986
+ if (background) timer.unref();
2987
+ });
2988
+ try {
2989
+ return await authorizeHttp(config, operations);
2990
+ } finally {
2991
+ current.last = Date.now();
2992
+ }
2993
+ });
2994
+ current.tail = result;
2995
+ return result;
2996
+ }
2997
+ async function prepareOssRequests(config, operations, background = false) {
2998
+ if (!config.broker) return;
2999
+ let entries = cache.get(config);
3000
+ if (!entries) {
3001
+ entries = /* @__PURE__ */ new Map();
3002
+ cache.set(config, entries);
3003
+ }
3004
+ const missing = operations.filter((o) => (entries.get(cacheKey(o))?.expiresAt ?? 0) <= Date.now() / 1e3 + 30);
3005
+ for (let i = 0; i < missing.length; i += 128) {
3006
+ const batch = missing.slice(i, i + 128), result = await authorize(config, batch, background);
3007
+ for (const [index, object] of result.objects.entries()) entries.set(cacheKey(batch[index]), { object, expiresAt: result.expiresAt });
3008
+ }
3009
+ }
3010
+ async function withOssBatches(config, items, operation, transfer, background = false) {
3011
+ for (let i = 0; i < items.length; i += 128) {
3012
+ const batch = items.slice(i, i + 128), operations = batch.map(operation);
3013
+ try {
3014
+ await prepareOssRequests(config, operations, background);
3015
+ await transfer(batch);
3016
+ } finally {
3017
+ for (const op of operations) cache.get(config)?.delete(cacheKey(op));
3018
+ }
3019
+ }
3020
+ }
3021
+ async function signedOssRequest(config, operation, refresh = false) {
3022
+ if (refresh) cache.get(config)?.delete(cacheKey(operation));
3023
+ for (let attempt = 0; attempt < 2; attempt++) {
3024
+ await prepareOssRequests(config, [operation]);
3025
+ const entry = cache.get(config)?.get(cacheKey(operation));
3026
+ if (entry && entry.expiresAt > Date.now() / 1e3 + 30) return entry.object;
3027
+ }
3028
+ throw Error("TRAVEL_OSS_AUTHORIZATION_EXPIRED");
3029
+ }
3030
+ async function brokerOssConfig(configPath, options = {}) {
3031
+ if (!configPath) return null;
3032
+ const { isUnresolvedEnvRef: isUnresolvedEnvRef2, makeEnvResolver: makeEnvResolver2 } = await Promise.resolve().then(() => (init_loader(), loader_exports));
3033
+ const { FREE_TIER_RELAY_URL: FREE_TIER_RELAY_URL2 } = await Promise.resolve().then(() => (init_cli_init_config(), cli_init_config_exports));
3034
+ const { loadSecretsEnvForConfig: loadSecretsEnvForConfig2 } = await Promise.resolve().then(() => (init_secrets_env(), secrets_env_exports));
3035
+ let providers;
3036
+ try {
3037
+ loadSecretsEnvForConfig2(configPath);
3038
+ const raw = makeEnvResolver2()(JSON.parse(readFileSync4(configPath, "utf8")));
3039
+ providers = { ...raw.models?.providers, ...raw.providers };
3040
+ } catch {
3041
+ return null;
3042
+ }
3043
+ const candidates = Object.entries(providers).sort(([a], [b]) => Number(b === "7yi-free") - Number(a === "7yi-free"));
3044
+ const relayOrigin = new URL(FREE_TIER_RELAY_URL2).origin;
3045
+ const tried = /* @__PURE__ */ new Set();
3046
+ let credentialRejected = false;
3047
+ for (const [providerId2, provider] of candidates) {
3048
+ if (!provider.apiKey || isUnresolvedEnvRef2(provider.apiKey)) continue;
3049
+ if (providerId2 !== "7yi" && !providerId2.startsWith("7yi-")) {
3050
+ if (!provider.baseUrl) continue;
3051
+ let base;
3052
+ try {
3053
+ base = new URL(provider.baseUrl);
3054
+ } catch {
3055
+ continue;
3056
+ }
3057
+ if (base.protocol !== "https:" || base.username || base.password || base.origin !== relayOrigin) continue;
3058
+ }
3059
+ const credential = provider.apiKey;
3060
+ if (tried.has(credential)) continue;
3061
+ tried.add(credential);
3062
+ const config = { bucket: "", endpoint: "", broker: { url: relayOrigin + "/api/engine7/oss/sign", apiKey: provider.apiKey, transferId: randomBytes(32).toString("hex"), providerId: providerId2, ...options.region !== void 0 ? { region: options.region } : {} } };
3063
+ let result;
3064
+ try {
3065
+ result = await authorize(config, []);
3066
+ } catch (error) {
3067
+ if (error instanceof Error && /^TRAVEL_OSS_AUTHORIZATION_HTTP_(401|403)$/.test(error.message)) {
3068
+ credentialRejected = true;
3069
+ continue;
3070
+ }
3071
+ throw error;
3072
+ }
3073
+ config.bucket = result.bucket;
3074
+ config.endpoint = result.endpoint;
3075
+ if (result.region !== void 0) config.broker.bucketRegion = result.region;
3076
+ return config;
3077
+ }
3078
+ if (credentialRejected) throw Error("TRAVEL_OSS_CREDENTIALS_UNAVAILABLE");
3079
+ return null;
3080
+ }
3081
+ var cache, signingQueues, cacheKey;
3082
+ var init_oss_broker = __esm({
3083
+ "src/travel/oss-broker.ts"() {
3084
+ "use strict";
3085
+ cache = /* @__PURE__ */ new WeakMap();
3086
+ signingQueues = /* @__PURE__ */ new WeakMap();
3087
+ cacheKey = (o) => JSON.stringify([o.method, o.key, o.contentMD5 ?? "", o.contentType ?? ""]);
3088
+ }
3089
+ });
3090
+
3091
+ // src/travel/cloud-region.ts
3092
+ var cloud_region_exports = {};
3093
+ __export(cloud_region_exports, {
3094
+ cloudRegion: () => cloudRegion,
3095
+ ossRouteBlock: () => ossRouteBlock,
3096
+ readCloudRegion: () => readCloudRegion
3097
+ });
3098
+ async function readCloudRegion(fetchImpl = fetch) {
3099
+ if (process.env.ENGINE7_TRAVEL_TEST_REGION !== void 0) return process.env.ENGINE7_TRAVEL_TEST_REGION;
3100
+ try {
3101
+ const response = await fetchImpl("http://100.100.100.200/latest/meta-data/region-id", { signal: AbortSignal.timeout(1e3) });
3102
+ if (!response.ok) return "";
3103
+ const region = (await response.text()).trim();
3104
+ return /^[a-z0-9-]{1,32}$/.test(region) ? region : "";
3105
+ } catch {
3106
+ return "";
3107
+ }
3108
+ }
3109
+ function ossRouteBlock(region, bucketRegion) {
3110
+ if (!region) return "\u4E91\u673A\u5730\u57DF\u672A\u77E5\uFF0COSS \u53EA\u80FD\u8D70\u516C\u7F51";
3111
+ if (bucketRegion === void 0) return "";
3112
+ if (region === bucketRegion || mainland(region) && mainland(bucketRegion)) return "";
3113
+ return `\u4E91\u673A\u5728 ${region}\u3001\u6876\u5728 ${bucketRegion}\uFF0C\u8DE8\u5883\u516C\u7F51\u6BD4 ssh \u8FD8\u6162`;
3114
+ }
3115
+ var cloudRegionPromise, cloudRegion, mainland;
3116
+ var init_cloud_region = __esm({
3117
+ "src/travel/cloud-region.ts"() {
3118
+ "use strict";
3119
+ cloudRegion = () => cloudRegionPromise ??= readCloudRegion();
3120
+ mainland = (region) => region.startsWith("cn-") && !region.startsWith("cn-hongkong");
3121
+ }
3122
+ });
3123
+
1
3124
  // src/travel/oss-bundle-stream.ts
2
- import { readFileSync as readFileSync3, existsSync as existsSync3 } from "node:fs";
3125
+ import { readFileSync as readFileSync6, existsSync as existsSync5 } from "node:fs";
3
3126
  import { fileURLToPath } from "node:url";
4
3127
  import { isAbsolute } from "node:path";
5
3128
 
@@ -26,7 +3149,7 @@ import { promisify } from "node:util";
26
3149
  import { dirname, join } from "node:path";
27
3150
  var CHUNK_BYTES = 4 * 1024 * 1024;
28
3151
  var DATABASE_CHUNK_BYTES = 64 * 1024;
29
- var chunkBytesFor = (path) => /\.(db|sqlite)(-wal|-shm)?$/.test(path) ? DATABASE_CHUNK_BYTES : CHUNK_BYTES;
3152
+ var chunkBytesFor = (path4) => /\.(db|sqlite)(-wal|-shm)?$/.test(path4) ? DATABASE_CHUNK_BYTES : CHUNK_BYTES;
30
3153
  var SHA = /^[a-f0-9]{64}$/;
31
3154
  var sha256 = (body) => createHash("sha256").update(body).digest("hex");
32
3155
  var compress = promisify(gzip);
@@ -54,8 +3177,8 @@ var ChunkStore = class {
54
3177
  chunkPath(sha) {
55
3178
  return join(this.dir, sha + ".gz");
56
3179
  }
57
- fingerprint(path) {
58
- const s = lstatSync(path, { bigint: true });
3180
+ fingerprint(path4) {
3181
+ const s = lstatSync(path4, { bigint: true });
59
3182
  if (!s.isFile()) throw Error("TRAVEL_CHUNK_CORRUPT");
60
3183
  return [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].join(":");
61
3184
  }
@@ -63,13 +3186,13 @@ var ChunkStore = class {
63
3186
  async put(body) {
64
3187
  if (!(body instanceof Buffer) || body.length < 1 || body.length > CHUNK_BYTES) throw new Error("TRAVEL_INVALID_CHUNK");
65
3188
  const stable = Buffer.from(body), ref = { sha256: sha256(stable), bytes: stable.length };
66
- const path = this.chunkPath(ref.sha256);
3189
+ const path4 = this.chunkPath(ref.sha256);
67
3190
  if (!await this.has(ref.sha256)) {
68
- const temp = path + "." + randomUUID() + ".tmp";
3191
+ const temp = path4 + "." + randomUUID() + ".tmp";
69
3192
  try {
70
3193
  writeFileSync(temp, await compress(stable), { flag: "wx", mode: 384 });
71
- renameSync(temp, path);
72
- this.verified.set(ref.sha256, this.fingerprint(path));
3194
+ renameSync(temp, path4);
3195
+ this.verified.set(ref.sha256, this.fingerprint(path4));
73
3196
  } finally {
74
3197
  try {
75
3198
  if (existsSync(temp)) unlinkSync(temp);
@@ -217,106 +3340,9 @@ function openChunkStore(dir) {
217
3340
  }
218
3341
 
219
3342
  // src/travel/oss-transport.ts
220
- import { createHmac, createHash as createHash2 } from "node:crypto";
221
-
222
- // src/travel/oss-broker.ts
223
- var cache = /* @__PURE__ */ new WeakMap();
224
- var signingQueues = /* @__PURE__ */ new WeakMap();
225
- var cacheKey = (o) => JSON.stringify([o.method, o.key, o.contentMD5 ?? "", o.contentType ?? ""]);
226
- function validateAuthorization(config, value, operations) {
227
- if (!value || !Number.isSafeInteger(value.expiresAt) || value.expiresAt > Date.now() / 1e3 + 960 || !Array.isArray(value.objects) || value.objects.length !== operations.length) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
228
- if (!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(value.bucket) || !/^oss-[a-z0-9-]+(?:-internal)?\.aliyuncs\.com$/.test(value.endpoint) && !/^http:\/\/127\.0\.0\.1:\d+$/.test(value.endpoint)) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
229
- if (config.bucket && config.bucket !== value.bucket || config.endpoint && config.endpoint !== value.endpoint) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
230
- let tokenId = config.broker.tokenId;
231
- for (let i = 0; i < operations.length; i++) {
232
- const expected = operations[i], actual = value.objects[i], url = new URL(actual.url);
233
- const local = value.endpoint.startsWith("http://127.0.0.1:");
234
- const host = local ? new URL(value.endpoint).host : `${value.bucket}.${value.endpoint}`;
235
- const root = (local ? "/" + value.bucket : "") + "/chunks/7yi/";
236
- const [owner, transferId, ...key] = url.pathname.slice(root.length).split("/");
237
- if (!url.pathname.startsWith(root) || !owner || !/^[1-9][0-9]{0,18}$/.test(owner) || transferId !== config.broker.transferId || key.join("/") !== expected.key || tokenId && owner !== tokenId) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
238
- tokenId = owner;
239
- if (actual.method !== expected.method || actual.key !== expected.key || url.host !== host || url.protocol !== (local ? "http:" : "https:") || url.username || url.password || url.hash || !actual.headers || Object.keys(actual.headers).some((k) => !["Content-MD5", "Content-Type"].includes(k))) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
240
- if (expected.method === "PUT" && (actual.headers["Content-MD5"] !== expected.contentMD5 || actual.headers["Content-Type"] !== expected.contentType)) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
241
- }
242
- config.broker.tokenId = tokenId;
243
- }
244
- async function authorizeHttp(config, operations) {
245
- const broker = config.broker;
246
- let result;
247
- try {
248
- const response = await fetch(broker.url, { method: "POST", redirect: "error", headers: { Authorization: "Bearer " + broker.apiKey, "Content-Type": "application/json" }, body: JSON.stringify({ transferId: broker.transferId, internal: config.endpoint.includes("-internal."), objects: operations }), signal: AbortSignal.timeout(2e4) });
249
- if (!response.ok) {
250
- await response.body?.cancel();
251
- throw Error(`TRAVEL_OSS_AUTHORIZATION_HTTP_${response.status}`);
252
- }
253
- result = await response.json();
254
- validateAuthorization(config, result, operations);
255
- } catch (error) {
256
- if (error instanceof Error && /^TRAVEL_OSS_AUTHORIZATION_HTTP_[0-9]{3}$/.test(error.message)) throw error;
257
- throw Error("TRAVEL_OSS_AUTHORIZATION_FAILED");
258
- }
259
- return result;
260
- }
261
- async function authorize(config, operations, background = false) {
262
- const broker = config.broker;
263
- let queue = signingQueues.get(broker);
264
- if (!queue) {
265
- queue = { tail: Promise.resolve(), last: 0 };
266
- signingQueues.set(broker, queue);
267
- }
268
- const current = queue;
269
- const result = current.tail.catch(() => {
270
- }).then(async () => {
271
- const wait = 1e3 - (Date.now() - current.last);
272
- if (wait > 0) await new Promise((resolve2) => {
273
- const timer = setTimeout(resolve2, wait);
274
- if (background) timer.unref();
275
- });
276
- try {
277
- return await authorizeHttp(config, operations);
278
- } finally {
279
- current.last = Date.now();
280
- }
281
- });
282
- current.tail = result;
283
- return result;
284
- }
285
- async function prepareOssRequests(config, operations, background = false) {
286
- if (!config.broker) return;
287
- let entries = cache.get(config);
288
- if (!entries) {
289
- entries = /* @__PURE__ */ new Map();
290
- cache.set(config, entries);
291
- }
292
- const missing = operations.filter((o) => (entries.get(cacheKey(o))?.expiresAt ?? 0) <= Date.now() / 1e3 + 30);
293
- for (let i = 0; i < missing.length; i += 128) {
294
- const batch = missing.slice(i, i + 128), result = await authorize(config, batch, background);
295
- for (const [index, object] of result.objects.entries()) entries.set(cacheKey(batch[index]), { object, expiresAt: result.expiresAt });
296
- }
297
- }
298
- async function withOssBatches(config, items, operation, transfer, background = false) {
299
- for (let i = 0; i < items.length; i += 128) {
300
- const batch = items.slice(i, i + 128), operations = batch.map(operation);
301
- try {
302
- await prepareOssRequests(config, operations, background);
303
- await transfer(batch);
304
- } finally {
305
- for (const op of operations) cache.get(config)?.delete(cacheKey(op));
306
- }
307
- }
308
- }
309
- async function signedOssRequest(config, operation, refresh = false) {
310
- if (refresh) cache.get(config)?.delete(cacheKey(operation));
311
- for (let attempt = 0; attempt < 2; attempt++) {
312
- await prepareOssRequests(config, [operation]);
313
- const entry = cache.get(config)?.get(cacheKey(operation));
314
- if (entry && entry.expiresAt > Date.now() / 1e3 + 30) return entry.object;
315
- }
316
- throw Error("TRAVEL_OSS_AUTHORIZATION_EXPIRED");
317
- }
318
-
319
- // src/travel/oss-transport.ts
3343
+ import { createHmac, createHash as createHash3 } from "node:crypto";
3344
+ init_oss_broker();
3345
+ init_oss_broker();
320
3346
  function ossFailureCode(error) {
321
3347
  const message = error instanceof Error ? error.message : "";
322
3348
  const code = /^TRAVEL_[A-Z_0-9]+/.exec(message)?.[0];
@@ -396,7 +3422,7 @@ async function ossFetch(config, method, resourcePath, body, headers = {}, okCode
396
3422
  return response;
397
3423
  }
398
3424
  function md5Base64(body) {
399
- return createHash2("md5").update(body).digest("base64");
3425
+ return createHash3("md5").update(body).digest("base64");
400
3426
  }
401
3427
  function objectPath(key) {
402
3428
  if (!/^[A-Za-z0-9/_.-]+$/.test(key) || key.startsWith("/") || key.includes("..")) throw Error("TRAVEL_OSS_INVALID_OBJECT_KEY");
@@ -430,7 +3456,7 @@ async function ossGetObject(config, key, maxBytes = 64 * 1048576) {
430
3456
  }
431
3457
 
432
3458
  // src/travel/oss-bundle.ts
433
- import { createHash as createHash3 } from "node:crypto";
3459
+ import { createHash as createHash4 } from "node:crypto";
434
3460
  import { gzip as gzip2, gunzip } from "node:zlib";
435
3461
  import { promisify as promisify2 } from "node:util";
436
3462
  var BUNDLE_GZIP_MAX = 8 * 1048576;
@@ -455,19 +3481,19 @@ function validateBundleRef(value) {
455
3481
  async function unpackBundle(body, expected) {
456
3482
  if (body.length > BUNDLE_GZIP_MAX || !/^[a-f0-9]{64}$/.test(expected.sha256) || !Number.isSafeInteger(expected.plainBytes) || expected.plainBytes > BUNDLE_RAW_MAX + BUNDLE_HEADER_MAX + 12) throw Error("TRAVEL_INVALID_BUNDLE");
457
3483
  const plain = await unzip(body, { maxOutputLength: BUNDLE_RAW_MAX + BUNDLE_HEADER_MAX + 12 });
458
- if (plain.length !== expected.plainBytes || createHash3("sha256").update(plain).digest("hex") !== expected.sha256 || !plain.subarray(0, 8).equals(MAGIC)) throw Error("TRAVEL_BUNDLE_CORRUPT");
3484
+ if (plain.length !== expected.plainBytes || createHash4("sha256").update(plain).digest("hex") !== expected.sha256 || !plain.subarray(0, 8).equals(MAGIC)) throw Error("TRAVEL_BUNDLE_CORRUPT");
459
3485
  const size = plain.readUInt32BE(8);
460
3486
  if (!size || size > BUNDLE_HEADER_MAX || 12 + size > plain.length) throw Error("TRAVEL_BUNDLE_CORRUPT");
461
3487
  const header = JSON.parse(plain.subarray(12, 12 + size).toString());
462
3488
  if (header.version !== 1) throw Error("TRAVEL_INVALID_BUNDLE");
463
- if (expected.refsDigest && createHash3("sha256").update(JSON.stringify(header.refs)).digest("hex") !== expected.refsDigest) throw Error("TRAVEL_BUNDLE_CORRUPT");
3489
+ if (expected.refsDigest && createHash4("sha256").update(JSON.stringify(header.refs)).digest("hex") !== expected.refsDigest) throw Error("TRAVEL_BUNDLE_CORRUPT");
464
3490
  const bundle = { ...expected, refs: header.refs };
465
3491
  validateBundleRef(bundle);
466
3492
  const parts = [];
467
3493
  let offset = 12 + size;
468
3494
  for (const ref of bundle.refs) {
469
3495
  const part = plain.subarray(offset, offset + ref.bytes);
470
- if (part.length !== ref.bytes || createHash3("sha256").update(part).digest("hex") !== ref.sha256) throw Error("TRAVEL_CHUNK_CORRUPT");
3496
+ if (part.length !== ref.bytes || createHash4("sha256").update(part).digest("hex") !== ref.sha256) throw Error("TRAVEL_CHUNK_CORRUPT");
471
3497
  parts.push({ ref, body: part });
472
3498
  offset += ref.bytes;
473
3499
  }
@@ -476,21 +3502,21 @@ async function unpackBundle(body, expected) {
476
3502
  }
477
3503
 
478
3504
  // src/travel/apply-transaction.ts
479
- import { closeSync as closeSync2, existsSync as existsSync2, fsyncSync as fsyncSync2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync2, readSync as readSync2, renameSync as renameSync2, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
480
- import { dirname as dirname2, join as join2, resolve } from "node:path";
3505
+ import { closeSync as closeSync2, existsSync as existsSync4, fsyncSync as fsyncSync2, linkSync, lstatSync as lstatSync2, mkdirSync as mkdirSync3, openSync as openSync2, readFileSync as readFileSync5, readSync as readSync2, renameSync as renameSync2, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
3506
+ import { dirname as dirname3, join as join5, resolve as resolve3 } from "node:path";
481
3507
  var safeRel = (rel) => !!rel && !/[\\:\x00-\x1f]/.test(rel) && rel.split("/").every((p) => p && p !== "." && p !== "..");
482
3508
  function assertPath(root, rel) {
483
3509
  if (!safeRel(rel)) throw Error("TRAVEL_UNSAFE_PATH");
484
- let path = root;
3510
+ let path4 = root;
485
3511
  for (const part of rel.split("/")) {
486
- path = join2(path, part);
3512
+ path4 = join5(path4, part);
487
3513
  try {
488
- if (lstatSync2(path).isSymbolicLink()) throw Error("TRAVEL_UNSAFE_PATH");
3514
+ if (lstatSync2(path4).isSymbolicLink()) throw Error("TRAVEL_UNSAFE_PATH");
489
3515
  } catch (e) {
490
3516
  if (e.code !== "ENOENT") throw e;
491
3517
  }
492
3518
  }
493
- return path;
3519
+ return path4;
494
3520
  }
495
3521
 
496
3522
  // src/travel/oss-bundle-stream.ts
@@ -534,7 +3560,18 @@ function makeBundleReceiver(root, config) {
534
3560
  };
535
3561
  }
536
3562
  async function runOssBundleStream(root, initial, lines, send) {
537
- const receive = makeBundleReceiver(root, { ...initial, endpoint: internalEndpointOf(initial.endpoint) }), jobs = /* @__PURE__ */ new Set();
3563
+ const { settleOssBroker: settleOssBroker2 } = await Promise.resolve().then(() => (init_oss_broker(), oss_broker_exports));
3564
+ const { cloudRegion: cloudRegion2 } = await Promise.resolve().then(() => (init_cloud_region(), cloud_region_exports));
3565
+ const legacy = { ...initial, endpoint: internalEndpointOf(initial.endpoint) };
3566
+ let config = legacy;
3567
+ if (initial.broker) {
3568
+ try {
3569
+ config = await settleOssBroker2({ ...initial, endpoint: "", broker: { ...initial.broker, region: await cloudRegion2(), internal: true } });
3570
+ } catch {
3571
+ config = legacy;
3572
+ }
3573
+ }
3574
+ const receive = makeBundleReceiver(root, config), jobs = /* @__PURE__ */ new Set();
538
3575
  send({ ready: true });
539
3576
  for await (const line of lines) {
540
3577
  const input = JSON.parse(line);
@@ -549,16 +3586,16 @@ async function runOssBundleStream(root, initial, lines, send) {
549
3586
  function openBundleStream(options) {
550
3587
  let source = options.source;
551
3588
  if (!source) {
552
- for (const url of [new URL("./travel-oss-bundle-stream.mjs", import.meta.url), new URL("../../dist/travel-oss-bundle-stream.mjs", import.meta.url)]) if (existsSync3(fileURLToPath(url))) {
553
- source = readFileSync3(url, "utf8");
3589
+ for (const url of [new URL("./travel-oss-bundle-stream.mjs", import.meta.url), new URL("../../dist/travel-oss-bundle-stream.mjs", import.meta.url)]) if (existsSync5(fileURLToPath(url))) {
3590
+ source = readFileSync6(url, "utf8");
554
3591
  break;
555
3592
  }
556
3593
  }
557
3594
  if (!source) throw Error("TRAVEL_OSS_HELPER_MISSING");
558
3595
  const child = options.spawn("node --input-type=module -e " + quote(bootstrap)), pending = /* @__PURE__ */ new Map();
559
3596
  let sequence = 0, text = "", settled = false, closed = false, resolveReady, rejectReady;
560
- const ready = new Promise((resolve2, reject) => {
561
- resolveReady = resolve2;
3597
+ const ready = new Promise((resolve4, reject) => {
3598
+ resolveReady = resolve4;
562
3599
  rejectReady = reject;
563
3600
  });
564
3601
  const fail = () => {
@@ -609,8 +3646,8 @@ function openBundleStream(options) {
609
3646
  await ready;
610
3647
  if (closed) throw Error("TRAVEL_OSS_BUNDLE_CONNECTION_CLOSED");
611
3648
  const id = ++sequence;
612
- return new Promise((resolve2, reject) => {
613
- pending.set(id, { resolve: resolve2, reject });
3649
+ return new Promise((resolve4, reject) => {
3650
+ pending.set(id, { resolve: resolve4, reject });
614
3651
  child.stdin.write(JSON.stringify({ id, bundles }) + "\n", (error) => {
615
3652
  if (error) {
616
3653
  pending.delete(id);