@kyun.si/codex-polish 0.0.1-beta.3 → 0.0.1-beta.5

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 (38) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/CONTRIBUTING.en.md +6 -6
  3. package/CONTRIBUTING.md +6 -6
  4. package/README.md +34 -64
  5. package/SECURITY.en.md +6 -4
  6. package/SECURITY.md +5 -3
  7. package/docs/README.zh-CN.md +56 -0
  8. package/docs/technical.en.md +66 -44
  9. package/docs/technical.md +62 -38
  10. package/evaluation/README.en.md +1 -1
  11. package/evaluation/README.md +1 -1
  12. package/package.json +1 -2
  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 +137 -114
  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 -33
  21. package/plugins/codex-polish/skills/codex-polish/WORKFLOW.md +47 -0
  22. package/plugins/codex-polish/skills/codex-polish/references/acp.md +30 -17
  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 -166
  33. package/plugins/codex-polish/skills/codex-polish-setup/SKILL.md +37 -11
  34. package/plugins/codex-polish/skills/codex-polish-setup/references/credentials.en.md +10 -8
  35. package/plugins/codex-polish/skills/codex-polish-setup/references/credentials.md +7 -5
  36. package/scripts/install.mjs +389 -123
  37. package/scripts/native_cache.mjs +5 -5
  38. package/README.en.md +0 -84
@@ -4,17 +4,19 @@ import * as fs from 'node:fs';
4
4
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
5
5
  import { homedir, tmpdir } from 'node:os';
6
6
  import { createHash, randomUUID } from 'node:crypto';
7
- import { execFileSync, spawn, spawnSync } from 'node:child_process';
7
+ import { spawn, spawnSync } from 'node:child_process';
8
+ import { on } from 'node:events';
8
9
  import { Readable } from 'node:stream';
9
10
  import { pipeline } from 'node:stream/promises';
10
- import { createInterface } from 'node:readline';
11
+ import { clearLine, createInterface, cursorTo, emitKeypressEvents, moveCursor } from 'node:readline';
11
12
  import { createInterface as createPrompt } from 'node:readline/promises';
12
13
  import { setTimeout as sleep } from 'node:timers/promises';
13
14
  import { isDeepStrictEqual } from 'node:util';
14
15
  import { fileURLToPath } from 'node:url';
15
16
  import { language, tr } from '../plugins/codex-polish/hooks/ui_locale.mjs';
16
- import { findAgy } from '../plugins/codex-polish/hooks/preferences.mjs';
17
+ import { DEFAULT_GEMINI_MODEL, findAgy } from '../plugins/codex-polish/hooks/preferences.mjs';
17
18
  import { removeProfileCache, sqliteModule } from '../plugins/codex-polish/hooks/recovery.mjs';
19
+ import { sessionCatalog } from '../plugins/codex-polish/skills/codex-polish/scripts/acp_models.mjs';
18
20
  import { preserve } from './native_cache.mjs';
19
21
 
20
22
  export const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
@@ -287,6 +289,50 @@ function registration(run) {
287
289
  }
288
290
  return registeredPath(source);
289
291
  }
292
+ function registeredMarket(run, store) {
293
+ const path = registration(run);
294
+ if (path && path !== store)
295
+ throw fail('同名市场使用了其他来源,请在 Codex 插件设置中检查。',
296
+ 'A marketplace with the same name uses a different source. Check it in Codex plugin settings.');
297
+ return path;
298
+ }
299
+ function marketIndex(snapshot) {
300
+ bundleVersion(snapshot);
301
+ const index = readJSON(join(snapshot, INDEX));
302
+ index.plugins[0].source.path = './' + basename(snapshot) + '/' + PRODUCT;
303
+ return index;
304
+ }
305
+ function activeSnapshot(store) {
306
+ if (!plainFile(store, INDEX)) return null;
307
+ const index = readJSON(join(store, INDEX));
308
+ const relative = index?.plugins?.[0]?.source?.path;
309
+ const name = typeof relative === 'string' && relative.split('/')[1];
310
+ if (name && snapshotName.test(name)) {
311
+ const snapshot = join(store, name);
312
+ if (ownsSnapshot(snapshot, store) && isDeepStrictEqual(index, marketIndex(snapshot))) return snapshot;
313
+ }
314
+ throw fail('本地市场清单已变更,请在 Codex 插件设置中检查。', 'The local marketplace manifest has changed. Check it in Codex plugin settings.');
315
+ }
316
+ function activateSnapshot(store, target) {
317
+ const current = activeSnapshot(store);
318
+ if (current === target) return;
319
+ const file = join(store, INDEX);
320
+ if (target) {
321
+ fs.mkdirSync(dirname(file), { recursive: true });
322
+ writeAtomicJson(file, marketIndex(target));
323
+ } else {
324
+ fs.unlinkSync(file);
325
+ syncStore(dirname(file));
326
+ for (let dir = dirname(file); dir !== store; dir = dirname(dir)) {
327
+ try {
328
+ fs.rmdirSync(dir);
329
+ } catch (error) {
330
+ if (error.code === 'ENOTEMPTY' || error.code === 'EEXIST') break;
331
+ throw error;
332
+ }
333
+ }
334
+ }
335
+ }
290
336
  function installed(run) {
291
337
  return lookup(run, 'installed', 'pluginId', PLUGIN_ID, 'list', '--marketplace', MARKET);
292
338
  }
@@ -390,6 +436,30 @@ export async function writeEnabled(value) {
390
436
  if (!['ok', 'okOverridden'].includes(result.status))
391
437
  throw fail('Codex 配置接口没有确认写入。', "Codex didn't confirm that it saved the setting.");
392
438
  }
