evolcore 0.0.41-test.0 → 0.0.41-test.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/agents/baseagent-availability.js +1 -1
  3. package/dist/agents/baseagent.js +20 -43
  4. package/dist/agents/claude-runner.js +177 -92
  5. package/dist/agents/codex-runner.js +84 -28
  6. package/dist/agents/ecagent-runner.js +1 -1
  7. package/dist/agents/gemini-runner.js +1 -1
  8. package/dist/aun/group/fs-download.js +39 -0
  9. package/dist/aun/group/identity.js +36 -21
  10. package/dist/aun/group/operations.js +5 -0
  11. package/dist/aun/msg/managed-operation.js +68 -7
  12. package/dist/aun/msg/p2p.js +5 -0
  13. package/dist/aun/service-proxy.js +36 -12
  14. package/dist/channels/aun.js +334 -20
  15. package/dist/channels/daemon.js +15 -1
  16. package/dist/cli/aun-commands.js +4 -20
  17. package/dist/cli/daemon-commands.js +678 -697
  18. package/dist/cli/fs-command.js +64 -2
  19. package/dist/cli/index.js +48 -4
  20. package/dist/cli/managed-command-guard.js +4 -0
  21. package/dist/cli/model.js +40 -40
  22. package/dist/cli/proxy-command.js +92 -0
  23. package/dist/cli/role.js +85 -0
  24. package/dist/config/access-policy.js +7 -2
  25. package/dist/config/boot-log.js +38 -1
  26. package/dist/config/config-field-policy.js +5 -32
  27. package/dist/config/config-manager.js +46 -39
  28. package/dist/config/config-operation-service.js +5 -19
  29. package/dist/config/contact-book-store.js +47 -21
  30. package/dist/config/contact-book.js +18 -12
  31. package/dist/config/contact-operation-service.js +3 -4
  32. package/dist/config/contact-request-service.js +11 -0
  33. package/dist/config/daemon-services.js +11 -0
  34. package/dist/config/gateway-config.js +88 -594
  35. package/dist/config/peer-role-resolver.js +13 -11
  36. package/dist/config/providers-config.js +12 -7
  37. package/dist/config/providers-import.js +3 -21
  38. package/dist/config/resolved-config-op.js +3 -0
  39. package/dist/config/role-command-service.js +166 -0
  40. package/dist/config/role-request-service.js +193 -0
  41. package/dist/config/schema-migration.js +686 -25
  42. package/dist/config-store.js +79 -3
  43. package/dist/contracts/ecweb-instance.js +41 -0
  44. package/dist/contracts/ecweb-service-protocol.js +3 -1
  45. package/dist/core/agent-runtime.js +1 -1
  46. package/dist/core/auth/agent-delegation.js +2 -1
  47. package/dist/core/auth/auth-gateway.js +1 -1
  48. package/dist/core/auth/authorization-audit.js +17 -6
  49. package/dist/core/auth/delegation-authorization.js +3 -1
  50. package/dist/core/auth/operation-authorizer.js +15 -0
  51. package/dist/core/auth/operation-catalog.js +31 -6
  52. package/dist/core/command/agent-control.js +3 -7
  53. package/dist/core/command/agent-storage-menu.js +5 -3
  54. package/dist/core/command/cli-intent-parser.js +2 -1
  55. package/dist/core/command/command-handler.js +48 -99
  56. package/dist/core/command/connect-menu.js +11 -3
  57. package/dist/core/command/data-root-resolver.js +5 -4
  58. package/dist/core/command/memory-slash.js +16 -8
  59. package/dist/core/command/menu-catalog.js +5 -6
  60. package/dist/core/command/menu-handler.js +49 -62
  61. package/dist/core/command/role-menu.js +147 -30
  62. package/dist/core/command/slash-handler.js +123 -254
  63. package/dist/core/daemon-control.js +8 -14
  64. package/dist/core/evolagent-registry.js +4 -4
  65. package/dist/core/evolagent.js +2 -2
  66. package/dist/core/inference/text-inference.js +31 -40
  67. package/dist/core/ipc-registration.js +6 -2
  68. package/dist/core/memory/consolidation-context.js +51 -5
  69. package/dist/core/memory/consolidation-ops-records.js +1 -1
  70. package/dist/core/memory/consolidation-trigger.js +189 -189
  71. package/dist/core/memory/consolidation.js +316 -29
  72. package/dist/core/memory/forget-log.js +96 -0
  73. package/dist/core/memory/index-manager.js +27 -5
  74. package/dist/core/memory/memory-admin.js +45 -5
  75. package/dist/core/memory/memory-writer.js +163 -18
  76. package/dist/core/memory/relation-idle-monitor.js +119 -58
  77. package/dist/core/memory/relation-sweep.js +44 -39
  78. package/dist/core/message/aun-ipc-sender.js +8 -2
  79. package/dist/core/message/im-renderer.js +7 -4
  80. package/dist/core/message/message-admission.js +89 -4
  81. package/dist/core/message/message-bridge.js +31 -18
  82. package/dist/core/message/response-engine.js +77 -8
  83. package/dist/core/model/catalog-service.js +4 -2
  84. package/dist/core/model/config-scope.js +24 -64
  85. package/dist/core/model/field-scope.js +1 -1
  86. package/dist/core/model/model-catalog.js +30 -41
  87. package/dist/core/model/model-diagnostics.js +4 -3
  88. package/dist/core/model/model-fallback.js +10 -7
  89. package/dist/core/model/model-permission.js +3 -2
  90. package/dist/core/ownership/owner-resolver.js +23 -21
  91. package/dist/core/permission/ec-command-parser.js +30 -2
  92. package/dist/core/permission/sandbox-runtime.js +18 -1
  93. package/dist/core/permission/tool-policy.js +14 -3
  94. package/dist/core/relation/peer-identity.js +64 -1
  95. package/dist/core/role/runtime-policy.js +72 -13
  96. package/dist/core/session/session-capsule.js +1 -1
  97. package/dist/core/session/session-idle-monitor.js +1 -1
  98. package/dist/core/session/session-manager.js +20 -0
  99. package/dist/core/session/session-renew.js +3 -3
  100. package/dist/core/skill/index-generator.js +15 -5
  101. package/dist/core/system-session/memory.js +6 -1
  102. package/dist/core/thread/thread-service.js +19 -6
  103. package/dist/directory/owner-directory-admission.js +95 -0
  104. package/dist/directory/owner-directory-authorization.js +309 -0
  105. package/dist/directory/owner-directory-cache.js +635 -0
  106. package/dist/eck/kit-renderer.js +2 -2
  107. package/dist/ecweb/basic-settings-service.js +33 -40
  108. package/dist/ecweb/message-context-service.js +110 -0
  109. package/dist/index.js +76 -14
  110. package/dist/ipc.js +170 -12
  111. package/dist/paths.js +4 -0
  112. package/dist/proxy/command.js +122 -0
  113. package/dist/proxy/ipc-service.js +68 -0
  114. package/dist/proxy/manager.js +485 -0
  115. package/dist/proxy/service-supervisor.js +603 -0
  116. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  117. package/dist/utils/cross-platform.js +14 -0
  118. package/dist/utils/ecweb-supervisor.js +258 -83
  119. package/dist/utils/error-utils.js +2 -2
  120. package/dist/utils/logger.js +24 -5
  121. package/dist/utils/package-version-info.js +4 -2
  122. package/kits/docs/channels/aun.md +9 -0
  123. package/kits/docs/evolcore/agent.md +1 -1
  124. package/kits/docs/evolcore/config.md +17 -6
  125. package/kits/docs/evolcore/contact.md +3 -0
  126. package/kits/docs/evolcore/fs.md +11 -0
  127. package/kits/docs/evolcore/memory-architecture.md +2 -2
  128. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  129. package/kits/docs/evolcore/memory.md +1 -1
  130. package/kits/docs/evolcore/menu-protocol.md +4 -0
  131. package/kits/docs/evolcore/model.md +23 -20
  132. package/kits/docs/evolcore/msg.md +4 -7
  133. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  134. package/kits/schemas/_meta.json +37 -4
  135. package/kits/schemas/agent-config.schema.13.json +8 -3
  136. package/kits/schemas/agent-config.schema.16.json +891 -0
  137. package/kits/schemas/daemon.schema.9.json +366 -0
  138. package/kits/schemas/defaults.schema.5.json +406 -127
  139. package/kits/schemas/relation-config.schema.11.json +260 -0
  140. package/kits/schemas/role-config.schema.1.json +7 -7
  141. package/kits/skills/.switches.json +3 -7
  142. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  143. package/kits/skills/ec-trigger/SKILL.md +13 -5
  144. package/kits/skills/personal-assistant/SKILL.md +176 -0
  145. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  146. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  147. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  148. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  149. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  150. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  151. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  152. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  153. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  154. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  155. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  156. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  157. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  158. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  159. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  160. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  161. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  162. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  163. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  164. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  165. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  166. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  167. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  168. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  169. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  170. package/kits/templates/memory-consolidation/forget.md +19 -6
  171. package/kits/templates/memory-consolidation/notes.md +1 -1
  172. package/kits/templates/memory-consolidation/profile.md +2 -2
  173. package/kits/templates/memory-consolidation/promote.md +20 -3
  174. package/kits/templates/roles/member.json +8 -1
  175. package/kits/templates/system-fragments/baseagent.md +2 -2
  176. package/kits/templates/system-fragments/memory.md +4 -4
  177. package/package.json +6 -2
