fix: plugin event shape mismatches, nav highlight bug, and README update

- Fix session.created/deleted reading props.info.id instead of props.id
- Fix session.diff reading FileDiff[] array instead of string
- Fix file.edited reading props.file instead of props.filePath
- Add auto-session creation fallback from tool/chat hooks
- Add flushSession() for intermediate trace sends on session.idle
- Fix dashboard nav: /dashboard exact match prevents false active state
- Update README with TypeScript SDK and OpenCode plugin sections
This commit is contained in:
Vectry
2026-02-10 11:23:33 +00:00
parent 5b388484f8
commit dcc32f36d3
5 changed files with 196 additions and 33 deletions

View File

@@ -6,6 +6,8 @@
<p align="center">
<a href="https://pypi.org/project/vectry-agentlens/"><img src="https://img.shields.io/pypi/v/vectry-agentlens?color=blue" alt="PyPI"></a>
<a href="https://www.npmjs.com/package/agentlens-sdk"><img src="https://img.shields.io/npm/v/agentlens-sdk?color=blue" alt="npm"></a>
<a href="https://www.npmjs.com/package/opencode-agentlens"><img src="https://img.shields.io/npm/v/opencode-agentlens?color=blue&label=opencode-plugin" alt="OpenCode Plugin"></a>
<a href="https://gitea.repi.fun/repi/agentlens/src/branch/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License"></a>
<a href="https://agentlens.vectry.tech"><img src="https://img.shields.io/badge/demo-live-brightgreen" alt="Demo"></a>
</p>
@@ -44,6 +46,8 @@ Open `https://agentlens.vectry.tech/dashboard` to see your traces.
## Features
- **Decision Tracing** -- Log every decision point with reasoning, alternatives, and confidence scores
- **OpenCode Plugin** -- Trace your coding agent sessions with `opencode-agentlens`
- **TypeScript SDK** -- First-class TypeScript support with `agentlens-sdk`
- **OpenAI Integration** -- Auto-instrument OpenAI calls with one line: `wrap_openai(client)`
- **LangChain Integration** -- Drop-in callback handler for LangChain agents
- **Nested Traces** -- Multi-agent workflows with parent-child span relationships
@@ -52,13 +56,62 @@ Open `https://agentlens.vectry.tech/dashboard` to see your traces.
- **Analytics** -- Token usage, cost tracking, duration timelines per trace
- **Self-Hostable** -- Docker Compose deployment, bring your own Postgres + Redis
## OpenCode Plugin
Trace your [OpenCode](https://opencode.ai) coding agent sessions automatically.
```bash
npm install -g opencode-agentlens
```
Add to your `opencode.json`:
```json
{
"plugin": ["opencode-agentlens"]
}
```
Set environment variables:
```bash
export AGENTLENS_API_KEY="your-key"
export AGENTLENS_ENDPOINT="https://agentlens.vectry.tech"
```
Every coding session automatically captures tool calls, LLM interactions, file edits, and permission flows.
## TypeScript SDK
```bash
npm install agentlens-sdk
```
```typescript
import { init, TraceBuilder, SpanType, SpanStatus } from "agentlens-sdk";
init({ apiKey: "your-key", endpoint: "https://agentlens.vectry.tech" });
const trace = new TraceBuilder("my-agent-task", {
tags: ["production"],
});
trace.addSpan({
name: "tool-call",
type: SpanType.TOOL_CALL,
status: SpanStatus.COMPLETED,
});
trace.end();
```
## Architecture
```
SDK (Python) API (Next.js) Dashboard (React)
SDK (Python/TS) API (Next.js) Dashboard (React)
agentlens.trace() ------> POST /api/traces ------> Real-time SSE stream
agentlens.log_decision() Prisma + Postgres Decision tree viz
wrap_openai(client) Redis pub/sub Analytics & filters
TraceBuilder.end() Prisma + Postgres Decision tree viz
OpenCode plugin Redis pub/sub Analytics & filters
```
## Integrations
@@ -145,13 +198,17 @@ agentlens/
apps/web/ # Next.js 15 dashboard + API
packages/database/ # Prisma schema + client
packages/sdk-python/ # Python SDK (PyPI: vectry-agentlens)
packages/sdk-ts/ # TypeScript SDK (npm: agentlens-sdk)
packages/opencode-plugin/ # OpenCode plugin (npm: opencode-agentlens)
examples/ # Example agent scripts
docker-compose.yml # Production deployment
```
## SDK Reference
See the full [Python SDK documentation](packages/sdk-python/README.md).
- [Python SDK documentation](packages/sdk-python/README.md)
- [TypeScript SDK documentation](packages/sdk-ts/README.md)
- [OpenCode plugin documentation](packages/opencode-plugin/README.md)
## Examples

View File

@@ -51,7 +51,11 @@ function Sidebar({ onNavigate }: { onNavigate?: () => void }) {
<nav className="flex-1 p-4 space-y-1">
{navItems.map((item) => {
const Icon = item.icon;
const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`);
const isActive =
item.href === "/dashboard"
? pathname === "/dashboard"
: pathname === item.href ||
pathname.startsWith(`${item.href}/`);
return (
<Link

View File

@@ -1,6 +1,6 @@
{
"name": "opencode-agentlens",
"version": "0.1.0",
"version": "0.1.1",
"description": "OpenCode plugin for AgentLens — trace your coding agent's decisions, tool calls, and sessions",
"type": "module",
"main": "./dist/index.cjs",

View File

@@ -5,6 +5,19 @@ import { loadConfig } from "./config.js";
import { SessionState } from "./state.js";
import { truncate, safeJsonValue } from "./utils.js";
/**
* OpenCode Event shapes (from @opencode-ai/sdk):
*
* session.created → { type, properties: { info: Session } }
* session.idle → { type, properties: { sessionID: string } }
* session.deleted → { type, properties: { info: Session } }
* session.error → { type, properties: { sessionID?: string, error?: ... } }
* session.diff → { type, properties: { sessionID: string, diff: FileDiff[] } }
* file.edited → { type, properties: { file: string } }
*
* Session = { id, projectID, directory, title, ... }
*/
const plugin: Plugin = async ({ project, directory, worktree }) => {
const config = loadConfig();
@@ -13,6 +26,8 @@ const plugin: Plugin = async ({ project, directory, worktree }) => {
return {};
}
console.log(`[agentlens] Plugin enabled — endpoint: ${config.endpoint}`);
init({
apiKey: config.apiKey,
endpoint: config.endpoint,
@@ -22,6 +37,11 @@ const plugin: Plugin = async ({ project, directory, worktree }) => {
const state = new SessionState();
/** Helper: get a session ID from the active traces (fallback for events that lack one) */
function getAnySessionId(): string | undefined {
return state.getActiveSessionIds()[0];
}
return {
event: async ({ event }) => {
const type = event.type;
@@ -29,66 +49,118 @@ const plugin: Plugin = async ({ project, directory, worktree }) => {
| Record<string, unknown>
| undefined;
if (type === "session.created" && props?.["id"]) {
state.startSession(String(props["id"]), {
if (type === "session.created") {
// props.info is a Session object with { id, projectID, ... }
const info = props?.["info"] as
| Record<string, unknown>
| undefined;
const sessionId = info?.["id"] as string | undefined;
if (sessionId) {
state.startSession(sessionId, {
project: project.id,
directory,
worktree,
title: info?.["title"] as string | undefined,
});
console.log(`[agentlens] Session started: ${sessionId}`);
}
}
if (type === "session.idle") {
const sessionId = props?.["sessionID"] ?? props?.["id"];
if (sessionId) await flush();
// props.sessionID is the session ID string
const sessionId =
(props?.["sessionID"] as string) || getAnySessionId();
if (sessionId) {
// Flush intermediate trace so data isn't lost if session ends abruptly
state.flushSession(sessionId);
await flush();
}
}
if (type === "session.error") {
const sessionId = String(props?.["sessionID"] ?? props?.["id"] ?? "");
const sessionId =
(props?.["sessionID"] as string) || getAnySessionId() || "";
if (sessionId) {
const trace = state.getTrace(sessionId);
if (trace) {
const error = props?.["error"] as
| Record<string, unknown>
| undefined;
trace.addEvent({
type: EventTypeValues.ERROR,
name: String(props?.["error"] ?? "session error"),
metadata: safeJsonValue(props) as JsonValue,
name: String(
error?.["name"] ?? error?.["message"] ?? "session error",
),
metadata: safeJsonValue(error ?? props) as JsonValue,
});
}
}
}
if (type === "session.deleted") {
const sessionId = String(props?.["sessionID"] ?? props?.["id"] ?? "");
if (sessionId) state.endSession(sessionId);
// props.info is a Session object with { id, ... }
const info = props?.["info"] as
| Record<string, unknown>
| undefined;
const sessionId =
(info?.["id"] as string) || getAnySessionId() || "";
if (sessionId) {
state.endSession(sessionId);
await flush();
console.log(`[agentlens] Session ended and flushed: ${sessionId}`);
}
}
if (type === "session.diff") {
const sessionId = String(props?.["sessionID"] ?? props?.["id"] ?? "");
// props.sessionID + props.diff (FileDiff[])
const sessionId =
(props?.["sessionID"] as string) || getAnySessionId() || "";
if (sessionId) {
const trace = state.getTrace(sessionId);
if (trace) {
trace.setMetadata({
diff: truncate(String(props?.["diff"] ?? ""), 5000),
});
const diffs = props?.["diff"];
trace.setMetadata(
safeJsonValue({
diff: Array.isArray(diffs)
? diffs.map((d: Record<string, unknown>) => ({
path: d?.["path"],
additions: d?.["additions"],
deletions: d?.["deletions"],
}))
: diffs,
}) as JsonValue,
);
}
}
}
if (type === "file.edited") {
const sessionId = String(props?.["sessionID"] ?? props?.["id"] ?? "");
// props.file is a string (file path), no sessionID on this event
const file = props?.["file"] as string | undefined;
const sessionId = getAnySessionId();
const trace = sessionId ? state.getTrace(sessionId) : undefined;
if (trace) {
if (trace && file) {
trace.addEvent({
type: EventTypeValues.CUSTOM,
name: "file.edited",
metadata: safeJsonValue({
filePath: props?.["filePath"],
}) as JsonValue,
metadata: safeJsonValue({ filePath: file }) as JsonValue,
});
}
}
},
"tool.execute.before": async (input, output) => {
// Auto-create session if we missed session.created event
if (!state.getTrace(input.sessionID)) {
state.startSession(input.sessionID, {
project: project.id,
directory,
worktree,
});
console.log(
`[agentlens] Auto-created session from tool call: ${input.sessionID}`,
);
}
state.startToolCall(
input.callID,
input.tool,
@@ -107,6 +179,17 @@ const plugin: Plugin = async ({ project, directory, worktree }) => {
},
"chat.message": async (input) => {
// Auto-create session if we missed session.created event
if (!state.getTrace(input.sessionID)) {
state.startSession(input.sessionID, {
project: project.id,
directory,
worktree,
});
console.log(
`[agentlens] Auto-created session from chat.message: ${input.sessionID}`,
);
}
if (input.model) {
state.recordLLMCall(input.sessionID, {
model: input.model,

View File

@@ -4,6 +4,7 @@ import {
SpanStatus,
DecisionType,
nowISO,
getClient,
} from "agentlens-sdk";
import type { JsonValue, TraceStatus } from "agentlens-sdk";
import { extractToolMetadata, safeJsonValue } from "./utils.js";
@@ -180,4 +181,22 @@ export class SessionState {
getRootSpanId(sessionId: string): string | undefined {
return this.rootSpans.get(sessionId);
}
getActiveSessionIds(): string[] {
return Array.from(this.traces.keys());
}
/**
* Send the current trace state without ending the session.
* This creates a snapshot so data isn't lost if the process exits unexpectedly.
*/
flushSession(sessionId: string): void {
const trace = this.traces.get(sessionId);
if (!trace) return;
const transport = getClient();
if (transport) {
transport.add(trace.toPayload());
}
}
}