@fanglinwei/agent-fit 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +161 -2
  3. package/VERSION +1 -0
  4. package/adapters/codex/modes.json +360 -0
  5. package/adapters/codex/skills/agent-fit/SKILL.md +120 -0
  6. package/adapters/codex/skills/agent-fit/agents/openai.yaml +6 -0
  7. package/adapters/codex/skills/agent-fit/assets/AGENTS.fragment.md +13 -0
  8. package/adapters/codex/skills/agent-fit/assets/codex/agents/task-delegate.toml +18 -0
  9. package/adapters/codex/skills/agent-fit/assets/codex/agents/task-execute.toml +20 -0
  10. package/adapters/codex/skills/agent-fit/assets/codex/agents/task-review.toml +20 -0
  11. package/adapters/codex/skills/agent-fit/assets/codex/agents/task-scan.toml +20 -0
  12. package/adapters/codex/skills/agent-fit/assets/codex/config.toml +17 -0
  13. package/adapters/codex/skills/agent-fit/references/calibration.md +66 -0
  14. package/adapters/codex/skills/agent-fit/references/configuration.md +42 -0
  15. package/adapters/codex/skills/agent-fit/references/failure-policy.md +26 -0
  16. package/adapters/codex/skills/agent-fit/references/task-routing.md +36 -0
  17. package/bin/agent-fit.mjs +265 -0
  18. package/docs/README.md +15 -0
  19. package/docs/implementation-review.md +119 -0
  20. package/docs/usage.md +481 -0
  21. package/lib/accounts.mjs +129 -0
  22. package/lib/codex.mjs +220 -0
  23. package/lib/install.mjs +796 -0
  24. package/lib/model-history.mjs +93 -0
  25. package/lib/models.mjs +376 -0
  26. package/lib/probe.mjs +186 -0
  27. package/lib/scopes.mjs +113 -0
  28. package/lib/server.mjs +200 -0
  29. package/lib/skill.mjs +145 -0
  30. package/package.json +15 -4
  31. package/web/app.js +744 -0
  32. package/web/index.html +109 -0
  33. package/web/styles.css +407 -0
