@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.
Files changed (38) hide show
  1. package/LICENSE +661 -0
  2. package/LICENSE-MIT +24 -0
  3. package/NOTICE.md +14 -0
  4. package/README.md +207 -2
  5. package/dist/gui-experimental.cjs +64 -0
  6. package/dist/integration.mjs +1986 -0
  7. package/docs/screenshots/code-indexes.png +0 -0
  8. package/package.json +61 -4
  9. package/scripts/prepare-runtime.mjs +298 -0
  10. package/src/binding.ts +33 -0
  11. package/src/bmad-artifact-preview.tsx +111 -0
  12. package/src/embedding-settings.tsx +191 -0
  13. package/src/gui.tsx +388 -0
  14. package/src/index.ts +484 -0
  15. package/src/integration.d.ts +75 -0
  16. package/src/rpc.ts +195 -0
  17. package/src/rule-document.ts +44 -0
  18. package/src/rules-contract.ts +77 -0
  19. package/src/rules.ts +237 -0
  20. package/src/runtime.ts +436 -0
  21. package/vendor/TENCENT-LICENSE +27 -0
  22. package/vendor/integration/native/config.ts +253 -0
  23. package/vendor/integration/native/embedding.ts +270 -0
  24. package/vendor/integration/native/index.ts +265 -0
  25. package/vendor/integration/project/index.ts +151 -0
  26. package/vendor/integration/project/knowledge.ts +283 -0
  27. package/vendor/integration/server.ts +154 -0
  28. package/vendor/integration/tencentChatRules.ts +84 -0
  29. package/vendor/integration/tencentGenerationContext.ts +4 -0
  30. package/vendor/integration/tencentKnowledgeClient.ts +512 -0
  31. package/vendor/integration/tencentMemoryClient.ts +391 -0
  32. package/vendor/integration/tencentUserQuestion.ts +51 -0
  33. package/vendor/locks/MemoryCore.json +4776 -0
  34. package/vendor/locks/MemoryKnowledge.json +3761 -0
  35. package/vendor/locks/MemoryPanel.json +467 -0
  36. package/vendor/locks/web.json +6418 -0
  37. package/vendor/provenance.json +21 -0
  38. package/vendor/runner.mjs +12 -0
