@litfamily/litcodex 1.0.7 → 1.0.8

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 (25) hide show
  1. package/README.md +105 -71
  2. package/dist/install/doctor-render.js +1 -0
  3. package/dist/install/doctor.js +8 -0
  4. package/dist/install/types.d.ts +3 -0
  5. package/marketplace/plugins/litcodex/.codex-plugin/plugin.json +1 -1
  6. package/marketplace/plugins/litcodex/components/auto-update/package.json +1 -1
  7. package/marketplace/plugins/litcodex/components/comment-checker/package.json +1 -1
  8. package/marketplace/plugins/litcodex/components/git-bash/package.json +1 -1
  9. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.d.ts +8 -1
  10. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.js +36 -4
  11. package/marketplace/plugins/litcodex/components/lit-loop/dist/jev-hint.d.ts +112 -0
  12. package/marketplace/plugins/litcodex/components/lit-loop/dist/jev-hint.js +522 -0
  13. package/marketplace/plugins/litcodex/components/lit-loop/package.json +1 -1
  14. package/marketplace/plugins/litcodex/components/lsp/package.json +1 -1
  15. package/marketplace/plugins/litcodex/components/rules/package.json +1 -1
  16. package/marketplace/plugins/litcodex/components/start-work-continuation/package.json +1 -1
  17. package/marketplace/plugins/litcodex/components/telemetry/package.json +1 -1
  18. package/marketplace/plugins/litcodex/components/wikify-knowledge/package.json +1 -1
  19. package/node_modules/@litcodex/lit-loop/dist/hook-cli.d.ts +8 -1
  20. package/node_modules/@litcodex/lit-loop/dist/hook-cli.js +36 -4
  21. package/node_modules/@litcodex/lit-loop/dist/jev-hint.d.ts +112 -0
  22. package/node_modules/@litcodex/lit-loop/dist/jev-hint.js +522 -0
  23. package/node_modules/@litcodex/lit-loop/package.json +1 -1
  24. package/package.json +3 -3
  25. package/readme-assets/badge-version.svg +1 -1
