codexmate 0.0.21 → 0.0.22

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 (114) hide show
  1. package/README.md +389 -284
  2. package/README.zh.md +321 -0
  3. package/cli/agents-files.js +224 -162
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +359 -359
  6. package/cli/builtin-proxy.js +1044 -580
  7. package/cli/claude-proxy.js +998 -998
  8. package/cli/config-bootstrap.js +384 -384
  9. package/cli/config-health.js +338 -338
  10. package/cli/openai-bridge.js +950 -0
  11. package/cli/openclaw-config.js +629 -629
  12. package/cli/session-usage.concurrent.js +28 -0
  13. package/cli/session-usage.js +112 -0
  14. package/cli/session-usage.models.js +176 -0
  15. package/cli/skills.js +1141 -1141
  16. package/cli/zip-commands.js +510 -510
  17. package/cli.js +13214 -13129
  18. package/lib/cli-file-utils.js +151 -151
  19. package/lib/cli-models-utils.js +419 -419
  20. package/lib/cli-network-utils.js +164 -164
  21. package/lib/cli-path-utils.js +69 -69
  22. package/lib/cli-session-utils.js +121 -121
  23. package/lib/cli-sessions.js +386 -386
  24. package/lib/cli-utils.js +155 -155
  25. package/lib/download-artifacts.js +77 -77
  26. package/lib/mcp-stdio.js +440 -440
  27. package/lib/task-orchestrator.js +869 -869
  28. package/lib/text-diff.js +303 -303
  29. package/lib/workflow-engine.js +340 -340
  30. package/package.json +74 -74
  31. package/res/json5.min.js +1 -1
  32. package/res/logo.png +0 -0
  33. package/res/vue.global.prod.js +13 -13
  34. package/web-ui/app.js +575 -530
  35. package/web-ui/index.html +34 -33
  36. package/web-ui/logic.agents-diff.mjs +386 -386
  37. package/web-ui/logic.claude.mjs +168 -168
  38. package/web-ui/logic.mjs +5 -5
  39. package/web-ui/logic.runtime.mjs +128 -124
  40. package/web-ui/logic.sessions.mjs +614 -581
  41. package/web-ui/modules/api.mjs +90 -90
  42. package/web-ui/modules/app.computed.dashboard.mjs +126 -113
  43. package/web-ui/modules/app.computed.index.mjs +17 -15
  44. package/web-ui/modules/app.computed.main-tabs.mjs +198 -195
  45. package/web-ui/modules/app.computed.session.mjs +653 -507
  46. package/web-ui/modules/app.constants.mjs +15 -15
  47. package/web-ui/modules/app.methods.agents.mjs +544 -493
  48. package/web-ui/modules/app.methods.claude-config.mjs +174 -174
  49. package/web-ui/modules/app.methods.codex-config.mjs +795 -640
  50. package/web-ui/modules/app.methods.index.mjs +92 -88
  51. package/web-ui/modules/app.methods.install.mjs +161 -149
  52. package/web-ui/modules/app.methods.navigation.mjs +619 -619
  53. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  54. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  55. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  56. package/web-ui/modules/app.methods.providers.mjs +404 -363
  57. package/web-ui/modules/app.methods.runtime.mjs +323 -323
  58. package/web-ui/modules/app.methods.session-actions.mjs +537 -520
  59. package/web-ui/modules/app.methods.session-browser.mjs +626 -626
  60. package/web-ui/modules/app.methods.session-timeline.mjs +448 -448
  61. package/web-ui/modules/app.methods.session-trash.mjs +422 -422
  62. package/web-ui/modules/app.methods.startup-claude.mjs +405 -412
  63. package/web-ui/modules/app.methods.task-orchestration.mjs +471 -471
  64. package/web-ui/modules/config-mode.computed.mjs +126 -126
  65. package/web-ui/modules/config-template-confirm-pref.mjs +33 -0
  66. package/web-ui/modules/i18n.mjs +1609 -0
  67. package/web-ui/modules/plugins.computed.mjs +220 -0
  68. package/web-ui/modules/plugins.methods.mjs +620 -0
  69. package/web-ui/modules/plugins.storage.mjs +37 -0
  70. package/web-ui/modules/skills.computed.mjs +107 -107
  71. package/web-ui/modules/skills.methods.mjs +481 -481
  72. package/web-ui/partials/index/layout-footer.html +13 -13
  73. package/web-ui/partials/index/layout-header.html +461 -402
  74. package/web-ui/partials/index/modal-config-template-agents.html +175 -125
  75. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  76. package/web-ui/partials/index/modal-health-check.html +72 -72
  77. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  78. package/web-ui/partials/index/modal-skills.html +200 -184
  79. package/web-ui/partials/index/modals-basic.html +165 -156
  80. package/web-ui/partials/index/panel-config-claude.html +138 -126
  81. package/web-ui/partials/index/panel-config-codex.html +234 -237
  82. package/web-ui/partials/index/panel-config-openclaw.html +78 -78
  83. package/web-ui/partials/index/panel-docs.html +147 -130
  84. package/web-ui/partials/index/panel-market.html +174 -174
  85. package/web-ui/partials/index/panel-orchestration.html +397 -397
  86. package/web-ui/partials/index/panel-plugins.html +243 -0
  87. package/web-ui/partials/index/panel-sessions.html +292 -292
  88. package/web-ui/partials/index/panel-settings.html +258 -190
  89. package/web-ui/partials/index/panel-usage.html +353 -213
  90. package/web-ui/session-helpers.mjs +573 -559
  91. package/web-ui/source-bundle.cjs +233 -233
  92. package/web-ui/styles/base-theme.css +264 -271
  93. package/web-ui/styles/controls-forms.css +362 -360
  94. package/web-ui/styles/docs-panel.css +247 -182
  95. package/web-ui/styles/feedback.css +108 -108
  96. package/web-ui/styles/health-check-dialog.css +144 -144
  97. package/web-ui/styles/layout-shell.css +596 -376
  98. package/web-ui/styles/modals-core.css +464 -464
  99. package/web-ui/styles/navigation-panels.css +382 -348
  100. package/web-ui/styles/openclaw-structured.css +266 -266
  101. package/web-ui/styles/plugins-panel.css +518 -0
  102. package/web-ui/styles/responsive.css +456 -450
  103. package/web-ui/styles/sessions-list.css +400 -400
  104. package/web-ui/styles/sessions-preview.css +411 -411
  105. package/web-ui/styles/sessions-toolbar-trash.css +268 -243
  106. package/web-ui/styles/sessions-usage.css +851 -628
  107. package/web-ui/styles/settings-panel.css +166 -0
  108. package/web-ui/styles/skills-list.css +303 -296
  109. package/web-ui/styles/skills-market.css +396 -335
  110. package/web-ui/styles/task-orchestration.css +776 -776
  111. package/web-ui/styles/titles-cards.css +408 -408
  112. package/web-ui/styles.css +20 -18
  113. package/web-ui.html +17 -17
  114. package/README.en.md +0 -349
