agent-knowledge 1.7.3 → 1.8.1

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 (66) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.mcp.json +1 -1
  3. package/CHANGELOG.md +101 -0
  4. package/README.md +43 -18
  5. package/agent-desk-plugin.json +1 -1
  6. package/dist/dashboard.d.ts.map +1 -1
  7. package/dist/dashboard.js +28 -1
  8. package/dist/dashboard.js.map +1 -1
  9. package/dist/knowledge/analyze.d.ts +18 -0
  10. package/dist/knowledge/analyze.d.ts.map +1 -1
  11. package/dist/knowledge/analyze.js +22 -0
  12. package/dist/knowledge/analyze.js.map +1 -1
  13. package/dist/knowledge/freshness.d.ts +99 -0
  14. package/dist/knowledge/freshness.d.ts.map +1 -0
  15. package/dist/knowledge/freshness.js +303 -0
  16. package/dist/knowledge/freshness.js.map +1 -0
  17. package/dist/knowledge/promote.d.ts +145 -0
  18. package/dist/knowledge/promote.d.ts.map +1 -0
  19. package/dist/knowledge/promote.js +532 -0
  20. package/dist/knowledge/promote.js.map +1 -0
  21. package/dist/knowledge/query-log.d.ts +88 -0
  22. package/dist/knowledge/query-log.d.ts.map +1 -0
  23. package/dist/knowledge/query-log.js +207 -0
  24. package/dist/knowledge/query-log.js.map +1 -0
  25. package/dist/knowledge/scoring.d.ts +22 -2
  26. package/dist/knowledge/scoring.d.ts.map +1 -1
  27. package/dist/knowledge/scoring.js +51 -3
  28. package/dist/knowledge/scoring.js.map +1 -1
  29. package/dist/knowledge/search.d.ts +56 -5
  30. package/dist/knowledge/search.d.ts.map +1 -1
  31. package/dist/knowledge/search.js +88 -10
  32. package/dist/knowledge/search.js.map +1 -1
  33. package/dist/knowledge/store.d.ts +12 -0
  34. package/dist/knowledge/store.d.ts.map +1 -1
  35. package/dist/knowledge/store.js +18 -0
  36. package/dist/knowledge/store.js.map +1 -1
  37. package/dist/search/mmr.d.ts +54 -0
  38. package/dist/search/mmr.d.ts.map +1 -0
  39. package/dist/search/mmr.js +138 -0
  40. package/dist/search/mmr.js.map +1 -0
  41. package/dist/server.d.ts +334 -0
  42. package/dist/server.d.ts.map +1 -1
  43. package/dist/server.js +378 -301
  44. package/dist/server.js.map +1 -1
  45. package/dist/sessions/indexer.d.ts.map +1 -1
  46. package/dist/sessions/indexer.js +13 -11
  47. package/dist/sessions/indexer.js.map +1 -1
  48. package/dist/tool-handlers.d.ts +10 -3
  49. package/dist/tool-handlers.d.ts.map +1 -1
  50. package/dist/tool-handlers.js +150 -21
  51. package/dist/tool-handlers.js.map +1 -1
  52. package/dist/ui/app.js +271 -1
  53. package/dist/ui/render-knowledge.js +3 -3
  54. package/dist/ui/styles.css +209 -0
  55. package/dist/wakeup.d.ts +59 -14
  56. package/dist/wakeup.d.ts.map +1 -1
  57. package/dist/wakeup.js +406 -43
  58. package/dist/wakeup.js.map +1 -1
  59. package/docs/ARCHITECTURE.md +31 -6
  60. package/docs/SETUP.md +20 -8
  61. package/docs/USER-MANUAL.md +205 -59
  62. package/docs/hooks.md +81 -21
  63. package/package.json +4 -1
  64. package/scripts/hooks/first-prompt-inject.mjs +230 -0
  65. package/scripts/hooks/precompact-flush.mjs +89 -60
  66. package/scripts/hooks/session-start.js +73 -9