@@ -0,0 +1,112 @@
1
+ export declare const JEV_FLAG_ENV = "LITCODEX_JEV";
2
+ export declare const JEV_KEY_ENV = "TYPESAFE_API_KEY";
3
+ export declare const JEV_ENDPOINT = "https://api.typesafe.ai/v1/systemone";
4
+ export declare const JEV_DEFAULT_MODEL = "jev-1.13.0";
5
+ export declare const JEV_DEFAULT_TIMEOUT_MS = 1500;
6
+ export declare const JEV_MAX_TIMEOUT_MS = 3000;
7
+ export declare const JEV_DEFAULT_MAX_CALLS = 200;
8
+ export declare const JEV_DEFAULT_MIN_CONFIDENCE = 0.35;
9
+ export declare const JEV_MAX_PROMPT_CHARS = 2000;
10
+ export declare const JEV_REDACTION_WINDOW_CHARS = 8000;
11
+ export declare const JEV_MAX_DESCRIPTION_CHARS = 300;
12
+ export declare const JEV_MAX_BODY_BYTES: number;
13
+ export declare const JEV_STATE_DIR = ".litcodex/jev";
14
+ export type JevSwitchState = "off" | "on" | "flag on but TYPESAFE_API_KEY missing";
15
+ /** The doctor/status state. Never reveals the key or its length. */
16
+ export declare function jevSwitchState(env: NodeJS.ProcessEnv): JevSwitchState;
17
+ /**
18
+ * Redact an 8,000-character window (home paths, e-mail addresses, the literal key and token-shaped
19
+ * strings, in that order), then cut to 2,000 characters. A run of 8 or more token characters left at
20
+ * the cut is part of something the cut split, so it becomes `[secret]` too.
21
+ */
22
+ export declare function redactJevPrompt(prompt: string, key?: string): string;
23
+ export interface JevCatalogEntry {
24
+ readonly id: string;
25
+ readonly description: string;
26
+ }
27
+ /** The installed plugin's `skills/` directory, resolved the same way the mode router finds bodies. */
28
+ export declare function defaultJevSkillsRoot(): string;
29
+ /**
30
+ * This plugin's own skills that the host may load on the model's initiative: every `skills/<id>/SKILL.md`
31
+ * whose frontmatter `name` equals its directory, minus skills whose `agents/openai.yaml` sets
32
+ * `allow_implicit_invocation: false` (those run only on an explicit user invocation).
33
+ */
34
+ export declare function loadJevCatalog(skillsRoot?: string): JevCatalogEntry[];
35
+ export type JevSkipReason = "slash-command" | "skill-mention" | "routed" | "too-short";
36
+ /** Why this turn gets no Jev request, or null when it is eligible. Pure. */
37
+ export declare function jevSkipReason(prompt: string, catalogIds?: ReadonlySet<string>): JevSkipReason | null;
38
+ export interface JevRequestBody {
39
+ readonly model: string;
40
+ readonly state: string;
41
+ readonly questions: {
42
+ readonly which: {
43
+ readonly type: "choice";
44
+ readonly instructions: string;
45
+ readonly criteria: Readonly<Record<string, string>>;
46
+ };
47
+ };
48
+ }
49
+ export declare function buildJevRequestBody(model: string, state: string, catalog: readonly JevCatalogEntry[]): JevRequestBody;
50
+ export type JevVerdict = {
51
+ readonly kind: "hint";
52
+ readonly skillId: string;
53
+ readonly confidence: number;
54
+ } | {
55
+ readonly kind: "none";
56
+ readonly confidence: number;
57
+ } | {
58
+ readonly kind: "low-confidence";
59
+ readonly choice: string;
60
+ readonly confidence: number;
61
+ } | {
62
+ readonly kind: "rejected";
63
+ };
64
+ /** Validate an already-parsed response against the ids that were sent. Nothing else is trusted. */
65
+ export declare function judgeJevResponse(parsed: unknown, catalogIds: ReadonlySet<string>, minConfidence: number): JevVerdict;
66
+ export declare function jevHintLine(skillId: string): string;
67
+ /** The opt-in (`LITCODEX_JEV_SHOW=1`) visible line for a hinted turn: skill id and latency only. */
68
+ export declare function jevShowLine(skillId: string, latencyMs: number): string;
69
+ /** Once-per-session awareness banner. Plain text: Codex renders hook systemMessage control characters literally. */
70
+ export declare const JEV_ON_BANNER = "\u2726 Jev skill hint ON";
71
+ export declare function jevFallbackNote(reason: string): string;
72
+ export interface JevHttpRequest {
73
+ readonly method: "POST";
74
+ readonly headers: Readonly<Record<string, string>>;
75
+ readonly body: string;
76
+ readonly signal: AbortSignal;
77
+ }
78
+ export interface JevHttpResponse {
79
+ readonly status: number;
80
+ text(): Promise<string>;
81
+ }
82
+ /** Injected in tests; the default uses the runtime's built-in `fetch`. */
83
+ export type JevHttpClient = (url: string, request: JevHttpRequest) => Promise<JevHttpResponse>;
84
+ export declare const fetchJevHttpClient: JevHttpClient;
85
+ export interface JevHintInput {
86
+ readonly prompt: string;
87
+ readonly sessionId: string | null;
88
+ readonly repoRoot: string;
89
+ readonly env: NodeJS.ProcessEnv;
90
+ readonly http?: JevHttpClient;
91
+ readonly skillsRoot?: string;
92
+ readonly now?: () => number;
93
+ }
94
+ /** A hint sets `additionalContext`, plus `systemMessage` only with `LITCODEX_JEV_SHOW=1`; a note sets `systemMessage`. */
95
+ export interface JevHintResult {
96
+ readonly additionalContext?: string;
97
+ readonly systemMessage?: string;
98
+ }
99
+ /**
100
+ * Decide the optional hint for one UserPromptSubmit turn. Never throws; every failure resolves to at
101
+ * most one visible fallback note per session and otherwise to nothing.
102
+ */
103
+ export declare function runJevSkillHint(input: JevHintInput): Promise<JevHintResult>;
104
+ /**
105
+ * The once-per-session banner, or null. Only when the hint is fully on (flag and key); it is claimed in
106
+ * the session state before it is shown, so a state write failure shows nothing rather than repeating.
107
+ */
108
+ export declare function claimJevOnBanner(repoRoot: string, sessionId: string | null, env: NodeJS.ProcessEnv): string | null;
109
+ /** Put the banner (when claimed) on its own line ahead of any other visible Jev line. */
110
+ export declare function withJevBanner(result: JevHintResult, banner: string | null): JevHintResult;
111
+ /** Codex UserPromptSubmit output for a hint and/or visible line; "" when there is nothing to say. */
112
+ export declare function formatJevHookOutput(result: JevHintResult): string;
@@ -0,0 +1,522 @@
1
+ // src/jev-hint.ts — optional Jev skill hint for the UserPromptSubmit hook.
2
+ //
3
+ // Off by default. Active only when `LITCODEX_JEV=1` AND a non-empty `TYPESAFE_API_KEY` are both in
4
+ // the hook's environment. On an eligible turn (not a slash command, not an explicit `$skill` mention,
5
+ // not already routed by the deterministic lit router, at least 4 non-space characters) it sends the
6
+ // redacted, truncated prompt text to Jev with one Choice question over this plugin's own implicitly
7
+ // invocable skills, and returns at most one fixed advisory sentence naming a validated skill id.
8
+ //
9
+ // The response is untrusted: only an exact catalog id (or `none`) with a numeric confidence at or
10
+ // above the threshold is accepted, and no response text ever reaches the model context. Every
11
+ // failure falls back to today's behavior, with one short visible note per session. With
12
+ // `LITCODEX_JEV_SHOW=1` as well, a hinted turn also shows one visible line naming the skill id and
13
+ // latency. Whenever the hint is on, the first prompt of each session the router leaves alone also shows
14
+ // a once-per-session plain-text banner (`JEV_ON_BANNER`). The key is read from the environment only and is never written to output, errors, state,
15
+ // or the trace.
16
+ import { createHash, randomBytes } from "node:crypto";
17
+ import { closeSync, constants, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, unlinkSync, writeSync, } from "node:fs";
18
+ import { dirname, isAbsolute, join } from "node:path";
19
+ import { isExactBrowserDrivePrompt } from "./browser-drive-route.js";
20
+ import { isExactBareHandoffPrompt } from "./handoff-route.js";
21
+ import { resolveSkillPath } from "./modes.js";
22
+ import { isExactBareScientificVisualizationPrompt } from "./scientific-visualization-route.js";
23
+ import { matchRenamedSkillInvocation } from "./skill-renames.js";
24
+ import { normalizeSessionId } from "./state-paths.js";
25
+ import { maskMarkdownCode, matchLitTrigger } from "./trigger.js";
26
+ export const JEV_FLAG_ENV = "LITCODEX_JEV";
27
+ export const JEV_KEY_ENV = "TYPESAFE_API_KEY";
28
+ export const JEV_ENDPOINT = "https://api.typesafe.ai/v1/systemone";
29
+ export const JEV_DEFAULT_MODEL = "jev-1.13.0";
30
+ export const JEV_DEFAULT_TIMEOUT_MS = 1_500;
31
+ export const JEV_MAX_TIMEOUT_MS = 3_000;
32
+ export const JEV_DEFAULT_MAX_CALLS = 200;
33
+ export const JEV_DEFAULT_MIN_CONFIDENCE = 0.35;
34
+ export const JEV_MAX_PROMPT_CHARS = 2_000;
35
+ export const JEV_REDACTION_WINDOW_CHARS = 8_000;
36
+ export const JEV_MAX_DESCRIPTION_CHARS = 300;
37
+ export const JEV_MAX_BODY_BYTES = 64 * 1024;
38
+ export const JEV_STATE_DIR = ".litcodex/jev";
39
+ const QUESTION_INSTRUCTIONS = "Which one skill, if any, is the best fit for the user's request? Choose none when no catalog skill fits.";
40
+ const NONE_CRITERION = "No specialized skill in this catalog fits; answer the user directly.";
41
+ const SKILL_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
42
+ const FRONTMATTER_READ_BYTES = 16 * 1024;
43
+ /** The doctor/status state. Never reveals the key or its length. */
44
+ export function jevSwitchState(env) {
45
+ if (env[JEV_FLAG_ENV] !== "1")
46
+ return "off";
47
+ return (env[JEV_KEY_ENV]?.trim() ?? "") !== "" ? "on" : "flag on but TYPESAFE_API_KEY missing";
48
+ }
49
+ // ── Redaction ────────────────────────────────────────────────────────────────
50
+ // The user name runs to the next separator and never ends in a dot, so `/Users/alice.` keeps its full stop.
51
+ const HOME_PATHS = [
52
+ /\/(?:Users|home)\/[^/\\\s,;:"'`()[\]<>{}]*[^/\\\s,;:"'`()[\]<>{}.](\/)?/g,
53
+ /[A-Za-z]:\\Users\\[^/\\\s,;:"'`()[\]<>{}]*[^/\\\s,;:"'`()[\]<>{}.](\\)?/gi,
54
+ ];
55
+ const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g;
56
+ const TOKEN_SHAPES = [
57
+ /-----BEGIN [A-Z0-9 ]+-----[\s\S]*?(?:-----END [A-Z0-9 ]+-----|$)/g,
58
+ /\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]*)?/g,
59
+ /\bsk-ant-[A-Za-z0-9_-]{8,}/g,
60
+ /\bsk-[A-Za-z0-9_-]{16,}/g,
61
+ /\bgh[op]_[A-Za-z0-9]{16,}/g,
62
+ /\bgithub_pat_[A-Za-z0-9_]{16,}/g,
63
+ /\bnpm_[A-Za-z0-9]{16,}/g,
64
+ /\bapikey_[A-Za-z0-9_-]{8,}/gi,
65
+ /\bxox[abprs]-[A-Za-z0-9-]{8,}/g,
66
+ /\bAKIA[A-Z0-9]{16}\b/g,
67
+ /\bAIza[A-Za-z0-9_-]{20,}/g,
68
+ /[A-Za-z0-9+/_-]{32,}={0,2}/g,
69
+ ];
70
+ const TRAILING_TOKEN_RUN = /[A-Za-z0-9+/_-]{8,}={0,2}$/;
71
+ /**
72
+ * Redact an 8,000-character window (home paths, e-mail addresses, the literal key and token-shaped
73
+ * strings, in that order), then cut to 2,000 characters. A run of 8 or more token characters left at
74
+ * the cut is part of something the cut split, so it becomes `[secret]` too.
75
+ */
76
+ export function redactJevPrompt(prompt, key = "") {
77
+ let text = Array.from(prompt).slice(0, JEV_REDACTION_WINDOW_CHARS).join("");
78
+ for (const pattern of HOME_PATHS)
79
+ text = text.replace(pattern, (_match, separator) => (separator ? "~/" : "~"));
80
+ text = text.replace(EMAIL, "[email]");
81
+ if (key !== "")
82
+ text = text.split(key).join("[secret]");
83
+ for (const pattern of TOKEN_SHAPES)
84
+ text = text.replace(pattern, "[secret]");
85
+ const chars = Array.from(text);
86
+ if (chars.length <= JEV_MAX_PROMPT_CHARS)
87
+ return text;
88
+ return chars.slice(0, JEV_MAX_PROMPT_CHARS).join("").replace(TRAILING_TOKEN_RUN, "[secret]");
89
+ }
90
+ /** The installed plugin's `skills/` directory, resolved the same way the mode router finds bodies. */
91
+ export function defaultJevSkillsRoot() {
92
+ return dirname(dirname(resolveSkillPath("lit-loop")));
93
+ }
94
+ function readHead(path) {
95
+ let fd;
96
+ try {
97
+ fd = openSync(path, "r");
98
+ const buffer = Buffer.alloc(FRONTMATTER_READ_BYTES);
99
+ const read = readSync(fd, buffer, 0, buffer.length, 0);
100
+ return buffer.subarray(0, read).toString("utf8");
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ finally {
106
+ if (fd !== undefined)
107
+ closeSync(fd);
108
+ }
109
+ }
110
+ function frontmatterValue(raw) {
111
+ const value = raw.trim();
112
+ if (value.startsWith('"') && value.endsWith('"') && value.length >= 2) {
113
+ try {
114
+ const parsed = JSON.parse(value);
115
+ if (typeof parsed === "string")
116
+ return parsed;
117
+ }
118
+ catch {
119
+ return value.slice(1, -1);
120
+ }
121
+ }
122
+ if (value.startsWith("'") && value.endsWith("'") && value.length >= 2)
123
+ return value.slice(1, -1).replace(/''/g, "'");
124
+ return value;
125
+ }
126
+ function readFrontmatter(text) {
127
+ const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
128
+ if (match?.[1] === undefined)
129
+ return {};
130
+ const out = {};
131
+ for (const line of match[1].split(/\r?\n/)) {
132
+ const field = /^(name|description):\s*(.*)$/.exec(line);
133
+ if (field?.[1] === "name" && field[2] !== undefined)
134
+ out.name = frontmatterValue(field[2]);
135
+ if (field?.[1] === "description" && field[2] !== undefined)
136
+ out.description = frontmatterValue(field[2]);
137
+ }
138
+ return out;
139
+ }
140
+ function implicitInvocationDisabled(skillDir) {
141
+ try {
142
+ return /^\s*allow_implicit_invocation:\s*false\s*$/m.test(readFileSync(join(skillDir, "agents", "openai.yaml"), "utf8"));
143
+ }
144
+ catch {
145
+ return false;
146
+ }
147
+ }
148
+ /**
149
+ * This plugin's own skills that the host may load on the model's initiative: every `skills/<id>/SKILL.md`
150
+ * whose frontmatter `name` equals its directory, minus skills whose `agents/openai.yaml` sets
151
+ * `allow_implicit_invocation: false` (those run only on an explicit user invocation).
152
+ */
153
+ export function loadJevCatalog(skillsRoot = defaultJevSkillsRoot()) {
154
+ let names;
155
+ try {
156
+ names = readdirSync(skillsRoot).sort();
157
+ }
158
+ catch {
159
+ return [];
160
+ }
161
+ const catalog = [];
162
+ for (const id of names) {
163
+ if (!SKILL_ID.test(id) || id === "none")
164
+ continue;
165
+ const head = readHead(join(skillsRoot, id, "SKILL.md"));
166
+ if (head === null)
167
+ continue;
168
+ const frontmatter = readFrontmatter(head);
169
+ const description = frontmatter.description?.trim() ?? "";
170
+ if (frontmatter.name !== id || description === "")
171
+ continue;
172
+ if (implicitInvocationDisabled(join(skillsRoot, id)))
173
+ continue;
174
+ catalog.push({ id, description: Array.from(description).slice(0, JEV_MAX_DESCRIPTION_CHARS).join("") });
175
+ }
176
+ return catalog;
177
+ }
178
+ /** Why this turn gets no Jev request, or null when it is eligible. Pure. */
179
+ export function jevSkipReason(prompt, catalogIds = new Set()) {
180
+ if (/^\s*\//u.test(prompt))
181
+ return "slash-command";
182
+ for (const mention of prompt.matchAll(/(?:^|\s)\$([A-Za-z0-9_-]+)(:[A-Za-z0-9_-]+)?/gu)) {
183
+ if (mention[2] !== undefined || catalogIds.has((mention[1] ?? "").toLowerCase()))
184
+ return "skill-mention";
185
+ }
186
+ if (matchLitTrigger(prompt) !== null ||
187
+ matchRenamedSkillInvocation(maskMarkdownCode(prompt), Number.POSITIVE_INFINITY) !== null ||
188
+ isExactBareHandoffPrompt(prompt) ||
189
+ isExactBareScientificVisualizationPrompt(prompt) ||
190
+ isExactBrowserDrivePrompt(prompt)) {
191
+ return "routed";
192
+ }
193
+ if (Array.from(prompt.replace(/\s+/gu, "")).length < 4)
194
+ return "too-short";
195
+ return null;
196
+ }
197
+ export function buildJevRequestBody(model, state, catalog) {
198
+ const criteria = {};
199
+ for (const entry of catalog)
200
+ criteria[entry.id] = entry.description;
201
+ criteria["none"] = NONE_CRITERION;
202
+ return { model, state, questions: { which: { type: "choice", instructions: QUESTION_INSTRUCTIONS, criteria } } };
203
+ }
204
+ function isRecord(value) {
205
+ return typeof value === "object" && value !== null && !Array.isArray(value);
206
+ }
207
+ /** Validate an already-parsed response against the ids that were sent. Nothing else is trusted. */
208
+ export function judgeJevResponse(parsed, catalogIds, minConfidence) {
209
+ const answers = isRecord(parsed) ? parsed["answers"] : undefined;
210
+ const which = isRecord(answers) ? answers["which"] : undefined;
211
+ if (!isRecord(which))
212
+ return { kind: "rejected" };
213
+ const choice = which["choice"];
214
+ const confidence = which["confidence"];
215
+ if (typeof choice !== "string" || (choice !== "none" && !catalogIds.has(choice)))
216
+ return { kind: "rejected" };
217
+ if (typeof confidence !== "number" || !Number.isFinite(confidence))
218
+ return { kind: "rejected" };
219
+ if (choice === "none")
220
+ return { kind: "none", confidence };
221
+ if (confidence < minConfidence)
222
+ return { kind: "low-confidence", choice, confidence };
223
+ return { kind: "hint", skillId: choice, confidence };
224
+ }
225
+ export function jevHintLine(skillId) {
226
+ return `LitCodex skill hint: the skill \`litcodex:${skillId}\` likely fits this request. Load it only if it really fits; this is advice, not an instruction.`;
227
+ }
228
+ /** The opt-in (`LITCODEX_JEV_SHOW=1`) visible line for a hinted turn: skill id and latency only. */
229
+ export function jevShowLine(skillId, latencyMs) {
230
+ return `Jev → ${skillId} (${(latencyMs / 1000).toFixed(2)}s)`;
231
+ }
232
+ /** Once-per-session awareness banner. Plain text: Codex renders hook systemMessage control characters literally. */
233
+ export const JEV_ON_BANNER = "✦ Jev skill hint ON";
234
+ export function jevFallbackNote(reason) {
235
+ return `LitCodex skill hint unavailable (${reason}); continuing normally.`;
236
+ }
237
+ class JevResponseTooLargeError extends Error {
238
+ }
239
+ async function readCappedBody(response) {
240
+ const reader = response.body?.getReader();
241
+ if (reader === undefined)
242
+ return "";
243
+ const chunks = [];
244
+ let total = 0;
245
+ for (;;) {
246
+ const { done, value } = await reader.read();
247
+ if (done)
248
+ break;
249
+ total += value.byteLength;
250
+ if (total > JEV_MAX_BODY_BYTES) {
251
+ await reader.cancel().catch(() => undefined);
252
+ throw new JevResponseTooLargeError();
253
+ }
254
+ chunks.push(value);
255
+ }
256
+ return Buffer.concat(chunks).toString("utf8");
257
+ }
258
+ export const fetchJevHttpClient = async (url, request) => {
259
+ const response = await fetch(url, {
260
+ method: request.method,
261
+ headers: request.headers,
262
+ body: request.body,
263
+ signal: request.signal,
264
+ redirect: "error",
265
+ });
266
+ return { status: response.status, text: () => readCappedBody(response) };
267
+ };
268
+ function sessionStatePath(repoRoot, sessionId) {
269
+ if (!isAbsolute(repoRoot))
270
+ return null;
271
+ return join(repoRoot, JEV_STATE_DIR, `${normalizeSessionId(sessionId) ?? "unscoped"}.json`);
272
+ }
273
+ function readSessionState(path) {
274
+ try {
275
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
276
+ if (isRecord(parsed) && typeof parsed["calls"] === "number" && typeof parsed["noted"] === "boolean") {
277
+ return { version: 1, calls: parsed["calls"], noted: parsed["noted"], announced: parsed["announced"] === true };
278
+ }
279
+ }
280
+ catch {
281
+ // Missing or malformed state starts a fresh session record.
282
+ }
283
+ return { version: 1, calls: 0, noted: false, announced: false };
284
+ }
285
+ const NO_FOLLOW = constants.O_NOFOLLOW ?? 0;
286
+ /**
287
+ * Create `.litcodex/jev` one level at a time. False when either level is a symlink or not a directory,
288
+ * so a checked-in link can never redirect state or trace writes elsewhere.
289
+ */
290
+ function ensureStateDir(dir) {
291
+ for (const level of [dirname(dir), dir]) {
292
+ try {
293
+ if (!lstatSync(level).isDirectory())
294
+ return false;
295
+ }
296
+ catch {
297
+ try {
298
+ mkdirSync(level);
299
+ }
300
+ catch {
301
+ return false;
302
+ }
303
+ }
304
+ }
305
+ return true;
306
+ }
307
+ /** False when `path` exists as anything but a regular file (a symlink included). */
308
+ function isRegularOrAbsent(path) {
309
+ return lstatSync(path, { throwIfNoEntry: false })?.isFile() ?? true;
310
+ }
311
+ function writeSessionState(path, state) {
312
+ if (!ensureStateDir(dirname(path)))
313
+ return false;
314
+ const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
315
+ try {
316
+ if (!isRegularOrAbsent(path))
317
+ return false;
318
+ const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | NO_FOLLOW);
319
+ try {
320
+ writeSync(fd, `${JSON.stringify(state)}\n`);
321
+ }
322
+ finally {
323
+ closeSync(fd);
324
+ }
325
+ renameSync(tmp, path);
326
+ return true;
327
+ }
328
+ catch {
329
+ try {
330
+ unlinkSync(tmp);
331
+ }
332
+ catch {
333
+ // Nothing was created.
334
+ }
335
+ return false;
336
+ }
337
+ }
338
+ function writeTrace(repoRoot, env, now, record) {
339
+ if (env[`${JEV_FLAG_ENV}_TRACE`] !== "1" || !isAbsolute(repoRoot))
340
+ return;
341
+ try {
342
+ const path = join(repoRoot, JEV_STATE_DIR, "trace.jsonl");
343
+ if (!ensureStateDir(dirname(path)) || !isRegularOrAbsent(path))
344
+ return;
345
+ const fd = openSync(path, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | NO_FOLLOW);
346
+ try {
347
+ writeSync(fd, `${JSON.stringify({ ts: new Date(now()).toISOString(), ...record })}\n`);
348
+ }
349
+ finally {
350
+ closeSync(fd);
351
+ }
352
+ }
353
+ catch {
354
+ // The trace is an optional debug aid; a write failure never affects the turn.
355
+ }
356
+ }
357
+ // ── Settings ─────────────────────────────────────────────────────────────────
358
+ function positiveInt(raw, fallback) {
359
+ const value = raw === undefined ? Number.NaN : Number(raw.trim());
360
+ return Number.isInteger(value) && value > 0 ? value : fallback;
361
+ }
362
+ function nonNegativeInt(raw, fallback) {
363
+ const value = raw === undefined || raw.trim() === "" ? Number.NaN : Number(raw.trim());
364
+ return Number.isInteger(value) && value >= 0 ? value : fallback;
365
+ }
366
+ function unitInterval(raw, fallback) {
367
+ const value = raw === undefined || raw.trim() === "" ? Number.NaN : Number(raw.trim());
368
+ return Number.isFinite(value) && value >= 0 && value <= 1 ? value : fallback;
369
+ }
370
+ function modelName(raw) {
371
+ const value = raw?.trim() ?? "";
372
+ return /^[A-Za-z0-9._:-]{1,64}$/.test(value) ? value : JEV_DEFAULT_MODEL;
373
+ }
374
+ const NOTHING = Object.freeze({});
375
+ async function exchange(http, key, body, timeoutMs) {
376
+ const controller = new AbortController();
377
+ let timer;
378
+ const timeout = new Promise((resolve) => {
379
+ timer = setTimeout(() => {
380
+ controller.abort();
381
+ resolve({ kind: "failed", reason: "timeout" });
382
+ }, timeoutMs);
383
+ });
384
+ const call = (async () => {
385
+ try {
386
+ const response = await http(JEV_ENDPOINT, {
387
+ method: "POST",
388
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/json", accept: "application/json" },
389
+ body,
390
+ signal: controller.signal,
391
+ });
392
+ if (response.status !== 200)
393
+ return { kind: "response", status: response.status, body: null };
394
+ const text = await response.text();
395
+ if (Buffer.byteLength(text, "utf8") > JEV_MAX_BODY_BYTES)
396
+ return { kind: "failed", reason: "response-too-large" };
397
+ return { kind: "response", status: 200, body: text };
398
+ }
399
+ catch (error) {
400
+ if (controller.signal.aborted)
401
+ return { kind: "failed", reason: "timeout" };
402
+ return {
403
+ kind: "failed",
404
+ reason: error instanceof JevResponseTooLargeError ? "response-too-large" : "network",
405
+ };
406
+ }
407
+ })();
408
+ try {
409
+ return await Promise.race([call, timeout]);
410
+ }
411
+ finally {
412
+ clearTimeout(timer);
413
+ }
414
+ }
415
+ /**
416
+ * Decide the optional hint for one UserPromptSubmit turn. Never throws; every failure resolves to at
417
+ * most one visible fallback note per session and otherwise to nothing.
418
+ */
419
+ export async function runJevSkillHint(input) {
420
+ const { env, repoRoot } = input;
421
+ const now = input.now ?? Date.now;
422
+ const switchState = jevSwitchState(env);
423
+ if (switchState === "off")
424
+ return NOTHING;
425
+ if (jevSkipReason(input.prompt) !== null)
426
+ return NOTHING;
427
+ const statePath = sessionStatePath(repoRoot, input.sessionId);
428
+ if (statePath === null)
429
+ return NOTHING;
430
+ const session = readSessionState(statePath);
431
+ const fail = (reason, record) => {
432
+ writeTrace(repoRoot, env, now, { ...record, fallback: reason });
433
+ if (session.noted)
434
+ return NOTHING;
435
+ const current = readSessionState(statePath);
436
+ if (!writeSessionState(statePath, { ...current, noted: true }))
437
+ return NOTHING;
438
+ return { systemMessage: jevFallbackNote(reason) };
439
+ };
440
+ const blank = { promptSha256: "", choice: null, confidence: null, latencyMs: null, httpStatus: null };
441
+ const catalog = loadJevCatalog(input.skillsRoot);
442
+ const catalogIds = new Set(catalog.map((entry) => entry.id));
443
+ if (jevSkipReason(input.prompt, catalogIds) !== null)
444
+ return NOTHING;
445
+ if (switchState !== "on")
446
+ return fail("key-missing", blank);
447
+ if (catalog.length === 0)
448
+ return fail("catalog-unavailable", blank);
449
+ if (session.calls >= nonNegativeInt(env[`${JEV_FLAG_ENV}_MAX_CALLS`], JEV_DEFAULT_MAX_CALLS)) {
450
+ return fail("cap-reached", blank);
451
+ }
452
+ const key = env[JEV_KEY_ENV]?.trim() ?? "";
453
+ const state = redactJevPrompt(input.prompt, key);
454
+ const promptSha256 = createHash("sha256").update(state).digest("hex");
455
+ const body = JSON.stringify(buildJevRequestBody(modelName(env[`${JEV_FLAG_ENV}_MODEL`]), state, catalog));
456
+ if (Buffer.byteLength(body, "utf8") > JEV_MAX_BODY_BYTES)
457
+ return fail("request-too-large", { ...blank, promptSha256 });
458
+ // Count the call before sending it, so a state write failure can never lift the per-session cap.
459
+ if (!writeSessionState(statePath, { ...session, calls: session.calls + 1 }))
460
+ return NOTHING;
461
+ const timeoutMs = Math.min(positiveInt(env[`${JEV_FLAG_ENV}_TIMEOUT_MS`], JEV_DEFAULT_TIMEOUT_MS), JEV_MAX_TIMEOUT_MS);
462
+ const started = now();
463
+ const result = await exchange(input.http ?? fetchJevHttpClient, key, body, timeoutMs);
464
+ const latencyMs = Math.max(0, now() - started);
465
+ const sent = { ...blank, promptSha256, latencyMs };
466
+ if (result.kind === "failed")
467
+ return fail(result.reason, sent);
468
+ if (result.status !== 200 || result.body === null) {
469
+ return fail(`http-${result.status}`, { ...sent, httpStatus: result.status });
470
+ }
471
+ let parsed;
472
+ try {
473
+ parsed = JSON.parse(result.body);
474
+ }
475
+ catch {
476
+ return fail("invalid-json", { ...sent, httpStatus: 200 });
477
+ }
478
+ const minConfidence = unitInterval(env[`${JEV_FLAG_ENV}_MIN_CONFIDENCE`], JEV_DEFAULT_MIN_CONFIDENCE);
479
+ const verdict = judgeJevResponse(parsed, catalogIds, minConfidence);
480
+ const choice = verdict.kind === "hint" ? verdict.skillId : verdict.kind === "none" ? "none" : null;
481
+ const confidence = verdict.kind === "rejected" ? null : verdict.confidence;
482
+ writeTrace(repoRoot, env, now, { ...sent, httpStatus: 200, choice, confidence, fallback: null });
483
+ if (verdict.kind !== "hint")
484
+ return NOTHING;
485
+ const additionalContext = jevHintLine(verdict.skillId);
486
+ if (env[`${JEV_FLAG_ENV}_SHOW`] !== "1")
487
+ return { additionalContext };
488
+ return { additionalContext, systemMessage: jevShowLine(verdict.skillId, latencyMs) };
489
+ }
490
+ /**
491
+ * The once-per-session banner, or null. Only when the hint is fully on (flag and key); it is claimed in
492
+ * the session state before it is shown, so a state write failure shows nothing rather than repeating.
493
+ */
494
+ export function claimJevOnBanner(repoRoot, sessionId, env) {
495
+ if (jevSwitchState(env) !== "on")
496
+ return null;
497
+ const statePath = sessionStatePath(repoRoot, sessionId);
498
+ if (statePath === null)
499
+ return null;
500
+ const session = readSessionState(statePath);
501
+ if (session.announced)
502
+ return null;
503
+ return writeSessionState(statePath, { ...session, announced: true }) ? JEV_ON_BANNER : null;
504
+ }
505
+ /** Put the banner (when claimed) on its own line ahead of any other visible Jev line. */
506
+ export function withJevBanner(result, banner) {
507
+ if (banner === null)
508
+ return result;
509
+ const systemMessage = result.systemMessage === undefined ? banner : `${banner}\n${result.systemMessage}`;
510
+ return { ...result, systemMessage };
511
+ }
512
+ /** Codex UserPromptSubmit output for a hint and/or visible line; "" when there is nothing to say. */
513
+ export function formatJevHookOutput(result) {
514
+ if (result.additionalContext === undefined && result.systemMessage === undefined)
515
+ return "";
516
+ return `${JSON.stringify({
517
+ ...(result.systemMessage === undefined ? {} : { systemMessage: result.systemMessage }),
518
+ ...(result.additionalContext === undefined
519
+ ? {}
520
+ : { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: result.additionalContext } }),
521
+ })}\n`;
522
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/lit-loop",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "LitCodex Lit-Loop runtime: durable repo-native multi-goal orchestration with embedded success criteria and observable evidence audit.",
5
5
  "type": "module",
6
6
  "private": true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litfamily/litcodex",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "Codex loop harness installer. Run `npm exec --package @litfamily/litcodex -- litcodex install` to set up the LitCodex Codex platform: the bare `lit` hook and the durable lit-loop runtime.",
5
5
  "keywords": [
6
6
  "codex",
@@ -43,7 +43,7 @@
43
43
  "readme-assets"
44
44
  ],
45
45
  "dependencies": {
46
- "@litcodex/lit-loop": "1.0.7"
46
+ "@litcodex/lit-loop": "1.0.8"
47
47
  },
48
48
  "bundledDependencies": [
49
49
  "@litcodex/lit-loop"
@@ -54,7 +54,7 @@
54
54
  "typecheck": "tsc --noEmit",
55
55
  "test": "vitest --run --passWithNoTests=false",
56
56
  "postinstall": "node dist/postinstall.js",
57
- "prepublishOnly": "npm --prefix ../.. run check:brand-history && npm --prefix ../.. run release:check",
57
+ "prepublishOnly": "npm --prefix ../.. run release:check",
58
58
  "prepack": "node ../../scripts/prepack-bundle-component.mjs",
59
59
  "postpack": "node ../../scripts/postpack-clean-component.mjs"
60
60
  },
@@ -1 +1 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" width="146" height="20" role="img" aria-label="release: 1.0.7"><title>release: 1.0.7</title><g shape-rendering="crispEdges"><rect width="49" height="20" fill="#080d14"/><rect x="49" width="97" height="20" fill="#ff6337"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text x="255" y="140" textLength="390" transform="scale(.1)">release</text><text x="965" y="140" textLength="870" transform="scale(.1)" fill="#080D14">1.0.7</text></g></svg>
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="146" height="20" role="img" aria-label="release: 1.0.8"><title>release: 1.0.8</title><g shape-rendering="crispEdges"><rect width="49" height="20" fill="#080d14"/><rect x="49" width="97" height="20" fill="#ff6337"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text x="255" y="140" textLength="390" transform="scale(.1)">release</text><text x="965" y="140" textLength="870" transform="scale(.1)" fill="#080D14">1.0.8</text></g></svg>