nlm-memory 0.5.0 → 0.5.2
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 +89 -34
- package/dist/cli/digest.d.ts +20 -0
- package/dist/cli/digest.js +142 -0
- package/dist/cli/digest.js.map +1 -0
- package/dist/cli/nlm.d.ts +1 -0
- package/dist/cli/nlm.js +25 -1
- package/dist/cli/nlm.js.map +1 -1
- package/dist/core/digest/compose.d.ts +38 -0
- package/dist/core/digest/compose.js +93 -0
- package/dist/core/digest/compose.js.map +1 -0
- package/dist/core/digest/hook-liveness.d.ts +32 -0
- package/dist/core/digest/hook-liveness.js +54 -0
- package/dist/core/digest/hook-liveness.js.map +1 -0
- package/dist/http/app.js +2 -1
- package/dist/http/app.js.map +1 -1
- package/dist/mcp/server.js +20 -1
- package/dist/mcp/server.js.map +1 -1
- package/dist/ui/assets/{index-C8cpwbYJ.css → index-Beo8psd-.css} +1 -1
- package/dist/ui/assets/{index-CB50QnL-.js → index-CSPTTeeM.js} +8 -8
- package/dist/ui/index.html +2 -2
- package/package.json +26 -1
- package/.agents/plugins/marketplace.json +0 -20
- package/.github/workflows/ci.yml +0 -30
- package/docs/methodology/re-derivation-rate.md +0 -112
- package/docs/methodology/useful-hit-rate.md +0 -79
- package/docs/plans/2026-05-20-fts5-lexical-recall.md +0 -1088
- package/docs/plans/2026-05-20-recall-daemon-wedge-fix.md +0 -662
- package/docs/plans/2026-05-20-recall-hook-design.md +0 -131
- package/docs/plans/2026-05-20-recall-hook-implementation.md +0 -1222
- package/docs/plans/desktop-product.md +0 -69
- package/docs/plans/factstore-design.md +0 -236
- package/logs/CHANGELOG/CHANGELOG-2026.md +0 -1575
- package/logs/CHANGELOG/CHANGELOG.md +0 -209
- package/migrations/000_initial_schema.sql +0 -174
- package/migrations/001_entity_type_rename.sql +0 -17
- package/migrations/002_adapter_state_extend.sql +0 -12
- package/migrations/003_session_embeddings.sql +0 -11
- package/migrations/004_facts.sql +0 -46
- package/migrations/005_sources.sql +0 -31
- package/migrations/006_providers.sql +0 -33
- package/migrations/007_source_tokens.sql +0 -17
- package/migrations/008_fts_rebuild.sql +0 -9
- package/migrations/009_session_embedding_chunks.sql +0 -46
- package/migrations/010_sources_opencode.sql +0 -30
- package/migrations/011_sources_hermes_agent.sql +0 -30
- package/migrations/012_sources_aider.sql +0 -30
- package/migrations/013_adapter_state_failure_count.sql +0 -12
- package/migrations/014_sources_cursor.sql +0 -30
- package/migrations/015_sources_windsurf.sql +0 -30
- package/plugin-hermes-agent/README.md +0 -49
- package/plugin-hermes-agent/__init__.py +0 -75
- package/plugin-hermes-agent/plugin.yaml +0 -15
- package/scripts/backfill-citations.mjs +0 -0
- package/scripts/build-codex-plugin.mjs +0 -61
- package/scripts/deepseek-probe.mjs +0 -67
- package/scripts/extract-triples.mjs +0 -207
- package/scripts/longmemeval/embedding-cache.ts +0 -77
- package/scripts/longmemeval/fetch-dataset.sh +0 -25
- package/scripts/longmemeval/run-harness.ts +0 -315
- package/scripts/longmemeval/scorer.ts +0 -99
- package/scripts/longmemeval/tsconfig.json +0 -9
- package/scripts/longmemeval/types.ts +0 -35
- package/scripts/nlm-daily-digest.py +0 -239
- package/scripts/nlm-daily-digest.sh +0 -28
- package/src/cli/classify-parity.ts +0 -257
- package/src/cli/launchctl-helpers.ts +0 -49
- package/src/cli/nlm.ts +0 -1078
- package/src/core/actions/actions-log.ts +0 -118
- package/src/core/actions/overlay.ts +0 -117
- package/src/core/adapters/aider.ts +0 -205
- package/src/core/adapters/claude-code.ts +0 -293
- package/src/core/adapters/common.ts +0 -54
- package/src/core/adapters/cursor.ts +0 -486
- package/src/core/adapters/from-source.ts +0 -67
- package/src/core/adapters/hermes-agent.ts +0 -240
- package/src/core/adapters/hermes.ts +0 -277
- package/src/core/adapters/jsonl-generic.ts +0 -208
- package/src/core/adapters/opencode.ts +0 -281
- package/src/core/adapters/pi.ts +0 -264
- package/src/core/adapters/windsurf.ts +0 -386
- package/src/core/classifier/prompt.ts +0 -200
- package/src/core/dataset/build-dataset.ts +0 -463
- package/src/core/embedding/chunk-body.ts +0 -76
- package/src/core/embedding/embed-backfill.ts +0 -210
- package/src/core/embedding/embed-normalize.ts +0 -135
- package/src/core/facts/backfill-facts.ts +0 -254
- package/src/core/facts/extract-facts.ts +0 -50
- package/src/core/hook/citation-detect.ts +0 -124
- package/src/core/hook/cite-memo.ts +0 -68
- package/src/core/hook/claude-settings.ts +0 -187
- package/src/core/hook/gate.ts +0 -25
- package/src/core/hook/hook-log.ts +0 -41
- package/src/core/hook/memo-sweep.ts +0 -164
- package/src/core/hook/memo.ts +0 -67
- package/src/core/hook/pointer-block.ts +0 -26
- package/src/core/hook/select.ts +0 -32
- package/src/core/hook/transcript.ts +0 -121
- package/src/core/ingest/ingest-session.ts +0 -111
- package/src/core/providers/provider-models.ts +0 -100
- package/src/core/providers/provider-registry.ts +0 -196
- package/src/core/recall/citation-log.ts +0 -108
- package/src/core/recall/filter.ts +0 -27
- package/src/core/recall/index.ts +0 -6
- package/src/core/recall/match-fields.ts +0 -40
- package/src/core/recall/query-log.ts +0 -149
- package/src/core/recall/query-shape.ts +0 -66
- package/src/core/recall/recall-service.ts +0 -320
- package/src/core/recall/recent-log.ts +0 -59
- package/src/core/recall/tokenize.ts +0 -18
- package/src/core/recall/useful-scan.ts +0 -336
- package/src/core/recall-facts/fact-query-log.ts +0 -150
- package/src/core/recall-facts/fact-recall-service.ts +0 -327
- package/src/core/scheduler/scan-once.ts +0 -142
- package/src/core/scheduler/scheduler.ts +0 -225
- package/src/core/sources/source-registry.ts +0 -278
- package/src/core/storage/db-restore.ts +0 -133
- package/src/core/storage/live-status.ts +0 -45
- package/src/core/storage/migrate.ts +0 -72
- package/src/core/storage/sqlite-fact-store.ts +0 -304
- package/src/core/storage/sqlite-session-store.ts +0 -810
- package/src/hook/hook-auth.ts +0 -18
- package/src/hook/prompt-recall-hook.ts +0 -180
- package/src/hook/session-end-hook.ts +0 -81
- package/src/hook/session-start-hook.ts +0 -168
- package/src/hook/stop-hook.ts +0 -239
- package/src/http/app.ts +0 -1215
- package/src/install/claude-code.ts +0 -128
- package/src/install/codex.ts +0 -367
- package/src/install/cursor.ts +0 -68
- package/src/install/hermes-agent.ts +0 -76
- package/src/install/hermes.ts +0 -78
- package/src/install/nlm-dir-perms.ts +0 -55
- package/src/install/ollama.ts +0 -284
- package/src/install/setup.ts +0 -489
- package/src/install/windsurf.ts +0 -68
- package/src/llm/classifier-box.ts +0 -64
- package/src/llm/deepseek-client.ts +0 -150
- package/src/llm/env-autoload.ts +0 -55
- package/src/llm/ollama-client.ts +0 -189
- package/src/mcp/server.ts +0 -534
- package/src/ports/fact-store.ts +0 -102
- package/src/ports/llm-client.ts +0 -52
- package/src/ports/logger.ts +0 -16
- package/src/ports/session-store.ts +0 -45
- package/src/ports/transcript-adapter.ts +0 -55
- package/src/shared/types.ts +0 -149
- package/src/ui/App.tsx +0 -58
- package/src/ui/components/PromoteOpenButton.tsx +0 -65
- package/src/ui/components/SessionDrawer.tsx +0 -199
- package/src/ui/components/SideNav.tsx +0 -162
- package/src/ui/components/Skeleton.tsx +0 -107
- package/src/ui/index.html +0 -13
- package/src/ui/lib/actions.ts +0 -30
- package/src/ui/lib/api.ts +0 -92
- package/src/ui/lib/dataset.ts +0 -141
- package/src/ui/lib/registries.ts +0 -155
- package/src/ui/lib/view-settings.ts +0 -41
- package/src/ui/main.tsx +0 -15
- package/src/ui/pages/Live.tsx +0 -229
- package/src/ui/pages/Pulse.tsx +0 -415
- package/src/ui/pages/Recall.tsx +0 -190
- package/src/ui/pages/River.tsx +0 -354
- package/src/ui/pages/Search.tsx +0 -386
- package/src/ui/pages/Stub.tsx +0 -9
- package/src/ui/pages/Thread.tsx +0 -473
- package/src/ui/pages/settings/Classifier.tsx +0 -227
- package/src/ui/pages/settings/Data.tsx +0 -190
- package/src/ui/pages/settings/Index.tsx +0 -65
- package/src/ui/pages/settings/Labels.tsx +0 -224
- package/src/ui/pages/settings/Providers.tsx +0 -305
- package/src/ui/pages/settings/SettingsSubnav.tsx +0 -28
- package/src/ui/pages/settings/Sources.tsx +0 -326
- package/src/ui/pages/settings/Views.tsx +0 -96
- package/src/ui/styles.css +0 -1890
- package/src/ui/tsconfig.json +0 -21
- package/src/ui/vite.config.ts +0 -19
- package/tests/fixtures/claude_code/short_session.jsonl +0 -2
- package/tests/fixtures/claude_code/standard_iso.jsonl +0 -4
- package/tests/fixtures/claude_code/tool_heavy.jsonl +0 -8
- package/tests/fixtures/claude_code/with_subagent.jsonl +0 -7
- package/tests/fixtures/facts.ts +0 -17
- package/tests/fixtures/golden-corpus.ts +0 -85
- package/tests/fixtures/hermes/paired_request_dump.json +0 -24
- package/tests/fixtures/hermes/paired_session.json +0 -23
- package/tests/fixtures/hermes/request_dump.json +0 -28
- package/tests/fixtures/hermes/session_iso.json +0 -38
- package/tests/fixtures/hermes/session_unix.json +0 -38
- package/tests/fixtures/hermes/system_only.json +0 -18
- package/tests/fixtures/pi/error-connection-abort.jsonl +0 -8
- package/tests/fixtures/pi/short-successful.jsonl +0 -5
- package/tests/fixtures/pi/with-custom-message.jsonl +0 -6
- package/tests/fixtures/sessions.ts +0 -22
- package/tests/integration/backfill-facts.test.ts +0 -362
- package/tests/integration/citation-explicit.test.ts +0 -111
- package/tests/integration/cite-event.test.ts +0 -169
- package/tests/integration/cite-memo.test.ts +0 -87
- package/tests/integration/db-restore.test.ts +0 -153
- package/tests/integration/embed-backfill.test.ts +0 -176
- package/tests/integration/fact-supersedence.test.ts +0 -313
- package/tests/integration/fts-index.test.ts +0 -60
- package/tests/integration/getbyids-sqlite.test.ts +0 -100
- package/tests/integration/hermes-agent-hooks.test.ts +0 -248
- package/tests/integration/hook-claude-settings.test.ts +0 -218
- package/tests/integration/hook-log.test.ts +0 -54
- package/tests/integration/hook-memo.test.ts +0 -68
- package/tests/integration/hook-pre-compact.test.ts +0 -105
- package/tests/integration/hook-subagent-start.test.ts +0 -102
- package/tests/integration/http.test.ts +0 -401
- package/tests/integration/keyword-search-fts.test.ts +0 -66
- package/tests/integration/mcp-recall-logging.test.ts +0 -88
- package/tests/integration/mcp.test.ts +0 -260
- package/tests/integration/memo-sweep.test.ts +0 -91
- package/tests/integration/prompt-recall-hook.test.ts +0 -88
- package/tests/integration/provider-registry.test.ts +0 -107
- package/tests/integration/recall-golden.test.ts +0 -59
- package/tests/integration/recall-sqlite.test.ts +0 -169
- package/tests/integration/scheduler.test.ts +0 -391
- package/tests/integration/session-end-hook.test.ts +0 -48
- package/tests/integration/session-start-hook.test.ts +0 -126
- package/tests/integration/source-registry.test.ts +0 -122
- package/tests/integration/sqlite-fact-store.test.ts +0 -346
- package/tests/integration/stop-hook.test.ts +0 -560
- package/tests/integration/wal-checkpoint.test.ts +0 -49
- package/tests/unit/cli/launchctl-helpers.test.ts +0 -60
- package/tests/unit/core/adapters/aider.test.ts +0 -230
- package/tests/unit/core/adapters/claude-code.test.ts +0 -118
- package/tests/unit/core/adapters/cursor.test.ts +0 -485
- package/tests/unit/core/adapters/hermes-agent.test.ts +0 -329
- package/tests/unit/core/adapters/hermes.test.ts +0 -81
- package/tests/unit/core/adapters/jsonl-generic.test.ts +0 -142
- package/tests/unit/core/adapters/opencode.test.ts +0 -354
- package/tests/unit/core/adapters/pi.test.ts +0 -110
- package/tests/unit/core/adapters/windsurf.test.ts +0 -416
- package/tests/unit/core/classifier/prompt.test.ts +0 -126
- package/tests/unit/core/embedding/chunk-body.test.ts +0 -100
- package/tests/unit/core/facts/extract-facts.test.ts +0 -117
- package/tests/unit/core/filter.test.ts +0 -40
- package/tests/unit/core/hook/citation-detect-cite-session.test.ts +0 -96
- package/tests/unit/core/hook/citation-detect.test.ts +0 -124
- package/tests/unit/core/hook/gate.test.ts +0 -29
- package/tests/unit/core/hook/pointer-block.test.ts +0 -22
- package/tests/unit/core/hook/select.test.ts +0 -66
- package/tests/unit/core/match-fields.test.ts +0 -39
- package/tests/unit/core/mcp-cite-session.test.ts +0 -51
- package/tests/unit/core/providers/provider-models.test.ts +0 -101
- package/tests/unit/core/query-shape.test.ts +0 -92
- package/tests/unit/core/recall-facts/fact-recall-service.test.ts +0 -258
- package/tests/unit/core/recall-service.test.ts +0 -200
- package/tests/unit/core/storage/live-status.test.ts +0 -54
- package/tests/unit/core/tokenize.test.ts +0 -32
- package/tests/unit/core/useful-scan.test.ts +0 -537
- package/tests/unit/llm/embed.test.ts +0 -93
- package/tests/unit/llm/ollama-client.test.ts +0 -124
- package/tests/unit/scripts/longmemeval-scorer.test.ts +0 -114
- package/tsconfig.json +0 -31
- package/tsconfig.test.json +0 -11
- package/vitest.config.ts +0 -22
package/src/hook/hook-auth.ts
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Shared helper: Bearer token for hook → /api/* HTTP calls.
|
|
3
|
-
*
|
|
4
|
-
* The HTTP daemon's /api/* gate requires either a same-origin browser
|
|
5
|
-
* request (Origin header set by the browser) or a Bearer token. Hooks
|
|
6
|
-
* are CLI processes with no Origin, so they need the token.
|
|
7
|
-
*
|
|
8
|
-
* Reads NLM_MCP_TOKEN from process.env (assumes autoloadEnv() has been
|
|
9
|
-
* called first). Returns an empty headers object when no token is set
|
|
10
|
-
* so legacy installs without a token still work — the daemon's gate
|
|
11
|
-
* also accepts unauthenticated loopback requests when no token is set.
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
export function hookAuthHeaders(extra: Record<string, string> = {}): Record<string, string> {
|
|
15
|
-
const token = process.env["NLM_MCP_TOKEN"];
|
|
16
|
-
if (!token) return { ...extra };
|
|
17
|
-
return { ...extra, authorization: `Bearer ${token}` };
|
|
18
|
-
}
|
|
@@ -1,180 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Claude Code UserPromptSubmit hook entrypoint for NLM recall.
|
|
3
|
-
*
|
|
4
|
-
* runHook is the testable orchestration; main() is the thin process wrapper
|
|
5
|
-
* (stdin / stdout / fetch / env). Every path is fail-open: any error yields
|
|
6
|
-
* no output and a clean exit, so the hook can never block or fail a prompt.
|
|
7
|
-
*
|
|
8
|
-
* Mode is read from NLM_HOOK_MODE (default "shadow"). In shadow mode the
|
|
9
|
-
* hook logs what it would inject and emits nothing; in live mode it emits a
|
|
10
|
-
* pointer block and records the per-conversation memo.
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
import { pathToFileURL } from "node:url";
|
|
14
|
-
import { classifyPrompt } from "@core/hook/gate.js";
|
|
15
|
-
import { appendHookLog } from "@core/hook/hook-log.js";
|
|
16
|
-
import { loadSurfaced, recordSurfaced } from "@core/hook/memo.js";
|
|
17
|
-
import { formatPointerBlock } from "@core/hook/pointer-block.js";
|
|
18
|
-
import { selectHits, type RecallHitInput } from "@core/hook/select.js";
|
|
19
|
-
import { autoloadEnv } from "../llm/env-autoload.js";
|
|
20
|
-
import { hookAuthHeaders } from "./hook-auth.js";
|
|
21
|
-
|
|
22
|
-
// Keyword recall returns raw BM25 scores (unbounded, not the 0..1 hybrid
|
|
23
|
-
// scale). FTS5 MATCH already gates relevance — only lexically-matching
|
|
24
|
-
// sessions come back — so the floor starts at 0 and a real cutoff is
|
|
25
|
-
// calibrated from the shadow log's score distribution.
|
|
26
|
-
const SCORE_THRESHOLD = 0;
|
|
27
|
-
const PER_FIRE_CAP = 3;
|
|
28
|
-
const PER_CONVERSATION_CAP = 10;
|
|
29
|
-
const RECALL_LIMIT = 5; // fetch more than PER_FIRE_CAP to absorb score-filter + dedup
|
|
30
|
-
const RECALL_TIMEOUT_MS = 2000; // keyword recall is ~400ms warm, ~1.4s cold
|
|
31
|
-
const PROMPT_PREVIEW_CHARS = 200;
|
|
32
|
-
|
|
33
|
-
export type HookMode = "shadow" | "live";
|
|
34
|
-
|
|
35
|
-
export interface HookInput {
|
|
36
|
-
readonly prompt: string;
|
|
37
|
-
readonly conversationId: string;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export interface RunHookDeps {
|
|
41
|
-
readonly mode: HookMode;
|
|
42
|
-
readonly recall: (prompt: string) => Promise<ReadonlyArray<RecallHitInput>>;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** Orchestration. Returns the text to emit on stdout ("" for nothing). */
|
|
46
|
-
export async function runHook(input: HookInput, deps: RunHookDeps): Promise<string> {
|
|
47
|
-
const gate = classifyPrompt(input.prompt);
|
|
48
|
-
const preview = input.prompt.slice(0, PROMPT_PREVIEW_CHARS);
|
|
49
|
-
|
|
50
|
-
if (gate === "generative") {
|
|
51
|
-
appendHookLog({
|
|
52
|
-
ts: new Date().toISOString(),
|
|
53
|
-
conversationId: input.conversationId,
|
|
54
|
-
promptPreview: preview,
|
|
55
|
-
gate,
|
|
56
|
-
hits: [],
|
|
57
|
-
wouldInject: [],
|
|
58
|
-
estTokens: 0,
|
|
59
|
-
mode: deps.mode,
|
|
60
|
-
});
|
|
61
|
-
return "";
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
let hits: ReadonlyArray<RecallHitInput> = [];
|
|
65
|
-
try {
|
|
66
|
-
hits = await deps.recall(input.prompt);
|
|
67
|
-
} catch {
|
|
68
|
-
hits = [];
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
const surfaced = loadSurfaced(input.conversationId);
|
|
72
|
-
const selected = selectHits({
|
|
73
|
-
hits,
|
|
74
|
-
surfaced,
|
|
75
|
-
scoreThreshold: SCORE_THRESHOLD,
|
|
76
|
-
perFireCap: PER_FIRE_CAP,
|
|
77
|
-
perConversationCap: PER_CONVERSATION_CAP,
|
|
78
|
-
});
|
|
79
|
-
const block = formatPointerBlock(selected);
|
|
80
|
-
const estTokens = Math.ceil(block.length / 4);
|
|
81
|
-
|
|
82
|
-
appendHookLog({
|
|
83
|
-
ts: new Date().toISOString(),
|
|
84
|
-
conversationId: input.conversationId,
|
|
85
|
-
promptPreview: preview,
|
|
86
|
-
gate,
|
|
87
|
-
hits: hits.map((h) => ({ id: h.id, score: h.matchScore })),
|
|
88
|
-
wouldInject: selected.map((h) => h.id),
|
|
89
|
-
estTokens,
|
|
90
|
-
mode: deps.mode,
|
|
91
|
-
});
|
|
92
|
-
|
|
93
|
-
if (deps.mode === "live" && selected.length > 0) {
|
|
94
|
-
recordSurfaced(input.conversationId, selected.map((h) => h.id));
|
|
95
|
-
return block;
|
|
96
|
-
}
|
|
97
|
-
return "";
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
function readStdin(): Promise<string> {
|
|
101
|
-
return new Promise((resolve) => {
|
|
102
|
-
let data = "";
|
|
103
|
-
process.stdin.setEncoding("utf8");
|
|
104
|
-
process.stdin.on("data", (chunk) => (data += chunk));
|
|
105
|
-
process.stdin.on("end", () => resolve(data));
|
|
106
|
-
process.stdin.on("error", () => resolve(data));
|
|
107
|
-
});
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
async function recallOverHttp(prompt: string): Promise<ReadonlyArray<RecallHitInput>> {
|
|
111
|
-
const portValue = process.env["NLM_PORT"] ?? "3940";
|
|
112
|
-
// keyword (FTS5) not hybrid: hybrid's Ollama embedding round-trip takes
|
|
113
|
-
// ~5s, far too slow for a hook that blocks prompt submission.
|
|
114
|
-
const url =
|
|
115
|
-
`http://localhost:${portValue}/api/recall` +
|
|
116
|
-
`?q=${encodeURIComponent(prompt)}&mode=keyword&limit=${RECALL_LIMIT}`;
|
|
117
|
-
const controller = new AbortController();
|
|
118
|
-
const timer = setTimeout(() => controller.abort(), RECALL_TIMEOUT_MS);
|
|
119
|
-
try {
|
|
120
|
-
const res = await fetch(url, {
|
|
121
|
-
headers: hookAuthHeaders({ "x-recall-source": "hook" }),
|
|
122
|
-
signal: controller.signal,
|
|
123
|
-
});
|
|
124
|
-
if (!res.ok) return [];
|
|
125
|
-
type RecallBody = {
|
|
126
|
-
results?: ReadonlyArray<{
|
|
127
|
-
id: string;
|
|
128
|
-
label: string;
|
|
129
|
-
startedAt: string;
|
|
130
|
-
matchScore: number;
|
|
131
|
-
}>;
|
|
132
|
-
};
|
|
133
|
-
let body: RecallBody;
|
|
134
|
-
try {
|
|
135
|
-
body = (await res.json()) as RecallBody;
|
|
136
|
-
} catch {
|
|
137
|
-
return [];
|
|
138
|
-
}
|
|
139
|
-
return (body.results ?? []).map((r) => ({
|
|
140
|
-
id: r.id,
|
|
141
|
-
label: r.label,
|
|
142
|
-
startedAt: r.startedAt,
|
|
143
|
-
matchScore: r.matchScore,
|
|
144
|
-
}));
|
|
145
|
-
} finally {
|
|
146
|
-
clearTimeout(timer);
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
async function main(): Promise<void> {
|
|
151
|
-
try {
|
|
152
|
-
// Load ~/.nlm/.env so NLM_MCP_TOKEN is available before we hit /api/recall.
|
|
153
|
-
// Hooks run as short-lived processes spawned by Claude Code with no shell
|
|
154
|
-
// env beyond what the parent passed — explicit .env load is required.
|
|
155
|
-
autoloadEnv();
|
|
156
|
-
const raw = await readStdin();
|
|
157
|
-
const payload = JSON.parse(raw) as {
|
|
158
|
-
prompt?: unknown;
|
|
159
|
-
session_id?: unknown;
|
|
160
|
-
};
|
|
161
|
-
const prompt = typeof payload.prompt === "string" ? payload.prompt : "";
|
|
162
|
-
const conversationId =
|
|
163
|
-
typeof payload.session_id === "string" ? payload.session_id : "unknown";
|
|
164
|
-
if (!prompt) return;
|
|
165
|
-
|
|
166
|
-
const mode: HookMode = process.env["NLM_HOOK_MODE"] === "live" ? "live" : "shadow";
|
|
167
|
-
const out = await runHook(
|
|
168
|
-
{ prompt, conversationId },
|
|
169
|
-
{ mode, recall: recallOverHttp },
|
|
170
|
-
);
|
|
171
|
-
if (out) process.stdout.write(out);
|
|
172
|
-
} catch {
|
|
173
|
-
// Fail open — never block or fail a prompt.
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// Run main() only when invoked directly as a script, not when imported by tests.
|
|
178
|
-
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
179
|
-
void main();
|
|
180
|
-
}
|
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Claude Code SessionEnd hook entrypoint for NLM.
|
|
3
|
-
*
|
|
4
|
-
* Fires when a Claude Code session closes. Deletes the per-conversation
|
|
5
|
-
* memo file written during the session so memo files don't accumulate
|
|
6
|
-
* indefinitely under ~/.nlm/hook-state/.
|
|
7
|
-
*
|
|
8
|
-
* Logs one JSON line per invocation to ~/.nlm/hook-log.jsonl with
|
|
9
|
-
* `kind: "session-end"` so the daily-digest liveness check can correlate
|
|
10
|
-
* Claude Code session closes against hook fires the same way it does for
|
|
11
|
-
* UserPromptSubmit. Fail-open by design: any error yields a clean exit
|
|
12
|
-
* with no output, so the hook can never block Claude Code shutdown.
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
import { pathToFileURL } from "node:url";
|
|
16
|
-
import { appendFileSync, mkdirSync } from "node:fs";
|
|
17
|
-
import { homedir } from "node:os";
|
|
18
|
-
import { dirname, join } from "node:path";
|
|
19
|
-
import { clearSurfaced } from "@core/hook/memo.js";
|
|
20
|
-
import { clearCited } from "@core/hook/cite-memo.js";
|
|
21
|
-
|
|
22
|
-
export interface SessionEndResult {
|
|
23
|
-
readonly conversationId: string;
|
|
24
|
-
readonly cleared: boolean;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export function runSessionEnd(conversationId: string): SessionEndResult {
|
|
28
|
-
const surfacedCleared = clearSurfaced(conversationId);
|
|
29
|
-
const citedCleared = clearCited(conversationId);
|
|
30
|
-
return { conversationId, cleared: surfacedCleared || citedCleared };
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function readStdin(): Promise<string> {
|
|
34
|
-
return new Promise((resolve) => {
|
|
35
|
-
let data = "";
|
|
36
|
-
process.stdin.setEncoding("utf8");
|
|
37
|
-
process.stdin.on("data", (chunk) => (data += chunk));
|
|
38
|
-
process.stdin.on("end", () => resolve(data));
|
|
39
|
-
process.stdin.on("error", () => resolve(data));
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function logPath(): string {
|
|
44
|
-
return process.env["NLM_HOOK_LOG"] ?? join(homedir(), ".nlm", "hook-log.jsonl");
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
function logSessionEnd(result: SessionEndResult): void {
|
|
48
|
-
try {
|
|
49
|
-
const path = logPath();
|
|
50
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
51
|
-
appendFileSync(
|
|
52
|
-
path,
|
|
53
|
-
`${JSON.stringify({
|
|
54
|
-
ts: new Date().toISOString(),
|
|
55
|
-
kind: "session-end",
|
|
56
|
-
conversationId: result.conversationId,
|
|
57
|
-
cleared: result.cleared,
|
|
58
|
-
mode: process.env["NLM_HOOK_MODE"] === "live" ? "live" : "shadow",
|
|
59
|
-
})}\n`,
|
|
60
|
-
"utf8",
|
|
61
|
-
);
|
|
62
|
-
} catch {
|
|
63
|
-
// Telemetry failure must never break the hook.
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
async function main(): Promise<void> {
|
|
68
|
-
try {
|
|
69
|
-
const raw = await readStdin();
|
|
70
|
-
const payload = JSON.parse(raw) as { session_id?: unknown };
|
|
71
|
-
const conversationId =
|
|
72
|
-
typeof payload.session_id === "string" ? payload.session_id : "unknown";
|
|
73
|
-
logSessionEnd(runSessionEnd(conversationId));
|
|
74
|
-
} catch {
|
|
75
|
-
// Fail open — never block Claude Code shutdown.
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
80
|
-
void main();
|
|
81
|
-
}
|
|
@@ -1,168 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Claude Code SessionStart hook entrypoint for NLM recall.
|
|
3
|
-
*
|
|
4
|
-
* Fires before any prompt in a new session (including cron-fired and background
|
|
5
|
-
* agents that never trigger UserPromptSubmit). Surfaces relevant prior context
|
|
6
|
-
* proactively so cold-start agents aren't recall-blind.
|
|
7
|
-
*
|
|
8
|
-
* Query is derived from working_directory + project_name since no user prompt
|
|
9
|
-
* exists yet — intentionally weaker than prompt-recall, best-effort only.
|
|
10
|
-
*
|
|
11
|
-
* Mirrors prompt-recall-hook.ts shape exactly: same pointer-block format, same
|
|
12
|
-
* memo writes, same NLM_HOOK_MODE semantics.
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
import { pathToFileURL } from "node:url";
|
|
16
|
-
import { appendHookLog } from "@core/hook/hook-log.js";
|
|
17
|
-
import { loadSurfaced, recordSurfaced } from "@core/hook/memo.js";
|
|
18
|
-
import { formatPointerBlock } from "@core/hook/pointer-block.js";
|
|
19
|
-
import { selectHits, type RecallHitInput } from "@core/hook/select.js";
|
|
20
|
-
import { autoloadEnv } from "../llm/env-autoload.js";
|
|
21
|
-
import { hookAuthHeaders } from "./hook-auth.js";
|
|
22
|
-
|
|
23
|
-
const SCORE_THRESHOLD = 0;
|
|
24
|
-
const PER_FIRE_CAP = 3;
|
|
25
|
-
const PER_CONVERSATION_CAP = 10;
|
|
26
|
-
const RECALL_LIMIT = 5;
|
|
27
|
-
const RECALL_TIMEOUT_MS = 2000;
|
|
28
|
-
|
|
29
|
-
export type HookMode = "shadow" | "live";
|
|
30
|
-
|
|
31
|
-
export interface SessionStartInput {
|
|
32
|
-
readonly conversationId: string;
|
|
33
|
-
readonly query: string;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export interface RunSessionStartDeps {
|
|
37
|
-
readonly mode: HookMode;
|
|
38
|
-
readonly recall: (query: string) => Promise<ReadonlyArray<RecallHitInput>>;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** Orchestration. Returns the text to emit on stdout ("" for nothing). */
|
|
42
|
-
export async function runHook(
|
|
43
|
-
input: SessionStartInput,
|
|
44
|
-
deps: RunSessionStartDeps,
|
|
45
|
-
): Promise<string> {
|
|
46
|
-
let hits: ReadonlyArray<RecallHitInput> = [];
|
|
47
|
-
try {
|
|
48
|
-
hits = await deps.recall(input.query);
|
|
49
|
-
} catch {
|
|
50
|
-
hits = [];
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
const surfaced = loadSurfaced(input.conversationId);
|
|
54
|
-
const selected = selectHits({
|
|
55
|
-
hits,
|
|
56
|
-
surfaced,
|
|
57
|
-
scoreThreshold: SCORE_THRESHOLD,
|
|
58
|
-
perFireCap: PER_FIRE_CAP,
|
|
59
|
-
perConversationCap: PER_CONVERSATION_CAP,
|
|
60
|
-
});
|
|
61
|
-
const block = formatPointerBlock(selected);
|
|
62
|
-
const estTokens = Math.ceil(block.length / 4);
|
|
63
|
-
|
|
64
|
-
appendHookLog({
|
|
65
|
-
ts: new Date().toISOString(),
|
|
66
|
-
conversationId: input.conversationId,
|
|
67
|
-
promptPreview: input.query,
|
|
68
|
-
gate: "evaluate",
|
|
69
|
-
hits: hits.map((h) => ({ id: h.id, score: h.matchScore })),
|
|
70
|
-
wouldInject: selected.map((h) => h.id),
|
|
71
|
-
estTokens,
|
|
72
|
-
mode: deps.mode,
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
if (deps.mode === "live" && selected.length > 0) {
|
|
76
|
-
recordSurfaced(input.conversationId, selected.map((h) => h.id));
|
|
77
|
-
return block;
|
|
78
|
-
}
|
|
79
|
-
return "";
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/** Derive a best-effort query from SessionStart payload fields. */
|
|
83
|
-
function buildQuery(workingDirectory: string, projectName: string): string {
|
|
84
|
-
const dirTail = workingDirectory.split("/").filter(Boolean).at(-1) ?? "";
|
|
85
|
-
const parts = [dirTail, projectName].filter(Boolean);
|
|
86
|
-
return parts.join(" ").trim() || "session start";
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
function readStdin(): Promise<string> {
|
|
90
|
-
return new Promise((resolve) => {
|
|
91
|
-
let data = "";
|
|
92
|
-
process.stdin.setEncoding("utf8");
|
|
93
|
-
process.stdin.on("data", (chunk) => (data += chunk));
|
|
94
|
-
process.stdin.on("end", () => resolve(data));
|
|
95
|
-
process.stdin.on("error", () => resolve(data));
|
|
96
|
-
});
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
async function recallOverHttp(query: string): Promise<ReadonlyArray<RecallHitInput>> {
|
|
100
|
-
const portValue = process.env["NLM_PORT"] ?? "3940";
|
|
101
|
-
const url =
|
|
102
|
-
`http://localhost:${portValue}/api/recall` +
|
|
103
|
-
`?q=${encodeURIComponent(query)}&mode=hybrid&limit=${RECALL_LIMIT}`;
|
|
104
|
-
const controller = new AbortController();
|
|
105
|
-
const timer = setTimeout(() => controller.abort(), RECALL_TIMEOUT_MS);
|
|
106
|
-
try {
|
|
107
|
-
const res = await fetch(url, {
|
|
108
|
-
headers: hookAuthHeaders({ "x-recall-source": "session-start-hook" }),
|
|
109
|
-
signal: controller.signal,
|
|
110
|
-
});
|
|
111
|
-
if (!res.ok) return [];
|
|
112
|
-
type RecallBody = {
|
|
113
|
-
results?: ReadonlyArray<{
|
|
114
|
-
id: string;
|
|
115
|
-
label: string;
|
|
116
|
-
startedAt: string;
|
|
117
|
-
matchScore: number;
|
|
118
|
-
}>;
|
|
119
|
-
};
|
|
120
|
-
let body: RecallBody;
|
|
121
|
-
try {
|
|
122
|
-
body = (await res.json()) as RecallBody;
|
|
123
|
-
} catch {
|
|
124
|
-
return [];
|
|
125
|
-
}
|
|
126
|
-
return (body.results ?? []).map((r) => ({
|
|
127
|
-
id: r.id,
|
|
128
|
-
label: r.label,
|
|
129
|
-
startedAt: r.startedAt,
|
|
130
|
-
matchScore: r.matchScore,
|
|
131
|
-
}));
|
|
132
|
-
} finally {
|
|
133
|
-
clearTimeout(timer);
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
async function main(): Promise<void> {
|
|
138
|
-
try {
|
|
139
|
-
autoloadEnv();
|
|
140
|
-
const raw = await readStdin();
|
|
141
|
-
const payload = JSON.parse(raw) as {
|
|
142
|
-
session_id?: unknown;
|
|
143
|
-
cwd?: unknown;
|
|
144
|
-
working_directory?: unknown;
|
|
145
|
-
project_name?: unknown;
|
|
146
|
-
};
|
|
147
|
-
const conversationId =
|
|
148
|
-
typeof payload.session_id === "string" ? payload.session_id : "unknown";
|
|
149
|
-
const workingDirectory =
|
|
150
|
-
typeof payload.cwd === "string"
|
|
151
|
-
? payload.cwd
|
|
152
|
-
: typeof payload.working_directory === "string"
|
|
153
|
-
? payload.working_directory
|
|
154
|
-
: "";
|
|
155
|
-
const projectName =
|
|
156
|
-
typeof payload.project_name === "string" ? payload.project_name : "";
|
|
157
|
-
const query = buildQuery(workingDirectory, projectName);
|
|
158
|
-
const mode: HookMode = process.env["NLM_HOOK_MODE"] === "live" ? "live" : "shadow";
|
|
159
|
-
const out = await runHook({ conversationId, query }, { mode, recall: recallOverHttp });
|
|
160
|
-
if (out) process.stdout.write(out);
|
|
161
|
-
} catch {
|
|
162
|
-
// Fail open — never block or fail a session start.
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
167
|
-
void main();
|
|
168
|
-
}
|
package/src/hook/stop-hook.ts
DELETED
|
@@ -1,239 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Claude Code Stop hook entrypoint for NLM.
|
|
3
|
-
*
|
|
4
|
-
* Fires after the model finishes a response. Scans the last assistant message
|
|
5
|
-
* in the transcript for substrings matching any session ID the recall hook
|
|
6
|
-
* surfaced this conversation (via the dedup memo). Each match becomes a
|
|
7
|
-
* citation event posted to the daemon at POST /api/recall/cite-event.
|
|
8
|
-
*
|
|
9
|
-
* Double duty:
|
|
10
|
-
* - Per-recall useful_hit_rate metric (was the returned ID actually used?)
|
|
11
|
-
* - Training-data substrate for a learned reranker (was_cited per query)
|
|
12
|
-
*
|
|
13
|
-
* Fail-open by design: any error yields a clean exit with no output. The
|
|
14
|
-
* Stop hook can never block Claude Code's response. The smoke test path
|
|
15
|
-
* succeeds even with missing transcript_path because the hook always logs
|
|
16
|
-
* a `kind:"stop"` line.
|
|
17
|
-
*/
|
|
18
|
-
|
|
19
|
-
import { pathToFileURL } from "node:url";
|
|
20
|
-
import { appendFileSync, mkdirSync } from "node:fs";
|
|
21
|
-
import { homedir } from "node:os";
|
|
22
|
-
import { dirname, join } from "node:path";
|
|
23
|
-
import {
|
|
24
|
-
detectCitations,
|
|
25
|
-
type CitationKind,
|
|
26
|
-
} from "@core/hook/citation-detect.js";
|
|
27
|
-
import { loadSurfaced } from "@core/hook/memo.js";
|
|
28
|
-
import { loadCited, recordCited } from "@core/hook/cite-memo.js";
|
|
29
|
-
import {
|
|
30
|
-
readAllAssistantTurns,
|
|
31
|
-
type ToolUseBlock,
|
|
32
|
-
} from "@core/hook/transcript.js";
|
|
33
|
-
import { autoloadEnv } from "../llm/env-autoload.js";
|
|
34
|
-
import { hookAuthHeaders } from "./hook-auth.js";
|
|
35
|
-
|
|
36
|
-
const RESPONSE_PREVIEW_CHARS = 200;
|
|
37
|
-
const POST_TIMEOUT_MS = 1500;
|
|
38
|
-
|
|
39
|
-
export interface StopHookInput {
|
|
40
|
-
readonly conversationId: string;
|
|
41
|
-
readonly transcriptPath: string;
|
|
42
|
-
readonly stopHookActive: boolean;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export interface CitationEvent {
|
|
46
|
-
readonly id: string;
|
|
47
|
-
readonly kind: CitationKind;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export interface StopHookResult {
|
|
51
|
-
readonly conversationId: string;
|
|
52
|
-
readonly surfacedCount: number;
|
|
53
|
-
readonly citations: ReadonlyArray<CitationEvent>;
|
|
54
|
-
readonly responsePreview: string;
|
|
55
|
-
readonly skipped: boolean;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export interface RunStopHookDeps {
|
|
59
|
-
readonly postCitation: (
|
|
60
|
-
conversationId: string,
|
|
61
|
-
citedId: string,
|
|
62
|
-
kind: CitationKind,
|
|
63
|
-
responsePreview: string,
|
|
64
|
-
) => Promise<void>;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export async function runStopHook(
|
|
68
|
-
input: StopHookInput,
|
|
69
|
-
deps: RunStopHookDeps,
|
|
70
|
-
): Promise<StopHookResult> {
|
|
71
|
-
// stop_hook_active=true means Stop is firing again because a prior Stop
|
|
72
|
-
// hook returned control to the model. Skip to avoid double-counting.
|
|
73
|
-
if (input.stopHookActive) {
|
|
74
|
-
return {
|
|
75
|
-
conversationId: input.conversationId,
|
|
76
|
-
surfacedCount: 0,
|
|
77
|
-
citations: [],
|
|
78
|
-
responsePreview: "",
|
|
79
|
-
skipped: true,
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
const surfaced = loadSurfaced(input.conversationId);
|
|
84
|
-
if (surfaced.size === 0) {
|
|
85
|
-
return {
|
|
86
|
-
conversationId: input.conversationId,
|
|
87
|
-
surfacedCount: 0,
|
|
88
|
-
citations: [],
|
|
89
|
-
responsePreview: "",
|
|
90
|
-
skipped: false,
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
const turns = readAllAssistantTurns(input.transcriptPath);
|
|
95
|
-
if (turns.length === 0) {
|
|
96
|
-
return {
|
|
97
|
-
conversationId: input.conversationId,
|
|
98
|
-
surfacedCount: surfaced.size,
|
|
99
|
-
citations: [],
|
|
100
|
-
responsePreview: "",
|
|
101
|
-
skipped: false,
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
const allToolUses: ToolUseBlock[] = [];
|
|
106
|
-
const textParts: string[] = [];
|
|
107
|
-
for (const turn of turns) {
|
|
108
|
-
if (turn.text) textParts.push(turn.text);
|
|
109
|
-
for (const tu of turn.toolUses) allToolUses.push(tu);
|
|
110
|
-
}
|
|
111
|
-
const unionText = textParts.join("\n");
|
|
112
|
-
|
|
113
|
-
const detected = detectCitations({
|
|
114
|
-
responseText: unionText,
|
|
115
|
-
toolUses: allToolUses,
|
|
116
|
-
surfacedIds: surfaced,
|
|
117
|
-
});
|
|
118
|
-
const alreadyCited = loadCited(input.conversationId);
|
|
119
|
-
const fresh = detected.filter((c) => !alreadyCited.has(c.id));
|
|
120
|
-
|
|
121
|
-
// Preview is the LAST turn's prose — that's what Edward saw when Stop
|
|
122
|
-
// fired. Stable substrate for the citation log even when detection
|
|
123
|
-
// ranges across earlier turns.
|
|
124
|
-
const lastText = turns[turns.length - 1]?.text ?? "";
|
|
125
|
-
const preview = lastText.slice(0, RESPONSE_PREVIEW_CHARS);
|
|
126
|
-
|
|
127
|
-
for (const c of fresh) {
|
|
128
|
-
try {
|
|
129
|
-
await deps.postCitation(input.conversationId, c.id, c.kind, preview);
|
|
130
|
-
} catch {
|
|
131
|
-
// Daemon down or HTTP error — local memo update below still records
|
|
132
|
-
// the citation so we don't repost on the next Stop fire.
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
if (fresh.length > 0) {
|
|
136
|
-
recordCited(input.conversationId, fresh.map((c) => c.id));
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
return {
|
|
140
|
-
conversationId: input.conversationId,
|
|
141
|
-
surfacedCount: surfaced.size,
|
|
142
|
-
citations: fresh,
|
|
143
|
-
responsePreview: preview,
|
|
144
|
-
skipped: false,
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function logPath(): string {
|
|
149
|
-
return process.env["NLM_HOOK_LOG"] ?? join(homedir(), ".nlm", "hook-log.jsonl");
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function logStopResult(result: StopHookResult): void {
|
|
153
|
-
try {
|
|
154
|
-
const path = logPath();
|
|
155
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
156
|
-
appendFileSync(
|
|
157
|
-
path,
|
|
158
|
-
`${JSON.stringify({
|
|
159
|
-
ts: new Date().toISOString(),
|
|
160
|
-
kind: "stop",
|
|
161
|
-
conversationId: result.conversationId,
|
|
162
|
-
surfacedCount: result.surfacedCount,
|
|
163
|
-
citedIds: result.citations.map((c) => c.id),
|
|
164
|
-
citationKinds: result.citations.map((c) => c.kind),
|
|
165
|
-
skipped: result.skipped,
|
|
166
|
-
mode: process.env["NLM_HOOK_MODE"] === "live" ? "live" : "shadow",
|
|
167
|
-
})}\n`,
|
|
168
|
-
"utf8",
|
|
169
|
-
);
|
|
170
|
-
} catch {
|
|
171
|
-
// Telemetry failure must never break the hook.
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
function readStdin(): Promise<string> {
|
|
176
|
-
return new Promise((resolve) => {
|
|
177
|
-
let data = "";
|
|
178
|
-
process.stdin.setEncoding("utf8");
|
|
179
|
-
process.stdin.on("data", (chunk) => (data += chunk));
|
|
180
|
-
process.stdin.on("end", () => resolve(data));
|
|
181
|
-
process.stdin.on("error", () => resolve(data));
|
|
182
|
-
});
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
async function postCitationOverHttp(
|
|
186
|
-
conversationId: string,
|
|
187
|
-
citedId: string,
|
|
188
|
-
kind: CitationKind,
|
|
189
|
-
responsePreview: string,
|
|
190
|
-
): Promise<void> {
|
|
191
|
-
const port = process.env["NLM_PORT"] ?? "3940";
|
|
192
|
-
const url = `http://localhost:${port}/api/recall/cite-event`;
|
|
193
|
-
const controller = new AbortController();
|
|
194
|
-
const timer = setTimeout(() => controller.abort(), POST_TIMEOUT_MS);
|
|
195
|
-
try {
|
|
196
|
-
await fetch(url, {
|
|
197
|
-
method: "POST",
|
|
198
|
-
headers: hookAuthHeaders({ "content-type": "application/json" }),
|
|
199
|
-
body: JSON.stringify({
|
|
200
|
-
conversation_id: conversationId,
|
|
201
|
-
cited_id: citedId,
|
|
202
|
-
kind,
|
|
203
|
-
response_preview: responsePreview,
|
|
204
|
-
}),
|
|
205
|
-
signal: controller.signal,
|
|
206
|
-
});
|
|
207
|
-
} finally {
|
|
208
|
-
clearTimeout(timer);
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
async function main(): Promise<void> {
|
|
213
|
-
try {
|
|
214
|
-
autoloadEnv();
|
|
215
|
-
const raw = await readStdin();
|
|
216
|
-
const payload = JSON.parse(raw) as {
|
|
217
|
-
session_id?: unknown;
|
|
218
|
-
transcript_path?: unknown;
|
|
219
|
-
stop_hook_active?: unknown;
|
|
220
|
-
};
|
|
221
|
-
const conversationId =
|
|
222
|
-
typeof payload.session_id === "string" ? payload.session_id : "unknown";
|
|
223
|
-
const transcriptPath =
|
|
224
|
-
typeof payload.transcript_path === "string" ? payload.transcript_path : "";
|
|
225
|
-
const stopHookActive = payload.stop_hook_active === true;
|
|
226
|
-
|
|
227
|
-
const result = await runStopHook(
|
|
228
|
-
{ conversationId, transcriptPath, stopHookActive },
|
|
229
|
-
{ postCitation: postCitationOverHttp },
|
|
230
|
-
);
|
|
231
|
-
logStopResult(result);
|
|
232
|
-
} catch {
|
|
233
|
-
// Fail open — never block Claude Code's response.
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
238
|
-
void main();
|
|
239
|
-
}
|