439
+ async function hookGuidance(lang, cwd = process.cwd()) {
440
+ const settings = tr('Codex「设置 → Hooks」(CLI 输入 /hooks)', 'Codex Settings → Hooks (/hooks in the CLI)', lang);
441
+ let hook;
442
+ try {
443
+ const { data } = await nativeConfig('hooks/list', { cwds: [cwd] }, { cwd, experimental: true });
444
+ hook = data.flatMap((entry) => entry.hooks).find((h) => h.pluginId === PLUGIN_ID && h.eventName === 'userPromptSubmit');
445
+ } catch {
446
+ return tr(`未能读取 hook 状态。可在 ${settings} 中查看 UserPromptSubmit。`,
447
+ `Couldn’t read the hook’s status. Check UserPromptSubmit in ${settings}.`, lang);
448
+ }
449
+ if (!hook) return tr('Codex 没有列出本插件的 UserPromptSubmit。请在插件设置中确认已安装并启用 Codex Polish。',
450
+ 'Codex hasn’t listed UserPromptSubmit for this plugin. Check that Codex Polish is installed and enabled in plugin settings.', lang);
451
+ if (!hook.enabled) return tr(`UserPromptSubmit 已停用。要自动润色或附带历史,可在 ${settings} 中启用它。`,
452
+ `UserPromptSubmit is disabled. To use automatic polishing or include history, enable it in ${settings}.`, lang);
453
+ if (hook.trustStatus === 'trusted') return tr('Codex 已信任 UserPromptSubmit。', 'Codex trusts UserPromptSubmit.', lang);
454
+ if (hook.trustStatus === 'modified')
455
+ return tr(`已安装的插件内容有变,Codex 要求重新确认。请在 ${settings} 中审查并重新信任 UserPromptSubmit,再新开聊天。`,
456
+ `The installed plugin changed. Review and trust UserPromptSubmit again in ${settings}, then start a new chat.`, lang);
457
+ if (hook.trustStatus === 'untrusted')
458
+ return tr(`要自动润色或附带历史,请在 ${settings} 中信任本插件的 UserPromptSubmit,再新开聊天。`,
459
+ `For automatic polishing or history, trust UserPromptSubmit in ${settings}, then start a new chat.`, lang);
460
+ return tr(`请在 ${settings} 中查看 UserPromptSubmit 的信任状态。`,
461
+ `Check the trust status of UserPromptSubmit in ${settings}.`, lang);
462
+ }
393
463
  async function hasUnlistedPlugin() {
394
464
  const { config } = await nativeConfig('config/read', { includeLayers: false });
395
465
  if (config.marketplaces?.[MARKET])
@@ -410,16 +480,15 @@ async function verifyInstalled(run, setEnabled, version, enabled) {
410
480
  throw fail('Codex 没有确认插件的启用状态。', "Codex didn't confirm whether the plugin is enabled.");
411
481
  }
412
482
  }
