@kyun.si/agy-polish 0.0.4-beta.7 → 0.0.4-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,10 +12,12 @@ npx @kyun.si/agy-polish@beta setup
12
12
 
13
13
  In Windows PowerShell, use `npx.cmd` in place of `npx`.
14
14
 
15
- Setup starts with **Manual · polish only when asked**. Press Enter to keep it, or select Normal, Turbo, or Off. AGY Polish uses `gpt-6.2-sol` with Extra High reasoning (`xhigh`) by default. In setup, you can also follow your local Codex settings or choose a model and reasoning effort from your provider. Run `setup` again to change your choices, or use `/polish-settings` in Antigravity.
15
+ Setup starts with **Manual · polish only when asked**. In Manual the mode hook defaults to off. Explicit edits such as “说人话” still work. Choosing Normal or Turbo enables the mode hook for automatic edits. Off also skips explicit rewrites. AGY Polish uses `gpt-6.2-sol` with Extra High reasoning (`xhigh`) by default. In setup, you can also follow your local Codex settings or choose a model and reasoning effort from your provider. Run `setup` again to change your choices, or use `/polish-settings` in Antigravity.
16
16
 
17
17
  Start a new `agy` chat and try `/polish Rewrite the previous reply in two sentences.` If Antigravity asks for permission, allow the `polish_reply` tool.
18
18
 
19
+ In a terminal, Normal and Turbo show the original draft before automatic polishing, then display the rewrite if it changes. If you decline the tool request, the original draft is already visible.
20
+
19
21
  For a full reply rewrite, your Codex provider receives the current draft, its question and your editing directions. For a selected passage, it receives just that passage and the relevant directions.
20
22
 
21
23
  ## Maintenance
@@ -26,6 +28,6 @@ npx @kyun.si/agy-polish@beta update
26
28
  npx @kyun.si/agy-polish@beta uninstall
