codexmate 0.0.20 → 0.0.21

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 (102) hide show
  1. package/README.en.md +349 -259
  2. package/README.md +284 -252
  3. package/cli/agents-files.js +162 -0
  4. package/cli/archive-helpers.js +446 -0
  5. package/cli/auth-profiles.js +359 -0
  6. package/cli/builtin-proxy.js +580 -0
  7. package/cli/claude-proxy.js +998 -0
  8. package/cli/config-bootstrap.js +384 -0
  9. package/cli/config-health.js +338 -338
  10. package/cli/openclaw-config.js +629 -0
  11. package/cli/skills.js +1141 -0
  12. package/cli/zip-commands.js +510 -0
  13. package/cli.js +13101 -13497
  14. package/lib/cli-file-utils.js +151 -151
  15. package/lib/cli-models-utils.js +419 -311
  16. package/lib/cli-network-utils.js +164 -164
  17. package/lib/cli-path-utils.js +69 -0
  18. package/lib/cli-session-utils.js +121 -121
  19. package/lib/cli-sessions.js +386 -0
  20. package/lib/cli-utils.js +155 -155
  21. package/lib/download-artifacts.js +77 -0
  22. package/lib/mcp-stdio.js +440 -440
  23. package/lib/task-orchestrator.js +869 -0
  24. package/lib/text-diff.js +303 -303
  25. package/lib/workflow-engine.js +340 -340
  26. package/package.json +74 -70
  27. package/res/json5.min.js +1 -1
  28. package/res/vue.global.prod.js +13 -0
  29. package/web-ui/app.js +530 -397
  30. package/web-ui/index.html +33 -30
  31. package/web-ui/logic.agents-diff.mjs +386 -386
  32. package/web-ui/logic.claude.mjs +168 -108
  33. package/web-ui/logic.mjs +5 -5
  34. package/web-ui/logic.runtime.mjs +124 -124
  35. package/web-ui/logic.sessions.mjs +581 -263
  36. package/web-ui/modules/api.mjs +90 -69
  37. package/web-ui/modules/app.computed.dashboard.mjs +113 -113
  38. package/web-ui/modules/app.computed.index.mjs +15 -13
  39. package/web-ui/modules/app.computed.main-tabs.mjs +195 -0
  40. package/web-ui/modules/app.computed.session.mjs +507 -141
  41. package/web-ui/modules/app.constants.mjs +15 -15
  42. package/web-ui/modules/app.methods.agents.mjs +493 -493
  43. package/web-ui/modules/app.methods.claude-config.mjs +174 -174
  44. package/web-ui/modules/app.methods.codex-config.mjs +640 -640
  45. package/web-ui/modules/app.methods.index.mjs +88 -86
  46. package/web-ui/modules/app.methods.install.mjs +149 -157
  47. package/web-ui/modules/app.methods.navigation.mjs +619 -478
  48. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -514
  49. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -337
  50. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -251
  51. package/web-ui/modules/app.methods.providers.mjs +363 -265
  52. package/web-ui/modules/app.methods.runtime.mjs +323 -323
  53. package/web-ui/modules/app.methods.session-actions.mjs +520 -457
  54. package/web-ui/modules/app.methods.session-browser.mjs +626 -435
  55. package/web-ui/modules/app.methods.session-timeline.mjs +448 -441
  56. package/web-ui/modules/app.methods.session-trash.mjs +422 -419
  57. package/web-ui/modules/app.methods.startup-claude.mjs +412 -406
  58. package/web-ui/modules/app.methods.task-orchestration.mjs +471 -0
  59. package/web-ui/modules/config-mode.computed.mjs +126 -124
  60. package/web-ui/modules/skills.computed.mjs +107 -107
  61. package/web-ui/modules/skills.methods.mjs +481 -481
  62. package/web-ui/partials/index/layout-footer.html +13 -69
  63. package/web-ui/partials/index/layout-header.html +402 -337
  64. package/web-ui/partials/index/modal-config-template-agents.html +125 -125
  65. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  66. package/web-ui/partials/index/modal-health-check.html +72 -72
  67. package/web-ui/partials/index/modal-openclaw-config.html +280 -275
  68. package/web-ui/partials/index/modal-skills.html +184 -184
  69. package/web-ui/partials/index/modals-basic.html +156 -196
  70. package/web-ui/partials/index/panel-config-claude.html +126 -100
  71. package/web-ui/partials/index/panel-config-codex.html +237 -237
  72. package/web-ui/partials/index/panel-config-openclaw.html +78 -84
  73. package/web-ui/partials/index/panel-docs.html +130 -0
  74. package/web-ui/partials/index/panel-market.html +174 -174
  75. package/web-ui/partials/index/panel-orchestration.html +397 -0
  76. package/web-ui/partials/index/panel-sessions.html +292 -387
  77. package/web-ui/partials/index/panel-settings.html +190 -166
  78. package/web-ui/partials/index/panel-usage.html +213 -0
  79. package/web-ui/session-helpers.mjs +559 -362
  80. package/web-ui/source-bundle.cjs +233 -233
  81. package/web-ui/styles/base-theme.css +271 -373
  82. package/web-ui/styles/controls-forms.css +360 -354
  83. package/web-ui/styles/docs-panel.css +182 -0
  84. package/web-ui/styles/feedback.css +108 -108
  85. package/web-ui/styles/health-check-dialog.css +144 -144
  86. package/web-ui/styles/layout-shell.css +376 -330
  87. package/web-ui/styles/modals-core.css +464 -449
  88. package/web-ui/styles/navigation-panels.css +348 -381
  89. package/web-ui/styles/openclaw-structured.css +266 -266
  90. package/web-ui/styles/responsive.css +450 -416
  91. package/web-ui/styles/sessions-list.css +400 -414
  92. package/web-ui/styles/sessions-preview.css +411 -405
  93. package/web-ui/styles/sessions-toolbar-trash.css +243 -243
  94. package/web-ui/styles/sessions-usage.css +628 -276
  95. package/web-ui/styles/skills-list.css +296 -298
  96. package/web-ui/styles/skills-market.css +335 -335
  97. package/web-ui/styles/task-orchestration.css +776 -0
  98. package/web-ui/styles/titles-cards.css +408 -407
  99. package/web-ui/styles.css +18 -16
  100. package/web-ui.html +17 -17
  101. package/res/screenshot.png +0 -0
  102. package/res/vue.global.js +0 -18552
