@litfamily/litcodex 1.0.26 → 1.0.28

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.
Files changed (71) hide show
  1. package/README-Ko-KR.md +27 -26
  2. package/README.md +31 -28
  3. package/dist/cli.d.ts +3 -2
  4. package/dist/cli.js +72 -3
  5. package/dist/install/generated-skill-payload-hashes.d.ts +2 -2
  6. package/dist/install/generated-skill-payload-hashes.js +2 -2
  7. package/dist/postinstall.js +12 -1
  8. package/dist/pty-helper.d.ts +7 -0
  9. package/dist/pty-helper.js +45 -0
  10. package/dist/run.d.ts +57 -0
  11. package/dist/run.js +354 -0
  12. package/marketplace/plugins/litcodex/.codex-plugin/plugin.json +1 -1
  13. package/marketplace/plugins/litcodex/components/auto-update/package.json +1 -1
  14. package/marketplace/plugins/litcodex/components/comment-checker/package.json +1 -1
  15. package/marketplace/plugins/litcodex/components/git-bash/package.json +1 -1
  16. package/marketplace/plugins/litcodex/components/lit-loop/dist/card-status.d.ts +8 -3
  17. package/marketplace/plugins/litcodex/components/lit-loop/dist/card-status.js +11 -6
  18. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.js +28 -10
  19. package/marketplace/plugins/litcodex/components/lit-loop/dist/hud-cli.d.ts +38 -0
  20. package/marketplace/plugins/litcodex/components/lit-loop/dist/hud-cli.js +155 -0
  21. package/marketplace/plugins/litcodex/components/lit-loop/dist/hud.d.ts +42 -0
  22. package/marketplace/plugins/litcodex/components/lit-loop/dist/hud.js +297 -0
  23. package/marketplace/plugins/litcodex/components/lit-loop/dist/run-filter.d.ts +23 -0
  24. package/marketplace/plugins/litcodex/components/lit-loop/dist/run-filter.js +142 -0
  25. package/marketplace/plugins/litcodex/components/lit-loop/dist/run-panel.d.ts +29 -0
  26. package/marketplace/plugins/litcodex/components/lit-loop/dist/run-panel.js +102 -0
  27. package/marketplace/plugins/litcodex/components/lit-loop/dist/screen-card.d.ts +24 -0
  28. package/marketplace/plugins/litcodex/components/lit-loop/dist/screen-card.js +104 -0
  29. package/marketplace/plugins/litcodex/components/lit-loop/dist/screen-status.d.ts +24 -0
  30. package/marketplace/plugins/litcodex/components/lit-loop/dist/screen-status.js +110 -0
  31. package/marketplace/plugins/litcodex/components/lit-loop/dist/statusline.d.ts +17 -0
  32. package/marketplace/plugins/litcodex/components/lit-loop/dist/statusline.js +113 -0
  33. package/marketplace/plugins/litcodex/components/lit-loop/dist/workflow-map.d.ts +7 -0
  34. package/marketplace/plugins/litcodex/components/lit-loop/dist/workflow-map.js +58 -10
  35. package/marketplace/plugins/litcodex/components/lit-loop/package.json +1 -1
  36. package/marketplace/plugins/litcodex/components/lsp/package.json +1 -1
  37. package/marketplace/plugins/litcodex/components/rules/bundled-rules/lit-humanizer.md +2 -0
  38. package/marketplace/plugins/litcodex/components/rules/dist/deliverable-hedge-guard.d.ts +8 -0
  39. package/marketplace/plugins/litcodex/components/rules/dist/deliverable-hedge-guard.js +381 -39
  40. package/marketplace/plugins/litcodex/components/rules/package.json +1 -1
  41. package/marketplace/plugins/litcodex/components/start-work-continuation/package.json +1 -1
  42. package/marketplace/plugins/litcodex/components/telemetry/package.json +1 -1
  43. package/marketplace/plugins/litcodex/components/wikify-knowledge/package.json +1 -1
  44. package/marketplace/plugins/litcodex/skills/lit-humanizer/SKILL.md +4 -0
  45. package/marketplace/plugins/litcodex/skills/lit-humanizer/scripts/core.mjs +5 -1
  46. package/marketplace/plugins/litcodex/skills/lit-loop/SKILL.md +2 -1
  47. package/node_modules/@litcodex/lit-loop/dist/card-status.d.ts +8 -3
  48. package/node_modules/@litcodex/lit-loop/dist/card-status.js +11 -6
  49. package/node_modules/@litcodex/lit-loop/dist/hook-cli.js +28 -10
  50. package/node_modules/@litcodex/lit-loop/dist/hud-cli.d.ts +38 -0
  51. package/node_modules/@litcodex/lit-loop/dist/hud-cli.js +155 -0
  52. package/node_modules/@litcodex/lit-loop/dist/hud.d.ts +42 -0
  53. package/node_modules/@litcodex/lit-loop/dist/hud.js +297 -0
  54. package/node_modules/@litcodex/lit-loop/dist/run-filter.d.ts +23 -0
  55. package/node_modules/@litcodex/lit-loop/dist/run-filter.js +142 -0
  56. package/node_modules/@litcodex/lit-loop/dist/run-panel.d.ts +29 -0
  57. package/node_modules/@litcodex/lit-loop/dist/run-panel.js +102 -0
  58. package/node_modules/@litcodex/lit-loop/dist/screen-card.d.ts +24 -0
  59. package/node_modules/@litcodex/lit-loop/dist/screen-card.js +104 -0
  60. package/node_modules/@litcodex/lit-loop/dist/screen-status.d.ts +24 -0
  61. package/node_modules/@litcodex/lit-loop/dist/screen-status.js +110 -0
  62. package/node_modules/@litcodex/lit-loop/dist/statusline.d.ts +17 -0
  63. package/node_modules/@litcodex/lit-loop/dist/statusline.js +113 -0
  64. package/node_modules/@litcodex/lit-loop/dist/workflow-map.d.ts +7 -0
  65. package/node_modules/@litcodex/lit-loop/dist/workflow-map.js +58 -10
  66. package/node_modules/@litcodex/lit-loop/package.json +1 -1
  67. package/node_modules/@litcodex/lit-loop/skills/lit-humanizer/SKILL.md +4 -0
  68. package/node_modules/@litcodex/lit-loop/skills/lit-humanizer/scripts/core.mjs +5 -1
  69. package/node_modules/@litcodex/lit-loop/skills/lit-loop/SKILL.md +2 -1
  70. package/package.json +5 -2
  71. package/readme-assets/badge-version.svg +1 -1
