@v1nvn/agentic-core 0.35.0 → 0.36.0
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.md +2 -3
- package/dist/index.js +31 -83
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/cli.ts +0 -30
- package/src/index.ts +0 -1
- package/src/input.ts +1 -1
- package/src/last-reply.ts +7 -1
- package/src/hook.ts +0 -56
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# @v1nvn/agentic-core
|
|
2
2
|
|
|
3
|
-
The shared runtime of the `@v1nvn` agent tools: transcript reading, CLI
|
|
4
|
-
|
|
3
|
+
The shared runtime of the `@v1nvn` agent tools: transcript reading, CLI
|
|
4
|
+
plumbing, logging, and the MCP server lifecycle helpers. A library — no
|
|
5
5
|
bin, not directly runnable; every other package consumes it as a workspace
|
|
6
6
|
dependency.
|
|
7
7
|
|
|
@@ -14,7 +14,6 @@ User-facing docs: [root README](../../README.md).
|
|
|
14
14
|
| `src/last-reply.ts` | finds the previous assistant reply across local Claude Code transcripts |
|
|
15
15
|
| `src/input.ts` | stdin and markdown-file input with the CLI error contracts |
|
|
16
16
|
| `src/cli.ts` | quiet commander parsing and usage/exit helpers shared by the tool bins |
|
|
17
|
-
| `src/hook.ts` | the `UserPromptExpansion` hook plumbing the zero-token plugins ride |
|
|
18
17
|
| `src/logger.ts` | level-filtered stderr logger for the MCP servers |
|
|
19
18
|
| `src/shutdown.ts` | close-then-exit signal handling for the server entrypoints |
|
|
20
19
|
| `src/dev.ts` | the hot-reload watcher wiring the servers' `yarn dev` harnesses share |
|
package/dist/index.js
CHANGED
|
@@ -1,70 +1,6 @@
|
|
|
1
1
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
-
//#region src/input.ts
|
|
5
|
-
function readAll(stream) {
|
|
6
|
-
return new Promise((resolve, reject) => {
|
|
7
|
-
let data = "";
|
|
8
|
-
stream.setEncoding("utf8");
|
|
9
|
-
stream.on("data", (chunk) => {
|
|
10
|
-
data += chunk;
|
|
11
|
-
});
|
|
12
|
-
stream.on("end", () => {
|
|
13
|
-
resolve(data);
|
|
14
|
-
});
|
|
15
|
-
stream.on("error", reject);
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
function readStdin(stream = process.stdin) {
|
|
19
|
-
return readAll(stream);
|
|
20
|
-
}
|
|
21
|
-
/** A markdown file's contents, with the CLI's no-such-file error. */
|
|
22
|
-
function readMarkdownFile(path) {
|
|
23
|
-
if (!statSync(path, { throwIfNoEntry: false })?.isFile()) throw new Error(`no such file: ${path}`);
|
|
24
|
-
return readFileSync(path, "utf8");
|
|
25
|
-
}
|
|
26
|
-
//#endregion
|
|
27
|
-
//#region src/hook.ts
|
|
28
|
-
/**
|
|
29
|
-
* Read the Claude Code hook event JSON from stdin; empty or unparseable input
|
|
30
|
-
* yields an empty event, never a thrown error — a hook must always answer.
|
|
31
|
-
*/
|
|
32
|
-
function readHookEvent(stream = process.stdin) {
|
|
33
|
-
return readAll(stream).then((data) => {
|
|
34
|
-
try {
|
|
35
|
-
return JSON.parse(data);
|
|
36
|
-
} catch {
|
|
37
|
-
return {};
|
|
38
|
-
}
|
|
39
|
-
}, () => ({}));
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Which transcript lastReply should read, per the hook event: transcript_path
|
|
43
|
-
* when it names a real file, else session_id, else nothing (lastReply then
|
|
44
|
-
* falls back to the newest session for the current project).
|
|
45
|
-
*/
|
|
46
|
-
function replyTarget(event) {
|
|
47
|
-
if (event.transcript_path !== void 0 && isFile(event.transcript_path)) return event.transcript_path;
|
|
48
|
-
return event.session_id || void 0;
|
|
49
|
-
}
|
|
50
|
-
function isFile(path) {
|
|
51
|
-
try {
|
|
52
|
-
return statSync(path).isFile();
|
|
53
|
-
} catch {
|
|
54
|
-
return false;
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Print the UserPromptExpansion decision for a zero-token command: `block`
|
|
59
|
-
* keeps the command from reaching the model, with the output as the `reason`.
|
|
60
|
-
*/
|
|
61
|
-
function emitHookBlock(reason) {
|
|
62
|
-
process.stdout.write(`${JSON.stringify({
|
|
63
|
-
decision: "block",
|
|
64
|
-
reason
|
|
65
|
-
})}\n`);
|
|
66
|
-
}
|
|
67
|
-
//#endregion
|
|
68
4
|
//#region src/cli.ts
|
|
69
5
|
function parseQuietly(program, args, recover) {
|
|
70
6
|
try {
|
|
@@ -81,24 +17,6 @@ function printUsageAndExit(program) {
|
|
|
81
17
|
console.error(program.helpInformation());
|
|
82
18
|
process.exit(1);
|
|
83
19
|
}
|
|
84
|
-
async function hookOrPrint(hook, failure, run, stdin = process.stdin) {
|
|
85
|
-
if (hook) {
|
|
86
|
-
let reason;
|
|
87
|
-
try {
|
|
88
|
-
reason = await run(await readHookEvent(stdin));
|
|
89
|
-
} catch (e) {
|
|
90
|
-
reason = `${failure}: ${e.message}`;
|
|
91
|
-
}
|
|
92
|
-
emitHookBlock(reason);
|
|
93
|
-
return;
|
|
94
|
-
}
|
|
95
|
-
try {
|
|
96
|
-
console.log(await run(void 0));
|
|
97
|
-
} catch (e) {
|
|
98
|
-
console.error(e.message);
|
|
99
|
-
process.exit(1);
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
20
|
//#endregion
|
|
103
21
|
//#region src/dev.ts
|
|
104
22
|
var RELOAD_DEBOUNCE_MS = 150;
|
|
@@ -128,7 +46,37 @@ function watchWithReload(vite, reload) {
|
|
|
128
46
|
});
|
|
129
47
|
}
|
|
130
48
|
//#endregion
|
|
49
|
+
//#region src/input.ts
|
|
50
|
+
function readAll(stream) {
|
|
51
|
+
return new Promise((resolve, reject) => {
|
|
52
|
+
let data = "";
|
|
53
|
+
stream.setEncoding("utf8");
|
|
54
|
+
stream.on("data", (chunk) => {
|
|
55
|
+
data += chunk;
|
|
56
|
+
});
|
|
57
|
+
stream.on("end", () => {
|
|
58
|
+
resolve(data);
|
|
59
|
+
});
|
|
60
|
+
stream.on("error", reject);
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
function readStdin(stream = process.stdin) {
|
|
64
|
+
return readAll(stream);
|
|
65
|
+
}
|
|
66
|
+
/** A markdown file's contents, with the CLI's no-such-file error. */
|
|
67
|
+
function readMarkdownFile(path) {
|
|
68
|
+
if (!statSync(path, { throwIfNoEntry: false })?.isFile()) throw new Error(`no such file: ${path}`);
|
|
69
|
+
return readFileSync(path, "utf8");
|
|
70
|
+
}
|
|
71
|
+
//#endregion
|
|
131
72
|
//#region src/last-reply.ts
|
|
73
|
+
function isFile(path) {
|
|
74
|
+
try {
|
|
75
|
+
return statSync(path).isFile();
|
|
76
|
+
} catch {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
132
80
|
function textBlocks(entry) {
|
|
133
81
|
const content = entry.message?.content;
|
|
134
82
|
if (entry.type !== "assistant" || !Array.isArray(content)) return;
|
|
@@ -232,6 +180,6 @@ function shutdownOnSignals(closables, signals = ["SIGINT", "SIGTERM"]) {
|
|
|
232
180
|
for (const signal of signals) process.on(signal, shutdown);
|
|
233
181
|
}
|
|
234
182
|
//#endregion
|
|
235
|
-
export { Logger, claudeProjectsDir,
|
|
183
|
+
export { Logger, claudeProjectsDir, lastReply, levelEnabled, parseQuietly, printUsageAndExit, readMarkdownFile, readStdin, shutdownOnSignals, watchWithReload };
|
|
236
184
|
|
|
237
185
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/input.ts","../src/hook.ts","../src/cli.ts","../src/dev.ts","../src/last-reply.ts","../src/logger.ts","../src/shutdown.ts"],"sourcesContent":["import { readFileSync, statSync } from 'node:fs';\n\nexport function readAll(stream: NodeJS.ReadableStream): Promise<string> {\n return new Promise((resolve, reject) => {\n let data = '';\n stream.setEncoding('utf8');\n stream.on('data', (chunk: string) => {\n data += chunk;\n });\n stream.on('end', () => {\n resolve(data);\n });\n stream.on('error', reject);\n });\n}\n\nexport function readStdin(\n stream: NodeJS.ReadableStream = process.stdin,\n): Promise<string> {\n return readAll(stream);\n}\n\n/** A markdown file's contents, with the CLI's no-such-file error. */\nexport function readMarkdownFile(path: string): string {\n const stats = statSync(path, { throwIfNoEntry: false });\n if (!stats?.isFile()) {\n throw new Error(`no such file: ${path}`);\n }\n return readFileSync(path, 'utf8');\n}\n","import { statSync } from 'node:fs';\n\nimport { readAll } from './input.js';\n\nexport interface HookEvent {\n cwd?: string;\n session_id?: string;\n transcript_path?: string;\n}\n\n/**\n * Read the Claude Code hook event JSON from stdin; empty or unparseable input\n * yields an empty event, never a thrown error — a hook must always answer.\n */\nexport function readHookEvent(\n stream: NodeJS.ReadableStream = process.stdin,\n): Promise<HookEvent> {\n return readAll(stream).then(\n data => {\n try {\n return JSON.parse(data) as HookEvent;\n } catch {\n return {};\n }\n },\n () => ({}),\n );\n}\n\n/**\n * Which transcript lastReply should read, per the hook event: transcript_path\n * when it names a real file, else session_id, else nothing (lastReply then\n * falls back to the newest session for the current project).\n */\nexport function replyTarget(event: HookEvent): string | undefined {\n if (event.transcript_path !== undefined && isFile(event.transcript_path)) {\n return event.transcript_path;\n }\n return event.session_id || undefined;\n}\n\nexport function isFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * Print the UserPromptExpansion decision for a zero-token command: `block`\n * keeps the command from reaching the model, with the output as the `reason`.\n */\nexport function emitHookBlock(reason: string): void {\n process.stdout.write(`${JSON.stringify({ decision: 'block', reason })}\\n`);\n}\n","import type { HookEvent } from './hook.js';\n\nimport { emitHookBlock, readHookEvent } from './hook.js';\n\nimport type { Command } from 'commander';\n\nexport function parseQuietly<T = never>(\n program: Command,\n args: readonly string[],\n recover?: (err: unknown) => T | undefined,\n): Command | T | undefined {\n try {\n program\n .allowExcessArguments(false)\n .exitOverride()\n .configureOutput({ writeOut: () => undefined, writeErr: () => undefined })\n .parse([...args], { from: 'user' });\n return program;\n } catch (err) {\n return recover?.(err);\n }\n}\n\nexport function printUsageAndExit(program: Command): never {\n console.error(program.helpInformation());\n // CLIs report failure through the exit code; the rule targets libraries.\n // eslint-disable-next-line n/no-process-exit\n process.exit(1);\n}\n\nexport async function hookOrPrint(\n hook: boolean,\n failure: string,\n run: (event: HookEvent | undefined) => Promise<string> | string,\n stdin: NodeJS.ReadableStream = process.stdin,\n): Promise<void> {\n if (hook) {\n let reason: string;\n try {\n reason = await run(await readHookEvent(stdin));\n } catch (e) {\n reason = `${failure}: ${(e as Error).message}`;\n }\n emitHookBlock(reason);\n return;\n }\n try {\n console.log(await run(undefined));\n } catch (e) {\n console.error((e as Error).message);\n // CLIs report failure through the exit code; the rule targets libraries.\n // eslint-disable-next-line n/no-process-exit\n process.exit(1);\n }\n}\n","// Structural stand-ins for vite's dev server and module runner — the shared\n// hot-reload wiring below must not pull vite into core's runtime surface; the\n// MCP packages pass their real instances through.\nexport interface ReloadableRunner {\n readonly evaluatedModules: { clear(): void };\n import<T>(entry: string): Promise<T>;\n}\n\nexport interface WatchableDevServer {\n close(): Promise<unknown>;\n readonly watcher: {\n on(event: 'change', cb: (file: string) => void): unknown;\n };\n}\n\nconst RELOAD_DEBOUNCE_MS = 150;\n\nconst IGNORED_SEGMENTS = ['/node_modules/', '/dist/', '/.git/', '/coverage/'];\n\nfunction shouldReload(file: string): boolean {\n return IGNORED_SEGMENTS.every(seg => !file.includes(seg));\n}\n\n/**\n * Debounced file-change reloads, serialized via a promise chain: concurrent\n * saves never overlap, and a mid-reload save still produces a follow-up.\n */\nexport function watchWithReload(\n vite: WatchableDevServer,\n reload: () => Promise<void>,\n): void {\n let chain: Promise<void> = Promise.resolve();\n let timer: NodeJS.Timeout | undefined;\n vite.watcher.on('change', file => {\n if (!shouldReload(file)) {\n return;\n }\n if (timer) {\n clearTimeout(timer);\n }\n timer = setTimeout(() => {\n timer = undefined;\n chain = chain.then(reload);\n }, RELOAD_DEBOUNCE_MS);\n });\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nimport { isFile } from './hook.js';\n\ninterface ContentBlock {\n text?: string;\n type: string;\n}\n\ninterface TranscriptEntry {\n message?: { content?: unknown };\n type?: string;\n}\n\nfunction textBlocks(entry: TranscriptEntry): ContentBlock[] | undefined {\n const content = entry.message?.content;\n if (entry.type !== 'assistant' || !Array.isArray(content)) {\n return undefined;\n }\n const blocks = content.filter(\n (b): b is ContentBlock =>\n typeof b === 'object' &&\n b !== null &&\n (b as ContentBlock).type === 'text',\n );\n return blocks.length > 0 ? blocks : undefined;\n}\n\nexport function claudeProjectsDir(): string {\n const claudeDir = process.env.CLAUDE_DIR ?? join(homedir(), '.claude');\n return join(claudeDir, 'projects');\n}\n\n/**\n * The last assistant text reply from a Claude Code session, reproducing Claude\n * Code's `/copy` byte-for-byte: the last assistant entry that contains a\n * `text` block, only its `text` block(s) (tool_use / thinking dropped), blocks\n * joined with a blank line, and no trailing newline.\n *\n * @param arg a transcript file, a session UUID under the project dir, or\n * nothing to use the newest session for the current project.\n */\nexport function lastReply(arg?: string): string {\n // Claude Code keys transcripts under the project root with \"/\" → \"-\".\n // Prefer $CLAUDE_PROJECT_DIR (exported to hook processes) over $PWD.\n const proj = (process.env.CLAUDE_PROJECT_DIR ?? process.cwd()).replaceAll(\n '/',\n '-',\n );\n const projDir = join(claudeProjectsDir(), proj);\n\n let file: string | undefined;\n if (arg !== undefined) {\n file = isFile(arg) ? arg : join(projDir, `${arg}.jsonl`);\n } else if (existsSync(projDir)) {\n const newest = readdirSync(projDir)\n .filter(f => f.endsWith('.jsonl'))\n .map(f => ({ f, mtimeMs: statSync(join(projDir, f)).mtimeMs }))\n .sort((a, b) => b.mtimeMs - a.mtimeMs)\n .at(0);\n if (newest) {\n file = join(projDir, newest.f);\n }\n }\n\n if (file === undefined || !isFile(file)) {\n throw new Error(`no session transcript found in ${projDir}`);\n }\n\n let last: ContentBlock[] | undefined;\n for (const line of readFileSync(file, 'utf8').split('\\n')) {\n if (!line.includes('\"assistant\"')) {\n continue;\n }\n let entry: TranscriptEntry;\n try {\n entry = JSON.parse(line) as TranscriptEntry;\n } catch {\n continue;\n }\n const blocks = textBlocks(entry);\n if (blocks) {\n last = blocks;\n }\n }\n return (last ?? []).map(b => b.text ?? '').join('\\n\\n');\n}\n","export type LogLevel = 'debug' | 'error' | 'info' | 'silent' | 'warn';\n\nconst LEVEL_RANK: Record<LogLevel, number> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n silent: Number.MAX_SAFE_INTEGER,\n};\n\nexport function levelEnabled(\n active: LogLevel,\n wanted: Exclude<LogLevel, 'silent'>,\n): boolean {\n return LEVEL_RANK[wanted] >= LEVEL_RANK[active];\n}\n\nconst LEVEL_LABEL: Record<Exclude<LogLevel, 'silent'>, string> = {\n debug: 'DEBUG',\n error: 'ERROR',\n info: 'INFO',\n warn: 'WARN',\n};\n\ntype Writer = (message: string) => void;\n\n// stdout carries the MCP transport; everything here goes to stderr.\nexport class Logger {\n private readonly stderr: Writer;\n\n constructor(\n readonly activeLevel: LogLevel,\n stderr: Writer = line => process.stderr.write(`${line}\\n`),\n ) {\n this.stderr = stderr;\n }\n\n debug(message: string): void {\n this.log('debug', message);\n }\n\n error(message: string): void {\n this.log('error', message);\n }\n\n info(message: string): void {\n this.log('info', message);\n }\n\n warn(message: string): void {\n this.log('warn', message);\n }\n\n private log(level: Exclude<LogLevel, 'silent'>, message: string): void {\n if (levelEnabled(this.activeLevel, level)) {\n this.stderr(`${LEVEL_LABEL[level]} ${message}`);\n }\n }\n}\n","/** Close each closable in order (best-effort), then force-exit. */\nexport function shutdownOnSignals(\n closables: readonly { close(): Promise<unknown> }[],\n signals: readonly NodeJS.Signals[] = ['SIGINT', 'SIGTERM'],\n): void {\n function shutdown(): void {\n void closables\n .reduce(\n (acc: Promise<void>, closable) =>\n acc.then(async () => {\n try {\n await closable.close();\n } catch {\n // best-effort; exiting regardless\n }\n return;\n }),\n Promise.resolve(),\n )\n .finally(() => {\n // Force-exit on signal; the n/no-process-exit rule targets libraries.\n // eslint-disable-next-line n/no-process-exit\n process.exit(0);\n });\n }\n for (const signal of signals) {\n process.on(signal, shutdown);\n }\n}\n"],"mappings":";;;;AAEA,SAAgB,QAAQ,QAAgD;CACtE,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,IAAI,OAAO;EACX,OAAO,YAAY,MAAM;EACzB,OAAO,GAAG,SAAS,UAAkB;GACnC,QAAQ;EACV,CAAC;EACD,OAAO,GAAG,aAAa;GACrB,QAAQ,IAAI;EACd,CAAC;EACD,OAAO,GAAG,SAAS,MAAM;CAC3B,CAAC;AACH;AAEA,SAAgB,UACd,SAAgC,QAAQ,OACvB;CACjB,OAAO,QAAQ,MAAM;AACvB;;AAGA,SAAgB,iBAAiB,MAAsB;CAErD,IAAI,CADU,SAAS,MAAM,EAAE,gBAAgB,MAAM,CAChD,CAAA,EAAO,OAAO,GACjB,MAAM,IAAI,MAAM,iBAAiB,MAAM;CAEzC,OAAO,aAAa,MAAM,MAAM;AAClC;;;;;;;ACfA,SAAgB,cACd,SAAgC,QAAQ,OACpB;CACpB,OAAO,QAAQ,MAAM,CAAC,CAAC,MACrB,SAAQ;EACN,IAAI;GACF,OAAO,KAAK,MAAM,IAAI;EACxB,QAAQ;GACN,OAAO,CAAC;EACV;CACF,UACO,CAAC,EACV;AACF;;;;;;AAOA,SAAgB,YAAY,OAAsC;CAChE,IAAI,MAAM,oBAAoB,KAAA,KAAa,OAAO,MAAM,eAAe,GACrE,OAAO,MAAM;CAEf,OAAO,MAAM,cAAc,KAAA;AAC7B;AAEA,SAAgB,OAAO,MAAuB;CAC5C,IAAI;EACF,OAAO,SAAS,IAAI,CAAC,CAAC,OAAO;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;;;AAM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AER;EAEF,CAAC,GACH,QAAQ,QAAQ,CAClB,CAAC,CACA,cAAc;GAGb,QAAQ,KAAK,CAAC;EAChB,CAAC;CACL;CACA,KAAK,MAAM,UAAU,SACnB,QAAQ,GAAG,QAAQ,QAAQ;AAE/B"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/cli.ts","../src/dev.ts","../src/input.ts","../src/last-reply.ts","../src/logger.ts","../src/shutdown.ts"],"sourcesContent":["import type { Command } from 'commander';\n\nexport function parseQuietly<T = never>(\n program: Command,\n args: readonly string[],\n recover?: (err: unknown) => T | undefined,\n): Command | T | undefined {\n try {\n program\n .allowExcessArguments(false)\n .exitOverride()\n .configureOutput({ writeOut: () => undefined, writeErr: () => undefined })\n .parse([...args], { from: 'user' });\n return program;\n } catch (err) {\n return recover?.(err);\n }\n}\n\nexport function printUsageAndExit(program: Command): never {\n console.error(program.helpInformation());\n // CLIs report failure through the exit code; the rule targets libraries.\n // eslint-disable-next-line n/no-process-exit\n process.exit(1);\n}\n","// Structural stand-ins for vite's dev server and module runner — the shared\n// hot-reload wiring below must not pull vite into core's runtime surface; the\n// MCP packages pass their real instances through.\nexport interface ReloadableRunner {\n readonly evaluatedModules: { clear(): void };\n import<T>(entry: string): Promise<T>;\n}\n\nexport interface WatchableDevServer {\n close(): Promise<unknown>;\n readonly watcher: {\n on(event: 'change', cb: (file: string) => void): unknown;\n };\n}\n\nconst RELOAD_DEBOUNCE_MS = 150;\n\nconst IGNORED_SEGMENTS = ['/node_modules/', '/dist/', '/.git/', '/coverage/'];\n\nfunction shouldReload(file: string): boolean {\n return IGNORED_SEGMENTS.every(seg => !file.includes(seg));\n}\n\n/**\n * Debounced file-change reloads, serialized via a promise chain: concurrent\n * saves never overlap, and a mid-reload save still produces a follow-up.\n */\nexport function watchWithReload(\n vite: WatchableDevServer,\n reload: () => Promise<void>,\n): void {\n let chain: Promise<void> = Promise.resolve();\n let timer: NodeJS.Timeout | undefined;\n vite.watcher.on('change', file => {\n if (!shouldReload(file)) {\n return;\n }\n if (timer) {\n clearTimeout(timer);\n }\n timer = setTimeout(() => {\n timer = undefined;\n chain = chain.then(reload);\n }, RELOAD_DEBOUNCE_MS);\n });\n}\n","import { readFileSync, statSync } from 'node:fs';\n\nfunction readAll(stream: NodeJS.ReadableStream): Promise<string> {\n return new Promise((resolve, reject) => {\n let data = '';\n stream.setEncoding('utf8');\n stream.on('data', (chunk: string) => {\n data += chunk;\n });\n stream.on('end', () => {\n resolve(data);\n });\n stream.on('error', reject);\n });\n}\n\nexport function readStdin(\n stream: NodeJS.ReadableStream = process.stdin,\n): Promise<string> {\n return readAll(stream);\n}\n\n/** A markdown file's contents, with the CLI's no-such-file error. */\nexport function readMarkdownFile(path: string): string {\n const stats = statSync(path, { throwIfNoEntry: false });\n if (!stats?.isFile()) {\n throw new Error(`no such file: ${path}`);\n }\n return readFileSync(path, 'utf8');\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nfunction isFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\ninterface ContentBlock {\n text?: string;\n type: string;\n}\n\ninterface TranscriptEntry {\n message?: { content?: unknown };\n type?: string;\n}\n\nfunction textBlocks(entry: TranscriptEntry): ContentBlock[] | undefined {\n const content = entry.message?.content;\n if (entry.type !== 'assistant' || !Array.isArray(content)) {\n return undefined;\n }\n const blocks = content.filter(\n (b): b is ContentBlock =>\n typeof b === 'object' &&\n b !== null &&\n (b as ContentBlock).type === 'text',\n );\n return blocks.length > 0 ? blocks : undefined;\n}\n\nexport function claudeProjectsDir(): string {\n const claudeDir = process.env.CLAUDE_DIR ?? join(homedir(), '.claude');\n return join(claudeDir, 'projects');\n}\n\n/**\n * The last assistant text reply from a Claude Code session, reproducing Claude\n * Code's `/copy` byte-for-byte: the last assistant entry that contains a\n * `text` block, only its `text` block(s) (tool_use / thinking dropped), blocks\n * joined with a blank line, and no trailing newline.\n *\n * @param arg a transcript file, a session UUID under the project dir, or\n * nothing to use the newest session for the current project.\n */\nexport function lastReply(arg?: string): string {\n // Claude Code keys transcripts under the project root with \"/\" → \"-\".\n // Prefer $CLAUDE_PROJECT_DIR (exported to hook processes) over $PWD.\n const proj = (process.env.CLAUDE_PROJECT_DIR ?? process.cwd()).replaceAll(\n '/',\n '-',\n );\n const projDir = join(claudeProjectsDir(), proj);\n\n let file: string | undefined;\n if (arg !== undefined) {\n file = isFile(arg) ? arg : join(projDir, `${arg}.jsonl`);\n } else if (existsSync(projDir)) {\n const newest = readdirSync(projDir)\n .filter(f => f.endsWith('.jsonl'))\n .map(f => ({ f, mtimeMs: statSync(join(projDir, f)).mtimeMs }))\n .sort((a, b) => b.mtimeMs - a.mtimeMs)\n .at(0);\n if (newest) {\n file = join(projDir, newest.f);\n }\n }\n\n if (file === undefined || !isFile(file)) {\n throw new Error(`no session transcript found in ${projDir}`);\n }\n\n let last: ContentBlock[] | undefined;\n for (const line of readFileSync(file, 'utf8').split('\\n')) {\n if (!line.includes('\"assistant\"')) {\n continue;\n }\n let entry: TranscriptEntry;\n try {\n entry = JSON.parse(line) as TranscriptEntry;\n } catch {\n continue;\n }\n const blocks = textBlocks(entry);\n if (blocks) {\n last = blocks;\n }\n }\n return (last ?? []).map(b => b.text ?? '').join('\\n\\n');\n}\n","export type LogLevel = 'debug' | 'error' | 'info' | 'silent' | 'warn';\n\nconst LEVEL_RANK: Record<LogLevel, number> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n silent: Number.MAX_SAFE_INTEGER,\n};\n\nexport function levelEnabled(\n active: LogLevel,\n wanted: Exclude<LogLevel, 'silent'>,\n): boolean {\n return LEVEL_RANK[wanted] >= LEVEL_RANK[active];\n}\n\nconst LEVEL_LABEL: Record<Exclude<LogLevel, 'silent'>, string> = {\n debug: 'DEBUG',\n error: 'ERROR',\n info: 'INFO',\n warn: 'WARN',\n};\n\ntype Writer = (message: string) => void;\n\n// stdout carries the MCP transport; everything here goes to stderr.\nexport class Logger {\n private readonly stderr: Writer;\n\n constructor(\n readonly activeLevel: LogLevel,\n stderr: Writer = line => process.stderr.write(`${line}\\n`),\n ) {\n this.stderr = stderr;\n }\n\n debug(message: string): void {\n this.log('debug', message);\n }\n\n error(message: string): void {\n this.log('error', message);\n }\n\n info(message: string): void {\n this.log('info', message);\n }\n\n warn(message: string): void {\n this.log('warn', message);\n }\n\n private log(level: Exclude<LogLevel, 'silent'>, message: string): void {\n if (levelEnabled(this.activeLevel, level)) {\n this.stderr(`${LEVEL_LABEL[level]} ${message}`);\n }\n }\n}\n","/** Close each closable in order (best-effort), then force-exit. */\nexport function shutdownOnSignals(\n closables: readonly { close(): Promise<unknown> }[],\n signals: readonly NodeJS.Signals[] = ['SIGINT', 'SIGTERM'],\n): void {\n function shutdown(): void {\n void closables\n .reduce(\n (acc: Promise<void>, closable) =>\n acc.then(async () => {\n try {\n await closable.close();\n } catch {\n // best-effort; exiting regardless\n }\n return;\n }),\n Promise.resolve(),\n )\n .finally(() => {\n // Force-exit on signal; the n/no-process-exit rule targets libraries.\n // eslint-disable-next-line n/no-process-exit\n process.exit(0);\n });\n }\n for (const signal of signals) {\n process.on(signal, shutdown);\n }\n}\n"],"mappings":";;;;AAEA,SAAgB,aACd,SACA,MACA,SACyB;CACzB,IAAI;EACF,QACG,qBAAqB,KAAK,CAAC,CAC3B,aAAa,CAAC,CACd,gBAAgB;GAAE,gBAAgB,KAAA;GAAW,gBAAgB,KAAA;EAAU,CAAC,CAAC,CACzE,MAAM,CAAC,GAAG,IAAI,GAAG,EAAE,MAAM,OAAO,CAAC;EACpC,OAAO;CACT,SAAS,KAAK;EACZ,OAAO,UAAU,GAAG;CACtB;AACF;AAEA,SAAgB,kBAAkB,SAAyB;CACzD,QAAQ,MAAM,QAAQ,gBAAgB,CAAC;CAGvC,QAAQ,KAAK,CAAC;AAChB;;;ACTA,IAAM,qBAAqB;AAE3B,IAAM,mBAAmB;CAAC;CAAkB;CAAU;CAA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FA,IAAM,aAAuC;CAC3C,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACP,QAAQ,OAAO;AACjB;AAEA,SAAgB,aACd,QACA,QACS;CACT,OAAO,WAAW,WAAW,WAAW;AAC1C;AAEA,IAAM,cAA2D;CAC/D,OAAO;CACP,OAAO;CACP,MAAM;CACN,MAAM;AACR;AAKA,IAAa,SAAb,MAAoB;CAIP;CAHX;CAEA,YACE,aACA,UAAiB,SAAQ,QAAQ,OAAO,MAAM,GAAG,KAAK,GAAG,GACzD;EAFS,KAAA,cAAA;EAGT,KAAK,SAAS;CAChB;CAEA,MAAM,SAAuB;EAC3B,KAAK,IAAI,SAAS,OAAO;CAC3B;CAEA,MAAM,SAAuB;EAC3B,KAAK,IAAI,SAAS,OAAO;CAC3B;CAEA,KAAK,SAAuB;EAC1B,KAAK,IAAI,QAAQ,OAAO;CAC1B;CAEA,KAAK,SAAuB;EAC1B,KAAK,IAAI,QAAQ,OAAO;CAC1B;CAEA,IAAY,OAAoC,SAAuB;EACrE,IAAI,aAAa,KAAK,aAAa,KAAK,GACtC,KAAK,OAAO,GAAG,YAAY,OAAO,GAAG,SAAS;CAElD;AACF;;;;ACzDA,SAAgB,kBACd,WACA,UAAqC,CAAC,UAAU,SAAS,GACnD;CACN,SAAS,WAAiB;EACxB,UACG,QACE,KAAoB,aACnB,IAAI,KAAK,YAAY;GACnB,IAAI;IACF,MAAM,SAAS,MAAM;GACvB,QAAQ,CAER;EAEF,CAAC,GACH,QAAQ,QAAQ,CAClB,CAAC,CACA,cAAc;GAGb,QAAQ,KAAK,CAAC;EAChB,CAAC;CACL;CACA,KAAK,MAAM,UAAU,SACnB,QAAQ,GAAG,QAAQ,QAAQ;AAE/B"}
|
package/package.json
CHANGED
package/src/cli.ts
CHANGED
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
import type { HookEvent } from './hook.js';
|
|
2
|
-
|
|
3
|
-
import { emitHookBlock, readHookEvent } from './hook.js';
|
|
4
|
-
|
|
5
1
|
import type { Command } from 'commander';
|
|
6
2
|
|
|
7
3
|
export function parseQuietly<T = never>(
|
|
@@ -27,29 +23,3 @@ export function printUsageAndExit(program: Command): never {
|
|
|
27
23
|
// eslint-disable-next-line n/no-process-exit
|
|
28
24
|
process.exit(1);
|
|
29
25
|
}
|
|
30
|
-
|
|
31
|
-
export async function hookOrPrint(
|
|
32
|
-
hook: boolean,
|
|
33
|
-
failure: string,
|
|
34
|
-
run: (event: HookEvent | undefined) => Promise<string> | string,
|
|
35
|
-
stdin: NodeJS.ReadableStream = process.stdin,
|
|
36
|
-
): Promise<void> {
|
|
37
|
-
if (hook) {
|
|
38
|
-
let reason: string;
|
|
39
|
-
try {
|
|
40
|
-
reason = await run(await readHookEvent(stdin));
|
|
41
|
-
} catch (e) {
|
|
42
|
-
reason = `${failure}: ${(e as Error).message}`;
|
|
43
|
-
}
|
|
44
|
-
emitHookBlock(reason);
|
|
45
|
-
return;
|
|
46
|
-
}
|
|
47
|
-
try {
|
|
48
|
-
console.log(await run(undefined));
|
|
49
|
-
} catch (e) {
|
|
50
|
-
console.error((e as Error).message);
|
|
51
|
-
// CLIs report failure through the exit code; the rule targets libraries.
|
|
52
|
-
// eslint-disable-next-line n/no-process-exit
|
|
53
|
-
process.exit(1);
|
|
54
|
-
}
|
|
55
|
-
}
|
package/src/index.ts
CHANGED
package/src/input.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readFileSync, statSync } from 'node:fs';
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
function readAll(stream: NodeJS.ReadableStream): Promise<string> {
|
|
4
4
|
return new Promise((resolve, reject) => {
|
|
5
5
|
let data = '';
|
|
6
6
|
stream.setEncoding('utf8');
|
package/src/last-reply.ts
CHANGED
|
@@ -2,7 +2,13 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
|
2
2
|
import { homedir } from 'node:os';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
function isFile(path: string): boolean {
|
|
6
|
+
try {
|
|
7
|
+
return statSync(path).isFile();
|
|
8
|
+
} catch {
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
6
12
|
|
|
7
13
|
interface ContentBlock {
|
|
8
14
|
text?: string;
|
package/src/hook.ts
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import { statSync } from 'node:fs';
|
|
2
|
-
|
|
3
|
-
import { readAll } from './input.js';
|
|
4
|
-
|
|
5
|
-
export interface HookEvent {
|
|
6
|
-
cwd?: string;
|
|
7
|
-
session_id?: string;
|
|
8
|
-
transcript_path?: string;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Read the Claude Code hook event JSON from stdin; empty or unparseable input
|
|
13
|
-
* yields an empty event, never a thrown error — a hook must always answer.
|
|
14
|
-
*/
|
|
15
|
-
export function readHookEvent(
|
|
16
|
-
stream: NodeJS.ReadableStream = process.stdin,
|
|
17
|
-
): Promise<HookEvent> {
|
|
18
|
-
return readAll(stream).then(
|
|
19
|
-
data => {
|
|
20
|
-
try {
|
|
21
|
-
return JSON.parse(data) as HookEvent;
|
|
22
|
-
} catch {
|
|
23
|
-
return {};
|
|
24
|
-
}
|
|
25
|
-
},
|
|
26
|
-
() => ({}),
|
|
27
|
-
);
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Which transcript lastReply should read, per the hook event: transcript_path
|
|
32
|
-
* when it names a real file, else session_id, else nothing (lastReply then
|
|
33
|
-
* falls back to the newest session for the current project).
|
|
34
|
-
*/
|
|
35
|
-
export function replyTarget(event: HookEvent): string | undefined {
|
|
36
|
-
if (event.transcript_path !== undefined && isFile(event.transcript_path)) {
|
|
37
|
-
return event.transcript_path;
|
|
38
|
-
}
|
|
39
|
-
return event.session_id || undefined;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export function isFile(path: string): boolean {
|
|
43
|
-
try {
|
|
44
|
-
return statSync(path).isFile();
|
|
45
|
-
} catch {
|
|
46
|
-
return false;
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* Print the UserPromptExpansion decision for a zero-token command: `block`
|
|
52
|
-
* keeps the command from reaching the model, with the output as the `reason`.
|
|
53
|
-
*/
|
|
54
|
-
export function emitHookBlock(reason: string): void {
|
|
55
|
-
process.stdout.write(`${JSON.stringify({ decision: 'block', reason })}\n`);
|
|
56
|
-
}
|