@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/recorder.js CHANGED
@@ -333,8 +333,14 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
333
333
  finalized: false,
334
334
  };
335
335
  const tokens = tokensFromMessage(info);
336
- if (existing.firstTokenAt == null && tokens.output > 0) {
337
- existing.firstTokenAt = now;
336
+ // A caller that reports first-token timing passes `firstTokenAt` (ms, or null
337
+ // when no first token was observed). Other callers keep the token heuristic.
338
+ if (existing.firstTokenAt == null) {
339
+ if (info && "firstTokenAt" in info) {
340
+ existing.firstTokenAt = Number.isFinite(info.firstTokenAt) ? info.firstTokenAt : null;
341
+ } else if (tokens.output > 0) {
342
+ existing.firstTokenAt = now;
343
+ }
338
344
  }
339
345
  existing.provider = assistantProvider(info);
340
346
  existing.model = assistantModel(info);
@@ -499,6 +505,10 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
499
505
  return payload;
500
506
  }
501
507
 
508
+ function discardSession(sessionID) {
509
+ sessions.delete(configuredValue(sessionID, ""));
510
+ }
511
+
502
512
  function snapshotSession(sessionID, result = "success", endedAtMs = Date.now()) {
503
513
  const recorder = sessions.get(sessionID);
504
514
  if (!recorder) {
@@ -523,12 +533,7 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
523
533
  }
524
534
  const recorder = ensureSession(id, Date.now());
525
535
  const entries = Array.isArray(system) ? system : [];
526
- recorder.systemContributors = entries.map((text, index) => contextContributor({
527
- category: index === 0 ? "system_prompt" : "instructions",
528
- label: index === 0 ? "OpenCode system prompt" : `System instruction ${index + 1}`,
529
- source: "opencode.system",
530
- text: String(text || ""),
531
- })).filter((item) => item.char_count > 0);
536
+ recorder.systemContributors = entries.map((entry, index) => contextContributor(systemContributorInput(entry, index))).filter((item) => item.char_count > 0);
532
537
  return { sessionID: id, details: recorder.systemContributors.length };
533
538
  }
534
539
 
@@ -546,6 +551,24 @@ export function createRecorder({ project, directory, initialPrompt = "" }) {
546
551
  finalizeSession,
547
552
  snapshotSession,
548
553
  observeSystemPrompt,
554
+ discardSession,
555
+ };
556
+ }
557
+
558
+ function systemContributorInput(entry, index) {
559
+ if (entry && typeof entry === "object") {
560
+ return {
561
+ category: configuredValue(entry.category, "instructions"),
562
+ label: configuredValue(entry.label, `System instruction ${index + 1}`),
563
+ source: configuredValue(entry.source, "opencode.system"),
564
+ text: String(entry.text || ""),
565
+ };
566
+ }
567
+ return {
568
+ category: index === 0 ? "system_prompt" : "instructions",
569
+ label: index === 0 ? "OpenCode system prompt" : `System instruction ${index + 1}`,
570
+ source: "opencode.system",
571
+ text: String(entry || ""),
549
572
  };
550
573
  }
551
574
 
