@datasynx/agentic-ai-cartography 2.0.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +32 -0
- package/README.md +115 -6
- package/dist/api-bin.js +24 -0
- package/dist/api-bin.js.map +1 -0
- package/dist/{bookmarks-VS56KVCO.js → bookmarks-WXHE7GN7.js} +6 -3
- package/dist/{chunk-CJ2PITFA.js → chunk-2SZ5QHGH.js} +71 -9
- package/dist/chunk-2SZ5QHGH.js.map +1 -0
- package/dist/chunk-7QEBFMN4.js +3278 -0
- package/dist/chunk-7QEBFMN4.js.map +1 -0
- package/dist/chunk-7VZH5PFV.js +1134 -0
- package/dist/chunk-7VZH5PFV.js.map +1 -0
- package/dist/chunk-B2AKONVW.js +2465 -0
- package/dist/chunk-B2AKONVW.js.map +1 -0
- package/dist/chunk-WCR47QA2.js +277 -0
- package/dist/chunk-WCR47QA2.js.map +1 -0
- package/dist/cli.js +2367 -663
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +9405 -57913
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3048 -69
- package/dist/index.d.ts +3048 -69
- package/dist/index.js +9150 -2607
- package/dist/index.js.map +1 -1
- package/dist/mcp-bin.js +17 -26
- package/dist/mcp-bin.js.map +1 -1
- package/dist/types-TJWXAQ2L.js +66 -0
- package/llms-full.txt +758 -0
- package/llms.txt +24 -0
- package/package.json +27 -9
- package/scripts/build-llms.mjs +89 -0
- package/scripts/build-mcpb.mjs +31 -0
- package/scripts/gen-api-schemas.ts +29 -0
- package/scripts/gen-docs.ts +123 -0
- package/scripts/sync-version.mjs +51 -0
- package/scripts/validate-server-json.mjs +54 -0
- package/server.json +4 -4
- package/dist/chunk-CJ2PITFA.js.map +0 -1
- package/dist/chunk-D6SRSLBF.js +0 -48
- package/dist/chunk-J6FDZ6HZ.js +0 -142
- package/dist/chunk-J6FDZ6HZ.js.map +0 -1
- package/dist/chunk-UGSNG3QJ.js +0 -49
- package/dist/chunk-UGSNG3QJ.js.map +0 -1
- package/dist/chunk-W7YE6AAH.js +0 -1516
- package/dist/chunk-W7YE6AAH.js.map +0 -1
- package/dist/onnxruntime_binding-6Q6HXASN.node +0 -0
- package/dist/onnxruntime_binding-EKZT2NRK.node +0 -0
- package/dist/onnxruntime_binding-P6S7V3CI.node +0 -0
- package/dist/onnxruntime_binding-PJNNIIUO.node +0 -0
- package/dist/onnxruntime_binding-UN6SPTQK.node +0 -0
- package/dist/sdk-A6NLO3DJ.js +0 -12294
- package/dist/sdk-A6NLO3DJ.js.map +0 -1
- package/dist/sdk-G5D4WQZ4.js +0 -12293
- package/dist/sdk-G5D4WQZ4.js.map +0 -1
- package/dist/sdk-QSTAREST.js +0 -4869
- package/dist/sdk-QSTAREST.js.map +0 -1
- package/dist/sqlite-vec-EZN67B2V.js +0 -40
- package/dist/sqlite-vec-EZN67B2V.js.map +0 -1
- package/dist/sqlite-vec-UK5YYE5T.js +0 -39
- package/dist/sqlite-vec-UK5YYE5T.js.map +0 -1
- package/dist/transformers.node-BTYUTJK5.js +0 -42884
- package/dist/transformers.node-BTYUTJK5.js.map +0 -1
- package/dist/transformers.node-J6PRTTOX.js +0 -42883
- package/dist/transformers.node-J6PRTTOX.js.map +0 -1
- package/dist/types-JG27FR3E.js +0 -29
- package/dist/types-JG27FR3E.js.map +0 -1
- package/scripts/postinstall.mjs +0 -7
- /package/dist/{bookmarks-VS56KVCO.js.map → bookmarks-WXHE7GN7.js.map} +0 -0
- /package/dist/{chunk-D6SRSLBF.js.map → types-TJWXAQ2L.js.map} +0 -0
package/dist/chunk-W7YE6AAH.js
DELETED
|
@@ -1,1516 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
EDGE_RELATIONSHIPS,
|
|
4
|
-
NODE_TYPES,
|
|
5
|
-
NODE_TYPE_GROUPS,
|
|
6
|
-
defaultConfig
|
|
7
|
-
} from "./chunk-J6FDZ6HZ.js";
|
|
8
|
-
import {
|
|
9
|
-
PLATFORM,
|
|
10
|
-
commandExists,
|
|
11
|
-
run,
|
|
12
|
-
scanAllBookmarks,
|
|
13
|
-
scanListeningPorts
|
|
14
|
-
} from "./chunk-CJ2PITFA.js";
|
|
15
|
-
|
|
16
|
-
// src/db.ts
|
|
17
|
-
import Database from "better-sqlite3";
|
|
18
|
-
import { mkdirSync } from "fs";
|
|
19
|
-
import { dirname } from "path";
|
|
20
|
-
import { z } from "zod";
|
|
21
|
-
var SessionRowSchema = z.object({
|
|
22
|
-
id: z.string(),
|
|
23
|
-
mode: z.literal("discover"),
|
|
24
|
-
started_at: z.string(),
|
|
25
|
-
completed_at: z.string().nullable().optional(),
|
|
26
|
-
config: z.string()
|
|
27
|
-
});
|
|
28
|
-
var NodeRowSchema = z.object({
|
|
29
|
-
id: z.string(),
|
|
30
|
-
session_id: z.string(),
|
|
31
|
-
type: z.enum(NODE_TYPES),
|
|
32
|
-
name: z.string(),
|
|
33
|
-
discovered_via: z.string().nullable().optional(),
|
|
34
|
-
discovered_at: z.string(),
|
|
35
|
-
path_id: z.string().nullable().optional(),
|
|
36
|
-
depth: z.number().default(0),
|
|
37
|
-
confidence: z.number().default(0.5),
|
|
38
|
-
metadata: z.string().default("{}"),
|
|
39
|
-
tags: z.string().default("[]"),
|
|
40
|
-
domain: z.string().nullable().optional(),
|
|
41
|
-
sub_domain: z.string().nullable().optional(),
|
|
42
|
-
quality_score: z.number().nullable().optional()
|
|
43
|
-
});
|
|
44
|
-
var EdgeRowSchema = z.object({
|
|
45
|
-
id: z.string(),
|
|
46
|
-
session_id: z.string(),
|
|
47
|
-
source_id: z.string(),
|
|
48
|
-
target_id: z.string(),
|
|
49
|
-
relationship: z.enum(EDGE_RELATIONSHIPS),
|
|
50
|
-
evidence: z.string().nullable().optional(),
|
|
51
|
-
confidence: z.number().default(0.5),
|
|
52
|
-
discovered_at: z.string()
|
|
53
|
-
});
|
|
54
|
-
var EventRowSchema = z.object({
|
|
55
|
-
id: z.string(),
|
|
56
|
-
session_id: z.string(),
|
|
57
|
-
task_id: z.string().nullable().optional(),
|
|
58
|
-
timestamp: z.string(),
|
|
59
|
-
event_type: z.string(),
|
|
60
|
-
process: z.string(),
|
|
61
|
-
pid: z.number(),
|
|
62
|
-
target: z.string().nullable().optional(),
|
|
63
|
-
target_type: z.string().nullable().optional(),
|
|
64
|
-
port: z.number().nullable().optional(),
|
|
65
|
-
duration_ms: z.number().nullable().optional()
|
|
66
|
-
});
|
|
67
|
-
var TaskRowSchema = z.object({
|
|
68
|
-
id: z.string(),
|
|
69
|
-
session_id: z.string(),
|
|
70
|
-
description: z.string().nullable().optional(),
|
|
71
|
-
started_at: z.string(),
|
|
72
|
-
completed_at: z.string().nullable().optional(),
|
|
73
|
-
steps: z.string().default("[]"),
|
|
74
|
-
involved_services: z.string().default("[]"),
|
|
75
|
-
status: z.enum(["active", "completed", "cancelled"])
|
|
76
|
-
});
|
|
77
|
-
var WorkflowRowSchema = z.object({
|
|
78
|
-
id: z.string(),
|
|
79
|
-
session_id: z.string(),
|
|
80
|
-
name: z.string().nullable().optional(),
|
|
81
|
-
pattern: z.string(),
|
|
82
|
-
task_ids: z.string().default("[]"),
|
|
83
|
-
occurrences: z.number().default(1),
|
|
84
|
-
first_seen: z.string(),
|
|
85
|
-
last_seen: z.string(),
|
|
86
|
-
avg_duration_ms: z.number().nullable().optional(),
|
|
87
|
-
involved_services: z.string().default("[]")
|
|
88
|
-
});
|
|
89
|
-
var ConnectionRowSchema = z.object({
|
|
90
|
-
id: z.string(),
|
|
91
|
-
session_id: z.string(),
|
|
92
|
-
source_asset_id: z.string(),
|
|
93
|
-
target_asset_id: z.string(),
|
|
94
|
-
type: z.string().nullable().optional(),
|
|
95
|
-
created_at: z.string()
|
|
96
|
-
});
|
|
97
|
-
var SCHEMA = `
|
|
98
|
-
PRAGMA journal_mode = WAL;
|
|
99
|
-
PRAGMA foreign_keys = ON;
|
|
100
|
-
PRAGMA busy_timeout = 5000;
|
|
101
|
-
|
|
102
|
-
CREATE TABLE IF NOT EXISTS sessions (
|
|
103
|
-
id TEXT PRIMARY KEY,
|
|
104
|
-
mode TEXT NOT NULL CHECK (mode IN ('discover')),
|
|
105
|
-
started_at TEXT NOT NULL,
|
|
106
|
-
completed_at TEXT,
|
|
107
|
-
config TEXT NOT NULL DEFAULT '{}'
|
|
108
|
-
);
|
|
109
|
-
|
|
110
|
-
CREATE TABLE IF NOT EXISTS nodes (
|
|
111
|
-
id TEXT NOT NULL,
|
|
112
|
-
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
113
|
-
type TEXT NOT NULL,
|
|
114
|
-
name TEXT NOT NULL,
|
|
115
|
-
discovered_via TEXT,
|
|
116
|
-
discovered_at TEXT NOT NULL,
|
|
117
|
-
path_id TEXT,
|
|
118
|
-
depth INTEGER DEFAULT 0,
|
|
119
|
-
confidence REAL DEFAULT 0.5,
|
|
120
|
-
metadata TEXT NOT NULL DEFAULT '{}',
|
|
121
|
-
tags TEXT NOT NULL DEFAULT '[]',
|
|
122
|
-
domain TEXT,
|
|
123
|
-
sub_domain TEXT,
|
|
124
|
-
quality_score REAL,
|
|
125
|
-
PRIMARY KEY (id, session_id)
|
|
126
|
-
);
|
|
127
|
-
|
|
128
|
-
CREATE TABLE IF NOT EXISTS connections (
|
|
129
|
-
id TEXT PRIMARY KEY,
|
|
130
|
-
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
131
|
-
source_asset_id TEXT NOT NULL,
|
|
132
|
-
target_asset_id TEXT NOT NULL,
|
|
133
|
-
type TEXT,
|
|
134
|
-
created_at TEXT NOT NULL
|
|
135
|
-
);
|
|
136
|
-
|
|
137
|
-
CREATE TABLE IF NOT EXISTS edges (
|
|
138
|
-
id TEXT PRIMARY KEY,
|
|
139
|
-
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
140
|
-
source_id TEXT NOT NULL,
|
|
141
|
-
target_id TEXT NOT NULL,
|
|
142
|
-
relationship TEXT NOT NULL,
|
|
143
|
-
evidence TEXT,
|
|
144
|
-
confidence REAL DEFAULT 0.5,
|
|
145
|
-
discovered_at TEXT NOT NULL
|
|
146
|
-
);
|
|
147
|
-
|
|
148
|
-
CREATE TABLE IF NOT EXISTS activity_events (
|
|
149
|
-
id TEXT PRIMARY KEY,
|
|
150
|
-
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
151
|
-
task_id TEXT,
|
|
152
|
-
timestamp TEXT NOT NULL,
|
|
153
|
-
event_type TEXT NOT NULL,
|
|
154
|
-
process TEXT NOT NULL,
|
|
155
|
-
pid INTEGER NOT NULL,
|
|
156
|
-
target TEXT,
|
|
157
|
-
target_type TEXT,
|
|
158
|
-
port INTEGER,
|
|
159
|
-
duration_ms INTEGER
|
|
160
|
-
);
|
|
161
|
-
|
|
162
|
-
CREATE TABLE IF NOT EXISTS tasks (
|
|
163
|
-
id TEXT PRIMARY KEY,
|
|
164
|
-
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
165
|
-
description TEXT,
|
|
166
|
-
started_at TEXT NOT NULL,
|
|
167
|
-
completed_at TEXT,
|
|
168
|
-
steps TEXT NOT NULL DEFAULT '[]',
|
|
169
|
-
involved_services TEXT NOT NULL DEFAULT '[]',
|
|
170
|
-
status TEXT DEFAULT 'active' CHECK (status IN ('active','completed','cancelled'))
|
|
171
|
-
);
|
|
172
|
-
|
|
173
|
-
CREATE TABLE IF NOT EXISTS workflows (
|
|
174
|
-
id TEXT PRIMARY KEY,
|
|
175
|
-
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
176
|
-
name TEXT,
|
|
177
|
-
pattern TEXT NOT NULL,
|
|
178
|
-
task_ids TEXT NOT NULL DEFAULT '[]',
|
|
179
|
-
occurrences INTEGER DEFAULT 1,
|
|
180
|
-
first_seen TEXT NOT NULL,
|
|
181
|
-
last_seen TEXT NOT NULL,
|
|
182
|
-
avg_duration_ms INTEGER,
|
|
183
|
-
involved_services TEXT NOT NULL DEFAULT '[]'
|
|
184
|
-
);
|
|
185
|
-
|
|
186
|
-
CREATE TABLE IF NOT EXISTS node_approvals (
|
|
187
|
-
pattern TEXT PRIMARY KEY,
|
|
188
|
-
action TEXT NOT NULL CHECK (action IN ('save','ignore','auto')),
|
|
189
|
-
created_at TEXT NOT NULL
|
|
190
|
-
);
|
|
191
|
-
|
|
192
|
-
CREATE INDEX IF NOT EXISTS idx_nodes_session ON nodes(session_id);
|
|
193
|
-
CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(session_id, type);
|
|
194
|
-
CREATE INDEX IF NOT EXISTS idx_edges_session ON edges(session_id);
|
|
195
|
-
CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(session_id, source_id);
|
|
196
|
-
CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(session_id, target_id);
|
|
197
|
-
CREATE INDEX IF NOT EXISTS idx_events_session ON activity_events(session_id);
|
|
198
|
-
CREATE INDEX IF NOT EXISTS idx_events_task ON activity_events(task_id);
|
|
199
|
-
CREATE INDEX IF NOT EXISTS idx_tasks_session ON tasks(session_id);
|
|
200
|
-
CREATE INDEX IF NOT EXISTS idx_connections_session ON connections(session_id);
|
|
201
|
-
CREATE INDEX IF NOT EXISTS idx_connections_lookup ON connections(session_id, source_asset_id, target_asset_id);
|
|
202
|
-
`;
|
|
203
|
-
var CartographyDB = class {
|
|
204
|
-
db;
|
|
205
|
-
constructor(dbPath) {
|
|
206
|
-
mkdirSync(dirname(dbPath), { recursive: true });
|
|
207
|
-
this.db = new Database(dbPath);
|
|
208
|
-
this.db.pragma("journal_mode = WAL");
|
|
209
|
-
this.db.pragma("foreign_keys = ON");
|
|
210
|
-
this.db.pragma("busy_timeout = 5000");
|
|
211
|
-
this.migrate();
|
|
212
|
-
}
|
|
213
|
-
migrate() {
|
|
214
|
-
const version = this.db.pragma("user_version", { simple: true });
|
|
215
|
-
if (version === 0) {
|
|
216
|
-
this.db.exec(SCHEMA);
|
|
217
|
-
this.db.pragma("user_version = 4");
|
|
218
|
-
return;
|
|
219
|
-
} else if (version === 1) {
|
|
220
|
-
const cols = this.db.prepare("PRAGMA table_info(nodes)").all().map((c) => c.name);
|
|
221
|
-
if (!cols.includes("domain")) this.db.exec("ALTER TABLE nodes ADD COLUMN domain TEXT");
|
|
222
|
-
if (!cols.includes("sub_domain")) this.db.exec("ALTER TABLE nodes ADD COLUMN sub_domain TEXT");
|
|
223
|
-
if (!cols.includes("quality_score")) this.db.exec("ALTER TABLE nodes ADD COLUMN quality_score REAL");
|
|
224
|
-
this.db.exec(`
|
|
225
|
-
CREATE TABLE IF NOT EXISTS connections (
|
|
226
|
-
id TEXT PRIMARY KEY,
|
|
227
|
-
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
228
|
-
source_asset_id TEXT NOT NULL,
|
|
229
|
-
target_asset_id TEXT NOT NULL,
|
|
230
|
-
type TEXT,
|
|
231
|
-
created_at TEXT NOT NULL
|
|
232
|
-
);
|
|
233
|
-
CREATE INDEX IF NOT EXISTS idx_connections_session ON connections(session_id);
|
|
234
|
-
CREATE INDEX IF NOT EXISTS idx_connections_lookup ON connections(session_id, source_asset_id, target_asset_id);
|
|
235
|
-
`);
|
|
236
|
-
this.db.pragma("user_version = 3");
|
|
237
|
-
}
|
|
238
|
-
if (version === 2) {
|
|
239
|
-
this.db.exec("CREATE INDEX IF NOT EXISTS idx_connections_lookup ON connections(session_id, source_asset_id, target_asset_id)");
|
|
240
|
-
this.db.pragma("user_version = 3");
|
|
241
|
-
}
|
|
242
|
-
const current = this.db.pragma("user_version", { simple: true });
|
|
243
|
-
if (current < 4) {
|
|
244
|
-
this.db.exec(`
|
|
245
|
-
CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(session_id, type);
|
|
246
|
-
CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(session_id, source_id);
|
|
247
|
-
CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(session_id, target_id);
|
|
248
|
-
`);
|
|
249
|
-
this.db.pragma("user_version = 4");
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
close() {
|
|
253
|
-
this.db.pragma("optimize");
|
|
254
|
-
this.db.close();
|
|
255
|
-
}
|
|
256
|
-
/**
|
|
257
|
-
* Advanced: the underlying better-sqlite3 connection. Used by the optional
|
|
258
|
-
* semantic-search layer to load the `sqlite-vec` extension and manage its
|
|
259
|
-
* virtual table. Prefer the typed methods above for everything else.
|
|
260
|
-
*/
|
|
261
|
-
rawConnection() {
|
|
262
|
-
return this.db;
|
|
263
|
-
}
|
|
264
|
-
// ── Sessions ────────────────────────────
|
|
265
|
-
createSession(mode, config) {
|
|
266
|
-
const id = crypto.randomUUID();
|
|
267
|
-
this.db.prepare(
|
|
268
|
-
"INSERT INTO sessions (id, mode, started_at, config) VALUES (?, ?, ?, ?)"
|
|
269
|
-
).run(id, mode, (/* @__PURE__ */ new Date()).toISOString(), JSON.stringify(config));
|
|
270
|
-
return id;
|
|
271
|
-
}
|
|
272
|
-
endSession(id) {
|
|
273
|
-
this.db.prepare("UPDATE sessions SET completed_at = ? WHERE id = ?").run((/* @__PURE__ */ new Date()).toISOString(), id);
|
|
274
|
-
}
|
|
275
|
-
getSession(id) {
|
|
276
|
-
const row = this.db.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
|
|
277
|
-
return row ? this.mapSession(row) : void 0;
|
|
278
|
-
}
|
|
279
|
-
getLatestSession(mode) {
|
|
280
|
-
const row = mode ? this.db.prepare("SELECT * FROM sessions WHERE mode = ? ORDER BY rowid DESC LIMIT 1").get(mode) : this.db.prepare("SELECT * FROM sessions ORDER BY rowid DESC LIMIT 1").get();
|
|
281
|
-
return row ? this.mapSession(row) : void 0;
|
|
282
|
-
}
|
|
283
|
-
getSessions() {
|
|
284
|
-
const rows = this.db.prepare("SELECT * FROM sessions ORDER BY rowid DESC").all();
|
|
285
|
-
return rows.map((r) => this.mapSession(r));
|
|
286
|
-
}
|
|
287
|
-
mapSession(r) {
|
|
288
|
-
const v = SessionRowSchema.parse(r);
|
|
289
|
-
return {
|
|
290
|
-
id: v.id,
|
|
291
|
-
mode: v.mode,
|
|
292
|
-
startedAt: v.started_at,
|
|
293
|
-
completedAt: v.completed_at ?? void 0,
|
|
294
|
-
config: v.config
|
|
295
|
-
};
|
|
296
|
-
}
|
|
297
|
-
// ── Nodes ───────────────────────────────
|
|
298
|
-
upsertNode(sessionId, node, depth = 0) {
|
|
299
|
-
this.db.prepare(`
|
|
300
|
-
INSERT OR REPLACE INTO nodes
|
|
301
|
-
(id, session_id, type, name, discovered_via, discovered_at, depth, confidence, metadata, tags,
|
|
302
|
-
domain, sub_domain, quality_score)
|
|
303
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
304
|
-
`).run(
|
|
305
|
-
node.id,
|
|
306
|
-
sessionId,
|
|
307
|
-
node.type,
|
|
308
|
-
node.name,
|
|
309
|
-
node.discoveredVia,
|
|
310
|
-
(/* @__PURE__ */ new Date()).toISOString(),
|
|
311
|
-
depth,
|
|
312
|
-
node.confidence,
|
|
313
|
-
JSON.stringify(node.metadata ?? {}),
|
|
314
|
-
JSON.stringify(node.tags ?? []),
|
|
315
|
-
node.domain ?? null,
|
|
316
|
-
node.subDomain ?? null,
|
|
317
|
-
node.qualityScore ?? null
|
|
318
|
-
);
|
|
319
|
-
}
|
|
320
|
-
getNodes(sessionId, opts) {
|
|
321
|
-
let sql = "SELECT * FROM nodes WHERE session_id = ?";
|
|
322
|
-
if (opts?.limit) {
|
|
323
|
-
sql += ` LIMIT ${opts.limit}`;
|
|
324
|
-
if (opts.offset) sql += ` OFFSET ${opts.offset}`;
|
|
325
|
-
}
|
|
326
|
-
const rows = this.db.prepare(sql).all(sessionId);
|
|
327
|
-
return rows.map((r) => this.mapNode(r));
|
|
328
|
-
}
|
|
329
|
-
getNodeCount(sessionId) {
|
|
330
|
-
const row = this.db.prepare("SELECT COUNT(*) as cnt FROM nodes WHERE session_id = ?").get(sessionId);
|
|
331
|
-
return row.cnt;
|
|
332
|
-
}
|
|
333
|
-
mapNode(r) {
|
|
334
|
-
const v = NodeRowSchema.parse(r);
|
|
335
|
-
return {
|
|
336
|
-
id: v.id,
|
|
337
|
-
sessionId: v.session_id,
|
|
338
|
-
type: v.type,
|
|
339
|
-
name: v.name,
|
|
340
|
-
discoveredVia: v.discovered_via ?? "",
|
|
341
|
-
discoveredAt: v.discovered_at,
|
|
342
|
-
depth: v.depth,
|
|
343
|
-
confidence: v.confidence,
|
|
344
|
-
metadata: JSON.parse(v.metadata),
|
|
345
|
-
tags: JSON.parse(v.tags),
|
|
346
|
-
pathId: v.path_id ?? void 0,
|
|
347
|
-
domain: v.domain ?? void 0,
|
|
348
|
-
subDomain: v.sub_domain ?? void 0,
|
|
349
|
-
qualityScore: v.quality_score ?? void 0
|
|
350
|
-
};
|
|
351
|
-
}
|
|
352
|
-
deleteNode(sessionId, nodeId) {
|
|
353
|
-
this.db.prepare("DELETE FROM nodes WHERE session_id = ? AND id = ?").run(sessionId, nodeId);
|
|
354
|
-
this.db.prepare(
|
|
355
|
-
"DELETE FROM edges WHERE session_id = ? AND (source_id = ? OR target_id = ?)"
|
|
356
|
-
).run(sessionId, nodeId, nodeId);
|
|
357
|
-
}
|
|
358
|
-
// ── Edges ───────────────────────────────
|
|
359
|
-
insertEdge(sessionId, edge) {
|
|
360
|
-
const id = crypto.randomUUID();
|
|
361
|
-
this.db.prepare(`
|
|
362
|
-
INSERT OR IGNORE INTO edges
|
|
363
|
-
(id, session_id, source_id, target_id, relationship, evidence, confidence, discovered_at)
|
|
364
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
365
|
-
`).run(
|
|
366
|
-
id,
|
|
367
|
-
sessionId,
|
|
368
|
-
edge.sourceId,
|
|
369
|
-
edge.targetId,
|
|
370
|
-
edge.relationship,
|
|
371
|
-
edge.evidence,
|
|
372
|
-
edge.confidence,
|
|
373
|
-
(/* @__PURE__ */ new Date()).toISOString()
|
|
374
|
-
);
|
|
375
|
-
}
|
|
376
|
-
getEdges(sessionId, opts) {
|
|
377
|
-
let sql = "SELECT * FROM edges WHERE session_id = ?";
|
|
378
|
-
if (opts?.limit) {
|
|
379
|
-
sql += ` LIMIT ${opts.limit}`;
|
|
380
|
-
if (opts.offset) sql += ` OFFSET ${opts.offset}`;
|
|
381
|
-
}
|
|
382
|
-
const rows = this.db.prepare(sql).all(sessionId);
|
|
383
|
-
return rows.map((r) => {
|
|
384
|
-
const v = EdgeRowSchema.parse(r);
|
|
385
|
-
return {
|
|
386
|
-
id: v.id,
|
|
387
|
-
sessionId: v.session_id,
|
|
388
|
-
sourceId: v.source_id,
|
|
389
|
-
targetId: v.target_id,
|
|
390
|
-
relationship: v.relationship,
|
|
391
|
-
evidence: v.evidence ?? "",
|
|
392
|
-
confidence: v.confidence,
|
|
393
|
-
discoveredAt: v.discovered_at
|
|
394
|
-
};
|
|
395
|
-
});
|
|
396
|
-
}
|
|
397
|
-
// ── Events ──────────────────────────────
|
|
398
|
-
insertEvent(sessionId, event, taskId) {
|
|
399
|
-
const id = crypto.randomUUID();
|
|
400
|
-
this.db.prepare(`
|
|
401
|
-
INSERT INTO activity_events
|
|
402
|
-
(id, session_id, task_id, timestamp, event_type, process, pid, target, target_type, port)
|
|
403
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
404
|
-
`).run(
|
|
405
|
-
id,
|
|
406
|
-
sessionId,
|
|
407
|
-
taskId ?? null,
|
|
408
|
-
(/* @__PURE__ */ new Date()).toISOString(),
|
|
409
|
-
event.eventType,
|
|
410
|
-
event.process,
|
|
411
|
-
event.pid,
|
|
412
|
-
event.target ?? null,
|
|
413
|
-
event.targetType ?? null,
|
|
414
|
-
event.port ?? null
|
|
415
|
-
);
|
|
416
|
-
}
|
|
417
|
-
getEvents(sessionId, since) {
|
|
418
|
-
const rows = since ? this.db.prepare("SELECT * FROM activity_events WHERE session_id = ? AND timestamp > ? ORDER BY timestamp").all(sessionId, since) : this.db.prepare("SELECT * FROM activity_events WHERE session_id = ? ORDER BY timestamp").all(sessionId);
|
|
419
|
-
return rows.map((r) => {
|
|
420
|
-
const v = EventRowSchema.parse(r);
|
|
421
|
-
return {
|
|
422
|
-
id: v.id,
|
|
423
|
-
sessionId: v.session_id,
|
|
424
|
-
taskId: v.task_id ?? void 0,
|
|
425
|
-
timestamp: v.timestamp,
|
|
426
|
-
eventType: v.event_type,
|
|
427
|
-
process: v.process,
|
|
428
|
-
pid: v.pid,
|
|
429
|
-
target: v.target ?? void 0,
|
|
430
|
-
targetType: v.target_type ?? void 0,
|
|
431
|
-
port: v.port ?? void 0,
|
|
432
|
-
durationMs: v.duration_ms ?? void 0
|
|
433
|
-
};
|
|
434
|
-
});
|
|
435
|
-
}
|
|
436
|
-
// ── Tasks ───────────────────────────────
|
|
437
|
-
startTask(sessionId, description) {
|
|
438
|
-
const id = crypto.randomUUID();
|
|
439
|
-
this.db.prepare(`
|
|
440
|
-
INSERT INTO tasks (id, session_id, description, started_at, steps, involved_services, status)
|
|
441
|
-
VALUES (?, ?, ?, ?, '[]', '[]', 'active')
|
|
442
|
-
`).run(id, sessionId, description ?? null, (/* @__PURE__ */ new Date()).toISOString());
|
|
443
|
-
return id;
|
|
444
|
-
}
|
|
445
|
-
endCurrentTask(sessionId) {
|
|
446
|
-
this.db.prepare(`
|
|
447
|
-
UPDATE tasks SET status = 'completed', completed_at = ?
|
|
448
|
-
WHERE session_id = ? AND status = 'active'
|
|
449
|
-
`).run((/* @__PURE__ */ new Date()).toISOString(), sessionId);
|
|
450
|
-
}
|
|
451
|
-
updateTaskDescription(sessionId, description) {
|
|
452
|
-
this.db.prepare(`
|
|
453
|
-
UPDATE tasks SET description = ?
|
|
454
|
-
WHERE session_id = ? AND status = 'active'
|
|
455
|
-
`).run(description, sessionId);
|
|
456
|
-
}
|
|
457
|
-
getActiveTask(sessionId) {
|
|
458
|
-
const row = this.db.prepare(
|
|
459
|
-
"SELECT * FROM tasks WHERE session_id = ? AND status = 'active' LIMIT 1"
|
|
460
|
-
).get(sessionId);
|
|
461
|
-
return row ? this.mapTask(row) : void 0;
|
|
462
|
-
}
|
|
463
|
-
getTasks(sessionId) {
|
|
464
|
-
const rows = this.db.prepare("SELECT * FROM tasks WHERE session_id = ? ORDER BY started_at").all(sessionId);
|
|
465
|
-
return rows.map((r) => this.mapTask(r));
|
|
466
|
-
}
|
|
467
|
-
mapTask(r) {
|
|
468
|
-
const v = TaskRowSchema.parse(r);
|
|
469
|
-
return {
|
|
470
|
-
id: v.id,
|
|
471
|
-
sessionId: v.session_id,
|
|
472
|
-
description: v.description ?? void 0,
|
|
473
|
-
startedAt: v.started_at,
|
|
474
|
-
completedAt: v.completed_at ?? void 0,
|
|
475
|
-
steps: v.steps,
|
|
476
|
-
involvedServices: v.involved_services,
|
|
477
|
-
status: v.status
|
|
478
|
-
};
|
|
479
|
-
}
|
|
480
|
-
// ── Workflows ───────────────────────────
|
|
481
|
-
insertWorkflow(sessionId, data) {
|
|
482
|
-
const id = crypto.randomUUID();
|
|
483
|
-
this.db.prepare(`
|
|
484
|
-
INSERT INTO workflows
|
|
485
|
-
(id, session_id, name, pattern, task_ids, occurrences,
|
|
486
|
-
first_seen, last_seen, avg_duration_ms, involved_services)
|
|
487
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
488
|
-
`).run(
|
|
489
|
-
id,
|
|
490
|
-
sessionId,
|
|
491
|
-
data.name ?? null,
|
|
492
|
-
data.pattern,
|
|
493
|
-
data.taskIds,
|
|
494
|
-
data.occurrences,
|
|
495
|
-
data.firstSeen,
|
|
496
|
-
data.lastSeen,
|
|
497
|
-
data.avgDurationMs,
|
|
498
|
-
data.involvedServices
|
|
499
|
-
);
|
|
500
|
-
}
|
|
501
|
-
getWorkflows(sessionId) {
|
|
502
|
-
const rows = this.db.prepare("SELECT * FROM workflows WHERE session_id = ?").all(sessionId);
|
|
503
|
-
return rows.map((r) => {
|
|
504
|
-
const v = WorkflowRowSchema.parse(r);
|
|
505
|
-
return {
|
|
506
|
-
id: v.id,
|
|
507
|
-
sessionId: v.session_id,
|
|
508
|
-
name: v.name ?? void 0,
|
|
509
|
-
pattern: v.pattern,
|
|
510
|
-
taskIds: v.task_ids,
|
|
511
|
-
occurrences: v.occurrences,
|
|
512
|
-
firstSeen: v.first_seen,
|
|
513
|
-
lastSeen: v.last_seen,
|
|
514
|
-
avgDurationMs: v.avg_duration_ms ?? 0,
|
|
515
|
-
involvedServices: v.involved_services
|
|
516
|
-
};
|
|
517
|
-
});
|
|
518
|
-
}
|
|
519
|
-
// ── Connections (user-created hex map links) ─────────────────────────────
|
|
520
|
-
upsertConnection(sessionId, conn) {
|
|
521
|
-
const existing = this.db.prepare(
|
|
522
|
-
"SELECT id FROM connections WHERE session_id = ? AND source_asset_id = ? AND target_asset_id = ?"
|
|
523
|
-
).get(sessionId, conn.sourceAssetId, conn.targetAssetId);
|
|
524
|
-
if (existing) return existing.id;
|
|
525
|
-
const id = crypto.randomUUID();
|
|
526
|
-
this.db.prepare(`
|
|
527
|
-
INSERT INTO connections (id, session_id, source_asset_id, target_asset_id, type, created_at)
|
|
528
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
529
|
-
`).run(id, sessionId, conn.sourceAssetId, conn.targetAssetId, conn.type ?? null, (/* @__PURE__ */ new Date()).toISOString());
|
|
530
|
-
return id;
|
|
531
|
-
}
|
|
532
|
-
getConnections(sessionId) {
|
|
533
|
-
const rows = this.db.prepare("SELECT * FROM connections WHERE session_id = ?").all(sessionId);
|
|
534
|
-
return rows.map((r) => {
|
|
535
|
-
const v = ConnectionRowSchema.parse(r);
|
|
536
|
-
return {
|
|
537
|
-
id: v.id,
|
|
538
|
-
sessionId: v.session_id,
|
|
539
|
-
sourceAssetId: v.source_asset_id,
|
|
540
|
-
targetAssetId: v.target_asset_id,
|
|
541
|
-
type: v.type ?? void 0,
|
|
542
|
-
createdAt: v.created_at
|
|
543
|
-
};
|
|
544
|
-
});
|
|
545
|
-
}
|
|
546
|
-
deleteConnection(sessionId, connectionId) {
|
|
547
|
-
this.db.prepare("DELETE FROM connections WHERE session_id = ? AND id = ?").run(sessionId, connectionId);
|
|
548
|
-
}
|
|
549
|
-
// ── Approvals ───────────────────────────
|
|
550
|
-
setApproval(pattern, action) {
|
|
551
|
-
this.db.prepare(`
|
|
552
|
-
INSERT OR REPLACE INTO node_approvals (pattern, action, created_at) VALUES (?, ?, ?)
|
|
553
|
-
`).run(pattern, action, (/* @__PURE__ */ new Date()).toISOString());
|
|
554
|
-
}
|
|
555
|
-
getApproval(pattern) {
|
|
556
|
-
const row = this.db.prepare("SELECT action FROM node_approvals WHERE pattern = ?").get(pattern);
|
|
557
|
-
return row?.action;
|
|
558
|
-
}
|
|
559
|
-
// ── Pruning ──────────────────────────────
|
|
560
|
-
/**
|
|
561
|
-
* Delete a session and all its associated data (nodes, edges, events, tasks, workflows, connections).
|
|
562
|
-
*/
|
|
563
|
-
deleteSession(sessionId) {
|
|
564
|
-
this.db.prepare("DELETE FROM connections WHERE session_id = ?").run(sessionId);
|
|
565
|
-
this.db.prepare("DELETE FROM workflows WHERE session_id = ?").run(sessionId);
|
|
566
|
-
this.db.prepare("DELETE FROM activity_events WHERE session_id = ?").run(sessionId);
|
|
567
|
-
this.db.prepare("DELETE FROM tasks WHERE session_id = ?").run(sessionId);
|
|
568
|
-
this.db.prepare("DELETE FROM edges WHERE session_id = ?").run(sessionId);
|
|
569
|
-
this.db.prepare("DELETE FROM nodes WHERE session_id = ?").run(sessionId);
|
|
570
|
-
this.db.prepare("DELETE FROM sessions WHERE id = ?").run(sessionId);
|
|
571
|
-
}
|
|
572
|
-
/**
|
|
573
|
-
* Prune sessions older than the given ISO date string. Returns count of deleted sessions.
|
|
574
|
-
*/
|
|
575
|
-
pruneSessions(olderThan) {
|
|
576
|
-
const rows = this.db.prepare(
|
|
577
|
-
"SELECT id FROM sessions WHERE started_at < ?"
|
|
578
|
-
).all(olderThan);
|
|
579
|
-
for (const row of rows) {
|
|
580
|
-
this.deleteSession(row.id);
|
|
581
|
-
}
|
|
582
|
-
return rows.length;
|
|
583
|
-
}
|
|
584
|
-
// ── Graph queries (read-only context layer) ─────────────────────────────────
|
|
585
|
-
/** Fetch a single node by id within a session. */
|
|
586
|
-
getNode(sessionId, nodeId) {
|
|
587
|
-
const row = this.db.prepare("SELECT * FROM nodes WHERE session_id = ? AND id = ?").get(sessionId, nodeId);
|
|
588
|
-
return row ? this.mapNode(row) : void 0;
|
|
589
|
-
}
|
|
590
|
-
/** Batch-fetch nodes by id, keyed for O(1) lookup. Chunked to stay under SQLite's bind-variable limit. */
|
|
591
|
-
getNodesByIds(sessionId, ids) {
|
|
592
|
-
const out = /* @__PURE__ */ new Map();
|
|
593
|
-
for (let i = 0; i < ids.length; i += 900) {
|
|
594
|
-
const chunk = ids.slice(i, i + 900);
|
|
595
|
-
const placeholders = chunk.map(() => "?").join(",");
|
|
596
|
-
const rows = this.db.prepare(
|
|
597
|
-
`SELECT * FROM nodes WHERE session_id = ? AND id IN (${placeholders})`
|
|
598
|
-
).all(sessionId, ...chunk);
|
|
599
|
-
for (const r of rows) {
|
|
600
|
-
const n = this.mapNode(r);
|
|
601
|
-
out.set(n.id, n);
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
return out;
|
|
605
|
-
}
|
|
606
|
-
/** Fetch all nodes of one or more types. */
|
|
607
|
-
getNodesByType(sessionId, types) {
|
|
608
|
-
if (types.length === 0) return [];
|
|
609
|
-
const placeholders = types.map(() => "?").join(",");
|
|
610
|
-
const rows = this.db.prepare(
|
|
611
|
-
`SELECT * FROM nodes WHERE session_id = ? AND type IN (${placeholders})`
|
|
612
|
-
).all(sessionId, ...types);
|
|
613
|
-
return rows.map((r) => this.mapNode(r));
|
|
614
|
-
}
|
|
615
|
-
/**
|
|
616
|
-
* Lexical search over node id, name, domain, sub-domain and tags.
|
|
617
|
-
* Case-insensitive substring match — the deterministic fallback for semantic search.
|
|
618
|
-
*/
|
|
619
|
-
searchNodes(sessionId, query, opts) {
|
|
620
|
-
const q = `%${query.trim().toLowerCase()}%`;
|
|
621
|
-
const params = [sessionId, q, q, q, q, q];
|
|
622
|
-
let sql = `
|
|
623
|
-
SELECT * FROM nodes
|
|
624
|
-
WHERE session_id = ?
|
|
625
|
-
AND (
|
|
626
|
-
lower(id) LIKE ? OR lower(name) LIKE ?
|
|
627
|
-
OR lower(COALESCE(domain, '')) LIKE ?
|
|
628
|
-
OR lower(COALESCE(sub_domain, '')) LIKE ?
|
|
629
|
-
OR lower(tags) LIKE ?
|
|
630
|
-
)`;
|
|
631
|
-
if (opts?.types && opts.types.length > 0) {
|
|
632
|
-
sql += ` AND type IN (${opts.types.map(() => "?").join(",")})`;
|
|
633
|
-
params.push(...opts.types);
|
|
634
|
-
}
|
|
635
|
-
sql += " ORDER BY confidence DESC";
|
|
636
|
-
if (opts?.limit) sql += ` LIMIT ${Math.max(1, Math.floor(opts.limit))}`;
|
|
637
|
-
const rows = this.db.prepare(sql).all(...params);
|
|
638
|
-
return rows.map((r) => this.mapNode(r));
|
|
639
|
-
}
|
|
640
|
-
/**
|
|
641
|
-
* Traverse the dependency graph from a node using a recursive CTE with a
|
|
642
|
-
* path-based cycle guard. `downstream` follows source→target (what the node
|
|
643
|
-
* depends on / points to); `upstream` follows target→source (what depends on it).
|
|
644
|
-
*/
|
|
645
|
-
getDependencies(sessionId, nodeId, opts = {}) {
|
|
646
|
-
const direction = opts.direction ?? "downstream";
|
|
647
|
-
const maxDepth = Math.max(1, Math.min(opts.maxDepth ?? 8, 64));
|
|
648
|
-
const root = this.getNode(sessionId, nodeId);
|
|
649
|
-
const depthById = /* @__PURE__ */ new Map();
|
|
650
|
-
const collect = (dir) => {
|
|
651
|
-
const [from, to] = dir === "downstream" ? ["source_id", "target_id"] : ["target_id", "source_id"];
|
|
652
|
-
const sql = `
|
|
653
|
-
WITH RECURSIVE walk(node_id, depth, path) AS (
|
|
654
|
-
SELECT ?, 0, char(10) || ? || char(10)
|
|
655
|
-
UNION ALL
|
|
656
|
-
SELECT e.${to}, w.depth + 1, w.path || e.${to} || char(10)
|
|
657
|
-
FROM edges e JOIN walk w ON e.${from} = w.node_id
|
|
658
|
-
WHERE e.session_id = ?
|
|
659
|
-
AND w.depth < ?
|
|
660
|
-
AND instr(w.path, char(10) || e.${to} || char(10)) = 0
|
|
661
|
-
)
|
|
662
|
-
SELECT node_id, MIN(depth) AS depth FROM walk WHERE node_id != ? GROUP BY node_id`;
|
|
663
|
-
const rows = this.db.prepare(sql).all(nodeId, nodeId, sessionId, maxDepth, nodeId);
|
|
664
|
-
for (const r of rows) {
|
|
665
|
-
const prev = depthById.get(r.node_id);
|
|
666
|
-
if (prev === void 0 || r.depth < prev) depthById.set(r.node_id, r.depth);
|
|
667
|
-
}
|
|
668
|
-
};
|
|
669
|
-
if (direction === "both") {
|
|
670
|
-
collect("downstream");
|
|
671
|
-
collect("upstream");
|
|
672
|
-
} else collect(direction);
|
|
673
|
-
const byId = this.getNodesByIds(sessionId, [...depthById.keys()]);
|
|
674
|
-
const nodes = [...depthById.entries()].map(([id, depth]) => {
|
|
675
|
-
const n = byId.get(id);
|
|
676
|
-
return n ? { ...n, depth } : void 0;
|
|
677
|
-
}).filter((n) => n !== void 0).sort((a, b) => a.depth - b.depth);
|
|
678
|
-
const reachable = /* @__PURE__ */ new Set([nodeId, ...depthById.keys()]);
|
|
679
|
-
const edges = this.getEdges(sessionId).filter((e) => reachable.has(e.sourceId) && reachable.has(e.targetId));
|
|
680
|
-
return { root, direction, maxDepth, nodes, edges };
|
|
681
|
-
}
|
|
682
|
-
/** Lightweight aggregate index of the whole topology — the progressive-disclosure summary. */
|
|
683
|
-
getGraphSummary(sessionId) {
|
|
684
|
-
const totals = {
|
|
685
|
-
nodes: this.db.prepare("SELECT COUNT(*) c FROM nodes WHERE session_id = ?").get(sessionId).c,
|
|
686
|
-
edges: this.db.prepare("SELECT COUNT(*) c FROM edges WHERE session_id = ?").get(sessionId).c
|
|
687
|
-
};
|
|
688
|
-
const byType = {};
|
|
689
|
-
for (const r of this.db.prepare("SELECT type, COUNT(*) c FROM nodes WHERE session_id = ? GROUP BY type").all(sessionId)) {
|
|
690
|
-
byType[r.type] = r.c;
|
|
691
|
-
}
|
|
692
|
-
const byDomain = {};
|
|
693
|
-
for (const r of this.db.prepare("SELECT COALESCE(domain, '(none)') d, COUNT(*) c FROM nodes WHERE session_id = ? GROUP BY d").all(sessionId)) {
|
|
694
|
-
byDomain[r.d] = r.c;
|
|
695
|
-
}
|
|
696
|
-
const byRelationship = {};
|
|
697
|
-
for (const r of this.db.prepare("SELECT relationship rel, COUNT(*) c FROM edges WHERE session_id = ? GROUP BY rel").all(sessionId)) {
|
|
698
|
-
byRelationship[r.rel] = r.c;
|
|
699
|
-
}
|
|
700
|
-
const topConnected = this.db.prepare(`
|
|
701
|
-
SELECT n.id, n.name, n.type, COUNT(e.id) AS degree
|
|
702
|
-
FROM nodes n
|
|
703
|
-
LEFT JOIN edges e ON e.session_id = n.session_id AND (e.source_id = n.id OR e.target_id = n.id)
|
|
704
|
-
WHERE n.session_id = ?
|
|
705
|
-
GROUP BY n.id, n.name, n.type
|
|
706
|
-
ORDER BY degree DESC, n.confidence DESC
|
|
707
|
-
LIMIT 10
|
|
708
|
-
`).all(sessionId);
|
|
709
|
-
return { sessionId, totals, nodesByType: byType, nodesByDomain: byDomain, edgesByRelationship: byRelationship, topConnected };
|
|
710
|
-
}
|
|
711
|
-
// ── Stats ───────────────────────────────
|
|
712
|
-
getStats(sessionId) {
|
|
713
|
-
const nodes = this.db.prepare("SELECT COUNT(*) as c FROM nodes WHERE session_id = ?").get(sessionId).c;
|
|
714
|
-
const edges = this.db.prepare("SELECT COUNT(*) as c FROM edges WHERE session_id = ?").get(sessionId).c;
|
|
715
|
-
const events = this.db.prepare("SELECT COUNT(*) as c FROM activity_events WHERE session_id = ?").get(sessionId).c;
|
|
716
|
-
const tasks = this.db.prepare("SELECT COUNT(*) as c FROM tasks WHERE session_id = ?").get(sessionId).c;
|
|
717
|
-
return { nodes, edges, events, tasks };
|
|
718
|
-
}
|
|
719
|
-
};
|
|
720
|
-
|
|
721
|
-
// src/mcp/server.ts
|
|
722
|
-
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
723
|
-
import { z as z2 } from "zod";
|
|
724
|
-
var SERVER_NAME = "cartography";
|
|
725
|
-
var SERVER_VERSION = "2.0.0";
|
|
726
|
-
var SERVICE_TYPES = NODE_TYPE_GROUPS.web;
|
|
727
|
-
var DATA_TYPES = NODE_TYPE_GROUPS.data;
|
|
728
|
-
var lexicalSearch = async (db, sessionId, query, opts) => db.searchNodes(sessionId, query, { types: opts.types, limit: opts.limit }).map((node) => ({ node }));
|
|
729
|
-
function compactNode(n) {
|
|
730
|
-
return {
|
|
731
|
-
id: n.id,
|
|
732
|
-
type: n.type,
|
|
733
|
-
name: n.name,
|
|
734
|
-
confidence: n.confidence,
|
|
735
|
-
...n.domain ? { domain: n.domain } : {},
|
|
736
|
-
...n.tags.length ? { tags: n.tags } : {}
|
|
737
|
-
};
|
|
738
|
-
}
|
|
739
|
-
function json(data) {
|
|
740
|
-
return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
|
|
741
|
-
}
|
|
742
|
-
function summaryText(s) {
|
|
743
|
-
const lines = [
|
|
744
|
-
`# Infrastructure topology \u2014 session ${s.sessionId}`,
|
|
745
|
-
``,
|
|
746
|
-
`Totals: ${s.totals.nodes} nodes, ${s.totals.edges} edges`,
|
|
747
|
-
``,
|
|
748
|
-
`Nodes by type:`,
|
|
749
|
-
...Object.entries(s.nodesByType).sort((a, b) => b[1] - a[1]).map(([t, c]) => ` - ${t}: ${c}`),
|
|
750
|
-
``,
|
|
751
|
-
`Nodes by domain:`,
|
|
752
|
-
...Object.entries(s.nodesByDomain).sort((a, b) => b[1] - a[1]).map(([d, c]) => ` - ${d}: ${c}`),
|
|
753
|
-
``,
|
|
754
|
-
`Edges by relationship:`,
|
|
755
|
-
...Object.entries(s.edgesByRelationship).sort((a, b) => b[1] - a[1]).map(([r, c]) => ` - ${r}: ${c}`),
|
|
756
|
-
``,
|
|
757
|
-
`Most connected:`,
|
|
758
|
-
...s.topConnected.map((n) => ` - ${n.id} (${n.type}) \u2014 degree ${n.degree}`),
|
|
759
|
-
``,
|
|
760
|
-
`Read cartography://nodes/{id} or cartography://dependencies/{id} for detail.`
|
|
761
|
-
];
|
|
762
|
-
return lines.join("\n");
|
|
763
|
-
}
|
|
764
|
-
function createMcpServer(opts = {}) {
|
|
765
|
-
const db = opts.db ?? new CartographyDB(opts.dbPath ?? defaultConfig().dbPath);
|
|
766
|
-
const search = opts.search ?? lexicalSearch;
|
|
767
|
-
const resolveSession = () => {
|
|
768
|
-
if (opts.session && opts.session !== "latest") return opts.session;
|
|
769
|
-
return db.getLatestSession("discover")?.id ?? db.getLatestSession()?.id;
|
|
770
|
-
};
|
|
771
|
-
const server = new McpServer(
|
|
772
|
-
{ name: SERVER_NAME, version: SERVER_VERSION },
|
|
773
|
-
{
|
|
774
|
-
capabilities: { resources: { subscribe: true, listChanged: true }, tools: {}, prompts: {}, logging: {} },
|
|
775
|
-
instructions: "Cartography exposes a discovered infrastructure/SaaS topology. Start by reading cartography://graph/summary for a low-token overview, then drill into specific nodes via cartography://nodes/{id} or query with the query_infrastructure / get_dependencies tools."
|
|
776
|
-
}
|
|
777
|
-
);
|
|
778
|
-
server.registerResource(
|
|
779
|
-
"graph-summary",
|
|
780
|
-
"cartography://graph/summary",
|
|
781
|
-
{ title: "Topology summary", description: "Low-token aggregate index of the whole landscape \u2014 read this first.", mimeType: "text/markdown" },
|
|
782
|
-
(uri) => {
|
|
783
|
-
const sid = resolveSession();
|
|
784
|
-
if (!sid) return { contents: [{ uri: uri.href, mimeType: "text/markdown", text: "No discovery session found. Run discovery first." }] };
|
|
785
|
-
return { contents: [{ uri: uri.href, mimeType: "text/markdown", text: summaryText(db.getGraphSummary(sid)) }] };
|
|
786
|
-
}
|
|
787
|
-
);
|
|
788
|
-
server.registerResource(
|
|
789
|
-
"nodes-index",
|
|
790
|
-
"cartography://nodes",
|
|
791
|
-
{ title: "Node index", description: "Lightweight list of all nodes (id, type, name only).", mimeType: "application/json" },
|
|
792
|
-
(uri) => {
|
|
793
|
-
const sid = resolveSession();
|
|
794
|
-
const nodes = sid ? db.getNodes(sid) : [];
|
|
795
|
-
return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify({ count: nodes.length, nodes: nodes.map((n) => ({ id: n.id, type: n.type, name: n.name })) }, null, 2) }] };
|
|
796
|
-
}
|
|
797
|
-
);
|
|
798
|
-
server.registerResource(
|
|
799
|
-
"node-detail",
|
|
800
|
-
new ResourceTemplate("cartography://nodes/{id}", { list: void 0 }),
|
|
801
|
-
{ title: "Node detail", description: "Full node record plus its incident edges.", mimeType: "application/json" },
|
|
802
|
-
(uri, variables) => {
|
|
803
|
-
const sid = resolveSession();
|
|
804
|
-
const id = decodeURIComponent(String(variables["id"]));
|
|
805
|
-
const node = sid ? db.getNode(sid, id) : void 0;
|
|
806
|
-
if (!node) return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify({ error: `node not found: ${id}` }) }] };
|
|
807
|
-
const edges = db.getEdges(sid).filter((e) => e.sourceId === id || e.targetId === id);
|
|
808
|
-
return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify({ node, edges }, null, 2) }] };
|
|
809
|
-
}
|
|
810
|
-
);
|
|
811
|
-
const typedListResource = (name, uri, title, types) => server.registerResource(name, uri, { title, description: `Nodes of type: ${types.join(", ")}.`, mimeType: "application/json" }, (u) => {
|
|
812
|
-
const sid = resolveSession();
|
|
813
|
-
const nodes = sid ? db.getNodesByType(sid, types) : [];
|
|
814
|
-
return { contents: [{ uri: u.href, mimeType: "application/json", text: JSON.stringify({ count: nodes.length, nodes: nodes.map(compactNode) }, null, 2) }] };
|
|
815
|
-
});
|
|
816
|
-
typedListResource("services", "cartography://services", "Services", SERVICE_TYPES);
|
|
817
|
-
typedListResource("databases", "cartography://databases", "Data stores", DATA_TYPES);
|
|
818
|
-
server.registerResource(
|
|
819
|
-
"dependencies",
|
|
820
|
-
new ResourceTemplate("cartography://dependencies/{id}", { list: void 0 }),
|
|
821
|
-
{ title: "Dependencies", description: "Transitive downstream dependencies of a node.", mimeType: "application/json" },
|
|
822
|
-
(uri, variables) => {
|
|
823
|
-
const sid = resolveSession();
|
|
824
|
-
const id = decodeURIComponent(String(variables["id"]));
|
|
825
|
-
if (!sid) return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify({ error: "no session" }) }] };
|
|
826
|
-
const r = db.getDependencies(sid, id, { direction: "downstream", maxDepth: 8 });
|
|
827
|
-
return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify({ root: id, count: r.nodes.length, nodes: r.nodes.map((n) => ({ ...compactNode(n), depth: n.depth })) }, null, 2) }] };
|
|
828
|
-
}
|
|
829
|
-
);
|
|
830
|
-
server.registerResource(
|
|
831
|
-
"sessions",
|
|
832
|
-
"cartography://sessions",
|
|
833
|
-
{ title: "Discovery sessions", description: "All discovery sessions in the catalog.", mimeType: "application/json" },
|
|
834
|
-
(uri) => ({ contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(db.getSessions(), null, 2) }] })
|
|
835
|
-
);
|
|
836
|
-
server.registerTool(
|
|
837
|
-
"get_summary",
|
|
838
|
-
{ title: "Get topology summary", description: "Low-token overview of the whole landscape (counts, types, domains, most-connected).", inputSchema: {} },
|
|
839
|
-
() => {
|
|
840
|
-
const sid = resolveSession();
|
|
841
|
-
if (!sid) return json({ error: "No discovery session found." });
|
|
842
|
-
return json(db.getGraphSummary(sid));
|
|
843
|
-
}
|
|
844
|
-
);
|
|
845
|
-
server.registerTool(
|
|
846
|
-
"query_infrastructure",
|
|
847
|
-
{
|
|
848
|
-
title: "Query infrastructure",
|
|
849
|
-
description: "Search the topology by name/id/domain (optionally filtered by node type). Returns compact node records.",
|
|
850
|
-
inputSchema: {
|
|
851
|
-
query: z2.string().describe('Free-text query, e.g. "postgres", "auth", "github"'),
|
|
852
|
-
types: z2.array(z2.enum(NODE_TYPES)).optional().describe("Restrict to these node types"),
|
|
853
|
-
limit: z2.number().int().min(1).max(200).default(25).optional()
|
|
854
|
-
}
|
|
855
|
-
},
|
|
856
|
-
async (args) => {
|
|
857
|
-
const sid = resolveSession();
|
|
858
|
-
if (!sid) return json({ error: "No discovery session found." });
|
|
859
|
-
const results = await search(db, sid, args.query, { types: args.types, limit: args.limit ?? 25 });
|
|
860
|
-
return json({ count: results.length, results: results.map((r) => ({ ...compactNode(r.node), ...r.score !== void 0 ? { score: r.score } : {} })) });
|
|
861
|
-
}
|
|
862
|
-
);
|
|
863
|
-
server.registerTool(
|
|
864
|
-
"search_topology",
|
|
865
|
-
{
|
|
866
|
-
title: "Search topology (semantic)",
|
|
867
|
-
description: "Find nodes related to a concept by meaning (semantic search when available, lexical otherwise).",
|
|
868
|
-
inputSchema: { query: z2.string(), limit: z2.number().int().min(1).max(100).default(10).optional() }
|
|
869
|
-
},
|
|
870
|
-
async (args) => {
|
|
871
|
-
const sid = resolveSession();
|
|
872
|
-
if (!sid) return json({ error: "No discovery session found." });
|
|
873
|
-
const results = await search(db, sid, args.query, { limit: args.limit ?? 10 });
|
|
874
|
-
return json({ count: results.length, results: results.map((r) => ({ ...compactNode(r.node), ...r.score !== void 0 ? { score: r.score } : {} })) });
|
|
875
|
-
}
|
|
876
|
-
);
|
|
877
|
-
server.registerTool(
|
|
878
|
-
"list_services",
|
|
879
|
-
{
|
|
880
|
-
title: "List services",
|
|
881
|
-
description: "List discovered services or data stores.",
|
|
882
|
-
inputSchema: { kind: z2.enum(["services", "databases", "all"]).default("all").optional() }
|
|
883
|
-
},
|
|
884
|
-
(args) => {
|
|
885
|
-
const sid = resolveSession();
|
|
886
|
-
if (!sid) return json({ error: "No discovery session found." });
|
|
887
|
-
const kind = args.kind ?? "all";
|
|
888
|
-
const types = kind === "services" ? SERVICE_TYPES : kind === "databases" ? DATA_TYPES : [...SERVICE_TYPES, ...DATA_TYPES];
|
|
889
|
-
return json(db.getNodesByType(sid, types).map(compactNode));
|
|
890
|
-
}
|
|
891
|
-
);
|
|
892
|
-
server.registerTool(
|
|
893
|
-
"get_node",
|
|
894
|
-
{ title: "Get node", description: "Fetch a single node with its incident edges.", inputSchema: { id: z2.string() } },
|
|
895
|
-
(args) => {
|
|
896
|
-
const sid = resolveSession();
|
|
897
|
-
if (!sid) return json({ error: "No discovery session found." });
|
|
898
|
-
const node = db.getNode(sid, args.id);
|
|
899
|
-
if (!node) return json({ error: `node not found: ${args.id}` });
|
|
900
|
-
const edges = db.getEdges(sid).filter((e) => e.sourceId === args.id || e.targetId === args.id);
|
|
901
|
-
return json({ node, edges });
|
|
902
|
-
}
|
|
903
|
-
);
|
|
904
|
-
server.registerTool(
|
|
905
|
-
"get_dependencies",
|
|
906
|
-
{
|
|
907
|
-
title: "Get dependencies",
|
|
908
|
-
description: "Traverse the dependency graph from a node (downstream/upstream/both) with a depth limit.",
|
|
909
|
-
inputSchema: {
|
|
910
|
-
id: z2.string(),
|
|
911
|
-
direction: z2.enum(["downstream", "upstream", "both"]).default("downstream").optional(),
|
|
912
|
-
maxDepth: z2.number().int().min(1).max(64).default(8).optional()
|
|
913
|
-
}
|
|
914
|
-
},
|
|
915
|
-
(args) => {
|
|
916
|
-
const sid = resolveSession();
|
|
917
|
-
if (!sid) return json({ error: "No discovery session found." });
|
|
918
|
-
const r = db.getDependencies(sid, args.id, { direction: args.direction ?? "downstream", maxDepth: args.maxDepth ?? 8 });
|
|
919
|
-
return json({
|
|
920
|
-
root: r.root ? compactNode(r.root) : null,
|
|
921
|
-
direction: r.direction,
|
|
922
|
-
count: r.nodes.length,
|
|
923
|
-
nodes: r.nodes.map((n) => ({ ...compactNode(n), depth: n.depth })),
|
|
924
|
-
edges: r.edges.map((e) => ({ from: e.sourceId, to: e.targetId, rel: e.relationship }))
|
|
925
|
-
});
|
|
926
|
-
}
|
|
927
|
-
);
|
|
928
|
-
if (opts.discovery) {
|
|
929
|
-
const discovery = opts.discovery;
|
|
930
|
-
server.registerTool(
|
|
931
|
-
"run_discovery",
|
|
932
|
-
{
|
|
933
|
-
title: "Run discovery",
|
|
934
|
-
description: "Scan the local system (read-only) and update the catalog. Returns counts of nodes/edges found.",
|
|
935
|
-
inputSchema: { hint: z2.string().optional().describe("Optional focus, e.g. tool names to look for") }
|
|
936
|
-
},
|
|
937
|
-
async (args) => {
|
|
938
|
-
let sid = resolveSession();
|
|
939
|
-
if (!sid) sid = db.createSession("discover", defaultConfig());
|
|
940
|
-
const result = await discovery(db, sid, { hint: args.hint });
|
|
941
|
-
server.server.sendResourceUpdated({ uri: "cartography://graph/summary" }).catch(() => {
|
|
942
|
-
});
|
|
943
|
-
server.server.sendResourceListChanged?.();
|
|
944
|
-
return json({ session: sid, ...result });
|
|
945
|
-
}
|
|
946
|
-
);
|
|
947
|
-
}
|
|
948
|
-
server.registerPrompt(
|
|
949
|
-
"audit-attack-surface",
|
|
950
|
-
{ title: "Audit attack surface", description: "Review the discovered topology for externally-reachable services and risky dependencies." },
|
|
951
|
-
() => ({
|
|
952
|
-
messages: [{
|
|
953
|
-
role: "user",
|
|
954
|
-
content: { type: "text", text: "Read cartography://graph/summary and cartography://services. Identify externally-reachable services, data stores with broad inbound dependencies, and any node with low confidence that warrants verification. Use get_dependencies to assess blast radius. Summarize the attack surface and concrete hardening recommendations." }
|
|
955
|
-
}]
|
|
956
|
-
})
|
|
957
|
-
);
|
|
958
|
-
server.registerPrompt(
|
|
959
|
-
"map-service-dependencies",
|
|
960
|
-
{
|
|
961
|
-
title: "Map service dependencies",
|
|
962
|
-
description: "Produce a dependency map for a given service.",
|
|
963
|
-
argsSchema: { service: z2.string().describe("Service node id or name") }
|
|
964
|
-
},
|
|
965
|
-
(args) => ({
|
|
966
|
-
messages: [{
|
|
967
|
-
role: "user",
|
|
968
|
-
content: { type: "text", text: `Use query_infrastructure to locate "${args.service}", then get_dependencies (direction=both) to map everything it depends on and everything that depends on it. Present the result as a clear dependency tree and call out single points of failure.` }
|
|
969
|
-
}]
|
|
970
|
-
})
|
|
971
|
-
);
|
|
972
|
-
server.registerPrompt(
|
|
973
|
-
"onboard-to-system",
|
|
974
|
-
{ title: "Onboard to system", description: "Explain the system landscape to a new engineer." },
|
|
975
|
-
() => ({
|
|
976
|
-
messages: [{
|
|
977
|
-
role: "user",
|
|
978
|
-
content: { type: "text", text: "Read cartography://graph/summary, then cartography://services and cartography://databases. Write a concise onboarding briefing for a new engineer: what the major systems are, how they connect, which data stores are central, and where to look first." }
|
|
979
|
-
}]
|
|
980
|
-
})
|
|
981
|
-
);
|
|
982
|
-
return server;
|
|
983
|
-
}
|
|
984
|
-
|
|
985
|
-
// src/mcp/transports.ts
|
|
986
|
-
import { randomUUID } from "crypto";
|
|
987
|
-
import http from "http";
|
|
988
|
-
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
989
|
-
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
990
|
-
async function runStdio(server) {
|
|
991
|
-
const transport = new StdioServerTransport();
|
|
992
|
-
await server.connect(transport);
|
|
993
|
-
}
|
|
994
|
-
async function readJsonBody(req) {
|
|
995
|
-
const chunks = [];
|
|
996
|
-
for await (const chunk of req) chunks.push(chunk);
|
|
997
|
-
if (chunks.length === 0) return void 0;
|
|
998
|
-
try {
|
|
999
|
-
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
1000
|
-
} catch {
|
|
1001
|
-
return void 0;
|
|
1002
|
-
}
|
|
1003
|
-
}
|
|
1004
|
-
async function runHttp(factory, opts = {}) {
|
|
1005
|
-
const host = opts.host ?? "127.0.0.1";
|
|
1006
|
-
const port = opts.port ?? 3737;
|
|
1007
|
-
const allowedHosts = opts.allowedHosts ?? [`${host}:${port}`, `localhost:${port}`, `127.0.0.1:${port}`];
|
|
1008
|
-
const transports = /* @__PURE__ */ new Map();
|
|
1009
|
-
const httpServer = http.createServer(async (req, res) => {
|
|
1010
|
-
try {
|
|
1011
|
-
const url = req.url ?? "";
|
|
1012
|
-
if (!url.startsWith("/mcp")) {
|
|
1013
|
-
res.writeHead(404, { "content-type": "application/json" }).end('{"error":"not found"}');
|
|
1014
|
-
return;
|
|
1015
|
-
}
|
|
1016
|
-
const sessionId = req.headers["mcp-session-id"];
|
|
1017
|
-
const existing = sessionId ? transports.get(sessionId) : void 0;
|
|
1018
|
-
if (existing) {
|
|
1019
|
-
const body2 = req.method === "POST" ? await readJsonBody(req) : void 0;
|
|
1020
|
-
await existing.handleRequest(req, res, body2);
|
|
1021
|
-
return;
|
|
1022
|
-
}
|
|
1023
|
-
if (req.method !== "POST") {
|
|
1024
|
-
res.writeHead(400, { "content-type": "application/json" }).end('{"error":"missing or unknown mcp-session-id"}');
|
|
1025
|
-
return;
|
|
1026
|
-
}
|
|
1027
|
-
const body = await readJsonBody(req);
|
|
1028
|
-
const transport = new StreamableHTTPServerTransport({
|
|
1029
|
-
sessionIdGenerator: () => randomUUID(),
|
|
1030
|
-
enableDnsRebindingProtection: true,
|
|
1031
|
-
allowedHosts,
|
|
1032
|
-
...opts.allowedOrigins ? { allowedOrigins: opts.allowedOrigins } : {},
|
|
1033
|
-
onsessioninitialized: (id) => {
|
|
1034
|
-
transports.set(id, transport);
|
|
1035
|
-
}
|
|
1036
|
-
});
|
|
1037
|
-
transport.onclose = () => {
|
|
1038
|
-
if (transport.sessionId) transports.delete(transport.sessionId);
|
|
1039
|
-
};
|
|
1040
|
-
await factory().connect(transport);
|
|
1041
|
-
await transport.handleRequest(req, res, body);
|
|
1042
|
-
} catch {
|
|
1043
|
-
if (!res.headersSent) res.writeHead(500, { "content-type": "application/json" }).end('{"error":"internal error"}');
|
|
1044
|
-
}
|
|
1045
|
-
});
|
|
1046
|
-
await new Promise((resolve) => httpServer.listen(port, host, resolve));
|
|
1047
|
-
return httpServer;
|
|
1048
|
-
}
|
|
1049
|
-
|
|
1050
|
-
// src/semantic/hash.ts
|
|
1051
|
-
function fnv1a(s) {
|
|
1052
|
-
let h = 2166136261;
|
|
1053
|
-
for (let i = 0; i < s.length; i++) {
|
|
1054
|
-
h ^= s.charCodeAt(i);
|
|
1055
|
-
h = Math.imul(h, 16777619);
|
|
1056
|
-
}
|
|
1057
|
-
return h >>> 0;
|
|
1058
|
-
}
|
|
1059
|
-
|
|
1060
|
-
// src/semantic/embeddings.ts
|
|
1061
|
-
async function createLocalEmbedder(model = "Xenova/all-MiniLM-L6-v2") {
|
|
1062
|
-
try {
|
|
1063
|
-
const tf = await import("./transformers.node-BTYUTJK5.js");
|
|
1064
|
-
const extractor = await tf.pipeline("feature-extraction", model);
|
|
1065
|
-
return {
|
|
1066
|
-
id: `local:${model}`,
|
|
1067
|
-
dimensions: 384,
|
|
1068
|
-
async embed(texts) {
|
|
1069
|
-
const out = [];
|
|
1070
|
-
for (const text of texts) {
|
|
1071
|
-
const tensor = await extractor(text, { pooling: "mean", normalize: true });
|
|
1072
|
-
out.push(Float32Array.from(tensor.data));
|
|
1073
|
-
}
|
|
1074
|
-
return out;
|
|
1075
|
-
}
|
|
1076
|
-
};
|
|
1077
|
-
} catch {
|
|
1078
|
-
return void 0;
|
|
1079
|
-
}
|
|
1080
|
-
}
|
|
1081
|
-
|
|
1082
|
-
// src/semantic/store.ts
|
|
1083
|
-
function nodeText(n) {
|
|
1084
|
-
const desc = typeof n.metadata?.["description"] === "string" ? n.metadata["description"] : "";
|
|
1085
|
-
const category = typeof n.metadata?.["category"] === "string" ? n.metadata["category"] : "";
|
|
1086
|
-
return [n.name, n.id.replace(/[:_]/g, " "), `type ${n.type}`, n.domain ?? "", n.subDomain ?? "", category, n.tags.join(" "), desc].filter(Boolean).join(" \u2014 ");
|
|
1087
|
-
}
|
|
1088
|
-
function hash(s) {
|
|
1089
|
-
return fnv1a(s).toString(16);
|
|
1090
|
-
}
|
|
1091
|
-
function toBuffer(v) {
|
|
1092
|
-
return Buffer.from(v.buffer, v.byteOffset, v.byteLength);
|
|
1093
|
-
}
|
|
1094
|
-
var VectorStore = class {
|
|
1095
|
-
constructor(db, embedder) {
|
|
1096
|
-
this.db = db;
|
|
1097
|
-
this.embedder = embedder;
|
|
1098
|
-
}
|
|
1099
|
-
loaded = false;
|
|
1100
|
-
/** Load sqlite-vec and ensure the schema exists. Returns false if unavailable. */
|
|
1101
|
-
async init() {
|
|
1102
|
-
if (this.loaded) return true;
|
|
1103
|
-
try {
|
|
1104
|
-
const conn = this.db.rawConnection();
|
|
1105
|
-
const sqliteVec = await import("./sqlite-vec-EZN67B2V.js");
|
|
1106
|
-
sqliteVec.load(conn);
|
|
1107
|
-
conn.exec(`
|
|
1108
|
-
CREATE TABLE IF NOT EXISTS vec_index (
|
|
1109
|
-
rowid INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1110
|
-
session_id TEXT NOT NULL,
|
|
1111
|
-
node_id TEXT NOT NULL,
|
|
1112
|
-
hash TEXT NOT NULL,
|
|
1113
|
-
UNIQUE(session_id, node_id)
|
|
1114
|
-
);
|
|
1115
|
-
CREATE TABLE IF NOT EXISTS vec_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
1116
|
-
`);
|
|
1117
|
-
const dimRow = conn.prepare("SELECT value FROM vec_meta WHERE key = 'dims'").get();
|
|
1118
|
-
const dims = this.embedder.dimensions;
|
|
1119
|
-
if (dimRow && Number(dimRow.value) !== dims) {
|
|
1120
|
-
conn.exec("DROP TABLE IF EXISTS vec_nodes; DELETE FROM vec_index;");
|
|
1121
|
-
}
|
|
1122
|
-
conn.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS vec_nodes USING vec0(embedding float[${dims}])`);
|
|
1123
|
-
conn.prepare("INSERT OR REPLACE INTO vec_meta(key, value) VALUES (?, ?)").run("dims", String(dims));
|
|
1124
|
-
conn.prepare("INSERT OR REPLACE INTO vec_meta(key, value) VALUES (?, ?)").run("embedder", this.embedder.id);
|
|
1125
|
-
this.loaded = true;
|
|
1126
|
-
return true;
|
|
1127
|
-
} catch {
|
|
1128
|
-
return false;
|
|
1129
|
-
}
|
|
1130
|
-
}
|
|
1131
|
-
/** Incrementally embed and index any new/changed nodes for a session. */
|
|
1132
|
-
async index(sessionId) {
|
|
1133
|
-
if (!await this.init()) return { embedded: 0, total: 0 };
|
|
1134
|
-
const conn = this.db.rawConnection();
|
|
1135
|
-
const nodes = this.db.getNodes(sessionId);
|
|
1136
|
-
const getRow = conn.prepare("SELECT rowid, hash FROM vec_index WHERE session_id = ? AND node_id = ?");
|
|
1137
|
-
const insIndex = conn.prepare("INSERT INTO vec_index (session_id, node_id, hash) VALUES (?, ?, ?)");
|
|
1138
|
-
const updHash = conn.prepare("UPDATE vec_index SET hash = ? WHERE rowid = ?");
|
|
1139
|
-
const delVec = conn.prepare("DELETE FROM vec_nodes WHERE rowid = ?");
|
|
1140
|
-
const insVec = conn.prepare("INSERT INTO vec_nodes (rowid, embedding) VALUES (?, ?)");
|
|
1141
|
-
const pending = [];
|
|
1142
|
-
for (const n of nodes) {
|
|
1143
|
-
const text = nodeText(n);
|
|
1144
|
-
const h = hash(`${this.embedder.id}:${text}`);
|
|
1145
|
-
const existing = getRow.get(sessionId, n.id);
|
|
1146
|
-
if (existing) {
|
|
1147
|
-
if (existing.hash === h) continue;
|
|
1148
|
-
updHash.run(h, existing.rowid);
|
|
1149
|
-
delVec.run(BigInt(existing.rowid));
|
|
1150
|
-
pending.push({ rowid: BigInt(existing.rowid), text });
|
|
1151
|
-
} else {
|
|
1152
|
-
const info = insIndex.run(sessionId, n.id, h);
|
|
1153
|
-
pending.push({ rowid: BigInt(info.lastInsertRowid), text });
|
|
1154
|
-
}
|
|
1155
|
-
}
|
|
1156
|
-
if (pending.length > 0) {
|
|
1157
|
-
const vectors = await this.embedder.embed(pending.map((p) => p.text));
|
|
1158
|
-
const tx = conn.transaction(() => {
|
|
1159
|
-
pending.forEach((p, i) => insVec.run(p.rowid, toBuffer(vectors[i])));
|
|
1160
|
-
});
|
|
1161
|
-
tx();
|
|
1162
|
-
}
|
|
1163
|
-
return { embedded: pending.length, total: nodes.length };
|
|
1164
|
-
}
|
|
1165
|
-
/** k-nearest-neighbour search within a session. Returns node ids + distances. */
|
|
1166
|
-
async search(sessionId, query, k) {
|
|
1167
|
-
if (!await this.init()) return [];
|
|
1168
|
-
await this.index(sessionId);
|
|
1169
|
-
const conn = this.db.rawConnection();
|
|
1170
|
-
const [qv] = await this.embedder.embed([query]);
|
|
1171
|
-
if (!qv) return [];
|
|
1172
|
-
const overfetch = Math.max(k * 5, k);
|
|
1173
|
-
const knn = conn.prepare(
|
|
1174
|
-
"SELECT rowid, distance FROM vec_nodes WHERE embedding MATCH ? ORDER BY distance LIMIT ?"
|
|
1175
|
-
).all(toBuffer(qv), overfetch);
|
|
1176
|
-
const meta = conn.prepare("SELECT node_id AS nodeId, session_id AS sessionId FROM vec_index WHERE rowid = ?");
|
|
1177
|
-
const out = [];
|
|
1178
|
-
for (const row of knn) {
|
|
1179
|
-
const m = meta.get(row.rowid);
|
|
1180
|
-
if (m && m.sessionId === sessionId) out.push({ nodeId: m.nodeId, distance: row.distance });
|
|
1181
|
-
if (out.length >= k) break;
|
|
1182
|
-
}
|
|
1183
|
-
return out;
|
|
1184
|
-
}
|
|
1185
|
-
};
|
|
1186
|
-
|
|
1187
|
-
// src/semantic/search.ts
|
|
1188
|
-
var lexical = (db, sessionId, query, opts) => db.searchNodes(sessionId, query, { types: opts.types, limit: opts.limit }).map((node) => ({ node }));
|
|
1189
|
-
var lexicalSearch2 = () => async (d, sid, q, opts) => lexical(d, sid, q, opts);
|
|
1190
|
-
async function createSemanticSearch(db, embedder) {
|
|
1191
|
-
const provider = embedder ?? await createLocalEmbedder();
|
|
1192
|
-
if (!provider) return lexicalSearch2();
|
|
1193
|
-
const store = new VectorStore(db, provider);
|
|
1194
|
-
const ok = await store.init();
|
|
1195
|
-
if (!ok) return lexicalSearch2();
|
|
1196
|
-
return async (d, sid, query, opts) => {
|
|
1197
|
-
const hits = await store.search(sid, query, opts.limit);
|
|
1198
|
-
if (hits.length === 0) return lexical(d, sid, query, opts);
|
|
1199
|
-
const byId = d.getNodesByIds(sid, hits.map((h) => h.nodeId));
|
|
1200
|
-
const results = [];
|
|
1201
|
-
for (const h of hits) {
|
|
1202
|
-
const node = byId.get(h.nodeId);
|
|
1203
|
-
if (!node) continue;
|
|
1204
|
-
if (opts.types && opts.types.length > 0 && !opts.types.includes(node.type)) continue;
|
|
1205
|
-
results.push({ node, score: Math.max(0, 1 - h.distance / 2) });
|
|
1206
|
-
}
|
|
1207
|
-
return results.length > 0 ? results : lexical(d, sid, query, opts);
|
|
1208
|
-
};
|
|
1209
|
-
}
|
|
1210
|
-
|
|
1211
|
-
// src/scanners/types.ts
|
|
1212
|
-
var ScannerRegistry = class {
|
|
1213
|
-
scanners = /* @__PURE__ */ new Map();
|
|
1214
|
-
register(scanner) {
|
|
1215
|
-
if (this.scanners.has(scanner.id)) throw new Error(`scanner already registered: ${scanner.id}`);
|
|
1216
|
-
this.scanners.set(scanner.id, scanner);
|
|
1217
|
-
return this;
|
|
1218
|
-
}
|
|
1219
|
-
get(id) {
|
|
1220
|
-
return this.scanners.get(id);
|
|
1221
|
-
}
|
|
1222
|
-
list() {
|
|
1223
|
-
return [...this.scanners.values()];
|
|
1224
|
-
}
|
|
1225
|
-
/** Scanners whose `platforms` include the given platform. */
|
|
1226
|
-
forPlatform(platform) {
|
|
1227
|
-
return this.list().filter((s) => s.platforms === "all" || s.platforms.includes(platform));
|
|
1228
|
-
}
|
|
1229
|
-
};
|
|
1230
|
-
|
|
1231
|
-
// src/scanners/bookmarks.ts
|
|
1232
|
-
var PERSONAL = [
|
|
1233
|
-
"facebook.",
|
|
1234
|
-
"instagram.",
|
|
1235
|
-
"twitter.",
|
|
1236
|
-
"x.com",
|
|
1237
|
-
"tiktok.",
|
|
1238
|
-
"reddit.",
|
|
1239
|
-
"youtube.",
|
|
1240
|
-
"netflix.",
|
|
1241
|
-
"spotify.",
|
|
1242
|
-
"twitch.",
|
|
1243
|
-
"pinterest.",
|
|
1244
|
-
"snapchat.",
|
|
1245
|
-
"whatsapp.",
|
|
1246
|
-
"amazon.",
|
|
1247
|
-
"ebay.",
|
|
1248
|
-
"aliexpress.",
|
|
1249
|
-
"cnn.",
|
|
1250
|
-
"bbc.",
|
|
1251
|
-
"nytimes.",
|
|
1252
|
-
"espn.",
|
|
1253
|
-
"booking.",
|
|
1254
|
-
"airbnb.",
|
|
1255
|
-
"tripadvisor.",
|
|
1256
|
-
"wikipedia."
|
|
1257
|
-
];
|
|
1258
|
-
var BUSINESS = [
|
|
1259
|
-
"github.",
|
|
1260
|
-
"gitlab.",
|
|
1261
|
-
"bitbucket.",
|
|
1262
|
-
"atlassian.",
|
|
1263
|
-
"jira.",
|
|
1264
|
-
"confluence.",
|
|
1265
|
-
"notion.",
|
|
1266
|
-
"linear.",
|
|
1267
|
-
"slack.",
|
|
1268
|
-
"zoom.",
|
|
1269
|
-
"figma.",
|
|
1270
|
-
"miro.",
|
|
1271
|
-
"vercel.",
|
|
1272
|
-
"netlify.",
|
|
1273
|
-
"heroku.",
|
|
1274
|
-
"datadog",
|
|
1275
|
-
"sentry.",
|
|
1276
|
-
"grafana.",
|
|
1277
|
-
"pagerduty.",
|
|
1278
|
-
"aws.amazon.",
|
|
1279
|
-
"console.cloud.google",
|
|
1280
|
-
"portal.azure",
|
|
1281
|
-
"cloudflare.",
|
|
1282
|
-
"hubspot.",
|
|
1283
|
-
"salesforce.",
|
|
1284
|
-
"stripe.",
|
|
1285
|
-
"twilio.",
|
|
1286
|
-
"sendgrid.",
|
|
1287
|
-
"mailchimp.",
|
|
1288
|
-
"segment.",
|
|
1289
|
-
"mixpanel.",
|
|
1290
|
-
"amplitude.",
|
|
1291
|
-
"looker.",
|
|
1292
|
-
"tableau.",
|
|
1293
|
-
"snowflake.",
|
|
1294
|
-
"databricks.",
|
|
1295
|
-
"mongodb.",
|
|
1296
|
-
"redis.",
|
|
1297
|
-
"elastic.",
|
|
1298
|
-
"openai.",
|
|
1299
|
-
"anthropic.",
|
|
1300
|
-
"huggingface.",
|
|
1301
|
-
"docker.",
|
|
1302
|
-
"npmjs.",
|
|
1303
|
-
"pypi.",
|
|
1304
|
-
"circleci.",
|
|
1305
|
-
"travis-ci.",
|
|
1306
|
-
"jenkins.",
|
|
1307
|
-
"terraform.",
|
|
1308
|
-
"hashicorp.",
|
|
1309
|
-
"okta.",
|
|
1310
|
-
"auth0.",
|
|
1311
|
-
"1password.",
|
|
1312
|
-
"asana.",
|
|
1313
|
-
"trello.",
|
|
1314
|
-
"monday."
|
|
1315
|
-
];
|
|
1316
|
-
function classify(hostname) {
|
|
1317
|
-
const h = hostname.toLowerCase();
|
|
1318
|
-
if (PERSONAL.some((p) => h.includes(p))) return null;
|
|
1319
|
-
if (BUSINESS.some((b) => h.includes(b))) return { type: "saas_tool", confidence: 0.7 };
|
|
1320
|
-
if (/^\d+\.\d+\.\d+\.\d+$/.test(h) || /\.(internal|local|corp|lan)\b/.test(h)) {
|
|
1321
|
-
return { type: "web_service", confidence: 0.6 };
|
|
1322
|
-
}
|
|
1323
|
-
return null;
|
|
1324
|
-
}
|
|
1325
|
-
var bookmarksScanner = {
|
|
1326
|
-
id: "bookmarks",
|
|
1327
|
-
title: "Browser bookmarks",
|
|
1328
|
-
platforms: "all",
|
|
1329
|
-
detect: () => true,
|
|
1330
|
-
async scan() {
|
|
1331
|
-
const hosts = await scanAllBookmarks();
|
|
1332
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1333
|
-
const nodes = [];
|
|
1334
|
-
for (const host of hosts) {
|
|
1335
|
-
const klass = classify(host.hostname);
|
|
1336
|
-
if (!klass) continue;
|
|
1337
|
-
const id = `${klass.type}:${host.hostname}`;
|
|
1338
|
-
if (seen.has(id)) continue;
|
|
1339
|
-
seen.add(id);
|
|
1340
|
-
nodes.push({
|
|
1341
|
-
id,
|
|
1342
|
-
type: klass.type,
|
|
1343
|
-
name: host.hostname,
|
|
1344
|
-
discoveredVia: "bookmark",
|
|
1345
|
-
confidence: klass.confidence,
|
|
1346
|
-
tags: ["bookmark"],
|
|
1347
|
-
metadata: { protocol: host.protocol, ...host.port ? { port: host.port } : {} }
|
|
1348
|
-
});
|
|
1349
|
-
}
|
|
1350
|
-
return { nodes, edges: [] };
|
|
1351
|
-
}
|
|
1352
|
-
};
|
|
1353
|
-
|
|
1354
|
-
// src/scanners/installed-apps.ts
|
|
1355
|
-
var KNOWN_TOOLS = {
|
|
1356
|
-
ide: ["code", "code-insiders", "cursor", "windsurf", "zed", "nvim", "vim", "emacs", "idea", "webstorm", "pycharm", "goland", "datagrip", "clion", "rider", "phpstorm"],
|
|
1357
|
-
"dev-tool": ["git", "gh", "docker", "docker-compose", "podman", "kubectl", "helm", "terraform", "ansible", "vagrant", "packer", "consul", "vault", "nomad"],
|
|
1358
|
-
runtime: ["node", "npm", "pnpm", "yarn", "bun", "deno", "python", "python3", "pip", "poetry", "ruby", "rails", "java", "mvn", "gradle", "go", "cargo", "rustc", "php", "composer", "dotnet"],
|
|
1359
|
-
database: ["psql", "mysql", "mongosh", "redis-cli", "sqlite3", "clickhouse-client"],
|
|
1360
|
-
cloud: ["aws", "gcloud", "az", "heroku", "fly", "vercel", "netlify", "wrangler", "supabase"],
|
|
1361
|
-
browser: ["google-chrome", "chromium", "firefox", "brave", "opera"],
|
|
1362
|
-
observability: ["prometheus", "grafana-cli", "datadog-agent", "newrelic-agent"]
|
|
1363
|
-
};
|
|
1364
|
-
var installedAppsScanner = {
|
|
1365
|
-
id: "installed-apps",
|
|
1366
|
-
title: "Installed apps & developer tools",
|
|
1367
|
-
platforms: "all",
|
|
1368
|
-
allowedCommands: ["which", "command", "Get-Command"],
|
|
1369
|
-
detect: () => true,
|
|
1370
|
-
async scan(ctx) {
|
|
1371
|
-
const nodes = [];
|
|
1372
|
-
const hintTerms = (ctx.hint ?? "").toLowerCase().split(/[\s,]+/).filter(Boolean);
|
|
1373
|
-
for (const [category, tools] of Object.entries(KNOWN_TOOLS)) {
|
|
1374
|
-
for (const tool of tools) {
|
|
1375
|
-
const path = commandExists(tool);
|
|
1376
|
-
if (!path) continue;
|
|
1377
|
-
const boosted = hintTerms.some((t) => tool.includes(t));
|
|
1378
|
-
nodes.push({
|
|
1379
|
-
id: `saas_tool:${tool}`,
|
|
1380
|
-
type: "saas_tool",
|
|
1381
|
-
name: tool,
|
|
1382
|
-
discoveredVia: "installed-app",
|
|
1383
|
-
confidence: boosted ? 0.95 : 0.9,
|
|
1384
|
-
tags: [category],
|
|
1385
|
-
metadata: { category, path }
|
|
1386
|
-
});
|
|
1387
|
-
}
|
|
1388
|
-
}
|
|
1389
|
-
return { nodes, edges: [] };
|
|
1390
|
-
}
|
|
1391
|
-
};
|
|
1392
|
-
|
|
1393
|
-
// src/scanners/ports.ts
|
|
1394
|
-
var PORT_MAP = {
|
|
1395
|
-
5432: { type: "database_server", service: "postgresql" },
|
|
1396
|
-
3306: { type: "database_server", service: "mysql" },
|
|
1397
|
-
1433: { type: "database_server", service: "sqlserver" },
|
|
1398
|
-
27017: { type: "database_server", service: "mongodb" },
|
|
1399
|
-
9200: { type: "database_server", service: "elasticsearch" },
|
|
1400
|
-
6379: { type: "cache_server", service: "redis" },
|
|
1401
|
-
11211: { type: "cache_server", service: "memcached" },
|
|
1402
|
-
9092: { type: "message_broker", service: "kafka" },
|
|
1403
|
-
5672: { type: "message_broker", service: "rabbitmq" },
|
|
1404
|
-
4222: { type: "message_broker", service: "nats" },
|
|
1405
|
-
9090: { type: "web_service", service: "prometheus" },
|
|
1406
|
-
3e3: { type: "web_service", service: "http-app" },
|
|
1407
|
-
8080: { type: "web_service", service: "http-app" },
|
|
1408
|
-
8e3: { type: "web_service", service: "http-app" },
|
|
1409
|
-
80: { type: "web_service", service: "http" },
|
|
1410
|
-
443: { type: "web_service", service: "https" },
|
|
1411
|
-
8200: { type: "web_service", service: "vault" },
|
|
1412
|
-
8500: { type: "web_service", service: "consul" },
|
|
1413
|
-
2379: { type: "web_service", service: "etcd" },
|
|
1414
|
-
5601: { type: "web_service", service: "kibana" },
|
|
1415
|
-
15672: { type: "web_service", service: "rabbitmq-management" }
|
|
1416
|
-
};
|
|
1417
|
-
function extractListeningPorts(raw) {
|
|
1418
|
-
const ports = /* @__PURE__ */ new Set();
|
|
1419
|
-
for (const m of raw.matchAll(/[:.](\d{2,5})\b/g)) {
|
|
1420
|
-
const p = Number(m[1]);
|
|
1421
|
-
if (p in PORT_MAP) ports.add(p);
|
|
1422
|
-
}
|
|
1423
|
-
return [...ports];
|
|
1424
|
-
}
|
|
1425
|
-
var portsScanner = {
|
|
1426
|
-
id: "local-ports",
|
|
1427
|
-
title: "Local listening ports",
|
|
1428
|
-
platforms: "all",
|
|
1429
|
-
allowedCommands: ["ss", "lsof", "Get-NetTCPConnection"],
|
|
1430
|
-
detect: () => true,
|
|
1431
|
-
async scan() {
|
|
1432
|
-
const raw = scanListeningPorts();
|
|
1433
|
-
const nodes = [];
|
|
1434
|
-
for (const port of extractListeningPorts(raw)) {
|
|
1435
|
-
const { type, service } = PORT_MAP[port];
|
|
1436
|
-
nodes.push({
|
|
1437
|
-
id: `${type}:localhost:${port}`,
|
|
1438
|
-
type,
|
|
1439
|
-
name: `${service} (:${port})`,
|
|
1440
|
-
discoveredVia: "listening-port",
|
|
1441
|
-
confidence: 0.9,
|
|
1442
|
-
tags: ["local", service],
|
|
1443
|
-
metadata: { port, service, host: "localhost" }
|
|
1444
|
-
});
|
|
1445
|
-
}
|
|
1446
|
-
return { nodes, edges: [] };
|
|
1447
|
-
}
|
|
1448
|
-
};
|
|
1449
|
-
|
|
1450
|
-
// src/scanners/registry.ts
|
|
1451
|
-
function defaultRegistry() {
|
|
1452
|
-
return new ScannerRegistry().register(bookmarksScanner).register(installedAppsScanner).register(portsScanner);
|
|
1453
|
-
}
|
|
1454
|
-
|
|
1455
|
-
// src/discovery/local.ts
|
|
1456
|
-
async function runLocalDiscovery(db, sessionId, opts = {}) {
|
|
1457
|
-
const registry = opts.registry ?? defaultRegistry();
|
|
1458
|
-
const ctx = { hint: opts.hint, platform: PLATFORM, run };
|
|
1459
|
-
const nodes = /* @__PURE__ */ new Map();
|
|
1460
|
-
const edges = [];
|
|
1461
|
-
const ran = [];
|
|
1462
|
-
for (const scanner of registry.forPlatform(PLATFORM)) {
|
|
1463
|
-
try {
|
|
1464
|
-
if (!await scanner.detect(ctx)) continue;
|
|
1465
|
-
const result = await scanner.scan(ctx);
|
|
1466
|
-
ran.push(scanner.id);
|
|
1467
|
-
for (const node of result.nodes) {
|
|
1468
|
-
const prev = nodes.get(node.id);
|
|
1469
|
-
if (!prev || node.confidence > prev.confidence) nodes.set(node.id, node);
|
|
1470
|
-
}
|
|
1471
|
-
edges.push(...result.edges);
|
|
1472
|
-
opts.onProgress?.(`${scanner.title}: +${result.nodes.length} nodes`);
|
|
1473
|
-
} catch (err) {
|
|
1474
|
-
opts.onProgress?.(`${scanner.title}: failed (${err instanceof Error ? err.message : String(err)})`);
|
|
1475
|
-
}
|
|
1476
|
-
}
|
|
1477
|
-
for (const node of nodes.values()) db.upsertNode(sessionId, node);
|
|
1478
|
-
for (const edge of edges) {
|
|
1479
|
-
if (nodes.has(edge.sourceId) && nodes.has(edge.targetId)) db.insertEdge(sessionId, edge);
|
|
1480
|
-
}
|
|
1481
|
-
return { nodes: nodes.size, edges: edges.length, scanners: ran };
|
|
1482
|
-
}
|
|
1483
|
-
function localDiscoveryFn(registry) {
|
|
1484
|
-
return async (db, sessionId, opts) => {
|
|
1485
|
-
const r = await runLocalDiscovery(db, sessionId, { hint: opts.hint, registry });
|
|
1486
|
-
return { nodes: r.nodes, edges: r.edges };
|
|
1487
|
-
};
|
|
1488
|
-
}
|
|
1489
|
-
|
|
1490
|
-
// src/mcp/start.ts
|
|
1491
|
-
async function startMcp(opts = {}) {
|
|
1492
|
-
const log = opts.log ?? ((m) => process.stderr.write(m + "\n"));
|
|
1493
|
-
const db = new CartographyDB(opts.dbPath ?? defaultConfig().dbPath);
|
|
1494
|
-
let search;
|
|
1495
|
-
if (opts.semantic !== false) {
|
|
1496
|
-
search = await createSemanticSearch(db);
|
|
1497
|
-
log("semantic search: ready");
|
|
1498
|
-
}
|
|
1499
|
-
const discovery = localDiscoveryFn();
|
|
1500
|
-
const factory = () => createMcpServer({ db, session: opts.session ?? "latest", search, discovery });
|
|
1501
|
-
if (opts.transport === "http") {
|
|
1502
|
-
const port = opts.port ?? 3737;
|
|
1503
|
-
const host = opts.host ?? "127.0.0.1";
|
|
1504
|
-
await runHttp(factory, { port, host });
|
|
1505
|
-
log(`Cartography MCP server (Streamable HTTP) on http://${host}:${port}/mcp`);
|
|
1506
|
-
} else {
|
|
1507
|
-
log("Cartography MCP server (stdio) ready");
|
|
1508
|
-
await runStdio(factory());
|
|
1509
|
-
}
|
|
1510
|
-
}
|
|
1511
|
-
|
|
1512
|
-
export {
|
|
1513
|
-
CartographyDB,
|
|
1514
|
-
startMcp
|
|
1515
|
-
};
|
|
1516
|
-
//# sourceMappingURL=chunk-W7YE6AAH.js.map
|