opencode-rag-plugin 1.23.2 → 2.0.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 (42) hide show
  1. package/dist/api.js +3 -0
  2. package/dist/chunker/factory.d.ts +4 -0
  3. package/dist/chunker/factory.js +36 -7
  4. package/dist/cli/commands/init-helpers.d.ts +2 -0
  5. package/dist/cli/commands/init-helpers.js +2 -5
  6. package/dist/core/chunk-role.d.ts +22 -0
  7. package/dist/core/chunk-role.js +47 -0
  8. package/dist/core/config.d.ts +19 -3
  9. package/dist/core/config.js +24 -4
  10. package/dist/core/interfaces.d.ts +10 -0
  11. package/dist/index.d.ts +2 -10
  12. package/dist/index.js +1 -7
  13. package/dist/indexer/pipeline.js +6 -0
  14. package/dist/indexer/worker.d.ts +2 -0
  15. package/dist/indexer/worker.js +2 -0
  16. package/dist/opencode/create-read-tool.js +2 -2
  17. package/dist/opencode/tools.js +7 -7
  18. package/dist/plugin-entry.d.ts +10 -12
  19. package/dist/plugin-entry.js +22 -8
  20. package/dist/plugin.js +10 -8
  21. package/dist/retriever/context-optimizer.js +13 -1
  22. package/dist/retriever/keyword-index.d.ts +15 -0
  23. package/dist/retriever/keyword-index.js +119 -7
  24. package/dist/retriever/retriever.d.ts +7 -0
  25. package/dist/retriever/retriever.js +56 -4
  26. package/dist/tui.d.ts +85 -2
  27. package/dist/tui.js +319 -378
  28. package/dist/v2/v2-adapter.d.ts +103 -0
  29. package/dist/v2/v2-adapter.js +226 -0
  30. package/dist/vectorstore/lancedb.d.ts +1 -1
  31. package/dist/vectorstore/lancedb.js +12 -4
  32. package/dist/vectorstore/memory.js +1 -0
  33. package/dist/web/ui/assets/ScatterPlot3D-CKwyh1Ec.js +4108 -0
  34. package/dist/web/ui/assets/index-Cgv1RsGv.js +4 -0
  35. package/dist/web/ui/assets/index-DjJHIo9R.css +1 -0
  36. package/dist/web/ui/assets/vendor-Dg8wMT7C.js +1 -0
  37. package/dist/web/ui/index.html +3 -3
  38. package/package.json +16 -11
  39. package/dist/web/ui/assets/ScatterPlot3D-DQLl3sKN.js +0 -4116
  40. package/dist/web/ui/assets/index-BZh9MitV.js +0 -4
  41. package/dist/web/ui/assets/index-DKhjGsql.css +0 -1
  42. package/dist/web/ui/assets/vendor-Dy7HKFCY.js +0 -1