@@ -0,0 +1,386 @@
1
+ const fs = require('fs');
2
+
3
+ const {
4
+ toIsoTime,
5
+ truncateText,
6
+ extractMessageText,
7
+ normalizeRole
8
+ } = require('./cli-session-utils');
9
+
10
+ const DEFAULT_SESSION_DETAIL_MESSAGES = 300;
11
+ const FAST_SESSION_DETAIL_PREVIEW_FILE_BYTES = 256 * 1024;
12
+ const FAST_SESSION_DETAIL_PREVIEW_CHUNK_BYTES = 64 * 1024;
13
+ const FAST_SESSION_DETAIL_PREVIEW_MAX_BYTES = 1024 * 1024;
14
+
15
+ const BOOTSTRAP_TEXT_MARKERS = [
16
+ 'agents.md instructions',
17
+ '<instructions>',
18
+ '<environment_context>',
19
+ 'you are a coding agent',
20
+ 'codex cli'
21
+ ];
22
+
23
+ function getFileStatSafe(filePath) {
24
+ try {
25
+ return fs.statSync(filePath);
26
+ } catch (e) {
27
+ return null;
28
+ }
29
+ }
30
+
31
+ function isBootstrapLikeText(text) {
32
+ if (!text || typeof text !== 'string') {
33
+ return false;
34
+ }
35
+
36
+ const normalized = text.toLowerCase().replace(/\s+/g, ' ').trim();
37
+ if (!normalized) {
38
+ return false;
39
+ }
40
+
41
+ return BOOTSTRAP_TEXT_MARKERS.some(marker => normalized.includes(marker));
42
+ }
43
+
44
+ function removeLeadingSystemMessage(messages) {
45
+ if (!Array.isArray(messages) || messages.length === 0) {
46
+ return [];
47
+ }
48
+
49
+ let startIndex = 0;
50
+ while (startIndex < messages.length) {
51
+ const item = messages[startIndex];
52
+ const role = item ? normalizeRole(item.role) : '';
53
+ const text = item && typeof item.text === 'string' ? item.text : '';
54
+ const isSystemRole = role === 'system';
55
+ const isBootstrapText = isBootstrapLikeText(text);
56
+ if (!item || isSystemRole || isBootstrapText) {
57
+ startIndex += 1;
58
+ continue;
59
+ }
60
+ break;
61
+ }
62
+
63
+ if (startIndex <= 0) {
64
+ return messages;
65
+ }
66
+ return messages.slice(startIndex);
67
+ }
68
+
69
+ function normalizeQueryTokens(query) {
70
+ if (typeof query !== 'string') {
71
+ return [];
72
+ }
73
+ return query
74
+ .split(/\s+/)
75
+ .map(item => item.trim())
76
+ .map(item => item.toLowerCase())
77
+ .filter(Boolean);
78
+ }
79
+
80
+ function expandSessionQueryTokens(tokens) {
81
+ const base = Array.isArray(tokens) ? tokens.map(t => String(t || '').toLowerCase()).filter(Boolean) : [];
82
+ const result = [];
83
+ const seen = new Set();
84
+ let hasClaudeAlias = false;
85
+ let hasDaudeAlias = false;
86
+
87
+ // First pass: detect multi-token aliases (e.g., "claude code", "daude code")
88
+ for (let i = 0; i < base.length; i++) {
89
+ const token = base[i];
90
+ const nextToken = base[i + 1] || '';
91
+
92
+ // Check for "claude code" pattern (two separate tokens)
93
+ if (token === 'claude' && nextToken === 'code') {
94
+ hasClaudeAlias = true;
95
+ i++; // Skip next token
96
+ continue;
97
+ }
98
+ // Check for "daude code" pattern (two separate tokens)
99
+ if (token === 'daude' && nextToken === 'code') {
100
+ hasDaudeAlias = true;
101
+ i++; // Skip next token
102
+ continue;
103
+ }
104
+ // Check for combined patterns (e.g., "claude-code", "claude_code", "claudecode")
105
+ if (/^claude[-_ ]?code$/.test(token) || token === 'claudecode') {
106
+ hasClaudeAlias = true;
107
+ continue;
108
+ }
109
+ if (/^daude[-_ ]?code$/.test(token) || token === 'daudecode') {
110
+ hasDaudeAlias = true;
111
+ continue;
112
+ }
113
+ if (!seen.has(token)) {
114
+ seen.add(token);
115
+ result.push(token);
116
+ }
117
+ }
118
+
119
+ const push = (token) => {
120
+ const normalized = String(token || '').toLowerCase();
121
+ if (!normalized || seen.has(normalized)) return;
122
+ seen.add(normalized);
123
+ result.push(normalized);
124
+ };
125
+
126
+ if (hasClaudeAlias) {
127
+ push('claude');
128
+ push('code');
129
+ }
130
+ if (hasDaudeAlias) {
131
+ push('daude');
132
+ push('code');
133
+ }
134
+
135
+ return result;
136
+ }
137
+
138
+ function matchTokensInText(text, tokens, mode = 'and') {
139
+ if (!Array.isArray(tokens) || tokens.length === 0) {
140
+ return true;
141
+ }
142
+ const haystack = String(text || '').toLowerCase();
143
+ if (!haystack) {
144
+ return false;
145
+ }
146
+ if (mode === 'or') {
147
+ return tokens.some(token => haystack.includes(token));
148
+ }
149
+ return tokens.every(token => haystack.includes(token));
150
+ }
151
+
152
+ function extractMessageFromRecord(record, source) {
153
+ if (!record) {
154
+ return null;
155
+ }
156
+ if (source === 'codex') {
157
+ if (record.type === 'response_item' && record.payload && record.payload.type === 'message') {
158
+ const role = normalizeRole(record.payload.role);
159
+ const text = extractMessageText(record.payload.content);
160
+ if (!role || !text) {
161
+ return null;
162
+ }
163
+ return { role, text };
164
+ }
165
+ return null;
166
+ }
167
+
168
+ const role = normalizeRole(record.type);
169
+ if (!role) {
170
+ return null;
171
+ }
172
+ const content = record.message ? record.message.content : '';
173
+ const text = extractMessageText(content);
174
+ if (!text) {
175
+ return null;
176
+ }
177
+ return { role, text };
178
+ }
179
+
180
+ function appendSessionDetailTailMessage(state, record, source, lineIndex = -1) {
181
+ if (!state || typeof state !== 'object') {
182
+ return;
183
+ }
184
+
185
+ const message = extractMessageFromRecord(record, source);
186
+ if (!message) {
187
+ return;
188
+ }
189
+
190
+ const role = normalizeRole(message.role);
191
+ const text = typeof message.text === 'string' ? message.text : '';
192
+ if (!role || !text) {
193
+ return;
194
+ }
195
+
196
+ if (state.leadingSystem && (role === 'system' || isBootstrapLikeText(text))) {
197
+ return;
198
+ }
199
+
200
+ state.leadingSystem = false;
201
+ state.totalMessages += 1;
202
+ if (!Number.isFinite(state.tailLimit) || state.tailLimit <= 0) {
203
+ return;
204
+ }
205
+
206
+ if (state.messages.length >= state.tailLimit) {
207
+ state.messages.shift();
208
+ }
209
+ state.messages.push({
210
+ role,
211
+ text,
212
+ timestamp: toIsoTime(record && record.timestamp, ''),
213
+ recordLineIndex: Number.isInteger(lineIndex) ? lineIndex : -1
214
+ });
215
+ }
216
+
217
+ function applySessionDetailRecordMetadata(record, source, state) {
218
+ if (!state || typeof state !== 'object' || !record) {
219
+ return;
220
+ }
221
+
222
+ if (record.timestamp) {
223
+ state.updatedAt = toIsoTime(record.timestamp, state.updatedAt);
224
+ }
225
+
226
+ if (source === 'codex') {
227
+ if (record.type === 'session_meta' && record.payload) {
228
+ state.sessionId = record.payload.id || state.sessionId;
229
+ state.cwd = record.payload.cwd || state.cwd;
230
+ }
231
+ return;
232
+ }
233
+
234
+ if (!state.sessionId && record.sessionId) {
235
+ state.sessionId = record.sessionId;
236
+ }
237
+ if (!state.cwd && record.cwd) {
238
+ state.cwd = record.cwd;
239
+ }
240
+ }
241
+
242
+ function extractSessionDetailPreviewFromTailText(text, source, messageLimit) {
243
+ const safeMessageLimit = Number.isFinite(Number(messageLimit))
244
+ ? Math.max(1, Math.floor(Number(messageLimit)))
245
+ : DEFAULT_SESSION_DETAIL_MESSAGES;
246
+ const state = {
247
+ sessionId: '',
248
+ cwd: '',
249
+ updatedAt: '',
250
+ messages: [],
251
+ tailLimit: safeMessageLimit,
252
+ totalMessages: null,
253
+ clipped: false
254
+ };
255
+ const lines = typeof text === 'string' && text
256
+ ? text.split(/\r?\n/)
257
+ : [];
258
+
259
+ for (let lineIndex = lines.length - 1; lineIndex >= 0; lineIndex -= 1) {
260
+ const trimmed = lines[lineIndex].trim();
261
+ if (!trimmed) {
262
+ continue;
263
+ }
264
+
265
+ let record;
266
+ try {
267
+ record = JSON.parse(trimmed);
268
+ } catch (_) {
269
+ continue;
270
+ }
271
+
272
+ if (record && record.timestamp && !state.updatedAt) {
273
+ state.updatedAt = toIsoTime(record.timestamp, '');
274
+ }
275
+ if ((!state.sessionId || !state.cwd) && record) {
276
+ applySessionDetailRecordMetadata(record, source, state);
277
+ }
278
+
279
+ const message = extractMessageFromRecord(record, source);
280
+ if (!message) {
281
+ continue;
282
+ }
283
+
284
+ const role = normalizeRole(message.role);
285
+ const textValue = typeof message.text === 'string' ? message.text : '';
286
+ if (!role || !textValue) {
287
+ continue;
288
+ }
289
+
290
+ if (state.messages.length >= safeMessageLimit) {
291
+ state.clipped = true;
292
+ break;
293
+ }
294
+
295
+ state.messages.unshift({
296
+ role,
297
+ text: textValue,
298
+ timestamp: toIsoTime(record && record.timestamp, ''),
299
+ recordLineIndex: -1
300
+ });
301
+ }
302
+
303
+ return state;
304
+ }
305
+
306
+ function extractSessionDetailPreviewFromFileFast(filePath, source, messageLimit) {
307
+ const fileStat = getFileStatSafe(filePath);
308
+ if (!fileStat || !Number.isFinite(fileStat.size) || fileStat.size <= FAST_SESSION_DETAIL_PREVIEW_FILE_BYTES) {
309
+ return null;
310
+ }
311
+ const safeMessageLimit = Number.isFinite(Number(messageLimit))
312
+ ? Math.max(1, Math.floor(Number(messageLimit)))
313
+ : DEFAULT_SESSION_DETAIL_MESSAGES;
314
+
315
+ let fd = null;
316
+ let position = fileStat.size;
317
+ let totalBytesRead = 0;
318
+ let combined = Buffer.alloc(0);
319
+ let latest = {
320
+ sessionId: '',
321
+ cwd: '',
322
+ updatedAt: '',
323
+ messages: [],
324
+ totalMessages: null,
325
+ clipped: false
326
+ };
327
+
328
+ try {
329
+ fd = fs.openSync(filePath, 'r');
330
+ while (position > 0 && totalBytesRead < FAST_SESSION_DETAIL_PREVIEW_MAX_BYTES) {
331
+ const remainingBudget = FAST_SESSION_DETAIL_PREVIEW_MAX_BYTES - totalBytesRead;
332
+ const chunkSize = Math.min(FAST_SESSION_DETAIL_PREVIEW_CHUNK_BYTES, position, remainingBudget);
333
+ if (chunkSize <= 0) {
334
+ break;
335
+ }
336
+
337
+ position -= chunkSize;
338
+ const chunk = Buffer.allocUnsafe(chunkSize);
339
+ const bytesRead = fs.readSync(fd, chunk, 0, chunkSize, position);
340
+ if (bytesRead <= 0) {
341
+ break;
342
+ }
343
+
344
+ totalBytesRead += bytesRead;
345
+ combined = Buffer.concat([chunk.subarray(0, bytesRead), combined]);
346
+ latest = extractSessionDetailPreviewFromTailText(combined.toString('utf-8'), source, safeMessageLimit);
347
+ if (latest.messages.length >= safeMessageLimit) {
348
+ latest.clipped = latest.clipped || position > 0;
349
+ return latest;
350
+ }
351
+ }
352
+
353
+ if (position > 0) {
354
+ latest.clipped = latest.clipped || position > 0;
355
+ return latest;
356
+ }
357
+ const normalizedMessages = removeLeadingSystemMessage(latest.messages);
358
+ latest.messages = normalizedMessages.length > safeMessageLimit
359
+ ? normalizedMessages.slice(-safeMessageLimit)
360
+ : normalizedMessages;
361
+ latest.totalMessages = normalizedMessages.length;
362
+ latest.clipped = latest.totalMessages > latest.messages.length;
363
+ return latest;
364
+ } catch (_) {
365
+ return null;
366
+ } finally {
367
+ if (fd !== null) {
368
+ try { fs.closeSync(fd); } catch (e) {}
369
+ }
370
+ }
371
+ }
372
+
373
+ module.exports = {
374
+ BOOTSTRAP_TEXT_MARKERS,
375
+ getFileStatSafe,
376
+ isBootstrapLikeText,
377
+ removeLeadingSystemMessage,
378
+ normalizeQueryTokens,
379
+ expandSessionQueryTokens,
380
+ matchTokensInText,
381
+ extractMessageFromRecord,
382
+ appendSessionDetailTailMessage,
383
+ applySessionDetailRecordMetadata,
384
+ extractSessionDetailPreviewFromTailText,
385
+ extractSessionDetailPreviewFromFileFast
386
+ };
package/lib/cli-utils.js CHANGED
@@ -1,155 +1,155 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const os = require('os');
4
-
5
- const UTF8_BOM = '\ufeff';
6
-
7
- function expandHomePath(value) {
8
- if (typeof value !== 'string') {
9
- return '';
10
- }
11
- const trimmed = value.trim();
12
- if (!trimmed) {
13
- return '';
14
- }
15
- if (trimmed === '~') {
16
- return os.homedir();
17
- }
18
- if (trimmed.startsWith(`~${path.sep}`) || trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
19
- return path.resolve(os.homedir(), trimmed.slice(2));
20
- }
21
- return trimmed;
22
- }
23
-
24
- function resolveExistingDir(candidates = [], fallback = '') {
25
- for (const raw of candidates) {
26
- const candidate = expandHomePath(raw);
27
- if (!candidate) continue;
28
- try {
29
- if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) {
30
- return candidate;
31
- }
32
- } catch (e) {}
33
- }
34
- return fallback;
35
- }
36
-
37
- function resolveHomePath(input) {
38
- const raw = typeof input === 'string' ? input.trim() : '';
39
- if (!raw) return '';
40
- if (raw === '~') return os.homedir();
41
- if (raw.startsWith('~/') || raw.startsWith('~\\')) {
42
- return path.join(os.homedir(), raw.slice(2));
43
- }
44
- return raw;
45
- }
46
-
47
- function hasUtf8Bom(text) {
48
- return typeof text === 'string' && text.charCodeAt(0) === 0xfeff;
49
- }
50
-
51
- function stripUtf8Bom(text) {
52
- if (!text) return '';
53
- return hasUtf8Bom(text) ? text.slice(1) : text;
54
- }
55
-
56
- function ensureUtf8Bom(text) {
57
- const content = typeof text === 'string' ? text : '';
58
- return hasUtf8Bom(content) ? content : UTF8_BOM + content;
59
- }
60
-
61
- function detectLineEnding(text) {
62
- return typeof text === 'string' && text.includes('\r\n') ? '\r\n' : '\n';
63
- }
64
-
65
- function normalizeLineEnding(text, lineEnding) {
66
- const normalized = String(text || '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
67
- return lineEnding === '\r\n' ? normalized.replace(/\n/g, '\r\n') : normalized;
68
- }
69
-
70
- function isValidProviderName(name) {
71
- return typeof name === 'string' && /^[a-zA-Z0-9._-]+$/.test(name.trim());
72
- }
73
-
74
- function escapeTomlBasicString(value) {
75
- return String(value || '')
76
- .replace(/\\/g, '\\\\')
77
- .replace(/"/g, '\\"');
78
- }
79
-
80
- function buildModelProviderTableHeader(providerName) {
81
- const raw = typeof providerName === 'string' ? providerName.trim() : '';
82
- if (/^[a-zA-Z0-9_-]+$/.test(raw)) {
83
- return `[model_providers.${raw}]`;
84
- }
85
- return `[model_providers."${escapeTomlBasicString(raw)}"]`;
86
- }
87
-
88
- function buildModelsCandidates(baseUrl) {
89
- const trimmed = typeof baseUrl === 'string' ? baseUrl.trim() : '';
90
- if (!trimmed) return [];
91
- if (/\/models\/?$/.test(trimmed)) {
92
- return [trimmed];
93
- }
94
- const normalized = trimmed.replace(/\/+$/, '');
95
- const candidates = [];
96
- const pushUnique = (url) => {
97
- if (url && !candidates.includes(url)) {
98
- candidates.push(url);
99
- }
100
- };
101
-
102
- if (/\/v1$/i.test(normalized)) {
103
- pushUnique(normalized + '/models');
104
- } else {
105
- pushUnique(normalized + '/v1/models');
106
- pushUnique(normalized + '/models');
107
- }
108
-
109
- pushUnique(trimmed);
110
- return candidates;
111
- }
112
-
113
- function isValidHttpUrl(value) {
114
- if (typeof value !== 'string' || !value.trim()) return false;
115
- try {
116
- const parsed = new URL(value);
117
- return parsed.protocol === 'http:' || parsed.protocol === 'https:';
118
- } catch (e) {
119
- return false;
120
- }
121
- }
122
-
123
- function normalizeBaseUrl(value) {
124
- if (typeof value !== 'string') return '';
125
- return value.trim().replace(/\/+$/g, '');
126
- }
127
-
128
- function joinApiUrl(baseUrl, pathSuffix) {
129
- const trimmed = normalizeBaseUrl(baseUrl);
130
- if (!trimmed) return '';
131
- const safeSuffix = String(pathSuffix || '').replace(/^\/+/g, '');
132
- if (!safeSuffix) return trimmed;
133
- if (/\/v1$/i.test(trimmed)) {
134
- return `${trimmed}/${safeSuffix}`;
135
- }
136
- return `${trimmed}/v1/${safeSuffix}`;
137
- }
138
-
139
- module.exports = {
140
- expandHomePath,
141
- resolveExistingDir,
142
- resolveHomePath,
143
- hasUtf8Bom,
144
- stripUtf8Bom,
145
- ensureUtf8Bom,
146
- detectLineEnding,
147
- normalizeLineEnding,
148
- isValidProviderName,
149
- escapeTomlBasicString,
150
- buildModelProviderTableHeader,
151
- buildModelsCandidates,
152
- isValidHttpUrl,
153
- normalizeBaseUrl,
154
- joinApiUrl
155
- };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+
5
+ const UTF8_BOM = '\ufeff';
6
+
7
+ function expandHomePath(value) {
8
+ if (typeof value !== 'string') {
9
+ return '';
10
+ }
11
+ const trimmed = value.trim();
12
+ if (!trimmed) {
13
+ return '';
14
+ }
15
+ if (trimmed === '~') {
16
+ return os.homedir();
17
+ }
18
+ if (trimmed.startsWith(`~${path.sep}`) || trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
19
+ return path.resolve(os.homedir(), trimmed.slice(2));
20
+ }
21
+ return trimmed;
22
+ }
23
+
24
+ function resolveExistingDir(candidates = [], fallback = '') {
25
+ for (const raw of candidates) {
26
+ const candidate = expandHomePath(raw);
27
+ if (!candidate) continue;
28
+ try {
29
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) {
30
+ return candidate;
31
+ }
32
+ } catch (e) {}
33
+ }
34
+ return fallback;
35
+ }
36
+
37
+ function resolveHomePath(input) {
38
+ const raw = typeof input === 'string' ? input.trim() : '';
39
+ if (!raw) return '';
40
+ if (raw === '~') return os.homedir();
41
+ if (raw.startsWith('~/') || raw.startsWith('~\\')) {
42
+ return path.join(os.homedir(), raw.slice(2));
43
+ }
44
+ return raw;
45
+ }
46
+
47
+ function hasUtf8Bom(text) {
48
+ return typeof text === 'string' && text.charCodeAt(0) === 0xfeff;
49
+ }
50
+
51
+ function stripUtf8Bom(text) {
52
+ if (!text) return '';
53
+ return hasUtf8Bom(text) ? text.slice(1) : text;
54
+ }
55
+
56
+ function ensureUtf8Bom(text) {
57
+ const content = typeof text === 'string' ? text : '';
58
+ return hasUtf8Bom(content) ? content : UTF8_BOM + content;
59
+ }
60
+
61
+ function detectLineEnding(text) {
62
+ return typeof text === 'string' && text.includes('\r\n') ? '\r\n' : '\n';
63
+ }
64
+
65
+ function normalizeLineEnding(text, lineEnding) {
66
+ const normalized = String(text || '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
67
+ return lineEnding === '\r\n' ? normalized.replace(/\n/g, '\r\n') : normalized;
68
+ }
69
+
70
+ function isValidProviderName(name) {
71
+ return typeof name === 'string' && /^[a-zA-Z0-9._-]+$/.test(name.trim());
72
+ }
73
+
74
+ function escapeTomlBasicString(value) {
75
+ return String(value || '')
76
+ .replace(/\\/g, '\\\\')
77
+ .replace(/"/g, '\\"');
78
+ }
79
+
80
+ function buildModelProviderTableHeader(providerName) {
81
+ const raw = typeof providerName === 'string' ? providerName.trim() : '';
82
+ if (/^[a-zA-Z0-9_-]+$/.test(raw)) {
83
+ return `[model_providers.${raw}]`;
84
+ }
85
+ return `[model_providers."${escapeTomlBasicString(raw)}"]`;
86
+ }
87
+
88
+ function buildModelsCandidates(baseUrl) {
89
+ const trimmed = typeof baseUrl === 'string' ? baseUrl.trim() : '';
90
+ if (!trimmed) return [];
91
+ if (/\/models\/?$/.test(trimmed)) {
92
+ return [trimmed];
93
+ }
94
+ const normalized = trimmed.replace(/\/+$/, '');
95
+ const candidates = [];
96
+ const pushUnique = (url) => {
97
+ if (url && !candidates.includes(url)) {
98
+ candidates.push(url);
99
+ }
100
+ };
101
+
102
+ if (/\/v1$/i.test(normalized)) {
103
+ pushUnique(normalized + '/models');
104
+ } else {
105
+ pushUnique(normalized + '/v1/models');
106
+ pushUnique(normalized + '/models');
107
+ }
108
+
109
+ pushUnique(trimmed);
110
+ return candidates;
111
+ }
112
+
113
+ function isValidHttpUrl(value) {
114
+ if (typeof value !== 'string' || !value.trim()) return false;
115
+ try {
116
+ const parsed = new URL(value);
117
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:';
118
+ } catch (e) {
119
+ return false;
120
+ }
121
+ }
122
+
123
+ function normalizeBaseUrl(value) {
124
+ if (typeof value !== 'string') return '';
125
+ return value.trim().replace(/\/+$/g, '');
126
+ }
127
+
128
+ function joinApiUrl(baseUrl, pathSuffix) {
129
+ const trimmed = normalizeBaseUrl(baseUrl);
130
+ if (!trimmed) return '';
131
+ const safeSuffix = String(pathSuffix || '').replace(/^\/+/g, '');
132
+ if (!safeSuffix) return trimmed;
133
+ if (/\/v1$/i.test(trimmed)) {
134
+ return `${trimmed}/${safeSuffix}`;
135
+ }
136
+ return `${trimmed}/v1/${safeSuffix}`;
137
+ }
138
+
139
+ module.exports = {
140
+ expandHomePath,
141
+ resolveExistingDir,
142
+ resolveHomePath,
143
+ hasUtf8Bom,
144
+ stripUtf8Bom,
145
+ ensureUtf8Bom,
146
+ detectLineEnding,
147
+ normalizeLineEnding,
148
+ isValidProviderName,
149
+ escapeTomlBasicString,
150
+ buildModelProviderTableHeader,
151
+ buildModelsCandidates,
152
+ isValidHttpUrl,
153
+ normalizeBaseUrl,
154
+ joinApiUrl
155
+ };