@distlang/opencode-plugin 0.2.5 → 0.4.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/README.md CHANGED
@@ -11,18 +11,21 @@ Add the plugin to your global OpenCode config:
11
11
  ```json
12
12
  {
13
13
  "$schema": "https://opencode.ai/config.json",
14
- "plugin": ["@distlang/opencode-plugin"]
14
+ "plugins": ["@distlang/opencode-plugin@latest"]
15
15
  }
16
16
  ```
17
17
 
18
- OpenCode installs npm plugins automatically with Bun at startup.
18
+ This version requires OpenCode 2.4.5 or later. OpenCode 1 users should remain
19
+ on an earlier plugin release. OpenCode installs npm plugins automatically.
19
20
 
20
21
  ## Local use
21
22
 
22
- The plugin uses `distlang` only for two things:
23
+ The plugin uses `distlang` for authentication, API requests, and the local MCP
24
+ server:
23
25
 
24
26
  - `distlang helpers auth status --json`
25
27
  - `distlang helpers request ...`
28
+ - `distlang mcp`
26
29
 
27
30
  If `distlang` is not already available, the plugin can install a managed copy automatically.
28
31
 
@@ -65,38 +68,13 @@ If you are not logged in, the plugin logs one warning and continues without uplo
65
68
 
66
69
  ## Distlang commands
67
70
 
68
- OpenCode commands are configured separately from plugins, so add command files to make the Distlang controls available in the TUI:
69
-
70
- `~/.config/opencode/commands/distlang-start.md`
71
-
72
- ```md
73
- ---
74
- description: Sign in and enable Distlang Agent Debugger uploads
75
- ---
76
- ```
77
-
78
- `~/.config/opencode/commands/distlang-stop.md`
79
-
80
- ```md
81
- ---
82
- description: Disable Distlang Agent Debugger uploads and sign out
83
- ---
84
- ```
85
-
86
- `~/.config/opencode/commands/distlang-status.md`
87
-
88
- ```md
89
- ---
90
- description: Show Distlang Agent Debugger upload status
91
- ---
92
- ```
93
-
94
- The plugin watches for these commands:
71
+ The plugin registers these commands:
95
72
 
96
73
  - `/distlang-start`
97
74
  - `/distlang-stop`
98
75
  - `/distlang-status`
99
76
  - `/distlang-view [session-id]`
77
+ - `/distlang-view-local`
100
78
 
101
79
  The legacy compact command also remains supported:
102
80
 
@@ -106,7 +84,12 @@ The legacy compact command also remains supported:
106
84
  - `/distlang login`
107
85
  - `/distlang logout`
108
86
 
109
- Command results are written to the OpenCode app log, and also to the debug log file when enabled.
87
+ If upgrading from the V1 plugin, remove or move the old `distlang*.md` command
88
+ files from `~/.config/opencode/commands/` (and any project command directories).
89
+ Those files override the plugin's command executors in OpenCode 2.
90
+
91
+ Command results are written to the server log, and to the debug log file when
92
+ enabled. This version does not show TUI toast notifications.
110
93
 
111
94
  If `/distlang-start` finds that Distlang auth is missing, the plugin starts `distlang helpers login`, which opens the browser login flow.
112
95
 
@@ -123,10 +106,21 @@ Commands:
123
106
 
124
107
  - `/distlang-status`: show whether uploads are enabled, whether auth is available, and whether recent Agent Debugger sessions are visible
125
108
  - `/distlang-start`: sign in if needed and enable Agent Debugger uploads
126
- - `/distlang-stop`: disable Agent Debugger uploads and sign out of Distlang
109
+ - `/distlang-stop`: disable Agent Debugger uploads without signing out
127
110
  - `/distlang-view [session-id]`: open the latest uploaded OpenCode Agent Debugger session, the provided session id, or the Agent Debugger overview when no session is available yet
111
+ - `/distlang-view-local`: start/open the local Agent Debugger without requiring Distlang login
112
+
113
+ Legacy aliases remain available: `/distlang status`, `/distlang start`, `/distlang stop`, `/distlang login`, `/distlang logout`, and `/distlang view-local`.
114
+
115
+ Capture is off by default for new installations; existing explicit settings are
116
+ preserved. `/distlang-start` checks login before enabling capture and registers
117
+ the local, read-only MCP server when the resolved CLI supports `distlang mcp`.
118
+ An older CLI continues to work for capture but cannot provide MCP; update the
119
+ CLI or set `DISTLANG_BIN` to a compatible binary. A user-configured MCP server
120
+ named `distlang` is never overwritten. `/distlang-stop` does not disconnect an
121
+ already connected MCP server; use OpenCode's `/mcps` controls for that.
128
122
 
