@distlang/opencode-plugin 0.2.4 → 0.3.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,11 +11,12 @@ 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
 
@@ -65,38 +66,13 @@ If you are not logged in, the plugin logs one warning and continues without uplo
65
66
 
66
67
  ## Distlang commands
67
68
 
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:
69
+ The plugin registers these commands:
95
70
 
96
71
  - `/distlang-start`
97
72
  - `/distlang-stop`
98
73
  - `/distlang-status`
99
74
  - `/distlang-view [session-id]`
75
+ - `/distlang-view-local`
100
76
 
101
77
  The legacy compact command also remains supported:
102
78
 
@@ -106,7 +82,12 @@ The legacy compact command also remains supported:
106
82
  - `/distlang login`
107
83
  - `/distlang logout`
108
84
 
109
- Command results are written to the OpenCode app log, and also to the debug log file when enabled.
85
+ If upgrading from the V1 plugin, remove or move the old `distlang*.md` command
86
+ files from `~/.config/opencode/commands/` (and any project command directories).
87
+ Those files override the plugin's command executors in OpenCode 2.
88
+
89
+ Command results are written to the server log, and to the debug log file when
90
+ enabled. This version does not show TUI toast notifications.
110
91
 
111
92
  If `/distlang-start` finds that Distlang auth is missing, the plugin starts `distlang helpers login`, which opens the browser login flow.
112
93
 
@@ -124,9 +105,12 @@ Commands:
124
105
  - `/distlang-status`: show whether uploads are enabled, whether auth is available, and whether recent Agent Debugger sessions are visible
125
106
  - `/distlang-start`: sign in if needed and enable Agent Debugger uploads
126
107
  - `/distlang-stop`: disable Agent Debugger uploads and sign out of Distlang
127
- - `/distlang-view [session-id]`: open the latest uploaded OpenCode Agent Debugger session in the browser, or the provided session id
108
+ - `/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
109
+ - `/distlang-view-local`: start/open the local Agent Debugger without requiring Distlang login
110
+
111
+ Legacy aliases remain available: `/distlang status`, `/distlang start`, `/distlang stop`, `/distlang login`, `/distlang logout`, and `/distlang view-local`.
128
112
 
129
- Legacy aliases remain available: `/distlang status`, `/distlang start`, `/distlang stop`, `/distlang login`, and `/distlang logout`.
113
+ 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
114
 
131
115
  ## Debugging
132
116
 
@@ -140,6 +124,8 @@ Useful overrides:
140
124
  DISTLANG_BIN=/path/to/distlang opencode
141
125
  DISTLANG_STORE_BASE_URL=https://api-staging.distlang.com opencode
142
126
  DISTLANG_AUTH_BASE_URL=https://auth-staging.distlang.com opencode
127
+ DISTLANG_AGENT_DEBUGGER_BASE_URL=http://127.0.0.1:4817 opencode
128
+ DISTLANG_AGENT_DEBUGGER_BIN=/path/to/distlang-agent-debugger opencode
143
129
  DISTLANG_OPENCODE_NO_INSTALL=1 opencode
144
130
  DISTLANG_OPENCODE_INSTALL_DIR=/tmp/distlang-plugin-bin opencode
145
131
  DISTLANG_OPENCODE_STATE_FILE=/tmp/distlang-plugin-state.json opencode
@@ -180,10 +166,10 @@ The repository includes a live local integration harness. It is not included in
180
166
  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
167
 
182
168
  ```bash
183
- npm run test:opencode -- --model openai/gpt-5.5
169
+ npm run test:opencode -- --model <provider/model>
184
170
  ```
185
171
 
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`.
172
+ 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
173
 
188
174
  Useful flags:
189
175
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@distlang/opencode-plugin",
3
- "version": "0.2.4",
3
+ "version": "0.3.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 and sign out",
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,6 +189,9 @@ 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
  }
@@ -169,9 +201,85 @@ export function distlangCommandInfo() {
169
201
  bin: distlangBinary(),
170
202
  managed_bin: managedBinaryPath(),
171
203
  auto_install_disabled: autoInstallDisabled(),
204
+ local_debugger_base_url: localDebuggerBaseUrl(),
205
+ local_debugger_managed_bin: localDebuggerManagedBinaryPath(),
172
206
  };
173
207
  }
174
208
 
