@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
package/lib/install.mjs
ADDED
|
@@ -0,0 +1,733 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import { constants, realpathSync, lstatSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
6
|
+
import { parse as parseToml } from 'smol-toml';
|
|
7
|
+
import { VERSION, LEVELS, ROLES, BUILTINS, resolveDefinition, validateDefinition, renderPayload, verificationRequirement } from './codex.mjs';
|
|
8
|
+
import { SCOPE_FILE, scopeContext, validateScopeStore, scopeEntry, visibleModes, scopedSelection, assertUnreferenced } from './scopes.mjs';
|
|
9
|
+
|
|
10
|
+
const SKILL = 'skills/agent-fit';
|
|
11
|
+
const STATE_DIR = '.agent-fit';
|
|
12
|
+
const STATE = `${STATE_DIR}/state.json`;
|
|
13
|
+
const BASELINE = `${STATE_DIR}/restore.json`;
|
|
14
|
+
const CUSTOM = `${STATE_DIR}/custom-modes.json`;
|
|
15
|
+
const LOCK = `${STATE_DIR}/install.lock`;
|
|
16
|
+
const START = '<!-- agent-fit:start -->';
|
|
17
|
+
const END = '<!-- agent-fit:end -->';
|
|
18
|
+
const SHA = /^[a-f0-9]{64}$/;
|
|
19
|
+
const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;
|
|
20
|
+
const ROLE_PATHS = Object.keys(ROLES).map(name => `agents/${name.replaceAll('_', '-')}.toml`);
|
|
21
|
+
const json = value => Buffer.from(`${JSON.stringify(value, null, 2)}\n`);
|
|
22
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
23
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
24
|
+
const permission = value => Number.isInteger(value) && value >= 0 && value <= 0o777;
|
|
25
|
+
const safeText = (value, maximum = 200) => typeof value === 'string' && [...value].length <= maximum && !/[\p{Cc}\p{Cf}]/u.test(value) ? value : null;
|
|
26
|
+
const safeSource = value => value.replace(/[\p{Cc}\p{Cf}]/gu, char => `\\u${char.codePointAt(0).toString(16).padStart(4, '0')}`);
|
|
27
|
+
const equal = (left, right) => JSON.stringify(left) === JSON.stringify(right);
|
|
28
|
+
let testHooks = {};
|
|
29
|
+
// These hooks inject filesystem faults in isolated tests; no CLI exposes them.
|
|
30
|
+
export function setTestHooks(hooks = {}) { testHooks = hooks; }
|
|
31
|
+
|
|
32
|
+
export class DelegationError extends Error {
|
|
33
|
+
constructor(code, message, exitCode = 1, details = {}) {
|
|
34
|
+
super(message); this.name = 'DelegationError'; this.code = code; this.exitCode = exitCode; this.details = details;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function fail(code, message, exitCode = 1, details = {}) { throw new DelegationError(code, message, exitCode, details); }
|
|
38
|
+
function keys(value, required, optional = []) {
|
|
39
|
+
return object(value) && required.every(key => Object.hasOwn(value, key)) && Object.keys(value).every(key => [...required, ...optional].includes(key));
|
|
40
|
+
}
|
|
41
|
+
export function resolveHome(explicit) {
|
|
42
|
+
let value = explicit ?? process.env.CODEX_HOME ?? path.join(os.homedir(), '.codex');
|
|
43
|
+
if (typeof value !== 'string' || !value || /[\p{Cc}\p{Cf}]/u.test(value)) fail('INVALID_HOME', 'Codex home 必须是有效路径。', 2);
|
|
44
|
+
if (value === '~' || value.startsWith('~/')) value = path.join(os.homedir(), value.slice(2));
|
|
45
|
+
const absolute = path.resolve(value);
|
|
46
|
+
let parent = path.dirname(absolute), suffix = [path.basename(absolute)];
|
|
47
|
+
while (parent !== path.dirname(parent)) {
|
|
48
|
+
try { lstatSync(parent); return path.join(realpathSync(parent), ...suffix); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
49
|
+
suffix.unshift(path.basename(parent)); parent = path.dirname(parent);
|
|
50
|
+
}
|
|
51
|
+
return path.join(parent, ...suffix);
|
|
52
|
+
}
|
|
53
|
+
function owned(relative) {
|
|
54
|
+
if (typeof relative !== 'string' || !relative || relative.includes('\\') || /[\p{Cc}\p{Cf}]/u.test(relative) || relative.split('/').some(part => !part || part === '.' || part === '..')) return false;
|
|
55
|
+
return relative === CUSTOM || relative === SCOPE_FILE || ROLE_PATHS.includes(relative) || relative.startsWith(`${SKILL}/`) && !relative.slice(SKILL.length + 1).split('/').some(part => part.startsWith('.'));
|
|
56
|
+
}
|
|
57
|
+
function ownedDirectory(relative) {
|
|
58
|
+
return ['agents', 'skills', SKILL, STATE_DIR].includes(relative) || relative.startsWith(`${SKILL}/`) && owned(`${relative}/entry`);
|
|
59
|
+
}
|
|
60
|
+
async function statOrNull(target) {
|
|
61
|
+
try { return await fs.lstat(target); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
62
|
+
}
|
|
63
|
+
export async function checkPath(home, relative = '') {
|
|
64
|
+
const target = relative ? path.join(home, relative) : home;
|
|
65
|
+
if (relative && (path.isAbsolute(relative) || path.relative(home, target).startsWith('..'))) fail('UNSAFE_PATH', '目标路径超出受管理范围。');
|
|
66
|
+
const parsed = path.parse(target);
|
|
67
|
+
let current = parsed.root;
|
|
68
|
+
for (const part of target.slice(parsed.root.length).split(path.sep).filter(Boolean)) {
|
|
69
|
+
current = path.join(current, part);
|
|
70
|
+
const metadata = await statOrNull(current);
|
|
71
|
+
if (metadata?.isSymbolicLink()) fail('UNSAFE_PATH', `不读写符号链接路径:${current}`);
|
|
72
|
+
if (metadata && current !== target && !metadata.isDirectory()) fail('UNSAFE_PATH', `路径父级不是目录:${current}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async function observe(home, relative, directory = false, ignoreLock = false) {
|
|
76
|
+
await checkPath(home, relative);
|
|
77
|
+
const target = relative ? path.join(home, relative) : home;
|
|
78
|
+
const metadata = await statOrNull(target);
|
|
79
|
+
if (!metadata) return { kind: 'missing', mode: null, bytes: null, entries: null };
|
|
80
|
+
if (metadata.mode & 0o7000) fail('UNSAFE_PERMISSIONS', `路径含特殊权限位:${target}`);
|
|
81
|
+
if (directory) {
|
|
82
|
+
if (!metadata.isDirectory()) fail('UNSAFE_PATH', `目标不是普通目录:${target}`);
|
|
83
|
+
const entries = (await fs.readdir(target, { withFileTypes: true })).filter(entry => !(relative === '' && entry.name === '.agent-fit-checks') && !(ignoreLock && relative === STATE_DIR && entry.name === 'install.lock')).map(entry => [entry.name, entry.isSymbolicLink() ? 'symlink' : entry.isDirectory() ? 'directory' : entry.isFile() ? 'file' : 'special']).sort((a, b) => a[0].localeCompare(b[0]));
|
|
84
|
+
return { kind: 'directory', mode: metadata.mode & 0o777, bytes: null, entries };
|
|
85
|
+
}
|
|
86
|
+
if (!metadata.isFile()) fail('UNSAFE_PATH', `目标不是普通文件:${target}`);
|
|
87
|
+
const handle = await fs.open(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
88
|
+
try {
|
|
89
|
+
const opened = await handle.stat();
|
|
90
|
+
if (!opened.isFile() || opened.mode & 0o7000) fail('UNSAFE_PATH', `目标不是安全普通文件:${target}`);
|
|
91
|
+
return { kind: 'file', mode: opened.mode & 0o777, bytes: await handle.readFile(), entries: null };
|
|
92
|
+
} finally { await handle.close(); }
|
|
93
|
+
}
|
|
94
|
+
function stamp(observation) {
|
|
95
|
+
return { kind: observation.kind, mode: observation.mode, sha256: observation.bytes === null ? null : hash(observation.bytes), entries: observation.entries };
|
|
96
|
+
}
|
|
97
|
+
function decode(bytes, code = 'CONFIG_INVALID', message = '配置无法解析;未输出原始内容。') {
|
|
98
|
+
try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { fail(code, message); }
|
|
99
|
+
}
|
|
100
|
+
function parseJson(bytes, code, message) {
|
|
101
|
+
try {
|
|
102
|
+
const text = decode(bytes, code, message), value = JSON.parse(text), stack = [];
|
|
103
|
+
for (let index = 0; index < text.length; index++) {
|
|
104
|
+
const char = text[index];
|
|
105
|
+
if (char === '{' || char === '[') stack.push({ object: char === '{', key: char === '{', names: new Set() });
|
|
106
|
+
else if (char === '}' || char === ']') stack.pop();
|
|
107
|
+
else if (char === ',' && stack.at(-1)?.object) stack.at(-1).key = true;
|
|
108
|
+
else if (char === '"') {
|
|
109
|
+
const begin = index++;
|
|
110
|
+
while (index < text.length && text[index] !== '"') { if (text[index] === '\\') index++; index++; }
|
|
111
|
+
const current = stack.at(-1);
|
|
112
|
+
if (current?.object && current.key) {
|
|
113
|
+
const name = JSON.parse(text.slice(begin, index + 1));
|
|
114
|
+
if (current.names.has(name)) fail(code, message);
|
|
115
|
+
current.names.add(name); current.key = false;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return value;
|
|
120
|
+
} catch (error) { if (error instanceof DelegationError) throw error; fail(code, message); }
|
|
121
|
+
}
|
|
122
|
+
function parseConfig(bytes, source) {
|
|
123
|
+
if (bytes === null) return {};
|
|
124
|
+
try { return parseToml(decode(bytes), { integersAsBigInt: 'asNeeded', unsafeKeyBehaviour: 'throw' }); } catch { fail('CONFIG_INVALID', `配置无法解析:${source};未输出原始内容。`); }
|
|
125
|
+
}
|
|
126
|
+
function extractRules(bytes) {
|
|
127
|
+
if (bytes === null) return null;
|
|
128
|
+
const text = decode(bytes, 'RULES_INVALID', 'AGENTS.md 不是有效 UTF-8;未修改规则。');
|
|
129
|
+
const matches = [...text.matchAll(/^<!-- agent-fit:start -->\n[\s\S]*?^<!-- agent-fit:end -->(?:\n|$)/gm)];
|
|
130
|
+
if (text.split(START).length - 1 !== matches.length || text.split(END).length - 1 !== matches.length || matches.length > 1) fail('RULES_INVALID', 'AGENTS.md 的受管理标记不完整或重复。');
|
|
131
|
+
if (!matches.length) return null;
|
|
132
|
+
const match = matches[0];
|
|
133
|
+
return { before: Buffer.from(text.slice(0, match.index)), block: Buffer.from(match[0]), after: Buffer.from(text.slice(match.index + match[0].length)) };
|
|
134
|
+
}
|
|
135
|
+
function normalizeName(name) {
|
|
136
|
+
if (typeof name !== 'string') fail('INVALID_NAME', '档位名称必须是字符串。', 2);
|
|
137
|
+
const normalized = name.trim().normalize('NFC');
|
|
138
|
+
if (!normalized || [...normalized].length > 80 || /[\p{Cc}\p{Cf}]/u.test(normalized)) fail('INVALID_NAME', '档位名称须为 1–80 个字符,且不能包含控制字符。', 2);
|
|
139
|
+
return normalized;
|
|
140
|
+
}
|
|
141
|
+
function validateCustom(bytes) {
|
|
142
|
+
if (bytes === null) return [];
|
|
143
|
+
const value = parseJson(bytes, 'CUSTOM_MODES_INVALID', '自定义档位记录无效。');
|
|
144
|
+
if (!keys(value, ['schema_version', 'agent', 'modes']) || value.schema_version !== 1 || value.agent !== 'codex' || !Array.isArray(value.modes)) fail('CUSTOM_MODES_INVALID', '自定义档位记录无效。');
|
|
145
|
+
const names = new Set(BUILTINS.flatMap(mode => [mode.id, mode.name]));
|
|
146
|
+
return value.modes.map(mode => {
|
|
147
|
+
if (!keys(mode, ['id', 'name', 'levels'], ['kind']) || typeof mode.id !== 'string' || !mode.id.startsWith('custom-') || !UUID.test(mode.id.slice(7)) || mode.kind !== undefined && mode.kind !== 'custom') fail('CUSTOM_MODES_INVALID', '自定义档位记录无效。');
|
|
148
|
+
let name, levels;
|
|
149
|
+
try { name = normalizeName(mode.name); levels = validateDefinition({ levels: mode.levels }); } catch { fail('CUSTOM_MODES_INVALID', '自定义档位定义无效。'); }
|
|
150
|
+
if (name !== mode.name || name === mode.id || names.has(name) || names.has(mode.id)) fail('CUSTOM_MODES_INVALID', '自定义档位名称或内部 id 重复。');
|
|
151
|
+
names.add(name); names.add(mode.id);
|
|
152
|
+
return { id: mode.id, name, kind: 'custom', levels };
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
function validateState(bytes) {
|
|
156
|
+
if (bytes === null) return null;
|
|
157
|
+
const state = parseJson(bytes, 'STATE_INVALID', '安装记录无效或格式不支持。');
|
|
158
|
+
const fields = ['schema_version', 'agent', 'version', 'files', 'rules_sha256', 'mode', 'mode_kind', 'instance_id', 'file_modes', 'rules_mode', 'restoration'];
|
|
159
|
+
if (state?.schema_version !== 2 || state.agent !== 'codex' || !keys(state, fields) || !object(state.files) || !SHA.test(state.rules_sha256)) fail('STATE_INVALID', '安装记录无效或格式不支持。');
|
|
160
|
+
if (state.version !== VERSION) fail('VERSION_MISMATCH', '配置版本与当前工具不一致;仅支持当前配置版本。未修改任何文件。');
|
|
161
|
+
for (const [relative, digest] of Object.entries(state.files)) if (!owned(relative) || !SHA.test(digest)) fail('STATE_INVALID', '安装记录含非法路径或摘要。');
|
|
162
|
+
if (![...ROLE_PATHS, `${SKILL}/SKILL.md`, `${SKILL}/references/current-mode.json`].every(relative => Object.hasOwn(state.files, relative)) || typeof state.mode !== 'string' || !['builtin', 'custom'].includes(state.mode_kind) || !UUID.test(state.instance_id) || !object(state.file_modes) || !equal(Object.keys(state.files).sort(), Object.keys(state.file_modes).sort()) || !Object.values(state.file_modes).every(permission) || !permission(state.rules_mode)) fail('STATE_INVALID', '安装记录字段无效。');
|
|
163
|
+
const restore = state.restoration;
|
|
164
|
+
if (!keys(restore, ['status', 'baseline_sha256']) || restore.status !== 'available' || !SHA.test(restore.baseline_sha256)) fail('STATE_INVALID', '恢复状态字段无效。');
|
|
165
|
+
return state;
|
|
166
|
+
}
|
|
167
|
+
function base64(value, code = 'RESTORE_METADATA_INVALID') {
|
|
168
|
+
if (typeof value !== 'string' || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) fail(code, '恢复记录字节编码无效。');
|
|
169
|
+
const bytes = Buffer.from(value, 'base64');
|
|
170
|
+
if (bytes.toString('base64') !== value) fail(code, '恢复记录字节编码无效。');
|
|
171
|
+
return bytes;
|
|
172
|
+
}
|
|
173
|
+
function validateBaseline(bytes, state) {
|
|
174
|
+
if (bytes === null || hash(bytes) !== state.restoration.baseline_sha256) fail('RESTORE_METADATA_INVALID', '安装前恢复记录缺失或摘要不符。');
|
|
175
|
+
const baseline = parseJson(bytes, 'RESTORE_METADATA_INVALID', '安装前恢复记录无法解析。');
|
|
176
|
+
if (!keys(baseline, ['schema_version', 'agent', 'entries', 'rules', 'created_directories']) || baseline.schema_version !== 1 || baseline.agent !== 'codex' || !object(baseline.entries) || !Array.isArray(baseline.created_directories) || new Set(baseline.created_directories).size !== baseline.created_directories.length || !baseline.created_directories.every(ownedDirectory)) fail('RESTORE_METADATA_INVALID', '安装前恢复记录结构无效。');
|
|
177
|
+
for (const [relative, entry] of Object.entries(baseline.entries)) {
|
|
178
|
+
if (!owned(relative)) fail('RESTORE_METADATA_INVALID', '恢复记录路径不在白名单中。');
|
|
179
|
+
if (entry !== null && (!keys(entry, ['bytes_base64', 'sha256', 'mode']) || !permission(entry.mode) || !SHA.test(entry.sha256) || hash(base64(entry.bytes_base64)) !== entry.sha256)) fail('RESTORE_METADATA_INVALID', '恢复记录条目无效。');
|
|
180
|
+
}
|
|
181
|
+
const expected = Object.keys(state.files).sort();
|
|
182
|
+
if (!equal(Object.keys(baseline.entries).sort(), expected)) fail('RESTORE_METADATA_INVALID', '恢复记录与当前管理文件不对应。');
|
|
183
|
+
const rules = baseline.rules;
|
|
184
|
+
if (!keys(rules, ['existed', 'mode', 'sha256', 'original_block_base64', 'separator_base64', 'original_prefix_sha256']) || typeof rules.existed !== 'boolean' || (rules.existed ? !permission(rules.mode) || !SHA.test(rules.sha256) : rules.mode !== null || rules.sha256 !== null) || !SHA.test(rules.original_prefix_sha256)) fail('RESTORE_METADATA_INVALID', '恢复规则记录无效。');
|
|
185
|
+
const separator = base64(rules.separator_base64);
|
|
186
|
+
if (![0, 1, 2].includes(separator.length) || [...separator].some(value => value !== 10)) fail('RESTORE_METADATA_INVALID', '恢复规则分隔字节无效。');
|
|
187
|
+
if (rules.original_block_base64 !== null) {
|
|
188
|
+
const block = base64(rules.original_block_base64);
|
|
189
|
+
const found = extractRules(block);
|
|
190
|
+
if (!rules.existed || !found || found.before.length || found.after.length || separator.length) fail('RESTORE_METADATA_INVALID', '原管理区块记录无效。');
|
|
191
|
+
}
|
|
192
|
+
return baseline;
|
|
193
|
+
}
|
|
194
|
+
function diagnostic(code, status, source, message, remedy = ['status', '--details']) { return { code, status, source: safeSource(source), message: safeSource(message), remedy }; }
|
|
195
|
+
|
|
196
|
+
async function lockExists(home) {
|
|
197
|
+
await checkPath(home, STATE_DIR);
|
|
198
|
+
return (await statOrNull(path.join(home, LOCK))) !== null;
|
|
199
|
+
}
|
|
200
|
+
async function collect(home, { ignoreLock = false } = {}) {
|
|
201
|
+
if (!ignoreLock && await lockExists(home)) fail('BUSY', '配置写入锁存在;请等待写入完成后重试。');
|
|
202
|
+
const observedFiles = new Map(), observedDirectories = new Map();
|
|
203
|
+
const file = async relative => { if (!observedFiles.has(relative)) observedFiles.set(relative, await observe(home, relative)); return observedFiles.get(relative); };
|
|
204
|
+
const directory = async relative => { if (!observedDirectories.has(relative)) observedDirectories.set(relative, await observe(home, relative, true, ignoreLock)); return observedDirectories.get(relative); };
|
|
205
|
+
await directory(''); await directory(STATE_DIR); await directory('agents'); await directory('skills');
|
|
206
|
+
for (const relative of [STATE, BASELINE, CUSTOM, SCOPE_FILE, 'AGENTS.md', 'AGENTS.override.md', 'config.toml', ...ROLE_PATHS]) await file(relative);
|
|
207
|
+
const state = validateState((await file(STATE)).bytes);
|
|
208
|
+
const customModes = validateCustom((await file(CUSTOM)).bytes);
|
|
209
|
+
let scopeStore;
|
|
210
|
+
try { const bytes = (await file(SCOPE_FILE)).bytes; scopeStore = validateScopeStore(bytes === null ? null : parseJson(bytes, 'SCOPE_CONFIG_INVALID', '作用域配置无法解析。')); }
|
|
211
|
+
catch { fail('SCOPE_CONFIG_INVALID', '作用域配置格式或版本无效;未回退到其他档位。'); }
|
|
212
|
+
await file(`${SKILL}/references/current-mode.json`);
|
|
213
|
+
let mode = null;
|
|
214
|
+
if (state) {
|
|
215
|
+
try { mode = resolveDefinition(state.mode, customModes); } catch { fail('STATE_INVALID', '活动档位引用无效。'); }
|
|
216
|
+
if (mode.kind !== state.mode_kind) fail('STATE_INVALID', '活动档位类型记录无效。');
|
|
217
|
+
const installedBytes = (await file(`${SKILL}/references/current-mode.json`)).bytes;
|
|
218
|
+
if (installedBytes !== null) {
|
|
219
|
+
const installed = parseJson(installedBytes, 'STATE_INVALID', '已部署档位说明无效。');
|
|
220
|
+
if (!keys(installed, ['id', 'name', 'kind', 'levels', 'version', 'roles', 'fallback_conditions']) || installed.id !== state.mode || installed.kind !== state.mode_kind || safeText(installed.name) === null || [...installed.name].length > 80 || !Array.isArray(installed.fallback_conditions) || !installed.fallback_conditions.every(value => typeof value === 'string' && /^[A-Z_]+$/.test(value)) || !equal(installed.roles, ROLES)) fail('STATE_INVALID', '已部署档位说明无效。');
|
|
221
|
+
if (installed.version !== VERSION) fail('STATE_INVALID', '已部署档位说明的版本与当前工具不一致。');
|
|
222
|
+
let levels;
|
|
223
|
+
try { levels = validateDefinition({ levels: installed.levels }); } catch { fail('STATE_INVALID', '已部署档位等级定义无效。'); }
|
|
224
|
+
mode = { id: installed.id, name: installed.name, kind: installed.kind, levels, fallback_conditions: installed.fallback_conditions, definition_version: installed.version };
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const candidates = await renderPayload(home, mode ?? resolveDefinition('official'));
|
|
228
|
+
const paths = new Set([...candidates.files.keys(), ...Object.keys(state?.files ?? {})]);
|
|
229
|
+
for (const relative of paths) {
|
|
230
|
+
if (!owned(relative)) fail('STATE_INVALID', '管理路径不在白名单中。');
|
|
231
|
+
await file(relative);
|
|
232
|
+
let parent = path.posix.dirname(relative);
|
|
233
|
+
while (parent !== '.') { await directory(parent); parent = path.posix.dirname(parent); }
|
|
234
|
+
}
|
|
235
|
+
async function discoverRoles(relative) {
|
|
236
|
+
for (const [name, kind] of (await directory(relative)).entries ?? []) {
|
|
237
|
+
const candidate = `${relative}/${name}`;
|
|
238
|
+
if (kind === 'directory') await discoverRoles(candidate);
|
|
239
|
+
else if (kind === 'file' && name.endsWith('.toml')) await file(candidate);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
await discoverRoles('agents');
|
|
243
|
+
const diagnostics = [];
|
|
244
|
+
let baseline = null;
|
|
245
|
+
if (!state && (await file(BASELINE)).bytes !== null) fail('RESTORE_METADATA_INVALID', '恢复记录存在但安装状态缺失;请人工核对残留配置。');
|
|
246
|
+
if (!state && (await file(CUSTOM)).bytes !== null) fail('STATE_INVALID', '自定义档位记录存在但安装状态缺失。');
|
|
247
|
+
if (!state && (await file(SCOPE_FILE)).bytes !== null) fail('STATE_INVALID', '作用域配置存在但安装状态缺失。');
|
|
248
|
+
if (state) {
|
|
249
|
+
if ((await file(STATE)).mode !== 0o600) diagnostics.push(diagnostic('STATE_PERMISSIONS_DRIFT', 'fail', path.join(home, STATE), '安装状态文件权限变化。'));
|
|
250
|
+
for (const [relative, digest] of Object.entries(state.files)) {
|
|
251
|
+
const actual = await file(relative);
|
|
252
|
+
if (actual.bytes === null || hash(actual.bytes) !== digest || actual.mode !== state.file_modes[relative]) diagnostics.push(diagnostic('MANAGED_FILE_DRIFT', 'fail', path.join(home, relative), '受管理文件被修改、删除或权限变化。'));
|
|
253
|
+
}
|
|
254
|
+
const rules = extractRules((await file('AGENTS.md')).bytes);
|
|
255
|
+
if (!rules || hash(rules.block) !== state.rules_sha256 || (await file('AGENTS.md')).mode !== state.rules_mode) diagnostics.push(diagnostic('MANAGED_RULES_DRIFT', 'fail', path.join(home, 'AGENTS.md'), '受管理区块被修改、移除或权限变化。'));
|
|
256
|
+
if ((await file(BASELINE)).mode !== 0o600) fail('RESTORE_METADATA_INVALID', '安装前恢复记录权限变化。');
|
|
257
|
+
baseline = validateBaseline((await file(BASELINE)).bytes, state);
|
|
258
|
+
if ((await file(CUSTOM)).bytes !== null && !Object.hasOwn(state.files, CUSTOM)) fail('STATE_INVALID', '自定义档位记录未登记所有权。');
|
|
259
|
+
if ((await file(SCOPE_FILE)).bytes !== null && !Object.hasOwn(state.files, SCOPE_FILE)) fail('STATE_INVALID', '作用域配置未登记所有权。');
|
|
260
|
+
}
|
|
261
|
+
let config = {};
|
|
262
|
+
try {
|
|
263
|
+
config = parseConfig((await file('config.toml')).bytes, path.join(home, 'config.toml'));
|
|
264
|
+
if (config.agents !== undefined && !object(config.agents)) fail('CONFIG_INVALID', 'config.toml 的 agents 字段不是配置表。');
|
|
265
|
+
} catch { diagnostics.push(diagnostic('CONFIG_INVALID', 'fail', path.join(home, 'config.toml'), '既有配置无法解析或 agents 字段不是配置表。')); config = {}; }
|
|
266
|
+
const externalRoles = [];
|
|
267
|
+
for (const [relative, observation] of observedFiles) if (relative.startsWith('agents/') && relative.endsWith('.toml') && observation.bytes !== null) {
|
|
268
|
+
let role;
|
|
269
|
+
try { role = parseConfig(observation.bytes, path.join(home, relative)); } catch { diagnostics.push(diagnostic('ROLE_CONFIG_INVALID', 'fail', path.join(home, relative), '角色配置无法解析。')); continue; }
|
|
270
|
+
if (Object.hasOwn(ROLES, role.name) && !ROLE_PATHS.includes(relative)) diagnostics.push(diagnostic('ROLE_NAME_CONFLICT', 'fail', path.join(home, relative), '另一文件定义了本库同名角色。'));
|
|
271
|
+
if (!ROLE_PATHS.includes(relative)) externalRoles.push({ name: safeText(role.name), model: safeText(role.model), effort: safeText(role.model_reasoning_effort), source: safeSource(path.join(home, relative)) });
|
|
272
|
+
}
|
|
273
|
+
for (const name of Object.keys(ROLES)) if (Object.hasOwn(config.agents ?? {}, name)) {
|
|
274
|
+
const registration = config.agents[name];
|
|
275
|
+
let configured = object(registration) && safeText(registration.config_file, 4096);
|
|
276
|
+
if (configured?.startsWith('~/')) configured = path.join(os.homedir(), configured.slice(2));
|
|
277
|
+
if (!configured || resolveHome(path.resolve(home, configured)) !== path.join(home, `agents/${name.replaceAll('_', '-')}.toml`)) diagnostics.push(diagnostic('ROLE_NAME_CONFLICT', 'fail', path.join(home, 'config.toml'), `既有注册指向不同角色配置:${name}。`));
|
|
278
|
+
}
|
|
279
|
+
const roles = Object.entries(ROLES).map(([name, level]) => {
|
|
280
|
+
const relative = `agents/${name.replaceAll('_', '-')}.toml`, source = path.join(home, relative);
|
|
281
|
+
const bytes = observedFiles.get(relative).bytes;
|
|
282
|
+
let role = null;
|
|
283
|
+
try { if (bytes !== null) role = parseConfig(bytes, source); } catch {}
|
|
284
|
+
const expected = level && mode?.levels[level];
|
|
285
|
+
const matches = mode ? role !== null && role.name === name && (expected ? role.model === expected.model && role.model_reasoning_effort === expected.effort : !Object.hasOwn(role, 'model') && !Object.hasOwn(role, 'model_reasoning_effort')) : null;
|
|
286
|
+
if (state && !matches) diagnostics.push(diagnostic('ROLE_CONTRACT_MISMATCH', 'fail', source, `角色 ${name} 的名称、模型或推理强度与当前档位职责不一致;缺失或无效文件也不能满足职责。`));
|
|
287
|
+
return { name, task_level: level, source, managed: !!state?.files[relative], configured_name: safeText(role?.name), configured_model: safeText(role?.model), configured_effort: safeText(role?.model_reasoning_effort), expected_model: expected?.model ?? null, expected_effort: expected?.effort ?? null, matches_mode: matches, availability: { status: 'unknown', source: null }, fallback_candidates: expected?.fallback ? [expected.fallback] : [] };
|
|
288
|
+
});
|
|
289
|
+
const override = (await file('AGENTS.override.md')).bytes;
|
|
290
|
+
if (override && /[^\p{White_Space}]/u.test(override.toString('utf8'))) diagnostics.push(diagnostic('RULES_SHADOWED', 'warn', path.join(home, 'AGENTS.override.md'), '非空 AGENTS.override.md 遮蔽本库 AGENTS.md。'));
|
|
291
|
+
diagnostics.push(diagnostic('MODEL_ACCESS_UNKNOWN', 'unknown', 'static_configuration', '静态配置不证明账号调用权限。', ['models', 'check']));
|
|
292
|
+
diagnostics.push(diagnostic('RULES_LOAD_UNVERIFIED', 'unknown', 'static_configuration', '规则读取与运行模型生效需要宿主证据。'));
|
|
293
|
+
const snapshot = { home, state, mode, customModes, scopeStore, baseline, observedFiles, observedDirectories, diagnostics, config, externalRoles, roles, payload: candidates };
|
|
294
|
+
snapshot.configuration_revision = revision(snapshot);
|
|
295
|
+
return snapshot;
|
|
296
|
+
}
|
|
297
|
+
function revision(snapshot) {
|
|
298
|
+
return hash(json({ instance: snapshot.state?.instance_id ?? 'not_installed', files: [...snapshot.observedFiles].sort(([a], [b]) => a.localeCompare(b)).map(([name, value]) => [name, stamp(value)]), directories: [...snapshot.observedDirectories].sort(([a], [b]) => a.localeCompare(b)).map(([name, value]) => [name, stamp(value)]) }));
|
|
299
|
+
}
|
|
300
|
+
async function stillObserved(snapshot, ignoreLock = false) {
|
|
301
|
+
if (!ignoreLock && await lockExists(snapshot.home)) return false;
|
|
302
|
+
for (const [relative, original] of snapshot.observedFiles) if (!equal(stamp(original), stamp(await observe(snapshot.home, relative)))) return false;
|
|
303
|
+
for (const [relative, original] of snapshot.observedDirectories) if (!equal(stamp(original), stamp(await observe(snapshot.home, relative, true, ignoreLock)))) return false;
|
|
304
|
+
return true;
|
|
305
|
+
}
|
|
306
|
+
export async function readSnapshot(home, options = {}) {
|
|
307
|
+
home = resolveHome(home);
|
|
308
|
+
try {
|
|
309
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
310
|
+
const snapshot = await collect(home, options);
|
|
311
|
+
await testHooks.afterSnapshotRead?.(snapshot, attempt);
|
|
312
|
+
if (await stillObserved(snapshot, options.ignoreLock)) return snapshot;
|
|
313
|
+
}
|
|
314
|
+
fail('BUSY', '配置读取期间持续变化;请刷新后重试。');
|
|
315
|
+
} catch (error) {
|
|
316
|
+
if (error instanceof DelegationError) throw error;
|
|
317
|
+
fail('READ_FAILED', '无法安全读取配置;请检查路径、权限或文件格式。');
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
function requireClean(snapshot, restore = false) {
|
|
321
|
+
const failures = snapshot.diagnostics.filter(value => value.status === 'fail' && (!restore || ['MANAGED_FILE_DRIFT', 'MANAGED_RULES_DRIFT', 'STATE_PERMISSIONS_DRIFT'].includes(value.code)));
|
|
322
|
+
if (failures.length) fail(restore ? 'RESTORE_CONFLICT' : failures[0].code, restore ? '受管理内容存在冲突,未恢复任何文件。' : '受管理内容存在冲突,未覆盖任何文件。', 1, { paths: failures.map(value => value.source) });
|
|
323
|
+
}
|
|
324
|
+
function requireRevision(snapshot, expected) {
|
|
325
|
+
if (expected !== undefined && expected !== snapshot.configuration_revision) fail('CONFIG_CHANGED', '配置已改变;请刷新后重新检查草稿。');
|
|
326
|
+
}
|
|
327
|
+
function restart(reason, restore = false, restartRequired = false) {
|
|
328
|
+
const messages = {
|
|
329
|
+
deployment_changed: restore ? '原配置已恢复,请重启 Codex 后使用原委派规则。' : '配置已写入,请重启 Codex 后使用新委派规则。',
|
|
330
|
+
definition_only: '档位定义已保存,尚未应用。', no_change: '无配置变化,无需重启 Codex。',
|
|
331
|
+
routing_changed: '档位配置已更新,无需重启 Codex;后续新任务读取新配置,全局角色在下一轮加载,已开始任务沿用原配置。',
|
|
332
|
+
preview: restartRequired ? restore ? '恢复预览未写入;实际恢复成功后请重启 Codex。' : '首次安装或基础规则更新的预览未写入;应用成功后请重启 Codex。' : '预览未写入;本次档位调整无需重启 Codex。',
|
|
333
|
+
not_applied: '配置未应用。', rolled_back: '配置未应用,已回退。', partial_or_unknown: '请核对残留配置并刷新状态;确认配置后重启 Codex。',
|
|
334
|
+
};
|
|
335
|
+
return { required: reason === 'deployment_changed' ? true : reason === 'partial_or_unknown' ? null : false, reason, message: messages[reason] };
|
|
336
|
+
}
|
|
337
|
+
function changeReport(plan, result, configurationStatus, after = null, reason) {
|
|
338
|
+
return { action: plan.action, agent: 'codex', home: plan.snapshot.home, scope: plan.scope ?? 'global', result, configuration_status: configurationStatus, changed_files: [...plan.changes.keys()], changes: [...plan.changes].map(([relative, change]) => ({ path: relative, action: change.after === null ? 'remove' : change.before.bytes === null ? 'create' : 'replace', permission_changed: change.after !== null && change.before.mode !== change.mode })), revision_before: plan.snapshot.configuration_revision, revision_after: after, mode: plan.mode ? { id: plan.mode.id, name: plan.mode.name, kind: plan.mode.kind } : null, custom_modes_removed: plan.action === 'restore' ? [...plan.snapshot.customModes, ...plan.snapshot.scopeStore.projects.flatMap(entry => entry.modes), ...plan.snapshot.scopeStore.sessions.flatMap(entry => entry.modes)].map(mode => mode.name) : [], warnings: plan.warnings ?? [], restart: restart(reason, plan.action === 'restore', plan.restartRequired), runtime_verification: 'unverified' };
|
|
339
|
+
}
|
|
340
|
+
async function directoryCreation(snapshot, relatives) {
|
|
341
|
+
const directories = new Set();
|
|
342
|
+
for (const relative of relatives) {
|
|
343
|
+
let parent = path.posix.dirname(relative);
|
|
344
|
+
while (parent !== '.') { directories.add(parent); parent = path.posix.dirname(parent); }
|
|
345
|
+
}
|
|
346
|
+
const missing = [];
|
|
347
|
+
for (const relative of [...directories].sort((a, b) => a.split('/').length - b.split('/').length || a.localeCompare(b))) if ((snapshot.observedDirectories.get(relative) ?? await observe(snapshot.home, relative, true)).kind === 'missing') missing.push(relative);
|
|
348
|
+
return missing;
|
|
349
|
+
}
|
|
350
|
+
function managedEntry(observation) {
|
|
351
|
+
return observation.bytes === null ? null : { bytes_base64: observation.bytes.toString('base64'), sha256: hash(observation.bytes), mode: observation.mode };
|
|
352
|
+
}
|
|
353
|
+
function mergeRules(original, block, state) {
|
|
354
|
+
const found = extractRules(original);
|
|
355
|
+
if (found) {
|
|
356
|
+
const expected = state?.rules_sha256 ?? hash(block);
|
|
357
|
+
if (hash(found.block) !== expected) fail('MANAGED_RULES_DRIFT', '既有受管理区块与记录不符。');
|
|
358
|
+
return { bytes: Buffer.concat([found.before, block, found.after]), separator: Buffer.alloc(0), found };
|
|
359
|
+
}
|
|
360
|
+
if (state) fail('MANAGED_RULES_DRIFT', '受管理规则区块已移除。');
|
|
361
|
+
let separator = '';
|
|
362
|
+
const text = original === null ? '' : decode(original);
|
|
363
|
+
if (text && !text.endsWith('\n')) separator += '\n';
|
|
364
|
+
if (text && !(text + separator).endsWith('\n\n')) separator += '\n';
|
|
365
|
+
return { bytes: Buffer.concat([original ?? Buffer.alloc(0), Buffer.from(separator), block]), separator: Buffer.from(separator), found: null };
|
|
366
|
+
}
|
|
367
|
+
function configuredLevels(definition, options) {
|
|
368
|
+
let levels;
|
|
369
|
+
if (options.definition !== undefined) {
|
|
370
|
+
if (['level', 'model', 'effort', 'fallbackModel', 'fallbackEffort', 'clearFallback'].some(key => options[key] !== undefined)) fail('INVALID_ARGUMENTS', '整表定义与单级配置参数不能混用。', 2);
|
|
371
|
+
if (json(options.definition).length > 65536) fail('DEFINITION_TOO_LARGE', '档位定义超过 64KiB。', 2);
|
|
372
|
+
levels = validateDefinition(options.definition);
|
|
373
|
+
} else {
|
|
374
|
+
if (!LEVELS.includes(options.level)) fail('INVALID_LEVEL', '请选择 L1–L4 中的一个任务等级。', 2);
|
|
375
|
+
if ((options.model === undefined) !== (options.effort === undefined) || (options.fallbackModel === undefined) !== (options.fallbackEffort === undefined) || options.clearFallback && options.fallbackModel !== undefined) fail('INVALID_ARGUMENTS', '主模型、备用模型与 effort 必须成对指定。', 2);
|
|
376
|
+
levels = structuredClone(definition.levels);
|
|
377
|
+
const current = levels[options.level];
|
|
378
|
+
const primaryChanged = options.model !== undefined && (options.model !== current.model || options.effort !== current.effort);
|
|
379
|
+
levels[options.level] = { ...current, model: options.model ?? current.model, effort: options.effort ?? current.effort, fallback: options.fallbackModel !== undefined ? { model: options.fallbackModel, effort: options.fallbackEffort } : options.clearFallback || primaryChanged ? null : current.fallback };
|
|
380
|
+
levels = validateDefinition({ levels });
|
|
381
|
+
}
|
|
382
|
+
return levels;
|
|
383
|
+
}
|
|
384
|
+
async function buildPlan(snapshot, action, options) {
|
|
385
|
+
requireRevision(snapshot, options.expectRevision);
|
|
386
|
+
requireClean(snapshot, action === 'restore');
|
|
387
|
+
const { state, home } = snapshot;
|
|
388
|
+
if (action !== 'setup' && action !== 'restore' && !state) fail('NOT_INSTALLED', '请先执行 setup 配置 Codex。');
|
|
389
|
+
if (!['setup', 'set', 'clear', 'delete', 'create', 'configure', 'restore'].includes(action)) fail('INVALID_ACTION', '不支持的写入动作。', 2);
|
|
390
|
+
const changes = new Map();
|
|
391
|
+
const plan = { snapshot, action, changes, mode: snapshot.mode, warnings: [], deploymentChanged: false, restartRequired: false, cleanupDirectories: [] };
|
|
392
|
+
const add = async (relative, after, mode) => {
|
|
393
|
+
const before = snapshot.observedFiles.get(relative) ?? await observe(home, relative);
|
|
394
|
+
const afterMode = after === null ? null : mode ?? before.mode ?? 0o600;
|
|
395
|
+
if (before.bytes?.equals(after ?? Buffer.alloc(0)) && after !== null && before.mode === afterMode || before.bytes === null && after === null) return;
|
|
396
|
+
changes.set(relative, { before, after, mode: afterMode });
|
|
397
|
+
};
|
|
398
|
+
if (action === 'restore') {
|
|
399
|
+
plan.mode = null;
|
|
400
|
+
if (!state) return plan;
|
|
401
|
+
for (const [relative, entry] of Object.entries(snapshot.baseline.entries)) await add(relative, entry === null ? null : base64(entry.bytes_base64), entry?.mode);
|
|
402
|
+
const current = snapshot.observedFiles.get('AGENTS.md');
|
|
403
|
+
const found = extractRules(current.bytes);
|
|
404
|
+
const rules = snapshot.baseline.rules;
|
|
405
|
+
let restored;
|
|
406
|
+
if (rules.original_block_base64 !== null) restored = Buffer.concat([found.before, base64(rules.original_block_base64), found.after]);
|
|
407
|
+
else {
|
|
408
|
+
const separator = base64(rules.separator_base64);
|
|
409
|
+
let before = found.before;
|
|
410
|
+
const prefix = separator.length && before.subarray(-separator.length).equals(separator) ? before.subarray(0, -separator.length) : before;
|
|
411
|
+
const outside = Buffer.concat([prefix, found.after]);
|
|
412
|
+
if (hash(prefix) === rules.original_prefix_sha256 && (rules.existed ? hash(outside) === rules.sha256 : outside.length === 0)) before = prefix;
|
|
413
|
+
else if (separator.length) plan.warnings.push('标记外正文已改变,保留无法确认归属的分隔空白。');
|
|
414
|
+
restored = Buffer.concat([before, found.after]);
|
|
415
|
+
}
|
|
416
|
+
await add('AGENTS.md', !rules.existed && !restored.length ? null : restored, rules.existed ? rules.mode : current.mode);
|
|
417
|
+
await add(BASELINE, null); await add(STATE, null);
|
|
418
|
+
plan.cleanupDirectories = snapshot.baseline.created_directories;
|
|
419
|
+
plan.createdDirectories = await directoryCreation(snapshot, [...changes].filter(([, change]) => change.after !== null).map(([relative]) => relative));
|
|
420
|
+
plan.deploymentChanged = changes.size > 0;
|
|
421
|
+
plan.restartRequired = plan.deploymentChanged;
|
|
422
|
+
return plan;
|
|
423
|
+
}
|
|
424
|
+
const context = await scopeContext(options);
|
|
425
|
+
if (action === 'setup' && context.scope !== 'global') fail('INVALID_ARGUMENT', 'setup 只安装全局基础设施;局部选择请使用 mode set。', 2);
|
|
426
|
+
plan.scope = context.scope;
|
|
427
|
+
const scopeStore = structuredClone(snapshot.scopeStore);
|
|
428
|
+
const local = context.scope !== 'global';
|
|
429
|
+
if (local) {
|
|
430
|
+
if (action === 'clear' && !scopeEntry(scopeStore, context)) { plan.mode = scopedSelection(snapshot, context).definition; return plan; }
|
|
431
|
+
const entry = scopeEntry(scopeStore, context, true);
|
|
432
|
+
const available = visibleModes(snapshot, context);
|
|
433
|
+
if (action === 'set') entry.selection = resolveDefinition(options.mode, available).id;
|
|
434
|
+
if (action === 'clear') entry.selection = null;
|
|
435
|
+
if (action === 'create') {
|
|
436
|
+
const name = normalizeName(options.name);
|
|
437
|
+
if ([...BUILTINS, ...available].some(mode => [mode.name, mode.id].includes(name))) fail('NAME_CONFLICT', '可见档位中已有此名称或 ID。', 2);
|
|
438
|
+
const source = scopedSelection(snapshot, context, options.from ?? 'official').definition;
|
|
439
|
+
const definition = { id: `custom-${randomUUID()}`, name, kind: 'custom', levels: structuredClone(source.levels) };
|
|
440
|
+
entry.modes.push(definition); plan.created_mode = definition;
|
|
441
|
+
}
|
|
442
|
+
if (action === 'configure') {
|
|
443
|
+
const source = resolveDefinition(options.mode, available);
|
|
444
|
+
if (source.kind !== 'custom') fail('BUILTIN_READ_ONLY', '内置档位不可修改;请先复制为自定义档位。', 2);
|
|
445
|
+
const levels = configuredLevels(source, options);
|
|
446
|
+
let definition = entry.modes.find(mode => mode.id === source.id);
|
|
447
|
+
if (!definition) {
|
|
448
|
+
let name = [...source.name].slice(0, 60).join('') + '(局部副本)';
|
|
449
|
+
for (let number = 2; [...BUILTINS, ...available].some(mode => mode.name === name); number++) name = [...source.name].slice(0, 55).join('') + `(局部副本 ${number})`;
|
|
450
|
+
definition = { id: `custom-${randomUUID()}`, name, kind: 'custom', levels };
|
|
451
|
+
entry.modes.push(definition); plan.created_mode = definition;
|
|
452
|
+
if (scopedSelection(snapshot, context).definition.id === source.id) entry.selection = definition.id;
|
|
453
|
+
} else definition.levels = levels;
|
|
454
|
+
}
|
|
455
|
+
if (action === 'delete') {
|
|
456
|
+
const definition = resolveDefinition(options.mode, available);
|
|
457
|
+
if (!entry.modes.some(mode => mode.id === definition.id)) fail('SCOPE_READ_ONLY', '只能删除当前作用域创建的自定义档位。', 2);
|
|
458
|
+
assertUnreferenced(snapshot, definition.id);
|
|
459
|
+
entry.modes = entry.modes.filter(mode => mode.id !== definition.id);
|
|
460
|
+
}
|
|
461
|
+
validateScopeStore(scopeStore);
|
|
462
|
+
plan.mode = scopedSelection({ ...snapshot, scopeStore }, context).definition;
|
|
463
|
+
}
|
|
464
|
+
let customModes = snapshot.customModes.map(mode => ({ ...mode, levels: structuredClone(mode.levels) }));
|
|
465
|
+
let desiredMode = snapshot.mode ? resolveDefinition(snapshot.mode.id, customModes) : resolveDefinition('official', customModes);
|
|
466
|
+
if (!local && (action === 'setup' && options.mode !== undefined || action === 'set')) desiredMode = resolveDefinition(options.mode, customModes);
|
|
467
|
+
if (!local && action === 'clear') desiredMode = resolveDefinition('official');
|
|
468
|
+
if (!local && action === 'delete') {
|
|
469
|
+
const definition = resolveDefinition(options.mode, customModes);
|
|
470
|
+
if (definition.kind !== 'custom') fail('BUILTIN_READ_ONLY', '内置档位不可删除。', 2);
|
|
471
|
+
assertUnreferenced(snapshot, definition.id);
|
|
472
|
+
customModes = customModes.filter(mode => mode.id !== definition.id);
|
|
473
|
+
}
|
|
474
|
+
if (!local && action === 'create') {
|
|
475
|
+
const name = normalizeName(options.name);
|
|
476
|
+
if ([...BUILTINS, ...customModes].some(mode => [mode.name, mode.id].includes(name))) fail('NAME_CONFLICT', '档位名称与内置命令、既有档位或内部 id 重复。', 2);
|
|
477
|
+
const source = scopedSelection(snapshot, context, options.from ?? 'official').definition;
|
|
478
|
+
const definition = { id: `custom-${randomUUID()}`, name, kind: 'custom', levels: structuredClone(source.levels) };
|
|
479
|
+
customModes.push(definition); plan.created_mode = definition;
|
|
480
|
+
}
|
|
481
|
+
if (!local && action === 'configure') {
|
|
482
|
+
const definition = resolveDefinition(options.mode, customModes);
|
|
483
|
+
if (definition.kind !== 'custom') fail('BUILTIN_READ_ONLY', '内置档位不可修改;请先复制为自定义档位。', 2);
|
|
484
|
+
const levels = configuredLevels(definition, options);
|
|
485
|
+
customModes = customModes.map(mode => mode.id === definition.id ? { ...mode, levels } : mode);
|
|
486
|
+
if (desiredMode.id === definition.id) desiredMode = resolveDefinition(definition.id, customModes);
|
|
487
|
+
}
|
|
488
|
+
const deploying = !local && (action === 'setup' || action === 'set' || action === 'clear' || action === 'configure' && desiredMode.id === resolveDefinition(options.mode, customModes).id);
|
|
489
|
+
if (deploying && snapshot.diagnostics.some(value => value.code === 'RULES_SHADOWED')) fail('RULES_SHADOWED', '非空 AGENTS.override.md 遮蔽本库规则;未写入部署配置。');
|
|
490
|
+
const payload = deploying ? await renderPayload(home, desiredMode) : snapshot.payload;
|
|
491
|
+
const files = new Map(payload.files);
|
|
492
|
+
if (!deploying) {
|
|
493
|
+
files.clear();
|
|
494
|
+
for (const relative of Object.keys(state.files)) files.set(relative, snapshot.observedFiles.get(relative).bytes);
|
|
495
|
+
}
|
|
496
|
+
if (customModes.length || snapshot.observedFiles.get(CUSTOM).bytes !== null) files.set(CUSTOM, json({ schema_version: 1, agent: 'codex', modes: customModes.map(({ id, name, levels }) => ({ id, name, levels })) }));
|
|
497
|
+
if (local || snapshot.observedFiles.get(SCOPE_FILE).bytes !== null) files.set(SCOPE_FILE, json(scopeStore));
|
|
498
|
+
const previous = state?.files ?? {};
|
|
499
|
+
for (const relative of [...new Set([...files.keys(), ...Object.keys(previous)])].sort()) {
|
|
500
|
+
if (!owned(relative)) fail('UNSAFE_PATH', '发布包含非法管理路径。');
|
|
501
|
+
const before = snapshot.observedFiles.get(relative) ?? await observe(home, relative);
|
|
502
|
+
const desired = files.get(relative) ?? null;
|
|
503
|
+
if (before.bytes !== null && !Object.hasOwn(previous, relative) && (!desired || !before.bytes.equals(desired))) fail('FILE_CONFLICT', `文件已有不同内容,未覆盖:${path.join(home, relative)}`);
|
|
504
|
+
await add(relative, desired);
|
|
505
|
+
}
|
|
506
|
+
const originalRules = snapshot.observedFiles.get('AGENTS.md');
|
|
507
|
+
const merged = deploying ? mergeRules(originalRules.bytes, payload.block, state) : { bytes: originalRules.bytes };
|
|
508
|
+
if (deploying) await add('AGENTS.md', merged.bytes);
|
|
509
|
+
const directories = await directoryCreation(snapshot, [...files.keys(), STATE, BASELINE, 'AGENTS.md']);
|
|
510
|
+
let baseline = snapshot.baseline ? structuredClone(snapshot.baseline) : null;
|
|
511
|
+
if (!state) {
|
|
512
|
+
baseline = { schema_version: 1, agent: 'codex', entries: {}, rules: { existed: originalRules.bytes !== null, mode: originalRules.mode, sha256: originalRules.bytes === null ? null : hash(originalRules.bytes), original_block_base64: merged.found?.block.toString('base64') ?? null, separator_base64: merged.separator.toString('base64'), original_prefix_sha256: hash(merged.found?.before ?? originalRules.bytes ?? Buffer.alloc(0)) }, created_directories: directories };
|
|
513
|
+
}
|
|
514
|
+
for (const relative of files.keys()) if (!Object.hasOwn(baseline.entries, relative)) baseline.entries[relative] = managedEntry(snapshot.observedFiles.get(relative) ?? await observe(home, relative));
|
|
515
|
+
baseline.created_directories = [...new Set([...baseline.created_directories, ...directories])];
|
|
516
|
+
await add(BASELINE, json(baseline), 0o600);
|
|
517
|
+
const stateBytes = json({ schema_version: 2, agent: 'codex', version: VERSION, mode: desiredMode.id, mode_kind: desiredMode.kind, instance_id: state?.instance_id ?? randomUUID(), files: Object.fromEntries([...files].sort(([a], [b]) => a.localeCompare(b)).map(([relative, bytes]) => [relative, hash(bytes)])), file_modes: Object.fromEntries([...files.keys()].sort().map(relative => [relative, changes.get(relative)?.mode ?? snapshot.observedFiles.get(relative)?.mode ?? 0o600])), rules_mode: changes.get('AGENTS.md')?.mode ?? originalRules.mode ?? 0o600, rules_sha256: deploying ? hash(payload.block) : state.rules_sha256, restoration: { status: 'available', baseline_sha256: hash(json(baseline)) } });
|
|
518
|
+
await add(STATE, stateBytes, 0o600);
|
|
519
|
+
const ordered = new Map();
|
|
520
|
+
if (changes.has(BASELINE)) ordered.set(BASELINE, changes.get(BASELINE));
|
|
521
|
+
for (const [relative, change] of changes) if (![BASELINE, STATE].includes(relative)) ordered.set(relative, change);
|
|
522
|
+
if (changes.has(STATE)) ordered.set(STATE, changes.get(STATE));
|
|
523
|
+
plan.changes = ordered; if (!local) plan.mode = desiredMode;
|
|
524
|
+
plan.deploymentChanged = [...ordered.keys()].some(relative => ![BASELINE, STATE, CUSTOM, SCOPE_FILE].includes(relative));
|
|
525
|
+
// Compare against today's templates rendered with the old mode, so model/effort changes alone do not require a restart.
|
|
526
|
+
plan.restartRequired = !state || deploying && [...ordered].some(([relative, change]) => {
|
|
527
|
+
if ([BASELINE, STATE, CUSTOM, SCOPE_FILE, `${SKILL}/references/current-mode.json`].includes(relative)) return false;
|
|
528
|
+
const expected = snapshot.payload.files.get(relative);
|
|
529
|
+
return !expected || !change.before.bytes?.equals(expected);
|
|
530
|
+
});
|
|
531
|
+
plan.createdDirectories = directories;
|
|
532
|
+
|
|
533
|
+
return plan;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async function atomicWrite(home, relative, bytes, mode, expected) {
|
|
537
|
+
await checkPath(home, relative);
|
|
538
|
+
const target = path.join(home, relative);
|
|
539
|
+
if (bytes === null) {
|
|
540
|
+
await testHooks.beforeAtomicCommit?.(relative, bytes);
|
|
541
|
+
if (expected && !equal(stamp(await observe(home, relative)), stamp(expected))) fail('CONFIG_CHANGED', `删除前文件发生变化:${safeSource(target)}`);
|
|
542
|
+
await fs.unlink(target); return;
|
|
543
|
+
}
|
|
544
|
+
await checkPath(home, relative);
|
|
545
|
+
const temporary = path.join(path.dirname(target), `.agent-fit-${randomUUID()}.tmp`);
|
|
546
|
+
let handle, committed = false;
|
|
547
|
+
try {
|
|
548
|
+
handle = await fs.open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), mode);
|
|
549
|
+
await handle.writeFile(bytes); await handle.chmod(mode); await handle.sync(); await handle.close(); handle = null;
|
|
550
|
+
await testHooks.beforeAtomicCommit?.(relative, bytes);
|
|
551
|
+
await checkPath(home, relative);
|
|
552
|
+
if (expected && !equal(stamp(await observe(home, relative)), stamp(expected))) fail('CONFIG_CHANGED', `原子替换前文件发生变化:${safeSource(target)}`);
|
|
553
|
+
await fs.rename(temporary, target); committed = true;
|
|
554
|
+
try { const directory = await fs.open(path.dirname(target), constants.O_RDONLY); try { await directory.sync(); } finally { await directory.close(); } } catch (error) { if (!['EINVAL', 'EISDIR', 'EPERM', 'ENOTSUP'].includes(error.code)) throw error; }
|
|
555
|
+
} catch (error) { error.atomicApplied = committed; throw error; } finally { await handle?.close(); await fs.unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
|
|
556
|
+
}
|
|
557
|
+
async function cleanDirectories(home, directories) {
|
|
558
|
+
for (const relative of [...new Set(directories)].sort((a, b) => b.split('/').length - a.split('/').length || b.localeCompare(a))) {
|
|
559
|
+
if (!ownedDirectory(relative)) continue;
|
|
560
|
+
try { await checkPath(home, relative); await fs.rmdir(path.join(home, relative)); } catch (error) { if (!(error instanceof DelegationError) && !['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; }
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
function normalizedLocked(snapshot, original, created) {
|
|
564
|
+
const normalize = new Map(snapshot.observedDirectories);
|
|
565
|
+
for (const [relative, value] of normalize) {
|
|
566
|
+
if (created.includes(relative) && original.observedDirectories.get(relative)?.kind === 'missing') normalize.set(relative, { kind: 'missing', mode: null, bytes: null, entries: null });
|
|
567
|
+
else if (value.entries) normalize.set(relative, { ...value, entries: value.entries.filter(([name]) => !created.includes(relative ? `${relative}/${name}` : name)) });
|
|
568
|
+
}
|
|
569
|
+
const files = snapshot.observedFiles;
|
|
570
|
+
for (const [relative, value] of original.observedFiles) if (!equal(stamp(value), stamp(files.get(relative) ?? { kind: 'missing', mode: null, bytes: null, entries: null }))) return false;
|
|
571
|
+
for (const [relative, value] of original.observedDirectories) if (!equal(stamp(value), stamp(normalize.get(relative) ?? { kind: 'missing', mode: null, bytes: null, entries: null }))) return false;
|
|
572
|
+
return true;
|
|
573
|
+
}
|
|
574
|
+
export async function applyPlan(plan, options = {}) {
|
|
575
|
+
if (options.dryRun) {
|
|
576
|
+
await testHooks.beforePreview?.(plan);
|
|
577
|
+
if (!await stillObserved(plan.snapshot)) fail('CONFIG_CHANGED', '预览前配置已改变;请刷新后重试。');
|
|
578
|
+
requireRevision(plan.snapshot, options.expectRevision);
|
|
579
|
+
const report = changeReport(plan, 'preview', 'not_written', null, 'preview');
|
|
580
|
+
if (plan.created_mode) report.created_mode = { id: plan.created_mode.id, name: plan.created_mode.name, kind: plan.created_mode.kind };
|
|
581
|
+
return report;
|
|
582
|
+
}
|
|
583
|
+
if (!plan.changes.size) {
|
|
584
|
+
if (!await stillObserved(plan.snapshot)) fail('CONFIG_CHANGED', '配置已改变;请刷新后重试。');
|
|
585
|
+
return changeReport(plan, 'unchanged', 'unchanged', plan.snapshot.configuration_revision, 'no_change');
|
|
586
|
+
}
|
|
587
|
+
await testHooks.beforeLock?.(plan);
|
|
588
|
+
const home = plan.snapshot.home;
|
|
589
|
+
const ownCreated = [];
|
|
590
|
+
let lockHandle, lockIdentity, ownsLock = false, canceled = false;
|
|
591
|
+
const applied = [];
|
|
592
|
+
const onSignal = () => { canceled = true; };
|
|
593
|
+
let report, pending;
|
|
594
|
+
const ownLock = async () => {
|
|
595
|
+
const actual = await statOrNull(path.join(home, LOCK));
|
|
596
|
+
return actual?.isFile() && actual.dev === lockIdentity?.dev && actual.ino === lockIdentity?.ino;
|
|
597
|
+
};
|
|
598
|
+
try {
|
|
599
|
+
try {
|
|
600
|
+
for (const relative of ['', STATE_DIR]) {
|
|
601
|
+
await checkPath(home, relative);
|
|
602
|
+
if ((await statOrNull(relative ? path.join(home, relative) : home)) === null) {
|
|
603
|
+
await fs.mkdir(relative ? path.join(home, relative) : home, { recursive: relative === '', mode: 0o700 }); ownCreated.push(relative);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
await checkPath(home, LOCK);
|
|
607
|
+
try { lockHandle = await fs.open(path.join(home, LOCK), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600); ownsLock = true; } catch (error) { if (error.code === 'EEXIST') fail('BUSY', '配置写入锁存在;未写入配置。'); throw error; }
|
|
608
|
+
lockIdentity = await lockHandle.stat(); await lockHandle.close(); lockHandle = null;
|
|
609
|
+
process.on('SIGINT', onSignal); process.on('SIGTERM', onSignal);
|
|
610
|
+
await testHooks.afterLock?.(plan);
|
|
611
|
+
const locked = await readSnapshot(home, { ignoreLock: true });
|
|
612
|
+
if (!normalizedLocked(locked, plan.snapshot, ownCreated)) fail('CONFIG_CHANGED', '锁内检测到配置或角色目录变化;未写入配置。');
|
|
613
|
+
requireRevision(plan.snapshot, options.expectRevision);
|
|
614
|
+
requireClean(locked, plan.action === 'restore');
|
|
615
|
+
for (const relative of plan.createdDirectories ?? []) {
|
|
616
|
+
if (ownCreated.includes(relative)) continue;
|
|
617
|
+
await checkPath(home, relative);
|
|
618
|
+
try { await fs.mkdir(path.join(home, relative), { mode: 0o700 }); ownCreated.push(relative); } catch (error) { if (error.code === 'EEXIST') fail('CONFIG_CHANGED', '目录在写入前出现;未覆盖配置。'); throw error; }
|
|
619
|
+
}
|
|
620
|
+
for (const [relative, change] of plan.changes) {
|
|
621
|
+
if (canceled) fail('CANCELED', '操作已取消;已写入内容将安全回退。');
|
|
622
|
+
await testHooks.beforeWrite?.(relative, change, applied.length);
|
|
623
|
+
if (!await ownLock()) fail('BUSY', '安装锁在写入期间被移除或替换,停止配置。');
|
|
624
|
+
if (canceled) fail('CANCELED', '操作已取消;已写入内容将安全回退。');
|
|
625
|
+
const current = await observe(home, relative);
|
|
626
|
+
if (!equal(stamp(current), stamp(change.before))) fail('CONFIG_CHANGED', `写入前文件发生变化:${path.join(home, relative)}`);
|
|
627
|
+
try { await atomicWrite(home, relative, change.after, change.mode, change.before); applied.push(relative); } catch (error) { if (error.atomicApplied) applied.push(relative); throw error; }
|
|
628
|
+
await testHooks.afterWrite?.(relative, change, applied.length);
|
|
629
|
+
}
|
|
630
|
+
if (!await ownLock()) fail('BUSY', '安装锁在写入期间被移除或替换,停止配置。');
|
|
631
|
+
for (const relative of applied) {
|
|
632
|
+
const change = plan.changes.get(relative);
|
|
633
|
+
const desired = { kind: change.after === null ? 'missing' : 'file', mode: change.mode, bytes: change.after, entries: null };
|
|
634
|
+
if (!equal(stamp(await observe(home, relative)), stamp(desired))) fail('CONFIG_CHANGED', `提交核对发现并发修改:${safeSource(path.join(home, relative))}`);
|
|
635
|
+
}
|
|
636
|
+
const after = await readSnapshot(home, { ignoreLock: true });
|
|
637
|
+
requireClean(after, plan.action === 'restore');
|
|
638
|
+
report = changeReport(plan, 'applied', 'written', after.configuration_revision, plan.restartRequired ? 'deployment_changed' : plan.deploymentChanged || plan.scope && plan.scope !== 'global' ? 'routing_changed' : 'definition_only');
|
|
639
|
+
if (plan.created_mode) report.created_mode = { id: plan.created_mode.id, name: plan.created_mode.name, kind: plan.created_mode.kind };
|
|
640
|
+
} catch (error) {
|
|
641
|
+
const failures = [];
|
|
642
|
+
for (const relative of [...applied].reverse()) {
|
|
643
|
+
const change = plan.changes.get(relative);
|
|
644
|
+
try {
|
|
645
|
+
const current = await observe(home, relative);
|
|
646
|
+
const desired = { kind: change.after === null ? 'missing' : 'file', mode: change.mode, bytes: change.after, entries: null };
|
|
647
|
+
if (!equal(stamp(current), stamp(desired))) { failures.push(path.join(home, relative)); continue; }
|
|
648
|
+
await testHooks.beforeRollback?.(relative, change);
|
|
649
|
+
await atomicWrite(home, relative, change.before.bytes, change.before.mode, desired);
|
|
650
|
+
} catch { failures.push(path.join(home, relative)); }
|
|
651
|
+
}
|
|
652
|
+
const status = failures.length ? 'partial' : applied.length ? 'rolled_back' : 'not_written';
|
|
653
|
+
const reason = failures.length ? 'partial_or_unknown' : applied.length ? 'rolled_back' : 'not_applied';
|
|
654
|
+
report = changeReport(plan, 'failed', status, null, reason);
|
|
655
|
+
report.rollback_failures = failures;
|
|
656
|
+
pending = error instanceof DelegationError ? error : new DelegationError('WRITE_FAILED', '配置写入失败;已尝试回退安全文件。');
|
|
657
|
+
pending.details = { ...pending.details, report };
|
|
658
|
+
} finally {
|
|
659
|
+
await lockHandle?.close();
|
|
660
|
+
if (ownsLock) await (async () => { await testHooks.beforeUnlock?.(plan); if (await statOrNull(path.join(home, LOCK))) { if (!await ownLock()) fail('LOCK_RELEASE_FAILED', '安装锁已被替换,保留新锁供人工核对。'); await fs.unlink(path.join(home, LOCK)); } })().catch(error => { if (error.code !== 'ENOENT') {
|
|
661
|
+
if (report) report.warnings.push('配置操作已结束,但锁无法释放;请核对状态与锁文件。');
|
|
662
|
+
pending ??= new DelegationError('LOCK_RELEASE_FAILED', '配置操作已结束,但锁无法释放;请核对状态。', 1, { report });
|
|
663
|
+
} });
|
|
664
|
+
}
|
|
665
|
+
if (pending) {
|
|
666
|
+
await cleanDirectories(home, ownCreated.filter(Boolean)).catch(() => {});
|
|
667
|
+
if (ownCreated.includes('')) await fs.rmdir(home).catch(() => {});
|
|
668
|
+
try { if (pending.details.report && pending.details.report.result !== 'applied') pending.details.report.revision_after = (await readSnapshot(home)).configuration_revision; } catch {}
|
|
669
|
+
process.off('SIGINT', onSignal); process.off('SIGTERM', onSignal);
|
|
670
|
+
throw pending;
|
|
671
|
+
}
|
|
672
|
+
if (plan.action === 'restore') {
|
|
673
|
+
try { await testHooks.beforeCleanup?.(plan); await cleanDirectories(home, plan.cleanupDirectories); } catch { report.warnings.push('受管理内容已恢复,部分空目录无法清理。'); }
|
|
674
|
+
try { report.revision_after = (await readSnapshot(home)).configuration_revision; } catch { report.revision_after = null; report.warnings.push('原配置已恢复,但完成后的配置观察不可用;请刷新状态。'); }
|
|
675
|
+
}
|
|
676
|
+
process.off('SIGINT', onSignal); process.off('SIGTERM', onSignal);
|
|
677
|
+
return report;
|
|
678
|
+
} finally { process.off('SIGINT', onSignal); process.off('SIGTERM', onSignal); }
|
|
679
|
+
}
|
|
680
|
+
export async function mutate(home, action, options = {}) {
|
|
681
|
+
let plan;
|
|
682
|
+
try {
|
|
683
|
+
const snapshot = await readSnapshot(home);
|
|
684
|
+
plan = await buildPlan(snapshot, action, options);
|
|
685
|
+
return await applyPlan(plan, options);
|
|
686
|
+
} catch (error) {
|
|
687
|
+
if (!(error instanceof DelegationError)) error = error.exitCode === 2 ? new DelegationError(error.code ?? 'INVALID_ARGUMENT', error.message, 2) : new DelegationError('WRITE_FAILED', '无法安全完成配置操作;未输出原始配置。');
|
|
688
|
+
if (!error.details.report && plan) error.details.report = changeReport(plan, 'failed', 'not_written', null, 'not_applied');
|
|
689
|
+
throw error;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
export async function planSetup(home, options = {}) { return buildPlan(await readSnapshot(home), 'setup', options); }
|
|
693
|
+
export async function planModeSwitch(home, options = {}) { return buildPlan(await readSnapshot(home), 'set', options); }
|
|
694
|
+
export async function planModeDefinition(home, action, options = {}) { return buildPlan(await readSnapshot(home), action, options); }
|
|
695
|
+
export async function planRestore(home, options = {}) { return buildPlan(await readSnapshot(home), 'restore', options); }
|
|
696
|
+
|
|
697
|
+
export async function statusReport(home, options = {}) {
|
|
698
|
+
const snapshot = await readSnapshot(home, options);
|
|
699
|
+
const { state } = snapshot;
|
|
700
|
+
const effective = scopedSelection(snapshot, await scopeContext(options));
|
|
701
|
+
const mode = state ? effective.definition : null;
|
|
702
|
+
const registeredRoles = [], profileCandidates = [], skippedPaths = [];
|
|
703
|
+
for (const [name, registration] of Object.entries(snapshot.config.agents ?? {})) if (object(registration) && safeText(name, 80) !== null) {
|
|
704
|
+
const configFile = safeText(registration.config_file, 4096);
|
|
705
|
+
let relative = null;
|
|
706
|
+
if (configFile) {
|
|
707
|
+
const configured = configFile.startsWith('~/') ? path.join(os.homedir(), configFile.slice(2)) : path.resolve(snapshot.home, configFile);
|
|
708
|
+
const candidate = path.relative(snapshot.home, configured);
|
|
709
|
+
if (candidate && !candidate.startsWith(`..${path.sep}`) && candidate !== '..' && !path.isAbsolute(candidate)) relative = candidate.split(path.sep).join('/');
|
|
710
|
+
}
|
|
711
|
+
const inspected = relative !== null && snapshot.observedFiles.get(relative)?.kind === 'file';
|
|
712
|
+
const reason = inspected ? null : relative === null ? 'outside_bound_home_or_not_inspected' : 'not_inspected';
|
|
713
|
+
registeredRoles.push({ name, config_file: configFile, source: path.join(snapshot.home, 'config.toml'), inspected, reason });
|
|
714
|
+
if (!inspected) skippedPaths.push({ path: configFile, source: path.join(snapshot.home, 'config.toml'), reason });
|
|
715
|
+
}
|
|
716
|
+
for (const [name, profile] of Object.entries(snapshot.config.profiles ?? {})) if (object(profile) && safeText(name, 80) !== null) profileCandidates.push({ name, model: safeText(profile.model), effort: safeText(profile.model_reasoning_effort, 40), default_subagent_model: safeText(profile.agents?.default_subagent_model), default_subagent_reasoning_effort: safeText(profile.agents?.default_subagent_reasoning_effort, 40), source: path.join(snapshot.home, 'config.toml'), active: null });
|
|
717
|
+
if (profileCandidates.length) skippedPaths.push({ path: path.join(snapshot.home, 'config.toml'), reason: 'conditional_active_profile_unknown' });
|
|
718
|
+
for (const [relative, observed] of snapshot.observedDirectories) if (relative === 'agents' || relative.startsWith('agents/')) for (const [name, kind] of observed.entries ?? []) if (kind === 'symlink') skippedPaths.push({ path: safeSource(path.join(snapshot.home, relative, name)), reason: 'unfollowed_symlink' });
|
|
719
|
+
const rulesSummary = ['仅在用户和宿主授权下委派', '按当前档位、任务难度和验证需求选择模型', '用户明确模型、预算和项目规则优先', '禁止递归委派', '禁止修改生产、共享环境、第三方系统和代理配置', '明确独占写入', '先读取真实材料与验收条件', '等价局部差异自行适配', '核心前提失效只阻断受影响部分', '必要验证通过后停止,不擅自扩大检查', '未知退出状态、陈旧报告或部分结果标记 PARTIAL', '固定角色不适用时使用 task_delegate,权限与验收不变', 'fire 每会话先验证;失败时用用户指定组合,否则继承父代理组合', '备用须满足原授权、预算、工具和能力;失败不得静默降级'];
|
|
720
|
+
return { ...effective, definition: undefined, global_mode: snapshot.mode, agent: 'codex', home: snapshot.home, cli_version: VERSION, configuration_version: state?.version ?? null, configuration_revision: snapshot.configuration_revision, installation: state ? 'installed' : 'not_installed', integrity: snapshot.diagnostics.some(value => value.status === 'fail') ? 'drifted' : 'clean', mode: mode ? { id: mode.id, name: mode.name, kind: mode.kind, levels: mode.levels } : null, verification: verificationRequirement(mode), restoration: { status: state?.restoration.status ?? 'not_installed' }, roles: snapshot.roles, task_levels: mode ? LEVELS.map(level => ({ level, ...mode.levels[level] })) : [], rules: { source: path.join(snapshot.home, SKILL, 'SKILL.md'), integrity: state ? snapshot.diagnostics.some(value => ['MANAGED_RULES_DRIFT', 'MANAGED_FILE_DRIFT'].includes(value.code)) ? 'drifted' : 'clean' : 'not_installed', summary: options.details ? rulesSummary : [] }, related_config: { agents_enabled: typeof snapshot.config.agents?.enabled === 'boolean' ? snapshot.config.agents.enabled : typeof snapshot.config.features?.multi_agent === 'boolean' ? snapshot.config.features.multi_agent : null, default_subagent_model: safeText(snapshot.config.agents?.default_subagent_model), default_subagent_reasoning_effort: safeText(snapshot.config.agents?.default_subagent_reasoning_effort), inheritance_note: 'task_delegate 的省略参数不证明继承;须核对全局子代理默认值与宿主派发参数。', external_roles: snapshot.externalRoles, registered_roles: registeredRoles, profile_candidates: profileCandidates, project_candidates: [] }, inspection: { checked_paths: [...snapshot.observedFiles.keys()].map(relative => safeSource(path.join(snapshot.home, relative))), skipped_paths: skippedPaths }, diagnostics: snapshot.diagnostics, warnings: state ? ['运行模型身份尚未验证;已开始任务沿用原配置。'] : [], runtime_verification: 'unverified' };
|
|
721
|
+
}
|
|
722
|
+
export async function listReport(home, options = {}) {
|
|
723
|
+
const snapshot = await readSnapshot(home, options);
|
|
724
|
+
const context = await scopeContext(options), effective = scopedSelection(snapshot, context);
|
|
725
|
+
return { ...effective, definition: undefined, configuration_revision: snapshot.configuration_revision, home: snapshot.home, modes: [...BUILTINS, ...visibleModes(snapshot, context)].map(mode => ({ ...(mode.kind === 'builtin' && snapshot.mode?.id === mode.id ? snapshot.mode : mode), active: effective.active && effective.definition.id === mode.id, definition_scope: mode.definition_scope ?? 'builtin', source: mode.kind === 'builtin' && snapshot.mode?.id === mode.id ? 'installed_snapshot' : mode.kind === 'builtin' ? 'package' : 'custom_definition', definition_version: mode.kind === 'builtin' && snapshot.mode?.id === mode.id ? snapshot.mode.definition_version ?? snapshot.state.version : mode.kind === 'builtin' ? VERSION : null })), diagnostics: snapshot.diagnostics };
|
|
726
|
+
}
|
|
727
|
+
export async function showReport(home, selector, options = {}) {
|
|
728
|
+
const snapshot = await readSnapshot(home, options);
|
|
729
|
+
const selected = scopedSelection(snapshot, await scopeContext(options), selector);
|
|
730
|
+
const { definition } = selected;
|
|
731
|
+
const activeBuiltin = definition.kind === 'builtin' && snapshot.mode?.id === definition.id;
|
|
732
|
+
return { ...selected, configuration_revision: snapshot.configuration_revision, home: snapshot.home, source: activeBuiltin ? path.join(snapshot.home, SKILL, 'references/current-mode.json') : definition.kind === 'builtin' ? 'package' : path.join(snapshot.home, selected.definition_scope === 'global' ? CUSTOM : SCOPE_FILE), definition_version: activeBuiltin ? snapshot.mode.definition_version ?? snapshot.state.version : definition.kind === 'builtin' ? VERSION : null, diagnostics: snapshot.diagnostics, runtime_verification: 'unverified' };
|
|
733
|
+
}
|