package/src/rpc.ts ADDED
@@ -0,0 +1,195 @@
1
+ import { Rpc } from "@opencode/plugin/rpc";
2
+ import { z } from "zod";
3
+ import {
4
+ ruleChange,
5
+ ruleList,
6
+ ruleScope,
7
+ rulesHistory,
8
+ } from "./rules-contract.js";
9
+ export {
10
+ ruleFields,
11
+ ruleIdentity,
12
+ ruleList,
13
+ ruleView,
14
+ rulesHistory,
15
+ } from "./rules-contract.js";
16
+ export const pluginID = "opencode-tencentdb-plugin";
17
+ const empty = z.strictObject({});
18
+ const rulesErrors = {
19
+ rules_error: z.strictObject({}).describe("No additional rule error data."),
20
+ };
21
+ export const bmadArtifactPath = z
22
+ .string()
23
+ .regex(/^bmad\/[a-z0-9]+(?:-[a-z0-9]+)*-[a-f0-9]{10}\/.+\.md$/u)
24
+ .refine(
25
+ (value) =>
26
+ !/[\\:\p{Cc}]/u.test(value) &&
27
+ !value.split("/").some((part) => ["", ".", ".."].includes(part)),
28
+ )
29
+ .describe("TencentDB-relative Markdown path in a BMAD project namespace.");
30
+ export const bmadArtifact = z
31
+ .object({
32
+ content: z.string().describe("The stored artifact's Markdown body."),
33
+ })
34
+ .describe("A read-only BMAD artifact preview from TencentDB.");
35
+ export const embeddingInput = z
36
+ .object({
37
+ baseUrl: z.url().describe("OpenAI compatible embedding API base URL."),
38
+ model: z
39
+ .string()
40
+ .trim()
41
+ .min(1)
42
+ .max(200)
43
+ .describe("Model identifier at the endpoint."),
44
+ apiKey: z
45
+ .string()
46
+ .optional()
47
+ .describe(
48
+ "New key, or omit to reuse the current key at the same endpoint.",
49
+ ),
50
+ })
51
+ .describe("Candidate embedding connection for verification or rebuild.");
52
+ export const embeddingState = z
53
+ .object({
54
+ available: z
55
+ .boolean()
56
+ .describe("Whether the native runtime is configured."),
57
+ phase: z
58
+ .string()
59
+ .describe(
60
+ "Current rebuild phase: idle, checking, reindexing, complete, failed, or unavailable.",
61
+ ),
62
+ done: z.number().int().describe("Memory records processed."),
63
+ total: z.number().int().describe("Total memory records to process."),
64
+ layer: z
65
+ .string()
66
+ .optional()
67
+ .describe("Current memory layer reported by the worker."),
68
+ error: z.string().optional().describe("Last rebuild failure detail."),
69
+ current: z
70
+ .object({
71
+ baseUrl: z.string().describe("Active embedding API base URL."),
72
+ model: z.string().describe("Active model identifier."),
73
+ dimensions: z.number().int().describe("Active vector dimensions."),
74
+ hasApiKey: z
75
+ .boolean()
76
+ .describe("Whether a key is configured, without exposing it."),
77
+ })
78
+ .optional()
79
+ .describe("Active embedding configuration, if available."),
80
+ })
81
+ .describe("Embedding configuration and rebuild progress.");
82
+ const repository = z.object({
83
+ name: z.string(),
84
+ path: z.string(),
85
+ code_graph_id: z.string().optional(),
86
+ status: z.string(),
87
+ indexed_at: z.string().nullable().optional(),
88
+ error: z.string().optional(),
89
+ stats: z
90
+ .object({ files: z.number(), nodes: z.number(), edges: z.number() })
91
+ .nullable()
92
+ .optional(),
93
+ });
94
+ export const repositoriesSchema = z.object({
95
+ project_id: z.string().nullable(),
96
+ name: z.string(),
97
+ workspace: z.string(),
98
+ repositories: z.array(repository),
99
+ errors: z.array(z.object({ path: z.string(), error: z.string() })),
100
+ });
101
+ export const indexResultSchema = z.object({
102
+ results: z.array(
103
+ z.object({
104
+ repository: z.string(),
105
+ name: z.string().optional(),
106
+ accepted: z.boolean(),
107
+ error: z.string().optional(),
108
+ }),
109
+ ),
110
+ errors: z.array(z.object({ path: z.string(), error: z.string() })),
111
+ });
112
+ export const TencentMemory = Rpc.define({
113
+ id: pluginID,
114
+ methods: {
115
+ rulesList: {
116
+ input: z
117
+ .strictObject({ scope: ruleScope })
118
+ .describe("Select the global or current project rule inventory."),
119
+ output: ruleList,
120
+ errors: rulesErrors,
121
+ },
122
+ rulesChange: {
123
+ input: ruleChange,
124
+ output: ruleList,
125
+ errors: rulesErrors,
126
+ },
127
+ rulesHistory: {
128
+ input: z
129
+ .strictObject({
130
+ sessionID: z
131
+ .string()
132
+ .min(1)
133
+ .max(128)
134
+ .describe("Session whose injected rules to inspect."),
135
+ })
136
+ .describe("Select a session's rule-load history."),
137
+ output: rulesHistory,
138
+ errors: rulesErrors,
139
+ },
140
+ status: {
141
+ input: empty,
142
+ output: z.object({
143
+ ready: z.boolean(),
144
+ dataDir: z.string(),
145
+ tools: z.number().int(),
146
+ error: z.string().optional(),
147
+ embedding: z
148
+ .object({
149
+ baseUrl: z.string(),
150
+ model: z.string(),
151
+ dimensions: z.number().int(),
152
+ })
153
+ .optional(),
154
+ }),
155
+ },
156
+ panel: { input: empty, output: z.object({ url: z.url() }) },
157
+ readBmadArtifact: {
158
+ input: z
159
+ .strictObject({ path: bmadArtifactPath })
160
+ .describe("Identifies the BMAD artifact to open in OpenCode."),
161
+ output: bmadArtifact,
162
+ },
163
+ embeddingStatus: { input: empty, output: embeddingState },
164
+ probeEmbedding: {
165
+ input: embeddingInput,
166
+ output: z
167
+ .object({
168
+ dimensions: z
169
+ .number()
170
+ .int()
171
+ .describe("Dimensions returned by the candidate model."),
172
+ })
173
+ .describe("Live connection check result."),
174
+ },
175
+ applyEmbedding: {
176
+ input: embeddingInput,
177
+ output: z
178
+ .object({
179
+ started: z
180
+ .boolean()
181
+ .describe("Whether an offline rebuild was started."),
182
+ })
183
+ .describe("Rebuild acceptance."),
184
+ },
185
+ repositories: {
186
+ input: empty,
187
+ output: repositoriesSchema,
188
+ },
189
+ index: {
190
+ input: z.object({ repository: z.string().optional() }),
191
+ output: indexResultSchema,
192
+ },
193
+ },
194
+ events: {},
195
+ });
@@ -0,0 +1,44 @@
1
+ /** Keep imported provenance and metadata outside the editable rule body. */
2
+ export function ruleDocument(raw: string, sourcePath: string) {
3
+ const marker = "<!-- ELLMSHA_V2_SOURCE_START -->";
4
+ const endMarker = "<!-- ELLMSHA_V2_SOURCE_END -->";
5
+ let metadataEnd = 0,
6
+ metadataCount = 0;
7
+ for (;;) {
8
+ const metadata = raw
9
+ .slice(metadataEnd)
10
+ .match(
11
+ /^\s*-----META-START-----\r?\n[\s\S]*?\r?\n-----META-END-----(?:\r?\n|$)/,
12
+ );
13
+ if (!metadata) break;
14
+ metadataEnd += metadata[0].length;
15
+ metadataCount++;
16
+ }
17
+ let start = raw.includes(marker)
18
+ ? raw.indexOf(marker) + marker.length
19
+ : metadataEnd;
20
+ const end = raw.includes(endMarker) ? raw.lastIndexOf(endMarker) : raw.length;
21
+ for (;;) {
22
+ const metadata = raw
23
+ .slice(start, end)
24
+ .match(
25
+ /^\s*(?:-----META-START-----\r?\n[\s\S]*?\r?\n-----META-END-----|---\r?\n[\s\S]*?\r?\n---)(?:\r?\n|$)/,
26
+ );
27
+ if (!metadata) break;
28
+ start += metadata[0].length;
29
+ }
30
+ const inner = raw.slice(start, end).trim();
31
+ const heading = inner.match(/^# ([^\r\n]+)(?:\r?\n|$)/);
32
+ return {
33
+ // Tencent regenerates its leading META block, retaining the original creation time.
34
+ prefix: raw.slice(metadataEnd, start),
35
+ suffix: raw.slice(end),
36
+ hasNestedMetadata: metadataCount > 1,
37
+ title:
38
+ heading?.[1] ??
39
+ raw.match(/^summary: (.+)$/m)?.[1] ??
40
+ sourcePath.split("/").at(-1)?.replace(/\.md$/, "") ??
41
+ "Standing rule",
42
+ body: heading ? inner.slice(heading[0].length).trim() : inner,
43
+ };
44
+ }
@@ -0,0 +1,77 @@
1
+ import { z } from "zod";
2
+
3
+ export const ruleScope = z.enum(["global", "project"]).describe("Rule scope.");
4
+ export const ruleFields = z
5
+ .strictObject({
6
+ title: z
7
+ .string()
8
+ .trim()
9
+ .min(1)
10
+ .max(160)
11
+ .regex(/^[^\r\n]+$/)
12
+ .describe("Single-line rule title."),
13
+ body: z
14
+ .string()
15
+ .trim()
16
+ .min(1)
17
+ .max(16384)
18
+ .describe("Editable Markdown instructions, without storage metadata."),
19
+ })
20
+ .describe("Editable standing rule.");
21
+ export const ruleIdentity = z
22
+ .strictObject({
23
+ id: z.string().min(1).describe("Canonical TencentDB source path."),
24
+ revision: z
25
+ .string()
26
+ .regex(/^[a-f0-9]{64}$/)
27
+ .describe("SHA-256 of the complete source read by the editor."),
28
+ })
29
+ .describe("Optimistic concurrency identity for a standing rule.");
30
+ export const ruleView = z
31
+ .strictObject({
32
+ ...ruleIdentity.shape,
33
+ title: z.string().describe("Rule title extracted from its source."),
34
+ body: z.string().describe("Editable Markdown body."),
35
+ source: z.string().describe("Canonical TencentDB source path."),
36
+ })
37
+ .describe("Standing rule as displayed in the editor.");
38
+ export const ruleList = z
39
+ .strictObject({
40
+ project: z
41
+ .string()
42
+ .nullable()
43
+ .describe("Canonical project directory, or null for global rules."),
44
+ rules: z.array(ruleView).describe("Complete rules in the selected scope."),
45
+ })
46
+ .describe("Current TencentDB rules for one scope.");
47
+ export const ruleChange = z
48
+ .discriminatedUnion("action", [
49
+ ruleFields.extend({
50
+ action: z.literal("add").describe("Create a rule."),
51
+ scope: ruleScope,
52
+ }),
53
+ ruleFields.extend({
54
+ ...ruleIdentity.shape,
55
+ action: z.literal("edit").describe("Replace a rule's editable body."),
56
+ scope: ruleScope,
57
+ }),
58
+ ruleIdentity.extend({
59
+ action: z.literal("delete").describe("Delete a rule."),
60
+ scope: ruleScope,
61
+ }),
62
+ ])
63
+ .describe("A revision-checked change to a TencentDB standing rule.");
64
+ export const rulesHistory = z
65
+ .array(
66
+ z
67
+ .strictObject({
68
+ time: z.number().describe("Snapshot timestamp in Unix milliseconds."),
69
+ project: z.string().describe("Canonical project directory."),
70
+ kind: z
71
+ .enum(["context", "compaction", "title", "generate"])
72
+ .describe("OpenCode request hook that supplied these rules."),
73
+ text: z.string().describe("Exact TencentDB standing-rules section."),
74
+ })
75
+ .describe("Rules supplied to an outgoing model request."),
76
+ )
77
+ .describe("Up to ten changes to the rules supplied in this session.");
package/src/rules.ts ADDED
@@ -0,0 +1,237 @@
1
+ import { createHash } from "node:crypto";
2
+ import { z } from "zod";
3
+ import type { Project } from "./binding.js";
4
+ import { memoryScope, TencentMemoryClient } from "../dist/integration.mjs";
5
+ import { ruleDocument } from "./rule-document.js";
6
+
7
+ const digest = (text: string) =>
8
+ createHash("sha256").update(text).digest("hex");
9
+ const record = z.object({
10
+ id: z.string().min(1),
11
+ source_path: z.string().min(1),
12
+ guidance_scope: z.enum(["global", "project"]),
13
+ guidance_status: z.literal("active"),
14
+ source_status: z.literal("active"),
15
+ type: z.enum(["instruction", "persona"]),
16
+ });
17
+ const page = z.object({
18
+ guidance_inventory: z.literal(true),
19
+ degraded: z.literal(false),
20
+ guidance_locality: z.literal("local"),
21
+ guidance_revision: z.string().min(1),
22
+ guidance_write_version: z.literal(1),
23
+ items: z.array(record),
24
+ returned: z.number().int().nonnegative(),
25
+ total_candidates: z.number().int().min(0).max(512),
26
+ complete: z.boolean(),
27
+ next_offset: z.number().int().optional().nullable(),
28
+ });
29
+ export type Rule = {
30
+ scope: "global" | "project";
31
+ path: string;
32
+ content: string;
33
+ revision: string;
34
+ source_id: string;
35
+ type: string;
36
+ };
37
+ export type Snapshot = {
38
+ rules: Rule[];
39
+ revision: string;
40
+ project_scope: string | null;
41
+ };
42
+ const mutation = z.discriminatedUnion("action", [
43
+ z.object({
44
+ action: z.literal("add"),
45
+ scope: z.enum(["global", "project"]),
46
+ title: z.string().trim().min(1).max(160),
47
+ content: z.string().trim().min(1).max(16384),
48
+ }),
49
+ z.object({
50
+ action: z.literal("edit"),
51
+ scope: z.enum(["global", "project"]),
52
+ title: z.string().trim().min(1).max(160),
53
+ content: z.string().trim().min(1).max(16384),
54
+ path: z.string().min(1),
55
+ revision: z.string().regex(/^[a-f0-9]{64}$/),
56
+ }),
57
+ z.object({
58
+ action: z.literal("delete"),
59
+ scope: z.enum(["global", "project"]),
60
+ path: z.string().min(1),
61
+ revision: z.string().regex(/^[a-f0-9]{64}$/),
62
+ }),
63
+ ]);
64
+
65
+ /** Reuse Tencent's complete inventory and transactional revision checks, never semantic top-k for rules. */
66
+ export async function readRules(
67
+ client: TencentMemoryClient,
68
+ project: Project,
69
+ ): Promise<Snapshot> {
70
+ const scope = project.project_id ? memoryScope(project.workspace) : null;
71
+ async function inventory() {
72
+ const rows: z.infer<typeof record>[] = [];
73
+ const ids = new Set<string>();
74
+ let offset = 0,
75
+ revision = "",
76
+ total = -1;
77
+ for (;;) {
78
+ const data = page.parse(
79
+ await client.call("atomic/search", {
80
+ query: "project guidance",
81
+ intent: "rules",
82
+ guidance_inventory: true,
83
+ include_global: true,
84
+ scope_mode: "current_project",
85
+ project_scopes: scope ? [scope] : [],
86
+ project_aliases: [],
87
+ limit: 100,
88
+ offset,
89
+ }),
90
+ );
91
+ if (
92
+ (revision && revision !== data.guidance_revision) ||
93
+ (total !== -1 && total !== data.total_candidates) ||
94
+ data.returned !== data.items.length ||
95
+ data.items.length > 100
96
+ )
97
+ throw new Error("Rule inventory changed or is incomplete. Retry.");
98
+ revision = data.guidance_revision;
99
+ total = data.total_candidates;
100
+ for (const row of data.items) {
101
+ if (ids.has(row.id)) throw new Error("Duplicate rule inventory entry.");
102
+ ids.add(row.id);
103
+ rows.push(row);
104
+ }
105
+ if (data.complete) {
106
+ if (rows.length !== total || data.next_offset != null)
107
+ throw new Error("Incomplete rules inventory.");
108
+ return { rows, revision };
109
+ }
110
+ if (
111
+ !data.items.length ||
112
+ data.next_offset !== offset + data.items.length ||
113
+ data.next_offset >= total
114
+ )
115
+ throw new Error("Invalid rules cursor.");
116
+ offset = data.next_offset;
117
+ }
118
+ }
119
+ const before = await inventory();
120
+ const rules: Rule[] = [];
121
+ const paths = new Set<string>();
122
+ for (const row of before.rows) {
123
+ const global = /^(knowledge\/global\/|global\/|v2\/wiki\/|wiki\/)/.test(
124
+ row.source_path,
125
+ );
126
+ if (
127
+ paths.has(row.source_path) ||
128
+ (row.guidance_scope === "global"
129
+ ? !global
130
+ : !scope || !row.source_path.startsWith(`knowledge/${scope}/`))
131
+ )
132
+ throw new Error("Rule source is outside the current scope.");
133
+ paths.add(row.source_path);
134
+ const source = z
135
+ .object({
136
+ path: z.literal(row.source_path),
137
+ content: z.string().min(1),
138
+ truncated: z.literal(false).optional(),
139
+ })
140
+ .parse(await client.call("scenario/read", { path: row.source_path }));
141
+ rules.push({
142
+ scope: row.guidance_scope,
143
+ path: source.path,
144
+ content: source.content,
145
+ revision: digest(source.content),
146
+ source_id: row.id,
147
+ type: row.type,
148
+ });
149
+ if (Buffer.byteLength(JSON.stringify(rules)) > 256 * 1024)
150
+ throw new Error(
151
+ "Complete standing rules exceed 256 KiB. Shorten the rules before retrying.",
152
+ );
153
+ }
154
+ const after = await inventory();
155
+ if (JSON.stringify(before) !== JSON.stringify(after))
156
+ throw new Error("Rules changed during preflight. Retry.");
157
+ return {
158
+ rules: rules.sort(
159
+ (a, b) => a.scope.localeCompare(b.scope) || a.path.localeCompare(b.path),
160
+ ),
161
+ revision: before.revision,
162
+ project_scope: scope,
163
+ };
164
+ }
165
+
166
+ export async function changeRule(
167
+ client: TencentMemoryClient,
168
+ project: Project,
169
+ input: unknown,
170
+ ) {
171
+ const change = mutation.parse(input);
172
+ const snapshot = await readRules(client, project);
173
+ if (change.scope === "project" && !snapshot.project_scope)
174
+ throw new Error("Temporary chats have no project rules.");
175
+ let request: Record<string, unknown>;
176
+ if (change.action === "add") {
177
+ const subject =
178
+ change.title
179
+ .toLowerCase()
180
+ .replace(/[^a-z0-9]+/g, "-")
181
+ .replace(/^-|-$/g, "")
182
+ .slice(0, 100) || `rule-${digest(change.title).slice(0, 12)}`;
183
+ request = {
184
+ action: "write",
185
+ path: `knowledge/${change.scope === "global" ? "global" : snapshot.project_scope}/${subject}.md`,
186
+ expected_sha256: null,
187
+ content: `# ${change.title}\n\n${change.content}`,
188
+ summary: change.title,
189
+ index_type: "instruction",
190
+ };
191
+ } else {
192
+ const current = snapshot.rules.find(
193
+ (r) =>
194
+ r.scope === change.scope &&
195
+ r.path === change.path &&
196
+ r.revision === change.revision,
197
+ );
198
+ if (!current)
199
+ throw new Error(
200
+ "Rule changed or is outside this chat. Read tdai_rules_read and retry.",
201
+ );
202
+ request = {
203
+ action: change.action === "delete" ? "delete" : "write",
204
+ path: current.path,
205
+ source_id: current.source_id,
206
+ expected_sha256: change.revision,
207
+ };
208
+ if (change.action === "edit") {
209
+ // Preserve imported provenance and metadata; edit its rule body in place.
210
+ const document = ruleDocument(current.content, current.path);
211
+ if (
212
+ !document.hasNestedMetadata &&
213
+ document.title === change.title &&
214
+ document.body === change.content
215
+ )
216
+ return { saved: true };
217
+ request.content =
218
+ document.prefix +
219
+ "\n\n" +
220
+ `# ${change.title}\n\n${change.content}\n` +
221
+ document.suffix;
222
+ request.summary = change.title;
223
+ request.index_type = current.type;
224
+ }
225
+ }
226
+ if (request.action === "write")
227
+ request.index_content = `${request.summary}\n\n${request.content}`.slice(
228
+ 0,
229
+ 7800,
230
+ );
231
+ await client.call("scenario/rule-mutate", {
232
+ ...request,
233
+ expected_inventory: snapshot.revision,
234
+ local_only: true,
235
+ });
236
+ return { saved: true };
237
+ }