@@ -0,0 +1,230 @@
1
+ #!/usr/bin/env node
2
+
3
+ // =============================================================================
4
+ // agent-knowledge UserPromptSubmit hook — first-prompt knowledge injection
5
+ //
6
+ // When the user sends the FIRST real prompt of a session, run the prompt text
7
+ // through knowledge_search and inject the top-K hits as additionalContext
8
+ // before the model sees the prompt. Complements the SessionStart wakeup
9
+ // (which is query-agnostic) by pulling in entries that are directly relevant
10
+ // to whatever the user is about to ask.
11
+ //
12
+ // Gates (all must pass to fire):
13
+ // - AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT != 0 / false / off
14
+ // - Prompt is >= 10 chars
15
+ // - Prompt does not start with `/` (skip slash commands)
16
+ // - No marker file exists yet for this session id
17
+ //
18
+ // Fires once per session. Subsequent prompts see only the wakeup pack and
19
+ // whatever they search for themselves. A marker file at
20
+ // `{dataDir}/.first-prompt-seen/<session_id>` records "already fired".
21
+ //
22
+ // Envs:
23
+ // AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT (default "1") — set "0" to disable
24
+ // AGENT_KNOWLEDGE_FIRSTPROMPT_BUDGET (default "600") — max chars/4 tokens
25
+ // AGENT_KNOWLEDGE_FIRSTPROMPT_MAX_HITS (default "4") — cap on rendered hits
26
+ // KNOWLEDGE_MEMORY_DIR — resolves memory dir (same as core)
27
+ //
28
+ // Fail-open: every error path prints `{}` so the host never blocks on this
29
+ // hook. Log-only stderr for diagnostics.
30
+ // =============================================================================
31
+
32
+ import fs from 'fs';
33
+ import path from 'path';
34
+ import { dirname, resolve } from 'path';
35
+ import { fileURLToPath } from 'url';
36
+ import { homedir } from 'os';
37
+
38
+ const __filename = fileURLToPath(import.meta.url);
39
+ const __dirname = dirname(__filename);
40
+
41
+ function emit(additionalContext) {
42
+ const payload = additionalContext
43
+ ? {
44
+ hookSpecificOutput: {
45
+ hookEventName: 'UserPromptSubmit',
46
+ additionalContext,
47
+ },
48
+ }
49
+ : {};
50
+ process.stdout.write(JSON.stringify(payload) + '\n');
51
+ process.exit(0);
52
+ }
53
+
54
+ function warn(msg) {
55
+ process.stderr.write(`[knowledge firstprompt] ${msg}\n`);
56
+ }
57
+
58
+ function isEnabled() {
59
+ const raw = (process.env.AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT ?? '1').trim().toLowerCase();
60
+ return raw !== '0' && raw !== 'false' && raw !== 'off';
61
+ }
62
+
63
+ function tokenBudget() {
64
+ const raw = process.env.AGENT_KNOWLEDGE_FIRSTPROMPT_BUDGET ?? '600';
65
+ const n = Number.parseInt(raw, 10);
66
+ if (Number.isFinite(n) && n >= 100 && n <= 8000) return n;
67
+ return 600;
68
+ }
69
+
70
+ function maxHits() {
71
+ const raw = process.env.AGENT_KNOWLEDGE_FIRSTPROMPT_MAX_HITS ?? '4';
72
+ const n = Number.parseInt(raw, 10);
73
+ if (Number.isFinite(n) && n >= 1 && n <= 20) return n;
74
+ return 4;
75
+ }
76
+
77
+ function memoryDir() {
78
+ return process.env.KNOWLEDGE_MEMORY_DIR || path.join(homedir(), 'agent-knowledge');
79
+ }
80
+
81
+ function dataDir() {
82
+ if (process.env.KNOWLEDGE_DATA_DIR) return process.env.KNOWLEDGE_DATA_DIR;
83
+ if (process.platform === 'win32') {
84
+ return path.join(
85
+ process.env.APPDATA || path.join(homedir(), 'AppData', 'Roaming'),
86
+ 'knowledge',
87
+ );
88
+ }
89
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), '.config'), 'knowledge');
90
+ }
91
+
92
+ async function readStdin() {
93
+ return new Promise((resolveP) => {
94
+ let data = '';
95
+ if (process.stdin.isTTY) return resolveP('');
96
+ process.stdin.setEncoding('utf-8');
97
+ process.stdin.on('data', (chunk) => (data += chunk));
98
+ process.stdin.on('end', () => resolveP(data));
99
+ setTimeout(() => resolveP(data), 1500);
100
+ });
101
+ }
102
+
103
+ function markerPath(sessionId) {
104
+ return path.join(dataDir(), '.first-prompt-seen', sessionId);
105
+ }
106
+
107
+ function hasFired(sessionId) {
108
+ try {
109
+ return fs.existsSync(markerPath(sessionId));
110
+ } catch {
111
+ return false;
112
+ }
113
+ }
114
+
115
+ function recordFired(sessionId) {
116
+ try {
117
+ const file = markerPath(sessionId);
118
+ fs.mkdirSync(path.dirname(file), { recursive: true });
119
+ fs.writeFileSync(file, new Date().toISOString(), 'utf-8');
120
+ } catch (err) {
121
+ warn(`marker write failed: ${err?.message || err}`);
122
+ }
123
+ }
124
+
125
+ function isSkippablePrompt(prompt) {
126
+ const trimmed = (prompt ?? '').trim();
127
+ if (trimmed.length < 10) return true;
128
+ if (trimmed.startsWith('/')) return true;
129
+ if (trimmed.startsWith('!')) return true;
130
+ return false;
131
+ }
132
+
133
+ async function loadSearch() {
134
+ const distSearch = resolve(__dirname, '..', '..', 'dist', 'knowledge', 'search.js');
135
+ if (!fs.existsSync(distSearch)) {
136
+ warn(`dist not built: ${distSearch} (run \`npm run build\`)`);
137
+ return null;
138
+ }
139
+ try {
140
+ const mod = await import(`file://${distSearch.replace(/\\/g, '/')}`);
141
+ if (typeof mod.searchKnowledge !== 'function') {
142
+ warn('searchKnowledge not exported');
143
+ return null;
144
+ }
145
+ return mod.searchKnowledge;
146
+ } catch (err) {
147
+ warn(`import failed: ${err?.message || err}`);
148
+ return null;
149
+ }
150
+ }
151
+
152
+ function renderHits(hits, budgetChars) {
153
+ if (!hits || hits.length === 0) return null;
154
+
155
+ const header =
156
+ '## Knowledge — top hits for your first prompt\n' +
157
+ '\n' +
158
+ '_Injected automatically by agent-knowledge. Query these entries with `knowledge` (action=read, path=…) before deciding whether to issue a wider `knowledge_search`._\n' +
159
+ '\n';
160
+
161
+ let used = header.length;
162
+ const lines = [];
163
+ for (const hit of hits) {
164
+ const title = hit.entry?.title || hit.entry?.path || '(untitled)';
165
+ const pathStr = hit.entry?.path ?? '';
166
+ const score = typeof hit.score === 'number' ? hit.score.toFixed(2) : '?';
167
+ const excerpt = (hit.excerpt ?? '').replace(/\s+/g, ' ').trim().slice(0, 220);
168
+ const line = `- **${title}** (\`${pathStr}\`, score ${score}) — ${excerpt}`;
169
+ if (used + line.length + 1 > budgetChars) break;
170
+ lines.push(line);
171
+ used += line.length + 1;
172
+ }
173
+ if (lines.length === 0) return null;
174
+
175
+ return header + lines.join('\n') + '\n';
176
+ }
177
+
178
+ async function main() {
179
+ if (!isEnabled()) return emit(null);
180
+
181
+ const raw = await readStdin();
182
+ let payload = {};
183
+ if (raw) {
184
+ try {
185
+ payload = JSON.parse(raw);
186
+ } catch {
187
+ /* ignore — host may not pipe JSON */
188
+ }
189
+ }
190
+
191
+ const sessionId = payload.session_id || process.env.CLAUDE_SESSION_ID;
192
+ const prompt = payload.prompt;
193
+
194
+ if (!sessionId || typeof prompt !== 'string') return emit(null);
195
+ if (hasFired(sessionId)) return emit(null);
196
+
197
+ // IMPORTANT: don't burn the marker on skip-gates. If the user starts with
198
+ // `/clear`, `!bash`, or "hi", we want the NEXT real prompt to still get
199
+ // injection. Same for missing-dist / missing-memoryDir: those are setup
200
+ // states that might be fixed before the agent's next turn. Only burn the
201
+ // marker once a real search has actually run against a real KB.
202
+ if (isSkippablePrompt(prompt)) return emit(null);
203
+
204
+ const searchFn = await loadSearch();
205
+ if (!searchFn) return emit(null);
206
+
207
+ const dir = memoryDir();
208
+ if (!fs.existsSync(dir)) return emit(null);
209
+
210
+ let hits;
211
+ try {
212
+ hits = searchFn(dir, prompt.trim(), { maxResults: maxHits(), mmr: true });
213
+ } catch (err) {
214
+ warn(`search failed: ${err?.message || err}`);
215
+ recordFired(sessionId);
216
+ return emit(null);
217
+ }
218
+
219
+ recordFired(sessionId);
220
+
221
+ const budgetChars = tokenBudget() * 4;
222
+ const rendered = renderHits(hits, budgetChars);
223
+ if (!rendered) return emit(null);
224
+ emit(rendered);
225
+ }
226
+
227
+ main().catch((err) => {
228
+ warn(err?.message || String(err));
229
+ emit(null);
230
+ });
@@ -1,34 +1,27 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // =============================================================================
4
- // agent-knowledge PreCompact / Stop hook
4
+ // agent-knowledge PreCompact / Stop hook — memory-flush
5
5
  //
