@kyun.si/codex-polish 0.0.1-beta.3 → 0.0.1-beta.4
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/CHANGELOG.md +15 -0
- package/CONTRIBUTING.en.md +6 -6
- package/CONTRIBUTING.md +6 -6
- package/README.en.md +45 -17
- package/README.md +45 -17
- package/SECURITY.en.md +5 -3
- package/SECURITY.md +4 -2
- package/docs/technical.en.md +57 -41
- package/docs/technical.md +54 -34
- package/evaluation/README.en.md +1 -1
- package/evaluation/README.md +1 -1
- package/package.json +1 -1
- package/plugins/codex-polish/.codex-plugin/plugin.json +1 -1
- package/plugins/codex-polish/hooks/editor_prompt.mjs +51 -0
- package/plugins/codex-polish/hooks/history.mjs +107 -66
- package/plugins/codex-polish/hooks/preferences.mjs +137 -114
- package/plugins/codex-polish/hooks/project_setting.mjs +40 -30
- package/plugins/codex-polish/hooks/recovery.mjs +2 -69
- package/plugins/codex-polish/hooks/rewrite_mode.mjs +19 -0
- package/plugins/codex-polish/skills/codex-polish/SKILL.md +3 -33
- package/plugins/codex-polish/skills/codex-polish/WORKFLOW.md +47 -0
- package/plugins/codex-polish/skills/codex-polish/references/acp.md +30 -17
- package/plugins/codex-polish/skills/codex-polish/references/codex-polish-editor.md +4 -2
- package/plugins/codex-polish/skills/codex-polish/scripts/acp_models.mjs +31 -6
- package/plugins/codex-polish/skills/codex-polish/scripts/acp_payload.mjs +55 -30
- package/plugins/codex-polish/skills/codex-polish/scripts/cli_io.mjs +2 -2
- package/plugins/codex-polish/skills/codex-polish/scripts/decisions.mjs +49 -58
- package/plugins/codex-polish/skills/codex-polish/scripts/editor_role.mjs +48 -0
- package/plugins/codex-polish/skills/codex-polish/scripts/format_reply.mjs +171 -0
- package/plugins/codex-polish/skills/codex-polish/scripts/previous_reply.mjs +31 -0
- package/plugins/codex-polish/skills/codex-polish/scripts/rewrite_material.mjs +28 -0
- package/plugins/codex-polish/skills/codex-polish/scripts/text_guard.mjs +65 -166
- package/plugins/codex-polish/skills/codex-polish-setup/SKILL.md +37 -11
- package/plugins/codex-polish/skills/codex-polish-setup/references/credentials.en.md +8 -6
- package/plugins/codex-polish/skills/codex-polish-setup/references/credentials.md +3 -3
- package/scripts/install.mjs +389 -123
- package/scripts/native_cache.mjs +5 -5
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import os from 'node:os';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
-
import { fileURLToPath } from 'node:url';
|
|
5
|
-
import { spawnSync } from 'node:child_process';
|
|
6
4
|
import { parseArgs } from 'node:util';
|
|
7
|
-
import { readProjectSetting, accessProjectSetting } from './project_setting.mjs';
|
|
5
|
+
import { projectRoot, readProjectSetting, accessProjectSetting } from './project_setting.mjs';
|
|
6
|
+
import { PROMPT_FILE, readEditorPrompt, readPromptInput } from './editor_prompt.mjs';
|
|
7
|
+
import { REWRITE_MODES, REWRITE_MODE_FILE, REWRITE_TRIGGERS, projectRewriteMode, rewriteModeSettings } from './rewrite_mode.mjs';
|
|
8
8
|
import { LANGUAGES, LANGUAGE_FILE, language, languageSettings, tr } from './ui_locale.mjs';
|
|
9
|
-
import {
|
|
9
|
+
import { cacheScope, withCache } from './recovery.mjs';
|
|
10
10
|
|
|
11
11
|
const MODES = ['auto', 'manual', 'off'];
|
|
12
12
|
const MODE_FILE = 'codex-polish.mode';
|
|
@@ -20,15 +20,16 @@ const GOOGLE_AUTH_MODES = ['existing-session', 'gemini-api-key', 'agent-platform
|
|
|
20
20
|
const SESSION_ID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
|
|
21
21
|
const TURN_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
22
22
|
const SOURCE_MAX_AGE = 7 * 24 * 60 * 60;
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
'
|
|
26
|
-
'
|
|
23
|
+
const DECISION_UNAVAILABLE = new Set([
|
|
24
|
+
'api_rate_limited', 'api_server_error', 'api_transport_error', 'api_timeout',
|
|
25
|
+
'api_auth_error', 'api_quota_exhausted', 'invalid_api_response', 'api_refusal',
|
|
26
|
+
'api_http_error', 'missing_api_key', 'invalid_api_key', 'decision_input_too_large',
|
|
27
27
|
]);
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
28
|
+
const LOCAL_DECISION_ERRORS = new Set([
|
|
29
|
+
'input_read_error', 'input_too_large', 'invalid_input', 'possible_credential', 'display_control',
|
|
30
|
+
'invalid_options', 'editor_prompt_invalid', 'decision_route_changed', 'rewrite_mode_invalid',
|
|
31
|
+
]);
|
|
32
|
+
const DECISION_REASONS = { rewrite: 'needs_rewrite', keep: 'already_clear' };
|
|
32
33
|
|
|
33
34
|
export function projectSettings(cwd) {
|
|
34
35
|
const [value, scope] = readProjectSetting(cwd, MODE_FILE, 16, { allowMissingLink: true });
|
|
@@ -54,11 +55,12 @@ export function projectHistoryTurns(cwd) {
|
|
|
54
55
|
}
|
|
55
56
|
}
|
|
56
57
|
|
|
57
|
-
export function decisionsSettings(cwd) {
|
|
58
|
+
export function decisionsSettings(cwd, rewriteMode = projectRewriteMode(cwd)) {
|
|
58
59
|
const [value] = readProjectSetting(cwd, DECISIONS_FILE, 16);
|
|
59
60
|
const mode = value === null || value === 'auto' ? 'auto' : 'off';
|
|
60
|
-
const
|
|
61
|
-
|
|
61
|
+
const key = process.env.OPENAI_API_KEY;
|
|
62
|
+
const hasKey = Boolean(key?.trim());
|
|
63
|
+
return { decisions_mode: mode, openai_key_configured: hasKey, openai_key_malformed: hasKey && /[^!-~]/.test(key), decisions_enabled: rewriteMode === 'normal' && mode === 'auto' && hasKey };
|
|
62
64
|
}
|
|
63
65
|
|
|
64
66
|
export function validModelId(value) {
|
|
@@ -66,23 +68,28 @@ export function validModelId(value) {
|
|
|
66
68
|
/^[A-Za-z0-9][A-Za-z0-9._-]*(?:[/:][A-Za-z0-9][A-Za-z0-9._-]*)*$/.test(value);
|
|
67
69
|
}
|
|
68
70
|
|
|
69
|
-
|
|
71
|
+
function modelPreference(cwd) {
|
|
70
72
|
const [value] = readProjectSetting(cwd, MODEL_FILE, 257, { allowMissingLink: true });
|
|
71
|
-
|
|
72
|
-
|
|
73
|
+
return { gemini_model: value === null ? DEFAULT_GEMINI_MODEL : validModelId(value) ? value : null,
|
|
74
|
+
gemini_model_configured: validModelId(value) };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function projectGeminiModel(cwd) {
|
|
78
|
+
return modelPreference(cwd).gemini_model;
|
|
73
79
|
}
|
|
74
80
|
|
|
75
81
|
function writeProjectSetting(cwd, filename, value, lang) {
|
|
76
82
|
if (!path.isAbsolute(cwd)) throw new RangeError(tr('请提供项目目录的完整路径。', 'Enter the full path to the project folder.', lang));
|
|
77
|
-
const project =
|
|
83
|
+
const project = projectRoot(cwd);
|
|
78
84
|
if (!fs.statSync(project).isDirectory() || path.dirname(project) === project || project === fs.realpathSync(os.homedir())) {
|
|
79
85
|
throw new RangeError(tr('请选择要配置的项目目录。', 'Choose a project folder to configure.', lang));
|
|
80
86
|
}
|
|
81
87
|
const settings = path.join(project, '.codex');
|
|
82
|
-
fs.mkdirSync(settings, { mode: 0o700, recursive: true });
|
|
88
|
+
if (value !== null) fs.mkdirSync(settings, { mode: 0o700, recursive: true });
|
|
83
89
|
try {
|
|
84
|
-
accessProjectSetting(settings, 'write', filename, value);
|
|
90
|
+
accessProjectSetting(settings, value === null ? 'remove' : 'write', filename, value);
|
|
85
91
|
} catch (error) {
|
|
92
|
+
if (value === null && error.code === 'ENOENT') return path.join(settings, filename);
|
|
86
93
|
if (error.code === 'EINVAL') throw new RangeError(tr('项目设置路径指向了链接或特殊文件。',
|
|
87
94
|
'The settings path points to a link or another special file.', lang));
|
|
88
95
|
throw error;
|
|
@@ -93,10 +100,7 @@ function writeProjectSetting(cwd, filename, value, lang) {
|
|
|
93
100
|
function setProjectModel(cwd, model, lang) {
|
|
94
101
|
if (!validModelId(model)) throw new RangeError(tr('这个模型 ID 无效,请从当前账号的 Gemini 模型列表里选一个。',
|
|
95
102
|
"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
103
|
const file = writeProjectSetting(cwd, MODEL_FILE, model, lang);
|
|
99
|
-
if (recent?.reason === 'acp_model_unavailable') clearFailure(scope, recent.token);
|
|
100
104
|
return { gemini_model: model, file };
|
|
101
105
|
}
|
|
102
106
|
|
|
@@ -146,11 +150,6 @@ export function historySource(cwd) {
|
|
|
146
150
|
return null;
|
|
147
151
|
}
|
|
148
152
|
|
|
149
|
-
function workflowCooldown(scope, decisionsEnabled) {
|
|
150
|
-
const recent = activeFailure(scope);
|
|
151
|
-
return !decisionsEnabled && DECISION_ERRORS.has(recent?.reason) ? null : recent;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
153
|
function findExecutable(name, extra = []) {
|
|
155
154
|
const directories = (process.env.PATH ?? '/bin:/usr/bin').split(path.delimiter);
|
|
156
155
|
for (const directory of [...directories, ...extra]) {
|
|
@@ -175,125 +174,122 @@ function supportedNode() {
|
|
|
175
174
|
return major > 22 || (major === 22 && minor >= 16);
|
|
176
175
|
}
|
|
177
176
|
|
|
178
|
-
export function runtimeStatus(cwd, mode,
|
|
177
|
+
export function runtimeStatus(cwd, mode, trigger) {
|
|
179
178
|
const googleAuth = process.env.CODEX_POLISH_AGY_AUTH ?? 'existing-session';
|
|
180
179
|
const agy = findAgy();
|
|
180
|
+
const rewriteSettings = rewriteModeSettings(cwd, trigger);
|
|
181
|
+
const rewriteMode = rewriteSettings.rewrite_mode;
|
|
182
|
+
let promptSource;
|
|
183
|
+
try { promptSource = readEditorPrompt(cwd, rewriteMode ?? 'normal').source; }
|
|
184
|
+
catch { promptSource = 'invalid'; }
|
|
181
185
|
const status = {
|
|
182
|
-
mode, node_available: supportedNode(),
|
|
186
|
+
mode, ...rewriteSettings, node_available: supportedNode(),
|
|
183
187
|
codex_available: Boolean(findExecutable('codex')), agy_available: Boolean(agy), agy_path: agy,
|
|
184
|
-
...decisionsSettings(cwd),
|
|
188
|
+
...decisionsSettings(cwd, rewriteMode), ...modelPreference(cwd), prompt_source: promptSource,
|
|
185
189
|
google_auth_method: GOOGLE_AUTH_MODES.includes(googleAuth) ? googleAuth : 'unsupported',
|
|
186
190
|
gemini_key_configured: googleAuth === 'existing-session' ? null : Boolean(process.env.GEMINI_API_KEY?.trim()),
|
|
187
191
|
};
|
|
188
192
|
const blockers = [];
|
|
193
|
+
if (rewriteMode === null) blockers.push('rewrite_mode_invalid');
|
|
189
194
|
if (!status.node_available) blockers.push('unsupported_node');
|
|
190
195
|
if (!status.agy_available) blockers.push('agy_missing');
|
|
191
196
|
if (status.google_auth_method === 'unsupported') blockers.push('unsupported_google_auth');
|
|
192
197
|
if (status.gemini_model === null) blockers.push('gemini_model_invalid');
|
|
193
|
-
|
|
194
|
-
if (
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
if (
|
|
198
|
-
else if (/[^!-~]/.test(key)) blockers.push(provider + '_key_invalid');
|
|
198
|
+
if (promptSource === 'invalid') blockers.push('editor_prompt_invalid');
|
|
199
|
+
if (googleAuth === 'gemini-api-key') {
|
|
200
|
+
const key = process.env.GEMINI_API_KEY;
|
|
201
|
+
if (!key?.trim()) blockers.push('gemini_key_missing');
|
|
202
|
+
else if (/[^!-~]/.test(key)) blockers.push('gemini_key_invalid');
|
|
199
203
|
}
|
|
200
|
-
return { ...status, blockers
|
|
204
|
+
return { ...status, blockers };
|
|
201
205
|
}
|
|
202
206
|
|
|
203
|
-
function runOpenaiDecision(
|
|
204
|
-
|
|
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;
|
|
207
|
+
async function runOpenaiDecision(cwd, pinned) {
|
|
208
|
+
// Run the one request in this process so cancelling the host command also cancels HTTPS.
|
|
214
209
|
let output;
|
|
210
|
+
let policy;
|
|
215
211
|
try {
|
|
216
|
-
|
|
212
|
+
const { decide } = await import('../skills/codex-polish/scripts/decisions.mjs');
|
|
213
|
+
output = await decide(['judge', '--cwd', cwd], process.stdin, process.env, undefined, () => {
|
|
214
|
+
policy = workflowPolicy(cwd, pinned);
|
|
215
|
+
return policy.action === 'accept';
|
|
216
|
+
});
|
|
217
|
+
if (policy?.action === 'keep') return [policy, 0];
|
|
217
218
|
} catch {
|
|
218
|
-
return
|
|
219
|
+
return [{ action: 'keep', reason: 'decision_helper_unavailable' }, 1];
|
|
220
|
+
}
|
|
221
|
+
const { action, reason, probability } = output ?? {};
|
|
222
|
+
if (DECISION_UNAVAILABLE.has(reason) && action === 'keep') {
|
|
223
|
+
return [{ action: 'rewrite', reason: 'decision_unavailable', decision_error: reason }, 0];
|
|
219
224
|
}
|
|
220
|
-
if (
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
noteFailure(scope, reason);
|
|
225
|
-
return [{ action, reason }, 1];
|
|
225
|
+
if (LOCAL_DECISION_ERRORS.has(reason) && action === 'keep') return [{ action, reason }, 1];
|
|
226
|
+
if (typeof action !== 'string' || !Object.hasOwn(DECISION_REASONS, action) || reason !== DECISION_REASONS[action] ||
|
|
227
|
+
typeof probability !== 'number' || !(probability >= 0 && probability <= 1)) {
|
|
228
|
+
return [{ action: 'keep', reason: 'decision_helper_unavailable' }, 1];
|
|
226
229
|
}
|
|
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
230
|
return [{ action, reason, probability }, 0];
|
|
230
231
|
}
|
|
231
232
|
|
|
232
|
-
function
|
|
233
|
-
const [mode
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
const
|
|
238
|
-
if (
|
|
239
|
-
if (
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
}
|
|
233
|
+
export function workflowPolicy(cwd, { trigger, route, rewriteMode, model }) {
|
|
234
|
+
const [mode] = projectSettings(cwd);
|
|
235
|
+
const keep = reason => ({ action: 'keep', reason });
|
|
236
|
+
if (!REWRITE_TRIGGERS.includes(trigger) || mode === 'off' || (mode !== 'auto' && trigger === 'auto'))
|
|
237
|
+
return keep('project_mode');
|
|
238
|
+
const status = runtimeStatus(cwd, mode, trigger);
|
|
239
|
+
if (status.blockers.length) return { ...keep(status.blockers[0]), blockers: status.blockers };
|
|
240
|
+
if (rewriteMode !== undefined && rewriteMode !== status.rewrite_mode) return keep('rewrite_mode_changed');
|
|
241
|
+
if (model !== undefined && model !== status.gemini_model) return keep('gemini_model_changed');
|
|
242
|
+
const selected = status.decisions_enabled ? 'decisions' : 'acp';
|
|
243
|
+
if (route !== undefined && route !== selected) return keep('decision_route_changed');
|
|
244
|
+
return { action: 'accept', reason: 'workflow_ready', route: selected };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function judgeDraft(args) {
|
|
248
|
+
const pinned = { trigger: args.trigger, route: args.route, rewriteMode: args['rewrite-mode'], model: args.model };
|
|
249
|
+
const policy = workflowPolicy(args.cwd, pinned);
|
|
250
|
+
if (policy.action === 'keep') return [policy, 0];
|
|
251
|
+
const { route } = policy;
|
|
252
|
+
const [result, code] = route === 'decisions'
|
|
253
|
+
? await runOpenaiDecision(args.cwd, { ...pinned, route })
|
|
254
|
+
: [{ action: 'rewrite', reason: 'direct_acp' }, 0];
|
|
255
|
+
if (code) return [result, code];
|
|
248
256
|
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
257
|
return [result, 0];
|
|
252
258
|
}
|
|
253
259
|
|
|
254
260
|
function runHook() {
|
|
255
261
|
if (!supportedNode()) return;
|
|
256
|
-
const limit = 2 * 1024 * 1024;
|
|
257
262
|
let event;
|
|
258
263
|
try {
|
|
259
|
-
|
|
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)));
|
|
264
|
+
event = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(fs.readFileSync(0)));
|
|
268
265
|
} catch {
|
|
269
266
|
return;
|
|
270
267
|
}
|
|
271
268
|
if (event?.hook_event_name !== 'UserPromptSubmit') return;
|
|
272
|
-
const [mode
|
|
269
|
+
const [mode] = projectSettings(event.cwd);
|
|
273
270
|
rememberHistorySource(event, mode);
|
|
274
271
|
if (mode !== 'auto') return;
|
|
275
272
|
const lang = language(event.cwd);
|
|
276
|
-
const
|
|
277
|
-
const additionalContext =
|
|
278
|
-
|
|
279
|
-
'Automatic polishing is temporarily paused after a service failure. For ordinary replies, mark the final answer as unpolished and show the original GPT draft. Honor the requested format. An explicit polish request can still use the skill.', lang)
|
|
280
|
-
: tr('本项目已开启自动改写。完成任务后,在发送最终回复前使用已安装的 codex-polish:codex-polish 技能。常规回复请在最终消息中显示润色结果和完整 GPT 原稿,两版相同时注明并只显示一次。遵守用户指定的输出格式、取消或禁止外发的要求。',
|
|
281
|
-
'Automatic rewriting is on for this project. Before sending the final answer, use the installed codex-polish:codex-polish skill. In ordinary replies show the result and the full original GPT draft. If identical, label it and show it once. Honor the requested format, cancellations, and requests to keep content local.', lang);
|
|
273
|
+
const workflow = JSON.stringify(path.resolve(import.meta.dirname, '../skills/codex-polish/WORKFLOW.md'));
|
|
274
|
+
const additionalContext = tr(`本项目已开启自动改写。用户要重写已有回复时,直接按 ${workflow} 处理用户指的那条回复。其他任务先准备本轮原稿,再按同一流程处理。无需向用户播报润色进度。只在最终回复中按流程展示结果和原稿。遵守用户指定的格式、取消或禁止外发的要求。`,
|
|
275
|
+
`Automatic rewriting is on for this project. If the user asks to rewrite an earlier reply, follow ${workflow} using the reply they refer to. For other tasks, prepare this turn’s draft and then follow the same workflow. Run the polishing steps without progress announcements. Show the result and original draft in the final answer as directed. Honor the requested format, cancellations, and requests to keep content local.`, lang);
|
|
282
276
|
console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext } }));
|
|
283
277
|
}
|
|
284
278
|
|
|
285
279
|
const commands = {
|
|
286
280
|
hook: ['', '处理 Codex 回合提醒', 'process a Codex hook event'],
|
|
287
281
|
'project-hook': ['', '输出项目提醒配置', 'print the project hook definition'],
|
|
288
|
-
mode: ['--cwd DIR', '
|
|
282
|
+
mode: ['--cwd DIR', '查看什么时候触发改写', 'show when replies are rewritten'],
|
|
289
283
|
'set-mode': ['{auto,manual,off} --cwd DIR', '设置什么时候改写回复', 'choose when replies are rewritten'],
|
|
290
|
-
'set-
|
|
291
|
-
'set-
|
|
284
|
+
'set-rewrite-mode': ['{normal,turbo} --cwd DIR', '选择普通或 Turbo 改写', 'choose normal or turbo rewriting'],
|
|
285
|
+
'set-history-turns': ['N --cwd DIR', '设置 Gemini 润色时能看到几轮历史(0 到 10 轮)', 'choose how many earlier exchanges Gemini receives (0–10)'],
|
|
286
|
+
'set-decisions': ['{auto,off} --cwd DIR', '设置是否让 OpenAI 判断原稿是否需要润色', 'choose whether OpenAI decides if a draft needs editing'],
|
|
292
287
|
'set-model': ['(MODEL_ID | --reset) --cwd DIR', '选择项目的 Gemini 改写模型,或恢复默认模型 ' + DEFAULT_GEMINI_MODEL, 'choose a Gemini model or reset to ' + DEFAULT_GEMINI_MODEL],
|
|
288
|
+
prompt: ['--cwd DIR', '查看当前生效的润色提示词和来源', 'show the effective editing prompt and its source'],
|
|
289
|
+
'set-prompt': ['[--reset] --cwd DIR', '从标准输入保存 UTF-8 润色提示词,或恢复默认', 'save a UTF-8 editing prompt from stdin, or restore the default'],
|
|
293
290
|
'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: ['
|
|
296
|
-
'note-failure': ['REASON --cwd DIR', '记录项目的临时服务故障', 'record a temporary service issue'],
|
|
291
|
+
check: ['--cwd DIR [--trigger {auto,explicit,turbo}]', '查看当前设置和缺少的依赖', 'check project settings and local requirements'],
|
|
292
|
+
decision: ['judge --trigger {auto,explicit,turbo} --cwd DIR [--route {acp,decisions}] [--rewrite-mode {normal,turbo}] [--model MODEL_ID]', '判断原稿是否需要润色', 'decide whether to rewrite a draft'],
|
|
297
293
|
};
|
|
298
294
|
|
|
299
295
|
function printHelp(command, t) {
|
|
@@ -308,7 +304,7 @@ function printHelp(command, t) {
|
|
|
308
304
|
console.log(`\n -h, --help ${t('显示帮助并退出', 'show this help message and exit')}`);
|
|
309
305
|
}
|
|
310
306
|
|
|
311
|
-
function main(args) {
|
|
307
|
+
async function main(args) {
|
|
312
308
|
if (args.length === 1 && args[0] === 'hook') return runHook();
|
|
313
309
|
const cwdOption = args.findIndex(arg => arg === '--cwd' || arg.startsWith('--cwd='));
|
|
314
310
|
const location = cwdOption < 0 ? undefined : args[cwdOption] === '--cwd' ? args[cwdOption + 1] : args[cwdOption].slice(6);
|
|
@@ -321,9 +317,12 @@ function main(args) {
|
|
|
321
317
|
if (rest.includes('--help') || rest.includes('-h')) { printHelp(command, t); return 0; }
|
|
322
318
|
const options = {};
|
|
323
319
|
if (commands[command][0]) options.cwd = { type: 'string' };
|
|
324
|
-
if (command === 'set-model') options.reset = { type: 'boolean' };
|
|
320
|
+
if (command === 'set-model' || command === 'set-prompt') options.reset = { type: 'boolean' };
|
|
321
|
+
if (command === 'decision' || command === 'check') options.trigger = { type: 'string' };
|
|
325
322
|
if (command === 'decision') {
|
|
326
|
-
|
|
323
|
+
options.route = { type: 'string' };
|
|
324
|
+
options['rewrite-mode'] = { type: 'string' };
|
|
325
|
+
options.model = { type: 'string' };
|
|
327
326
|
}
|
|
328
327
|
let values, positionals;
|
|
329
328
|
try {
|
|
@@ -332,13 +331,14 @@ function main(args) {
|
|
|
332
331
|
return usageError(t('参数无效或缺少参数值。使用 --help 查看用法。', 'Invalid option or missing option value. Use --help for usage.'));
|
|
333
332
|
}
|
|
334
333
|
if (options.cwd && !values.cwd) return usageError(t('缺少必填参数 --cwd', 'The --cwd option is required.'));
|
|
335
|
-
const expected = command.startsWith('set-')
|
|
334
|
+
const expected = (command.startsWith('set-') && command !== 'set-prompt') || command === 'decision' ? 1 : 0;
|
|
336
335
|
if (positionals.length !== (values.reset ? 0 : expected)) return usageError(t('参数组合无效。使用 --help 查看用法。', 'Invalid arguments. Use --help for usage.'));
|
|
337
336
|
const value = positionals[0];
|
|
338
|
-
const choices = { 'set-mode': MODES, 'set-language': LANGUAGES, 'set-decisions': ['auto', 'off'], decision: ['judge'
|
|
337
|
+
const choices = { 'set-mode': MODES, 'set-rewrite-mode': REWRITE_MODES, 'set-language': LANGUAGES, 'set-decisions': ['auto', 'off'], decision: ['judge'] };
|
|
339
338
|
const toCheck = [[value, choices[command]]];
|
|
339
|
+
if (command === 'decision' || values.trigger !== undefined) toCheck.push([values.trigger, REWRITE_TRIGGERS]);
|
|
340
340
|
if (command === 'decision') {
|
|
341
|
-
toCheck.push([values
|
|
341
|
+
if (values['rewrite-mode'] !== undefined) toCheck.push([values['rewrite-mode'], REWRITE_MODES]);
|
|
342
342
|
if (values.route !== undefined) toCheck.push([values.route, ['acp', 'decisions']]);
|
|
343
343
|
}
|
|
344
344
|
for (const [selected, allowed] of toCheck) {
|
|
@@ -358,17 +358,24 @@ function main(args) {
|
|
|
358
358
|
return 0;
|
|
359
359
|
}
|
|
360
360
|
if (command === 'mode') { console.log(projectSettings(cwd)[0]); return 0; }
|
|
361
|
-
if (command === '
|
|
362
|
-
console.log(JSON.stringify(
|
|
361
|
+
if (command === 'prompt') {
|
|
362
|
+
try { console.log(JSON.stringify(readEditorPrompt(cwd))); }
|
|
363
|
+
catch (error) {
|
|
364
|
+
console.error(error.message === 'rewrite_mode_invalid'
|
|
365
|
+
? t('无法读取有效的改写模式。请用 set-rewrite-mode 选择 normal 或 turbo。',
|
|
366
|
+
'Could not read a valid rewrite mode. Use set-rewrite-mode to choose normal or turbo.')
|
|
367
|
+
: t('无法读取有效的润色提示词。可用 set-prompt --reset 恢复默认。',
|
|
368
|
+
'Could not read a valid editing prompt. Use set-prompt --reset to restore the default.'));
|
|
369
|
+
return 1;
|
|
370
|
+
}
|
|
363
371
|
return 0;
|
|
364
372
|
}
|
|
365
|
-
if (command === '
|
|
366
|
-
|
|
367
|
-
if (mode !== 'off') noteFailure(scope, value);
|
|
373
|
+
if (command === 'check') {
|
|
374
|
+
console.log(JSON.stringify({ ...runtimeStatus(cwd, projectSettings(cwd)[0], values.trigger), ...languageSettings(cwd), history_turns: projectHistoryTurns(cwd) }));
|
|
368
375
|
return 0;
|
|
369
376
|
}
|
|
370
377
|
if (command === 'decision') {
|
|
371
|
-
const [output, code] =
|
|
378
|
+
const [output, code] = await judgeDraft(values);
|
|
372
379
|
console.log(JSON.stringify(output));
|
|
373
380
|
return code;
|
|
374
381
|
}
|
|
@@ -377,6 +384,7 @@ function main(args) {
|
|
|
377
384
|
try {
|
|
378
385
|
switch (command) {
|
|
379
386
|
case 'set-mode': result = { mode: value, file: save(MODE_FILE, value) }; break;
|
|
387
|
+
case 'set-rewrite-mode': result = { rewrite_mode: value, file: save(REWRITE_MODE_FILE, value) }; break;
|
|
380
388
|
case 'set-decisions': result = { decisions_mode: value, file: save(DECISIONS_FILE, value) }; break;
|
|
381
389
|
case 'set-history-turns': {
|
|
382
390
|
const turns = parseHistoryTurns(value, lang);
|
|
@@ -385,6 +393,21 @@ function main(args) {
|
|
|
385
393
|
}
|
|
386
394
|
case 'set-language': result = { file: save(LANGUAGE_FILE, value), ...languageSettings(cwd) }; break;
|
|
387
395
|
case 'set-model': result = setProjectModel(cwd, values.reset ? DEFAULT_GEMINI_MODEL : value, lang); break;
|
|
396
|
+
case 'set-prompt': {
|
|
397
|
+
let data;
|
|
398
|
+
if (values.reset) data = null;
|
|
399
|
+
else {
|
|
400
|
+
try { data = await readPromptInput(process.stdin); }
|
|
401
|
+
catch (error) {
|
|
402
|
+
if (error.message === 'possible_credential') throw new RangeError(t('提示词含有疑似凭据,请移除后保存。',
|
|
403
|
+
'The prompt appears to contain a credential. Remove it before saving.'));
|
|
404
|
+
throw new RangeError(t('请输入非空的 UTF-8 文本,并移除显示控制字符。',
|
|
405
|
+
'Enter nonempty UTF-8 text and remove display control characters.'));
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
result = { prompt_source: values.reset ? 'default' : 'custom', file: save(PROMPT_FILE, data) };
|
|
409
|
+
break;
|
|
410
|
+
}
|
|
388
411
|
}
|
|
389
412
|
} catch (error) {
|
|
390
413
|
console.error(error instanceof RangeError ? t('无法保存设置。', "Couldn't save the setting. ") + error.message :
|
|
@@ -397,5 +420,5 @@ function main(args) {
|
|
|
397
420
|
}
|
|
398
421
|
|
|
399
422
|
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;
|
|
423
|
+
process.exitCode = (await main(process.argv.slice(2))) ?? 0;
|
|
401
424
|
}
|
|
@@ -13,26 +13,39 @@ function sameDirectory(a, b) {
|
|
|
13
13
|
|
|
14
14
|
function accessSetting(directory, operation, filename, value) {
|
|
15
15
|
const target = path.join(directory, filename);
|
|
16
|
-
if (operation === 'read') {
|
|
16
|
+
if (operation === 'read' || operation === 'read-bytes') {
|
|
17
17
|
const fd = fs.openSync(target, O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
|
|
18
18
|
try {
|
|
19
|
-
|
|
19
|
+
const stat = fs.fstatSync(fd);
|
|
20
|
+
if (!stat.isFile() || (operation === 'read-bytes' && stat.nlink > 1)) return '';
|
|
21
|
+
if (operation === 'read-bytes' && value === undefined) return fs.readFileSync(fd);
|
|
20
22
|
const raw = Buffer.alloc(value + 1);
|
|
21
|
-
|
|
23
|
+
let size = 0;
|
|
24
|
+
while (size < raw.length) {
|
|
25
|
+
const count = fs.readSync(fd, raw, size, raw.length - size, size);
|
|
26
|
+
if (!count) break;
|
|
27
|
+
size += count;
|
|
28
|
+
}
|
|
22
29
|
if (size > value) return '';
|
|
23
|
-
|
|
30
|
+
const bytes = raw.subarray(0, size);
|
|
31
|
+
return operation === 'read-bytes' ? bytes : bytes.toString('latin1').replace(/^[\t-\r ]+|[\t-\r ]+$/g, '');
|
|
24
32
|
} finally {
|
|
25
33
|
fs.closeSync(fd);
|
|
26
34
|
}
|
|
27
35
|
}
|
|
28
|
-
if (operation !== 'write') throw new Error('invalid operation');
|
|
36
|
+
if (operation !== 'write' && operation !== 'remove') throw new Error('invalid operation');
|
|
29
37
|
const current = fs.lstatSync(target, { throwIfNoEntry: false });
|
|
30
38
|
if (current && !current.isFile()) throw Object.assign(new Error('invalid setting'), { code: 'EINVAL' });
|
|
39
|
+
if (operation === 'remove') {
|
|
40
|
+
if (current) fs.unlinkSync(target);
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
31
43
|
const temporary = path.join(directory, '.' + filename + '-' + randomBytes(12).toString('hex'));
|
|
32
44
|
const fd = fs.openSync(temporary, 'wx', 0o600);
|
|
33
45
|
try {
|
|
34
46
|
try {
|
|
35
|
-
fs.writeFileSync(fd, value
|
|
47
|
+
if (Buffer.isBuffer(value)) fs.writeFileSync(fd, value);
|
|
48
|
+
else fs.writeFileSync(fd, value + '\n', 'ascii');
|
|
36
49
|
} finally {
|
|
37
50
|
fs.closeSync(fd);
|
|
38
51
|
}
|
|
@@ -63,31 +76,28 @@ export function accessProjectSetting(directory, operation, filename, value) {
|
|
|
63
76
|
}
|
|
64
77
|
}
|
|
65
78
|
|
|
66
|
-
|
|
79
|
+
// Git worktrees and nested repositories each own their project preferences.
|
|
80
|
+
export function projectRoot(cwd) {
|
|
81
|
+
if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) throw new Error('invalid project path');
|
|
82
|
+
const directory = fs.realpathSync(cwd);
|
|
83
|
+
if (!fs.statSync(directory).isDirectory()) throw new Error('invalid project directory');
|
|
84
|
+
for (let base = directory; base !== os.homedir() && base !== path.dirname(base); base = path.dirname(base)) {
|
|
85
|
+
if (fs.lstatSync(path.join(base, '.git'), { throwIfNoEntry: false })) return base;
|
|
86
|
+
}
|
|
87
|
+
return directory;
|
|
88
|
+
}
|
|
67
89
|
|
|
68
|
-
export function readProjectSetting(cwd, filename, maxBytes, { allowMissingLink = false } = {}) {
|
|
69
|
-
|
|
90
|
+
export function readProjectSetting(cwd, filename, maxBytes, { allowMissingLink = false, raw = false } = {}) {
|
|
91
|
+
let base;
|
|
70
92
|
try {
|
|
71
|
-
|
|
72
|
-
if (
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
}
|
|
81
|
-
} else {
|
|
82
|
-
return [accessProjectSetting(settings, 'read', filename, maxBytes), base];
|
|
83
|
-
}
|
|
84
|
-
} catch (error) {
|
|
85
|
-
if (error.code !== 'ENOENT') return [invalid, base];
|
|
86
|
-
}
|
|
87
|
-
if (fs.existsSync(path.join(base, '.git'))) return [null, base];
|
|
88
|
-
}
|
|
89
|
-
return [null, directory];
|
|
90
|
-
} catch {
|
|
91
|
-
return [invalid, null];
|
|
93
|
+
base = projectRoot(cwd);
|
|
94
|
+
if (base === os.homedir() || base === path.dirname(base)) return [null, base];
|
|
95
|
+
const settings = path.join(base, '.codex');
|
|
96
|
+
if (allowMissingLink && fs.lstatSync(settings).isSymbolicLink() &&
|
|
97
|
+
fs.statSync(settings, { throwIfNoEntry: false })?.isDirectory() &&
|
|
98
|
+
!fs.lstatSync(path.join(settings, filename), { throwIfNoEntry: false })) return [null, base];
|
|
99
|
+
return [accessProjectSetting(settings, raw ? 'read-bytes' : 'read', filename, maxBytes), base];
|
|
100
|
+
} catch (error) {
|
|
101
|
+
return [base && error.code === 'ENOENT' ? null : '', base ?? null];
|
|
92
102
|
}
|
|
93
103
|
}
|
|
@@ -1,20 +1,11 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Private storage for the current thread’s transcript pointer.
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import os from 'node:os';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { pathToFileURL } from 'node:url';
|
|
6
6
|
import { createHash, randomBytes } from 'node:crypto';
|
|
7
7
|
|
|
8
|
-
export const COOLDOWNS = Object.freeze({
|
|
9
|
-
api_rate_limited: 60, api_server_error: 60, api_transport_error: 60,
|
|
10
|
-
api_timeout: 60, invalid_api_response: 60, acp_start_failed: 60,
|
|
11
|
-
acp_timeout: 60, acp_protocol_error: 60, acp_provider_error: 60,
|
|
12
|
-
acp_incomplete: 60, api_auth_error: 300, api_quota_exhausted: 300,
|
|
13
|
-
acp_auth_failed: 300, acp_model_unavailable: 300,
|
|
14
|
-
});
|
|
15
8
|
export const APPLICATION_ID = 0x43504f4c;
|
|
16
|
-
const TOKEN = /^[0-9a-f]{32}$/;
|
|
17
|
-
const validToken = value => typeof value === 'string' && value.length === 32 && TOKEN.test(value);
|
|
18
9
|
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
19
10
|
|
|
20
11
|
function canonicalPath(value) {
|
|
@@ -131,7 +122,7 @@ export function removeProfileCache() {
|
|
|
131
122
|
return withCache('write', db => {
|
|
132
123
|
db.exec('BEGIN EXCLUSIVE');
|
|
133
124
|
const objects = db.prepare('SELECT type, name FROM sqlite_master WHERE sql IS NOT NULL').all();
|
|
134
|
-
if (objects.some(row => row.type !== 'table' ||
|
|
125
|
+
if (objects.some(row => row.type !== 'table' || row.name !== 'history_source')) return file;
|
|
135
126
|
if (db.prepare('PRAGMA journal_mode').get().journal_mode !== 'delete') return file;
|
|
136
127
|
fs.unlinkSync(file);
|
|
137
128
|
return null;
|
|
@@ -141,61 +132,3 @@ export function removeProfileCache() {
|
|
|
141
132
|
throw Object.assign(new Error('could not clean up runtime cache', { cause }), { code: 'EIO', path: file });
|
|
142
133
|
}
|
|
143
134
|
}
|
|
144
|
-
|
|
145
|
-
function clocks() {
|
|
146
|
-
return [Date.now(), Number(process.hrtime.bigint() / 1_000_000n)];
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
export function activeFailure(scope, now = clocks) {
|
|
150
|
-
try {
|
|
151
|
-
const key = cacheScope(scope);
|
|
152
|
-
const row = withCache('read', db => {
|
|
153
|
-
const query = db.prepare('SELECT reason, wall_ms, mono_ms, token FROM cooldown WHERE scope = ?');
|
|
154
|
-
return query.get(key);
|
|
155
|
-
});
|
|
156
|
-
if (!row || typeof row.reason !== 'string' || !Object.hasOwn(COOLDOWNS, row.reason) || !validToken(row.token) ||
|
|
157
|
-
!Number.isSafeInteger(row.wall_ms) || !Number.isSafeInteger(row.mono_ms)) return null;
|
|
158
|
-
const [wall, mono] = now();
|
|
159
|
-
const wallElapsed = wall - row.wall_ms;
|
|
160
|
-
const monoElapsed = mono - row.mono_ms;
|
|
161
|
-
if (wallElapsed < 0 || monoElapsed < 0) return null;
|
|
162
|
-
const elapsed = Math.max(wallElapsed, monoElapsed);
|
|
163
|
-
const remaining = COOLDOWNS[row.reason] - Math.floor(elapsed / 1000);
|
|
164
|
-
return remaining > 0 ? { reason: row.reason, remaining_seconds: remaining, token: row.token } : null;
|
|
165
|
-
} catch {
|
|
166
|
-
return null;
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
export function noteFailure(scope, reason, now = clocks) {
|
|
171
|
-
if (typeof reason !== 'string' || !Object.hasOwn(COOLDOWNS, reason)) return false;
|
|
172
|
-
try {
|
|
173
|
-
const key = cacheScope(scope);
|
|
174
|
-
return withCache('create', db => {
|
|
175
|
-
db.exec(`BEGIN IMMEDIATE;
|
|
176
|
-
CREATE TABLE IF NOT EXISTS cooldown (
|
|
177
|
-
scope TEXT PRIMARY KEY, reason TEXT NOT NULL, wall_ms INTEGER NOT NULL,
|
|
178
|
-
mono_ms INTEGER NOT NULL, token TEXT NOT NULL)`);
|
|
179
|
-
const [wall, mono] = now();
|
|
180
|
-
const cutoff = Math.max(...Object.values(COOLDOWNS)) * 1000;
|
|
181
|
-
db.prepare('DELETE FROM cooldown WHERE wall_ms < ? OR mono_ms < ? OR wall_ms > ? OR mono_ms > ?')
|
|
182
|
-
.run(wall - cutoff, mono - cutoff, wall, mono);
|
|
183
|
-
db.prepare('INSERT OR REPLACE INTO cooldown(scope, reason, wall_ms, mono_ms, token) VALUES(?, ?, ?, ?, ?)')
|
|
184
|
-
.run(key, reason, wall, mono, randomBytes(16).toString('hex'));
|
|
185
|
-
db.exec('COMMIT');
|
|
186
|
-
return true;
|
|
187
|
-
});
|
|
188
|
-
} catch {
|
|
189
|
-
return false;
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
export function clearFailure(scope, token) {
|
|
194
|
-
if (!validToken(token)) return false;
|
|
195
|
-
try {
|
|
196
|
-
const key = cacheScope(scope);
|
|
197
|
-
return withCache('write', db => db.prepare('DELETE FROM cooldown WHERE scope = ? AND token = ?').run(key, token).changes === 1);
|
|
198
|
-
} catch {
|
|
199
|
-
return false;
|
|
200
|
-
}
|
|
201
|
-
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { readProjectSetting } from './project_setting.mjs';
|
|
2
|
+
|
|
3
|
+
export const REWRITE_MODE_FILE = 'codex-polish.rewrite-mode';
|
|
4
|
+
export const REWRITE_MODES = ['normal', 'turbo'];
|
|
5
|
+
export const REWRITE_TRIGGERS = ['auto', 'explicit', 'turbo'];
|
|
6
|
+
|
|
7
|
+
export function rewriteModeSettings(cwd, trigger) {
|
|
8
|
+
const [value] = readProjectSetting(cwd, REWRITE_MODE_FILE, 16, { allowMissingLink: true });
|
|
9
|
+
if (value !== null && !REWRITE_MODES.includes(value)) return { rewrite_mode: null, rewrite_mode_configured: false };
|
|
10
|
+
return { rewrite_mode: trigger === 'turbo' ? 'turbo' : (value ?? 'normal'), rewrite_mode_configured: value !== null };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function projectRewriteMode(cwd) {
|
|
14
|
+
return rewriteModeSettings(cwd).rewrite_mode;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function effectiveRewriteMode(cwd, trigger) {
|
|
18
|
+
return rewriteModeSettings(cwd, trigger).rewrite_mode;
|
|
19
|
+
}
|