@kyun.si/codex-polish 0.0.0-stage → 0.0.1-beta.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/.agents/plugins/marketplace.json +12 -0
- package/CHANGELOG.md +19 -0
- package/CONTRIBUTING.en.md +47 -0
- package/CONTRIBUTING.md +46 -0
- package/Install Codex Polish.command +29 -0
- package/LICENSE +202 -0
- package/README.en.md +77 -0
- package/README.md +78 -2
- package/SECURITY.en.md +17 -0
- package/SECURITY.md +17 -0
- package/docs/technical.en.md +98 -0
- package/docs/technical.md +91 -0
- package/evaluation/README.en.md +47 -0
- package/evaluation/README.md +47 -0
- package/package.json +48 -4
- package/plugins/codex-polish/.codex-plugin/plugin.json +21 -0
- package/plugins/codex-polish/LICENSE +202 -0
- package/plugins/codex-polish/hooks/history.mjs +169 -0
- package/plugins/codex-polish/hooks/hooks.json +15 -0
- package/plugins/codex-polish/hooks/preferences.mjs +401 -0
- package/plugins/codex-polish/hooks/project_setting.mjs +92 -0
- package/plugins/codex-polish/hooks/recovery.mjs +201 -0
- package/plugins/codex-polish/hooks/ui_locale.mjs +61 -0
- package/plugins/codex-polish/skills/codex-polish/SKILL.md +36 -0
- package/plugins/codex-polish/skills/codex-polish/references/acp.md +94 -0
- package/plugins/codex-polish/skills/codex-polish/references/codex-polish-editor.md +15 -0
- package/plugins/codex-polish/skills/codex-polish/scripts/acp_models.mjs +99 -0
- package/plugins/codex-polish/skills/codex-polish/scripts/acp_payload.mjs +53 -0
- package/plugins/codex-polish/skills/codex-polish/scripts/cli_io.mjs +29 -0
- package/plugins/codex-polish/skills/codex-polish/scripts/decisions.mjs +224 -0
- package/plugins/codex-polish/skills/codex-polish/scripts/text_guard.mjs +203 -0
- package/plugins/codex-polish/skills/codex-polish-setup/SKILL.md +52 -0
- package/plugins/codex-polish/skills/codex-polish-setup/references/credentials.en.md +45 -0
- package/plugins/codex-polish/skills/codex-polish-setup/references/credentials.md +54 -0
- package/scripts/install.mjs +1216 -0
- package/scripts/native_cache.mjs +86 -0
- package//345/256/211/350/243/205/345/233/236/345/244/215/346/266/246/350/211/262.command +2 -0
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// Read recent visible chat turns from only the hook's own rollout.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { isDeepStrictEqual, parseArgs } from 'node:util';
|
|
5
|
+
import { CREDENTIAL, DISPLAY_CONTROL, PREFIX } from '../skills/codex-polish/scripts/text_guard.mjs';
|
|
6
|
+
import { DEFAULT_HISTORY_TURNS, MAX_HISTORY_TURNS } from './preferences.mjs';
|
|
7
|
+
|
|
8
|
+
export const MAX_HISTORY_BYTES = 16 * 1024;
|
|
9
|
+
export const MAX_SCAN_BYTES = 4 * 1024 * 1024;
|
|
10
|
+
const MAX_HEADER_BYTES = 1024 * 1024;
|
|
11
|
+
const HOST_TEXT = /^\s*(?:<\/?(?:environment_context|system-reminder|subagent_notification|turn_aborted|user_shell_command|task-notification|user_instructions|skills_instructions|permissions|developer_instructions|instructions|goal_context|ide_context|local-command-[\w-]+|agent_message|skill|t3_code_[\w-]+)(?:[\s>/])|# AGENTS\.md instructions\b|# (?:Context from my IDE setup|Files mentioned by the user):|Subagent completed:)/im;
|
|
12
|
+
const ATTACHMENTS = ['images', 'file_ids', 'local_images', 'audio', 'audio_references', 'local_audio'];
|
|
13
|
+
|
|
14
|
+
function safeText(text) {
|
|
15
|
+
return typeof text === 'string' && text.trim() !== '' && text.length <= MAX_HISTORY_BYTES && text.isWellFormed() &&
|
|
16
|
+
!CREDENTIAL.test(text) && !DISPLAY_CONTROL.test(text) && !HOST_TEXT.test(text) && !text.includes(PREFIX);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function textMessage(parts, kind) {
|
|
20
|
+
if (!Array.isArray(parts) || !parts.length || !parts.every(p => p?.type === kind && typeof p.text === 'string')) return null;
|
|
21
|
+
return parts.map(p => p.text).join('');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function present(value) {
|
|
25
|
+
if (Array.isArray(value)) return value.length > 0;
|
|
26
|
+
if (value && typeof value === 'object') return Object.keys(value).length > 0;
|
|
27
|
+
return Boolean(value);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
class Turn {
|
|
31
|
+
constructor(start) {
|
|
32
|
+
this.id = start.turn_id;
|
|
33
|
+
this.events = [];
|
|
34
|
+
this.messages = [];
|
|
35
|
+
this.answer = null;
|
|
36
|
+
const source = start.turn_attribution ?? {};
|
|
37
|
+
this.ordinary = typeof source === 'object' && !Array.isArray(source) &&
|
|
38
|
+
[undefined, null, 'user', 'exec'].includes(source.turn_trigger) &&
|
|
39
|
+
!source.initiating_agent_path && !source.parent_turn_id && (start.root_turn_id ?? this.id) === this.id;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
read(kind, item) {
|
|
43
|
+
if (kind === 'event_msg') {
|
|
44
|
+
if (item.type === 'user_message') {
|
|
45
|
+
this.events.push(ATTACHMENTS.some(key => present(item[key])) ? null : item.message);
|
|
46
|
+
} else if (item.type === 'agent_message' && item.phase === 'final_answer') {
|
|
47
|
+
this.answer = present(item.moderation) ? null : item.message;
|
|
48
|
+
}
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (kind !== 'response_item' || item.type !== 'message') return;
|
|
52
|
+
const metadata = item.internal_chat_message_metadata_passthrough ?? {};
|
|
53
|
+
if (Object.hasOwn(metadata, 'turn_id') && metadata.turn_id !== this.id) return;
|
|
54
|
+
if (item.role === 'assistant' && item.phase === 'final_answer') {
|
|
55
|
+
if (item.status == null || item.status === 'completed') this.answer = textMessage(item.content, 'output_text');
|
|
56
|
+
} else if (item.role === 'user' && Array.isArray(item.content) && item.content.length) {
|
|
57
|
+
// A "user" role is also used for skills, tool notices, and host context.
|
|
58
|
+
const kinds = metadata.content_item_kinds, origins = metadata.content_item_metadata;
|
|
59
|
+
if (Array.isArray(kinds) && kinds.length === item.content.length && kinds.every(k => k === 'user.text') &&
|
|
60
|
+
Array.isArray(origins) && origins.length === item.content.length &&
|
|
61
|
+
origins.every(origin => isDeepStrictEqual(origin, { provenance: { type: 'user' } }))) {
|
|
62
|
+
this.messages.push(textMessage(item.content, 'input_text'));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
finish(completed) {
|
|
68
|
+
const messages = this.events.length ? this.events : this.messages;
|
|
69
|
+
if (completed.last_agent_message !== this.answer || !safeText(this.answer) || !messages.every(safeText)) return null;
|
|
70
|
+
const user = messages.join('\n\n');
|
|
71
|
+
if (Buffer.byteLength(user) + Buffer.byteLength(this.answer) > MAX_HISTORY_BYTES) return null;
|
|
72
|
+
return { user, assistant: this.answer };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function completedExchanges(data, sessionId, turnId, turns) {
|
|
77
|
+
const last = [];
|
|
78
|
+
let active = null;
|
|
79
|
+
for (const line of data.split('\n')) {
|
|
80
|
+
const { type: kind, payload: item } = JSON.parse(line);
|
|
81
|
+
if (typeof kind !== 'string') return [];
|
|
82
|
+
if (!['session_meta', 'event_msg', 'response_item'].includes(kind)) continue;
|
|
83
|
+
if (!item || typeof item !== 'object' || Array.isArray(item)) return [];
|
|
84
|
+
if (kind === 'session_meta') {
|
|
85
|
+
if (item.id !== sessionId) return [];
|
|
86
|
+
} else if (kind === 'event_msg' && item.type === 'task_started') {
|
|
87
|
+
active = typeof item.turn_id === 'string' && item.turn_id ? new Turn(item) : null;
|
|
88
|
+
} else if (kind === 'event_msg' && ['turn_aborted', 'thread_rolled_back'].includes(item.type)) {
|
|
89
|
+
active = null;
|
|
90
|
+
if (item.type === 'thread_rolled_back') last.length = 0;
|
|
91
|
+
} else if (kind === 'event_msg' && item.type === 'task_complete') {
|
|
92
|
+
if (active?.ordinary && active.id !== turnId && item.turn_id === active.id && !present(item.error) &&
|
|
93
|
+
(active.events.length || active.messages.length) && item.last_agent_message) {
|
|
94
|
+
last.push(active.finish(item));
|
|
95
|
+
if (last.length > Math.min(turns, MAX_HISTORY_TURNS)) last.shift();
|
|
96
|
+
}
|
|
97
|
+
active = null;
|
|
98
|
+
} else {
|
|
99
|
+
active?.read(kind, item);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (!active?.ordinary || (turnId !== null && active.id !== turnId)) return [];
|
|
103
|
+
let budget = MAX_HISTORY_BYTES;
|
|
104
|
+
const result = [];
|
|
105
|
+
for (const exchange of last.reverse()) {
|
|
106
|
+
if (!exchange) continue;
|
|
107
|
+
budget -= Buffer.byteLength(exchange.user) + Buffer.byteLength(exchange.assistant);
|
|
108
|
+
if (budget < 0) break;
|
|
109
|
+
result.push(exchange);
|
|
110
|
+
}
|
|
111
|
+
return result.reverse();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function readRange(fd, start, length) {
|
|
115
|
+
const raw = Buffer.alloc(length);
|
|
116
|
+
let count = 0;
|
|
117
|
+
while (count < length) {
|
|
118
|
+
const n = fs.readSync(fd, raw, count, length - count, start + count);
|
|
119
|
+
if (!n) break;
|
|
120
|
+
count += n;
|
|
121
|
+
}
|
|
122
|
+
return raw.subarray(0, count);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function readHistory(file, sessionId, turnId = null, turns = DEFAULT_HISTORY_TURNS) {
|
|
126
|
+
if (!Number.isInteger(turns) || turns <= 0 || !sessionId || typeof file !== 'string' || !path.isAbsolute(file)) return [];
|
|
127
|
+
try {
|
|
128
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW);
|
|
129
|
+
try {
|
|
130
|
+
const info = fs.fstatSync(fd);
|
|
131
|
+
if (!info.isFile()) return [];
|
|
132
|
+
const head = readRange(fd, 0, Math.min(info.size, MAX_HEADER_BYTES));
|
|
133
|
+
const headerEnd = head.indexOf(10) + 1;
|
|
134
|
+
if (!headerEnd || info.size <= headerEnd) return [];
|
|
135
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
136
|
+
const { type, payload } = JSON.parse(decoder.decode(head.subarray(0, headerEnd)));
|
|
137
|
+
if (type !== 'session_meta' || payload?.id !== sessionId || payload.parent_thread_id || payload.forked_from_id) return [];
|
|
138
|
+
const start = Math.max(headerEnd, info.size - MAX_SCAN_BYTES);
|
|
139
|
+
let raw = readRange(fd, start, info.size - start);
|
|
140
|
+
if (raw.length !== info.size - start || raw.at(-1) !== 10) return [];
|
|
141
|
+
// Drop the truncated first line before decoding, since it may start mid-codepoint.
|
|
142
|
+
if (start > headerEnd) raw = raw.subarray(raw.indexOf(10) + 1);
|
|
143
|
+
if (!raw.length) return [];
|
|
144
|
+
return completedExchanges(decoder.decode(raw.subarray(0, -1)), sessionId, turnId, turns);
|
|
145
|
+
} finally {
|
|
146
|
+
fs.closeSync(fd);
|
|
147
|
+
}
|
|
148
|
+
} catch {
|
|
149
|
+
return [];
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (process.argv[1] && fs.existsSync(process.argv[1]) && fs.realpathSync(process.argv[1]) === import.meta.filename) {
|
|
154
|
+
try {
|
|
155
|
+
const { values } = parseArgs({ options: {
|
|
156
|
+
transcript: { type: 'string' }, 'session-id': { type: 'string' }, 'turn-id': { type: 'string' },
|
|
157
|
+
turns: { type: 'string', default: String(DEFAULT_HISTORY_TURNS) }, help: { type: 'boolean', short: 'h' },
|
|
158
|
+
} });
|
|
159
|
+
if (values.help) console.log('Usage: history.mjs --transcript FILE --session-id ID [--turn-id ID] [--turns 0–10]');
|
|
160
|
+
else {
|
|
161
|
+
if (!values.transcript || !values['session-id']) throw new Error('--transcript and --session-id are required');
|
|
162
|
+
if (!/^[+]?[0-9]+$/.test(values.turns) || Number(values.turns) > MAX_HISTORY_TURNS) throw new Error(`--turns must be between 0 and ${MAX_HISTORY_TURNS}`);
|
|
163
|
+
console.log(JSON.stringify(readHistory(values.transcript, values['session-id'], values['turn-id'], Number(values.turns))));
|
|
164
|
+
}
|
|
165
|
+
} catch (error) {
|
|
166
|
+
console.error(error.message);
|
|
167
|
+
process.exitCode = 2;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { parseArgs } from 'node:util';
|
|
7
|
+
import { readProjectSetting, accessProjectSetting } from './project_setting.mjs';
|
|
8
|
+
import { LANGUAGES, LANGUAGE_FILE, language, languageSettings, tr } from './ui_locale.mjs';
|
|
9
|
+
import { COOLDOWNS, activeFailure, cacheScope, clearFailure, noteFailure, withCache } from './recovery.mjs';
|
|
10
|
+
|
|
11
|
+
const MODES = ['auto', 'manual', 'off'];
|
|
12
|
+
const MODE_FILE = 'codex-polish.mode';
|
|
13
|
+
const HISTORY_FILE = 'codex-polish.history-turns';
|
|
14
|
+
const DECISIONS_FILE = 'codex-polish.decisions';
|
|
15
|
+
const MODEL_FILE = 'codex-polish.model';
|
|
16
|
+
export const DEFAULT_GEMINI_MODEL = 'gemini-4-hydrogen';
|
|
17
|
+
export const DEFAULT_HISTORY_TURNS = 2;
|
|
18
|
+
export const MAX_HISTORY_TURNS = 10;
|
|
19
|
+
const GOOGLE_AUTH_MODES = ['existing-session', 'gemini-api-key', 'agent-platform'];
|
|
20
|
+
const SESSION_ID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
|
|
21
|
+
const TURN_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
22
|
+
const SOURCE_MAX_AGE = 7 * 24 * 60 * 60;
|
|
23
|
+
const DECISION_ERRORS = new Set([
|
|
24
|
+
...Object.keys(COOLDOWNS).filter(reason => reason.startsWith('api_')),
|
|
25
|
+
'invalid_api_response', 'api_refusal', 'api_http_error', 'input_read_error',
|
|
26
|
+
'input_too_large', 'invalid_input', 'invalid_options', 'missing_api_key', 'invalid_api_key',
|
|
27
|
+
]);
|
|
28
|
+
const DECISION_REASONS = {
|
|
29
|
+
judge: { rewrite: 'needs_rewrite', keep: 'already_clear' },
|
|
30
|
+
verify: { accept: 'meaning_preserved', keep: 'meaning_changed' },
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export function projectSettings(cwd) {
|
|
34
|
+
const [value, scope] = readProjectSetting(cwd, MODE_FILE, 16, { allowMissingLink: true });
|
|
35
|
+
return [value === null ? 'manual' : MODES.includes(value) ? value : 'off', scope];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function parseHistoryTurns(value, lang) {
|
|
39
|
+
if (typeof value === 'string' && value.length && !/[^0-9]/.test(value)) {
|
|
40
|
+
const turns = Number(value);
|
|
41
|
+
if (turns <= MAX_HISTORY_TURNS) return turns;
|
|
42
|
+
}
|
|
43
|
+
throw new RangeError(tr(`历史轮数必须是 0 到 ${MAX_HISTORY_TURNS} 之间的整数。设为 0 可以关闭历史。`,
|
|
44
|
+
`Use a whole number from 0 to ${MAX_HISTORY_TURNS}. Set it to 0 to turn off history.`, lang));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function projectHistoryTurns(cwd) {
|
|
48
|
+
const [value] = readProjectSetting(cwd, HISTORY_FILE, 32);
|
|
49
|
+
if (value === null) return DEFAULT_HISTORY_TURNS;
|
|
50
|
+
try {
|
|
51
|
+
return parseHistoryTurns(value, 'en');
|
|
52
|
+
} catch {
|
|
53
|
+
return 0;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function decisionsSettings(cwd) {
|
|
58
|
+
const [value] = readProjectSetting(cwd, DECISIONS_FILE, 16);
|
|
59
|
+
const mode = value === null || value === 'auto' ? 'auto' : 'off';
|
|
60
|
+
const hasKey = Boolean(process.env.OPENAI_API_KEY?.trim());
|
|
61
|
+
return { decisions_mode: mode, openai_key_configured: hasKey, decisions_enabled: mode === 'auto' && hasKey };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function validModelId(value) {
|
|
65
|
+
return typeof value === 'string' && value.length <= 256 &&
|
|
66
|
+
/^[A-Za-z0-9][A-Za-z0-9._-]*(?:[/:][A-Za-z0-9][A-Za-z0-9._-]*)*$/.test(value);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function projectGeminiModel(cwd) {
|
|
70
|
+
const [value] = readProjectSetting(cwd, MODEL_FILE, 257, { allowMissingLink: true });
|
|
71
|
+
if (value === null) return DEFAULT_GEMINI_MODEL;
|
|
72
|
+
return validModelId(value) ? value : null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function writeProjectSetting(cwd, filename, value, lang) {
|
|
76
|
+
if (!path.isAbsolute(cwd)) throw new RangeError(tr('请提供项目目录的完整路径。', 'Enter the full path to the project folder.', lang));
|
|
77
|
+
const project = fs.realpathSync(cwd);
|
|
78
|
+
if (!fs.statSync(project).isDirectory() || path.dirname(project) === project || project === fs.realpathSync(os.homedir())) {
|
|
79
|
+
throw new RangeError(tr('请选择要配置的项目目录。', 'Choose a project folder to configure.', lang));
|
|
80
|
+
}
|
|
81
|
+
const settings = path.join(project, '.codex');
|
|
82
|
+
fs.mkdirSync(settings, { mode: 0o700, recursive: true });
|
|
83
|
+
try {
|
|
84
|
+
accessProjectSetting(settings, 'write', filename, value);
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (error.code === 'EINVAL') throw new RangeError(tr('项目设置路径指向了链接或特殊文件。',
|
|
87
|
+
'The settings path points to a link or another special file.', lang));
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
return path.join(settings, filename);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function setProjectModel(cwd, model, lang) {
|
|
94
|
+
if (!validModelId(model)) throw new RangeError(tr('这个模型 ID 无效,请从当前账号的 Gemini 模型列表里选一个。',
|
|
95
|
+
"This model ID isn't valid. Choose a Gemini model from your account's list.", lang));
|
|
96
|
+
const [, scope] = projectSettings(cwd);
|
|
97
|
+
const recent = model !== projectGeminiModel(cwd) ? activeFailure(scope) : null;
|
|
98
|
+
const file = writeProjectSetting(cwd, MODEL_FILE, model, lang);
|
|
99
|
+
if (recent?.reason === 'acp_model_unavailable') clearFailure(scope, recent.token);
|
|
100
|
+
return { gemini_model: model, file };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function validSource(turn, file) {
|
|
104
|
+
return typeof turn === 'string' && TURN_ID.test(turn) && typeof file === 'string' &&
|
|
105
|
+
Array.from(file).length <= 4096 && path.isAbsolute(file) && !/[\p{C}\p{Zl}\p{Zp}]/u.test(file) &&
|
|
106
|
+
!/[^\S\x20]/u.test(file);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function rememberHistorySource(event, mode) {
|
|
110
|
+
const { session_id: session, turn_id: turn, transcript_path: file } = event;
|
|
111
|
+
if (typeof session !== 'string' || !SESSION_ID.test(session) || event.agent_id || event.agent_type) return;
|
|
112
|
+
if (process.env.CODEX_THREAD_ID && process.env.CODEX_THREAD_ID !== session) return;
|
|
113
|
+
const valid = mode !== 'off' && validSource(turn, file);
|
|
114
|
+
try {
|
|
115
|
+
const scope = cacheScope(event.cwd);
|
|
116
|
+
withCache(valid ? 'create' : 'write', db => {
|
|
117
|
+
if (!valid) {
|
|
118
|
+
db.prepare('DELETE FROM history_source WHERE scope=? AND session=?').run(scope, session);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
const now = Math.floor(Date.now() / 1000);
|
|
122
|
+
db.exec(`BEGIN IMMEDIATE;
|
|
123
|
+
CREATE TABLE IF NOT EXISTS history_source (
|
|
124
|
+
scope TEXT, session TEXT, turn TEXT, path TEXT, updated INTEGER, PRIMARY KEY(scope, session))`);
|
|
125
|
+
db.prepare('DELETE FROM history_source WHERE updated NOT BETWEEN ? AND ?').run(now - SOURCE_MAX_AGE, now);
|
|
126
|
+
db.prepare('INSERT OR REPLACE INTO history_source VALUES (?,?,?,?,?)').run(scope, session, turn, file, now);
|
|
127
|
+
db.exec('COMMIT');
|
|
128
|
+
});
|
|
129
|
+
} catch {
|
|
130
|
+
// Cache unavailability must never interrupt a user turn.
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function historySource(cwd) {
|
|
135
|
+
const session = process.env.CODEX_THREAD_ID || '';
|
|
136
|
+
if (!SESSION_ID.test(session) || projectSettings(cwd)[0] === 'off') return null;
|
|
137
|
+
try {
|
|
138
|
+
const scope = cacheScope(cwd);
|
|
139
|
+
const now = Math.floor(Date.now() / 1000);
|
|
140
|
+
const row = withCache('read', db => db.prepare(`SELECT turn, path FROM history_source
|
|
141
|
+
WHERE scope=? AND session=? AND updated BETWEEN ? AND ?`).get(scope, session, now - SOURCE_MAX_AGE, now));
|
|
142
|
+
if (row && validSource(row.turn, row.path)) return { transcript_path: row.path, session_id: session, turn_id: row.turn };
|
|
143
|
+
} catch {
|
|
144
|
+
// Missing, private to another user, stale, or unreadable.
|
|
145
|
+
}
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function workflowCooldown(scope, decisionsEnabled) {
|
|
150
|
+
const recent = activeFailure(scope);
|
|
151
|
+
return !decisionsEnabled && DECISION_ERRORS.has(recent?.reason) ? null : recent;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function findExecutable(name, extra = []) {
|
|
155
|
+
const directories = (process.env.PATH ?? '/bin:/usr/bin').split(path.delimiter);
|
|
156
|
+
for (const directory of [...directories, ...extra]) {
|
|
157
|
+
const file = path.resolve(directory, name);
|
|
158
|
+
try {
|
|
159
|
+
if (!fs.statSync(file).isFile()) continue;
|
|
160
|
+
fs.accessSync(file, fs.constants.X_OK);
|
|
161
|
+
return file;
|
|
162
|
+
} catch {
|
|
163
|
+
// Continue along PATH.
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function findAgy() {
|
|
170
|
+
return findExecutable('agy', [path.join(os.homedir(), '.local/bin')]);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function supportedNode() {
|
|
174
|
+
const [major, minor] = process.versions.node.split('.').map(Number);
|
|
175
|
+
return major > 22 || (major === 22 && minor >= 16);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function runtimeStatus(cwd, mode, scope) {
|
|
179
|
+
const googleAuth = process.env.CODEX_POLISH_AGY_AUTH ?? 'existing-session';
|
|
180
|
+
const agy = findAgy();
|
|
181
|
+
const status = {
|
|
182
|
+
mode, node_available: supportedNode(),
|
|
183
|
+
codex_available: Boolean(findExecutable('codex')), agy_available: Boolean(agy), agy_path: agy,
|
|
184
|
+
...decisionsSettings(cwd), gemini_model: projectGeminiModel(cwd),
|
|
185
|
+
google_auth_method: GOOGLE_AUTH_MODES.includes(googleAuth) ? googleAuth : 'unsupported',
|
|
186
|
+
gemini_key_configured: googleAuth === 'existing-session' ? null : Boolean(process.env.GEMINI_API_KEY?.trim()),
|
|
187
|
+
};
|
|
188
|
+
const blockers = [];
|
|
189
|
+
if (!status.node_available) blockers.push('unsupported_node');
|
|
190
|
+
if (!status.agy_available) blockers.push('agy_missing');
|
|
191
|
+
if (status.google_auth_method === 'unsupported') blockers.push('unsupported_google_auth');
|
|
192
|
+
if (status.gemini_model === null) blockers.push('gemini_model_invalid');
|
|
193
|
+
const keys = [];
|
|
194
|
+
if (status.decisions_enabled) keys.push(['openai', process.env.OPENAI_API_KEY]);
|
|
195
|
+
if (googleAuth === 'gemini-api-key') keys.push(['gemini', process.env.GEMINI_API_KEY]);
|
|
196
|
+
for (const [provider, key] of keys) {
|
|
197
|
+
if (!key?.trim()) blockers.push(provider + '_key_missing');
|
|
198
|
+
else if (/[^!-~]/.test(key)) blockers.push(provider + '_key_invalid');
|
|
199
|
+
}
|
|
200
|
+
return { ...status, blockers, cooldown: workflowCooldown(scope, status.decisions_enabled) };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function runOpenaiDecision(stage, scope) {
|
|
204
|
+
const helper = fileURLToPath(new URL('../skills/codex-polish/scripts/decisions.mjs', import.meta.url));
|
|
205
|
+
const unavailable = [{ action: 'keep', reason: 'decision_helper_unavailable' }, 1];
|
|
206
|
+
const child = spawnSync(process.execPath, [helper, stage], {
|
|
207
|
+
stdio: ['inherit', 'pipe', 'ignore'], timeout: 15000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024,
|
|
208
|
+
});
|
|
209
|
+
if (child.error?.code === 'ETIMEDOUT') {
|
|
210
|
+
noteFailure(scope, 'api_timeout');
|
|
211
|
+
return [{ action: 'keep', reason: 'api_timeout' }, 1];
|
|
212
|
+
}
|
|
213
|
+
if (child.error || child.status === null) return unavailable;
|
|
214
|
+
let output;
|
|
215
|
+
try {
|
|
216
|
+
output = JSON.parse(child.stdout);
|
|
217
|
+
} catch {
|
|
218
|
+
return unavailable;
|
|
219
|
+
}
|
|
220
|
+
if (!output || typeof output !== 'object' || Array.isArray(output)) return unavailable;
|
|
221
|
+
const { action, reason, probability } = output;
|
|
222
|
+
if (child.status) {
|
|
223
|
+
if (action !== 'keep' || !DECISION_ERRORS.has(reason)) return unavailable;
|
|
224
|
+
noteFailure(scope, reason);
|
|
225
|
+
return [{ action, reason }, 1];
|
|
226
|
+
}
|
|
227
|
+
if (typeof action !== 'string' || !Object.hasOwn(DECISION_REASONS[stage], action) ||
|
|
228
|
+
reason !== DECISION_REASONS[stage][action] || typeof probability !== 'number' || !(probability >= 0 && probability <= 1)) return unavailable;
|
|
229
|
+
return [{ action, reason, probability }, 0];
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function guardedDecision(stage, args) {
|
|
233
|
+
const [mode, scope] = projectSettings(args.cwd);
|
|
234
|
+
if (mode === 'off' || (mode !== 'auto' && args.trigger === 'auto')) return [{ action: 'keep', reason: 'project_mode' }, 0];
|
|
235
|
+
const { blockers, cooldown, decisions_enabled } = runtimeStatus(args.cwd, mode, scope);
|
|
236
|
+
if (blockers.length) return [{ action: 'keep', reason: blockers[0], blockers }, 0];
|
|
237
|
+
const route = decisions_enabled ? 'decisions' : 'acp';
|
|
238
|
+
if (args.route && args.route !== route) return [{ action: 'keep', reason: 'decision_route_changed' }, 0];
|
|
239
|
+
if (cooldown && args.trigger === 'auto') return [{ action: 'keep', reason: 'cooldown', cooldown }, 0];
|
|
240
|
+
let result;
|
|
241
|
+
if (decisions_enabled) {
|
|
242
|
+
const [output, code] = runOpenaiDecision(stage, scope);
|
|
243
|
+
if (code) return [output, code];
|
|
244
|
+
result = output;
|
|
245
|
+
} else {
|
|
246
|
+
result = stage === 'judge' ? { action: 'rewrite', reason: 'direct_acp' } : { action: 'accept', reason: 'decisions_skipped' };
|
|
247
|
+
}
|
|
248
|
+
result.route = route;
|
|
249
|
+
if (cooldown && stage === 'judge' && result.action === 'rewrite') result.recovery_token = cooldown.token;
|
|
250
|
+
if (cooldown && stage === 'verify' && args['recovery-token'] === cooldown.token) clearFailure(scope, cooldown.token);
|
|
251
|
+
return [result, 0];
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function runHook() {
|
|
255
|
+
if (!supportedNode()) return;
|
|
256
|
+
const limit = 2 * 1024 * 1024;
|
|
257
|
+
let event;
|
|
258
|
+
try {
|
|
259
|
+
const raw = Buffer.alloc(limit + 1);
|
|
260
|
+
let size = 0;
|
|
261
|
+
while (size < raw.length) {
|
|
262
|
+
const count = fs.readSync(0, raw, size, raw.length - size);
|
|
263
|
+
if (count === 0) break;
|
|
264
|
+
size += count;
|
|
265
|
+
}
|
|
266
|
+
if (size > limit) return;
|
|
267
|
+
event = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(raw.subarray(0, size)));
|
|
268
|
+
} catch {
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
if (event?.hook_event_name !== 'UserPromptSubmit') return;
|
|
272
|
+
const [mode, scope] = projectSettings(event.cwd);
|
|
273
|
+
rememberHistorySource(event, mode);
|
|
274
|
+
if (mode === 'auto' && !workflowCooldown(scope, decisionsSettings(event.cwd).decisions_enabled)) {
|
|
275
|
+
console.log(JSON.stringify({ hookSpecificOutput: {
|
|
276
|
+
hookEventName: 'UserPromptSubmit',
|
|
277
|
+
additionalContext: tr(
|
|
278
|
+
'本项目已开启自动改写。完成任务后,在发送最终回复前使用已安装的 codex-polish:codex-polish 技能。请遵守用户本轮指定的输出格式、取消或禁止外发的要求。',
|
|
279
|
+
'Automatic rewriting is on for this project. After completing the task, use the installed codex-polish:codex-polish skill before sending the final answer. Honor the user’s requested format, cancellations, and requests to keep content local.',
|
|
280
|
+
language(event.cwd)),
|
|
281
|
+
} }));
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const commands = {
|
|
286
|
+
hook: ['', '处理 Codex 回合提醒', 'process a Codex hook event'],
|
|
287
|
+
'project-hook': ['', '输出项目提醒配置', 'print the project hook definition'],
|
|
288
|
+
mode: ['--cwd DIR', '查看改写模式', 'show the rewrite mode'],
|
|
289
|
+
'set-mode': ['{auto,manual,off} --cwd DIR', '设置什么时候改写回复', 'choose when replies are rewritten'],
|
|
290
|
+
'set-history-turns': ['N --cwd DIR', '设置改写时附带的历史轮数(0 到 10 轮,0 表示不带历史)', 'choose how much chat history to include (0–10 turns, 0 turns off history)'],
|
|
291
|
+
'set-decisions': ['{auto,off} --cwd DIR', '配置 OpenAI 改写前后的检查', 'configure the optional OpenAI review'],
|
|
292
|
+
'set-model': ['(MODEL_ID | --reset) --cwd DIR', '选择项目的 Gemini 改写模型,或恢复默认模型 ' + DEFAULT_GEMINI_MODEL, 'choose a Gemini model or reset to ' + DEFAULT_GEMINI_MODEL],
|
|
293
|
+
'set-language': ['{auto,zh,en} --cwd DIR', '选择设置和提示的显示语言(auto 自动识别,zh 中文,en 英文)', 'choose the language for settings and messages (auto detects, zh Chinese, en English)'],
|
|
294
|
+
check: ['--cwd DIR', '查看当前设置和缺少的依赖', 'check project settings and local requirements'],
|
|
295
|
+
decision: ['{judge,verify} --trigger {auto,explicit} --cwd DIR [--route {acp,decisions}] [--recovery-token TOKEN]', '检查本轮该改写还是发出回复', 'check whether to rewrite or deliver a reply'],
|
|
296
|
+
'note-failure': ['REASON --cwd DIR', '记录项目的临时服务故障', 'record a temporary service issue'],
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
function printHelp(command, t) {
|
|
300
|
+
const prefix = t('用法:', 'Usage: ');
|
|
301
|
+
if (command) {
|
|
302
|
+
const [syntax, zh, en] = commands[command];
|
|
303
|
+
console.log(`${prefix}preferences.mjs ${command} ${syntax}\n\n${t(zh, en)}`);
|
|
304
|
+
} else {
|
|
305
|
+
console.log(`${prefix}preferences.mjs COMMAND [OPTIONS]\n\n${t('管理项目的回复润色设置。', 'Manage Codex Polish settings for a project.')}\n`);
|
|
306
|
+
for (const [name, [, zh, en]] of Object.entries(commands)) console.log(` ${name.padEnd(18)} ${t(zh, en)}`);
|
|
307
|
+
}
|
|
308
|
+
console.log(`\n -h, --help ${t('显示帮助并退出', 'show this help message and exit')}`);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function main(args) {
|
|
312
|
+
if (args.length === 1 && args[0] === 'hook') return runHook();
|
|
313
|
+
const cwdOption = args.findIndex(arg => arg === '--cwd' || arg.startsWith('--cwd='));
|
|
314
|
+
const location = cwdOption < 0 ? undefined : args[cwdOption] === '--cwd' ? args[cwdOption + 1] : args[cwdOption].slice(6);
|
|
315
|
+
const lang = language(location);
|
|
316
|
+
const t = (zh, en) => tr(zh, en, lang);
|
|
317
|
+
const [command, ...rest] = args;
|
|
318
|
+
const usageError = message => { console.error(message); return 2; };
|
|
319
|
+
if (command === '--help' || command === '-h') { printHelp(null, t); return 0; }
|
|
320
|
+
if (!Object.hasOwn(commands, command)) return usageError(t('请提供有效的命令。使用 --help 查看帮助。', 'Provide a valid command. Use --help to see available commands.'));
|
|
321
|
+
if (rest.includes('--help') || rest.includes('-h')) { printHelp(command, t); return 0; }
|
|
322
|
+
const options = {};
|
|
323
|
+
if (commands[command][0]) options.cwd = { type: 'string' };
|
|
324
|
+
if (command === 'set-model') options.reset = { type: 'boolean' };
|
|
325
|
+
if (command === 'decision') {
|
|
326
|
+
for (const key of ['route', 'trigger', 'recovery-token']) options[key] = { type: 'string' };
|
|
327
|
+
}
|
|
328
|
+
let values, positionals;
|
|
329
|
+
try {
|
|
330
|
+
({ values, positionals } = parseArgs({ args: rest, options, allowPositionals: true }));
|
|
331
|
+
} catch {
|
|
332
|
+
return usageError(t('参数无效或缺少参数值。使用 --help 查看用法。', 'Invalid option or missing option value. Use --help for usage.'));
|
|
333
|
+
}
|
|
334
|
+
if (options.cwd && !values.cwd) return usageError(t('缺少必填参数 --cwd', 'The --cwd option is required.'));
|
|
335
|
+
const expected = command.startsWith('set-') || command === 'decision' || command === 'note-failure' ? 1 : 0;
|
|
336
|
+
if (positionals.length !== (values.reset ? 0 : expected)) return usageError(t('参数组合无效。使用 --help 查看用法。', 'Invalid arguments. Use --help for usage.'));
|
|
337
|
+
const value = positionals[0];
|
|
338
|
+
const choices = { 'set-mode': MODES, 'set-language': LANGUAGES, 'set-decisions': ['auto', 'off'], decision: ['judge', 'verify'] };
|
|
339
|
+
const toCheck = [[value, choices[command]]];
|
|
340
|
+
if (command === 'decision') {
|
|
341
|
+
toCheck.push([values.trigger, ['auto', 'explicit']]);
|
|
342
|
+
if (values.route !== undefined) toCheck.push([values.route, ['acp', 'decisions']]);
|
|
343
|
+
}
|
|
344
|
+
for (const [selected, allowed] of toCheck) {
|
|
345
|
+
if (allowed && !allowed.includes(selected)) {
|
|
346
|
+
const valid = allowed.map(item => "'" + item + "'").join(', ');
|
|
347
|
+
return usageError(t(`值 '${selected ?? ''}' 无效,请从 ${valid} 中选择`, `Invalid choice '${selected ?? ''}' (choose from ${valid}).`));
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
const { cwd } = values;
|
|
351
|
+
if (command === 'hook') return runHook();
|
|
352
|
+
if (command === 'project-hook') {
|
|
353
|
+
const definition = JSON.parse(fs.readFileSync(new URL('./hooks.json', import.meta.url), 'utf8'));
|
|
354
|
+
const hook = definition.hooks.UserPromptSubmit[0].hooks[0];
|
|
355
|
+
const quoted = "'" + import.meta.filename.replaceAll("'", "'\\''") + "'";
|
|
356
|
+
hook.command = hook.command.replace('"$' + '{PLUGIN_ROOT}/hooks/preferences.mjs"', () => quoted);
|
|
357
|
+
console.log(JSON.stringify(definition, null, 2));
|
|
358
|
+
return 0;
|
|
359
|
+
}
|
|
360
|
+
if (command === 'mode') { console.log(projectSettings(cwd)[0]); return 0; }
|
|
361
|
+
if (command === 'check') {
|
|
362
|
+
console.log(JSON.stringify({ ...runtimeStatus(cwd, ...projectSettings(cwd)), ...languageSettings(cwd), history_turns: projectHistoryTurns(cwd) }));
|
|
363
|
+
return 0;
|
|
364
|
+
}
|
|
365
|
+
if (command === 'note-failure') {
|
|
366
|
+
const [mode, scope] = projectSettings(cwd);
|
|
367
|
+
if (mode !== 'off') noteFailure(scope, value);
|
|
368
|
+
return 0;
|
|
369
|
+
}
|
|
370
|
+
if (command === 'decision') {
|
|
371
|
+
const [output, code] = guardedDecision(value, values);
|
|
372
|
+
console.log(JSON.stringify(output));
|
|
373
|
+
return code;
|
|
374
|
+
}
|
|
375
|
+
const save = (file, data) => writeProjectSetting(cwd, file, data, lang);
|
|
376
|
+
let result;
|
|
377
|
+
try {
|
|
378
|
+
switch (command) {
|
|
379
|
+
case 'set-mode': result = { mode: value, file: save(MODE_FILE, value) }; break;
|
|
380
|
+
case 'set-decisions': result = { decisions_mode: value, file: save(DECISIONS_FILE, value) }; break;
|
|
381
|
+
case 'set-history-turns': {
|
|
382
|
+
const turns = parseHistoryTurns(value, lang);
|
|
383
|
+
result = { history_turns: turns, file: save(HISTORY_FILE, String(turns)) };
|
|
384
|
+
break;
|
|
385
|
+
}
|
|
386
|
+
case 'set-language': result = { file: save(LANGUAGE_FILE, value), ...languageSettings(cwd) }; break;
|
|
387
|
+
case 'set-model': result = setProjectModel(cwd, values.reset ? DEFAULT_GEMINI_MODEL : value, lang); break;
|
|
388
|
+
}
|
|
389
|
+
} catch (error) {
|
|
390
|
+
console.error(error instanceof RangeError ? t('无法保存设置。', "Couldn't save the setting. ") + error.message :
|
|
391
|
+
t('无法保存设置。请确认项目目录存在,而且能在 .codex 目录里写入普通文件。',
|
|
392
|
+
"Couldn't save the setting. Check that the project exists and you can write to its .codex folder."));
|
|
393
|
+
return 1;
|
|
394
|
+
}
|
|
395
|
+
console.log(JSON.stringify(result));
|
|
396
|
+
return 0;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
if (process.argv[1] && fs.existsSync(process.argv[1]) && fs.realpathSync(process.argv[1]) === import.meta.filename) {
|
|
400
|
+
process.exitCode = main(process.argv.slice(2)) ?? 0;
|
|
401
|
+
}
|