@kyun.si/codex-polish 0.0.0-stage → 0.0.1-beta.2

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/.agents/plugins/marketplace.json +12 -0
  2. package/CHANGELOG.md +24 -0
  3. package/CONTRIBUTING.en.md +48 -0
  4. package/CONTRIBUTING.md +47 -0
  5. package/Install Codex Polish.command +29 -0
  6. package/LICENSE +202 -0
  7. package/README.en.md +77 -0
  8. package/README.md +78 -2
  9. package/SECURITY.en.md +17 -0
  10. package/SECURITY.md +17 -0
  11. package/docs/technical.en.md +98 -0
  12. package/docs/technical.md +91 -0
  13. package/evaluation/README.en.md +47 -0
  14. package/evaluation/README.md +47 -0
  15. package/package.json +48 -4
  16. package/plugins/codex-polish/.codex-plugin/plugin.json +21 -0
  17. package/plugins/codex-polish/LICENSE +202 -0
  18. package/plugins/codex-polish/hooks/history.mjs +169 -0
  19. package/plugins/codex-polish/hooks/hooks.json +15 -0
  20. package/plugins/codex-polish/hooks/preferences.mjs +401 -0
  21. package/plugins/codex-polish/hooks/project_setting.mjs +93 -0
  22. package/plugins/codex-polish/hooks/recovery.mjs +201 -0
  23. package/plugins/codex-polish/hooks/ui_locale.mjs +61 -0
  24. package/plugins/codex-polish/skills/codex-polish/SKILL.md +36 -0
  25. package/plugins/codex-polish/skills/codex-polish/references/acp.md +94 -0
  26. package/plugins/codex-polish/skills/codex-polish/references/codex-polish-editor.md +15 -0
  27. package/plugins/codex-polish/skills/codex-polish/scripts/acp_models.mjs +99 -0
  28. package/plugins/codex-polish/skills/codex-polish/scripts/acp_payload.mjs +53 -0
  29. package/plugins/codex-polish/skills/codex-polish/scripts/cli_io.mjs +29 -0
  30. package/plugins/codex-polish/skills/codex-polish/scripts/decisions.mjs +224 -0
  31. package/plugins/codex-polish/skills/codex-polish/scripts/text_guard.mjs +203 -0
  32. package/plugins/codex-polish/skills/codex-polish-setup/SKILL.md +52 -0
  33. package/plugins/codex-polish/skills/codex-polish-setup/references/credentials.en.md +47 -0
  34. package/plugins/codex-polish/skills/codex-polish-setup/references/credentials.md +56 -0
  35. package/scripts/install.mjs +1221 -0
  36. package/scripts/native_cache.mjs +86 -0
  37. package//345/256/211/350/243/205/345/233/236/345/244/215/346/266/246/350/211/262.command +2 -0
