@litfamily/litcodex 1.0.21 → 1.0.23
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 +9 -9
- package/README.md +9 -9
- package/dist/install/doctor-render.js +5 -0
- package/dist/install/doctor.js +9 -0
- package/dist/install/types.d.ts +4 -0
- package/marketplace/plugins/litcodex/.codex-plugin/plugin.json +1 -1
- package/marketplace/plugins/litcodex/.mcp.json +9 -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/card-html.d.ts +1 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/card-html.js +313 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/card-mcp.d.ts +14 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/card-mcp.js +141 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/card-server.d.ts +2 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/card-server.js +38 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/card-status.d.ts +43 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/card-status.js +363 -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 +14 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.js +76 -2
- package/marketplace/plugins/litcodex/components/lit-loop/dist/live-step.d.ts +59 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/live-step.js +287 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/workflow-map.d.ts +30 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/workflow-map.js +113 -45
- 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/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/node_modules/@litcodex/lit-loop/dist/card-html.d.ts +1 -0
- package/node_modules/@litcodex/lit-loop/dist/card-html.js +313 -0
- package/node_modules/@litcodex/lit-loop/dist/card-mcp.d.ts +14 -0
- package/node_modules/@litcodex/lit-loop/dist/card-mcp.js +141 -0
- package/node_modules/@litcodex/lit-loop/dist/card-server.d.ts +2 -0
- package/node_modules/@litcodex/lit-loop/dist/card-server.js +38 -0
- package/node_modules/@litcodex/lit-loop/dist/card-status.d.ts +43 -0
- package/node_modules/@litcodex/lit-loop/dist/card-status.js +363 -0
- package/node_modules/@litcodex/lit-loop/dist/cli.js +5 -1
- package/node_modules/@litcodex/lit-loop/dist/hook-cli.d.ts +14 -0
- package/node_modules/@litcodex/lit-loop/dist/hook-cli.js +76 -2
- package/node_modules/@litcodex/lit-loop/dist/live-step.d.ts +59 -0
- package/node_modules/@litcodex/lit-loop/dist/live-step.js +287 -0
- package/node_modules/@litcodex/lit-loop/dist/workflow-map.d.ts +30 -0
- package/node_modules/@litcodex/lit-loop/dist/workflow-map.js +113 -45
- package/node_modules/@litcodex/lit-loop/package.json +1 -1
- package/package.json +2 -2
- package/readme-assets/badge-version.svg +1 -1
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// src/card-server.ts — stdio entry of the LIT card MCP server (`.mcp.json` starts it in the plugin folder).
|
|
3
|
+
//
|
|
4
|
+
// The desktop app may start dozens of copies in one launch, so the process does nothing until a request
|
|
5
|
+
// arrives: no state reads, timers, locks, ports or files. It answers newline-delimited JSON-RPC, writes
|
|
6
|
+
// only to stdout, and ends when stdin closes. `LITCODEX_CARD_DEBUG=1` adds one stderr line per request.
|
|
7
|
+
import { createInterface } from "node:readline";
|
|
8
|
+
import { handleCardMessage } from "./card-mcp.js";
|
|
9
|
+
/** Requests are small; a longer line is refused with a parse error instead of being parsed. */
|
|
10
|
+
const MAX_LINE_BYTES = 1_000_000;
|
|
11
|
+
const debug = process.env["LITCODEX_CARD_DEBUG"] === "1";
|
|
12
|
+
const context = { env: process.env, now: () => Date.now() };
|
|
13
|
+
// A host that stops reading ends the conversation; the process leaves instead of crashing on EPIPE.
|
|
14
|
+
process.stdout.on("error", () => process.exit(0));
|
|
15
|
+
const lines = createInterface({ input: process.stdin, crlfDelay: Number.POSITIVE_INFINITY });
|
|
16
|
+
lines.on("line", (line) => {
|
|
17
|
+
if (line.trim() === "")
|
|
18
|
+
return;
|
|
19
|
+
let reply;
|
|
20
|
+
if (Buffer.byteLength(line, "utf8") > MAX_LINE_BYTES) {
|
|
21
|
+
reply = { jsonrpc: "2.0", id: null, error: { code: -32700, message: "request too large" } };
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
try {
|
|
25
|
+
reply = handleCardMessage(JSON.parse(line), context);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
reply = { jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (debug)
|
|
32
|
+
process.stderr.write(`[lit-card] ${line.slice(0, 300)}\n`);
|
|
33
|
+
if (reply !== null)
|
|
34
|
+
process.stdout.write(`${JSON.stringify(reply)}\n`);
|
|
35
|
+
});
|
|
36
|
+
lines.on("close", () => {
|
|
37
|
+
process.exitCode = 0;
|
|
38
|
+
});
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { type WorkflowMap } from "./workflow-map.js";
|
|
2
|
+
export interface CardStatus {
|
|
3
|
+
readonly version: 1;
|
|
4
|
+
/** The normalized thread id, so the card can name its thread when the host does not. */
|
|
5
|
+
readonly thread: string | null;
|
|
6
|
+
readonly state: "ready" | "ignited" | "complete";
|
|
7
|
+
readonly mode: string | null;
|
|
8
|
+
readonly ignitedAt: number | null;
|
|
9
|
+
readonly map: WorkflowMap | null;
|
|
10
|
+
readonly step: {
|
|
11
|
+
readonly tool: string;
|
|
12
|
+
readonly startedAt: number;
|
|
13
|
+
} | null;
|
|
14
|
+
readonly lastStepAt: number | null;
|
|
15
|
+
/** The tool that finished last in this turn, named the way the step is. */
|
|
16
|
+
readonly lastTool: string | null;
|
|
17
|
+
/** When the current turn began, so the card can count the turn's time while no tool runs. */
|
|
18
|
+
readonly turnStartedAt: number | null;
|
|
19
|
+
/** When the current turn ended, so a finished turn shows its own length. */
|
|
20
|
+
readonly turnEndedAt: number | null;
|
|
21
|
+
readonly working: boolean;
|
|
22
|
+
/** Percent of the context window and of each quota window in use, from the thread's last token count. */
|
|
23
|
+
readonly usage: Usage | null;
|
|
24
|
+
/** The workspace's checked-out branch, or a short commit when detached. */
|
|
25
|
+
readonly branch: string | null;
|
|
26
|
+
/** Folder name of the workspace only; the full path stays out of the card. */
|
|
27
|
+
readonly workspace: string | null;
|
|
28
|
+
readonly now: number;
|
|
29
|
+
}
|
|
30
|
+
export interface Usage {
|
|
31
|
+
readonly ctx: number | null;
|
|
32
|
+
readonly fiveHour: number | null;
|
|
33
|
+
readonly week: number | null;
|
|
34
|
+
}
|
|
35
|
+
/** The workspace a thread runs in: the hook pointer, else the rollout header; null when unknown. */
|
|
36
|
+
export declare function resolveThreadCwd(threadId: string | null, env: NodeJS.ProcessEnv): string | null;
|
|
37
|
+
/** Context and quota use from the newest token count in a rollout tail; null when there is none. */
|
|
38
|
+
export declare function usageFromRollout(text: string): Usage | null;
|
|
39
|
+
/** A tool name as the card shows it: an MCP tool reads `server · tool` rather than its joined id. */
|
|
40
|
+
export declare function toolDisplayName(tool: string): string;
|
|
41
|
+
export declare function readCardStatus(threadId: string | null, env: NodeJS.ProcessEnv, now?: number): CardStatus;
|
|
42
|
+
/** The card as plain text, for hosts that cannot draw it (the terminal `codex`). */
|
|
43
|
+
export declare function cardStatusText(status: CardStatus): string;
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
// src/card-status.ts — what the LIT card shows for one Codex thread.
|
|
2
|
+
//
|
|
3
|
+
// The desktop app names the thread in every card poll; the hooks recorded which workspace that thread
|
|
4
|
+
// runs in (live-step.ts). From there the card reads the same saved state the text map reads, plus the
|
|
5
|
+
// live step. The workspace comes from the owned pointer first; Codex's own rollout header is read only
|
|
6
|
+
// when no pointer exists yet, because its format is private. The rollout's last token count gives the
|
|
7
|
+
// context and quota use for the bottom row; when that format moves, the row simply stays empty. Thread ids are normalized before they
|
|
8
|
+
// touch a path, every file read is size-capped and refuses symlinks, and nothing here writes.
|
|
9
|
+
import { closeSync, fstatSync, readdirSync, readSync } from "node:fs";
|
|
10
|
+
import { basename, isAbsolute, join } from "node:path";
|
|
11
|
+
import { codexHomeFrom, openRegularFile, plainDirs, readLiveStep, readThreadPointer, } from "./live-step.js";
|
|
12
|
+
import { normalizeSessionId } from "./state-paths.js";
|
|
13
|
+
import { readWorkflowSignals, workflowMapCells, workflowMapText, workflowTurn, } from "./workflow-map.js";
|
|
14
|
+
/** The rollout header carries the base instructions, so it is read up to this many bytes. */
|
|
15
|
+
const MAX_ROLLOUT_HEADER_BYTES = 256 * 1024;
|
|
16
|
+
/** The newest token count sits near the end of the rollout; only this much of the tail is read. */
|
|
17
|
+
const MAX_ROLLOUT_TAIL_BYTES = 256 * 1024;
|
|
18
|
+
/** Day folders searched, newest first, for a rollout file when no pointer exists. */
|
|
19
|
+
const ROLLOUT_DAYS = 7;
|
|
20
|
+
/** A step that ended this recently still counts as work in progress, so the card keeps polling fast. */
|
|
21
|
+
const RECENT_STEP_MS = 20_000;
|
|
22
|
+
/** A step older than this never ended cleanly (a killed hook, a crash), so it is no longer shown. */
|
|
23
|
+
const STALE_STEP_MS = 30 * 60 * 1000;
|
|
24
|
+
/** An open turn with no tool and no step for this long lost its Stop (an interrupt, a crash); it is not working. */
|
|
25
|
+
const OPEN_TURN_IDLE_MS = 10 * 60 * 1000;
|
|
26
|
+
/** Stages a turn can finish the workflow from; a turn that stops while interviewing or planning waits for the user. */
|
|
27
|
+
const FINISHING_STAGES = new Set(["work", "review"]);
|
|
28
|
+
/** Rollout files resolved during this server's life, with the workspace each one names. */
|
|
29
|
+
const rolloutCache = new Map();
|
|
30
|
+
/** When a thread's rollout was last looked for and not found; the card polls often, the search waits. */
|
|
31
|
+
const rolloutMisses = new Map();
|
|
32
|
+
const ROLLOUT_RETRY_MS = 30_000;
|
|
33
|
+
function isRecord(value) {
|
|
34
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
35
|
+
}
|
|
36
|
+
/** Names in `dir` that match `pattern`, newest-looking first; [] on any failure. */
|
|
37
|
+
function listDesc(dir, pattern) {
|
|
38
|
+
try {
|
|
39
|
+
return readdirSync(dir)
|
|
40
|
+
.filter((name) => pattern.test(name))
|
|
41
|
+
.sort()
|
|
42
|
+
.reverse();
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** The first line of a regular, non-symlinked file, read through one bounded buffer; null when longer. */
|
|
49
|
+
function firstLine(path, maxBytes) {
|
|
50
|
+
let fd = null;
|
|
51
|
+
try {
|
|
52
|
+
fd = openRegularFile(path);
|
|
53
|
+
if (fd === null)
|
|
54
|
+
return null;
|
|
55
|
+
if (!fstatSync(fd).isFile())
|
|
56
|
+
return null;
|
|
57
|
+
const buffer = Buffer.alloc(maxBytes);
|
|
58
|
+
const read = readSync(fd, buffer, 0, maxBytes, 0);
|
|
59
|
+
const end = buffer.subarray(0, read).indexOf(0x0a);
|
|
60
|
+
if (end < 0)
|
|
61
|
+
return null;
|
|
62
|
+
return buffer.subarray(0, end).toString("utf8");
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
if (fd !== null)
|
|
69
|
+
closeSync(fd);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** This thread's rollout file in the last week of day folders and the `session_meta.cwd` it names, or null. */
|
|
73
|
+
function findRollout(home, id) {
|
|
74
|
+
const key = `${home}\0${id}`;
|
|
75
|
+
const cached = rolloutCache.get(key);
|
|
76
|
+
if (cached !== undefined)
|
|
77
|
+
return cached;
|
|
78
|
+
const missed = rolloutMisses.get(key);
|
|
79
|
+
if (missed !== undefined && Date.now() - missed < ROLLOUT_RETRY_MS)
|
|
80
|
+
return null;
|
|
81
|
+
rolloutMisses.set(key, Date.now());
|
|
82
|
+
const sessions = join(home, "sessions");
|
|
83
|
+
const days = [];
|
|
84
|
+
for (const year of listDesc(sessions, /^\d{4}$/u)) {
|
|
85
|
+
for (const month of listDesc(join(sessions, year), /^\d{2}$/u)) {
|
|
86
|
+
for (const day of listDesc(join(sessions, year, month), /^\d{2}$/u)) {
|
|
87
|
+
days.push(join(sessions, year, month, day));
|
|
88
|
+
if (days.length >= ROLLOUT_DAYS)
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
if (days.length >= ROLLOUT_DAYS)
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
if (days.length >= ROLLOUT_DAYS)
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
const suffix = `-${id}.jsonl`;
|
|
98
|
+
for (const day of days) {
|
|
99
|
+
const file = listDesc(day, /^rollout-/u).find((name) => name.endsWith(suffix));
|
|
100
|
+
if (file === undefined)
|
|
101
|
+
continue;
|
|
102
|
+
const line = firstLine(join(day, file), MAX_ROLLOUT_HEADER_BYTES);
|
|
103
|
+
try {
|
|
104
|
+
const record = line === null ? null : JSON.parse(line);
|
|
105
|
+
if (!isRecord(record) || record["type"] !== "session_meta" || !isRecord(record["payload"]))
|
|
106
|
+
return null;
|
|
107
|
+
const { id: metaId, session_id: sessionId, cwd } = record["payload"];
|
|
108
|
+
if ((metaId !== id && sessionId !== id) || typeof cwd !== "string" || !isAbsolute(cwd))
|
|
109
|
+
return null;
|
|
110
|
+
const found = { path: join(day, file), cwd };
|
|
111
|
+
rolloutCache.set(key, found);
|
|
112
|
+
rolloutMisses.delete(key);
|
|
113
|
+
return found;
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
/** The workspace a thread runs in: the hook pointer, else the rollout header; null when unknown. */
|
|
122
|
+
export function resolveThreadCwd(threadId, env) {
|
|
123
|
+
const id = normalizeSessionId(threadId);
|
|
124
|
+
// A thread id that needed cleaning is not one Codex issued; it gets no workspace.
|
|
125
|
+
if (id === null || id !== threadId)
|
|
126
|
+
return null;
|
|
127
|
+
const pointer = readThreadPointer(env, id);
|
|
128
|
+
if (pointer !== null)
|
|
129
|
+
return pointer.cwd;
|
|
130
|
+
const home = codexHomeFrom(env);
|
|
131
|
+
return home === null ? null : (findRollout(home, id)?.cwd ?? null);
|
|
132
|
+
}
|
|
133
|
+
/** The last `bytes` of a regular, non-symlinked file; null on any failure. */
|
|
134
|
+
function tail(path, bytes) {
|
|
135
|
+
let fd = null;
|
|
136
|
+
try {
|
|
137
|
+
fd = openRegularFile(path);
|
|
138
|
+
if (fd === null)
|
|
139
|
+
return null;
|
|
140
|
+
const stat = fstatSync(fd);
|
|
141
|
+
if (!stat.isFile())
|
|
142
|
+
return null;
|
|
143
|
+
const length = Math.min(stat.size, bytes);
|
|
144
|
+
const buffer = Buffer.alloc(length);
|
|
145
|
+
const read = readSync(fd, buffer, 0, length, stat.size - length);
|
|
146
|
+
return buffer.subarray(0, read).toString("utf8");
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
finally {
|
|
152
|
+
if (fd !== null)
|
|
153
|
+
closeSync(fd);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function percent(value) {
|
|
157
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.min(100, Math.round(value))) : null;
|
|
158
|
+
}
|
|
159
|
+
/** Context and quota use from the newest token count in a rollout tail; null when there is none. */
|
|
160
|
+
export function usageFromRollout(text) {
|
|
161
|
+
const lines = text.split("\n");
|
|
162
|
+
for (let index = lines.length - 1; index >= 0; index--) {
|
|
163
|
+
const line = lines[index] ?? "";
|
|
164
|
+
if (!line.includes('"token_count"'))
|
|
165
|
+
continue;
|
|
166
|
+
let record;
|
|
167
|
+
try {
|
|
168
|
+
record = JSON.parse(line);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
const payload = isRecord(record) && isRecord(record["payload"]) ? record["payload"] : null;
|
|
174
|
+
if (payload === null || payload["type"] !== "token_count")
|
|
175
|
+
continue;
|
|
176
|
+
const info = isRecord(payload["info"]) ? payload["info"] : null;
|
|
177
|
+
const last = info !== null && isRecord(info["last_token_usage"]) ? info["last_token_usage"] : null;
|
|
178
|
+
const input = last?.["input_tokens"];
|
|
179
|
+
const window = info?.["model_context_window"];
|
|
180
|
+
const ctx = typeof input === "number" && typeof window === "number" && window > 0 ? percent((input / window) * 100) : null;
|
|
181
|
+
let fiveHour = null;
|
|
182
|
+
let week = null;
|
|
183
|
+
const limits = isRecord(payload["rate_limits"]) ? payload["rate_limits"] : null;
|
|
184
|
+
for (const key of ["primary", "secondary"]) {
|
|
185
|
+
const limit = limits !== null && isRecord(limits[key]) ? limits[key] : null;
|
|
186
|
+
const minutes = limit?.["window_minutes"];
|
|
187
|
+
const used = percent(limit?.["used_percent"]);
|
|
188
|
+
if (used === null || typeof minutes !== "number")
|
|
189
|
+
continue;
|
|
190
|
+
if (minutes <= 24 * 60)
|
|
191
|
+
fiveHour = used;
|
|
192
|
+
else
|
|
193
|
+
week = used;
|
|
194
|
+
}
|
|
195
|
+
if (ctx === null && fiveHour === null && week === null)
|
|
196
|
+
continue;
|
|
197
|
+
return { ctx, fiveHour, week };
|
|
198
|
+
}
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
function readUsage(threadId, env) {
|
|
202
|
+
const home = codexHomeFrom(env);
|
|
203
|
+
const rollout = home === null ? null : findRollout(home, threadId);
|
|
204
|
+
const text = rollout === null ? null : tail(rollout.path, MAX_ROLLOUT_TAIL_BYTES);
|
|
205
|
+
return text === null ? null : usageFromRollout(text);
|
|
206
|
+
}
|
|
207
|
+
/** A small regular file read without following a symlink at any moment; null on any failure. */
|
|
208
|
+
function readSmallText(path, maxBytes) {
|
|
209
|
+
let fd = null;
|
|
210
|
+
try {
|
|
211
|
+
fd = openRegularFile(path);
|
|
212
|
+
if (fd === null)
|
|
213
|
+
return null;
|
|
214
|
+
const stat = fstatSync(fd);
|
|
215
|
+
if (!stat.isFile() || stat.size > maxBytes)
|
|
216
|
+
return null;
|
|
217
|
+
const buffer = Buffer.alloc(stat.size);
|
|
218
|
+
const read = readSync(fd, buffer, 0, stat.size, 0);
|
|
219
|
+
return buffer.subarray(0, read).toString("utf8");
|
|
220
|
+
}
|
|
221
|
+
catch {
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
finally {
|
|
225
|
+
if (fd !== null)
|
|
226
|
+
closeSync(fd);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* The checked-out branch, or a short commit when detached, else null. A worktree or submodule keeps a
|
|
231
|
+
* `.git` file that names its git folder (`gitdir: <path>`); HEAD is read from there.
|
|
232
|
+
*/
|
|
233
|
+
function readBranch(cwd) {
|
|
234
|
+
const pointer = readSmallText(join(cwd, ".git"), 1024)
|
|
235
|
+
?.trim()
|
|
236
|
+
.match(/^gitdir: (.+)$/u)?.[1];
|
|
237
|
+
const gitDir = pointer === undefined ? join(cwd, ".git") : isAbsolute(pointer) ? pointer : join(cwd, pointer);
|
|
238
|
+
const text = readSmallText(join(gitDir, "HEAD"), 512)?.trim();
|
|
239
|
+
if (text === undefined)
|
|
240
|
+
return null;
|
|
241
|
+
const ref = text.match(/^ref: refs\/heads\/([\w./-]{1,80})$/u)?.[1];
|
|
242
|
+
if (ref !== undefined)
|
|
243
|
+
return ref;
|
|
244
|
+
return /^[0-9a-f]{40,64}$/u.test(text) ? text.slice(0, 7) : null;
|
|
245
|
+
}
|
|
246
|
+
/** A tool name as the card shows it: an MCP tool reads `server · tool` rather than its joined id. */
|
|
247
|
+
export function toolDisplayName(tool) {
|
|
248
|
+
const parts = tool.split("__");
|
|
249
|
+
if (parts[0] === "mcp" && parts.length >= 3 && parts[1] !== "")
|
|
250
|
+
return `${parts[1]} · ${parts.slice(2).join("__")}`;
|
|
251
|
+
return tool;
|
|
252
|
+
}
|
|
253
|
+
/** The map once the turn has ended with nothing left open: the running stage and the last stage are done. */
|
|
254
|
+
function finishedMap(map) {
|
|
255
|
+
const lastKey = map.cells.at(-1)?.key;
|
|
256
|
+
return {
|
|
257
|
+
...map,
|
|
258
|
+
cells: map.cells.map((cell) => cell.state === "current" || cell.key === lastKey ? { ...cell, state: "done", label: null } : cell),
|
|
259
|
+
next: null,
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
function ready(thread, workspace, now) {
|
|
263
|
+
return {
|
|
264
|
+
version: 1,
|
|
265
|
+
thread,
|
|
266
|
+
state: "ready",
|
|
267
|
+
mode: null,
|
|
268
|
+
ignitedAt: null,
|
|
269
|
+
map: null,
|
|
270
|
+
step: null,
|
|
271
|
+
lastStepAt: null,
|
|
272
|
+
lastTool: null,
|
|
273
|
+
turnStartedAt: null,
|
|
274
|
+
turnEndedAt: null,
|
|
275
|
+
working: false,
|
|
276
|
+
usage: null,
|
|
277
|
+
branch: null,
|
|
278
|
+
workspace,
|
|
279
|
+
now,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Whether the model is still on the turn while no tool runs. A record that knows its turn says so
|
|
284
|
+
* directly (open until Stop, unless it has gone quiet for the stale window); an older record without
|
|
285
|
+
* turn marks falls back to "a step ended a moment ago".
|
|
286
|
+
*/
|
|
287
|
+
function turnWorking(live, lastStepAt, now) {
|
|
288
|
+
if (live !== null && (live.turnStartedAt !== null || live.turnEndedAt !== null)) {
|
|
289
|
+
if (live.turnEndedAt !== null)
|
|
290
|
+
return false;
|
|
291
|
+
const last = Math.max(live.turnStartedAt ?? 0, live.startedAt ?? 0, live.endedAt ?? 0);
|
|
292
|
+
return now - last < OPEN_TURN_IDLE_MS;
|
|
293
|
+
}
|
|
294
|
+
return lastStepAt !== null && now - lastStepAt < RECENT_STEP_MS;
|
|
295
|
+
}
|
|
296
|
+
export function readCardStatus(threadId, env, now = Date.now()) {
|
|
297
|
+
const cwd = resolveThreadCwd(threadId, env);
|
|
298
|
+
const thread = cwd === null ? null : threadId;
|
|
299
|
+
if (cwd === null || thread === null)
|
|
300
|
+
return ready(null, null, now);
|
|
301
|
+
const workspace = basename(cwd);
|
|
302
|
+
// Every saved state lives under `.litcodex`; a symlink there would point the card at foreign files.
|
|
303
|
+
if (!plainDirs(cwd, ".litcodex"))
|
|
304
|
+
return ready(thread, workspace, now);
|
|
305
|
+
const turn = workflowTurn(cwd, thread);
|
|
306
|
+
if (turn === null)
|
|
307
|
+
return ready(thread, workspace, now);
|
|
308
|
+
const signals = readWorkflowSignals(cwd, thread, now);
|
|
309
|
+
const drawn = workflowMapCells(turn.mode, signals);
|
|
310
|
+
const live = readLiveStep(cwd, thread);
|
|
311
|
+
const step = live !== null && live.tool !== null && live.startedAt !== null && now - live.startedAt < STALE_STEP_MS
|
|
312
|
+
? { tool: toolDisplayName(live.tool), startedAt: live.startedAt }
|
|
313
|
+
: null;
|
|
314
|
+
const lastStepAt = live?.endedAt ?? live?.startedAt ?? null;
|
|
315
|
+
const recorded = signals.work?.status === "completed" ||
|
|
316
|
+
drawn?.cells.some((cell) => cell.key === "done" && cell.state === "current") === true;
|
|
317
|
+
// A LIT turn that has ended with no task or goal still open is done, even though no stage record says so.
|
|
318
|
+
const turnOver = live !== null &&
|
|
319
|
+
live.turnEndedAt !== null &&
|
|
320
|
+
live.turnEndedAt >= turn.startedAt &&
|
|
321
|
+
(live.turnStartedAt === null || live.turnEndedAt >= live.turnStartedAt);
|
|
322
|
+
const open = (signals.work !== null && signals.work.done < signals.work.total) ||
|
|
323
|
+
(signals.goals !== null && signals.goals.done < signals.goals.total);
|
|
324
|
+
const stage = drawn?.cells.find((cell) => cell.state === "current")?.key;
|
|
325
|
+
const finished = !recorded && turnOver && !open && drawn?.family === "main" && stage !== undefined && FINISHING_STAGES.has(stage);
|
|
326
|
+
const map = finished && drawn !== null ? finishedMap(drawn) : drawn;
|
|
327
|
+
return {
|
|
328
|
+
version: 1,
|
|
329
|
+
thread,
|
|
330
|
+
state: recorded || finished ? "complete" : "ignited",
|
|
331
|
+
mode: turn.mode,
|
|
332
|
+
ignitedAt: turn.startedAt,
|
|
333
|
+
map,
|
|
334
|
+
step,
|
|
335
|
+
lastStepAt,
|
|
336
|
+
lastTool: live?.lastTool ? toolDisplayName(live.lastTool) : null,
|
|
337
|
+
turnStartedAt: live?.turnStartedAt ?? null,
|
|
338
|
+
turnEndedAt: turnOver ? live.turnEndedAt : null,
|
|
339
|
+
working: step !== null || turnWorking(live, lastStepAt, now),
|
|
340
|
+
usage: readUsage(thread, env),
|
|
341
|
+
branch: readBranch(cwd),
|
|
342
|
+
workspace,
|
|
343
|
+
now,
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
function clock(ms) {
|
|
347
|
+
const seconds = Math.max(0, Math.floor(ms / 1000));
|
|
348
|
+
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
|
|
349
|
+
}
|
|
350
|
+
/** The card as plain text, for hosts that cannot draw it (the terminal `codex`). */
|
|
351
|
+
export function cardStatusText(status) {
|
|
352
|
+
if (status.state === "ready")
|
|
353
|
+
return "🔥 LIT · ready — no LIT skill in this thread yet. Type `lit <task>` to start one.";
|
|
354
|
+
const lines = [`🔥 LIT ${status.state === "complete" ? "COMPLETE ✓" : "IGNITED"} · ${status.mode ?? "lit"}`];
|
|
355
|
+
if (status.map !== null) {
|
|
356
|
+
lines.push(workflowMapText(status.map));
|
|
357
|
+
if (status.map.next !== null)
|
|
358
|
+
lines.push(`next ▸ ${status.map.next}`);
|
|
359
|
+
}
|
|
360
|
+
if (status.step !== null)
|
|
361
|
+
lines.push(`⠹ ${status.step.tool} · ${clock(status.now - status.step.startedAt)}`);
|
|
362
|
+
return lines.join("\n");
|
|
363
|
+
}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
//
|
|
15
15
|
// `main` NEVER calls process.exit (the shebang wrapper does); it resolves exactly one integer, so
|
|
16
16
|
// the dispatcher is unit-testable with an injected argv array.
|
|
17
|
-
import { runPostCompactHookCli, runPreToolUseCreateGoalGuardCli, runSessionStartHookCli, runStopPlanPersistenceHookCli, runUserPromptSubmitHookCli, } from "./hook-cli.js";
|
|
17
|
+
import { runPostCompactHookCli, runPostToolUseLiveHookCli, runPreToolUseCreateGoalGuardCli, runPreToolUseLiveHookCli, runSessionStartHookCli, runStopPlanPersistenceHookCli, runUserPromptSubmitHookCli, } from "./hook-cli.js";
|
|
18
18
|
import { loopCommand } from "./loop-cli.js";
|
|
19
19
|
const UNKNOWN_COMMAND = "lit-loop: unknown command\n";
|
|
20
20
|
/**
|
|
@@ -35,6 +35,10 @@ export async function main(argv, stdin, stdout, stderr) {
|
|
|
35
35
|
return runSessionStartHookCli(stdin, stdout, stderr);
|
|
36
36
|
if (subcommand === "post-compact")
|
|
37
37
|
return runPostCompactHookCli(stdin, stdout, stderr);
|
|
38
|
+
if (subcommand === "pre-tool-use-live")
|
|
39
|
+
return runPreToolUseLiveHookCli(stdin, stdout, stderr);
|
|
40
|
+
if (subcommand === "post-tool-use-live")
|
|
41
|
+
return runPostToolUseLiveHookCli(stdin, stdout, stderr);
|
|
38
42
|
stderr.write(UNKNOWN_COMMAND);
|
|
39
43
|
return 1;
|
|
40
44
|
}
|
|
@@ -21,6 +21,8 @@ export interface AutoHandoffHookOptions {
|
|
|
21
21
|
readonly env?: NodeJS.ProcessEnv;
|
|
22
22
|
readonly now?: number;
|
|
23
23
|
}
|
|
24
|
+
/** Asks the model to open the LIT card; in the terminal `codex` the same tool returns the map as text. */
|
|
25
|
+
export declare const CARD_OFFER_CONTEXT = "LIT card: if the `lit_card` tool (litcodex MCP server) is available, call the `lit_card` tool once now, with no arguments, so the user sees the live LIT card for this thread. Do not call it again in this thread; it updates by itself.";
|
|
24
26
|
/** Injectable Jev dependencies; production uses the process environment and built-in `fetch`. */
|
|
25
27
|
export interface JevHookOptions {
|
|
26
28
|
readonly env?: NodeJS.ProcessEnv;
|
|
@@ -34,3 +36,15 @@ export declare function runSessionStartHookCli(stdin: NodeJS.ReadableStream, std
|
|
|
34
36
|
/** PostCompact: remember that a session that saved a handoff has now been compacted. Writes nothing to stdout. */
|
|
35
37
|
export declare function runPostCompactHookCli(stdin: NodeJS.ReadableStream, _stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream, repoRoot?: string, auto?: AutoHandoffHookOptions): Promise<number>;
|
|
36
38
|
export declare function runPreToolUseCreateGoalGuardCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream): Promise<number>;
|
|
39
|
+
/** Injectable environment and clock for the live-step hooks. */
|
|
40
|
+
export interface LiveStepHookOptions {
|
|
41
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
42
|
+
readonly now?: number;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Catch-all PreToolUse: in a thread with a LIT activation, remember the running tool for the LIT card
|
|
46
|
+
* and point the thread at its workspace. It prints nothing and exits 0 on every input, so it can never block or change a tool call.
|
|
47
|
+
*/
|
|
48
|
+
export declare function runPreToolUseLiveHookCli(stdin: NodeJS.ReadableStream, _stdout: NodeJS.WritableStream, _stderr: NodeJS.WritableStream, options?: LiveStepHookOptions): Promise<number>;
|
|
49
|
+
/** Catch-all PostToolUse: clear the live step this call set. Prints nothing; exits 0 on every input. */
|
|
50
|
+
export declare function runPostToolUseLiveHookCli(stdin: NodeJS.ReadableStream, _stdout: NodeJS.WritableStream, _stderr: NodeJS.WritableStream, options?: LiveStepHookOptions): Promise<number>;
|
|
@@ -9,12 +9,14 @@
|
|
|
9
9
|
// hint (./jev-hint.ts) and, once per session while it is on, a plain-text banner; with its switch
|
|
10
10
|
// off, that path makes no request and writes nothing.
|
|
11
11
|
import { isAbsolute } from "node:path";
|
|
12
|
+
import { Writable } from "node:stream";
|
|
12
13
|
import { claimReloadContext, evaluateAutoHandoffStop, recordCompaction, takeReloadContext } from "./auto-handoff.js";
|
|
13
14
|
import { applyAutoHandoffRoute, clearManagedCompactionWhenOff, parseAutoHandoffRoute, } from "./auto-handoff-settings.js";
|
|
14
15
|
import { applyPreToolUseCreateGoalGuard, isLitUserPromptSubmitInput, runUserPromptSubmitHook } from "./codex-hook.js";
|
|
15
16
|
import { claimJevOnBanner, formatJevHookOutput, jevSwitchState, runJevSkillHint, withJevBanner, } from "./jev-hint.js";
|
|
17
|
+
import { endLiveStep, readThreadPointer, recordLiveStepEnd, recordLiveStepStart, recordTurnStart, writeThreadPointer, } from "./live-step.js";
|
|
16
18
|
import { evaluatePlanPersistence, formatStopBlockOutput, recordLitPlanActivation } from "./plan-persistence.js";
|
|
17
|
-
import { recordWorkflowTurn, workflowMapLine, workflowStopLine } from "./workflow-map.js";
|
|
19
|
+
import { recordWorkflowTurn, workflowMapLine, workflowStopLine, workflowTurn } from "./workflow-map.js";
|
|
18
20
|
/** Hard cap on stdin to bound memory / ReDoS exposure inside the 5 s Codex hook budget. 8 MB. */
|
|
19
21
|
export const MAX_STDIN_BYTES = 8_000_000;
|
|
20
22
|
const INVALID_JSON_MESSAGE = "lit hook: stdin was not valid JSON";
|
|
@@ -100,14 +102,20 @@ export async function runUserPromptSubmitHookCli(stdin, stdout, stderr, repoRoot
|
|
|
100
102
|
return 0;
|
|
101
103
|
}
|
|
102
104
|
clearManagedCompactionWhenOff(hookCwd(parsed, repoRoot), auto.env ?? process.env);
|
|
105
|
+
const pointer = hookSessionScope(parsed, repoRoot);
|
|
103
106
|
const decision = runUserPromptSubmitHook(parsed);
|
|
107
|
+
// Only a LIT thread gets a pointer: this prompt ignites LIT, or an earlier one already did.
|
|
108
|
+
if (pointer !== null && (decision.kind === "inject" || workflowTurn(pointer.cwd, pointer.sessionId) !== null)) {
|
|
109
|
+
writeThreadPointer(auto.env ?? process.env, pointer.sessionId, pointer.cwd, auto.now);
|
|
110
|
+
recordTurnStart(pointer.cwd, pointer.sessionId, auto.now);
|
|
111
|
+
}
|
|
104
112
|
if (decision.kind === "inject" && decision.mode === "lit-plan") {
|
|
105
113
|
const scope = hookSessionScope(parsed, repoRoot);
|
|
106
114
|
if (scope !== null)
|
|
107
115
|
recordLitPlanActivation(scope.cwd, scope.sessionId);
|
|
108
116
|
}
|
|
109
117
|
const own = decision.kind === "inject"
|
|
110
|
-
? withWorkflowMap(decision.stdout, parsed, decision.mode)
|
|
118
|
+
? withCardOffer(withWorkflowMap(decision.stdout, parsed, decision.mode), pointer, auto)
|
|
111
119
|
: await jevHintOutput(parsed, repoRoot, jev);
|
|
112
120
|
const output = withAutoHandoffReload(own, parsed, repoRoot, auto);
|
|
113
121
|
if (output !== "")
|
|
@@ -192,6 +200,22 @@ function withWorkflowMap(stdout, parsed, mode) {
|
|
|
192
200
|
return stdout;
|
|
193
201
|
}
|
|
194
202
|
}
|
|
203
|
+
/** Asks the model to open the LIT card; in the terminal `codex` the same tool returns the map as text. */
|
|
204
|
+
export const CARD_OFFER_CONTEXT = "LIT card: if the `lit_card` tool (litcodex MCP server) is available, call the `lit_card` tool once now, with no arguments, so the user sees the live LIT card for this thread. Do not call it again in this thread; it updates by itself.";
|
|
205
|
+
function offered(env, sessionId) {
|
|
206
|
+
return (readThreadPointer(env, sessionId)?.cardOfferedAt ?? null) !== null;
|
|
207
|
+
}
|
|
208
|
+
/** Add the card request to the first LIT activation of a thread, and remember that it was made. */
|
|
209
|
+
function withCardOffer(stdout, scope, auto) {
|
|
210
|
+
const env = auto.env ?? process.env;
|
|
211
|
+
if (scope === null || stdout === "" || offered(env, scope.sessionId))
|
|
212
|
+
return stdout;
|
|
213
|
+
const merged = withReloadContext(stdout, CARD_OFFER_CONTEXT);
|
|
214
|
+
if (merged === null)
|
|
215
|
+
return stdout;
|
|
216
|
+
writeThreadPointer(env, scope.sessionId, scope.cwd, auto.now, { cardOffered: true });
|
|
217
|
+
return offered(env, scope.sessionId) ? merged : stdout;
|
|
218
|
+
}
|
|
195
219
|
function isRecord(value) {
|
|
196
220
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
197
221
|
}
|
|
@@ -260,6 +284,9 @@ export async function runStopPlanPersistenceHookCli(stdin, stdout, stderr, repoR
|
|
|
260
284
|
clearManagedCompactionWhenOff(hookCwd(parsed, repoRoot), auto.env ?? process.env);
|
|
261
285
|
const scope = hookSessionScope(parsed, repoRoot);
|
|
262
286
|
if (scope !== null) {
|
|
287
|
+
// No tool runs once Stop fires: one whose PostToolUse never came (interrupted, or denied by another hook) is over.
|
|
288
|
+
// The turn itself closes only below, after the guards that can send the model back to work.
|
|
289
|
+
endLiveStep(scope.cwd, scope.sessionId, auto.now, false);
|
|
263
290
|
const persistence = evaluatePlanPersistence(scope.cwd, scope.sessionId);
|
|
264
291
|
if (persistence.decision === "block") {
|
|
265
292
|
stdout.write(formatStopBlockOutput(persistence.reason));
|
|
@@ -278,6 +305,7 @@ export async function runStopPlanPersistenceHookCli(stdin, stdout, stderr, repoR
|
|
|
278
305
|
stdout.write(formatStopBlockOutput(handoff.reason));
|
|
279
306
|
return 0;
|
|
280
307
|
}
|
|
308
|
+
endLiveStep(scope.cwd, scope.sessionId, auto.now);
|
|
281
309
|
const line = typeof record["turn_id"] === "string"
|
|
282
310
|
? workflowStopLine(scope.cwd, scope.sessionId, record["turn_id"], {
|
|
283
311
|
stopHookActive: record["stop_hook_active"] === true,
|
|
@@ -365,3 +393,49 @@ export async function runPreToolUseCreateGoalGuardCli(stdin, stdout, stderr) {
|
|
|
365
393
|
}
|
|
366
394
|
return 0;
|
|
367
395
|
}
|
|
396
|
+
/** The card's own tools: opening or polling the card is not a step of the work. */
|
|
397
|
+
const OWN_CARD_TOOL = /^mcp__litcodex__lit_card(?:_status)?$/u;
|
|
398
|
+
/** `{ sessionId, cwd, tool, toolUseId }` from a tool event that names its own absolute cwd, else null. */
|
|
399
|
+
function toolEventScope(parsed) {
|
|
400
|
+
if (!isRecord(parsed))
|
|
401
|
+
return null;
|
|
402
|
+
const { session_id: sessionId, cwd, tool_name: tool, tool_use_id: toolUseId } = parsed;
|
|
403
|
+
if (typeof sessionId !== "string" || sessionId === "" || typeof tool !== "string" || tool === "")
|
|
404
|
+
return null;
|
|
405
|
+
if (typeof cwd !== "string" || !isAbsolute(cwd))
|
|
406
|
+
return null;
|
|
407
|
+
return { sessionId, cwd, tool, toolUseId: typeof toolUseId === "string" && toolUseId !== "" ? toolUseId : null };
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Catch-all PreToolUse: in a thread with a LIT activation, remember the running tool for the LIT card
|
|
411
|
+
* and point the thread at its workspace. It prints nothing and exits 0 on every input, so it can never block or change a tool call.
|
|
412
|
+
*/
|
|
413
|
+
export async function runPreToolUseLiveHookCli(stdin, _stdout, _stderr, options = {}) {
|
|
414
|
+
const event = await readHookEvent(stdin, nullSink());
|
|
415
|
+
if (event.exit !== null)
|
|
416
|
+
return 0;
|
|
417
|
+
const scope = toolEventScope(event.parsed);
|
|
418
|
+
if (scope === null || OWN_CARD_TOOL.test(scope.tool))
|
|
419
|
+
return 0;
|
|
420
|
+
const now = options.now ?? Date.now();
|
|
421
|
+
// Only a LIT thread has a card to feed, so other sessions leave no `.litcodex` folder and no pointer.
|
|
422
|
+
if (workflowTurn(scope.cwd, scope.sessionId) === null)
|
|
423
|
+
return 0;
|
|
424
|
+
recordLiveStepStart(scope.cwd, scope.sessionId, scope, now);
|
|
425
|
+
writeThreadPointer(options.env ?? process.env, scope.sessionId, scope.cwd, now);
|
|
426
|
+
return 0;
|
|
427
|
+
}
|
|
428
|
+
/** Catch-all PostToolUse: clear the live step this call set. Prints nothing; exits 0 on every input. */
|
|
429
|
+
export async function runPostToolUseLiveHookCli(stdin, _stdout, _stderr, options = {}) {
|
|
430
|
+
const event = await readHookEvent(stdin, nullSink());
|
|
431
|
+
if (event.exit !== null)
|
|
432
|
+
return 0;
|
|
433
|
+
const scope = toolEventScope(event.parsed);
|
|
434
|
+
if (scope !== null && !OWN_CARD_TOOL.test(scope.tool))
|
|
435
|
+
recordLiveStepEnd(scope.cwd, scope.sessionId, scope, options.now ?? Date.now());
|
|
436
|
+
return 0;
|
|
437
|
+
}
|
|
438
|
+
/** Swallows the parse errors the shared reader reports; the live-step hooks stay silent. */
|
|
439
|
+
function nullSink() {
|
|
440
|
+
return new Writable({ write: (_chunk, _encoding, callback) => callback() });
|
|
441
|
+
}
|