@distlang/opencode-plugin 0.2.5 → 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/src/index.js CHANGED
@@ -1,9 +1,29 @@
1
- import { createRecorder, extractSessionTitle } from "./recorder.js";
2
- import { extractDistlangInvocation } from "./command.js";
3
- import { distlangCommandInfo, fetchAgentDebuggerSessions, getAuthStatus, loginWithDistlang, logoutWithDistlang, resolveDistlangBinary, uploadAgentDebuggerPayload } from "./distlang.js";
4
- import { pluginStatePath, readPluginState, writePluginState } from "./state.js";
1
+ import { Plugin } from "@opencode/plugin";
5
2
  import { appendFile } from "node:fs/promises";
3
+ import { realpathSync } from "node:fs";
6
4
  import { spawn } from "node:child_process";
5
+ import path from "node:path";
6
+ import { createRecorder, extractSessionTitle } from "./recorder.js";
7
+ import { createV2Bridge } from "./v2.js";
8
+ import { commandInvocation, distlangCommands, legacyCommandInvocation } from "./command.js";
9
+ import { distlangCommandInfo, ensureLocalAgentDebugger, fetchAgentDebuggerSessions, fetchLocalAgentDebuggerSessions, getAuthStatus, localAgentDebuggerUrl, loginWithDistlang, logoutWithDistlang, resolveDistlangBinary, uploadAgentDebuggerPayload, uploadLocalAgentDebuggerPayload } from "./distlang.js";
10
+ import { pluginStatePath, readPluginState, writePluginState } from "./state.js";
11
+
12
+ // Server events the plugin records. Anything else on the event stream is ignored.
13
+ const recordedEventTypes = [
14
+ "session.created",
15
+ "session.renamed",
16
+ "session.deleted",
17
+ "session.step.started",
18
+ "session.step.first-token",
19
+ "session.step.ended",
20
+ "session.step.failed",
21
+ "session.text.ended",
22
+ "session.execution.succeeded",
23
+ "session.execution.failed",
24
+ "session.execution.interrupted",
25
+ "session.idle",
26
+ ];
7
27
 
