opencode-rag-plugin 1.23.3 → 2.0.1

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.
@@ -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