@@ -0,0 +1,103 @@
1
+ /**
2
+ * @fileoverview OpenCode V2 adapter for OpenCodeRAG.
3
+ *
4
+ * OpenCode V2 (server API) loads plugins as a default export with `id` and a
5
+ * `setup(ctx)` (or Effect `effect`) function, while OpenCode V1 used a
6
+ * `{ id, server }` default export whose `server` factory returned a hooks
7
+ * object. This adapter keeps the V1 `ragPlugin` factory as the single source
8
+ * of truth for RAG logic and re-registers its returned hooks on the V2
9
+ * context:
10
+ *
11
+ * | V1 hook | V2 registration |
12
+ * |------------------------------|------------------------------------------|
13
+ * | `tool` map | `ctx.tool.transform(...)` |
14
+ * | `chat.message` | `ctx.session.hook("prompt", ...)` |
15
+ * | `experimental.chat.system.transform` | `ctx.session.hook("context", ...)` |
16
+ * | `tool.execute.after` | `ctx.tool.hook("execute.after", ...)` |
17
+ * | `event` | `ctx.event.subscribe({ signal })` |
18
+ *
19
+ * The V2 prompt hook exposes the user's text as a mutable `event.prompt.text`
20
+ * instead of V1's parts-mutation contract; the adapter shims a V1-shaped
21
+ * `output.parts` view around it and writes the mutated text back.
22
+ *
23
+ * Degradations (documented, non-fatal):
24
+ * - V2 event payloads use `data` instead of V1 `properties`, so the session
25
+ * logger and assistant-text accumulation skip V2 events; hotkey 2-message
26
+ * queries and session-end extraction fall back gracefully.
27
+ * - The read-tool override keeps its V1 execute contract (args + sessionID).
28
+ */
29
+ type V2Registration = {
30
+ dispose(): Promise<void>;
31
+ };
32
+ type V2ToolEditor = {
33
+ add(tool: V2Tool): void;
34
+ };
35
+ type V2ToolDomain = {
36
+ transform(callback: (editor: V2ToolEditor) => void): Promise<V2Registration>;
37
+ hook(name: "execute.after", callback: (event: V2ToolExecuteAfterEvent) => Promise<void> | void): Promise<V2Registration>;
38
+ };
39
+ type V2SessionDomain = {
40
+ hook(name: "prompt", callback: (event: V2PromptHookEvent) => Promise<void> | void): Promise<V2Registration>;
41
+ hook(name: "context", callback: (event: V2ContextHookEvent) => Promise<void> | void): Promise<V2Registration>;
42
+ };
43
+ type V2EventDomain = {
44
+ subscribe(options: {
45
+ signal: AbortSignal;
46
+ }): AsyncIterable<unknown>;
47
+ };
48
+ /** Structural subset of the OpenCode V2 plugin context. */
49
+ export type V2Context = {
50
+ location: {
51
+ directory: string;
52
+ };
53
+ options: Record<string, unknown>;
54
+ tool: V2ToolDomain;
55
+ session: V2SessionDomain;
56
+ event: V2EventDomain;
57
+ };
58
+ /** A registered V2 tool definition (structural subset of Tool.Info). */
59
+ type V2Tool = {
60
+ name: string;
61
+ description: string;
62
+ input: Record<string, unknown>;
63
+ execute(input: unknown, context: {
64
+ sessionID?: string;
65
+ }): Promise<{
66
+ content?: string;
67
+ output?: unknown;
68
+ metadata?: Record<string, unknown>;
69
+ }>;
70
+ };
71
+ /** V2 `execute.after` hook event (completed branch). */
72
+ type V2ToolExecuteAfterEvent = {
73
+ tool: string;
74
+ sessionID: string;
75
+ id: unknown;
76
+ status: "completed" | "error";
77
+ result?: {
78
+ output?: unknown;
79
+ content?: string | readonly unknown[];
80
+ };
81
+ };
82
+ /** V2 `prompt` hook event. */
83
+ type V2PromptHookEvent = {
84
+ sessionID: string;
85
+ prompt: {
86
+ text: string;
87
+ };
88
+ };
89
+ /** V2 `context` hook event. */
90
+ type V2ContextHookEvent = {
91
+ sessionID: string;
92
+ system: Array<{
93
+ type: "text";
94
+ text: string;
95
+ }>;
96
+ };
97
+ /**
98
+ * Run the V1 `ragPlugin` factory for the V2 context's location and register
99
+ * all returned hooks as V2 transforms/hooks. Returns a cleanup function that
100
+ * disposes every registration and aborts the event subscription.
101
+ */
102
+ export declare function registerRagPluginV2(ctx: V2Context): Promise<() => Promise<void>>;
103
+ export {};
@@ -0,0 +1,226 @@
1
+ /**
2
+ * @fileoverview OpenCode V2 adapter for OpenCodeRAG.
3
+ *
4
+ * OpenCode V2 (server API) loads plugins as a default export with `id` and a
5
+ * `setup(ctx)` (or Effect `effect`) function, while OpenCode V1 used a
6
+ * `{ id, server }` default export whose `server` factory returned a hooks
7
+ * object. This adapter keeps the V1 `ragPlugin` factory as the single source
8
+ * of truth for RAG logic and re-registers its returned hooks on the V2
9
+ * context:
10
+ *
11
+ * | V1 hook | V2 registration |
12
+ * |------------------------------|------------------------------------------|
13
+ * | `tool` map | `ctx.tool.transform(...)` |
14
+ * | `chat.message` | `ctx.session.hook("prompt", ...)` |
15
+ * | `experimental.chat.system.transform` | `ctx.session.hook("context", ...)` |
16
+ * | `tool.execute.after` | `ctx.tool.hook("execute.after", ...)` |
17
+ * | `event` | `ctx.event.subscribe({ signal })` |
18
+ *
19
+ * The V2 prompt hook exposes the user's text as a mutable `event.prompt.text`
20
+ * instead of V1's parts-mutation contract; the adapter shims a V1-shaped
21
+ * `output.parts` view around it and writes the mutated text back.
22
+ *
23
+ * Degradations (documented, non-fatal):
24
+ * - V2 event payloads use `data` instead of V1 `properties`, so the session
25
+ * logger and assistant-text accumulation skip V2 events; hotkey 2-message
26
+ * queries and session-end extraction fall back gracefully.
27
+ * - The read-tool override keeps its V1 execute contract (args + sessionID).
28
+ */
29
+ import { ragPlugin } from "../plugin.js";
30
+ // ────────────────────────────────────────────────────────────────────────────
31
+ // V1 tool (`@opencode-ai/plugin/tool`, zod-backed) → V2 Tool.Info converter
32
+ // ────────────────────────────────────────────────────────────────────────────
33
+ /**
34
+ * Convert a single zod-shaped argument schema into a minimal JSON schema
35
+ * object. Duck-types on zod v3/v4 class names (`constructor.name`) — avoids
36
+ * depending on zod internals (`_def.typeName`) which changed between majors.
37
+ */
38
+ function zodArgToJsonSchema(schema) {
39
+ const candidate = schema;
40
+ // Unwrap optional wrappers (zod v3.23+/v4 expose isOptional()).
41
+ if (typeof candidate?.isOptional === "function" && candidate.isOptional()) {
42
+ const inner = typeof candidate.unwrap === "function" ? candidate.unwrap() : undefined;
43
+ return zodArgToJsonSchema(inner ?? schema);
44
+ }
45
+ switch (candidate?.constructor?.name) {
46
+ case "ZodString":
47
+ return { type: "string" };
48
+ case "ZodNumber":
49
+ return { type: "number" };
50
+ case "ZodBoolean":
51
+ return { type: "boolean" };
52
+ case "ZodArray": {
53
+ const element = candidate.element;
54
+ return { type: "array", items: element ? zodArgToJsonSchema(element) : {} };
55
+ }
56
+ case "ZodObject":
57
+ return zodShapeToJsonSchema(candidate.shape ?? {});
58
+ default:
59
+ // Unknown wrapper — expose as unconstrained value rather than failing.
60
+ return {};
61
+ }
62
+ }
63
+ /** Convert a V1 `args` record (zod raw shape) to a JSON schema object. */
64
+ function zodShapeToJsonSchema(shape) {
65
+ const properties = {};
66
+ const required = [];
67
+ for (const [key, schema] of Object.entries(shape)) {
68
+ properties[key] = zodArgToJsonSchema(schema);
69
+ const candidate = schema;
70
+ if (typeof candidate?.isOptional !== "function" || !candidate.isOptional()) {
71
+ required.push(key);
72
+ }
73
+ }
74
+ return { type: "object", properties, required: required.length > 0 ? required : undefined };
75
+ }
76
+ /**
77
+ * Convert a V1 tool definition (from `@opencode-ai/plugin/tool`) into a V2
78
+ * tool definition. V1 executors return `{ title, output, metadata }`; V2
79
+ * results carry `content`/`output`/`metadata`.
80
+ */
81
+ function v1ToolToV2(name, def) {
82
+ const v1Result = (result) => {
83
+ const r = result;
84
+ const metadata = { ...(r?.metadata ?? {}) };
85
+ if (typeof r?.title === "string" && r.title.length > 0)
86
+ metadata.title = r.title;
87
+ return {
88
+ content: typeof r?.output === "string" ? r.output : "",
89
+ metadata,
90
+ };
91
+ };
92
+ return {
93
+ name,
94
+ description: def.description ?? "",
95
+ input: zodShapeToJsonSchema(def.args ?? {}),
96
+ async execute(input, context) {
97
+ const fn = def.execute;
98
+ if (typeof fn !== "function") {
99
+ return { content: "Tool executor unavailable", metadata: { tool: name } };
100
+ }
101
+ return v1Result(await fn(input, context));
102
+ },
103
+ };
104
+ }
105
+ // ────────────────────────────────────────────────────────────────────────────
106
+ // Registration entry point
107
+ // ────────────────────────────────────────────────────────────────────────────
108
+ /**
109
+ * Run the V1 `ragPlugin` factory for the V2 context's location and register
110
+ * all returned hooks as V2 transforms/hooks. Returns a cleanup function that
111
+ * disposes every registration and aborts the event subscription.
112
+ */
113
+ export async function registerRagPluginV2(ctx) {
114
+ // The V1 factory only consumes `input.directory`; project/client/$ are unused.
115
+ const hooks = (await ragPlugin({ directory: ctx.location.directory }, ctx.options));
116
+ const registrations = [];
117
+ // ── Tools ────────────────────────────────────────────────────────────────
118
+ const toolDefs = (hooks.tool ?? {});
119
+ const toolEntries = Object.entries(toolDefs);
120
+ if (toolEntries.length > 0) {
121
+ const registration = await ctx.tool.transform((editor) => {
122
+ for (const [name, def] of toolEntries) {
123
+ editor.add(v1ToolToV2(name, def));
124
+ }
125
+ });
126
+ registrations.push(registration);
127
+ }
128
+ // ── prompt hook (V1 `chat.message`) ─────────────────────────────────────
129
+ // Shims a V1-shaped output (parts array) around the mutable prompt text,
130
+ // runs the V1 handler, and writes the (possibly replaced) text back.
131
+ const chatMessageHook = hooks["chat.message"];
132
+ if (chatMessageHook) {
133
+ const registration = await ctx.session.hook("prompt", async (event) => {
134
+ const text = event.prompt.text;
135
+ if (!text || text.length === 0)
136
+ return;
137
+ const parts = [{ type: "text", text }];
138
+ const output = { message: { parts }, parts };
139
+ try {
140
+ await chatMessageHook({ sessionID: event.sessionID }, output);
141
+ }
142
+ catch {
143
+ // Non-critical — must never throw
144
+ }
145
+ const first = output.parts?.[0];
146
+ if (typeof first?.text === "string")
147
+ event.prompt.text = first.text;
148
+ });
149
+ registrations.push(registration);
150
+ }
151
+ // ── context hook (V1 `experimental.chat.system.transform`) ──────────────
152
+ // V1 unshifted guidance lines onto `output.system`; replicate the final
153
+ // ordering by unshifting in reverse iteration order.
154
+ const systemTransformHook = hooks["experimental.chat.system.transform"];
155
+ if (systemTransformHook) {
156
+ const registration = await ctx.session.hook("context", async (event) => {
157
+ const output = { system: [] };
158
+ try {
159
+ await systemTransformHook({ sessionID: event.sessionID }, output);
160
+ }
161
+ catch {
162
+ // Non-critical — must never throw
163
+ }
164
+ const lines = output.system ?? [];
165
+ for (let i = lines.length - 1; i >= 0; i--) {
166
+ event.system.unshift({ type: "text", text: lines[i] });
167
+ }
168
+ });
169
+ registrations.push(registration);
170
+ }
171
+ // ── tool.execute.after ───────────────────────────────────────────────────
172
+ const toolAfterHook = hooks["tool.execute.after"];
173
+ if (toolAfterHook) {
174
+ const registration = await ctx.tool.hook("execute.after", async (event) => {
175
+ try {
176
+ if (event.status !== "completed")
177
+ return;
178
+ const result = event.result;
179
+ const outputText = typeof result?.content === "string"
180
+ ? result.content
181
+ : result?.output !== undefined
182
+ ? JSON.stringify(result.output)
183
+ : "";
184
+ await toolAfterHook({ sessionID: event.sessionID, tool: event.tool, callID: event.id }, { output: outputText });
185
+ }
186
+ catch {
187
+ // Non-critical — must never throw
188
+ }
189
+ });
190
+ registrations.push(registration);
191
+ }
192
+ // ── event subscription (V1 `event`) ─────────────────────────────────────
193
+ // V2 event payloads differ from V1 (data vs properties) — the V1 handler
194
+ // reads `event.type`/`properties` defensively and skips foreign shapes.
195
+ const eventHook = hooks.event;
196
+ if (eventHook) {
197
+ const controller = new AbortController();
198
+ void (async () => {
199
+ try {
200
+ for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
201
+ try {
202
+ await eventHook({ event });
203
+ }
204
+ catch {
205
+ // Non-critical — must never throw
206
+ }
207
+ }
208
+ }
209
+ catch {
210
+ // Aborted or stream ended
211
+ }
212
+ })();
213
+ registrations.push({ dispose: async () => controller.abort() });
214
+ }
215
+ return async () => {
216
+ for (const registration of registrations.reverse()) {
217
+ try {
218
+ await registration.dispose();
219
+ }
220
+ catch {
221
+ // Best-effort unload
222
+ }
223
+ }
224
+ };
225
+ }
226
+ //# sourceMappingURL=v2-adapter.js.map
@@ -180,7 +180,7 @@ export declare class LanceDbStore implements VectorStore {
180
180
  */
181
181
  private assertEmbeddingDimensions;
182
182
  private hasColumn;
183
- /** Add kind/quirkType/tags columns if missing from an existing table. */
183
+ /** Add kind/role/quirkType/tags columns if missing from an existing table. */
184
184
  private migrateNewColumns;
185
185
  /**
186
186
  * Ensure that kind/quirkType/tags columns are nullable so that queries
@@ -8,7 +8,7 @@ import path from "node:path";
8
8
  import { normalizeFilePath, manifestPathFor } from "../core/manifest.js";
9
9
  import { normalizeFileExtensions, matchesFileExtension } from "../core/filters.js";
10
10
  const TABLE_NAME = "chunks";
11
- const QUERY_COLUMNS = ["id", "content", "description", "filePath", "startLine", "endLine", "language", "kind", "quirkType", "tags"];
11
+ const QUERY_COLUMNS = ["id", "content", "description", "filePath", "startLine", "endLine", "language", "kind", "role", "quirkType", "tags"];
12
12
  /**
13
13
  * Upper bound for the number of failed index-creation attempts per process.
14
14
  * Beyond this the repair gives up for the process lifetime instead of
@@ -453,6 +453,7 @@ export class LanceDbStore {
453
453
  endLine: 0,
454
454
  language: "",
455
455
  kind: "",
456
+ role: "",
456
457
  quirkType: "",
457
458
  tags: "",
458
459
  };
@@ -543,10 +544,10 @@ export class LanceDbStore {
543
544
  return false;
544
545
  }
545
546
  }
546
- /** Add kind/quirkType/tags columns if missing from an existing table. */
547
+ /** Add kind/role/quirkType/tags columns if missing from an existing table. */
547
548
  async migrateNewColumns() {
548
549
  const missing = [];
549
- for (const col of ["kind", "quirkType", "tags"]) {
550
+ for (const col of ["kind", "role", "quirkType", "tags"]) {
550
551
  if (!(await this.hasColumn(col))) {
551
552
  missing.push({ name: col, valueSql: "''" });
552
553
  }
@@ -562,7 +563,7 @@ export class LanceDbStore {
562
563
  return;
563
564
  }
564
565
  }
565
- await this.ensureColumnsNullable(["kind", "quirkType", "tags"]);
566
+ await this.ensureColumnsNullable(["kind", "role", "quirkType", "tags"]);
566
567
  }
567
568
  /**
568
569
  * Ensure that kind/quirkType/tags columns are nullable so that queries
@@ -656,6 +657,7 @@ export class LanceDbStore {
656
657
  endLine: c.metadata.endLine,
657
658
  language: c.metadata.language,
658
659
  kind: c.metadata.kind ?? "",
660
+ role: c.metadata.role ?? "",
659
661
  quirkType: c.metadata.quirkType ?? "",
660
662
  tags: c.metadata.tags ? JSON.stringify(c.metadata.tags) : "",
661
663
  };
@@ -801,6 +803,7 @@ export class LanceDbStore {
801
803
  endLine: row.endLine,
802
804
  language: row.language,
803
805
  kind: row.kind || undefined,
806
+ role: row.role === "source" || row.role === "test" || row.role === "doc" ? row.role : undefined,
804
807
  quirkType: row.quirkType || undefined,
805
808
  tags,
806
809
  },
@@ -869,6 +872,7 @@ export class LanceDbStore {
869
872
  endLine: row.endLine,
870
873
  language: row.language,
871
874
  kind: row.kind || undefined,
875
+ role: row.role === "source" || row.role === "test" || row.role === "doc" ? row.role : undefined,
872
876
  quirkType: row.quirkType || undefined,
873
877
  tags,
874
878
  },
@@ -900,6 +904,7 @@ export class LanceDbStore {
900
904
  content: row.content,
901
905
  description: row.description ?? "",
902
906
  kind: row.kind ?? "",
907
+ role: row.role ?? "",
903
908
  quirkType: row.quirkType ?? "",
904
909
  tags: row.tags ?? "",
905
910
  }));
@@ -944,6 +949,7 @@ export class LanceDbStore {
944
949
  content: row.content,
945
950
  description: row.description ?? "",
946
951
  kind: row.kind ?? "",
952
+ role: row.role ?? "",
947
953
  quirkType: row.quirkType ?? "",
948
954
  tags: row.tags ?? "",
949
955
  })),
@@ -972,6 +978,7 @@ export class LanceDbStore {
972
978
  content: row.content,
973
979
  description: row.description ?? "",
974
980
  kind: row.kind ?? "",
981
+ role: row.role ?? "",
975
982
  quirkType: row.quirkType ?? "",
976
983
  tags: row.tags ?? "",
977
984
  };
@@ -998,6 +1005,7 @@ export class LanceDbStore {
998
1005
  content: row.content,
999
1006
  description: row.description ?? "",
1000
1007
  kind: row.kind ?? "",
1008
+ role: row.role ?? "",
1001
1009
  quirkType: row.quirkType ?? "",
1002
1010
  tags: row.tags ?? "",
1003
1011
  }));
@@ -70,6 +70,7 @@ export class InMemoryVectorStore {
70
70
  content: c.content,
71
71
  description: c.description ?? "",
72
72
  kind: c.metadata.kind ?? "",
73
+ role: c.metadata.role ?? "",
73
74
  quirkType: c.metadata.quirkType ?? "",
74
75
  tags: c.metadata.tags ? JSON.stringify(c.metadata.tags) : "",
75
76
  }));