@morozinc/opencode-tencentdb-plugin 0.0.0-stage → 0.1.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/LICENSE +661 -0
- package/LICENSE-MIT +24 -0
- package/NOTICE.md +14 -0
- package/README.md +207 -2
- package/dist/gui-experimental.cjs +64 -0
- package/dist/integration.mjs +1986 -0
- package/docs/screenshots/code-indexes.png +0 -0
- package/package.json +61 -4
- package/scripts/prepare-runtime.mjs +298 -0
- package/src/binding.ts +33 -0
- package/src/bmad-artifact-preview.tsx +111 -0
- package/src/embedding-settings.tsx +191 -0
- package/src/gui.tsx +388 -0
- package/src/index.ts +484 -0
- package/src/integration.d.ts +75 -0
- package/src/rpc.ts +195 -0
- package/src/rule-document.ts +44 -0
- package/src/rules-contract.ts +77 -0
- package/src/rules.ts +237 -0
- package/src/runtime.ts +436 -0
- package/vendor/TENCENT-LICENSE +27 -0
- package/vendor/integration/native/config.ts +253 -0
- package/vendor/integration/native/embedding.ts +270 -0
- package/vendor/integration/native/index.ts +265 -0
- package/vendor/integration/project/index.ts +151 -0
- package/vendor/integration/project/knowledge.ts +283 -0
- package/vendor/integration/server.ts +154 -0
- package/vendor/integration/tencentChatRules.ts +84 -0
- package/vendor/integration/tencentGenerationContext.ts +4 -0
- package/vendor/integration/tencentKnowledgeClient.ts +512 -0
- package/vendor/integration/tencentMemoryClient.ts +391 -0
- package/vendor/integration/tencentUserQuestion.ts +51 -0
- package/vendor/locks/MemoryCore.json +4776 -0
- package/vendor/locks/MemoryKnowledge.json +3761 -0
- package/vendor/locks/MemoryPanel.json +467 -0
- package/vendor/locks/web.json +6418 -0
- package/vendor/provenance.json +21 -0
- package/vendor/runner.mjs +12 -0
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdirSync, openSync, closeSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createServer } from "node:net";
|
|
5
|
+
import { nativeConfig, provision, recoverEmbeddingChange } from "./config";
|
|
6
|
+
|
|
7
|
+
const children = new Set<ChildProcess>();
|
|
8
|
+
let stopping = false;
|
|
9
|
+
|
|
10
|
+
type StopMemoryChildOptions = {
|
|
11
|
+
graceMs?: number;
|
|
12
|
+
forceWaitMs?: number;
|
|
13
|
+
signal?: (signal: NodeJS.Signals) => Promise<"sent" | "missing">;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
async function signalProcessGroup(
|
|
17
|
+
pid: number,
|
|
18
|
+
signal: NodeJS.Signals,
|
|
19
|
+
): Promise<"sent" | "missing"> {
|
|
20
|
+
if (process.platform !== "win32") {
|
|
21
|
+
try {
|
|
22
|
+
process.kill(-pid, signal);
|
|
23
|
+
return "sent";
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if ((error as NodeJS.ErrnoException).code === "ESRCH") return "missing";
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return await new Promise((resolve, reject) => {
|
|
31
|
+
const taskkill = spawn(
|
|
32
|
+
"taskkill.exe",
|
|
33
|
+
["/pid", String(pid), "/T", ...(signal === "SIGKILL" ? ["/F"] : [])],
|
|
34
|
+
{
|
|
35
|
+
windowsHide: true,
|
|
36
|
+
stdio: "ignore",
|
|
37
|
+
},
|
|
38
|
+
);
|
|
39
|
+
taskkill.once("error", reject);
|
|
40
|
+
taskkill.once("exit", (code) => {
|
|
41
|
+
if (code === 0) resolve("sent");
|
|
42
|
+
else
|
|
43
|
+
reject(
|
|
44
|
+
new Error(`taskkill failed with exit code ${code ?? "unknown"}`),
|
|
45
|
+
);
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Do not let callers touch SQLite files until the owning process has actually exited. */
|
|
51
|
+
export async function stopOwnedMemoryChild(
|
|
52
|
+
child: ChildProcess,
|
|
53
|
+
{ graceMs = 5_000, forceWaitMs = 5_000, signal }: StopMemoryChildOptions = {},
|
|
54
|
+
): Promise<void> {
|
|
55
|
+
if (child.exitCode !== null || !child.pid) return;
|
|
56
|
+
const pid = child.pid;
|
|
57
|
+
const sendSignal =
|
|
58
|
+
signal ??
|
|
59
|
+
((nextSignal: NodeJS.Signals) => signalProcessGroup(pid, nextSignal));
|
|
60
|
+
|
|
61
|
+
await new Promise<void>((resolve, reject) => {
|
|
62
|
+
let settled = false;
|
|
63
|
+
let forceTimer: NodeJS.Timeout | undefined;
|
|
64
|
+
let forceConfirmationTimer: NodeJS.Timeout | undefined;
|
|
65
|
+
const finish = (error?: Error) => {
|
|
66
|
+
if (settled) return;
|
|
67
|
+
settled = true;
|
|
68
|
+
if (forceTimer) clearTimeout(forceTimer);
|
|
69
|
+
if (forceConfirmationTimer) clearTimeout(forceConfirmationTimer);
|
|
70
|
+
child.off("exit", onExit);
|
|
71
|
+
child.off("error", onError);
|
|
72
|
+
if (error) reject(error);
|
|
73
|
+
else resolve();
|
|
74
|
+
};
|
|
75
|
+
const onExit = () => finish();
|
|
76
|
+
const onError = (error: Error) => finish(error);
|
|
77
|
+
child.once("exit", onExit);
|
|
78
|
+
child.once("error", onError);
|
|
79
|
+
|
|
80
|
+
// Cover an exit between the initial state check and listener registration.
|
|
81
|
+
if (child.exitCode !== null) {
|
|
82
|
+
finish();
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
forceTimer = setTimeout(() => {
|
|
87
|
+
forceConfirmationTimer = setTimeout(
|
|
88
|
+
() =>
|
|
89
|
+
finish(
|
|
90
|
+
new Error(
|
|
91
|
+
`Memory service process ${pid} did not exit after forced termination`,
|
|
92
|
+
),
|
|
93
|
+
),
|
|
94
|
+
forceWaitMs,
|
|
95
|
+
);
|
|
96
|
+
void sendSignal("SIGKILL")
|
|
97
|
+
.then((result) => {
|
|
98
|
+
if (result === "missing") finish();
|
|
99
|
+
})
|
|
100
|
+
.catch((error) =>
|
|
101
|
+
finish(error instanceof Error ? error : new Error(String(error))),
|
|
102
|
+
);
|
|
103
|
+
}, graceMs);
|
|
104
|
+
|
|
105
|
+
// A graceful signal failure is retried with forced termination after the grace period.
|
|
106
|
+
void sendSignal("SIGTERM")
|
|
107
|
+
.then((result) => {
|
|
108
|
+
if (result === "missing") finish();
|
|
109
|
+
})
|
|
110
|
+
.catch(() => {});
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Stop only owned service process groups; never remove persistent data. */
|
|
115
|
+
export async function stopNativeMemory(): Promise<void> {
|
|
116
|
+
stopping = true;
|
|
117
|
+
await Promise.all([...children].map((child) => stopOwnedMemoryChild(child)));
|
|
118
|
+
children.clear();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Launch the bundled services before AionCore; all mutable files live in userData. */
|
|
122
|
+
export async function startNativeMemory(
|
|
123
|
+
bundle: string,
|
|
124
|
+
userData: string,
|
|
125
|
+
recover = true,
|
|
126
|
+
): Promise<string> {
|
|
127
|
+
if (!existsSync(path.join(bundle, "runtime.json")))
|
|
128
|
+
throw new Error("Bundled Tencent memory runtime is missing");
|
|
129
|
+
stopping = false;
|
|
130
|
+
if (recover) recoverEmbeddingChange(userData);
|
|
131
|
+
const config = nativeConfig(userData);
|
|
132
|
+
const logDir = path.join(config.root, "logs");
|
|
133
|
+
mkdirSync(logDir, { recursive: true });
|
|
134
|
+
const node = path.join(
|
|
135
|
+
bundle,
|
|
136
|
+
"bin",
|
|
137
|
+
process.platform === "win32" ? "node.exe" : "node",
|
|
138
|
+
);
|
|
139
|
+
const common = {
|
|
140
|
+
...process.env,
|
|
141
|
+
NODE_ENV: "production",
|
|
142
|
+
NODE_OPTIONS: "",
|
|
143
|
+
ELECTRON_RUN_AS_NODE: "",
|
|
144
|
+
PATH: `${path.dirname(node)}${path.delimiter}${process.env.PATH || ""}`,
|
|
145
|
+
AION_LLM_REQUIRE_CONTEXT: "1",
|
|
146
|
+
AION_LLM_CALLBACK_ALLOWED_HOSTS: "127.0.0.1,localhost,[::1]",
|
|
147
|
+
LOG_LEVEL: "info",
|
|
148
|
+
LOG_PATH: logDir,
|
|
149
|
+
};
|
|
150
|
+
const start = async (
|
|
151
|
+
name: string,
|
|
152
|
+
entry: string,
|
|
153
|
+
url: string,
|
|
154
|
+
env: Record<string, string>,
|
|
155
|
+
) => {
|
|
156
|
+
await new Promise<void>((resolve, reject) => {
|
|
157
|
+
const probe = createServer();
|
|
158
|
+
probe.once("error", () =>
|
|
159
|
+
reject(
|
|
160
|
+
new Error(
|
|
161
|
+
`${name} port is occupied; stop the other memory instance first`,
|
|
162
|
+
),
|
|
163
|
+
),
|
|
164
|
+
);
|
|
165
|
+
probe.listen(Number(new URL(url).port), "127.0.0.1", () =>
|
|
166
|
+
probe.close(() => resolve()),
|
|
167
|
+
);
|
|
168
|
+
});
|
|
169
|
+
const log = openSync(path.join(logDir, `${name}.log`), "a", 0o600);
|
|
170
|
+
const child = spawn(
|
|
171
|
+
node,
|
|
172
|
+
[
|
|
173
|
+
"--import",
|
|
174
|
+
"tsx",
|
|
175
|
+
path.join(bundle, "runner.mjs"),
|
|
176
|
+
path.join(bundle, name, entry),
|
|
177
|
+
],
|
|
178
|
+
{
|
|
179
|
+
cwd: path.join(bundle, name),
|
|
180
|
+
env: { ...common, ...env },
|
|
181
|
+
detached: process.platform !== "win32",
|
|
182
|
+
windowsHide: true,
|
|
183
|
+
stdio: ["ignore", log, log, "ipc"],
|
|
184
|
+
},
|
|
185
|
+
);
|
|
186
|
+
closeSync(log);
|
|
187
|
+
children.add(child);
|
|
188
|
+
let exited = false;
|
|
189
|
+
child.once("error", () => {
|
|
190
|
+
exited = true;
|
|
191
|
+
});
|
|
192
|
+
child.once("exit", () => {
|
|
193
|
+
exited = true;
|
|
194
|
+
children.delete(child);
|
|
195
|
+
if (!stopping) console.error(`[Memory] ${name} exited; see ${logDir}`);
|
|
196
|
+
});
|
|
197
|
+
for (let attempt = 0; attempt < 120; attempt++) {
|
|
198
|
+
if (exited) throw new Error(`${name} could not start; see ${logDir}`);
|
|
199
|
+
try {
|
|
200
|
+
if (
|
|
201
|
+
(await fetch(`${url}/health`, { signal: AbortSignal.timeout(500) }))
|
|
202
|
+
.ok
|
|
203
|
+
) {
|
|
204
|
+
// A foreign listener must not make a failed child appear healthy.
|
|
205
|
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
206
|
+
if (exited) throw new Error(`${name} port is occupied`);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
} catch {
|
|
210
|
+
/* Wait for our child, bounded below. */
|
|
211
|
+
}
|
|
212
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
213
|
+
}
|
|
214
|
+
throw new Error(`${name} startup timed out; see ${logDir}`);
|
|
215
|
+
};
|
|
216
|
+
try {
|
|
217
|
+
await start("MemoryCore", "src/gateway/server.ts", config.coreUrl, {
|
|
218
|
+
TDAI_GATEWAY_CONFIG: config.gatewayFile,
|
|
219
|
+
TDAI_GATEWAY_HOST: "127.0.0.1",
|
|
220
|
+
TDAI_GATEWAY_PORT: String(config.settings.corePort),
|
|
221
|
+
TDAI_GATEWAY_API_KEY: config.secrets.gateway,
|
|
222
|
+
TDAI_DATA_DIR: path.join(config.root, "core"),
|
|
223
|
+
STORE_MODE: "sqlite",
|
|
224
|
+
});
|
|
225
|
+
const appConfig = await provision(config);
|
|
226
|
+
await start("MemoryKnowledge", "src/server.ts", config.knowledgeUrl, {
|
|
227
|
+
HOST: "127.0.0.1",
|
|
228
|
+
PORT: String(config.settings.knowledgePort),
|
|
229
|
+
KNOWLEDGE_SERVICE_KEY: config.secrets.knowledge,
|
|
230
|
+
KNOWLEDGE_DATA_DIR: path.join(config.root, "knowledge"),
|
|
231
|
+
KNOWLEDGE_DB_PATH: path.join(config.root, "knowledge/knowledge.db"),
|
|
232
|
+
KNOWLEDGE_PUBLIC_BASE_URL: `${config.knowledgeUrl}/v3`,
|
|
233
|
+
TMC_CALLBACK_URL: config.panelUrl,
|
|
234
|
+
KNOWLEDGE_LOCAL_ROOTS: config.settings.knowledgeWorkspaces
|
|
235
|
+
.map((item) => item.servicePath)
|
|
236
|
+
.join(path.delimiter),
|
|
237
|
+
KNOWLEDGE_LOCAL_PROJECTS_DIR: path.join(
|
|
238
|
+
config.root,
|
|
239
|
+
"knowledge-projects",
|
|
240
|
+
),
|
|
241
|
+
LLM_MODE: "custom",
|
|
242
|
+
});
|
|
243
|
+
await start("MemoryPanel", "src/index.ts", config.panelUrl, {
|
|
244
|
+
HOST: "127.0.0.1",
|
|
245
|
+
PORT: String(config.settings.panelPort),
|
|
246
|
+
UI_DIST_DIR: path.join(bundle, "MemoryPanel/web/dist"),
|
|
247
|
+
METADATA_INSTANCES_CONFIG: config.instancesFile,
|
|
248
|
+
KNOWLEDGE_SERVICE_URL: config.knowledgeUrl,
|
|
249
|
+
KNOWLEDGE_AUTH_TOKEN: config.secrets.knowledge,
|
|
250
|
+
KNOWLEDGE_LLM_BINDING_SYNC: "0",
|
|
251
|
+
TDAI_AGENT_TEMPLATE_DIR: path.join(
|
|
252
|
+
config.root,
|
|
253
|
+
"knowledge/agent-templates",
|
|
254
|
+
),
|
|
255
|
+
PANEL_AUTH_IDENTITY_STORE_PATH: path.join(
|
|
256
|
+
config.root,
|
|
257
|
+
"panel/identities.json",
|
|
258
|
+
),
|
|
259
|
+
});
|
|
260
|
+
return appConfig;
|
|
261
|
+
} catch (error) {
|
|
262
|
+
await stopNativeMemory();
|
|
263
|
+
throw error;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { binding } from "../../../src/binding";
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
import {
|
|
5
|
+
lstat,
|
|
6
|
+
readdir,
|
|
7
|
+
realpath,
|
|
8
|
+
mkdir,
|
|
9
|
+
writeFile,
|
|
10
|
+
rename,
|
|
11
|
+
} from "node:fs/promises";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { promisify } from "node:util";
|
|
14
|
+
import type {
|
|
15
|
+
ChatRuleMutation,
|
|
16
|
+
ChatRuleScope,
|
|
17
|
+
} from "@/common/types/agent/chatRules";
|
|
18
|
+
import { z } from "zod";
|
|
19
|
+
|
|
20
|
+
export const projectContextSchema = z.object({
|
|
21
|
+
project_id: z.string().nullable(),
|
|
22
|
+
name: z.string(),
|
|
23
|
+
workspace: z.string().min(1),
|
|
24
|
+
roots: z.array(z.string().min(1)).min(1).max(64),
|
|
25
|
+
});
|
|
26
|
+
export type ProjectContext = z.infer<typeof projectContextSchema>;
|
|
27
|
+
export type Repository = { name: string; path: string };
|
|
28
|
+
const git = promisify(execFile);
|
|
29
|
+
const omitted = new Set([
|
|
30
|
+
"node_modules",
|
|
31
|
+
"vendor",
|
|
32
|
+
"build",
|
|
33
|
+
"dist",
|
|
34
|
+
"out",
|
|
35
|
+
"target",
|
|
36
|
+
"coverage",
|
|
37
|
+
"tmp",
|
|
38
|
+
"output",
|
|
39
|
+
"worktrees",
|
|
40
|
+
"qa-artifacts",
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
/** Discover repositories in a product folder; stop at each Git root (its index includes submodules).
|
|
44
|
+
* ponytail: bounded discovery (3 levels, 2000 directories). Attach deeper repositories explicitly.
|
|
45
|
+
*/
|
|
46
|
+
export async function discoverRepositories(context: ProjectContext) {
|
|
47
|
+
const repositories: Repository[] = [];
|
|
48
|
+
const errors: Array<{ path: string; error: string }> = [];
|
|
49
|
+
const seen = new Set<string>();
|
|
50
|
+
let visited = 0;
|
|
51
|
+
const walk = async (
|
|
52
|
+
directory: string,
|
|
53
|
+
depth: number,
|
|
54
|
+
label: string,
|
|
55
|
+
): Promise<void> => {
|
|
56
|
+
if (++visited > 2000)
|
|
57
|
+
throw new Error(
|
|
58
|
+
"Repository discovery exceeded 2000 directories; attach repositories directly",
|
|
59
|
+
);
|
|
60
|
+
const marker = await lstat(path.join(directory, ".git")).catch(
|
|
61
|
+
(): null => null,
|
|
62
|
+
);
|
|
63
|
+
if (marker && !marker.isSymbolicLink()) {
|
|
64
|
+
const { stdout } = await git(
|
|
65
|
+
"git",
|
|
66
|
+
["-C", directory, "rev-parse", "--show-toplevel"],
|
|
67
|
+
{ timeout: 5000 },
|
|
68
|
+
);
|
|
69
|
+
if ((await realpath(stdout.trim())) !== directory)
|
|
70
|
+
throw new Error("Git root differs from the selected directory");
|
|
71
|
+
if (
|
|
72
|
+
!repositories.some((repo) => directory.startsWith(repo.path + path.sep))
|
|
73
|
+
) {
|
|
74
|
+
repositories.push({ name: label, path: directory });
|
|
75
|
+
}
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (depth === 3) return;
|
|
79
|
+
for (const entry of (
|
|
80
|
+
await readdir(directory, { withFileTypes: true })
|
|
81
|
+
).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
82
|
+
if (
|
|
83
|
+
!entry.isDirectory() ||
|
|
84
|
+
entry.name.startsWith(".") ||
|
|
85
|
+
omitted.has(entry.name)
|
|
86
|
+
)
|
|
87
|
+
continue;
|
|
88
|
+
await walk(
|
|
89
|
+
path.join(directory, entry.name),
|
|
90
|
+
depth + 1,
|
|
91
|
+
`${label}/${entry.name}`,
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
for (const root of context.roots) {
|
|
96
|
+
try {
|
|
97
|
+
const canonical = await realpath(root);
|
|
98
|
+
if (seen.has(canonical)) continue;
|
|
99
|
+
seen.add(canonical);
|
|
100
|
+
await walk(canonical, 0, path.basename(canonical));
|
|
101
|
+
} catch (error) {
|
|
102
|
+
errors.push({
|
|
103
|
+
path: root,
|
|
104
|
+
error: error instanceof Error ? error.message : String(error),
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// Attached subdirectories can overlap discovered roots, regardless of entry order.
|
|
109
|
+
return {
|
|
110
|
+
repositories: repositories.filter(
|
|
111
|
+
(r) =>
|
|
112
|
+
!repositories.some(
|
|
113
|
+
(p) => p.path !== r.path && r.path.startsWith(p.path + path.sep),
|
|
114
|
+
),
|
|
115
|
+
),
|
|
116
|
+
errors,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function hasMemoryChatBinding(): boolean {
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
export async function callMemoryChatHost(
|
|
124
|
+
route: string,
|
|
125
|
+
mutation?: unknown,
|
|
126
|
+
questions?: unknown[],
|
|
127
|
+
signal?: AbortSignal,
|
|
128
|
+
): Promise<unknown> {
|
|
129
|
+
return binding().host(route, mutation, questions, signal);
|
|
130
|
+
}
|
|
131
|
+
export async function resolveProjectContext(): Promise<ProjectContext> {
|
|
132
|
+
return binding().project;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Native desktop: grant snapshot access only after explicit project indexing.
|
|
136
|
+
* Each project has its own atomic file so concurrent projects cannot overwrite each other.
|
|
137
|
+
*/
|
|
138
|
+
export async function allowNativeProject(
|
|
139
|
+
directory: string,
|
|
140
|
+
context: ProjectContext,
|
|
141
|
+
): Promise<void> {
|
|
142
|
+
const roots = await Promise.all(context.roots.map((root) => realpath(root)));
|
|
143
|
+
const key = createHash("sha256")
|
|
144
|
+
.update(context.project_id || context.workspace)
|
|
145
|
+
.digest("hex");
|
|
146
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
147
|
+
const target = path.join(directory, `${key}.json`);
|
|
148
|
+
const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`;
|
|
149
|
+
await writeFile(temporary, JSON.stringify(roots), { mode: 0o600 });
|
|
150
|
+
await rename(temporary, target);
|
|
151
|
+
}
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import type { ProjectIndexCatalog } from "@/common/types/platform/electron";
|
|
2
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import {
|
|
5
|
+
TencentKnowledgeClient,
|
|
6
|
+
knowledgeRepositoryUrl,
|
|
7
|
+
type KnowledgeConfig,
|
|
8
|
+
type KnowledgeDetail,
|
|
9
|
+
type CodeRuntimeAction,
|
|
10
|
+
} from "../tencentKnowledgeClient";
|
|
11
|
+
import type { MemoryConfig } from "../tencentMemoryClient";
|
|
12
|
+
import {
|
|
13
|
+
allowNativeProject,
|
|
14
|
+
discoverRepositories,
|
|
15
|
+
resolveProjectContext,
|
|
16
|
+
type ProjectContext,
|
|
17
|
+
} from "./index";
|
|
18
|
+
|
|
19
|
+
/** Current project roots are the registry. Tencent already deduplicates graphs by repository URL. */
|
|
20
|
+
export class ProjectKnowledge {
|
|
21
|
+
constructor(private readonly config: MemoryConfig & KnowledgeConfig) {}
|
|
22
|
+
|
|
23
|
+
private client(context: ProjectContext) {
|
|
24
|
+
return new TencentKnowledgeClient({
|
|
25
|
+
...this.config,
|
|
26
|
+
knowledgeWorkspaces: [
|
|
27
|
+
...(this.config.knowledgeWorkspaces || []),
|
|
28
|
+
...(this.config.nativeKnowledgeProjectsDir
|
|
29
|
+
? context.roots.map((root) => ({ hostPath: root, servicePath: root }))
|
|
30
|
+
: []),
|
|
31
|
+
],
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async catalog(context: ProjectContext): Promise<ProjectIndexCatalog> {
|
|
36
|
+
const discovered = await discoverRepositories(context);
|
|
37
|
+
const client = this.client(context);
|
|
38
|
+
const graphs: KnowledgeDetail[] = [];
|
|
39
|
+
for (let offset = 0; ; offset += 100) {
|
|
40
|
+
const page = await client.call<{
|
|
41
|
+
items: KnowledgeDetail[];
|
|
42
|
+
total: number;
|
|
43
|
+
}>("code-graph/list", {
|
|
44
|
+
team_id: this.config.teamId,
|
|
45
|
+
user_id: this.config.userId,
|
|
46
|
+
offset,
|
|
47
|
+
limit: 100,
|
|
48
|
+
});
|
|
49
|
+
graphs.push(...page.items);
|
|
50
|
+
if (offset + page.items.length >= page.total) break;
|
|
51
|
+
if (!page.items.length)
|
|
52
|
+
throw new Error("Tencent returned an incomplete index catalog");
|
|
53
|
+
}
|
|
54
|
+
const repositories = discovered.repositories.map((repo) => {
|
|
55
|
+
try {
|
|
56
|
+
const url = knowledgeRepositoryUrl(repo.path, [
|
|
57
|
+
...(this.config.knowledgeWorkspaces || []),
|
|
58
|
+
...(this.config.nativeKnowledgeProjectsDir
|
|
59
|
+
? context.roots.map((root) => ({
|
|
60
|
+
hostPath: root,
|
|
61
|
+
servicePath: root,
|
|
62
|
+
}))
|
|
63
|
+
: []),
|
|
64
|
+
]);
|
|
65
|
+
const graph = graphs.find(
|
|
66
|
+
(g) => g.repo_url === url && g.branch === "local",
|
|
67
|
+
);
|
|
68
|
+
return {
|
|
69
|
+
...repo,
|
|
70
|
+
code_graph_id: graph?.code_graph_id,
|
|
71
|
+
status: graph?.status || "not_indexed",
|
|
72
|
+
indexed_at: graph?.last_sync_at,
|
|
73
|
+
error: graph?.sync_error || undefined,
|
|
74
|
+
stats: graph?.stats,
|
|
75
|
+
};
|
|
76
|
+
} catch (error) {
|
|
77
|
+
return {
|
|
78
|
+
...repo,
|
|
79
|
+
status: "unavailable",
|
|
80
|
+
error: error instanceof Error ? error.message : String(error),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
return {
|
|
85
|
+
project_id: context.project_id,
|
|
86
|
+
name: context.name,
|
|
87
|
+
workspace: context.workspace,
|
|
88
|
+
repositories,
|
|
89
|
+
errors: discovered.errors,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async index(context: ProjectContext, repository?: string) {
|
|
94
|
+
const catalog = await this.catalog(context);
|
|
95
|
+
const selected = repository
|
|
96
|
+
? catalog.repositories.filter((repo) => repo.path === repository)
|
|
97
|
+
: catalog.repositories;
|
|
98
|
+
if (!selected.length)
|
|
99
|
+
throw new Error(
|
|
100
|
+
repository
|
|
101
|
+
? "Repository is not in the current project"
|
|
102
|
+
: "No Git repositories discovered; attach repository folders",
|
|
103
|
+
);
|
|
104
|
+
if (this.config.nativeKnowledgeProjectsDir) {
|
|
105
|
+
// Grant only discovered/selected repository roots, not unrelated files in product folders.
|
|
106
|
+
await allowNativeProject(this.config.nativeKnowledgeProjectsDir, {
|
|
107
|
+
...context,
|
|
108
|
+
roots: catalog.repositories.map((repo) => repo.path),
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
const client = this.client(context);
|
|
112
|
+
const results = [];
|
|
113
|
+
for (const repo of selected) {
|
|
114
|
+
try {
|
|
115
|
+
results.push({
|
|
116
|
+
repository: repo.path,
|
|
117
|
+
name: repo.name,
|
|
118
|
+
...(await client.index(repo.path)),
|
|
119
|
+
});
|
|
120
|
+
} catch (error) {
|
|
121
|
+
results.push({
|
|
122
|
+
repository: repo.path,
|
|
123
|
+
name: repo.name,
|
|
124
|
+
accepted: false,
|
|
125
|
+
error: error instanceof Error ? error.message : String(error),
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
project_id: context.project_id,
|
|
131
|
+
results,
|
|
132
|
+
errors: catalog.errors,
|
|
133
|
+
next: "Poll tdai_project_repositories; accepted is not ready.",
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async runtime(
|
|
138
|
+
context: ProjectContext,
|
|
139
|
+
graphId: string,
|
|
140
|
+
action: CodeRuntimeAction,
|
|
141
|
+
) {
|
|
142
|
+
const catalog = await this.catalog(context);
|
|
143
|
+
if (!catalog.repositories.some((repo) => repo.code_graph_id === graphId))
|
|
144
|
+
throw new Error("Code graph is not in the current project");
|
|
145
|
+
return this.client(context).runtime(graphId, action);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async search(
|
|
149
|
+
context: ProjectContext,
|
|
150
|
+
query: string,
|
|
151
|
+
repository?: string,
|
|
152
|
+
limit = 5,
|
|
153
|
+
) {
|
|
154
|
+
const catalog = await this.catalog(context);
|
|
155
|
+
const selected = repository
|
|
156
|
+
? catalog.repositories.filter((repo) => repo.path === repository)
|
|
157
|
+
: catalog.repositories;
|
|
158
|
+
if (repository && !selected.length)
|
|
159
|
+
throw new Error("Repository is not in the current project");
|
|
160
|
+
const client = this.client(context);
|
|
161
|
+
const results = [];
|
|
162
|
+
for (const repo of selected) {
|
|
163
|
+
if (repo.status !== "ready" || !repo.code_graph_id) {
|
|
164
|
+
results.push({
|
|
165
|
+
repository: repo.path,
|
|
166
|
+
name: repo.name,
|
|
167
|
+
status: repo.status,
|
|
168
|
+
error: repo.error,
|
|
169
|
+
});
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
results.push({
|
|
174
|
+
repository: repo.path,
|
|
175
|
+
name: repo.name,
|
|
176
|
+
status: "ready",
|
|
177
|
+
...(await client.query(repo.code_graph_id, "search", {
|
|
178
|
+
query,
|
|
179
|
+
limit,
|
|
180
|
+
})),
|
|
181
|
+
});
|
|
182
|
+
} catch (error) {
|
|
183
|
+
results.push({
|
|
184
|
+
repository: repo.path,
|
|
185
|
+
name: repo.name,
|
|
186
|
+
status: "error",
|
|
187
|
+
error: error instanceof Error ? error.message : String(error),
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return {
|
|
192
|
+
project_id: context.project_id,
|
|
193
|
+
results,
|
|
194
|
+
errors: catalog.errors,
|
|
195
|
+
complete:
|
|
196
|
+
selected.length > 0 &&
|
|
197
|
+
!catalog.errors.length &&
|
|
198
|
+
results.every((r) => r.status === "ready"),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export function registerProjectKnowledgeTools(
|
|
204
|
+
server: McpServer,
|
|
205
|
+
config: MemoryConfig & KnowledgeConfig,
|
|
206
|
+
): void {
|
|
207
|
+
const client = new ProjectKnowledge(config);
|
|
208
|
+
const result = (value: unknown) => ({
|
|
209
|
+
content: [{ type: "text" as const, text: JSON.stringify(value) }],
|
|
210
|
+
});
|
|
211
|
+
const repositorySchema = z
|
|
212
|
+
.string()
|
|
213
|
+
.min(1)
|
|
214
|
+
.optional()
|
|
215
|
+
.describe(
|
|
216
|
+
"Optional exact repository path from tdai_project_repositories; omit for all project repositories",
|
|
217
|
+
);
|
|
218
|
+
server.tool(
|
|
219
|
+
"tdai_project_repositories",
|
|
220
|
+
"Discover Git repositories under the current project workspace and attached folders, with index status. Includes product folders which are not Git repositories. Does not index code.",
|
|
221
|
+
{},
|
|
222
|
+
async () => result(await client.catalog(await resolveProjectContext())),
|
|
223
|
+
);
|
|
224
|
+
server.tool(
|
|
225
|
+
"tdai_project_index",
|
|
226
|
+
"Create or refresh separate Tencent code indexes for all current project repositories, or one selected repository. Asynchronous; accepted is not ready. Poll tdai_project_repositories for completion. Refresh only a missing or stale index relevant to the task, not on every turn. No code is changed.",
|
|
227
|
+
{ repository: repositorySchema },
|
|
228
|
+
async ({ repository }) =>
|
|
229
|
+
result(await client.index(await resolveProjectContext(), repository)),
|
|
230
|
+
);
|
|
231
|
+
server.tool(
|
|
232
|
+
"tdai_code_runtime",
|
|
233
|
+
"Inspect, load, or release a current-project code index in runtime memory. Deallocate only closes idle handles; it preserves index files, metadata, and user code. Queries load indexes again automatically. Busy indexes return an error; retry later. Use tdai_project_index to create or refresh an index.",
|
|
234
|
+
{
|
|
235
|
+
code_graph_id: z
|
|
236
|
+
.string()
|
|
237
|
+
.regex(/^cg-[a-zA-Z0-9_-]+$/)
|
|
238
|
+
.describe("Existing ID from tdai_project_repositories"),
|
|
239
|
+
action: z.enum(["status", "allocate", "deallocate"]),
|
|
240
|
+
},
|
|
241
|
+
{ destructiveHint: false, openWorldHint: false, idempotentHint: true },
|
|
242
|
+
async ({ code_graph_id, action }) =>
|
|
243
|
+
result(
|
|
244
|
+
await client.runtime(
|
|
245
|
+
await resolveProjectContext(),
|
|
246
|
+
code_graph_id,
|
|
247
|
+
action,
|
|
248
|
+
),
|
|
249
|
+
),
|
|
250
|
+
);
|
|
251
|
+
server.tool(
|
|
252
|
+
"tdai_project_code_search",
|
|
253
|
+
"Search current-project code symbols by component, class/function name, or route (for example auth handler or PaymentService). For current architecture inspect repository/index freshness first, search relevant symbols, then verify source. Results identify repository and snapshot; incomplete/failed indexes are explicit. Use returned code_graph_id with tdai_code_explore/impact for details.",
|
|
254
|
+
{
|
|
255
|
+
query: z
|
|
256
|
+
.string()
|
|
257
|
+
.min(1)
|
|
258
|
+
.max(2048)
|
|
259
|
+
.describe(
|
|
260
|
+
"1–2048 characters: symbol, component, or route query; use separate focused queries for unrelated topics.",
|
|
261
|
+
),
|
|
262
|
+
repository: repositorySchema,
|
|
263
|
+
limit: z
|
|
264
|
+
.number()
|
|
265
|
+
.int()
|
|
266
|
+
.min(1)
|
|
267
|
+
.max(10)
|
|
268
|
+
.optional()
|
|
269
|
+
.describe(
|
|
270
|
+
"Maximum returned matches: 1–10, default 5. Narrow the query or repository for more useful results.",
|
|
271
|
+
),
|
|
272
|
+
},
|
|
273
|
+
async ({ query, repository, limit }) =>
|
|
274
|
+
result(
|
|
275
|
+
await client.search(
|
|
276
|
+
await resolveProjectContext(),
|
|
277
|
+
query,
|
|
278
|
+
repository,
|
|
279
|
+
limit,
|
|
280
|
+
),
|
|
281
|
+
),
|
|
282
|
+
);
|
|
283
|
+
}
|