@@ -0,0 +1,1221 @@
1
+ #!/usr/bin/env node
2
+ // Install Codex Polish through the native Codex plugin manager.
3
+ import * as fs from 'node:fs';
4
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
5
+ import { homedir, tmpdir } from 'node:os';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
+ import { execFileSync, spawn, spawnSync } from 'node:child_process';
8
+ import { Readable } from 'node:stream';
9
+ import { pipeline } from 'node:stream/promises';
10
+ import { createInterface } from 'node:readline';
11
+ import { createInterface as createPrompt } from 'node:readline/promises';
12
+ import { setTimeout as sleep } from 'node:timers/promises';
13
+ import { isDeepStrictEqual } from 'node:util';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { language, tr } from '../plugins/codex-polish/hooks/ui_locale.mjs';
16
+ import { findAgy } from '../plugins/codex-polish/hooks/preferences.mjs';
17
+ import { removeProfileCache, sqliteModule } from '../plugins/codex-polish/hooks/recovery.mjs';
18
+ import { preserve } from './native_cache.mjs';
19
+
20
+ export const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
21
+ export const MARKET = 'codex-polish-local',
22
+ NAME = 'codex-polish',
23
+ PLUGIN_ID = NAME + '@' + MARKET;
24
+ export const INDEX = '.agents/plugins/marketplace.json',
25
+ PRODUCT = 'plugins/' + NAME;
26
+ export const GUIDE = PRODUCT + '/skills/codex-polish-setup/references/credentials.md';
27
+ const CODEX_INSTALL = 'https://developers.openai.com/codex/cli/';
28
+ const GEMINI_KEYS = 'https://aistudio.google.com/apikey';
29
+ const AGY_INSTALL = 'https://antigravity.google/docs/getting-started/?tab=cli';
30
+ const AGY_BOOTSTRAP = 'https://antigravity.google/cli/install.sh';
31
+ const VERSION = '[0-9]+\\.[0-9]+\\.[0-9]+(?:[-+][a-zA-Z0-9.+-]+)?';
32
+ const validVersion = new RegExp('^' + VERSION + '$');
33
+ const snapshotName = new RegExp('^' + VERSION + '-[0-9a-f]{20}$');
34
+ const localSource = { source: 'local', path: './' + PRODUCT };
35
+ const { O_RDONLY, O_NOFOLLOW, O_DIRECTORY, O_NONBLOCK } = fs.constants;
36
+ const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
37
+ const sha = (data) => createHash('sha256').update(data);
38
+ const readJSON = (file) => JSON.parse(readPlain(file));
39
+ const fail = (zh, en) => new SetupError(tr(zh, en));
40
+ export class SetupError extends Error {}
41
+
42
+ function statMaybe(path) {
43
+ return fs.lstatSync(path, { throwIfNoEntry: false });
44
+ }
45
+ function readPlain(path) {
46
+ const fd = fs.openSync(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
47
+ try {
48
+ if (!fs.fstatSync(fd).isFile()) throw fail('文件类型异常。', 'Unexpected file type.');
49
+ return fs.readFileSync(fd);
50
+ } finally {
51
+ fs.closeSync(fd);
52
+ }
53
+ }
54
+ // Keep each Codex profile separate, including profiles that have not been created yet.
55
+ function canonical(path) {
56
+ path = resolve(path);
57
+ if (fs.existsSync(path)) return fs.realpathSync.native(path);
58
+ return join(canonical(dirname(path)), basename(path));
59
+ }
60
+ function registeredPath(path) {
61
+ return join(canonical(dirname(path)), basename(path));
62
+ }
63
+ export function codexProfile() {
64
+ return canonical(process.env.CODEX_HOME || join(homedir(), '.codex'));
65
+ }
66
+ export function snapshotStore() {
67
+ return join(codexProfile(), 'codex-polish', 'sources');
68
+ }
69
+ function plainFile(base, relative) {
70
+ let current = base;
71
+ const target = join(base, relative);
72
+ for (const part of relative.split('/')) {
73
+ current = join(current, part);
74
+ const info = statMaybe(current);
75
+ if (!info) return false;
76
+ if (!(current === target ? info.isFile() : info.isDirectory())) {
77
+ throw fail(
78
+ `市场路径有异常,请在 Codex 里检查:${current}`,
79
+ `Check this unexpected marketplace path in Codex: ${current}`
80
+ );
81
+ }
82
+ }
83
+ return true;
84
+ }
85
+ function productFiles(root) {
86
+ const files = [];
87
+ function walk(relative) {
88
+ const dir = join(root, relative);
89
+ if (!fs.lstatSync(dir).isDirectory())
90
+ throw fail('插件目录异常。请重新解压插件包。', 'Unexpected plugin directory. Extract a fresh copy.');
91
+ const entries = fs.readdirSync(dir, { withFileTypes: true }).sort((a,b) => a.name < b.name ? -1 : Number(a.name > b.name));
92
+ for (const entry of entries) {
93
+ const child = join(relative, entry.name);
94
+ if (entry.isDirectory()) walk(child);
95
+ else if (entry.name === '.DS_Store') continue;
96
+ else if (entry.isFile()) files.push(child);
97
+ else throw fail('插件包里有不支持的文件类型,请重新解压。', 'The plugin contains an unsupported file or symlink. Extract a fresh copy.');
98
+ }
99
+ }
100
+ walk('');
101
+ return files;
102
+ }
103
+ function fingerprint(root) {
104
+ const files = [INDEX, ...productFiles(join(root, PRODUCT)).map((file) => join(PRODUCT, file))];
105
+ const hash = createHash('sha256');
106
+ for (const file of files) {
107
+ const path = join(root,file);
108
+ const mode = fs.lstatSync(path).mode & 0o7777;
109
+ hash.update(file + '\0' + mode + '\0').update(sha(readPlain(path)).digest());
110
+ }
111
+ return { digest: hash.digest('hex').slice(0, 20), files };
112
+ }
113
+ function ownsSnapshot(path, store) {
114
+ return dirname(path) === store && snapshotName.test(basename(path)) && !statMaybe(path)?.isSymbolicLink();
115
+ }
116
+ export function bundleVersion(root) {
117
+ if (!plainFile(root, INDEX)) throw fail('缺少市场清单。', 'Missing marketplace manifest.');
118
+ const index = readJSON(join(root, INDEX));
119
+ if (
120
+ index?.name !== MARKET ||
121
+ !Array.isArray(index.plugins) || index.plugins.length !== 1 ||
122
+ index.plugins[0]?.name !== NAME ||
123
+ !isDeepStrictEqual(index.plugins[0].source, localSource)
124
+ ) {
125
+ throw fail(
126
+ '安装源里的本地市场清单无效。请重新解压一份新的插件包再试。',
127
+ "The local marketplace manifest isn't valid. Extract a fresh copy of the plugin and try again."
128
+ );
129
+ }
130
+ const manifest = PRODUCT + '/.codex-plugin/plugin.json';
131
+ const metadata = plainFile(root, manifest) && readJSON(join(root, manifest));
132
+ if (metadata?.name !== NAME || typeof metadata.version !== 'string' || !validVersion.test(metadata.version)) {
133
+ throw fail('插件清单里的名称或版本无效。', 'The plugin manifest has an invalid name or version.');
134
+ }
135
+ return metadata.version;
136
+ }
137
+ export function compareVersions(a, b) {
138
+ function parts(version) {
139
+ if (typeof version !== 'string' || !validVersion.test(version))
140
+ throw fail('没法确定已安装插件的版本。', "Couldn't determine the installed plugin version.");
141
+ const [release, prerelease] = version.split('+')[0].split(/-(.*)/s);
142
+ return [release.split('.').map(BigInt), prerelease?.split('.')];
143
+ }
144
+ const [x, xp] = parts(a),
145
+ [y, yp] = parts(b);
146
+ const cmp = (a, b) => (a < b ? -1 : Number(a > b));
147
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return cmp(x[i], y[i]);
148
+ if (!xp || !yp) return Number(!xp) - Number(!yp);
149
+ for (let i = 0; i < Math.min(xp.length, yp.length); i++) {
150
+ const l = xp[i],
151
+ r = yp[i],
152
+ ln = /^\d+$/.test(l),
153
+ rn = /^\d+$/.test(r);
154
+ const order = ln !== rn ? Number(rn) - Number(ln) : ln ? cmp(BigInt(l), BigInt(r)) : cmp(l, r);
155
+ if (order) return order;
156
+ }
157
+ return cmp(xp.length, yp.length);
158
+ }
159
+ function verifiedPaths(entry) {
160
+ if (!fs.lstatSync(entry).isDirectory()) return null;
161
+ const actual = new Set();
162
+ function walk(relative) {
163
+ for (const name of fs.readdirSync(join(entry, relative))) {
164
+ const child = join(relative, name),
165
+ info = fs.lstatSync(join(entry, child));
166
+ if (!info.isFile() && !info.isDirectory()) return false;
167
+ actual.add(child);
168
+ if (info.isDirectory() && !walk(child)) return false;
169
+ }
170
+ return true;
171
+ }
172
+ if (!walk('') || !actual.has(INDEX)) return null;
173
+ try {
174
+ const version = bundleVersion(entry),
175
+ { digest, files } = fingerprint(entry);
176
+ if (basename(entry) !== version + '-' + digest) return null;
177
+ const expected = new Set(files);
178
+ for (const file of files) {
179
+ for (let dir = dirname(file); dir !== '.'; dir = dirname(dir)) expected.add(dir);
180
+ }
181
+ return isDeepStrictEqual(expected, actual) ? expected : null;
182
+ } catch (error) {
183
+ if (error.code && !['EISDIR', 'ENOENT', 'ENOTDIR', 'ELOOP'].includes(error.code)) throw error;
184
+ return null;
185
+ }
186
+ }
187
+ function makeSnapshot(root, store, minimumVersions, registered) {
188
+ const version = bundleVersion(root);
189
+ for (const existing of minimumVersions) {
190
+ if (compareVersions(version, existing) < 0)
191
+ throw fail(
192
+ `这个安装包是 ${version},比已安装的 ${existing} 旧。请使用更新的安装包。`,
193
+ `This package has ${version}, which is older than the installed ${existing}. Use a newer package.`
194
+ );
195
+ }
196
+ const { digest, files } = fingerprint(root),
197
+ target = join(store, version + '-' + digest);
198
+ const occupied = statMaybe(target);
199
+ if (occupied) {
200
+ if (!ownsSnapshot(target, store) || !occupied.isDirectory())
201
+ throw fail('安装路径已被占用。', 'The snapshot path is already occupied.');
202
+ if (target === registered || verifiedPaths(target)) return [target, version];
203
+ }
204
+ const temp = fs.mkdtempSync(join(store, '.prepare-'));
205
+ try {
206
+ const stage = join(temp, 'market');
207
+ for (const file of files) {
208
+ const dest = join(stage, file),
209
+ src = join(root, file);
210
+ fs.mkdirSync(dirname(dest), { recursive: true });
211
+ fs.writeFileSync(dest, readPlain(src));
212
+ fs.chmodSync(dest, fs.lstatSync(src).mode & 0o7777);
213
+ }
214
+ if (fingerprint(stage).digest !== digest)
215
+ throw fail(
216
+ '安装过程中插件文件变了,请重新运行安装。',
217
+ 'The plugin files changed during installation. Run setup again.'
218
+ );
219
+ if (occupied) {
220
+ const backup = join(fs.mkdtempSync(join(store, 'retained-')), basename(target));
221
+ fs.renameSync(target, backup);
222
+ console.log(tr(`本地改动已保存在 ${backup}`, `Your local changes were kept at ${backup}`));
223
+ }
224
+ fs.renameSync(stage, target);
225
+ } finally {
226
+ fs.rmSync(temp, { recursive: true, force: true });
227
+ }
228
+ return [target, version];
229
+ }
230
+ export function codex(...args) {
231
+ const result = spawnSync('codex', ['plugin', ...args, '--json'], {
232
+ encoding: 'utf8',
233
+ timeout: 120_000,
234
+ maxBuffer: 16 * 1024 * 1024,
235
+ stdio: ['ignore', 'pipe', 'pipe']
236
+ });
237
+ if (result.error?.code === 'ENOENT')
238
+ throw fail(
239
+ '没找到 Codex CLI。请按官方指南安装,或把 codex 加入 PATH。\n ' + CODEX_INSTALL,
240
+ "Couldn't find Codex CLI. Follow the official installation guide or add codex to PATH.\n " + CODEX_INSTALL
241
+ );
242
+ if (result.error || result.signal)
243
+ throw fail(
244
+ 'Codex CLI 没有正常结束,请检查后再试。',
245
+ "Codex CLI didn't finish. Check that it runs, then try again."
246
+ );
247
+ const label = args[0] === 'marketplace' ? args.slice(0, 2).join(' ') : args[0];
248
+ if (result.status !== 0)
249
+ throw new SetupError(
250
+ tr(
251
+ `Codex plugin ${label} 运行失败。请检查插件状态后再试。`,
252
+ `codex plugin ${label} failed. Check the plugin in Codex and try again.`
253
+ )
254
+ );
255
+ let reply;
256
+ try {
257
+ reply = JSON.parse(result.stdout);
258
+ } catch {
259
+ throw fail('Codex CLI 返回的内容没法读取。', "Couldn't read the response from Codex CLI.");
260
+ }
261
+ if (!isObject(reply))
262
+ throw fail('不支持 Codex CLI 返回的格式。', 'This version of Codex CLI returned an unsupported response.');
263
+ return reply;
264
+ }
265
+ function lookup(run, field, key, value, ...args) {
266
+ const rows = run(...args)[field];
267
+ if (!Array.isArray(rows) || !rows.every(isObject))
268
+ throw fail(
269
+ '没法核对 Codex 的市场或插件列表,请检查 CLI 版本。',
270
+ "Couldn't verify the marketplace or plugin list. Check your Codex CLI version."
271
+ );
272
+ const found = rows.filter((row) => row[key] === value);
273
+ if (found.length > 1)
274
+ throw fail('Codex 返回了重复的市场或插件记录。', 'Codex returned duplicate marketplace or plugin records.');
275
+ return found[0] ?? null;
276
+ }
277
+ function registration(run) {
278
+ const row = lookup(run, 'marketplaces', 'name', MARKET, 'marketplace', 'list');
279
+ if (!row) return null;
280
+ const info = row.marketplaceSource,
281
+ source = info?.source;
282
+ if (info?.sourceType !== 'local' || typeof source !== 'string' || !isAbsolute(source)) {
283
+ throw fail(
284
+ '同名市场用了其他来源。请在 Codex 的插件设置里核对。',
285
+ 'A marketplace with the same name uses a different source. Check it in Codex plugin settings.'
286
+ );
287
+ }
288
+ return registeredPath(source);
289
+ }
290
+ function installed(run) {
291
+ return lookup(run, 'installed', 'pluginId', PLUGIN_ID, 'list', '--marketplace', MARKET);
292
+ }
293
+ function requireManagedSource(previous, store) {
294
+ if (previous && !ownsSnapshot(previous, store)) {
295
+ throw fail(
296
+ '同名市场使用了其他来源,请在 Codex 插件设置中检查。',
297
+ 'A marketplace with the same name uses a different source. Check it in Codex plugin settings.'
298
+ );
299
+ }
300
+ }
301
+ function checkSource(previous, store) {
302
+ requireManagedSource(previous, store);
303
+ if (previous && !verifiedPaths(previous))
304
+ throw fail(
305
+ '已注册的安装副本被改动了。请先运行 node scripts/install.mjs uninstall,再运行 node scripts/install.mjs setup。项目设置会保留。',
306
+ 'The registered plugin source has changed. Run node scripts/install.mjs uninstall, then node scripts/install.mjs setup. Your project settings will be kept.'
307
+ );
308
+ }
309
+ function verifyReceipt(receipt, target, version) {
310
+ const directory = receipt.installedPath;
311
+ if (
312
+ receipt.pluginId !== PLUGIN_ID ||
313
+ receipt.version !== version ||
314
+ typeof directory !== 'string' ||
315
+ !isAbsolute(directory)
316
+ ) {
317
+ throw fail(
318
+ 'Codex 没有返回能核对的插件安装目录和版本。',
319
+ "Codex didn't confirm the installation directory and plugin version."
320
+ );
321
+ }
322
+ const source = join(target, PRODUCT),
323
+ files = productFiles(source);
324
+ if (
325
+ !statMaybe(directory)?.isDirectory() ||
326
+ !isDeepStrictEqual(productFiles(directory), files) ||
327
+ files.some((file) => !readPlain(join(directory, file)).equals(readPlain(join(source, file))))
328
+ ) {
329
+ throw fail('Codex 的安装缓存和这次发行的内容不一致。', "The files Codex installed don't match this release.");
330
+ }
331
+ }
332
+ export async function nativeConfig(method, params, { experimental = false, cwd, env = process.env } = {}) {
333
+ const proc = spawn('codex', ['app-server', '--stdio'], { stdio: ['pipe', 'pipe', 'ignore'], cwd, env });
334
+ let ended = false;
335
+ const closed = new Promise((done) =>
336
+ proc.once('close', () => {
337
+ ended = true;
338
+ done();
339
+ })
340
+ );
341
+ proc.on('error', () => {});
342
+ proc.stdin.on('error', () => {});
343
+ const deadline = setTimeout(() => proc.kill('SIGKILL'), 20_000);
344
+ const lines = createInterface({ input: proc.stdout, crlfDelay: Infinity });
345
+ const stream = lines[Symbol.asyncIterator]();
346
+ async function send(frame) {
347
+ proc.stdin.write(JSON.stringify(frame) + '\n');
348
+ if (frame.id == null) return;
349
+ for (;;) {
350
+ const { value, done } = await stream.next();
351
+ if (done) break;
352
+ const msg = JSON.parse(value);
353
+ if (msg.id !== frame.id) continue;
354
+ if (!msg.error && isObject(msg.result)) return msg.result;
355
+ break;
356
+ }
357
+ throw fail('Codex 配置接口没有确认这次请求。', "The Codex configuration service didn't confirm the request.");
358
+ }
359
+ try {
360
+ await send({
361
+ id: 1,
362
+ method: 'initialize',
363
+ params: {
364
+ clientInfo: { name: 'codex-polish-installer', version: '1' },
365
+ ...(experimental && { capabilities: { experimentalApi: true } })
366
+ }
367
+ });
368
+ await send({ method: 'initialized' });
369
+ return await send({ id: 2, method, params });
370
+ } finally {
371
+ proc.stdin.end();
372
+ lines.close();
373
+ if (!ended) {
374
+ const force = setTimeout(() => proc.kill('SIGKILL'), 2000);
375
+ try {
376
+ await closed;
377
+ } finally {
378
+ clearTimeout(force);
379
+ }
380
+ }
381
+ clearTimeout(deadline);
382
+ }
383
+ }
384
+ export async function writeEnabled(value) {
385
+ const result = await nativeConfig('config/value/write', {
386
+ keyPath: `plugins.${PLUGIN_ID}.enabled`,
387
+ value,
388
+ mergeStrategy: 'upsert'
389
+ });
390
+ if (!['ok', 'okOverridden'].includes(result.status))
391
+ throw fail('Codex 配置接口没有确认写入。', "Codex didn't confirm that it saved the setting.");
392
+ }
393
+ async function hasUnlistedPlugin() {
394
+ const { config } = await nativeConfig('config/read', { includeLayers: false });
395
+ if (config.marketplaces?.[MARKET])
396
+ throw fail('市场来源变了,请再试一次。', 'The marketplace source changed. Try again.');
397
+ return Object.hasOwn(config.plugins ?? {}, PLUGIN_ID);
398
+ }
399
+ async function verifyInstalled(run, setEnabled, version, enabled) {
400
+ let state = installed(run);
401
+ if (state?.version !== version)
402
+ throw fail(
403
+ 'Codex 没有确认已安装预期版本。',
404
+ "Codex didn't confirm that the requested plugin version is installed."
405
+ );
406
+ if (state.enabled !== enabled) {
407
+ await setEnabled(enabled);
408
+ state = installed(run);
409
+ if (state?.version !== version || state.enabled !== enabled)
410
+ throw fail('Codex 没有确认插件的启用状态。', "Codex didn't confirm whether the plugin is enabled.");
411
+ }
412
+ }
413
+ async function rollback(run, setEnabled, previous, before, target) {
414
+ const current = registration(run);
415
+ if (![null, previous, target].includes(current))
416
+ throw fail('其他进程修改了市场。', 'Another process changed the marketplace.');
417
+ 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)
423
+ throw fail('Codex 没有恢复更新前的市场来源。', "Codex didn't restore the previous marketplace.");
424
+ if (before) {
425
+ verifyReceipt(run('add', PLUGIN_ID), previous, before.version);
426
+ await verifyInstalled(run, setEnabled, before.version, before.enabled);
427
+ } else if (installed(run))
428
+ throw fail('Codex 没有清除未完成的安装。', "Codex didn't remove the incomplete installation.");
429
+ }
430
+ const sourceId = (path) => (path === null ? null : sha(path).digest('hex'));
431
+ export function pendingUpdate(store) {
432
+ let fd;
433
+ try {
434
+ fd = fs.openSync(join(store, '.pending-update.json'), O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
435
+ } catch (error) {
436
+ if (error.code === 'ENOENT') return null;
437
+ throw error;
438
+ }
439
+ try {
440
+ const buffer = Buffer.alloc(1025);
441
+ if (fs.fstatSync(fd).isFile()) {
442
+ const n = fs.readSync(fd, buffer);
443
+ if (n <= 1024) {
444
+ let entry;
445
+ try {
446
+ entry = JSON.parse(buffer.subarray(0, n));
447
+ } catch {}
448
+ if (
449
+ entry &&
450
+ typeof entry.enabled === 'boolean' &&
451
+ typeof entry.target === 'string' &&
452
+ snapshotName.test(entry.target) &&
453
+ typeof entry.version === 'string' &&
454
+ validVersion.test(entry.version) &&
455
+ (entry.previous === null || (typeof entry.previous === 'string' && /^[0-9a-f]{64}$/.test(entry.previous)))
456
+ )
457
+ return entry;
458
+ }
459
+ }
460
+ } finally {
461
+ fs.closeSync(fd);
462
+ }
463
+ throw fail(
464
+ '上次更新的记录损坏了。请先在 Codex 里检查插件来源,再卸载并重新安装。',
465
+ 'The interrupted update record is invalid. Check its source in Codex, then uninstall and reinstall.'
466
+ );
467
+ }
468
+ function syncStore(store) {
469
+ const fd = fs.openSync(store, O_RDONLY | O_DIRECTORY);
470
+ try {
471
+ fs.fsyncSync(fd);
472
+ } finally {
473
+ fs.closeSync(fd);
474
+ }
475
+ }
476
+ function savePending(store, entry) {
477
+ const tmp = join(store, '.prepare-update-' + randomUUID());
478
+ const fd = fs.openSync(tmp, 'wx', 0o600);
479
+ try {
480
+ fs.writeFileSync(fd, JSON.stringify(entry));
481
+ fs.fsyncSync(fd);
482
+ fs.renameSync(tmp, join(store, '.pending-update.json'));
483
+ syncStore(store);
484
+ } finally {
485
+ fs.closeSync(fd);
486
+ fs.rmSync(tmp, { force: true });
487
+ }
488
+ }
489
+ function finishPending(store) {
490
+ try {
491
+ fs.unlinkSync(join(store, '.pending-update.json'));
492
+ } catch (error) {
493
+ if (error.code === 'ENOENT') return;
494
+ throw error;
495
+ }
496
+ syncStore(store);
497
+ }
498
+ export function preserveNativeCache(store, previous, state) {
499
+ if (store !== snapshotStore()) return;
500
+ 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;
504
+ }
505
+ try {
506
+ const backup = preserve(codexProfile(), MARKET, NAME, version, verifiedSource);
507
+ if (backup)
508
+ console.log(tr('已保留有改动或没法核对的插件缓存:', 'Kept a changed or unverified plugin cache at: ') + backup);
509
+ } catch (error) {
510
+ throw fail(
511
+ '没法安全保留 Codex 里的插件缓存。先检查下面这个路径再重试。\n ' + error.message,
512
+ "Couldn't safely keep the plugin cache in Codex intact. Check this path and try again.\n " + error.message
513
+ );
514
+ }
515
+ }
516
+ async function setup(root, store, run, setEnabled, action) {
517
+ const previous = registration(run);
518
+ checkSource(previous, store);
519
+ 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
+ );
525
+ }
526
+ const before = installed(run);
527
+ if (!previous && !pending && (before || (store === snapshotStore() && (await hasUnlistedPlugin())))) {
528
+ throw fail(
529
+ 'Codex 里还有安装记录,但市场来源已被移除。请用这个包运行 uninstall,再运行 setup。项目设置会保留。',
530
+ 'Codex still has an installation record, but the marketplace was removed. Run uninstall from this package, then setup. Your project settings will be kept.'
531
+ );
532
+ }
533
+ if (before && (typeof before.enabled !== 'boolean' || typeof before.version !== 'string')) {
534
+ throw fail(
535
+ 'Codex 没有返回能核对的原安装版本和启用状态。',
536
+ "Codex didn't report the installed version and enabled state."
537
+ );
538
+ }
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 });
545
+ preserveNativeCache(store, previous, before);
546
+ try {
547
+ if (previous !== target) {
548
+ if (previous) run('marketplace', 'remove', MARKET);
549
+ run('marketplace', 'add', target);
550
+ }
551
+ verifyReceipt(run('add', PLUGIN_ID), target, version);
552
+ if (registration(run) !== target)
553
+ throw fail(
554
+ 'Codex 没有确认这次安装的市场来源。',
555
+ "Codex didn't confirm the marketplace source for this installation."
556
+ );
557
+ await verifyInstalled(run, setEnabled, version, enabled);
558
+ } catch (error) {
559
+ try {
560
+ await rollback(run, setEnabled, previous, before, target);
561
+ } catch {
562
+ throw fail(
563
+ '安装失败,Codex 没能恢复。本地快照已保留,请重新运行 setup。',
564
+ "Codex couldn't restore the previous installation. The local copy is still there. Run setup again."
565
+ );
566
+ }
567
+ if (before && !pending) finishPending(store);
568
+ throw error;
569
+ }
570
+ if (original) finishPending(store);
571
+ if (!enabled)
572
+ return [
573
+ tr(
574
+ `回复润色 ${version} 已安装,目前仍是停用状态。要用时可以在 Codex 的插件设置里启用。`,
575
+ `Codex Polish ${version} is installed, but it's still disabled. You can enable it in Codex plugin settings.`
576
+ ),
577
+ false
578
+ ];
579
+ const lang = language();
580
+ const status = action === 'setup'
581
+ ? tr(`回复润色 ${version} 已安装。`, `Codex Polish ${version} is installed.`, lang)
582
+ : tr(`回复润色已更新到 ${version}。`, `Updated Codex Polish to ${version}.`, lang);
583
+ const lines = [
584
+ status,
585
+ 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.',
588
+ lang
589
+ ),
590
+ 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”.',
593
+ lang
594
+ )
595
+ ];
596
+ if (action === 'setup') {
597
+ const guide = join(target, lang === 'zh' ? GUIDE : GUIDE.replace('credentials.md', 'credentials.en.md'));
598
+ lines.push(tr(`配置指南:${guide}`, `Setup guide: ${guide}`, lang));
599
+ }
600
+ return [lines.join('\n'), action === 'setup'];
601
+ }
602
+ // Node has no unlinkat. Pin each directory as the kernel cwd for this synchronous
603
+ // walk and check inode identity after chdir, before any relative unlink/rmdir.
604
+ function removeVerifiedEntries(entry, paths) {
605
+ function enter(path, expected) {
606
+ process.chdir(path);
607
+ const current = fs.statSync('.');
608
+ if (current.dev !== expected.dev || current.ino !== expected.ino)
609
+ throw new Error('Directory changed during cleanup');
610
+ }
611
+ function removeChildren(relative) {
612
+ const parent = fs.statSync('.');
613
+ for (const name of fs.readdirSync('.')) {
614
+ const child = join(relative, name);
615
+ if (!paths.has(child)) continue;
616
+ const info = fs.lstatSync(name);
617
+ if (info.isDirectory()) {
618
+ enter(name, info);
619
+ removeChildren(child);
620
+ enter('..', parent);
621
+ fs.rmdirSync(name);
622
+ } else if (info.isFile()) fs.unlinkSync(name);
623
+ }
624
+ }
625
+ const cwd = process.cwd();
626
+ try {
627
+ process.chdir(dirname(entry));
628
+ const store = fs.statSync('.');
629
+ const info = fs.lstatSync(basename(entry));
630
+ if (!info.isDirectory()) throw new Error('Snapshot changed during cleanup');
631
+ enter(basename(entry), info);
632
+ removeChildren('');
633
+ enter('..', store);
634
+ fs.rmdirSync(basename(entry));
635
+ } finally {
636
+ process.chdir(cwd);
637
+ }
638
+ }
639
+ function cleanUninstallData(store) {
640
+ const kept = [],
641
+ errors = [];
642
+ let entries = [];
643
+ try {
644
+ entries = fs.readdirSync(store).sort();
645
+ } catch {
646
+ errors.push(store);
647
+ }
648
+ for (const name of entries.filter((name) => snapshotName.test(name))) {
649
+ const entry = join(store, name);
650
+ try {
651
+ const paths = verifiedPaths(entry);
652
+ if (paths) removeVerifiedEntries(entry, paths);
653
+ else kept.push(entry);
654
+ } catch {
655
+ errors.push(entry);
656
+ }
657
+ }
658
+ if (store === snapshotStore()) {
659
+ try {
660
+ const retained = removeProfileCache();
661
+ if (retained) kept.push(retained);
662
+ } catch (error) {
663
+ errors.push(error.path || store);
664
+ }
665
+ }
666
+ let message = tr('回复润色已卸载。项目设置已保留。', 'Uninstalled Codex Polish and kept your project settings.');
667
+ if (kept.length)
668
+ message +=
669
+ '\n' +
670
+ tr('下面这些路径有改动或额外内容,已保留:', 'Kept these paths because they have changes or extra contents:') +
671
+ '\n' +
672
+ kept.join('\n');
673
+ if (errors.length)
674
+ throw new SetupError(
675
+ message +
676
+ '\n' +
677
+ tr(
678
+ '没法检查或清理下面这些路径。请关闭还在用这个插件的会话,检查权限,再重新卸载:',
679
+ "Couldn't clean up these paths. Close any sessions using the plugin, check permissions, and run uninstall again:"
680
+ ) +
681
+ '\n' +
682
+ errors.join('\n')
683
+ );
684
+ return message;
685
+ }
686
+ async function uninstall(store, run) {
687
+ const previous = registration(run);
688
+ requireManagedSource(previous, store);
689
+ if (previous) bundleVersion(previous);
690
+ const before = installed(run);
691
+ let present = Boolean(before);
692
+ // The native plugin list hides an installed plugin when an interrupted
693
+ // update has already removed its marketplace. Read its current config key.
694
+ if (!previous && store === snapshotStore()) {
695
+ present = await hasUnlistedPlugin();
696
+ }
697
+ if (present && !previous) {
698
+ const known = fs
699
+ .readdirSync(store)
700
+ .map((name) => join(store, name))
701
+ .some((entry) => ownsSnapshot(entry, store) && verifiedPaths(entry));
702
+ if (!known && !pendingUpdate(store))
703
+ throw fail(
704
+ '没法确定这个已安装插件来自哪个市场,卸载已停止。',
705
+ "Couldn't verify the marketplace for the installed plugin. Check its source before uninstalling."
706
+ );
707
+ }
708
+ if (present || previous) preserveNativeCache(store, previous, before);
709
+ if (present) {
710
+ run('remove', PLUGIN_ID);
711
+ if (!previous && store === snapshotStore() ? await hasUnlistedPlugin() : installed(run))
712
+ throw fail(
713
+ 'Codex 还是显示这个插件已安装,请再试一次卸载。',
714
+ 'Codex still lists the plugin as installed. Run uninstall again.'
715
+ );
716
+ }
717
+ if (previous) {
718
+ run('marketplace', 'remove', MARKET);
719
+ if (registration(run))
720
+ throw fail(
721
+ 'Codex 还是显示这个市场已注册,请再试一次卸载。',
722
+ 'Codex still lists the marketplace. Run uninstall again.'
723
+ );
724
+ }
725
+ return cleanUninstallData(store);
726
+ }
727
+ // An exclusive SQLite transaction serializes installers on both supported
728
+ // platforms. The OS releases it immediately if the process is interrupted.
729
+ // Keep the native handle live even when a caller awaits a promise whose
730
+ // resolver has been discarded. V8 can collect the suspended async stack.
731
+ const heldLocks = new Set();
732
+ export async function withLock(file, action) {
733
+ const entry = statMaybe(file);
734
+ if (entry && (!entry.isFile() || entry.nlink !== 1)) throw fail('锁文件路径异常。', 'Unexpected lock file.');
735
+ const { DatabaseSync } = sqliteModule();
736
+ const db = new DatabaseSync(file);
737
+ heldLocks.add(db);
738
+ try {
739
+ for (;;) {
740
+ try {
741
+ db.exec('BEGIN EXCLUSIVE');
742
+ break;
743
+ } catch (error) {
744
+ if (error.errcode !== 5 && error.errcode !== 6) throw error;
745
+ await sleep(50);
746
+ }
747
+ }
748
+ return await action();
749
+ } finally {
750
+ heldLocks.delete(db);
751
+ db.close();
752
+ }
753
+ }
754
+ export async function manage(action, root, store, run = codex, setEnabled = writeEnabled) {
755
+ fs.mkdirSync(store, { recursive: true, mode: 0o700 });
756
+ if (!fs.lstatSync(store).isDirectory() || fs.realpathSync.native(store) !== store) {
757
+ throw fail(
758
+ '快照目录路径异常,请检查后再试。',
759
+ 'Unexpected snapshot directory. Check this path before trying again.'
760
+ );
761
+ }
762
+ return withLock(join(store, '.installer.sqlite'), async () => {
763
+ if (action === 'uninstall') {
764
+ const message = await uninstall(store, run);
765
+ finishPending(store);
766
+ return [message, false];
767
+ }
768
+ return setup(root, store, run, setEnabled, action);
769
+ });
770
+ }
771
+ function readChecks() {
772
+ const helper = join(ROOT, PRODUCT, 'hooks/preferences.mjs');
773
+ const result = spawnSync(process.execPath, [helper, 'check', '--cwd', process.cwd()], {
774
+ encoding: 'utf8',
775
+ timeout: 10_000
776
+ });
777
+ if (result.status !== 0 || result.error)
778
+ throw fail('没法读取插件的环境检查结果。', "Couldn't read the plugin environment check results.");
779
+ return JSON.parse(result.stdout);
780
+ }
781
+ async function runBootstrap(script, target, options) {
782
+ const proc = spawn('/bin/bash', [script, '--dir', target], { ...options, stdio: 'ignore', detached: true });
783
+ function killGroup() {
784
+ if (proc.pid) {
785
+ try {
786
+ process.kill(-proc.pid, 'SIGKILL');
787
+ } catch (error) {
788
+ if (error.code !== 'ESRCH') throw error;
789
+ }
790
+ }
791
+ }
792
+ const timer = setTimeout(killGroup, 180_000);
793
+ process.once('SIGINT', killGroup);
794
+ process.once('SIGTERM', killGroup);
795
+ try {
796
+ const status = await new Promise((done, reject) => proc.once('error', reject).once('close', done));
797
+ if (status !== 0) throw fail('Google 的安装程序没有完成。', 'Google’s installer didn’t finish.');
798
+ } finally {
799
+ clearTimeout(timer);
800
+ process.off('SIGINT', killGroup);
801
+ process.off('SIGTERM', killGroup);
802
+ }
803
+ }
804
+ async function downloadBootstrap(file) {
805
+ const signal = AbortSignal.timeout(30_000);
806
+ let url = new URL(AGY_BOOTSTRAP);
807
+ for (let redirects = 0; redirects <= 5; redirects++) {
808
+ const response = await fetch(url, { signal, redirect: 'manual' });
809
+ if (response.ok && response.body) {
810
+ await pipeline(Readable.fromWeb(response.body), fs.createWriteStream(file, { flags: 'wx', mode: 0o600 }), {
811
+ signal
812
+ });
813
+ return;
814
+ }
815
+ await response.body?.cancel();
816
+ const location = response.headers.get('location');
817
+ if (![301, 302, 303, 307, 308].includes(response.status) || !location) break;
818
+ url = new URL(location, url);
819
+ if (url.protocol !== 'https:') break;
820
+ }
821
+ throw fail('从 Google 下载 agy 失败。', 'Could not download agy from Google.');
822
+ }
823
+ export async function installAgy() {
824
+ const target = join(homedir(), '.local/bin');
825
+ fs.mkdirSync(target, { recursive: true });
826
+ await withLock(join(target, '.codex-polish-agy.sqlite'), async () => {
827
+ if (findAgy()) return;
828
+ const binary = join(target, 'agy');
829
+ if (statMaybe(binary))
830
+ throw fail(`请先检查 ${binary},这个路径已被占用。`, `Check ${binary}. That path is already in use.`);
831
+ const temp = fs.mkdtempSync(join(tmpdir(), 'codex-polish-agy-')),
832
+ 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 };
836
+ try {
837
+ await downloadBootstrap(script);
838
+ try {
839
+ 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)
849
+ throw fail('需要 Antigravity CLI 1.2.1 或更新版。', 'Antigravity CLI 1.2.1 or later is required.');
850
+ } catch (error) {
851
+ if (statMaybe(binary) && !fs.lstatSync(binary).isDirectory()) fs.unlinkSync(binary);
852
+ throw error;
853
+ }
854
+ } finally {
855
+ fs.rmSync(temp, { recursive: true, force: true });
856
+ }
857
+ });
858
+ }
859
+ function decisionsSummary(checks, lang) {
860
+ if (checks.decisions_mode === 'off')
861
+ return tr(
862
+ '改写检查:未开启,回复会直接交给 Gemini 润色。',
863
+ 'Rewrite checks: off. Replies go straight to Gemini.',
864
+ lang
865
+ );
866
+ if (checks.blockers.includes('openai_key_invalid'))
867
+ return tr('OpenAI 检查目前用不了。', "OpenAI checks aren't available right now.", lang);
868
+ if (checks.decisions_enabled)
869
+ 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.',
872
+ lang
873
+ );
874
+ 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”.',
877
+ lang
878
+ );
879
+ }
880
+ 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
+ gemini_key_missing: [
886
+ '你选了用 API 密钥登录 Google。去 Google AI Studio 点 Create API key,然后把密钥设为 GEMINI_API_KEY。',
887
+ 'You chose Google API key sign-in. Select Create API key in Google AI Studio, then set GEMINI_API_KEY.',
888
+ GEMINI_KEYS
889
+ ],
890
+ gemini_key_invalid: [
891
+ 'GEMINI_API_KEY 格式不对。请重新复制完整密钥,去掉空格和换行。要创建新密钥可以访问',
892
+ 'GEMINI_API_KEY is invalid. Copy the full key without spaces or newlines. To create a new key, visit',
893
+ GEMINI_KEYS
894
+ ],
895
+ agy_missing: [
896
+ '找不到 agy。在插件解压目录运行 node scripts/install.mjs setup --install-agy,或按 Google 的指南安装。',
897
+ "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
+ AGY_INSTALL
899
+ ],
900
+ unsupported_google_auth: [
901
+ '移除 CODEX_POLISH_AGY_AUTH 就能恢复 Antigravity 默认登录(existing-session)。',
902
+ 'Unset CODEX_POLISH_AGY_AUTH to use the default Antigravity sign-in (existing-session).'
903
+ ],
904
+ gemini_model_invalid: [
905
+ '这个项目的改写模型设置无效。请在 Codex 里说「选择改写模型」。',
906
+ "The project's model setting is invalid. Ask Codex to “Choose a rewrite model”."
907
+ ],
908
+ unsupported_node: [
909
+ '安装 Node.js 22.16 或更高版本,再用 node --version 检查。',
910
+ 'Install Node.js 22.16 or later and check with node --version.'
911
+ ]
912
+ };
913
+ function setupIssues(checks, lang) {
914
+ const lines = [],
915
+ pages = new Set();
916
+ for (const [code, [zh, en, url]] of Object.entries(issues))
917
+ if (checks.blockers.includes(code)) {
918
+ lines.push(tr(zh, en, lang) + (url ? '\n ' + url : ''));
919
+ if (url === GEMINI_KEYS) pages.add(url);
920
+ }
921
+ return [lines, [...pages]];
922
+ }
923
+ export function configurationSteps(checks) {
924
+ const lang = checks.ui_language || language(),
925
+ [issues, pages] = setupIssues(checks, lang);
926
+ const lines = [
927
+ issues.length
928
+ ? tr('开始改写前,先完成下面的设置。', 'Finish these steps before your first rewrite.', lang)
929
+ : tr('本地配置检查都通过了。', 'Your local setup checks out.', lang),
930
+ ...issues
931
+ ];
932
+ if (checks.google_auth_method === 'existing-session')
933
+ lines.push(
934
+ tr(
935
+ 'Gemini 会复用你现有的 Antigravity 登录。第一次改写如果提示登录,在运行 Codex 的机器上打开终端,运行 agy 登录就行。',
936
+ 'Gemini reuses your Antigravity sign-in. If your first rewrite asks you to sign in, open a terminal on the machine running Codex, run agy, and sign in there.',
937
+ lang
938
+ )
939
+ );
940
+ if (checks.google_auth_method === 'agent-platform')
941
+ lines.push(
942
+ tr(
943
+ '已选择 Google 企业身份。管理员需要先在运行 Codex 的环境里配置好身份。',
944
+ 'Google enterprise authentication is selected. Your admin needs to set it up in the environment running Codex.',
945
+ lang
946
+ )
947
+ );
948
+ lines.push(
949
+ decisionsSummary(checks, lang),
950
+ tr(
951
+ '在项目里新开一个 Codex 对话,说「配置回复润色」就能查看或修改设置。',
952
+ 'Open a new project chat in Codex and say “Set up Codex Polish” to view or change settings.',
953
+ lang
954
+ )
955
+ );
956
+ const examples = {
957
+ auto: [
958
+ '在已信任 hook 的新聊天里,直接问「用一句话解释 DNS。」就会触发自动润色。',
959
+ 'After trusting the hook, try automatic polishing in a new chat. Ask “Explain what DNS does in one sentence.”'
960
+ ],
961
+ manual: [
962
+ '这个项目只在点名时润色。试一句:「用一句话解释 DNS,再把你的回复润色一下。」',
963
+ 'This project polishes only when asked. Try “Explain what DNS does in one sentence, then polish your reply.”'
964
+ ],
965
+ off: [
966
+ '这个项目已关闭改写。想试用的话,可以先说「改回手动润色」。',
967
+ 'Rewriting is off in this project. To try it, say “Switch to on-demand rewrites”.'
968
+ ]
969
+ };
970
+ lines.push(tr(...examples[checks.mode], lang));
971
+ return [lines, pages];
972
+ }
973
+ async function ask(prompt) {
974
+ const io = createPrompt({ input: process.stdin, output: process.stdout });
975
+ const controller = new AbortController();
976
+ const cancel = () => controller.abort();
977
+ io.once('SIGINT', cancel);
978
+ io.once('close', cancel);
979
+ try {
980
+ return (await io.question(prompt, { signal: controller.signal })).trim().toLowerCase();
981
+ } catch {
982
+ console.log();
983
+ return null;
984
+ } finally {
985
+ io.close();
986
+ }
987
+ }
988
+ function openPage(url) {
989
+ return (
990
+ spawnSync(process.platform === 'darwin' ? '/usr/bin/open' : 'xdg-open', [url], { stdio: 'ignore', timeout: 5000 })
991
+ .status === 0
992
+ );
993
+ }
994
+ export async function showSetupGuidance({
995
+ installDependency = false,
996
+ dependencyOnly = false,
997
+ interactive = process.stdin.isTTY && process.stdout.isTTY,
998
+ check = readChecks,
999
+ install = installAgy,
1000
+ prompt = ask,
1001
+ browse = openPage
1002
+ } = {}) {
1003
+ let checks, lang;
1004
+ try {
1005
+ checks = check();
1006
+ lang = checks.ui_language || language();
1007
+ } catch {
1008
+ console.log(
1009
+ tr(
1010
+ '没能完成环境检查。在项目里新开一个 Codex 对话,说「配置回复润色」再试一次。',
1011
+ "Couldn't finish the environment check. Open a new project chat in Codex and say “Set up Codex Polish” to try again."
1012
+ )
1013
+ );
1014
+ return !installDependency;
1015
+ }
1016
+ if (checks.blockers.includes('agy_missing')) {
1017
+ let requested = installDependency;
1018
+ if (interactive && !requested)
1019
+ requested = ['', 'y', 'yes', '是'].includes(
1020
+ await prompt(
1021
+ tr(
1022
+ '改写回复需要 Google 的 Antigravity 命令行工具(agy)。现在安装吗?[Y/n] ',
1023
+ 'Codex Polish needs Google’s Antigravity CLI (agy). Install it now? [Y/n] ',
1024
+ lang
1025
+ )
1026
+ )
1027
+ );
1028
+ if (requested) {
1029
+ try {
1030
+ console.log(tr('正在从 Google 下载并安装 agy…', 'Downloading and installing agy from Google…', lang));
1031
+ await install();
1032
+ checks = check();
1033
+ if (!checks.agy_available)
1034
+ throw fail('装好后仍找不到 agy。', 'The installer finished, but agy is still missing.');
1035
+ console.log(tr('agy 已安装,可以使用。', 'agy is installed and ready to use.', lang));
1036
+ } catch (error) {
1037
+ if (error instanceof SetupError) console.error(error.message);
1038
+ console.error(
1039
+ tr(
1040
+ '插件已安装,agy 安装未完成。可在解压目录运行 node scripts/install.mjs setup --install-agy 重试。',
1041
+ 'The plugin is installed. To retry the agy installation, run node scripts/install.mjs setup --install-agy from the extracted folder.',
1042
+ lang
1043
+ ) +
1044
+ '\n' +
1045
+ AGY_INSTALL
1046
+ );
1047
+ return false;
1048
+ }
1049
+ }
1050
+ } else if (installDependency)
1051
+ console.log(tr('已找到 agy,直接使用现有安装。', 'Found agy. Your existing installation will be used.', lang));
1052
+ if (dependencyOnly) return true;
1053
+ const [lines, pages] = configurationSteps(checks);
1054
+ console.log(lines.join('\n'));
1055
+ if (
1056
+ pages.length &&
1057
+ interactive &&
1058
+ (await prompt(
1059
+ tr(
1060
+ '输入 y 在浏览器打开上面的官方页面,直接回车跳过:',
1061
+ 'Type y to open the official links above, or press Enter to skip: ',
1062
+ lang
1063
+ )
1064
+ )) === 'y'
1065
+ ) {
1066
+ for (const page of pages)
1067
+ if (!browse(page))
1068
+ console.log(tr(`浏览器没能打开页面,请手动访问 ${page}`, `Couldn't open the browser. Visit ${page}`, lang));
1069
+ }
1070
+ return true;
1071
+ }
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
+ export function doctor(checks = readChecks()) {
1089
+ const lang = checks.ui_language,
1090
+ modes = { manual: ['只在我要求时', 'only when asked'], auto: ['自动改写', 'automatic'], off: ['已关闭', 'off'] };
1091
+ 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)
1095
+ ];
1096
+ const turns = checks.history_turns;
1097
+ lines.push(
1098
+ turns
1099
+ ? tr(
1100
+ `最多带上最近 ${turns} 组问答(你的提问 + Codex 的回复),这一次的提问和草稿另算。`,
1101
+ `Sends up to ${turns} past Q&As (your question + Codex's reply), plus your current request and draft.`,
1102
+ lang
1103
+ )
1104
+ : tr(
1105
+ '历史记录设为 0,只发这一次的提问和草稿。',
1106
+ 'History is off, so only your current request and draft go out.',
1107
+ lang
1108
+ )
1109
+ );
1110
+ const detected =
1111
+ checks.language_mode === 'auto' ? tr('自动识别', 'automatic', lang) : tr('项目设置', 'project setting', lang);
1112
+ lines.push(tr(`界面语言:中文(${detected})`, `Interface language: English (${detected})`, lang));
1113
+ for (const [tool, ready] of [
1114
+ ['Node.js 22.16+', checks.node_available],
1115
+ ['Codex CLI', checks.codex_available],
1116
+ ['Antigravity CLI', checks.agy_available]
1117
+ ]) {
1118
+ lines.push(tool + tr(':', ': ', lang) + (ready ? tr('可用', 'available', lang) : tr('未找到', 'not found', lang)));
1119
+ }
1120
+ switch (checks.google_auth_method) {
1121
+ case 'existing-session':
1122
+ lines.push(
1123
+ tr(
1124
+ 'Google 账号:复用 Antigravity 里的登录,真正改写时才会验证状态。',
1125
+ 'Google sign-in: reuses your Antigravity account (verified when you run a rewrite).',
1126
+ lang
1127
+ )
1128
+ );
1129
+ break;
1130
+ case 'agent-platform':
1131
+ lines.push(tr('Google 身份:企业平台。', 'Google sign-in: enterprise platform.', lang));
1132
+ break;
1133
+ case 'gemini-api-key':
1134
+ lines.push(
1135
+ tr('Gemini API 密钥:', 'Gemini API key: ', lang) +
1136
+ (checks.gemini_key_configured ? tr('已配置', 'configured', lang) : tr('未配置', 'not configured', lang))
1137
+ );
1138
+ break;
1139
+ }
1140
+ if (checks.blockers.length)
1141
+ lines.unshift(
1142
+ tr(
1143
+ '现在会先原样保留草稿。完成下面的设置后就可以使用改写了。',
1144
+ 'Codex Polish is leaving your drafts as-is for now. Finish these steps, then try again.',
1145
+ lang
1146
+ ),
1147
+ ...setupIssues(checks, lang)[0]
1148
+ );
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
+ return lines.join('\n');
1161
+ }
1162
+ function usage(lang) {
1163
+ return tr(
1164
+ '用法:node scripts/install.mjs [setup|update|doctor|uninstall] [--install-agy]\nsetup 安装(默认),update 更新,doctor 检查当前项目,uninstall 卸载。\n--install-agy 在缺少 agy 时安装,仅限 setup 和 update。\n-h, --help 显示帮助并退出。',
1165
+ 'Usage: node scripts/install.mjs [setup|update|doctor|uninstall] [--install-agy]\nsetup installs the plugin (default), update upgrades it, doctor checks this project, and uninstall removes it.\n--install-agy installs Google’s Antigravity CLI if missing during setup or update.\n-h, --help shows this help.',
1166
+ lang
1167
+ );
1168
+ }
1169
+ export async function main(args = process.argv.slice(2)) {
1170
+ const lang = language();
1171
+ if (args.includes('-h') || args.includes('--help')) {
1172
+ console.log(usage(lang));
1173
+ return 0;
1174
+ }
1175
+ const actions = args.filter((arg) => arg !== '--install-agy');
1176
+ const action = actions[0] ?? 'setup';
1177
+ if (actions.length > 1 || !['setup', 'update', 'doctor', 'uninstall'].includes(action)) {
1178
+ console.error(usage(lang));
1179
+ return 2;
1180
+ }
1181
+ const installDependency = args.includes('--install-agy');
1182
+ if (installDependency && !['setup', 'update'].includes(action)) {
1183
+ const flag = '--install-agy';
1184
+ console.error(tr(`${flag} 只能用于 setup 或 update`, `${flag} only works with setup or update`, lang));
1185
+ return 2;
1186
+ }
1187
+ try {
1188
+ if (action === 'doctor') {
1189
+ console.log(doctor());
1190
+ return 0;
1191
+ }
1192
+ const [message, offerSetup] = await manage(action, ROOT, snapshotStore());
1193
+ console.log(message);
1194
+ if (
1195
+ (offerSetup || installDependency) &&
1196
+ !(await showSetupGuidance({ installDependency, dependencyOnly: !offerSetup }))
1197
+ )
1198
+ return 1;
1199
+ return 0;
1200
+ } catch (error) {
1201
+ console.error(
1202
+ error instanceof SetupError
1203
+ ? error.message
1204
+ : tr(
1205
+ '没法核对安装文件或环境。请检查文件权限和发行包后再试。',
1206
+ "Couldn't verify the installation files or environment. Check the package and file permissions, then try again.",
1207
+ lang
1208
+ )
1209
+ );
1210
+ return 1;
1211
+ }
1212
+ }
1213
+ if (
1214
+ process.argv[1] &&
1215
+ fs.existsSync(process.argv[1]) &&
1216
+ fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)
1217
+ ) {
1218
+ process.exitCode = await main();
1219
+ if (process.env.CODEX_POLISH_INSTALL_WINDOW === '1' && process.stdin.isTTY)
1220
+ await ask(tr('按回车关闭安装窗口。', 'Press Enter to close the installer.'));
1221
+ }