@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.
Files changed (32) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +157 -2
  3. package/VERSION +1 -0
  4. package/adapters/codex/modes.json +360 -0
  5. package/adapters/codex/skills/agent-fit/SKILL.md +118 -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 +38 -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 +246 -0
  18. package/docs/README.md +15 -0
  19. package/docs/implementation-review.md +119 -0
  20. package/docs/usage.md +458 -0
  21. package/lib/accounts.mjs +129 -0
  22. package/lib/codex.mjs +215 -0
  23. package/lib/install.mjs +733 -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/package.json +15 -4
  30. package/web/app.js +744 -0
  31. package/web/index.html +109 -0
  32. package/web/styles.css +407 -0
package/lib/probe.mjs ADDED
@@ -0,0 +1,186 @@
1
+ import { constants } from 'node:fs';
2
+ import { open } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+ import { checkPath } from './install.mjs';
6
+
7
+ const LIMIT = 2 * 1024 * 1024;
8
+ const valid = value => typeof value === 'string' && value.length > 0 && value.length <= 8192 && !/[\p{Cc}\p{Cf}]/u.test(value);
9
+ const fail = code => Object.assign(new Error(code), { code });
10
+ export function providerCredential(config, env = process.env) {
11
+ const provider = config.model_providers?.[config.model_provider ?? 'openai'] ?? {};
12
+ if (provider.env_key) return { source: valid(env[provider.env_key]) ? 'provider_environment' : 'not_confirmed', value: env[provider.env_key] };
13
+ if (provider.experimental_bearer_token) return { source: valid(provider.experimental_bearer_token) ? 'provider_config' : 'not_confirmed', value: provider.experimental_bearer_token };
14
+ return null;
15
+ }
16
+ async function fileAuth(home) {
17
+ await checkPath(home, 'auth.json');
18
+ const handle = await open(path.join(home, 'auth.json'), constants.O_RDONLY | constants.O_NOFOLLOW);
19
+ try {
20
+ const info = await handle.stat();
21
+ if (!info.isFile() || info.size > 1024 * 1024 || process.platform !== 'win32' && (info.uid !== process.getuid() || (info.mode & 0o022))) throw fail('PROBE_AUTH_UNAVAILABLE');
22
+ return JSON.parse(await handle.readFile('utf8'));
23
+ } finally { await handle.close(); }
24
+ }
25
+ async function connection(home, config, env) {
26
+ const name = config.model_provider ?? 'openai';
27
+ const provider = config.model_providers?.[name] ?? {};
28
+ if (name !== 'openai' && !valid(provider.base_url) || provider.wire_api && provider.wire_api !== 'responses' || provider.auth || provider.aws || provider.gateway_oauth) throw fail('PROBE_PROVIDER_UNSUPPORTED');
29
+ let base = provider.base_url ?? env.OPENAI_BASE_URL ?? 'https://api.openai.com/v1';
30
+ const headers = new Headers();
31
+ let credential;
32
+ const configured = providerCredential(config, env);
33
+ if (configured) {
34
+ credential = configured.value;
35
+ if (!valid(credential)) throw fail('PROBE_AUTH_UNAVAILABLE');
36
+ } else if (name === 'openai' || provider.requires_openai_auth) {
37
+ if (config.cli_auth_credentials_store && config.cli_auth_credentials_store !== 'file') throw fail('PROBE_AUTH_UNAVAILABLE');
38
+ // The native account reader has already checked the selected home; never copy its auth file.
39
+ const auth = await fileAuth(home).catch(() => { throw fail('PROBE_AUTH_UNAVAILABLE'); });
40
+ credential = auth.auth_mode === 'chatgpt' ? null : auth.OPENAI_API_KEY;
41
+ if ((!credential || auth.auth_mode === 'chatgpt') && auth.tokens?.access_token) {
42
+ if (provider.base_url || name !== 'openai') throw fail('PROBE_PROVIDER_UNSUPPORTED');
43
+ credential = auth.tokens.access_token;
44
+ base = 'https://chatgpt.com/backend-api/codex';
45
+ if (valid(auth.tokens.account_id)) headers.set('chatgpt-account-id', auth.tokens.account_id);
46
+ }
47
+ if (!valid(credential)) throw fail('PROBE_AUTH_UNAVAILABLE');
48
+ }
49
+ let url;
50
+ try { url = new URL(base.replace(/\/+$/, '') + '/responses'); } catch { throw fail('PROBE_PROVIDER_UNSUPPORTED'); }
51
+ if (url.username || url.password || url.search || url.hash || url.protocol !== 'https:' && !(url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))) throw fail('PROBE_PROVIDER_UNSUPPORTED');
52
+ for (const [key, value] of Object.entries(provider.query_params ?? {})) url.searchParams.set(key, value);
53
+ for (const [key, value] of Object.entries(provider.http_headers ?? {})) headers.set(key, value);
54
+ for (const [key, variable] of Object.entries(provider.env_http_headers ?? {})) if (env[variable]) headers.set(key, env[variable]);
55
+ if (credential) {
56
+ if (!valid(credential)) throw fail('PROBE_AUTH_UNAVAILABLE');
57
+ headers.set('authorization', 'Bearer ' + credential);
58
+ }
59
+ headers.set('content-type', 'application/json');
60
+ headers.set('accept', 'text/event-stream, application/json');
61
+ return { url, headers };
62
+ }
63
+ export async function bindProbeAuthorization(home, config, env = process.env) {
64
+ const fingerprint = ({ url, headers }) => createHash('sha256').update(JSON.stringify([url.href, [...headers]])).digest('hex');
65
+ let expected, changed = false;
66
+ try { expected = fingerprint(await connection(home, config, env)); }
67
+ catch (error) { return async () => { throw error; }; }
68
+ // Keep the binding private to this check; credentials and their digest never enter reports.
69
+ return async () => {
70
+ let current;
71
+ try { current = await connection(home, config, env); }
72
+ catch { changed = true; }
73
+ if (!current || fingerprint(current) !== expected) changed = true;
74
+ if (changed) throw fail('PROBE_AUTH_CHANGED');
75
+ return current;
76
+ };
77
+ }
78
+ async function responseData(response) {
79
+ let bytes = 0, buffer = '', completed = null;
80
+ const decoder = new TextDecoder('utf-8', { fatal: true });
81
+ const stream = response.headers.get('content-type')?.includes('text/event-stream');
82
+ const consume = line => {
83
+ if (!line.startsWith('data:')) return;
84
+ const value = line.slice(5).trim();
85
+ if (!value || value === '[DONE]') return;
86
+ const event = JSON.parse(value);
87
+ if (['response.completed', 'response.failed', 'response.incomplete'].includes(event.type)) completed = event.response;
88
+ if (event.type === 'error') throw fail('PROBE_RESPONSE_FAILED');
89
+ };
90
+ if (!response.body) throw fail('PROBE_RESPONSE_INVALID');
91
+ for await (const chunk of response.body) {
92
+ bytes += chunk.length;
93
+ if (bytes > LIMIT) throw fail('PROBE_RESPONSE_LIMIT');
94
+ buffer += decoder.decode(chunk, { stream: true });
95
+ if (stream) {
96
+ let newline;
97
+ while ((newline = buffer.indexOf('\n')) !== -1) { consume(buffer.slice(0, newline).trimEnd()); buffer = buffer.slice(newline + 1); }
98
+ }
99
+ }
100
+ buffer += decoder.decode();
101
+ if (!stream) return JSON.parse(buffer);
102
+ if (buffer.trim()) consume(buffer.trimEnd());
103
+ if (!completed) throw fail('PROBE_STREAM_INCOMPLETE');
104
+ return completed;
105
+ }
106
+
107
+ export function usesProviderCatalog(config, env = process.env) {
108
+ const name = config.model_provider ?? 'openai';
109
+ return name !== 'openai' || Boolean(config.model_providers?.[name]?.base_url || env.OPENAI_BASE_URL);
110
+ }
111
+
112
+ export async function providerModels({ home, config, deadline }, internal = {}) {
113
+ const result = { source: 'provider_models', status: 'incomplete', includes_hidden: null, pages: 0, models: [], revision: null };
114
+ const controller = new AbortController();
115
+ const timer = setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));
116
+ try {
117
+ const { url, headers } = await (internal.authorization ? internal.authorization() : connection(home, config, internal.env ?? process.env));
118
+ url.pathname = url.pathname.replace(/\/responses$/, '/models');
119
+ headers.set('accept', 'application/json');
120
+ if (Date.now() >= deadline) throw fail('PROBE_TIMEOUT');
121
+ const response = await (internal.fetch ?? fetch)(url, { method: 'GET', headers, redirect: 'error', signal: controller.signal });
122
+ if (!response.ok) {
123
+ await response.body?.cancel();
124
+ throw fail(({ 401: 'PROBE_AUTH_FAILED', 403: 'PROBE_ACCESS_DENIED', 429: 'PROBE_RATE_LIMITED' })[response.status] ?? 'PROVIDER_CATALOG_FAILED');
125
+ }
126
+ const data = await responseData(response);
127
+ await internal.authorization?.();
128
+ if (!Array.isArray(data?.data) || data.data.length > 1000 || data.data.some(model => !valid(model?.id) || model.id.length > 200 || model.id.trim() !== model.id)) throw fail('PROVIDER_CATALOG_INVALID');
129
+ result.models = [...new Set(data.data.map(model => model.id))].map(id => ({ id, model: id, display_name: id, hidden: false, default_reasoning_effort: null, supported_reasoning_efforts: [], input_modalities: null }));
130
+ result.pages = 1;
131
+ // shortcut: provider pagination dialects differ; require a complete list before batch verification.
132
+ if (data.has_more === true || data.next_cursor || data.nextCursor) throw fail('PROVIDER_CATALOG_PARTIAL');
133
+ result.revision = createHash('sha256').update(JSON.stringify(result.models.map(model => model.id).sort())).digest('hex');
134
+ result.status = 'complete';
135
+ } catch (error) {
136
+ result.reason_code = controller.signal.aborted ? 'PROBE_TIMEOUT' : /^(PROBE|PROVIDER)_[A-Z_]+$/.test(error.code ?? '') ? error.code : 'PROVIDER_CATALOG_FAILED';
137
+ } finally { clearTimeout(timer); }
138
+ return result;
139
+ }
140
+
141
+ // No agent loop or tool executor exists here: even an unexpected call in output cannot execute.
142
+ export async function probeResponses({ home, config, pair, deadline }, internal = {}) {
143
+ const result = { request_status: 'not_checked', access: 'unknown', actual_model: null, actual_effort: null, identity_status: 'unverified', reason_code: 'PROBE_RESPONSE_FAILED', http_status: null };
144
+ const controller = new AbortController();
145
+ const timer = setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));
146
+ try {
147
+ const { url, headers } = await (internal.authorization ? internal.authorization() : connection(home, config, internal.env ?? process.env));
148
+ if (Date.now() >= deadline) throw fail('PROBE_TIMEOUT');
149
+ result.request_status = 'incomplete';
150
+ const response = await (internal.fetch ?? fetch)(url, {
151
+ method: 'POST', headers, redirect: 'error', signal: controller.signal,
152
+ body: JSON.stringify({ model: pair.model, ...(pair.effort === null ? {} : { reasoning: { effort: pair.effort } }), instructions: 'Reply with OK only.', input: [{ role: 'user', content: [{ type: 'input_text', text: 'Reply with OK.' }] }], tools: [], tool_choice: 'none', store: false, stream: true }),
153
+ });
154
+ result.http_status = response.status;
155
+ if (!response.ok) {
156
+ // Project known error codes only; provider messages can contain credentials or private URLs.
157
+ let rejection;
158
+ try { rejection = await responseData(response); } catch { /* HTTP status still gives a safe result. */ }
159
+ result.request_status = 'failed';
160
+ if ([401, 403].includes(response.status)) result.access = 'denied';
161
+ if (rejection?.error?.code === 'model_not_found' && [400, 404].includes(response.status)) {
162
+ result.access = 'unavailable'; throw fail('PROBE_MODEL_NOT_FOUND');
163
+ }
164
+ if (response.status === 400 && ['reasoning', 'reasoning.effort'].includes(rejection?.error?.param)) throw fail('PROBE_EFFORT_UNSUPPORTED');
165
+ if (response.status === 400 && ['reasoning', 'reasoning.effort', 'tool_choice', 'tools', 'stream', 'store', 'input'].includes(rejection?.error?.param)) throw fail('PROBE_PARAMETER_REJECTED');
166
+ throw fail(({ 401: 'PROBE_AUTH_FAILED', 403: 'PROBE_ACCESS_DENIED', 429: 'PROBE_RATE_LIMITED' })[response.status] ?? 'PROBE_HTTP_FAILED');
167
+ }
168
+ const data = await responseData(response);
169
+ await internal.authorization?.();
170
+ if (data?.status !== 'completed') throw fail('PROBE_RESPONSE_FAILED');
171
+ if (!Array.isArray(data.output) || !data.output.some(item => item.type === 'message') || data.output.some(item => !['message', 'reasoning'].includes(item.type))) throw fail('PROBE_UNEXPECTED_OUTPUT');
172
+ result.request_status = 'succeeded'; result.access = 'available';
173
+ result.actual_model = valid(data.model) && data.model.length <= 200 ? data.model : null;
174
+ result.actual_effort = valid(data.reasoning?.effort) && data.reasoning.effort.length <= 40 ? data.reasoning.effort : null;
175
+ if (pair.effort === null) {
176
+ result.reason_code = 'PROBE_AVAILABLE';
177
+ if (result.actual_model && result.actual_model !== pair.model) { result.identity_status = 'mismatch'; result.reason_code = 'PROBE_IDENTITY_MISMATCH'; }
178
+ }
179
+ else if (!result.actual_model || !result.actual_effort) result.reason_code = 'PROBE_IDENTITY_UNVERIFIED';
180
+ else if (result.actual_model !== pair.model || result.actual_effort !== pair.effort) { result.identity_status = 'mismatch'; result.reason_code = 'PROBE_IDENTITY_MISMATCH'; }
181
+ else { result.identity_status = 'matched'; result.reason_code = 'PROBE_VERIFIED'; }
182
+ } catch (error) {
183
+ result.reason_code = controller.signal.aborted ? 'PROBE_TIMEOUT' : /^PROBE_[A-Z_]+$/.test(error.code ?? '') ? error.code : 'PROBE_NETWORK_FAILED';
184
+ } finally { clearTimeout(timer); }
185
+ return result;
186
+ }
package/lib/scopes.mjs ADDED
@@ -0,0 +1,113 @@
1
+ import path from 'node:path';
2
+ import { realpath, stat, lstat } from 'node:fs/promises';
3
+ import { execFile } from 'node:child_process';
4
+ import { promisify } from 'node:util';
5
+ import { argumentError, BUILTINS, resolveDefinition, validateDefinition, validateText } from './codex.mjs';
6
+
7
+ export const SCOPE_FILE = '.agent-fit/scopes.json';
8
+ export const SCOPES = ['global', 'project', 'session'];
9
+ const exec = promisify(execFile);
10
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
11
+ const exact = (value, names) => object(value) && Object.keys(value).length === names.length && names.every(name => Object.hasOwn(value, name));
12
+
13
+ export async function scopeContext(options = {}) {
14
+ const scope = options.scope ?? 'global';
15
+ if (!SCOPES.includes(scope)) throw argumentError('作用域必须是 global、project 或 session。');
16
+ let project = null;
17
+ const directory = options.project ?? process.cwd();
18
+ try {
19
+ const root = await realpath(directory);
20
+ if (!(await stat(root)).isDirectory()) throw new Error();
21
+ try { project = (await exec('git', ['-C', root, 'rev-parse', '--show-toplevel'], { timeout: 5000, maxBuffer: 65536 })).stdout.trim(); }
22
+ catch {
23
+ // A missing Git executable must not turn a worktree subdirectory into a new project.
24
+ for (let current = root; ; current = path.dirname(current)) {
25
+ const marker = await lstat(path.join(current, '.git')).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
26
+ if (marker?.isFile() || marker?.isDirectory()) { project = current; break; }
27
+ if (current === path.dirname(current)) break;
28
+ }
29
+ if (!project && options.project !== undefined) project = root;
30
+ }
31
+ if (project) project = await realpath(project);
32
+ } catch { throw argumentError('项目路径必须是已存在的目录。', 'INVALID_PROJECT'); }
33
+ const thread = options.thread ?? process.env.CODEX_THREAD_ID ?? null;
34
+ if (thread !== null) validateText(thread, 200, '聊天线程 ID');
35
+ if (scope === 'project' && !project) throw argumentError('非 Git 项目需要显式指定 --project。', 'PROJECT_REQUIRED');
36
+ if (scope === 'session' && !thread) throw argumentError('会话作用域需要当前聊天线程 ID;在聊天中调用或显式指定 --thread。', 'THREAD_REQUIRED');
37
+ return { scope, project, thread };
38
+ }
39
+
40
+ export function validateScopeStore(value) {
41
+ if (value === null) return { schema_version: 1, projects: [], sessions: [] };
42
+ if (!exact(value, ['schema_version', 'projects', 'sessions']) || value.schema_version !== 1) throw argumentError('作用域配置版本或结构无效。');
43
+ for (const [collection, key] of [['projects', 'project'], ['sessions', 'thread']]) {
44
+ if (!Array.isArray(value[collection])) throw argumentError('作用域配置列表无效。');
45
+ const identities = new Set();
46
+ for (const entry of value[collection]) {
47
+ if (!exact(entry, [key, 'selection', 'modes'])) throw argumentError('作用域配置条目无效。');
48
+ validateText(entry[key], key === 'project' ? 4096 : 200, '作用域标识');
49
+ if (key === 'project' && !path.isAbsolute(entry[key]) || identities.has(entry[key])) throw argumentError('作用域标识无效或重复。');
50
+ identities.add(entry[key]);
51
+ if (entry.selection !== null) validateText(entry.selection, 200, '档位引用');
52
+ if (!Array.isArray(entry.modes)) throw argumentError('作用域自定义档位无效。');
53
+ const names = new Set(BUILTINS.flatMap(mode => [mode.id, mode.name]));
54
+ for (const mode of entry.modes) {
55
+ if (!exact(mode, ['id', 'name', 'kind', 'levels']) || mode.kind !== 'custom' || !/^custom-[a-f0-9-]{36}$/i.test(mode.id)) throw argumentError('作用域档位结构无效。');
56
+ validateText(mode.name, 80, '档位名称');
57
+ if (names.has(mode.id) || names.has(mode.name)) throw argumentError('作用域档位名称或 ID 重复。');
58
+ names.add(mode.id); names.add(mode.name);
59
+ validateDefinition({ levels: mode.levels });
60
+ }
61
+ }
62
+ }
63
+ return value;
64
+ }
65
+
66
+ export function scopeEntry(store, context, create = false) {
67
+ if (context.scope === 'global') return null;
68
+ const [list, key] = context.scope === 'project' ? ['projects', 'project'] : ['sessions', 'thread'];
69
+ let entry = store[list].find(value => value[key] === context[key]);
70
+ if (!entry && create) { entry = { [key]: context[key], selection: null, modes: [] }; store[list].push(entry); }
71
+ return entry ?? null;
72
+ }
73
+
74
+ export function visibleModes(snapshot, context) {
75
+ const result = snapshot.customModes.map(mode => ({ ...mode, definition_scope: 'global' }));
76
+ for (const scope of ['project', 'session']) {
77
+ if (SCOPES.indexOf(scope) > SCOPES.indexOf(context.scope)) break;
78
+ const entry = scopeEntry(snapshot.scopeStore, { ...context, scope });
79
+ for (const mode of entry?.modes ?? []) result.push({ ...mode, definition_scope: scope });
80
+ }
81
+ return result;
82
+ }
83
+
84
+ export function scopedSelection(snapshot, context, selector) {
85
+ const modes = visibleModes(snapshot, context);
86
+ let effectiveScope = 'global', selection = snapshot.mode?.id ?? null;
87
+ for (const scope of ['project', 'session']) {
88
+ if (SCOPES.indexOf(scope) > SCOPES.indexOf(context.scope)) break;
89
+ const entry = scopeEntry(snapshot.scopeStore, { ...context, scope });
90
+ if (entry?.selection !== null && entry?.selection !== undefined) { selection = entry.selection; effectiveScope = scope; }
91
+ }
92
+ let definition;
93
+ try { definition = resolveDefinition(selector ?? selection ?? 'official', modes); }
94
+ catch (error) {
95
+ if (selector !== undefined) throw error;
96
+ throw Object.assign(new Error('有效作用域的档位引用无效;请修复或清除该层选择。'), { code: 'SCOPE_REFERENCE_INVALID', exitCode: 1 });
97
+ }
98
+ if (definition.id === snapshot.mode?.id) definition = { ...definition, ...snapshot.mode };
99
+ const own = scopeEntry(snapshot.scopeStore, context);
100
+ return {
101
+ definition, active: selection === definition.id,
102
+ scope: context.scope, effective_scope: effectiveScope, context: { project: context.project, thread: context.thread },
103
+ selection: context.scope === 'global' ? snapshot.mode?.id ?? null : own?.selection ?? null,
104
+ inherited: effectiveScope !== context.scope,
105
+ definition_scope: definition.kind === 'builtin' ? 'builtin' : modes.find(mode => mode.id === definition.id)?.definition_scope,
106
+ };
107
+ }
108
+
109
+ export function assertUnreferenced(snapshot, id) {
110
+ if (snapshot.mode?.id === id || [...snapshot.scopeStore.projects, ...snapshot.scopeStore.sessions].some(entry => entry.selection === id)) {
111
+ throw argumentError('档位仍被某个作用域选择;请先替换或清除选择,再删除。', 'MODE_IN_USE');
112
+ }
113
+ }
package/lib/server.mjs ADDED
@@ -0,0 +1,200 @@
1
+ import http from 'node:http';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { spawn } from 'node:child_process';
4
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { VERSION, argumentError, validateDefinition, validatePair, validateText, LEVELS, TASKS, ROLES } from './codex.mjs';
7
+ import { createAccountController } from './accounts.mjs';
8
+ import { scopeContext } from './scopes.mjs';
9
+
10
+ const CLI = fileURLToPath(new URL('../bin/agent-fit.mjs', import.meta.url));
11
+ const staticFiles = new Map([
12
+ ['/', ['index.html', 'text/html; charset=utf-8']],
13
+ ['/app.js', ['app.js', 'text/javascript; charset=utf-8']],
14
+ ['/styles.css', ['styles.css', 'text/css; charset=utf-8']],
15
+ ]);
16
+ const allowed = {
17
+ status: ['details'], list: [], show: ['mode'], explain: ['mode', 'level', 'task', 'role'],
18
+ setup: ['mode', 'expectRevision', 'dryRun'], set: ['mode', 'expectRevision', 'dryRun'],
19
+ create: ['name', 'from', 'expectRevision', 'dryRun'],
20
+ configure: ['mode', 'definition', 'level', 'model', 'effort', 'fallbackModel', 'fallbackEffort', 'clearFallback', 'expectRevision', 'dryRun'],
21
+ restore: ['expectRevision', 'dryRun'], verify: ['expectRevision'],
22
+ clear: ['expectRevision', 'dryRun'], delete: ['mode', 'expectRevision', 'dryRun'],
23
+ };
24
+ for (const action of ['status', 'list', 'show', 'explain', 'set', 'create', 'configure', 'clear', 'delete', 'verify']) allowed[action].push('scope');
25
+ const writing = new Set(['setup', 'set', 'create', 'configure', 'clear', 'delete', 'restore']);
26
+ const booleanFields = new Set(['details', 'dryRun', 'clearFallback']);
27
+ const required = { show: ['mode'], set: ['mode'], delete: ['mode'], create: ['name'], configure: ['mode'], explain: ['level'], verify: ['expectRevision'] };
28
+
29
+ export function actionCommand(body, { home, project, thread = null }) {
30
+ if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).some(k => !['action', 'params'].includes(k)) || !Object.hasOwn(allowed, body.action)) throw argumentError('网页动作无效。');
31
+ const params = body.params ?? {};
32
+ if (!params || typeof params !== 'object' || Array.isArray(params) || Object.keys(params).some(k => !allowed[body.action].includes(k))) throw argumentError('网页动作参数无效。');
33
+ for (const [key, value] of Object.entries(params)) {
34
+ if (booleanFields.has(key)) { if (typeof value !== 'boolean') throw argumentError('布尔参数类型无效。'); }
35
+ else if (key !== 'definition') validateText(value, key === 'expectRevision' ? 200 : 200, '参数');
36
+ }
37
+ for (const key of required[body.action] || []) if (!Object.hasOwn(params, key)) throw argumentError('网页动作缺少参数。');
38
+ if (writing.has(body.action) && !params.expectRevision) throw argumentError('网页写入必须携带配置版本。');
39
+ if (params.scope !== undefined && !['global', 'project', 'session'].includes(params.scope)) throw argumentError('作用域无效。');
40
+ if (params.scope === 'session' && !thread) throw argumentError('此服务未绑定聊天线程;请从目标聊天启动 serve。', 'THREAD_REQUIRED');
41
+ if (params.level && !LEVELS.includes(params.level)) throw argumentError('任务等级无效。');
42
+ if (params.task && (!Object.hasOwn(TASKS, params.task) || !TASKS[params.task].includes(params.level))) throw argumentError('任务类型与复杂度等级不匹配。');
43
+ if (params.role && !Object.hasOwn(ROLES, params.role)) throw argumentError('职责无效。');
44
+ if (Boolean(params.model) !== Boolean(params.effort)) throw argumentError('模型与推理强度必须成对。');
45
+ if (params.model) validatePair({ model: params.model, effort: params.effort });
46
+ let stdin;
47
+ if (body.action === 'configure') {
48
+ if (Object.hasOwn(params, 'definition')) {
49
+ if (['level', 'model', 'effort', 'fallbackModel', 'fallbackEffort', 'clearFallback'].some(k => Object.hasOwn(params, k))) throw argumentError('整表定义与单级参数互斥。');
50
+ stdin = JSON.stringify({ levels: validateDefinition(params.definition) });
51
+ if (Buffer.byteLength(stdin) > 65536) throw argumentError('整表输入超过 64 KiB。');
52
+ } else if (!params.level || !params.model || !params.effort) throw argumentError('配置需要完整定义或单级参数。');
53
+ if (Boolean(params.fallbackModel) !== Boolean(params.fallbackEffort) || (params.clearFallback && params.fallbackModel)) throw argumentError('备用参数无效。');
54
+ }
55
+ const argv = body.action === 'verify' ? ['models', 'check', '--verify'] : ['set', 'clear', 'delete', 'list', 'show', 'create', 'configure'].includes(body.action) ? ['mode', body.action] : [body.action];
56
+ for (const key of ['mode', 'name']) if (params[key] !== undefined && ['set', 'delete', 'show', 'create', 'configure'].includes(body.action)) argv.push('--', params[key]);
57
+ // Keep positional names after all flags so even a name beginning with '-' is data.
58
+ const positional = argv.includes('--') ? argv.splice(argv.indexOf('--')) : [];
59
+ argv.push(`--codex-home=${home}`, '--json');
60
+ if (body.action === 'status' || params.scope !== undefined) argv.push(`--project=${project}`);
61
+ if (params.scope !== undefined && thread) argv.push(`--thread=${thread}`);
62
+ for (const [key, value] of Object.entries(params)) {
63
+ if (key === 'name' || (key === 'mode' && positional.length) || key === 'definition') continue;
64
+ const flag = key.replace(/[A-Z]/g, char => '-' + char.toLowerCase());
65
+ if (typeof value === 'boolean') { if (value) argv.push(`--${flag}`); }
66
+ else argv.push(`--${flag}=${value}`);
67
+ }
68
+ if (stdin !== undefined) argv.push('--definition-stdin');
69
+ argv.push(...positional);
70
+ return { argv, stdin };
71
+ }
72
+
73
+ function equalSecret(a, b) {
74
+ const left = Buffer.from(a || ''), right = Buffer.from(b);
75
+ return left.length === right.length && timingSafeEqual(left, right);
76
+ }
77
+
78
+ function validEnvelope(value) {
79
+ return value && value.report_schema_version === 1 && Object.keys(value).every(k => ['report_schema_version', 'data', 'errors'].includes(k)) && (value.data === null || (typeof value.data === 'object' && !Array.isArray(value.data))) && Array.isArray(value.errors) && value.errors.every(e => e && typeof e.code === 'string' && typeof e.message === 'string');
80
+ }
81
+
82
+ async function runCLI(command, project) {
83
+ return await new Promise(resolve => {
84
+ const child = spawn(process.execPath, [CLI, ...command.argv], { shell: false, cwd: project, stdio: ['pipe', 'pipe', 'pipe'] });
85
+ const chunks = []; let bytes = 0; let overflow = false;
86
+ child.stdout.on('data', chunk => { bytes += chunk.length; if (bytes <= 2 * 1024 * 1024) chunks.push(chunk); else overflow = true; });
87
+ child.stderr.resume();
88
+ child.stdin.on('error', () => {});
89
+ child.stdin.end(command.stdin || '');
90
+ let done = false;
91
+ const finish = (code, error = false) => {
92
+ if (done) return; done = true;
93
+ let report;
94
+ try { report = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))); }
95
+ catch { /* Invalid child output is never exposed. */ }
96
+ if (error || overflow || ![0, 1, 2, 3].includes(code) || !validEnvelope(report) || (code === 0 && report.errors.length)) {
97
+ resolve({ exit_code: 1, report: { report_schema_version: 1, data: { result: 'unknown', configuration_status: 'unknown', restart: { required: null, reason: 'partial_or_unknown', message: '命令结果未确认;先查询当前配置,再决定是否重试。' } }, errors: [{ code: 'COMMAND_RESULT_INVALID', message: '命令结果未确认;查询配置后再继续。' }] }, command: { argv: command.argv } });
98
+ } else resolve({ exit_code: code, report, command: { argv: command.argv } });
99
+ };
100
+ child.on('error', () => finish(null, true));
101
+ child.on('close', code => finish(code));
102
+ });
103
+ }
104
+
105
+ function localAction(body) {
106
+ if (body?.action !== 'account') return false;
107
+ const fields = ['operation', 'method', 'apiKey'];
108
+ if (Object.keys(body).some(key => !['action', 'params'].includes(key)) || !body.params || typeof body.params !== 'object' || Array.isArray(body.params) || Object.keys(body.params).some(key => !fields.includes(key))) throw argumentError('本地账号参数无效。');
109
+ for (const [key, value] of Object.entries(body.params)) validateText(value, key === 'apiKey' ? 4096 : 200, '参数');
110
+ const { operation, method, apiKey } = body.params;
111
+ if (!['status', 'login', 'cancel', 'logout'].includes(operation)) throw argumentError('账号操作无效。');
112
+ if (operation !== 'login' && (method !== undefined || apiKey !== undefined)) throw argumentError('此账号操作不接受登录参数。');
113
+ if (operation === 'login' && (!['chatgpt', 'chatgptDeviceCode', 'apiKey'].includes(method) || (method === 'apiKey') !== (apiKey !== undefined))) throw argumentError('登录方式与凭据参数不匹配。');
114
+ return true;
115
+ }
116
+ export async function serveLocal({ home, project = process.cwd(), thread = null, port = 0, open = false }, internal = {}) {
117
+ if (!Number.isInteger(port) || (port !== 0 && (port < 1024 || port > 65535))) throw argumentError('端口必须是 0 或 1024–65535。');
118
+ const context = await scopeContext({ project, ...(thread ? { scope: 'session', thread } : {}) });
119
+ project = context.project; thread = thread ? context.thread : null;
120
+ const csrf = randomBytes(32).toString('hex'), session = randomBytes(32).toString('hex');
121
+ const accounts = createAccountController(home, internal.accounts);
122
+ let active = null, recent = null, closing = false, origin;
123
+ const server = http.createServer(async (req, res) => {
124
+ res.setHeader('Cache-Control', 'no-store');
125
+ res.setHeader('X-Content-Type-Options', 'nosniff');
126
+ res.setHeader('Referrer-Policy', 'no-referrer');
127
+ res.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'");
128
+ const send = (status, data) => { res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(data)); };
129
+ const fail = (status, code, message) => { if (!res.headersSent && !res.destroyed) send(status, { exit_code: 1, report: { report_schema_version: 1, data: null, errors: [{ code, message }] } }); };
130
+ if (req.headers.host !== new URL(origin).host) return fail(403, 'HOST_REJECTED', '请求地址不匹配本地服务。');
131
+ if (closing) return fail(503, 'SERVICE_CLOSING', '服务正在停止。');
132
+ let pathname;
133
+ try { pathname = new URL(req.url, origin).pathname; } catch { return fail(400, 'INVALID_REQUEST', '请求无效。'); }
134
+ if (req.method === 'GET' && staticFiles.has(pathname)) {
135
+ try {
136
+ const [file, type] = staticFiles.get(pathname);
137
+ const bytes = await readFile(new URL(`../web/${file}`, import.meta.url));
138
+ res.writeHead(200, { 'Content-Type': type }); res.end(bytes);
139
+ } catch { fail(500, 'STATIC_UNAVAILABLE', '页面资源不可读取。'); }
140
+ return;
141
+ }
142
+ if (req.method === 'GET' && pathname === '/api/bootstrap') {
143
+ res.setHeader('Set-Cookie', `delegation_session=${session}; HttpOnly; SameSite=Strict; Path=/`);
144
+ return send(200, { home, project, thread, cli_version: VERSION, csrf_token: csrf, recent_result: recent });
145
+ }
146
+ if (req.method !== 'POST' || pathname !== '/api/actions') return fail(404, 'NOT_FOUND', '请求路径不存在。');
147
+ const cookies = (req.headers.cookie || '').split(';').map(v => v.trim());
148
+ if (req.headers.origin !== origin || !equalSecret(req.headers['x-delegation-token'], csrf) || !cookies.some(v => equalSecret(v, `delegation_session=${session}`))) return fail(403, 'CSRF_REJECTED', '请求会话无效;重新加载页面。');
149
+ if (!/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(req.headers['content-type'] || '')) return fail(415, 'CONTENT_TYPE_REJECTED', '仅接受 UTF-8 JSON。');
150
+ if (active) return fail(409, 'BUSY', '已有命令正在执行,请稍后重新操作。');
151
+ try {
152
+ let length = 0; const chunks = [];
153
+ for await (const chunk of req) {
154
+ length += chunk.length;
155
+ if (length > 131072) { fail(413, 'BODY_TOO_LARGE', '请求超过 128 KiB。'); req.resume(); return; }
156
+ chunks.push(chunk);
157
+ }
158
+ let body;
159
+ try { body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))); }
160
+ catch { return fail(400, 'INVALID_JSON', '请求必须是有效 UTF-8 JSON。'); }
161
+ const local = localAction(body);
162
+ const command = local ? null : actionCommand(body, { home, project, thread });
163
+ // Recheck after reading the body: two simultaneous uploads must not launch two children.
164
+ if (active || closing) return fail(409, 'BUSY', '已有命令正在执行或服务正在停止。');
165
+ active = local ? (async () => {
166
+ try {
167
+ const data = await accounts.action(body.params);
168
+ return { exit_code: 0, report: { report_schema_version: 1, data, errors: [] }, command: { argv: [] } };
169
+ } catch (error) {
170
+ return { exit_code: 1, report: { report_schema_version: 1, data: null, errors: [{ code: error.exitCode ? error.code : 'LOCAL_ACTION_FAILED', message: error.exitCode ? error.message : '本地账号操作未完成,请检查客户端与目录权限。' }] }, command: { argv: [] } };
171
+ }
172
+ })() : runCLI(command, project);
173
+ const response = await active;
174
+ if (!local) recent = response;
175
+ active = null;
176
+ send(200, response);
177
+ } catch (error) {
178
+ fail(400, error.exitCode === 2 ? error.code : 'INVALID_REQUEST', error.exitCode === 2 ? error.message : '请求无法执行。');
179
+ }
180
+ });
181
+ server.requestTimeout = 10000; server.headersTimeout = 10000;
182
+ await new Promise((resolve, reject) => {
183
+ server.once('error', () => reject(Object.assign(new Error('端口被占用或本地服务无法启动。'), { code: 'SERVER_UNAVAILABLE', exitCode: 1 })));
184
+ server.listen(port, '127.0.0.1', () => { server.removeAllListeners('error'); resolve(); });
185
+ });
186
+ origin = `http://127.0.0.1:${server.address().port}`;
187
+ if (open) {
188
+ const command = process.platform === 'darwin' ? ['open', [origin]] : process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', origin]] : ['xdg-open', [origin]];
189
+ const child = spawn(command[0], command[1], { shell: false, stdio: 'ignore' });
190
+ child.on('error', () => process.stderr.write('浏览器未打开,请手动访问上面的本地网址。\n'));
191
+ child.on('exit', code => { if (code) process.stderr.write('浏览器未打开,请手动访问上面的本地网址。\n'); });
192
+ }
193
+ return { url: origin, async close() {
194
+ closing = true;
195
+ if (active) await active;
196
+ await accounts.close();
197
+ server.closeIdleConnections();
198
+ await new Promise(resolve => server.close(resolve));
199
+ } };
200
+ }
package/package.json CHANGED
@@ -1,6 +1,17 @@
1
1
  {
2
2
  "name": "@fanglinwei/agent-fit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.1",
4
+ "description": "Match delegated tasks to model and reasoning effort profiles for Codex, with scoped configuration and restore.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "fanglinwei",
8
+ "repository": { "type": "git", "url": "https://github.com/fanglinwei/agent-fit.git" },
9
+ "homepage": "https://github.com/fanglinwei/agent-fit#readme",
10
+ "bugs": { "url": "https://github.com/fanglinwei/agent-fit/issues" },
11
+ "keywords": ["codex", "subagents", "model-routing", "reasoning", "skills", "cli"],
12
+ "bin": { "agent-fit": "bin/agent-fit.mjs" },
13
+ "engines": { "node": ">=22" },
14
+ "files": ["bin/", "lib/", "web/", "adapters/", "VERSION", "README.md", "docs/README.md", "docs/usage.md", "docs/implementation-review.md", "LICENSE"],
15
+ "scripts": { "test": "node --test tests/*.test.mjs", "test:browser": "node tests/browser.mjs" },
16
+ "dependencies": { "smol-toml": "1.9.1" }
17
+ }