27
29
  ```
28
30
 
29
- AGY Polish keeps your mode and model settings when you update or uninstall the plugin.
31
+ Use `update --hook on` or `update --hook off` to change just the mode hook. Start a new chat after changing it. AGY Polish keeps your mode and model settings when you update or uninstall the plugin.
30
32
 
31
33
  [Agent Polish source and documentation](https://github.com/mreasonyang/agent-polish) · [Apache-2.0 License](LICENSE)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kyun.si/agy-polish",
3
- "version": "0.0.4-beta.7",
3
+ "version": "0.0.4-beta.9",
4
4
  "description": "Polish Antigravity replies with Codex · 用 Codex 润色 Antigravity 回复",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -1,5 +1,6 @@
1
1
  {
2
2
  "agy-polish-mode": {
3
+ "enabled": false,
3
4
  "PreInvocation": [
4
5
  { "type": "command", "command": "node ./scripts/mode-hook.mjs", "timeout": 3 }
5
6
  ]
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agy-polish",
3
3
  "displayName": "AGY Polish · 回复润色",
4
- "version": "0.0.4-beta.7",
4
+ "version": "0.0.4-beta.9",
5
5
  "description": "Polish Antigravity replies with your local Codex CLI. 用本机 Codex CLI 润色 Antigravity 的回复。",
6
6
  "author": { "name": "mreasonyang" },
7
7
  "repository": "https://github.com/mreasonyang/agent-polish",
@@ -1,9 +1,9 @@
1
1
  # Reply polishing
2
2
 
3
- Answer the user normally, including doing any requested work. Use the latest Codex Polish mode message for this user turn. In Normal or Turbo, finish the complete Gemini draft before publishing, then call the `polish_reply` MCP tool from the agy-polish plugin once with the current user question, the complete draft, and `trigger: "auto"`. In Manual (Only when asked), send ordinary answers directly and use the tool only for explicit polishing requests. If the current-turn mode message is missing, answer directly. Never call the MCP tool or run a command to determine the mode for an ordinary answer.
3
+ Answer the user normally, including doing any requested work. On an ordinary question, use only the Codex Polish mode message for **this user turn**. In Normal or Turbo, finish the complete Gemini draft, then call the `polish_reply` MCP tool from the agy-polish plugin once with the current user question, the complete draft, and `trigger: "auto"`. Publish the draft before calling the tool only when the current-turn mode message requests a visible draft in the interactive terminal. With no current-turn mode message (the default), or in Manual, send ordinary answers directly. Never call the MCP tool or run a command to determine the mode for an ordinary answer. On an explicit polishing request, including a standalone “说人话”, follow the polish skill even when the hook is disabled.
4
4
 
5
5
  - In Off, never invoke Codex or the `polish_reply` MCP tool for reply polishing. If the request only asks to polish supplied text or an identifiable previous reply, return the original text or complete reply verbatim, preserving leading and trailing whitespace, line breaks, Markdown, and code. Do not rewrite it yourself or add anything to it, even if the user specifies edits. If `/polish` accompanies a new question or task, answer it normally and send the answer directly.
6
6
  - Use `trigger: "explicit"` when the user asks to polish or invokes `/polish`. A standalone “说人话” asks to rewrite the previous assistant reply in plain language. Pass that reply verbatim as `draft` and the user's wording as `rewrite_request`. Follow the polish skill for a prior reply or a selected passage. Ordinary requests to edit a file or write content are not explicit requests to polish the chat reply.
7
7
  - For “配置回复润色”, “configure reply polishing”, or requests to view or change **reply polishing** mode, Codex model, or thinking level, use the `polish-settings` skill. Send the settings answer directly. Unrelated Antigravity settings remain ordinary host settings.
8
8
  - Skip polishing when the user asks to cancel, skip polishing, keep the turn private, use Gemini only, or avoid sharing the material with another model or service. Also skip it for exact-format or verbatim responses, such as a JSON-only answer, literal transcription, or a raw command. A request for prose with no preamble or extra commentary still permits polishing. Follow these instructions even in Turbo and on an explicit turn. When uncertain about permission to share, keep the Gemini response.
9
- - Send only the current question, the final draft, and explicitly requested editing instructions. Keep the draft private within this workflow until the tool returns. Use the tool's full text as the final reply verbatim, preserving the language, Markdown, code, and whitespace. On tool errors, unavailability, cancellation, or if the tool returns no usable body, keep the Gemini draft and never retry in the same turn. If the turn itself is cancelled, stop.
9
+ - Send only the current question, the final draft, and explicitly requested editing instructions. Use the tool's full text as the final reply verbatim, preserving the language, Markdown, code, and whitespace. On tool errors, unavailability, cancellation, or if the tool returns no usable body, keep the Gemini draft and never retry in the same turn. If the original draft is already visible and no usable rewrite was returned, end the turn without repeating the draft. If the turn itself is cancelled, stop.
@@ -1,6 +1,8 @@
1
1
  import { createInterface } from 'node:readline';
2
+ import { dirname } from 'node:path';
2
3
  import manifest from '../plugin.json' with { type: 'json' };
3
4
  import { polishInputSchema, polishReply, validInput } from './polish-reply.mjs';
5
+ import { eagerPolishAvailable } from './mode-hook-config.mjs';
4
6
 
5
7
  const versions = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
6
8
  const tool = {
@@ -8,6 +10,7 @@ const tool = {
8
10
  description: 'Polish one complete Antigravity draft with the local Codex CLI when the current polishing settings permit it. The response text is the entire final reply, or the original draft unchanged if skipped or unsuccessful.',
9
11
  inputSchema: polishInputSchema
10
12
  };
13
+ const available = () => eagerPolishAvailable(dirname(import.meta.dirname), process.argv.slice(2));
11
14
 
12
15
  const active = new Map();
13
16
  const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
@@ -25,7 +28,7 @@ async function call(id, input) {
25
28
  const controller = new AbortController();
26
29
  active.set(id, controller);
27
30
  try {
28
- const text = await polishReply(input, { signal: controller.signal });
31
+ const text = await polishReply(input, { signal: controller.signal, available });
29
32
  if (!controller.signal.aborted) write({ id, result: { content: [{ type: 'text', text }] } });
30
33
  } finally {
31
34
  active.delete(id);
@@ -68,10 +71,10 @@ lines.on('line', (line) => {
68
71
  write({ id, result: {} });
69
72
  break;
70
73
  case 'tools/list':
71
- write({ id, result: { tools: [tool] } });
74
+ write({ id, result: { tools: available() ? [tool] : [] } });
72
75
  break;
73
76
  case 'tools/call':
74
- if (params?.name !== tool.name || !validInput(params.arguments)) {
77
+ if (!available() || params?.name !== tool.name || !validInput(params.arguments)) {
75
78
  fail(id, -32602, 'Invalid polish_reply arguments');
76
79
  } else {
77
80
  void call(id, params.arguments);
@@ -0,0 +1,95 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { chmodSync, lstatSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { isDeepStrictEqual } from 'node:util';
5
+
6
+ const group = 'agy-polish-mode';
7
+ const server = 'agy-polish_agy-polish';
8
+ const managedFlag = '--agy-polish-eager';
9
+ export const automaticMode = mode => mode === 'normal' || mode === 'turbo';
10
+
11
+ function readJson(path, allowEmpty = false) {
12
+ const entry = lstatSync(path);
13
+ if (!entry.isFile()) throw new Error('Expected a regular Antigravity configuration file');
14
+ const raw = readFileSync(path, 'utf8');
15
+ const data = allowEmpty && !raw.trim() ? {} : JSON.parse(raw);
16
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('Invalid Antigravity configuration');
17
+ return { data, mode: entry.mode & 0o777 };
18
+ }
19
+
20
+ function writeJson(path, data, mode) {
21
+ const temp = join(dirname(path), '.agy-polish-' + randomUUID() + '.tmp');
22
+ try {
23
+ writeFileSync(temp, JSON.stringify(data, null, 2) + '\n', { flag: 'wx', mode });
24
+ chmodSync(temp, mode);
25
+ renameSync(temp, path);
26
+ } finally {
27
+ rmSync(temp, { force: true });
28
+ }
29
+ }
30
+
31
+ export function savedModeHook(root) {
32
+ try {
33
+ const enabled = readJson(join(root, 'hooks.json')).data[group]?.enabled;
34
+ if (enabled !== undefined && typeof enabled !== 'boolean') throw new Error('Invalid mode hook setting');
35
+ return enabled;
36
+ } catch (error) {
37
+ if (error.code === 'ENOENT') return undefined;
38
+ throw error;
39
+ }
40
+ }
41
+
42
+ // Write only the plugin's own hook, preserving the other declarations and file permissions.
43
+ export function setModeHook(root, enabled) {
44
+ const path = join(root, 'hooks.json');
45
+ const { data: hooks, mode } = readJson(path);
46
+ const previous = hooks[group].enabled;
47
+ if (previous === enabled) return previous;
48
+ hooks[group].enabled = enabled;
49
+ writeJson(path, hooks, mode);
50
+ return previous;
51
+ }
52
+
53
+ // AgY 1.5.21 applies eager tool preferences from the profile MCP configuration.
54
+ // Use the bundled server's exact name so the existing per-tool permission still applies.
55
+ export function setEagerPolishTool(root, enabled) {
56
+ const profile = dirname(dirname(root));
57
+ const file = join(profile, 'mcp_config.json');
58
+ let data, mode;
59
+ try {
60
+ // Antigravity can create this file with no initial contents.
61
+ ({ data, mode } = readJson(file, true));
62
+ } catch (error) {
63
+ if (!enabled) return;
64
+ if (error.code !== 'ENOENT') throw error;
65
+ data = {};
66
+ mode = 0o600;
67
+ }
68
+ const servers = Object.hasOwn(data, 'mcpServers') ? data.mcpServers : {};
69
+ if (!servers || typeof servers !== 'object' || Array.isArray(servers)) {
70
+ if (!enabled) return;
71
+ throw new Error('Invalid Antigravity MCP servers');
72
+ }
73
+ const args = [join(root, 'scripts', 'mcp-server.mjs'), managedFlag];
74
+ const existing = servers[server];
75
+ const managed = existing?.command === 'node' && isDeepStrictEqual(existing.args, args);
76
+ if (enabled) {
77
+ if (Object.hasOwn(servers, server)) return;
78
+ servers[server] = { command: 'node', args, tools: { polish_reply: { eager: true } } };
79
+ } else {
80
+ if (!managed) return;
81
+ delete servers[server];
82
+ }
83
+ data.mcpServers = servers;
84
+ writeJson(file, data, mode);
85
+ }
86
+
87
+ export function eagerPolishAvailable(root, argv) {
88
+ if (!argv.includes(managedFlag)) return true;
89
+ try {
90
+ const { data } = readJson(join(dirname(dirname(root)), 'config.json'));
91
+ return data.plugins?.['agy-polish']?.enabled === true && savedModeHook(root) === true;
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
@@ -1,5 +1,6 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { readSettings } from './settings.mjs';
3
+ import { showsTerminalDraft } from './terminal-draft.mjs';
3
4
 
4
5
  const instructions = {
5
6
  normal: 'On an eligible ordinary turn call polish_reply once with trigger auto. On an explicit polishing turn use trigger explicit.',
@@ -11,6 +12,11 @@ const instructions = {
11
12
  'If /polish accompanies a new question or task, answer it normally and deliver the answer directly.'
12
13
  };
13
14
 
15
+ const terminalDraft = 'For automatic polishing in this interactive terminal, first send the complete draft as visible assistant text before making the tool call. ' +
16
+ 'Label that message “Original draft” in the user’s language. Pass the same draft text without the label to polish_reply with trigger auto. ' +
17
+ 'After a successful edit, send the returned rewrite verbatim. If the call fails or returns the original draft, end the turn without repeating the draft. ' +
18
+ 'Use the usual workflow for explicit polishing requests and for turns that should skip polishing.';
19
+
14
20
  function modeContext() {
15
21
  const input = JSON.parse(readFileSync(0, 'utf8'));
16
22
  // ProtoJSON may omit the initial, zero-valued invocation number.
@@ -22,6 +28,9 @@ function modeContext() {
22
28
  // Treat unavailable settings as off for this turn.
23
29
  }
24
30
  let guidance = instructions[mode];
31
+ if ((mode === 'normal' || mode === 'turbo') && showsTerminalDraft(input.artifactDirectoryPath)) {
32
+ guidance += ' ' + terminalDraft;
33
+ }
25
34
  if (typeof input.lastUserInput === 'string' && /^说人话[。!.!]*$/u.test(input.lastUserInput.trim())) {
26
35
  guidance = mode === 'off'
27
36
  ? 'For this request, return the previous assistant reply verbatim. Do not call polish_reply or invoke Codex.'
@@ -129,7 +129,7 @@ export function validInput(input) {
129
129
  (input.selection === undefined || (typeof input.selection === 'string' && !!input.selection.trim()));
130
130
  }
131
131
 
132
- export async function polishReply(input, { signal, timeout = 90_000 } = {}) {
132
+ export async function polishReply(input, { signal, timeout = 90_000, available = () => true } = {}) {
133
133
  if (!validInput(input)) return typeof input?.draft === 'string' ? input.draft : '';
134
134
  const { draft, question, trigger, rewrite_request, selection } = input;
135
135
  try {
@@ -147,7 +147,7 @@ export async function polishReply(input, { signal, timeout = 90_000 } = {}) {
147
147
  const reply = await withWorkspace((workspace) => editWithCodex(workspace, { signal, timeout }, outputSchema, () => {
148
148
  // Provider and credential lookup can take time. Read the current preferences at dispatch.
149
149
  const { mode, model, effort } = readSettings();
150
- if (signal?.aborted || mode === 'off' || (mode === 'manual' && initialMode !== 'manual')) return;
150
+ if (signal?.aborted || !available() || mode === 'off' || (mode === 'manual' && initialMode !== 'manual')) return;
151
151
  return { model, effort, prompt: promptFor(input, mode, selected) };
152
152
  }));
153
153
  if (reply === undefined || signal?.aborted) return draft;
@@ -3,11 +3,12 @@ import {
3
3
  mkdirSync, readFileSync, renameSync, rmSync, writeFileSync
4
4
  } from 'node:fs';
5
5
  import { homedir } from 'node:os';
6
- import { dirname, join, resolve } from 'node:path';
6
+ import { basename, dirname, join, resolve } from 'node:path';
7
7
  import { pathToFileURL } from 'node:url';
8
8
  import { withWorkspace } from './codex-process.mjs';
9
9
  import { withCodexAppServer } from './codex-provider.mjs';
10
10
  import { withLock } from './directory-lock.mjs';
11
+ import { automaticMode, setEagerPolishTool, setModeHook } from './mode-hook-config.mjs';
11
12
 
12
13
  const MODES = ['normal', 'turbo', 'manual', 'off'];
13
14
  export const DEFAULT_MODEL = 'gpt-6.2-sol';
@@ -71,7 +72,7 @@ function replaceSettings(source, destination) {
71
72
  }
72
73
  }
73
74
 
74
- export async function writeSettings(patch) {
75
+ export async function writeSettings(patch, hookRoot, profileInstall = false) {
75
76
  if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) {
76
77
  throw new Error('Invalid polishing settings patch');
77
78
  }
@@ -88,12 +89,22 @@ export async function writeSettings(patch) {
88
89
  mkdirSync(writer, { recursive: true, mode: 0o700 });
89
90
  return withLock(writer, () => {
90
91
  // Store the choice itself so changing only the model can use that model's default effort.
91
- const document = { ...EMPTY_SETTINGS, ...readDocument(file), ...patch };
92
+ const current = readDocument(file);
93
+ const document = { ...EMPTY_SETTINGS, ...current, ...patch };
92
94
  const settings = preferences(document);
93
95
  const stage = join(writer, randomUUID() + '.tmp');
94
96
  try {
95
97
  writeFileSync(stage, JSON.stringify(document, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
96
- replaceSettings(stage, file);
98
+ const auto = automaticMode(settings.mode);
99
+ const previous = hookRoot && setModeHook(hookRoot, auto);
100
+ try {
101
+ if (profileInstall) setEagerPolishTool(hookRoot, auto);
102
+ replaceSettings(stage, file);
103
+ } catch (error) {
104
+ if (hookRoot) setModeHook(hookRoot, previous);
105
+ if (profileInstall) setEagerPolishTool(hookRoot, previous === true && automaticMode(current.mode));
106
+ throw error;
107
+ }
97
108
  return settings;
98
109
  } finally {
99
110
  rmSync(stage, { force: true });
@@ -101,6 +112,16 @@ export async function writeSettings(patch) {
101
112
  });
102
113
  }
103
114
 
115
+ function setFromChat(patch) {
116
+ const root = dirname(import.meta.dirname);
117
+ const profile = dirname(dirname(root));
118
+ // Only change the active plugin's installed copy. Source checkouts and npm packages are immutable.
119
+ const profileInstall = basename(profile) === 'config' && basename(dirname(profile)) === '.gemini';
120
+ const installed = basename(dirname(root)) === 'plugins' && (basename(profile) === '.agents' || profileInstall);
121
+ if (!patch.mode || !installed) return writeSettings(patch);
122
+ return withLock(profile, () => writeSettings(patch, root, profileInstall));
123
+ }
124
+
104
125
  export async function listModels({ signal, timeout = 20_000 } = {}) {
105
126
  return withWorkspace(({ cwd }) => withCodexAppServer(cwd, { signal, timeout }, async (request) => {
106
127
  const { config } = await request('config/read', { includeLayers: false, cwd });
@@ -159,7 +180,7 @@ export async function runSettingsCommand([command, ...args]) {
159
180
  if (own(patch, key)) throw new Error('Duplicate flag');
160
181
  patch[key] = key !== 'mode' && value === 'default' ? null : value;
161
182
  }
162
- result = await writeSettings(patch);
183
+ result = await setFromChat(patch);
163
184
  } else {
164
185
  throw new Error('Invalid command');
165
186
  }
@@ -0,0 +1,22 @@
1
+ import { closeSync, openSync } from 'node:fs';
2
+ import { basename, dirname, isAbsolute } from 'node:path';
3
+ import { isatty } from 'node:tty';
4
+
5
+ function hasControllingTerminal() {
6
+ // Hook stdin and stdout are pipes even when the host is interactive.
7
+ let fd;
8
+ try {
9
+ fd = openSync(process.platform === 'win32' ? '\\\\.\\CONIN$' : '/dev/tty', 'r');
10
+ return isatty(fd);
11
+ } catch {
12
+ return false;
13
+ } finally {
14
+ if (fd !== undefined) closeSync(fd);
15
+ }
16
+ }
17
+
18
+ export function showsTerminalDraft(artifactDirectoryPath, hasTerminal = hasControllingTerminal) {
19
+ if (typeof artifactDirectoryPath !== 'string' || !isAbsolute(artifactDirectoryPath)) return false;
20
+ const brain = dirname(artifactDirectoryPath);
21
+ return basename(brain) === 'brain' && basename(dirname(brain)) === 'antigravity-cli' && hasTerminal();
22
+ }
@@ -3,7 +3,7 @@ name: polish
3
3
  description: Explicitly polish an Antigravity reply with Codex. Use /polish or when explicitly asked to polish this or a previous reply, with optional editing instructions or a selected passage. 润色这条或上一条回复,可指定改法或只选一段。单独发送「说人话」时,把上一条回复改成大白话。
4
4
  ---
5
5
 
6
- Use the current-turn Codex Polish mode from the plugin hook. Respect the plugin rule about sharing, cancellation, and exact-format responses.
6
+ Respect the plugin rule about sharing, cancellation, and exact-format responses. For an explicit request, use the mode message from this user turn if present. The hook is off by default. When there is no current-turn message, run `node "<absolute path to this skill>/../../scripts/settings.mjs" show` locally and read its `mode` field. This check takes no conversation text and makes no model request. Use it only for an explicit edit. Never infer the mode from an earlier turn.
7
7
 
8
8
  In Off mode, or if the current mode is unavailable, never invoke Codex or the `polish_reply` MCP tool. For a polish-only request, copy just the supplied source text or the complete referenced reply verbatim. Preserve leading and trailing whitespace, line breaks, Markdown, and code. Do not apply any editing directions yourself or add an introduction, status message, or wrapping. For `/polish` with a new question or task, answer normally and send that answer directly. If no text or reply can be identified for a polish-only request, ask which one the user means.
9
9
 
@@ -14,6 +14,7 @@ node "<skill directory>/scripts/settings.mjs" set --model codex-default --effort
14
14
  ```