413
- async function rollback(run, setEnabled, previous, before, target) {
414
- const current = registration(run);
415
- if (![null, previous, target].includes(current))
483
+ async function rollback(run, setEnabled, previous, before, target, store) {
484
+ const market = registeredMarket(run, store);
485
+ if (![null, previous, target].includes(activeSnapshot(store)))
416
486
  throw fail('其他进程修改了市场。', 'Another process changed the marketplace.');
417
487
  if (!before && installed(run)) run('remove', PLUGIN_ID);
418
- if (current !== previous) {
419
- if (current) run('marketplace', 'remove', MARKET);
420
- if (previous) run('marketplace', 'add', previous);
421
- }
422
- if (registration(run) !== previous)
488
+ if (!previous && market) run('marketplace', 'remove', MARKET);
489
+ activateSnapshot(store, previous);
490
+ if (previous && !market) run('marketplace', 'add', store);
491
+ if (registeredMarket(run, store) !== (previous ? store : null) || activeSnapshot(store) !== previous)
423
492
  throw fail('Codex 没有恢复更新前的市场来源。', "Codex didn't restore the previous marketplace.");
424
493
  if (before) {
425
494
  verifyReceipt(run('add', PLUGIN_ID), previous, before.version);
@@ -427,7 +496,6 @@ async function rollback(run, setEnabled, previous, before, target) {
427
496
  } else if (installed(run))
428
497
  throw fail('Codex 没有清除未完成的安装。', "Codex didn't remove the incomplete installation.");
429
498
  }
430
- const sourceId = (path) => (path === null ? null : sha(path).digest('hex'));
431
499
  export function pendingUpdate(store) {
432
500
  let fd;
433
501
  try {
@@ -452,7 +520,7 @@ export function pendingUpdate(store) {
452
520
  snapshotName.test(entry.target) &&
453
521
  typeof entry.version === 'string' &&
454
522
  validVersion.test(entry.version) &&
455
- (entry.previous === null || (typeof entry.previous === 'string' && /^[0-9a-f]{64}$/.test(entry.previous)))
523
+ typeof entry.previous === 'string' && snapshotName.test(entry.previous)
456
524
  )
457
525
  return entry;
458
526
  }
@@ -473,14 +541,15 @@ function syncStore(store) {
473
541
  fs.closeSync(fd);
474
542
  }
475
543
  }
476
- function savePending(store, entry) {
477
- const tmp = join(store, '.prepare-update-' + randomUUID());
544
+ function writeAtomicJson(file, entry) {
545
+ const dir = dirname(file);
546
+ const tmp = join(dir, '.prepare-update-' + randomUUID());
478
547
  const fd = fs.openSync(tmp, 'wx', 0o600);
479
548
  try {
480
549
  fs.writeFileSync(fd, JSON.stringify(entry));
481
550
  fs.fsyncSync(fd);
482
- fs.renameSync(tmp, join(store, '.pending-update.json'));
483
- syncStore(store);
551
+ fs.renameSync(tmp, file);
552
+ syncStore(dir);
484
553
  } finally {
485
554
  fs.closeSync(fd);
486
555
  fs.rmSync(tmp, { force: true });
@@ -495,15 +564,16 @@ function finishPending(store) {
495
564
  }
496
565
  syncStore(store);
497
566
  }
498
- export function preserveNativeCache(store, previous, state) {
567
+ export function preserveNativeCache(store, previous, state, alternate) {
499
568
  if (store !== snapshotStore()) return;
500
569
  const version = state?.version;
501
- function verifiedSource() {
502
- if (!previous || !ownsSnapshot(previous, store) || !statMaybe(previous)) return null;
503
- return verifiedPaths(previous) && bundleVersion(previous) === version ? join(previous, PRODUCT) : null;
570
+ function verifiedSources() {
571
+ return [...new Set([previous, alternate])].filter((path) =>
572
+ path && ownsSnapshot(path, store) && statMaybe(path) && verifiedPaths(path) && bundleVersion(path) === version
573
+ ).map((path) => join(path, PRODUCT));
504
574
  }
505
575
  try {
506
- const backup = preserve(codexProfile(), MARKET, NAME, version, verifiedSource);
576
+ const backup = preserve(codexProfile(), MARKET, NAME, version, verifiedSources);
507
577
  if (backup)
508
578
  console.log(tr('已保留有改动或没法核对的插件缓存:', 'Kept a changed or unverified plugin cache at: ') + backup);
509
579
  } catch (error) {
@@ -514,17 +584,25 @@ export function preserveNativeCache(store, previous, state) {
514
584
  }
515
585
  }
516
586
  async function setup(root, store, run, setEnabled, action) {
517
- const previous = registration(run);
587
+ const market = registeredMarket(run, store);
588
+ const active = activeSnapshot(store);
589
+ if (market && !active)
590
+ throw fail('已注册的市场缺少安装清单,请在 Codex 插件设置中检查。', 'The registered marketplace manifest is missing. Check it in Codex plugin settings.');
591
+ let previous = market ? active : null;
518
592
  checkSource(previous, store);
519
593
  const pending = pendingUpdate(store);
520
- if (pending && previous && sourceId(previous) !== pending.previous && previous !== join(store, pending.target)) {
521
- throw fail(
522
- '上次更新后,市场来源变了。请先在 Codex 里核对来源,再重新安装。',
523
- 'The marketplace source changed after the interrupted update. Check it in Codex before reinstalling.'
524
- );
594
+ if (pending) {
595
+ const original = join(store, pending.previous);
596
+ checkSource(original, store);
597
+ if (!market || ![original, join(store, pending.target)].includes(active))
598
+ throw fail('上次更新后,市场来源变了。请先在 Codex 里核对来源。', 'The marketplace source changed after the interrupted update. Check the source in Codex.');
599
+ preserveNativeCache(store, active, installed(run), original);
600
+ await rollback(run, setEnabled, original, pending, join(store, pending.target), store);
601
+ finishPending(store);
602
+ previous = original;
525
603
  }
526
604
  const before = installed(run);
527
- if (!previous && !pending && (before || (store === snapshotStore() && (await hasUnlistedPlugin())))) {
605
+ if (!previous && (before || (store === snapshotStore() && (await hasUnlistedPlugin())))) {
528
606
  throw fail(
529
607
  'Codex 里还有安装记录,但市场来源已被移除。请用这个包运行 uninstall,再运行 setup。项目设置会保留。',
530
608
  'Codex still has an installation record, but the marketplace was removed. Run uninstall from this package, then setup. Your project settings will be kept.'
@@ -536,20 +614,16 @@ async function setup(root, store, run, setEnabled, action) {
536
614
  "Codex didn't report the installed version and enabled state."
537
615
  );
538
616
  }
539
- const original = pending || before,
540
- enabled = original?.enabled ?? true;
541
- const versions = [before, pending].filter(Boolean).map((row) => row.version);
542
- const [target, version] = makeSnapshot(root, store, versions, previous);
543
- if (original)
544
- savePending(store, { previous: sourceId(previous), target: basename(target), version: original.version, enabled });
617
+ const enabled = before?.enabled ?? true;
618
+ const [target, version] = makeSnapshot(root, store, before ? [before.version] : [], previous);
619
+ if (before)
620
+ writeAtomicJson(join(store, '.pending-update.json'), { previous: basename(previous), target: basename(target), version: before.version, enabled });
545
621
  preserveNativeCache(store, previous, before);
546
622
  try {
547
- if (previous !== target) {
548
- if (previous) run('marketplace', 'remove', MARKET);
549
- run('marketplace', 'add', target);
550
- }
623
+ activateSnapshot(store, target);
624
+ if (!market) run('marketplace', 'add', store);
551
625
  verifyReceipt(run('add', PLUGIN_ID), target, version);
552
- if (registration(run) !== target)
626
+ if (registeredMarket(run, store) !== store || activeSnapshot(store) !== target)
553
627
  throw fail(
554
628
  'Codex 没有确认这次安装的市场来源。',
555
629
  "Codex didn't confirm the marketplace source for this installation."
@@ -557,17 +631,17 @@ async function setup(root, store, run, setEnabled, action) {
557
631
  await verifyInstalled(run, setEnabled, version, enabled);
558
632
  } catch (error) {
559
633
  try {
560
- await rollback(run, setEnabled, previous, before, target);
634
+ await rollback(run, setEnabled, previous, before, target, store);
561
635
  } catch {
562
636
  throw fail(
563
637
  '安装失败,Codex 没能恢复。本地快照已保留,请重新运行 setup。',
564
638
  "Codex couldn't restore the previous installation. The local copy is still there. Run setup again."
565
639
  );
566
640
  }
567
- if (before && !pending) finishPending(store);
641
+ if (before) finishPending(store);
568
642
  throw error;
569
643
  }
570
- if (original) finishPending(store);
644
+ if (before) finishPending(store);
571
645
  if (!enabled)
572
646
  return [
573
647
  tr(
@@ -583,16 +657,22 @@ async function setup(root, store, run, setEnabled, action) {
583
657
  const lines = [
584
658
  status,
585
659
  tr(
586
- '未设置模式的项目默认自动润色,已保存的模式继续生效。改写时,Google 会收到用占位符保护了固定内容的本轮问题和草稿,以及按原文附带的历史问答(默认最多 2 轮)。开启 OpenAI 检查时,OpenAI 只收到本轮材料。',
587
- 'Projects without a saved mode default to automatic polishing. Saved modes still apply. On a rewrite, Google receives the current question and draft with fixed details masked, plus earlier exchanges as written (up to two by default). Optional OpenAI checks use only current-turn material.',
660
+ '未设置模式的项目默认自动润色,已保存的模式继续生效。使用默认的普通改写模式并开启风格检查时,OpenAI 根据本轮问题和草稿原文判断要不要润色。Google 收到待改的答复、它所回答的问题,以及你这次提出的改写要求。默认还会附带这份答复之前最多 2 轮问答。',
661
+ 'Projects without a saved mode default to automatic polishing. Saved modes still apply. In normal rewrite mode (the default), the optional OpenAI style check uses your current question and draft as written. Gemini receives the selected draft, its question, any editing directions you give for this rewrite and, by default, up to two exchanges that preceded the draft.',
588
662
  lang
589
663
  ),
590
664
  tr(
591
- '要自动润色或附带历史,请在 Codex 的「设置 → Hooks」(CLI 输入 /hooks)中信任本插件的 UserPromptSubmit,再新开一个聊天。想改模式,可以说「只在我要求时润色」或「关闭回复润色」。',
592
- 'For automatic polishing or history, trust the plugin’s UserPromptSubmit hook in Codex Settings → Hooks (/hooks in the CLI), then start a new chat. To change modes, say “Only polish when I ask” or “Turn off Codex Polish”.',
665
+ '如果你写了自己的润色提示词,插件会把它和草稿一起发给 Google。开了 OpenAI 检查的话,OpenAI 只在判断草稿要不要改时用到这段提示词。',
666
+ 'If you set a custom polishing prompt, it is also sent to Google when rewriting. If the OpenAI style check is on, it also uses that prompt to decide whether the draft needs editing.',
667
+ lang
668
+ ),
669
+ tr(
670
+ '想改触发时机,可以说「只在我要求时润色」或「关闭回复润色」。想跳过 OpenAI,可以说「这条用 Turbo」或「让 Gemini 重写上一条」。希望以后都这样,可以说「把这个项目的默认模式设成 Turbo」。',
671
+ 'To change when polishing runs, say “Only polish when I ask” or “Turn off Codex Polish”. To skip OpenAI once, say “Use Turbo for this answer” or “Have Gemini rewrite your last reply”. To keep using Turbo, say “Make Turbo the default for this project”.',
593
672
  lang
594
673
  )
595
674
  ];
675
+ if (store === snapshotStore()) lines.push(await hookGuidance(lang));
596
676
  if (action === 'setup') {
597
677
  const guide = join(target, lang === 'zh' ? GUIDE : GUIDE.replace('credentials.md', 'credentials.en.md'));
598
678
  lines.push(tr(`配置指南:${guide}`, `Setup guide: ${guide}`, lang));
@@ -684,7 +764,9 @@ function cleanUninstallData(store) {
684
764
  return message;
685
765
  }
686
766
  async function uninstall(store, run) {
687
- const previous = registration(run);
767
+ const market = registeredMarket(run, store);
768
+ const active = activeSnapshot(store);
769
+ const previous = market && active;
688
770
  requireManagedSource(previous, store);
689
771
  if (previous) bundleVersion(previous);
690
772
  const before = installed(run);
@@ -705,7 +787,16 @@ async function uninstall(store, run) {
705
787
  "Couldn't verify the marketplace for the installed plugin. Check its source before uninstalling."
706
788
  );
707
789
  }
708
- if (present || previous) preserveNativeCache(store, previous, before);
790
+ if (present || previous) {
791
+ // A known marketplace can still be removed if its interrupted-update journal is damaged.
792
+ let pending;
793
+ try {
794
+ pending = pendingUpdate(store);
795
+ } catch (error) {
796
+ if (!(error instanceof SetupError)) throw error;
797
+ }
798
+ preserveNativeCache(store, previous, before, pending && join(store, pending.previous));
799
+ }
709
800
  if (present) {
710
801
  run('remove', PLUGIN_ID);
711
802
  if (!previous && store === snapshotStore() ? await hasUnlistedPlugin() : installed(run))
@@ -714,7 +805,7 @@ async function uninstall(store, run) {
714
805
  'Codex still lists the plugin as installed. Run uninstall again.'
715
806
  );
716
807
  }
717
- if (previous) {
808
+ if (market) {
718
809
  run('marketplace', 'remove', MARKET);
719
810
  if (registration(run))
720
811
  throw fail(
@@ -722,6 +813,7 @@ async function uninstall(store, run) {
722
813
  'Codex still lists the marketplace. Run uninstall again.'
723
814
  );
724
815
  }
816
+ activateSnapshot(store, null);
725
817
  return cleanUninstallData(store);
726
818
  }
727
819
  // An exclusive SQLite transaction serializes installers on both supported
@@ -768,15 +860,29 @@ export async function manage(action, root, store, run = codex, setEnabled = writ
768
860
  return setup(root, store, run, setEnabled, action);
769
861
  });
770
862
  }
771
- function readChecks() {
863
+ function projectPreference(args, cwd) {
772
864
  const helper = join(ROOT, PRODUCT, 'hooks/preferences.mjs');
773
- const result = spawnSync(process.execPath, [helper, 'check', '--cwd', process.cwd()], {
865
+ return spawnSync(process.execPath, [helper, ...args, '--cwd', cwd], {
774
866
  encoding: 'utf8',
775
867
  timeout: 10_000
776
868
  });
869
+ }
870
+ function readChecks(cwd = process.cwd()) {
871
+ const result = projectPreference(['check'], cwd);
777
872
  if (result.status !== 0 || result.error)
778
873
  throw fail('没法读取插件的环境检查结果。', "Couldn't read the plugin environment check results.");
779
- return JSON.parse(result.stdout);
874
+ const checks = JSON.parse(result.stdout);
875
+ if (checks.agy_available && !supportedAgy(checks.agy_path)) {
876
+ checks.agy_available = false;
877
+ checks.blockers.push('agy_unsupported');
878
+ }
879
+ return checks;
880
+ }
881
+ function saveSetupMode(mode, cwd) {
882
+ const result = projectPreference(['set-rewrite-mode', mode], cwd);
883
+ if (result.status !== 0 || result.error || JSON.parse(result.stdout).rewrite_mode !== mode)
884
+ throw fail(`插件已安装,但没能将改写模式保存到 ${cwd}。请检查项目的写入权限。`,
885
+ `The plugin is installed, but the rewrite mode could not be saved in ${cwd}. Check the project’s write permissions.`);
780
886
  }
781
887
  async function runBootstrap(script, target, options) {
782
888
  const proc = spawn('/bin/bash', [script, '--dir', target], { ...options, stdio: 'ignore', detached: true });
@@ -820,32 +926,39 @@ async function downloadBootstrap(file) {
820
926
  }
821
927
  throw fail('从 Google 下载 agy 失败。', 'Could not download agy from Google.');
822
928
  }
929
+ function agyEnvironment() {
930
+ const env = { ...process.env };
931
+ for (const key of ['OPENAI_API_KEY', 'GEMINI_API_KEY', 'BASH_ENV', 'ENV']) delete env[key];
932
+ return env;
933
+ }
934
+ function supportedAgy(binary) {
935
+ const result = spawnSync(binary, ['--version'], {
936
+ env: agyEnvironment(), encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'],
937
+ timeout: 5000, maxBuffer: 16 * 1024, killSignal: 'SIGKILL'
938
+ });
939
+ const version = result.status === 0 && /(?:^|\s)v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?)(?=\s|$)/.exec(result.stdout);
940
+ return Boolean(version && compareVersions(version[1], '1.2.1') >= 0);
941
+ }
823
942
  export async function installAgy() {
824
943
  const target = join(homedir(), '.local/bin');
825
944
  fs.mkdirSync(target, { recursive: true });
826
945
  await withLock(join(target, '.codex-polish-agy.sqlite'), async () => {
827
- if (findAgy()) return;
946
+ const existing = findAgy();
947
+ if (existing) {
948
+ if (supportedAgy(existing)) return;
949
+ throw fail('请将现有的 Antigravity CLI 更新到 1.2.1 或更高版本。', 'Update your existing Antigravity CLI to version 1.2.1 or later.');
950
+ }
828
951
  const binary = join(target, 'agy');
829
952
  if (statMaybe(binary))
830
953
  throw fail(`请先检查 ${binary},这个路径已被占用。`, `Check ${binary}. That path is already in use.`);
831
954
  const temp = fs.mkdtempSync(join(tmpdir(), 'codex-polish-agy-')),
832
955
  script = join(temp, 'install.sh');
833
- const env = { ...process.env };
834
- for (const key of ['OPENAI_API_KEY', 'GEMINI_API_KEY', 'BASH_ENV', 'ENV']) delete env[key];
835
- const options = { cwd: temp, env };
956
+ const options = { cwd: temp, env: agyEnvironment() };
836
957
  try {
837
958
  await downloadBootstrap(script);
838
959
  try {
839
960
  await runBootstrap(script, target, options);
840
- const output = execFileSync(binary, ['--version'], {
841
- ...options,
842
- encoding: 'utf8',
843
- stdio: ['ignore', 'pipe', 'pipe'],
844
- timeout: 10_000,
845
- killSignal: 'SIGKILL'
846
- });
847
- const version = /\b(\d+\.\d+\.\d+)\b/.exec(output);
848
- if (!version || compareVersions(version[1], '1.2.1') < 0)
961
+ if (!supportedAgy(binary))
849
962
  throw fail('需要 Antigravity CLI 1.2.1 或更新版。', 'Antigravity CLI 1.2.1 or later is required.');
850
963
  } catch (error) {
851
964
  if (statMaybe(binary) && !fs.lstatSync(binary).isDirectory()) fs.unlinkSync(binary);
@@ -857,31 +970,34 @@ export async function installAgy() {
857
970
  });
858
971
  }
859
972
  function decisionsSummary(checks, lang) {
973
+ if (checks.rewrite_mode === 'turbo')
974
+ return tr(
975
+ 'Turbo 会跳过 OpenAI 检查,把每份符合条件的草稿直接交给 Gemini。可在项目里说「恢复普通模式」。',
976
+ 'Turbo skips the OpenAI check and sends each eligible draft directly to Gemini. Say “Switch back to normal mode” to restore the normal workflow.',
977
+ lang
978
+ );
860
979
  if (checks.decisions_mode === 'off')
861
980
  return tr(
862
- '改写检查:未开启,回复会直接交给 Gemini 润色。',
863
- 'Rewrite checks: off. Replies go straight to Gemini.',
981
+ 'OpenAI 风格检查已关闭,草稿会直接交给 Gemini 润色。',
982
+ 'The OpenAI style check is off. Drafts go straight to Gemini.',
864
983
  lang
865
984
  );
866
- if (checks.blockers.includes('openai_key_invalid'))
867
- return tr('OpenAI 检查目前用不了。', "OpenAI checks aren't available right now.", lang);
985
+ if (checks.openai_key_malformed)
986
+ return tr('OPENAI_API_KEY 格式有误,草稿将直接交给 Gemini。要启用 OpenAI 检查,请重新复制密钥。',
987
+ 'OPENAI_API_KEY has an invalid format. Drafts go straight to Gemini. Copy the key again to enable the OpenAI check.', lang);
868
988
  if (checks.decisions_enabled)
869
989
  return tr(
870
- '改写检查:已配置 OpenAI Decisions,先判断要不要改写,改完再核对原意没变。',
871
- 'Rewrite checks: using OpenAI Decisions to decide whether a reply needs a rewrite and verify the meaning stays intact.',
990
+ '已启用 OpenAI Decisions。OpenAI 只用本轮问题、草稿和已设置的自定义润色提示词判断是否需要改写。',
991
+ 'OpenAI Decisions is on. OpenAI uses only the current question, draft, and any custom polishing prompt to decide whether to rewrite.',
872
992
  lang
873
993
  );
874
994
  return tr(
875
- '改写检查:回复直接交给 Gemini 润色。想加一层检查,在 Codex 里说「配置 OpenAI Decisions」。',
876
- 'Rewrite checks: replies go straight to Gemini. If you want extra checks, tell Codex “Set up OpenAI Decisions”.',
995
+ '草稿会直接交给 Gemini 润色。想先让 OpenAI 判断草稿是否需要润色,可以在 Codex 里说「配置 OpenAI Decisions」。',
996
+ 'Drafts go straight to Gemini. To have OpenAI check whether they need editing first, tell Codex “Set up OpenAI Decisions”.',
877
997
  lang
878
998
  );
879
999
  }
880
1000
  const issues = {
881
- openai_key_invalid: [
882
- 'OPENAI_API_KEY 格式不对。请重新复制密钥,或者在项目里说「这个项目只用 Gemini 改写」,跳过 OpenAI 检查。',
883
- 'OPENAI_API_KEY is invalid. Copy the key again, or ask Codex to “Use only Gemini for rewrites in this project”.'
884
- ],
885
1001
  gemini_key_missing: [
886
1002
  '你选了用 API 密钥登录 Google。去 Google AI Studio 点 Create API key,然后把密钥设为 GEMINI_API_KEY。',
887
1003
  'You chose Google API key sign-in. Select Create API key in Google AI Studio, then set GEMINI_API_KEY.',
@@ -897,14 +1013,27 @@ const issues = {
897
1013
  "Couldn't find agy. Install it from the extracted plugin folder with node scripts/install.mjs setup --install-agy, or follow Google’s guide.",
898
1014
  AGY_INSTALL
899
1015
  ],
1016
+ agy_unsupported: [
1017
+ '请确认 agy --version 能显示 1.2.1 或更高版本。需要更新时可参考 Google 的安装指南。',
1018
+ 'Check that agy --version reports 1.2.1 or later. To update your installation, follow Google’s guide.',
1019
+ AGY_INSTALL
1020
+ ],
900
1021
  unsupported_google_auth: [
901
1022
  '移除 CODEX_POLISH_AGY_AUTH 就能恢复 Antigravity 默认登录(existing-session)。',
902
1023
  'Unset CODEX_POLISH_AGY_AUTH to use the default Antigravity sign-in (existing-session).'
903
1024
  ],
1025
+ rewrite_mode_invalid: [
1026
+ '这个项目的改写模式无效。请在 Codex 里说「恢复普通模式」或「切换到 Turbo 模式」。',
1027
+ 'The project rewrite mode is invalid. Ask Codex to “Switch back to normal mode” or “Switch to turbo mode”.'
1028
+ ],
904
1029
  gemini_model_invalid: [
905
1030
  '这个项目的改写模型设置无效。请在 Codex 里说「选择改写模型」。',
906
1031
  "The project's model setting is invalid. Ask Codex to “Choose a rewrite model”."
907
1032
  ],
1033
+ editor_prompt_invalid: [
1034
+ '这个项目的润色提示词无效。请在 Codex 里说「设置润色提示词」并提供新文本,或说「恢复默认润色提示词」。',
1035
+ 'The project polishing prompt is invalid. Ask Codex to “Set the polishing prompt” with new text or “Restore the default polishing prompt”.'
1036
+ ],
908
1037
  unsupported_node: [
909
1038
  '安装 Node.js 22.16 或更高版本,再用 node --version 检查。',
910
1039
  'Install Node.js 22.16 or later and check with node --version.'
@@ -945,8 +1074,8 @@ export function configurationSteps(checks) {
945
1074
  lang
946
1075
  )
947
1076
  );
1077
+ if (checks.rewrite_mode) lines.push(decisionsSummary(checks, lang));
948
1078
  lines.push(
949
- decisionsSummary(checks, lang),
950
1079
  tr(
951
1080
  '在项目里新开一个 Codex 对话,说「配置回复润色」就能查看或修改设置。',
952
1081
  'Open a new project chat in Codex and say “Set up Codex Polish” to view or change settings.',
@@ -955,8 +1084,8 @@ export function configurationSteps(checks) {
955
1084
  );
956
1085
  const examples = {
957
1086
  auto: [
958
- '在已信任 hook 的新聊天里,直接问「用一句话解释 DNS。」就会触发自动润色。',
959
- 'After trusting the hook, try automatic polishing in a new chat. Ask “Explain what DNS does in one sentence.”'
1087
+ '在项目里新开聊天,问「用一句话解释 DNS。」即可试用自动润色。',
1088
+ 'To try automatic polishing, open a new project chat and ask “Explain what DNS does in one sentence.”'
960
1089
  ],
961
1090
  manual: [
962
1091
  '这个项目只在点名时润色。试一句:「用一句话解释 DNS,再把你的回复润色一下。」',
@@ -977,7 +1106,7 @@ async function ask(prompt) {
977
1106
  io.once('SIGINT', cancel);
978
1107
  io.once('close', cancel);
979
1108
  try {
980
- return (await io.question(prompt, { signal: controller.signal })).trim().toLowerCase();
1109
+ return (await io.question(prompt, { signal: controller.signal })).trim();
981
1110
  } catch {
982
1111
  console.log();
983
1112
  return null;
@@ -991,18 +1120,153 @@ function openPage(url) {
991
1120
  .status === 0
992
1121
  );
993
1122
  }
1123
+ function isProjectDirectory(directory) {
1124
+ return directory !== dirname(directory) && directory !== canonical(homedir());
1125
+ }
1126
+ async function chooseSetupProject(cwd, prompt, lang) {
1127
+ const launchedFromPackage = cwd === ROOT && !fs.existsSync(join(ROOT, '.git'));
1128
+ const launchedFromDownloads = cwd === canonical(join(homedir(), 'Downloads'));
1129
+ if (isProjectDirectory(cwd) && !launchedFromPackage && !launchedFromDownloads &&
1130
+ process.env.CODEX_POLISH_INSTALL_WINDOW !== '1') return cwd;
1131
+ for (;;) {
1132
+ const answer = await prompt(tr('输入要配置的项目目录,或按回车稍后在 Codex 里选择:',
1133
+ 'Enter the project folder, or press Enter to choose later in Codex: ', lang));
1134
+ if (!answer) return null;
1135
+ const name = answer.startsWith('~/') ? join(homedir(), answer.slice(2)) : resolve(cwd, answer);
1136
+ try {
1137
+ const project = fs.realpathSync(name);
1138
+ if (isProjectDirectory(project) && fs.statSync(project).isDirectory()) return project;
1139
+ } catch { /* Ask again if the folder does not exist or cannot be accessed. */ }
1140
+ console.log(tr('请输入已有的项目文件夹。', 'Enter an existing project folder.', lang));
1141
+ }
1142
+ }
1143
+ async function chooseOption(title, options, lang, input = process.stdin, output = process.stdout) {
1144
+ if (input.destroyed || input.readableEnded) return null;
1145
+ const wasRaw = !!input.isRaw;
1146
+ const wasFlowing = input.readableFlowing;
1147
+ let selected = 0;
1148
+ function draw() {
1149
+ for (const [index, option] of options.entries()) {
1150
+ clearLine(output, 0);
1151
+ output.write((selected === index ? '❯ ● ' : ' ○ ') + option.name);
1152
+ if (index < options.length - 1) output.write('\r\n');
1153
+ }
1154
+ }
1155
+ function restoreInput() {
1156
+ if (!wasRaw && input.isRaw && !input.destroyed) input.setRawMode(false);
1157
+ }
1158
+ emitKeypressEvents(input);
1159
+ const keys = on(input, 'keypress', { close: ['end', 'close'] });
1160
+ // A stream may destroy its terminal handle immediately after emitting end.
1161
+ input.once('end', restoreInput);
1162
+ try {
1163
+ if (!wasRaw) input.setRawMode(true);
1164
+ input.resume();
1165
+ output.write(title + '\n' + tr('用 ↑ ↓ 方向键移动,按回车确认。\n', 'Use ↑ ↓ to move and Enter to confirm.\n', lang));
1166
+ draw();
1167
+ for await (const [, key] of keys) {
1168
+ if (key.name === 'return' || key.name === 'enter') return options[selected].id;
1169
+ if (key.name === 'escape' || (key.ctrl && ['c', 'd'].includes(key.name))) return null;
1170
+ if (key.name !== 'up' && key.name !== 'down') continue;
1171
+ const next = Math.max(0, Math.min(options.length - 1, selected + (key.name === 'up' ? -1 : 1)));
1172
+ if (next === selected) continue;
1173
+ selected = next;
1174
+ moveCursor(output, 0, 1 - options.length);
1175
+ cursorTo(output, 0);
1176
+ draw();
1177
+ }
1178
+ return null;
1179
+ } finally {
1180
+ await keys.return();
1181
+ input.off('end', restoreInput);
1182
+ restoreInput();
1183
+ if (!wasFlowing) input.pause();
1184
+ output.write('\n');
1185
+ }
1186
+ }
1187
+ export function chooseSetupMode(project, lang, input, output) {
1188
+ const title = tr(
1189
+ `为这个项目选择改写模式:${project}\nNormal(默认):按需润色,可先用 OpenAI 判断。\nTurbo:跳过 OpenAI,将每条可润色的回复直接交给 Gemini。`,
1190
+ `Choose a rewrite mode for ${project}\nNormal (default): Polish as needed, with an optional OpenAI check.\nTurbo: Skip OpenAI and send every eligible reply directly to Gemini.`, lang);
1191
+ return chooseOption(title, [{ id: 'normal', name: 'Normal' }, { id: 'turbo', name: 'Turbo' }], lang, input, output);
1192
+ }
1193
+
1194
+ export async function discoverSetupModels(checks) {
1195
+ const workspace = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), 'codex-polish-models-')));
1196
+ try {
1197
+ const skill = join(ROOT, PRODUCT, 'skills/codex-polish');
1198
+ const task = [
1199
+ 'Discover the Gemini models available to this account. This is a metadata lookup. Do not send a prompt to Gemini.',
1200
+ 'Use your own execution tools to directly hold and drive the official agy acp process. Do not run an ACP client script.',
1201
+ 'Follow the startup, authentication, session/new (id 3) and cleanup steps in ' + JSON.stringify(join(skill, 'references/acp.md')) + '.',
1202
+ 'Use the current temporary directory as the private workspace, and the bundled default editor role.',
1203
+ 'The official agy executable is ' + JSON.stringify(checks.agy_path) + ' and the authentication mode is ' + JSON.stringify(checks.google_auth_method) + '.',
1204
+ 'When starting the official process, pipe its stdout through tee acp-frames.jsonl in the current working directory.',
1205
+ 'The installer reads the actual session/new response from that file. Never create or modify that file yourself, delete it, or write any model list. Close the session and stop after session/new. If the lookup fails, stop.'
1206
+ ].join('\n');
1207
+ const child = spawn('codex', ['exec', '--ephemeral', '--skip-git-repo-check', '-C', workspace,
1208
+ '-c', 'plugins."codex-polish@codex-polish-local".enabled=false', task], { cwd: workspace, stdio: 'ignore' });
1209
+ const interrupt = () => child.kill('SIGINT');
1210
+ const terminate = () => child.kill('SIGTERM');
1211
+ process.once('SIGINT', interrupt);
1212
+ process.once('SIGTERM', terminate);
1213
+ let code;
1214
+ try {
1215
+ code = await new Promise((done, reject) => child.once('error', reject).once('close', done));
1216
+ } finally {
1217
+ process.off('SIGINT', interrupt);
1218
+ process.off('SIGTERM', terminate);
1219
+ }
1220
+ if (code !== 0) return [];
1221
+ for (const line of readPlain(join(workspace, 'acp-frames.jsonl')).toString('utf8').split('\n')) {
1222
+ if (!line.trim()) continue;
1223
+ const frame = JSON.parse(line);
1224
+ if (frame.id === 3 && !frame.method) return sessionCatalog(line, 3n).models;
1225
+ }
1226
+ return [];
1227
+ } finally {
1228
+ fs.rmSync(workspace, { force: true, recursive: true });
1229
+ }
1230
+ }
1231
+
1232
+ export async function chooseSetupModel(checks, lang, input, output, discover = discoverSetupModels) {
1233
+ const choose = (title, rows) => chooseOption(title, rows, lang, input, output);
1234
+ const choice = await choose(tr('选择改写用的 Gemini 模型', 'Choose the Gemini model for rewrites', lang), [
1235
+ { id: 'default', name: tr('Gemini 4 Hydrogen(默认)', 'Gemini 4 Hydrogen (default)', lang) },
1236
+ { id: 'lookup', name: tr('让 Codex 查询我账号的可用模型…', 'Ask Codex to list models available to my account…', lang) }
1237
+ ]);
1238
+ if (choice !== 'lookup') return choice === 'default' ? DEFAULT_GEMINI_MODEL : null;
1239
+ console.log(tr('Codex 正在通过 Antigravity 获取模型列表…', 'Codex is reading the model list from Antigravity…', lang));
1240
+ let models;
1241
+ try { models = await discover(checks); } catch { /* Report failed lookup below. */ }
1242
+ if (!Array.isArray(models) || !models.length) {
1243
+ console.log(tr('没能读取模型。稍后在 Codex 里说「选择改写模型」可重试。',
1244
+ 'Couldn’t read the model list. Say “Choose a rewrite model” in Codex to retry.', lang));
1245
+ return null;
1246
+ }
1247
+ const rows = models.map(({ id, name }) => ({
1248
+ id, name: models.some(model => model.id !== id && model.name === name) ? name + ' (' + id + ')' : name
1249
+ }));
1250
+ return choose(tr('用哪个模型改写?', 'Which model should rewrite your replies?', lang), rows);
1251
+ }
1252
+
994
1253
  export async function showSetupGuidance({
1254
+ cwd = process.cwd(),
995
1255
  installDependency = false,
996
1256
  dependencyOnly = false,
997
1257
  interactive = process.stdin.isTTY && process.stdout.isTTY,
998
1258
  check = readChecks,
1259
+ saveRewriteMode = saveSetupMode,
1260
+ chooseMode = chooseSetupMode,
1261
+ chooseModel = chooseSetupModel,
999
1262
  install = installAgy,
1000
1263
  prompt = ask,
1001
1264
  browse = openPage
1002
1265
  } = {}) {
1003
1266
  let checks, lang;
1267
+ const project = interactive && !dependencyOnly ? await chooseSetupProject(cwd, prompt, language(cwd)) : cwd;
1004
1268
  try {
1005
- checks = check();
1269
+ checks = check(project ?? cwd);
1006
1270
  lang = checks.ui_language || language();
1007
1271
  } catch {
1008
1272
  console.log(
@@ -1013,23 +1277,36 @@ export async function showSetupGuidance({
1013
1277
  );
1014
1278
  return !installDependency;
1015
1279
  }
1280
+ if (interactive && !dependencyOnly && project && checks.rewrite_mode && checks.rewrite_mode_configured === false) {
1281
+ const selected = await chooseMode(project, lang);
1282
+ if (selected) {
1283
+ await saveRewriteMode(selected, project);
1284
+ checks = check(project);
1285
+ console.log(tr(`已为这个项目保存 ${selected === 'turbo' ? 'Turbo' : 'Normal'} 模式。`,
1286
+ `Saved ${selected === 'turbo' ? 'Turbo' : 'Normal'} mode for this project.`, lang));
1287
+ }
1288
+ }
1289
+ if (installDependency && checks.blockers.includes('agy_unsupported')) {
1290
+ console.error(tr(issues.agy_unsupported[0], issues.agy_unsupported[1], lang) + '\n' + AGY_INSTALL);
1291
+ return false;
1292
+ }
1016
1293
  if (checks.blockers.includes('agy_missing')) {
1017
1294
  let requested = installDependency;
1018
1295
  if (interactive && !requested)
1019
1296
  requested = ['', 'y', 'yes', '是'].includes(
1020
- await prompt(
1297
+ (await prompt(
1021
1298
  tr(
1022
1299
  '改写回复需要 Google 的 Antigravity 命令行工具(agy)。现在安装吗?[Y/n] ',
1023
1300
  'Codex Polish needs Google’s Antigravity CLI (agy). Install it now? [Y/n] ',
1024
1301
  lang
1025
1302
  )
1026
- )
1303
+ ))?.toLowerCase()
1027
1304
  );
1028
1305
  if (requested) {
1029
1306
  try {
1030
1307
  console.log(tr('正在从 Google 下载并安装 agy…', 'Downloading and installing agy from Google…', lang));
1031
1308
  await install();
1032
- checks = check();
1309
+ checks = check(project ?? cwd);
1033
1310
  if (!checks.agy_available)
1034
1311
  throw fail('装好后仍找不到 agy。', 'The installer finished, but agy is still missing.');
1035
1312
  console.log(tr('agy 已安装,可以使用。', 'agy is installed and ready to use.', lang));
@@ -1050,6 +1327,16 @@ export async function showSetupGuidance({
1050
1327
  } else if (installDependency)
1051
1328
  console.log(tr('已找到 agy,直接使用现有安装。', 'Found agy. Your existing installation will be used.', lang));
1052
1329
  if (dependencyOnly) return true;
1330
+ if (interactive && project && checks.gemini_model_configured === false && checks.agy_available && !checks.blockers.includes('agy_unsupported')) {
1331
+ const model = await chooseModel(checks, lang);
1332
+ if (model) {
1333
+ const result = projectPreference(['set-model', model], project);
1334
+ if (result.status !== 0 || result.error || JSON.parse(result.stdout).gemini_model !== model)
1335
+ throw fail('没能保存改写模型,请检查项目目录的写入权限。', 'Could not save the model. Check write access to the project folder.');
1336
+ checks = check(project);
1337
+ console.log(tr(`已为这个项目保存模型 ${model}。`, `Saved ${model} for this project.`, lang));
1338
+ }
1339
+ }
1053
1340
  const [lines, pages] = configurationSteps(checks);
1054
1341
  console.log(lines.join('\n'));
1055
1342
  if (
@@ -1061,7 +1348,7 @@ export async function showSetupGuidance({
1061
1348
  'Type y to open the official links above, or press Enter to skip: ',
1062
1349
  lang
1063
1350
  )
1064
- )) === 'y'
1351
+ ))?.toLowerCase() === 'y'
1065
1352
  ) {
1066
1353
  for (const page of pages)
1067
1354
  if (!browse(page))
@@ -1069,41 +1356,26 @@ export async function showSetupGuidance({
1069
1356
  }
1070
1357
  return true;
1071
1358
  }
1072
- const serviceIssues = {
1073
- api_rate_limited: ['OpenAI 请求过于频繁', 'OpenAI rate limit'],
1074
- api_server_error: ['OpenAI 服务暂不可用', 'OpenAI service unavailable'],
1075
- api_transport_error: ['无法连接 OpenAI', 'OpenAI connection failed'],
1076
- api_timeout: ['OpenAI 请求超时', 'OpenAI request timed out'],
1077
- invalid_api_response: ['OpenAI 返回了无效结果', 'invalid OpenAI response'],
1078
- api_auth_error: ['OpenAI 认证失败,请检查密钥', 'OpenAI authentication failed; check your key'],
1079
- api_quota_exhausted: ['OpenAI 额度不足', 'OpenAI quota exhausted'],
1080
- acp_start_failed: ['Antigravity 启动失败', 'Antigravity failed to start'],
1081
- acp_timeout: ['Antigravity 请求超时', 'Antigravity request timed out'],
1082
- acp_protocol_error: ['Antigravity 通信中断', 'Antigravity communication failed'],
1083
- acp_provider_error: ['Antigravity 服务暂不可用', 'Antigravity service unavailable'],
1084
- acp_incomplete: ['Antigravity 没返回完整回复', 'incomplete Antigravity response'],
1085
- acp_auth_failed: ['Antigravity 登录失效,请重新登录', 'Antigravity sign-in failed; sign in again'],
1086
- acp_model_unavailable: ['所选 Gemini 模型不可用,请重新选择', 'selected Gemini model unavailable; choose a new model']
1087
- };
1088
1359
  export function doctor(checks = readChecks()) {
1089
1360
  const lang = checks.ui_language,
1090
1361
  modes = { manual: ['只在我要求时', 'only when asked'], auto: ['自动改写', 'automatic'], off: ['已关闭', 'off'] };
1091
1362
  const lines = [
1092
- tr('当前项目模式:', 'Project mode: ', lang) + tr(...modes[checks.mode], lang),
1093
- tr('项目改写模型:', 'Rewrite model: ', lang) + (checks.gemini_model || tr('设置无效', 'invalid setting', lang)),
1094
- decisionsSummary(checks, lang)
1363
+ tr('润色时机:', 'When to polish: ', lang) + tr(...modes[checks.mode], lang),
1364
+ tr('改写模式:', 'Rewrite mode: ', lang) + (checks.rewrite_mode || tr('设置无效', 'invalid setting', lang)),
1365
+ tr('项目改写模型:', 'Rewrite model: ', lang) + (checks.gemini_model || tr('设置无效', 'invalid setting', lang))
1095
1366
  ];
1367
+ if (checks.rewrite_mode) lines.push(decisionsSummary(checks, lang));
1096
1368
  const turns = checks.history_turns;
1097
1369
  lines.push(
1098
1370
  turns
1099
1371
  ? tr(
1100
- `最多带上最近 ${turns} 组问答(你的提问 + Codex 的回复),这一次的提问和草稿另算。`,
1101
- `Sends up to ${turns} past Q&As (your question + Codex's reply), plus your current request and draft.`,
1372
+ `Gemini 改写时最多带上最近 ${turns} 轮完整问答,本轮问题和草稿另算。`,
1373
+ `Gemini receives up to ${turns} earlier completed exchanges when it rewrites, plus the current question and draft.`,
1102
1374
  lang
1103
1375
  )
1104
1376
  : tr(
1105
- '历史记录设为 0,只发这一次的提问和草稿。',
1106
- 'History is off, so only your current request and draft go out.',
1377
+ '历史记录设为 0,Gemini 改写时不附带以前的问答。',
1378
+ 'History is off. Gemini rewrites use only the current turn and any custom polishing prompt.',
1107
1379
  lang
1108
1380
  )
1109
1381
  );
@@ -1115,7 +1387,10 @@ export function doctor(checks = readChecks()) {
1115
1387
  ['Codex CLI', checks.codex_available],
1116
1388
  ['Antigravity CLI', checks.agy_available]
1117
1389
  ]) {
1118
- lines.push(tool + tr(':', ': ', lang) + (ready ? tr('可用', 'available', lang) : tr('未找到', 'not found', lang)));
1390
+ const status = tool === 'Antigravity CLI' && checks.blockers.includes('agy_unsupported')
1391
+ ? tr('需要 1.2.1 或更高版本', 'requires version 1.2.1 or later', lang)
1392
+ : ready ? tr('可用', 'available', lang) : tr('未找到', 'not found', lang);
1393
+ lines.push(tool + tr(':', ': ', lang) + status);
1119
1394
  }
1120
1395
  switch (checks.google_auth_method) {
1121
1396
  case 'existing-session':
@@ -1146,17 +1421,6 @@ export function doctor(checks = readChecks()) {
1146
1421
  ),
1147
1422
  ...setupIssues(checks, lang)[0]
1148
1423
  );
1149
- if (checks.cooldown) {
1150
- const reason = tr(...(serviceIssues[checks.cooldown.reason] || ['服务暂不可用', 'service unavailable']), lang),
1151
- seconds = checks.cooldown.remaining_seconds;
1152
- lines.push(
1153
- tr(
1154
- `自动改写已暂停,${seconds} 秒后可以再试。上次遇到的问题:${reason}。`,
1155
- `Automatic rewrites are paused for ${seconds} more seconds. Last issue: ${reason}.`,
1156
- lang
1157
- )
1158
- );
1159
- }
1160
1424
  return lines.join('\n');
1161
1425
  }
1162
1426
  function usage(lang) {
@@ -1186,7 +1450,9 @@ export async function main(args = process.argv.slice(2)) {
1186
1450
  }
1187
1451
  try {
1188
1452
  if (action === 'doctor') {
1189
- console.log(doctor());
1453
+ const checks = readChecks();
1454
+ console.log(doctor(checks));
1455
+ console.log(await hookGuidance(checks.ui_language));
1190
1456
  return 0;
1191
1457
  }
1192
1458
  const [message, offerSetup] = await manage(action, ROOT, snapshotStore());