@chatpanel/gateway 0.6.109 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +24 -4
  2. package/bin/chatpanel-gateway-bin.mjs +1 -24
  3. package/bin/chatpanel-gateway.js +3 -97
  4. package/package.json +1 -7
  5. package/src/access-log-store.js +1 -45
  6. package/src/agent.js +2 -256
  7. package/src/anthropic.js +3 -83
  8. package/src/backup-decrypt.js +1 -45
  9. package/src/backup-ingest.js +6 -120
  10. package/src/bridge-supervisor.js +3 -212
  11. package/src/bridge.js +4 -252
  12. package/src/budget.js +1 -117
  13. package/src/config.js +1 -209
  14. package/src/configstore.js +1 -181
  15. package/src/connect-agents.js +22 -179
  16. package/src/diarize-engine.js +1 -188
  17. package/src/egress.js +2 -0
  18. package/src/engine-ledger-store.js +1 -150
  19. package/src/engine.js +1 -132
  20. package/src/entitlement-refresh.js +1 -84
  21. package/src/entitlement.js +1 -76
  22. package/src/extraction.js +4 -294
  23. package/src/freegate.js +1 -47
  24. package/src/gate.js +1 -75
  25. package/src/gateway-token.js +1 -60
  26. package/src/history-store.js +1 -251
  27. package/src/job.js +3 -148
  28. package/src/knowledge.js +3 -215
  29. package/src/local-status.js +6 -102
  30. package/src/log.js +1 -21
  31. package/src/mcp-cli.js +19 -113
  32. package/src/mcp.js +34 -546
  33. package/src/memory-store.js +1 -176
  34. package/src/memory.js +2 -642
  35. package/src/model-integrity.js +1 -82
  36. package/src/model-ledger.js +1 -229
  37. package/src/model-runtime.js +1 -37
  38. package/src/models.js +1 -92
  39. package/src/ner-engine.js +1 -318
  40. package/src/ner.js +1 -113
  41. package/src/observability.js +1 -123
  42. package/src/openai.js +2 -84
  43. package/src/ort.js +1 -52
  44. package/src/parakeet-engine.js +2 -228
  45. package/src/pocket-tts-engine.js +1 -520
  46. package/src/prefs-store.js +1 -149
  47. package/src/project-store.js +1 -139
  48. package/src/project.js +1 -171
  49. package/src/recruit.js +3 -424
  50. package/src/recruiting.js +1 -93
  51. package/src/redact.js +2 -123
  52. package/src/responses.js +2 -80
  53. package/src/router.js +1 -292
  54. package/src/rrf.js +1 -93
  55. package/src/scorecard-store.js +1 -92
  56. package/src/scorecard.js +1 -336
  57. package/src/search-index.js +2 -134
  58. package/src/secure-fetch.js +1 -58
  59. package/src/sentencepiece.js +1 -184
  60. package/src/server.js +10 -2290
  61. package/src/service.js +11 -189
  62. package/src/shape.js +5 -121
  63. package/src/sqlite-store.js +3 -212
  64. package/src/stream.js +5 -182
  65. package/src/structured.js +4 -902
  66. package/src/stt-engine.js +1 -486
  67. package/src/stt-models.js +1 -144
  68. package/src/subject-kinds.js +1 -6
  69. package/src/subject-name.js +1 -97
  70. package/src/team-board.js +6 -338
  71. package/src/team-record.js +1 -226
  72. package/src/team-store.js +1 -261
  73. package/src/team.js +1 -303
  74. package/src/toolrelay.js +3 -122
  75. package/src/tts-engine.js +1 -453
  76. package/src/tts-models.js +1 -254
  77. package/src/tts-remote.js +1 -109
  78. package/src/tts-voice-resolve.js +1 -78
  79. package/src/tts-voices.js +1 -192
  80. package/src/update.js +1 -305