129
- Legacy aliases remain available: `/distlang status`, `/distlang start`, `/distlang stop`, `/distlang login`, and `/distlang logout`.
123
+ If Distlang cloud login is unavailable, the plugin attempts to save session snapshots to the local Agent Debugger instead of dropping them. The local fallback expects `distlang-agent-debugger` to be installed and available on `PATH`, or configured with `DISTLANG_AGENT_DEBUGGER_BIN`.
130
124
 
131
125
  ## Debugging
132
126
 
@@ -140,6 +134,8 @@ Useful overrides:
140
134
  DISTLANG_BIN=/path/to/distlang opencode
141
135
  DISTLANG_STORE_BASE_URL=https://api-staging.distlang.com opencode
142
136
  DISTLANG_AUTH_BASE_URL=https://auth-staging.distlang.com opencode
137
+ DISTLANG_AGENT_DEBUGGER_BASE_URL=http://127.0.0.1:4817 opencode
138
+ DISTLANG_AGENT_DEBUGGER_BIN=/path/to/distlang-agent-debugger opencode
143
139
  DISTLANG_OPENCODE_NO_INSTALL=1 opencode
144
140
  DISTLANG_OPENCODE_INSTALL_DIR=/tmp/distlang-plugin-bin opencode
145
141
  DISTLANG_OPENCODE_STATE_FILE=/tmp/distlang-plugin-state.json opencode
@@ -180,10 +176,10 @@ The repository includes a live local integration harness. It is not included in
180
176
  The harness uses your existing local OpenCode auth to run the requested model. It does not read, copy, or print OpenCode credential files. It writes only a temporary OpenCode config that loads this local plugin source.
181
177
 
182
178
  ```bash
183
- npm run test:opencode -- --model openai/gpt-5.5
179
+ npm run test:opencode -- --model <provider/model>
184
180
  ```
185
181
 
186
- If `--model` and `OPENCODE_MODEL` are omitted, the harness defaults to `openai/gpt-5.5`. Use any provider-qualified model ID shown by `opencode models`.
182
+ If `--model` and `OPENCODE_MODEL` are omitted, the harness defaults to `openai/gpt-5.5`. Use a model available in your installation, as shown by `opencode models`.
187
183
 
188
184
  Useful flags:
189
185
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@distlang/opencode-plugin",
3
- "version": "0.2.5",
3
+ "version": "0.4.0",
4
4
  "description": "OpenCode plugin for Distlang Agent Debugger",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -14,7 +14,7 @@
14
14
  "README.md"
15
15
  ],
16
16
  "scripts": {
17
- "test": "node --check src/index.js && node --check src/recorder.js && node --check src/distlang.js && node --check src/state.js && node --check src/command.js && node --check integration/opencode-local-test.mjs && node --check integration/assert-package-contents.mjs && node --test test/*.test.js",
17
+ "test": "node --check src/index.js && node --check src/v2.js && node --check src/recorder.js && node --check src/distlang.js && node --check src/state.js && node --check src/command.js && node --check integration/opencode-local-test.mjs && node --check integration/assert-package-contents.mjs && node --test test/*.test.js",
18
18
  "check": "npm test",
19
19
  "pack:check": "node integration/assert-package-contents.mjs",
20
20
  "test:opencode": "node integration/opencode-local-test.mjs",
@@ -38,5 +38,8 @@
38
38
  "publishConfig": {
39
39
  "access": "public"
40
40
  },
41
- "license": "MIT"
41
+ "license": "MIT",
42
+ "dependencies": {
43
+ "@opencode/plugin": "^2.4.5"
44
+ }
42
45
  }
package/src/command.js CHANGED
@@ -1,90 +1,60 @@
1
- function configuredValue(value, fallback = "") {
2
- return typeof value === "string" && value.trim() !== "" ? value.trim() : fallback;
3
- }
1
+ // Distlang slash commands. OpenCode 2 runs a plugin command's executor instead of
2
+ // sending the prompt to the model, so no hook interception is needed.
4
3
 