@@ -1,28 +1,28 @@
1
1
  /**
2
- * command-handler-gateway-control.ts — 网关(baseagent 后端)配置管理。
2
+ * gateway-config.ts — baseagent 模型选择与 provider 指认管理。
3
3
  *
4
- * "网关" = baseagent 的 baseUrl + apiKey + model 等接入配置。两级作用域:
5
- * - 'defaults':agents/defaults.json 的 baseagents 块(全局默认)
6
- * - <aid>:agents/<aid>/config.json 的 baseagents 块(单 agent 覆盖)
4
+ * 连接信息(baseUrl / apiKey / headers / queryParams)只存在于 providers.json;
5
+ * Agent 级 config.json 的 baseagents.<ba> 只承载 provider / model / effort / fallback
6
+ * 与 runner 自身运行参数。因此本模块只负责:
7
+ * - list:列出各 agent 的模型选择与所指向的 provider
8
+ * - update / delete:写 Agent 级 baseagents.<type> 的运行参数
9
+ * - test / models:经 providers.json 解析真实凭证做连通性与模型列表探测(key 不出 daemon)
10
+ * - set-price:写入网关价覆盖层 model-prices-gateway.jsonl
7
11
  *
8
- * 设计要点:
9
- * - 写入复用既有安全路径:saveDefaultsSafe(自动备份+深合并)/ saveAgent(校验)。
10
- * - apiKey 永不明文出站:list 时掩码,update 仅接受 "$ENV:NAME" 引用。
11
- * - test 在 daemon 内用 resolve*Config 解析真实 key 发请求,key 不离开进程。
12
- * - 写后触发 evolagent.reload 让运行中的 runner 重新解析凭证。
12
+ * 写后触发 evolagent.reload 让运行中的 runner 重新解析。
13
13
  */
14
14
  import fs from 'fs';
15
15
  import path from 'path';
16
16
  import { resolvePaths } from '../paths.js';
17
- import { saveDefaultsSafe, saveAgent } from '../config-store.js';
18
- import { resolveAnthropicConfig, resolveEcagentConfig, resolveOpenaiConfig } from '../agents/baseagent.js';
17
+ import { saveAgent } from '../config-store.js';
19
18
  import { buildModelRequestHeaders } from '../agents/request-identity.js';
20
19
  import { appendV1RequestPath } from '../agents/request-identity.js';
21
20
  import { resolvePriceRow } from '../stats/price-resolver.js';
22
21
  import { ipcQuery } from '../ipc.js';
23
22
  import { logger } from '../utils/logger.js';