@@ -0,0 +1,129 @@
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 { rpcClient, safeAccount } from './models.mjs';
6
+ import { checkPath } from './install.mjs';
7
+ import { VERSION, argumentError } from './codex.mjs';
8
+ import { providerCredential } from './probe.mjs';
9
+
10
+ const failure = (code, message) => Object.assign(new Error(message), { code, exitCode: 1 });
11
+ const text = value => typeof value === 'string' && value.length > 0 && value.length <= 4096 && !/[\p{Cc}\p{Cf}]/u.test(value);
12
+ function authUrl(value) {
13
+ if (!text(value)) throw failure('AUTH_RESPONSE_INVALID', '客户端返回的授权地址无效。');
14
+ let url;
15
+ try { url = new URL(value); } catch { throw failure('AUTH_RESPONSE_INVALID', '客户端返回的授权地址无效。'); }
16
+ if (url.protocol !== 'https:' || !['auth.openai.com', 'auth0.openai.com', 'chatgpt.com'].includes(url.hostname) || url.username || url.password || url.port) throw failure('AUTH_RESPONSE_INVALID', '客户端返回了非官方授权地址,登录已停止。');
17
+ return url.href;
18
+ }
19
+
20
+ // Only the test harness supplies a child/deadline; HTTP callers cannot override either.
21
+ export function createAccountController(home, internal = {}) {
22
+ let session = null, attempt = null, account = { status: 'unknown', type: null }, provider = null, credentialSource = 'not_confirmed';
23
+ let completion = null, closing = null, usesConfiguredCredential = false;
24
+ const timeoutMs = internal.timeoutMs ?? 10 * 60_000;
25
+ function completed(message) {
26
+ if (message.method !== 'account/login/completed') return;
27
+ const value = message.params;
28
+ if (!value || typeof value.success !== 'boolean') return;
29
+ completion = { loginId: value.loginId, success: value.success };
30
+ if (attempt?.id && completion.loginId === attempt.id) {
31
+ attempt.status = completion.success ? 'succeeded' : 'failed';
32
+ attempt.url = null; attempt.user_code = null;
33
+ }
34
+ }
35
+ async function stop() {
36
+ if (closing) return closing;
37
+ const current = session; session = null;
38
+ if (!current) return;
39
+ closing = (async () => { await current.rpc.close(); await rm(current.directory, { recursive: true, force: true }); })();
40
+ try { await closing; } finally { closing = null; }
41
+ }
42
+ async function open() {
43
+ if (closing) await closing;
44
+ if (session) return session.rpc;
45
+ await checkPath(home);
46
+ const info = await lstat(home);
47
+ if (!info.isDirectory()) throw failure('INVALID_HOME', '所选 Codex 配置目录不存在或不可访问。');
48
+ const directory = await mkdtemp(path.join(os.tmpdir(), 'agent-fit-login-'));
49
+ const child = (internal.spawn ?? spawn)('codex', ['app-server'], { shell: false, cwd: directory, env: { ...process.env, CODEX_HOME: home }, stdio: ['pipe', 'pipe', 'pipe'] });
50
+ const rpc = rpcClient(child, Date.now() + timeoutMs, { requestTimeoutMs: 30_000, onNotification: completed, onFailure: error => {
51
+ if (attempt?.status === 'pending' || attempt?.status === 'starting') {
52
+ attempt.status = error.code === 'RPC_TIMEOUT' ? 'expired' : 'failed';
53
+ attempt.url = null; attempt.user_code = null;
54
+ }
55
+ void stop().catch(() => { if (attempt) attempt.status = 'failed'; });
56
+ } });
57
+ session = { rpc, directory };
58
+ try {
59
+ const handshake = await rpc.request('initialize', { clientInfo: { name: 'subagent_delegation_login', version: VERSION }, capabilities: { experimentalApi: true } });
60
+ if (!handshake || handshake.codexHome !== home) throw failure('RPC_HOME_MISMATCH', '客户端配置目录与当前页面不一致,登录已停止。');
61
+ rpc.notify('initialized');
62
+ const config = await rpc.request('config/read', { includeLayers: false, cwd: null });
63
+ provider = text(config?.config?.model_provider) ? config.config.model_provider : null;
64
+ const configured = providerCredential(config?.config ?? {});
65
+ usesConfiguredCredential = configured !== null;
66
+ credentialSource = configured?.source ?? 'not_confirmed';
67
+ return rpc;
68
+ } catch (error) { await stop(); throw error; }
69
+ }
70
+ async function read() {
71
+ const rpc = await open();
72
+ account = safeAccount(await rpc.request('account/read', { refreshToken: false }), provider);
73
+ if (account.status === 'authenticated' && !usesConfiguredCredential) credentialSource = 'codex_login';
74
+ }
75
+ function view() {
76
+ return { home, account, provider, credential_source: credentialSource, login: attempt ? { status: attempt.status, method: attempt.method, url: attempt.url, user_code: attempt.user_code, expires_at: attempt.expires_at } : null };
77
+ }
78
+ return {
79
+ async action({ operation, method, apiKey }) {
80
+ try {
81
+ if (operation === 'status') {
82
+ await read();
83
+ if (attempt?.status === 'succeeded' && account.status !== 'authenticated') attempt.status = 'failed';
84
+ } else if (operation === 'login') {
85
+ if (attempt?.status === 'pending') throw failure('LOGIN_PENDING', '已有授权等待完成。请继续授权或先取消。');
86
+ if (!['chatgpt', 'chatgptDeviceCode', 'apiKey'].includes(method)) throw argumentError('不支持的登录方式。');
87
+ if (method === 'apiKey' && (!text(apiKey) || apiKey.trim() !== apiKey)) throw argumentError('请输入有效 API Key。');
88
+ if (method !== 'apiKey' && apiKey !== undefined) throw argumentError('此登录方式不接受 API Key。');
89
+ await stop(); completion = null;
90
+ attempt = { status: 'starting', method, id: null, url: null, user_code: null, expires_at: new Date(Date.now() + timeoutMs).toISOString() };
91
+ const rpc = await open();
92
+ const result = await rpc.request('account/login/start', method === 'apiKey' ? { type: method, apiKey } : { type: method });
93
+ apiKey = undefined;
94
+ if (!result || result.type !== method) throw failure('AUTH_RESPONSE_INVALID', '客户端未返回可识别的登录结果。');
95
+ if (method === 'apiKey') {
96
+ await read();
97
+ if (account.status !== 'authenticated' || account.type !== 'apiKey') throw failure('AUTH_NOT_CONFIRMED', 'API Key 登录状态未确认,请重新检查。');
98
+ attempt.status = 'succeeded';
99
+ } else {
100
+ if (!text(result.loginId) || method === 'chatgptDeviceCode' && (!text(result.userCode) || result.userCode.length > 100)) throw failure('AUTH_RESPONSE_INVALID', '客户端返回的授权信息无效。');
101
+ attempt.id = result.loginId;
102
+ attempt.url = authUrl(method === 'chatgpt' ? result.authUrl : result.verificationUrl);
103
+ attempt.user_code = method === 'chatgptDeviceCode' ? result.userCode : null;
104
+ attempt.status = 'pending';
105
+ if (completion?.loginId === attempt.id) completed({ method: 'account/login/completed', params: completion });
106
+ if (attempt.status === 'succeeded') await read();
107
+ }
108
+ } else if (operation === 'cancel') {
109
+ if (attempt?.status === 'pending' && session) await session.rpc.request('account/login/cancel', { loginId: attempt.id });
110
+ if (attempt) { attempt.status = 'cancelled'; attempt.url = null; attempt.user_code = null; }
111
+ } else if (operation === 'logout') {
112
+ if (attempt?.status === 'pending' && session) await session.rpc.request('account/login/cancel', { loginId: attempt.id });
113
+ const rpc = await open();
114
+ await rpc.request('account/logout', {}); attempt = null;
115
+ await read();
116
+ } else throw argumentError('不支持的账号操作。');
117
+ return view();
118
+ } catch (error) {
119
+ if (attempt?.status === 'starting') { attempt.status = 'failed'; attempt.url = null; attempt.user_code = null; }
120
+ if (error.exitCode === 2 || ['LOGIN_PENDING', 'AUTH_RESPONSE_INVALID', 'AUTH_NOT_CONFIRMED', 'RPC_HOME_MISMATCH'].includes(error.code)) throw error;
121
+ throw failure(error.code === 'CODEX_NOT_FOUND' ? 'CODEX_NOT_FOUND' : 'ACCOUNT_UNAVAILABLE', error.code === 'CODEX_NOT_FOUND' ? '本地服务未找到 Codex CLI,请检查启动服务的终端。' : '账号操作未完成。请重试或在 Codex CLI 中检查登录状态。');
122
+ } finally { if (attempt?.status !== 'pending') await stop(); }
123
+ },
124
+ async close() {
125
+ if (attempt) { attempt.status = 'cancelled'; attempt.url = null; attempt.user_code = null; }
126
+ await stop();
127
+ },
128
+ };
129
+ }
package/lib/codex.mjs ADDED
@@ -0,0 +1,220 @@
1
+ import { readFile, readdir, lstat } from 'node:fs/promises';
2
+ import { fileURLToPath } from 'node:url';
3
+ import path from 'node:path';
4
+ import { parse, stringify } from 'smol-toml';
5
+
6
+ export const PACKAGE_ROOT = fileURLToPath(new URL('../', import.meta.url));
7
+ export const VERSION = (await readFile(new URL('../VERSION', import.meta.url), 'utf8')).trim();
8
+ export const LEVELS = ['L1', 'L2', 'L3', 'L4'];
9
+ export const TASKS = { mechanical: ['L1'], bounded: ['L2'], scan: ['L1', 'L2'], deep: ['L1', 'L2'], complex: ['L2', 'L3'], uncertain: ['L3', 'L4'], reasoning: ['L3', 'L4'], latency: LEVELS };
10
+ export const ROLES = { task_scan: 'L1', task_execute: 'L2', task_review: 'L3', task_delegate: null };
11
+ export const START = '<!-- agent-fit:start -->';
12
+ export const END = '<!-- agent-fit:end -->';
13
+ const policy = JSON.parse(await readFile(new URL('../adapters/codex/modes.json', import.meta.url), 'utf8'));
14
+ export const FALLBACK_CONDITIONS = policy.fallback_conditions;
15
+ export const BUILTINS = policy.modes.map(mode => ({ ...mode, kind: 'builtin', fallback_conditions: FALLBACK_CONDITIONS }));
16
+
17
+ export function argumentError(message, code = 'INVALID_ARGUMENT') {
18
+ return Object.assign(new Error(message), { code, exitCode: 2 });
19
+ }
20
+
21
+ export function validateText(value, maximum, label) {
22
+ if (typeof value !== 'string' || !value || !value.isWellFormed() || value.trim() !== value || [...value].length > maximum || /[\p{Cc}\p{Cf}]/u.test(value)) {
23
+ throw argumentError(`${label}必须为有效 Unicode、无控制字符、无首尾空白的 1–${maximum} 字符文本。`);
24
+ }
25
+ return value;
26
+ }
27
+
28
+ export function validatePair(pair) {
29
+ if (!pair || typeof pair !== 'object' || Array.isArray(pair) || Object.keys(pair).some(k => !['model', 'effort'].includes(k))) {
30
+ throw argumentError('模型组合只接受 model 和 effort。');
31
+ }
32
+ return { model: validateText(pair.model, 200, '模型'), effort: validateText(pair.effort, 40, '推理强度') };
33
+ }
34
+
35
+ export function validateDefinition(input) {
36
+ if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).length !== 1 || !Object.hasOwn(input, 'levels')) throw argumentError('完整定义只接受 levels 对象。');
37
+ const levels = input.levels;
38
+ if (!levels || typeof levels !== 'object' || Array.isArray(levels) || Object.keys(levels).length !== 4 || LEVELS.some(level => !Object.hasOwn(levels, level))) throw argumentError('必须提供完整 L1–L4。');
39
+ return Object.fromEntries(LEVELS.map(level => {
40
+ const value = levels[level];
41
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(k => !['model', 'effort', 'fallback', 'tasks'].includes(k)) || !['model', 'effort', 'fallback'].every(k => Object.hasOwn(value, k))) throw argumentError(`${level} 必须显式提供 model、effort、fallback(可为 null),可选 tasks。`);
42
+ const primary = validatePair({ model: value.model, effort: value.effort });
43
+ const fallback = value.fallback === null ? null : validatePair(value.fallback);
44
+ if (fallback && primary.model === fallback.model && primary.effort === fallback.effort) throw argumentError('主配置与备用不能完全相同。');
45
+ let tasks;
46
+ if (Object.hasOwn(value, 'tasks')) {
47
+ if (!value.tasks || typeof value.tasks !== 'object' || Array.isArray(value.tasks)) throw argumentError('tasks 必须为任务候选对象。');
48
+ tasks = Object.fromEntries(Object.entries(value.tasks).map(([task, candidate]) => {
49
+ if (!Object.hasOwn(TASKS, task) || !TASKS[task].includes(level) || !candidate || typeof candidate !== 'object' || Array.isArray(candidate) || Object.keys(candidate).length !== 3 || !['model', 'effort', 'fallback'].every(k => Object.hasOwn(candidate, k))) throw argumentError(`${level} 的任务候选类型或结构无效。`);
50
+ const pair = validatePair({ model: candidate.model, effort: candidate.effort });
51
+ const backup = candidate.fallback === null ? null : validatePair(candidate.fallback);
52
+ if (backup && pair.model === backup.model && pair.effort === backup.effort) throw argumentError('任务候选与备用不能完全相同。');
53
+ return [task, { ...pair, fallback: backup }];
54
+ }));
55
+ }
56
+ return [level, { ...primary, fallback, ...(tasks === undefined ? {} : { tasks }) }];
57
+ }));
58
+ }
59
+
60
+ export function resolveDefinition(selector, customModes = []) {
61
+ const name = typeof selector === 'string' ? selector.trim().normalize('NFC') : selector;
62
+ const matches = [...BUILTINS.filter(mode => mode.id === selector), ...customModes.filter(mode => mode.id === selector || mode.name === name)];
63
+ if (matches.length !== 1) throw argumentError('档位不存在或名称不唯一;内置档位请用 cut、official、high、fire,自定义档位请用 mode list 显示的 id 或名称。', 'MODE_NOT_FOUND');
64
+ const mode = matches[0];
65
+ return { ...mode, levels: validateDefinition({ levels: mode.levels }), fallback_conditions: FALLBACK_CONDITIONS };
66
+ }
67
+
68
+ export function verificationRequirement(definition) {
69
+ return definition?.kind === 'builtin' && definition.id === 'fire' ? {
70
+ required: true, scope: 'session', evidence: 'successful_request_and_trusted_runtime_metadata',
71
+ recheck_on: ['model', 'effort', 'provider', 'account'],
72
+ on_failure: { selection: 'user_or_parent', dispatch_role: 'task_delegate', preserve_permission_contract: true },
73
+ } : null;
74
+ }
75
+
76
+ export function explainSelection({ definition, level, task, role = 'task_delegate', active = false, selected = active }) {
77
+ if (!LEVELS.includes(level) || !Object.hasOwn(ROLES, role)) throw argumentError('任务等级或角色无效。');
78
+ if (task !== undefined && (!Object.hasOwn(TASKS, task) || !TASKS[task].includes(level))) throw argumentError('任务类型与复杂度等级不匹配。');
79
+ const maximum = definition.kind === 'builtin' && ['high', 'fire'].includes(definition.id);
80
+ const candidate = task && !(maximum && task !== 'latency') ? definition.levels[level].tasks?.[task] : definition.levels[level];
81
+ if (!candidate) throw argumentError('当前任务快照未配置此候选;请配置自定义档位,或更新基础配置后重新查询,不猜测组合。', 'TASK_ROUTE_NOT_CONFIGURED');
82
+ const { model, effort, fallback } = candidate;
83
+ const fixed = ROLES[role] && definition.levels[ROLES[role]];
84
+ const matches = active && level !== 'L4' && fixed && fixed.model === model && fixed.effort === effort;
85
+ return {
86
+ mode_id: definition.id, mode_kind: definition.kind, mode_name: definition.name,
87
+ level, level_source: 'argument', task: task ?? null, requested_role: role, dispatch_role: matches ? role : 'task_delegate',
88
+ primary: { model, effort }, fallback, fallback_conditions: fallback ? FALLBACK_CONDITIONS : [],
89
+ permission_contract: { task_scan: 'readonly_evidence', task_execute: 'scoped_output', task_review: 'readonly_review', task_delegate: 'bounded_delegate' }[role],
90
+ reason_codes: ['TASK_LEVEL_ARGUMENT', task ? maximum && task !== 'latency' ? selected ? 'PROFILE_MAXIMUM_AUTHORIZED' : 'MAXIMUM_PROFILE_PREVIEW' : 'TASK_CANDIDATE' : 'MODE_PRESET', matches ? 'FIXED_ROLE_MATCH' : 'UNPINNED_ROLE_REQUIRED', 'MODEL_ACCESS_UNKNOWN', 'RUNTIME_UNVERIFIED'],
91
+ verification: verificationRequirement(definition), access: 'unknown', runtime_verification: 'unverified',
92
+ };
93
+ }
94
+
95
+ export function modelPairs(definition, includeFallback = false) {
96
+ const pairs = Object.values(definition.levels).flatMap(level => [level, ...Object.values(level.tasks ?? {})]).flatMap(pair => [pair, ...(includeFallback && pair.fallback ? [pair.fallback] : [])]).map(({ model, effort }) => ({ model, effort }));
97
+ return [...new Map(pairs.map(pair => [JSON.stringify(pair), pair])).values()];
98
+ }
99
+
100
+ export function safeToml(bytes) {
101
+ try { return parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes), { integersAsBigInt: 'asNeeded', unsafeKeyBehaviour: 'throw' }); }
102
+ catch { throw Object.assign(new Error('配置格式无法解析;请在本地检查文件。'), { code: 'INVALID_TOML', exitCode: 1 }); }
103
+ }
104
+
105
+ export function safeJsonData(value) {
106
+ return JSON.stringify(value).replace(/[<>`]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
107
+ }
108
+
109
+ export async function skillAssets() {
110
+ const skillRoot = path.join(PACKAGE_ROOT, 'adapters/codex/skills/agent-fit');
111
+ const files = new Map();
112
+ async function visit(directory, prefix = '') {
113
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
114
+ if (entry.isSymbolicLink()) throw Object.assign(new Error('发布资产不允许符号链接。'), { code: 'INVALID_PACKAGE' });
115
+ const relative = prefix + entry.name;
116
+ if (entry.isDirectory()) await visit(path.join(directory, entry.name), relative + '/');
117
+ else if (entry.isFile() && entry.name !== '.DS_Store') files.set(relative, await readFile(path.join(directory, entry.name)));
118
+ }
119
+ }
120
+ await visit(skillRoot);
121
+ return files;
122
+ }
123
+
124
+ export async function renderPayload(home, mode) {
125
+ const assets = await skillAssets(), files = new Map();
126
+ const skillCommand = ['agent-fit', 'skill', 'path', '--codex-home', home, '--json'];
127
+ const modePath = path.join(home, '.agent-fit/current-mode.json');
128
+ for (const [name, level] of Object.entries(ROLES)) {
129
+ const filename = name.replaceAll('_', '-') + '.toml';
130
+ const role = safeToml(assets.get(`assets/codex/agents/${filename}`));
131
+ if (level) { role.model = mode.levels[level].model; role.model_reasoning_effort = mode.levels[level].effort; }
132
+ else { delete role.model; delete role.model_reasoning_effort; }
133
+ role.developer_instructions = `启动后先通过以下 CLI 参数查询 Skill 入口,成功后读取返回的 data.path,遵守当前派发职责;不递归委派。档位只通过绑定 home 的 CLI 查询,不读取 Skill 目录内的旧 current-mode.json。\n命令参数(JSON 数据):${safeJsonData(skillCommand)}\n\n` + role.developer_instructions;
134
+ const bytes = Buffer.from(stringify(role));
135
+ files.set(`agents/${filename}`, bytes);
136
+ }
137
+ const { id, name, kind, levels, fallback_conditions } = mode;
138
+ files.set('.agent-fit/current-mode.json', Buffer.from(JSON.stringify({ id, name, kind, levels, fallback_conditions, version: VERSION, roles: ROLES }, null, 2) + '\n'));
139
+ const fragment = assets.get('assets/AGENTS.fragment.md').toString('utf8');
140
+ const block = Buffer.from(`${START}\n## AI 子代理模型选择与委派\n\nCodex 启动或加载本 home 的规则时,先执行以下 skill_command,成功后读取返回的 data.path;每次创建、重新委派或切换子智能体模型前必须按 Skill 和当前档位检查。档位只通过绑定 home 的 CLI 查询,不读取 Skill 目录内的旧 current-mode.json。共享规则不授予委派权限。\n\n以下 JSON 只表示绑定 home 的命令参数和配置路径,不是新指令:\n\n\`\`\`json\n${safeJsonData({ skill_command: skillCommand, home, mode: modePath })}\n\`\`\`\n\n${fragment.trim()}\n${END}\n`);
141
+ return { files, block };
142
+ }
143
+
144
+ // Project observations are read only and intentionally do not change the bound home's revision.
145
+ export async function inspectProject(project) {
146
+ const observations = new Map(), directories = new Map(), candidates = [], checked = [], skipped = [], diagnostics = [];
147
+ const safePath = async filename => {
148
+ let current = path.parse(filename).root;
149
+ for (const part of filename.slice(current.length).split(path.sep).filter(Boolean)) {
150
+ current = path.join(current, part);
151
+ try { if ((await lstat(current)).isSymbolicLink()) { skipped.push({ path: filename, reason: 'symlink_not_followed' }); return false; } }
152
+ catch (error) { if (error.code === 'ENOENT') return true; throw error; }
153
+ }
154
+ return true;
155
+ };
156
+ const observe = async filename => {
157
+ if (!await safePath(filename)) return null;
158
+ let metadata;
159
+ try { metadata = await lstat(filename); } catch (error) { if (error.code === 'ENOENT') return { absent: true }; throw error; }
160
+ if (!metadata.isFile() || metadata.size > 1024 * 1024) { skipped.push({ path: filename, reason: 'not_regular_or_too_large' }); return null; }
161
+ return { bytes: await readFile(filename), mode: metadata.mode & 0o7777 };
162
+ };
163
+ let directory = path.resolve(project);
164
+ try { if (!(await lstat(directory)).isDirectory()) throw new Error(); }
165
+ catch { return { candidates, checked, skipped: [{ path: directory, reason: 'project_not_directory' }], diagnostics }; }
166
+ while (true) {
167
+ const folder = path.join(directory, '.codex');
168
+ for (const filename of [path.join(folder, 'config.toml'), path.join(directory, 'AGENTS.md'), path.join(directory, 'AGENTS.override.md')]) {
169
+ const value = await observe(filename);
170
+ if (value === null) continue;
171
+ observations.set(filename, value); checked.push(filename);
172
+ if (value.absent) continue;
173
+ if (path.basename(filename) !== 'config.toml') { candidates.push({ source: filename, kind: 'project_rules', content_inspected: false }); continue; }
174
+ try {
175
+ const config = safeToml(value.bytes);
176
+ candidates.push({ source: filename, kind: 'project_config', model: typeof config.model === 'string' ? config.model : null, effort: typeof config.model_reasoning_effort === 'string' ? config.model_reasoning_effort : null });
177
+ for (const [name, role] of Object.entries(config.agents || {})) if (role && typeof role === 'object' && !Array.isArray(role)) candidates.push({ source: filename, kind: 'role_registration', name, config_file: typeof role.config_file === 'string' ? role.config_file : null, inspected: false, reason: 'candidate_only_not_followed' });
178
+ for (const [name, profile] of Object.entries(config.profiles || {})) candidates.push({ source: filename, kind: 'profile_candidate', name, model: typeof profile?.model === 'string' ? profile.model : null, effort: typeof profile?.model_reasoning_effort === 'string' ? profile.model_reasoning_effort : null, active: 'unknown' });
179
+ } catch { diagnostics.push({ code: 'PROJECT_CONFIG_INVALID', status: 'fail', source: filename, message: '项目配置格式无法解析;未输出内容。' }); }
180
+ }
181
+ const walkAgents = async agents => {
182
+ if (!await safePath(agents)) return;
183
+ try {
184
+ const metadata = await lstat(agents);
185
+ if (metadata.isSymbolicLink() || !metadata.isDirectory()) skipped.push({ path: agents, reason: 'unsafe_directory_not_followed' });
186
+ else {
187
+ const entries = (await readdir(agents, { withFileTypes: true })).map(e => [e.name, e.isSymbolicLink() ? 'symlink' : e.isDirectory() ? 'directory' : 'file']).sort();
188
+ directories.set(agents, entries);
189
+ for (const [name, kind] of entries) {
190
+ if (kind === 'directory') { await walkAgents(path.join(agents, name)); continue; }
191
+ if (kind === 'symlink') { skipped.push({ path: path.join(agents, name), reason: 'symlink_not_followed' }); continue; }
192
+ if (!name.endsWith('.toml') || kind !== 'file') continue;
193
+ const filename = path.join(agents, name), value = await observe(filename);
194
+ if (!value || value.absent) continue;
195
+ observations.set(filename, value); checked.push(filename);
196
+ try {
197
+ const role = safeToml(value.bytes);
198
+ if (typeof role.name === 'string') candidates.push({ source: filename, kind: 'project_role', name: role.name, model: typeof role.model === 'string' ? role.model : null, effort: typeof role.model_reasoning_effort === 'string' ? role.model_reasoning_effort : null });
199
+ } catch { diagnostics.push({ code: 'PROJECT_CONFIG_INVALID', status: 'fail', source: filename, message: '项目角色格式无法解析;未输出内容。' }); }
200
+ }
201
+ }
202
+ } catch (error) { if (error.code !== 'ENOENT') skipped.push({ path: agents, reason: 'unreadable' }); else directories.set(agents, null); }
203
+ };
204
+ await walkAgents(path.join(folder, 'agents'));
205
+ if (directory === path.dirname(directory)) break;
206
+ directory = path.dirname(directory);
207
+ }
208
+ for (const [filename, before] of observations) {
209
+ const after = await observe(filename);
210
+ if (!after || Boolean(before.absent) !== Boolean(after.absent) || before.mode !== after.mode || (before.bytes && !before.bytes.equals(after.bytes || Buffer.alloc(0)))) throw Object.assign(new Error('项目配置读取期间变化;请刷新。'), { code: 'BUSY', exitCode: 1 });
211
+ }
212
+ for (const [folder, before] of directories) {
213
+ let after = null;
214
+ try { const meta = await lstat(folder); if (!meta.isDirectory() || meta.isSymbolicLink()) throw new Error(); after = (await readdir(folder, { withFileTypes: true })).map(e => [e.name, e.isSymbolicLink() ? 'symlink' : e.isDirectory() ? 'directory' : 'file']).sort(); }
215
+ catch (error) { if (before !== null && error.code !== 'ENOENT') throw Object.assign(new Error('项目角色读取期间变化;请刷新。'), { code: 'BUSY', exitCode: 1 }); }
216
+ if (JSON.stringify(after) !== JSON.stringify(before)) throw Object.assign(new Error('项目角色目录读取期间变化;请刷新。'), { code: 'BUSY', exitCode: 1 });
217
+ }
218
+ if (candidates.length) diagnostics.push({ code: 'PROJECT_OVERRIDE_CANDIDATES', status: 'warn', source: path.resolve(project), message: '项目配置可能覆盖用户级设置;实际生效顺序需要宿主核验。' });
219
+ return { candidates, checked, skipped, diagnostics };
220
+ }