@@ -1,580 +1,1044 @@
1
- const http = require('http');
2
- const net = require('net');
3
- const toml = require('@iarna/toml');
4
- const { readJsonFile, writeJsonAtomic } = require('../lib/cli-file-utils');
5
- const { isValidHttpUrl, normalizeBaseUrl, joinApiUrl } = require('../lib/cli-utils');
6
- const { toIsoTime } = require('../lib/cli-session-utils');
7
-
8
- function createBuiltinProxyRuntimeController(deps = {}) {
9
- const {
10
- fs,
11
- https,
12
- CONFIG_FILE,
13
- BUILTIN_PROXY_SETTINGS_FILE,
14
- DEFAULT_BUILTIN_PROXY_SETTINGS,
15
- BUILTIN_PROXY_PROVIDER_NAME,
16
- CODEXMATE_MANAGED_MARKER,
17
- HTTP_KEEP_ALIVE_AGENT,
18
- HTTPS_KEEP_ALIVE_AGENT,
19
- readConfig,
20
- writeConfig,
21
- readConfigOrVirtualDefault,
22
- resolveAuthTokenFromCurrentProfile,
23
- isPlainObject,
24
- isBuiltinManagedProvider,
25
- findProviderSectionRanges,
26
- findProviderDescendantSectionRanges,
27
- normalizeLegacySegments,
28
- buildLegacySegmentsKey,
29
- formatHostForUrl
30
- } = deps;
31
-
32
- if (!fs) throw new Error('createBuiltinProxyRuntimeController 缺少 fs');
33
- if (!https) throw new Error('createBuiltinProxyRuntimeController 缺少 https');
34
- if (!CONFIG_FILE) throw new Error('createBuiltinProxyRuntimeController 缺少 CONFIG_FILE');
35
- if (!BUILTIN_PROXY_SETTINGS_FILE) throw new Error('createBuiltinProxyRuntimeController 缺少 BUILTIN_PROXY_SETTINGS_FILE');
36
- if (!DEFAULT_BUILTIN_PROXY_SETTINGS || typeof DEFAULT_BUILTIN_PROXY_SETTINGS !== 'object') {
37
- throw new Error('createBuiltinProxyRuntimeController 缺少 DEFAULT_BUILTIN_PROXY_SETTINGS');
38
- }
39
- if (!BUILTIN_PROXY_PROVIDER_NAME) throw new Error('createBuiltinProxyRuntimeController 缺少 BUILTIN_PROXY_PROVIDER_NAME');
40
- if (typeof readConfig !== 'function') throw new Error('createBuiltinProxyRuntimeController 缺少 readConfig');
41
- if (typeof writeConfig !== 'function') throw new Error('createBuiltinProxyRuntimeController 缺少 writeConfig');
42
- if (typeof readConfigOrVirtualDefault !== 'function') {
43
- throw new Error('createBuiltinProxyRuntimeController 缺少 readConfigOrVirtualDefault');
44
- }
45
- if (typeof resolveAuthTokenFromCurrentProfile !== 'function') {
46
- throw new Error('createBuiltinProxyRuntimeController 缺少 resolveAuthTokenFromCurrentProfile');
47
- }
48
- if (typeof isPlainObject !== 'function') throw new Error('createBuiltinProxyRuntimeController 缺少 isPlainObject');
49
- if (typeof isBuiltinManagedProvider !== 'function') {
50
- throw new Error('createBuiltinProxyRuntimeController 缺少 isBuiltinManagedProvider');
51
- }
52
- if (typeof findProviderSectionRanges !== 'function') {
53
- throw new Error('createBuiltinProxyRuntimeController 缺少 findProviderSectionRanges');
54
- }
55
- if (typeof findProviderDescendantSectionRanges !== 'function') {
56
- throw new Error('createBuiltinProxyRuntimeController 缺少 findProviderDescendantSectionRanges');
57
- }
58
- if (typeof normalizeLegacySegments !== 'function') {
59
- throw new Error('createBuiltinProxyRuntimeController 缺少 normalizeLegacySegments');
60
- }
61
- if (typeof buildLegacySegmentsKey !== 'function') {
62
- throw new Error('createBuiltinProxyRuntimeController 缺少 buildLegacySegmentsKey');
63
- }
64
- if (typeof formatHostForUrl !== 'function') throw new Error('createBuiltinProxyRuntimeController 缺少 formatHostForUrl');
65
-
66
- let runtime = null;
67
-
68
- function canListenPort(host, port) {
69
- return new Promise((resolve) => {
70
- const tester = net.createServer();
71
- tester.unref();
72
- tester.once('error', () => resolve(false));
73
- tester.once('listening', () => {
74
- tester.close(() => resolve(true));
75
- });
76
- tester.listen(port, host);
77
- });
78
- }
79
-
80
- async function findAvailablePort(host, startPort, maxAttempts = 20) {
81
- const start = parseInt(String(startPort), 10);
82
- if (!Number.isFinite(start) || start <= 0) {
83
- return 0;
84
- }
85
- const attempts = Number.isFinite(maxAttempts) && maxAttempts > 0 ? maxAttempts : 20;
86
- for (let offset = 0; offset < attempts; offset += 1) {
87
- const candidate = start + offset;
88
- if (candidate > 65535) {
89
- break;
90
- }
91
- // eslint-disable-next-line no-await-in-loop
92
- const ok = await canListenPort(host, candidate);
93
- if (ok) {
94
- return candidate;
95
- }
96
- }
97
- return 0;
98
- }
99
-
100
- function resolveBuiltinProxyProviderName(rawProviderName, providers = {}, preferredProvider = '') {
101
- const providerMap = providers && isPlainObject(providers) ? providers : {};
102
- const providerNames = Object.keys(providerMap)
103
- .filter((name) => name && !isBuiltinManagedProvider(name));
104
- const requested = typeof rawProviderName === 'string' ? rawProviderName.trim() : '';
105
- if (requested && !isBuiltinManagedProvider(requested) && providerMap[requested]) {
106
- return requested;
107
- }
108
- const preferred = typeof preferredProvider === 'string' ? preferredProvider.trim() : '';
109
- if (preferred && !isBuiltinManagedProvider(preferred) && providerMap[preferred]) {
110
- return preferred;
111
- }
112
- return providerNames[0] || '';
113
- }
114
-
115
- function normalizeBuiltinProxySettings(raw) {
116
- const merged = {
117
- ...DEFAULT_BUILTIN_PROXY_SETTINGS,
118
- ...(isPlainObject(raw) ? raw : {})
119
- };
120
- const host = typeof merged.host === 'string' ? merged.host.trim() : '';
121
- const port = parseInt(String(merged.port), 10);
122
- const provider = typeof merged.provider === 'string' ? merged.provider.trim() : '';
123
- const authSourceRaw = typeof merged.authSource === 'string' ? merged.authSource.trim().toLowerCase() : '';
124
- const timeoutMs = parseInt(String(merged.timeoutMs), 10);
125
- const authSource = authSourceRaw === 'profile' || authSourceRaw === 'none' ? authSourceRaw : 'provider';
126
-
127
- return {
128
- enabled: merged.enabled !== false,
129
- host: host || DEFAULT_BUILTIN_PROXY_SETTINGS.host,
130
- port: Number.isFinite(port) && port > 0 && port <= 65535 ? port : DEFAULT_BUILTIN_PROXY_SETTINGS.port,
131
- provider,
132
- authSource,
133
- timeoutMs: Number.isFinite(timeoutMs) && timeoutMs >= 1000
134
- ? timeoutMs
135
- : DEFAULT_BUILTIN_PROXY_SETTINGS.timeoutMs
136
- };
137
- }
138
-
139
- function readBuiltinProxySettings() {
140
- const parsed = readJsonFile(BUILTIN_PROXY_SETTINGS_FILE, null);
141
- return normalizeBuiltinProxySettings(parsed);
142
- }
143
-
144
- function saveBuiltinProxySettings(payload = {}, options = {}) {
145
- const current = readBuiltinProxySettings();
146
- const merged = normalizeBuiltinProxySettings({
147
- ...current,
148
- ...(isPlainObject(payload) ? payload : {})
149
- });
150
-
151
- if (!merged.host) {
152
- return { error: '代理 host 不能为空' };
153
- }
154
- if (!Number.isFinite(merged.port) || merged.port <= 0 || merged.port > 65535) {
155
- return { error: '代理端口无效(1-65535)' };
156
- }
157
-
158
- const { config } = readConfigOrVirtualDefault();
159
- const providers = config && isPlainObject(config.model_providers) ? config.model_providers : {};
160
- const preferredProvider = typeof config.model_provider === 'string' ? config.model_provider.trim() : '';
161
- const finalProvider = resolveBuiltinProxyProviderName(merged.provider, providers, preferredProvider);
162
-
163
- const normalized = {
164
- ...merged,
165
- provider: finalProvider
166
- };
167
-
168
- if (!options.skipWrite) {
169
- writeJsonAtomic(BUILTIN_PROXY_SETTINGS_FILE, normalized);
170
- }
171
-
172
- return {
173
- success: true,
174
- settings: normalized
175
- };
176
- }
177
-
178
- function buildProxyListenUrl(settings) {
179
- const host = formatHostForUrl(settings.host || DEFAULT_BUILTIN_PROXY_SETTINGS.host);
180
- return `http://${host}:${settings.port}`;
181
- }
182
-
183
- function buildBuiltinProxyProviderBaseUrl(settings) {
184
- return `${buildProxyListenUrl(settings).replace(/\/+$/, '')}/v1`;
185
- }
186
-
187
- function removePersistedBuiltinProxyProviderFromConfig() {
188
- if (!fs.existsSync(CONFIG_FILE)) {
189
- return { success: true, removed: false };
190
- }
191
-
192
- let config;
193
- try {
194
- config = readConfig();
195
- } catch (e) {
196
- return { error: e.message || '读取 config.toml 失败' };
197
- }
198
-
199
- if (!config.model_providers || !config.model_providers[BUILTIN_PROXY_PROVIDER_NAME]) {
200
- return { success: true, removed: false };
201
- }
202
-
203
- const content = fs.readFileSync(CONFIG_FILE, 'utf-8');
204
- const lineEnding = content.includes('\r\n') ? '\r\n' : '\n';
205
- const hasBom = content.charCodeAt(0) === 0xFEFF;
206
- const providerConfig = config.model_providers[BUILTIN_PROXY_PROVIDER_NAME];
207
- const providerSegments = providerConfig && Array.isArray(providerConfig.__codexmate_legacy_segments)
208
- ? providerConfig.__codexmate_legacy_segments
209
- : null;
210
- const providerSegmentVariants = (() => {
211
- const variants = [];
212
- const seen = new Set();
213
- const pushVariant = (segments) => {
214
- const normalized = normalizeLegacySegments(segments);
215
- const key = buildLegacySegmentsKey(normalized);
216
- if (!key || seen.has(key)) return;
217
- seen.add(key);
218
- variants.push(normalized);
219
- };
220
- if (providerConfig && Array.isArray(providerConfig.__codexmate_legacy_segments)) {
221
- pushVariant(providerConfig.__codexmate_legacy_segments);
222
- }
223
- if (providerConfig && Array.isArray(providerConfig.__codexmate_legacy_segment_variants)) {
224
- for (const segments of providerConfig.__codexmate_legacy_segment_variants) {
225
- pushVariant(segments);
226
- }
227
- }
228
- if (providerSegments) {
229
- pushVariant(providerSegments);
230
- }
231
- if (variants.length === 0) {
232
- pushVariant(String(BUILTIN_PROXY_PROVIDER_NAME || '').split('.').filter((item) => item));
233
- }
234
- return variants;
235
- })();
236
-
237
- let updatedContent = null;
238
- const combinedRanges = [];
239
- for (const segments of providerSegmentVariants) {
240
- combinedRanges.push(...findProviderSectionRanges(content, BUILTIN_PROXY_PROVIDER_NAME, segments));
241
- combinedRanges.push(...findProviderDescendantSectionRanges(content, segments));
242
- }
243
- if (combinedRanges.length === 0) {
244
- combinedRanges.push(...findProviderSectionRanges(content, BUILTIN_PROXY_PROVIDER_NAME, providerSegments));
245
- }
246
-
247
- if (combinedRanges.length > 0) {
248
- const sorted = combinedRanges.sort((a, b) => b.start - a.start || b.end - a.end);
249
- const seen = new Set();
250
- let removedContent = content;
251
- for (const range of sorted) {
252
- const rangeKey = `${range.start}:${range.end}`;
253
- if (seen.has(rangeKey)) continue;
254
- seen.add(rangeKey);
255
- removedContent = removedContent.slice(0, range.start) + removedContent.slice(range.end);
256
- }
257
- updatedContent = removedContent.replace(/\n{3,}/g, lineEnding + lineEnding);
258
- }
259
-
260
- if (!updatedContent) {
261
- const rebuilt = JSON.parse(JSON.stringify(config));
262
- delete rebuilt.model_providers[BUILTIN_PROXY_PROVIDER_NAME];
263
- const hasMarker = content.includes(CODEXMATE_MANAGED_MARKER);
264
- let rebuiltToml = toml.stringify(rebuilt).trimEnd();
265
- rebuiltToml = rebuiltToml.replace(/\n/g, lineEnding);
266
- if (hasMarker && !rebuiltToml.includes(CODEXMATE_MANAGED_MARKER)) {
267
- rebuiltToml = `${CODEXMATE_MANAGED_MARKER}${lineEnding}${rebuiltToml}`;
268
- }
269
- updatedContent = rebuiltToml + lineEnding;
270
- if (hasBom && updatedContent.charCodeAt(0) !== 0xFEFF) {
271
- updatedContent = '\uFEFF' + updatedContent;
272
- }
273
- }
274
-
275
- try {
276
- writeConfig(updatedContent.trimEnd() + lineEnding);
277
- } catch (e) {
278
- return { error: e.message || '写入 config.toml 失败' };
279
- }
280
-
281
- return { success: true, removed: true };
282
- }
283
-
284
- function hasCodexConfigReadyForProxy() {
285
- const result = readConfigOrVirtualDefault();
286
- if (!result || result.isVirtual) {
287
- return false;
288
- }
289
- const config = result.config || {};
290
- if (!isPlainObject(config.model_providers)) {
291
- return false;
292
- }
293
- const providerNames = Object.keys(config.model_providers)
294
- .filter((name) => name && !isBuiltinManagedProvider(name));
295
- return providerNames.length > 0;
296
- }
297
-
298
- function resolveBuiltinProxyUpstream(settings) {
299
- const { config } = readConfigOrVirtualDefault();
300
- const providers = config && isPlainObject(config.model_providers) ? config.model_providers : {};
301
- const currentProvider = typeof config.model_provider === 'string' ? config.model_provider.trim() : '';
302
- const providerName = resolveBuiltinProxyProviderName(settings.provider, providers, currentProvider);
303
- if (!providerName) {
304
- return { error: '未找到可用的上游 provider,请先添加 provider' };
305
- }
306
- if (providerName === BUILTIN_PROXY_PROVIDER_NAME) {
307
- return { error: `上游 provider 不能是 ${BUILTIN_PROXY_PROVIDER_NAME}` };
308
- }
309
- const provider = providers[providerName];
310
- if (!provider || !isPlainObject(provider)) {
311
- return { error: `上游 provider 不存在: ${providerName}` };
312
- }
313
-
314
- const baseUrl = typeof provider.base_url === 'string' ? provider.base_url.trim() : '';
315
- if (!baseUrl || !isValidHttpUrl(baseUrl)) {
316
- return { error: `上游 provider base_url 无效: ${providerName}` };
317
- }
318
-
319
- let token = '';
320
- if (settings.authSource === 'profile') {
321
- token = resolveAuthTokenFromCurrentProfile();
322
- } else if (settings.authSource === 'provider') {
323
- token = typeof provider.preferred_auth_method === 'string' ? provider.preferred_auth_method.trim() : '';
324
- if (!token) {
325
- token = resolveAuthTokenFromCurrentProfile();
326
- }
327
- }
328
-
329
- let authHeader = '';
330
- if (token) {
331
- authHeader = /^bearer\s+/i.test(token) ? token : `Bearer ${token}`;
332
- }
333
-
334
- return {
335
- providerName,
336
- baseUrl: normalizeBaseUrl(baseUrl),
337
- authHeader
338
- };
339
- }
340
-
341
- function createBuiltinProxyServer(settings, upstream) {
342
- const connections = new Set();
343
- const timeoutMs = settings.timeoutMs;
344
-
345
- const server = http.createServer((req, res) => {
346
- let parsedIncoming;
347
- try {
348
- parsedIncoming = new URL(req.url || '/', 'http://localhost');
349
- } catch (e) {
350
- res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
351
- res.end(JSON.stringify({ error: 'invalid request path' }));
352
- return;
353
- }
354
-
355
- const incomingPath = parsedIncoming.pathname || '/';
356
- if (incomingPath === '/health' || incomingPath === '/status') {
357
- const body = JSON.stringify({
358
- ok: true,
359
- upstreamProvider: upstream.providerName,
360
- upstreamBaseUrl: upstream.baseUrl
361
- });
362
- res.writeHead(200, {
363
- 'Content-Type': 'application/json; charset=utf-8',
364
- 'Content-Length': Buffer.byteLength(body, 'utf-8')
365
- });
366
- res.end(body, 'utf-8');
367
- return;
368
- }
369
-
370
- if (!(incomingPath === '/v1' || incomingPath.startsWith('/v1/'))) {
371
- const body = JSON.stringify({ error: 'proxy only supports /v1/* paths' });
372
- res.writeHead(404, {
373
- 'Content-Type': 'application/json; charset=utf-8',
374
- 'Content-Length': Buffer.byteLength(body, 'utf-8')
375
- });
376
- res.end(body, 'utf-8');
377
- return;
378
- }
379
-
380
- const suffix = incomingPath === '/v1'
381
- ? ''
382
- : incomingPath.replace(/^\/v1\/?/, '');
383
- const targetBase = joinApiUrl(upstream.baseUrl, suffix);
384
- if (!targetBase) {
385
- const body = JSON.stringify({ error: 'failed to build upstream URL' });
386
- res.writeHead(500, {
387
- 'Content-Type': 'application/json; charset=utf-8',
388
- 'Content-Length': Buffer.byteLength(body, 'utf-8')
389
- });
390
- res.end(body, 'utf-8');
391
- return;
392
- }
393
-
394
- let targetUrl;
395
- try {
396
- targetUrl = new URL(targetBase);
397
- targetUrl.search = parsedIncoming.search || '';
398
- } catch (e) {
399
- const body = JSON.stringify({ error: `invalid upstream URL: ${e.message}` });
400
- res.writeHead(500, {
401
- 'Content-Type': 'application/json; charset=utf-8',
402
- 'Content-Length': Buffer.byteLength(body, 'utf-8')
403
- });
404
- res.end(body, 'utf-8');
405
- return;
406
- }
407
-
408
- const requestHeaders = { ...req.headers };
409
- delete requestHeaders.host;
410
- delete requestHeaders.connection;
411
- delete requestHeaders['content-length'];
412
- if (upstream.authHeader) {
413
- requestHeaders.authorization = upstream.authHeader;
414
- }
415
- requestHeaders['x-codexmate-proxy'] = '1';
416
- if (!requestHeaders['x-forwarded-for'] && req.socket && req.socket.remoteAddress) {
417
- requestHeaders['x-forwarded-for'] = req.socket.remoteAddress;
418
- }
419
-
420
- const transport = targetUrl.protocol === 'https:' ? https : http;
421
- const upstreamReq = transport.request({
422
- protocol: targetUrl.protocol,
423
- hostname: targetUrl.hostname,
424
- port: targetUrl.port || (targetUrl.protocol === 'https:' ? 443 : 80),
425
- method: req.method || 'GET',
426
- path: `${targetUrl.pathname}${targetUrl.search}`,
427
- headers: requestHeaders,
428
- agent: targetUrl.protocol === 'https:' ? HTTPS_KEEP_ALIVE_AGENT : HTTP_KEEP_ALIVE_AGENT
429
- }, (upstreamRes) => {
430
- const responseHeaders = { ...upstreamRes.headers };
431
- delete responseHeaders.connection;
432
- res.writeHead(upstreamRes.statusCode || 502, responseHeaders);
433
- upstreamRes.pipe(res);
434
- });
435
-
436
- upstreamReq.setTimeout(timeoutMs, () => {
437
- upstreamReq.destroy(new Error(`upstream timeout (${timeoutMs}ms)`));
438
- });
439
-
440
- upstreamReq.on('error', (err) => {
441
- if (res.headersSent) {
442
- try { res.destroy(err); } catch (_) {}
443
- return;
444
- }
445
- const body = JSON.stringify({ error: `proxy request failed: ${err.message}` });
446
- res.writeHead(502, {
447
- 'Content-Type': 'application/json; charset=utf-8',
448
- 'Content-Length': Buffer.byteLength(body, 'utf-8')
449
- });
450
- res.end(body, 'utf-8');
451
- });
452
-
453
- req.pipe(upstreamReq);
454
- });
455
-
456
- server.on('connection', (socket) => {
457
- connections.add(socket);
458
- socket.on('close', () => connections.delete(socket));
459
- });
460
-
461
- return new Promise((resolve, reject) => {
462
- server.once('error', reject);
463
- server.listen(settings.port, settings.host, () => {
464
- server.removeListener('error', reject);
465
- resolve({
466
- server,
467
- connections,
468
- settings,
469
- upstream,
470
- startedAt: toIsoTime(Date.now()),
471
- listenUrl: buildProxyListenUrl(settings)
472
- });
473
- });
474
- });
475
- }
476
-
477
- async function startBuiltinProxyRuntime(payload = {}) {
478
- if (runtime) {
479
- return {
480
- error: '内建代理已在运行',
481
- runtime: {
482
- listenUrl: runtime.listenUrl,
483
- upstreamProvider: runtime.upstream.providerName
484
- }
485
- };
486
- }
487
-
488
- const saveResult = saveBuiltinProxySettings(payload);
489
- if (saveResult.error) {
490
- return { error: saveResult.error };
491
- }
492
- const settings = saveResult.settings;
493
- const upstream = resolveBuiltinProxyUpstream(settings);
494
- if (upstream.error) {
495
- return { error: upstream.error };
496
- }
497
-
498
- try {
499
- runtime = await createBuiltinProxyServer(settings, upstream);
500
- return {
501
- success: true,
502
- running: true,
503
- listenUrl: runtime.listenUrl,
504
- upstreamProvider: upstream.providerName,
505
- settings
506
- };
507
- } catch (e) {
508
- return { error: `启动内建代理失败: ${e.message}` };
509
- }
510
- }
511
-
512
- async function stopBuiltinProxyRuntime() {
513
- if (!runtime) {
514
- return { success: true, running: false };
515
- }
516
- const currentRuntime = runtime;
517
- runtime = null;
518
-
519
- await new Promise((resolve) => {
520
- let settled = false;
521
- const finish = () => {
522
- if (settled) return;
523
- settled = true;
524
- resolve();
525
- };
526
-
527
- currentRuntime.server.close(() => finish());
528
- setTimeout(() => finish(), 1000);
529
- });
530
-
531
- for (const socket of currentRuntime.connections) {
532
- try { socket.destroy(); } catch (_) {}
533
- }
534
- currentRuntime.connections.clear();
535
-
536
- return {
537
- success: true,
538
- running: false
539
- };
540
- }
541
-
542
- function getBuiltinProxyStatus() {
543
- const settings = readBuiltinProxySettings();
544
- return {
545
- running: !!runtime,
546
- settings,
547
- runtime: runtime
548
- ? {
549
- provider: BUILTIN_PROXY_PROVIDER_NAME,
550
- startedAt: runtime.startedAt,
551
- listenUrl: runtime.listenUrl,
552
- upstreamProvider: runtime.upstream.providerName,
553
- upstreamBaseUrl: runtime.upstream.baseUrl
554
- }
555
- : null
556
- };
557
- }
558
-
559
- return {
560
- canListenPort,
561
- findAvailablePort,
562
- normalizeBuiltinProxySettings,
563
- readBuiltinProxySettings,
564
- resolveBuiltinProxyProviderName,
565
- saveBuiltinProxySettings,
566
- buildProxyListenUrl,
567
- buildBuiltinProxyProviderBaseUrl,
568
- removePersistedBuiltinProxyProviderFromConfig,
569
- hasCodexConfigReadyForProxy,
570
- resolveBuiltinProxyUpstream,
571
- createBuiltinProxyServer,
572
- startBuiltinProxyRuntime,
573
- stopBuiltinProxyRuntime,
574
- getBuiltinProxyStatus
575
- };
576
- }
577
-
578
- module.exports = {
579
- createBuiltinProxyRuntimeController
580
- };
1
+ const http = require('http');
2
+ const net = require('net');
3
+ const crypto = require('crypto');
4
+ const toml = require('@iarna/toml');
5
+ const { readJsonFile, writeJsonAtomic } = require('../lib/cli-file-utils');
6
+ const { isValidHttpUrl, normalizeBaseUrl, joinApiUrl } = require('../lib/cli-utils');
7
+ const { toIsoTime } = require('../lib/cli-session-utils');
8
+
9
+ function createBuiltinProxyRuntimeController(deps = {}) {
10
+ const {
11
+ fs,
12
+ https,
13
+ CONFIG_FILE,
14
+ BUILTIN_PROXY_SETTINGS_FILE,
15
+ DEFAULT_BUILTIN_PROXY_SETTINGS,
16
+ BUILTIN_PROXY_PROVIDER_NAME,
17
+ CODEXMATE_MANAGED_MARKER,
18
+ HTTP_KEEP_ALIVE_AGENT,
19
+ HTTPS_KEEP_ALIVE_AGENT,
20
+ readConfig,
21
+ writeConfig,
22
+ readConfigOrVirtualDefault,
23
+ resolveAuthTokenFromCurrentProfile,
24
+ isPlainObject,
25
+ isBuiltinManagedProvider,
26
+ findProviderSectionRanges,
27
+ findProviderDescendantSectionRanges,
28
+ normalizeLegacySegments,
29
+ buildLegacySegmentsKey,
30
+ formatHostForUrl
31
+ } = deps;
32
+
33
+ if (!fs) throw new Error('createBuiltinProxyRuntimeController 缺少 fs');
34
+ if (!https) throw new Error('createBuiltinProxyRuntimeController 缺少 https');
35
+ if (!CONFIG_FILE) throw new Error('createBuiltinProxyRuntimeController 缺少 CONFIG_FILE');
36
+ if (!BUILTIN_PROXY_SETTINGS_FILE) throw new Error('createBuiltinProxyRuntimeController 缺少 BUILTIN_PROXY_SETTINGS_FILE');
37
+ if (!DEFAULT_BUILTIN_PROXY_SETTINGS || typeof DEFAULT_BUILTIN_PROXY_SETTINGS !== 'object') {
38
+ throw new Error('createBuiltinProxyRuntimeController 缺少 DEFAULT_BUILTIN_PROXY_SETTINGS');
39
+ }
40
+ if (!BUILTIN_PROXY_PROVIDER_NAME) throw new Error('createBuiltinProxyRuntimeController 缺少 BUILTIN_PROXY_PROVIDER_NAME');
41
+ if (typeof readConfig !== 'function') throw new Error('createBuiltinProxyRuntimeController 缺少 readConfig');
42
+ if (typeof writeConfig !== 'function') throw new Error('createBuiltinProxyRuntimeController 缺少 writeConfig');
43
+ if (typeof readConfigOrVirtualDefault !== 'function') {
44
+ throw new Error('createBuiltinProxyRuntimeController 缺少 readConfigOrVirtualDefault');
45
+ }
46
+ if (typeof resolveAuthTokenFromCurrentProfile !== 'function') {
47
+ throw new Error('createBuiltinProxyRuntimeController 缺少 resolveAuthTokenFromCurrentProfile');
48
+ }
49
+ if (typeof isPlainObject !== 'function') throw new Error('createBuiltinProxyRuntimeController 缺少 isPlainObject');
50
+ if (typeof isBuiltinManagedProvider !== 'function') {
51
+ throw new Error('createBuiltinProxyRuntimeController 缺少 isBuiltinManagedProvider');
52
+ }
53
+ if (typeof findProviderSectionRanges !== 'function') {
54
+ throw new Error('createBuiltinProxyRuntimeController 缺少 findProviderSectionRanges');
55
+ }
56
+ if (typeof findProviderDescendantSectionRanges !== 'function') {
57
+ throw new Error('createBuiltinProxyRuntimeController 缺少 findProviderDescendantSectionRanges');
58
+ }
59
+ if (typeof normalizeLegacySegments !== 'function') {
60
+ throw new Error('createBuiltinProxyRuntimeController 缺少 normalizeLegacySegments');
61
+ }
62
+ if (typeof buildLegacySegmentsKey !== 'function') {
63
+ throw new Error('createBuiltinProxyRuntimeController 缺少 buildLegacySegmentsKey');
64
+ }
65
+ if (typeof formatHostForUrl !== 'function') throw new Error('createBuiltinProxyRuntimeController 缺少 formatHostForUrl');
66
+
67
+ let runtime = null;
68
+
69
+ function readRequestBody(req, maxBytes) {
70
+ return new Promise((resolve) => {
71
+ let body = '';
72
+ let size = 0;
73
+ let aborted = false;
74
+ req.on('data', (chunk) => {
75
+ if (aborted) return;
76
+ size += chunk.length;
77
+ if (Number.isFinite(maxBytes) && maxBytes > 0 && size > maxBytes) {
78
+ aborted = true;
79
+ try { req.destroy(); } catch (_) {}
80
+ resolve({ error: '请求体过大' });
81
+ return;
82
+ }
83
+ body += chunk;
84
+ });
85
+ req.on('end', () => {
86
+ if (aborted) return;
87
+ resolve({ body });
88
+ });
89
+ req.on('error', (err) => resolve({ error: err && err.message ? err.message : 'request failed' }));
90
+ });
91
+ }
92
+
93
+ function parseJsonOrError(text) {
94
+ if (typeof text !== 'string' || !text.trim()) {
95
+ return { value: null, error: 'empty body' };
96
+ }
97
+ try {
98
+ return { value: JSON.parse(text), error: '' };
99
+ } catch (e) {
100
+ return { value: null, error: e && e.message ? e.message : 'invalid json' };
101
+ }
102
+ }
103
+
104
+ function shouldFallbackFromUpstreamResponses(status, bodyText) {
105
+ if (!Number.isFinite(status)) return false;
106
+ if (status === 404 || status === 405 || status === 501) return true;
107
+ const text = String(bodyText || '');
108
+ if (!text) return false;
109
+ if (/not implemented/i.test(text)) return true;
110
+ if (/convert_request_failed/i.test(text)) return true;
111
+ try {
112
+ const parsed = JSON.parse(text);
113
+ const code = parsed && parsed.error && typeof parsed.error.code === 'string' ? parsed.error.code : '';
114
+ const msg = parsed && parsed.error && typeof parsed.error.message === 'string' ? parsed.error.message : '';
115
+ if (code === 'convert_request_failed') return true;
116
+ if (/not implemented/i.test(msg)) return true;
117
+ } catch (_) {}
118
+ return false;
119
+ }
120
+
121
+ function proxyRequestJson(targetUrl, options = {}) {
122
+ const parsed = new URL(targetUrl);
123
+ const transport = parsed.protocol === 'https:' ? https : http;
124
+ const bodyText = options.body ? JSON.stringify(options.body) : '';
125
+ const headers = {
126
+ 'Accept': 'application/json',
127
+ ...(options.body ? { 'Content-Type': 'application/json' } : {}),
128
+ ...(options.headers || {})
129
+ };
130
+ if (options.body) {
131
+ headers['Content-Length'] = Buffer.byteLength(bodyText, 'utf-8');
132
+ }
133
+ const timeoutMs = Number.isFinite(options.timeoutMs)
134
+ ? Math.max(1000, Number(options.timeoutMs))
135
+ : 30000;
136
+
137
+ return new Promise((resolve) => {
138
+ let settled = false;
139
+ const finish = (value) => {
140
+ if (settled) return;
141
+ settled = true;
142
+ resolve(value);
143
+ };
144
+ const req = transport.request({
145
+ protocol: parsed.protocol,
146
+ hostname: parsed.hostname,
147
+ port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
148
+ method: options.method || 'GET',
149
+ path: `${parsed.pathname}${parsed.search}`,
150
+ headers,
151
+ agent: parsed.protocol === 'https:' ? HTTPS_KEEP_ALIVE_AGENT : HTTP_KEEP_ALIVE_AGENT
152
+ }, (upstreamRes) => {
153
+ const chunks = [];
154
+ upstreamRes.on('data', (chunk) => chunk && chunks.push(chunk));
155
+ upstreamRes.on('end', () => {
156
+ const text = chunks.length ? Buffer.concat(chunks).toString('utf-8') : '';
157
+ finish({
158
+ ok: true,
159
+ status: upstreamRes.statusCode || 0,
160
+ headers: upstreamRes.headers || {},
161
+ bodyText: text
162
+ });
163
+ });
164
+ });
165
+ req.setTimeout(timeoutMs, () => {
166
+ try { req.destroy(new Error('timeout')); } catch (_) {}
167
+ finish({ ok: false, error: 'timeout' });
168
+ });
169
+ req.on('error', (err) => finish({ ok: false, error: err && err.message ? err.message : 'request failed' }));
170
+ if (bodyText) {
171
+ req.write(bodyText);
172
+ }
173
+ req.end();
174
+ });
175
+ }
176
+
177
+ function extractChatCompletionResult(payload) {
178
+ if (!payload || typeof payload !== 'object') return { text: '' };
179
+ const choice = Array.isArray(payload.choices) ? payload.choices[0] : null;
180
+ const message = choice && typeof choice === 'object' ? choice.message : null;
181
+ const content = message && typeof message === 'object' ? message.content : '';
182
+ let text = '';
183
+ if (typeof content === 'string') {
184
+ text = content;
185
+ } else if (Array.isArray(content)) {
186
+ text = content
187
+ .map((item) => {
188
+ if (!item) return '';
189
+ if (typeof item === 'string') return item;
190
+ if (typeof item === 'object') {
191
+ if (typeof item.text === 'string') return item.text;
192
+ if (typeof item.content === 'string') return item.content;
193
+ }
194
+ return '';
195
+ })
196
+ .filter(Boolean)
197
+ .join('');
198
+ }
199
+ return { text };
200
+ }
201
+
202
+ function normalizeResponsesInputToChatMessages(input) {
203
+ // 支持:
204
+ // - string
205
+ // - { role, content }(单条 message)
206
+ // - { type:"input_text"|"input_image", ... }(单个 block)
207
+ // - [{ role, content: [{type:"input_text"|"input_image", ...}] }]
208
+ // - [{ type:"input_text"|"input_image", ... }](视为单条 user 消息)
209
+ if (typeof input === 'string') {
210
+ return [{ role: 'user', content: input }];
211
+ }
212
+ if (input && typeof input === 'object' && !Array.isArray(input)) {
213
+ if (typeof input.role === 'string' && input.content != null) {
214
+ const role = input.role.trim() || 'user';
215
+ const content = Array.isArray(input.content)
216
+ ? toChatContent(input.content)
217
+ : input.content;
218
+ return content ? [{ role, content }] : [];
219
+ }
220
+ // 单个 block:{type:"input_text"|"input_image", ...}
221
+ if (typeof input.type === 'string') {
222
+ const content = toChatContent([input]);
223
+ return content ? [{ role: 'user', content }] : [];
224
+ }
225
+ return [];
226
+ }
227
+ if (!Array.isArray(input)) {
228
+ return [];
229
+ }
230
+
231
+ const toChatContent = (blocks) => {
232
+ if (!Array.isArray(blocks)) return '';
233
+ const out = [];
234
+ for (const block of blocks) {
235
+ if (!block || typeof block !== 'object') continue;
236
+ const type = typeof block.type === 'string' ? block.type : '';
237
+ if (type === 'input_text' && typeof block.text === 'string') {
238
+ out.push({ type: 'text', text: block.text });
239
+ continue;
240
+ }
241
+ if (type === 'input_image') {
242
+ const raw = block.image_url != null ? block.image_url : block.imageUrl;
243
+ const url = typeof raw === 'string'
244
+ ? raw
245
+ : (raw && typeof raw === 'object' && typeof raw.url === 'string' ? raw.url : '');
246
+ if (url) {
247
+ out.push({ type: 'image_url', image_url: { url } });
248
+ }
249
+ continue;
250
+ }
251
+ // 容错:兼容已是 chat content {type:"text"} / {type:"image_url"}
252
+ if (type === 'text' && typeof block.text === 'string') {
253
+ out.push({ type: 'text', text: block.text });
254
+ continue;
255
+ }
256
+ if (type === 'image_url' && block.image_url) {
257
+ out.push({ type: 'image_url', image_url: block.image_url });
258
+ }
259
+ }
260
+ if (out.length === 0) return '';
261
+ return out;
262
+ };
263
+
264
+ const messages = [];
265
+ for (const item of input) {
266
+ if (!item || typeof item !== 'object') continue;
267
+ if (typeof item.role === 'string' && item.content != null) {
268
+ const role = item.role.trim() || 'user';
269
+ const content = Array.isArray(item.content)
270
+ ? toChatContent(item.content)
271
+ : item.content;
272
+ if (content) {
273
+ messages.push({ role, content });
274
+ }
275
+ continue;
276
+ }
277
+ }
278
+
279
+ if (messages.length > 0) {
280
+ return messages;
281
+ }
282
+
283
+ // 退化:把 input array 当作单条 user content blocks
284
+ const fallbackContent = toChatContent(input);
285
+ if (fallbackContent) {
286
+ return [{ role: 'user', content: fallbackContent }];
287
+ }
288
+ return [];
289
+ }
290
+
291
+ function ensureResponseMetadata(payload) {
292
+ const base = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : {};
293
+ const id = typeof base.id === 'string' && base.id.trim()
294
+ ? base.id.trim()
295
+ : `resp_${crypto.randomBytes(10).toString('hex')}`;
296
+ const model = typeof base.model === 'string' ? base.model : '';
297
+ return {
298
+ object: 'response',
299
+ id,
300
+ model,
301
+ ...base
302
+ };
303
+ }
304
+
305
+ function writeSse(res, eventName, dataObj) {
306
+ if (eventName) {
307
+ res.write(`event: ${eventName}\n`);
308
+ }
309
+ if (dataObj === '[DONE]') {
310
+ res.write('data: [DONE]\n\n');
311
+ return;
312
+ }
313
+ res.write(`data: ${JSON.stringify(dataObj)}\n\n`);
314
+ }
315
+
316
+ function sendResponsesSse(res, responsePayload) {
317
+ const response = ensureResponseMetadata(responsePayload);
318
+ const responseId = response.id;
319
+ const model = response.model;
320
+ let sequence = 0;
321
+ const nextSeq = () => {
322
+ sequence += 1;
323
+ return sequence;
324
+ };
325
+
326
+ writeSse(res, 'response.created', {
327
+ type: 'response.created',
328
+ response: {
329
+ id: responseId,
330
+ model,
331
+ created_at: response.created_at
332
+ }
333
+ });
334
+
335
+ const output = Array.isArray(response.output) ? response.output : [];
336
+ for (let outputIndex = 0; outputIndex < output.length; outputIndex += 1) {
337
+ const item = output[outputIndex];
338
+ if (!item || typeof item !== 'object') continue;
339
+ const itemType = typeof item.type === 'string' ? item.type : '';
340
+ const itemId = typeof item.id === 'string' && item.id.trim()
341
+ ? item.id.trim()
342
+ : `item_${crypto.randomBytes(8).toString('hex')}`;
343
+
344
+ writeSse(res, 'response.output_item.added', {
345
+ type: 'response.output_item.added',
346
+ output_index: outputIndex,
347
+ item: { ...item, id: itemId }
348
+ });
349
+
350
+ if (itemType === 'message') {
351
+ const content = Array.isArray(item.content) ? item.content : [];
352
+ for (let contentIndex = 0; contentIndex < content.length; contentIndex += 1) {
353
+ const block = content[contentIndex];
354
+ if (!block || typeof block !== 'object') continue;
355
+ if (block.type !== 'output_text') continue;
356
+ const text = typeof block.text === 'string' ? block.text : '';
357
+ if (text) {
358
+ writeSse(res, 'response.output_text.delta', {
359
+ type: 'response.output_text.delta',
360
+ item_id: itemId,
361
+ output_index: outputIndex,
362
+ content_index: contentIndex,
363
+ delta: text,
364
+ sequence_number: nextSeq()
365
+ });
366
+ }
367
+ writeSse(res, 'response.output_text.done', {
368
+ type: 'response.output_text.done',
369
+ item_id: itemId,
370
+ output_index: outputIndex,
371
+ content_index: contentIndex,
372
+ text,
373
+ sequence_number: nextSeq()
374
+ });
375
+ }
376
+ }
377
+
378
+ writeSse(res, 'response.output_item.done', {
379
+ type: 'response.output_item.done',
380
+ output_index: outputIndex,
381
+ item: { ...item, id: itemId },
382
+ sequence_number: nextSeq()
383
+ });
384
+ }
385
+
386
+ writeSse(res, 'response.completed', { type: 'response.completed', response });
387
+ writeSse(res, 'done', '[DONE]');
388
+ }
389
+
390
+ function canListenPort(host, port) {
391
+ return new Promise((resolve) => {
392
+ const tester = net.createServer();
393
+ tester.unref();
394
+ tester.once('error', () => resolve(false));
395
+ tester.once('listening', () => {
396
+ tester.close(() => resolve(true));
397
+ });
398
+ tester.listen(port, host);
399
+ });
400
+ }
401
+
402
+ async function findAvailablePort(host, startPort, maxAttempts = 20) {
403
+ const start = parseInt(String(startPort), 10);
404
+ if (!Number.isFinite(start) || start <= 0) {
405
+ return 0;
406
+ }
407
+ const attempts = Number.isFinite(maxAttempts) && maxAttempts > 0 ? maxAttempts : 20;
408
+ for (let offset = 0; offset < attempts; offset += 1) {
409
+ const candidate = start + offset;
410
+ if (candidate > 65535) {
411
+ break;
412
+ }
413
+ // eslint-disable-next-line no-await-in-loop
414
+ const ok = await canListenPort(host, candidate);
415
+ if (ok) {
416
+ return candidate;
417
+ }
418
+ }
419
+ return 0;
420
+ }
421
+
422
+ function resolveBuiltinProxyProviderName(rawProviderName, providers = {}, preferredProvider = '') {
423
+ const providerMap = providers && isPlainObject(providers) ? providers : {};
424
+ const providerNames = Object.keys(providerMap)
425
+ .filter((name) => name && !isBuiltinManagedProvider(name));
426
+ const requested = typeof rawProviderName === 'string' ? rawProviderName.trim() : '';
427
+ if (requested && !isBuiltinManagedProvider(requested) && providerMap[requested]) {
428
+ return requested;
429
+ }
430
+ const preferred = typeof preferredProvider === 'string' ? preferredProvider.trim() : '';
431
+ if (preferred && !isBuiltinManagedProvider(preferred) && providerMap[preferred]) {
432
+ return preferred;
433
+ }
434
+ return providerNames[0] || '';
435
+ }
436
+
437
+ function normalizeBuiltinProxySettings(raw) {
438
+ const merged = {
439
+ ...DEFAULT_BUILTIN_PROXY_SETTINGS,
440
+ ...(isPlainObject(raw) ? raw : {})
441
+ };
442
+ const host = typeof merged.host === 'string' ? merged.host.trim() : '';
443
+ const port = parseInt(String(merged.port), 10);
444
+ const provider = typeof merged.provider === 'string' ? merged.provider.trim() : '';
445
+ const authSourceRaw = typeof merged.authSource === 'string' ? merged.authSource.trim().toLowerCase() : '';
446
+ const timeoutMs = parseInt(String(merged.timeoutMs), 10);
447
+ const authSource = authSourceRaw === 'profile' || authSourceRaw === 'none' ? authSourceRaw : 'provider';
448
+
449
+ return {
450
+ enabled: merged.enabled !== false,
451
+ host: host || DEFAULT_BUILTIN_PROXY_SETTINGS.host,
452
+ port: Number.isFinite(port) && port > 0 && port <= 65535 ? port : DEFAULT_BUILTIN_PROXY_SETTINGS.port,
453
+ provider,
454
+ authSource,
455
+ timeoutMs: Number.isFinite(timeoutMs) && timeoutMs >= 1000
456
+ ? timeoutMs
457
+ : DEFAULT_BUILTIN_PROXY_SETTINGS.timeoutMs
458
+ };
459
+ }
460
+
461
+ function readBuiltinProxySettings() {
462
+ const parsed = readJsonFile(BUILTIN_PROXY_SETTINGS_FILE, null);
463
+ return normalizeBuiltinProxySettings(parsed);
464
+ }
465
+
466
+ function saveBuiltinProxySettings(payload = {}, options = {}) {
467
+ const current = readBuiltinProxySettings();
468
+ const merged = normalizeBuiltinProxySettings({
469
+ ...current,
470
+ ...(isPlainObject(payload) ? payload : {})
471
+ });
472
+
473
+ if (!merged.host) {
474
+ return { error: '代理 host 不能为空' };
475
+ }
476
+ if (!Number.isFinite(merged.port) || merged.port <= 0 || merged.port > 65535) {
477
+ return { error: '代理端口无效(1-65535)' };
478
+ }
479
+
480
+ const { config } = readConfigOrVirtualDefault();
481
+ const providers = config && isPlainObject(config.model_providers) ? config.model_providers : {};
482
+ const preferredProvider = typeof config.model_provider === 'string' ? config.model_provider.trim() : '';
483
+ const finalProvider = resolveBuiltinProxyProviderName(merged.provider, providers, preferredProvider);
484
+
485
+ const normalized = {
486
+ ...merged,
487
+ provider: finalProvider
488
+ };
489
+
490
+ if (!options.skipWrite) {
491
+ writeJsonAtomic(BUILTIN_PROXY_SETTINGS_FILE, normalized);
492
+ }
493
+
494
+ return {
495
+ success: true,
496
+ settings: normalized
497
+ };
498
+ }
499
+
500
+ function buildProxyListenUrl(settings) {
501
+ const host = formatHostForUrl(settings.host || DEFAULT_BUILTIN_PROXY_SETTINGS.host);
502
+ return `http://${host}:${settings.port}`;
503
+ }
504
+
505
+ function buildBuiltinProxyProviderBaseUrl(settings) {
506
+ return `${buildProxyListenUrl(settings).replace(/\/+$/, '')}/v1`;
507
+ }
508
+
509
+ function removePersistedBuiltinProxyProviderFromConfig() {
510
+ if (!fs.existsSync(CONFIG_FILE)) {
511
+ return { success: true, removed: false };
512
+ }
513
+
514
+ let config;
515
+ try {
516
+ config = readConfig();
517
+ } catch (e) {
518
+ return { error: e.message || '读取 config.toml 失败' };
519
+ }
520
+
521
+ if (!config.model_providers || !config.model_providers[BUILTIN_PROXY_PROVIDER_NAME]) {
522
+ return { success: true, removed: false };
523
+ }
524
+
525
+ const content = fs.readFileSync(CONFIG_FILE, 'utf-8');
526
+ const lineEnding = content.includes('\r\n') ? '\r\n' : '\n';
527
+ const hasBom = content.charCodeAt(0) === 0xFEFF;
528
+ const providerConfig = config.model_providers[BUILTIN_PROXY_PROVIDER_NAME];
529
+ const providerSegments = providerConfig && Array.isArray(providerConfig.__codexmate_legacy_segments)
530
+ ? providerConfig.__codexmate_legacy_segments
531
+ : null;
532
+ const providerSegmentVariants = (() => {
533
+ const variants = [];
534
+ const seen = new Set();
535
+ const pushVariant = (segments) => {
536
+ const normalized = normalizeLegacySegments(segments);
537
+ const key = buildLegacySegmentsKey(normalized);
538
+ if (!key || seen.has(key)) return;
539
+ seen.add(key);
540
+ variants.push(normalized);
541
+ };
542
+ if (providerConfig && Array.isArray(providerConfig.__codexmate_legacy_segments)) {
543
+ pushVariant(providerConfig.__codexmate_legacy_segments);
544
+ }
545
+ if (providerConfig && Array.isArray(providerConfig.__codexmate_legacy_segment_variants)) {
546
+ for (const segments of providerConfig.__codexmate_legacy_segment_variants) {
547
+ pushVariant(segments);
548
+ }
549
+ }
550
+ if (providerSegments) {
551
+ pushVariant(providerSegments);
552
+ }
553
+ if (variants.length === 0) {
554
+ pushVariant(String(BUILTIN_PROXY_PROVIDER_NAME || '').split('.').filter((item) => item));
555
+ }
556
+ return variants;
557
+ })();
558
+
559
+ let updatedContent = null;
560
+ const combinedRanges = [];
561
+ for (const segments of providerSegmentVariants) {
562
+ combinedRanges.push(...findProviderSectionRanges(content, BUILTIN_PROXY_PROVIDER_NAME, segments));
563
+ combinedRanges.push(...findProviderDescendantSectionRanges(content, segments));
564
+ }
565
+ if (combinedRanges.length === 0) {
566
+ combinedRanges.push(...findProviderSectionRanges(content, BUILTIN_PROXY_PROVIDER_NAME, providerSegments));
567
+ }
568
+
569
+ if (combinedRanges.length > 0) {
570
+ const sorted = combinedRanges.sort((a, b) => b.start - a.start || b.end - a.end);
571
+ const seen = new Set();
572
+ let removedContent = content;
573
+ for (const range of sorted) {
574
+ const rangeKey = `${range.start}:${range.end}`;
575
+ if (seen.has(rangeKey)) continue;
576
+ seen.add(rangeKey);
577
+ removedContent = removedContent.slice(0, range.start) + removedContent.slice(range.end);
578
+ }
579
+ updatedContent = removedContent.replace(/\n{3,}/g, lineEnding + lineEnding);
580
+ }
581
+
582
+ if (!updatedContent) {
583
+ const rebuilt = JSON.parse(JSON.stringify(config));
584
+ delete rebuilt.model_providers[BUILTIN_PROXY_PROVIDER_NAME];
585
+ const hasMarker = content.includes(CODEXMATE_MANAGED_MARKER);
586
+ let rebuiltToml = toml.stringify(rebuilt).trimEnd();
587
+ rebuiltToml = rebuiltToml.replace(/\n/g, lineEnding);
588
+ if (hasMarker && !rebuiltToml.includes(CODEXMATE_MANAGED_MARKER)) {
589
+ rebuiltToml = `${CODEXMATE_MANAGED_MARKER}${lineEnding}${rebuiltToml}`;
590
+ }
591
+ updatedContent = rebuiltToml + lineEnding;
592
+ if (hasBom && updatedContent.charCodeAt(0) !== 0xFEFF) {
593
+ updatedContent = '\uFEFF' + updatedContent;
594
+ }
595
+ }
596
+
597
+ try {
598
+ writeConfig(updatedContent.trimEnd() + lineEnding);
599
+ } catch (e) {
600
+ return { error: e.message || '写入 config.toml 失败' };
601
+ }
602
+
603
+ return { success: true, removed: true };
604
+ }
605
+
606
+ function hasCodexConfigReadyForProxy() {
607
+ const result = readConfigOrVirtualDefault();
608
+ if (!result || result.isVirtual) {
609
+ return false;
610
+ }
611
+ const config = result.config || {};
612
+ if (!isPlainObject(config.model_providers)) {
613
+ return false;
614
+ }
615
+ const providerNames = Object.keys(config.model_providers)
616
+ .filter((name) => name && !isBuiltinManagedProvider(name));
617
+ return providerNames.length > 0;
618
+ }
619
+
620
+ function resolveBuiltinProxyUpstream(settings) {
621
+ const { config } = readConfigOrVirtualDefault();
622
+ const providers = config && isPlainObject(config.model_providers) ? config.model_providers : {};
623
+ const currentProvider = typeof config.model_provider === 'string' ? config.model_provider.trim() : '';
624
+ const providerName = resolveBuiltinProxyProviderName(settings.provider, providers, currentProvider);
625
+ if (!providerName) {
626
+ return { error: '未找到可用的上游 provider,请先添加 provider' };
627
+ }
628
+ if (providerName === BUILTIN_PROXY_PROVIDER_NAME) {
629
+ return { error: `上游 provider 不能是 ${BUILTIN_PROXY_PROVIDER_NAME}` };
630
+ }
631
+ const provider = providers[providerName];
632
+ if (!provider || !isPlainObject(provider)) {
633
+ return { error: `上游 provider 不存在: ${providerName}` };
634
+ }
635
+
636
+ const baseUrl = typeof provider.base_url === 'string' ? provider.base_url.trim() : '';
637
+ if (!baseUrl || !isValidHttpUrl(baseUrl)) {
638
+ return { error: `上游 provider base_url 无效: ${providerName}` };
639
+ }
640
+
641
+ let token = '';
642
+ if (settings.authSource === 'profile') {
643
+ token = resolveAuthTokenFromCurrentProfile();
644
+ } else if (settings.authSource === 'provider') {
645
+ token = typeof provider.preferred_auth_method === 'string' ? provider.preferred_auth_method.trim() : '';
646
+ if (!token) {
647
+ token = resolveAuthTokenFromCurrentProfile();
648
+ }
649
+ }
650
+
651
+ let authHeader = '';
652
+ if (token) {
653
+ authHeader = /^bearer\s+/i.test(token) ? token : `Bearer ${token}`;
654
+ }
655
+
656
+ return {
657
+ providerName,
658
+ baseUrl: normalizeBaseUrl(baseUrl),
659
+ authHeader
660
+ };
661
+ }
662
+
663
+ function createBuiltinProxyServer(settings, upstream) {
664
+ const connections = new Set();
665
+ const timeoutMs = settings.timeoutMs;
666
+
667
+ const server = http.createServer((req, res) => {
668
+ let parsedIncoming;
669
+ try {
670
+ parsedIncoming = new URL(req.url || '/', 'http://localhost');
671
+ } catch (e) {
672
+ res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
673
+ res.end(JSON.stringify({ error: 'invalid request path' }));
674
+ return;
675
+ }
676
+
677
+ const incomingPath = parsedIncoming.pathname || '/';
678
+ if (incomingPath === '/health' || incomingPath === '/status') {
679
+ const body = JSON.stringify({
680
+ ok: true,
681
+ upstreamProvider: upstream.providerName,
682
+ upstreamBaseUrl: upstream.baseUrl
683
+ });
684
+ res.writeHead(200, {
685
+ 'Content-Type': 'application/json; charset=utf-8',
686
+ 'Content-Length': Buffer.byteLength(body, 'utf-8')
687
+ });
688
+ res.end(body, 'utf-8');
689
+ return;
690
+ }
691
+
692
+ if (!(incomingPath === '/v1' || incomingPath.startsWith('/v1/'))) {
693
+ const body = JSON.stringify({ error: 'proxy only supports /v1/* paths' });
694
+ res.writeHead(404, {
695
+ 'Content-Type': 'application/json; charset=utf-8',
696
+ 'Content-Length': Buffer.byteLength(body, 'utf-8')
697
+ });
698
+ res.end(body, 'utf-8');
699
+ return;
700
+ }
701
+
702
+ // Responses shim:
703
+ // - Codex CLI 默认走 /v1/responses(含 SSE)
704
+ // - 某些上游只支持 /v1/chat/completions
705
+ // 因此这里优先尝试 /v1/responses(stream=false),失败再转换到 chat/completions 并回包为 responses。
706
+ if ((incomingPath === '/v1/responses' || incomingPath === '/v1/responses/') && (req.method || 'GET').toUpperCase() === 'POST') {
707
+ void (async () => {
708
+ const { body, error } = await readRequestBody(req, 10 * 1024 * 1024);
709
+ if (error) {
710
+ res.writeHead(413, { 'Content-Type': 'application/json; charset=utf-8' });
711
+ res.end(JSON.stringify({ error }));
712
+ return;
713
+ }
714
+ const parsed = parseJsonOrError(body);
715
+ if (parsed.error) {
716
+ res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
717
+ res.end(JSON.stringify({ error: `invalid json: ${parsed.error}` }));
718
+ return;
719
+ }
720
+
721
+ const payload = parsed.value && typeof parsed.value === 'object' ? parsed.value : {};
722
+ const wantsStream = payload.stream === true;
723
+
724
+ const commonHeaders = {
725
+ ...(upstream.authHeader ? { 'Authorization': upstream.authHeader } : {}),
726
+ 'X-Codexmate-Proxy': '1'
727
+ };
728
+
729
+ const upstreamResponsesUrl = joinApiUrl(upstream.baseUrl, 'responses');
730
+ const upstreamResponses = upstreamResponsesUrl
731
+ ? await proxyRequestJson(upstreamResponsesUrl, {
732
+ method: 'POST',
733
+ headers: commonHeaders,
734
+ timeoutMs,
735
+ body: { ...payload, stream: false }
736
+ })
737
+ : { ok: false, error: 'failed to build upstream URL' };
738
+
739
+ // 优先走上游 /responses(如果支持)。若上游报错且不是“端点不支持”,则直接透传错误。
740
+ if (upstreamResponses.ok && upstreamResponses.status >= 200 && upstreamResponses.status < 300) {
741
+ const json = parseJsonOrError(upstreamResponses.bodyText);
742
+ if (json.error) {
743
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
744
+ res.end(JSON.stringify({ error: `Upstream JSON parse failed: ${json.error}` }));
745
+ return;
746
+ }
747
+ const responsesPayload = ensureResponseMetadata(json.value);
748
+ if (wantsStream) {
749
+ res.writeHead(200, {
750
+ 'Content-Type': 'text/event-stream; charset=utf-8',
751
+ 'Cache-Control': 'no-cache',
752
+ 'Connection': 'keep-alive',
753
+ 'X-Accel-Buffering': 'no'
754
+ });
755
+ sendResponsesSse(res, responsesPayload);
756
+ res.end();
757
+ return;
758
+ }
759
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
760
+ res.end(JSON.stringify(responsesPayload));
761
+ return;
762
+ }
763
+
764
+ if (upstreamResponses.ok && upstreamResponses.status >= 400) {
765
+ if (!shouldFallbackFromUpstreamResponses(upstreamResponses.status, upstreamResponses.bodyText)) {
766
+ res.writeHead(upstreamResponses.status, { 'Content-Type': 'application/json; charset=utf-8' });
767
+ res.end(upstreamResponses.bodyText || JSON.stringify({ error: 'Upstream error' }));
768
+ return;
769
+ }
770
+ // fallthrough to chat/completions conversion
771
+ }
772
+
773
+ if (!upstreamResponses.ok) {
774
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
775
+ res.end(JSON.stringify({ error: upstreamResponses.error || 'Upstream request failed' }));
776
+ return;
777
+ }
778
+
779
+ const model = typeof payload.model === 'string' ? payload.model : '';
780
+ const messages = normalizeResponsesInputToChatMessages(payload.input);
781
+ const chatBody = {
782
+ model,
783
+ messages,
784
+ stream: false
785
+ };
786
+ if (payload.max_output_tokens != null && chatBody.max_tokens == null) {
787
+ chatBody.max_tokens = payload.max_output_tokens;
788
+ }
789
+
790
+ const upstreamChatUrl = joinApiUrl(upstream.baseUrl, 'chat/completions');
791
+ if (!upstreamChatUrl) {
792
+ res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
793
+ res.end(JSON.stringify({ error: 'failed to build upstream URL' }));
794
+ return;
795
+ }
796
+
797
+ const upstreamChat = await proxyRequestJson(upstreamChatUrl, {
798
+ method: 'POST',
799
+ headers: commonHeaders,
800
+ timeoutMs,
801
+ body: chatBody
802
+ });
803
+ if (!upstreamChat.ok) {
804
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
805
+ res.end(JSON.stringify({ error: upstreamChat.error || 'proxy request failed' }));
806
+ return;
807
+ }
808
+
809
+ const chatJson = parseJsonOrError(upstreamChat.bodyText);
810
+ if (chatJson.error) {
811
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
812
+ res.end(JSON.stringify({ error: `invalid upstream response: ${chatJson.error}` }));
813
+ return;
814
+ }
815
+
816
+ const { text } = extractChatCompletionResult(chatJson.value);
817
+ const responsesPayload = ensureResponseMetadata({
818
+ model,
819
+ output: [{
820
+ type: 'message',
821
+ role: 'assistant',
822
+ content: [{ type: 'output_text', text }]
823
+ }],
824
+ usage: chatJson.value && chatJson.value.usage ? chatJson.value.usage : undefined
825
+ });
826
+
827
+ if (wantsStream) {
828
+ res.writeHead(200, {
829
+ 'Content-Type': 'text/event-stream; charset=utf-8',
830
+ 'Cache-Control': 'no-cache',
831
+ 'Connection': 'keep-alive',
832
+ 'X-Accel-Buffering': 'no'
833
+ });
834
+ sendResponsesSse(res, responsesPayload);
835
+ res.end();
836
+ return;
837
+ }
838
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
839
+ res.end(JSON.stringify(responsesPayload));
840
+ })();
841
+ return;
842
+ }
843
+
844
+ const suffix = incomingPath === '/v1'
845
+ ? ''
846
+ : incomingPath.replace(/^\/v1\/?/, '');
847
+ const targetBase = joinApiUrl(upstream.baseUrl, suffix);
848
+ if (!targetBase) {
849
+ const body = JSON.stringify({ error: 'failed to build upstream URL' });
850
+ res.writeHead(500, {
851
+ 'Content-Type': 'application/json; charset=utf-8',
852
+ 'Content-Length': Buffer.byteLength(body, 'utf-8')
853
+ });
854
+ res.end(body, 'utf-8');
855
+ return;
856
+ }
857
+
858
+ let targetUrl;
859
+ try {
860
+ targetUrl = new URL(targetBase);
861
+ targetUrl.search = parsedIncoming.search || '';
862
+ } catch (e) {
863
+ const body = JSON.stringify({ error: `invalid upstream URL: ${e.message}` });
864
+ res.writeHead(500, {
865
+ 'Content-Type': 'application/json; charset=utf-8',
866
+ 'Content-Length': Buffer.byteLength(body, 'utf-8')
867
+ });
868
+ res.end(body, 'utf-8');
869
+ return;
870
+ }
871
+
872
+ const requestHeaders = { ...req.headers };
873
+ delete requestHeaders.host;
874
+ delete requestHeaders.connection;
875
+ delete requestHeaders['content-length'];
876
+ if (upstream.authHeader) {
877
+ requestHeaders.authorization = upstream.authHeader;
878
+ }
879
+ requestHeaders['x-codexmate-proxy'] = '1';
880
+ if (!requestHeaders['x-forwarded-for'] && req.socket && req.socket.remoteAddress) {
881
+ requestHeaders['x-forwarded-for'] = req.socket.remoteAddress;
882
+ }
883
+
884
+ const transport = targetUrl.protocol === 'https:' ? https : http;
885
+ const upstreamReq = transport.request({
886
+ protocol: targetUrl.protocol,
887
+ hostname: targetUrl.hostname,
888
+ port: targetUrl.port || (targetUrl.protocol === 'https:' ? 443 : 80),
889
+ method: req.method || 'GET',
890
+ path: `${targetUrl.pathname}${targetUrl.search}`,
891
+ headers: requestHeaders,
892
+ agent: targetUrl.protocol === 'https:' ? HTTPS_KEEP_ALIVE_AGENT : HTTP_KEEP_ALIVE_AGENT
893
+ }, (upstreamRes) => {
894
+ const responseHeaders = { ...upstreamRes.headers };
895
+ delete responseHeaders.connection;
896
+ res.writeHead(upstreamRes.statusCode || 502, responseHeaders);
897
+ upstreamRes.pipe(res);
898
+ });
899
+
900
+ upstreamReq.setTimeout(timeoutMs, () => {
901
+ upstreamReq.destroy(new Error(`upstream timeout (${timeoutMs}ms)`));
902
+ });
903
+
904
+ upstreamReq.on('error', (err) => {
905
+ if (res.headersSent) {
906
+ try { res.destroy(err); } catch (_) {}
907
+ return;
908
+ }
909
+ const body = JSON.stringify({ error: `proxy request failed: ${err.message}` });
910
+ res.writeHead(502, {
911
+ 'Content-Type': 'application/json; charset=utf-8',
912
+ 'Content-Length': Buffer.byteLength(body, 'utf-8')
913
+ });
914
+ res.end(body, 'utf-8');
915
+ });
916
+
917
+ req.pipe(upstreamReq);
918
+ });
919
+
920
+ server.on('connection', (socket) => {
921
+ connections.add(socket);
922
+ socket.on('close', () => connections.delete(socket));
923
+ });
924
+
925
+ return new Promise((resolve, reject) => {
926
+ server.once('error', reject);
927
+ server.listen(settings.port, settings.host, () => {
928
+ server.removeListener('error', reject);
929
+ resolve({
930
+ server,
931
+ connections,
932
+ settings,
933
+ upstream,
934
+ startedAt: toIsoTime(Date.now()),
935
+ listenUrl: buildProxyListenUrl(settings)
936
+ });
937
+ });
938
+ });
939
+ }
940
+
941
+ async function startBuiltinProxyRuntime(payload = {}) {
942
+ if (runtime) {
943
+ return {
944
+ error: '内建代理已在运行',
945
+ runtime: {
946
+ listenUrl: runtime.listenUrl,
947
+ upstreamProvider: runtime.upstream.providerName
948
+ }
949
+ };
950
+ }
951
+
952
+ const saveResult = saveBuiltinProxySettings(payload);
953
+ if (saveResult.error) {
954
+ return { error: saveResult.error };
955
+ }
956
+ const settings = saveResult.settings;
957
+ const upstream = resolveBuiltinProxyUpstream(settings);
958
+ if (upstream.error) {
959
+ return { error: upstream.error };
960
+ }
961
+
962
+ try {
963
+ runtime = await createBuiltinProxyServer(settings, upstream);
964
+ return {
965
+ success: true,
966
+ running: true,
967
+ listenUrl: runtime.listenUrl,
968
+ upstreamProvider: upstream.providerName,
969
+ settings
970
+ };
971
+ } catch (e) {
972
+ return { error: `启动内建代理失败: ${e.message}` };
973
+ }
974
+ }
975
+
976
+ async function stopBuiltinProxyRuntime() {
977
+ if (!runtime) {
978
+ return { success: true, running: false };
979
+ }
980
+ const currentRuntime = runtime;
981
+ runtime = null;
982
+
983
+ await new Promise((resolve) => {
984
+ let settled = false;
985
+ const finish = () => {
986
+ if (settled) return;
987
+ settled = true;
988
+ resolve();
989
+ };
990
+
991
+ currentRuntime.server.close(() => finish());
992
+ setTimeout(() => finish(), 1000);
993
+ });
994
+
995
+ for (const socket of currentRuntime.connections) {
996
+ try { socket.destroy(); } catch (_) {}
997
+ }
998
+ currentRuntime.connections.clear();
999
+
1000
+ return {
1001
+ success: true,
1002
+ running: false
1003
+ };
1004
+ }
1005
+
1006
+ function getBuiltinProxyStatus() {
1007
+ const settings = readBuiltinProxySettings();
1008
+ return {
1009
+ running: !!runtime,
1010
+ settings,
1011
+ runtime: runtime
1012
+ ? {
1013
+ provider: BUILTIN_PROXY_PROVIDER_NAME,
1014
+ startedAt: runtime.startedAt,
1015
+ listenUrl: runtime.listenUrl,
1016
+ upstreamProvider: runtime.upstream.providerName,
1017
+ upstreamBaseUrl: runtime.upstream.baseUrl
1018
+ }
1019
+ : null
1020
+ };
1021
+ }
1022
+
1023
+ return {
1024
+ canListenPort,
1025
+ findAvailablePort,
1026
+ normalizeBuiltinProxySettings,
1027
+ readBuiltinProxySettings,
1028
+ resolveBuiltinProxyProviderName,
1029
+ saveBuiltinProxySettings,
1030
+ buildProxyListenUrl,
1031
+ buildBuiltinProxyProviderBaseUrl,
1032
+ removePersistedBuiltinProxyProviderFromConfig,
1033
+ hasCodexConfigReadyForProxy,
1034
+ resolveBuiltinProxyUpstream,
1035
+ createBuiltinProxyServer,
1036
+ startBuiltinProxyRuntime,
1037
+ stopBuiltinProxyRuntime,
1038
+ getBuiltinProxyStatus
1039
+ };
1040
+ }
1041
+
1042
+ module.exports = {
1043
+ createBuiltinProxyRuntimeController
1044
+ };