@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/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,582 +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
114
 
73
- async function uploadEnabled() {
74
- const state = await readPluginState();
75
- return state.enabled !== false;
76
- }
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
+ });
126
+ }
77
127
 
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(() => {});
128
+ async function uploadEnabled() {
129
+ const state = await readPluginState();
130
+ return state.enabled !== false;
91
131
  }
92
- }
93
132
 
94
- function dashboardBaseUrl() {
95
- return configuredValue(process.env.DISTLANG_DASHBOARD_URL, "https://dash.distlang.com").replace(/\/+$/, "");
96
- }
133
+ async function logCommandResult(level, message, extra = undefined) {
134
+ await log(level, message, extra);
135
+ }
97
136
 
98
- function sessionUrl(sessionID) {
99
- const id = configuredValue(sessionID, "");
100
- return id ? `${dashboardBaseUrl()}/agent-debugger/sessions/${encodeURIComponent(id)}` : "";
101
- }
137
+ function dashboardBaseUrl() {
138
+ return configuredValue(process.env.DISTLANG_DASHBOARD_URL, "https://dash.distlang.com").replace(/\/+$/, "");
139
+ }
102
140
 
103
- function openerCommand() {
104
- if (process.platform === "darwin") return { command: "open", args: [] };
105
- if (process.platform === "win32") return { command: "cmd", args: ["/c", "start", ""] };
106
- return { command: "xdg-open", args: [] };
107
- }
141
+ function sessionUrl(sessionID) {
142
+ const id = configuredValue(sessionID, "");
143
+ return id ? `${dashboardBaseUrl()}/agent-debugger/sessions/${encodeURIComponent(id)}` : "";
144
+ }
108
145
 
109
- function openUrl(url) {
110
- const { command, args } = openerCommand();
111
- return new Promise((resolve) => {
112
- try {
113
- const child = spawn(command, [...args, url], { detached: true, stdio: "ignore" });
114
- child.on("error", () => resolve(false));
115
- child.unref();
116
- resolve(true);
117
- } catch {
118
- resolve(false);
119
- }
120
- });
121
- }
146
+ function agentDebuggerUrl() {
147
+ return `${dashboardBaseUrl()}/agent-debugger`;
148
+ }
122
149
 
123
- function commandArgument(invocation, action) {
124
- const args = Array.isArray(invocation?.args) ? invocation.args : [];
125
- if (configuredValue(invocation?.action, "")) {
126
- 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: [] };
127
154
  }
128
- return configuredValue(args[0], "").toLowerCase() === action ? configuredValue(args[1], "") : configuredValue(args[0], "");
129
- }
130
155
 
131
- function sessionsFromResponse(response) {
132
- const candidates = [
133
- response?.body?.sessions,
134
- response?.sessions,
135
- response?.body?.data?.sessions,
136
- response?.data?.sessions,
137
- response?.body?.items,
138
- response?.items,
139
- ];
140
- for (const candidate of candidates) {
141
- 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
+ });
142
168
  }
143
- return [];
144
- }
145
169
 
146
- function firstSessionID(response) {
147
- for (const session of sessionsFromResponse(response)) {
148
- const id = configuredValue(session?.id, configuredValue(session?.session_id, ""));
149
- 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], "");
150
176
  }
151
- return "";
152
- }
153
177
 
154
- async function ensureCommandAuth(source, action, state = null, resolved = null) {
155
- let auth = await getAuthStatus();
156
- if (!auth || auth.ok !== true || auth.logged_in !== true) {
157
- await maybeLogCommandResult("info", "Opening browser for Distlang login", { source, action, state, distlang: resolved });
158
- await loginWithDistlang();
159
- 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 [];
160
191
  }
161
- return auth;
162
- }
163
192
 
164
- async function handleDistlangCommand(invocation, source) {
165
- const now = Date.now();
166
- if (now - commandHandledAt < 250) {
167
- 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 "";
168
199
  }
169
- commandHandledAt = now;
170
- const requestedAction = configuredValue(invocation.action, configuredValue(invocation.args[0], "status")).toLowerCase();
171
- const action = requestedAction === "login" ? "start" : requestedAction === "logout" ? "stop" : requestedAction;
172
- if (!["status", "start", "stop", "view"].includes(action)) {
173
- await maybeLogCommandResult("warn", "Unknown Distlang command. Use /distlang-status, /distlang-start, /distlang-stop, or /distlang-view", {
174
- source,
175
- action: requestedAction,
176
- command_hint: "/distlang-status | /distlang-start | /distlang-stop | /distlang-view",
177
- });
178
- 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;
179
209
  }
180
- if (action === "start") {
181
- const state = await writePluginState(true);
182
- authWarningLogged = false;
183
- let resolved = null;
184
- let auth = null;
185
- try {
186
- resolved = await resolveDistlangBinary({ installIfMissing: true });
187
- } catch (error) {
188
- 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
+ });
189
220
  return;
190
221
  }