8
28
  function configuredValue(value, fallback = "") {
9
29
  return typeof value === "string" && value.trim() !== "" ? value.trim() : fallback;
@@ -18,589 +38,731 @@ function debugLogFile() {
18
38
  return configuredValue(process.env.DISTLANG_OPENCODE_LOG_FILE, "");
19
39
  }
20
40
 
21
- export const DistlangAgentDebugger = async ({ project, directory, client }) => {
22
- const debug = debugEnabled();
23
- const recorder = createRecorder({ project, directory, initialPrompt: extractOpenCodeRunPrompt(process.argv) });
24
- let loggedInit = false;
25
- let authWarningLogged = false;
26
- let distlangMissingLogged = false;
27
- let commandHandledAt = 0;
28
-
29
- async function log(level, message, extra = undefined) {
30
- const line = JSON.stringify({
31
- ts: new Date().toISOString(),
32
- service: "distlang-agent-debugger",
33
- level,
34
- message,
35
- extra,
36
- });
37
- const outputPath = debugLogFile();
38
- if (outputPath) {
39
- await appendFile(outputPath, `${line}\n`).catch(() => {});
40
- }
41
- if (!client || !client.app || typeof client.app.log !== "function") {
42
- return;
43
- }
44
- await client.app.log({
45
- body: {
41
+ function sleep(ms) {
42
+ return new Promise((resolve) => setTimeout(resolve, ms));
43
+ }
44
+
45
+ // Details of a failed distlang CLI run, so the log shows whether the process was
46
+ // killed or exited with an error.
47
+ function commandFailure(error) {
48
+ if (!error || typeof error !== "object") {
49
+ return {};
50
+ }
51
+ return {
52
+ exitCode: Number.isFinite(error.code) ? error.code : undefined,
53
+ signal: typeof error.signal === "string" ? error.signal : undefined,
54
+ killed: error.killed === true || undefined,
55
+ stderr: typeof error.stderr === "string" && error.stderr.trim() ? error.stderr.trim().slice(0, 500) : undefined,
56
+ };
57
+ }
58
+
59
+ // OpenCode stops a plugin's subprocesses when it unloads the plugin, which
60
+ // rejects the pending CLI call. Such an upload was cut off, not rejected by the
61
+ // server, so it is retried from the cleanup function.
62
+ class UploadInterruptedError extends Error {}
63
+
64
+ function interrupted(error) {
65
+ return Boolean(error) && typeof error === "object" && (typeof error.signal === "string" || error.killed === true);
66
+ }
67
+
68
+ function interruptedError(error) {
69
+ return new UploadInterruptedError(String(error));
70
+ }
71
+
72
+ export default Plugin.define({
73
+ id: "distlang-agent-debugger",
74
+ async setup(ctx) {
75
+ const debug = debugEnabled();
76
+ const recorder = createRecorder({ project: undefined, directory: ctx.location.directory });
77
+ const bridge = createV2Bridge(recorder);
78
+ const controller = new AbortController();
79
+ const pendingUploads = new Set();
80
+ const uploadQueues = new Map();
81
+ const unfinishedUploads = new Map();
82
+ const knownDirectories = new Map();
83
+ const knownSessions = new Set();
84
+ let loggedInit = false;
85
+ let authWarningLogged = false;
86
+ let distlangMissingLogged = false;
87
+
88
+ async function log(level, message, extra = undefined) {
89
+ const line = JSON.stringify({
90
+ ts: new Date().toISOString(),
46
91
  service: "distlang-agent-debugger",
47
92
  level,
48
93
  message,
49
94
  extra,
50
- },
51
- }).catch(() => {});
52
- }
53
-
54
- async function debugLog(message, extra = undefined) {
55
- if (!debug) {
56
- return;
95
+ });
96
+ const outputPath = debugLogFile();
97
+ if (outputPath) {
98
+ await appendFile(outputPath, `${line}\n`).catch(() => {});
99
+ }
100
+ const consoleLine = `[distlang-agent-debugger] ${level}: ${message}`;
101
+ if (level === "error" || level === "warn") {
102
+ console.error(consoleLine);
103
+ } else {
104
+ console.log(consoleLine);
105
+ }
57
106
  }
58
- await log("debug", message, extra);
59
- }
60
107
 
61
- async function logInit() {
62
- if (loggedInit) {
63
- return;
108
+ async function debugLog(message, extra = undefined) {
109
+ if (!debug) {
110
+ return;
111
+ }
112
+ await log("debug", message, extra);
64
113
  }
65
- loggedInit = true;
66
- await log(debug ? "debug" : "info", "Distlang OpenCode Agent Debugger plugin initialized", {
67
- debug,
68
- statePath: pluginStatePath(),
69
- distlang: distlangCommandInfo(),
70
- });
71
- }
72
-
73
- async function uploadEnabled() {
74
- const state = await readPluginState();
75
- return state.enabled !== false;
76
- }
77
114
 
78
- async function maybeLogCommandResult(level, message, extra = undefined) {
79
- await log(level, message, extra);
80
- if (client?.tui && typeof client.tui.showToast === "function") {
81
- const variant = level === "error" ? "error" : level === "warn" ? "warning" : level === "info" ? "success" : "info";
82
- const detail = typeof extra?.error === "string" && extra.error.trim() !== "" ? extra.error.trim() : undefined;
83
- await client.tui.showToast({
84
- body: {
85
- title: "Distlang",
86
- message: detail ? `${message}: ${detail}` : message,
87
- variant,
88
- duration: 5000,
89
- },
90
- }).catch(() => {});
115
+ async function logInit() {
116
+ if (loggedInit) {
117
+ return;
118
+ }
119
+ loggedInit = true;
120
+ await log(debug ? "debug" : "info", "Distlang OpenCode Agent Debugger plugin initialized", {
121
+ debug,
122
+ opencode: ctx.app?.version,
123
+ statePath: pluginStatePath(),
124
+ distlang: distlangCommandInfo(),
125
+ });
91
126
  }
92
- }
93
127
 
94
- function dashboardBaseUrl() {
95
- return configuredValue(process.env.DISTLANG_DASHBOARD_URL, "https://dash.distlang.com").replace(/\/+$/, "");
96
- }
128
+ async function uploadEnabled() {
129
+ const state = await readPluginState();
130
+ return state.enabled !== false;
131
+ }
97
132
 
98
- function sessionUrl(sessionID) {
99
- const id = configuredValue(sessionID, "");
100
- return id ? `${dashboardBaseUrl()}/agent-debugger/sessions/${encodeURIComponent(id)}` : "";
101
- }
133
+ async function logCommandResult(level, message, extra = undefined) {
134
+ await log(level, message, extra);
135
+ }
102
136
 
103
- function agentDebuggerUrl() {
104
- return `${dashboardBaseUrl()}/agent-debugger`;
105
- }
137
+ function dashboardBaseUrl() {
138
+ return configuredValue(process.env.DISTLANG_DASHBOARD_URL, "https://dash.distlang.com").replace(/\/+$/, "");
139
+ }
106
140
 
107
- function openerCommand() {
108
- if (process.platform === "darwin") return { command: "open", args: [] };
109
- if (process.platform === "win32") return { command: "cmd", args: ["/c", "start", ""] };
110
- return { command: "xdg-open", args: [] };
111
- }
141
+ function sessionUrl(sessionID) {
142
+ const id = configuredValue(sessionID, "");
143
+ return id ? `${dashboardBaseUrl()}/agent-debugger/sessions/${encodeURIComponent(id)}` : "";
144
+ }
112
145
 
113
- function openUrl(url) {
114
- const { command, args } = openerCommand();
115
- return new Promise((resolve) => {
116
- try {
117
- const child = spawn(command, [...args, url], { detached: true, stdio: "ignore" });
118
- child.on("error", () => resolve(false));
119
- child.unref();
120
- resolve(true);
121
- } catch {
122
- resolve(false);
123
- }
124
- });
125
- }
146
+ function agentDebuggerUrl() {
147
+ return `${dashboardBaseUrl()}/agent-debugger`;
148
+ }
126
149
 
127
- function commandArgument(invocation, action) {
128
- const args = Array.isArray(invocation?.args) ? invocation.args : [];
129
- if (configuredValue(invocation?.action, "")) {
130
- return configuredValue(args[0], "");
150
+ function openerCommand() {
151
+ if (process.platform === "darwin") return { command: "open", args: [] };
152
+ if (process.platform === "win32") return { command: "cmd", args: ["/c", "start", ""] };
153
+ return { command: "xdg-open", args: [] };
131
154
  }
132
- return configuredValue(args[0], "").toLowerCase() === action ? configuredValue(args[1], "") : configuredValue(args[0], "");
133
- }
134
155
 
135
- function sessionsFromResponse(response) {
136
- const candidates = [
137
- response?.body?.sessions,
138
- response?.sessions,
139
- response?.body?.data?.sessions,
140
- response?.data?.sessions,
141
- response?.body?.items,
142
- response?.items,
143
- ];
144
- for (const candidate of candidates) {
145
- if (Array.isArray(candidate)) return candidate;
156
+ function openUrl(url) {
157
+ const { command, args } = openerCommand();
158
+ return new Promise((resolve) => {
159
+ try {
160
+ const child = spawn(command, [...args, url], { detached: true, stdio: "ignore" });
161
+ child.on("error", () => resolve(false));
162
+ child.unref();
163
+ resolve(true);
164
+ } catch {
165
+ resolve(false);
166
+ }
167
+ });
146
168
  }
147
- return [];
148
- }
149
169
 
150
- function firstSessionID(response) {
151
- for (const session of sessionsFromResponse(response)) {
152
- const id = configuredValue(session?.id, configuredValue(session?.session_id, ""));
153
- if (id) return id;
170
+ function commandArgument(invocation, action) {
171
+ const args = Array.isArray(invocation?.args) ? invocation.args : [];
172
+ if (configuredValue(invocation?.action, "")) {
173
+ return configuredValue(args[0], "");
174
+ }
175
+ return configuredValue(args[0], "").toLowerCase() === action ? configuredValue(args[1], "") : configuredValue(args[0], "");
154
176
  }
155
- return "";
156
- }
157
177
 
158
- async function ensureCommandAuth(source, action, state = null, resolved = null) {
159
- let auth = await getAuthStatus();
160
- if (!auth || auth.ok !== true || auth.logged_in !== true) {
161
- await maybeLogCommandResult("info", "Opening browser for Distlang login", { source, action, state, distlang: resolved });
162
- await loginWithDistlang();
163
- auth = await getAuthStatus();
178
+ function sessionsFromResponse(response) {
179
+ const candidates = [
180
+ response?.body?.sessions,
181
+ response?.sessions,
182
+ response?.body?.data?.sessions,
183
+ response?.data?.sessions,
184
+ response?.body?.items,
185
+ response?.items,
186
+ ];
187
+ for (const candidate of candidates) {
188
+ if (Array.isArray(candidate)) return candidate;
189
+ }
190
+ return [];
164
191
  }
165
- return auth;
166
- }
167
192
 
168
- async function handleDistlangCommand(invocation, source) {
169
- const now = Date.now();
170
- if (now - commandHandledAt < 250) {
171
- return;
193
+ function firstSessionID(response) {
194
+ for (const session of sessionsFromResponse(response)) {
195
+ const id = configuredValue(session?.id, configuredValue(session?.session_id, ""));
196
+ if (id) return id;
197
+ }
198
+ return "";
172
199
  }
173
- commandHandledAt = now;
174
- const requestedAction = configuredValue(invocation.action, configuredValue(invocation.args[0], "status")).toLowerCase();
175
- const action = requestedAction === "login" ? "start" : requestedAction === "logout" ? "stop" : requestedAction;
176
- if (!["status", "start", "stop", "view"].includes(action)) {
177
- await maybeLogCommandResult("warn", "Unknown Distlang command. Use /distlang-status, /distlang-start, /distlang-stop, or /distlang-view", {
178
- source,
179
- action: requestedAction,
180
- command_hint: "/distlang-status | /distlang-start | /distlang-stop | /distlang-view",
181
- });
182
- return;
200
+
201
+ async function ensureCommandAuth(source, action, state = null, resolved = null) {
202
+ let auth = await getAuthStatus();
203
+ if (!auth || auth.ok !== true || auth.logged_in !== true) {
204
+ await logCommandResult("info", "Opening browser for Distlang login", { source, action, state, distlang: resolved });
205
+ await loginWithDistlang();
206
+ auth = await getAuthStatus();
207
+ }
208
+ return auth;
183
209
  }
184
- if (action === "start") {
185
- const state = await writePluginState(true);
186
- authWarningLogged = false;
187
- let resolved = null;
188
- let auth = null;
189
- try {
190
- resolved = await resolveDistlangBinary({ installIfMissing: true });
191
- } catch (error) {
192
- await maybeLogCommandResult("warn", "Distlang uploads enabled, but distlang install/resolve failed", { source, action, error: String(error) });
210
+
211
+ async function handleDistlangCommand(invocation, source) {
212
+ const requestedAction = configuredValue(invocation.action, configuredValue(invocation.args[0], "status")).toLowerCase();
213
+ const action = requestedAction === "login" ? "start" : requestedAction === "logout" ? "stop" : requestedAction;
214
+ if (!["status", "start", "stop", "view", "view-local"].includes(action)) {
215
+ await logCommandResult("warn", "Unknown Distlang command. Use /distlang-status, /distlang-start, /distlang-stop, /distlang-view, or /distlang-view-local", {
216
+ source,
217
+ action: requestedAction,
218
+ command_hint: "/distlang-status | /distlang-start | /distlang-stop | /distlang-view | /distlang-view-local",
219
+ });
193
220
  return;
194
221
  }
195
- try {
196
- auth = await ensureCommandAuth(source, action, state, resolved);
197
- } catch (error) {
198
- await maybeLogCommandResult("warn", "Distlang uploads enabled, but auth check failed", { source, action, state, distlang: resolved, error: String(error) });
222
+ if (action === "start") {
223
+ const state = await writePluginState(true);
224
+ authWarningLogged = false;
225
+ let resolved = null;
226
+ let auth = null;
227
+ try {
228
+ resolved = await resolveDistlangBinary({ installIfMissing: true });
229
+ } catch (error) {
230
+ await logCommandResult("warn", "Distlang uploads enabled, but distlang install/resolve failed", { source, action, error: String(error) });
231
+ return;
232
+ }
233
+ try {
234
+ auth = await ensureCommandAuth(source, action, state, resolved);
235
+ } catch (error) {
236
+ await logCommandResult("warn", "Distlang uploads enabled, but auth check failed", { source, action, state, distlang: resolved, error: String(error) });
237
+ return;
238
+ }
239
+ await logCommandResult("info", "Distlang Agent Debugger uploads enabled", {
240
+ source,
241
+ action,
242
+ state,
243
+ distlang: resolved,
244
+ auth,
245
+ });
199
246
  return;
200
247
  }
201
- await maybeLogCommandResult("info", "Distlang Agent Debugger uploads enabled", {
202
- source,
203
- action,
204
- state,
205
- distlang: resolved,
206
- auth,
207
- });
208
- return;
209
- }
210
248
 
211
- if (action === "stop") {
212
- const state = await writePluginState(false);
213
- authWarningLogged = false;
214
- try {
215
- const resolved = await resolveDistlangBinary({ installIfMissing: true });
216
- await logoutWithDistlang();
217
- await maybeLogCommandResult("info", "Distlang Agent Debugger uploads disabled and signed out", { source, action, state, distlang: resolved });
218
- } catch (error) {
219
- await maybeLogCommandResult("warn", "Distlang Agent Debugger uploads disabled, but sign out failed", { source, action, state, error: String(error) });
249
+ if (action === "stop") {
250
+ const state = await writePluginState(false);
251
+ authWarningLogged = false;
252
+ try {
253
+ const resolved = await resolveDistlangBinary({ installIfMissing: true });
254
+ await logoutWithDistlang();
255
+ await logCommandResult("info", "Distlang Agent Debugger uploads disabled and signed out", { source, action, state, distlang: resolved });
256
+ } catch (error) {
257
+ await logCommandResult("warn", "Distlang Agent Debugger uploads disabled, but sign out failed", { source, action, state, error: String(error) });
258
+ }
259
+ return;
220
260
  }
221
- return;
222
- }
223
261
 
224
- if (action === "view") {
225
- const state = await readPluginState();
226
- let resolved = null;
227
- let auth = null;
228
- let sessions = null;
229
- try {
230
- resolved = await resolveDistlangBinary({ installIfMissing: true });
231
- auth = await ensureCommandAuth(source, action, state, resolved);
232
- sessions = await fetchAgentDebuggerSessions();
233
- } catch (error) {
234
- await maybeLogCommandResult("warn", "Unable to open Distlang Agent Debugger session", { source, action, state, distlang: resolved, error: String(error) });
262
+ if (action === "view-local") {
263
+ const state = await writePluginState(true);
264
+ authWarningLogged = false;
265
+ let local = null;
266
+ let sessions = null;
267
+ try {
268
+ local = await ensureLocalAgentDebugger();
269
+ sessions = await fetchLocalAgentDebuggerSessions().catch((error) => ({ error: String(error) }));
270
+ } catch (error) {
271
+ await logCommandResult("warn", "Unable to start local Distlang Agent Debugger", {
272
+ source,
273
+ action,
274
+ state,
275
+ error: String(error),
276
+ install_hint: "Install from https://distlang.com/agent-debugger/install or put distlang-agent-debugger on PATH.",
277
+ });
278
+ return;
279
+ }
280
+ const url = localAgentDebuggerUrl();
281
+ const opened = await openUrl(url);
282
+ await logCommandResult("info", `Open local Distlang Agent Debugger: ${url}`, {
283
+ source,
284
+ action,
285
+ state,
286
+ local,
287
+ sessions,
288
+ url,
289
+ opened,
290
+ });
235
291
  return;
236
292
  }
237
- const sessionID = commandArgument(invocation, action) || firstSessionID(sessions);
238
- const url = sessionID ? sessionUrl(sessionID) : agentDebuggerUrl();
239
- const opened = await openUrl(url);
240
- if (!sessionID) {
241
- await maybeLogCommandResult("info", `Open Distlang Agent Debugger: ${url}`, {
293
+
294
+ if (action === "view") {
295
+ const state = await readPluginState();
296
+ let resolved = null;
297
+ let auth = null;
298
+ let sessions = null;
299
+ try {
300
+ resolved = await resolveDistlangBinary({ installIfMissing: true });
301
+ auth = await ensureCommandAuth(source, action, state, resolved);
302
+ sessions = await fetchAgentDebuggerSessions();
303
+ } catch (error) {
304
+ await logCommandResult("warn", "Unable to open Distlang Agent Debugger session", { source, action, state, distlang: resolved, error: String(error) });
305
+ return;
306
+ }
307
+ const sessionID = commandArgument(invocation, action) || firstSessionID(sessions);
308
+ const url = sessionID ? sessionUrl(sessionID) : agentDebuggerUrl();
309
+ const opened = await openUrl(url);
310
+ if (!sessionID) {
311
+ await logCommandResult("info", `Open Distlang Agent Debugger: ${url}`, {
312
+ source,
313
+ action,
314
+ state,
315
+ distlang: resolved,
316
+ auth,
317
+ session_id: null,
318
+ url,
319
+ opened,
320
+ fallback: "agent_debugger_overview",
321
+ sessions,
322
+ });
323
+ return;
324
+ }
325
+ await logCommandResult("info", `Open Distlang Agent Debugger session: ${url}`, {
242
326
  source,
243
327
  action,
244
328
  state,
245
329
  distlang: resolved,
246
330
  auth,
247
- session_id: null,
331
+ session_id: sessionID,
248
332
  url,
249
333
  opened,
250
- fallback: "agent_debugger_overview",
251
334
  sessions,
252
335
  });
253
336
  return;
254
337
  }
255
- await maybeLogCommandResult("info", `Open Distlang Agent Debugger session: ${url}`, {
338
+
339
+ const state = await readPluginState();
340
+ let resolved = null;
341
+ let auth = null;
342
+ let sessions = null;
343
+ let resolutionError = null;
344
+ try {
345
+ resolved = await resolveDistlangBinary({ installIfMissing: true });
346
+ auth = await getAuthStatus();
347
+ sessions = await fetchAgentDebuggerSessions();
348
+ } catch (error) {
349
+ resolutionError = String(error);
350
+ }
351
+ await logCommandResult("info", "Distlang Agent Debugger status", {
256
352
  source,
257
353
  action,
258
354
  state,
259
355
  distlang: resolved,
260
356
  auth,
261
- session_id: sessionID,
262
- url,
263
- opened,
264
357
  sessions,
358
+ error: resolutionError,
359
+ command_hint: "/distlang-status | /distlang-start | /distlang-stop | /distlang-view",
265
360
  });
266
- return;
267
361
  }
268
362
 
269
- const state = await readPluginState();
270
- let resolved = null;
271
- let auth = null;
272
- let sessions = null;
273
- let resolutionError = null;
274
- try {
275
- resolved = await resolveDistlangBinary({ installIfMissing: true });
276
- auth = await getAuthStatus();
277
- sessions = await fetchAgentDebuggerSessions();
278
- } catch (error) {
279
- resolutionError = String(error);
363
+ async function runCommand(invocation, source) {
364
+ await logInit();
365
+ try {
366
+ await handleDistlangCommand(invocation, source);
367
+ } catch (error) {
368
+ await log("error", "Distlang command failed", { source, action: invocation?.action, error: String(error) });
369
+ }
280
370
  }
281
- await maybeLogCommandResult("info", "Distlang Agent Debugger status", {
282
- source,
283
- action,
284
- state,
285
- distlang: resolved,
286
- auth,
287
- sessions,
288
- error: resolutionError,
289
- command_hint: "/distlang-status | /distlang-start | /distlang-stop | /distlang-view",
290
- });
291
- }
292
371
 
293
- async function ensureAuthStatus() {
294
- if (!(await uploadEnabled())) {
295
- await debugLog("Distlang Agent Debugger uploads are disabled", { state: await readPluginState() });
296
- return false;
297
- }
298
- try {
299
- const resolved = await resolveDistlangBinary({ installIfMissing: true });
300
- const payload = await getAuthStatus();
301
- const authAvailable = payload && payload.ok === true && payload.logged_in === true;
302
- await debugLog("Distlang auth status resolved", { authAvailable, payload, distlang: resolved });
303
- if (!authAvailable && !authWarningLogged) {
304
- authWarningLogged = true;
305
- await maybeLogCommandResult("warn", "Distlang Agent Debugger upload disabled: run `/distlang-start` to sign in and enable uploads", {
306
- auth: payload,
307
- command_hint: "/distlang-start",
308
- });
309
- } else if (authAvailable) {
310
- authWarningLogged = false;
311
- }
312
- return authAvailable;
313
- } catch (error) {
314
- if (error && typeof error === "object" && error.code === "ENOENT") {
315
- if (!distlangMissingLogged) {
316
- distlangMissingLogged = true;
317
- await log("warn", "distlang CLI not found; Agent Debugger upload disabled", { distlang: distlangCommandInfo() });
372
+ async function uploadPayloadToLocal(payload, sessionID, result, reason) {
373
+ let local = null;
374
+ try {
375
+ local = await ensureLocalAgentDebugger();
376
+ const response = await uploadLocalAgentDebuggerPayload(payload);
377
+ await debugLog("Local Agent Debugger upload response received", { sessionID, result, reason, response, local });
378
+ if (!response.ok) {
379
+ await log("warn", "Local Agent Debugger upload failed", { sessionID, result, reason, response, local });
380
+ return false;
381
+ }
382
+ if (reason !== "cloud_auth_unavailable") {
383
+ await log("info", "Saved Agent Debugger session locally", { sessionID, result, reason, local, response });
384
+ } else {
385
+ await debugLog("Agent Debugger session saved locally because cloud auth is unavailable", { sessionID, result, local, response });
318
386
  }
319
- } else if (!authWarningLogged) {
320
- authWarningLogged = true;
321
- await log("warn", "Distlang Agent Debugger auth check failed; upload disabled", { error: String(error) });
387
+ return true;
388
+ } catch (error) {
389
+ await log("warn", "Local Agent Debugger upload failed", {
390
+ sessionID,
391
+ result,
392
+ reason,
393
+ local,
394
+ error: String(error),
395
+ install_hint: "Run /distlang-view-local after installing distlang-agent-debugger.",
396
+ });
397
+ return false;
322
398
  }
323
- return false;
324
399
  }
325
- }
326
400
 
327
- async function finalizeSession(sessionID, result) {
328
- let payload;
329
- try {
330
- await refreshSessionMetadata(sessionID, { retry: true });
331
- payload = recorder.finalizeSession(sessionID, result, Date.now());
332
- } catch (error) {
333
- await log("error", "Agent Debugger session finalization failed", { sessionID, result, error: String(error) });
334
- return;
335
- }
336
- if (!payload) {
337
- await debugLog("No payload produced during session finalization", { sessionID, result });
338
- return;
339
- }
340
- await debugLog("Finalized Agent Debugger session payload", {
341
- sessionID,
342
- result,
343
- interactions: Array.isArray(payload.interactions) ? payload.interactions.length : 0,
344
- steps: Array.isArray(payload.interactions) ? payload.interactions.reduce((total, interaction) => total + (Array.isArray(interaction.steps) ? interaction.steps.length : 0), 0) : 0,
345
- project: payload.project,
346
- });
347
- if (!(await ensureAuthStatus())) {
348
- await debugLog("Skipping AI debugger upload because auth is unavailable", { sessionID });
349
- return;
350
- }
351
- try {
352
- const response = await uploadAgentDebuggerPayload(payload);
353
- await debugLog("Agent Debugger upload response received", { sessionID, response });
401
+ // Uploads one snapshot. The result says whether it reached the cloud, the
402
+ // local Agent Debugger, or neither. A shutdown that kills the Distlang CLI
403
+ // mid-upload throws, so the snapshot can be retried from the cleanup function.
404
+ async function uploadPayload(payload, sessionID, result) {
405
+ if (!(await uploadEnabled())) {
406
+ await debugLog("Distlang Agent Debugger uploads are disabled", { state: await readPluginState(), sessionID, result });
407
+ return "skipped";
408
+ }
409
+ let authAvailable = false;
410
+ try {
411
+ authAvailable = await ensureAuthStatus();
412
+ } catch (error) {
413
+ throw interruptedError(error);
414
+ }
415
+ if (!authAvailable) {
416
+ return (await uploadPayloadToLocal(payload, sessionID, result, "cloud_auth_unavailable")) ? "local" : "failed";
417
+ }
418
+ let response;
419
+ try {
420
+ response = await uploadAgentDebuggerPayload(payload);
421
+ } catch (error) {
422
+ if (interrupted(error)) {
423
+ throw interruptedError(error);
424
+ }
425
+ await log("warn", "Agent Debugger upload failed; trying local fallback", { sessionID, result, ...commandFailure(error), error: String(error) });
426
+ return (await uploadPayloadToLocal(payload, sessionID, result, "cloud_upload_error")) ? "local" : "failed";
427
+ }
428
+ await debugLog("Agent Debugger upload response received", { sessionID, result, response });
354
429
  if (!response.ok) {
355
- await log("warn", "Agent Debugger upload failed", { sessionID, response });
356
- return;
430
+ await log("warn", "Agent Debugger upload failed", { sessionID, result, response });
431
+ return (await uploadPayloadToLocal(payload, sessionID, result, "cloud_upload_failed")) ? "local" : "failed";
357
432
  }
358
- await debugLog("Agent Debugger session uploaded", { sessionID, response });
359
- } catch (error) {
360
- await log("warn", "Agent Debugger upload failed", { sessionID, error: String(error) });
433
+ await debugLog("Agent Debugger session uploaded", { sessionID, result, response });
434
+ return "uploaded";
361
435
  }
362
- }
363
436
 
364
- async function uploadSessionSnapshot(sessionID, result = "success") {
365
- let payload;
366
- try {
367
- await refreshSessionMetadata(sessionID, { retry: true });
368
- payload = recorder.snapshotSession(sessionID, result, Date.now());
369
- } catch (error) {
370
- await log("error", "Agent Debugger session snapshot failed", { sessionID, result, error: String(error) });
371
- return;
372
- }
373
- if (!payload) {
374
- await debugLog("No payload produced during session snapshot", { sessionID, result });
375
- return;
376
- }
377
- await debugLog("Prepared Agent Debugger session snapshot", {
378
- sessionID,
379
- result,
380
- interactions: Array.isArray(payload.interactions) ? payload.interactions.length : 0,
381
- steps: Array.isArray(payload.interactions) ? payload.interactions.reduce((total, interaction) => total + (Array.isArray(interaction.steps) ? interaction.steps.length : 0), 0) : 0,
382
- project: payload.project,
383
- });
384
- if (!(await ensureAuthStatus())) {
385
- await debugLog("Skipping AI debugger snapshot upload because auth is unavailable", { sessionID });
386
- return;
387
- }
388
- try {
389
- const response = await uploadAgentDebuggerPayload(payload);
390
- await debugLog("Agent Debugger snapshot upload response received", { sessionID, response });
391
- if (!response.ok) {
392
- await log("warn", "Agent Debugger snapshot upload failed", { sessionID, response });
393
- return;
437
+ async function ensureAuthStatus() {
438
+ if (!(await uploadEnabled())) {
439
+ await debugLog("Distlang Agent Debugger uploads are disabled", { state: await readPluginState() });
440
+ return false;
441
+ }
442
+ try {
443
+ const resolved = await resolveDistlangBinary({ installIfMissing: true });
444
+ const payload = await getAuthStatus();
445
+ const authAvailable = payload && payload.ok === true && payload.logged_in === true;
446
+ await debugLog("Distlang auth status resolved", { authAvailable, payload, distlang: resolved });
447
+ if (!authAvailable && !authWarningLogged) {
448
+ authWarningLogged = true;
449
+ await log("warn", "Distlang Agent Debugger upload disabled: run `/distlang-start` to sign in and enable uploads", {
450
+ auth: payload,
451
+ command_hint: "/distlang-start",
452
+ });
453
+ } else if (authAvailable) {
454
+ authWarningLogged = false;
455
+ }
456
+ return authAvailable;
457
+ } catch (error) {
458
+ if (interrupted(error)) {
459
+ throw interruptedError(error);
460
+ }
461
+ if (error && typeof error === "object" && error.code === "ENOENT") {
462
+ if (!distlangMissingLogged) {
463
+ distlangMissingLogged = true;
464
+ await log("warn", "distlang CLI not found; Agent Debugger upload disabled", { distlang: distlangCommandInfo() });
465
+ }
466
+ } else if (!authWarningLogged) {
467
+ authWarningLogged = true;
468
+ await log("warn", "Distlang Agent Debugger auth check failed; upload disabled", { ...commandFailure(error), error: String(error) });
469
+ }
470
+ return false;
394
471
  }
395
- await debugLog("Agent Debugger session snapshot uploaded", { sessionID, response });
396
- } catch (error) {
397
- await log("warn", "Agent Debugger snapshot upload failed", { sessionID, error: String(error) });
398
472
  }
399
- }
400
473
 
401
- async function refreshSessionMetadata(sessionID, options = {}) {
402
- if (!sessionID || !client?.session || typeof client.session.get !== "function") {
403
- return;
404
- }
405
- const attempts = options.retry ? 3 : 1;
406
- for (let attempt = 1; attempt <= attempts; attempt += 1) {
474
+ async function refreshSessionMetadata(sessionID) {
475
+ if (bridge.hasTitle(sessionID) || typeof ctx.session?.get !== "function") {
476
+ return;
477
+ }
407
478
  try {
408
- const response = await client.session.get({ path: { id: sessionID } });
409
- const session = response?.data ?? response;
479
+ const session = await ctx.session.get({ sessionID });
410
480
  const title = extractSessionTitle(session);
411
- await debugLog("OpenCode session metadata inspected", { sessionID, attempt, sessionKeys: session && typeof session === "object" ? Object.keys(session) : [] });
412
481
  if (title) {
482
+ bridge.setTitle(sessionID, title);
413
483
  recorder.setSessionTitle(sessionID, title);
414
- await debugLog("OpenCode session metadata refreshed", { sessionID, attempt, titleLength: title.length });
415
- return;
484
+ await debugLog("OpenCode session metadata refreshed", { sessionID, titleLength: title.length });
416
485
  }
417
486
  } catch (error) {
418
- await debugLog("OpenCode session metadata refresh failed", { sessionID, attempt, error: String(error) });
419
- }
420
- if (attempt < attempts) {
421
- await sleep(500);
487
+ await debugLog("OpenCode session metadata refresh failed", { sessionID, error: String(error) });
422
488
  }
423
489
  }
424
- }
425
-
426
- function sleep(ms) {
427
- return new Promise((resolve) => setTimeout(resolve, ms));
428
- }
429
490
 
430
- function extractOpenCodeRunPrompt(argv) {
431
- const args = Array.isArray(argv) ? argv : [];
432
- const runIndex = args.findIndex((arg) => arg === "run");
433
- if (runIndex < 0) {
434
- return "";
435
- }
436
- const promptParts = [];
437
- for (let index = runIndex + 1; index < args.length; index += 1) {
438
- const arg = configuredValue(args[index], "");
439
- if (!arg) {
440
- continue;
441
- }
442
- if (arg === "--") {
443
- continue;
444
- }
445
- if (arg === "--dangerously-skip-permissions") {
446
- continue;
447
- }
448
- if (arg === "--model" || arg === "-m") {
449
- index += 1;
450
- continue;
491
+ async function uploadSessionSnapshot(sessionID, result) {
492
+ let payload;
493
+ try {
494
+ await refreshSessionMetadata(sessionID);
495
+ payload = recorder.snapshotSession(sessionID, result, Date.now());
496
+ } catch (error) {
497
+ await log("error", "Agent Debugger session snapshot failed", { sessionID, result, error: String(error) });
498
+ return true;
451
499
  }
452
- if (arg.startsWith("--model=")) {
453
- continue;
500
+ if (!payload) {
501
+ await debugLog("No payload produced during session snapshot", { sessionID, result });
502
+ return true;
454
503
  }
455
- if (arg.startsWith("-")) {
456
- continue;
504
+ await debugLog("Prepared Agent Debugger session snapshot", {
505
+ sessionID,
506
+ result,
507
+ interactions: Array.isArray(payload.interactions) ? payload.interactions.length : 0,
508
+ steps: Array.isArray(payload.interactions) ? payload.interactions.reduce((total, interaction) => total + (Array.isArray(interaction.steps) ? interaction.steps.length : 0), 0) : 0,
509
+ project: payload.project,
510
+ });
511
+ try {
512
+ await uploadPayload(payload, sessionID, result);
513
+ } catch (error) {
514
+ if (error instanceof UploadInterruptedError) {
515
+ await debugLog("Agent Debugger upload interrupted", { sessionID, result, error: error.message });
516
+ return false;
517
+ }
518
+ throw error;
457
519
  }
458
- promptParts.push(arg);
520
+ return true;
459
521
  }
460
- return promptParts.join(" ").trim();
461
- }
462
522
 
463
- function messageShape(event) {
464
- const info = event && typeof event === "object" ? event.info ?? event.properties?.info : null;
465
- if (!info || typeof info !== "object") {
466
- return { eventKeys: Object.keys(event || {}) };
523
+ // Snapshots of one session upload in order, so an older snapshot can never
524
+ // overwrite a newer one. The task builds its payload when it runs. A snapshot
525
+ // that was cut off by shutdown stays in `unfinishedUploads` for the cleanup
526
+ // function to retry.
527
+ function scheduleSnapshot(sessionID, result) {
528
+ const scheduled = { result };
529
+ unfinishedUploads.set(sessionID, scheduled);
530
+ const previous = uploadQueues.get(sessionID) || Promise.resolve();
531
+ const run = previous
532
+ .catch(() => {})
533
+ .then(() => uploadSessionSnapshot(sessionID, result))
534
+ .then((settled) => {
535
+ if (settled && unfinishedUploads.get(sessionID) === scheduled) {
536
+ unfinishedUploads.delete(sessionID);
537
+ }
538
+ })
539
+ .catch((error) => log("error", "Agent Debugger session upload failed", { sessionID, result, error: String(error) }))
540
+ .then(() => {
541
+ pendingUploads.delete(run);
542
+ if (uploadQueues.get(sessionID) === run) {
543
+ uploadQueues.delete(sessionID);
544
+ }
545
+ });
546
+ uploadQueues.set(sessionID, run);
547
+ pendingUploads.add(run);
467
548
  }
468
- return {
469
- eventKeys: Object.keys(event || {}),
470
- infoKeys: Object.keys(info),
471
- tokenKeys: info.tokens && typeof info.tokens === "object" ? Object.keys(info.tokens) : [],
472
- usageKeys: info.usage && typeof info.usage === "object" ? Object.keys(info.usage) : [],
473
- metadataKeys: info.metadata && typeof info.metadata === "object" ? Object.keys(info.metadata) : [],
474
- responseKeys: info.response && typeof info.response === "object" ? Object.keys(info.response) : [],
475
- hasTitle: Boolean(info.title || info.name || info.summary),
476
- };
477
- }
478
549
 
479
- return {
480
- event: async ({ event }) => {
481
- await logInit();
482
- if (!event || typeof event !== "object") {
550
+ // OpenCode stops the subprocesses a plugin started before it runs the cleanup
551
+ // function, but subprocesses started from cleanup run normally. This sends
552
+ // each cut-off snapshot directly, without the usual auth check, because the
553
+ // server is shutting down. An unauthenticated request fails and is logged.
554
+ async function retryInterruptedUploads() {
555
+ if (unfinishedUploads.size === 0) {
483
556
  return;
484
557
  }
558
+ const waiting = [...unfinishedUploads];
559
+ await debugLog("Retrying snapshots interrupted by shutdown", { sessions: waiting.map(([sessionID]) => sessionID) });
560
+ await Promise.allSettled(
561
+ waiting.map(async ([sessionID, { result }]) => {
562
+ try {
563
+ if (!(await uploadEnabled())) {
564
+ return;
565
+ }
566
+ const payload = recorder.snapshotSession(sessionID, result, Date.now());
567
+ if (!payload) {
568
+ return;
569
+ }
570
+ const response = await uploadAgentDebuggerPayload(payload);
571
+ await log(response.ok ? "info" : "warn", response.ok ? "Agent Debugger session uploaded" : "Agent Debugger upload failed", {
572
+ sessionID,
573
+ result,
574
+ retried: true,
575
+ status: response.status,
576
+ });
577
+ if (!response.ok) {
578
+ await uploadPayloadToLocal(payload, sessionID, result, "cloud_upload_failed");
579
+ }
580
+ } catch (error) {
581
+ await log("warn", "Agent Debugger upload retry failed", { sessionID, result, ...commandFailure(error), error: String(error) });
582
+ const payload = recorder.snapshotSession(sessionID, result, Date.now());
583
+ if (payload) await uploadPayloadToLocal(payload, sessionID, result, "cloud_upload_error");
584
+ }
585
+ }),
586
+ );
587
+ unfinishedUploads.clear();
588
+ }
485
589
 
486
- if (event.type === "command.executed") {
487
- const invocation = extractDistlangInvocation(event);
488
- if (invocation) {
489
- await handleDistlangCommand(invocation, "command.executed");
490
- }
590
+ async function finishExecution(sessionID, result, type) {
591
+ if (!sessionID) {
491
592
  return;
492
593
  }
493
-
494
-
495
- if (event.type === "session.created") {
496
- const observed = recorder.observeSessionCreated(event);
497
- if (observed) {
498
- await debugLog("session.created observed", observed);
499
- }
594
+ // A failed execution always uploads so the error status is not lost. Other
595
+ // end events only upload when something changed since the last snapshot,
596
+ // because session.execution.succeeded and session.idle both arrive.
597
+ if (result !== "error" && !bridge.consumeDirty(sessionID)) {
598
+ await debugLog(`${type} observed without new session data`, { sessionID });
500
599
  return;
501
600
  }
601
+ bridge.consumeDirty(sessionID);
602
+ await debugLog(`${type} observed`, { sessionID, result });
603
+ scheduleSnapshot(sessionID, result);
604
+ }
502
605
 
503
- if (event.type === "session.updated") {
504
- const observed = recorder.observeSessionUpdated(event);
505
- if (observed) {
506
- await debugLog("session.updated observed", observed);
507
- }
508
- return;
606
+ async function handleEvent(event) {
607
+ await logInit();
608
+ const data = event.data || {};
609
+ switch (event.type) {
610
+ case "session.created":
611
+ bridge.sessionCreated(event);
612
+ return;
613
+ case "session.renamed":
614
+ bridge.sessionRenamed(event);
615
+ return;
616
+ case "session.deleted":
617
+ bridge.sessionDeleted(event);
618
+ return;
619
+ case "session.step.started":
620
+ bridge.stepStarted(event);
621
+ return;
622
+ case "session.step.first-token":
623
+ bridge.stepFirstToken(event);
624
+ return;
625
+ case "session.text.ended":
626
+ bridge.textEnded(event);
627
+ await debugLog("session.text.ended observed", { sessionID: data.sessionID });
628
+ return;
629
+ case "session.step.ended":
630
+ case "session.step.failed": {
631
+ const failed = event.type === "session.step.failed";
632
+ const observed = failed ? bridge.stepFailed(event) : bridge.stepEnded(event);
633
+ if (observed) {
634
+ bridge.consumeDirty(data.sessionID);
635
+ await debugLog(failed ? "assistant step failed" : "assistant step finalized", observed);
636
+ scheduleSnapshot(observed.sessionID, "success");
637
+ }
638
+ return;
639
+ }
640
+ case "session.execution.succeeded":
641
+ await finishExecution(data.sessionID, "success", event.type);
642
+ return;
643
+ case "session.execution.failed":
644
+ await finishExecution(data.sessionID, "error", event.type);
645
+ return;
646
+ case "session.execution.interrupted":
647
+ await finishExecution(data.sessionID, "success", event.type);
648
+ return;
649
+ case "session.idle":
650
+ await finishExecution(data.sessionID, "success", event.type);
651
+ return;
652
+ default:
509
653
  }
654
+ }
510
655
 
511
-
512
-
513
- if (event.type === "session.idle" || event.type === "session.error") {
514
- const sessionID = configuredValue(event.sessionID, recorder.activeSessionID());
515
- if (!sessionID) {
516
- await debugLog("Session snapshot event missing sessionID", { type: event.type, eventKeys: Object.keys(event) });
517
- return;
518
- }
519
- const result = event.type === "session.error" ? "error" : "success";
520
- await debugLog(`${event.type} observed`, { sessionID, result });
521
- await uploadSessionSnapshot(sessionID, result);
522
- return;
523
- }
524
-
525
- if (event.type === "file.edited") {
526
- const observed = recorder.observeFileEdited(event);
527
- if (observed) {
528
- await debugLog("file.edited observed", observed);
529
- }
530
- return;
531
- }
532
-
533
- if (event.type === "message.part.updated") {
534
- const observed = recorder.observeMessagePartUpdated(event);
535
- if (observed) {
536
- await debugLog("message.part.updated observed", observed);
537
- }
538
- return;
539
- }
540
-
541
- if (event.type !== "message.updated") {
542
- return;
543
- }
544
-
545
- const userMessage = recorder.observeUserMessage(event);
546
- if (userMessage) {
547
- await debugLog("user message observed", userMessage);
548
- return;
549
- }
550
-
551
- const assistantMessage = recorder.observeAssistantMessage(event);
552
- if (assistantMessage) {
553
- await debugLog("assistant message update observed", { ...assistantMessage, shape: messageShape(event) });
554
- if (assistantMessage.finalized) {
555
- await uploadSessionSnapshot(assistantMessage.sessionID, "success");
556
- }
557
- }
558
- },
559
-
560
- "tui.command.execute": async (input) => {
561
- await logInit();
562
- const invocation = extractDistlangInvocation(input);
563
- if (!invocation) {
564
- return;
656
+ // The event stream is server-wide. Only record sessions that belong to the
657
+ // directory this plugin instance was loaded for.
658
+ function canonicalDirectory(directory) {
659
+ const cached = knownDirectories.get(directory);
660
+ if (cached) {
661
+ return cached;
565
662
  }
566
- await handleDistlangCommand(invocation, "tui.command.execute");
567
- },
663
+ let canonical = path.resolve(directory);
664
+ try {
665
+ canonical = realpathSync(directory);
666
+ } catch {
667
+ // Keep the resolved path when the directory does not exist yet.
668
+ }
669
+ knownDirectories.set(directory, canonical);
670
+ return canonical;
671
+ }
568
672
 
569
- "command.execute.before": async (input, output) => {
570
- await logInit();
571
- const invocation = extractDistlangInvocation(input);
572
- if (!invocation) {
573
- return;
673
+ function belongsHere(event) {
674
+ const directory = event.location?.directory;
675
+ if (typeof directory !== "string" || !directory) {
676
+ return knownSessions.has(event.data?.sessionID);
574
677
  }
575
- await handleDistlangCommand(invocation, "command.execute.before");
576
- output.parts = [];
577
- },
678
+ const matches = canonicalDirectory(directory) === pluginDirectory;
679
+ if (matches && event.data?.sessionID) knownSessions.add(event.data.sessionID);
680
+ return matches;
681
+ }
578
682
 
579
- "tool.execute.before": async (input) => {
580
- await logInit();
581
- const observed = recorder.observeToolBefore(input);
683
+ const pluginDirectory = canonicalDirectory(ctx.location.directory);
684
+
685
+ await ctx.tool.hook("execute.before", (event) => {
686
+ knownSessions.add(event.sessionID);
687
+ const observed = bridge.toolBefore(event);
582
688
  if (observed) {
583
- await debugLog("tool.execute.before observed", observed);
689
+ void debugLog("tool.execute.before observed", observed);
584
690
  }
585
- },
586
-
587
- "tool.execute.after": async (input, output) => {
588
- await logInit();
589
- const observed = recorder.observeToolAfter(input, output);
691
+ });
692
+ await ctx.tool.hook("execute.after", (event) => {
693
+ knownSessions.add(event.sessionID);
694
+ const observed = bridge.toolAfter(event);
590
695
  if (observed) {
591
- await debugLog("tool.execute.after observed", observed);
696
+ void debugLog("tool.execute.after observed", { ...observed, status: event.status });
592
697
  }
593
- },
594
-
595
- "experimental.chat.system.transform": async (input, output) => {
596
- await logInit();
597
- const sessionID = configuredValue(input && input.sessionID, recorder.activeSessionID());
598
- const observed = recorder.observeSystemPrompt(sessionID, output && output.system);
698
+ });
699
+ await ctx.session.hook("prompt", (event) => {
700
+ knownSessions.add(event.sessionID);
701
+ void logInit();
702
+ const observed = bridge.prompt(event);
599
703
  if (observed) {
600
- await debugLog("experimental.chat.system.transform observed", observed);
704
+ void debugLog("user message observed", observed);
601
705
  }
602
- },
603
- };
604
- };
706
+ });
707
+ await ctx.session.hook("context", (event) => {
708
+ knownSessions.add(event.sessionID);
709
+ void logInit();
710
+ const observed = bridge.context(event);
711
+ if (observed) {
712
+ void debugLog("session context observed", observed);
713
+ }
714
+ });
715
+
716
+ await ctx.command.transform((editor) => {
717
+ for (const command of distlangCommands) {
718
+ editor.add({
719
+ name: command.name,
720
+ description: command.description,
721
+ execute: ({ prompt }) => runCommand(commandInvocation(command, prompt?.text), command.name),
722
+ });
723
+ }
724
+ editor.add({
725
+ name: "distlang",
726
+ description: "Manage Distlang Agent Debugger uploads (status, start, stop, view)",
727
+ execute: ({ prompt }) => runCommand(legacyCommandInvocation(prompt?.text), "distlang"),
728
+ });
729
+ });
730
+
731
+ void (async () => {
732
+ while (!controller.signal.aborted) {
733
+ try {
734
+ for await (const event of ctx.event.subscribe({ types: recordedEventTypes, signal: controller.signal })) {
735
+ if (!belongsHere(event)) {
736
+ continue;
737
+ }
738
+ try {
739
+ await handleEvent(event);
740
+ } catch (error) {
741
+ await log("error", "Agent Debugger event handling failed", { type: event.type, error: String(error) });
742
+ }
743
+ }
744
+ } catch (error) {
745
+ if (controller.signal.aborted) {
746
+ return;
747
+ }
748
+ await log("warn", "OpenCode event stream ended; resubscribing", { error: String(error) });
749
+ }
750
+ if (controller.signal.aborted) {
751
+ return;
752
+ }
753
+ await sleep(2000);
754
+ }
755
+ })();
605
756
 
606
- export default DistlangAgentDebugger;
757
+ await logInit();
758
+
759
+ return async () => {
760
+ const waiting = pendingUploads.size;
761
+ await debugLog("Plugin unloading", { pendingUploads: waiting });
762
+ controller.abort();
763
+ await Promise.allSettled([...pendingUploads]);
764
+ await retryInterruptedUploads();
765
+ await debugLog("Plugin cleanup finished", { pendingUploads: waiting });
766
+ };
767
+ },
768
+ });