@kyun.si/agy-polish 0.0.0-stage → 0.0.4-beta.3

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # AGY Polish
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Use Codex to polish Antigravity replies. The rewrite appears in the same conversation.
4
+
5
+ ## Setup
6
+
7
+ Install Node.js 22.16 or later, the Antigravity CLI with native plugin support and the Codex CLI. AGY Polish uses the model provider configured in Codex. If you use an OpenAI account, run `codex login` to sign in. [Antigravity CLI guide](https://antigravity.google/docs/cli) · [Codex CLI guide](https://developers.openai.com/codex/cli/)
8
+
9
+ ```sh
10
+ npx @kyun.si/agy-polish@beta setup
11
+ ```
12
+
13
+ In Windows PowerShell, use `npx.cmd` in place of `npx`.
14
+
15
+ Choose when Codex should edit your replies, then start a new `agy` chat. Try `/polish Rewrite the previous reply in two sentences.` If Antigravity asks for permission, allow the `polish_reply` tool. Add `--advanced` to `setup` to choose a mode, model and reasoning effort, or say **“Set up reply polishing”** to change them in chat.
16
+
17
+ 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.
18
+
19
+ ## Maintenance
20
+
21
+ ```sh
22
+ npx @kyun.si/agy-polish@beta doctor
23
+ npx @kyun.si/agy-polish@beta update
24
+ npx @kyun.si/agy-polish@beta uninstall
25
+ ```
26
+
27
+ AGY Polish keeps your mode and model settings when you update or uninstall the plugin.
28
+
29
+ [Agent Polish source and documentation](https://github.com/mreasonyang/agent-polish) · [Apache-2.0 License](LICENSE)
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@kyun.si/agy-polish",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.4-beta.3",
4
+ "description": "Polish Antigravity replies with Codex · 用 Codex 润色 Antigravity 回复",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22.16.0"
9
+ },
10
+ "os": ["darwin", "linux", "win32"],
11
+ "bin": {
12
+ "agy-polish": "scripts/agy-cli.mjs"
13
+ },
14
+ "files": [
15
+ "plugins/agy-polish",
16
+ "scripts/agy-cli.mjs",
17
+ "scripts/agy_bootstrap.mjs",
18
+ "scripts/agy_install.mjs",
19
+ "scripts/installer_common.mjs",
20
+ "scripts/installer_locale.mjs",
21
+ "scripts/installer_lock.mjs",
22
+ "scripts/installer_terminal.mjs"
23
+ ],
24
+ "scripts": {
25
+ "prepack": "node ../../scripts/pack-workspace.mjs"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/mreasonyang/agent-polish.git",
30
+ "directory": "packages/agy-polish"
31
+ },
32
+ "homepage": "https://github.com/mreasonyang/agent-polish#readme",
33
+ "bugs": {
34
+ "url": "https://github.com/mreasonyang/agent-polish/issues"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public",
38
+ "registry": "https://registry.npmjs.org/",
39
+ "tag": "beta"
40
+ }
41
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "agy-polish-mode": {
3
+ "PreInvocation": [
4
+ { "type": "command", "command": "node ./scripts/mode-hook.mjs", "timeout": 3 }
5
+ ]
6
+ }
7
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "mcpServers": {
3
+ "agy-polish": {
4
+ "command": "node",
5
+ "args": ["${PLUGIN_ROOT}/scripts/mcp-server.mjs"]
6
+ }
7
+ }
8
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "agy-polish",
3
+ "displayName": "AGY Polish · 回复润色",
4
+ "version": "0.0.4-beta.3",
5
+ "description": "Polish Antigravity replies with your local Codex CLI. 用本机 Codex CLI 润色 Antigravity 的回复。",
6
+ "author": { "name": "mreasonyang" },
7
+ "repository": "https://github.com/mreasonyang/agent-polish",
8
+ "suggestedPrompts": [
9
+ "配置回复润色",
10
+ "Configure reply polishing",
11
+ "/polish 用一句话解释 DNS。"
12
+ ]
13
+ }
@@ -0,0 +1,9 @@
1
+ # Reply polishing
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.
4
+
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
+ - Use `trigger: "explicit"` only when the user asks to polish or invokes `/polish`. 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
+ - 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
+ - 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.
@@ -0,0 +1,184 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, symlink, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { configArguments, fileLoginExists, startCodex } from './codex-process.mjs';
5
+ import { readProviderBearer } from './codex-provider-auth.mjs';
6
+ import {
7
+ isolation, loadCodexProvider, noDiagnosticLog, privateLogging, readNativeAuth, withCodexAppServer
8
+ } from './codex-provider.mjs';
9
+
10
+ const editorOverrides = [
11
+ 'approval_policy="never"',
12
+ 'developer_instructions=""',
13
+ 'notify=[]',
14
+ 'web_search="disabled"',
15
+ ...privateLogging,
16
+ 'include_permissions_instructions=false',
17
+ 'include_apps_instructions=false',
18
+ 'include_collaboration_mode_instructions=false',
19
+ 'include_environment_context=false',
20
+ 'skills.include_instructions=false',
21
+ 'tools.experimental_request_user_input.enabled=false',
22
+ 'features.code_mode=false',
23
+ 'features.browser_use=false',
24
+ 'features.computer_use=false',
25
+ 'features.image_generation=false',
26
+ 'features.shell_tool=false',
27
+ 'features.shell_snapshot=false',
28
+ 'features.unified_exec=false',
29
+ 'features.default_mode_request_user_input=false',
30
+ 'features.view_image=false',
31
+ 'features.goals=false',
32
+ 'features.multi_agent=false',
33
+ 'features.multi_agent_v2=false',
34
+ 'features.memories=false',
35
+ 'features.skip_host_skill_discovery=true',
36
+ 'features.skill_mcp_dependency_install=false'
37
+ ];
38
+
39
+ function tomlValue(value) {
40
+ if (typeof value === 'string') return JSON.stringify(value).replaceAll('\x7f', '\\u007f');
41
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
42
+ if (Array.isArray(value)) return '[' + value.map(tomlValue).join(', ') + ']';
43
+ return '{ ' + tomlEntries(value).join(', ') + ' }';
44
+ }
45
+
46
+ function tomlEntries(settings) {
47
+ return Object.entries(settings).filter(([, value]) => value != null)
48
+ .map(([key, value]) => tomlValue(key) + ' = ' + tomlValue(value));
49
+ }
50
+
51
+ async function linkFileAuth(sourceHome, editorHome) {
52
+ if (!fileLoginExists(sourceHome)) return false;
53
+ const authFile = join(sourceHome, 'auth.json');
54
+ // Codex resolves the auth.json target before atomic refresh. Share its lock too.
55
+ await symlink(join(sourceHome, 'auth.lock'), join(editorHome, 'auth.lock'), 'file');
56
+ await symlink(authFile, join(editorHome, 'auth.json'), 'file');
57
+ return true;
58
+ }
59
+
60
+ function completedReply(text) {
61
+ const { reply, complete } = JSON.parse(text);
62
+ if (complete === true && typeof reply === 'string' && reply.trim()) return reply;
63
+ }
64
+
65
+ async function editWithExec(cwd, directory, options, outputSchema, dispatch) {
66
+ const output = join(directory, 'reply.json');
67
+ const schema = join(directory, 'schema.json');
68
+ await writeFile(schema, JSON.stringify(outputSchema), { mode: 0o600 });
69
+ const selection = dispatch();
70
+ if (!selection) return;
71
+ const { model, effort, prompt } = selection;
72
+ const args = [
73
+ 'exec', '--json', '--ephemeral', '--skip-git-repo-check', '--sandbox', 'read-only',
74
+ '--ignore-rules', '--output-schema', schema, '-o', output,
75
+ ...configArguments([...isolation, ...editorOverrides, noDiagnosticLog(cwd)])
76
+ ];
77
+ if (model !== null) args.push('--model', model);
78
+ if (effort !== null) args.push('-c', 'model_reasoning_effort=' + JSON.stringify(effort));
79
+ const { child, closed } = startCodex([...args, '-'], cwd, options);
80
+ child.stdin.end(prompt);
81
+ if (await closed && !options.signal?.aborted) {
82
+ return completedReply(new TextDecoder('utf-8', { fatal: true }).decode(await readFile(output)));
83
+ }
84
+ }
85
+
86
+ async function editWithChatgptAuth(cwd, options, nativeOptions, provider, auth, outputSchema, dispatch) {
87
+ if (!dispatch()) return;
88
+ return withCodexAppServer(cwd, {
89
+ ...options, overrides: [...editorOverrides, noDiagnosticLog(cwd)],
90
+ experimental: true, explicitGatewayOauth: true, oneShot: true
91
+ },
92
+ async (request, { receive, send }) => {
93
+ await request('account/login/start', { type: 'chatgptAuthTokens', ...auth, chatgptPlanType: null });
94
+ const { thread, modelProvider } = await request('thread/start', {
95
+ ephemeral: true, sandbox: 'read-only', approvalPolicy: 'never', environments: []
96
+ });
97
+ if (modelProvider !== provider) throw new Error('Isolated Codex provider changed');
98
+ const selection = dispatch();
99
+ if (!selection) return;
100
+ const { model, effort, prompt } = selection;
101
+ let reply;
102
+ let replyTurnId;
103
+ let completed;
104
+ let refreshed = false;
105
+ async function handle(message) {
106
+ const { method, params, id } = message;
107
+ if (id != null) {
108
+ // The native profile owns refresh and keeps the long-lived grant in its store.
109
+ if (method !== 'account/chatgptAuthTokens/refresh' || refreshed ||
110
+ params.previousAccountId !== auth.chatgptAccountId) throw new Error('Unexpected Codex request');
111
+ refreshed = true;
112
+ const fresh = await readNativeAuth(cwd, nativeOptions, auth.chatgptAccountId);
113
+ send({ id, result: { ...fresh, chatgptPlanType: null } });
114
+ }
115
+ if (method === 'item/completed' && params.threadId === thread.id &&
116
+ params.item.type === 'agentMessage' && !['commentary', 'partial_answer'].includes(params.item.phase)) {
117
+ reply = params.item.text;
118
+ replyTurnId = params.turnId;
119
+ }
120
+ if (method === 'turn/completed' && params.threadId === thread.id) completed = params.turn;
121
+ }
122
+ const { turn } = await request('turn/start', {
123
+ threadId: thread.id, input: [{ type: 'text', text: prompt, text_elements: [] }],
124
+ model, effort, outputSchema
125
+ }, handle);
126
+ while (!completed) await handle(await receive());
127
+ if (completed.id === turn.id && completed.status === 'completed' && replyTurnId === turn.id) {
128
+ return completedReply(reply);
129
+ }
130
+ });
131
+ }
132
+
133
+ export async function editWithCodex({ cwd, directory }, { signal, timeout }, outputSchema, dispatch) {
134
+ const nativeOptions = { signal, timeout: Math.min(timeout, 15_000) };
135
+ // Codex 0.170 can run without its diagnostics DB when the log directory is unavailable.
136
+ await writeFile(join(directory, 'no-logs'), '', { flag: 'wx', mode: 0o600 });
137
+ const { settings, codexHome, store, requiresOpenaiAuth, auth: nativeAuth } = await loadCodexProvider(cwd, nativeOptions);
138
+ const provider = settings.model_provider ?? 'openai';
139
+ const editorHome = join(directory, 'codex');
140
+ const userHome = join(directory, 'home');
141
+ await Promise.all([mkdir(editorHome, { mode: 0o700 }), mkdir(userHome, { mode: 0o700 })]);
142
+ const env = {
143
+ ...process.env,
144
+ CODEX_HOME: editorHome, CODEX_SQLITE_HOME: editorHome,
145
+ HOME: userHome, USERPROFILE: userHome, APPDATA: userHome, LOCALAPPDATA: userHome,
146
+ XDG_CONFIG_HOME: userHome, XDG_CACHE_HOME: userHome, XDG_DATA_HOME: userHome, XDG_STATE_HOME: userHome
147
+ };
148
+ let auth = nativeAuth;
149
+ const definition = settings.model_providers?.[provider];
150
+ // Built-in providers have their own rules for applying auth overrides.
151
+ const builtIn = ['openai', 'amazon-bedrock', 'amazon-bedrock-runtime', 'gcp', 'ollama', 'lmstudio'].includes(provider);
152
+ const commandAuth = !builtIn && definition?.auth;
153
+ if (commandAuth) {
154
+ const envKey = 'CODEX_POLISH_PROVIDER_BEARER_' + randomUUID().replaceAll('-', '');
155
+ env[envKey] = await readProviderBearer(commandAuth, { cwd, signal, timeout });
156
+ settings.model_providers[provider] = { ...definition, auth: undefined, env_key: envKey };
157
+ } else if (store === 'file') {
158
+ try {
159
+ const linked = await linkFileAuth(codexHome, editorHome);
160
+ if (!linked && provider === 'openai' && settings.forced_login_method !== 'chatgpt' &&
161
+ !env.CODEX_API_KEY?.trim() && !env.CODEX_ACCESS_TOKEN?.trim() && env.OPENAI_API_KEY?.trim()) {
162
+ // Exec uses CODEX_API_KEY. Accept OPENAI_API_KEY when there is no selected login.
163
+ env.CODEX_API_KEY = env.OPENAI_API_KEY;
164
+ }
165
+ } catch (error) {
166
+ if (process.platform !== 'win32' || !['EPERM', 'EACCES', 'ENOSYS'].includes(error.code)) throw error;
167
+ // Windows can restrict symlink creation. Use the same in-memory bridge as keyring auth.
168
+ if (requiresOpenaiAuth) auth = await readNativeAuth(cwd, nativeOptions);
169
+ }
170
+ } else if (!['keyring', 'auto', 'ephemeral'].includes(store)) {
171
+ throw new Error('Unsupported Codex credentials store');
172
+ }
173
+ if (auth?.apiKey) env.CODEX_API_KEY = auth.apiKey;
174
+ const config = {
175
+ ...settings,
176
+ cli_auth_credentials_store: store === 'file' && !auth && !commandAuth ? 'file' : 'ephemeral',
177
+ instructions: 'You are a copyeditor. Return the requested structured edit of the supplied text.'
178
+ };
179
+ await writeFile(join(editorHome, 'config.toml'), tomlEntries(config).join('\n') + '\n',
180
+ { flag: 'wx', mode: 0o600 });
181
+ const options = { env, signal, timeout };
182
+ if (auth?.accessToken) return editWithChatgptAuth(cwd, options, nativeOptions, provider, auth, outputSchema, dispatch);
183
+ return editWithExec(cwd, directory, options, outputSchema, dispatch);
184
+ }
@@ -0,0 +1,143 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { accessSync, constants, realpathSync, statSync } from 'node:fs';
3
+ import { mkdtemp, mkdir, rm } from 'node:fs/promises';
4
+ import { createRequire } from 'node:module';
5
+ import { homedir, tmpdir } from 'node:os';
6
+ import { delimiter, dirname, isAbsolute, join } from 'node:path';
7
+
8
+ const windows = process.platform === 'win32';
9
+
10
+ export function fileLoginExists(codexHome) {
11
+ if (typeof codexHome !== 'string' || !isAbsolute(codexHome)) throw new Error('Native Codex home unavailable');
12
+ const file = statSync(join(codexHome, 'auth.json'), { throwIfNoEntry: false });
13
+ if (file && !file.isFile()) throw new Error('Invalid Codex credential file');
14
+ return Boolean(file);
15
+ }
16
+
17
+ function executable(file) {
18
+ try {
19
+ accessSync(file, constants.X_OK);
20
+ return statSync(file).isFile();
21
+ } catch {
22
+ return false;
23
+ }
24
+ }
25
+
26
+ function windowsNpmBinary(directory) {
27
+ if (!executable(join(directory, 'codex.cmd'))) return;
28
+ const entry = join(directory, 'node_modules', '@openai', 'codex', 'bin', 'codex.js');
29
+ if (!executable(entry)) return;
30
+ const shim = realpathSync(entry);
31
+ const require = createRequire(shim);
32
+ const target = process.arch === 'arm64' ? 'aarch64-pc-windows-msvc' : 'x86_64-pc-windows-msvc';
33
+ const roots = [dirname(dirname(shim))];
34
+ try {
35
+ roots.unshift(dirname(require.resolve(`@openai/codex-win32-${process.arch}/package.json`)));
36
+ } catch {
37
+ // Older npm packages included the native binary in the main package.
38
+ }
39
+ for (const root of roots) {
40
+ for (const folder of ['bin', 'codex']) {
41
+ const file = join(root, 'vendor', target, folder, 'codex.exe');
42
+ if (executable(file)) return file;
43
+ }
44
+ }
45
+ }
46
+
47
+ function findCodex() {
48
+ const paths = (process.env.PATH ?? process.env.Path ?? '').split(delimiter);
49
+ paths.push(process.env.CODEX_INSTALL_DIR, join(homedir(), '.local', 'bin'));
50
+ if (windows) {
51
+ const local = process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local');
52
+ paths.push(join(local, 'Programs', 'OpenAI', 'Codex', 'bin'));
53
+ }
54
+ for (const path of paths) {
55
+ const directory = windows ? path?.replace(/^"(.*)"$/, '$1') : path;
56
+ if (!directory || !isAbsolute(directory)) continue;
57
+ const file = join(directory, windows ? 'codex.exe' : 'codex');
58
+ if (executable(file)) return file;
59
+ if (windows) {
60
+ const native = windowsNpmBinary(directory);
61
+ if (native) return native;
62
+ }
63
+ }
64
+ throw new Error('Codex CLI unavailable');
65
+ }
66
+
67
+ export async function withWorkspace(operation) {
68
+ const directory = await mkdtemp(join(tmpdir(), 'agy-polish-'));
69
+ try {
70
+ const cwd = join(directory, 'workspace');
71
+ await mkdir(cwd);
72
+ return await operation({ directory, cwd });
73
+ } finally {
74
+ await rm(directory, { recursive: true, force: true, maxRetries: 3 });
75
+ }
76
+ }
77
+
78
+ export function configArguments(settings) {
79
+ return settings.flatMap((setting) => ['-c', setting]);
80
+ }
81
+
82
+ export function startCodex(args, cwd, { signal, timeout, env = process.env, captureOutput = false }) {
83
+ signal?.throwIfAborted();
84
+ const child = spawn(findCodex(), args, {
85
+ cwd,
86
+ env: { ...env, RUST_LOG: 'off', RUST_BACKTRACE: '0' },
87
+ detached: !windows,
88
+ windowsHide: true,
89
+ stdio: ['pipe', captureOutput ? 'pipe' : 'ignore', 'ignore']
90
+ });
91
+ let aborted = false;
92
+ let failed = false;
93
+ let stopping = false;
94
+ let finished = false;
95
+ let escalation;
96
+ const sentSignals = new Set();
97
+
98
+ function killGroup(signalName) {
99
+ if (!child.pid) return;
100
+ const running = child.exitCode === null && child.signalCode === null;
101
+ let sent;
102
+ try {
103
+ sent = windows ? child.kill(signalName) : process.kill(-child.pid, signalName);
104
+ } catch (error) {
105
+ if (error.code !== 'ESRCH') sent = child.kill(signalName);
106
+ }
107
+ if (sent && running) sentSignals.add(signalName);
108
+ }
109
+
110
+ function stop() {
111
+ if (stopping || finished) return;
112
+ stopping = true;
113
+ clearTimeout(deadline);
114
+ child.stdin.destroy();
115
+ if (windows) killGroup('SIGKILL');
116
+ else {
117
+ killGroup('SIGTERM');
118
+ escalation = setTimeout(() => killGroup('SIGKILL'), 350);
119
+ }
120
+ }
121
+
122
+ function terminate() {
123
+ aborted = true;
124
+ stop();
125
+ }
126
+
127
+ const deadline = setTimeout(terminate, timeout);
128
+ signal?.addEventListener('abort', terminate, { once: true });
129
+ child.on('error', () => { failed = true; });
130
+ child.stdin.on('error', () => { if (!stopping) failed = true; });
131
+ const closed = new Promise((resolve) => {
132
+ child.once('close', (code, exitSignal) => {
133
+ finished = true;
134
+ clearTimeout(deadline);
135
+ clearTimeout(escalation);
136
+ signal?.removeEventListener('abort', terminate);
137
+ // A launcher may have exited from SIGTERM while a descendant still has work.
138
+ if (stopping && !windows) killGroup('SIGKILL');
139
+ resolve(!aborted && !failed && (code === 0 || sentSignals.has(exitSignal)));
140
+ });
141
+ });
142
+ return { child, closed, stop };
143
+ }