191
- try {
192
- auth = await ensureCommandAuth(source, action, state, resolved);
193
- } catch (error) {
194
- 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
+ });
195
246
  return;
196
247
  }
197
- await maybeLogCommandResult("info", "Distlang Agent Debugger uploads enabled", {
198
- source,
199
- action,
200
- state,
201
- distlang: resolved,
202
- auth,
203
- });
204
- return;
205
- }
206
248
 
207
- if (action === "stop") {
208
- const state = await writePluginState(false);
209
- authWarningLogged = false;
210
- try {
211
- const resolved = await resolveDistlangBinary({ installIfMissing: true });
212
- await logoutWithDistlang();
213
- await maybeLogCommandResult("info", "Distlang Agent Debugger uploads disabled and signed out", { source, action, state, distlang: resolved });
214
- } catch (error) {
215
- 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;
216
260
  }
217
- return;
218
- }
219
261
 
220
- if (action === "view") {
221
- const state = await readPluginState();
222
- let resolved = null;
223
- let auth = null;
224
- let sessions = null;
225
- try {
226
- resolved = await resolveDistlangBinary({ installIfMissing: true });
227
- auth = await ensureCommandAuth(source, action, state, resolved);
228
- sessions = await fetchAgentDebuggerSessions();
229
- } catch (error) {
230
- 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
+ });
231
291
  return;
232
292
  }
