@distlang/opencode-plugin 0.1.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/README.md +98 -0
- package/package.json +41 -0
- package/src/distlang.js +40 -0
- package/src/index.js +170 -0
- package/src/recorder.js +542 -0
package/README.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# @distlang/opencode-plugin
|
|
2
|
+
|
|
3
|
+
OpenCode plugin for capturing coding sessions and uploading them to Distlang AI Debugger.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
Add the plugin to your global OpenCode config:
|
|
8
|
+
|
|
9
|
+
`~/.config/opencode/opencode.json`
|
|
10
|
+
|
|
11
|
+
```json
|
|
12
|
+
{
|
|
13
|
+
"$schema": "https://opencode.ai/config.json",
|
|
14
|
+
"plugin": ["@distlang/opencode-plugin"]
|
|
15
|
+
}
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
OpenCode installs npm plugins automatically with Bun at startup.
|
|
19
|
+
|
|
20
|
+
## Auth
|
|
21
|
+
|
|
22
|
+
The plugin does not manage tokens directly.
|
|
23
|
+
|
|
24
|
+
It relies on Distlang CLI for auth and authenticated requests:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
distlang helpers auth status
|
|
28
|
+
distlang helpers login
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The plugin uses:
|
|
32
|
+
|
|
33
|
+
- `distlang helpers auth status --json`
|
|
34
|
+
- `distlang helpers request POST /ai-debugger/v1/ingest ...`
|
|
35
|
+
|
|
36
|
+
If you are not logged in, the plugin logs one warning and continues without uploading.
|
|
37
|
+
|
|
38
|
+
## Debugging
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
DISTLANG_OPENCODE_DEBUG=1 opencode
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Captured Model
|
|
45
|
+
|
|
46
|
+
The plugin builds a session-batch payload for Distlang AI Debugger:
|
|
47
|
+
|
|
48
|
+
- `session`
|
|
49
|
+
- `interaction`
|
|
50
|
+
- `step`
|
|
51
|
+
|
|
52
|
+
Step kinds currently emitted when observable:
|
|
53
|
+
|
|
54
|
+
- `llm_call`
|
|
55
|
+
- `tool_call`
|
|
56
|
+
- `file_edit`
|
|
57
|
+
|
|
58
|
+
## Development
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
npm test
|
|
62
|
+
npm run pack:check
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Release
|
|
66
|
+
|
|
67
|
+
This repo uses a manual release flow.
|
|
68
|
+
|
|
69
|
+
1. Verify the package locally:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
npm run release
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
2. Push the release commit:
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
git push origin main
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
3. Publish to npm:
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
npm run publish
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
4. Create and push the release tag:
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
git tag -a v0.1.0 -m "v0.1.0"
|
|
91
|
+
git push origin v0.1.0
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
5. Optional GitHub release:
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
gh release create v0.1.0 --title "v0.1.0"
|
|
98
|
+
```
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@distlang/opencode-plugin",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "OpenCode plugin for Distlang AI Debugger",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"default": "./src/index.js"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"src",
|
|
14
|
+
"README.md"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"test": "node --check src/index.js && node --check src/recorder.js && node --check src/distlang.js",
|
|
18
|
+
"check": "npm test",
|
|
19
|
+
"pack:check": "npm pack --dry-run",
|
|
20
|
+
"release": "npm test && npm run pack:check",
|
|
21
|
+
"publish": "npm publish --access public"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"distlang",
|
|
25
|
+
"opencode",
|
|
26
|
+
"plugin",
|
|
27
|
+
"ai-debugger"
|
|
28
|
+
],
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/distlanglabs/opencode-plugin.git"
|
|
32
|
+
},
|
|
33
|
+
"homepage": "https://github.com/distlanglabs/opencode-plugin#readme",
|
|
34
|
+
"bugs": {
|
|
35
|
+
"url": "https://github.com/distlanglabs/opencode-plugin/issues"
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public"
|
|
39
|
+
},
|
|
40
|
+
"license": "MIT"
|
|
41
|
+
}
|
package/src/distlang.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promises as fs } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
|
|
8
|
+
const execFileAsync = promisify(execFile);
|
|
9
|
+
|
|
10
|
+
export async function runDistlang(args, options = {}) {
|
|
11
|
+
return execFileAsync("distlang", args, {
|
|
12
|
+
env: process.env,
|
|
13
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
14
|
+
...options,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function getAuthStatus() {
|
|
19
|
+
const { stdout } = await runDistlang(["helpers", "auth", "status", "--json"]);
|
|
20
|
+
return JSON.parse(stdout || "{}");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function uploadAIDebuggerPayload(payload) {
|
|
24
|
+
const tempFile = join(tmpdir(), `distlang-ai-debugger-${randomUUID()}.json`);
|
|
25
|
+
await fs.writeFile(tempFile, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
|
|
26
|
+
try {
|
|
27
|
+
const { stdout } = await runDistlang([
|
|
28
|
+
"helpers",
|
|
29
|
+
"request",
|
|
30
|
+
"POST",
|
|
31
|
+
"/ai-debugger/v1/ingest",
|
|
32
|
+
`--body-file=${tempFile}`,
|
|
33
|
+
"--content-type=application/json",
|
|
34
|
+
"--json",
|
|
35
|
+
]);
|
|
36
|
+
return JSON.parse(stdout || "{}");
|
|
37
|
+
} finally {
|
|
38
|
+
await fs.unlink(tempFile).catch(() => {});
|
|
39
|
+
}
|
|
40
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { createRecorder } from "./recorder.js";
|
|
2
|
+
import { getAuthStatus, uploadAIDebuggerPayload } from "./distlang.js";
|
|
3
|
+
|
|
4
|
+
function configuredValue(value, fallback = "") {
|
|
5
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : fallback;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function debugEnabled() {
|
|
9
|
+
const value = configuredValue(process.env.DISTLANG_OPENCODE_DEBUG, "").toLowerCase();
|
|
10
|
+
return value === "1" || value === "true" || value === "yes" || value === "on";
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export const DistlangAIDebugger = async ({ project, directory, client }) => {
|
|
14
|
+
const debug = debugEnabled();
|
|
15
|
+
const recorder = createRecorder({ project, directory });
|
|
16
|
+
let loggedInit = false;
|
|
17
|
+
let authChecked = false;
|
|
18
|
+
let authAvailable = false;
|
|
19
|
+
let authWarningLogged = false;
|
|
20
|
+
let distlangMissingLogged = false;
|
|
21
|
+
|
|
22
|
+
async function log(level, message, extra = undefined) {
|
|
23
|
+
if (!client || !client.app || typeof client.app.log !== "function") {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
await client.app.log({
|
|
27
|
+
body: {
|
|
28
|
+
service: "distlang-ai-debugger",
|
|
29
|
+
level,
|
|
30
|
+
message,
|
|
31
|
+
extra,
|
|
32
|
+
},
|
|
33
|
+
}).catch(() => {});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function debugLog(message, extra = undefined) {
|
|
37
|
+
if (!debug) {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
await log("debug", message, extra);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function logInit() {
|
|
44
|
+
if (loggedInit) {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
loggedInit = true;
|
|
48
|
+
await log(debug ? "debug" : "info", "Distlang OpenCode AI Debugger plugin initialized", {
|
|
49
|
+
debug,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function ensureAuthStatus() {
|
|
54
|
+
if (authChecked) {
|
|
55
|
+
return authAvailable;
|
|
56
|
+
}
|
|
57
|
+
authChecked = true;
|
|
58
|
+
try {
|
|
59
|
+
const payload = await getAuthStatus();
|
|
60
|
+
authAvailable = payload && payload.ok === true && payload.logged_in === true;
|
|
61
|
+
if (!authAvailable && !authWarningLogged) {
|
|
62
|
+
authWarningLogged = true;
|
|
63
|
+
await log("warn", "Distlang AI Debugger upload disabled: run `distlang helpers login` first", { auth: payload });
|
|
64
|
+
}
|
|
65
|
+
return authAvailable;
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (error && typeof error === "object" && error.code === "ENOENT") {
|
|
68
|
+
if (!distlangMissingLogged) {
|
|
69
|
+
distlangMissingLogged = true;
|
|
70
|
+
await log("warn", "distlang CLI not found; AI Debugger upload disabled");
|
|
71
|
+
}
|
|
72
|
+
} else if (!authWarningLogged) {
|
|
73
|
+
authWarningLogged = true;
|
|
74
|
+
await log("warn", "Distlang AI Debugger auth check failed; upload disabled", { error: String(error) });
|
|
75
|
+
}
|
|
76
|
+
authAvailable = false;
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function finalizeSession(sessionID, result) {
|
|
82
|
+
const payload = recorder.finalizeSession(sessionID, result, Date.now());
|
|
83
|
+
if (!payload) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (!(await ensureAuthStatus())) {
|
|
87
|
+
await debugLog("Skipping AI debugger upload because auth is unavailable", { sessionID });
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
const response = await uploadAIDebuggerPayload(payload);
|
|
92
|
+
if (!response.ok) {
|
|
93
|
+
await log("warn", "AI Debugger upload failed", { sessionID, response });
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
await debugLog("AI Debugger session uploaded", { sessionID, response });
|
|
97
|
+
} catch (error) {
|
|
98
|
+
await log("warn", "AI Debugger upload failed", { sessionID, error: String(error) });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
event: async ({ event }) => {
|
|
104
|
+
await logInit();
|
|
105
|
+
if (!event || typeof event !== "object") {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (event.type === "session.created") {
|
|
110
|
+
const observed = recorder.observeSessionCreated(event);
|
|
111
|
+
if (observed) {
|
|
112
|
+
await debugLog("session.created observed", observed);
|
|
113
|
+
}
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (event.type === "session.idle" || event.type === "session.error") {
|
|
118
|
+
const sessionID = configuredValue(event.sessionID, "");
|
|
119
|
+
if (!sessionID) {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const result = event.type === "session.error" ? "error" : "success";
|
|
123
|
+
await debugLog(`${event.type} observed`, { sessionID, result });
|
|
124
|
+
await finalizeSession(sessionID, result);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (event.type === "file.edited") {
|
|
129
|
+
const observed = recorder.observeFileEdited(event);
|
|
130
|
+
if (observed) {
|
|
131
|
+
await debugLog("file.edited observed", observed);
|
|
132
|
+
}
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (event.type !== "message.updated") {
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const userMessage = recorder.observeUserMessage(event);
|
|
141
|
+
if (userMessage) {
|
|
142
|
+
await debugLog("user message observed", userMessage);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const assistantMessage = recorder.observeAssistantMessage(event);
|
|
147
|
+
if (assistantMessage) {
|
|
148
|
+
await debugLog("assistant message update observed", assistantMessage);
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
|
|
152
|
+
"tool.execute.before": async (input) => {
|
|
153
|
+
await logInit();
|
|
154
|
+
const observed = recorder.observeToolBefore(input);
|
|
155
|
+
if (observed) {
|
|
156
|
+
await debugLog("tool.execute.before observed", observed);
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
|
|
160
|
+
"tool.execute.after": async (input, output) => {
|
|
161
|
+
await logInit();
|
|
162
|
+
const observed = recorder.observeToolAfter(input, output);
|
|
163
|
+
if (observed) {
|
|
164
|
+
await debugLog("tool.execute.after observed", observed);
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
export default DistlangAIDebugger;
|
package/src/recorder.js
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
import { basename, extname } from "node:path";
|
|
2
|
+
|
|
3
|
+
const extensionLanguages = {
|
|
4
|
+
".c": "c",
|
|
5
|
+
".cc": "cpp",
|
|
6
|
+
".cpp": "cpp",
|
|
7
|
+
".cs": "csharp",
|
|
8
|
+
".css": "css",
|
|
9
|
+
".go": "go",
|
|
10
|
+
".h": "c",
|
|
11
|
+
".hpp": "cpp",
|
|
12
|
+
".html": "html",
|
|
13
|
+
".java": "java",
|
|
14
|
+
".js": "javascript",
|
|
15
|
+
".json": "json",
|
|
16
|
+
".jsx": "javascript",
|
|
17
|
+
".kt": "kotlin",
|
|
18
|
+
".md": "markdown",
|
|
19
|
+
".mjs": "javascript",
|
|
20
|
+
".php": "php",
|
|
21
|
+
".py": "python",
|
|
22
|
+
".rb": "ruby",
|
|
23
|
+
".rs": "rust",
|
|
24
|
+
".sh": "shell",
|
|
25
|
+
".sql": "sql",
|
|
26
|
+
".svg": "svg",
|
|
27
|
+
".toml": "toml",
|
|
28
|
+
".ts": "typescript",
|
|
29
|
+
".tsx": "typescript",
|
|
30
|
+
".txt": "text",
|
|
31
|
+
".yaml": "yaml",
|
|
32
|
+
".yml": "yaml",
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export function createRecorder({ project, directory }) {
|
|
36
|
+
const projectName = deriveProjectName(project, directory);
|
|
37
|
+
const sessions = new Map();
|
|
38
|
+
|
|
39
|
+
function activeSessionID() {
|
|
40
|
+
if (sessions.size === 1) {
|
|
41
|
+
return Array.from(sessions.keys())[0] || "";
|
|
42
|
+
}
|
|
43
|
+
return "";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function ensureSession(sessionID, startedAtMs = Date.now()) {
|
|
47
|
+
if (sessions.has(sessionID)) {
|
|
48
|
+
return sessions.get(sessionID);
|
|
49
|
+
}
|
|
50
|
+
const recorder = {
|
|
51
|
+
id: sessionID,
|
|
52
|
+
source: "opencode",
|
|
53
|
+
project: projectName,
|
|
54
|
+
startedAtMs,
|
|
55
|
+
endedAtMs: 0,
|
|
56
|
+
status: "success",
|
|
57
|
+
summary: "",
|
|
58
|
+
interactions: [],
|
|
59
|
+
currentInteractionID: "",
|
|
60
|
+
interactionCounter: 0,
|
|
61
|
+
stepCounter: 0,
|
|
62
|
+
assistantStates: new Map(),
|
|
63
|
+
toolStarts: new Map(),
|
|
64
|
+
seenUserMessages: new Set(),
|
|
65
|
+
};
|
|
66
|
+
sessions.set(sessionID, recorder);
|
|
67
|
+
return recorder;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function createInteraction(recorder, prompt, timestampMs) {
|
|
71
|
+
recorder.interactionCounter += 1;
|
|
72
|
+
const interaction = {
|
|
73
|
+
id: `${recorder.id}:int:${recorder.interactionCounter}`,
|
|
74
|
+
index: recorder.interactionCounter,
|
|
75
|
+
prompt: configuredValue(prompt, `OpenCode interaction ${recorder.interactionCounter}`),
|
|
76
|
+
mode: "build",
|
|
77
|
+
startedAtMs: timestampMs,
|
|
78
|
+
endedAtMs: 0,
|
|
79
|
+
status: "success",
|
|
80
|
+
summary: "",
|
|
81
|
+
steps: [],
|
|
82
|
+
};
|
|
83
|
+
recorder.interactions.push(interaction);
|
|
84
|
+
recorder.currentInteractionID = interaction.id;
|
|
85
|
+
return interaction;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function findInteraction(recorder, interactionID) {
|
|
89
|
+
return recorder.interactions.find((interaction) => interaction.id === interactionID) || null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function ensureInteraction(recorder, timestampMs, prompt = "") {
|
|
93
|
+
const current = findInteraction(recorder, recorder.currentInteractionID);
|
|
94
|
+
if (current) {
|
|
95
|
+
if (prompt && (!current.prompt || current.prompt.startsWith("OpenCode interaction "))) {
|
|
96
|
+
current.prompt = prompt;
|
|
97
|
+
}
|
|
98
|
+
return current;
|
|
99
|
+
}
|
|
100
|
+
return createInteraction(recorder, prompt, timestampMs);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function addStep(recorder, interaction, step) {
|
|
104
|
+
recorder.stepCounter += 1;
|
|
105
|
+
const normalized = {
|
|
106
|
+
id: `${recorder.id}:step:${recorder.stepCounter}`,
|
|
107
|
+
index: recorder.stepCounter,
|
|
108
|
+
kind: step.kind,
|
|
109
|
+
phase: configuredValue(step.phase, "build"),
|
|
110
|
+
title: configuredValue(step.title, step.kind),
|
|
111
|
+
started_at: normalizeDateTime(step.started_at, new Date().toISOString()),
|
|
112
|
+
ended_at: step.ended_at ? normalizeDateTime(step.ended_at, new Date().toISOString()) : null,
|
|
113
|
+
duration_ms: Math.max(0, Math.floor(finiteNumber(step.duration_ms))),
|
|
114
|
+
status: configuredValue(step.status, "success"),
|
|
115
|
+
provider: configuredValue(step.provider, "") || null,
|
|
116
|
+
model: configuredValue(step.model, "") || null,
|
|
117
|
+
tool_name: configuredValue(step.tool_name, "") || null,
|
|
118
|
+
input_tokens: Math.max(0, Math.floor(finiteNumber(step.input_tokens))),
|
|
119
|
+
output_tokens: Math.max(0, Math.floor(finiteNumber(step.output_tokens))),
|
|
120
|
+
reasoning_tokens: Math.max(0, Math.floor(finiteNumber(step.reasoning_tokens))),
|
|
121
|
+
cached_tokens: Math.max(0, Math.floor(finiteNumber(step.cached_tokens))),
|
|
122
|
+
context_size_tokens: Math.max(0, Math.floor(finiteNumber(step.context_size_tokens))),
|
|
123
|
+
cost_usd: finiteNumber(step.cost_usd),
|
|
124
|
+
first_token_at: step.first_token_at ? normalizeDateTime(step.first_token_at, new Date().toISOString()) : null,
|
|
125
|
+
first_token_latency_ms: Math.max(0, Math.floor(finiteNumber(step.first_token_latency_ms))),
|
|
126
|
+
payload_json: step.payload_json ?? null,
|
|
127
|
+
};
|
|
128
|
+
interaction.steps.push(normalized);
|
|
129
|
+
interaction.endedAtMs = Math.max(interaction.endedAtMs || 0, Date.parse(normalized.ended_at || normalized.started_at));
|
|
130
|
+
recorder.summary = configuredValue(recorder.summary, summarizePrompt(interaction.prompt, interaction.summary || `OpenCode session ${recorder.id}`));
|
|
131
|
+
return normalized;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function observeSessionCreated(event) {
|
|
135
|
+
const sessionInfo = event.info && typeof event.info === "object" ? event.info : {};
|
|
136
|
+
const sessionID = configuredValue(event.sessionID, configuredValue(sessionInfo.id, ""));
|
|
137
|
+
if (!sessionID) {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
ensureSession(sessionID, parseTimestamp(sessionInfo.time, Date.now()));
|
|
141
|
+
return { sessionID };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function observeFileEdited(event) {
|
|
145
|
+
const filePath = configuredValue(event.file, configuredValue(event.properties && event.properties.file, ""));
|
|
146
|
+
const sessionID = configuredValue(event.sessionID, activeSessionID());
|
|
147
|
+
if (!filePath || !sessionID) {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
const recorder = ensureSession(sessionID, Date.now());
|
|
151
|
+
const interaction = ensureInteraction(recorder, Date.now());
|
|
152
|
+
addStep(recorder, interaction, {
|
|
153
|
+
kind: "file_edit",
|
|
154
|
+
phase: "build",
|
|
155
|
+
title: `Edit ${filePath}`,
|
|
156
|
+
started_at: new Date().toISOString(),
|
|
157
|
+
ended_at: new Date().toISOString(),
|
|
158
|
+
status: "success",
|
|
159
|
+
payload_json: { file_path: filePath, language: inferLanguage(filePath) },
|
|
160
|
+
});
|
|
161
|
+
return { sessionID, filePath, language: inferLanguage(filePath) };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function observeUserMessage(event) {
|
|
165
|
+
const info = extractMessageInfo(event);
|
|
166
|
+
const sessionID = messageSessionID(info, event) || activeSessionID();
|
|
167
|
+
if (!sessionID || !isUserMessage(info)) {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
const recorder = ensureSession(sessionID, Date.now());
|
|
171
|
+
const id = messageID(info) || `${sessionID}:user:${Date.now()}`;
|
|
172
|
+
const prompt = extractMessageText(info);
|
|
173
|
+
if (!prompt || recorder.seenUserMessages.has(id)) {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
recorder.seenUserMessages.add(id);
|
|
177
|
+
createInteraction(recorder, prompt, parseTimestamp(info && info.time, Date.now()));
|
|
178
|
+
return { sessionID, messageID: id, prompt };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function observeAssistantMessage(event) {
|
|
182
|
+
const info = extractMessageInfo(event);
|
|
183
|
+
const sessionID = messageSessionID(info, event) || activeSessionID();
|
|
184
|
+
if (!sessionID || !isAssistantMessage(info)) {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
const id = messageID(info);
|
|
188
|
+
if (!id) {
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
const recorder = ensureSession(sessionID, Date.now());
|
|
192
|
+
const interaction = ensureInteraction(recorder, Date.now());
|
|
193
|
+
const now = Date.now();
|
|
194
|
+
const existing = recorder.assistantStates.get(id) || {
|
|
195
|
+
firstSeenAt: parseTimestamp(info && info.time, now),
|
|
196
|
+
firstTokenAt: null,
|
|
197
|
+
interactionID: interaction.id,
|
|
198
|
+
provider: assistantProvider(info),
|
|
199
|
+
model: assistantModel(info),
|
|
200
|
+
finalized: false,
|
|
201
|
+
};
|
|
202
|
+
const tokens = tokensFromMessage(info);
|
|
203
|
+
if (existing.firstTokenAt == null && tokens.output > 0) {
|
|
204
|
+
existing.firstTokenAt = now;
|
|
205
|
+
}
|
|
206
|
+
existing.provider = assistantProvider(info);
|
|
207
|
+
existing.model = assistantModel(info);
|
|
208
|
+
const finalState = assistantFinalState(info);
|
|
209
|
+
if (finalState.isFinal && !existing.finalized) {
|
|
210
|
+
existing.finalized = true;
|
|
211
|
+
const targetInteraction = findInteraction(recorder, existing.interactionID) || interaction;
|
|
212
|
+
addStep(recorder, targetInteraction, {
|
|
213
|
+
kind: "llm_call",
|
|
214
|
+
phase: targetInteraction.mode,
|
|
215
|
+
title: summarizePrompt(extractMessageText(info), `Assistant response ${targetInteraction.index}`),
|
|
216
|
+
started_at: new Date(existing.firstSeenAt).toISOString(),
|
|
217
|
+
ended_at: new Date(now).toISOString(),
|
|
218
|
+
duration_ms: Math.max(0, now - existing.firstSeenAt),
|
|
219
|
+
status: finalState.result,
|
|
220
|
+
provider: existing.provider,
|
|
221
|
+
model: existing.model,
|
|
222
|
+
input_tokens: tokens.input,
|
|
223
|
+
output_tokens: tokens.output,
|
|
224
|
+
reasoning_tokens: tokens.reasoning,
|
|
225
|
+
cached_tokens: tokens.cached,
|
|
226
|
+
cost_usd: finiteNumber(info && info.cost),
|
|
227
|
+
first_token_at: existing.firstTokenAt != null ? new Date(existing.firstTokenAt).toISOString() : null,
|
|
228
|
+
first_token_latency_ms: existing.firstTokenAt != null ? Math.max(0, existing.firstTokenAt - existing.firstSeenAt) : 0,
|
|
229
|
+
payload_json: { message_id: id },
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
recorder.assistantStates.set(id, existing);
|
|
233
|
+
return {
|
|
234
|
+
sessionID,
|
|
235
|
+
messageID: id,
|
|
236
|
+
provider: existing.provider,
|
|
237
|
+
model: existing.model,
|
|
238
|
+
tokens,
|
|
239
|
+
cost: finiteNumber(info && info.cost),
|
|
240
|
+
finalized: existing.finalized,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function observeToolBefore(input) {
|
|
245
|
+
const sessionID = configuredValue(input && input.sessionID, activeSessionID());
|
|
246
|
+
const callID = configuredValue(input && input.callID, "");
|
|
247
|
+
if (!sessionID || !callID) {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
const recorder = ensureSession(sessionID, Date.now());
|
|
251
|
+
recorder.toolStarts.set(callID, {
|
|
252
|
+
startedAt: Date.now(),
|
|
253
|
+
tool: configuredValue(input && input.tool, "unknown"),
|
|
254
|
+
});
|
|
255
|
+
return { sessionID, callID, tool: configuredValue(input && input.tool, "unknown") };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function observeToolAfter(input, output) {
|
|
259
|
+
const sessionID = configuredValue(input && input.sessionID, activeSessionID());
|
|
260
|
+
const callID = configuredValue(input && input.callID, "");
|
|
261
|
+
if (!sessionID) {
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
const recorder = ensureSession(sessionID, Date.now());
|
|
265
|
+
const toolState = callID && recorder.toolStarts.has(callID)
|
|
266
|
+
? recorder.toolStarts.get(callID)
|
|
267
|
+
: { startedAt: Date.now(), tool: configuredValue(input && input.tool, "unknown") };
|
|
268
|
+
const interaction = ensureInteraction(recorder, Date.now());
|
|
269
|
+
addStep(recorder, interaction, {
|
|
270
|
+
kind: "tool_call",
|
|
271
|
+
phase: interaction.mode,
|
|
272
|
+
title: `Run ${configuredValue(toolState.tool, "unknown")}`,
|
|
273
|
+
started_at: new Date(toolState.startedAt).toISOString(),
|
|
274
|
+
ended_at: new Date().toISOString(),
|
|
275
|
+
duration_ms: Math.max(0, Date.now() - toolState.startedAt),
|
|
276
|
+
status: output && output.error ? "error" : "success",
|
|
277
|
+
tool_name: configuredValue(toolState.tool, "unknown"),
|
|
278
|
+
payload_json: output && output.metadata && typeof output.metadata === "object" ? output.metadata : null,
|
|
279
|
+
});
|
|
280
|
+
if (callID) {
|
|
281
|
+
recorder.toolStarts.delete(callID);
|
|
282
|
+
}
|
|
283
|
+
return { sessionID, callID, tool: configuredValue(toolState.tool, "unknown"), result: output && output.error ? "error" : "success" };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function finalizeSession(sessionID, result, endedAtMs) {
|
|
287
|
+
const recorder = sessions.get(sessionID);
|
|
288
|
+
if (!recorder) {
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
recorder.status = result;
|
|
292
|
+
recorder.endedAtMs = endedAtMs;
|
|
293
|
+
for (const interaction of recorder.interactions) {
|
|
294
|
+
if (!interaction.endedAtMs || interaction.endedAtMs < interaction.startedAtMs) {
|
|
295
|
+
interaction.endedAtMs = endedAtMs;
|
|
296
|
+
}
|
|
297
|
+
interaction.status = inferResultStatus(interaction.steps.map((step) => step.status), result);
|
|
298
|
+
interaction.summary = configuredValue(interaction.summary, summarizePrompt(interaction.prompt, `Interaction ${interaction.index}`));
|
|
299
|
+
}
|
|
300
|
+
const payload = buildSessionPayload(recorder);
|
|
301
|
+
sessions.delete(sessionID);
|
|
302
|
+
return payload;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
return {
|
|
306
|
+
observeSessionCreated,
|
|
307
|
+
observeFileEdited,
|
|
308
|
+
observeUserMessage,
|
|
309
|
+
observeAssistantMessage,
|
|
310
|
+
observeToolBefore,
|
|
311
|
+
observeToolAfter,
|
|
312
|
+
finalizeSession,
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function buildSessionPayload(recorder) {
|
|
317
|
+
const interactions = recorder.interactions.map(buildInteractionPayload);
|
|
318
|
+
const allSteps = interactions.flatMap((interaction) => interaction.steps);
|
|
319
|
+
const llmSteps = allSteps.filter((step) => step.kind === "llm_call");
|
|
320
|
+
const contextValues = llmSteps.map((step) => step.context_size_tokens).filter((value) => value > 0);
|
|
321
|
+
const modelsUsed = Array.from(new Set(llmSteps.map((step) => step.model).filter(Boolean)));
|
|
322
|
+
return {
|
|
323
|
+
source: recorder.source,
|
|
324
|
+
project: recorder.project,
|
|
325
|
+
session: {
|
|
326
|
+
id: recorder.id,
|
|
327
|
+
started_at: new Date(recorder.startedAtMs).toISOString(),
|
|
328
|
+
ended_at: new Date(recorder.endedAtMs || Date.now()).toISOString(),
|
|
329
|
+
duration_ms: Math.max(0, (recorder.endedAtMs || Date.now()) - recorder.startedAtMs),
|
|
330
|
+
status: inferResultStatus(interactions.map((interaction) => interaction.status), recorder.status),
|
|
331
|
+
summary: configuredValue(recorder.summary, interactions[0]?.summary || `OpenCode session ${recorder.id}`),
|
|
332
|
+
total_cost_usd: allSteps.reduce((total, step) => total + finiteNumber(step.cost_usd), 0),
|
|
333
|
+
input_tokens: allSteps.reduce((total, step) => total + finiteNumber(step.input_tokens), 0),
|
|
334
|
+
output_tokens: allSteps.reduce((total, step) => total + finiteNumber(step.output_tokens), 0),
|
|
335
|
+
reasoning_tokens: allSteps.reduce((total, step) => total + finiteNumber(step.reasoning_tokens), 0),
|
|
336
|
+
cached_tokens: allSteps.reduce((total, step) => total + finiteNumber(step.cached_tokens), 0),
|
|
337
|
+
llm_call_count: llmSteps.length,
|
|
338
|
+
context_size_tokens_p50: percentile(contextValues, 50),
|
|
339
|
+
context_size_tokens_p95: percentile(contextValues, 95),
|
|
340
|
+
context_size_tokens_max: contextValues.length > 0 ? Math.max(...contextValues) : 0,
|
|
341
|
+
models_used: modelsUsed,
|
|
342
|
+
files_changed_count: allSteps.filter((step) => step.kind === "file_edit").length,
|
|
343
|
+
retry_count: allSteps.filter((step) => step.kind === "retry").length,
|
|
344
|
+
},
|
|
345
|
+
interactions,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function buildInteractionPayload(interaction) {
|
|
350
|
+
const llmSteps = interaction.steps.filter((step) => step.kind === "llm_call");
|
|
351
|
+
const contextValues = llmSteps.map((step) => step.context_size_tokens).filter((value) => value > 0);
|
|
352
|
+
const prompt = configuredValue(interaction.prompt, `Interaction ${interaction.index}`);
|
|
353
|
+
return {
|
|
354
|
+
id: interaction.id,
|
|
355
|
+
index: interaction.index,
|
|
356
|
+
prompt,
|
|
357
|
+
mode: interaction.mode,
|
|
358
|
+
started_at: new Date(interaction.startedAtMs || Date.now()).toISOString(),
|
|
359
|
+
ended_at: interaction.endedAtMs > 0 ? new Date(interaction.endedAtMs).toISOString() : new Date(Date.now()).toISOString(),
|
|
360
|
+
duration_ms: Math.max(0, (interaction.endedAtMs || Date.now()) - interaction.startedAtMs),
|
|
361
|
+
status: inferResultStatus(interaction.steps.map((step) => step.status), interaction.status),
|
|
362
|
+
summary: configuredValue(interaction.summary, summarizePrompt(prompt, `Interaction ${interaction.index}`)),
|
|
363
|
+
llm_call_count: llmSteps.length,
|
|
364
|
+
cost_usd: interaction.steps.reduce((total, step) => total + finiteNumber(step.cost_usd), 0),
|
|
365
|
+
input_tokens: interaction.steps.reduce((total, step) => total + finiteNumber(step.input_tokens), 0),
|
|
366
|
+
output_tokens: interaction.steps.reduce((total, step) => total + finiteNumber(step.output_tokens), 0),
|
|
367
|
+
reasoning_tokens: interaction.steps.reduce((total, step) => total + finiteNumber(step.reasoning_tokens), 0),
|
|
368
|
+
cached_tokens: interaction.steps.reduce((total, step) => total + finiteNumber(step.cached_tokens), 0),
|
|
369
|
+
context_size_tokens_p50: percentile(contextValues, 50),
|
|
370
|
+
context_size_tokens_p95: percentile(contextValues, 95),
|
|
371
|
+
context_size_tokens_max: contextValues.length > 0 ? Math.max(...contextValues) : 0,
|
|
372
|
+
step_count: interaction.steps.length,
|
|
373
|
+
steps: interaction.steps,
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function configuredValue(value, fallback = "") {
|
|
378
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : fallback;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function deriveProjectName(project, directory) {
|
|
382
|
+
const explicit = configuredValue(project && project.name, "");
|
|
383
|
+
if (explicit !== "") {
|
|
384
|
+
return explicit;
|
|
385
|
+
}
|
|
386
|
+
return configuredValue(basename(directory || ""), "unknown");
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function inferLanguage(filePath) {
|
|
390
|
+
const extension = extname(String(filePath || "")).toLowerCase();
|
|
391
|
+
return extensionLanguages[extension] || "unknown";
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function finiteNumber(value) {
|
|
395
|
+
const amount = Number(value);
|
|
396
|
+
return Number.isFinite(amount) ? amount : 0;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function parseTimestamp(value, fallback) {
|
|
400
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
401
|
+
const timestamp = Date.parse(value);
|
|
402
|
+
if (Number.isFinite(timestamp)) {
|
|
403
|
+
return timestamp;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
407
|
+
return value;
|
|
408
|
+
}
|
|
409
|
+
return fallback;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function normalizeDateTime(value, fallback = new Date().toISOString()) {
|
|
413
|
+
const timestamp = parseTimestamp(value, Number.NaN);
|
|
414
|
+
if (Number.isFinite(timestamp)) {
|
|
415
|
+
return new Date(timestamp).toISOString();
|
|
416
|
+
}
|
|
417
|
+
return fallback;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function extractMessageInfo(event) {
|
|
421
|
+
if (!event || typeof event !== "object") {
|
|
422
|
+
return null;
|
|
423
|
+
}
|
|
424
|
+
if (event.info && typeof event.info === "object") {
|
|
425
|
+
return event.info;
|
|
426
|
+
}
|
|
427
|
+
if (event.properties && event.properties.info && typeof event.properties.info === "object") {
|
|
428
|
+
return event.properties.info;
|
|
429
|
+
}
|
|
430
|
+
return null;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function isAssistantMessage(info) {
|
|
434
|
+
if (!info || typeof info !== "object") {
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
if (info.role === "assistant" || info.type === "assistant") {
|
|
438
|
+
return true;
|
|
439
|
+
}
|
|
440
|
+
if (configuredValue(info.providerID, "") !== "" || configuredValue(info.modelID, "") !== "") {
|
|
441
|
+
return true;
|
|
442
|
+
}
|
|
443
|
+
if (info.tokens || typeof info.cost !== "undefined" || info.finish || info.error) {
|
|
444
|
+
return true;
|
|
445
|
+
}
|
|
446
|
+
return false;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function isUserMessage(info) {
|
|
450
|
+
if (!info || typeof info !== "object") {
|
|
451
|
+
return false;
|
|
452
|
+
}
|
|
453
|
+
return info.role === "user" || info.type === "user";
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function messageID(info) {
|
|
457
|
+
return configuredValue(info && info.id, "");
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function messageSessionID(info, event) {
|
|
461
|
+
return configuredValue(info && info.sessionID, configuredValue(event && event.sessionID, ""));
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function assistantProvider(info) {
|
|
465
|
+
return configuredValue(info && info.providerID, configuredValue(info && info.model && info.model.providerID, "unknown"));
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function assistantModel(info) {
|
|
469
|
+
return configuredValue(info && info.modelID, configuredValue(info && info.model && info.model.modelID, "unknown"));
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function assistantFinalState(info) {
|
|
473
|
+
const hasError = Boolean(info && info.error);
|
|
474
|
+
const status = configuredValue(info && info.status, "").toLowerCase();
|
|
475
|
+
const finish = info && info.finish;
|
|
476
|
+
const done = info && info.done;
|
|
477
|
+
const isFinal = hasError || finish != null || done === true || status === "completed" || status === "error" || status === "failed";
|
|
478
|
+
return {
|
|
479
|
+
isFinal,
|
|
480
|
+
result: hasError || status === "error" || status === "failed" ? "error" : "success",
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function tokensFromMessage(info) {
|
|
485
|
+
const tokens = info && typeof info === "object" ? info.tokens : null;
|
|
486
|
+
const cacheValue = tokens && typeof tokens === "object"
|
|
487
|
+
? (tokens.cache ?? tokens.cached ?? tokens.cacheReadInputTokens ?? tokens.cachedInput)
|
|
488
|
+
: 0;
|
|
489
|
+
return {
|
|
490
|
+
input: finiteNumber(tokens && tokens.input),
|
|
491
|
+
output: finiteNumber(tokens && tokens.output),
|
|
492
|
+
reasoning: finiteNumber(tokens && tokens.reasoning),
|
|
493
|
+
cached: finiteNumber(cacheValue),
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function extractMessageText(info) {
|
|
498
|
+
const direct = configuredValue(info && (info.text ?? info.prompt ?? info.message ?? info.body), "");
|
|
499
|
+
if (direct !== "") {
|
|
500
|
+
return direct;
|
|
501
|
+
}
|
|
502
|
+
if (typeof info?.content === "string" && info.content.trim() !== "") {
|
|
503
|
+
return info.content.trim();
|
|
504
|
+
}
|
|
505
|
+
if (Array.isArray(info?.content)) {
|
|
506
|
+
return info.content
|
|
507
|
+
.map((part) => {
|
|
508
|
+
if (typeof part === "string") {
|
|
509
|
+
return part;
|
|
510
|
+
}
|
|
511
|
+
if (part && typeof part === "object") {
|
|
512
|
+
return configuredValue(part.text ?? part.content ?? part.value, "");
|
|
513
|
+
}
|
|
514
|
+
return "";
|
|
515
|
+
})
|
|
516
|
+
.filter(Boolean)
|
|
517
|
+
.join("\n")
|
|
518
|
+
.trim();
|
|
519
|
+
}
|
|
520
|
+
return "";
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function summarizePrompt(prompt, fallback) {
|
|
524
|
+
const trimmed = configuredValue(prompt, fallback);
|
|
525
|
+
if (trimmed.length <= 80) {
|
|
526
|
+
return trimmed;
|
|
527
|
+
}
|
|
528
|
+
return `${trimmed.slice(0, 77)}...`;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function inferResultStatus(values, fallback = "success") {
|
|
532
|
+
return values.some((value) => value === "error" || value === "failed") ? "error" : fallback;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function percentile(values, p) {
|
|
536
|
+
if (values.length === 0) {
|
|
537
|
+
return 0;
|
|
538
|
+
}
|
|
539
|
+
const sorted = [...values].sort((left, right) => left - right);
|
|
540
|
+
const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1));
|
|
541
|
+
return sorted[index];
|
|
542
|
+
}
|