@distlang/opencode-plugin 0.1.2 → 0.1.3

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
@@ -17,6 +17,28 @@ Add the plugin to your global OpenCode config:
17
17
 
18
18
  OpenCode installs npm plugins automatically with Bun at startup.
19
19
 
20
+ ## Local use
21
+
22
+ The plugin uses `distlang` only for two things:
23
+
24
+ - `distlang helpers auth status --json`
25
+ - `distlang helpers request ...`
26
+
27
+ If `distlang` is not already available, the plugin can install a managed copy automatically.
28
+
29
+ Managed install location:
30
+
31
+ ```text
32
+ ~/.cache/distlang/opencode-plugin/bin/distlang
33
+ ```
34
+
35
+ Resolution order:
36
+
37
+ 1. `DISTLANG_BIN`
38
+ 2. `distlang` on `PATH`
39
+ 3. managed plugin install
40
+ 4. auto-install into the managed plugin path
41
+
20
42
  ## Auth
21
43
 
22
44
  The plugin does not manage tokens directly.
@@ -28,6 +50,12 @@ distlang helpers auth status
28
50
  distlang helpers login
29
51
  ```
30
52
 
53
+ If the plugin installs a managed copy because `distlang` was missing, you can log in with that binary directly:
54
+
55
+ ```bash
56
+ ~/.cache/distlang/opencode-plugin/bin/distlang helpers login
57
+ ```
58
+
31
59
  The plugin uses:
32
60
 
33
61
  - `distlang helpers auth status --json`
@@ -35,12 +63,53 @@ The plugin uses:
35
63
 
36
64
  If you are not logged in, the plugin logs one warning and continues without uploading.
37
65
 
66
+ ## `/distlang` command
67
+
68
+ OpenCode commands are configured separately from plugins, so add a command file to make `/distlang` available in the TUI:
69
+
70
+ `~/.config/opencode/commands/distlang.md`
71
+
72
+ ```md
73
+ ---
74
+ description: Manage Distlang AI Debugger uploads
75
+ ---
76
+
77
+ Handled locally by the Distlang OpenCode plugin.
78
+ Use `/distlang status`, `/distlang start`, or `/distlang stop`.
79
+ ```
80
+
81
+ The plugin watches for this command and handles:
82
+
83
+ - `/distlang status`
84
+ - `/distlang start`
85
+ - `/distlang stop`
86
+
87
+ Command results are written to the OpenCode app log, and also to the debug log file when enabled.
88
+
38
89
  ## Debugging
39
90
 
40
91
  ```bash
41
92
  DISTLANG_OPENCODE_DEBUG=1 opencode