package/src/mcp.js CHANGED
@@ -1,546 +1,34 @@
1
- // `chatpanel-gateway mcp` — a stdio MCP server that exposes the WARM history store
2
- // (chats · meetings · notes) as agent tools. Point any MCP client (Codex, OpenCode,
3
- // Claude Desktop, …) at `chatpanel-gateway mcp` and it gets search/get/list over the
4
- // full local corpus — the reliable fallback when an agent's own context holds only
5
- // hot/recent data.
6
- //
7
- // It PROXIES to the already-running gateway's HTTP API (127.0.0.1:<port>), so there
8
- // is exactly one warm store (the service's) and this process never opens the DB.
9
- // JSON-RPC 2.0 over stdio, newline-delimited — implemented directly (zero deps).
10
- //
11
- // The gateway is the SUPERSET (docs/bridge-gateway-unification.md, U2): this one MCP
12
- // server exposes both the gateway's warm history (chats/meetings/notes, redacted) AND the
13
- // bridge's on-disk skills — so a CLI adds ONE server and gets everything ChatPanel local
14
- // can do. History tools proxy to the gateway; skill tools proxy to the bridge. The bridge
15
- // is optional: if it is not running, the skill tools say so instead of failing the connect.
16
-
17
- import { loadConfig } from './config.js';
18
- import { readBridgeToken } from './bridge.js';
19
- import { ensureGatewayToken } from './gateway-token.js';
20
- import { MEMORY_KINDS, MEMORY_KIND_NAMES } from './memory.js';
21
- import { parseBriefText } from './knowledge.js';
22
-
23
- const PROTOCOL_VERSION = '2024-11-05';
24
- const SERVER = { name: 'chatpanel-history', version: '1.0.0' };
25
-
26
- // MCP servers may return `instructions` from initialize; hosts (Codex, Claude Code, …) fold
27
- // them into the model's context. This is where we STEER tool selection so a person doesn't
28
- // have to say "use ChatPanel": it tells the model that the user's personal meetings/notes/
29
- // chats live here and must be reached through these tools, not by grepping the working dir.
30
- const INSTRUCTIONS = [
31
- 'ChatPanel holds the USER\'S OWN meetings, notes and past chats — transcripts, decisions,',
32
- 'action items, summaries — which usually are NOT in the working directory.',
33
- '',
34
- 'Keep using all your normal tools. ADDITIONALLY, whenever the user\'s question touches a',
35
- 'meeting, call, demo, note, or past conversation ("outcome of the meeting", "what did we',
36
- 'decide", "action items", "notes from yesterday", a person/day/topic in their history),',
37
- 'ALSO consult ChatPanel — it is the source of truth for that personal history:',
38
- ' • smart_search — START HERE: give it the question plus 2-4 of your own keyword',
39
- ' phrasings; it runs them all and fuses the rankings, finding what one query misses.',
40
- ' • search_history — one exact keyword query, when you already know the terms. Search by',
41
- ' CONTENT (not the generic meeting title). Supports filters:',
42
- ' type (chat|meeting|note), since/before (dates or relative like "7d", "yesterday"),',
43
- ' and limit/offset paging. Returns compact snippets, not full bodies.',
44
- ' • get_record — the full text of one result id; use maxChars/offset to page a long',
45
- ' transcript instead of pulling it all into context.',
46
- ' • find_related — follow the graph: given a record id, the records most connected to it.',
47
- '',
48
- 'ChatPanel also holds the user\'s MEMORY — a short list of durable facts about them (their',
49
- 'name, how they want answers written, what they are working on) that applies to EVERY task,',
50
- 'not just ones about their history:',
51
- ' • recall — call it EARLY in a session, and whenever the user states a preference, to see',
52
- ' what is already known. Then simply follow it; do not tell them you looked.',
53
- ' • remember — save a new durable fact when they state one ("call me Alex", "always use',
54
- ' pnpm"). One short sentence. Not for task details or anything true only today.',
55
- ' • forget — remove one when they say it no longer holds.',
56
- 'Prefer these for the user\'s history and combine them with your other tools as you see fit.',
57
- 'Every result states how fresh the local copy is; if something recent is missing it may not',
58
- 'have synced yet — say so rather than concluding it does not exist.',
59
- ].join('\n');
60
-
61
- // The calling agent's self-reported name (from MCP `initialize` clientInfo), so the
62
- // observability dashboard can say WHICH agent read what. Untrusted; the gateway coerces it.
63
- let clientName = 'unknown';
64
-
65
- // Report one tool call to the long-lived gateway service's access log. Fire-and-forget:
66
- // telemetry must never slow, block or fail a tool call. Authorized with the gateway token
67
- // (readable only by this same-user process), so a drive-by localhost page can't forge entries.
68
- // Raw args are sent, but the server REDACTS them before storing (a search query is never
69
- // kept) — and the query already crossed this same loopback on the search call itself.
70
- function reportAccess(evt) {
71
- try {
72
- const token = ensureGatewayToken();
73
- fetch(`${baseUrl()}/v1/observability/access`, {
74
- method: 'POST',
75
- headers: { 'content-type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
76
- body: JSON.stringify(evt),
77
- }).catch(() => {});
78
- } catch { /* no token or gateway down — drop the telemetry, never the call */ }
79
- }
80
-
81
- function baseUrl() {
82
- const env = process.env.CHATPANEL_GATEWAY_URL;
83
- if (env) return env.replace(/\/+$/, '');
84
- let port = 4320;
85
- try {
86
- port = loadConfig().port || 4320;
87
- } catch {
88
- /* default */
89
- }
90
- return `http://127.0.0.1:${port}`;
91
- }
92
-
93
- // The bridge the gateway fronts. Its skills live on disk, so the skill tools proxy here
94
- // rather than through the gateway's history API.
95
- function bridgeBase() {
96
- try {
97
- return String(loadConfig().bridge?.url || 'http://127.0.0.1:4319').replace(/\/+$/, '');
98
- } catch {
99
- return 'http://127.0.0.1:4319';
100
- }
101
- }
102
- function bridgeToken() {
103
- try {
104
- return readBridgeToken(loadConfig().bridge?.token || '');
105
- } catch {
106
- return readBridgeToken('');
107
- }
108
- }
109
- async function bridgeJson(path) {
110
- const token = bridgeToken();
111
- const res = await fetch(bridgeBase() + path, {
112
- headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
113
- });
114
- const data = await res.json().catch(() => ({}));
115
- if (!res.ok || data.ok === false) throw new Error(data?.error || `bridge ${res.status}`);
116
- return data;
117
- }
118
-
119
- const TOOLS = [
120
- {
121
- name: 'smart_search',
122
- description: 'BEST first choice for a question about the user\'s ChatPanel history (meetings, notes, past chats). Ask it a natural-language QUESTION and it expands that into several complementary keyword queries, runs them all, and fuses the rankings — which finds things a single query misses, in one round trip instead of several probes. You know the domain, so pass 2-4 of your own phrasings in `queries` too (e.g. for "what did we decide in the Ben demo": ["Ben demo decisions", "tooling demo action items", "demo outcome next steps"]). Supports the same filters as search_history (type, since, before) and returns snippets with each result\'s id; follow up with get_record for the full text or find_related to expand around a hit. BRIEFS come first when they match: a brief is a maintained page about one person, project or topic, derived from ALL the records that mention it, with every claim citing its record — so for "what do we know about X" read the brief, then open only the records it cites.',
123
- inputSchema: {
124
- type: 'object',
125
- properties: {
126
- question: { type: 'string', description: 'The user\'s question, in natural language.' },
127
- queries: { type: 'array', items: { type: 'string' }, description: 'Your own 2-4 keyword formulations of it — these lead the search.' },
128
- type: { type: 'string', enum: ['brief', 'chat', 'meeting', 'note'], description: 'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".' },
129
- since: { type: 'string', description: 'Earliest date: 2026-08-01, or a window like "7d"/"yesterday".' },
130
- before: { type: 'string', description: 'Latest date: a date or window like `since`.' },
131
- limit: { type: 'number', description: 'Max fused results (default 10).' },
132
- },
133
- required: ['question'],
134
- },
135
- },
136
- {
137
- name: 'search_history',
138
- description: 'Search the user\'s ChatPanel history — their past chats, meeting/call transcripts, and notes — by keyword relevance. Consult this (in ADDITION to your other tools) whenever the question touches a meeting, call, demo, note, or past conversation: "outcome of the meeting", "what did we decide", "action items", "what did <person> say", "notes from yesterday". Filters: `type` (chat|meeting|note), `since`/`before` (a date like 2026-08-01 or a relative window like "7d"/"yesterday"), and `limit`/`offset` for paging. Returns compact SNIPPETS (the matching excerpt) with each record\'s id/title/type/date — token-friendly; call get_record for the full text and find_related to follow connections. This is a LOCAL WARM COPY that syncs from ChatPanel; very recent items may not be here yet — results report how current the index is, so if something is missing it likely has not synced. Meeting titles are often generic ("Zoom Meeting"), so search by CONTENT, not the title.',
139
- inputSchema: {
140
- type: 'object',
141
- properties: {
142
- query: { type: 'string', description: 'Content keywords (topics, names, decisions) — not the meeting title.' },
143
- type: { type: 'string', enum: ['brief', 'chat', 'meeting', 'note'], description: 'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".' },
144
- since: { type: 'string', description: 'Earliest date: 2026-08-01, or a relative window like "7d", "2 weeks", "yesterday".' },
145
- before: { type: 'string', description: 'Latest date: a date or relative window like `since`.' },
146
- limit: { type: 'number', description: 'Max results (default 10).' },
147
- offset: { type: 'number', description: 'Skip N results for paging (default 0).' },
148
- },
149
- required: ['query'],
150
- },
151
- },
152
- {
153
- name: 'get_record',
154
- description: 'Fetch one history record\'s full text by id (chat:<id>, meeting:<id>, note:<id> from search_history). For a long transcript, page it with maxChars + offset instead of pulling it all into context — the result says how many chars remain.',
155
- inputSchema: {
156
- type: 'object',
157
- properties: {
158
- id: { type: 'string', description: 'Record id such as chat:abc, meeting:imp_123, or note:xyz.' },
159
- maxChars: { type: 'number', description: 'Return at most this many characters (token management for long transcripts).' },
160
- offset: { type: 'number', description: 'Start at this character offset — page through with the offset the previous call reports.' },
161
- },
162
- required: ['id'],
163
- },
164
- },
165
- {
166
- name: 'find_related',
167
- description: 'Graph navigation: given a record id (from search_history), return the records most connected to it by shared content — the meetings/notes/chats about the same topic, people or thread. Use it to expand from one hit to the surrounding context instead of re-searching.',
168
- inputSchema: {
169
- type: 'object',
170
- properties: {
171
- id: { type: 'string', description: 'The record id to find neighbours of.' },
172
- limit: { type: 'number', description: 'Max related records (default 5).' },
173
- },
174
- required: ['id'],
175
- },
176
- },
177
- {
178
- name: 'list_history',
179
- description: 'List history records (newest first) with their id, title, type and date — no bodies. Reports how current this warm copy is (its newest record). Use to see the index horizon and browse/page the corpus.',
180
- inputSchema: {
181
- type: 'object',
182
- properties: {
183
- limit: { type: 'number', description: 'Max items (default 50).' },
184
- offset: { type: 'number', description: 'Skip N items for paging (default 0).' },
185
- },
186
- },
187
- },
188
- {
189
- name: 'list_briefs',
190
- description: 'The BRIEFS ChatPanel maintains — one page per person, project or topic that appears across enough records, each claim citing the record it came from. This is the index of what the user\'s corpus KNOWS, as opposed to what it merely contains: read it before asking "what do we know about X", then get_brief for the one you need. Briefs are rebuilt from the records, so they are as current as the last rebuild (dates shown).',
191
- inputSchema: {
192
- type: 'object',
193
- properties: {
194
- limit: { type: 'number', description: 'Max briefs (default 50).' },
195
- offset: { type: 'number', description: 'Skip N for paging (default 0).' },
196
- },
197
- },
198
- },
199
- {
200
- name: 'get_brief',
201
- description: 'One brief as STRUCTURE: the subject, its other spellings, and each claim with the record ids it cites — so you can cite the record rather than the synthesis, and open only what you need with get_record. Prefer this over get_record for a brief:… id; get_record returns the same text as prose.',
202
- inputSchema: {
203
- type: 'object',
204
- properties: {
205
- id: { type: 'string', description: 'A brief id (brief:…) from list_briefs or search results.' },
206
- },
207
- required: ['id'],
208
- },
209
- },
210
- {
211
- name: 'recall',
212
- description: "What ChatPanel already knows about the USER — their name, how they want answers written, their ongoing work and environment. Short and cheap; call it at the START of a session and whenever the user states a preference, then just FOLLOW what it returns without announcing that you checked. Pass the current task in `text` and it also returns the facts relevant to that task, not only the always-on ones. This is memory, not history: for what was said in a meeting or a past chat use smart_search instead.",
213
- inputSchema: {
214
- type: 'object',
215
- properties: {
216
- text: { type: 'string', description: 'What the user is asking about right now, so task-relevant facts come back too. Omit for just the always-on ones.' },
217
- },
218
- },
219
- },
220
- {
221
- name: 'remember',
222
- description: "Save a durable fact about the USER to ChatPanel, carried into every future session on every model and agent — the side panel, other CLIs, everything. Use it the moment they state a standing preference (\"always use pnpm\"), an identity fact (\"call me Alex\") or a constraint that will still be true next week. Do NOT use it for task details, anything obvious from the current work, or notes about a codebase — those belong in the repo. One short self-contained sentence, written in the third person. Saving is a change to the user's own data, so say in a short clause what you saved.",
223
- inputSchema: {
224
- type: 'object',
225
- properties: {
226
- text: { type: 'string', description: 'The fact, one short sentence in the third person ("Prefers pnpm over npm"). Max 280 characters.' },
227
- kind: { type: 'string', enum: MEMORY_KIND_NAMES, description: MEMORY_KIND_NAMES.map((k) => `${k}: ${MEMORY_KINDS[k].hint}`).join(' ') },
228
- tags: { type: 'array', items: { type: 'string' }, description: 'Optional short tags for grouping.' },
229
- },
230
- required: ['text'],
231
- },
232
- },
233
- {
234
- name: 'forget',
235
- description: 'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',
236
- inputSchema: {
237
- type: 'object',
238
- properties: { query: { type: 'string', description: 'The memory to remove: its text, roughly how the user named it, or its id.' } },
239
- required: ['query'],
240
- },
241
- },
242
- {
243
- name: 'list_skills',
244
- description: 'List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill\'s name and one-line description. Call open_skill to load the one that fits the task.',
245
- inputSchema: { type: 'object', properties: {} },
246
- },
247
- {
248
- name: 'open_skill',
249
- description: 'Load one skill\'s full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.',
250
- inputSchema: {
251
- type: 'object',
252
- properties: { name: { type: 'string', description: 'The skill name from list_skills.' } },
253
- required: ['name'],
254
- },
255
- },
256
- {
257
- name: 'read_skill_file',
258
- description: 'Read one reference file a skill\'s instructions point at (any path inside the skill\'s own folder). Use only when the task needs it.',
259
- inputSchema: {
260
- type: 'object',
261
- properties: {
262
- name: { type: 'string', description: 'The skill name.' },
263
- path: { type: 'string', description: 'The reference path as written in the instructions, e.g. references/auth.md.' },
264
- },
265
- required: ['name', 'path'],
266
- },
267
- },
268
- ];
269
-
270
- // A one-line freshness banner from the store's newest record, so every answer states the
271
- // index horizon — the model can then say "not synced yet" instead of "does not exist".
272
- function horizonLine(newest, size) {
273
- if (!newest) return `Index: ${size} records (warm copy synced from ChatPanel).`;
274
- const d = new Date(newest);
275
- const iso = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
276
- return `Index: ${size} records, current through ${iso} (local warm copy — items newer than this may not have synced from ChatPanel yet).`;
277
- }
278
-
279
- // Memory WRITES are admin-gated on the gateway (a drive-by localhost page must not be able to
280
- // install a standing instruction), so they carry the gateway token — readable only by this
281
- // same-user process. Reads need none: an open warm index is the product.
282
- function writeAuth() {
283
- try {
284
- const token = ensureGatewayToken();
285
- return token ? { Authorization: `Bearer ${token}` } : {};
286
- } catch { return {}; }
287
- }
288
-
289
- async function gatewayJson(path, init) {
290
- let res;
291
- try {
292
- res = await fetch(baseUrl() + path, init);
293
- } catch (e) {
294
- // The most common cause by far: the gateway service is not running. Say so, and how to
295
- // fix it, so the agent can relay something actionable instead of a bare fetch error.
296
- throw new Error(`the ChatPanel gateway is not running at ${baseUrl()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${e.message}]`);
297
- }
298
- const data = await res.json().catch(() => ({}));
299
- if (!res.ok) throw new Error(data?.error?.message || `the gateway returned HTTP ${res.status} for ${path}`);
300
- return data;
301
- }
302
-
303
- // Run a tool → a plain-text result an agent can read.
304
- // Parse a since/before value into epoch ms: an ISO-ish date (2026-08-01) or a relative window
305
- // meaning "within the last N" — "7d", "2 weeks", "3 months", "yesterday", "today".
306
- function parseWhen(v) {
307
- if (v == null || v === '') return null;
308
- if (typeof v === 'number') return v;
309
- const s = String(v).trim().toLowerCase();
310
- const DAY = 86_400_000;
311
- if (s === 'today') return Date.now() - DAY;
312
- if (s === 'yesterday') return Date.now() - 2 * DAY;
313
- const rel = /^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(s);
314
- if (rel) {
315
- const n = Number(rel[1]);
316
- const u = rel[2][0];
317
- const mult = u === 'd' ? DAY : u === 'w' ? 7 * DAY : u === 'm' ? 30 * DAY : 365 * DAY;
318
- return Date.now() - n * mult;
319
- }
320
- const t = Date.parse(s);
321
- return Number.isNaN(t) ? null : t;
322
- }
323
-
324
- const fmtRow = (r, i) => `${i + 1}. [${r.id}] ${r.title || '(untitled)'} · ${r.type}${r.date ? ' · ' + new Date(r.date).toISOString().slice(0, 10) : ''}${r.snippet ? `\n ${r.snippet}` : ''}`;
325
-
326
- async function callTool(name, args = {}) {
327
- if (name === 'smart_search') {
328
- const body = {
329
- question: String(args.question || ''),
330
- queries: Array.isArray(args.queries) ? args.queries.map(String) : [],
331
- limit: Number(args.limit) || 10,
332
- };
333
- if (args.type) body.type = String(args.type);
334
- const since = parseWhen(args.since); if (since != null) body.since = since;
335
- const before = parseWhen(args.before); if (before != null) body.before = before;
336
- const data = await gatewayJson('/v1/history/smart-search', {
337
- method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
338
- });
339
- const rows = data.results || [];
340
- const horizon = horizonLine(data.newest, data.size);
341
- const asked = (data.queries || []).map((q) => `"${q}"`).join(', ');
342
- if (!rows.length) {
343
- return `No match for "${args.question}".\nSearched ${data.queries?.length || 0} way(s): ${asked}.\n${horizon}\nIf you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`;
344
- }
345
- return [
346
- horizon, '',
347
- `${rows.length} result(s) for "${args.question}" — searched ${data.queries.length} way(s): ${asked}`,
348
- ...rows.map((r, i) => `${fmtRow(r, i)}${r.foundBy?.length > 1 ? `\n (matched ${r.foundBy.length} of the queries)` : ''}`),
349
- ].join('\n') + '\n\nget_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.';
350
- }
351
- if (name === 'search_history') {
352
- const body = { query: String(args.query || ''), limit: Number(args.limit) || 10, offset: Math.max(0, Number(args.offset) || 0) };
353
- if (args.type) body.type = String(args.type);
354
- const since = parseWhen(args.since); if (since != null) body.since = since;
355
- const before = parseWhen(args.before); if (before != null) body.before = before;
356
- const data = await gatewayJson('/v1/history/search', {
357
- method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
358
- });
359
- const rows = data.results || [];
360
- const horizon = horizonLine(data.newest, data.size);
361
- const filt = [args.type && `type=${args.type}`, args.since && `since=${args.since}`, args.before && `before=${args.before}`].filter(Boolean).join(', ');
362
- const tag = filt ? ` (${filt})` : '';
363
- if (!rows.length) return `No match for "${args.query}"${tag}.\n${horizon}\nIf you expected a recent item, it may not have synced yet — check ChatPanel directly, or broaden the query (titles are often generic; try content keywords, or drop a filter).`;
364
- return [horizon, '', `${rows.length} result(s) for "${args.query}"${tag}:`, ...rows.map(fmtRow)].join('\n')
365
- + '\n\nget_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.';
366
- }
367
- if (name === 'get_record') {
368
- const q = new URLSearchParams({ id: String(args.id || '') });
369
- if (args.maxChars != null) q.set('maxChars', String(Math.max(1, Number(args.maxChars) || 0)));
370
- if (args.offset != null) q.set('offset', String(Math.max(0, Number(args.offset) || 0)));
371
- const data = await gatewayJson(`/v1/history/get?${q}`);
372
- const r = data.record;
373
- const head = `[${r.id}] ${r.title || '(untitled)'} · ${r.type}${r.date ? ' · ' + new Date(r.date).toISOString().slice(0, 10) : ''}`;
374
- const more = r.truncated
375
- ? `\n\n[showing ${r.text.length} of ${r.totalChars} chars (from offset ${r.offset}). For the next part call get_record again with offset=${r.offset + r.text.length}.]`
376
- : '';
377
- return `${head}\n\n${r.text || '(empty)'}${more}`;
378
- }
379
- if (name === 'find_related') {
380
- const data = await gatewayJson(`/v1/history/related?id=${encodeURIComponent(String(args.id || ''))}&limit=${Number(args.limit) || 5}`);
381
- const rows = data.results || [];
382
- if (!rows.length) return `Nothing related to ${args.id} found (or that id isn't in the warm index — run search_history first to get a valid id).`;
383
- return [`Records related to ${args.id}:`, ...rows.map(fmtRow)].join('\n') + '\n\nget_record <id> for full text.';
384
- }
385
- if (name === 'list_history') {
386
- const q = new URLSearchParams({ limit: String(Number(args.limit) || 50), offset: String(Number(args.offset) || 0) });
387
- const data = await gatewayJson(`/v1/history/list?${q}`);
388
- const items = data.items || [];
389
- if (!items.length) return 'History is empty (or the gateway has not been seeded yet — open ChatPanel with warm sync enabled).';
390
- const newest = items[0]?.date || null;
391
- return [horizonLine(newest, data.total), '', `${items.length} of ${data.total} records:`, ...items.map((it) => `[${it.id}] ${it.title || '(untitled)'} · ${it.type}${it.date ? ' · ' + new Date(it.date).toISOString().slice(0, 10) : ''} · ${it.chars} chars`)].join('\n');
392
- }
393
- if (name === 'list_briefs') {
394
- const q = new URLSearchParams({ limit: String(Number(args.limit) || 50), offset: String(Number(args.offset) || 0), type: 'brief' });
395
- const data = await gatewayJson(`/v1/history/list?${q}`);
396
- const items = data.items || [];
397
- if (!items.length) return 'No briefs yet. ChatPanel builds them from the user\'s records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.';
398
- return [
399
- `${items.length} of ${data.total} briefs (each is a page about one subject, with every claim cited):`,
400
- ...items.map((it) => `[${it.id}] ${it.title || '(untitled)'}${it.date ? ' · rebuilt ' + new Date(it.date).toISOString().slice(0, 10) : ''}`),
401
- ].join('\n') + '\n\nget_brief <id> for its claims and the records they cite.';
402
- }
403
- if (name === 'get_brief') {
404
- const id = String(args.id || '');
405
- const data = await gatewayJson(`/v1/history/get?${new URLSearchParams({ id })}`);
406
- const r = data.record;
407
- const brief = parseBriefText(r?.text);
408
- if (!brief) return `${id} is not a brief (type ${r?.type || 'unknown'}). Use get_record for it, or list_briefs for the brief ids.`;
409
- const lines = [`BRIEF ${id} — ${brief.name} (${brief.kind})${brief.aliases.length ? ` · also known as ${brief.aliases.join(', ')}` : ''}`, ''];
410
- lines.push(`${brief.claims.length} claim(s), each with the records it cites:`);
411
- for (const c of brief.claims) {
412
- lines.push(`• ${c.text}`);
413
- if (c.refs.length) lines.push(` cites: ${c.refs.map((x) => `${x.kind}:${x.id}`).join(', ')}`);
414
- }
415
- if (brief.records.length) lines.push('', `Built from ${brief.records.length} record(s) (most recent first): ${brief.records.slice(0, 12).map((x) => x.title).join(' · ')}${brief.records.length > 12 ? ' …' : ''}`);
416
- lines.push('', 'get_record <kind:id> opens a cited record; find_related <id> follows its connections.');
417
- return lines.join('\n');
418
- }
419
- if (name === 'recall') {
420
- const data = await gatewayJson('/v1/memory/recall', {
421
- method: 'POST', headers: { 'content-type': 'application/json' },
422
- body: JSON.stringify({ text: String(args.text || '') }),
423
- });
424
- if (!data.memories?.length) {
425
- return data.size
426
- ? 'Nothing in ChatPanel memory applies here.'
427
- : 'ChatPanel memory is empty — nothing is known about this user yet. Use `remember` when they state something durable about themselves or how they want to work.';
428
- }
429
- // The SHARED rendering, straight from the gateway, so a CLI agent is told exactly what
430
- // the side panel's models are told. Two renderings would drift, invisibly.
431
- return data.block;
432
- }
433
- if (name === 'remember') {
434
- const text = String(args.text || '').trim();
435
- if (!text) return 'remember needs `text` — one short sentence about the user.';
436
- const data = await gatewayJson('/v1/memory/remember', {
437
- method: 'POST', headers: { 'content-type': 'application/json', ...writeAuth() },
438
- body: JSON.stringify({
439
- text,
440
- kind: args.kind ? String(args.kind) : 'fact',
441
- tags: Array.isArray(args.tags) ? args.tags.map(String) : [],
442
- // Attribution is the accountability here. A CLI has no confirm dialog to show, so
443
- // instead every memory an agent writes is stamped with WHICH agent wrote it and
444
- // shows up that way in the extension's Memory page, where the user can correct or
445
- // delete it. Silent and anonymous would be the unacceptable combination.
446
- source: { via: 'mcp', surface: 'mcp', agent: clientName },
447
- }),
448
- });
449
- if (data.action === 'duplicate') return `Already known: "${data.record.text}" — nothing changed.`;
450
- if (data.action === 'update') return `Updated memory to "${data.record.text}" (was "${data.replaced?.text}"). It applies to every future session.`;
451
- return `Remembered: "${data.record.text}". It applies to every future ChatPanel session, on every model.`;
452
- }
453
- if (name === 'forget') {
454
- const query = String(args.query || '').trim();
455
- if (!query) return 'forget needs `query` — the memory to remove.';
456
- const data = await gatewayJson('/v1/memory/forget', {
457
- method: 'POST', headers: { 'content-type': 'application/json', ...writeAuth() }, body: JSON.stringify({ query }),
458
- });
459
- if (!data.removed?.length) return `No memory matches "${query}". Call recall to see what is stored.`;
460
- return `Forgot: ${data.removed.map((m) => `"${m.text}"`).join(', ')}.`;
461
- }
462
- if (name === 'list_skills') {
463
- let data;
464
- try { data = await bridgeJson('/skills'); }
465
- catch (e) { return `Installed skills are unavailable because the ChatPanel bridge is not running at ${bridgeBase()}. Install/start it with:\n curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash\nThen retry. History tools work without the bridge. [${e.message}]`; }
466
- const rows = data.skills || [];
467
- if (!rows.length) return 'No skills installed on this machine yet.';
468
- return [`${rows.length} skill(s) installed:`, ...rows.map((r) => `- ${r.command || r.id}: ${r.description || r.name}${r.origin?.source ? ` (from ${r.origin.source})` : ''}`)].join('\n') + '\n\nUse open_skill with a name to load its instructions.';
469
- }
470
- if (name === 'open_skill') {
471
- let data;
472
- try { data = await bridgeJson(`/skills/${encodeURIComponent(String(args.name || '').trim())}`); }
473
- catch (e) { return `Could not open "${args.name}": ${e.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`; }
474
- return data.skill?.prompt || '(this skill has no extra instructions — just apply it.)';
475
- }
476
- if (name === 'read_skill_file') {
477
- const skill = encodeURIComponent(String(args.name || '').trim());
478
- const path = String(args.path || '').trim().split('/').map(encodeURIComponent).join('/');
479
- let data;
480
- try { data = await bridgeJson(`/skills/${skill}/file/${path}`); }
481
- catch (e) { return `Could not read ${args.path}: ${e.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`; }
482
- return data.text || '(empty)';
483
- }
484
- throw new Error(`unknown tool: ${name}`);
485
- }
486
-
487
- // Dispatch a JSON-RPC request → a response object (or null for a notification).
488
- export async function handleRpc(msg) {
489
- const { id, method, params } = msg || {};
490
- const ok = (result) => ({ jsonrpc: '2.0', id, result });
491
- const err = (code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
492
- try {
493
- switch (method) {
494
- case 'initialize':
495
- clientName = params?.clientInfo?.name || clientName;
496
- return ok({ protocolVersion: PROTOCOL_VERSION, capabilities: { tools: {} }, serverInfo: SERVER, instructions: INSTRUCTIONS });
497
- case 'tools/list':
498
- return ok({ tools: TOOLS });
499
- case 'tools/call': {
500
- const started = Date.now();
501
- try {
502
- const text = await callTool(params?.name, params?.arguments || {});
503
- reportAccess({ client: clientName, tool: params?.name, ok: true, ms: Date.now() - started, args: params?.arguments || {} });
504
- return ok({ content: [{ type: 'text', text }] });
505
- } catch (e) {
506
- reportAccess({ client: clientName, tool: params?.name, ok: false, ms: Date.now() - started, args: params?.arguments || {}, error: e.message });
507
- throw e;
508
- }
509
- }
510
- case 'ping':
511
- return ok({});
512
- default:
513
- if (typeof method === 'string' && method.startsWith('notifications/')) return null; // notification: no reply
514
- if (id === undefined) return null; // other notification
515
- return err(-32601, `method not found: ${method}`);
516
- }
517
- } catch (e) {
518
- // Tool failures come back as a tool result with isError so the agent can react.
519
- if (method === 'tools/call') return ok({ content: [{ type: 'text', text: `Error: ${e.message}` }], isError: true });
520
- return err(-32603, e.message);
521
- }
522
- }
523
-
524
- // Read newline-delimited JSON-RPC from stdin, write responses to stdout.
525
- export async function runMcpServer() {
526
- let buf = '';
527
- process.stdin.setEncoding('utf8');
528
- const write = (obj) => process.stdout.write(JSON.stringify(obj) + '\n');
529
- for await (const chunk of process.stdin) {
530
- buf += chunk;
531
- let nl;
532
- while ((nl = buf.indexOf('\n')) >= 0) {
533
- const line = buf.slice(0, nl).trim();
534
- buf = buf.slice(nl + 1);
535
- if (!line) continue;
536
- let msg;
537
- try {
538
- msg = JSON.parse(line);
539
- } catch {
540
- continue; // ignore malformed lines
541
- }
542
- const reply = await handleRpc(msg);
543
- if (reply) write(reply);
544
- }
545
- }
546
- }
1
+ import{loadConfig as p}from"./config.js";import{readBridgeToken as w}from"./bridge.js";import{ensureGatewayToken as b}from"./gateway-token.js";import{MEMORY_KINDS as _,MEMORY_KIND_NAMES as $}from"./memory.js";import{parseBriefText as C}from"./knowledge.js";const N="2024-11-05",j={name:"chatpanel-history",version:"1.0.0"},O=["ChatPanel holds the USER'S OWN meetings, notes and past chats — transcripts, decisions,","action items, summaries — which usually are NOT in the working directory.","","Keep using all your normal tools. ADDITIONALLY, whenever the user's question touches a",'meeting, call, demo, note, or past conversation ("outcome of the meeting", "what did we','decide", "action items", "notes from yesterday", a person/day/topic in their history),',"ALSO consult ChatPanel — it is the source of truth for that personal history:"," • smart_search — START HERE: give it the question plus 2-4 of your own keyword"," phrasings; it runs them all and fuses the rankings, finding what one query misses."," • search_history — one exact keyword query, when you already know the terms. Search by"," CONTENT (not the generic meeting title). Supports filters:",' type (chat|meeting|note), since/before (dates or relative like "7d", "yesterday"),'," and limit/offset paging. Returns compact snippets, not full bodies."," • get_record — the full text of one result id; use maxChars/offset to page a long"," transcript instead of pulling it all into context."," • find_related — follow the graph: given a record id, the records most connected to it.","","ChatPanel also holds the user's MEMORY — a short list of durable facts about them (their","name, how they want answers written, what they are working on) that applies to EVERY task,","not just ones about their history:"," • recall — call it EARLY in a session, and whenever the user states a preference, to see"," what is already known. Then simply follow it; do not tell them you looked.",' • remember — save a new durable fact when they state one ("call me Alex", "always use',' pnpm"). One short sentence. Not for task details or anything true only today.'," • forget — remove one when they say it no longer holds.","Prefer these for the user's history and combine them with your other tools as you see fit.","Every result states how fresh the local copy is; if something recent is missing it may not","have synced yet — say so rather than concluding it does not exist."].join(`
2
+ `);let d="unknown";function k(i){try{const e=b();fetch(`${m()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(i)}).catch(()=>{})}catch{}}function m(){const i=process.env.CHATPANEL_GATEWAY_URL;if(i)return i.replace(/\/+$/,"");let e=4320;try{e=p().port||4320}catch{}return`http://127.0.0.1:${e}`}function S(){try{return String(p().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function T(){try{return w(p().bridge?.token||"")}catch{return w("")}}async function f(i){const e=T(),t=await fetch(S()+i,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),n=await t.json().catch(()=>({}));if(!t.ok||n.ok===!1)throw new Error(n?.error||`bridge ${t.status}`);return n}const q=[{name:"smart_search",description:'BEST first choice for a question about the user\'s ChatPanel history (meetings, notes, past chats). Ask it a natural-language QUESTION and it expands that into several complementary keyword queries, runs them all, and fuses the rankings — which finds things a single query misses, in one round trip instead of several probes. You know the domain, so pass 2-4 of your own phrasings in `queries` too (e.g. for "what did we decide in the Ben demo": ["Ben demo decisions", "tooling demo action items", "demo outcome next steps"]). Supports the same filters as search_history (type, since, before) and returns snippets with each result\'s id; follow up with get_record for the full text or find_related to expand around a hit. BRIEFS come first when they match: a brief is a maintained page about one person, project or topic, derived from ALL the records that mention it, with every claim citing its record — so for "what do we know about X" read the brief, then open only the records it cites.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in natural language."},queries:{type:"array",items:{type:"string"},description:"Your own 2-4 keyword formulations of it — these lead the search."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a window like "7d"/"yesterday".'},before:{type:"string",description:"Latest date: a date or window like `since`."},limit:{type:"number",description:"Max fused results (default 10)."}},required:["question"]}},{name:"search_history",description:'Search the user\'s ChatPanel history — their past chats, meeting/call transcripts, and notes — by keyword relevance. Consult this (in ADDITION to your other tools) whenever the question touches a meeting, call, demo, note, or past conversation: "outcome of the meeting", "what did we decide", "action items", "what did <person> say", "notes from yesterday". Filters: `type` (chat|meeting|note), `since`/`before` (a date like 2026-08-01 or a relative window like "7d"/"yesterday"), and `limit`/`offset` for paging. Returns compact SNIPPETS (the matching excerpt) with each record\'s id/title/type/date — token-friendly; call get_record for the full text and find_related to follow connections. This is a LOCAL WARM COPY that syncs from ChatPanel; very recent items may not be here yet — results report how current the index is, so if something is missing it likely has not synced. Meeting titles are often generic ("Zoom Meeting"), so search by CONTENT, not the title.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Content keywords (topics, names, decisions) — not the meeting title."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a relative window like "7d", "2 weeks", "yesterday".'},before:{type:"string",description:"Latest date: a date or relative window like `since`."},limit:{type:"number",description:"Max results (default 10)."},offset:{type:"number",description:"Skip N results for paging (default 0)."}},required:["query"]}},{name:"get_record",description:"Fetch one history record's full text by id (chat:<id>, meeting:<id>, note:<id> from search_history). For a long transcript, page it with maxChars + offset instead of pulling it all into context — the result says how many chars remain.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Record id such as chat:abc, meeting:imp_123, or note:xyz."},maxChars:{type:"number",description:"Return at most this many characters (token management for long transcripts)."},offset:{type:"number",description:"Start at this character offset — page through with the offset the previous call reports."}},required:["id"]}},{name:"find_related",description:"Graph navigation: given a record id (from search_history), return the records most connected to it by shared content — the meetings/notes/chats about the same topic, people or thread. Use it to expand from one hit to the surrounding context instead of re-searching.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The record id to find neighbours of."},limit:{type:"number",description:"Max related records (default 5)."}},required:["id"]}},{name:"list_history",description:"List history records (newest first) with their id, title, type and date — no bodies. Reports how current this warm copy is (its newest record). Use to see the index horizon and browse/page the corpus.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max items (default 50)."},offset:{type:"number",description:"Skip N items for paging (default 0)."}}}},{name:"list_briefs",description:`The BRIEFS ChatPanel maintains — one page per person, project or topic that appears across enough records, each claim citing the record it came from. This is the index of what the user's corpus KNOWS, as opposed to what it merely contains: read it before asking "what do we know about X", then get_brief for the one you need. Briefs are rebuilt from the records, so they are as current as the last rebuild (dates shown).`,inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max briefs (default 50)."},offset:{type:"number",description:"Skip N for paging (default 0)."}}}},{name:"get_brief",description:"One brief as STRUCTURE: the subject, its other spellings, and each claim with the record ids it cites — so you can cite the record rather than the synthesis, and open only what you need with get_record. Prefer this over get_record for a brief:… id; get_record returns the same text as prose.",inputSchema:{type:"object",properties:{id:{type:"string",description:"A brief id (brief:…) from list_briefs or search results."}},required:["id"]}},{name:"recall",description:"What ChatPanel already knows about the USER — their name, how they want answers written, their ongoing work and environment. Short and cheap; call it at the START of a session and whenever the user states a preference, then just FOLLOW what it returns without announcing that you checked. Pass the current task in `text` and it also returns the facts relevant to that task, not only the always-on ones. This is memory, not history: for what was said in a meeting or a past chat use smart_search instead.",inputSchema:{type:"object",properties:{text:{type:"string",description:"What the user is asking about right now, so task-relevant facts come back too. Omit for just the always-on ones."}}}},{name:"remember",description:`Save a durable fact about the USER to ChatPanel, carried into every future session on every model and agent — the side panel, other CLIs, everything. Use it the moment they state a standing preference ("always use pnpm"), an identity fact ("call me Alex") or a constraint that will still be true next week. Do NOT use it for task details, anything obvious from the current work, or notes about a codebase — those belong in the repo. One short self-contained sentence, written in the third person. Saving is a change to the user's own data, so say in a short clause what you saved.`,inputSchema:{type:"object",properties:{text:{type:"string",description:'The fact, one short sentence in the third person ("Prefers pnpm over npm"). Max 280 characters.'},kind:{type:"string",enum:$,description:$.map(i=>`${i}: ${_[i].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["text"]}},{name:"forget",description:'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',inputSchema:{type:"object",properties:{query:{type:"string",description:"The memory to remove: its text, roughly how the user named it, or its id."}},required:["query"]}},{name:"list_skills",description:"List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill's name and one-line description. Call open_skill to load the one that fits the task.",inputSchema:{type:"object",properties:{}}},{name:"open_skill",description:"Load one skill's full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name from list_skills."}},required:["name"]}},{name:"read_skill_file",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]}}];function y(i,e){if(!i)return`Index: ${e} records (warm copy synced from ChatPanel).`;const t=new Date(i),n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${n} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function x(){try{const i=b();return i?{Authorization:`Bearer ${i}`}:{}}catch{return{}}}async function c(i,e){let t;try{t=await fetch(m()+i,e)}catch(r){throw new Error(`the ChatPanel gateway is not running at ${m()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${r.message}]`)}const n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n?.error?.message||`the gateway returned HTTP ${t.status} for ${i}`);return n}function u(i){if(i==null||i==="")return null;if(typeof i=="number")return i;const e=String(i).trim().toLowerCase(),t=864e5;if(e==="today")return Date.now()-t;if(e==="yesterday")return Date.now()-2*t;const n=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(n){const o=Number(n[1]),s=n[2][0],a=s==="d"?t:s==="w"?7*t:s==="m"?30*t:365*t;return Date.now()-o*a}const r=Date.parse(e);return Number.isNaN(r)?null:r}const g=(i,e)=>`${e+1}. [${i.id}] ${i.title||"(untitled)"} · ${i.type}${i.date?" · "+new Date(i.date).toISOString().slice(0,10):""}${i.snippet?`
3
+ ${i.snippet}`:""}`;async function R(i,e={}){if(i==="smart_search"){const t={question:String(e.question||""),queries:Array.isArray(e.queries)?e.queries.map(String):[],limit:Number(e.limit)||10};e.type&&(t.type=String(e.type));const n=u(e.since);n!=null&&(t.since=n);const r=u(e.before);r!=null&&(t.before=r);const o=await c("/v1/history/smart-search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),s=o.results||[],a=y(o.newest,o.size),h=(o.queries||[]).map(l=>`"${l}"`).join(", ");return s.length?[a,"",`${s.length} result(s) for "${e.question}" — searched ${o.queries.length} way(s): ${h}`,...s.map((l,v)=>`${g(l,v)}${l.foundBy?.length>1?`
4
+ (matched ${l.foundBy.length} of the queries)`:""}`)].join(`
5
+ `)+`
6
+
7
+ get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.question}".
8
+ Searched ${o.queries?.length||0} way(s): ${h}.
9
+ ${a}
10
+ If you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`}if(i==="search_history"){const t={query:String(e.query||""),limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0)};e.type&&(t.type=String(e.type));const n=u(e.since);n!=null&&(t.since=n);const r=u(e.before);r!=null&&(t.before=r);const o=await c("/v1/history/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),s=o.results||[],a=y(o.newest,o.size),h=[e.type&&`type=${e.type}`,e.since&&`since=${e.since}`,e.before&&`before=${e.before}`].filter(Boolean).join(", "),l=h?` (${h})`:"";return s.length?[a,"",`${s.length} result(s) for "${e.query}"${l}:`,...s.map(g)].join(`
11
+ `)+`
12
+
13
+ get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.query}"${l}.
14
+ ${a}
15
+ If you expected a recent item, it may not have synced yet — check ChatPanel directly, or broaden the query (titles are often generic; try content keywords, or drop a filter).`}if(i==="get_record"){const t=new URLSearchParams({id:String(e.id||"")});e.maxChars!=null&&t.set("maxChars",String(Math.max(1,Number(e.maxChars)||0))),e.offset!=null&&t.set("offset",String(Math.max(0,Number(e.offset)||0)));const r=(await c(`/v1/history/get?${t}`)).record,o=`[${r.id}] ${r.title||"(untitled)"} · ${r.type}${r.date?" · "+new Date(r.date).toISOString().slice(0,10):""}`,s=r.truncated?`
16
+
17
+ [showing ${r.text.length} of ${r.totalChars} chars (from offset ${r.offset}). For the next part call get_record again with offset=${r.offset+r.text.length}.]`:"";return`${o}
18
+
19
+ ${r.text||"(empty)"}${s}`}if(i==="find_related"){const n=(await c(`/v1/history/related?id=${encodeURIComponent(String(e.id||""))}&limit=${Number(e.limit)||5}`)).results||[];return n.length?[`Records related to ${e.id}:`,...n.map(g)].join(`
20
+ `)+`
21
+
22
+ get_record <id> for full text.`:`Nothing related to ${e.id} found (or that id isn't in the warm index — run search_history first to get a valid id).`}if(i==="list_history"){const t=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0)}),n=await c(`/v1/history/list?${t}`),r=n.items||[];if(!r.length)return"History is empty (or the gateway has not been seeded yet — open ChatPanel with warm sync enabled).";const o=r[0]?.date||null;return[y(o,n.total),"",`${r.length} of ${n.total} records:`,...r.map(s=>`[${s.id}] ${s.title||"(untitled)"} · ${s.type}${s.date?" · "+new Date(s.date).toISOString().slice(0,10):""} · ${s.chars} chars`)].join(`
23
+ `)}if(i==="list_briefs"){const t=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0),type:"brief"}),n=await c(`/v1/history/list?${t}`),r=n.items||[];return r.length?[`${r.length} of ${n.total} briefs (each is a page about one subject, with every claim cited):`,...r.map(o=>`[${o.id}] ${o.title||"(untitled)"}${o.date?" · rebuilt "+new Date(o.date).toISOString().slice(0,10):""}`)].join(`
24
+ `)+`
25
+
26
+ get_brief <id> for its claims and the records they cite.`:`No briefs yet. ChatPanel builds them from the user's records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.`}if(i==="get_brief"){const t=String(e.id||""),r=(await c(`/v1/history/get?${new URLSearchParams({id:t})}`)).record,o=C(r?.text);if(!o)return`${t} is not a brief (type ${r?.type||"unknown"}). Use get_record for it, or list_briefs for the brief ids.`;const s=[`BRIEF ${t} — ${o.name} (${o.kind})${o.aliases.length?` · also known as ${o.aliases.join(", ")}`:""}`,""];s.push(`${o.claims.length} claim(s), each with the records it cites:`);for(const a of o.claims)s.push(`• ${a.text}`),a.refs.length&&s.push(` cites: ${a.refs.map(h=>`${h.kind}:${h.id}`).join(", ")}`);return o.records.length&&s.push("",`Built from ${o.records.length} record(s) (most recent first): ${o.records.slice(0,12).map(a=>a.title).join(" · ")}${o.records.length>12?" …":""}`),s.push("","get_record <kind:id> opens a cited record; find_related <id> follows its connections."),s.join(`
27
+ `)}if(i==="recall"){const t=await c("/v1/memory/recall",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:String(e.text||"")})});return t.memories?.length?t.block:t.size?"Nothing in ChatPanel memory applies here.":"ChatPanel memory is empty — nothing is known about this user yet. Use `remember` when they state something durable about themselves or how they want to work."}if(i==="remember"){const t=String(e.text||"").trim();if(!t)return"remember needs `text` — one short sentence about the user.";const n=await c("/v1/memory/remember",{method:"POST",headers:{"content-type":"application/json",...x()},body:JSON.stringify({text:t,kind:e.kind?String(e.kind):"fact",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:"mcp",surface:"mcp",agent:d}})});return n.action==="duplicate"?`Already known: "${n.record.text}" — nothing changed.`:n.action==="update"?`Updated memory to "${n.record.text}" (was "${n.replaced?.text}"). It applies to every future session.`:`Remembered: "${n.record.text}". It applies to every future ChatPanel session, on every model.`}if(i==="forget"){const t=String(e.query||"").trim();if(!t)return"forget needs `query` — the memory to remove.";const n=await c("/v1/memory/forget",{method:"POST",headers:{"content-type":"application/json",...x()},body:JSON.stringify({query:t})});return n.removed?.length?`Forgot: ${n.removed.map(r=>`"${r.text}"`).join(", ")}.`:`No memory matches "${t}". Call recall to see what is stored.`}if(i==="list_skills"){let t;try{t=await f("/skills")}catch(r){return`Installed skills are unavailable because the ChatPanel bridge is not running at ${S()}. Install/start it with:
28
+ curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash
29
+ Then retry. History tools work without the bridge. [${r.message}]`}const n=t.skills||[];return n.length?[`${n.length} skill(s) installed:`,...n.map(r=>`- ${r.command||r.id}: ${r.description||r.name}${r.origin?.source?` (from ${r.origin.source})`:""}`)].join(`
30
+ `)+`
31
+
32
+ Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(i==="open_skill"){let t;try{t=await f(`/skills/${encodeURIComponent(String(e.name||"").trim())}`)}catch(n){return`Could not open "${e.name}": ${n.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return t.skill?.prompt||"(this skill has no extra instructions — just apply it.)"}if(i==="read_skill_file"){const t=encodeURIComponent(String(e.name||"").trim()),n=String(e.path||"").trim().split("/").map(encodeURIComponent).join("/");let r;try{r=await f(`/skills/${t}/file/${n}`)}catch(o){return`Could not read ${e.path}: ${o.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return r.text||"(empty)"}throw new Error(`unknown tool: ${i}`)}async function P(i){const{id:e,method:t,params:n}=i||{},r=s=>({jsonrpc:"2.0",id:e,result:s}),o=(s,a)=>({jsonrpc:"2.0",id:e,error:{code:s,message:a}});try{switch(t){case"initialize":return d=n?.clientInfo?.name||d,r({protocolVersion:N,capabilities:{tools:{}},serverInfo:j,instructions:O});case"tools/list":return r({tools:q});case"tools/call":{const s=Date.now();try{const a=await R(n?.name,n?.arguments||{});return k({client:d,tool:n?.name,ok:!0,ms:Date.now()-s,args:n?.arguments||{}}),r({content:[{type:"text",text:a}]})}catch(a){throw k({client:d,tool:n?.name,ok:!1,ms:Date.now()-s,args:n?.arguments||{},error:a.message}),a}}case"ping":return r({});default:return typeof t=="string"&&t.startsWith("notifications/")||e===void 0?null:o(-32601,`method not found: ${t}`)}}catch(s){return t==="tools/call"?r({content:[{type:"text",text:`Error: ${s.message}`}],isError:!0}):o(-32603,s.message)}}async function M(){let i="";process.stdin.setEncoding("utf8");const e=t=>process.stdout.write(JSON.stringify(t)+`
33
+ `);for await(const t of process.stdin){i+=t;let n;for(;(n=i.indexOf(`
34
+ `))>=0;){const r=i.slice(0,n).trim();if(i=i.slice(n+1),!r)continue;let o;try{o=JSON.parse(r)}catch{continue}const s=await P(o);s&&e(s)}}}export{P as handleRpc,M as runMcpServer};