codexmate 0.1.32 → 0.1.34
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/README.md +18 -2
- package/README.vi.md +18 -2
- package/README.zh.md +18 -2
- package/cli/claude-proxy.js +2 -2
- package/cli/local-bridge.js +10 -6
- package/cli/openai-chat-routing.js +38 -0
- package/cli/prompt-history.js +2 -0
- package/cli/routing-bridge.js +143 -0
- package/cli/system-prompt-files.js +75 -53
- package/cli.js +325 -215
- package/lib/cli-config-engine.js +6 -1
- package/lib/cli-file-utils.js +6 -1
- package/lib/config-change-fs.js +132 -0
- package/lib/config-changes.js +293 -0
- package/lib/file-sharing-lan.js +111 -0
- package/lib/file-sharing.js +196 -0
- package/lib/handoff-mcp.js +18 -2
- package/lib/local-feature-store.js +39 -0
- package/lib/model-test-client.js +61 -0
- package/lib/model-test.js +126 -0
- package/lib/routing-groups.js +161 -0
- package/lib/session-bookmarks.js +72 -0
- package/lib/session-context-health.js +23 -3
- package/lib/session-diagnostics.js +75 -0
- package/lib/session-feature-settings.js +21 -0
- package/lib/session-features.js +63 -0
- package/lib/session-handoff-draft.js +43 -0
- package/lib/session-projects.js +76 -0
- package/lib/session-search-index.js +188 -0
- package/lib/thread-handoff.js +8 -0
- package/lib/web-server.js +216 -0
- package/package.json +1 -1
- package/plugins/file-sharing/manifest.mjs +10 -0
- package/plugins/file-sharing/methods.mjs +101 -0
- package/plugins/file-sharing/overview.mjs +3 -0
- package/plugins/file-sharing/ownership.mjs +5 -0
- package/plugins/registry.mjs +3 -0
- package/web-ui/app.js +22 -3
- package/web-ui/index.html +4 -2
- package/web-ui/logic.context-window.mjs +15 -0
- package/web-ui/modules/api.mjs +72 -39
- package/web-ui/modules/app.computed.main-tabs.mjs +3 -0
- package/web-ui/modules/app.methods.agents.mjs +17 -0
- package/web-ui/modules/app.methods.claude-config.mjs +2 -0
- package/web-ui/modules/app.methods.codex-config.mjs +9 -0
- package/web-ui/modules/app.methods.config-changes.mjs +124 -0
- package/web-ui/modules/app.methods.install.mjs +23 -3
- package/web-ui/modules/app.methods.kilocode-config.mjs +2 -0
- package/web-ui/modules/app.methods.navigation.mjs +2 -0
- package/web-ui/modules/app.methods.openclaw-persist.mjs +2 -0
- package/web-ui/modules/app.methods.opencode-config.mjs +2 -0
- package/web-ui/modules/app.methods.pi-config.mjs +12 -3
- package/web-ui/modules/app.methods.prompts-editor.mjs +7 -4
- package/web-ui/modules/app.methods.provider-cache.mjs +9 -3
- package/web-ui/modules/app.methods.providers.mjs +6 -0
- package/web-ui/modules/app.methods.session-actions.mjs +2 -2
- package/web-ui/modules/app.methods.startup-claude.mjs +8 -47
- package/web-ui/modules/app.methods.system-prompt.mjs +88 -17
- package/web-ui/modules/app.methods.theme.mjs +4 -3
- package/web-ui/modules/app.methods.web-ui-preferences.mjs +7 -0
- package/web-ui/modules/config-change-actions.mjs +9 -0
- package/web-ui/modules/i18n/locales/en.mjs +254 -8
- package/web-ui/modules/i18n/locales/ja.mjs +254 -8
- package/web-ui/modules/i18n/locales/vi.mjs +254 -8
- package/web-ui/modules/i18n/locales/zh-tw.mjs +254 -8
- package/web-ui/modules/i18n/locales/zh.mjs +254 -8
- package/web-ui/modules/model-test.mjs +82 -0
- package/web-ui/modules/plugins.methods.mjs +3 -1
- package/web-ui/modules/prompt-ecosystem.methods.mjs +4 -3
- package/web-ui/modules/request-deadline.mjs +33 -0
- package/web-ui/modules/routing.mjs +206 -0
- package/web-ui/modules/session-features.mjs +279 -0
- package/web-ui/modules/thread-handoff.mjs +1 -1
- package/web-ui/partials/index/config-changes.html +25 -0
- package/web-ui/partials/index/context-window-reference.html +17 -0
- package/web-ui/partials/index/layout-header.html +40 -42
- package/web-ui/partials/index/modal-openclaw-config.html +0 -2
- package/web-ui/partials/index/modal-skills.html +0 -1
- package/web-ui/partials/index/modals-basic.html +15 -8
- package/web-ui/partials/index/modals-pi-provider.html +0 -1
- package/web-ui/partials/index/panel-config-codex.html +0 -3
- package/web-ui/partials/index/panel-config-openclaw.html +16 -13
- package/web-ui/partials/index/panel-dashboard.html +0 -2
- package/web-ui/partials/index/panel-plugins.html +3 -10
- package/web-ui/partials/index/panel-prompts.html +13 -8
- package/web-ui/partials/index/panel-routing.html +3 -0
- package/web-ui/partials/index/panel-sessions.html +9 -0
- package/web-ui/partials/index/panel-settings.html +12 -13
- package/web-ui/partials/index/panel-trash.html +0 -1
- package/web-ui/partials/index/plugin-file-sharing.html +47 -0
- package/web-ui/partials/index/routing-model-test.html +53 -0
- package/web-ui/partials/index/session-diagnostics.html +32 -0
- package/web-ui/partials/index/session-features.html +107 -0
- package/web-ui/partials/index/thread-handoff.html +6 -3
- package/web-ui/res/web-ui-render.precompiled.js +1689 -246
- package/web-ui/styles/base-theme.css +1 -1
- package/web-ui/styles/config-changes.css +30 -0
- package/web-ui/styles/modals-core.css +6 -5
- package/web-ui/styles/navigation-panels.css +4 -0
- package/web-ui/styles/openclaw-structured.css +205 -189
- package/web-ui/styles/plugins-panel.css +40 -1
- package/web-ui/styles/responsive.css +10 -5
- package/web-ui/styles/routing.css +78 -0
- package/web-ui/styles/session-features.css +258 -0
- package/web-ui/styles/settings-panel.css +30 -0
- package/web-ui/styles/system-prompt.css +8 -7
- package/web-ui/styles/theme-violet-tokens.css +52 -0
- package/web-ui/styles/theme-violet.css +1736 -0
- package/web-ui/styles.css +5 -1
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { randomBytes } = require('crypto');
|
|
7
|
+
const { Transform, pipeline } = require('stream');
|
|
8
|
+
const { promisify } = require('util');
|
|
9
|
+
const { createLanDownloads } = require('./file-sharing-lan');
|
|
10
|
+
|
|
11
|
+
const pipelineFiles = promisify(pipeline);
|
|
12
|
+
const ROUTE = '/api/file-sharing';
|
|
13
|
+
const MAX_MANIFEST = 512 * 1024;
|
|
14
|
+
const MAX_UPLOAD_MS = 10 * 60 * 1000;
|
|
15
|
+
|
|
16
|
+
function uploadError(status, code) {
|
|
17
|
+
return Object.assign(new Error(code), { status, code });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function isSafeRelativeName(name) {
|
|
21
|
+
return typeof name === 'string' && name.length <= 1024 && name.split('/').every(part =>
|
|
22
|
+
part && part !== '.' && part !== '..' && !/[\\:\u0000-\u001f\u007f\u202a-\u202e\u2066-\u2069\uD800-\uDFFF]/u.test(part));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function parseManifest(manifestBytes, expectedSize) {
|
|
26
|
+
let manifest;
|
|
27
|
+
try { manifest = JSON.parse(manifestBytes.toString('utf8')); }
|
|
28
|
+
catch (_) { throw uploadError(400, 'invalid'); }
|
|
29
|
+
const { folder, files } = manifest || {};
|
|
30
|
+
if (!Array.isArray(files) || !files.length) throw uploadError(400, 'emptyFolder');
|
|
31
|
+
if (folder !== '' && (!isSafeRelativeName(folder) || folder.includes('/'))) throw uploadError(400, 'invalid');
|
|
32
|
+
const names = new Set();
|
|
33
|
+
let offset = 0;
|
|
34
|
+
const entries = files.map(file => {
|
|
35
|
+
const { name, size } = file || {};
|
|
36
|
+
if (!isSafeRelativeName(name) || names.has(name)
|
|
37
|
+
|| (folder ? !name.startsWith(`${folder}/`) : name.includes('/'))
|
|
38
|
+
|| !Number.isSafeInteger(size) || size < 0) throw uploadError(400, 'invalid');
|
|
39
|
+
if (size > expectedSize - offset) throw uploadError(400, 'invalid');
|
|
40
|
+
names.add(name);
|
|
41
|
+
const entry = { name, size, offset };
|
|
42
|
+
offset += size;
|
|
43
|
+
return entry;
|
|
44
|
+
});
|
|
45
|
+
if (offset !== expectedSize) throw uploadError(400, 'invalid');
|
|
46
|
+
return { folder, entries };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function createUploadStream(length, acceptManifest) {
|
|
50
|
+
const prefix = Buffer.alloc(4);
|
|
51
|
+
let prefixRead = 0;
|
|
52
|
+
let manifestBytes;
|
|
53
|
+
let manifestRead = 0;
|
|
54
|
+
let received = 0;
|
|
55
|
+
return new Transform({
|
|
56
|
+
transform(chunk, encoding, callback) {
|
|
57
|
+
try {
|
|
58
|
+
received += chunk.length;
|
|
59
|
+
if (received > length) throw uploadError(400, 'invalid');
|
|
60
|
+
if (prefixRead < prefix.length) {
|
|
61
|
+
const count = chunk.copy(prefix, prefixRead);
|
|
62
|
+
prefixRead += count;
|
|
63
|
+
chunk = chunk.subarray(count);
|
|
64
|
+
if (prefixRead < prefix.length) return callback();
|
|
65
|
+
const manifestSize = prefix.readUInt32BE();
|
|
66
|
+
if (!manifestSize || manifestSize > MAX_MANIFEST || manifestSize > length - prefix.length) {
|
|
67
|
+
throw uploadError(400, 'invalid');
|
|
68
|
+
}
|
|
69
|
+
manifestBytes = Buffer.alloc(manifestSize);
|
|
70
|
+
}
|
|
71
|
+
if (manifestRead < manifestBytes.length) {
|
|
72
|
+
const count = chunk.copy(manifestBytes, manifestRead);
|
|
73
|
+
manifestRead += count;
|
|
74
|
+
chunk = chunk.subarray(count);
|
|
75
|
+
if (manifestRead < manifestBytes.length) return callback();
|
|
76
|
+
acceptManifest(parseManifest(manifestBytes, length - prefix.length - manifestBytes.length));
|
|
77
|
+
}
|
|
78
|
+
callback(null, chunk);
|
|
79
|
+
} catch (error) { callback(error); }
|
|
80
|
+
},
|
|
81
|
+
flush(callback) { callback(received === length ? null : uploadError(400, 'invalid')); }
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function sharingJson(res, status, payload, headers = {}) {
|
|
86
|
+
res.writeHead(status, {
|
|
87
|
+
'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', ...headers
|
|
88
|
+
});
|
|
89
|
+
res.end(JSON.stringify(payload));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function createFileSharingRoutes() {
|
|
93
|
+
// User paths are display metadata only. Disk names come from server-generated IDs.
|
|
94
|
+
const batches = new Map();
|
|
95
|
+
let root;
|
|
96
|
+
let activeUpload;
|
|
97
|
+
const diskPath = id => path.join(root, id);
|
|
98
|
+
const summary = ({ id, folder, entries }) => ({ id, folder, files: entries.map(({ name, size }) => ({ name, size })) });
|
|
99
|
+
|
|
100
|
+
async function upload(req, res) {
|
|
101
|
+
if (req.headers['content-type'] !== 'application/octet-stream') throw uploadError(415, 'invalid');
|
|
102
|
+
const length = Number(req.headers['content-length']);
|
|
103
|
+
if (!Number.isSafeInteger(length) || length <= 4) throw uploadError(400, 'invalid');
|
|
104
|
+
const id = randomBytes(16).toString('hex');
|
|
105
|
+
let manifest;
|
|
106
|
+
let committed = false;
|
|
107
|
+
let blobPath;
|
|
108
|
+
try {
|
|
109
|
+
if (!root) root = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'codexmate-file-sharing-'));
|
|
110
|
+
blobPath = diskPath(id);
|
|
111
|
+
const stream = createUploadStream(length, parsed => {
|
|
112
|
+
manifest = parsed;
|
|
113
|
+
});
|
|
114
|
+
const interruptUpload = () => stream.destroy(uploadError(400, 'invalid'));
|
|
115
|
+
const closeUpload = () => { if (!req.complete) interruptUpload(); };
|
|
116
|
+
const timeout = setTimeout(interruptUpload, MAX_UPLOAD_MS).unref();
|
|
117
|
+
req.once('close', closeUpload);
|
|
118
|
+
try {
|
|
119
|
+
if (req.destroyed) throw uploadError(400, 'invalid');
|
|
120
|
+
await pipelineFiles(req.pipe(stream), fs.createWriteStream(blobPath, { flags: 'wx', mode: 0o600 }));
|
|
121
|
+
} finally {
|
|
122
|
+
clearTimeout(timeout);
|
|
123
|
+
req.removeListener('close', closeUpload);
|
|
124
|
+
}
|
|
125
|
+
batches.set(id, { id, ...manifest });
|
|
126
|
+
committed = true;
|
|
127
|
+
sharingJson(res, 201, { batch: summary(batches.get(id)) });
|
|
128
|
+
} finally {
|
|
129
|
+
if (blobPath && !committed) await fs.promises.rm(blobPath, { force: true });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const lanDownloads = createLanDownloads((req, res, id, index) => sendFile(req, res, batches.get(id), index));
|
|
134
|
+
|
|
135
|
+
async function serve(req, res, requestPath) {
|
|
136
|
+
if (requestPath === ROUTE && req.method === 'GET') return sharingJson(res, 200, { batches: [...batches.values()].map(summary) });
|
|
137
|
+
if (requestPath === ROUTE && req.method === 'POST') {
|
|
138
|
+
if (activeUpload) throw uploadError(409, 'busy');
|
|
139
|
+
activeUpload = upload(req, res);
|
|
140
|
+
try { return await activeUpload; }
|
|
141
|
+
finally { activeUpload = null; }
|
|
142
|
+
}
|
|
143
|
+
const match = /^\/api\/file-sharing\/([a-f0-9]{32})(?:\/(\d+)(\/link)?)?$/.exec(requestPath);
|
|
144
|
+
const batch = match && batches.get(match[1]);
|
|
145
|
+
if (!batch) throw uploadError(404, 'notFound');
|
|
146
|
+
if (req.method === 'DELETE' && match[2] === undefined) {
|
|
147
|
+
await fs.promises.rm(diskPath(batch.id), { force: true });
|
|
148
|
+
batches.delete(batch.id);
|
|
149
|
+
return sharingJson(res, 200, { removed: true });
|
|
150
|
+
}
|
|
151
|
+
const index = match[2] === undefined ? -1 : Number(match[2]);
|
|
152
|
+
if (match[3]) {
|
|
153
|
+
if (req.method !== 'POST') throw uploadError(405, 'invalid');
|
|
154
|
+
if (!batch.entries[index]) throw uploadError(404, 'notFound');
|
|
155
|
+
const link = await lanDownloads.issue(batch.id, index, req.socket.localAddress);
|
|
156
|
+
if (!link) throw uploadError(503, 'lanUnavailable');
|
|
157
|
+
if (!batches.has(batch.id)) throw uploadError(404, 'notFound');
|
|
158
|
+
return sharingJson(res, 201, link);
|
|
159
|
+
}
|
|
160
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') throw uploadError(405, 'invalid');
|
|
161
|
+
return sendFile(req, res, batch, index);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function sendFile(req, res, batch, index) {
|
|
165
|
+
const file = batch && batch.entries[index];
|
|
166
|
+
if (!file) throw uploadError(404, 'notFound');
|
|
167
|
+
const filename = file.name.split('/').pop();
|
|
168
|
+
const encoded = encodeURIComponent(filename).replace(/['()*]/g, char => `%${char.charCodeAt(0).toString(16)}`);
|
|
169
|
+
res.writeHead(200, {
|
|
170
|
+
'Content-Type': 'application/octet-stream', 'Content-Length': file.size,
|
|
171
|
+
'Content-Disposition': `attachment; filename*=UTF-8''${encoded}`,
|
|
172
|
+
'Cache-Control': 'private, no-store', 'Referrer-Policy': 'no-referrer',
|
|
173
|
+
'Content-Security-Policy': "sandbox; default-src 'none'", 'X-Content-Type-Options': 'nosniff'
|
|
174
|
+
});
|
|
175
|
+
if (!file.size || req.method === 'HEAD') return res.end();
|
|
176
|
+
await pipelineFiles(fs.createReadStream(diskPath(batch.id), { start: file.offset, end: file.offset + file.size - 1 }), res);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
match(requestPath) { return requestPath === ROUTE || requestPath.startsWith(`${ROUTE}/`); },
|
|
181
|
+
serve(req, res, requestPath) {
|
|
182
|
+
void serve(req, res, requestPath).catch(error => {
|
|
183
|
+
if (res.headersSent || res.destroyed) return;
|
|
184
|
+
sharingJson(res, error.status || 500, { error: error.status ? error.code : 'failed' },
|
|
185
|
+
req.method === 'POST' ? { Connection: 'close' } : {});
|
|
186
|
+
});
|
|
187
|
+
},
|
|
188
|
+
async dispose() {
|
|
189
|
+
// The server has stopped receiving requests. Wait for any interrupted write to release its file handle.
|
|
190
|
+
await Promise.allSettled([activeUpload, lanDownloads.close()]);
|
|
191
|
+
if (root) await fs.promises.rm(root, { recursive: true, force: true });
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
module.exports = { createFileSharingRoutes };
|
package/lib/handoff-mcp.js
CHANGED
|
@@ -35,7 +35,7 @@ function discoverServers(options = {}, warnings = []) {
|
|
|
35
35
|
const disabled = new Set([...(config.disabledMcpServers || []), ...(project.disabledMcpServers || [])]);
|
|
36
36
|
for (const [name, entry] of Object.entries(entries)) {
|
|
37
37
|
if (!entry || entry.disabled || entry.enabled === false || disabled.has(name)) continue;
|
|
38
|
-
if (!SHARED_SERVER.test([name, entry.command, ...(entry.args || []), entry.url].join(' '))) continue;
|
|
38
|
+
if (!options.allServers && !SHARED_SERVER.test([name, entry.command, ...(entry.args || []), entry.url].join(' '))) continue;
|
|
39
39
|
if (!servers.some(server => server.name === name)) servers.push({ ...entry, name, cwd: entry.cwd || cwd });
|
|
40
40
|
}
|
|
41
41
|
}
|
|
@@ -279,4 +279,20 @@ async function deliver(handoff, options = {}) {
|
|
|
279
279
|
}
|
|
280
280
|
}
|
|
281
281
|
|
|
282
|
-
|
|
282
|
+
async function probeServer(name, options = {}) {
|
|
283
|
+
const server = discoverServers({ ...options, allServers: true }).find((entry) => entry.name === name);
|
|
284
|
+
if (!server) throw new Error('diagnostic-input-invalid');
|
|
285
|
+
const timeout = Math.min(TIMEOUT_MS, options.timeoutMs || TIMEOUT_MS);
|
|
286
|
+
const connection = server.url ? openHttp(server, timeout) : openStdio(server, timeout);
|
|
287
|
+
try {
|
|
288
|
+
if (options.isCancelled?.()) throw new Error('diagnostic-cancelled');
|
|
289
|
+
const initialized = await connection.request('initialize', { protocolVersion: '2025-11-25',
|
|
290
|
+
capabilities: {}, clientInfo: { name: 'codexmate-doctor', version: '1' } });
|
|
291
|
+
await connection.request('notifications/initialized', {}, true);
|
|
292
|
+
if (options.isCancelled?.()) throw new Error('diagnostic-cancelled');
|
|
293
|
+
const listing = await connection.request('tools/list', {});
|
|
294
|
+
return { ok: true, name, protocolVersion: initialized.protocolVersion,
|
|
295
|
+
tools: (listing.tools || []).map((tool) => tool.name) };
|
|
296
|
+
} finally { await connection.close(); }
|
|
297
|
+
}
|
|
298
|
+
module.exports = { deliver, discoverServers, nativeWrite, probeServer };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const crypto = require('crypto');
|
|
5
|
+
const MAX_STORE_BYTES = 5 * 1024 * 1024;
|
|
6
|
+
const digest = (text) => crypto.createHash('sha256').update(text).digest('hex');
|
|
7
|
+
|
|
8
|
+
function createLocalFeatureStore(filePath, initial) {
|
|
9
|
+
function read() {
|
|
10
|
+
try {
|
|
11
|
+
const stat = fs.lstatSync(filePath);
|
|
12
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_STORE_BYTES) throw new Error('feature-store-invalid');
|
|
13
|
+
const text = fs.readFileSync(filePath, 'utf8');
|
|
14
|
+
const value = JSON.parse(text);
|
|
15
|
+
if (value.version !== initial.version) throw new Error('feature-store-invalid');
|
|
16
|
+
return { value, revision: digest(text) };
|
|
17
|
+
} catch (error) {
|
|
18
|
+
if (error.code !== 'ENOENT') throw error;
|
|
19
|
+
return { value: JSON.parse(JSON.stringify(initial)), revision: '' };
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function write(value, revision) {
|
|
23
|
+
if (read().revision !== revision) throw new Error('feature-store-conflict');
|
|
24
|
+
const text = JSON.stringify(value) + '\n';
|
|
25
|
+
if (Buffer.byteLength(text) > MAX_STORE_BYTES) throw new Error('feature-store-full');
|
|
26
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
|
|
27
|
+
const temporary = `${filePath}.${crypto.randomBytes(12).toString('hex')}.tmp`;
|
|
28
|
+
try {
|
|
29
|
+
fs.writeFileSync(temporary, text, { mode: 0o600, flag: 'wx' });
|
|
30
|
+
if (read().revision !== revision) throw new Error('feature-store-conflict');
|
|
31
|
+
fs.renameSync(temporary, filePath);
|
|
32
|
+
} finally {
|
|
33
|
+
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
|
|
34
|
+
}
|
|
35
|
+
return { value, revision: digest(text) };
|
|
36
|
+
}
|
|
37
|
+
return { read, write };
|
|
38
|
+
}
|
|
39
|
+
module.exports = { createLocalFeatureStore, digest };
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const os = require('os');
|
|
4
|
+
const { execFileSync } = require('child_process');
|
|
5
|
+
const { version: appVersion } = require('../package.json');
|
|
6
|
+
|
|
7
|
+
const CLIENT_VERSION_TIMEOUT_MS = 1500;
|
|
8
|
+
const CLIENT_HEADER_CACHE = new Map();
|
|
9
|
+
const SDK_NAMES = { 'anthropic-messages': '@anthropic-ai/sdk' };
|
|
10
|
+
const SDK_CLIENT_NAMES = { '@anthropic-ai/sdk': 'Anthropic', openai: 'OpenAI' };
|
|
11
|
+
const SDK_OS_NAMES = { android: 'Android', darwin: 'MacOS', win32: 'Windows', linux: 'Linux' };
|
|
12
|
+
const SDK_ARCH_NAMES = { x32: 'x32', x64: 'x64', arm: 'arm', arm64: 'arm64' };
|
|
13
|
+
|
|
14
|
+
function sdkVersion(packageName) {
|
|
15
|
+
const roots = [process.cwd(), path.resolve(path.dirname(process.execPath), '../lib/node_modules')];
|
|
16
|
+
for (const directory of (process.env.PATH || '').split(path.delimiter)) {
|
|
17
|
+
const executable = path.join(directory, process.platform === 'win32' ? 'pi.cmd' : 'pi');
|
|
18
|
+
if (fs.existsSync(executable)) roots.push(path.dirname(fs.realpathSync(executable)));
|
|
19
|
+
}
|
|
20
|
+
try {
|
|
21
|
+
const metadata = require.resolve(`${packageName}/package.json`, { paths: roots });
|
|
22
|
+
return JSON.parse(fs.readFileSync(metadata, 'utf8')).version;
|
|
23
|
+
} catch (error) {
|
|
24
|
+
if (error.code !== 'MODULE_NOT_FOUND' && error.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') throw error;
|
|
25
|
+
return '';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function modelTestClientHeaders(target, api) {
|
|
30
|
+
const cacheKey = `${target}:${api}`;
|
|
31
|
+
if (CLIENT_HEADER_CACHE.has(cacheKey)) return CLIENT_HEADER_CACHE.get(cacheKey);
|
|
32
|
+
const fallback = `codexmate/${appVersion} (${target} API test)`;
|
|
33
|
+
let headers = { 'user-agent': fallback };
|
|
34
|
+
if (target === 'codex') {
|
|
35
|
+
let version = '';
|
|
36
|
+
try {
|
|
37
|
+
const output = execFileSync('codex', ['--version'], { encoding: 'utf8', timeout: CLIENT_VERSION_TIMEOUT_MS, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
38
|
+
version = output.trim().match(/^codex-cli\s+(\S+)$/)?.[1] || '';
|
|
39
|
+
} catch (error) {
|
|
40
|
+
// Version probing is optional; never invent an installed client version.
|
|
41
|
+
if (!error.code && !Number.isInteger(error.status)) throw error;
|
|
42
|
+
}
|
|
43
|
+
const platform = `${os.type()} ${os.release()}; ${os.arch()}`.replace(/[^\x20-\x7e]/g, '_');
|
|
44
|
+
headers = { 'user-agent': version ? `codex_cli_rs/${version} (${platform})` : fallback, originator: 'codex_cli_rs' };
|
|
45
|
+
} else {
|
|
46
|
+
const packageName = SDK_NAMES[api] || 'openai';
|
|
47
|
+
const version = sdkVersion(packageName);
|
|
48
|
+
if (version) headers = {
|
|
49
|
+
'user-agent': `${SDK_CLIENT_NAMES[packageName]}/JS ${version}`,
|
|
50
|
+
'x-stainless-lang': 'js', 'x-stainless-package-version': version,
|
|
51
|
+
'x-stainless-runtime': 'node', 'x-stainless-runtime-version': process.version,
|
|
52
|
+
'x-stainless-os': SDK_OS_NAMES[process.platform] || `other:${process.platform}`,
|
|
53
|
+
'x-stainless-arch': SDK_ARCH_NAMES[process.arch] || `other:${process.arch}`,
|
|
54
|
+
'x-stainless-retry-count': '0'
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
CLIENT_HEADER_CACHE.set(cacheKey, headers);
|
|
58
|
+
return headers;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
module.exports = { modelTestClientHeaders };
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
const http = require('http');
|
|
2
|
+
const https = require('https');
|
|
3
|
+
const { modelTestClientHeaders } = require('./model-test-client');
|
|
4
|
+
const { buildApiProbeUrlCandidates, extractModelResponseText } = require('./cli-models-utils');
|
|
5
|
+
|
|
6
|
+
const MAX_PROMPT_LENGTH = 8000;
|
|
7
|
+
const MAX_RESPONSE_BYTES = 256 * 1024;
|
|
8
|
+
const MAX_OUTPUT_TOKENS = 2048;
|
|
9
|
+
const SUPPORTED_APIS = new Set(['responses', 'chat_completions', 'completions', 'anthropic-messages']);
|
|
10
|
+
const PI_NON_STANDARD_PROVIDERS = new Set(['cerebras', 'xai', 'zai', 'opencode']);
|
|
11
|
+
|
|
12
|
+
function buildTestRequest(provider, model, prompt) {
|
|
13
|
+
const api = provider.api;
|
|
14
|
+
if (!SUPPORTED_APIS.has(api)) throw new Error('此配置的接口暂不支持真实测试');
|
|
15
|
+
const paths = { responses: 'responses', chat_completions: 'chat/completions', completions: 'completions', 'anthropic-messages': 'messages' };
|
|
16
|
+
const url = buildApiProbeUrlCandidates(provider.baseUrl, paths[api])[0];
|
|
17
|
+
const key = (provider.apiKey || '').replace(/^Bearer\s+/i, '');
|
|
18
|
+
const authentication = api === 'anthropic-messages'
|
|
19
|
+
? { 'anthropic-version': '2023-06-01', ...(key ? { 'x-api-key': key } : {}) }
|
|
20
|
+
: key ? { authorization: `Bearer ${key}` } : {};
|
|
21
|
+
const headers = Object.fromEntries([
|
|
22
|
+
...Object.entries(provider.clientHeaders || {}), ...Object.entries(authentication),
|
|
23
|
+
...Object.entries(provider.headers || {})
|
|
24
|
+
].map(([name, value]) => [name.toLowerCase(), value]));
|
|
25
|
+
const maxTokens = Number.isFinite(provider.maxTokens) && provider.maxTokens > 0
|
|
26
|
+
? Math.min(provider.maxTokens, MAX_OUTPUT_TOKENS) : MAX_OUTPUT_TOKENS;
|
|
27
|
+
let body;
|
|
28
|
+
if (api === 'responses') {
|
|
29
|
+
body = { model, input: [{ role: 'user', content: [{ type: 'input_text', text: prompt }] }],
|
|
30
|
+
store: false, max_output_tokens: maxTokens, stream: false };
|
|
31
|
+
if (provider.target === 'codex') {
|
|
32
|
+
body.instructions = '';
|
|
33
|
+
body.parallel_tool_calls = false;
|
|
34
|
+
if (provider.reasoningEffort) body.reasoning = { effort: provider.reasoningEffort };
|
|
35
|
+
if (provider.reasoningSummary && provider.reasoningSummary !== 'none') {
|
|
36
|
+
body.reasoning = { ...body.reasoning, summary: provider.reasoningSummary };
|
|
37
|
+
}
|
|
38
|
+
if (provider.verbosity) body.text = { verbosity: provider.verbosity };
|
|
39
|
+
}
|
|
40
|
+
} else if (api === 'completions') {
|
|
41
|
+
body = { model, prompt, max_tokens: maxTokens, stream: false };
|
|
42
|
+
} else {
|
|
43
|
+
body = { model, messages: [{ role: 'user', content: prompt }], stream: false };
|
|
44
|
+
const isPiChat = provider.target === 'pi' && api === 'chat_completions';
|
|
45
|
+
const maxTokensField = isPiChat && provider.compat?.maxTokensField !== 'max_tokens' && !url.includes('chutes.ai')
|
|
46
|
+
? 'max_completion_tokens' : 'max_tokens';
|
|
47
|
+
body[maxTokensField] = maxTokens;
|
|
48
|
+
const isNonStandard = PI_NON_STANDARD_PROVIDERS.has(provider.name) || /cerebras\.ai|api\.x\.ai|chutes\.ai|deepseek\.com|api\.z\.ai|opencode\.ai/.test(url);
|
|
49
|
+
if (isPiChat && (provider.compat?.supportsStore ?? !isNonStandard)) body.store = false;
|
|
50
|
+
}
|
|
51
|
+
return { url, headers, body };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function requestModel({ url, headers, body }, { timeoutMs = 0, maxBytes = MAX_RESPONSE_BYTES } = {}) {
|
|
55
|
+
return new Promise((resolve, reject) => {
|
|
56
|
+
const parsed = new URL(url);
|
|
57
|
+
if (!['http:', 'https:'].includes(parsed.protocol)) throw new Error('供应商地址必须使用 HTTP 或 HTTPS');
|
|
58
|
+
const payload = JSON.stringify(body);
|
|
59
|
+
const transport = parsed.protocol === 'https:' ? https : http;
|
|
60
|
+
// A single request, no probe fallback or retry: a test can incur usage charges.
|
|
61
|
+
const request = transport.request(parsed, { method: 'POST', headers: {
|
|
62
|
+
...headers, 'Content-Type': 'application/json', Accept: 'application/json', 'Content-Length': Buffer.byteLength(payload)
|
|
63
|
+
} }, response => {
|
|
64
|
+
const chunks = [];
|
|
65
|
+
let size = 0;
|
|
66
|
+
response.on('data', chunk => {
|
|
67
|
+
size += chunk.length;
|
|
68
|
+
if (size > maxBytes) {
|
|
69
|
+
reject(new Error('回复超过 256 KiB,测试已停止'));
|
|
70
|
+
response.destroy(); request.destroy(); return;
|
|
71
|
+
}
|
|
72
|
+
chunks.push(chunk);
|
|
73
|
+
});
|
|
74
|
+
response.on('error', reject);
|
|
75
|
+
response.on('aborted', () => reject(new Error('上游回复中断')));
|
|
76
|
+
response.on('end', () => resolve({ status: response.statusCode, body: Buffer.concat(chunks).toString('utf8') }));
|
|
77
|
+
});
|
|
78
|
+
if (timeoutMs > 0) {
|
|
79
|
+
const timer = setTimeout(() => {
|
|
80
|
+
reject(new Error('测试等待超时'));
|
|
81
|
+
request.destroy();
|
|
82
|
+
}, timeoutMs);
|
|
83
|
+
request.on('close', () => clearTimeout(timer));
|
|
84
|
+
}
|
|
85
|
+
request.on('error', error => reject(new Error(`连接失败:${error.code || 'network-error'}`)));
|
|
86
|
+
request.end(payload);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function createModelTestService({ providers, request = requestModel, clientHeaders = modelTestClientHeaders }) {
|
|
91
|
+
function catalog() {
|
|
92
|
+
return Object.fromEntries(['codex', 'pi'].map(target => [target, providers(target).map(provider => ({
|
|
93
|
+
name: provider.name, models: provider.models, supported: SUPPORTED_APIS.has(provider.api)
|
|
94
|
+
}))]));
|
|
95
|
+
}
|
|
96
|
+
async function run(params = {}) {
|
|
97
|
+
const started = Date.now();
|
|
98
|
+
const identity = { target: params.target, provider: params.provider, model: params.model };
|
|
99
|
+
const elapsed = () => Date.now() - started;
|
|
100
|
+
try {
|
|
101
|
+
const { target, provider: name, model, prompt } = params;
|
|
102
|
+
if (!['codex', 'pi'].includes(target)) throw new Error('测试仅支持 Codex 和 Pi');
|
|
103
|
+
if (typeof prompt !== 'string' || !prompt.trim() || prompt.length > MAX_PROMPT_LENGTH) throw new Error('输入 1–8000 字符的测试内容');
|
|
104
|
+
const provider = providers(target).find(entry => entry.name === name);
|
|
105
|
+
if (!provider || !provider.models.includes(model)) throw new Error('请选择已有供应商与模型,刷新后重试');
|
|
106
|
+
if (provider.error) throw new Error(provider.error);
|
|
107
|
+
const selected = { ...provider, ...provider.modelOptions?.[model], target };
|
|
108
|
+
selected.clientHeaders = clientHeaders(target, selected.api);
|
|
109
|
+
const result = await request(buildTestRequest(selected, model, prompt.trim()));
|
|
110
|
+
if (result.status < 200 || result.status >= 300) return { ...identity, ok: false, status: result.status, durationMs: elapsed(), error: `HTTP ${result.status}` };
|
|
111
|
+
let payload;
|
|
112
|
+
try { payload = JSON.parse(result.body); } catch (_) { throw new Error('上游未返回有效 JSON 回复'); }
|
|
113
|
+
if (payload.error) throw new Error('上游返回错误,未生成回复');
|
|
114
|
+
const text = extractModelResponseText(payload);
|
|
115
|
+
if (!text) throw new Error('上游未返回可显示的回复内容');
|
|
116
|
+
const incomplete = payload.status === 'incomplete' || payload.choices?.[0]?.finish_reason === 'length' || payload.stop_reason === 'max_tokens';
|
|
117
|
+
return { ...identity, ok: true, status: result.status, durationMs: elapsed(), text, incomplete,
|
|
118
|
+
responseModel: typeof payload.model === 'string' ? payload.model : model };
|
|
119
|
+
} catch (error) {
|
|
120
|
+
return { ...identity, ok: false, durationMs: elapsed(), error: error.message };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return { catalog, run };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
module.exports = { createModelTestService, buildTestRequest, requestModel };
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const crypto = require('crypto');
|
|
5
|
+
|
|
6
|
+
const OPENAI_CHAT_TARGET = 'openai-chat';
|
|
7
|
+
const TARGETS = new Set(['codex', 'claude', OPENAI_CHAT_TARGET]);
|
|
8
|
+
const STRATEGIES = new Set(['order', 'rotate']);
|
|
9
|
+
const MAX_GROUPS = 64;
|
|
10
|
+
const MAX_MEMBERS = 16;
|
|
11
|
+
const MAX_NAME_LENGTH = 128;
|
|
12
|
+
const MAX_MODEL_LENGTH = 256;
|
|
13
|
+
const VERSION = 1;
|
|
14
|
+
const MAX_STORAGE_BYTES = 2 * 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
function routeError(code, message) {
|
|
17
|
+
const error = new Error(message);
|
|
18
|
+
error.code = code;
|
|
19
|
+
return error;
|
|
20
|
+
}
|
|
21
|
+
function revisionOf(source) {
|
|
22
|
+
return crypto.createHash('sha256').update(source).digest('hex');
|
|
23
|
+
}
|
|
24
|
+
function validText(value, limit) {
|
|
25
|
+
return typeof value === 'string' && value.trim() && value.trim().length <= limit;
|
|
26
|
+
}
|
|
27
|
+
function validateGroup(group) {
|
|
28
|
+
if (!group || !validText(group.name, MAX_NAME_LENGTH) || !TARGETS.has(group.target) || !STRATEGIES.has(group.strategy)) {
|
|
29
|
+
throw routeError('routing-invalid', '路由组名称、目标或策略无效');
|
|
30
|
+
}
|
|
31
|
+
if (!Array.isArray(group.members) || !group.members.length || group.members.length > MAX_MEMBERS) {
|
|
32
|
+
throw routeError('routing-invalid', '每组需要 1–16 个成员');
|
|
33
|
+
}
|
|
34
|
+
const seen = new Set();
|
|
35
|
+
const members = group.members.map(member => {
|
|
36
|
+
if (!member || !validText(member.provider, MAX_NAME_LENGTH) || !validText(member.model, MAX_MODEL_LENGTH)) {
|
|
37
|
+
throw routeError('routing-invalid', '成员必须指定供应商与模型');
|
|
38
|
+
}
|
|
39
|
+
const normalized = { provider: member.provider.trim(), model: member.model.trim() };
|
|
40
|
+
const key = JSON.stringify(normalized);
|
|
41
|
+
if (seen.has(key)) throw routeError('routing-invalid', '成员不能重复');
|
|
42
|
+
seen.add(key);
|
|
43
|
+
return normalized;
|
|
44
|
+
});
|
|
45
|
+
return { id: group.id, name: group.name.trim(), target: group.target, strategy: group.strategy, members };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function createRoutingGroups({ filePath, assertAllowed, catalog }) {
|
|
49
|
+
function read() {
|
|
50
|
+
if (fs.existsSync(filePath) && fs.statSync(filePath).size > MAX_STORAGE_BYTES) throw routeError('routing-corrupt', '路由组文件超过 2 MiB');
|
|
51
|
+
const source = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : '';
|
|
52
|
+
const state = source ? JSON.parse(source) : { version: VERSION, groups: [], bindings: { codex: '', claude: '' } };
|
|
53
|
+
if (!state || state.version !== VERSION || !Array.isArray(state.groups) || !state.bindings || state.groups.length > MAX_GROUPS) {
|
|
54
|
+
throw routeError('routing-corrupt', '路由组文件格式无效');
|
|
55
|
+
}
|
|
56
|
+
if (state.bindings[OPENAI_CHAT_TARGET] === undefined) state.bindings[OPENAI_CHAT_TARGET] = '';
|
|
57
|
+
const ids = new Set();
|
|
58
|
+
state.groups = state.groups.map(group => {
|
|
59
|
+
if (!validText(group.id, MAX_NAME_LENGTH) || ids.has(group.id)) throw routeError('routing-corrupt', '路由组标识无效');
|
|
60
|
+
ids.add(group.id);
|
|
61
|
+
return validateGroup(group);
|
|
62
|
+
});
|
|
63
|
+
for (const target of TARGETS) {
|
|
64
|
+
const id = state.bindings[target];
|
|
65
|
+
if (typeof id !== 'string' || (id && !state.groups.some(group => group.id === id && group.target === target))) {
|
|
66
|
+
throw routeError('routing-corrupt', '路由绑定无效');
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return { version: VERSION, groups: state.groups, bindings: Object.fromEntries([...TARGETS].map(target => [target, state.bindings[target]])), revision: revisionOf(source) };
|
|
70
|
+
}
|
|
71
|
+
function write(state, expectedRevision) {
|
|
72
|
+
if (read().revision !== expectedRevision) throw routeError('routing-conflict', '路由组已被修改,请刷新后重试');
|
|
73
|
+
const source = JSON.stringify({ version: VERSION, groups: state.groups, bindings: state.bindings }, null, 2) + '\n';
|
|
74
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
75
|
+
const temporary = filePath + '.' + crypto.randomBytes(8).toString('hex') + '.tmp';
|
|
76
|
+
try {
|
|
77
|
+
fs.writeFileSync(temporary, source, { mode: 0o600, flag: 'wx' });
|
|
78
|
+
fs.renameSync(temporary, filePath);
|
|
79
|
+
} finally {
|
|
80
|
+
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
|
|
81
|
+
}
|
|
82
|
+
return { ...state, revision: revisionOf(source) };
|
|
83
|
+
}
|
|
84
|
+
function checkRevision(state, revision) {
|
|
85
|
+
if (revision !== state.revision) throw routeError('routing-conflict', '路由组已被修改,请刷新后重试');
|
|
86
|
+
}
|
|
87
|
+
function checkMembers(group) {
|
|
88
|
+
const names = new Set(catalog(group.target).map(entry => entry.name));
|
|
89
|
+
if (group.members.some(member => !names.has(member.provider))) {
|
|
90
|
+
throw routeError('routing-provider-missing', '成员供应商不存在或已排除');
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function save(params) {
|
|
94
|
+
const state = read();
|
|
95
|
+
checkRevision(state, params.revision);
|
|
96
|
+
const previous = params.id ? state.groups.find(group => group.id === params.id) : null;
|
|
97
|
+
if (params.id && !previous) throw routeError('routing-not-found', '路由组不存在');
|
|
98
|
+
const group = validateGroup({ ...params, id: previous ? previous.id : crypto.randomBytes(12).toString('hex') });
|
|
99
|
+
if (previous && previous.target !== group.target) throw routeError('routing-invalid', '已有路由组不能更换目标工具');
|
|
100
|
+
assertAllowed(group.target);
|
|
101
|
+
checkMembers(group);
|
|
102
|
+
if (state.groups.some(item => item.id !== group.id && item.target === group.target && item.name === group.name)) {
|
|
103
|
+
throw routeError('routing-invalid', '同一工具的路由组名称不能重复');
|
|
104
|
+
}
|
|
105
|
+
if (!previous && state.groups.length >= MAX_GROUPS) throw routeError('routing-invalid', '最多保存 64 个路由组');
|
|
106
|
+
state.groups = previous ? state.groups.map(item => item.id === group.id ? group : item) : [...state.groups, group];
|
|
107
|
+
return write(state, params.revision);
|
|
108
|
+
}
|
|
109
|
+
function remove(params) {
|
|
110
|
+
const state = read();
|
|
111
|
+
checkRevision(state, params.revision);
|
|
112
|
+
const group = state.groups.find(item => item.id === params.id);
|
|
113
|
+
if (!group) throw routeError('routing-not-found', '路由组不存在');
|
|
114
|
+
assertAllowed(group.target);
|
|
115
|
+
if (state.bindings[group.target] === group.id) throw routeError('routing-in-use', '请先解除绑定再删除路由组');
|
|
116
|
+
state.groups = state.groups.filter(item => item.id !== group.id);
|
|
117
|
+
return write(state, params.revision);
|
|
118
|
+
}
|
|
119
|
+
function bind(params) {
|
|
120
|
+
const state = read();
|
|
121
|
+
checkRevision(state, params.revision);
|
|
122
|
+
if (!TARGETS.has(params.target) || typeof params.id !== 'string') throw routeError('routing-invalid', '路由绑定参数无效');
|
|
123
|
+
assertAllowed(params.target);
|
|
124
|
+
if (params.id) {
|
|
125
|
+
const group = state.groups.find(item => item.id === params.id && item.target === params.target);
|
|
126
|
+
if (!group) throw routeError('routing-not-found', '路由组不存在或工具不匹配');
|
|
127
|
+
checkMembers(group);
|
|
128
|
+
}
|
|
129
|
+
state.bindings[params.target] = params.id;
|
|
130
|
+
return write(state, params.revision);
|
|
131
|
+
}
|
|
132
|
+
function resolve(target) {
|
|
133
|
+
const state = read();
|
|
134
|
+
const id = state.bindings[target];
|
|
135
|
+
if (!id) return null;
|
|
136
|
+
const group = state.groups.find(item => item.id === id && item.target === target);
|
|
137
|
+
const entries = catalog(target);
|
|
138
|
+
const members = group.members.map(member => {
|
|
139
|
+
const entry = entries.find(item => item.name === member.provider);
|
|
140
|
+
return entry ? { ...entry, model: member.model } : null;
|
|
141
|
+
}).filter(Boolean);
|
|
142
|
+
if (!members.length) throw routeError('routing-no-upstream', '绑定路由组没有可用成员,请检查供应商与排除设置');
|
|
143
|
+
return { ...group, members };
|
|
144
|
+
}
|
|
145
|
+
return { read, save, remove, bind, resolve };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function createRoutingScheduler() {
|
|
149
|
+
const positions = new Map();
|
|
150
|
+
return group => {
|
|
151
|
+
if (group.strategy === 'order') return group.members;
|
|
152
|
+
const signature = JSON.stringify([group.strategy, group.members.map(member => [member.name, member.model])]);
|
|
153
|
+
const previous = positions.get(group.id);
|
|
154
|
+
const index = previous && previous.signature === signature ? previous.index % group.members.length : 0;
|
|
155
|
+
positions.delete(group.id);
|
|
156
|
+
positions.set(group.id, { signature, index: index + 1 });
|
|
157
|
+
while (positions.size > MAX_GROUPS) positions.delete(positions.keys().next().value);
|
|
158
|
+
return [...group.members.slice(index), ...group.members.slice(0, index)];
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
module.exports = { createRoutingGroups, createRoutingScheduler, OPENAI_CHAT_TARGET };
|