@distlang/opencode-plugin 0.2.5 → 0.4.0

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