@fanglinwei/agent-fit 0.0.0-stage → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +157 -2
- package/VERSION +1 -0
- package/adapters/codex/modes.json +360 -0
- package/adapters/codex/skills/agent-fit/SKILL.md +118 -0
- package/adapters/codex/skills/agent-fit/agents/openai.yaml +6 -0
- package/adapters/codex/skills/agent-fit/assets/AGENTS.fragment.md +13 -0
- package/adapters/codex/skills/agent-fit/assets/codex/agents/task-delegate.toml +18 -0
- package/adapters/codex/skills/agent-fit/assets/codex/agents/task-execute.toml +20 -0
- package/adapters/codex/skills/agent-fit/assets/codex/agents/task-review.toml +20 -0
- package/adapters/codex/skills/agent-fit/assets/codex/agents/task-scan.toml +20 -0
- package/adapters/codex/skills/agent-fit/assets/codex/config.toml +17 -0
- package/adapters/codex/skills/agent-fit/references/calibration.md +66 -0
- package/adapters/codex/skills/agent-fit/references/configuration.md +38 -0
- package/adapters/codex/skills/agent-fit/references/failure-policy.md +26 -0
- package/adapters/codex/skills/agent-fit/references/task-routing.md +36 -0
- package/bin/agent-fit.mjs +246 -0
- package/docs/README.md +15 -0
- package/docs/implementation-review.md +119 -0
- package/docs/usage.md +458 -0
- package/lib/accounts.mjs +129 -0
- package/lib/codex.mjs +215 -0
- package/lib/install.mjs +733 -0
- package/lib/model-history.mjs +93 -0
- package/lib/models.mjs +376 -0
- package/lib/probe.mjs +186 -0
- package/lib/scopes.mjs +113 -0
- package/lib/server.mjs +200 -0
- package/package.json +15 -4
- package/web/app.js +744 -0
- package/web/index.html +109 -0
- package/web/styles.css +407 -0
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { lstat, mkdir, open, readdir, rename, rm } from 'node:fs/promises';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { checkPath } from './install.mjs';
|
|
6
|
+
import { argumentError } from './codex.mjs';
|
|
7
|
+
|
|
8
|
+
const DIRECTORY = '.agent-fit-checks';
|
|
9
|
+
const ID = /^\d{13}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
10
|
+
const MAX_BYTES = 4 * 1024 * 1024;
|
|
11
|
+
const failure = () => Object.assign(new Error('检查记录无法安全读写,请核对当前配置目录的权限和记录文件。'), { code: 'MODEL_HISTORY_UNAVAILABLE', exitCode: 1 });
|
|
12
|
+
const pick = (value, keys) => Object.fromEntries(keys.filter(key => Object.hasOwn(value ?? {}, key)).map(key => [key, value[key]]));
|
|
13
|
+
|
|
14
|
+
// Keep an explicit projection: later RPC fields must not silently become persisted credentials.
|
|
15
|
+
function resultFields(data) {
|
|
16
|
+
return {
|
|
17
|
+
...pick(data, ['cli_version', 'codex_version', 'probe_transport', 'check_kind', 'configuration_revision', 'source_revision', 'configuration_changed', 'authorization_changed', 'status', 'exit_code', 'stop_reason', 'inheritance_fallback']),
|
|
18
|
+
...(['setup', 'set', 'configure', 'manual'].includes(data.trigger) ? { trigger: data.trigger } : {}),
|
|
19
|
+
availability: pick(data.availability, ['total', 'available', 'unavailable', 'unconfirmed']),
|
|
20
|
+
account: pick(data.account, ['status', 'type']),
|
|
21
|
+
context: pick(data.context, ['scope', 'provider', 'context_match']),
|
|
22
|
+
mode: pick(data.mode, ['id', 'name', 'kind']),
|
|
23
|
+
catalog: { ...pick(data.catalog, ['status', 'source', 'revision', 'reason_code', 'pages', 'includes_hidden']), models: (data.catalog?.models ?? []).map(model => pick(model, ['id', 'model', 'display_name', 'hidden', 'default_reasoning_effort', 'supported_reasoning_efforts', 'input_modalities'])) },
|
|
24
|
+
checked_pairs: (data.checked_pairs ?? []).map(pair => pick(pair, ['model', 'effort', 'access', 'parameter_support', 'request_status', 'actual_model', 'actual_effort', 'identity_status', 'http_status', 'reason_code', 'stopped_by'])),
|
|
25
|
+
diagnostics: (data.diagnostics ?? []).map(item => pick(item, ['code', 'status'])),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
async function directory(home, create = false) {
|
|
29
|
+
await checkPath(home, DIRECTORY);
|
|
30
|
+
const root = await lstat(home);
|
|
31
|
+
if (!root.isDirectory()) throw failure();
|
|
32
|
+
const target = path.join(home, DIRECTORY);
|
|
33
|
+
if (create) await mkdir(target, { mode: 0o700 }).catch(error => { if (error.code !== 'EEXIST') throw error; });
|
|
34
|
+
let info;
|
|
35
|
+
try { info = await lstat(target); } catch (error) { if (error.code === 'ENOENT' && !create) return null; throw error; }
|
|
36
|
+
if (!info.isDirectory() || info.isSymbolicLink() || process.platform !== 'win32' && ((info.mode & 0o777) !== 0o700 || info.uid !== process.getuid())) throw failure();
|
|
37
|
+
return target;
|
|
38
|
+
}
|
|
39
|
+
async function readRecord(home, id) {
|
|
40
|
+
if (!ID.test(id)) throw argumentError('检查记录标识无效。');
|
|
41
|
+
await directory(home);
|
|
42
|
+
const relative = `${DIRECTORY}/${id}.json`;
|
|
43
|
+
await checkPath(home, relative);
|
|
44
|
+
const handle = await open(path.join(home, relative), constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
45
|
+
try {
|
|
46
|
+
const info = await handle.stat();
|
|
47
|
+
if (!info.isFile() || info.size > MAX_BYTES || process.platform !== 'win32' && ((info.mode & 0o777) !== 0o600 || info.uid !== process.getuid())) throw failure();
|
|
48
|
+
const record = JSON.parse(await handle.readFile('utf8'));
|
|
49
|
+
if (record.schema_version !== 1 || record.id !== id || !['catalog', 'verify', 'availability'].includes(record.kind) || !Number.isFinite(Date.parse(record.checked_at)) || !record.result || typeof record.result !== 'object' || Array.isArray(record.result)) throw failure();
|
|
50
|
+
return { ...pick(record, ['schema_version', 'id', 'checked_at', 'kind']), result: resultFields(record.result) };
|
|
51
|
+
} finally { await handle.close(); }
|
|
52
|
+
}
|
|
53
|
+
export async function saveModelCheck(home, data, { verify = false } = {}) {
|
|
54
|
+
const id = `${Date.now()}-${randomUUID()}`;
|
|
55
|
+
const record = { schema_version: 1, id, checked_at: new Date().toISOString(), kind: data.check_kind === 'availability' ? 'availability' : verify ? 'verify' : 'catalog', result: resultFields(data) };
|
|
56
|
+
const bytes = JSON.stringify(record, null, 2) + '\n';
|
|
57
|
+
if (Buffer.byteLength(bytes) > MAX_BYTES) throw failure();
|
|
58
|
+
let temporary;
|
|
59
|
+
try {
|
|
60
|
+
const target = await directory(home, true);
|
|
61
|
+
await checkPath(home, `${DIRECTORY}/${id}.json`);
|
|
62
|
+
temporary = path.join(target, `.tmp-${id}`);
|
|
63
|
+
const handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
64
|
+
try { await handle.writeFile(bytes); await handle.sync(); } finally { await handle.close(); }
|
|
65
|
+
await checkPath(home, DIRECTORY);
|
|
66
|
+
await rename(temporary, path.join(target, `${id}.json`)); temporary = null;
|
|
67
|
+
return { status: 'saved', id, checked_at: record.checked_at };
|
|
68
|
+
} catch { throw failure(); }
|
|
69
|
+
finally { if (temporary) { await checkPath(home, DIRECTORY); await rm(temporary, { force: true }); } }
|
|
70
|
+
}
|
|
71
|
+
export async function modelHistory(home, { id, cursor } = {}) {
|
|
72
|
+
try {
|
|
73
|
+
if (id !== undefined) return { record: await readRecord(home, id) };
|
|
74
|
+
if (cursor !== undefined && !ID.test(cursor)) throw argumentError('检查记录分页标识无效。');
|
|
75
|
+
const target = await directory(home);
|
|
76
|
+
if (!target) return { records: [], next_cursor: null };
|
|
77
|
+
const files = (await readdir(target)).filter(file => file.endsWith('.json') && ID.test(file.slice(0, -5))).map(file => file.slice(0, -5)).sort().reverse().filter(value => !cursor || value < cursor);
|
|
78
|
+
const records = [];
|
|
79
|
+
for (const value of files.slice(0, 30)) {
|
|
80
|
+
const record = await readRecord(home, value);
|
|
81
|
+
records.push({ ...pick(record, ['id', 'checked_at', 'kind']), ...pick(record.result, ['status', 'exit_code', 'source_revision', 'configuration_changed', 'authorization_changed', 'trigger', 'stop_reason']), account: record.result.account, context: record.result.context, checked_pairs: record.result.checked_pairs, diagnostics: record.result.diagnostics, catalog_status: record.result.catalog.status });
|
|
82
|
+
}
|
|
83
|
+
return { records, next_cursor: files.length > 30 ? files[29] : null };
|
|
84
|
+
} catch (error) { if (error.exitCode === 2) throw error; throw failure(); }
|
|
85
|
+
}
|
|
86
|
+
export async function recordedModelCheck(options, internal = {}) {
|
|
87
|
+
const { checkAccountModels } = await import('./models.mjs');
|
|
88
|
+
const data = await checkAccountModels(options, internal);
|
|
89
|
+
data.trigger = 'manual';
|
|
90
|
+
try { data.history = await saveModelCheck(options.home, data, { verify: options.verify }); }
|
|
91
|
+
catch { data.history = { status: 'failed', code: 'MODEL_HISTORY_UNAVAILABLE' }; data.exit_code ||= 1; }
|
|
92
|
+
return data;
|
|
93
|
+
}
|
package/lib/models.mjs
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { lstat, mkdtemp, rm } from 'node:fs/promises';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { readSnapshot } from './install.mjs';
|
|
6
|
+
import { VERSION, modelPairs, validatePair, argumentError, verificationRequirement } from './codex.mjs';
|
|
7
|
+
import { probeResponses, providerModels, usesProviderCatalog, bindProbeAuthorization } from './probe.mjs';
|
|
8
|
+
import { scopeContext, scopedSelection } from './scopes.mjs';
|
|
9
|
+
|
|
10
|
+
const FRAME_BYTES = 1024 * 1024;
|
|
11
|
+
const TOTAL_BYTES = 8 * FRAME_BYTES;
|
|
12
|
+
const MESSAGES = {
|
|
13
|
+
HOME_NOT_FOUND: '所选 Codex home 不存在;未启动检查进程。',
|
|
14
|
+
INVALID_HOME: '所选 Codex home 不是可检查的普通目录。',
|
|
15
|
+
CONFIG_SNAPSHOT_UNAVAILABLE: '无法稳定读取配置版本;检查结果不能证明当前配置。',
|
|
16
|
+
CODEX_NOT_FOUND: '未找到 Codex CLI;请安装受支持的客户端后重试。',
|
|
17
|
+
RPC_FAILED: 'Codex 协议请求失败;未输出原始响应或错误内容。',
|
|
18
|
+
RPC_UNSUPPORTED: '客户端不支持所需的账号或模型目录接口。',
|
|
19
|
+
RPC_INVALID: '客户端响应格式无效;未输出原始响应。',
|
|
20
|
+
RPC_HOME_MISMATCH: '客户端报告的 Codex home 与所选 home 不一致。',
|
|
21
|
+
RPC_EXITED: '检查进程在目录读取完成前退出。',
|
|
22
|
+
RPC_TIMEOUT: '账号和模型目录检查超过共享期限。',
|
|
23
|
+
RPC_FRAME_LIMIT: '客户端响应超过单帧 1MiB 限制。',
|
|
24
|
+
RPC_TOTAL_LIMIT: '客户端响应超过整轮 8MiB 限制。',
|
|
25
|
+
RPC_CURSOR_LOOP: '目录分页 cursor 重复;目录未完整读取。',
|
|
26
|
+
RPC_PAGE_LIMIT: '目录超过 100 页限制;目录未完整读取。',
|
|
27
|
+
CONTEXT_UNVERIFIED: '本次仅检查所选 home 的 CLI 上下文;桌面会话、启动参数和 profile 未验证。',
|
|
28
|
+
MODEL_ACCESS_UNKNOWN: '模型目录和参数支持不证明账号实际调用权限。',
|
|
29
|
+
MODEL_NOT_LISTED: '目录未列出目标模型;调用权限仍未知。',
|
|
30
|
+
MODEL_EFFORT_UNSUPPORTED: '目录明确未包含目标推理强度;请修改该模型组合。',
|
|
31
|
+
ACCOUNT_AUTHENTICATION_REQUIRED: '所检查 CLI 的 OpenAI 上下文需要登录;请完成登录后重新检查。',
|
|
32
|
+
PROBE_TARGET_REQUIRED: '推理验证需要有效当前档位,或显式提供 model 和 effort。',
|
|
33
|
+
PROBE_ISOLATION_UNSUPPORTED: '已核验的 Codex CLI 接口不能证明禁用全部工具和限制读取范围;未创建线程或发送推理请求。',
|
|
34
|
+
CONFIG_CHANGED: '配置在确认后发生变化;本次未发起验证,请刷新状态后重新确认组合。',
|
|
35
|
+
PROVIDER_CATALOG_FAILED: '无法读取当前供应商的 /models 候选目录;未使用 Codex 目录代替。可手动填写模型和强度进行 Responses 验证。',
|
|
36
|
+
PROVIDER_CATALOG_INVALID: '供应商模型目录格式无效或超过 1000 个候选;未开始批量调用。',
|
|
37
|
+
PROVIDER_CATALOG_PARTIAL: '供应商目录仍有后续分页,本次未完整枚举;请手动选择模型验证。',
|
|
38
|
+
PROVIDER_CATALOG_CHANGED: '供应商候选目录在确认后发生变化;未发起批量调用,请重新检查并确认。',
|
|
39
|
+
PROBE_AVAILABLE: '供应商 Responses 请求已完成,本次可调用;使用供应商默认参数,未验证指定推理强度及严格模型身份。',
|
|
40
|
+
PROBE_VERIFIED: '实际请求完成,响应中的模型与推理强度均匹配。',
|
|
41
|
+
PROBE_AUTH_UNAVAILABLE: '无法读取此配置对应的授权;请检查凭据存储、供应商环境变量,或重新登录。系统凭据库中的授权尚不支持独立请求。',
|
|
42
|
+
PROBE_AUTH_CHANGED: '授权在检查期间发生变化或已无法确认;本轮结果已失效,后续请求已停止,请重新检测。',
|
|
43
|
+
PROBE_PROVIDER_UNSUPPORTED: '当前供应商的地址、协议或特殊授权不支持独立 Responses 验证;未发送请求。',
|
|
44
|
+
PROBE_AUTH_FAILED: '供应商拒绝授权(401),请检查当前配置目录的登录及凭据。',
|
|
45
|
+
PROBE_ACCESS_DENIED: '供应商拒绝访问(403),请检查模型与账号权限。',
|
|
46
|
+
PROBE_RATE_LIMITED: '供应商返回额度或频率限制(429),请检查额度后再试。',
|
|
47
|
+
PROBE_HTTP_FAILED: '供应商返回请求错误;请核对模型、推理强度及服务状态。',
|
|
48
|
+
PROBE_MODEL_NOT_FOUND: '当前供应商返回 model_not_found:未提供所选模型或未向此账号开放。Codex 目录记录不代表该供应商支持此模型,请核对供应商的模型标识。',
|
|
49
|
+
CHECK_STOPPED: '本轮验证已停止,此组合未检查;请查看停止原因。',
|
|
50
|
+
PROBE_EFFORT_UNSUPPORTED: '供应商拒绝所选推理强度;此组合不可用。',
|
|
51
|
+
PROBE_PARAMETER_REJECTED: '当前供应商拒绝验证参数;请核对其 Responses 协议及推理强度支持。',
|
|
52
|
+
PROBE_NETWORK_FAILED: '验证连接或响应格式异常,请检查当前供应商网络后重试。',
|
|
53
|
+
PROBE_RESPONSE_FAILED: '供应商未返回完整成功结果;实际调用未确认。',
|
|
54
|
+
PROBE_RESPONSE_LIMIT: '验证响应超过 2 MiB,读取已停止。',
|
|
55
|
+
PROBE_STREAM_INCOMPLETE: '响应流提前结束,未取得完整完成事件。',
|
|
56
|
+
PROBE_UNEXPECTED_OUTPUT: '验证返回了非预期输出;不会执行其中的任何工具调用。',
|
|
57
|
+
PROBE_TIMEOUT: '实际调用验证超时;请求已停止,未自动重试。',
|
|
58
|
+
PROBE_IDENTITY_UNVERIFIED: '实际请求成功,但响应没有同时提供模型与推理强度,严格身份验证未完成。',
|
|
59
|
+
PROBE_IDENTITY_MISMATCH: '实际请求成功,但响应报告的模型或推理强度与所选组合不同。',
|
|
60
|
+
};
|
|
61
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
62
|
+
const text = (value, maximum) => typeof value === 'string' && value.length > 0 && [...value].length <= maximum && value.trim() === value && !/[\p{Cc}\p{Cf}]/u.test(value);
|
|
63
|
+
const failure = code => Object.assign(new Error(MESSAGES[code]), { code });
|
|
64
|
+
const diagnostic = (code, status = 'unknown') => ({ code, status, source: 'codex_app_server', message: MESSAGES[code] });
|
|
65
|
+
|
|
66
|
+
async function withinDeadline(promise, deadline) {
|
|
67
|
+
let timer;
|
|
68
|
+
try {
|
|
69
|
+
return await Promise.race([promise, new Promise((_, reject) => { timer = setTimeout(() => reject(failure('RPC_TIMEOUT')), Math.max(0, deadline - Date.now())); })]);
|
|
70
|
+
} finally { clearTimeout(timer); }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function rpcClient(child, deadline, { onNotification = () => {}, onFailure = () => {}, requestTimeoutMs = null } = {}) {
|
|
74
|
+
let buffer = Buffer.alloc(0), received = 0, nextId = 0, stopped = false, fatal = null;
|
|
75
|
+
const pending = new Map();
|
|
76
|
+
const exited = new Promise(resolve => child.once('close', resolve));
|
|
77
|
+
function fail(code) {
|
|
78
|
+
if (fatal || stopped) return;
|
|
79
|
+
fatal = failure(code);
|
|
80
|
+
for (const { reject } of pending.values()) reject(fatal);
|
|
81
|
+
pending.clear();
|
|
82
|
+
onFailure(fatal);
|
|
83
|
+
}
|
|
84
|
+
const timer = setTimeout(() => fail('RPC_TIMEOUT'), Math.max(0, deadline - Date.now()));
|
|
85
|
+
child.on('error', error => fail(error.code === 'ENOENT' ? 'CODEX_NOT_FOUND' : 'RPC_FAILED'));
|
|
86
|
+
child.stdin.on('error', () => fail('RPC_EXITED'));
|
|
87
|
+
child.once('close', () => fail('RPC_EXITED'));
|
|
88
|
+
function count(bytes) {
|
|
89
|
+
received += bytes;
|
|
90
|
+
if (received > TOTAL_BYTES) fail('RPC_TOTAL_LIMIT');
|
|
91
|
+
}
|
|
92
|
+
child.stderr.on('data', bytes => count(bytes.length));
|
|
93
|
+
child.stdout.on('data', chunk => {
|
|
94
|
+
count(chunk.length);
|
|
95
|
+
if (fatal || stopped) return;
|
|
96
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
97
|
+
let newline;
|
|
98
|
+
while ((newline = buffer.indexOf(10)) !== -1) {
|
|
99
|
+
if (newline > FRAME_BYTES) { fail('RPC_FRAME_LIMIT'); return; }
|
|
100
|
+
const frame = buffer.subarray(0, newline);
|
|
101
|
+
buffer = buffer.subarray(newline + 1);
|
|
102
|
+
let message;
|
|
103
|
+
try { message = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(frame)); }
|
|
104
|
+
catch { fail('RPC_INVALID'); return; }
|
|
105
|
+
if (!object(message) || message.jsonrpc !== undefined && message.jsonrpc !== '2.0') { fail('RPC_INVALID'); return; }
|
|
106
|
+
if (typeof message.method === 'string' && !Object.hasOwn(message, 'id')) { onNotification(message); continue; }
|
|
107
|
+
const request = pending.get(message.id);
|
|
108
|
+
if (!request || Object.hasOwn(message, 'method') || Object.hasOwn(message, 'result') === Object.hasOwn(message, 'error')) { fail('RPC_INVALID'); return; }
|
|
109
|
+
pending.delete(message.id);
|
|
110
|
+
if (Object.hasOwn(message, 'error')) {
|
|
111
|
+
if (!object(message.error) || !Number.isInteger(message.error.code) || typeof message.error.message !== 'string') { fail('RPC_INVALID'); request.reject(failure('RPC_INVALID')); return; }
|
|
112
|
+
request.reject(failure(message.error.code === -32601 ? 'RPC_UNSUPPORTED' : 'RPC_FAILED'));
|
|
113
|
+
} else request.resolve(message.result);
|
|
114
|
+
}
|
|
115
|
+
if (buffer.length > FRAME_BYTES) fail('RPC_FRAME_LIMIT');
|
|
116
|
+
});
|
|
117
|
+
function send(value) {
|
|
118
|
+
if (fatal) throw fatal;
|
|
119
|
+
if (stopped || child.exitCode !== null || Date.now() >= deadline) throw failure(Date.now() >= deadline ? 'RPC_TIMEOUT' : 'RPC_EXITED');
|
|
120
|
+
child.stdin.write(`${JSON.stringify(value)}\n`);
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
request(method, params) {
|
|
124
|
+
return new Promise((resolve, reject) => {
|
|
125
|
+
const id = nextId++;
|
|
126
|
+
const timeout = requestTimeoutMs ? setTimeout(() => fail('RPC_TIMEOUT'), requestTimeoutMs) : null;
|
|
127
|
+
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
|
|
128
|
+
try { send({ id, method, params }); }
|
|
129
|
+
catch (error) { pending.delete(id); clearTimeout(timeout); reject(error); }
|
|
130
|
+
});
|
|
131
|
+
},
|
|
132
|
+
notify(method) { send({ method }); },
|
|
133
|
+
async close() {
|
|
134
|
+
stopped = true;
|
|
135
|
+
clearTimeout(timer);
|
|
136
|
+
child.stdin.end();
|
|
137
|
+
for (const { reject } of pending.values()) reject(failure('RPC_EXITED'));
|
|
138
|
+
pending.clear();
|
|
139
|
+
const wait = async () => {
|
|
140
|
+
let timeout;
|
|
141
|
+
const done = await Promise.race([exited.then(() => true), new Promise(resolve => { timeout = setTimeout(() => resolve(false), 250); })]);
|
|
142
|
+
clearTimeout(timeout);
|
|
143
|
+
return done;
|
|
144
|
+
};
|
|
145
|
+
if (!await wait()) {
|
|
146
|
+
child.kill('SIGTERM');
|
|
147
|
+
if (!await wait()) { child.kill('SIGKILL'); await wait(); }
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function safeAccount(value, provider) {
|
|
154
|
+
if (!object(value) || typeof value.requiresOpenaiAuth !== 'boolean') throw failure('RPC_INVALID');
|
|
155
|
+
const account = value.account ?? null;
|
|
156
|
+
if (account !== null && (!object(account) || !['apiKey', 'chatgpt', 'amazonBedrock'].includes(account.type))) throw failure('RPC_INVALID');
|
|
157
|
+
return {
|
|
158
|
+
status: account ? 'authenticated' : provider === 'openai' && value.requiresOpenaiAuth ? 'authentication_required' : 'unknown',
|
|
159
|
+
type: account?.type ?? null, requires_openai_auth: value.requiresOpenaiAuth,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function safeModel(value) {
|
|
164
|
+
if (!object(value) || !text(value.id, 200) || !text(value.model, 200) || !text(value.displayName, 200) || typeof value.hidden !== 'boolean' || !text(value.defaultReasoningEffort, 40) || !Array.isArray(value.supportedReasoningEfforts) || value.supportedReasoningEfforts.length > 100 || value.supportedReasoningEfforts.some(option => !object(option) || !text(option.reasoningEffort, 40))) throw failure('RPC_INVALID');
|
|
165
|
+
const modalities = Object.hasOwn(value, 'inputModalities') ? value.inputModalities : null;
|
|
166
|
+
if (Object.hasOwn(value, 'inputModalities') && modalities === null) throw failure('RPC_INVALID');
|
|
167
|
+
if (modalities !== null && (!Array.isArray(modalities) || modalities.length > 100 || modalities.some(modality => !text(modality, 40)))) throw failure('RPC_INVALID');
|
|
168
|
+
return {
|
|
169
|
+
id: value.id, model: value.model, display_name: value.displayName, hidden: value.hidden,
|
|
170
|
+
default_reasoning_effort: value.defaultReasoningEffort,
|
|
171
|
+
supported_reasoning_efforts: [...new Set(value.supportedReasoningEfforts.map(option => option.reasoningEffort))],
|
|
172
|
+
input_modalities: modalities === null ? null : [...new Set(modalities)],
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function selectedMode(mode) {
|
|
177
|
+
return object(mode) ? { id: mode.id, name: mode.name, kind: mode.kind } : mode ?? null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// The second argument only injects a child/snapshots/deadline in isolated tests; no CLI exposes it.
|
|
181
|
+
export async function checkAccountModels({ home, scope, project, thread, verify = false, discover = false, target, expectRevision, expectCatalog } = {}, internal = {}) {
|
|
182
|
+
if (typeof home !== 'string' || !home || home.length > 4096 || /[\p{Cc}\p{Cf}]/u.test(home) || !path.isAbsolute(home)) throw argumentError('必须提供绝对路径 Codex home。', 'INVALID_HOME');
|
|
183
|
+
if (typeof verify !== 'boolean' || typeof discover !== 'boolean' || discover && (!verify || target)) throw argumentError('模型检查参数无效。');
|
|
184
|
+
if (expectRevision !== undefined && !text(expectRevision, 200)) throw argumentError('模型检查配置版本无效。');
|
|
185
|
+
if (expectCatalog !== undefined && (!discover || !/^[a-f0-9]{64}$/.test(expectCatalog))) throw argumentError('供应商目录版本无效。');
|
|
186
|
+
const explicit = target === undefined ? null : validatePair(target);
|
|
187
|
+
const context = scope === undefined ? null : await scopeContext({ scope, project, thread });
|
|
188
|
+
const read = internal.readSnapshot ?? readSnapshot;
|
|
189
|
+
const snapshotReader = async home => {
|
|
190
|
+
const snapshot = await read(home);
|
|
191
|
+
if (!context) return snapshot;
|
|
192
|
+
if (snapshot.diagnostics?.some(item => item.status === 'fail')) throw failure('CONFIG_SNAPSHOT_UNAVAILABLE');
|
|
193
|
+
const effective = scopedSelection(snapshot, context);
|
|
194
|
+
return { ...snapshot, mode: snapshot.state ? effective.definition : null };
|
|
195
|
+
};
|
|
196
|
+
const deadline = Date.now() + (internal.deadlineMs ?? (verify ? 90_000 : 30_000));
|
|
197
|
+
const result = {
|
|
198
|
+
agent: 'codex', home, cli_version: VERSION, configuration_revision: null, source_revision: null,
|
|
199
|
+
mode: null, checked_pairs: [], account: { status: 'unknown', type: null, requires_openai_auth: null },
|
|
200
|
+
catalog: { status: 'not_checked', includes_hidden: true, pages: 0, models: [] },
|
|
201
|
+
context: { scope: 'selected_cli_home', provider: null, profile: null, context_match: 'unverified' },
|
|
202
|
+
configuration_changed: null, authorization_changed: null, status: 'incomplete', diagnostics: [], exit_code: 0,
|
|
203
|
+
};
|
|
204
|
+
let snapshot, unsafeHome = false, snapshotTimedOut = false;
|
|
205
|
+
try { snapshot = await withinDeadline(snapshotReader(home), deadline); result.configuration_revision = snapshot.configuration_revision; }
|
|
206
|
+
catch (error) {
|
|
207
|
+
snapshotTimedOut = error.code === 'RPC_TIMEOUT';
|
|
208
|
+
unsafeHome = ['UNSAFE_PATH', 'UNSAFE_PERMISSIONS', 'INVALID_HOME'].includes(error.code);
|
|
209
|
+
result.diagnostics.push(diagnostic('CONFIG_SNAPSHOT_UNAVAILABLE'));
|
|
210
|
+
result.exit_code = 1;
|
|
211
|
+
}
|
|
212
|
+
result.source_revision = result.configuration_revision;
|
|
213
|
+
if (context) {
|
|
214
|
+
result.routing_scope = context.scope;
|
|
215
|
+
if (!snapshot) return result;
|
|
216
|
+
}
|
|
217
|
+
if (expectRevision !== undefined && expectRevision !== result.configuration_revision) {
|
|
218
|
+
result.source_revision = expectRevision; result.configuration_changed = true; result.exit_code = 1;
|
|
219
|
+
result.diagnostics.push(diagnostic('CONFIG_CHANGED'));
|
|
220
|
+
if (explicit) result.checked_pairs = [{ ...explicit, access: 'unknown', parameter_support: 'unknown', request_status: 'not_checked', actual_model: null, actual_effort: null, reason_code: 'CONFIG_CHANGED' }];
|
|
221
|
+
return result;
|
|
222
|
+
}
|
|
223
|
+
let pairs;
|
|
224
|
+
if (discover) pairs = [];
|
|
225
|
+
else if (explicit) pairs = [explicit];
|
|
226
|
+
else if (snapshot?.mode) {
|
|
227
|
+
result.mode = selectedMode(snapshot.mode);
|
|
228
|
+
pairs = modelPairs(snapshot.mode, !verify);
|
|
229
|
+
} else pairs = [];
|
|
230
|
+
pairs = [...new Map(pairs.map(pair => [JSON.stringify(pair), pair])).values()];
|
|
231
|
+
result.verification = discover ? { required: false, scope: 'model_availability' } : verificationRequirement(snapshot?.mode);
|
|
232
|
+
if (discover) result.check_kind = 'availability';
|
|
233
|
+
result.checked_pairs = pairs.map(pair => ({ ...pair, access: 'unknown', parameter_support: 'unknown', request_status: verify ? 'not_checked' : 'not_requested', actual_model: null, actual_effort: null, reason_code: 'MODEL_ACCESS_UNKNOWN' }));
|
|
234
|
+
if (verify && !discover && !pairs.length) {
|
|
235
|
+
result.exit_code = 1;
|
|
236
|
+
result.diagnostics.push(diagnostic('PROBE_TARGET_REQUIRED'));
|
|
237
|
+
return result;
|
|
238
|
+
}
|
|
239
|
+
let rpc, directory, providerConfig, authorization;
|
|
240
|
+
let requestInternal = internal;
|
|
241
|
+
try {
|
|
242
|
+
if (unsafeHome) throw failure('INVALID_HOME');
|
|
243
|
+
const metadata = await lstat(home).catch(error => { if (error.code === 'ENOENT') throw failure('HOME_NOT_FOUND'); throw error; });
|
|
244
|
+
if (!metadata.isDirectory() || metadata.isSymbolicLink()) throw failure('INVALID_HOME');
|
|
245
|
+
if (snapshotTimedOut || Date.now() >= deadline) throw failure('RPC_TIMEOUT');
|
|
246
|
+
directory = await mkdtemp(path.join(os.tmpdir(), 'agent-fit-models-'));
|
|
247
|
+
const child = (internal.spawn ?? spawn)('codex', ['app-server'], { shell: false, cwd: directory, env: { ...process.env, CODEX_HOME: home }, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
248
|
+
rpc = rpcClient(child, Math.min(deadline, Date.now() + 30_000));
|
|
249
|
+
const initialized = await rpc.request('initialize', { clientInfo: { name: 'subagent_delegation', version: VERSION }, capabilities: { experimentalApi: true } });
|
|
250
|
+
if (!object(initialized) || !text(initialized.userAgent, 1000) || !text(initialized.platformFamily, 200) || !text(initialized.platformOs, 200) || typeof initialized.codexHome !== 'string' || !path.isAbsolute(initialized.codexHome)) throw failure('RPC_INVALID');
|
|
251
|
+
if (path.resolve(initialized.codexHome) !== path.resolve(home)) throw failure('RPC_HOME_MISMATCH');
|
|
252
|
+
result.codex_version = initialized.userAgent.match(/\b\d+\.\d+\.\d+\b/)?.[0] ?? null;
|
|
253
|
+
rpc.notify('initialized');
|
|
254
|
+
const account = await rpc.request('account/read', { refreshToken: false });
|
|
255
|
+
try {
|
|
256
|
+
const config = await rpc.request('config/read', { includeLayers: false, cwd: null });
|
|
257
|
+
if (!object(config) || !object(config.config) || config.config.model_provider != null && !text(config.config.model_provider, 200)) throw failure('RPC_INVALID');
|
|
258
|
+
result.context.provider = config.config.model_provider ?? null;
|
|
259
|
+
providerConfig = config.config;
|
|
260
|
+
if (verify) {
|
|
261
|
+
authorization = await withinDeadline(bindProbeAuthorization(home, providerConfig, internal.env ?? process.env), deadline);
|
|
262
|
+
requestInternal = { ...internal, authorization };
|
|
263
|
+
}
|
|
264
|
+
} catch (error) { if (error.code !== 'RPC_UNSUPPORTED') throw error; }
|
|
265
|
+
result.account = safeAccount(account, result.context.provider);
|
|
266
|
+
if (result.account.status === 'authentication_required') {
|
|
267
|
+
result.exit_code = 1;
|
|
268
|
+
result.diagnostics.push(diagnostic('ACCOUNT_AUTHENTICATION_REQUIRED'));
|
|
269
|
+
}
|
|
270
|
+
if (providerConfig && usesProviderCatalog(providerConfig, internal.env ?? process.env)) {
|
|
271
|
+
result.catalog = await providerModels({ home, config: providerConfig, deadline }, requestInternal);
|
|
272
|
+
if (result.catalog.status !== 'complete') {
|
|
273
|
+
result.diagnostics.push({ ...diagnostic(result.catalog.reason_code), source: 'provider_models' });
|
|
274
|
+
if (!verify || discover || ['PROBE_AUTH_FAILED', 'PROBE_ACCESS_DENIED', 'PROBE_RATE_LIMITED'].includes(result.catalog.reason_code)) result.exit_code = 1;
|
|
275
|
+
}
|
|
276
|
+
} else {
|
|
277
|
+
result.catalog.source = 'codex_app_server';
|
|
278
|
+
let cursor = null;
|
|
279
|
+
const cursors = new Set();
|
|
280
|
+
result.catalog.status = 'incomplete';
|
|
281
|
+
for (let page = 0; page < 100; page++) {
|
|
282
|
+
const value = await rpc.request('model/list', { cursor, limit: 100, includeHidden: true });
|
|
283
|
+
if (!object(value) || !Array.isArray(value.data) || value.nextCursor != null && !text(value.nextCursor, 4096)) throw failure('RPC_INVALID');
|
|
284
|
+
const models = value.data.map(safeModel);
|
|
285
|
+
result.catalog.models.push(...models);
|
|
286
|
+
result.catalog.pages++;
|
|
287
|
+
cursor = value.nextCursor ?? null;
|
|
288
|
+
if (cursor === null) { result.catalog.status = 'complete'; break; }
|
|
289
|
+
if (cursors.has(cursor)) throw failure('RPC_CURSOR_LOOP');
|
|
290
|
+
cursors.add(cursor);
|
|
291
|
+
if (page === 99) throw failure('RPC_PAGE_LIMIT');
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (discover) {
|
|
295
|
+
if (result.catalog.source !== 'provider_models' || result.catalog.status !== 'complete') result.exit_code = 1;
|
|
296
|
+
else if (expectCatalog && expectCatalog !== result.catalog.revision) { result.exit_code = 1; result.diagnostics.push(diagnostic('PROVIDER_CATALOG_CHANGED')); }
|
|
297
|
+
else result.checked_pairs = result.catalog.models.map(model => ({ model: model.id, effort: null, access: 'unknown', parameter_support: 'unknown', request_status: 'not_checked', actual_model: null, actual_effort: null, reason_code: 'MODEL_ACCESS_UNKNOWN' }));
|
|
298
|
+
}
|
|
299
|
+
result.diagnostics.push(diagnostic('CONTEXT_UNVERIFIED'), diagnostic('MODEL_ACCESS_UNKNOWN'));
|
|
300
|
+
for (const pair of result.checked_pairs) {
|
|
301
|
+
const models = result.catalog.models.filter(model => model.model === pair.model || model.id === pair.model);
|
|
302
|
+
if (models.length === 0) { pair.reason_code = 'MODEL_NOT_LISTED'; continue; }
|
|
303
|
+
if (result.catalog.source === 'provider_models') continue;
|
|
304
|
+
pair.parameter_support = models.some(model => model.supported_reasoning_efforts.includes(pair.effort)) ? 'supported' : 'incompatible';
|
|
305
|
+
if (pair.parameter_support === 'incompatible') {
|
|
306
|
+
pair.reason_code = 'MODEL_EFFORT_UNSUPPORTED';
|
|
307
|
+
if (!result.exit_code) result.exit_code = 3;
|
|
308
|
+
result.diagnostics.push({ ...diagnostic(pair.reason_code, 'incompatible'), model: pair.model, effort: pair.effort });
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
} catch (error) {
|
|
312
|
+
result.exit_code = 1;
|
|
313
|
+
result.diagnostics.push(diagnostic(Object.hasOwn(MESSAGES, error.code) ? error.code : 'RPC_FAILED'));
|
|
314
|
+
} finally {
|
|
315
|
+
if (rpc) await rpc.close();
|
|
316
|
+
if (directory) await rm(directory, { recursive: true, force: true });
|
|
317
|
+
}
|
|
318
|
+
if (verify) {
|
|
319
|
+
result.probe_transport = 'responses_without_tools';
|
|
320
|
+
const stop = (reason, attempted = null) => {
|
|
321
|
+
result.stop_reason = reason;
|
|
322
|
+
for (const pair of result.checked_pairs) if (pair !== attempted && pair.request_status === 'not_checked' && pair.parameter_support !== 'incompatible') {
|
|
323
|
+
pair.reason_code = reason === 'PROBE_TIMEOUT' ? 'PROBE_TIMEOUT' : 'CHECK_STOPPED'; pair.stopped_by = reason;
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
if (!providerConfig || !result.source_revision || result.exit_code === 1) {
|
|
327
|
+
result.exit_code = 1;
|
|
328
|
+
stop(result.diagnostics.find(item => !['CONTEXT_UNVERIFIED', 'MODEL_ACCESS_UNKNOWN'].includes(item.code))?.code ?? 'CONFIG_SNAPSHOT_UNAVAILABLE');
|
|
329
|
+
}
|
|
330
|
+
else {
|
|
331
|
+
for (const pair of result.checked_pairs) {
|
|
332
|
+
if (pair.parameter_support === 'incompatible') continue;
|
|
333
|
+
if (Date.now() >= deadline) { result.exit_code = 1; stop('PROBE_TIMEOUT'); break; }
|
|
334
|
+
const current = await withinDeadline(snapshotReader(home), deadline).catch(() => null);
|
|
335
|
+
if (!current || current.configuration_revision !== result.source_revision) {
|
|
336
|
+
result.exit_code = 1; pair.reason_code = 'CONFIG_CHANGED';
|
|
337
|
+
result.diagnostics.push(diagnostic('CONFIG_CHANGED')); stop('CONFIG_CHANGED'); break;
|
|
338
|
+
}
|
|
339
|
+
Object.assign(pair, await probeResponses({ home, config: providerConfig, pair, deadline }, requestInternal));
|
|
340
|
+
result.diagnostics.push({ ...diagnostic(pair.reason_code, pair.identity_status), source: 'provider_responses', model: pair.model, effort: pair.effort });
|
|
341
|
+
if (discover) {
|
|
342
|
+
if (pair.identity_status === 'mismatch' || pair.request_status !== 'succeeded' && !['denied', 'unavailable'].includes(pair.access)) result.exit_code = 1;
|
|
343
|
+
} else if (pair.identity_status !== 'matched') result.exit_code = pair.identity_status === 'mismatch' || pair.request_status === 'failed' ? result.exit_code === 1 ? 1 : 3 : 1;
|
|
344
|
+
if (!['PROBE_VERIFIED', 'PROBE_AVAILABLE', 'PROBE_MODEL_NOT_FOUND', 'PROBE_EFFORT_UNSUPPORTED', 'PROBE_IDENTITY_MISMATCH', 'PROBE_IDENTITY_UNVERIFIED'].includes(pair.reason_code)) {
|
|
345
|
+
result.exit_code ||= 1; stop(pair.reason_code, pair); break;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (result.checked_pairs.every(pair => pair.access !== 'unknown')) result.diagnostics = result.diagnostics.filter(item => item.code !== 'MODEL_ACCESS_UNKNOWN');
|
|
350
|
+
}
|
|
351
|
+
if (Date.now() < deadline) {
|
|
352
|
+
try {
|
|
353
|
+
const end = await withinDeadline(snapshotReader(home), deadline);
|
|
354
|
+
result.configuration_changed = result.source_revision === null ? null : end.configuration_revision !== result.source_revision;
|
|
355
|
+
} catch { result.configuration_changed = null; }
|
|
356
|
+
}
|
|
357
|
+
if (result.configuration_changed === true && verify) { result.exit_code = 1; result.stop_reason = 'CONFIG_CHANGED'; }
|
|
358
|
+
if (authorization) {
|
|
359
|
+
try { await withinDeadline(authorization(), deadline); result.authorization_changed = false; }
|
|
360
|
+
catch (error) {
|
|
361
|
+
if (error.code === 'PROBE_AUTH_CHANGED') {
|
|
362
|
+
result.authorization_changed = true; result.exit_code = 1; result.stop_reason = error.code;
|
|
363
|
+
result.diagnostics = result.diagnostics.filter(item => !['PROBE_VERIFIED', 'PROBE_AVAILABLE'].includes(item.code));
|
|
364
|
+
result.diagnostics.push(diagnostic(error.code));
|
|
365
|
+
for (const pair of result.checked_pairs) {
|
|
366
|
+
pair.access = 'unknown'; pair.identity_status = 'unverified';
|
|
367
|
+
pair.reason_code = pair.request_status === 'not_checked' ? 'CHECK_STOPPED' : error.code;
|
|
368
|
+
pair.stopped_by = error.code;
|
|
369
|
+
}
|
|
370
|
+
} else if (!result.exit_code) { result.exit_code = 1; result.diagnostics.push(diagnostic(Object.hasOwn(MESSAGES, error.code) ? error.code : 'PROBE_AUTH_UNAVAILABLE')); }
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
if (discover) result.availability = { total: result.checked_pairs.length, available: result.checked_pairs.filter(pair => pair.access === 'available' && pair.identity_status !== 'mismatch').length, unavailable: result.checked_pairs.filter(pair => ['unavailable', 'denied'].includes(pair.access)).length, unconfirmed: result.checked_pairs.filter(pair => !['available', 'unavailable', 'denied'].includes(pair.access) || pair.identity_status === 'mismatch').length };
|
|
374
|
+
result.status = result.exit_code === 1 ? 'incomplete' : result.exit_code === 3 ? 'failed' : 'passed';
|
|
375
|
+
return result;
|
|
376
|
+
}
|