233
- const sessionID = commandArgument(invocation, action) || firstSessionID(sessions);
234
- const url = sessionUrl(sessionID);
235
- if (!url) {
236
- await maybeLogCommandResult("warn", "No uploaded OpenCode Agent Debugger session found yet", {
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}`, {
237
326
  source,
238
327
  action,
239
328
  state,
240
329
  distlang: resolved,
241
330
  auth,
331
+ session_id: sessionID,
332
+ url,
333
+ opened,
242
334
  sessions,
243
- command_hint: "Run a prompt first, wait for upload, then run /distlang-view again",
244
335
  });
245
336
  return;
246
337
  }
247
- const opened = await openUrl(url);
248
- 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", {
249
352
  source,
250
353
  action,
251
354
  state,
252
355
  distlang: resolved,
253
356
  auth,
254
- session_id: sessionID,
255
- url,
256
- opened,
257
357
  sessions,
358
+ error: resolutionError,
359
+ command_hint: "/distlang-status | /distlang-start | /distlang-stop | /distlang-view",
258
360
  });
259
- return;
260
361
  }
261
362
 
262
- const state = await readPluginState();
263
- let resolved = null;
264
- let auth = null;
265
- let sessions = null;
266
- let resolutionError = null;
267
- try {
268
- resolved = await resolveDistlangBinary({ installIfMissing: true });
269
- auth = await getAuthStatus();
270
- sessions = await fetchAgentDebuggerSessions();
271
- } catch (error) {
272
- 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
+ }
273
370
  }
274
- await maybeLogCommandResult("info", "Distlang Agent Debugger status", {
275
- source,
276
- action,
277
- state,
278
- distlang: resolved,
279
- auth,
280
- sessions,
281
- error: resolutionError,
282
- command_hint: "/distlang-status | /distlang-start | /distlang-stop | /distlang-view",
283
- });
284
- }
285
371
 
286
- async function ensureAuthStatus() {
287
- if (!(await uploadEnabled())) {
288
- await debugLog("Distlang Agent Debugger uploads are disabled", { state: await readPluginState() });
289
- return false;
290
- }
291
- try {
292
- const resolved = await resolveDistlangBinary({ installIfMissing: true });
293
- const payload = await getAuthStatus();
294
- const authAvailable = payload && payload.ok === true && payload.logged_in === true;
295
- await debugLog("Distlang auth status resolved", { authAvailable, payload, distlang: resolved });
296
- if (!authAvailable && !authWarningLogged) {
297
- authWarningLogged = true;
298
- await maybeLogCommandResult("warn", "Distlang Agent Debugger upload disabled: run `/distlang-start` to sign in and enable uploads", {
299
- auth: payload,
300
- command_hint: "/distlang-start",
301
- });
302
- } else if (authAvailable) {
303
- authWarningLogged = false;
304
- }
305
- return authAvailable;
306
- } catch (error) {
307
- if (error && typeof error === "object" && error.code === "ENOENT") {
308
- if (!distlangMissingLogged) {
309
- distlangMissingLogged = true;
310
- 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;
311
381
  }
312
- } else if (!authWarningLogged) {
313
- authWarningLogged = true;
314
- await log("warn", "Distlang Agent Debugger auth check failed; upload disabled", { error: String(error) });
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 });
386
+ }
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;
315
398
  }
316
- return false;
317
399
  }
318
- }
319
400
 
320
- async function finalizeSession(sessionID, result) {
321
- let payload;
322
- try {
323
- await refreshSessionMetadata(sessionID, { retry: true });
324
- payload = recorder.finalizeSession(sessionID, result, Date.now());
325
- } catch (error) {
326
- await log("error", "Agent Debugger session finalization failed", { sessionID, result, error: String(error) });
327
- return;
328
- }
329
- if (!payload) {
330
- await debugLog("No payload produced during session finalization", { sessionID, result });
331
- return;
332
- }
333
- await debugLog("Finalized Agent Debugger session payload", {
334
- sessionID,
335
- result,
336
- interactions: Array.isArray(payload.interactions) ? payload.interactions.length : 0,
337
- steps: Array.isArray(payload.interactions) ? payload.interactions.reduce((total, interaction) => total + (Array.isArray(interaction.steps) ? interaction.steps.length : 0), 0) : 0,
338
- project: payload.project,
339
- });
340
- if (!(await ensureAuthStatus())) {
341
- await debugLog("Skipping AI debugger upload because auth is unavailable", { sessionID });
342
- return;
343
- }
344
- try {
345
- const response = await uploadAgentDebuggerPayload(payload);
346
- 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 });
347
429
  if (!response.ok) {
348
- await log("warn", "Agent Debugger upload failed", { sessionID, response });
349
- return;
430
+ await log("warn", "Agent Debugger upload failed", { sessionID, result, response });
431
+ return (await uploadPayloadToLocal(payload, sessionID, result, "cloud_upload_failed")) ? "local" : "failed";
350
432
  }
351
- await debugLog("Agent Debugger session uploaded", { sessionID, response });
352
- } catch (error) {
353
- await log("warn", "Agent Debugger upload failed", { sessionID, error: String(error) });
433
+ await debugLog("Agent Debugger session uploaded", { sessionID, result, response });
434
+ return "uploaded";
354
435
  }
355
- }
356
436
 
357
- async function uploadSessionSnapshot(sessionID, result = "success") {
358
- let payload;
359
- try {
360
- await refreshSessionMetadata(sessionID, { retry: true });
361
- payload = recorder.snapshotSession(sessionID, result, Date.now());
362
- } catch (error) {
363
- await log("error", "Agent Debugger session snapshot failed", { sessionID, result, error: String(error) });
364
- return;
365
- }
366
- if (!payload) {
367
- await debugLog("No payload produced during session snapshot", { sessionID, result });
368
- return;
369
- }
370
- await debugLog("Prepared Agent Debugger session snapshot", {
371
- sessionID,
372
- result,
373
- interactions: Array.isArray(payload.interactions) ? payload.interactions.length : 0,
374
- steps: Array.isArray(payload.interactions) ? payload.interactions.reduce((total, interaction) => total + (Array.isArray(interaction.steps) ? interaction.steps.length : 0), 0) : 0,
375
- project: payload.project,
376
- });
377
- if (!(await ensureAuthStatus())) {
378
- await debugLog("Skipping AI debugger snapshot upload because auth is unavailable", { sessionID });
379
- return;
380
- }
381
- try {
382
- const response = await uploadAgentDebuggerPayload(payload);
383
- await debugLog("Agent Debugger snapshot upload response received", { sessionID, response });
384
- if (!response.ok) {
385
- await log("warn", "Agent Debugger snapshot upload failed", { sessionID, response });
386
- 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;
387
471
  }
388
- await debugLog("Agent Debugger session snapshot uploaded", { sessionID, response });
389
- } catch (error) {
390
- await log("warn", "Agent Debugger snapshot upload failed", { sessionID, error: String(error) });
391
472
  }
392
- }
393
473
 
394
- async function refreshSessionMetadata(sessionID, options = {}) {
395
- if (!sessionID || !client?.session || typeof client.session.get !== "function") {
396
- return;
397
- }
398
- const attempts = options.retry ? 3 : 1;
399
- 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
+ }
400
478
  try {
401
- const response = await client.session.get({ path: { id: sessionID } });
402
- const session = response?.data ?? response;
479
+ const session = await ctx.session.get({ sessionID });
403
480
  const title = extractSessionTitle(session);
404
- await debugLog("OpenCode session metadata inspected", { sessionID, attempt, sessionKeys: session && typeof session === "object" ? Object.keys(session) : [] });
405
481
  if (title) {
482
+ bridge.setTitle(sessionID, title);
406
483
  recorder.setSessionTitle(sessionID, title);
407
- await debugLog("OpenCode session metadata refreshed", { sessionID, attempt, titleLength: title.length });
408
- return;
484
+ await debugLog("OpenCode session metadata refreshed", { sessionID, titleLength: title.length });
409
485
  }
410
486
  } catch (error) {
411
- await debugLog("OpenCode session metadata refresh failed", { sessionID, attempt, error: String(error) });
412
- }
413
- if (attempt < attempts) {
414
- await sleep(500);
487
+ await debugLog("OpenCode session metadata refresh failed", { sessionID, error: String(error) });
415
488
  }
416
489
  }
417
- }
418
-
419
- function sleep(ms) {
420
- return new Promise((resolve) => setTimeout(resolve, ms));
421
- }
422
490
 
423
- function extractOpenCodeRunPrompt(argv) {
424
- const args = Array.isArray(argv) ? argv : [];
425
- const runIndex = args.findIndex((arg) => arg === "run");
426
- if (runIndex < 0) {
427
- return "";
428
- }
429
- const promptParts = [];
430
- for (let index = runIndex + 1; index < args.length; index += 1) {
431
- const arg = configuredValue(args[index], "");
432
- if (!arg) {
433
- continue;
434
- }
435
- if (arg === "--") {
436
- continue;
437
- }
438
- if (arg === "--dangerously-skip-permissions") {
439
- continue;
440
- }
441
- if (arg === "--model" || arg === "-m") {
442
- index += 1;
443
- 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;
444
499
  }
445
- if (arg.startsWith("--model=")) {
446
- continue;
500
+ if (!payload) {
501
+ await debugLog("No payload produced during session snapshot", { sessionID, result });
502
+ return true;
447
503
  }
448
- if (arg.startsWith("-")) {
449
- 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;
450
519
  }
451
- promptParts.push(arg);
520
+ return true;
452
521
  }
453
- return promptParts.join(" ").trim();
454
- }
455
522
 
456
- function messageShape(event) {
457
- const info = event && typeof event === "object" ? event.info ?? event.properties?.info : null;
458
- if (!info || typeof info !== "object") {
459
- 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);
460
548
  }
461
- return {
462
- eventKeys: Object.keys(event || {}),
463
- infoKeys: Object.keys(info),
464
- tokenKeys: info.tokens && typeof info.tokens === "object" ? Object.keys(info.tokens) : [],
465
- usageKeys: info.usage && typeof info.usage === "object" ? Object.keys(info.usage) : [],
466
- metadataKeys: info.metadata && typeof info.metadata === "object" ? Object.keys(info.metadata) : [],
467
- responseKeys: info.response && typeof info.response === "object" ? Object.keys(info.response) : [],
468
- hasTitle: Boolean(info.title || info.name || info.summary),
469
- };
470
- }
471
549
 
472
- return {
473
- event: async ({ event }) => {
474
- await logInit();
475
- 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) {
476
556
  return;
477
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
+ }
478
589
 
479
- if (event.type === "command.executed") {
480
- const invocation = extractDistlangInvocation(event);
481
- if (invocation) {
482
- await handleDistlangCommand(invocation, "command.executed");
483
- }
590
+ async function finishExecution(sessionID, result, type) {
591
+ if (!sessionID) {
484
592
  return;
485
593
  }
486
-
487
-
488
- if (event.type === "session.created") {
489
- const observed = recorder.observeSessionCreated(event);
490
- if (observed) {
491
- await debugLog("session.created observed", observed);
492
- }
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 });
493
599
  return;
494
600
  }
601
+ bridge.consumeDirty(sessionID);
602
+ await debugLog(`${type} observed`, { sessionID, result });
603
+ scheduleSnapshot(sessionID, result);
604
+ }
495
605
 
496
- if (event.type === "session.updated") {
497
- const observed = recorder.observeSessionUpdated(event);
498
- if (observed) {
499
- await debugLog("session.updated observed", observed);
500
- }
501
- 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:
502
653
  }
654
+ }
503
655
 
504
-
505
-
506
- if (event.type === "session.idle" || event.type === "session.error") {
507
- const sessionID = configuredValue(event.sessionID, recorder.activeSessionID());
508
- if (!sessionID) {
509
- await debugLog("Session snapshot event missing sessionID", { type: event.type, eventKeys: Object.keys(event) });
510
- return;
511
- }
512
- const result = event.type === "session.error" ? "error" : "success";
513
- await debugLog(`${event.type} observed`, { sessionID, result });
514
- await uploadSessionSnapshot(sessionID, result);
515
- return;
516
- }
517
-
518
- if (event.type === "file.edited") {
519
- const observed = recorder.observeFileEdited(event);
520
- if (observed) {
521
- await debugLog("file.edited observed", observed);
522
- }
523
- return;
524
- }
525
-
526
- if (event.type === "message.part.updated") {
527
- const observed = recorder.observeMessagePartUpdated(event);
528
- if (observed) {
529
- await debugLog("message.part.updated observed", observed);
530
- }
531
- return;
532
- }
533
-
534
- if (event.type !== "message.updated") {
535
- return;
536
- }
537
-
538
- const userMessage = recorder.observeUserMessage(event);
539
- if (userMessage) {
540
- await debugLog("user message observed", userMessage);
541
- return;
542
- }
543
-
544
- const assistantMessage = recorder.observeAssistantMessage(event);
545
- if (assistantMessage) {
546
- await debugLog("assistant message update observed", { ...assistantMessage, shape: messageShape(event) });
547
- if (assistantMessage.finalized) {
548
- await uploadSessionSnapshot(assistantMessage.sessionID, "success");
549
- }
550
- }
551
- },
552
-
553
- "tui.command.execute": async (input) => {
554
- await logInit();
555
- const invocation = extractDistlangInvocation(input);
556
- if (!invocation) {
557
- 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;
558
662
  }
559
- await handleDistlangCommand(invocation, "tui.command.execute");
560
- },
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
+ }
561
672
 
562
- "command.execute.before": async (input, output) => {
563
- await logInit();
564
- const invocation = extractDistlangInvocation(input);
565
- if (!invocation) {
566
- return;
673
+ function belongsHere(event) {
674
+ const directory = event.location?.directory;
675
+ if (typeof directory !== "string" || !directory) {
676
+ return knownSessions.has(event.data?.sessionID);
567
677
  }
568
- await handleDistlangCommand(invocation, "command.execute.before");
569
- output.parts = [];
570
- },
678
+ const matches = canonicalDirectory(directory) === pluginDirectory;
679
+ if (matches && event.data?.sessionID) knownSessions.add(event.data.sessionID);
680
+ return matches;
681
+ }
571
682
 
572
- "tool.execute.before": async (input) => {
573
- await logInit();
574
- 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);
575
688
  if (observed) {
576
- await debugLog("tool.execute.before observed", observed);
689
+ void debugLog("tool.execute.before observed", observed);
577
690
  }
578
- },
579
-
580
- "tool.execute.after": async (input, output) => {
581
- await logInit();
582
- 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);
583
695
  if (observed) {
584
- await debugLog("tool.execute.after observed", observed);
696
+ void debugLog("tool.execute.after observed", { ...observed, status: event.status });
585
697
  }
586
- },
587
-
588
- "experimental.chat.system.transform": async (input, output) => {
589
- await logInit();
590
- const sessionID = configuredValue(input && input.sessionID, recorder.activeSessionID());
591
- 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);
592
703
  if (observed) {
593
- await debugLog("experimental.chat.system.transform observed", observed);
704
+ void debugLog("user message observed", observed);
594
705
  }
595
- },
596
- };
597
- };
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
+ })();
598
756
 
599
- 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
+ });