package/src/v2.js ADDED
@@ -0,0 +1,336 @@
1
+ // Translates OpenCode 2 hooks and server events into recorder calls.
2
+ //
3
+ // OpenCode 2 reports a session as a sequence of steps. Each model call is one
4
+ // step with its own assistant message ID, and tools, text, and usage arrive as
5
+ // separate hooks and events. This module keeps that per-session bookkeeping so
6
+ // the recorder can keep building the session, interaction, and step payloads.
7
+
8
+ function configuredValue(value, fallback = "") {
9
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : fallback;
10
+ }
11
+
12
+ function isPlanAgent(agent) {
13
+ return /plan/i.test(configuredValue(agent, ""));
14
+ }
15
+
16
+ function modeHint(state) {
17
+ return state.plan ? { mode: "plan" } : {};
18
+ }
19
+
20
+ function headingLabel(text, index) {
21
+ const heading = String(text || "")
22
+ .split("\n")
23
+ .map((line) => line.replace(/^#+\s*/, "").trim())
24
+ .find((line) => line !== "");
25
+ return configuredValue(heading, `System instruction ${index + 1}`);
26
+ }
27
+
28
+ export function systemContributors(parts) {
29
+ const contributors = [];
30
+ (Array.isArray(parts) ? parts : []).forEach((part, index) => {
31
+ const text = typeof part?.text === "string" ? part.text : "";
32
+ const instructions = Array.isArray(part?.metadata?.experimental?.instructions) ? part.metadata.experimental.instructions : [];
33
+ let own = text;
34
+ for (const instruction of instructions) {
35
+ const instructionText = typeof instruction?.text === "string" ? instruction.text : "";
36
+ if (!instructionText.trim()) {
37
+ continue;
38
+ }
39
+ if (own.includes(instructionText)) {
40
+ own = own.replace(instructionText, "");
41
+ }
42
+ contributors.push({
43
+ category: "instructions",
44
+ label: `Instruction ${configuredValue(instruction?.key, "source")}`,
45
+ text: instructionText,
46
+ });
47
+ }
48
+ if (own.trim()) {
49
+ contributors.push({
50
+ category: index === 0 ? "system_prompt" : "instructions",
51
+ label: index === 0 ? "OpenCode system prompt" : headingLabel(own, index),
52
+ text: own,
53
+ });
54
+ }
55
+ });
56
+ return contributors;
57
+ }
58
+
59
+ function toolOutput(result) {
60
+ if (!result || typeof result !== "object") {
61
+ return {};
62
+ }
63
+ const output = {};
64
+ if (typeof result.content === "string") {
65
+ output.text = result.content;
66
+ } else if (Array.isArray(result.content)) {
67
+ output.content = result.content;
68
+ }
69
+ if (result.metadata && typeof result.metadata === "object") {
70
+ output.metadata = result.metadata;
71
+ }
72
+ return output;
73
+ }
74
+
75
+ function assistantText(state, assistantMessageID) {
76
+ return Array.from(state.texts.get(assistantMessageID)?.values() || []).filter(Boolean).join("\n");
77
+ }
78
+
79
+ function assistantInfo(sessionID, assistantMessageID, state, step, details, created) {
80
+ return {
81
+ id: assistantMessageID,
82
+ sessionID,
83
+ role: "assistant",
84
+ providerID: step?.providerID,
85
+ modelID: step?.modelID,
86
+ time: { created: step?.startedAt ?? created },
87
+ firstTokenAt: step?.firstTokenAt,
88
+ text: assistantText(state, assistantMessageID),
89
+ ...details,
90
+ ...modeHint(state),
91
+ };
92
+ }
93
+
94
+ export function createV2Bridge(recorder) {
95
+ const sessions = new Map();
96
+ const dirty = new Set();
97
+
98
+ function sessionState(sessionID) {
99
+ let state = sessions.get(sessionID);
100
+ if (!state) {
101
+ state = { plan: false, title: "", steps: new Map(), texts: new Map() };
102
+ sessions.set(sessionID, state);
103
+ }
104
+ return state;
105
+ }
106
+
107
+ function markDirty(sessionID) {
108
+ dirty.add(sessionID);
109
+ }
110
+
111
+ function noteAgent(state, agent) {
112
+ if (configuredValue(agent, "")) {
113
+ state.plan = isPlanAgent(agent);
114
+ }
115
+ }
116
+
117
+ function recordStepEnd(sessionID, assistantMessageID, details, created) {
118
+ const state = sessionState(sessionID);
119
+ const step = state.steps.get(assistantMessageID) || { startedAt: created, firstTokenAt: null };
120
+ markDirty(sessionID);
121
+ const observed = recorder.observeAssistantMessage({
122
+ type: "message.updated",
123
+ info: assistantInfo(sessionID, assistantMessageID, state, step, details, created),
124
+ });
125
+ state.steps.delete(assistantMessageID);
126
+ state.texts.delete(assistantMessageID);
127
+ return observed?.finalized ? { sessionID } : null;
128
+ }
129
+
130
+ return {
131
+ sessionCreated(event) {
132
+ const data = event?.data || {};
133
+ const sessionID = configuredValue(data.sessionID, "");
134
+ if (!sessionID) {
135
+ return null;
136
+ }
137
+ noteAgent(sessionState(sessionID), data.agent);
138
+ return recorder.observeSessionCreated({ sessionID, info: { id: sessionID, title: data.title, time: event.created } });
139
+ },
140
+
141
+ sessionRenamed(event) {
142
+ const data = event?.data || {};
143
+ const sessionID = configuredValue(data.sessionID, "");
144
+ const title = configuredValue(data.title, "");
145
+ if (!sessionID || !title) {
146
+ return null;
147
+ }
148
+ sessionState(sessionID).title = title;
149
+ markDirty(sessionID);
150
+ return recorder.setSessionTitle(sessionID, title);
151
+ },
152
+
153
+ sessionDeleted(event) {
154
+ const sessionID = configuredValue(event?.data?.sessionID, "");
155
+ if (!sessionID) {
156
+ return null;
157
+ }
158
+ sessions.delete(sessionID);
159
+ dirty.delete(sessionID);
160
+ recorder.discardSession(sessionID);
161
+ return { sessionID };
162
+ },
163
+
164
+ // ctx.session.hook("prompt"): every admitted user prompt, with its message ID.
165
+ prompt(event) {
166
+ const sessionID = configuredValue(event?.sessionID, "");
167
+ const messageID = configuredValue(event?.messageID, "");
168
+ if (!sessionID || !messageID) {
169
+ return null;
170
+ }
171
+ const state = sessionState(sessionID);
172
+ markDirty(sessionID);
173
+ return recorder.observeUserMessage({
174
+ info: { id: messageID, sessionID, role: "user", text: event.prompt?.text ?? "" },
175
+ ...modeHint(state),
176
+ });
177
+ },
178
+
179
+ // ctx.session.hook("context"): the assembled system instructions for a model call.
180
+ context(event) {
181
+ const sessionID = configuredValue(event?.sessionID, "");
182
+ if (!sessionID) {
183
+ return null;
184
+ }
185
+ const state = sessionState(sessionID);
186
+ noteAgent(state, event.agent);
187
+ if ((Array.isArray(event.system) ? event.system : []).some((part) => /plan mode/i.test(String(part?.text || "")))) {
188
+ state.plan = true;
189
+ }
190
+ markDirty(sessionID);
191
+ return recorder.observeSystemPrompt(sessionID, systemContributors(event.system));
192
+ },
193
+
194
+ stepStarted(event) {
195
+ const data = event?.data || {};
196
+ const sessionID = configuredValue(data.sessionID, "");
197
+ const assistantMessageID = configuredValue(data.assistantMessageID, "");
198
+ if (!sessionID || !assistantMessageID) {
199
+ return null;
200
+ }
201
+ const state = sessionState(sessionID);
202
+ noteAgent(state, data.agent);
203
+ state.steps.set(assistantMessageID, {
204
+ startedAt: Number.isFinite(data.started) ? data.started : event.created,
205
+ firstTokenAt: null,
206
+ providerID: configuredValue(data.model?.providerID, ""),
207
+ modelID: configuredValue(data.model?.id, ""),
208
+ });
209
+ return { sessionID, assistantMessageID };
210
+ },
211
+
212
+ stepFirstToken(event) {
213
+ const data = event?.data || {};
214
+ const step = sessions.get(configuredValue(data.sessionID, ""))?.steps.get(configuredValue(data.assistantMessageID, ""));
215
+ if (!step || step.firstTokenAt != null) {
216
+ return null;
217
+ }
218
+ step.firstTokenAt = Number.isFinite(event.created) ? event.created : null;
219
+ return { sessionID: data.sessionID, assistantMessageID: data.assistantMessageID };
220
+ },
221
+
222
+ textEnded(event) {
223
+ const data = event?.data || {};
224
+ const state = sessions.get(configuredValue(data.sessionID, ""));
225
+ const assistantMessageID = configuredValue(data.assistantMessageID, "");
226
+ if (!state || !assistantMessageID) {
227
+ return null;
228
+ }
229
+ let parts = state.texts.get(assistantMessageID);
230
+ if (!parts) {
231
+ parts = new Map();
232
+ state.texts.set(assistantMessageID, parts);
233
+ }
234
+ parts.set(data.ordinal, typeof data.text === "string" ? data.text : "");
235
+ return { sessionID: data.sessionID, assistantMessageID };
236
+ },
237
+
238
+ // session.step.ended: the model call finished, with its usage and changed files.
239
+ stepEnded(event) {
240
+ const data = event?.data || {};
241
+ const sessionID = configuredValue(data.sessionID, "");
242
+ const assistantMessageID = configuredValue(data.assistantMessageID, "");
243
+ if (!sessionID || !assistantMessageID) {
244
+ return null;
245
+ }
246
+ const state = sessionState(sessionID);
247
+ // Edits are recorded before this step's model call, so each edit keeps the
248
+ // tool call that caused it as its parent instead of the call that follows it.
249
+ for (const file of Array.isArray(data.files) ? data.files : []) {
250
+ if (typeof file !== "string" || !file.trim()) {
251
+ continue;
252
+ }
253
+ recorder.observeFileEdited({ file, sessionID, ...modeHint(state) });
254
+ }
255
+ return recordStepEnd(sessionID, assistantMessageID, {
256
+ tokens: data.tokens,
257
+ cost: data.cost,
258
+ finish: configuredValue(data.finish, "stop"),
259
+ }, event.created);
260
+ },
261
+
262
+ stepFailed(event) {
263
+ const data = event?.data || {};
264
+ const sessionID = configuredValue(data.sessionID, "");
265
+ const assistantMessageID = configuredValue(data.assistantMessageID, "");
266
+ if (!sessionID || !assistantMessageID) {
267
+ return null;
268
+ }
269
+ return recordStepEnd(sessionID, assistantMessageID, {
270
+ tokens: data.tokens,
271
+ cost: data.cost,
272
+ error: data.error || { message: "model call failed" },
273
+ }, event.created);
274
+ },
275
+
276
+ // ctx.tool.hook("execute.before" | "execute.after")
277
+ toolBefore(event) {
278
+ const sessionID = configuredValue(event?.sessionID, "");
279
+ const callID = configuredValue(event?.id, "");
280
+ if (!sessionID || !callID) {
281
+ return null;
282
+ }
283
+ const state = sessionState(sessionID);
284
+ markDirty(sessionID);
285
+ return recorder.observeToolBefore({
286
+ sessionID,
287
+ callID,
288
+ tool: configuredValue(event.tool, "unknown"),
289
+ messageID: configuredValue(event.messageID, ""),
290
+ ...modeHint(state),
291
+ });
292
+ },
293
+
294
+ toolAfter(event) {
295
+ const sessionID = configuredValue(event?.sessionID, recorder.activeSessionID());
296
+ if (!sessionID) {
297
+ return null;
298
+ }
299
+ const state = sessionState(sessionID);
300
+ markDirty(sessionID);
301
+ const output = toolOutput(event.result);
302
+ if (event.status === "error" || (typeof event.result?.metadata?.exit === "number" && event.result.metadata.exit !== 0)) {
303
+ output.error = event.error || { message: "tool failed" };
304
+ }
305
+ return recorder.observeToolAfter(
306
+ {
307
+ sessionID,
308
+ callID: configuredValue(event?.id, ""),
309
+ tool: configuredValue(event.tool, "unknown"),
310
+ messageID: configuredValue(event.messageID, ""),
311
+ ...modeHint(state),
312
+ },
313
+ output,
314
+ );
315
+ },
316
+
317
+ setTitle(sessionID, title) {
318
+ const state = sessions.get(configuredValue(sessionID, ""));
319
+ if (state && configuredValue(title, "")) {
320
+ state.title = title;
321
+ }
322
+ },
323
+
324
+ hasTitle(sessionID) {
325
+ return configuredValue(sessions.get(configuredValue(sessionID, ""))?.title, "") !== "";
326
+ },
327
+
328
+ // Sessions changed since their last upload. Execution-end events use this to
329
+ // avoid uploading the same snapshot twice when session.idle also arrives.
330
+ consumeDirty(sessionID) {
331
+ const isDirty = dirty.has(sessionID);
332
+ dirty.delete(sessionID);
333
+ return isDirty;
334
+ },
335
+ };
336
+ }