209
+ export async function resolveLocalDebuggerBinary() {
210
+ const explicit = configuredValue(process.env.DISTLANG_AGENT_DEBUGGER_BIN, "");
211
+ if (explicit) {
212
+ await fs.access(explicit, fs.constants.X_OK);
213
+ return { path: explicit, source: "env" };
214
+ }
215
+ const fromPath = await findExecutableOnPath(process.platform === "win32" ? ["distlang-agent-debugger.exe", "distlang-agent-debugger.cmd", "distlang-agent-debugger.bat"] : ["distlang-agent-debugger"]);
216
+ if (fromPath) {
217
+ return { path: fromPath, source: "path" };
218
+ }
219
+ const managedPath = localDebuggerManagedBinaryPath();
220
+ if (await pathHasExecutable(managedPath)) {
221
+ return { path: managedPath, source: "managed" };
222
+ }
223
+ const error = new Error("distlang-agent-debugger binary not found");
224
+ error.code = "ENOENT";
225
+ throw error;
226
+ }
227
+
228
+ export function localAgentDebuggerUrl() {
229
+ return `${localDebuggerBaseUrl()}/agent-debugger`;
230
+ }
231
+
232
+ export function localAgentDebuggerSessionUrl(sessionID) {
233
+ const id = configuredValue(sessionID, "");
234
+ return id ? `${localDebuggerBaseUrl()}/agent-debugger/sessions/${encodeURIComponent(id)}` : "";
235
+ }
236
+
237
+ export async function localAgentDebuggerHealth() {
238
+ const response = await fetch(`${localDebuggerBaseUrl()}/health`, { signal: AbortSignal.timeout(1500) });
239
+ if (!response.ok) {
240
+ throw new Error(`local Agent Debugger health returned ${response.status}`);
241
+ }
242
+ return response.json().catch(() => ({ ok: true }));
243
+ }
244
+
245
+ export async function ensureLocalAgentDebugger() {
246
+ try {
247
+ await localAgentDebuggerHealth();
248
+ return { running: true, started: false, base_url: localDebuggerBaseUrl() };
249
+ } catch {
250
+ // Start below.
251
+ }
252
+ if (!localDebuggerStartPromise) {
253
+ localDebuggerStartPromise = (async () => {
254
+ const resolved = await resolveLocalDebuggerBinary();
255
+ const child = spawn(resolved.path, ["serve", "--no-open"], {
256
+ detached: true,
257
+ stdio: "ignore",
258
+ env: process.env,
259
+ });
260
+ child.on("error", () => undefined);
261
+ child.unref();
262
+ const deadline = Date.now() + 8000;
263
+ let lastError = null;
264
+ while (Date.now() < deadline) {
265
+ await new Promise((resolve) => setTimeout(resolve, 300));
266
+ try {
267
+ await localAgentDebuggerHealth();
268
+ return { running: true, started: true, base_url: localDebuggerBaseUrl(), debugger: resolved };
269
+ } catch (error) {
270
+ lastError = error;
271
+ }
272
+ }
273
+ throw new Error(`local Agent Debugger did not become healthy: ${lastError ? String(lastError) : "timeout"}`);
274
+ })();
275
+ }
276
+ try {
277
+ return await localDebuggerStartPromise;
278
+ } finally {
279
+ localDebuggerStartPromise = null;
280
+ }
281
+ }
282
+
175
283
  export async function getAuthStatus() {
176
284
  const { stdout } = await runDistlang(["helpers", "auth", "status", "--json"]);
177
285
  return JSON.parse(stdout || "{}");
@@ -204,6 +312,29 @@ export async function uploadAgentDebuggerPayload(payload) {
204
312
  }
205
313
  }
206
314
 
315
+ export async function uploadLocalAgentDebuggerPayload(payload) {
316
+ const response = await fetch(`${localDebuggerBaseUrl()}/agent-debugger/v1/ingest`, {
317
+ method: "POST",
318
+ headers: { "content-type": "application/json" },
319
+ body: JSON.stringify(payload),
320
+ });
321
+ const body = await response.json().catch(async () => ({ text: await response.text().catch(() => "") }));
322
+ return {
323
+ ok: response.ok,
324
+ status: response.status,
325
+ body,
326
+ ...body,
327
+ };
328
+ }
329
+
330
+ export async function fetchLocalAgentDebuggerSessions() {
331
+ const response = await fetch(`${localDebuggerBaseUrl()}/agent-debugger/v1/sessions?source=opencode&limit=5`);
332
+ if (!response.ok) {
333
+ throw new Error(`local Agent Debugger sessions returned ${response.status}`);
334
+ }
335
+ return response.json();
336
+ }
337
+
207
338
  export async function fetchAgentDebuggerSessions() {
208
339
  const { stdout } = await runDistlang([
209
340
  "helpers",