@distlang/opencode-plugin 0.1.5 → 0.1.7

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.5",
3
+ "version": "0.1.7",
4
4
  "description": "OpenCode plugin for Distlang AI Debugger",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -14,7 +14,7 @@
14
14
  "README.md"
15
15
  ],
16
16
  "scripts": {
17
- "test": "node --check src/index.js && node --check src/recorder.js && node --check src/distlang.js && node --check src/state.js && node --check src/command.js",
17
+ "test": "node --check src/index.js && node --check src/recorder.js && node --check src/distlang.js && node --check src/state.js && node --check src/command.js && node --test test/*.test.js",
18
18
  "check": "npm test",
19
19
  "pack:check": "npm pack --dry-run",
20
20
  "release": "npm test && npm run pack:check",
package/src/index.js CHANGED
@@ -193,6 +193,7 @@ export const DistlangAIDebugger = async ({ project, directory, client }) => {
193
193
  async function finalizeSession(sessionID, result) {
194
194
  let payload;
195
195
  try {
196
+ await refreshSessionMetadata(sessionID);
196
197
  payload = recorder.finalizeSession(sessionID, result, Date.now());
197
198
  } catch (error) {
198
199
  await log("error", "AI Debugger session finalization failed", { sessionID, result, error: String(error) });
@@ -229,6 +230,7 @@ export const DistlangAIDebugger = async ({ project, directory, client }) => {
229
230
  async function uploadSessionSnapshot(sessionID, result = "success") {
230
231
  let payload;
231
232
  try {
233
+ await refreshSessionMetadata(sessionID);
232
234
  payload = recorder.snapshotSession(sessionID, result, Date.now());
233
235
  } catch (error) {
234
236
  await log("error", "AI Debugger session snapshot failed", { sessionID, result, error: String(error) });
@@ -262,6 +264,39 @@ export const DistlangAIDebugger = async ({ project, directory, client }) => {
262
264
  }
263
265
  }
264
266
 
267
+ async function refreshSessionMetadata(sessionID) {
268
+ if (!sessionID || !client?.session || typeof client.session.get !== "function") {
269
+ return;
270
+ }
271
+ try {
272
+ const response = await client.session.get({ path: { id: sessionID } });
273
+ const session = response?.data ?? response;
274
+ const title = session && typeof session === "object" ? configuredValue(session.title ?? session.name ?? session.summary, "") : "";
275
+ if (title) {
276
+ recorder.setSessionTitle(sessionID, title);
277
+ await debugLog("OpenCode session metadata refreshed", { sessionID, titleLength: title.length });
278
+ }
279
+ } catch (error) {
280
+ await debugLog("OpenCode session metadata refresh failed", { sessionID, error: String(error) });
281
+ }
282
+ }
283
+
284
+ function messageShape(event) {
285
+ const info = event && typeof event === "object" ? event.info ?? event.properties?.info : null;
286
+ if (!info || typeof info !== "object") {
287
+ return { eventKeys: Object.keys(event || {}) };
288
+ }
289
+ return {
290
+ eventKeys: Object.keys(event || {}),
291
+ infoKeys: Object.keys(info),
292
+ tokenKeys: info.tokens && typeof info.tokens === "object" ? Object.keys(info.tokens) : [],
293
+ usageKeys: info.usage && typeof info.usage === "object" ? Object.keys(info.usage) : [],
294
+ metadataKeys: info.metadata && typeof info.metadata === "object" ? Object.keys(info.metadata) : [],
295
+ responseKeys: info.response && typeof info.response === "object" ? Object.keys(info.response) : [],
296
+ hasTitle: Boolean(info.title || info.name || info.summary),
297
+ };
298
+ }
299
+
265
300
  return {
266
301
  event: async ({ event }) => {
267
302
  await logInit();
@@ -286,6 +321,14 @@ export const DistlangAIDebugger = async ({ project, directory, client }) => {
286
321
  return;
287
322
  }
288
323
 
324
+ if (event.type === "session.updated") {
325
+ const observed = recorder.observeSessionUpdated(event);
326
+ if (observed) {
327
+ await debugLog("session.updated observed", observed);
328
+ }
329
+ return;
330
+ }
331
+
289
332
 
290
333
  if (event.type === "session.idle" || event.type === "session.error") {
291
334
  const sessionID = configuredValue(event.sessionID, recorder.activeSessionID());
@@ -319,7 +362,7 @@ export const DistlangAIDebugger = async ({ project, directory, client }) => {
319
362
 
320
363
  const assistantMessage = recorder.observeAssistantMessage(event);
321
364
  if (assistantMessage) {
322
- await debugLog("assistant message update observed", assistantMessage);
365
+ await debugLog("assistant message update observed", { ...assistantMessage, shape: messageShape(event) });
323
366
  if (assistantMessage.finalized) {
324
367
  await uploadSessionSnapshot(assistantMessage.sessionID, "success");
325
368
  }
package/src/recorder.js CHANGED
@@ -55,6 +55,7 @@ export function createRecorder({ project, directory }) {
55
55
  endedAtMs: 0,
56
56
  status: "success",
57
57
  summary: "",
58
+ title: "",
58
59
  interactions: [],
59
60
  currentInteractionID: "",
60
61
  interactionCounter: 0,
@@ -137,10 +138,30 @@ export function createRecorder({ project, directory }) {
137
138
  if (!sessionID) {
138
139
  return null;
139
140
  }
140
- ensureSession(sessionID, parseTimestamp(sessionInfo.time, Date.now()));
141
+ const recorder = ensureSession(sessionID, parseTimestamp(sessionInfo.time, Date.now()));
142
+ updateSessionTitle(recorder, sessionInfo);
141
143
  return { sessionID };
142
144
  }
143
145
 
146
+ function observeSessionUpdated(event) {
147
+ const sessionInfo = event.info && typeof event.info === "object" ? event.info : event.properties && typeof event.properties === "object" ? event.properties : {};
148
+ const sessionID = configuredValue(event.sessionID, configuredValue(sessionInfo.id, ""));
149
+ if (!sessionID) {
150
+ return null;
151
+ }
152
+ const recorder = ensureSession(sessionID, parseTimestamp(sessionInfo.time, Date.now()));
153
+ const title = updateSessionTitle(recorder, sessionInfo);
154
+ return { sessionID, title };
155
+ }
156
+
157
+ function setSessionTitle(sessionID, title) {
158
+ if (!sessionID) {
159
+ return null;
160
+ }
161
+ const recorder = ensureSession(sessionID, Date.now());
162
+ return updateSessionTitle(recorder, { title });
163
+ }
164
+
144
165
  function observeFileEdited(event) {
145
166
  const filePath = configuredValue(event.file, configuredValue(event.properties && event.properties.file, ""));
146
167
  const sessionID = configuredValue(event.sessionID, activeSessionID());
@@ -223,6 +244,7 @@ export function createRecorder({ project, directory }) {
223
244
  output_tokens: tokens.output,
224
245
  reasoning_tokens: tokens.reasoning,
225
246
  cached_tokens: tokens.cached,
247
+ context_size_tokens: tokens.context,
226
248
  cost_usd: finiteNumber(info && info.cost),
227
249
  first_token_at: existing.firstTokenAt != null ? new Date(existing.firstTokenAt).toISOString() : null,
228
250
  first_token_latency_ms: existing.firstTokenAt != null ? Math.max(0, existing.firstTokenAt - existing.firstSeenAt) : 0,
@@ -322,6 +344,8 @@ export function createRecorder({ project, directory }) {
322
344
  return {
323
345
  activeSessionID,
324
346
  observeSessionCreated,
347
+ observeSessionUpdated,
348
+ setSessionTitle,
325
349
  observeFileEdited,
326
350
  observeUserMessage,
327
351
  observeAssistantMessage,
@@ -333,7 +357,8 @@ export function createRecorder({ project, directory }) {
333
357
  }
334
358
 
335
359
  function buildSessionPayload(recorder) {
336
- const interactions = recorder.interactions.map(buildInteractionPayload);
360
+ const sessionTitle = sanitizeDebuggerText(recorder.title);
361
+ const interactions = recorder.interactions.map((interaction) => buildInteractionPayload(interaction, sessionTitle));
337
362
  const allSteps = interactions.flatMap((interaction) => interaction.steps);
338
363
  const llmSteps = allSteps.filter((step) => step.kind === "llm_call");
339
364
  const contextValues = llmSteps.map((step) => step.context_size_tokens).filter((value) => value > 0);
@@ -347,7 +372,7 @@ function buildSessionPayload(recorder) {
347
372
  ended_at: new Date(recorder.endedAtMs || Date.now()).toISOString(),
348
373
  duration_ms: Math.max(0, (recorder.endedAtMs || Date.now()) - recorder.startedAtMs),
349
374
  status: inferResultStatus(interactions.map((interaction) => interaction.status), recorder.status),
350
- summary: configuredValue(recorder.summary, interactions[0]?.summary || `OpenCode session ${recorder.id}`),
375
+ summary: configuredValue(recorder.title, configuredValue(recorder.summary, interactions[0]?.summary || `OpenCode session ${recorder.id}`)),
351
376
  total_cost_usd: allSteps.reduce((total, step) => total + finiteNumber(step.cost_usd), 0),
352
377
  input_tokens: allSteps.reduce((total, step) => total + finiteNumber(step.input_tokens), 0),
353
378
  output_tokens: allSteps.reduce((total, step) => total + finiteNumber(step.output_tokens), 0),
@@ -365,10 +390,14 @@ function buildSessionPayload(recorder) {
365
390
  };
366
391
  }
367
392
 
368
- function buildInteractionPayload(interaction) {
393
+ function buildInteractionPayload(interaction, sessionTitle = "") {
369
394
  const llmSteps = interaction.steps.filter((step) => step.kind === "llm_call");
370
395
  const contextValues = llmSteps.map((step) => step.context_size_tokens).filter((value) => value > 0);
371
- const prompt = configuredValue(interaction.prompt, `Interaction ${interaction.index}`);
396
+ const promptFallback = configuredValue(sessionTitle, `Interaction ${interaction.index}`);
397
+ const rawPrompt = sanitizeDebuggerText(interaction.prompt);
398
+ const rawSummary = sanitizeDebuggerText(interaction.summary);
399
+ const prompt = isGenericInteractionLabel(rawPrompt) ? promptFallback : configuredValue(rawPrompt, promptFallback);
400
+ const summaryFallback = summarizePrompt(prompt, promptFallback);
372
401
  return {
373
402
  id: interaction.id,
374
403
  index: interaction.index,
@@ -378,7 +407,7 @@ function buildInteractionPayload(interaction) {
378
407
  ended_at: interaction.endedAtMs > 0 ? new Date(interaction.endedAtMs).toISOString() : new Date(Date.now()).toISOString(),
379
408
  duration_ms: Math.max(0, (interaction.endedAtMs || Date.now()) - interaction.startedAtMs),
380
409
  status: inferResultStatus(interaction.steps.map((step) => step.status), interaction.status),
381
- summary: configuredValue(interaction.summary, summarizePrompt(prompt, `Interaction ${interaction.index}`)),
410
+ summary: isGenericInteractionLabel(rawSummary) ? summaryFallback : configuredValue(rawSummary, summaryFallback),
382
411
  llm_call_count: llmSteps.length,
383
412
  cost_usd: interaction.steps.reduce((total, step) => total + finiteNumber(step.cost_usd), 0),
384
413
  input_tokens: interaction.steps.reduce((total, step) => total + finiteNumber(step.input_tokens), 0),
@@ -393,6 +422,11 @@ function buildInteractionPayload(interaction) {
393
422
  };
394
423
  }
395
424
 
425
+ function isGenericInteractionLabel(value) {
426
+ const label = String(value || "").trim();
427
+ return /^OpenCode interaction \d+$/i.test(label) || /^Interaction \d+$/i.test(label);
428
+ }
429
+
396
430
  function configuredValue(value, fallback = "") {
397
431
  return typeof value === "string" && value.trim() !== "" ? value.trim() : fallback;
398
432
  }
@@ -501,18 +535,64 @@ function assistantFinalState(info) {
501
535
  }
502
536
 
503
537
  function tokensFromMessage(info) {
504
- const tokens = info && typeof info === "object" ? info.tokens : null;
505
- const cacheValue = tokens && typeof tokens === "object"
506
- ? (tokens.cache ?? tokens.cached ?? tokens.cacheReadInputTokens ?? tokens.cachedInput)
507
- : 0;
538
+ const sources = tokenSources(info);
539
+ const cacheValue = firstNumber(sources, ["cache", "cached", "cached_tokens", "cachedTokens", "cacheReadInputTokens", "cachedInput", "cachedInputTokens"]);
540
+ const input = firstNumber(sources, ["input", "input_tokens", "inputTokens", "prompt", "prompt_tokens", "promptTokens"]);
541
+ const output = firstNumber(sources, ["output", "output_tokens", "outputTokens", "completion", "completion_tokens", "completionTokens"]);
542
+ const reasoning = firstNumber(sources, ["reasoning", "reasoning_tokens", "reasoningTokens"]);
543
+ const explicitContext = firstNumber(sources, ["context", "context_tokens", "contextTokens", "context_size", "contextSize", "context_size_tokens", "contextSizeTokens"]);
508
544
  return {
509
- input: finiteNumber(tokens && tokens.input),
510
- output: finiteNumber(tokens && tokens.output),
511
- reasoning: finiteNumber(tokens && tokens.reasoning),
512
- cached: finiteNumber(cacheValue),
545
+ input,
546
+ output,
547
+ reasoning,
548
+ cached: cacheValue,
549
+ context: explicitContext > 0 ? explicitContext : input + cacheValue + reasoning,
513
550
  };
514
551
  }
515
552
 
553
+ function tokenSources(info) {
554
+ if (!info || typeof info !== "object") {
555
+ return [];
556
+ }
557
+ return [
558
+ info.tokens,
559
+ info.usage,
560
+ info.usageTokens,
561
+ info.metadata && info.metadata.tokens,
562
+ info.metadata && info.metadata.usage,
563
+ info.response && info.response.tokens,
564
+ info.response && info.response.usage,
565
+ info.model && info.model.tokens,
566
+ info.model && info.model.usage,
567
+ info,
568
+ ].filter((source) => source && typeof source === "object");
569
+ }
570
+
571
+ function firstNumber(sources, keys) {
572
+ for (const source of sources) {
573
+ for (const key of keys) {
574
+ const value = source[key];
575
+ if (typeof value === "undefined" || value === null) {
576
+ continue;
577
+ }
578
+ const parsed = finiteNumber(value);
579
+ if (parsed > 0) {
580
+ return parsed;
581
+ }
582
+ }
583
+ }
584
+ return 0;
585
+ }
586
+
587
+ function updateSessionTitle(recorder, info) {
588
+ const title = sanitizeDebuggerText(configuredValue(info && (info.title ?? info.name ?? info.summary), ""));
589
+ if (title) {
590
+ recorder.title = title;
591
+ recorder.summary = title;
592
+ }
593
+ return recorder.title;
594
+ }
595
+
516
596
  function extractMessageText(info) {
517
597
  const direct = sanitizeDebuggerText(configuredValue(info && (info.text ?? info.prompt ?? info.message ?? info.body), ""));
518
598
  if (direct !== "") {