@litfamily/litcodex 1.0.11 → 1.0.13
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-Ko-KR.md +16 -16
- package/README.md +17 -17
- package/dist/cli.js +11 -4
- package/dist/config-migration/gpt56-policy.js +3 -0
- package/dist/install/auto-handoff-doctor.d.ts +4 -0
- package/dist/install/auto-handoff-doctor.js +135 -0
- package/dist/install/doctor-render.js +2 -0
- package/dist/install/doctor.js +10 -0
- package/dist/install/types.d.ts +10 -0
- package/marketplace/plugins/litcodex/.codex-plugin/plugin.json +1 -1
- package/marketplace/plugins/litcodex/components/auto-update/package.json +1 -1
- package/marketplace/plugins/litcodex/components/comment-checker/package.json +1 -1
- package/marketplace/plugins/litcodex/components/git-bash/package.json +1 -1
- package/marketplace/plugins/litcodex/components/lit-loop/dist/auto-handoff-settings.d.ts +87 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/auto-handoff-settings.js +414 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/auto-handoff.d.ts +72 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/auto-handoff.js +317 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/cli.js +5 -1
- package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.d.ts +11 -2
- package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.js +137 -10
- package/marketplace/plugins/litcodex/components/lit-loop/package.json +1 -1
- package/marketplace/plugins/litcodex/components/lsp/package.json +1 -1
- package/marketplace/plugins/litcodex/components/rules/dist/model-metadata.d.ts +1 -1
- package/marketplace/plugins/litcodex/components/rules/dist/model-metadata.js +1 -0
- package/marketplace/plugins/litcodex/components/rules/package.json +1 -1
- package/marketplace/plugins/litcodex/components/start-work-continuation/package.json +1 -1
- package/marketplace/plugins/litcodex/components/telemetry/package.json +1 -1
- package/marketplace/plugins/litcodex/components/wikify-knowledge/package.json +1 -1
- package/marketplace/plugins/litcodex/hooks/hooks.json +20 -0
- package/model-catalog.json +25 -5
- package/node_modules/@litcodex/lit-loop/README.md +10 -0
- package/node_modules/@litcodex/lit-loop/dist/auto-handoff-settings.d.ts +87 -0
- package/node_modules/@litcodex/lit-loop/dist/auto-handoff-settings.js +414 -0
- package/node_modules/@litcodex/lit-loop/dist/auto-handoff.d.ts +72 -0
- package/node_modules/@litcodex/lit-loop/dist/auto-handoff.js +317 -0
- package/node_modules/@litcodex/lit-loop/dist/cli.js +5 -1
- package/node_modules/@litcodex/lit-loop/dist/hook-cli.d.ts +11 -2
- package/node_modules/@litcodex/lit-loop/dist/hook-cli.js +137 -10
- package/node_modules/@litcodex/lit-loop/package.json +1 -1
- package/package.json +2 -2
- package/readme-assets/badge-version.svg +1 -1
- package/readme-assets/ab-simple/assets/s11-baseline-desktop.webp +0 -0
- package/readme-assets/ab-simple/assets/s11-baseline-phone.webp +0 -0
- package/readme-assets/ab-simple/assets/s11-lit-desktop.webp +0 -0
- package/readme-assets/ab-simple/assets/s11-lit-phone.webp +0 -0
- package/readme-assets/ab-simple/assets/s3-baseline-desktop.webp +0 -0
- package/readme-assets/ab-simple/assets/s3-baseline-phone.webp +0 -0
- package/readme-assets/ab-simple/assets/s3-lit-desktop.webp +0 -0
- package/readme-assets/ab-simple/assets/s3-lit-phone.webp +0 -0
- package/readme-assets/ab-simple/assets/s4-baseline-desktop.webp +0 -0
- package/readme-assets/ab-simple/assets/s4-baseline-phone.webp +0 -0
- package/readme-assets/ab-simple/assets/s4-lit-desktop.webp +0 -0
- package/readme-assets/ab-simple/assets/s4-lit-phone.webp +0 -0
- package/readme-assets/ab-simple/assets/s5-baseline-slides.webp +0 -0
- package/readme-assets/ab-simple/assets/s5-lit-slides.webp +0 -0
- package/readme-assets/ab-simple/assets/s7-lit-diagram.webp +0 -0
- package/readme-assets/ab-simple/assets/s8-baseline-slides.webp +0 -0
- package/readme-assets/ab-simple/assets/s8-lit-slides.webp +0 -0
- package/readme-assets/ab-simple/assets/s9-lit-pages.webp +0 -0
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
// src/auto-handoff-settings.ts — the user-controlled switch for automatic handoff.
|
|
2
|
+
//
|
|
3
|
+
// Off by default. The user turns it on with the exact prompt `lit-handoff auto on <percent>` (or sets
|
|
4
|
+
// `LITCODEX_AUTO_HANDOFF=1` plus `LITCODEX_AUTO_HANDOFF_PERCENT`), turns it off with
|
|
5
|
+
// `lit-handoff auto off`, and reads the state with `lit-handoff auto status`. The percent is never
|
|
6
|
+
// hard-coded: `on` without a number reuses the last value the user stored and asks for one when there
|
|
7
|
+
// is none. A percent that is not a whole number from 1 to 99 keeps the feature off and is reported.
|
|
8
|
+
//
|
|
9
|
+
// Command-set values live in `.litcodex/auto-handoff/settings.json` under the project folder. When the
|
|
10
|
+
// feature is turned on by command, the same percent is written to the PROJECT `.codex/config.toml` as
|
|
11
|
+
// `model_post_turn_compact_threshold_percent`, so Codex itself compacts once the turn that saved the
|
|
12
|
+
// handoff is over. The key is written inside a marked block and removed again by `off`; a key the user
|
|
13
|
+
// wrote by hand is never touched. Codex reads a project's `.codex/config.toml` only when the project is
|
|
14
|
+
// trusted in `$CODEX_HOME/config.toml`, so every claim that Codex compacts also checks that trust.
|
|
15
|
+
import { randomBytes } from "node:crypto";
|
|
16
|
+
import { closeSync, constants, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeSync, } from "node:fs";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
import { dirname, isAbsolute, join, relative, sep } from "node:path";
|
|
19
|
+
export const AUTO_HANDOFF_FLAG_ENV = "LITCODEX_AUTO_HANDOFF";
|
|
20
|
+
export const AUTO_HANDOFF_PERCENT_ENV = "LITCODEX_AUTO_HANDOFF_PERCENT";
|
|
21
|
+
export const AUTO_HANDOFF_DIR = ".litcodex/auto-handoff";
|
|
22
|
+
export const AUTO_HANDOFF_SETTINGS_FILE = "settings.json";
|
|
23
|
+
export const HOST_COMPACT_KEY = "model_post_turn_compact_threshold_percent";
|
|
24
|
+
export const HOST_COMPACT_BEGIN = "# litcodex automatic handoff (managed by `lit-handoff auto`; `lit-handoff auto off` removes it)";
|
|
25
|
+
const NO_FOLLOW = constants.O_NOFOLLOW ?? 0;
|
|
26
|
+
const MAX_FILE_BYTES = 256 * 1024;
|
|
27
|
+
const DEFAULT_STORED = Object.freeze({ enabled: false, percent: null });
|
|
28
|
+
/** A whole number from 1 to 99 written as plain digits, else null. */
|
|
29
|
+
export function parsePercent(raw) {
|
|
30
|
+
const text = raw?.trim() ?? "";
|
|
31
|
+
if (!/^\d{1,2}$/u.test(text))
|
|
32
|
+
return null;
|
|
33
|
+
const value = Number(text);
|
|
34
|
+
return value >= 1 && value <= 99 ? value : null;
|
|
35
|
+
}
|
|
36
|
+
export function settingsPath(repoRoot) {
|
|
37
|
+
return join(repoRoot, AUTO_HANDOFF_DIR, AUTO_HANDOFF_SETTINGS_FILE);
|
|
38
|
+
}
|
|
39
|
+
function isRecord(value) {
|
|
40
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
41
|
+
}
|
|
42
|
+
/** Read a small regular file; null when missing, a symlink, too large, or unreadable. */
|
|
43
|
+
export function readSmallFile(path) {
|
|
44
|
+
let fd;
|
|
45
|
+
try {
|
|
46
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
47
|
+
if (stat === undefined || !stat.isFile() || stat.size > MAX_FILE_BYTES)
|
|
48
|
+
return null;
|
|
49
|
+
fd = openSync(path, constants.O_RDONLY | NO_FOLLOW);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
return readFileSync(fd, "utf8");
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
closeSync(fd);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** The stored choice; a missing, malformed or hand-edited file reads as "off, no percent". */
|
|
65
|
+
export function readStoredAutoHandoff(repoRoot) {
|
|
66
|
+
if (!isAbsolute(repoRoot))
|
|
67
|
+
return { stored: DEFAULT_STORED, warning: null };
|
|
68
|
+
const raw = readSmallFile(settingsPath(repoRoot));
|
|
69
|
+
if (raw === null)
|
|
70
|
+
return { stored: DEFAULT_STORED, warning: null };
|
|
71
|
+
try {
|
|
72
|
+
const parsed = JSON.parse(raw);
|
|
73
|
+
if (!isRecord(parsed))
|
|
74
|
+
throw new Error("not an object");
|
|
75
|
+
const percent = parsed["percent"] === null ? null : parsePercent(String(parsed["percent"]));
|
|
76
|
+
const warning = parsed["percent"] !== null && percent === null
|
|
77
|
+
? "The stored percent is not a whole number from 1 to 99 and was ignored."
|
|
78
|
+
: null;
|
|
79
|
+
return { stored: { enabled: parsed["enabled"] === true, percent }, warning };
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return {
|
|
83
|
+
stored: DEFAULT_STORED,
|
|
84
|
+
warning: `${AUTO_HANDOFF_DIR}/${AUTO_HANDOFF_SETTINGS_FILE} could not be read, so automatic handoff stays off.`,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function shown(raw) {
|
|
89
|
+
const clean = raw.replace(/[^\x20-\x7e]/gu, "?");
|
|
90
|
+
return clean.length > 24 ? `${clean.slice(0, 24)}...` : clean;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Combine the environment with the stored choice. The environment wins when it is set: `=1` turns the
|
|
94
|
+
* feature on and `=0` turns it off. The percent comes from its variable first, then from the stored
|
|
95
|
+
* value. Nothing is active without a valid percent.
|
|
96
|
+
*/
|
|
97
|
+
export function resolveAutoHandoff(env, stored, storedWarning = null) {
|
|
98
|
+
const warnings = [];
|
|
99
|
+
if (storedWarning !== null)
|
|
100
|
+
warnings.push(storedWarning);
|
|
101
|
+
const flag = env[AUTO_HANDOFF_FLAG_ENV]?.trim() ?? "";
|
|
102
|
+
if (flag !== "" && flag !== "1" && flag !== "0") {
|
|
103
|
+
warnings.push(`${AUTO_HANDOFF_FLAG_ENV}=${shown(flag)} is not 1 or 0 and was ignored.`);
|
|
104
|
+
}
|
|
105
|
+
const envDecision = flag === "1" ? true : flag === "0" ? false : null;
|
|
106
|
+
const enabled = envDecision ?? stored.enabled;
|
|
107
|
+
const rawPercent = env[AUTO_HANDOFF_PERCENT_ENV]?.trim() ?? "";
|
|
108
|
+
const envPercent = rawPercent === "" ? null : parsePercent(rawPercent);
|
|
109
|
+
const envPercentInvalid = rawPercent !== "" && envPercent === null;
|
|
110
|
+
if (envPercentInvalid) {
|
|
111
|
+
warnings.push(`${AUTO_HANDOFF_PERCENT_ENV}=${shown(rawPercent)} is not a whole number from 1 to 99, so automatic handoff stays off.`);
|
|
112
|
+
}
|
|
113
|
+
const percent = envPercentInvalid ? null : (envPercent ?? stored.percent);
|
|
114
|
+
const source = envDecision !== null || envPercent !== null ? "environment" : enabled ? "command" : "default";
|
|
115
|
+
if (enabled && !envPercentInvalid && percent === null) {
|
|
116
|
+
warnings.push(`Automatic handoff is on but has no percent. Run "lit-handoff auto on <percent>" or set ${AUTO_HANDOFF_PERCENT_ENV}.`);
|
|
117
|
+
}
|
|
118
|
+
return { active: enabled && percent !== null, percent, source, warnings };
|
|
119
|
+
}
|
|
120
|
+
export function loadAutoHandoffState(repoRoot, env) {
|
|
121
|
+
const { stored, warning } = readStoredAutoHandoff(repoRoot);
|
|
122
|
+
return resolveAutoHandoff(env, stored, warning);
|
|
123
|
+
}
|
|
124
|
+
// ── Safe small-file writes ───────────────────────────────────────────────────
|
|
125
|
+
/**
|
|
126
|
+
* True when no existing component of `target` below `root` is a symlink, so a write or delete cannot be
|
|
127
|
+
* redirected out of the project. Components that do not exist yet are fine; `root` itself is trusted.
|
|
128
|
+
*/
|
|
129
|
+
function clearOfSymlinks(root, target) {
|
|
130
|
+
const below = relative(root, target);
|
|
131
|
+
if (below === "" || below === ".." || below.startsWith(`..${sep}`) || isAbsolute(below))
|
|
132
|
+
return false;
|
|
133
|
+
let current = root;
|
|
134
|
+
try {
|
|
135
|
+
for (const part of below.split(sep)) {
|
|
136
|
+
current = join(current, part);
|
|
137
|
+
const stat = lstatSync(current, { throwIfNoEntry: false });
|
|
138
|
+
if (stat === undefined)
|
|
139
|
+
return true;
|
|
140
|
+
if (stat.isSymbolicLink())
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function ensureDir(dir) {
|
|
150
|
+
try {
|
|
151
|
+
const stat = lstatSync(dir, { throwIfNoEntry: false });
|
|
152
|
+
if (stat === undefined) {
|
|
153
|
+
mkdirSync(dir, { recursive: true });
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
return stat.isDirectory();
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/** Atomic write that refuses to go through a symlink (in any component below `root`) or replace anything but a regular file. */
|
|
163
|
+
export function writeSmallFile(path, text, root) {
|
|
164
|
+
if (!clearOfSymlinks(root, path) || !ensureDir(dirname(path)))
|
|
165
|
+
return false;
|
|
166
|
+
const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
167
|
+
try {
|
|
168
|
+
const existing = lstatSync(path, { throwIfNoEntry: false });
|
|
169
|
+
if (existing !== undefined && !existing.isFile())
|
|
170
|
+
return false;
|
|
171
|
+
const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | NO_FOLLOW, 0o644);
|
|
172
|
+
try {
|
|
173
|
+
writeSync(fd, text);
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
closeSync(fd);
|
|
177
|
+
}
|
|
178
|
+
renameSync(tmp, path);
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
try {
|
|
183
|
+
unlinkSync(tmp);
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
// nothing was created
|
|
187
|
+
}
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
export function writeStoredAutoHandoff(repoRoot, stored) {
|
|
192
|
+
return writeSmallFile(settingsPath(repoRoot), `${JSON.stringify({ version: 1, ...stored })}\n`, repoRoot);
|
|
193
|
+
}
|
|
194
|
+
// ── Project config: Codex compacts after the handoff turn ────────────────────
|
|
195
|
+
const KEY_LINE = new RegExp(`^\\s*${HOST_COMPACT_KEY}\\s*=\\s*(\\d+)\\s*(?:#.*)?$`, "u");
|
|
196
|
+
export function projectConfigPath(repoRoot) {
|
|
197
|
+
return join(repoRoot, ".codex", "config.toml");
|
|
198
|
+
}
|
|
199
|
+
/** What the project's `.codex/config.toml` says about compacting after a turn. */
|
|
200
|
+
export function readProjectCompaction(repoRoot) {
|
|
201
|
+
const raw = readSmallFile(projectConfigPath(repoRoot));
|
|
202
|
+
if (raw === null)
|
|
203
|
+
return { kind: "absent" };
|
|
204
|
+
const lines = raw.split(/\r?\n/u);
|
|
205
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
206
|
+
const match = KEY_LINE.exec(lines[index] ?? "");
|
|
207
|
+
if (match?.[1] === undefined)
|
|
208
|
+
continue;
|
|
209
|
+
const percent = Number(match[1]);
|
|
210
|
+
return lines[index - 1] === HOST_COMPACT_BEGIN ? { kind: "managed", percent } : { kind: "user-set", percent };
|
|
211
|
+
}
|
|
212
|
+
return { kind: "absent" };
|
|
213
|
+
}
|
|
214
|
+
function codexHomeDir(env) {
|
|
215
|
+
const fromEnv = env["CODEX_HOME"]?.trim() ?? "";
|
|
216
|
+
return fromEnv === "" ? join(homedir(), ".codex") : fromEnv;
|
|
217
|
+
}
|
|
218
|
+
/** The project path a `[projects."<path>"]` table header names, else null. */
|
|
219
|
+
function projectOfHeader(header) {
|
|
220
|
+
const match = /^\s*projects\s*\.\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')\s*$/u.exec(header);
|
|
221
|
+
if (match === null)
|
|
222
|
+
return null;
|
|
223
|
+
return match[1] !== undefined ? match[1].replace(/\\(["\\])/gu, "$1") : (match[2] ?? null);
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* True when `$CODEX_HOME/config.toml` marks this project trusted. Codex ignores a project's own
|
|
227
|
+
* `.codex/config.toml` until then, so an untrusted project never gets the compaction setting applied.
|
|
228
|
+
*/
|
|
229
|
+
export function projectTrusted(repoRoot, env) {
|
|
230
|
+
const raw = readSmallFile(join(codexHomeDir(env), "config.toml"));
|
|
231
|
+
if (raw === null)
|
|
232
|
+
return false;
|
|
233
|
+
const wanted = new Set([repoRoot]);
|
|
234
|
+
try {
|
|
235
|
+
wanted.add(realpathSync(repoRoot));
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
// the plain path is enough
|
|
239
|
+
}
|
|
240
|
+
let current = null;
|
|
241
|
+
for (const line of raw.split(/\r?\n/u)) {
|
|
242
|
+
const header = /^\s*\[(.*)\]\s*(?:#.*)?$/u.exec(line);
|
|
243
|
+
if (header?.[1] !== undefined) {
|
|
244
|
+
current = projectOfHeader(header[1]);
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
if (current !== null && wanted.has(current) && /^\s*trust_level\s*=\s*["']trusted["']\s*(?:#.*)?$/u.test(line)) {
|
|
248
|
+
return true;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return false;
|
|
252
|
+
}
|
|
253
|
+
/** True when Codex itself will compact once a turn ends with usage at or above `percent`. */
|
|
254
|
+
export function hostCompactsAt(repoRoot, percent, env) {
|
|
255
|
+
const current = readProjectCompaction(repoRoot);
|
|
256
|
+
return current.kind !== "absent" && current.percent <= percent && projectTrusted(repoRoot, env);
|
|
257
|
+
}
|
|
258
|
+
/** Write (or update) the marked block. A key the user wrote by hand stays as it is. */
|
|
259
|
+
export function writeProjectCompaction(repoRoot, percent) {
|
|
260
|
+
const path = projectConfigPath(repoRoot);
|
|
261
|
+
if (!clearOfSymlinks(repoRoot, path))
|
|
262
|
+
return "failed";
|
|
263
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
264
|
+
if (stat !== undefined && !stat.isFile())
|
|
265
|
+
return "failed";
|
|
266
|
+
const raw = stat === undefined ? "" : readSmallFile(path);
|
|
267
|
+
if (raw === null)
|
|
268
|
+
return "failed";
|
|
269
|
+
const current = readProjectCompaction(repoRoot);
|
|
270
|
+
if (current.kind === "user-set")
|
|
271
|
+
return "unchanged-user-key";
|
|
272
|
+
const block = `${HOST_COMPACT_BEGIN}\n${HOST_COMPACT_KEY} = ${percent}\n`;
|
|
273
|
+
if (current.kind === "managed") {
|
|
274
|
+
const lines = raw.split("\n");
|
|
275
|
+
const at = lines.findIndex((line) => KEY_LINE.test(line.replace(/\r$/u, "")));
|
|
276
|
+
lines[at] = `${HOST_COMPACT_KEY} = ${percent}`;
|
|
277
|
+
return writeSmallFile(path, lines.join("\n"), repoRoot) ? "written" : "failed";
|
|
278
|
+
}
|
|
279
|
+
return writeSmallFile(path, raw === "" ? block : `${block}\n${raw}`, repoRoot) ? "written" : "failed";
|
|
280
|
+
}
|
|
281
|
+
/** Remove only the marked block; delete the file (and an empty `.codex`) when nothing else is left. */
|
|
282
|
+
export function removeProjectCompaction(repoRoot) {
|
|
283
|
+
const path = projectConfigPath(repoRoot);
|
|
284
|
+
if (readProjectCompaction(repoRoot).kind !== "managed")
|
|
285
|
+
return "nothing-to-remove";
|
|
286
|
+
if (!clearOfSymlinks(repoRoot, path))
|
|
287
|
+
return "failed";
|
|
288
|
+
const raw = readSmallFile(path);
|
|
289
|
+
if (raw === null)
|
|
290
|
+
return "failed";
|
|
291
|
+
const lines = raw.split("\n");
|
|
292
|
+
const at = lines.findIndex((line) => line.replace(/\r$/u, "") === HOST_COMPACT_BEGIN);
|
|
293
|
+
if (at < 0)
|
|
294
|
+
return "nothing-to-remove";
|
|
295
|
+
lines.splice(at, 2);
|
|
296
|
+
if (lines[at] === "" && (at === 0 || lines[at - 1] === ""))
|
|
297
|
+
lines.splice(at, 1);
|
|
298
|
+
const rest = lines.join("\n");
|
|
299
|
+
if (rest.trim() === "") {
|
|
300
|
+
try {
|
|
301
|
+
unlinkSync(path);
|
|
302
|
+
try {
|
|
303
|
+
rmdirSync(dirname(path));
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
// other files live there
|
|
307
|
+
}
|
|
308
|
+
return "removed";
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
return "failed";
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return writeSmallFile(path, rest, repoRoot) ? "removed" : "failed";
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Remove the managed block when the feature is effectively off, however it got there: `lit-handoff auto
|
|
318
|
+
* off`, `LITCODEX_AUTO_HANDOFF=0`, a deleted settings file, or a percent that is not valid. Without this the
|
|
319
|
+
* block outlives the switch and Codex keeps compacting at that percent with no handoff. Only the marked
|
|
320
|
+
* block goes; a key the user wrote by hand is never touched. Never throws.
|
|
321
|
+
*/
|
|
322
|
+
export function clearManagedCompactionWhenOff(repoRoot, env) {
|
|
323
|
+
try {
|
|
324
|
+
if (!isAbsolute(repoRoot) || loadAutoHandoffState(repoRoot, env).active)
|
|
325
|
+
return "nothing-to-remove";
|
|
326
|
+
return removeProjectCompaction(repoRoot);
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
return "failed";
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
/** Only the complete prompt `lit-handoff auto ...` (case-insensitive, edge whitespace allowed) is a route. */
|
|
333
|
+
export function parseAutoHandoffRoute(prompt) {
|
|
334
|
+
const match = /^\s*lit-handoff\s+auto(?:\s+(.*?))?\s*$/isu.exec(prompt);
|
|
335
|
+
if (match === null)
|
|
336
|
+
return null;
|
|
337
|
+
const words = (match[1] ?? "").split(/\s+/u).filter(Boolean);
|
|
338
|
+
const verb = words[0]?.toLowerCase();
|
|
339
|
+
if (verb === "on" && words.length <= 2)
|
|
340
|
+
return { action: "on", argument: words[1] ?? null };
|
|
341
|
+
if (verb === "off" && words.length === 1)
|
|
342
|
+
return { action: "off" };
|
|
343
|
+
if (verb === "status" && words.length === 1)
|
|
344
|
+
return { action: "status" };
|
|
345
|
+
return { action: "usage" };
|
|
346
|
+
}
|
|
347
|
+
const USAGE = "Usage: lit-handoff auto on <percent from 1 to 99> | lit-handoff auto off | lit-handoff auto status";
|
|
348
|
+
/** Sentence describing how the conversation gets compacted once the handoff is saved. */
|
|
349
|
+
function compactionSentence(repoRoot, percent, env) {
|
|
350
|
+
return hostCompactsAt(repoRoot, percent, env)
|
|
351
|
+
? "Codex compacts the conversation as soon as the turn that saved the handoff ends."
|
|
352
|
+
: "After the handoff is saved you will be asked to run /compact yourself.";
|
|
353
|
+
}
|
|
354
|
+
export function describeAutoHandoff(repoRoot, state, env) {
|
|
355
|
+
const lines = [];
|
|
356
|
+
if (state.active && state.percent !== null) {
|
|
357
|
+
const origin = state.source === "environment" ? "set by environment variables" : "set by command";
|
|
358
|
+
lines.push(`Automatic handoff is ON at ${state.percent}% (${origin}).`);
|
|
359
|
+
lines.push(compactionSentence(repoRoot, state.percent, env));
|
|
360
|
+
}
|
|
361
|
+
else {
|
|
362
|
+
lines.push("Automatic handoff is OFF.");
|
|
363
|
+
if (state.percent !== null)
|
|
364
|
+
lines.push(`Your last percent is ${state.percent}%; "lit-handoff auto on" turns it back on with that value.`);
|
|
365
|
+
}
|
|
366
|
+
for (const warning of state.warnings)
|
|
367
|
+
lines.push(`Warning: ${warning}`);
|
|
368
|
+
return lines.join(" ");
|
|
369
|
+
}
|
|
370
|
+
/** Apply a parsed route and return the one message the user sees. Never throws. */
|
|
371
|
+
export function applyAutoHandoffRoute(repoRoot, env, route) {
|
|
372
|
+
try {
|
|
373
|
+
if (route.action === "usage")
|
|
374
|
+
return USAGE;
|
|
375
|
+
const { stored } = readStoredAutoHandoff(repoRoot);
|
|
376
|
+
if (route.action === "status") {
|
|
377
|
+
clearManagedCompactionWhenOff(repoRoot, env);
|
|
378
|
+
return describeAutoHandoff(repoRoot, loadAutoHandoffState(repoRoot, env), env);
|
|
379
|
+
}
|
|
380
|
+
const envNote = (env[AUTO_HANDOFF_FLAG_ENV]?.trim() ?? "") === ""
|
|
381
|
+
? ""
|
|
382
|
+
: ` ${AUTO_HANDOFF_FLAG_ENV} is set in the environment and takes priority over this command.`;
|
|
383
|
+
if (route.action === "off") {
|
|
384
|
+
if (!writeStoredAutoHandoff(repoRoot, { enabled: false, percent: stored.percent })) {
|
|
385
|
+
return "Automatic handoff could not save its setting (the project folder is not writable), so nothing changed.";
|
|
386
|
+
}
|
|
387
|
+
removeProjectCompaction(repoRoot);
|
|
388
|
+
const kept = stored.percent === null ? "" : ` Your last percent (${stored.percent}%) is kept for next time.`;
|
|
389
|
+
return `Automatic handoff is OFF.${kept}${envNote}`;
|
|
390
|
+
}
|
|
391
|
+
const percent = route.argument === null ? stored.percent : parsePercent(route.argument);
|
|
392
|
+
if (route.argument === null && percent === null) {
|
|
393
|
+
return "Which percent should trigger the handoff? Run: lit-handoff auto on <percent from 1 to 99> (for example 60).";
|
|
394
|
+
}
|
|
395
|
+
if (percent === null)
|
|
396
|
+
return `"${shown(route.argument ?? "")}" is not a whole number from 1 to 99. Nothing changed.`;
|
|
397
|
+
if (!writeStoredAutoHandoff(repoRoot, { enabled: true, percent })) {
|
|
398
|
+
return "Automatic handoff could not save its setting (the project folder is not writable), so nothing changed.";
|
|
399
|
+
}
|
|
400
|
+
const config = writeProjectCompaction(repoRoot, percent);
|
|
401
|
+
const untrusted = config === "written" && !projectTrusted(repoRoot, env)
|
|
402
|
+
? "Codex reads the project .codex/config.toml only after you trust this project, so until then you will be asked to run /compact yourself."
|
|
403
|
+
: "";
|
|
404
|
+
const asked = config === "unchanged-user-key"
|
|
405
|
+
? ` Your project .codex/config.toml already sets ${HOST_COMPACT_KEY}, so it was left as it is.`
|
|
406
|
+
: config === "failed"
|
|
407
|
+
? " The project .codex/config.toml could not be updated, so you will be asked to run /compact yourself."
|
|
408
|
+
: "";
|
|
409
|
+
return `Automatic handoff is ON at ${percent}%. When a conversation reaches ${percent}% of the context window, Codex is asked to save a handoff. ${untrusted === "" ? compactionSentence(repoRoot, percent, env) : untrusted}${asked}${envNote}`;
|
|
410
|
+
}
|
|
411
|
+
catch {
|
|
412
|
+
return "Automatic handoff hit an unexpected error and changed nothing.";
|
|
413
|
+
}
|
|
414
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
export declare const HANDOFF_MARKER_LABEL = "Auto-handoff session:";
|
|
2
|
+
export declare const SAVED_LINE_RUN_COMPACT = "Handoff saved. Run /compact now.";
|
|
3
|
+
export declare const SAVED_LINE_HOST_COMPACTS = "Handoff saved. Codex compacts the conversation next.";
|
|
4
|
+
export declare const RELOAD_EXCERPT_CHARS = 3000;
|
|
5
|
+
declare const STATE_VERSION = 1;
|
|
6
|
+
export type AutoHandoffPhase = "idle" | "fired" | "compacted" | "reloaded";
|
|
7
|
+
export interface AutoHandoffSession {
|
|
8
|
+
readonly version: typeof STATE_VERSION;
|
|
9
|
+
readonly sessionId: string;
|
|
10
|
+
readonly phase: AutoHandoffPhase;
|
|
11
|
+
readonly firedAt: number | null;
|
|
12
|
+
readonly firedPercent: number | null;
|
|
13
|
+
readonly lastPercent: number | null;
|
|
14
|
+
}
|
|
15
|
+
export interface ContextReading {
|
|
16
|
+
readonly percent: number;
|
|
17
|
+
readonly tokens: number;
|
|
18
|
+
readonly window: number;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Context used by the last model request, as a percent of the window Codex reports for the session.
|
|
22
|
+
* Codex's own post-turn compaction compares the same two numbers, so the hook and the host cross the
|
|
23
|
+
* threshold together. Null when the transcript has no usage yet.
|
|
24
|
+
*/
|
|
25
|
+
export declare function readContextPercent(transcriptPath: string | null | undefined): ContextReading | null;
|
|
26
|
+
export interface AutoHandoffStopInput {
|
|
27
|
+
readonly repoRoot: string;
|
|
28
|
+
readonly sessionId: string;
|
|
29
|
+
readonly transcriptPath: string | null | undefined;
|
|
30
|
+
readonly stopHookActive: boolean;
|
|
31
|
+
readonly env: NodeJS.ProcessEnv;
|
|
32
|
+
readonly now?: number;
|
|
33
|
+
}
|
|
34
|
+
export type AutoHandoffStopDecision = {
|
|
35
|
+
readonly decision: "pass";
|
|
36
|
+
} | {
|
|
37
|
+
readonly decision: "block";
|
|
38
|
+
readonly reason: string;
|
|
39
|
+
};
|
|
40
|
+
export declare function buildHandoffInstruction(sessionId: string, percent: number, threshold: number, hostCompacts: boolean): string;
|
|
41
|
+
/**
|
|
42
|
+
* Decide the Stop for one turn. Fires at most once per crossing: the record moves to "fired" before the
|
|
43
|
+
* instruction is returned, `stop_hook_active` never fires again, and the record is re-armed only after
|
|
44
|
+
* the context has been seen back under the percent.
|
|
45
|
+
*/
|
|
46
|
+
export declare function evaluateAutoHandoffStop(input: AutoHandoffStopInput): AutoHandoffStopDecision;
|
|
47
|
+
/** Mark a fired session as compacted. Sessions that never fired are left alone. */
|
|
48
|
+
export declare function recordCompaction(repoRoot: string, sessionId: string): void;
|
|
49
|
+
interface FreshHandoff {
|
|
50
|
+
readonly path: string;
|
|
51
|
+
readonly mtimeMs: number;
|
|
52
|
+
readonly text: string;
|
|
53
|
+
}
|
|
54
|
+
/** The newest HANDOFF file written after `since` that names `sessionId`; everything else is ignored. */
|
|
55
|
+
export declare function findFreshHandoff(repoRoot: string, sessionId: string, since: number): FreshHandoff | null;
|
|
56
|
+
/** A reload the record has already been moved past; `release` puts the record back if the text never reached the model. */
|
|
57
|
+
export interface ReloadClaim {
|
|
58
|
+
readonly text: string;
|
|
59
|
+
readonly release: () => void;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Claim the reload text for a session that fired and then compacted, or null when there is nothing to bring
|
|
63
|
+
* back. `allowFired` lets SessionStart (source "compact") reload even when PostCompact has not run yet.
|
|
64
|
+
* The record moves to "reloaded" first, so the excerpt is injected once; a caller that then fails to put
|
|
65
|
+
* the text into its hook output calls `release` so the next prompt can try again.
|
|
66
|
+
*/
|
|
67
|
+
export declare function claimReloadContext(repoRoot: string, sessionId: string, env: NodeJS.ProcessEnv, allowFired: boolean): ReloadClaim | null;
|
|
68
|
+
/** The reload text, claimed for good. Use `claimReloadContext` when the text might not reach the output. */
|
|
69
|
+
export declare function takeReloadContext(repoRoot: string, sessionId: string, env: NodeJS.ProcessEnv, allowFired: boolean): string | null;
|
|
70
|
+
/** Mirror of the rendered state for the doctor: what this session's record says. */
|
|
71
|
+
export declare function readSessionPhase(repoRoot: string, sessionId: string): AutoHandoffPhase | null;
|
|
72
|
+
export {};
|