agent-knowledge 1.9.6 → 1.9.7
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/CHANGELOG.md +28 -0
- package/agent-desk-plugin.json +1 -1
- package/docs/SETUP.md +52 -14
- package/package.json +5 -3
- package/scripts/plugins/opencode/agent-knowledge.ts +341 -0
- package/scripts/setup.js +108 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.9.7 (2026-04-21) — first-class OpenCode plugin + setup auto-wiring
|
|
4
|
+
|
|
5
|
+
OpenCode parity for the lifecycle hooks that were previously Claude-Code-only.
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **`scripts/plugins/opencode/agent-knowledge.ts`** — in-repo opencode plugin, exposed via the new `"./opencode"` subpath export in `package.json`. Users register it with a single line in `opencode.json`: `"plugin": ["agent-knowledge/opencode"]`. Covers four of the six Claude Code lifecycle hooks:
|
|
10
|
+
- `event: session.created` → session-start announce (dashboard URL toast + clears stale first-prompt marker on resume)
|
|
11
|
+
- `chat.message` → first-prompt-inject (searches KB via dashboard `/api/knowledge/search`, prepends rendered hits block to user parts, sets marker, emits a `"injected N hits"` toast)
|
|
12
|
+
- `experimental.session.compacting` → precompact-flush (pushes the "save unsaved knowledge before compaction" nudge into `output.context`)
|
|
13
|
+
- `event: session.deleted` → sessionend-distill (walks `client.session.messages`, writes `~/agent-knowledge/projects/session-opencode-<slug>.md` with turn counts, tool uses, and first 20 user prompts)
|
|
14
|
+
|
|
15
|
+
Honours the same env vars as the Claude hooks (`AGENT_KNOWLEDGE_MEMORY_DIR`, `AGENT_KNOWLEDGE_DATA_DIR`, `AGENT_KNOWLEDGE_PORT`, `AGENT_KNOWLEDGE_FIRSTPROMPT_*`). Fails open on every handler — search timeout, toast failure (CLI mode), SDK error on session walk, disk write failure — so the user is never blocked.
|
|
16
|
+
|
|
17
|
+
- **`scripts/setup.js --host=opencode|all`** — new flag alongside the existing `--agent` (kept for back-compat). Auto-detects `~/.config/opencode/opencode.json` (Linux/macOS) or `%APPDATA%\opencode\opencode.json` (Windows); `--workspace=<path>` configures a project-local config. Idempotently ensures `mcp.agent-knowledge` + `plugin` array contain the plugin id.
|
|
18
|
+
|
|
19
|
+
- **`tests/plugins/opencode.test.ts`** — direct-import vitest suite covering plugin shape, first-prompt gating (short / slash / bang prompts skipped, marker set even on zero-hit, second turn does not re-inject), `AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT=0` kill-switch, compacting context push, session.deleted distill disk output, and fail-open on toast + session-walk errors.
|
|
20
|
+
|
|
21
|
+
### Not ported (no opencode analog)
|
|
22
|
+
|
|
23
|
+
- `session-start-ingest.mjs` — paired with the `/knowledge-ingest` skill flow, which is Claude-Code-specific.
|
|
24
|
+
- `precompact-distill.mjs` — opencode compaction does not expose the transcript to plugins.
|
|
25
|
+
- L0 identity auto-load — opencode has no `additionalContext` equivalent; identity lives in `AGENTS.md` or on-demand `knowledge(action="wakeup")` calls.
|
|
26
|
+
|
|
27
|
+
### Tests
|
|
28
|
+
|
|
29
|
+
571 → 583 passing (12 new assertions across plugin shape, first-prompt gating, compacting context, and session.deleted distill). No changes to the Claude hook suite.
|
|
30
|
+
|
|
3
31
|
## 1.9.6 (2026-04-21) — visible SessionEnd receipts + live dashboard toasts
|
|
4
32
|
|
|
5
33
|
Three-layer visibility for the SessionEnd distill hook, so "did it actually run?" never has to be guessed again.
|
package/agent-desk-plugin.json
CHANGED
package/docs/SETUP.md
CHANGED
|
@@ -258,24 +258,62 @@ See [`docs/HOOKS.md`](HOOKS.md) for the full hook reference including environmen
|
|
|
258
258
|
|
|
259
259
|
### OpenCode Plugins
|
|
260
260
|
|
|
261
|
-
|
|
261
|
+
agent-knowledge ships a first-class opencode plugin at `scripts/plugins/opencode/agent-knowledge.ts`, exposed via the `"./opencode"` subpath export. Register it by adding one line to your `opencode.json`:
|
|
262
262
|
|
|
263
|
-
```
|
|
264
|
-
|
|
265
|
-
|
|
263
|
+
```json
|
|
264
|
+
{
|
|
265
|
+
"$schema": "https://opencode.ai/config.json",
|
|
266
|
+
"mcp": {
|
|
267
|
+
"agent-knowledge": {
|
|
268
|
+
"type": "local",
|
|
269
|
+
"command": ["node", "/absolute/path/to/agent-knowledge/dist/index.js"],
|
|
270
|
+
"enabled": true,
|
|
271
|
+
"timeout": 60000
|
|
272
|
+
}
|
|
273
|
+
},
|
|
274
|
+
"plugin": ["agent-knowledge/opencode"]
|
|
275
|
+
}
|
|
276
|
+
```
|
|
266
277
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
},
|
|
274
|
-
};
|
|
275
|
-
};
|
|
278
|
+
Or let `scripts/setup.js` wire it automatically:
|
|
279
|
+
|
|
280
|
+
```bash
|
|
281
|
+
node scripts/setup.js --host=opencode # global ~/.config/opencode/opencode.json
|
|
282
|
+
node scripts/setup.js --host=opencode --workspace=/proj # workspace-local opencode.json
|
|
283
|
+
node scripts/setup.js --host=all # both Claude Code and OpenCode
|
|
276
284
|
```
|
|
277
285
|
|
|
278
|
-
|
|
286
|
+
#### What the plugin does
|
|
287
|
+
|
|
288
|
+
Mirrors the Claude Code hooks where opencode has an equivalent event:
|
|
289
|
+
|
|
290
|
+
| Claude Code hook | OpenCode analog | Behavior |
|
|
291
|
+
| ------------------------- | --------------------------------- | --------------------------------------------------------------------- |
|
|
292
|
+
| `session-start.js` | `event: session.created` | Dashboard URL toast + clears stale first-prompt marker on resume. |
|
|
293
|
+
| `first-prompt-inject.mjs` | `chat.message` | Searches the KB and prepends a rendered hits block to the user parts. |
|
|
294
|
+
| `precompact-flush.mjs` | `experimental.session.compacting` | Pushes a "save unsaved knowledge before compaction" nudge. |
|
|
295
|
+
| `sessionend-distill.mjs` | `event: session.deleted` | Writes `~/agent-knowledge/projects/session-opencode-<slug>.md`. |
|
|
296
|
+
|
|
297
|
+
Not ported (opencode has no equivalent surface):
|
|
298
|
+
|
|
299
|
+
- `session-start-ingest.mjs` (paired with the `/knowledge-ingest` skill flow).
|
|
300
|
+
- `precompact-distill.mjs` (opencode compaction does not expose the transcript to plugins).
|
|
301
|
+
- L0 identity auto-load (no `additionalContext` equivalent — put identity in `AGENTS.md` or call `knowledge(action="wakeup")` manually).
|
|
302
|
+
|
|
303
|
+
#### Environment variables
|
|
304
|
+
|
|
305
|
+
Same as the Claude hooks, all optional:
|
|
306
|
+
|
|
307
|
+
| Variable | Default | Description |
|
|
308
|
+
| -------------------------------------- | ------------------- | -------------------------------------------------------- |
|
|
309
|
+
| `AGENT_KNOWLEDGE_MEMORY_DIR` | `~/agent-knowledge` | Knowledge base root. |
|
|
310
|
+
| `AGENT_KNOWLEDGE_DATA_DIR` | `<memory>/.data` | Marker/cache dir (first-prompt-seen markers live here). |
|
|
311
|
+
| `AGENT_KNOWLEDGE_PORT` | `3423` | Dashboard port (plugin queries `/api/knowledge/search`). |
|
|
312
|
+
| `AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT` | `1` | Set `0` / `false` / `off` to disable inject entirely. |
|
|
313
|
+
| `AGENT_KNOWLEDGE_FIRSTPROMPT_BUDGET` | `600` | Max inject tokens (chars/4), clamped `[100, 8000]`. |
|
|
314
|
+
| `AGENT_KNOWLEDGE_FIRSTPROMPT_MAX_HITS` | `4` | Max rendered hits, clamped `[1, 20]`. |
|
|
315
|
+
|
|
316
|
+
Every hook fails open — errors during search, toast, session walk, or disk write are swallowed and the user is never blocked.
|
|
279
317
|
|
|
280
318
|
Combine with `AGENTS.md` instructions (see below).
|
|
281
319
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-knowledge",
|
|
3
|
-
"version": "1.9.
|
|
3
|
+
"version": "1.9.7",
|
|
4
4
|
"description": "Cross-session memory and recall for AI agents — git-synced knowledge base, knowledge graph, confidence scoring, hybrid semantic+TF-IDF search, auto-distillation with secrets scrubbing",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -17,7 +17,8 @@
|
|
|
17
17
|
"./dist/lib.js": {
|
|
18
18
|
"types": "./dist/lib.d.ts",
|
|
19
19
|
"default": "./dist/lib.js"
|
|
20
|
-
}
|
|
20
|
+
},
|
|
21
|
+
"./opencode": "./scripts/plugins/opencode/agent-knowledge.ts"
|
|
21
22
|
},
|
|
22
23
|
"bin": {
|
|
23
24
|
"agent-knowledge": "dist/index.js"
|
|
@@ -67,7 +68,8 @@
|
|
|
67
68
|
"model-context-protocol",
|
|
68
69
|
"ai-agents",
|
|
69
70
|
"coding-assistants",
|
|
70
|
-
"claude-code"
|
|
71
|
+
"claude-code",
|
|
72
|
+
"opencode"
|
|
71
73
|
],
|
|
72
74
|
"author": "keshrath",
|
|
73
75
|
"mcpName": "io.github.keshrath/agent-knowledge",
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
// =============================================================================
|
|
2
|
+
// agent-knowledge opencode plugin
|
|
3
|
+
//
|
|
4
|
+
// Ports the Claude Code lifecycle hooks (session-start announce, first-prompt
|
|
5
|
+
// knowledge injection, pre-compact save nudge, session-end distill) to
|
|
6
|
+
// opencode's plugin API (@opencode-ai/plugin).
|
|
7
|
+
//
|
|
8
|
+
// Coverage vs. the Claude hook set:
|
|
9
|
+
// - session.created → session-start.js (dashboard announce)
|
|
10
|
+
// - chat.message → first-prompt-inject.mjs (first-prompt KB inject)
|
|
11
|
+
// - experimental.session.compacting → precompact-flush.mjs (save-context nudge)
|
|
12
|
+
// - session.deleted → sessionend-distill.mjs (session summary file)
|
|
13
|
+
//
|
|
14
|
+
// Gaps (no opencode analog):
|
|
15
|
+
// - session-start-ingest.mjs (paired with /knowledge-ingest skill)
|
|
16
|
+
// - precompact-distill.mjs (opencode compaction doesn't expose the transcript)
|
|
17
|
+
// - L0 identity auto-load (no additionalContext equivalent — use AGENTS.md)
|
|
18
|
+
//
|
|
19
|
+
// Register via opencode.json:
|
|
20
|
+
// {
|
|
21
|
+
// "plugin": ["agent-knowledge/opencode"]
|
|
22
|
+
// }
|
|
23
|
+
//
|
|
24
|
+
// Env vars (same as the Claude hooks):
|
|
25
|
+
// AGENT_KNOWLEDGE_MEMORY_DIR — knowledge base root (default ~/agent-knowledge)
|
|
26
|
+
// AGENT_KNOWLEDGE_DATA_DIR — marker/cache dir (default <memory>/.data)
|
|
27
|
+
// AGENT_KNOWLEDGE_PORT — dashboard port for search (default 3423)
|
|
28
|
+
// AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT — "0" / "false" / "off" to disable inject
|
|
29
|
+
// AGENT_KNOWLEDGE_FIRSTPROMPT_BUDGET — max inject tokens (chars/4, clamped [100,8000])
|
|
30
|
+
// AGENT_KNOWLEDGE_FIRSTPROMPT_MAX_HITS — max rendered hits (clamped [1,20])
|
|
31
|
+
//
|
|
32
|
+
// Fails open on every hook — any error is swallowed, the user is never blocked.
|
|
33
|
+
// =============================================================================
|
|
34
|
+
|
|
35
|
+
import type { Plugin } from '@opencode-ai/plugin';
|
|
36
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
37
|
+
import { homedir } from 'node:os';
|
|
38
|
+
import { join } from 'node:path';
|
|
39
|
+
|
|
40
|
+
// ── Config ──────────────────────────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
function memoryDir(): string {
|
|
43
|
+
return process.env.AGENT_KNOWLEDGE_MEMORY_DIR || join(homedir(), 'agent-knowledge');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function dataDir(): string {
|
|
47
|
+
return process.env.AGENT_KNOWLEDGE_DATA_DIR || join(memoryDir(), '.data');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function markerDir(): string {
|
|
51
|
+
return join(dataDir(), '.first-prompt-seen');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function dashboardUrl(): string {
|
|
55
|
+
const port = process.env.AGENT_KNOWLEDGE_PORT || '3423';
|
|
56
|
+
return `http://localhost:${port}`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function clamp(n: number, lo: number, hi: number): number {
|
|
60
|
+
return Math.max(lo, Math.min(hi, n));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function injectEnabled(): boolean {
|
|
64
|
+
const raw = (process.env.AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT ?? '1').toLowerCase();
|
|
65
|
+
return raw !== '0' && raw !== 'false' && raw !== 'off';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function maxHits(): number {
|
|
69
|
+
const raw = parseInt(process.env.AGENT_KNOWLEDGE_FIRSTPROMPT_MAX_HITS ?? '4', 10);
|
|
70
|
+
return clamp(Number.isFinite(raw) && raw > 0 ? raw : 4, 1, 20);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function budgetChars(): number {
|
|
74
|
+
const raw = parseInt(process.env.AGENT_KNOWLEDGE_FIRSTPROMPT_BUDGET ?? '600', 10);
|
|
75
|
+
return clamp(Number.isFinite(raw) && raw > 0 ? raw : 600, 100, 8000) * 4;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ── Helpers ─────────────────────────────────────────────────────────────────
|
|
79
|
+
|
|
80
|
+
function ensureDir(dir: string): void {
|
|
81
|
+
try {
|
|
82
|
+
mkdirSync(dir, { recursive: true });
|
|
83
|
+
} catch {
|
|
84
|
+
/* ignore */
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function markerPath(sessionId: string): string {
|
|
89
|
+
return join(markerDir(), sessionId);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
type TextPart = { type: 'text'; text?: string };
|
|
93
|
+
|
|
94
|
+
function isTextPart(part: unknown): part is TextPart {
|
|
95
|
+
return !!part && typeof part === 'object' && (part as { type?: unknown }).type === 'text';
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function extractText(parts: unknown[]): string {
|
|
99
|
+
return parts
|
|
100
|
+
.filter(isTextPart)
|
|
101
|
+
.map((p) => p.text ?? '')
|
|
102
|
+
.join('\n')
|
|
103
|
+
.trim();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function shouldInject(text: string): boolean {
|
|
107
|
+
if (!text || text.length < 10) return false;
|
|
108
|
+
const first = text.trimStart().charAt(0);
|
|
109
|
+
return first !== '/' && first !== '!';
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ── Knowledge search via dashboard HTTP ─────────────────────────────────────
|
|
113
|
+
|
|
114
|
+
type Hit = {
|
|
115
|
+
entry?: { path?: string; category?: string; title?: string };
|
|
116
|
+
path?: string;
|
|
117
|
+
score?: number;
|
|
118
|
+
snippet?: string;
|
|
119
|
+
excerpt?: string;
|
|
120
|
+
title?: string;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
async function searchKnowledge(query: string): Promise<Hit[]> {
|
|
124
|
+
try {
|
|
125
|
+
const url = new URL(`${dashboardUrl()}/api/knowledge/search`);
|
|
126
|
+
url.searchParams.set('q', query);
|
|
127
|
+
url.searchParams.set('max_results', String(maxHits()));
|
|
128
|
+
const resp = await fetch(url, { signal: AbortSignal.timeout(3000) });
|
|
129
|
+
if (!resp.ok) return [];
|
|
130
|
+
const data = (await resp.json()) as unknown;
|
|
131
|
+
if (!Array.isArray(data)) return [];
|
|
132
|
+
return (data as Hit[]).slice(0, maxHits());
|
|
133
|
+
} catch {
|
|
134
|
+
return [];
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function renderHits(hits: Hit[]): string {
|
|
139
|
+
if (!hits.length) return '';
|
|
140
|
+
const lines = hits.map((h) => {
|
|
141
|
+
const path = h.entry?.path || h.path || h.title || '?';
|
|
142
|
+
const score = typeof h.score === 'number' ? ` (score ${h.score.toFixed(2)})` : '';
|
|
143
|
+
const snippetRaw = h.snippet || h.excerpt || h.entry?.title || '';
|
|
144
|
+
const snippet = snippetRaw.replace(/\s+/g, ' ').slice(0, 200);
|
|
145
|
+
return `- **${path}**${score}${snippet ? ` — ${snippet}` : ''}`;
|
|
146
|
+
});
|
|
147
|
+
const header =
|
|
148
|
+
'## Knowledge — top hits for your first prompt\n\n' +
|
|
149
|
+
'_Injected by agent-knowledge (opencode plugin). Query these entries with the ' +
|
|
150
|
+
'`knowledge` MCP tool (action=read, path=…) before issuing a wider `knowledge_search`._';
|
|
151
|
+
let out = `${header}\n\n${lines.join('\n')}\n`;
|
|
152
|
+
const budget = budgetChars();
|
|
153
|
+
if (out.length > budget) out = out.slice(0, budget) + '\n…';
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ── Session-end distill ─────────────────────────────────────────────────────
|
|
158
|
+
|
|
159
|
+
type ClientLike = {
|
|
160
|
+
session: {
|
|
161
|
+
messages: (opts: { path: { id: string } }) => Promise<unknown>;
|
|
162
|
+
};
|
|
163
|
+
tui?: {
|
|
164
|
+
showToast?: (opts: {
|
|
165
|
+
body?: { title?: string; message: string; variant: string; duration?: number };
|
|
166
|
+
}) => Promise<unknown>;
|
|
167
|
+
};
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
async function distillSession(sessionId: string, client: ClientLike): Promise<void> {
|
|
171
|
+
try {
|
|
172
|
+
const raw = await client.session.messages({ path: { id: sessionId } });
|
|
173
|
+
const list = Array.isArray((raw as { data?: unknown })?.data)
|
|
174
|
+
? ((raw as { data: unknown[] }).data as unknown[])
|
|
175
|
+
: Array.isArray(raw)
|
|
176
|
+
? (raw as unknown[])
|
|
177
|
+
: [];
|
|
178
|
+
if (!list.length) return;
|
|
179
|
+
|
|
180
|
+
let userTurns = 0;
|
|
181
|
+
let assistantTurns = 0;
|
|
182
|
+
let toolUses = 0;
|
|
183
|
+
const userPrompts: string[] = [];
|
|
184
|
+
|
|
185
|
+
for (const m of list) {
|
|
186
|
+
const entry = m as { info?: { role?: string }; parts?: unknown[] };
|
|
187
|
+
const role = entry.info?.role;
|
|
188
|
+
const parts = Array.isArray(entry.parts) ? entry.parts : [];
|
|
189
|
+
if (role === 'user') {
|
|
190
|
+
userTurns++;
|
|
191
|
+
const text = extractText(parts);
|
|
192
|
+
if (text && userPrompts.length < 20) userPrompts.push(text);
|
|
193
|
+
} else if (role === 'assistant') {
|
|
194
|
+
assistantTurns++;
|
|
195
|
+
for (const p of parts) {
|
|
196
|
+
if (p && typeof p === 'object' && (p as { type?: unknown }).type === 'tool') {
|
|
197
|
+
toolUses++;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const slug = sessionId.slice(0, 8);
|
|
204
|
+
const projectsDir = join(memoryDir(), 'projects');
|
|
205
|
+
ensureDir(projectsDir);
|
|
206
|
+
const outPath = join(projectsDir, `session-opencode-${slug}.md`);
|
|
207
|
+
const body =
|
|
208
|
+
[
|
|
209
|
+
'---',
|
|
210
|
+
'type: session-end',
|
|
211
|
+
`session: ${sessionId}`,
|
|
212
|
+
'host: opencode',
|
|
213
|
+
`ended: ${new Date().toISOString()}`,
|
|
214
|
+
`turns: ${userTurns}u/${assistantTurns}a`,
|
|
215
|
+
`tool_uses: ${toolUses}`,
|
|
216
|
+
'---',
|
|
217
|
+
'',
|
|
218
|
+
`# Session ${slug}`,
|
|
219
|
+
'',
|
|
220
|
+
'**Host**: opencode',
|
|
221
|
+
`**Turns**: ${userTurns} user / ${assistantTurns} assistant`,
|
|
222
|
+
`**Tool uses**: ${toolUses}`,
|
|
223
|
+
'',
|
|
224
|
+
'## First user prompts',
|
|
225
|
+
'',
|
|
226
|
+
...userPrompts.map((p) => `- ${p.replace(/\s+/g, ' ').slice(0, 240)}`),
|
|
227
|
+
].join('\n') + '\n';
|
|
228
|
+
writeFileSync(outPath, body);
|
|
229
|
+
} catch {
|
|
230
|
+
/* fail open */
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// ── Plugin entry point ──────────────────────────────────────────────────────
|
|
235
|
+
|
|
236
|
+
export const AgentKnowledgePlugin: Plugin = async ({ client }) => {
|
|
237
|
+
ensureDir(markerDir());
|
|
238
|
+
const typedClient = client as unknown as ClientLike;
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
event: async ({ event }) => {
|
|
242
|
+
try {
|
|
243
|
+
const type = (event as { type?: string }).type;
|
|
244
|
+
if (type === 'session.created') {
|
|
245
|
+
const info = (event as { properties?: { info?: { id?: string } } }).properties?.info;
|
|
246
|
+
if (info?.id) {
|
|
247
|
+
// Resumed sessions reuse the same id — clear stale marker so first-prompt
|
|
248
|
+
// inject re-arms, matching the Claude session-start.js behaviour.
|
|
249
|
+
const p = markerPath(info.id);
|
|
250
|
+
if (existsSync(p)) {
|
|
251
|
+
try {
|
|
252
|
+
writeFileSync(p, '');
|
|
253
|
+
} catch {
|
|
254
|
+
/* ignore */
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
try {
|
|
259
|
+
await typedClient.tui?.showToast?.({
|
|
260
|
+
body: {
|
|
261
|
+
title: 'agent-knowledge',
|
|
262
|
+
message: `dashboard: ${dashboardUrl()}`,
|
|
263
|
+
variant: 'info',
|
|
264
|
+
duration: 3000,
|
|
265
|
+
},
|
|
266
|
+
});
|
|
267
|
+
} catch {
|
|
268
|
+
/* CLI mode / no TUI — ignore */
|
|
269
|
+
}
|
|
270
|
+
} else if (type === 'session.deleted') {
|
|
271
|
+
const id =
|
|
272
|
+
(event as { properties?: { info?: { id?: string }; sessionID?: string } }).properties
|
|
273
|
+
?.info?.id ||
|
|
274
|
+
(event as { properties?: { sessionID?: string } }).properties?.sessionID;
|
|
275
|
+
if (id) await distillSession(id, typedClient);
|
|
276
|
+
}
|
|
277
|
+
} catch {
|
|
278
|
+
/* fail open */
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
|
|
282
|
+
'chat.message': async (input, output) => {
|
|
283
|
+
if (!injectEnabled()) return;
|
|
284
|
+
try {
|
|
285
|
+
const parts = (output as { parts?: unknown[] }).parts;
|
|
286
|
+
if (!Array.isArray(parts)) return;
|
|
287
|
+
const text = extractText(parts);
|
|
288
|
+
if (!shouldInject(text)) return;
|
|
289
|
+
|
|
290
|
+
const marker = markerPath(input.sessionID);
|
|
291
|
+
if (existsSync(marker)) return;
|
|
292
|
+
|
|
293
|
+
const hits = await searchKnowledge(text);
|
|
294
|
+
// Always set marker, even on zero-hit — don't burn searches on every turn
|
|
295
|
+
try {
|
|
296
|
+
writeFileSync(marker, String(Date.now()));
|
|
297
|
+
} catch {
|
|
298
|
+
/* ignore */
|
|
299
|
+
}
|
|
300
|
+
if (!hits.length) return;
|
|
301
|
+
|
|
302
|
+
const rendered = renderHits(hits);
|
|
303
|
+
if (!rendered) return;
|
|
304
|
+
|
|
305
|
+
// Prepend so the model sees the knowledge block before the user question.
|
|
306
|
+
(parts as unknown[]).unshift({ type: 'text', text: rendered });
|
|
307
|
+
|
|
308
|
+
try {
|
|
309
|
+
await typedClient.tui?.showToast?.({
|
|
310
|
+
body: {
|
|
311
|
+
title: 'agent-knowledge',
|
|
312
|
+
message: `injected ${hits.length} hit${hits.length === 1 ? '' : 's'}`,
|
|
313
|
+
variant: 'success',
|
|
314
|
+
duration: 2500,
|
|
315
|
+
},
|
|
316
|
+
});
|
|
317
|
+
} catch {
|
|
318
|
+
/* ignore */
|
|
319
|
+
}
|
|
320
|
+
} catch {
|
|
321
|
+
/* fail open */
|
|
322
|
+
}
|
|
323
|
+
},
|
|
324
|
+
|
|
325
|
+
'experimental.session.compacting': async (_input, output) => {
|
|
326
|
+
try {
|
|
327
|
+
output.context.push(
|
|
328
|
+
'## Save unsaved knowledge before compaction\n\n' +
|
|
329
|
+
'Before the transcript is compacted, write any important facts, decisions, or ' +
|
|
330
|
+
'workflows to agent-knowledge via the `knowledge` MCP tool (action=write). ' +
|
|
331
|
+
'Compaction summarises the conversation away — durable facts must live in the ' +
|
|
332
|
+
'knowledge base to survive.',
|
|
333
|
+
);
|
|
334
|
+
} catch {
|
|
335
|
+
/* fail open */
|
|
336
|
+
}
|
|
337
|
+
},
|
|
338
|
+
};
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
export default AgentKnowledgePlugin;
|
package/scripts/setup.js
CHANGED
|
@@ -4,16 +4,21 @@
|
|
|
4
4
|
// agent-knowledge setup script
|
|
5
5
|
//
|
|
6
6
|
// Configures an MCP-compatible AI agent to use agent-knowledge.
|
|
7
|
-
//
|
|
7
|
+
// Supports: Claude Code (auto-detected via ~/.claude.json) and OpenCode
|
|
8
|
+
// (auto-detected via ~/.config/opencode/opencode.json on Linux/macOS or
|
|
9
|
+
// %APPDATA%\opencode\opencode.json on Windows).
|
|
8
10
|
//
|
|
9
11
|
// What it does:
|
|
10
12
|
// - Builds the project if dist/ is missing
|
|
11
13
|
// - Registers the MCP server in the agent's config
|
|
12
14
|
// - Adds lifecycle hooks for Claude Code (SessionStart banner, PreCompact
|
|
13
15
|
// flush + distill, SessionEnd distill)
|
|
16
|
+
// - Registers the opencode plugin ("agent-knowledge/opencode") in opencode.json
|
|
14
17
|
// - Adds permission for mcp__agent-knowledge__* tools
|
|
15
18
|
//
|
|
16
|
-
// Usage: node scripts/setup.js [--
|
|
19
|
+
// Usage: node scripts/setup.js [--host=claude|opencode|all|auto]
|
|
20
|
+
// node scripts/setup.js [--agent claude|generic] # deprecated alias
|
|
21
|
+
// node scripts/setup.js --host=opencode --workspace=/path/to/project
|
|
17
22
|
// =============================================================================
|
|
18
23
|
|
|
19
24
|
import { readFileSync, writeFileSync, existsSync, statSync, cpSync, mkdirSync } from 'fs';
|
|
@@ -28,11 +33,42 @@ const HOME = homedir();
|
|
|
28
33
|
const CLAUDE_JSON = join(HOME, '.claude.json');
|
|
29
34
|
const SETTINGS_JSON = join(HOME, '.claude', 'settings.json');
|
|
30
35
|
|
|
31
|
-
|
|
32
|
-
|
|
36
|
+
// OpenCode global config path — per opencode docs / XDG on Linux/macOS,
|
|
37
|
+
// %APPDATA%\opencode on Windows (APPDATA is always defined on supported Windows).
|
|
38
|
+
const OPENCODE_GLOBAL_JSON =
|
|
39
|
+
process.platform === 'win32'
|
|
40
|
+
? join(process.env.APPDATA || join(HOME, 'AppData', 'Roaming'), 'opencode', 'opencode.json')
|
|
41
|
+
: join(HOME, '.config', 'opencode', 'opencode.json');
|
|
42
|
+
|
|
43
|
+
function argValue(name) {
|
|
44
|
+
const eqMatch = process.argv.find((a) => a.startsWith(`--${name}=`));
|
|
45
|
+
if (eqMatch) return eqMatch.slice(name.length + 3);
|
|
46
|
+
const idx = process.argv.findIndex((a) => a === `--${name}`);
|
|
47
|
+
if (idx !== -1 && idx + 1 < process.argv.length) return process.argv[idx + 1];
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const HOST_FLAG = argValue('host') || argValue('agent') || 'auto';
|
|
52
|
+
const WORKSPACE_FLAG = argValue('workspace');
|
|
53
|
+
|
|
54
|
+
function hostSelected(name) {
|
|
55
|
+
if (HOST_FLAG === 'all') return true;
|
|
56
|
+
if (HOST_FLAG === 'auto') {
|
|
57
|
+
if (name === 'claude') return existsSync(CLAUDE_JSON);
|
|
58
|
+
if (name === 'opencode') return existsSync(OPENCODE_GLOBAL_JSON) || !!WORKSPACE_FLAG;
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
// Back-compat: `generic` from the old --agent flag means no host
|
|
62
|
+
if (HOST_FLAG === 'generic') return false;
|
|
63
|
+
return HOST_FLAG === name;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const IS_CLAUDE = hostSelected('claude');
|
|
67
|
+
const IS_OPENCODE = hostSelected('opencode');
|
|
33
68
|
|
|
34
69
|
console.log('agent-knowledge setup\n');
|
|
35
|
-
|
|
70
|
+
const active = [IS_CLAUDE && 'Claude Code', IS_OPENCODE && 'OpenCode'].filter(Boolean);
|
|
71
|
+
console.log(`Hosts: ${active.length ? active.join(', ') : 'Generic (manual MCP config)'}`);
|
|
36
72
|
|
|
37
73
|
// ---------------------------------------------------------------------------
|
|
38
74
|
// Build if needed
|
|
@@ -64,7 +100,7 @@ if (IS_CLAUDE && existsSync(CLAUDE_JSON)) {
|
|
|
64
100
|
|
|
65
101
|
writeFileSync(CLAUDE_JSON, JSON.stringify(config, null, 2));
|
|
66
102
|
console.log(` Added agent-knowledge MCP server → ${distPath}`);
|
|
67
|
-
} else {
|
|
103
|
+
} else if (!IS_OPENCODE) {
|
|
68
104
|
console.log(' Add this to your MCP client config:');
|
|
69
105
|
console.log(' {');
|
|
70
106
|
console.log(' "mcpServers": {');
|
|
@@ -77,6 +113,67 @@ if (IS_CLAUDE && existsSync(CLAUDE_JSON)) {
|
|
|
77
113
|
}
|
|
78
114
|
|
|
79
115
|
// ---------------------------------------------------------------------------
|
|
116
|
+
// Configure OpenCode
|
|
117
|
+
// ---------------------------------------------------------------------------
|
|
118
|
+
|
|
119
|
+
if (IS_OPENCODE) {
|
|
120
|
+
const targets = [];
|
|
121
|
+
if (WORKSPACE_FLAG) {
|
|
122
|
+
const workspacePath = resolve(WORKSPACE_FLAG);
|
|
123
|
+
const cfgPath = join(workspacePath, 'opencode.json');
|
|
124
|
+
targets.push({ label: `workspace: ${workspacePath}`, path: cfgPath });
|
|
125
|
+
} else if (existsSync(OPENCODE_GLOBAL_JSON)) {
|
|
126
|
+
targets.push({ label: 'global', path: OPENCODE_GLOBAL_JSON });
|
|
127
|
+
} else {
|
|
128
|
+
console.log(
|
|
129
|
+
`\nOpenCode: no opencode.json found at ${OPENCODE_GLOBAL_JSON}. Create it or pass --workspace=<path> to configure a project.`,
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
for (const target of targets) {
|
|
134
|
+
console.log(`\nConfiguring OpenCode (${target.label})...`);
|
|
135
|
+
let cfg = {};
|
|
136
|
+
if (existsSync(target.path)) {
|
|
137
|
+
try {
|
|
138
|
+
cfg = JSON.parse(readFileSync(target.path, 'utf-8')) || {};
|
|
139
|
+
} catch (err) {
|
|
140
|
+
console.log(` Warning: could not parse ${target.path}: ${err.message}`);
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
} else {
|
|
144
|
+
mkdirSync(dirname(target.path), { recursive: true });
|
|
145
|
+
cfg = { $schema: 'https://opencode.ai/config.json' };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (!cfg.mcp) cfg.mcp = {};
|
|
149
|
+
if (!cfg.mcp['agent-knowledge']) {
|
|
150
|
+
cfg.mcp['agent-knowledge'] = {
|
|
151
|
+
type: 'local',
|
|
152
|
+
command: ['node', distPath],
|
|
153
|
+
enabled: true,
|
|
154
|
+
timeout: 60000,
|
|
155
|
+
};
|
|
156
|
+
console.log(' Added mcp.agent-knowledge');
|
|
157
|
+
} else {
|
|
158
|
+
console.log(' mcp.agent-knowledge: already configured');
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (!Array.isArray(cfg.plugin)) cfg.plugin = [];
|
|
162
|
+
const pluginId = 'agent-knowledge/opencode';
|
|
163
|
+
const already = cfg.plugin.some((p) =>
|
|
164
|
+
typeof p === 'string' ? p === pluginId : Array.isArray(p) && p[0] === pluginId,
|
|
165
|
+
);
|
|
166
|
+
if (!already) {
|
|
167
|
+
cfg.plugin.push(pluginId);
|
|
168
|
+
console.log(` Added plugin "${pluginId}"`);
|
|
169
|
+
} else {
|
|
170
|
+
console.log(` plugin "${pluginId}": already configured`);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
writeFileSync(target.path, JSON.stringify(cfg, null, 2) + '\n');
|
|
174
|
+
console.log(` Saved ${target.path}`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
80
177
|
|
|
81
178
|
if (!IS_CLAUDE) {
|
|
82
179
|
console.log(`
|
|
@@ -85,7 +182,11 @@ Setup complete!
|
|
|
85
182
|
Start the dashboard: node dist/server.js
|
|
86
183
|
MCP server (stdio): node dist/index.js
|
|
87
184
|
Dashboard URL: http://localhost:3423
|
|
88
|
-
|
|
185
|
+
${
|
|
186
|
+
IS_OPENCODE
|
|
187
|
+
? 'OpenCode: the plugin loads automatically on next session start. See docs/SETUP.md#opencode-plugins for env-var tuning.\n'
|
|
188
|
+
: ''
|
|
189
|
+
}`);
|
|
89
190
|
process.exit(0);
|
|
90
191
|
}
|
|
91
192
|
|