15
15
 
16
16
  - `show` reports the current choice; offer the available modes in the user's language when they just ask to configure polishing. Normal (普通) edits when useful. Turbo (积极润色) edits more actively. Manual (仅手动) is the default and runs only on explicit requests. Off (关闭) disables polishing. The supported mode values are `normal`, `turbo`, `manual`, and `off`.
17
+ - Setting Normal or Turbo enables the installed plugin’s mode hook. Setting Manual or Off disables it. Start a new chat to load a changed hook declaration. In Manual, explicit requests such as “说人话” also work with the hook off.
17
18
  - The AGY Polish default is `gpt-6.2-sol` with Extra High (`xhigh`) reasoning. Use `set --model default --effort default` to restore both. When the user wants to follow their local Codex configuration, use `codex-default` for the requested field or fields. A null in the output of `show` means Codex determines that setting.
18
19
  - Make an unambiguous requested change directly. When changing to a specific Codex model or thinking level, consult `list-models` and use the exact model ID and a supported effort. Use the row marked `isDefault` when following the local Codex model. If a newly chosen model does not support the current effort, offer its supported levels and the option to follow Codex. Supply only the requested options to `set` and quote their values for the shell. Resetting effort with `default` selects `xhigh` for `gpt-6.2-sol` and lets Codex determine the effort for other models.