24
- import { ConfigTarget, read as readConfig, stripLegacyAunGatewayConfig } from './config-manager.js';
25
- /** 已知 baseagent 类型(网关可管理范围)。 */
23
+ import { resolveProviderServiceForBaseagent } from './providers.js';
24
+ import { stripLegacyAunGatewayConfig } from './config-manager.js';
25
+ /** 已知 baseagent 类型(模型选择可管理范围)。 */
26
26
  const GATEWAY_TYPES = ['claude', 'codex', 'gemini', 'ecagent'];
27
27
  const DISPLAY_NAMES = {
28
28
  claude: 'Claude',
@@ -30,56 +30,6 @@ const DISPLAY_NAMES = {
30
30
  gemini: 'Gemini',
31
31
  ecagent: 'ecagent (EvolCore)',
32
32
  };
33
- // ── 掩码 ──
34
- const ENV_PREFIX = '$ENV:';
35
- // Claude Code supports both credential variable names. Keep AUTH_TOKEN first
36
- // to match the runtime resolver's precedence.
37
- const standardEnvKeys = {
38
- apiKey: ['ANTHROPIC_AUTH_TOKEN'],
39
- baseUrl: ['ANTHROPIC_BASE_URL'],
40
- };
41
- function envKeysForGateway(type, field) {
42
- if (type === 'claude' && field === 'apiKey')
43
- return ['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY'];
44
- return standardEnvKeys[field];
45
- }
46
- function firstEnvValue(env, names) {
47
- for (const name of names) {
48
- const value = env[name];
49
- if (value)
50
- return { name, value };
51
- }
52
- return undefined;
53
- }
54
- const DEBUG_SECRET_KEY = /(?:key|token|secret|password|authorization|credential|private)/i;
55
- function redactDebugValue(value, key) {
56
- if (typeof value === 'string') {
57
- if (value === '(未设置)')
58
- return value;
59
- if (key && DEBUG_SECRET_KEY.test(key) && !value.startsWith(ENV_PREFIX))
60
- return '***';
61
- return value;
62
- }
63
- if (Array.isArray(value))
64
- return value.map(item => redactDebugValue(item));
65
- if (value && typeof value === 'object') {
66
- return Object.fromEntries(Object.entries(value)
67
- .map(([childKey, childValue]) => [childKey, redactDebugValue(childValue, childKey)]));
68
- }
69
- return value;
70
- }
71
- function redactMismatchValue(value, field) {
72
- if (!value)
73
- return value;
74
- return field === 'apiKey' && !value.startsWith(ENV_PREFIX) ? '***' : value;
75
- }
76
- function maskApiKey(raw) {
77
- if (typeof raw !== 'string' || !raw)
78
- return { mask: undefined, isEnvRef: false };
79
- if (raw.startsWith(ENV_PREFIX))
80
- return { mask: raw, isEnvRef: true }; // $ENV 引用原样展示(非秘密)
81
- return { mask: '***', isEnvRef: false }; // 明文:隐藏真实值
82
- }
83
33
  // ── 读取 ──
84
34
  function readDefaultsRaw() {
85
35
  // loadDefaults 会展开 $ENV,掩码逻辑需看原始引用,故直接读盘
@@ -119,96 +69,56 @@ function listAgentAids() {
119
69
  return [];
120
70
  }
121
71
  }
122
- function extractEntries(raw, scope, includeEmpty = false) {
72
+ function extractEntries(raw, scope) {
123
73
  const out = [];
124
74
  const ba = raw?.baseagents;
125
- if (!ba || typeof ba !== 'object') {
126
- if (!includeEmpty)
127
- return out;
128
- for (const type of GATEWAY_TYPES) {
129
- out.push({
130
- scope,
131
- type,
132
- name: DISPLAY_NAMES[type] ?? type,
133
- apiKeyIsEnvRef: false,
134
- });
135
- }
75
+ if (!ba || typeof ba !== 'object')
136
76
  return out;
137
- }
138
77
  for (const type of GATEWAY_TYPES) {
139
78
  const c = ba[type];
140
- if ((!c || typeof c !== 'object') && !includeEmpty)
79
+ if (!c || typeof c !== 'object')
141
80
  continue;
142
- const cfg = c && typeof c === 'object' ? c : {};
143
- const { mask, isEnvRef } = maskApiKey(cfg.apiKey);
144
81
  out.push({
145
82
  scope,
146
83
  type,
147
84
  name: DISPLAY_NAMES[type] ?? type,
148
- baseUrl: cfg.baseUrl,
149
- apiKeyMask: mask,
150
- apiKeyIsEnvRef: isEnvRef,
151
- model: cfg.model,
152
- effort: cfg.effort ?? cfg.reasoning,
153
- mode: cfg.mode,
154
- cliPath: cfg.cliPath,
155
- useVertex: cfg.useVertex,
156
- project: cfg.project,
157
- location: cfg.location,
85
+ provider: c.provider,
86
+ model: c.model,
87
+ effort: c.effort,
88
+ cliPath: c.cliPath,
89
+ timeoutMs: c.timeoutMs,
90
+ maxRetries: c.maxRetries,
91
+ maxRetryDelayMs: c.maxRetryDelayMs,
158
92
  });
159
93
  }
160
94
  return out;
161
95
  }
162
- /** gatewayList — 列出全部作用域的网关配置(apiKey 掩码)+ 每个 agent 的 effective 配置(带来源标注)。 */
96
+ /** gatewayList — 列出各 agent 的 baseagent 模型选择与 provider 指认,外加每个 agent 实际生效的选择。 */
163
97
  export function gatewayList() {
164
98
  try {
165
99
  const gateways = [];
166
- const defaults = readDefaultsRaw();
167
- if (defaults)
168
- gateways.push(...extractEntries(defaults, 'defaults', true));
169
100
  const aids = listAgentAids();
170
101
  for (const aid of aids) {
171
102
  const raw = readAgentRaw(aid);
172
103
  if (raw)
173
104
  gateways.push(...extractEntries(raw, aid));
174
105
  }
175
- // 计算每个 agent 的 effective 配置(含来源标注)
176
- const effective = computeEffective(defaults, aids);
177
- // 检测环境变量配置与全局配置的差异
178
- const envMismatch = detectEnvMismatch(defaults, aids);
179
- return { data: { gateways, scopes: ['defaults', ...aids], types: GATEWAY_TYPES, effective, envMismatch } };
106
+ const effective = computeEffective(aids);
107
+ return { data: { gateways, scopes: aids, types: GATEWAY_TYPES, effective } };
180
108
  }
181
109
  catch (e) {
182
110
  logger.error('[gateway] gatewayList 执行出错:', e);
183
111
  throw e;
184
112
  }
185
113
  }
186
- /** 判断字段来源:agent 自己有 → 'agent';defaults 有 → 'defaults';否则 'none'。 */
187
- function fieldSource(agentBlock, defaultsBlock, key) {
188
- const agentVal = agentBlock?.[key];
189
- if (agentVal !== undefined && agentVal !== null && agentVal !== '') {
190
- return { value: key === 'apiKey' ? maskApiKey(agentVal).mask : String(agentVal), source: 'agent' };
191
- }
192
- const defaultsVal = defaultsBlock?.[key];
193
- if (defaultsVal !== undefined && defaultsVal !== null && defaultsVal !== '') {
194
- return { value: key === 'apiKey' ? maskApiKey(defaultsVal).mask : String(defaultsVal), source: 'defaults' };
195
- }
196
- return { value: undefined, source: 'none' };
197
- }
198
- /** 为所有 agent 计算 effective 网关配置。
199
- * 聚焦每个 agent 的 active_baseagent(实际使用的后端):
200
- * - agent 自己配了该后端的网关块 → 用 agent 的(标注 'agent')
201
- * - 没配 → 回落 defaults 对应后端的默认网关(标注 'defaults')
202
- * active_baseagent 缺失时回落 defaults.active_baseagent,再回落 'claude'。 */
203
- function computeEffective(defaults, aids) {
114
+ /** 每个 agent 实际生效的 baseagent 与模型选择(active_baseagent 决定用哪个后端)。 */
115
+ function computeEffective(aids) {
204
116
  const result = [];
205
- const defaultsBa = defaults?.baseagents || {};
206
- const defaultsActive = defaults?.active_baseagent;
207
117
  for (const aid of aids) {
208
118
  const agentRaw = readAgentRaw(aid);
209
- const agentBa = agentRaw?.baseagents || {};
210
- // 该 agent 实际使用的后端
211
- const activeRaw = agentRaw?.active_baseagent || defaultsActive;
119
+ if (!agentRaw)
120
+ continue;
121
+ const activeRaw = agentRaw.active_baseagent;
212
122
  if (!activeRaw) {
213
123
  logger.error(`[GatewayConfig] active_baseagent is empty for aid=${aid}, skipping`);
214
124
  continue;
@@ -218,217 +128,38 @@ function computeEffective(defaults, aids) {
218
128
  continue;
219
129
  }
220
130
  const type = activeRaw;
221
- const activeSource = agentRaw?.active_baseagent ? 'agent' : 'defaults';
222
- const dBlock = defaultsBa[type] || {};
223
- const aBlock = agentBa[type] || {};
224
- // 整块来源:agent 配了该后端的网关块 → 'agent';否则继承 defaults
225
- const blockSource = (aBlock && Object.keys(aBlock).length > 0) ? 'agent' : 'defaults';
226
- const keys = type === 'gemini'
227
- ? ['model', 'apiKey', 'mode', 'cliPath', 'useVertex', 'project', 'location']
228
- : ['baseUrl', 'apiKey', 'model', 'effort'];
229
- const fields = {};
230
- for (const k of keys) {
231
- fields[k] = fieldSource(aBlock, dBlock, k);
232
- }
131
+ const block = agentRaw.baseagents?.[type] ?? {};
233
132
  result.push({
234
133
  aid,
235
134
  type,
236
135
  name: DISPLAY_NAMES[type] ?? type,
237
- activeBaseagent: type,
238
- activeSource,
239
- blockSource,
240
- fields,
136
+ provider: block.provider,
137
+ model: block.model,
138
+ effort: block.effort,
241
139
  });
242
140
  }
243
141
  return result;
244
142
  }
245
- /** 检测环境变量配置与本地 .env 文件的差异 */
246
- function detectEnvMismatch(defaults, aids) {
247
- const result = { hasMismatch: false, mismatches: [] };
248
- const defaultsBa = defaults?.baseagents || {};
249
- // 读取全局 .env 文件
250
- const rootEnvPath = path.join(resolvePaths().root, '.env');
251
- const rootEnvVars = parseEnvFileSync(rootEnvPath);
252
- // 记录进程环境变量
253
- const processEnvDebug = redactDebugValue({
254
- ANTHROPIC_BASE_URL: process.env.ANTHROPIC_BASE_URL || '(未设置)',
255
- ANTHROPIC_AUTH_TOKEN: process.env.ANTHROPIC_AUTH_TOKEN || '(未设置)',
256
- ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY || '(未设置)',
257
- });
258
- // 收集调试信息返回给前端
259
- result.debug = {
260
- processEnv: processEnvDebug,
261
- rootEnvFile: redactDebugValue(rootEnvVars),
262
- defaultsConfig: redactDebugValue(defaultsBa),
263
- };
264
- // 检测全局默认配置中的环境变量
265
- for (const type of GATEWAY_TYPES) {
266
- const block = defaultsBa[type];
267
- if (!block)
268
- continue;
269
- for (const [field, val] of Object.entries(block)) {
270
- // 情况1:配置值是 $ENV 引用
271
- if (typeof val === 'string' && val.startsWith(ENV_PREFIX)) {
272
- const envVarName = val.slice(ENV_PREFIX.length);
273
- const fileValue = rootEnvVars[envVarName];
274
- const processValue = process.env[envVarName];
275
- // .env 文件中未设置,但进程环境中有值
276
- if (!fileValue && processValue) {
277
- result.hasMismatch = true;
278
- result.mismatches.push({
279
- aid: 'defaults',
280
- type,
281
- field,
282
- envValue: '(.env 中未设置)',
283
- configValue: val,
284
- });
285
- }
286
- }
287
- // 情况2:配置值是实际值(非 $ENV 引用),检查是否应该使用环境变量
288
- else if (typeof val === 'string' && val && envKeysForGateway(type, field)) {
289
- const envKeys = envKeysForGateway(type, field);
290
- const envValue = firstEnvValue(process.env, envKeys);
291
- const fileValue = firstEnvValue(rootEnvVars, envKeys);
292
- const envVarName = envValue?.name;
293
- const processValue = envValue?.value;
294
- // 如果进程环境中有值,但配置中的值与进程环境不一致
295
- if (processValue && val !== processValue && envVarName) {
296
- // 同时检查 .env 文件:如果 .env 也没有这个值,说明需要同步
297
- if (!fileValue || fileValue.value !== processValue) {
298
- result.hasMismatch = true;
299
- result.mismatches.push({
300
- aid: 'defaults',
301
- type,
302
- field,
303
- envValue: redactMismatchValue(fileValue?.value, field) || '(.env 中未设置)',
304
- configValue: redactMismatchValue(val, field) || val,
305
- envVarName,
306
- processValue: redactMismatchValue(processValue, field),
307
- });
308
- }
309
- }
310
- }
311
- }
312
- }
313
- // 检测每个 agent 的配置
314
- for (const aid of aids) {
315
- const agentRaw = readAgentRaw(aid);
316
- const agentBa = agentRaw?.baseagents || {};
317
- // 读取该 agent 的 .env 文件
318
- const agentEnvPath = path.join(resolvePaths().agentsDir, aid, '.env');
319
- const agentEnvVars = parseEnvFileSync(agentEnvPath);
320
- for (const type of GATEWAY_TYPES) {
321
- const block = agentBa[type];
322
- if (!block)
323
- continue;
324
- for (const [field, val] of Object.entries(block)) {
325
- // 情况1:配置值是 $ENV 引用
326
- if (typeof val === 'string' && val.startsWith(ENV_PREFIX)) {
327
- const envVarName = val.slice(ENV_PREFIX.length);
328
- const fileValue = agentEnvVars[envVarName];
329
- const processValue = process.env[envVarName];
330
- if (!fileValue && processValue) {
331
- result.hasMismatch = true;
332
- result.mismatches.push({
333
- aid,
334
- type,
335
- field,
336
- envValue: '(.env 中未设置)',
337
- configValue: val,
338
- });
339
- }
340
- }
341
- // 情况2:配置值是实际值
342
- else if (typeof val === 'string' && val && envKeysForGateway(type, field)) {
343
- const envKeys = envKeysForGateway(type, field);
344
- const envValue = firstEnvValue(process.env, envKeys);
345
- const fileValue = firstEnvValue(agentEnvVars, envKeys);
346
- const envVarName = envValue?.name;
347
- const processValue = envValue?.value;
348
- if (processValue && val !== processValue && envVarName) {
349
- if (!fileValue || fileValue.value !== processValue) {
350
- result.hasMismatch = true;
351
- result.mismatches.push({
352
- aid,
353
- type,
354
- field,
355
- envValue: redactMismatchValue(fileValue?.value, field) || '(.env 中未设置)',
356
- configValue: `配置值与环境变量 ${envVarName} 不一致`,
357
- });
358
- }
359
- }
360
- }
361
- }
362
- }
363
- }
364
- return result;
365
- }
366
- /** 同步解析 .env 文件(复用 merge.ts 的逻辑) */
367
- function parseEnvFileSync(file) {
368
- try {
369
- const text = fs.readFileSync(file, 'utf-8');
370
- const out = {};
371
- for (const line of text.split(/\r?\n/)) {
372
- const t = line.trim();
373
- if (!t || t.startsWith('#'))
374
- continue;
375
- const eq = t.indexOf('=');
376
- if (eq <= 0)
377
- continue;
378
- const key = t.slice(0, eq).trim();
379
- let val = t.slice(eq + 1).trim();
380
- if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
381
- val = val.slice(1, -1);
382
- }
383
- out[key] = val;
384
- }
385
- return out;
386
- }
387
- catch {
388
- return {};
389
- }
390
- }
391
143
  // ── 写入 ──
392
144
  /** 校验 type 合法。 */
393
145
  function validateType(type) {
394
146
  return typeof type === 'string' && GATEWAY_TYPES.includes(type);
395
147
  }
396
- /** 从 patch 提取允许写入的字段。apiKey 仅接受 $ENV 引用。 */
148
+ /** 网关连接信息(baseUrl/apiKey/headers/queryParams)只存在于 providers.json,Agent 级只选 provider。 */
149
+ const REMOVED_GATEWAY_FIELDS = ['baseUrl', 'apiKey', 'model', 'effort', 'reasoning', 'mode', 'useVertex', 'project', 'location'];
150
+ /**
151
+ * 从 patch 提取允许写入的 Agent 级 baseagent 运行参数。
152
+ * 连接信息已迁入 providers.json,命中则直接报错并指明去处。
153
+ */
397
154
  function buildPatch(type, patch) {
398
- const f = {};
399
- if (patch.baseUrl !== undefined)
400
- f.baseUrl = String(patch.baseUrl).trim() || undefined;
401
- if (patch.model !== undefined)
402
- f.model = String(patch.model).trim() || undefined;
403
- if (patch.apiKey !== undefined && patch.apiKey !== '') {
404
- const v = String(patch.apiKey).trim();
405
- // 掩码占位符(未修改)忽略;其余必须是 $ENV 引用,拒绝明文
406
- if (v === '***') { /* 未修改,跳过 */ }
407
- else if (v.startsWith(ENV_PREFIX))
408
- f.apiKey = v;
409
- else
410
- return { error: 'apiKey 仅接受 "$ENV:NAME" 环境变量引用,不接受明文' };
411
- }
412
- if (type === 'claude' || type === 'codex' || type === 'ecagent') {
413
- if (patch.effort !== undefined)
414
- f.effort = String(patch.effort).trim() || undefined;
415
- }
416
- if (type === 'codex') {
417
- if (patch.reasoning !== undefined && patch.effort === undefined)
418
- f.effort = String(patch.reasoning).trim() || undefined;
419
- delete f.reasoning;
155
+ const removed = REMOVED_GATEWAY_FIELDS.filter(key => patch?.[key] !== undefined);
156
+ if (removed.length > 0) {
157
+ return { error: `${removed.join('/')} 已迁入 providers.json,请用 provider 管理入口修改;Agent 级只配置 baseagents.${type}.provider` };
420
158
  }
159
+ const f = {};
421
160
  if (type === 'gemini') {
422
- if (patch.mode !== undefined)
423
- f.mode = (patch.mode === 'sdk' ? 'sdk' : 'cli');
424
161
  if (patch.cliPath !== undefined)
425
162
  f.cliPath = String(patch.cliPath).trim() || undefined;
426
- if (patch.useVertex !== undefined)
427
- f.useVertex = !!patch.useVertex;
428
- if (patch.project !== undefined)
429
- f.project = String(patch.project).trim() || undefined;
430
- if (patch.location !== undefined)
431
- f.location = String(patch.location).trim() || undefined;
432
163
  }
433
164
  if (type === 'ecagent') {
434
165
  for (const key of ['timeoutMs', 'maxRetries', 'maxRetryDelayMs']) {
@@ -442,14 +173,10 @@ function buildPatch(type, patch) {
442
173
  }
443
174
  return { fields: f };
444
175
  }
445
- /** 触发 reload:defaults 改动影响全部 agent(resync),单 agent 改动只 reload 它。 */
176
+ /** 触发 reload:单 agent 改动只 reload 它。 */
446
177
  async function triggerReload(scope) {
447
178
  const sock = resolvePaths().socket;
448
179
  try {
449
- if (scope === 'defaults') {
450
- const r = await ipcQuery(sock, { type: 'evolagent.resync' });
451
- return !!r?.ok;
452
- }
453
180
  const r = await ipcQuery(sock, { type: 'evolagent.reload', name: scope });
454
181
  return !!r?.ok;
455
182
  }
@@ -457,33 +184,28 @@ async function triggerReload(scope) {
457
184
  return false;
458
185
  }
459
186
  }
460
- /** gatewayUpdate — 写入/更新一条网关配置。 */
187
+ /** gatewayUpdate — 写入/更新某 agent 的一条 baseagent 运行参数。 */
461
188
  export async function gatewayUpdate(args) {
462
189
  const scope = String(args?.scope ?? '').trim();
463
190
  const type = args?.type;
464
191
  if (!scope)
465
192
  return { error: '缺少 scope', code: 'INVALID_ARGS' };
193
+ if (scope === 'defaults') {
194
+ return { error: 'defaults 不承载 baseagent 配置;连接信息在 providers.json,模型选择在各 Agent 的 config.json', code: 'INVALID_ARGS' };
195
+ }
466
196
  if (!validateType(type))
467
197
  return { error: `无效 type: ${type}(可选 ${GATEWAY_TYPES.join('/')})`, code: 'INVALID_ARGS' };
468
198
  const built = buildPatch(type, args?.patch ?? {});
469
199
  if ('error' in built)
470
200
  return { error: built.error, code: 'INVALID_ARGS' };
471
201
  try {
472
- if (scope === 'defaults') {
473
- const cur = readDefaultsRaw() ?? {};
474
- const baseagents = { ...(cur.baseagents ?? {}) };
475
- baseagents[type] = { ...(baseagents[type] ?? {}), ...built.fields };
476
- saveDefaultsSafe({ baseagents });
477
- }
478
- else {
479
- const cfg = readAgentRaw(scope);
480
- if (!cfg)
481
- return { error: `Agent "${scope}" 不存在`, code: 'NOT_FOUND' };
482
- if (!cfg.baseagents)
483
- cfg.baseagents = {};
484
- cfg.baseagents[type] = { ...(cfg.baseagents[type] ?? {}), ...built.fields };
485
- saveAgent(cfg); // 含 aid/owners/admins 校验
486
- }
202
+ const cfg = readAgentRaw(scope);
203
+ if (!cfg)
204
+ return { error: `Agent "${scope}" 不存在`, code: 'NOT_FOUND' };
205
+ if (!cfg.baseagents)
206
+ cfg.baseagents = {};
207
+ cfg.baseagents[type] = { ...(cfg.baseagents[type] ?? {}), ...built.fields };
208
+ saveAgent(cfg); // 含 aid/owners/admins 校验
487
209
  }
488
210
  catch (e) {
489
211
  return { error: e?.message || String(e), code: 'EXEC_FAILED' };
@@ -491,32 +213,24 @@ export async function gatewayUpdate(args) {
491
213
  const reloaded = await triggerReload(scope);
492
214
  return { data: { scope, type, reloaded } };
493
215
  }
494
- /** gatewayDelete — 删除一条网关配置。 */
216
+ /** gatewayDelete — 删除某 agent 的一条 baseagent 配置块。 */
495
217
  export async function gatewayDelete(args) {
496
218
  const scope = String(args?.scope ?? '').trim();
497
219
  const type = args?.type;
498
220
  if (!scope)
499
221
  return { error: '缺少 scope', code: 'INVALID_ARGS' };
222
+ if (scope === 'defaults') {
223
+ return { error: 'defaults 不承载 baseagent 配置;连接信息在 providers.json,模型选择在各 Agent 的 config.json', code: 'INVALID_ARGS' };
224
+ }
500
225
  if (!validateType(type))
501
226
  return { error: `无效 type: ${type}`, code: 'INVALID_ARGS' };
502
227
  try {
503
- if (scope === 'defaults') {
504
- const cur = readDefaultsRaw();
505
- if (cur?.baseagents?.[type]) {
506
- const baseagents = { ...cur.baseagents };
507
- delete baseagents[type];
508
- // saveDefaultsSafe 是深合并不会删键,故直接整块覆盖 baseagents
509
- saveDefaultsSafe({ baseagents });
510
- }
511
- }
512
- else {
513
- const cfg = readAgentRaw(scope);
514
- if (!cfg)
515
- return { error: `Agent "${scope}" 不存在`, code: 'NOT_FOUND' };
516
- if (cfg.baseagents?.[type]) {
517
- delete cfg.baseagents[type];
518
- saveAgent(cfg);
519
- }
228
+ const cfg = readAgentRaw(scope);
229
+ if (!cfg)
230
+ return { error: `Agent "${scope}" 不存在`, code: 'NOT_FOUND' };
231
+ if (cfg.baseagents?.[type]) {
232
+ delete cfg.baseagents[type];
233
+ saveAgent(cfg);
520
234
  }
521
235
  }
522
236
  catch (e) {
@@ -525,45 +239,31 @@ export async function gatewayDelete(args) {
525
239
  const reloaded = await triggerReload(scope);
526
240
  return { data: { scope, type, deleted: true, reloaded } };
527
241
  }
528
- /** 解析某 scope/type 的真实 baseUrl + apiKey(在 daemon 内展开 $ENV,不出站)。 */
242
+ /** 解析某 agent 的 baseagent 经 providers.json 得到的真实 baseUrl + apiKey(不出站)。 */
529
243
  function resolveGatewayCreds(scope, type) {
530
- const expandedConfig = scope === 'defaults'
531
- ? readConfig(ConfigTarget.Defaults, undefined, { expand: true, cache: true })
532
- : readConfig(ConfigTarget.Agent, { self: scope }, { expand: true, cache: true });
533
- const block = expandedConfig?.baseagents?.[type];
244
+ const agentRaw = readAgentRaw(scope);
245
+ if (!agentRaw)
246
+ return { error: `Agent "${scope}" 不存在`, code: 'NOT_FOUND' };
247
+ const block = agentRaw.baseagents?.[type];
534
248
  if (!block)
535
249
  return { error: `${scope}/${type} 未配置`, code: 'NOT_FOUND' };
536
- const expanded = expandEnv(block);
537
- try {
538
- const synth = { agents: { [type]: expanded } };
539
- if (type === 'codex') {
540
- const r = resolveOpenaiConfig(synth, expanded);
541
- return {
542
- baseUrl: r.baseUrl,
543
- apiKey: r.apiKey,
544
- headers: buildModelRequestHeaders({ baseagent: 'codex', baseUrl: r.baseUrl, agentAid: scope === 'defaults' ? undefined : scope, configuredHeaders: r.headers }),
545
- queryParams: r.queryParams,
546
- };
547
- }
548
- else if (type === 'claude') {
549
- const r = resolveAnthropicConfig(synth, expanded);
550
- return {
551
- baseUrl: r.baseUrl,
552
- apiKey: r.apiKey,
553
- headers: buildModelRequestHeaders({ baseagent: 'claude', baseUrl: r.baseUrl, agentAid: scope === 'defaults' ? undefined : scope, configuredHeaders: r.headers }),
554
- queryParams: r.queryParams,
555
- };
556
- }
557
- else if (type === 'ecagent') {
558
- const r = resolveEcagentConfig(synth, expanded);
559
- return {
560
- baseUrl: r.baseUrl,
561
- apiKey: r.apiKey,
562
- headers: buildModelRequestHeaders({ baseagent: 'ecagent', baseUrl: r.baseUrl, agentAid: scope === 'defaults' ? undefined : scope, configuredHeaders: r.headers }),
563
- queryParams: r.queryParams,
564
- };
565
- }
250
+ if (!block.provider)
251
+ return { error: `${scope}/${type} 未选择 provider`, code: 'INVALID_ARGS' };
252
+ if (type === 'gemini')
566
253
  return { error: 'gemini 暂不支持 HTTP 探测(CLI 后端)', code: 'NOT_SUPPORTED' };
254
+ try {
255
+ const resolved = resolveProviderServiceForBaseagent(block.provider, type);
256
+ return {
257
+ baseUrl: resolved.baseUrl,
258
+ apiKey: resolved.apiKey,
259
+ headers: buildModelRequestHeaders({
260
+ baseagent: type,
261
+ baseUrl: resolved.baseUrl,
262
+ agentAid: scope,
263
+ configuredHeaders: resolved.headers,
264
+ }),
265
+ queryParams: resolved.queryParams,
266
+ };
567
267
  }
568
268
  catch (e) {
569
269
  return { error: `凭证解析失败:${e?.message || e}`, code: 'EXEC_FAILED' };
@@ -741,209 +441,3 @@ export function gatewaySetPrice(args) {
741
441
  }
742
442
  return { data: { modelId, saved: true } };
743
443
  }
744
- /** gatewaySyncEnv — 同步环境变量到配置文件(将进程环境变量的值写入配置文件) */
745
- export async function gatewaySyncEnv(args) {
746
- const syncType = args?.syncType; // 'global' | 'all-agents' | 'specific-agents'
747
- const targetAids = args?.targetAids || []; // 指定的 agent IDs(仅 specific-agents 时使用)
748
- if (!['global', 'all-agents', 'specific-agents'].includes(syncType)) {
749
- return { error: '无效的 syncType,可选值:global / all-agents / specific-agents', code: 'INVALID_ARGS' };
750
- }
751
- if (syncType === 'specific-agents' && (!Array.isArray(targetAids) || targetAids.length === 0)) {
752
- return { error: 'specific-agents 模式需要提供 targetAids 数组', code: 'INVALID_ARGS' };
753
- }
754
- try {
755
- const synced = [];
756
- // 1. 同步全局配置
757
- if (syncType === 'global' || syncType === 'all-agents' || syncType === 'specific-agents') {
758
- const defaults = readDefaultsRaw();
759
- if (defaults?.baseagents) {
760
- let hasChanges = false;
761
- for (const type of GATEWAY_TYPES) {
762
- const block = defaults.baseagents[type];
763
- if (!block)
764
- continue;
765
- for (const [field, val] of Object.entries(block)) {
766
- // 检测配置值是否与进程环境变量不一致
767
- if (typeof val === 'string') {
768
- // 情况1:引用型 $ENV:XXX
769
- if (val.startsWith(ENV_PREFIX)) {
770
- const varName = val.slice(ENV_PREFIX.length);
771
- const processValue = process.env[varName];
772
- if (processValue) {
773
- // 将引用改为实际值
774
- block[field] = processValue;
775
- hasChanges = true;
776
- }
777
- }
778
- // 情况2:实际值型,但与进程环境变量不一致
779
- else {
780
- const envKeys = envKeysForGateway(type, field);
781
- const envValue = envKeys
782
- ? firstEnvValue(process.env, envKeys)
783
- : undefined;
784
- if (envValue) {
785
- if (val !== envValue.value) {
786
- block[field] = envValue.value;
787
- hasChanges = true;
788
- }
789
- }
790
- }
791
- }
792
- }
793
- }
794
- if (hasChanges) {
795
- const defaultsPath = path.join(resolvePaths().agentsDir, 'defaults.json');
796
- saveDefaultsSafe(stripLegacyAunGatewayConfig(defaults, defaultsPath, message => logger.warn(message)));
797
- synced.push('全局配置 (defaults.json)');
798
- }
799
- }
800
- }
801
- // 2. 同步 agent 配置
802
- if (syncType === 'all-agents' || syncType === 'specific-agents') {
803
- const aids = syncType === 'all-agents' ? listAgentAids() : targetAids;
804
- for (const aid of aids) {
805
- const agentRaw = readAgentRaw(aid);
806
- if (!agentRaw?.baseagents)
807
- continue;
808
- let hasChanges = false;
809
- for (const type of GATEWAY_TYPES) {
810
- const block = agentRaw.baseagents[type];
811
- if (!block)
812
- continue;
813
- for (const [field, val] of Object.entries(block)) {
814
- if (typeof val === 'string') {
815
- // 情况1:引用型
816
- if (val.startsWith(ENV_PREFIX)) {
817
- const varName = val.slice(ENV_PREFIX.length);
818
- const processValue = process.env[varName];
819
- if (processValue) {
820
- block[field] = processValue;
821
- hasChanges = true;
822
- }
823
- }
824
- // 情况2:实际值型
825
- else {
826
- const envKeys = envKeysForGateway(type, field);
827
- const envValue = envKeys
828
- ? firstEnvValue(process.env, envKeys)
829
- : undefined;
830
- if (envValue) {
831
- if (val !== envValue.value) {
832
- block[field] = envValue.value;
833
- hasChanges = true;
834
- }
835
- }
836
- }
837
- }
838
- }
839
- }
840
- if (hasChanges) {
841
- const agentConfigPath = path.join(resolvePaths().agentsDir, aid, 'config.json');
842
- saveAgent(stripLegacyAunGatewayConfig(agentRaw, agentConfigPath, message => logger.warn(message)));
843
- synced.push(`${aid} (config.json)`);
844
- }
845
- }
846
- }
847
- return { data: { synced, count: synced.length } };
848
- }
849
- catch (e) {
850
- return { error: e?.message || String(e), code: 'EXEC_FAILED' };
851
- }
852
- }
853
- /** 从配置中提取所有环境变量引用 */
854
- function extractEnvVarsFromConfig(baseagents) {
855
- const envVars = [];
856
- const seen = new Set();
857
- for (const type of GATEWAY_TYPES) {
858
- const block = baseagents[type];
859
- if (!block)
860
- continue;
861
- for (const val of Object.values(block)) {
862
- if (typeof val === 'string' && val.startsWith(ENV_PREFIX)) {
863
- const varName = val.slice(ENV_PREFIX.length);
864
- if (!seen.has(varName)) {
865
- seen.add(varName);
866
- const currentValue = process.env[varName] || '';
867
- envVars.push({ varName, currentValue });
868
- }
869
- }
870
- }
871
- }
872
- return envVars;
873
- }
874
- /** 同步环境变量到 .env 文件(保留现有内容,更新或追加变量) */
875
- async function syncEnvFile(envPath, envVars) {
876
- let existingContent = '';
877
- const existingVars = new Map();
878
- // 读取现有 .env 文件
879
- if (fs.existsSync(envPath)) {
880
- existingContent = fs.readFileSync(envPath, 'utf-8');
881
- const lines = existingContent.split(/\r?\n/);
882
- for (const line of lines) {
883
- const t = line.trim();
884
- if (!t || t.startsWith('#'))
885
- continue;
886
- const eq = t.indexOf('=');
887
- if (eq <= 0)
888
- continue;
889
- const key = t.slice(0, eq).trim();
890
- existingVars.set(key, line); // 保留原始行(含格式)
891
- }
892
- }
893
- // 构建新内容
894
- const newLines = [];
895
- const updatedVars = new Set();
896
- // 保留现有内容,更新匹配的变量
897
- if (existingContent) {
898
- const lines = existingContent.split(/\r?\n/);
899
- for (const line of lines) {
900
- const t = line.trim();
901
- if (!t || t.startsWith('#')) {
902
- newLines.push(line);
903
- continue;
904
- }
905
- const eq = t.indexOf('=');
906
- if (eq <= 0) {
907
- newLines.push(line);
908
- continue;
909
- }
910
- const key = t.slice(0, eq).trim();
911
- const envVar = envVars.find(v => v.varName === key);
912
- if (envVar && envVar.currentValue) {
913
- // 更新为当前进程环境变量的值
914
- newLines.push(`${key}=${envVar.currentValue}`);
915
- updatedVars.add(key);
916
- }
917
- else {
918
- newLines.push(line);
919
- }
920
- }
921
- }
922
- // 追加新的环境变量
923
- for (const envVar of envVars) {
924
- if (!updatedVars.has(envVar.varName) && envVar.currentValue) {
925
- newLines.push(`${envVar.varName}=${envVar.currentValue}`);
926
- }
927
- }
928
- // 写入文件
929
- fs.mkdirSync(path.dirname(envPath), { recursive: true });
930
- fs.writeFileSync(envPath, newLines.join('\n') + '\n', 'utf-8');
931
- logger.info(`[gateway] 已同步环境变量到: ${envPath}`);
932
- }
933
- /** 递归展开 $ENV 引用(仅用于 test 的临时解析,不落盘)。 */
934
- function expandEnv(obj) {
935
- if (typeof obj === 'string') {
936
- if (obj.startsWith(ENV_PREFIX))
937
- return process.env[obj.slice(ENV_PREFIX.length)] ?? '';
938
- return obj.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => process.env[name] ?? '');
939
- }
940
- if (Array.isArray(obj))
941
- return obj.map(expandEnv);
942
- if (obj && typeof obj === 'object') {
943
- const out = {};
944
- for (const [k, v] of Object.entries(obj))
945
- out[k] = expandEnv(v);
946
- return out;
947
- }
948
- return obj;
949
- }