@@ -119,8 +119,8 @@ function findRollout(home, id) {
119
119
  }
120
120
  return null;
121
121
  }
122
- /** The workspace a thread runs in: the hook pointer, else the rollout header; null when unknown. */
123
- export function resolveThreadCwd(threadId, env) {
122
+ /** The workspace a thread runs in: the hook pointer, else (when `rollout` allows) the rollout header; null when unknown. */
123
+ export function resolveThreadCwd(threadId, env, rollout = true) {
124
124
  const id = normalizeSessionId(threadId);
125
125
  // A thread id that needed cleaning is not one Codex issued; it gets no workspace.
126
126
  if (id === null || id !== threadId)
@@ -128,6 +128,8 @@ export function resolveThreadCwd(threadId, env) {
128
128
  const pointer = readThreadPointer(env, id);
129
129
  if (pointer !== null)
130
130
  return pointer.cwd;
131
+ if (!rollout)
132
+ return null;
131
133
  const home = codexHomeFrom(env);
132
134
  return home === null ? null : (findRollout(home, id)?.cwd ?? null);
133
135
  }
@@ -295,8 +297,10 @@ function turnWorking(live, lastStepAt, now) {
295
297
  }
296
298
  return lastStepAt !== null && now - lastStepAt < RECENT_STEP_MS;
297
299
  }
298
- export function readCardStatus(threadId, env, now = Date.now()) {
299
- const cwd = resolveThreadCwd(threadId, env);
300
+ /** The card for one thread. `rollout: false` keeps every Codex rollout file unread; the usage row then stays empty. */
301
+ export function readCardStatus(threadId, env, now = Date.now(), options = {}) {
302
+ const rollout = options.rollout !== false;
303
+ const cwd = resolveThreadCwd(threadId, env, rollout);
300
304
  const thread = cwd === null ? null : threadId;
301
305
  if (cwd === null || thread === null)
302
306
  return ready(null, null, null, now);
@@ -340,14 +344,15 @@ export function readCardStatus(threadId, env, now = Date.now()) {
340
344
  turnStartedAt: live?.turnStartedAt ?? null,
341
345
  turnEndedAt: turnOver ? live.turnEndedAt : null,
342
346
  working: step !== null || turnWorking(live, lastStepAt, now),
343
- usage: readUsage(thread, env),
347
+ usage: rollout ? readUsage(thread, env) : null,
344
348
  branch: readBranch(cwd),
345
349
  workspace,
346
350
  cardOpenedAt,
347
351
  now,
348
352
  };
349
353
  }
350
- function clock(ms) {
354
+ /** Minutes and seconds, `m:ss`. */
355
+ export function clock(ms) {
351
356
  const seconds = Math.max(0, Math.floor(ms / 1000));
352
357
  return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
353
358
  }
@@ -13,7 +13,9 @@ import { applyAutoHandoffRoute, clearManagedCompactionWhenOff, parseAutoHandoffR
13
13
  import { applyPreToolUseCreateGoalGuard, isLitUserPromptSubmitInput, runUserPromptSubmitHook } from "./codex-hook.js";
14
14
  import { endLiveStep, recordLiveStepEnd, recordLiveStepStart, recordTurnStart, writeThreadPointer, } from "./live-step.js";
15
15
  import { evaluatePlanPersistence, formatStopBlockOutput, recordLitPlanActivation } from "./plan-persistence.js";
16
- import { recordWorkflowTurn, workflowMapLine, workflowStopLine, workflowTurn } from "./workflow-map.js";
16
+ import { workflowCard } from "./screen-card.js";
17
+ import { screenColor } from "./screen-status.js";
18
+ import { recordWorkflowTurn, workflowStopLine, workflowTurn } from "./workflow-map.js";
17
19
  /** Hard cap on stdin to bound memory / ReDoS exposure inside the 5 s Codex hook budget. 8 MB. */
18
20
  export const MAX_STDIN_BYTES = 8_000_000;
19
21
  const INVALID_JSON_MESSAGE = "lit hook: stdin was not valid JSON";
@@ -111,8 +113,9 @@ export async function runUserPromptSubmitHookCli(stdin, stdout, stderr, repoRoot
111
113
  if (scope !== null)
112
114
  recordLitPlanActivation(scope.cwd, scope.sessionId);
113
115
  }
116
+ const env = auto.env ?? process.env;
114
117
  const own = decision.kind === "inject"
115
- ? withCardOffer(withWorkflowMap(decision.stdout, parsed, decision.mode), pointer, auto)
118
+ ? withCardOffer(withWorkflowMap(decision.stdout, parsed, decision.mode, env), pointer, auto)
116
119
  : "";
117
120
  const output = withAutoHandoffReload(own, parsed, repoRoot, auto);
118
121
  if (output !== "")
@@ -172,10 +175,11 @@ function withReloadContext(stdout, reload) {
172
175
  }
173
176
  }
174
177
  /**
175
- * Add the workflow map under the activation banner and remember the turn for the Stop line. Only an
176
- * event that names its own absolute `cwd` is mapped, so the map always describes the session's repo.
178
+ * Add the LIT card (map and checklist) under the activation banner and remember the turn for the Stop
179
+ * card. Only an event that names its own absolute `cwd` is mapped, so the card always describes the
180
+ * session's repo.
177
181
  */
178
- function withWorkflowMap(stdout, parsed, mode) {
182
+ function withWorkflowMap(stdout, parsed, mode, env) {
179
183
  if (!isRecord(parsed) || typeof parsed["cwd"] !== "string" || !isAbsolute(parsed["cwd"]))
180
184
  return stdout;
181
185
  const cwd = parsed["cwd"];
@@ -184,13 +188,16 @@ function withWorkflowMap(stdout, parsed, mode) {
184
188
  if (sessionId !== null && typeof parsed["turn_id"] === "string") {
185
189
  recordWorkflowTurn(cwd, sessionId, parsed["turn_id"], mode);
186
190
  }
187
- const map = workflowMapLine(cwd, sessionId, mode);
188
- if (map === null)
191
+ const card = workflowCard(cwd, sessionId, mode, "turn started", {
192
+ color: screenColor(env),
193
+ quietWhenEmpty: true,
194
+ });
195
+ if (card === null)
189
196
  return stdout;
190
197
  const output = JSON.parse(stdout);
191
198
  if (!isRecord(output) || typeof output["systemMessage"] !== "string")
192
199
  return stdout;
193
- output["systemMessage"] = `${output["systemMessage"]}\n${map}`;
200
+ output["systemMessage"] = `${output["systemMessage"]}\n${card}`;
194
201
  return `${JSON.stringify(output)}\n`;
195
202
  }
196
203
  catch {
@@ -237,6 +244,10 @@ function withContextAfterBanner(stdout, text) {
237
244
  function isRecord(value) {
238
245
  return typeof value === "object" && value !== null && !Array.isArray(value);
239
246
  }
247
+ /** A subagent's hooks carry the root session id, so its Stop must not end the parent's turn card. */
248
+ function isSubagent(parsed) {
249
+ return isRecord(parsed) && typeof parsed["agent_id"] === "string" && parsed["agent_id"] !== "";
250
+ }
240
251
  /** Absolute `cwd` from a hook event, else the fallback root. */
241
252
  function hookCwd(parsed, repoRoot) {
242
253
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
@@ -299,15 +310,22 @@ export async function runStopPlanPersistenceHookCli(stdin, stdout, stderr, repoR
299
310
  stdout.write(formatStopBlockOutput(handoff.reason));
300
311
  return 0;
301
312
  }
313
+ // A subagent's Stop carries the parent's session id; the parent's turn is still running.
314
+ if (isSubagent(parsed))
315
+ return 0;
302
316
  endLiveStep(scope.cwd, scope.sessionId, auto.now);
317
+ const env = auto.env ?? process.env;
303
318
  const line = typeof record["turn_id"] === "string"
304
319
  ? workflowStopLine(scope.cwd, scope.sessionId, record["turn_id"], {
305
320
  stopHookActive: record["stop_hook_active"] === true,
306
321
  transcriptPath: typeof record["transcript_path"] === "string" ? record["transcript_path"] : null,
307
322
  })
308
323
  : null;
309
- if (line !== null)
310
- stdout.write(`${JSON.stringify({ systemMessage: line })}\n`);
324
+ const turn = line === null ? null : workflowTurn(scope.cwd, scope.sessionId);
325
+ const card = turn === null ? null : workflowCard(scope.cwd, scope.sessionId, turn.mode, line, { color: screenColor(env) });
326
+ // Codex puts a hook label before the first row, so the card starts on the next one.
327
+ if (card !== null)
328
+ stdout.write(`${JSON.stringify({ systemMessage: `\n${card}` })}\n`);
311
329
  }
312
330
  return 0;
313
331
  }
@@ -0,0 +1,38 @@
1
+ export declare const HUD_HELP_TEXT = "litcodex hud [--session <id>] [--once]\n\nWatch the LIT card of your newest Codex session from a second terminal window or tab.\nIt reads only LIT's own records, never writes a file and never touches Codex. Ctrl-C quits.\n\nOptions:\n --session <id> Follow this session (an exact id or a unique prefix) instead of the newest.\n --once Print one plain frame and exit.\n --help Show this help.\n";
2
+ export interface HudOutput {
3
+ write(text: string): unknown;
4
+ readonly isTTY?: boolean;
5
+ readonly columns?: number | undefined;
6
+ on?(event: "error", listener: (error: unknown) => void): unknown;
7
+ }
8
+ export interface HudLoopOptions {
9
+ readonly env: NodeJS.ProcessEnv;
10
+ readonly wanted: string | null;
11
+ readonly out: HudOutput;
12
+ readonly color: boolean;
13
+ readonly now: () => number;
14
+ }
15
+ /**
16
+ * A frame writer: each `tick` reads and renders once, and writes only when the frame text changed or the
17
+ * terminal was resized. On a terminal the frame stays one column short of the edge, where a full line
18
+ * followed by erase-to-end would lose its last glyph or wrap.
19
+ */
20
+ export declare function createHudLoop(options: HudLoopOptions): {
21
+ tick(): boolean;
22
+ };
23
+ /** The process events the command listens to; a test passes its own emitter. */
24
+ interface HudSignals {
25
+ on(event: string, listener: (...args: unknown[]) => void): unknown;
26
+ off(event: string, listener: (...args: unknown[]) => void): unknown;
27
+ }
28
+ export interface HudIo {
29
+ readonly stdout: HudOutput;
30
+ readonly stderr: {
31
+ write(text: string): unknown;
32
+ };
33
+ readonly env: NodeJS.ProcessEnv;
34
+ readonly signals?: HudSignals;
35
+ readonly now?: () => number;
36
+ }
37
+ export declare function hudCommand(args: readonly string[], io: HudIo): Promise<number>;
38
+ export {};
@@ -0,0 +1,155 @@
1
+ // src/hud-cli.ts — `litcodex hud`: the LIT card, kept live in a second terminal window.
2
+ //
3
+ // One 1 s timer reads the small, size-capped LIT records (hud.ts), builds the frame and writes it only
4
+ // when its text changed; a running step changes it once a second through its clock. On a terminal the
5
+ // frame is drawn in place on the alternate screen with the cursor hidden, and both come back on every
6
+ // way out: a signal, an unexpected error or process exit. The command resolves its exit code and never
7
+ // calls `process.exit`; it writes no file, starts no process and opens no Codex rollout.
8
+ import { readHud, renderHud } from "./hud.js";
9
+ const TICK_MS = 1_000;
10
+ const DEFAULT_WIDTH = 80;
11
+ const ENTER_SCREEN = "\u001b[?1049h\u001b[?25l";
12
+ const LEAVE_SCREEN = "\u001b[?25h\u001b[?1049l";
13
+ const HOME = "\u001b[H";
14
+ const CLEAR_LINE = "\u001b[K";
15
+ const CLEAR_BELOW = "\u001b[J";
16
+ const USAGE_EXIT_CODE = 64;
17
+ const STOP_EVENTS = ["SIGINT", "SIGTERM", "SIGHUP"];
18
+ export const HUD_HELP_TEXT = `litcodex hud [--session <id>] [--once]
19
+
20
+ Watch the LIT card of your newest Codex session from a second terminal window or tab.
21
+ It reads only LIT's own records, never writes a file and never touches Codex. Ctrl-C quits.
22
+
23
+ Options:
24
+ --session <id> Follow this session (an exact id or a unique prefix) instead of the newest.
25
+ --once Print one plain frame and exit.
26
+ --help Show this help.
27
+ `;
28
+ /**
29
+ * A frame writer: each `tick` reads and renders once, and writes only when the frame text changed or the
30
+ * terminal was resized. On a terminal the frame stays one column short of the edge, where a full line
31
+ * followed by erase-to-end would lose its last glyph or wrap.
32
+ */
33
+ export function createHudLoop(options) {
34
+ let last = null;
35
+ let lastColumns;
36
+ return {
37
+ tick() {
38
+ const now = options.now();
39
+ const tty = options.out.isTTY === true;
40
+ const columns = options.out.columns;
41
+ if (columns !== lastColumns)
42
+ last = null;
43
+ lastColumns = columns;
44
+ const width = columns ?? DEFAULT_WIDTH;
45
+ const frame = renderHud(readHud(options.env, options.wanted, now), {
46
+ width: tty ? width - 1 : width,
47
+ color: options.color,
48
+ now,
49
+ });
50
+ if (frame === last)
51
+ return false;
52
+ last = frame;
53
+ options.out.write(tty ? `${HOME}${frame.split("\n").join(`${CLEAR_LINE}\n`)}${CLEAR_LINE}${CLEAR_BELOW}` : `${frame}\n`);
54
+ return true;
55
+ },
56
+ };
57
+ }
58
+ function parseArgs(args) {
59
+ let help = false;
60
+ let once = false;
61
+ let session = null;
62
+ for (let index = 0; index < args.length; index++) {
63
+ const arg = args[index];
64
+ if (arg === "--help" || arg === "-h")
65
+ help = true;
66
+ else if (arg === "--once")
67
+ once = true;
68
+ else if (arg === "--session") {
69
+ const value = args[index + 1];
70
+ if (value === undefined || value.startsWith("-") || value.trim() === "")
71
+ return "--session needs a session id";
72
+ session = value.trim();
73
+ index++;
74
+ }
75
+ else
76
+ return `unknown option "${arg}"`;
77
+ }
78
+ return { help, once, session };
79
+ }
80
+ function colorAllowed(env) {
81
+ const noColor = env["NO_COLOR"];
82
+ return noColor === undefined || noColor === "";
83
+ }
84
+ export async function hudCommand(args, io) {
85
+ const parsed = parseArgs(args);
86
+ if (typeof parsed === "string") {
87
+ io.stderr.write(`litcodex hud: ${parsed}.\n\n${HUD_HELP_TEXT}`);
88
+ return USAGE_EXIT_CODE;
89
+ }
90
+ if (parsed.help) {
91
+ io.stdout.write(HUD_HELP_TEXT);
92
+ return 0;
93
+ }
94
+ const now = io.now ?? Date.now;
95
+ if (parsed.once) {
96
+ createHudLoop({ env: io.env, wanted: parsed.session, out: plain(io.stdout), color: false, now }).tick();
97
+ return 0;
98
+ }
99
+ const tty = io.stdout.isTTY === true;
100
+ const loop = createHudLoop({
101
+ env: io.env,
102
+ wanted: parsed.session,
103
+ out: io.stdout,
104
+ color: tty && colorAllowed(io.env),
105
+ now,
106
+ });
107
+ const signals = io.signals ?? process;
108
+ // A write to a terminal that has gone away (SIGHUP) fails with EIO; it must not become a stack trace.
109
+ io.stdout.on?.("error", () => undefined);
110
+ return new Promise((resolve) => {
111
+ let restored = false;
112
+ let timer;
113
+ const restore = () => {
114
+ if (restored)
115
+ return;
116
+ restored = true;
117
+ clearInterval(timer);
118
+ for (const event of STOP_EVENTS)
119
+ signals.off(event, stop);
120
+ signals.off("uncaughtException", crash);
121
+ signals.off("exit", restore);
122
+ if (tty)
123
+ io.stdout.write(LEAVE_SCREEN);
124
+ };
125
+ const stop = () => {
126
+ restore();
127
+ resolve(0);
128
+ };
129
+ const crash = (error) => {
130
+ restore();
131
+ io.stderr.write(`litcodex hud: stopped: ${error instanceof Error ? error.message : String(error)}\n`);
132
+ resolve(1);
133
+ };
134
+ for (const event of STOP_EVENTS)
135
+ signals.on(event, stop);
136
+ signals.on("uncaughtException", crash);
137
+ signals.on("exit", restore);
138
+ if (tty)
139
+ io.stdout.write(ENTER_SCREEN);
140
+ const tick = () => {
141
+ try {
142
+ loop.tick();
143
+ }
144
+ catch (error) {
145
+ crash(error);
146
+ }
147
+ };
148
+ timer = setInterval(tick, TICK_MS);
149
+ tick();
150
+ });
151
+ }
152
+ /** The stream as a plain, non-terminal writer: one frame, no cursor moves. */
153
+ function plain(out) {
154
+ return { write: (text) => out.write(text), columns: out.isTTY === true ? out.columns : DEFAULT_WIDTH };
155
+ }
@@ -0,0 +1,42 @@
1
+ import { type CardStatus } from "./card-status.js";
2
+ export interface HudSession {
3
+ readonly id: string;
4
+ readonly cwd: string;
5
+ readonly updatedAt: number;
6
+ /** The newest LIT activity: the pointer time or a time the live step or workflow record carries. */
7
+ readonly activeAt: number;
8
+ }
9
+ export interface HudView {
10
+ /** What `--session` asked for, or null to follow the newest session. */
11
+ readonly wanted: string | null;
12
+ readonly session: {
13
+ readonly id: string;
14
+ readonly folder: string;
15
+ readonly lastSeen: number;
16
+ } | null;
17
+ readonly status: CardStatus | null;
18
+ /** Records that exist but could not be read, named for the user. */
19
+ readonly unreadable: readonly string[];
20
+ /** How many sessions `wanted` matched when it named more than one. */
21
+ readonly matches?: number;
22
+ }
23
+ export interface HudRenderOptions {
24
+ readonly width: number;
25
+ readonly color: boolean;
26
+ readonly now: number;
27
+ }
28
+ /** Every session with a readable pointer, newest LIT activity first. */
29
+ export declare function listSessions(env: NodeJS.ProcessEnv): HudSession[];
30
+ /** The most recently active session, or the one `wanted` names by exact id or unique prefix; else null. */
31
+ export declare function pickSession(env: NodeJS.ProcessEnv, wanted?: string | null): HudSession | null;
32
+ /** Everything one frame needs, read once. Never throws and never writes. */
33
+ export declare function readHud(env: NodeJS.ProcessEnv, wanted: string | null, now: number): HudView;
34
+ export declare function clean(text: string): string;
35
+ /** The card with every record-derived string stripped of control characters. */
36
+ export declare function cleanStatus(status: CardStatus): CardStatus;
37
+ /** Terminal cells a plain string takes: CJK and emoji take two, combining marks none. */
38
+ export declare function displayWidth(text: string): number;
39
+ /** The line cut to `width` terminal cells, ending in `…` when anything was cut. */
40
+ export declare function fit(line: string, width: number): string;
41
+ /** One frame as text: a header, the card, and at most one "cannot read" line. Pure. */
42
+ export declare function renderHud(view: HudView, options: HudRenderOptions): string;
@@ -0,0 +1,297 @@
1
+ // src/hud.ts — the LIT card for a second terminal window (`litcodex hud`).
2
+ //
3
+ // Every LIT session leaves a thread pointer in the Codex home (live-step.ts) naming its project folder, so
4
+ // the HUD can run from any directory. A pointer is written once per session, so the session to follow is
5
+ // the one with the newest LIT activity: the pointer time or the times its live step and workflow record
6
+ // carry, which the hooks rewrite on every prompt and tool. Files are re-parsed only after their `lstat`
7
+ // identity (inode, size, times) changes, so an idle HUD costs a few `lstat` calls a tick. The card itself is
8
+ // the one `cardStatusText` prints, read with `rollout: false` so no Codex rollout file is ever opened.
9
+ // Nothing here writes. A record that exists but cannot be read becomes one "cannot read" line instead
10
+ // of a quiet "ready". Record text is data: control characters and escapes are stripped before printing.
11
+ import { lstatSync, readdirSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { cardStatusText, readCardStatus } from "./card-status.js";
14
+ import { codexHomeFrom, liveStepPath, plainDirsOrMissing, readLiveStep, readSmallJson, readThreadPointer, threadPointerPath, } from "./live-step.js";
15
+ import { LIT_LOOP_DIR, LIT_LOOP_GOALS, normalizeSessionId } from "./state-paths.js";
16
+ import { workflowTurn } from "./workflow-map.js";
17
+ const POINTER_DIR = "litcodex/lit-loop/threads";
18
+ const MAX_LIVE_STEP_BYTES = 4_096;
19
+ /** The cap the workflow map itself reads its state files under. */
20
+ const MAX_STATE_BYTES = 1_000_000;
21
+ const SHORT_ID = 8;
22
+ /** Past this, the session is likely gone; the header says when it was last seen instead. */
23
+ const LAST_SEEN_MS = 10 * 60 * 1000;
24
+ /** Parsed files keyed by reader and path, kept while the file's `lstat` identity stays the same. */
25
+ const parsed = new Map();
26
+ /** `read()` for `path`, re-run only when the file's inode, size or times changed since `reader` last read it. */
27
+ function cachedRead(reader, path, read) {
28
+ let key;
29
+ try {
30
+ const stat = lstatSync(path, { throwIfNoEntry: false });
31
+ key = stat === undefined ? "missing" : `${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;
32
+ }
33
+ catch {
34
+ return read();
35
+ }
36
+ const slot = `${reader}\0${path}`;
37
+ const hit = parsed.get(slot);
38
+ if (hit !== undefined && hit.key === key)
39
+ return hit.value;
40
+ const value = read();
41
+ parsed.set(slot, { key, value });
42
+ return value;
43
+ }
44
+ function mtimeOf(path) {
45
+ try {
46
+ return lstatSync(path, { throwIfNoEntry: false })?.mtimeMs ?? 0;
47
+ }
48
+ catch {
49
+ return 0;
50
+ }
51
+ }
52
+ /** The newest time the session's live step or workflow record carries; null when neither has one. */
53
+ function activityAt(cwd, id) {
54
+ const stepPath = liveStepPath(cwd, id);
55
+ const step = stepPath === null ? null : cachedRead("live step", stepPath, () => readLiveStep(cwd, id));
56
+ const turn = cachedRead("turn", join(cwd, ".litcodex/workflow-map", `${id}.json`), () => workflowTurn(cwd, id));
57
+ const times = [step?.turnStartedAt, step?.turnEndedAt, step?.startedAt, step?.endedAt, turn?.startedAt];
58
+ const known = times.filter((time) => typeof time === "number");
59
+ return known.length === 0 ? null : Math.max(...known);
60
+ }
61
+ function scanPointers(env) {
62
+ const home = codexHomeFrom(env);
63
+ if (home === null)
64
+ return { sessions: [], brokenAt: null };
65
+ if (!plainDirsOrMissing(home, POINTER_DIR))
66
+ return { sessions: [], brokenAt: Number.POSITIVE_INFINITY };
67
+ let names;
68
+ try {
69
+ names = readdirSync(join(home, POINTER_DIR)).filter((name) => name.endsWith(".json"));
70
+ }
71
+ catch (error) {
72
+ const missing = error.code === "ENOENT";
73
+ return { sessions: [], brokenAt: missing ? null : Number.POSITIVE_INFINITY };
74
+ }
75
+ const sessions = [];
76
+ let brokenAt = null;
77
+ for (const name of names) {
78
+ const id = name.slice(0, -".json".length);
79
+ const path = threadPointerPath(env, id);
80
+ if (path === null || normalizeSessionId(id) !== id)
81
+ continue;
82
+ const pointer = cachedRead("pointer", path, () => readThreadPointer(env, id));
83
+ const pointerMtime = mtimeOf(path);
84
+ if (pointer === null) {
85
+ brokenAt = Math.max(brokenAt ?? 0, pointerMtime);
86
+ continue;
87
+ }
88
+ const activity = activityAt(pointer.cwd, id);
89
+ const activeAt = Math.max(pointer.updatedAt, activity ?? pointer.updatedAt);
90
+ sessions.push({ id, cwd: pointer.cwd, updatedAt: pointer.updatedAt, activeAt, pointerMtime });
91
+ }
92
+ sessions.sort((a, b) => b.activeAt - a.activeAt || a.id.localeCompare(b.id));
93
+ return { sessions, brokenAt };
94
+ }
95
+ /** Every session with a readable pointer, newest LIT activity first. */
96
+ export function listSessions(env) {
97
+ return scanPointers(env).sessions.map(({ id, cwd, updatedAt, activeAt }) => ({ id, cwd, updatedAt, activeAt }));
98
+ }
99
+ function choose(sessions, wanted) {
100
+ if (wanted === null || wanted === undefined || wanted === "") {
101
+ const newest = sessions[0] ?? null;
102
+ return { session: newest, matches: newest === null ? 0 : 1 };
103
+ }
104
+ const exact = sessions.find((session) => session.id === wanted);
105
+ if (exact !== undefined)
106
+ return { session: exact, matches: 1 };
107
+ const found = sessions.filter((session) => session.id.startsWith(wanted));
108
+ return { session: found.length === 1 ? (found[0] ?? null) : null, matches: found.length };
109
+ }
110
+ /** The most recently active session, or the one `wanted` names by exact id or unique prefix; else null. */
111
+ export function pickSession(env, wanted) {
112
+ return choose(listSessions(env), wanted).session;
113
+ }
114
+ /** True when a record exists at `base/rel/name` but is not a small, regular, parseable file. */
115
+ function unreadableRecord(base, rel, name, maxBytes) {
116
+ if (!plainDirsOrMissing(base, rel))
117
+ return true;
118
+ const path = join(base, rel, name);
119
+ try {
120
+ const stat = lstatSync(path, { throwIfNoEntry: false });
121
+ if (stat === undefined)
122
+ return false;
123
+ if (!stat.isFile() || stat.size > maxBytes)
124
+ return true;
125
+ }
126
+ catch {
127
+ return true;
128
+ }
129
+ return cachedRead(`unreadable ${maxBytes}`, path, () => readSmallJson(path, maxBytes) === null);
130
+ }
131
+ /** Every record the card reads, with the name the "cannot read" line gives it. */
132
+ function recordsOf(id) {
133
+ return [
134
+ ["live step", ".litcodex/live-step", `${id}.json`, MAX_LIVE_STEP_BYTES],
135
+ ["workflow record", ".litcodex/workflow-map", `${id}.json`, MAX_STATE_BYTES],
136
+ ["start-work state", ".litcodex/start-work", "state.json", MAX_STATE_BYTES],
137
+ ["session goals", `${LIT_LOOP_DIR}/${id}`, LIT_LOOP_GOALS, MAX_STATE_BYTES],
138
+ ["shared goals", LIT_LOOP_DIR, LIT_LOOP_GOALS, MAX_STATE_BYTES],
139
+ ["lit-plan record", ".litcodex/lit-plan", `${id}.json`, MAX_STATE_BYTES],
140
+ ];
141
+ }
142
+ function unreadableRecords(cwd, id) {
143
+ if (!plainDirsOrMissing(cwd, ".litcodex"))
144
+ return ["project records (.litcodex)"];
145
+ return recordsOf(id)
146
+ .filter(([, rel, name, maxBytes]) => unreadableRecord(cwd, rel, name, maxBytes))
147
+ .map(([label]) => label);
148
+ }
149
+ function tilde(path, home) {
150
+ if (home === undefined || home === "" || home === "/")
151
+ return path;
152
+ if (path === home)
153
+ return "~";
154
+ return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
155
+ }
156
+ /** Everything one frame needs, read once. Never throws and never writes. */
157
+ export function readHud(env, wanted, now) {
158
+ try {
159
+ const { sessions, brokenAt } = scanPointers(env);
160
+ const { session, matches } = choose(sessions, wanted);
161
+ if (session === null) {
162
+ return {
163
+ wanted,
164
+ session: null,
165
+ status: null,
166
+ unreadable: brokenAt !== null ? ["session pointer"] : [],
167
+ matches,
168
+ };
169
+ }
170
+ const status = readCardStatus(session.id, env, now, { rollout: false });
171
+ const lastSeen = Math.min(now, session.activeAt);
172
+ // A broken pointer written after the chosen one may be the session the user is actually in.
173
+ const pointer = brokenAt !== null && brokenAt > session.pointerMtime ? ["session pointer"] : [];
174
+ const unreadable = [...pointer, ...unreadableRecords(session.cwd, session.id)];
175
+ return {
176
+ wanted,
177
+ session: { id: session.id, folder: tilde(session.cwd, env["HOME"]), lastSeen },
178
+ status,
179
+ unreadable,
180
+ };
181
+ }
182
+ catch {
183
+ return { wanted, session: null, status: null, unreadable: ["LIT records"] };
184
+ }
185
+ }
186
+ /** C0/C1 controls (ESC, CSI, BEL among them) plus zero-width and bidi format characters. */
187
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/gu;
188
+ export function clean(text) {
189
+ return text.replace(CONTROL, "");
190
+ }
191
+ /** The card with every record-derived string stripped of control characters. */
192
+ export function cleanStatus(status) {
193
+ return {
194
+ ...status,
195
+ mode: status.mode === null ? null : clean(status.mode),
196
+ step: status.step === null ? null : { ...status.step, tool: clean(status.step.tool) },
197
+ map: status.map === null ? null : { ...status.map, next: status.map.next === null ? null : clean(status.map.next) },
198
+ };
199
+ }
200
+ const MARK = /^\p{M}$/u;
201
+ const WIDE_EMOJI = /^\p{Emoji_Presentation}$/u;
202
+ function charWidth(char) {
203
+ const code = char.codePointAt(0) ?? 0;
204
+ if (MARK.test(char) || (code >= 0x200b && code <= 0x200f) || (code >= 0xfe00 && code <= 0xfe0f))
205
+ return 0;
206
+ if (WIDE_EMOJI.test(char))
207
+ return 2;
208
+ if ((code >= 0x1100 && code <= 0x115f) ||
209
+ (code >= 0x2e80 && code <= 0xa4cf) ||
210
+ (code >= 0xac00 && code <= 0xd7a3) ||
211
+ (code >= 0xf900 && code <= 0xfaff) ||
212
+ (code >= 0xfe30 && code <= 0xfe4f) ||
213
+ (code >= 0xff00 && code <= 0xff60) ||
214
+ (code >= 0xffe0 && code <= 0xffe6) ||
215
+ (code >= 0x20000 && code <= 0x3fffd))
216
+ return 2;
217
+ return 1;
218
+ }
219
+ /** The string as terminal cells; a narrow character followed by U+FE0F (emoji presentation) takes two. */
220
+ function cells(text) {
221
+ const out = [];
222
+ for (const char of text) {
223
+ const previous = out.at(-1);
224
+ if (char === "\ufe0f" && previous !== undefined) {
225
+ previous.text += char;
226
+ previous.width = Math.max(previous.width, 2);
227
+ continue;
228
+ }
229
+ out.push({ text: char, width: charWidth(char) });
230
+ }
231
+ return out;
232
+ }
233
+ /** Terminal cells a plain string takes: CJK and emoji take two, combining marks none. */
234
+ export function displayWidth(text) {
235
+ return cells(text).reduce((sum, cell) => sum + cell.width, 0);
236
+ }
237
+ /** The line cut to `width` terminal cells, ending in `…` when anything was cut. */
238
+ export function fit(line, width) {
239
+ if (displayWidth(line) <= width)
240
+ return line;
241
+ let out = "";
242
+ let used = 0;
243
+ for (const cell of cells(line)) {
244
+ if (used + cell.width > width - 1)
245
+ break;
246
+ out += cell.text;
247
+ used += cell.width;
248
+ }
249
+ return `${out}…`;
250
+ }
251
+ function age(lastSeen, now) {
252
+ const seconds = Math.max(0, Math.floor((now - lastSeen) / 1000));
253
+ if (now - lastSeen > LAST_SEEN_MS)
254
+ return `last seen ${Math.floor(seconds / 60)} min ago`;
255
+ return seconds < 60 ? `updated ${seconds}s ago` : `updated ${Math.floor(seconds / 60)} min ago`;
256
+ }
257
+ const BOLD = "\u001b[1m";
258
+ const DIM = "\u001b[2m";
259
+ const RESET = "\u001b[0m";
260
+ /** One frame as text: a header, the card, and at most one "cannot read" line. Pure. */
261
+ export function renderHud(view, options) {
262
+ const width = Math.max(10, Math.floor(options.width));
263
+ const lines = [];
264
+ if ((view.session === null || view.status === null) && view.wanted !== null && (view.matches ?? 0) > 1) {
265
+ lines.push({ text: "🔥 LIT · which session?", style: BOLD });
266
+ lines.push({
267
+ text: `--session ${clean(view.wanted)} matches ${view.matches} sessions; give more of the id`,
268
+ style: DIM,
269
+ });
270
+ }
271
+ else if (view.session === null || view.status === null) {
272
+ lines.push({ text: "🔥 LIT · waiting for a LIT session", style: BOLD });
273
+ lines.push({
274
+ text: view.wanted === null
275
+ ? "Start `codex` in a project and type `lit <task>`."
276
+ : `waiting for session ${clean(view.wanted)}`,
277
+ style: DIM,
278
+ });
279
+ }
280
+ else {
281
+ const { id, folder, lastSeen } = view.session;
282
+ lines.push({ text: `${id.slice(0, SHORT_ID)} · ${clean(folder)} · ${age(lastSeen, options.now)}`, style: DIM });
283
+ cardStatusText(cleanStatus(view.status))
284
+ .split("\n")
285
+ .forEach((text, index) => {
286
+ lines.push({ text, style: index === 0 ? BOLD : "" });
287
+ });
288
+ }
289
+ if (view.unreadable.length > 0)
290
+ lines.push({ text: `cannot read ${view.unreadable.join(", ")}`, style: DIM });
291
+ return lines
292
+ .map(({ text, style }) => {
293
+ const line = fit(clean(text), width);
294
+ return options.color && style !== "" ? `${style}${line}${RESET}` : line;
295
+ })
296
+ .join("\n");
297
+ }