6
- // Flushes a session summary to ~/agent-knowledge/sessions/ before the host
7
- // (Claude Code, Cursor, Codex CLI, etc.) compacts or ends the conversation,
8
- // so the verbatim distillation has something to anchor against later.
6
+ // Two jobs, both best-effort:
9
7
  //
10
- // Fail-open: any error
11
- // is logged to stderr and the hook still prints `{}` so it never blocks the host.
8
+ // 1. Dump the session summary to ~/agent-knowledge/sessions/<project>/ so
9
+ // later distillation/promotion has a durable anchor even if the host
10
+ // garbage-collects the transcript.
12
11
  //
13
- // Wire-up (host-specific — examples):
12
+ // 2. Inject a short "save-your-context" nudge into the host's PreCompact
13
+ // response (`hookSpecificOutput.additionalContext`). The compaction pass
14
+ // is about to summarize — anything important and unsaved should be
15
+ // written to the knowledge base NOW via `knowledge(action="write", …)`.
16
+ // Pre-compaction memory-flush primitive.
14
17
  //
15
- // Claude Code (~/.claude/settings.json):
16
- // {
17
- // "hooks": {
18
- // "PreCompact": [{"matcher": "", "hooks": [
19
- // {"type": "command",
20
- // "command": "node \"$HOME/.claude/mcp-servers/agent-knowledge/scripts/hooks/precompact-flush.mjs\"",
21
- // "timeout": 10}
22
- // ]}],
23
- // "Stop": [{"matcher": "", "hooks": [
24
- // {"type": "command",
25
- // "command": "node \"$HOME/.claude/mcp-servers/agent-knowledge/scripts/hooks/precompact-flush.mjs\"",
26
- // "timeout": 10}
27
- // ]}]
28
- // }
29
- // }
18
+ // Disable the nudge by exporting AGENT_KNOWLEDGE_PRECOMPACT_NUDGE=0 (the disk
19
+ // dump still runs). Set AGENT_KNOWLEDGE_PRECOMPACT_NUDGE=off to suppress both.
30
20
  //