19
20
  - If the catalog is unavailable, mode changes and resets remain available. Report the command result in the user's language. Do not ask for keys or credentials in chat.
@@ -10,8 +10,9 @@ import { chooseOption, thinkingLabels, waitForCatalog } from './installer_termin
10
10
  import { AGY_INSTALL, installAgyBootstrap } from './agy_bootstrap.mjs';
11
11
  import {
12
12
  AgyInstallError, agyProfile, requireAgyCli, installedAgy, validateAgyBundle,
13
- changeAgyPlugin, loadAgySettings, checkCodexProvider
13
+ changeAgyPlugin, installAgyPlugin, loadAgySettings, checkCodexProvider
14
14
  } from './agy_install.mjs';
15
+ import { automaticMode, savedModeHook, setEagerPolishTool } from '../plugins/agy-polish/scripts/mode-hook-config.mjs';
15
16
 
16
17
  const fail = (zh, en) => new AgyInstallError(tr(zh, en));
17
18
 
@@ -145,6 +146,10 @@ async function doctorAgy(lang) {
145
146
  if (entry) {
146
147
  console.log(t('agy-polish 已安装,版本 ', 'agy-polish is installed, version ') + entry.version +
147
148
  (entry.enabled ? '' : t('(已停用)', ' (disabled)')));
149
+ const hook = savedModeHook(entry.path);
150
+ if (hook !== undefined) console.log(hook
151
+ ? t('agy-polish-mode hook 已启用。', 'The agy-polish-mode hook is on.')
152
+ : t('agy-polish-mode hook 已关闭。', 'The agy-polish-mode hook is off.'));
148
153
  } else {
149
154
  console.log(t('agy-polish 未安装。运行 ', 'agy-polish is not installed. Run ') + agySetupCommand);
150
155
  }
@@ -157,7 +162,7 @@ async function doctorAgy(lang) {
157
162
  return entry && provider.ready ? 0 : 1;
158
163
  }
159
164
 
160
- async function runAgyHost(action, plan, installDependency, lang) {
165
+ async function runAgyHost(action, plan, installDependency, lang, hook) {
161
166
  if (action === 'doctor') return doctorAgy(lang);
162
167
  const t = (zh, en) => tr(zh, en, lang);
163
168
  const settingsHelp = t('可在 Antigravity 对话中输入 /polish-settings 调整模式、模型和思考等级。',
@@ -186,17 +191,18 @@ async function runAgyHost(action, plan, installDependency, lang) {
186
191
  requireAgyCli();
187
192
  const profile = canonical(agyProfile());
188
193
  fs.mkdirSync(profile, { recursive: true, mode: 0o700 });
189
- const enabled = await withLock(profile, async () => {
194
+ const installed = await withLock(profile, async () => {
190
195
  const before = installedAgy();
191
196
  if (action === 'uninstall') {
192
197
  if (before) changeAgyPlugin('uninstall');
193
198
  if (installedAgy()) throw fail('agy 仍显示插件已安装,请再试一次卸载。', 'agy still lists the plugin as installed. Run uninstall again.');
199
+ setEagerPolishTool(before?.path ?? join(profile, 'plugins', 'agy-polish'), false);
194
200
  console.log(t('agy-polish 已卸载,模式和模型设置已保留。', 'agy-polish is uninstalled. Your mode and model settings were kept.'));
195
- return false;
201
+ return null;
196
202
  }
197
203
  if (action === 'update' && !before) {
198
204
  console.log(t('agy-polish 未安装。要加装,运行 ', 'agy-polish is not installed. To add it, run ') + agySetupCommand);
199
- return false;
205
+ return null;
200
206
  }
201
207
  const { path, version } = validateAgyBundle();
202
208
  if (before && compareVersions(version, before.version,
@@ -204,9 +210,15 @@ async function runAgyHost(action, plan, installDependency, lang) {
204
210
  throw fail('这个包比已安装的 agy-polish 旧。请使用更新的安装包。',
205
211
  'This package is older than the installed agy-polish. Use a newer package.');
206
212
  }
213
+ const previousHook = hook === undefined && before && !plan?.patch.mode ? savedModeHook(before.path) : undefined;
214
+ const auto = hook !== 'off' && (hook === 'on' || previousHook !== false) &&
215
+ automaticMode(plan?.mode ?? (await loadAgySettings()).current.mode);
216
+ const hookEnabled = hook === undefined
217
+ ? previousHook ?? auto
218
+ : hook === 'on';
207
219
  // Persist a fresh install's selected mode before agy can load the plugin.
208
220
  if (!before) await save();
209
- changeAgyPlugin('install', path);
221
+ installAgyPlugin(path, hookEnabled);
210
222
  let entry = installedAgy();
211
223
  if (before?.enabled === false && entry?.enabled === true) {
212
224
  changeAgyPlugin('disable');
@@ -217,24 +229,28 @@ async function runAgyHost(action, plan, installDependency, lang) {
217
229
  'agy did not confirm the plugin version and enabled state. Check the installation in Antigravity.');
218
230
  }
219
231
  if (before) await save();
232
+ try { setEagerPolishTool(entry.path, hookEnabled && auto); }
233
+ catch { throw fail('无法写入 Antigravity 的 MCP 设置,请检查 mcp_config.json。', 'Could not update Antigravity MCP settings. Check mcp_config.json.'); }
220
234
  console.log(action === 'update'
221
235
  ? t('agy-polish 已更新到 ', 'Updated agy-polish to ') + version
222
236
  : t('agy-polish 已安装,版本 ', 'agy-polish is installed, version ') + version);
223
237
  if (!entry.enabled) console.log(t('插件目前仍是停用状态,可在 Antigravity 的插件设置中启用。',
224
238
  'The plugin is still disabled. You can enable it in Antigravity plugin settings.'));
225
- return entry.enabled;
239
+ return entry;
226
240
  });
227
241
  if (!plan) return 0;
228
- if (plan.mode === 'off') console.log(enabled ? off + ' ' + settingsHelp : off);
229
- else if (enabled) {
242
+ if (plan.mode === 'off') console.log(installed?.enabled ? off + ' ' + settingsHelp : off);
243
+ else if (installed?.enabled) {
230
244
  const provider = plan.provider ?? await checkCodexProvider(lang);
231
245
  if (!provider.ready) console.log(provider.message);
232
246
  const start = provider.ready
233
247
  ? t('在 Antigravity 中新开对话。', 'Start a new chat in Antigravity.')
234
248
  : t('处理上面的 Codex 问题后,在 Antigravity 中新开对话。', 'After resolving the Codex issue above, start a new chat in Antigravity.');
235
- const use = plan.mode === 'manual'
236
- ? t('输入 /polish,或提问时加一句「请润色」。', 'Use /polish or ask for polishing in your question.')
237
- : t('输入 /polish,或像平常一样提问。', 'Use /polish or ask a question as usual.');
249
+ let use = t('输入 /polish,或像平常一样提问。', 'Use /polish or ask a question as usual.');
250
+ if (plan.mode === 'manual') use = t('手动润色无需 hook。输入 /polish,或提问时加一句「请润色」。',
251
+ 'Manual polishing works without a hook. Use /polish or ask for polishing in your question.');
252
+ else if (savedModeHook(installed.path) === false) use = t('模式 hook 已关闭。可直接输入 /polish,或用 update --hook on 开启自动润色。',
253
+ 'The mode hook is off. Use /polish for a single edit, or run update --hook on for automatic edits.');
238
254
  console.log(start + ' ' + use);
239
255
  console.log(t('看到 MCP 授权提示时,只授权 agy-polish 的 polish_reply 工具。',
240
256
  'If Antigravity prompts for MCP approval, approve only the agy-polish tool polish_reply.'));
@@ -245,8 +261,8 @@ async function runAgyHost(action, plan, installDependency, lang) {
245
261
 
246
262
  function usage(lang) {
247
263
  return tr(
248
- '用法:agy-polish [setup|update|doctor|uninstall] [--install-agy]\nsetup(默认命令)安装 Antigravity 插件,可选择润色模式、Codex 模型和思考等级。\n--install-agy 可在 setup 或 update 中安装 Google 的 Antigravity CLI。\n-h, --help 显示帮助。',
249
- 'Usage: agy-polish [setup|update|doctor|uninstall] [--install-agy]\nsetup (default) installs the Antigravity plugin and lets you choose the polishing mode, Codex model and reasoning effort.\n--install-agy can install Google’s Antigravity CLI during setup or update.\n-h, --help shows this help.',
264
+ '用法:agy-polish [setup|update|doctor|uninstall] [--install-agy] [--hook on|off]\nsetup(默认命令)安装 Antigravity 插件,可选择润色模式、Codex 模型和思考等级。\n--install-agy 可在 setup 或 update 中安装 Google 的 Antigravity CLI。\n--hook on|off 可在 setup 或 update 中单独开关本插件的 hook。\n-h, --help 显示帮助。',
265
+ 'Usage: agy-polish [setup|update|doctor|uninstall] [--install-agy] [--hook on|off]\nsetup (default) installs the Antigravity plugin and lets you choose the polishing mode, Codex model and reasoning effort.\n--install-agy can install Google’s Antigravity CLI during setup or update.\n--hook on|off enables or disables this plugin’s mode hook during setup or update.\n-h, --help shows this help.',
250
266
  lang
251
267
  );
252
268
  }
@@ -257,15 +273,17 @@ export async function main(args = process.argv.slice(2)) {
257
273
  console.log(usage(lang));
258
274
  return 0;
259
275
  }
260
- let action, installDependency;
276
+ let action, installDependency, hook;
261
277
  try {
262
278
  const { values, positionals } = parseArgs({
263
279
  args, allowPositionals: true,
264
- options: { 'install-agy': { type: 'boolean' }, advanced: { type: 'boolean' } }
280
+ options: { 'install-agy': { type: 'boolean' }, advanced: { type: 'boolean' }, hook: { type: 'string' } }
265
281
  });
266
282
  action = positionals[0] ?? 'setup';
267
283
  installDependency = values['install-agy'] ?? false;
284
+ hook = values.hook;
268
285
  if (positionals.length > 1 || !['setup', 'update', 'doctor', 'uninstall'].includes(action) ||
286
+ (hook !== undefined && (!['on', 'off'].includes(hook) || !['setup', 'update'].includes(action))) ||
269
287
  (values.advanced && action !== 'setup') || (installDependency && !['setup', 'update'].includes(action))) {
270
288
  throw new Error('invalid installer arguments');
271
289
  }
@@ -282,7 +300,7 @@ export async function main(args = process.argv.slice(2)) {
282
300
  if (legacy === 'codex-failed') console.log(tr('Antigravity 配置已取消。', 'Antigravity setup was cancelled.', lang));
283
301
  return 0;
284
302
  }
285
- return await runAgyHost(action, plan, installDependency, lang);
303
+ return await runAgyHost(action, plan, installDependency, lang, hook);
286
304
  } catch (error) {
287
305
  console.error(error instanceof AgyInstallError ? error.message :
288
306
  tr('没法核对安装文件或环境。请检查文件权限和发行包后再试。',
@@ -1,6 +1,6 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { constants, readFileSync } from 'node:fs';
3
- import { homedir } from 'node:os';
2
+ import { constants, cpSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
3
+ import { homedir, tmpdir } from 'node:os';
4
4
  import { isAbsolute, join } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { agyExecutable, available, pathDirectories, windows } from './installer_common.mjs';
@@ -8,6 +8,7 @@ import { tr } from './installer_locale.mjs';
8
8
  import { AGY_INSTALL } from './agy_bootstrap.mjs';
9
9
  import { fileLoginExists, withWorkspace } from '../plugins/agy-polish/scripts/codex-process.mjs';
10
10
  import { withCodexAppServer } from '../plugins/agy-polish/scripts/codex-provider.mjs';
11
+ import { setModeHook } from '../plugins/agy-polish/scripts/mode-hook-config.mjs';
11
12
 
12
13
  const PLUGIN = 'agy-polish';
13
14
  const SOURCE = new URL('../plugins/agy-polish/', import.meta.url);
@@ -97,6 +98,20 @@ export function changeAgyPlugin(action, target = PLUGIN) {
97
98
  pluginCommand([action, target]);
98
99
  }
99
100
 
101
+ export function installAgyPlugin(source, hookEnabled) {
102
+ if (!hookEnabled) return changeAgyPlugin('install', source);
103
+ // agy copies the source directory. Give it the opted-in declaration before the host can load it.
104
+ const stage = mkdtempSync(join(tmpdir(), 'agy-polish-install-'));
105
+ try {
106
+ const plugin = join(stage, PLUGIN);
107
+ cpSync(source, plugin, { recursive: true });
108
+ setModeHook(plugin, true);
109
+ changeAgyPlugin('install', plugin);
110
+ } finally {
111
+ rmSync(stage, { recursive: true, force: true });
112
+ }
113
+ }
114
+
100
115
  export async function loadAgySettings(options) {
101
116
  let settings;
102
117
  try {