42
93
  ```
43
94
 
95
+ Useful overrides:
96
+
97
+ ```bash
98
+ DISTLANG_BIN=/path/to/distlang opencode
99
+ DISTLANG_STORE_BASE_URL=https://api-staging.distlang.com opencode
100
+ DISTLANG_AUTH_BASE_URL=https://auth-staging.distlang.com opencode
101
+ DISTLANG_OPENCODE_NO_INSTALL=1 opencode
102
+ DISTLANG_OPENCODE_INSTALL_DIR=/tmp/distlang-plugin-bin opencode
103
+ DISTLANG_OPENCODE_STATE_FILE=/tmp/distlang-plugin-state.json opencode
104
+ DISTLANG_OPENCODE_LOG_FILE=/tmp/distlang-opencode.log opencode
105
+ ```
106
+
107
+ To inspect whether uploads are visible after a run:
108
+
109
+ ```bash
110
+ distlang helpers request GET /ai-debugger/v1/sessions --json
111
+ ```
112
+
44
113
  ## Captured Model
45
114
 
46
115
  The plugin builds a session-batch payload for Distlang AI Debugger:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@distlang/opencode-plugin",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "OpenCode plugin for Distlang AI 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",
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",
18
18
  "check": "npm test",
19
19
  "pack:check": "npm pack --dry-run",
20
20
  "release": "npm test && npm run pack:check",
package/src/command.js ADDED
@@ -0,0 +1,72 @@
1
+ function configuredValue(value, fallback = "") {
2
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : fallback;
3
+ }
4
+
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
+ }
20
+
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
+ }
30
+
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
+ };
43
+ }
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;
49
+ }
50
+
51
+ export function extractDistlangInvocation(input) {
52
+ const candidates = [
53
+ input,
54
+ input?.event,
55
+ input?.command,
56
+ input?.info,
57
+ input?.properties,
58
+ input?.payload,
59
+ ];
60
+ for (const candidate of candidates) {
61
+ const parsed = commandLike(candidate);
62
+ if (parsed && parsed.name === "distlang") {
63
+ return parsed;
64
+ }
65
+ }
66
+
67
+ const directText = splitCommandText(configuredValue(input?.commandLine, configuredValue(input?.text, configuredValue(input?.input, configuredValue(input?.raw, "")))));
68
+ if (directText && directText.name === "distlang") {
69
+ return directText;
70
+ }
71
+ return null;
72
+ }
package/src/distlang.js CHANGED
@@ -1,29 +1,174 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promises as fs } from "node:fs";
3
3
  import { join } from "node:path";
4
- import { tmpdir } from "node:os";
4
+ import { homedir, tmpdir } from "node:os";
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { promisify } from "node:util";
7
7
 
8
8
  const execFileAsync = promisify(execFile);
9
9
 
10
+ let managedInstallPromise = null;
11
+ let resolvedBinaryPromise = null;
12
+
13
+ function configuredValue(value, fallback = "") {
14
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : fallback;
15
+ }
16
+
17
+ function autoInstallDisabled() {
18
+ const value = configuredValue(process.env.DISTLANG_OPENCODE_NO_INSTALL, "").toLowerCase();
19
+ return value === "1" || value === "true" || value === "yes" || value === "on";
20
+ }
21
+
22
+ function managedInstallDir() {
23
+ const override = configuredValue(process.env.DISTLANG_OPENCODE_INSTALL_DIR, "");
24
+ if (override) {
25
+ return override;
26
+ }
27
+ return join(homedir(), ".cache", "distlang", "opencode-plugin", "bin");
28
+ }
29
+
30
+ function managedBinaryPath() {
31
+ return join(managedInstallDir(), process.platform === "win32" ? "distlang.exe" : "distlang");
32
+ }
33
+
34
+ async function pathHasExecutable(filePath) {
35
+ try {
36
+ await fs.access(filePath, fs.constants.X_OK);
37
+ return true;
38
+ } catch {
39
+ return false;
40
+ }
41
+ }
42
+
43
+ async function findDistlangOnPath() {
44
+ const pathValue = configuredValue(process.env.PATH, "");
45
+ if (!pathValue) {
46
+ return "";
47
+ }
48
+ const executableNames = process.platform === "win32" ? ["distlang.exe", "distlang.cmd", "distlang.bat"] : ["distlang"];
49
+ for (const part of pathValue.split(process.platform === "win32" ? ";" : ":")) {
50
+ const base = configuredValue(part, "");
51
+ if (!base) {
52
+ continue;
53
+ }
54
+ for (const executableName of executableNames) {
55
+ const candidate = join(base, executableName);
56
+ if (await pathHasExecutable(candidate)) {
57
+ return candidate;
58
+ }
59
+ }
60
+ }
61
+ return "";
62
+ }
63
+
64
+ async function verifyDistlangBinary(filePath) {
65
+ const trimmed = configuredValue(filePath, "");
66
+ if (!trimmed) {
67
+ const error = new Error("distlang binary path is empty");
68
+ error.code = "ENOENT";
69
+ throw error;
70
+ }
71
+ await execFileAsync(trimmed, ["--version"], {
72
+ env: process.env,
73
+ maxBuffer: 16 * 1024 * 1024,
74
+ });
75
+ return trimmed;
76
+ }
77
+
78
+ async function installManagedDistlang() {
79
+ if (managedInstallPromise) {
80
+ return managedInstallPromise;
81
+ }
82
+ managedInstallPromise = (async () => {
83
+ const installDir = managedInstallDir();
84
+ await fs.mkdir(installDir, { recursive: true });
85
+ await execFileAsync("bash", ["-lc", "curl -fsSL https://distlang.com/install-main | bash"], {
86
+ env: {
87
+ ...process.env,
88
+ DISTLANG_INSTALL_DIR: installDir,
89
+ },
90
+ maxBuffer: 16 * 1024 * 1024,
91
+ });
92
+ const binaryPath = managedBinaryPath();
93
+ await verifyDistlangBinary(binaryPath);
94
+ return binaryPath;
95
+ })();
96
+ try {
97
+ return await managedInstallPromise;
98
+ } finally {
99
+ managedInstallPromise = null;
100
+ }
101
+ }
102
+
10
103
  function distlangBinary() {
11
104
  return process.env.DISTLANG_BIN && process.env.DISTLANG_BIN.trim() !== ""
12
105
  ? process.env.DISTLANG_BIN.trim()
13
106
  : "distlang";
14
107
  }
15
108
 
109
+ export async function resolveDistlangBinary(options = {}) {
110
+ const installIfMissing = options.installIfMissing !== false;
111
+ const explicit = configuredValue(process.env.DISTLANG_BIN, "");
112
+ if (explicit) {
113
+ await verifyDistlangBinary(explicit);
114
+ return { path: explicit, source: "env" };
115
+ }
116
+
117
+ if (resolvedBinaryPromise && installIfMissing) {
118
+ return resolvedBinaryPromise;
119
+ }
120
+
121
+ const resolver = (async () => {
122
+ const fromPath = await findDistlangOnPath();
123
+ if (fromPath) {
124
+ await verifyDistlangBinary(fromPath);
125
+ return { path: fromPath, source: "path" };
126
+ }
127
+
128
+ const managedPath = managedBinaryPath();
129
+ if (await pathHasExecutable(managedPath)) {
130
+ await verifyDistlangBinary(managedPath);
131
+ return { path: managedPath, source: "managed" };
132
+ }
133
+
134
+ if (!installIfMissing || autoInstallDisabled()) {
135
+ const error = new Error("distlang CLI not found");
136
+ error.code = "ENOENT";
137
+ throw error;
138
+ }
139
+
140
+ const installed = await installManagedDistlang();
141
+ return { path: installed, source: "installed" };
142
+ })();
143
+
144
+ if (installIfMissing) {
145
+ resolvedBinaryPromise = resolver;
146
+ }
147
+ try {
148
+ return await resolver;
149
+ } catch (error) {
150
+ if (installIfMissing) {
151
+ resolvedBinaryPromise = null;
152
+ }
153
+ throw error;
154
+ }
155
+ }
156
+
16
157
  export async function runDistlang(args, options = {}) {
17
- return execFileAsync(distlangBinary(), args, {
158
+ const { installIfMissing, ...execOptions } = options;
159
+ const resolved = await resolveDistlangBinary({ installIfMissing: installIfMissing !== false });
160
+ return execFileAsync(resolved.path, args, {
18
161
  env: process.env,
19
162
  maxBuffer: 16 * 1024 * 1024,
20
- ...options,
163
+ ...execOptions,
21
164
  });
22
165
  }
23
166
 
24
167
  export function distlangCommandInfo() {
25
168
  return {
26
169
  bin: distlangBinary(),
170
+ managed_bin: managedBinaryPath(),
171
+ auto_install_disabled: autoInstallDisabled(),
27
172
  };
28
173
  }
29
174
 
@@ -50,3 +195,14 @@ export async function uploadAIDebuggerPayload(payload) {
50
195
  await fs.unlink(tempFile).catch(() => {});
51
196
  }
52
197
  }
198
+
199
+ export async function fetchAIDebuggerSessions() {
200
+ const { stdout } = await runDistlang([
201
+ "helpers",
202
+ "request",
203
+ "GET",
204
+ "/ai-debugger/v1/sessions?source=opencode&limit=5",
205
+ "--json",
206
+ ]);
207
+ return JSON.parse(stdout || "{}");
208
+ }
package/src/index.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { createRecorder } from "./recorder.js";
2
- import { distlangCommandInfo, getAuthStatus, uploadAIDebuggerPayload } from "./distlang.js";
2
+ import { extractDistlangInvocation } from "./command.js";
3
+ import { distlangCommandInfo, fetchAIDebuggerSessions, getAuthStatus, resolveDistlangBinary, uploadAIDebuggerPayload } from "./distlang.js";
4
+ import { pluginStatePath, readPluginState, writePluginState } from "./state.js";
3
5
  import { appendFile } from "node:fs/promises";
4
6
 
5
7
  function configuredValue(value, fallback = "") {
@@ -19,10 +21,9 @@ export const DistlangAIDebugger = async ({ project, directory, client }) => {
19
21
  const debug = debugEnabled();
20
22
  const recorder = createRecorder({ project, directory });
21
23
  let loggedInit = false;
22
- let authChecked = false;
23
- let authAvailable = false;
24
24
  let authWarningLogged = false;
25
25
  let distlangMissingLogged = false;
26
+ let commandHandledAt = 0;
26
27
 
27
28
  async function log(level, message, extra = undefined) {
28
29
  const line = JSON.stringify({
@@ -63,22 +64,99 @@ export const DistlangAIDebugger = async ({ project, directory, client }) => {
63
64
  loggedInit = true;
64
65
  await log(debug ? "debug" : "info", "Distlang OpenCode AI Debugger plugin initialized", {
65
66
  debug,
67
+ statePath: pluginStatePath(),
66
68
  distlang: distlangCommandInfo(),
67
69
  });
68
70
  }
69
71
 
72
+ async function uploadEnabled() {
73
+ const state = await readPluginState();
74
+ return state.enabled !== false;
75
+ }
76
+
77
+ async function maybeLogCommandResult(level, message, extra = undefined) {
78
+ await log(level, message, extra);
79
+ }
80
+
81
+ async function handleDistlangCommand(invocation, source) {
82
+ const now = Date.now();
83
+ if (now - commandHandledAt < 250) {
84
+ return;
85
+ }
86
+ commandHandledAt = now;
87
+ const action = configuredValue(invocation.args[0], "status").toLowerCase();
88
+ if (action === "start") {
89
+ const state = await writePluginState(true);
90
+ authWarningLogged = false;
91
+ let resolved = null;
92
+ let auth = null;
93
+ try {
94
+ resolved = await resolveDistlangBinary({ installIfMissing: true });
95
+ } catch (error) {
96
+ await maybeLogCommandResult("warn", "Distlang uploads enabled, but distlang install/resolve failed", { source, action, error: String(error) });
97
+ return;
98
+ }
99
+ try {
100
+ auth = await getAuthStatus();
101
+ } catch (error) {
102
+ await maybeLogCommandResult("warn", "Distlang uploads enabled, but auth check failed", { source, action, state, distlang: resolved, error: String(error) });
103
+ return;
104
+ }
105
+ await maybeLogCommandResult("info", "Distlang AI Debugger uploads enabled", {
106
+ source,
107
+ action,
108
+ state,
109
+ distlang: resolved,
110
+ auth,
111
+ });
112
+ return;
113
+ }
114
+
115
+ if (action === "stop") {
116
+ const state = await writePluginState(false);
117
+ await maybeLogCommandResult("info", "Distlang AI Debugger uploads disabled", { source, action, state });
118
+ return;
119
+ }
120
+
121
+ const state = await readPluginState();
122
+ let resolved = null;
123
+ let auth = null;
124
+ let sessions = null;
125
+ let resolutionError = null;
126
+ try {
127
+ resolved = await resolveDistlangBinary({ installIfMissing: true });
128
+ auth = await getAuthStatus();
129
+ sessions = await fetchAIDebuggerSessions();
130
+ } catch (error) {
131
+ resolutionError = String(error);
132
+ }
133
+ await maybeLogCommandResult("info", "Distlang AI Debugger status", {
134
+ source,
135
+ action,
136
+ state,
137
+ distlang: resolved,
138
+ auth,
139
+ sessions,
140
+ error: resolutionError,
141
+ command_hint: "/distlang status | /distlang start | /distlang stop",
142
+ });
143
+ }
144
+
70
145
  async function ensureAuthStatus() {
71
- if (authChecked) {
72
- return authAvailable;
146
+ if (!(await uploadEnabled())) {
147
+ await debugLog("Distlang AI Debugger uploads are disabled", { state: await readPluginState() });
148
+ return false;
73
149
  }
74
- authChecked = true;
75
150
  try {
151
+ const resolved = await resolveDistlangBinary({ installIfMissing: true });
76
152
  const payload = await getAuthStatus();
77
- authAvailable = payload && payload.ok === true && payload.logged_in === true;
78
- await debugLog("Distlang auth status resolved", { authAvailable, payload });
153
+ const authAvailable = payload && payload.ok === true && payload.logged_in === true;
154
+ await debugLog("Distlang auth status resolved", { authAvailable, payload, distlang: resolved });
79
155
  if (!authAvailable && !authWarningLogged) {
80
156
  authWarningLogged = true;
81
157
  await log("warn", "Distlang AI Debugger upload disabled: run `distlang helpers login` first", { auth: payload });
158
+ } else if (authAvailable) {
159
+ authWarningLogged = false;
82
160
  }
83
161
  return authAvailable;
84
162
  } catch (error) {
@@ -91,7 +169,6 @@ export const DistlangAIDebugger = async ({ project, directory, client }) => {
91
169
  authWarningLogged = true;
92
170
  await log("warn", "Distlang AI Debugger auth check failed; upload disabled", { error: String(error) });
93
171
  }
94
- authAvailable = false;
95
172
  return false;
96
173
  }
97
174
  }
@@ -175,6 +252,14 @@ export const DistlangAIDebugger = async ({ project, directory, client }) => {
175
252
  return;
176
253
  }
177
254
 
255
+ if (event.type === "command.executed") {
256
+ const invocation = extractDistlangInvocation(event);
257
+ if (invocation) {
258
+ await handleDistlangCommand(invocation, "command.executed");
259
+ }
260
+ return;
261
+ }
262
+
178
263
 
179
264
  if (event.type === "session.created") {
180
265
  const observed = recorder.observeSessionCreated(event);
@@ -224,6 +309,15 @@ export const DistlangAIDebugger = async ({ project, directory, client }) => {
224
309
  }
225
310
  },
226
311
 
312
+ "tui.command.execute": async (input) => {
313
+ await logInit();
314
+ const invocation = extractDistlangInvocation(input);
315
+ if (!invocation) {
316
+ return;
317
+ }
318
+ await handleDistlangCommand(invocation, "tui.command.execute");
319
+ },
320
+
227
321
  "tool.execute.before": async (input) => {
228
322
  await logInit();
229
323
  const observed = recorder.observeToolBefore(input);
package/src/state.js ADDED
@@ -0,0 +1,50 @@
1
+ import { promises as fs } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { homedir } from "node:os";
4
+
5
+ function configuredValue(value, fallback = "") {
6
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : fallback;
7
+ }
8
+
9
+ function defaultState() {
10
+ return {
11
+ enabled: true,
12
+ updated_at: null,
13
+ };
14
+ }
15
+
16
+ export function pluginStatePath() {
17
+ const override = configuredValue(process.env.DISTLANG_OPENCODE_STATE_FILE, "");
18
+ if (override) {
19
+ return override;
20
+ }
21
+ return join(homedir(), ".config", "opencode", "distlang-plugin.json");
22
+ }
23
+
24
+ export async function readPluginState() {
25
+ const filePath = pluginStatePath();
26
+ try {
27
+ const raw = await fs.readFile(filePath, "utf8");
28
+ const parsed = JSON.parse(raw);
29
+ return {
30
+ enabled: parsed && parsed.enabled === false ? false : true,
31
+ updated_at: typeof parsed?.updated_at === "string" && parsed.updated_at.trim() !== "" ? parsed.updated_at : null,
32
+ };
33
+ } catch (error) {
34
+ if (error && typeof error === "object" && error.code === "ENOENT") {
35
+ return defaultState();
36
+ }
37
+ return defaultState();
38
+ }
39
+ }
40
+
41
+ export async function writePluginState(enabled) {
42
+ const filePath = pluginStatePath();
43
+ await fs.mkdir(dirname(filePath), { recursive: true });
44
+ const payload = {
45
+ enabled: enabled !== false,
46
+ updated_at: new Date().toISOString(),
47
+ };
48
+ await fs.writeFile(filePath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
49
+ return payload;
50
+ }