@distlang/opencode-plugin 0.1.12 → 0.1.14

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@distlang/opencode-plugin",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
4
4
  "description": "OpenCode plugin for Distlang AI Debugger",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/index.js CHANGED
@@ -457,6 +457,15 @@ export const DistlangAIDebugger = async ({ project, directory, client }) => {
457
457
  await debugLog("tool.execute.after observed", observed);
458
458
  }
459
459
  },
460
+
461
+ "experimental.chat.system.transform": async (input, output) => {
462
+ await logInit();
463
+ const sessionID = configuredValue(input && input.sessionID, recorder.activeSessionID());
464
+ const observed = recorder.observeSystemPrompt(sessionID, output && output.system);
465
+ if (observed) {
466
+ await debugLog("experimental.chat.system.transform observed", observed);
467
+ }
468
+ },
460
469
  };
461
470
  };
462
471
 
package/src/recorder.js CHANGED
@@ -34,6 +34,7 @@ const extensionLanguages = {
34
34
 
35
35
  export function createRecorder({ project, directory, initialPrompt = "" }) {
36
36
  const projectName = deriveProjectName(project, directory);
37
+ const initialMode = inferInteractionMode(initialPrompt);
37
38
  const configuredInitialPrompt = sanitizeDebuggerText(initialPrompt);
38
39
  const sessions = new Map();
39
40
 
@@ -58,6 +59,7 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
58
59
  summary: "",
59
60
  title: "",
60
61
  initialPrompt: configuredInitialPrompt,
62
+ initialMode,
61
63
  interactions: [],
62
64
  currentInteractionID: "",
63
65
  interactionCounter: 0,
@@ -68,12 +70,14 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
68
70
  messageInteractions: new Map(),
69
71
  toolStarts: new Map(),
70
72
  seenUserMessages: new Set(),
73
+ contextContributors: [],
74
+ systemContributors: [],
71
75
  };
72
76
  sessions.set(sessionID, recorder);
73
77
  return recorder;
74
78
  }
75
79
 