5
- function splitCommandText(value) {
6
- const trimmed = configuredValue(value, "");
7
- if (!trimmed.startsWith("/")) {
8
- return null;
9
- }
10
- const parts = trimmed.slice(1).trim().split(/\s+/).filter(Boolean);
11
- if (parts.length === 0) {
12
- return null;
13
- }
14
- return {
15
- name: parts[0].toLowerCase(),
16
- args: parts.slice(1),
17
- raw: trimmed,
18
- };
19
- }
4
+ export const distlangCommandNames = ["distlang-start", "distlang-stop", "distlang-status", "distlang-view", "distlang-view-local", "distlang"];
20
5
 
21
- function normalizeArgs(value) {
22
- if (Array.isArray(value)) {
23
- return value.map((entry) => configuredValue(entry, "")).filter(Boolean);
24
- }
25
- if (typeof value === "string" && value.trim() !== "") {
26
- return value.trim().split(/\s+/).filter(Boolean);
27
- }
28
- return [];
29
- }
6
+ export const distlangCommands = [
7
+ {
8
+ name: "distlang-start",
9
+ description: "Sign in and enable Distlang Agent Debugger uploads",
10
+ action: "start",
11
+ },
12
+ {
13
+ name: "distlang-stop",
14
+ description: "Disable Distlang Agent Debugger uploads",
15
+ action: "stop",
16
+ },
17
+ {
18
+ name: "distlang-status",
19
+ description: "Show Distlang Agent Debugger upload status",
20
+ action: "status",
21
+ },
22
+ {
23
+ name: "distlang-view",
24
+ description: "Open the current Agent Debugger session in the browser",
25
+ action: "view",
26
+ },
27
+ {
28
+ name: "distlang-view-local",
29
+ description: "Start or open the local Distlang Agent Debugger",
30
+ action: "view-local",
31
+ },
32
+ ];
30
33
 
