@kyun.si/codex-polish 0.0.1-beta.2 → 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.
Files changed (37) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/CONTRIBUTING.en.md +6 -6
  3. package/CONTRIBUTING.md +6 -6
  4. package/README.en.md +53 -18
  5. package/README.md +53 -18
  6. package/SECURITY.en.md +5 -3
  7. package/SECURITY.md +4 -2
  8. package/docs/technical.en.md +61 -39
  9. package/docs/technical.md +58 -32
  10. package/evaluation/README.en.md +4 -4
  11. package/evaluation/README.md +4 -4
  12. package/package.json +1 -1
  13. package/plugins/codex-polish/.codex-plugin/plugin.json +1 -1
  14. package/plugins/codex-polish/hooks/editor_prompt.mjs +51 -0
  15. package/plugins/codex-polish/hooks/history.mjs +107 -66
  16. package/plugins/codex-polish/hooks/preferences.mjs +140 -117
  17. package/plugins/codex-polish/hooks/project_setting.mjs +40 -30
  18. package/plugins/codex-polish/hooks/recovery.mjs +2 -69
  19. package/plugins/codex-polish/hooks/rewrite_mode.mjs +19 -0
  20. package/plugins/codex-polish/skills/codex-polish/SKILL.md +3 -31
  21. package/plugins/codex-polish/skills/codex-polish/WORKFLOW.md +47 -0
  22. package/plugins/codex-polish/skills/codex-polish/references/acp.md +30 -18
  23. package/plugins/codex-polish/skills/codex-polish/references/codex-polish-editor.md +4 -2
  24. package/plugins/codex-polish/skills/codex-polish/scripts/acp_models.mjs +31 -6
  25. package/plugins/codex-polish/skills/codex-polish/scripts/acp_payload.mjs +55 -30
  26. package/plugins/codex-polish/skills/codex-polish/scripts/cli_io.mjs +2 -2
  27. package/plugins/codex-polish/skills/codex-polish/scripts/decisions.mjs +49 -58
  28. package/plugins/codex-polish/skills/codex-polish/scripts/editor_role.mjs +48 -0
  29. package/plugins/codex-polish/skills/codex-polish/scripts/format_reply.mjs +171 -0
  30. package/plugins/codex-polish/skills/codex-polish/scripts/previous_reply.mjs +31 -0
  31. package/plugins/codex-polish/skills/codex-polish/scripts/rewrite_material.mjs +28 -0
  32. package/plugins/codex-polish/skills/codex-polish/scripts/text_guard.mjs +65 -154
  33. package/plugins/codex-polish/skills/codex-polish-setup/SKILL.md +39 -11
  34. package/plugins/codex-polish/skills/codex-polish-setup/references/credentials.en.md +8 -6
  35. package/plugins/codex-polish/skills/codex-polish-setup/references/credentials.md +3 -3
  36. package/scripts/install.mjs +389 -123
  37. 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 { COOLDOWNS, activeFailure, cacheScope, clearFailure, noteFailure, withCache } from './recovery.mjs';
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 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',
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 DECISION_REASONS = {
29
- judge: { rewrite: 'needs_rewrite', keep: 'already_clear' },
30
- verify: { accept: 'meaning_preserved', keep: 'meaning_changed' },
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 hasKey = Boolean(process.env.OPENAI_API_KEY?.trim());
61
- return { decisions_mode: mode, openai_key_configured: hasKey, decisions_enabled: mode === 'auto' && hasKey };
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
- export function projectGeminiModel(cwd) {
71
+ function modelPreference(cwd) {
70
72
  const [value] = readProjectSetting(cwd, MODEL_FILE, 257, { allowMissingLink: true });
71
- if (value === null) return DEFAULT_GEMINI_MODEL;
72
- return validModelId(value) ? value : null;
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 = fs.realpathSync(cwd);
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, scope) {
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), gemini_model: projectGeminiModel(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
- 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');
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, cooldown: workflowCooldown(scope, status.decisions_enabled) };
204
+ return { ...status, blockers };
201
205
  }
202
206
 
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;
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
- output = JSON.parse(child.stdout);
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 unavailable;
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 (!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];
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 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
- }
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
- 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)));
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, scope] = projectSettings(event.cwd);
269
+ const [mode] = projectSettings(event.cwd);
273
270
  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
- }
271
+ if (mode !== 'auto') return;
272
+ const lang = language(event.cwd);
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);
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', '查看改写模式', 'show the rewrite mode'],
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-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'],
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: ['{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'],
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
- for (const key of ['route', 'trigger', 'recovery-token']) options[key] = { type: 'string' };
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-') || command === 'decision' || command === 'note-failure' ? 1 : 0;
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', 'verify'] };
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.trigger, ['auto', 'explicit']]);
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 === 'check') {
362
- console.log(JSON.stringify({ ...runtimeStatus(cwd, ...projectSettings(cwd)), ...languageSettings(cwd), history_turns: projectHistoryTurns(cwd) }));
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 === 'note-failure') {
366
- const [mode, scope] = projectSettings(cwd);
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] = guardedDecision(value, values);
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
- if (!fs.fstatSync(fd).isFile()) return '';
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
- const size = fs.readSync(fd, raw, 0, raw.length, 0);
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
- return raw.subarray(0, size).toString('latin1').replace(/^[\t-\r ]+|[\t-\r ]+$/g, '');
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 + '\n', 'ascii');
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
- const invalid = '';
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
- if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return [invalid, null];
90
+ export function readProjectSetting(cwd, filename, maxBytes, { allowMissingLink = false, raw = false } = {}) {
91
+ let base;
70
92
  try {
71
- const directory = fs.realpathSync(cwd);
72
- if (!fs.statSync(directory).isDirectory()) return [invalid, null];
73
- for (let base = directory; base !== os.homedir() && base !== path.dirname(base); base = path.dirname(base)) {
74
- const settings = path.join(base, '.codex');
75
- try {
76
- if (fs.lstatSync(settings).isSymbolicLink()) {
77
- if (!allowMissingLink || !fs.statSync(settings, { throwIfNoEntry: false })?.isDirectory() ||
78
- fs.lstatSync(path.join(settings, filename), { throwIfNoEntry: false })) {
79
- return [invalid, base];
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
- // Short-lived service failures scoped to a Codex profile and project.
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' || !['cooldown', 'history_source'].includes(row.name))) return file;
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
+ }