76
- function createInteraction(recorder, prompt, timestampMs, messageID = "") {
80
+ function createInteraction(recorder, prompt, timestampMs, messageID = "", mode = inferInteractionMode(prompt)) {
77
81
  recorder.interactionCounter += 1;
78
82
  const stableID = configuredValue(messageID, "");
79
83
  const interactionID = stableID ? `${recorder.id}:int:${safeID(stableID)}` : `${recorder.id}:int:${recorder.interactionCounter}`;
@@ -81,7 +85,7 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
81
85
  id: interactionID,
82
86
  index: recorder.interactionCounter,
83
87
  prompt: configuredValue(prompt, `OpenCode interaction ${recorder.interactionCounter}`),
84
- mode: "build",
88
+ mode,
85
89
  startedAtMs: timestampMs,
86
90
  endedAtMs: 0,
87
91
  status: "success",
@@ -97,24 +101,26 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
97
101
  return recorder.interactions.find((interaction) => interaction.id === interactionID) || null;
98
102
  }
99
103
 
100
- function ensureInteraction(recorder, timestampMs, prompt = "") {
104
+ function ensureInteraction(recorder, timestampMs, prompt = "", mode = inferInteractionMode(prompt)) {
101
105
  const current = findInteraction(recorder, recorder.currentInteractionID);
102
106
  if (current) {
103
107
  if (prompt && (!current.prompt || isGenericInteractionLabel(current.prompt))) {
104
108
  current.prompt = prompt;
105
109
  }
110
+ applyInteractionMode(current, mode);
106
111
  return current;
107
112
  }
108
- return createInteraction(recorder, configuredValue(prompt, recorder.initialPrompt), timestampMs);
113
+ return createInteraction(recorder, configuredValue(prompt, recorder.initialPrompt), timestampMs, "", mode === "plan" ? mode : recorder.initialMode);
109
114
  }
110
115
 
111
- function observeUserPrompt(recorder, messageID, prompt, timestampMs) {
116
+ function observeUserPrompt(recorder, messageID, prompt, timestampMs, mode = inferInteractionMode(prompt)) {
112
117
  const cleanPrompt = sanitizeDebuggerText(prompt);
113
118
  const existingID = recorder.messageInteractions.get(messageID);
114
119
  const existing = existingID ? findInteraction(recorder, existingID) : null;
115
120
  if (existing) {
116
121
  existing.prompt = cleanPrompt;
117
122
  existing.summary = summarizePrompt(cleanPrompt, existing.summary || `Interaction ${existing.index}`);
123
+ applyInteractionMode(existing, mode);
118
124
  return existing;
119
125
  }
120
126
  const current = findInteraction(recorder, recorder.currentInteractionID);
@@ -122,35 +128,42 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
122
128
  if (current && isGenericInteractionLabel(current.prompt) && !currentHasMessage) {
123
129
  current.prompt = cleanPrompt;
124
130
  current.summary = summarizePrompt(cleanPrompt, `Interaction ${current.index}`);
131
+ applyInteractionMode(current, mode);
125
132
  recorder.messageInteractions.set(messageID, current.id);
126
133
  recorder.seenUserMessages.add(messageID);
127
134
  return current;
128
135
  }
129
136
  if (recorder.seenUserMessages.has(messageID)) {
130
- return current || createInteraction(recorder, cleanPrompt, timestampMs);
137
+ if (current) {
138
+ applyInteractionMode(current, mode);
139
+ return current;
140
+ }
141
+ return createInteraction(recorder, cleanPrompt, timestampMs, "", mode);
131
142
  }
132
143
  recorder.seenUserMessages.add(messageID);
133
- const interaction = createInteraction(recorder, cleanPrompt, timestampMs, messageID);
144
+ const interaction = createInteraction(recorder, cleanPrompt, timestampMs, messageID, mode);
134
145
  recorder.messageInteractions.set(messageID, interaction.id);
135
146
  return interaction;
136
147
  }
137
148
 
138
- function interactionForMessage(recorder, messageID, fallbackTimestampMs, prompt = "") {
149
+ function interactionForMessage(recorder, messageID, fallbackTimestampMs, prompt = "", mode = inferInteractionMode(prompt)) {
139
150
  const interactionID = configuredValue(recorder.messageInteractions.get(messageID), "");
140
151
  const interaction = interactionID ? findInteraction(recorder, interactionID) : null;
141
152
  if (interaction) {
142
153
  if (prompt && (!interaction.prompt || isGenericInteractionLabel(interaction.prompt))) {
143
154
  interaction.prompt = prompt;
144
155
  }
156
+ applyInteractionMode(interaction, mode);
145
157
  return interaction;
146
158
  }
147
- return ensureInteraction(recorder, fallbackTimestampMs, prompt);
159
+ return ensureInteraction(recorder, fallbackTimestampMs, prompt, mode);
148
160
  }
149
161
 
150
162
  function addStep(recorder, interaction, step) {
151
163
  recorder.stepCounter += 1;
164
+ const stepID = `${recorder.id}:step:${recorder.stepCounter}`;
152
165
  const normalized = {
153
- id: `${recorder.id}:step:${recorder.stepCounter}`,
166
+ id: stepID,
154
167
  index: recorder.stepCounter,
155
168
  kind: step.kind,
156
169
  phase: configuredValue(step.phase, "build"),
@@ -171,6 +184,7 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
171
184
  first_token_at: step.first_token_at ? normalizeDateTime(step.first_token_at, new Date().toISOString()) : null,
172
185
  first_token_latency_ms: Math.max(0, Math.floor(finiteNumber(step.first_token_latency_ms))),
173
186
  payload_json: step.payload_json ?? null,
187
+ details: normalizeStepDetails(step.details, stepID, interaction.id),
174
188
  };
175
189
  interaction.steps.push(normalized);
176
190
  interaction.endedAtMs = Math.max(interaction.endedAtMs || 0, Date.parse(normalized.ended_at || normalized.started_at));
@@ -215,10 +229,10 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
215
229
  return null;
216
230
  }
217
231
  const recorder = ensureSession(sessionID, Date.now());
218
- const interaction = ensureInteraction(recorder, Date.now());
232
+ const interaction = ensureInteraction(recorder, Date.now(), "", inferInteractionMode(event));
219
233
  addStep(recorder, interaction, {
220
234
  kind: "file_edit",
221
- phase: "build",
235
+ phase: interaction.mode,
222
236
  title: `Edit ${filePath}`,
223
237
  started_at: new Date().toISOString(),
224
238
  ended_at: new Date().toISOString(),
@@ -237,11 +251,18 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
237
251
  const recorder = ensureSession(sessionID, Date.now());
238
252
  const id = messageID(info) || `${sessionID}:user:${Date.now()}`;
239
253
  recorder.messageRoles.set(id, "user");
254
+ const mode = inferInteractionMode(info, event);
240
255
  const prompt = extractMessageText(info) || storedMessageText(recorder, id);
241
256
  if (!prompt) {
242
257
  return { sessionID, messageID: id, prompt: "" };
243
258
  }
244
- const interaction = observeUserPrompt(recorder, id, prompt, parseMessageTime(info, Date.now()));
259
+ const interaction = observeUserPrompt(recorder, id, prompt, parseMessageTime(info, Date.now()), mode);
260
+ addContextContributor(recorder, {
261
+ category: "user_prompt",
262
+ label: `User prompt ${interaction.index}`,
263
+ source: "opencode.message",
264
+ text: prompt,
265
+ });
245
266
  return { sessionID, messageID: id, prompt: interaction.prompt };
246
267
  }
247
268
 
@@ -263,7 +284,7 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
263
284
  if (role !== "user") {
264
285
  return { sessionID, messageID, role: configuredValue(role, "unknown"), text };
265
286
  }
266
- const interaction = observeUserPrompt(recorder, messageID, storedMessageText(recorder, messageID), parsePartTime(part, Date.now()));
287
+ const interaction = observeUserPrompt(recorder, messageID, storedMessageText(recorder, messageID), parsePartTime(part, Date.now()), inferInteractionMode(part, event));
267
288
  return { sessionID, messageID, role, text: interaction.prompt };
268
289
  }
269
290
 
@@ -282,7 +303,10 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
282
303
  const parentID = messageParentID(info);
283
304
  const parentInteractionID = configuredValue(recorder.messageInteractions.get(parentID), "");
284
305
  const parentInteraction = parentInteractionID ? findInteraction(recorder, parentInteractionID) : null;
285
- const interaction = parentInteraction || interactionForMessage(recorder, id, Date.now());
306
+ const assistantText = extractMessageText(info) || storedMessageText(recorder, id);
307
+ const mode = inferInteractionMode(info, event, assistantText);
308
+ const interaction = parentInteraction || interactionForMessage(recorder, id, Date.now(), "", mode);
309
+ applyInteractionMode(interaction, mode);
286
310
  recorder.messageInteractions.set(id, interaction.id);
287
311
  const now = Date.now();
288
312
  const existing = recorder.assistantStates.get(id) || {
@@ -303,7 +327,7 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
303
327
  if (finalState.isFinal && !existing.finalized) {
304
328
  existing.finalized = true;
305
329
  const targetInteraction = findInteraction(recorder, existing.interactionID) || interaction;
306
- const assistantText = extractMessageText(info) || storedMessageText(recorder, id);
330
+ applyInteractionMode(targetInteraction, mode);
307
331
  addStep(recorder, targetInteraction, {
308
332
  kind: "llm_call",
309
333
  phase: targetInteraction.mode,
@@ -323,6 +347,13 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
323
347
  first_token_at: existing.firstTokenAt != null ? new Date(existing.firstTokenAt).toISOString() : null,
324
348
  first_token_latency_ms: existing.firstTokenAt != null ? Math.max(0, existing.firstTokenAt - existing.firstSeenAt) : 0,
325
349
  payload_json: { message_id: id },
350
+ details: buildLLMStepDetails(recorder, targetInteraction, id),
351
+ });
352
+ addContextContributor(recorder, {
353
+ category: "assistant_history",
354
+ label: `Assistant response ${targetInteraction.index}`,
355
+ source: "opencode.message",
356
+ text: assistantText,
326
357
  });
327
358
  }
328
359
  recorder.assistantStates.set(id, existing);
@@ -346,6 +377,8 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
346
377
  const recorder = ensureSession(sessionID, Date.now());
347
378
  const messageID = toolMessageID(input);
348
379
  const interactionID = configuredValue(recorder.messageInteractions.get(messageID), configuredValue(recorder.currentInteractionID, ""));
380
+ const interaction = interactionID ? findInteraction(recorder, interactionID) : null;
381
+ applyInteractionMode(interaction, inferInteractionMode(input));
349
382
  recorder.toolStarts.set(callID, {
350
383
  startedAt: Date.now(),
351
384
  tool: configuredValue(input && input.tool, "unknown"),
@@ -366,7 +399,9 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
366
399
  : { startedAt: Date.now(), tool: configuredValue(input && input.tool, "unknown") };
367
400
  const messageID = toolMessageID(input) || toolMessageID(output);
368
401
  const mappedInteractionID = configuredValue(toolState.interactionID, configuredValue(recorder.messageInteractions.get(messageID), ""));
369
- const interaction = mappedInteractionID ? findInteraction(recorder, mappedInteractionID) || ensureInteraction(recorder, Date.now()) : ensureInteraction(recorder, Date.now());
402
+ const mode = inferInteractionMode(input, output);
403
+ const interaction = mappedInteractionID ? findInteraction(recorder, mappedInteractionID) || ensureInteraction(recorder, Date.now(), "", mode) : ensureInteraction(recorder, Date.now(), "", mode);
404
+ applyInteractionMode(interaction, mode);
370
405
  addStep(recorder, interaction, {
371
406
  kind: "tool_call",
372
407
  phase: interaction.mode,
@@ -378,6 +413,13 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
378
413
  tool_name: configuredValue(toolState.tool, "unknown"),
379
414
  payload_json: output && output.metadata && typeof output.metadata === "object" ? output.metadata : null,
380
415
  });
416
+ addContextContributor(recorder, {
417
+ category: "tool_output",
418
+ label: `Tool ${configuredValue(toolState.tool, "unknown")}`,
419
+ source: "opencode.tool",
420
+ text: extractToolOutputText(output),
421
+ metadata: safeToolMetadata(output),
422
+ });
381
423
  if (callID) {
382
424
  recorder.toolStarts.delete(callID);
383
425
  }
@@ -420,6 +462,22 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
420
462
  return buildSessionPayload(recorder);
421
463
  }
422
464
 
465
+ function observeSystemPrompt(sessionID, system) {
466
+ const id = configuredValue(sessionID, activeSessionID());
467
+ if (!id) {
468
+ return null;
469
+ }
470
+ const recorder = ensureSession(id, Date.now());
471
+ const entries = Array.isArray(system) ? system : [];
472
+ recorder.systemContributors = entries.map((text, index) => contextContributor({
473
+ category: index === 0 ? "system_prompt" : "instructions",
474
+ label: index === 0 ? "OpenCode system prompt" : `System instruction ${index + 1}`,
475
+ source: "opencode.system",
476
+ text: String(text || ""),
477
+ })).filter((item) => item.char_count > 0);
478
+ return { sessionID: id, details: recorder.systemContributors.length };
479
+ }
480
+
423
481
  return {
424
482
  activeSessionID,
425
483
  observeSessionCreated,
@@ -433,6 +491,7 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
433
491
  observeToolAfter,
434
492
  finalizeSession,
435
493
  snapshotSession,
494
+ observeSystemPrompt,
436
495
  };
437
496
  }
438
497
 
@@ -442,6 +501,135 @@ function storeMessageTextPart(recorder, messageID, partID, text) {
442
501
  recorder.messageTextParts.set(messageID, parts);
443
502
  }
444
503
 
504
+ function addContextContributor(recorder, input) {
505
+ const contributor = contextContributor(input);
506
+ if (contributor.char_count <= 0) {
507
+ return;
508
+ }
509
+ recorder.contextContributors.push(contributor);
510
+ if (recorder.contextContributors.length > 200) {
511
+ recorder.contextContributors = recorder.contextContributors.slice(-200);
512
+ }
513
+ }
514
+
515
+ function contextContributor(input) {
516
+ const text = configuredValue(input && input.text, "");
517
+ const charCount = text.length;
518
+ return {
519
+ category: configuredValue(input && input.category, "unknown"),
520
+ label: safeDetailLabel(input && input.label, configuredValue(input && input.category, "unknown")),
521
+ source: configuredValue(input && input.source, "opencode"),
522
+ token_estimate: estimateTokens(text),
523
+ char_count: charCount,
524
+ item_count: 1,
525
+ metadata_json: input && input.metadata && typeof input.metadata === "object" ? input.metadata : null,
526
+ };
527
+ }
528
+
529
+ function buildLLMStepDetails(recorder, interaction, assistantMessageID) {
530
+ const contributors = [
531
+ ...recorder.systemContributors,
532
+ ...recorder.contextContributors,
533
+ ].filter((item) => item && item.char_count > 0);
534
+ const byCategory = new Map();
535
+ for (const item of contributors) {
536
+ const category = configuredValue(item.category, "unknown");
537
+ const current = byCategory.get(category) || {
538
+ category,
539
+ label: detailCategoryLabel(category),
540
+ token_estimate: 0,
541
+ char_count: 0,
542
+ item_count: 0,
543
+ source: item.source,
544
+ top_items: [],
545
+ };
546
+ current.token_estimate += Math.max(0, Math.floor(finiteNumber(item.token_estimate)));
547
+ current.char_count += Math.max(0, Math.floor(finiteNumber(item.char_count)));
548
+ current.item_count += Math.max(1, Math.floor(finiteNumber(item.item_count)) || 1);
549
+ current.top_items.push({
550
+ label: safeDetailLabel(item.label, detailCategoryLabel(category)),
551
+ token_estimate: Math.max(0, Math.floor(finiteNumber(item.token_estimate))),
552
+ char_count: Math.max(0, Math.floor(finiteNumber(item.char_count))),
553
+ source: configuredValue(item.source, "opencode"),
554
+ ...(item.metadata_json ? { metadata: item.metadata_json } : {}),
555
+ });
556
+ byCategory.set(category, current);
557
+ }
558
+ return Array.from(byCategory.values())
559
+ .sort((left, right) => right.token_estimate - left.token_estimate || left.category.localeCompare(right.category))
560
+ .map((item, index) => ({
561
+ id: `${assistantMessageID || interaction.id}:detail:${index + 1}`,
562
+ index: index + 1,
563
+ category: item.category,
564
+ label: item.label,
565
+ token_estimate: item.token_estimate,
566
+ char_count: item.char_count,
567
+ item_count: item.item_count,
568
+ source: item.source,
569
+ metadata_json: {
570
+ top_items: item.top_items
571
+ .sort((left, right) => right.token_estimate - left.token_estimate)
572
+ .slice(0, 5),
573
+ },
574
+ }));
575
+ }
576
+
577
+ function normalizeStepDetails(details, stepID, interactionID) {
578
+ if (!Array.isArray(details)) {
579
+ return [];
580
+ }
581
+ return details.map((detail, index) => ({
582
+ id: configuredValue(detail && detail.id, `${stepID}:detail:${index + 1}`),
583
+ step_id: stepID,
584
+ interaction_id: interactionID,
585
+ index: Math.max(1, Math.floor(finiteNumber(detail && detail.index)) || index + 1),
586
+ category: configuredValue(detail && detail.category, "unknown"),
587
+ label: safeDetailLabel(detail && detail.label, configuredValue(detail && detail.category, "unknown")),
588
+ token_estimate: Math.max(0, Math.floor(finiteNumber(detail && detail.token_estimate))),
589
+ char_count: Math.max(0, Math.floor(finiteNumber(detail && detail.char_count))),
590
+ item_count: Math.max(0, Math.floor(finiteNumber(detail && detail.item_count))),
591
+ source: configuredValue(detail && detail.source, "") || null,
592
+ metadata_json: detail && detail.metadata_json && typeof detail.metadata_json === "object" ? detail.metadata_json : null,
593
+ }));
594
+ }
595
+
596
+ function estimateTokens(text) {
597
+ return Math.max(0, Math.round(String(text || "").length / 4));
598
+ }
599
+
600
+ function detailCategoryLabel(category) {
601
+ return String(category || "unknown").split("_").map((part) => part ? part[0].toUpperCase() + part.slice(1) : part).join(" ");
602
+ }
603
+
604
+ function safeDetailLabel(value, fallback) {
605
+ const label = configuredValue(value, fallback).replace(/\s+/g, " ").trim();
606
+ return label.length > 120 ? `${label.slice(0, 117)}...` : label;
607
+ }
608
+
609
+ function extractToolOutputText(output) {
610
+ if (!output || typeof output !== "object") {
611
+ return "";
612
+ }
613
+ if (typeof output.output === "string") {
614
+ return output.output;
615
+ }
616
+ if (typeof output.text === "string") {
617
+ return output.text;
618
+ }
619
+ if (output.metadata && typeof output.metadata.output === "string") {
620
+ return output.metadata.output;
621
+ }
622
+ if (Array.isArray(output.content)) {
623
+ return output.content.map((item) => item && typeof item.text === "string" ? item.text : "").filter(Boolean).join("\n");
624
+ }
625
+ return "";
626
+ }
627
+
628
+ function safeToolMetadata(output) {
629
+ const attachments = Array.isArray(output && output.attachments) ? output.attachments : [];
630
+ return attachments.length > 0 ? { attachments: attachments.length } : null;
631
+ }
632
+
445
633
  function storedMessageText(recorder, messageID) {
446
634
  const parts = recorder.messageTextParts.get(messageID);
447
635
  if (!parts) {
@@ -817,6 +1005,41 @@ function summarizePrompt(prompt, fallback) {
817
1005
  return `${trimmed.slice(0, 77)}...`;
818
1006
  }
819
1007
 
1008
+ function inferInteractionMode(...values) {
1009
+ const normalized = values.map((value) => {
1010
+ if (typeof value === "string") {
1011
+ return value;
1012
+ }
1013
+ try {
1014
+ return JSON.stringify(value || {});
1015
+ } catch {
1016
+ return "";
1017
+ }
1018
+ }).join("\n").toLowerCase();
1019
+ if (
1020
+ normalized.includes("plan mode - system reminder") ||
1021
+ normalized.includes("plan mode active") ||
1022
+ normalized.includes('"mode":"plan"') ||
1023
+ normalized.includes('"modeid":"plan"') ||
1024
+ normalized.includes('"mode_id":"plan"')
1025
+ ) {
1026
+ return "plan";
1027
+ }
1028
+ return "build";
1029
+ }
1030
+
1031
+ function applyInteractionMode(interaction, mode) {
1032
+ if (!interaction || mode !== "plan") {
1033
+ return;
1034
+ }
1035
+ interaction.mode = "plan";
1036
+ for (const step of interaction.steps) {
1037
+ if (step.phase === "build") {
1038
+ step.phase = "plan";
1039
+ }
1040
+ }
1041
+ }
1042
+
820
1043
  function inferResultStatus(values, fallback = "success") {
821
1044
  return values.some((value) => value === "error" || value === "failed") ? "error" : fallback;
822
1045
  }