31
- function commandLike(entry) {
32
- if (!entry || typeof entry !== "object") {
33
- return null;
34
- }
35
- const directName = configuredValue(entry.name, configuredValue(entry.command, configuredValue(entry.id, configuredValue(entry.slug, "")))).replace(/^\//, "").toLowerCase();
36
- const args = normalizeArgs(entry.args ?? entry.arguments ?? entry.argv);
37
- if (directName) {
38
- return {
39
- name: directName,
40
- args,
41
- raw: configuredValue(entry.raw, args.length > 0 ? `/${directName} ${args.join(" ")}` : `/${directName}`),
42
- };
34
+ export function splitArguments(text) {
35
+ if (Array.isArray(text)) {
36
+ return text.map((entry) => String(entry ?? "").trim()).filter(Boolean);
43
37
  }
44
- const text = splitCommandText(configuredValue(entry.text, configuredValue(entry.input, configuredValue(entry.value, configuredValue(entry.prompt, "")))));
45
- if (text) {
46
- return text;
47
- }
48
- return null;
38
+ return typeof text === "string" ? text.trim().split(/\s+/).filter(Boolean) : [];
49
39
  }
50
40
 
51
- export function extractDistlangInvocation(input) {
52
- const candidates = [
53
- input,
54
- input?.event,
55
- input?.properties,
56
- input?.command,
57
- input?.info,
58
- input?.properties,
59
- input?.payload,
60
- ];
61
- for (const candidate of candidates) {
62
- const parsed = commandLike(candidate);
63
- const invocation = distlangInvocation(parsed);
64
- if (invocation) {
65
- return invocation;
66
- }
67
- }
68
-
69
- const directText = splitCommandText(configuredValue(input?.commandLine, configuredValue(input?.text, configuredValue(input?.input, configuredValue(input?.raw, "")))));
70
- return distlangInvocation(directText);
41
+ // /distlang-view ses_123 -> { action: "view", args: ["ses_123"] }
42
+ export function commandInvocation(command, text) {
43
+ const args = splitArguments(text);
44
+ return {
45
+ name: "distlang",
46
+ action: command.action,
47
+ args,
48
+ raw: args.length > 0 ? `/${command.name} ${args.join(" ")}` : `/${command.name}`,
49
+ };
71
50
  }
72
51
 
73
- function distlangInvocation(parsed) {
74
- if (!parsed) {
75
- return null;
76
- }
77
- if (parsed.name === "distlang") {
78
- return parsed;
79
- }
80
- const action = parsed.name.startsWith("distlang-") ? parsed.name.slice("distlang-".length) : "";
81
- if (action === "start" || action === "stop" || action === "status" || action === "view") {
82
- return {
83
- ...parsed,
84
- name: "distlang",
85
- action,
86
- raw: parsed.raw || `/${parsed.name}`,
87
- };
88
- }
89
- return null;
52
+ // /distlang status | start | stop | login | logout | view [session-id] | view-local
53
+ export function legacyCommandInvocation(text) {
54
+ const args = splitArguments(text);
55
+ return {
56
+ name: "distlang",
57
+ args,
58
+ raw: args.length > 0 ? `/distlang ${args.join(" ")}` : "/distlang",
59
+ };
90
60
  }
package/src/distlang.js CHANGED
@@ -1,4 +1,4 @@
1
- import { execFile } from "node:child_process";
1
+ import { execFile, spawn } from "node:child_process";
2
2
  import { promises as fs } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { homedir, tmpdir } from "node:os";
@@ -9,6 +9,7 @@ const execFileAsync = promisify(execFile);
9
9
 
10
10
  let managedInstallPromise = null;
11
11
  let resolvedBinaryPromise = null;
12
+ let localDebuggerStartPromise = null;
12
13
 
13
14
  function configuredValue(value, fallback = "") {
14
15
  return typeof value === "string" && value.trim() !== "" ? value.trim() : fallback;
@@ -31,6 +32,14 @@ function managedBinaryPath() {
31
32
  return join(managedInstallDir(), process.platform === "win32" ? "distlang.exe" : "distlang");
32
33
  }
33
34
 
35
+ function localDebuggerBaseUrl() {
36
+ return configuredValue(process.env.DISTLANG_AGENT_DEBUGGER_BASE_URL, "http://127.0.0.1:4817").replace(/\/+$/, "");
37
+ }
38
+
39
+ function localDebuggerManagedBinaryPath() {
40
+ return join(homedir(), ".cache", "distlang", "agent-debugger", "bin", process.platform === "win32" ? "distlang-agent-debugger.exe" : "distlang-agent-debugger");
41
+ }
42
+
34
43
  async function pathHasExecutable(filePath) {
35
44
  try {
36
45
  await fs.access(filePath, fs.constants.X_OK);
@@ -61,6 +70,26 @@ async function findDistlangOnPath() {
61
70
  return "";
62
71
  }
63
72
 
73
+ async function findExecutableOnPath(names) {
74
+ const pathValue = configuredValue(process.env.PATH, "");
75
+ if (!pathValue) {
76
+ return "";
77
+ }
78
+ for (const part of pathValue.split(process.platform === "win32" ? ";" : ":")) {
79
+ const base = configuredValue(part, "");
80
+ if (!base) {
81
+ continue;
82
+ }
83
+ for (const executableName of names) {
84
+ const candidate = join(base, executableName);
85
+ if (await pathHasExecutable(candidate)) {
86
+ return candidate;
87
+ }
88
+ }
89
+ }
90
+ return "";
91
+ }
92
+
64
93
  async function verifyDistlangBinary(filePath) {
65
94
  const trimmed = configuredValue(filePath, "");
66
95
  if (!trimmed) {
@@ -160,18 +189,106 @@ export async function runDistlang(args, options = {}) {
160
189
  return execFileAsync(resolved.path, args, {
161
190
  env: process.env,
162
191
  maxBuffer: 16 * 1024 * 1024,
192
+ // OpenCode stops a private server by signalling its process group. A CLI in
193
+ // its own group survives that, so an upload started at shutdown can finish.
194
+ ...(process.platform === "win32" ? {} : { detached: true }),
163
195
  ...execOptions,
164
196
  });
165
197
  }
166
198
 
199
+ export async function supportsDistlangMcp(binaryPath) {
200
+ try {
201
+ const { stdout } = await execFileAsync(binaryPath, ["mcp", "--help"], { timeout: 5000 });
202
+ return stdout.includes("distlang mcp");
203
+ } catch {
204
+ return false;
205
+ }
206
+ }
207
+
167
208
  export function distlangCommandInfo() {
168
209
  return {
169
210
  bin: distlangBinary(),
170
211
  managed_bin: managedBinaryPath(),
171
212
  auto_install_disabled: autoInstallDisabled(),
213
+ local_debugger_base_url: localDebuggerBaseUrl(),
214
+ local_debugger_managed_bin: localDebuggerManagedBinaryPath(),
172
215
  };
173
216
  }
174
217
 
218
+ export async function resolveLocalDebuggerBinary() {
219
+ const explicit = configuredValue(process.env.DISTLANG_AGENT_DEBUGGER_BIN, "");
220
+ if (explicit) {
221
+ await fs.access(explicit, fs.constants.X_OK);
222
+ return { path: explicit, source: "env" };
223
+ }
224
+ const fromPath = await findExecutableOnPath(process.platform === "win32" ? ["distlang-agent-debugger.exe", "distlang-agent-debugger.cmd", "distlang-agent-debugger.bat"] : ["distlang-agent-debugger"]);
225
+ if (fromPath) {
226
+ return { path: fromPath, source: "path" };
227
+ }
228
+ const managedPath = localDebuggerManagedBinaryPath();
229
+ if (await pathHasExecutable(managedPath)) {
230
+ return { path: managedPath, source: "managed" };
231
+ }
232
+ const error = new Error("distlang-agent-debugger binary not found");
233
+ error.code = "ENOENT";
234
+ throw error;
235
+ }
236
+
237
+ export function localAgentDebuggerUrl() {
238
+ return `${localDebuggerBaseUrl()}/agent-debugger`;
239
+ }
240
+
241
+ export function localAgentDebuggerSessionUrl(sessionID) {
242
+ const id = configuredValue(sessionID, "");
243
+ return id ? `${localDebuggerBaseUrl()}/agent-debugger/sessions/${encodeURIComponent(id)}` : "";
244
+ }
245
+
246
+ export async function localAgentDebuggerHealth() {
247
+ const response = await fetch(`${localDebuggerBaseUrl()}/health`, { signal: AbortSignal.timeout(1500) });
248
+ if (!response.ok) {
249
+ throw new Error(`local Agent Debugger health returned ${response.status}`);
250
+ }
251
+ return response.json().catch(() => ({ ok: true }));
252
+ }
253
+
254
+ export async function ensureLocalAgentDebugger() {
255
+ try {
256
+ await localAgentDebuggerHealth();
257
+ return { running: true, started: false, base_url: localDebuggerBaseUrl() };
258
+ } catch {
259
+ // Start below.
260
+ }
261
+ if (!localDebuggerStartPromise) {
262
+ localDebuggerStartPromise = (async () => {
263
+ const resolved = await resolveLocalDebuggerBinary();
264
+ const child = spawn(resolved.path, ["serve", "--no-open"], {
265
+ detached: true,
266
+ stdio: "ignore",
267
+ env: process.env,
268
+ });
269
+ child.on("error", () => undefined);
270
+ child.unref();
271
+ const deadline = Date.now() + 8000;
272
+ let lastError = null;
273
+ while (Date.now() < deadline) {
274
+ await new Promise((resolve) => setTimeout(resolve, 300));
275
+ try {
276
+ await localAgentDebuggerHealth();
277
+ return { running: true, started: true, base_url: localDebuggerBaseUrl(), debugger: resolved };
278
+ } catch (error) {
279
+ lastError = error;
280
+ }
281
+ }
282
+ throw new Error(`local Agent Debugger did not become healthy: ${lastError ? String(lastError) : "timeout"}`);
283
+ })();
284
+ }
285
+ try {
286
+ return await localDebuggerStartPromise;
287
+ } finally {
288
+ localDebuggerStartPromise = null;
289
+ }
290
+ }
291
+
175
292
  export async function getAuthStatus() {
176
293
  const { stdout } = await runDistlang(["helpers", "auth", "status", "--json"]);
177
294
  return JSON.parse(stdout || "{}");
@@ -204,6 +321,29 @@ export async function uploadAgentDebuggerPayload(payload) {
204
321
  }
205
322
  }
206
323
 
324
+ export async function uploadLocalAgentDebuggerPayload(payload) {
325
+ const response = await fetch(`${localDebuggerBaseUrl()}/agent-debugger/v1/ingest`, {
326
+ method: "POST",
327
+ headers: { "content-type": "application/json" },
328
+ body: JSON.stringify(payload),
329
+ });
330
+ const body = await response.json().catch(async () => ({ text: await response.text().catch(() => "") }));
331
+ return {
332
+ ok: response.ok,
333
+ status: response.status,
334
+ body,
335
+ ...body,
336
+ };
337
+ }
338
+
339
+ export async function fetchLocalAgentDebuggerSessions() {
340
+ const response = await fetch(`${localDebuggerBaseUrl()}/agent-debugger/v1/sessions?source=opencode&limit=5`);
341
+ if (!response.ok) {
342
+ throw new Error(`local Agent Debugger sessions returned ${response.status}`);
343
+ }
344
+ return response.json();
345
+ }
346
+
207
347
  export async function fetchAgentDebuggerSessions() {
208
348
  const { stdout } = await runDistlang([
209
349
  "helpers",