31
- // Reads hook JSON from stdin (the host pipes it). The fields we look at:
21
+ // Fail-open: every error path prints a valid JSON response so the host never
22
+ // blocks on this hook.
23
+ //
24
+ // Reads hook JSON from stdin (the host pipes it). Fields used:
32
25
  // { session_id, hook_event_name, cwd? }
33
26
  // =============================================================================
34
27
 
@@ -40,15 +33,39 @@ import { homedir } from 'os';
40
33
  const __filename = fileURLToPath(import.meta.url);
41
34
  const __dirname = dirname(__filename);
42
35
 
43
- function fail(msg) {
44
- process.stderr.write(`[precompact-flush] ${msg}\n`);
45
- process.stdout.write('{}\n');
36
+ const NUDGE_MODE = (process.env.AGENT_KNOWLEDGE_PRECOMPACT_NUDGE ?? '1').trim().toLowerCase();
37
+ const nudgeEnabled = NUDGE_MODE !== '0' && NUDGE_MODE !== 'false' && NUDGE_MODE !== 'off';
38
+ const diskDumpEnabled = NUDGE_MODE !== 'off';
39
+
40
+ const NUDGE_TEXT = [
41
+ '## PreCompact — memory-flush nudge',
42
+ '',
43
+ 'The host is about to compact the conversation. Anything you learned this',
44
+ 'turn that the next session will need MUST be written to the knowledge base',
45
+ 'before the summary replaces the transcript. Use:',
46
+ '',
47
+ ' `knowledge(action="write", category="decisions"|"notes"|"workflows", filename=..., content=...)`',
48
+ '',
49
+ 'Candidates worth a write: architectural decisions, non-obvious gotchas,',
50
+ 'hard-won commands, people/ownership facts, project state. Skip transient',
51
+ 'things (file diffs, TODO lists, in-flight plans — plan/task systems own those).',
52
+ ].join('\n');
53
+
54
+ function emitResult(additionalContext) {
55
+ const payload = additionalContext
56
+ ? {
57
+ hookSpecificOutput: {
58
+ hookEventName: 'PreCompact',
59
+ additionalContext,
60
+ },
61
+ }
62
+ : {};
63
+ process.stdout.write(JSON.stringify(payload) + '\n');
46
64
  process.exit(0);
47
65
  }
48
66
 
49
- function ok() {
50
- process.stdout.write('{}\n');
51
- process.exit(0);
67
+ function warn(msg) {
68
+ process.stderr.write(`[precompact-flush] ${msg}\n`);
52
69
  }
53
70
 
54
71
  async function readStdin() {
@@ -58,7 +75,6 @@ async function readStdin() {
58
75
  process.stdin.setEncoding('utf-8');
59
76
  process.stdin.on('data', (chunk) => (data += chunk));
60
77
  process.stdin.on('end', () => resolveP(data));
61
- // Don't hang forever if the host doesn't pipe anything
62
78
  setTimeout(() => resolveP(data), 2000);
63
79
  });
64
80
  }
@@ -75,27 +91,11 @@ function memoryDir() {
75
91
  return process.env.KNOWLEDGE_MEMORY_DIR || join(homedir(), 'agent-knowledge');
76
92
  }
77
93
 
78
- async function main() {
79
- const raw = await readStdin();
80
- let payload = {};
81
- if (raw) {
82
- try {
83
- payload = JSON.parse(raw);
84
- } catch {
85
- // Ignore — host may not have piped JSON
86
- }
87
- }
88
-
89
- const sessionId = payload.session_id || process.env.CLAUDE_SESSION_ID || 'unknown';
90
- const event = payload.hook_event_name || 'precompact';
91
- const cwd = payload.cwd || process.cwd();
92
- const projectSlug = slugify(cwd.split(/[\\/]/).filter(Boolean).pop() || 'project');
93
-
94
- // Try to import the agent-knowledge summary helper directly (ESM dynamic import).
95
- // The compiled output lives next to this script: ../../dist/sessions/summary.js
94
+ async function dumpSummaryToDisk({ sessionId, event, cwd, projectSlug }) {
96
95
  const distSummary = resolve(__dirname, '..', '..', 'dist', 'sessions', 'summary.js');
97
96
  if (!existsSync(distSummary)) {
98
- return fail(`dist not built: ${distSummary} (run \`npm run build\`)`);
97
+ warn(`dist not built: ${distSummary} (run \`npm run build\`)`);
98
+ return;
99
99
  }
100
100
 
101
101
  let summaryFn;
@@ -103,27 +103,32 @@ async function main() {
103
103
  const mod = await import(`file://${distSummary.replace(/\\/g, '/')}`);
104
104
  summaryFn = mod.getSessionSummary;
105
105
  } catch (err) {
106
- return fail(`import failed: ${err?.message || err}`);
106
+ warn(`import failed: ${err?.message || err}`);
107
+ return;
107
108
  }
108
109
  if (typeof summaryFn !== 'function') {
109
- return fail('getSessionSummary not exported from dist/sessions/summary.js');
110
+ warn('getSessionSummary not exported from dist/sessions/summary.js');
111
+ return;
110
112
  }
111
113
 
112
114
  let summary;
113
115
  try {
114
116
  summary = summaryFn(sessionId);
115
117
  } catch (err) {
116
- return fail(`getSessionSummary threw: ${err?.message || err}`);
118
+ warn(`getSessionSummary threw: ${err?.message || err}`);
119
+ return;
117
120
  }
118
121
  if (!summary) {
119
- return fail(`session ${sessionId} not found — nothing to flush`);
122
+ warn(`session ${sessionId} not found — nothing to flush`);
123
+ return;
120
124
  }
121
125
 
122
126
  const outDir = join(memoryDir(), 'sessions', projectSlug);
123
127
  try {
124
128
  mkdirSync(outDir, { recursive: true });
125
129
  } catch (err) {
126
- return fail(`mkdir ${outDir}: ${err?.message || err}`);
130
+ warn(`mkdir ${outDir}: ${err?.message || err}`);
131
+ return;
127
132
  }
128
133
 
129
134
  const stamp = new Date().toISOString().replace(/[:.]/g, '-');
@@ -147,13 +152,13 @@ async function main() {
147
152
 
148
153
  try {
149
154
  writeFileSync(outPath, body, 'utf-8');
155
+ warn(`wrote ${outPath}`);
150
156
  } catch (err) {
151
- return fail(`write ${outPath}: ${err?.message || err}`);
157
+ warn(`write ${outPath}: ${err?.message || err}`);
158
+ return;
152
159
  }
153
160
 
154
- process.stderr.write(`[precompact-flush] wrote ${outPath}\n`);
155
-
156
- // Best-effort: append a one-line breadcrumb readable later by `knowledge` action=list
161
+ // Best-effort: append a breadcrumb readable later by `knowledge` action=list
157
162
  try {
158
163
  const breadcrumb = join(memoryDir(), 'sessions', 'index.md');
159
164
  const existing = existsSync(breadcrumb)
@@ -167,8 +172,32 @@ async function main() {
167
172
  } catch {
168
173
  /* ignore */
169
174
  }
175
+ }
176
+
177
+ async function main() {
178
+ const raw = await readStdin();
179
+ let payload = {};
180
+ if (raw) {
181
+ try {
182
+ payload = JSON.parse(raw);
183
+ } catch {
184
+ /* ignore — host may not pipe JSON */
185
+ }
186
+ }
187
+
188
+ const sessionId = payload.session_id || process.env.CLAUDE_SESSION_ID || 'unknown';
189
+ const event = payload.hook_event_name || 'precompact';
190
+ const cwd = payload.cwd || process.cwd();
191
+ const projectSlug = slugify(cwd.split(/[\\/]/).filter(Boolean).pop() || 'project');
192
+
193
+ if (diskDumpEnabled) {
194
+ await dumpSummaryToDisk({ sessionId, event, cwd, projectSlug });
195
+ }
170
196
 
171
- ok();
197
+ emitResult(nudgeEnabled ? NUDGE_TEXT : undefined);
172
198
  }
173
199
 
174
- main().catch((err) => fail(err?.message || String(err)));
200
+ main().catch((err) => {
201
+ warn(err?.message || String(err));
202
+ emitResult(nudgeEnabled ? NUDGE_TEXT : undefined);
203
+ });
@@ -3,17 +3,81 @@
3
3
  // =============================================================================
4
4
  // agent-knowledge SessionStart hook
5
5
  //
6
- // Announces the knowledge dashboard URL.
6
+ // 1. Announces the knowledge dashboard URL.
7
+ // 2. Auto-loads a token-budgeted wakeup payload (L0 identity + L1 top-weighted
8
+ // entries) into the host's additionalContext so the agent starts each
9
+ // session with a small, well-chosen window into the knowledge base — no
10
+ // manual `knowledge action=wakeup` call required.
11
+ //
12
+ // Disable auto-wakeup by exporting AGENT_KNOWLEDGE_AUTOWAKE=0. Tune budget
13
+ // with AGENT_KNOWLEDGE_WAKEUP_BUDGET (default 800 tokens).
14
+ //
15
+ // Fail-open: every error path still prints a valid JSON hook response so the
16
+ // session never blocks on this hook.
7
17
  // =============================================================================
8
18
 
19
+ import { existsSync } from 'fs';
20
+ import { dirname, resolve } from 'path';
21
+ import { fileURLToPath } from 'url';
22
+
23
+ const __filename = fileURLToPath(import.meta.url);
24
+ const __dirname = dirname(__filename);
25
+
9
26
  const knowledgePort = process.env.AGENT_KNOWLEDGE_PORT || '3423';
27
+ const autoWakeEnabled =
28
+ (process.env.AGENT_KNOWLEDGE_AUTOWAKE ?? '1').trim().toLowerCase() !== '0' &&
29
+ (process.env.AGENT_KNOWLEDGE_AUTOWAKE ?? '1').trim().toLowerCase() !== 'false';
30
+ const wakeupBudget = Number.parseInt(process.env.AGENT_KNOWLEDGE_WAKEUP_BUDGET ?? '800', 10) || 800;
31
+
32
+ function emit(additionalContext) {
33
+ const msg = {
34
+ systemMessage: `agent-knowledge: http://localhost:${knowledgePort}`,
35
+ hookSpecificOutput: {
36
+ hookEventName: 'SessionStart',
37
+ additionalContext,
38
+ },
39
+ };
40
+ process.stdout.write(JSON.stringify(msg) + '\n');
41
+ process.exit(0);
42
+ }
43
+
44
+ async function loadWakeup() {
45
+ const distWakeup = resolve(__dirname, '..', '..', 'dist', 'wakeup.js');
46
+ if (!existsSync(distWakeup)) return null;
47
+ try {
48
+ const mod = await import(`file://${distWakeup.replace(/\\/g, '/')}`);
49
+ if (typeof mod.wakeup !== 'function') return null;
50
+ const result = mod.wakeup({ tokenBudget: wakeupBudget });
51
+ if (result && typeof result.rendered === 'string') return result.rendered;
52
+ } catch (err) {
53
+ process.stderr.write(`[knowledge session-start] wakeup failed: ${err?.message || err}\n`);
54
+ }
55
+ return null;
56
+ }
57
+
58
+ async function main() {
59
+ const dashboardLine = `Knowledge: http://localhost:${knowledgePort}`;
60
+
61
+ if (!autoWakeEnabled) {
62
+ return emit(dashboardLine);
63
+ }
64
+
65
+ const rendered = await loadWakeup();
66
+ if (!rendered) {
67
+ return emit(dashboardLine);
68
+ }
69
+
70
+ const combined = [
71
+ dashboardLine,
72
+ '',
73
+ '--- Knowledge wakeup (auto-loaded; call `knowledge action=wakeup` to refresh) ---',
74
+ rendered,
75
+ ].join('\n');
10
76
 
11
- const msg = {
12
- systemMessage: `agent-knowledge: http://localhost:${knowledgePort}`,
13
- hookSpecificOutput: {
14
- hookEventName: 'SessionStart',
15
- additionalContext: `Knowledge: http://localhost:${knowledgePort}`,
16
- },
17
- };
77
+ emit(combined);
78
+ }
18
79
 
19
- console.log(JSON.stringify(msg));
80
+ main().catch((err) => {
81
+ process.stderr.write(`[knowledge session-start] ${err?.message || err}\n`);
82
+ emit(`Knowledge: http://localhost:${knowledgePort}`);
83
+ });