codexmate 0.0.7 → 0.0.8
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.
- package/.github/workflows/release.yml +122 -8
- package/README.md +48 -40
- package/README.zh-CN.md +48 -40
- package/cli.js +791 -1211
- package/lib/cli-file-utils.js +149 -0
- package/lib/cli-models-utils.js +152 -0
- package/lib/cli-network-utils.js +148 -0
- package/lib/cli-session-utils.js +121 -0
- package/lib/cli-utils.js +139 -0
- package/package.json +3 -2
- package/tests/e2e/helpers.js +214 -0
- package/tests/e2e/recent-health.e2e.js +6 -0
- package/tests/e2e/run.js +84 -302
- package/tests/e2e/test-claude.js +21 -0
- package/tests/e2e/test-config.js +124 -0
- package/tests/e2e/test-health-speed.js +75 -0
- package/tests/e2e/test-openclaw.js +47 -0
- package/tests/e2e/test-sessions.js +60 -0
- package/tests/e2e/test-setup.js +90 -0
- package/web-ui.html +912 -423
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
|
|
4
|
+
function ensureDir(dirPath) {
|
|
5
|
+
if (!fs.existsSync(dirPath)) {
|
|
6
|
+
fs.mkdirSync(dirPath, { recursive: true });
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function stripUtf8Bom(content) {
|
|
11
|
+
if (typeof content !== 'string') return '';
|
|
12
|
+
return content.charCodeAt(0) === 0xFEFF ? content.slice(1) : content;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function readJsonFile(filePath, fallback = null) {
|
|
16
|
+
if (!fs.existsSync(filePath)) {
|
|
17
|
+
return fallback;
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
const content = stripUtf8Bom(fs.readFileSync(filePath, 'utf-8'));
|
|
21
|
+
return JSON.parse(content);
|
|
22
|
+
} catch (e) {
|
|
23
|
+
return fallback;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function readJsonArrayFile(filePath, fallback = []) {
|
|
28
|
+
if (!fs.existsSync(filePath)) {
|
|
29
|
+
return Array.isArray(fallback) ? [...fallback] : [];
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
const content = stripUtf8Bom(fs.readFileSync(filePath, 'utf-8'));
|
|
33
|
+
if (!content.trim()) {
|
|
34
|
+
return Array.isArray(fallback) ? [...fallback] : [];
|
|
35
|
+
}
|
|
36
|
+
const parsed = JSON.parse(content);
|
|
37
|
+
return Array.isArray(parsed) ? parsed : (Array.isArray(fallback) ? [...fallback] : []);
|
|
38
|
+
} catch (e) {
|
|
39
|
+
return Array.isArray(fallback) ? [...fallback] : [];
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function readJsonObjectFromFile(filePath, fallback = {}) {
|
|
44
|
+
if (!fs.existsSync(filePath)) {
|
|
45
|
+
return { ok: true, exists: false, data: { ...fallback } };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
const content = stripUtf8Bom(fs.readFileSync(filePath, 'utf-8'));
|
|
50
|
+
if (!content.trim()) {
|
|
51
|
+
return { ok: true, exists: true, data: { ...fallback } };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const parsed = JSON.parse(content);
|
|
55
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
56
|
+
return {
|
|
57
|
+
ok: false,
|
|
58
|
+
exists: true,
|
|
59
|
+
error: `配置文件格式错误(根节点必须是对象): ${filePath}`
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
return { ok: true, exists: true, data: parsed };
|
|
63
|
+
} catch (e) {
|
|
64
|
+
return {
|
|
65
|
+
ok: false,
|
|
66
|
+
exists: true,
|
|
67
|
+
error: `配置文件解析失败: ${e.message}`
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function formatTimestampForFileName(value) {
|
|
73
|
+
const date = value ? new Date(value) : new Date();
|
|
74
|
+
const normalized = Number.isNaN(date.getTime()) ? new Date() : date;
|
|
75
|
+
const pad = (num) => String(num).padStart(2, '0');
|
|
76
|
+
return [
|
|
77
|
+
normalized.getFullYear(),
|
|
78
|
+
pad(normalized.getMonth() + 1),
|
|
79
|
+
pad(normalized.getDate()),
|
|
80
|
+
'-',
|
|
81
|
+
pad(normalized.getHours()),
|
|
82
|
+
pad(normalized.getMinutes()),
|
|
83
|
+
pad(normalized.getSeconds())
|
|
84
|
+
].join('');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function backupFileIfNeededOnce(filePath, backupPrefix = 'codexmate-backup') {
|
|
88
|
+
if (!fs.existsSync(filePath)) {
|
|
89
|
+
return '';
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const dirPath = path.dirname(filePath);
|
|
93
|
+
const baseName = path.basename(filePath);
|
|
94
|
+
const existingPrefix = `${baseName}.${backupPrefix}-`;
|
|
95
|
+
const hasBackup = fs.readdirSync(dirPath).some(fileName =>
|
|
96
|
+
fileName.startsWith(existingPrefix) && fileName.endsWith('.bak')
|
|
97
|
+
);
|
|
98
|
+
|
|
99
|
+
if (hasBackup) {
|
|
100
|
+
return '';
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const backupPath = path.join(dirPath, `${existingPrefix}${formatTimestampForFileName()}.bak`);
|
|
104
|
+
fs.copyFileSync(filePath, backupPath);
|
|
105
|
+
return backupPath;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function writeJsonAtomic(filePath, data) {
|
|
109
|
+
const dirPath = path.dirname(filePath);
|
|
110
|
+
ensureDir(dirPath);
|
|
111
|
+
|
|
112
|
+
const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
|
113
|
+
const content = `${JSON.stringify(data, null, 2)}\n`;
|
|
114
|
+
|
|
115
|
+
try {
|
|
116
|
+
fs.writeFileSync(tmpPath, content, 'utf-8');
|
|
117
|
+
if (fs.existsSync(filePath)) {
|
|
118
|
+
const existingMode = fs.statSync(filePath).mode;
|
|
119
|
+
fs.chmodSync(tmpPath, existingMode);
|
|
120
|
+
} else {
|
|
121
|
+
fs.chmodSync(tmpPath, 0o600);
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
fs.renameSync(tmpPath, filePath);
|
|
125
|
+
} catch (renameError) {
|
|
126
|
+
if (process.platform === 'win32') {
|
|
127
|
+
fs.copyFileSync(tmpPath, filePath);
|
|
128
|
+
fs.unlinkSync(tmpPath);
|
|
129
|
+
} else {
|
|
130
|
+
throw renameError;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
} catch (e) {
|
|
134
|
+
if (fs.existsSync(tmpPath)) {
|
|
135
|
+
try { fs.unlinkSync(tmpPath); } catch (_) {}
|
|
136
|
+
}
|
|
137
|
+
throw new Error(`写入 JSON 文件失败: ${e.message}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
module.exports = {
|
|
142
|
+
ensureDir,
|
|
143
|
+
readJsonFile,
|
|
144
|
+
readJsonArrayFile,
|
|
145
|
+
readJsonObjectFromFile,
|
|
146
|
+
backupFileIfNeededOnce,
|
|
147
|
+
writeJsonAtomic,
|
|
148
|
+
formatTimestampForFileName
|
|
149
|
+
};
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
const crypto = require('crypto');
|
|
2
|
+
const { joinApiUrl, normalizeBaseUrl } = require('./cli-utils');
|
|
3
|
+
|
|
4
|
+
function extractModelNames(payload) {
|
|
5
|
+
if (!payload || typeof payload !== 'object') return [];
|
|
6
|
+
const data = Array.isArray(payload.data)
|
|
7
|
+
? payload.data
|
|
8
|
+
: (Array.isArray(payload.models) ? payload.models : []);
|
|
9
|
+
const names = [];
|
|
10
|
+
for (const item of data) {
|
|
11
|
+
if (typeof item === 'string') {
|
|
12
|
+
if (item.trim()) names.push(item.trim());
|
|
13
|
+
continue;
|
|
14
|
+
}
|
|
15
|
+
if (!item || typeof item !== 'object') continue;
|
|
16
|
+
const name = item.id || item.name || item.model || '';
|
|
17
|
+
if (typeof name === 'string' && name.trim()) {
|
|
18
|
+
names.push(name.trim());
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return Array.from(new Set(names));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function hasModelsListPayload(payload) {
|
|
25
|
+
if (!payload || typeof payload !== 'object') return false;
|
|
26
|
+
return Array.isArray(payload.data) || Array.isArray(payload.models);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function extractModelIds(payload) {
|
|
30
|
+
const ids = [];
|
|
31
|
+
const pushValue = (value) => {
|
|
32
|
+
if (typeof value === 'string' && value.trim()) {
|
|
33
|
+
ids.push(value.trim());
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
if (!payload) return ids;
|
|
38
|
+
|
|
39
|
+
if (Array.isArray(payload)) {
|
|
40
|
+
for (const item of payload) {
|
|
41
|
+
if (item && typeof item === 'object') {
|
|
42
|
+
pushValue(item.id);
|
|
43
|
+
pushValue(item.model);
|
|
44
|
+
pushValue(item.name);
|
|
45
|
+
} else {
|
|
46
|
+
pushValue(item);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return ids;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (Array.isArray(payload.data)) {
|
|
53
|
+
for (const item of payload.data) {
|
|
54
|
+
if (item && typeof item === 'object') {
|
|
55
|
+
pushValue(item.id);
|
|
56
|
+
pushValue(item.model);
|
|
57
|
+
pushValue(item.name);
|
|
58
|
+
} else {
|
|
59
|
+
pushValue(item);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (Array.isArray(payload.models)) {
|
|
65
|
+
for (const item of payload.models) {
|
|
66
|
+
if (item && typeof item === 'object') {
|
|
67
|
+
pushValue(item.id);
|
|
68
|
+
pushValue(item.model);
|
|
69
|
+
pushValue(item.name);
|
|
70
|
+
} else {
|
|
71
|
+
pushValue(item);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return ids;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function normalizeWireApi(value) {
|
|
80
|
+
const raw = typeof value === 'string' ? value.trim().toLowerCase() : '';
|
|
81
|
+
if (!raw) return 'responses';
|
|
82
|
+
return raw.replace(/[\s\-\/]/g, '_');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function buildModelsProbeUrl(baseUrl) {
|
|
86
|
+
return joinApiUrl(baseUrl, 'models');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function buildModelProbeSpec(provider, modelName, baseUrl) {
|
|
90
|
+
const model = typeof modelName === 'string' ? modelName.trim() : '';
|
|
91
|
+
if (!model) return null;
|
|
92
|
+
|
|
93
|
+
const wireApi = normalizeWireApi(provider && provider.wire_api);
|
|
94
|
+
if (wireApi === 'chat_completions' || wireApi === 'chat') {
|
|
95
|
+
return {
|
|
96
|
+
url: joinApiUrl(baseUrl, 'chat/completions'),
|
|
97
|
+
body: {
|
|
98
|
+
model,
|
|
99
|
+
messages: [{ role: 'user', content: 'ping' }],
|
|
100
|
+
max_tokens: 1,
|
|
101
|
+
temperature: 0
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (wireApi === 'completions') {
|
|
107
|
+
return {
|
|
108
|
+
url: joinApiUrl(baseUrl, 'completions'),
|
|
109
|
+
body: {
|
|
110
|
+
model,
|
|
111
|
+
prompt: 'ping',
|
|
112
|
+
max_tokens: 1,
|
|
113
|
+
temperature: 0
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
url: joinApiUrl(baseUrl, 'responses'),
|
|
120
|
+
body: {
|
|
121
|
+
model,
|
|
122
|
+
input: 'ping',
|
|
123
|
+
max_output_tokens: 1
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function hashModelsCacheValue(value) {
|
|
129
|
+
if (!value) return '';
|
|
130
|
+
try {
|
|
131
|
+
return crypto.createHash('sha256').update(String(value)).digest('hex');
|
|
132
|
+
} catch (e) {
|
|
133
|
+
return '';
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function buildModelsCacheKey(baseUrl, apiKey) {
|
|
138
|
+
const normalizedUrl = normalizeBaseUrl(baseUrl);
|
|
139
|
+
const apiKeyHash = hashModelsCacheValue(apiKey);
|
|
140
|
+
return `${normalizedUrl}|${apiKeyHash}`;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
module.exports = {
|
|
144
|
+
extractModelNames,
|
|
145
|
+
hasModelsListPayload,
|
|
146
|
+
extractModelIds,
|
|
147
|
+
normalizeWireApi,
|
|
148
|
+
buildModelsProbeUrl,
|
|
149
|
+
buildModelProbeSpec,
|
|
150
|
+
hashModelsCacheValue,
|
|
151
|
+
buildModelsCacheKey
|
|
152
|
+
};
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
const http = require('http');
|
|
2
|
+
const https = require('https');
|
|
3
|
+
|
|
4
|
+
function probeUrl(targetUrl, options = {}) {
|
|
5
|
+
return new Promise((resolve) => {
|
|
6
|
+
let parsed;
|
|
7
|
+
try {
|
|
8
|
+
parsed = new URL(targetUrl);
|
|
9
|
+
} catch (e) {
|
|
10
|
+
return resolve({ ok: false, error: 'Invalid URL' });
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const protocol = parsed.protocol;
|
|
14
|
+
if (protocol !== 'http:' && protocol !== 'https:') {
|
|
15
|
+
return resolve({
|
|
16
|
+
ok: false,
|
|
17
|
+
error: `ERR_INVALID_PROTOCOL: Protocol "${protocol}" not supported. Expected "http:" or "https:"`
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const transport = protocol === 'https:' ? https : http;
|
|
22
|
+
const headers = {
|
|
23
|
+
'User-Agent': 'codexmate-health-check',
|
|
24
|
+
'Accept': 'application/json'
|
|
25
|
+
};
|
|
26
|
+
if (options.apiKey) {
|
|
27
|
+
headers['Authorization'] = `Bearer ${options.apiKey}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 0;
|
|
31
|
+
const maxBytes = Number.isFinite(options.maxBytes) ? options.maxBytes : 256 * 1024;
|
|
32
|
+
const start = Date.now();
|
|
33
|
+
const req = transport.request(parsed, { method: 'GET', headers }, (res) => {
|
|
34
|
+
const chunks = [];
|
|
35
|
+
let size = 0;
|
|
36
|
+
res.on('data', (chunk) => {
|
|
37
|
+
if (!chunk) return;
|
|
38
|
+
size += chunk.length;
|
|
39
|
+
if (size <= maxBytes) {
|
|
40
|
+
chunks.push(chunk);
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
res.on('end', () => {
|
|
44
|
+
const body = chunks.length > 0 ? Buffer.concat(chunks).toString('utf-8') : '';
|
|
45
|
+
resolve({
|
|
46
|
+
ok: true,
|
|
47
|
+
status: res.statusCode || 0,
|
|
48
|
+
durationMs: Date.now() - start,
|
|
49
|
+
body
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
if (timeoutMs > 0) {
|
|
55
|
+
req.setTimeout(timeoutMs, () => {
|
|
56
|
+
req.destroy(new Error('timeout'));
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
req.on('error', (err) => {
|
|
61
|
+
resolve({
|
|
62
|
+
ok: false,
|
|
63
|
+
error: err.message || 'request failed',
|
|
64
|
+
durationMs: Date.now() - start
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
req.end();
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function probeJsonPost(targetUrl, body, options = {}) {
|
|
73
|
+
return new Promise((resolve) => {
|
|
74
|
+
let parsed;
|
|
75
|
+
try {
|
|
76
|
+
parsed = new URL(targetUrl);
|
|
77
|
+
} catch (e) {
|
|
78
|
+
return resolve({ ok: false, error: 'Invalid URL' });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const protocol = parsed.protocol;
|
|
82
|
+
if (protocol !== 'http:' && protocol !== 'https:') {
|
|
83
|
+
return resolve({
|
|
84
|
+
ok: false,
|
|
85
|
+
error: `ERR_INVALID_PROTOCOL: Protocol "${protocol}" not supported. Expected "http:" or "https:"`
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const transport = protocol === 'https:' ? https : http;
|
|
90
|
+
const headers = {
|
|
91
|
+
'User-Agent': 'codexmate-health-check',
|
|
92
|
+
'Accept': 'application/json',
|
|
93
|
+
'Content-Type': 'application/json'
|
|
94
|
+
};
|
|
95
|
+
if (options.apiKey) {
|
|
96
|
+
headers['Authorization'] = `Bearer ${options.apiKey}`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const payload = JSON.stringify(body || {});
|
|
100
|
+
headers['Content-Length'] = Buffer.byteLength(payload);
|
|
101
|
+
|
|
102
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 0;
|
|
103
|
+
const maxBytes = Number.isFinite(options.maxBytes) ? options.maxBytes : 256 * 1024;
|
|
104
|
+
const start = Date.now();
|
|
105
|
+
const req = transport.request(parsed, { method: 'POST', headers }, (res) => {
|
|
106
|
+
const chunks = [];
|
|
107
|
+
let size = 0;
|
|
108
|
+
res.on('data', (chunk) => {
|
|
109
|
+
if (!chunk) return;
|
|
110
|
+
size += chunk.length;
|
|
111
|
+
if (size <= maxBytes) {
|
|
112
|
+
chunks.push(chunk);
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
res.on('end', () => {
|
|
116
|
+
const bodyText = chunks.length > 0 ? Buffer.concat(chunks).toString('utf-8') : '';
|
|
117
|
+
resolve({
|
|
118
|
+
ok: true,
|
|
119
|
+
status: res.statusCode || 0,
|
|
120
|
+
durationMs: Date.now() - start,
|
|
121
|
+
body: bodyText
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
if (timeoutMs > 0) {
|
|
127
|
+
req.setTimeout(timeoutMs, () => {
|
|
128
|
+
req.destroy(new Error('timeout'));
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
req.on('error', (err) => {
|
|
133
|
+
resolve({
|
|
134
|
+
ok: false,
|
|
135
|
+
error: err.message || 'request failed',
|
|
136
|
+
durationMs: Date.now() - start
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
req.write(payload);
|
|
141
|
+
req.end();
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
module.exports = {
|
|
146
|
+
probeUrl,
|
|
147
|
+
probeJsonPost
|
|
148
|
+
};
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
function toIsoTime(value, fallback = '') {
|
|
2
|
+
if (value === undefined || value === null || value === '') {
|
|
3
|
+
return fallback;
|
|
4
|
+
}
|
|
5
|
+
const date = new Date(value);
|
|
6
|
+
if (Number.isNaN(date.getTime())) {
|
|
7
|
+
return fallback;
|
|
8
|
+
}
|
|
9
|
+
return date.toISOString();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function updateLatestIso(currentIso, candidate) {
|
|
13
|
+
const currentTime = Date.parse(currentIso || '') || 0;
|
|
14
|
+
const candidateIso = toIsoTime(candidate, '');
|
|
15
|
+
const candidateTime = Date.parse(candidateIso || '') || 0;
|
|
16
|
+
if (!candidateTime) {
|
|
17
|
+
return currentIso;
|
|
18
|
+
}
|
|
19
|
+
return candidateTime > currentTime ? candidateIso : currentIso;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function truncateText(text, maxLength = 90) {
|
|
23
|
+
if (!text) return '';
|
|
24
|
+
const normalized = String(text).replace(/\s+/g, ' ').trim();
|
|
25
|
+
if (normalized.length <= maxLength) return normalized;
|
|
26
|
+
return normalized.slice(0, maxLength - 1) + '…';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function extractMessageText(content) {
|
|
30
|
+
if (typeof content === 'string') {
|
|
31
|
+
return content.trim();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (Array.isArray(content)) {
|
|
35
|
+
const parts = content
|
|
36
|
+
.map(item => extractMessageText(item))
|
|
37
|
+
.filter(Boolean);
|
|
38
|
+
return parts.join('\n').trim();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (!content || typeof content !== 'object') {
|
|
42
|
+
return '';
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (typeof content.text === 'string') {
|
|
46
|
+
return content.text.trim();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (typeof content.value === 'string') {
|
|
50
|
+
return content.value.trim();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (content.content !== undefined) {
|
|
54
|
+
return extractMessageText(content.content);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (typeof content.output === 'string') {
|
|
58
|
+
return content.output.trim();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return '';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function normalizeRole(value) {
|
|
65
|
+
if (typeof value !== 'string') {
|
|
66
|
+
return '';
|
|
67
|
+
}
|
|
68
|
+
const role = value.trim().toLowerCase();
|
|
69
|
+
if (role === 'assistant' || role === 'user' || role === 'system') {
|
|
70
|
+
return role;
|
|
71
|
+
}
|
|
72
|
+
return '';
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function parseMaxMessagesValue(value) {
|
|
76
|
+
if (value === Infinity) {
|
|
77
|
+
return Infinity;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (typeof value === 'string') {
|
|
81
|
+
const trimmed = value.trim();
|
|
82
|
+
if (!trimmed) {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
const lower = trimmed.toLowerCase();
|
|
86
|
+
if (lower === 'all' || lower === 'infinity' || lower === 'inf') {
|
|
87
|
+
return Infinity;
|
|
88
|
+
}
|
|
89
|
+
const parsed = Number(trimmed);
|
|
90
|
+
if (Number.isFinite(parsed)) {
|
|
91
|
+
return parsed;
|
|
92
|
+
}
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (Number.isFinite(value)) {
|
|
97
|
+
return value;
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function resolveMaxMessagesValue(value, fallback) {
|
|
103
|
+
const parsed = parseMaxMessagesValue(value);
|
|
104
|
+
if (parsed === null) {
|
|
105
|
+
return fallback;
|
|
106
|
+
}
|
|
107
|
+
if (parsed === Infinity) {
|
|
108
|
+
return Infinity;
|
|
109
|
+
}
|
|
110
|
+
return Math.max(1, Math.floor(parsed));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
module.exports = {
|
|
114
|
+
toIsoTime,
|
|
115
|
+
updateLatestIso,
|
|
116
|
+
truncateText,
|
|
117
|
+
extractMessageText,
|
|
118
|
+
normalizeRole,
|
|
119
|
+
parseMaxMessagesValue,
|
|
120
|
+
resolveMaxMessagesValue
|
|
121
|
+
};
|
package/lib/cli-utils.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
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 buildModelsCandidates(baseUrl) {
|
|
75
|
+
const trimmed = typeof baseUrl === 'string' ? baseUrl.trim() : '';
|
|
76
|
+
if (!trimmed) return [];
|
|
77
|
+
if (/\/models\/?$/.test(trimmed)) {
|
|
78
|
+
return [trimmed];
|
|
79
|
+
}
|
|
80
|
+
const normalized = trimmed.replace(/\/+$/, '');
|
|
81
|
+
const candidates = [];
|
|
82
|
+
const pushUnique = (url) => {
|
|
83
|
+
if (url && !candidates.includes(url)) {
|
|
84
|
+
candidates.push(url);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
if (/\/v1$/i.test(normalized)) {
|
|
89
|
+
pushUnique(normalized + '/models');
|
|
90
|
+
} else {
|
|
91
|
+
pushUnique(normalized + '/v1/models');
|
|
92
|
+
pushUnique(normalized + '/models');
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
pushUnique(trimmed);
|
|
96
|
+
return candidates;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function isValidHttpUrl(value) {
|
|
100
|
+
if (typeof value !== 'string' || !value.trim()) return false;
|
|
101
|
+
try {
|
|
102
|
+
const parsed = new URL(value);
|
|
103
|
+
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
|
|
104
|
+
} catch (e) {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function normalizeBaseUrl(value) {
|
|
110
|
+
if (typeof value !== 'string') return '';
|
|
111
|
+
return value.trim().replace(/\/+$/g, '');
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function joinApiUrl(baseUrl, pathSuffix) {
|
|
115
|
+
const trimmed = normalizeBaseUrl(baseUrl);
|
|
116
|
+
if (!trimmed) return '';
|
|
117
|
+
const safeSuffix = String(pathSuffix || '').replace(/^\/+/g, '');
|
|
118
|
+
if (!safeSuffix) return trimmed;
|
|
119
|
+
if (/\/v1$/i.test(trimmed)) {
|
|
120
|
+
return `${trimmed}/${safeSuffix}`;
|
|
121
|
+
}
|
|
122
|
+
return `${trimmed}/v1/${safeSuffix}`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
module.exports = {
|
|
126
|
+
expandHomePath,
|
|
127
|
+
resolveExistingDir,
|
|
128
|
+
resolveHomePath,
|
|
129
|
+
hasUtf8Bom,
|
|
130
|
+
stripUtf8Bom,
|
|
131
|
+
ensureUtf8Bom,
|
|
132
|
+
detectLineEnding,
|
|
133
|
+
normalizeLineEnding,
|
|
134
|
+
isValidProviderName,
|
|
135
|
+
buildModelsCandidates,
|
|
136
|
+
isValidHttpUrl,
|
|
137
|
+
normalizeBaseUrl,
|
|
138
|
+
joinApiUrl
|
|
139
|
+
};
|