@kyun.si/codex-polish 0.0.1-beta.3 → 0.0.1-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -1
- package/CONTRIBUTING.en.md +6 -6
- package/CONTRIBUTING.md +6 -6
- package/README.md +34 -64
- package/SECURITY.en.md +6 -4
- package/SECURITY.md +5 -3
- package/docs/README.zh-CN.md +56 -0
- package/docs/technical.en.md +66 -44
- package/docs/technical.md +62 -38
- package/evaluation/README.en.md +1 -1
- package/evaluation/README.md +1 -1
- package/package.json +1 -2
- package/plugins/codex-polish/.codex-plugin/plugin.json +1 -1
- package/plugins/codex-polish/hooks/editor_prompt.mjs +51 -0
- package/plugins/codex-polish/hooks/history.mjs +107 -66
- package/plugins/codex-polish/hooks/preferences.mjs +137 -114
- package/plugins/codex-polish/hooks/project_setting.mjs +40 -30
- package/plugins/codex-polish/hooks/recovery.mjs +2 -69
- package/plugins/codex-polish/hooks/rewrite_mode.mjs +19 -0
- package/plugins/codex-polish/skills/codex-polish/SKILL.md +3 -33
- package/plugins/codex-polish/skills/codex-polish/WORKFLOW.md +47 -0
- package/plugins/codex-polish/skills/codex-polish/references/acp.md +30 -17
- package/plugins/codex-polish/skills/codex-polish/references/codex-polish-editor.md +4 -2
- package/plugins/codex-polish/skills/codex-polish/scripts/acp_models.mjs +31 -6
- package/plugins/codex-polish/skills/codex-polish/scripts/acp_payload.mjs +55 -30
- package/plugins/codex-polish/skills/codex-polish/scripts/cli_io.mjs +2 -2
- package/plugins/codex-polish/skills/codex-polish/scripts/decisions.mjs +49 -58
- package/plugins/codex-polish/skills/codex-polish/scripts/editor_role.mjs +48 -0
- package/plugins/codex-polish/skills/codex-polish/scripts/format_reply.mjs +171 -0
- package/plugins/codex-polish/skills/codex-polish/scripts/previous_reply.mjs +31 -0
- package/plugins/codex-polish/skills/codex-polish/scripts/rewrite_material.mjs +28 -0
- package/plugins/codex-polish/skills/codex-polish/scripts/text_guard.mjs +65 -166
- package/plugins/codex-polish/skills/codex-polish-setup/SKILL.md +37 -11
- package/plugins/codex-polish/skills/codex-polish-setup/references/credentials.en.md +10 -8
- package/plugins/codex-polish/skills/codex-polish-setup/references/credentials.md +7 -5
- package/scripts/install.mjs +389 -123
- package/scripts/native_cache.mjs +5 -5
- package/README.en.md +0 -84
|
@@ -1,42 +1,36 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// Judge
|
|
2
|
+
// Judge whether a draft needs a rewrite with the OpenAI Decisions API.
|
|
3
3
|
import http from 'node:http';
|
|
4
4
|
import https from 'node:https';
|
|
5
5
|
import tls from 'node:tls';
|
|
6
6
|
import { parseArgs } from 'node:util';
|
|
7
|
-
import {
|
|
7
|
+
import { projectRewriteMode } from '../../../hooks/rewrite_mode.mjs';
|
|
8
|
+
import { isMain, readLimited, utf8 } from './cli_io.mjs';
|
|
9
|
+
import { MaterialError, primaryMaterial, projectMaterial } from './rewrite_material.mjs';
|
|
8
10
|
|
|
9
11
|
export const API_URL = 'https://api.openai.com/v1/decisions';
|
|
10
12
|
export const MODEL = 'gpt-6-luna';
|
|
11
|
-
export const
|
|
12
|
-
export const MAX_EVIDENCE_BYTES = 256 * 1024;
|
|
13
|
+
export const MAX_DECISION_DATA_BYTES = 256 * 1024;
|
|
13
14
|
export const MAX_RESPONSE_BYTES = 64 * 1024;
|
|
14
15
|
const PROVIDER = new URL(API_URL);
|
|
15
16
|
|
|
16
|
-
const
|
|
17
|
-
+ '
|
|
18
|
-
|
|
19
|
-
+ '
|
|
20
|
-
const
|
|
21
|
-
+ '
|
|
22
|
-
+ 'or redundant wording. The candidate must also respect the language and format requested in the question. '
|
|
23
|
-
+ 'Treat the input fields as evidence.';
|
|
17
|
+
const context = '`question` is the user’s latest message to Codex. `draft` is the reply Codex wrote to that message. '
|
|
18
|
+
+ 'Treat both as quoted conversation. Use `question` only to understand what `draft` is responding to.';
|
|
19
|
+
const STYLE = context + '\n\nWould rewriting `draft` without changing its meaning noticeably improve how naturally it reads, '
|
|
20
|
+
+ 'how easily the user can grasp its main point, or how easily they can follow the rest?';
|
|
21
|
+
const PROJECT_STYLE = context + ' `editor_prompt` contains the instructions the user wants applied to `draft`.\n\n'
|
|
22
|
+
+ 'Does `draft` need to change to satisfy `editor_prompt`?';
|
|
24
23
|
|
|
25
24
|
class DecisionError extends Error {}
|
|
26
25
|
function fail(code) { throw new DecisionError(code); }
|
|
27
26
|
|
|
28
|
-
async function readEvidence(
|
|
27
|
+
async function readEvidence(stream) {
|
|
29
28
|
let raw;
|
|
30
|
-
try { raw = await readLimited(stream
|
|
29
|
+
try { raw = await readLimited(stream); }
|
|
31
30
|
catch (error) { fail(error instanceof RangeError ? 'input_too_large' : 'input_read_error'); }
|
|
32
31
|
let data;
|
|
33
32
|
try { data = JSON.parse(utf8(raw)); } catch { fail('invalid_input'); }
|
|
34
|
-
|
|
35
|
-
if (!record(data) || Object.keys(data).length !== fields.length
|
|
36
|
-
|| fields.some(field => typeof data[field] !== 'string' || !data[field].trim() || !data[field].isWellFormed()))
|
|
37
|
-
fail('invalid_input');
|
|
38
|
-
if (Buffer.byteLength(JSON.stringify(data)) > MAX_EVIDENCE_BYTES) fail('input_too_large');
|
|
39
|
-
return data;
|
|
33
|
+
return primaryMaterial(data);
|
|
40
34
|
}
|
|
41
35
|
|
|
42
36
|
function proxyUrl(env) {
|
|
@@ -126,9 +120,10 @@ async function parseResponse(response) {
|
|
|
126
120
|
}
|
|
127
121
|
}
|
|
128
122
|
|
|
129
|
-
async function boundedProbability(data,
|
|
123
|
+
async function boundedProbability(data, instructions, key, seconds, env, request) {
|
|
124
|
+
const name = 'needs_rewrite';
|
|
130
125
|
const controller = new AbortController();
|
|
131
|
-
const deadline = performance.now() + seconds * 1000;
|
|
126
|
+
const deadline = seconds === undefined ? Infinity : performance.now() + seconds * 1000;
|
|
132
127
|
let timer;
|
|
133
128
|
const expired = new Promise((_, reject) => {
|
|
134
129
|
function arm() {
|
|
@@ -138,7 +133,7 @@ async function boundedProbability(data, name, instructions, key, seconds, env, r
|
|
|
138
133
|
controller.abort();
|
|
139
134
|
} else timer = setTimeout(arm, Math.min(2 ** 31 - 1, Math.ceil(remaining)));
|
|
140
135
|
}
|
|
141
|
-
arm();
|
|
136
|
+
if (seconds !== undefined) arm();
|
|
142
137
|
});
|
|
143
138
|
try {
|
|
144
139
|
const body = JSON.stringify({model: MODEL, input: [{role:'user', content:[{ type:'input_json', data }]}],
|
|
@@ -165,57 +160,53 @@ async function boundedProbability(data, name, instructions, key, seconds, env, r
|
|
|
165
160
|
}
|
|
166
161
|
}
|
|
167
162
|
|
|
168
|
-
// Decimal subtraction preserves the inclusive 0.95/0.05 threshold without rounding nearby scores into it.
|
|
169
|
-
function changeRisk(probability) {
|
|
170
|
-
const [digits, exponent = '0'] = String(probability).split('e');
|
|
171
|
-
const places = (digits.split('.')[1]?.length ?? 0) - Number(exponent);
|
|
172
|
-
const denominator = 10n ** BigInt(places);
|
|
173
|
-
const numerator = denominator - BigInt(digits.replace('.', ''));
|
|
174
|
-
return Number(numerator.toString() + 'e-' + places);
|
|
175
|
-
}
|
|
176
|
-
|
|
177
163
|
function options(args) {
|
|
178
164
|
let parsed;
|
|
179
165
|
try {
|
|
180
|
-
parsed = parseArgs({ args, allowPositionals:true, options: {
|
|
166
|
+
parsed = parseArgs({ args, allowPositionals:true, options: {
|
|
167
|
+
cwd:{type:'string'}, timeout:{type:'string'},
|
|
168
|
+
} });
|
|
181
169
|
} catch { fail('invalid_options'); }
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
}
|
|
189
|
-
const threshold = decimal(parsed.values.threshold, mode === 'judge' ? 0.80 : 0.05);
|
|
190
|
-
const timeout = decimal(parsed.values.timeout, 10);
|
|
191
|
-
if (!(threshold >= 0 && threshold <= 1 && timeout > 0 && timeout <= 9223372036)) fail('invalid_options');
|
|
192
|
-
return {mode, threshold, timeout};
|
|
170
|
+
if (parsed.positionals.length !== 1 || parsed.positionals[0] !== 'judge') fail('invalid_options');
|
|
171
|
+
const raw = parsed.values.timeout;
|
|
172
|
+
const seconds = raw === undefined ? undefined : Number(raw);
|
|
173
|
+
if (raw !== undefined && (!Number.isFinite(seconds) || seconds <= 0 || seconds > Number.MAX_SAFE_INTEGER / 1000))
|
|
174
|
+
fail('invalid_options');
|
|
175
|
+
return {timeout: seconds, cwd: parsed.values.cwd};
|
|
193
176
|
}
|
|
194
177
|
|
|
195
|
-
export async function decide(args, stream, env = process.env, request = send) {
|
|
178
|
+
export async function decide(args, stream, env = process.env, request = send, canSend) {
|
|
196
179
|
try {
|
|
197
|
-
const {
|
|
198
|
-
const
|
|
180
|
+
const { timeout, cwd } = options(args);
|
|
181
|
+
const primary = await readEvidence(stream);
|
|
182
|
+
const directory = cwd ?? process.cwd();
|
|
183
|
+
const rewriteMode = projectRewriteMode(directory);
|
|
184
|
+
if (rewriteMode === null) fail('rewrite_mode_invalid');
|
|
185
|
+
if (rewriteMode === 'turbo') fail('decision_route_changed');
|
|
186
|
+
if (!canSend) {
|
|
187
|
+
// Standalone judge calls also respect the project's opt-outs.
|
|
188
|
+
const { projectSettings, decisionsSettings } = await import('../../../hooks/preferences.mjs');
|
|
189
|
+
if (projectSettings(directory)[0] === 'off') fail('project_mode');
|
|
190
|
+
if (decisionsSettings(directory, rewriteMode).decisions_mode !== 'auto') fail('decision_route_changed');
|
|
191
|
+
}
|
|
199
192
|
const key = env.OPENAI_API_KEY;
|
|
200
193
|
if (!key) fail('missing_api_key');
|
|
201
194
|
if (/[^!-~]/.test(key)) fail('invalid_api_key');
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
return probability <= threshold ? {action:'accept', probability, reason:'meaning_preserved'}
|
|
210
|
-
: {action:'keep', probability, reason:'meaning_changed'};
|
|
195
|
+
const { evidence: data } = projectMaterial(primary, cwd);
|
|
196
|
+
if (Buffer.byteLength(JSON.stringify(data)) > MAX_DECISION_DATA_BYTES) fail('decision_input_too_large');
|
|
197
|
+
const instructions = Object.hasOwn(data, 'editor_prompt') ? PROJECT_STYLE : STYLE;
|
|
198
|
+
if (canSend && !canSend()) fail('decision_route_changed');
|
|
199
|
+
const probability = await boundedProbability(data, instructions, key, timeout, env, request);
|
|
200
|
+
return probability > 0.5 ? {action:'rewrite', probability, reason:'needs_rewrite'}
|
|
201
|
+
: {action:'keep', probability, reason:'already_clear'};
|
|
211
202
|
} catch (error) {
|
|
212
|
-
return {action:'keep', reason: error instanceof DecisionError ? error.message : '
|
|
203
|
+
return {action:'keep', reason: error instanceof DecisionError || error instanceof MaterialError ? error.message : 'decision_helper_unavailable'};
|
|
213
204
|
}
|
|
214
205
|
}
|
|
215
206
|
|
|
216
207
|
if (isMain(import.meta.url)) {
|
|
217
208
|
const args = process.argv.slice(2);
|
|
218
|
-
if (args.includes('--help') || args.includes('-h')) console.log('Usage: decisions.mjs judge
|
|
209
|
+
if (args.includes('--help') || args.includes('-h')) console.log('Usage: decisions.mjs judge [--cwd DIR] [--timeout SECONDS]');
|
|
219
210
|
else {
|
|
220
211
|
const output = await decide(args, process.stdin);
|
|
221
212
|
// A cancelled OS resolver may finish in the background. Bound the lifetime of this one-shot CLI too.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { closeSync, constants, fstatSync, openSync, readSync } from 'node:fs';
|
|
2
|
+
import { isAbsolute } from 'node:path';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { readBundledEditorRole, readEditorPrompt } from '../../../hooks/editor_prompt.mjs';
|
|
5
|
+
import { effectiveRewriteMode, REWRITE_TRIGGERS } from '../../../hooks/rewrite_mode.mjs';
|
|
6
|
+
import { isMain } from './cli_io.mjs';
|
|
7
|
+
|
|
8
|
+
function renderEditorRole({ source, text }) {
|
|
9
|
+
const { header } = readBundledEditorRole();
|
|
10
|
+
return header + (source === 'custom' ? text : text + '\n');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function editorRole(cwd, trigger) {
|
|
14
|
+
if (trigger !== undefined && !REWRITE_TRIGGERS.includes(trigger)) throw new Error('invalid_trigger');
|
|
15
|
+
return renderEditorRole(readEditorPrompt(cwd, effectiveRewriteMode(cwd, trigger)));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function checkStagedEditorRole(file, prompt) {
|
|
19
|
+
const expected = Buffer.from(renderEditorRole(prompt));
|
|
20
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
21
|
+
try {
|
|
22
|
+
const info = fstatSync(fd);
|
|
23
|
+
if (!info.isFile() || info.size !== expected.length) throw new Error('editor_role_changed');
|
|
24
|
+
// Bound the read even if the staged file grows after the size check.
|
|
25
|
+
const actual = Buffer.alloc(expected.length + 1);
|
|
26
|
+
let bytes = 0;
|
|
27
|
+
while (bytes < actual.length) {
|
|
28
|
+
const count = readSync(fd, actual, bytes, actual.length - bytes, bytes);
|
|
29
|
+
if (!count) break;
|
|
30
|
+
bytes += count;
|
|
31
|
+
}
|
|
32
|
+
if (!actual.subarray(0, bytes).equals(expected)) throw new Error('editor_role_changed');
|
|
33
|
+
} finally {
|
|
34
|
+
closeSync(fd);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (isMain(import.meta.url)) {
|
|
39
|
+
try {
|
|
40
|
+
const { values } = parseArgs({ options: { cwd: { type: 'string' }, trigger: { type: 'string' }, help: { type: 'boolean', short: 'h' } } });
|
|
41
|
+
if (values.help) console.log('Usage: editor_role.mjs --cwd PROJECT [--trigger auto|explicit|turbo]');
|
|
42
|
+
else if (!values.cwd || !isAbsolute(values.cwd)) process.exitCode = 2;
|
|
43
|
+
else process.stdout.write(editorRole(values.cwd, values.trigger));
|
|
44
|
+
} catch (error) {
|
|
45
|
+
process.stderr.write(error.message === 'rewrite_mode_invalid' ? 'rewrite_mode_invalid\n' : 'editor_prompt_invalid\n');
|
|
46
|
+
process.exitCode = 1;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { isMain, readLimited, utf8 } from './cli_io.mjs';
|
|
2
|
+
|
|
3
|
+
const FENCE = /^ {0,3}(`{3,}|~{3,})/;
|
|
4
|
+
const VISUAL_START = '\uE200visualize\uE202';
|
|
5
|
+
const VISUAL_END = '\uE201';
|
|
6
|
+
const VISUAL_LINE = /^( {0,3})(\uE200?visualize\uE202?(\{[^\r\n]*\})\uE201?)[ \t]*$/u;
|
|
7
|
+
const VISUAL_TOKEN = /\uE200visualize\uE202([^\uE201\r\n]*)\uE201/gu;
|
|
8
|
+
const DISPLAY_LABELS = {
|
|
9
|
+
zh: { polished: 'Gemini 润色版', original: '查看 GPT 原稿', unchanged: 'Gemini 返回了原稿',
|
|
10
|
+
quoted: '查看原文', unchangedQuote: 'Gemini 返回了原文' },
|
|
11
|
+
en: { polished: 'Polished by Gemini', original: 'View original GPT draft', unchanged: 'Gemini returned the original draft',
|
|
12
|
+
quoted: 'View original text', unchangedQuote: 'Gemini returned the original text' },
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
function originalDisclosure(label, draft) {
|
|
16
|
+
// The desktop client converts HTML details to a Markdown container. If the
|
|
17
|
+
// draft documents either delimiter, quote its source inside that container.
|
|
18
|
+
if (/<\/?details\b|<!--|^[\t ]*:::/im.test(draft)) {
|
|
19
|
+
let fenceLength = 3;
|
|
20
|
+
for (const [ticks] of draft.matchAll(/`+/g)) fenceLength = Math.max(fenceLength, ticks.length + 1);
|
|
21
|
+
const fence = '`'.repeat(fenceLength);
|
|
22
|
+
const quoted = draft.replace(VISUAL_TOKEN, (_, data) => '\\uE200visualize\\uE202' + data + '\\uE201')
|
|
23
|
+
.replace(/\r\n|[\r\n]/g, '$&> ');
|
|
24
|
+
return `:::github-details{summary=${JSON.stringify(label)}}\n\n> ${fence}text\n> ${quoted}\n> ${fence}\n\n:::`;
|
|
25
|
+
}
|
|
26
|
+
// Desktop expands live references before it renders the Markdown disclosure.
|
|
27
|
+
// Entities display the original characters as text without instantiating a second chart.
|
|
28
|
+
let original = draft;
|
|
29
|
+
if (draft.includes(VISUAL_START)) {
|
|
30
|
+
const edits = visualizationLines(draft).filter(ref => ref.live).map(ref => ({
|
|
31
|
+
...ref, replacement: literalVisual(ref.data)
|
|
32
|
+
}));
|
|
33
|
+
original = replaceReferences(draft, edits);
|
|
34
|
+
}
|
|
35
|
+
return `<details><summary>${label}</summary>\n\n${original}\n\n</details>`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Recover the displayed original from our own comparison format. Encoded
|
|
39
|
+
// chart references may also be literal examples, so never unescape those into
|
|
40
|
+
// a live widget. A malformed comparison has no trustworthy target.
|
|
41
|
+
export function originalReplyText(reply) {
|
|
42
|
+
const skipped = /^\*\*(?:未润色|Polishing skipped)\*\* · [^\r\n]+\n\n/.exec(reply);
|
|
43
|
+
if (skipped) return reply.slice(skipped[0].length);
|
|
44
|
+
for (const labels of Object.values(DISPLAY_LABELS)) {
|
|
45
|
+
for (const heading of [labels.unchanged, labels.unchangedQuote]) {
|
|
46
|
+
const unchanged = `**${heading}**\n\n`;
|
|
47
|
+
if (reply.startsWith(unchanged)) return reply.slice(unchanged.length);
|
|
48
|
+
}
|
|
49
|
+
if (!reply.startsWith(`**${labels.polished}**\n\n`)) continue;
|
|
50
|
+
|
|
51
|
+
const html = reply.endsWith('\n\n</details>');
|
|
52
|
+
const index = reply.lastIndexOf(html ? '\n\n<details><summary>' : '\n\n:::github-details{summary=');
|
|
53
|
+
if (index === -1) return null;
|
|
54
|
+
const disclosure = reply.slice(index + 2);
|
|
55
|
+
const prefix = label => html ? `<details><summary>${label}</summary>\n\n` : `:::github-details{summary=${JSON.stringify(label)}}\n\n`;
|
|
56
|
+
const label = [labels.original, labels.quoted].find(label => disclosure.startsWith(prefix(label)));
|
|
57
|
+
if (!label) return null;
|
|
58
|
+
const body = disclosure.slice(prefix(label).length);
|
|
59
|
+
let draft;
|
|
60
|
+
if (html) {
|
|
61
|
+
draft = body.slice(0, -'\n\n</details>'.length);
|
|
62
|
+
if (draft.includes('visualize')) return null;
|
|
63
|
+
} else {
|
|
64
|
+
const match = /^> (`{3,})text\n> /.exec(body);
|
|
65
|
+
if (!match) return null;
|
|
66
|
+
const suffix = `\n> ${match[1]}\n\n:::`;
|
|
67
|
+
if (!body.endsWith(suffix)) return null;
|
|
68
|
+
draft = body.slice(match[0].length, -suffix.length).replace(/(\r\n|[\r\n])> /g, '$1');
|
|
69
|
+
if (draft.includes('\\uE200visualize\\uE202')) return null;
|
|
70
|
+
}
|
|
71
|
+
return originalDisclosure(label, draft) === disclosure ? draft : null;
|
|
72
|
+
}
|
|
73
|
+
return reply;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// A Codex visual is a standalone reference. A provider can return its exact
|
|
77
|
+
// JSON while dropping the private-use characters that make it render in chat.
|
|
78
|
+
function visualizationLines(text) {
|
|
79
|
+
const refs = [];
|
|
80
|
+
let fence;
|
|
81
|
+
for (const line of text.matchAll(/^[^\r\n]+/gm)) {
|
|
82
|
+
const delimiter = FENCE.exec(line[0])?.[1];
|
|
83
|
+
if (fence) {
|
|
84
|
+
if (delimiter?.[0] === fence[0] && delimiter.length >= fence.length && line[0].trim() === delimiter) fence = null;
|
|
85
|
+
} else if (delimiter) {
|
|
86
|
+
fence = delimiter;
|
|
87
|
+
} else {
|
|
88
|
+
const match = VISUAL_LINE.exec(line[0]);
|
|
89
|
+
if (!match) continue;
|
|
90
|
+
const [, indent, token, data] = match;
|
|
91
|
+
let attrs;
|
|
92
|
+
try { attrs = JSON.parse(data); } catch { continue; }
|
|
93
|
+
if (typeof attrs?.path !== 'string' || !attrs.path.startsWith('/')) continue;
|
|
94
|
+
refs.push({ data, token, at: line.index + indent.length, live: token === VISUAL_START + data + VISUAL_END });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return refs;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Restore unambiguous widget delimiters for the original chart. Other returned
|
|
101
|
+
// text is still displayed, even when no original chart can be matched.
|
|
102
|
+
function formatVisualizations(draft, candidate) {
|
|
103
|
+
if (!draft.includes(VISUAL_START) && !candidate.includes(VISUAL_START)) return candidate;
|
|
104
|
+
const groups = new Map();
|
|
105
|
+
for (const ref of visualizationLines(draft)) {
|
|
106
|
+
const group = groups.get(ref.data) ?? { live: 0, literal: false, slots: [] };
|
|
107
|
+
if (ref.live) group.live++; else group.literal = true;
|
|
108
|
+
groups.set(ref.data, group);
|
|
109
|
+
}
|
|
110
|
+
const edits = [];
|
|
111
|
+
for (const ref of visualizationLines(candidate)) {
|
|
112
|
+
const group = groups.get(ref.data);
|
|
113
|
+
if (!ref.live) {
|
|
114
|
+
if (group) group.slots.push(ref);
|
|
115
|
+
} else if (group?.live) {
|
|
116
|
+
group.live--;
|
|
117
|
+
} else {
|
|
118
|
+
// A model can write text for a new reference, but only the authoring
|
|
119
|
+
// agent's original references have a corresponding trusted local widget.
|
|
120
|
+
edits.push({ ...ref, replacement: literalVisual(ref.data) });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
for (const [data, group] of groups) {
|
|
124
|
+
if (group.literal || group.slots.length !== group.live) continue;
|
|
125
|
+
for (const ref of group.slots) edits.push({ ...ref, replacement: VISUAL_START + data + VISUAL_END });
|
|
126
|
+
}
|
|
127
|
+
return replaceReferences(candidate, edits.sort((a, b) => a.at - b.at));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function literalVisual(data) {
|
|
131
|
+
return 'visualize' + data + '';
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function replaceReferences(text, edits) {
|
|
135
|
+
if (!edits.length) return text;
|
|
136
|
+
let result = '', start = 0;
|
|
137
|
+
for (const edit of edits) {
|
|
138
|
+
result += text.slice(start, edit.at) + edit.replacement;
|
|
139
|
+
start = edit.at + edit.token.length;
|
|
140
|
+
}
|
|
141
|
+
return result + text.slice(start);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function comparableProse(text) {
|
|
145
|
+
return text.replace(/\r\n?/g, '\n').trim();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function formatReply({ draft, candidate, display_language, source_label }) {
|
|
149
|
+
if (source_label !== undefined && source_label !== 'quoted') throw new Error('invalid_source_label');
|
|
150
|
+
const text = formatVisualizations(draft, candidate);
|
|
151
|
+
if (display_language === undefined) return { text };
|
|
152
|
+
const labels = DISPLAY_LABELS[display_language];
|
|
153
|
+
const same = comparableProse(text) === comparableProse(draft);
|
|
154
|
+
const quoted = source_label === 'quoted';
|
|
155
|
+
const display_text = same
|
|
156
|
+
? `**${quoted ? labels.unchangedQuote : labels.unchanged}**\n\n${text}`
|
|
157
|
+
: `**${labels.polished}**\n\n${text}\n\n${originalDisclosure(quoted ? labels.quoted : labels.original, draft)}`;
|
|
158
|
+
return { text, display_text };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (isMain(import.meta.url)) {
|
|
162
|
+
try {
|
|
163
|
+
if (process.argv.length !== 2) throw new Error('unexpected arguments');
|
|
164
|
+
const payload = JSON.parse(utf8(await readLimited(process.stdin)));
|
|
165
|
+
if (typeof payload?.draft !== 'string' || typeof payload?.candidate !== 'string' ||
|
|
166
|
+
(payload.display_language !== undefined && !Object.hasOwn(DISPLAY_LABELS, payload.display_language))) {
|
|
167
|
+
throw new Error('invalid input');
|
|
168
|
+
}
|
|
169
|
+
console.log(JSON.stringify(formatReply(payload)));
|
|
170
|
+
} catch { process.exitCode = 2; }
|
|
171
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { isAbsolute } from 'node:path';
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { readPreviousReply } from '../../../hooks/history.mjs';
|
|
4
|
+
import { historySource, projectHistoryTurns } from '../../../hooks/preferences.mjs';
|
|
5
|
+
import { isMain } from './cli_io.mjs';
|
|
6
|
+
|
|
7
|
+
export function previousReply(cwd, { noHistory = false, turnsBack = 1 } = {}) {
|
|
8
|
+
const source = historySource(cwd);
|
|
9
|
+
if (!source) return null;
|
|
10
|
+
return readPreviousReply(source.transcript_path, source.session_id, source.turn_id,
|
|
11
|
+
noHistory ? 0 : projectHistoryTurns(cwd), turnsBack);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
if (isMain(import.meta.url)) {
|
|
15
|
+
try {
|
|
16
|
+
const { values } = parseArgs({ options: {
|
|
17
|
+
cwd: { type: 'string' }, 'turns-back': { type: 'string', default: '1' }, help: { type: 'boolean', short: 'h' },
|
|
18
|
+
} });
|
|
19
|
+
if (values.help) console.log('Usage: previous_reply.mjs --cwd PROJECT [--turns-back N]');
|
|
20
|
+
else {
|
|
21
|
+
if (!values.cwd || !isAbsolute(values.cwd) || !/^[1-9]\d*$/.test(values['turns-back']) ||
|
|
22
|
+
!Number.isSafeInteger(Number(values['turns-back']))) throw new Error('invalid_arguments');
|
|
23
|
+
const target = previousReply(values.cwd, { noHistory: true, turnsBack: Number(values['turns-back']) });
|
|
24
|
+
if (!target) throw new Error('previous_reply_unavailable');
|
|
25
|
+
console.log(JSON.stringify({ question: target.question, draft: target.draft }));
|
|
26
|
+
}
|
|
27
|
+
} catch (error) {
|
|
28
|
+
console.error(error.message === 'previous_reply_unavailable' ? error.message : 'invalid_arguments');
|
|
29
|
+
process.exitCode = 1;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { readEditorPrompt } from '../../../hooks/editor_prompt.mjs';
|
|
2
|
+
import { record } from './cli_io.mjs';
|
|
3
|
+
import { CREDENTIAL, DISPLAY_CONTROL } from './text_guard.mjs';
|
|
4
|
+
|
|
5
|
+
export class MaterialError extends Error {}
|
|
6
|
+
|
|
7
|
+
export function validateSourceText(value, maxBytes) {
|
|
8
|
+
if (typeof value !== 'string' || !value.trim() || !value.isWellFormed()) throw new MaterialError('invalid_input');
|
|
9
|
+
if (maxBytes !== undefined && Buffer.byteLength(value) > maxBytes) throw new MaterialError('input_too_large');
|
|
10
|
+
if (CREDENTIAL.test(value)) throw new MaterialError('possible_credential');
|
|
11
|
+
if (DISPLAY_CONTROL.test(value)) throw new MaterialError('display_control');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function primaryMaterial(data) {
|
|
15
|
+
if (!record(data) || Object.keys(data).length !== 2 || !Object.hasOwn(data, 'question') || !Object.hasOwn(data, 'draft'))
|
|
16
|
+
throw new MaterialError('invalid_input');
|
|
17
|
+
validateSourceText(data.question);
|
|
18
|
+
validateSourceText(data.draft);
|
|
19
|
+
return { question: data.question, draft: data.draft };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function projectMaterial(primary, cwd, mode) {
|
|
23
|
+
let prompt;
|
|
24
|
+
try { prompt = readEditorPrompt(cwd ?? process.cwd(), mode); }
|
|
25
|
+
catch { throw new MaterialError('editor_prompt_invalid'); }
|
|
26
|
+
const evidence = prompt.source === 'custom' ? { ...primary, editor_prompt: prompt.text } : primary;
|
|
27
|
+
return { evidence, prompt };
|
|
28
|
+
}
|