Spaces:
Sleeping
Sleeping
File size: 20,018 Bytes
116524e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 | /**
* @kayba_ai/openclaw-tracing β OpenClaw plugin that captures full agent turns
* (user message, LLM input/output with thinking, tool calls, final reply) and
* emits one structured Kayba trace per turn with real wall-clock timing,
* trace-level sessionId/userId, and folder tagging.
*
* Pairs with `@kayba_ai/tracing`. The trader plugin (or any other tool plugin)
* can keep its existing `kayba.trace()` wrapping for tool-level spans β those
* land in the same kayba folder and can be cross-referenced by `runId`.
*/
import kayba from "@kayba_ai/tracing";
import {
startSpan as mlflowStartSpan,
updateCurrentTrace,
SpanStatusCode,
SpanType,
} from "mlflow-tracing";
// ββ Hook payload shapes (probed against openclaw 2026.4.24) ββββββββββββ
interface PluginApi {
pluginConfig?: Record<string, unknown>;
logger: { info: (m: string) => void; warn: (m: string) => void; error?: (m: string) => void };
on: (event: string, handler: (event: unknown, ctx: unknown) => unknown) => void;
}
interface MessageReceivedEvent {
from?: string;
content?: string;
timestamp?: number;
messageId?: string;
senderId?: string;
sessionKey?: string;
metadata?: Record<string, unknown>;
}
interface MessageReceivedCtx {
channelId?: string;
sessionKey?: string;
messageId?: string;
senderId?: string;
}
interface BeforeAgentStartEvent {
prompt?: string;
runId?: string;
}
interface BeforeAgentStartCtx {
runId?: string;
agentId?: string;
sessionKey?: string;
sessionId?: string;
channelId?: string;
}
interface LlmInputEvent {
runId: string;
sessionId: string;
provider: string;
model: string;
systemPrompt?: string;
prompt: string;
historyMessages: unknown[];
imagesCount: number;
}
interface LlmOutputEvent {
runId: string;
sessionId: string;
provider: string;
model: string;
resolvedRef?: string;
harnessId?: string;
assistantTexts: string[];
lastAssistant?: {
role?: string;
content?: Array<{ type: string; text?: string; thinking?: string; name?: string; arguments?: unknown }>;
usage?: unknown;
stopReason?: string;
timestamp?: string | number;
responseId?: string;
};
usage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; total?: number };
}
interface AgentEndEvent {
runId?: string;
messages: unknown[];
success: boolean;
error?: string;
durationMs?: number;
}
interface ConversationCtx {
runId?: string;
trace?: { traceId?: string; spanId?: string; traceFlags?: string };
agentId?: string;
sessionKey?: string;
sessionId?: string;
channelId?: string;
trigger?: string;
}
// ββ Per-turn state βββββββββββββββββββββββββββββββββββββββββββββββββββββ
interface PendingTurn {
runId?: string;
sessionId?: string;
sessionKey?: string;
agentId?: string;
channelId?: string;
senderId?: string;
userMessage?: string;
startedAtMs: number;
llmInputAtMs?: number;
llmOutputAtMs?: number;
endedAtMs?: number;
llmIn?: LlmInputEvent;
llmOut?: LlmOutputEvent;
agentEnd?: AgentEndEvent;
agentEndArrived?: boolean;
finalized?: boolean;
}
const TURN_FINALIZE_DELAY_MS = 250;
const TURN_TIMEOUT_MS = 5 * 60 * 1000;
// ββ Config βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
interface PluginConfig {
apiKey: string;
baseUrl?: string;
folder?: string;
captureSystemPrompt: boolean;
/**
* "delta" β only messages added since the previous turn for this sessionId (default).
* Traces stay ~5β10 KB regardless of conversation length.
* "full" β full historyMessages array on every turn. Bigger traces, no reconstruction needed.
* "none" β drop history entirely.
*/
captureHistory: "delta" | "full" | "none";
maxAttributeBytes: number;
userField: "agentId" | "senderId";
}
function parseConfig(raw: unknown): PluginConfig {
const obj = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};
let captureHistory: PluginConfig["captureHistory"] = "delta";
if (obj.captureHistory === "full" || obj.captureHistory === true) captureHistory = "full";
else if (obj.captureHistory === "none" || obj.captureHistory === false) captureHistory = "none";
// Back-compat: systemPrompt should default to "first turn only" β capture once per session.
// We model it by capturing only when captureSystemPrompt is true AND it's the session's first turn.
return {
apiKey: typeof obj.apiKey === "string" ? obj.apiKey : "",
baseUrl: typeof obj.baseUrl === "string" ? obj.baseUrl : undefined,
folder: typeof obj.folder === "string" ? obj.folder : undefined,
captureSystemPrompt: obj.captureSystemPrompt !== false,
captureHistory,
maxAttributeBytes: typeof obj.maxAttributeBytes === "number" ? obj.maxAttributeBytes : 65536,
userField: obj.userField === "senderId" ? "senderId" : "agentId",
};
}
// ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function truncate(value: unknown, maxBytes: number): unknown {
if (typeof value !== "string") return value;
if (value.length <= maxBytes) return value;
return value.slice(0, maxBytes) + `β¦[truncated ${value.length - maxBytes} bytes]`;
}
/**
* Recursively parse JSON-string fields back into structured values.
*
* OpenClaw's `historyMessages` is array<string>, where each string is a JSON
* encoding of `{role, content, ...}`. The `content` field of those decoded
* objects is *itself* a JSON-encoded array of `[{type, text|thinking|...}]`.
* The same nesting shows up on `lastAssistant.content`, `usage`, `cost`, etc.
*
* If we ship those raw, mlflow JSON-stringifies the whole inputs/outputs blob
* one more time on top, producing an unreadable wall of `\\\\\\\"`. Unwrapping
* once before handoff yields clean, single-level JSON in the dashboard.
*
* Heuristic: a string is "wrapped JSON" if it starts with `{` or `[` and
* `JSON.parse` succeeds. We cap recursion depth so a malicious payload can't
* blow the stack.
*/
function unwrapJsonStrings(value: unknown, depth = 0): unknown {
if (depth > 8) return value;
if (typeof value === "string") {
const trimmed = value.trim();
if (trimmed.length >= 2 && (trimmed[0] === "{" || trimmed[0] === "[")) {
try {
return unwrapJsonStrings(JSON.parse(trimmed), depth + 1);
} catch {
return value;
}
}
return value;
}
if (Array.isArray(value)) return value.map((v) => unwrapJsonStrings(v, depth + 1));
if (value && typeof value === "object") {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
out[k] = unwrapJsonStrings(v, depth + 1);
}
return out;
}
return value;
}
function safe<T>(fn: () => T, label: string, log: PluginApi["logger"]): T | undefined {
try {
return fn();
} catch (err) {
log.warn(`[kayba-tracing] ${label} failed: ${err instanceof Error ? err.message : String(err)}`);
return undefined;
}
}
function resolveUserId(turn: PendingTurn, field: PluginConfig["userField"]): string {
return (field === "senderId" ? turn.senderId : turn.agentId) ?? "";
}
// ββ Plugin entry βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export function register(api: PluginApi): void {
const cfg = parseConfig(api.pluginConfig);
if (!cfg.apiKey) {
api.logger.error?.(
`[kayba-tracing] missing required "apiKey" in plugin config; tracing disabled. ` +
`Add plugins.entries.kayba-tracing.config.apiKey in openclaw.json.`,
);
return;
}
safe(
() =>
kayba.configure({
apiKey: cfg.apiKey,
baseUrl: cfg.baseUrl,
folder: cfg.folder,
}),
"kayba.configure",
api.logger,
);
if (!kayba.isConfigured()) {
api.logger.warn(`[kayba-tracing] kayba SDK did not configure; tracing disabled`);
return;
}
api.logger.info(`[kayba-tracing] configured (folder=${cfg.folder ?? "<none>"}, base=${cfg.baseUrl ?? "default"})`);
// Per-turn state. Keyed by runId once known; before that, by `${sessionKey}:${messageId}` for
// the brief window between message_received and before_agent_start.
const turnsByRunId = new Map<string, PendingTurn>();
const turnsByMessageKey = new Map<string, PendingTurn>();
// Per-session bookkeeping for delta-mode history capture and one-shot system prompt.
// Maps sessionId β number of historyMessages we've already shipped on prior turns.
const sessionHistoryCursor = new Map<string, number>();
const sessionsWithSystemPromptShipped = new Set<string>();
function evictStaleTurns(): void {
const cutoff = Date.now() - TURN_TIMEOUT_MS;
for (const [k, t] of turnsByRunId) if (t.startedAtMs < cutoff) turnsByRunId.delete(k);
for (const [k, t] of turnsByMessageKey) if (t.startedAtMs < cutoff) turnsByMessageKey.delete(k);
}
// ββ message_received: open a turn keyed by sessionKey+messageId βββββ
api.on("message_received", (rawEvent, rawCtx) => {
api.logger.info(`[kayba-tracing] hook: message_received`);
const event = (rawEvent ?? {}) as MessageReceivedEvent;
const ctx = (rawCtx ?? {}) as MessageReceivedCtx;
const sessionKey = event.sessionKey ?? ctx.sessionKey ?? "";
const messageId = event.messageId ?? ctx.messageId ?? "";
if (!sessionKey || !messageId) return;
const key = `${sessionKey}:${messageId}`;
turnsByMessageKey.set(key, {
sessionKey,
channelId: ctx.channelId,
senderId: event.senderId ?? ctx.senderId,
userMessage: event.content,
startedAtMs: typeof event.timestamp === "number" ? event.timestamp : Date.now(),
});
evictStaleTurns();
});
// ββ before_agent_start: bind runId, promote to runId-keyed map ββββββ
api.on("before_agent_start", (rawEvent, rawCtx) => {
api.logger.info(`[kayba-tracing] hook: before_agent_start`);
const event = (rawEvent ?? {}) as BeforeAgentStartEvent;
const ctx = (rawCtx ?? {}) as BeforeAgentStartCtx;
const runId = event.runId ?? ctx.runId;
if (!runId) return;
let turn: PendingTurn | undefined;
if (ctx.sessionKey) {
for (const [k, t] of turnsByMessageKey) {
if (k.startsWith(ctx.sessionKey + ":") && !t.runId) {
turn = t;
turnsByMessageKey.delete(k);
break;
}
}
}
if (!turn) {
// No prior message_received (e.g. CLI-initiated agent run).
turn = { startedAtMs: Date.now() };
}
turn.runId = runId;
turn.sessionId = ctx.sessionId;
turn.agentId = ctx.agentId;
turn.channelId = turn.channelId ?? ctx.channelId;
turnsByRunId.set(runId, turn);
});
// ββ llm_input: stash the prompt + history, mark start time ββββββββββ
api.on("llm_input", (rawEvent, rawCtx) => {
api.logger.info(`[kayba-tracing] hook: llm_input`);
const event = (rawEvent ?? {}) as LlmInputEvent;
const ctx = (rawCtx ?? {}) as ConversationCtx;
const runId = event.runId ?? ctx.runId;
if (!runId) return;
let turn = turnsByRunId.get(runId);
if (!turn) {
turn = { runId, sessionId: event.sessionId, agentId: ctx.agentId, channelId: ctx.channelId, startedAtMs: Date.now() };
turnsByRunId.set(runId, turn);
}
turn.llmIn = event;
turn.llmInputAtMs = Date.now();
turn.sessionId = turn.sessionId ?? event.sessionId;
});
// ββ llm_output: stash response, mark end time βββββββββββββββββββββββ
api.on("llm_output", (rawEvent, rawCtx) => {
api.logger.info(`[kayba-tracing] hook: llm_output`);
const event = (rawEvent ?? {}) as LlmOutputEvent;
const ctx = (rawCtx ?? {}) as ConversationCtx;
const runId = event.runId ?? ctx.runId;
if (!runId) return;
const turn = turnsByRunId.get(runId);
if (!turn) return;
turn.llmOut = event;
turn.llmOutputAtMs = Date.now();
if (turn.agentEndArrived) {
void finalizeTurn(runId);
}
});
// ββ agent_end: defer finalize a tick to absorb any straggling llm_output β
api.on("agent_end", (rawEvent, rawCtx) => {
api.logger.info(`[kayba-tracing] hook: agent_end`);
const event = (rawEvent ?? {}) as AgentEndEvent;
const ctx = (rawCtx ?? {}) as ConversationCtx;
const runId = event.runId ?? ctx.runId;
if (!runId) return;
const turn = turnsByRunId.get(runId);
if (!turn) return;
turn.agentEnd = event;
turn.endedAtMs = Date.now();
turn.agentEndArrived = true;
setTimeout(() => void finalizeTurn(runId), TURN_FINALIZE_DELAY_MS);
});
// ββ Finalize: emit one trace per turn βββββββββββββββββββββββββββββββ
async function finalizeTurn(runId: string): Promise<void> {
const turn = turnsByRunId.get(runId);
if (!turn || turn.finalized) {
api.logger.info(`[kayba-tracing] finalize skipped (turn=${!!turn} finalized=${turn?.finalized})`);
return;
}
turn.finalized = true;
turnsByRunId.delete(runId);
api.logger.info(`[kayba-tracing] finalizing turn runId=${runId} sess=${turn.sessionId} hasLlmIn=${!!turn.llmIn} hasLlmOut=${!!turn.llmOut}`);
const sessionId = turn.sessionId ?? "";
const userId = resolveUserId(turn, cfg.userField);
const success = turn.agentEnd?.success ?? true;
const realDurationMs = turn.agentEnd?.durationMs ?? (turn.endedAtMs ?? Date.now()) - turn.startedAtMs;
// Set process-global session/user so the kayba SDK injects them into trace metadata.
safe(() => kayba.setSession(sessionId || null), "setSession", api.logger);
safe(() => kayba.setUser(userId || null), "setUser", api.logger);
const traced = kayba.trace(
async () => {
// Trace-level metadata + previews. We're inside an active trace context here.
safe(
() =>
updateCurrentTrace({
metadata: {
"openclaw.runId": runId,
"openclaw.agentId": turn.agentId ?? "",
"openclaw.channelId": turn.channelId ?? "",
"openclaw.realDurationMs": String(realDurationMs),
},
requestPreview: turn.userMessage?.slice(0, 200),
responsePreview: turn.llmOut?.assistantTexts?.[0]?.slice(0, 200),
}),
"updateCurrentTrace",
api.logger,
);
// Nested llm.call span. Wall-clock duration is captured as an attribute
// (Number.MAX_SAFE_INTEGER < Date.now() * 1_000_000, so passing startTimeNs
// explicitly to mlflow corrupts the span β the OTel API expects nanos as a
// number which JS can't represent past ~285k years from epoch).
if (turn.llmIn || turn.llmOut) {
const llmRealDurationMs =
(turn.llmOutputAtMs ?? turn.endedAtMs ?? Date.now()) -
(turn.llmInputAtMs ?? turn.startedAtMs);
// Resolve which slice of historyMessages to ship.
const fullHistory = turn.llmIn?.historyMessages ?? [];
let historyToShip: unknown[] | undefined;
let historyMode: "full" | "delta" | "none" = "none";
let historySkipped = 0;
if (cfg.captureHistory === "full" && fullHistory.length > 0) {
historyToShip = fullHistory;
historyMode = "full";
} else if (cfg.captureHistory === "delta" && sessionId) {
const cursor = sessionHistoryCursor.get(sessionId) ?? 0;
historySkipped = Math.min(cursor, fullHistory.length);
historyToShip = fullHistory.slice(historySkipped);
historyMode = "delta";
sessionHistoryCursor.set(sessionId, fullHistory.length);
}
// Capture systemPrompt only on the first turn of each session (it rarely changes).
const shouldShipSystemPrompt =
cfg.captureSystemPrompt &&
!!turn.llmIn?.systemPrompt &&
!!sessionId &&
!sessionsWithSystemPromptShipped.has(sessionId);
if (shouldShipSystemPrompt && sessionId) sessionsWithSystemPromptShipped.add(sessionId);
const llmSpan = mlflowStartSpan({
name: "llm.call",
spanType: SpanType.LLM,
attributes: {
"openclaw.realDurationMs": String(llmRealDurationMs),
"openclaw.startedAtMs": String(turn.llmInputAtMs ?? ""),
"openclaw.endedAtMs": String(turn.llmOutputAtMs ?? ""),
"openclaw.historyMode": historyMode,
"openclaw.historySkipped": String(historySkipped),
"openclaw.historyTotalLength": String(fullHistory.length),
},
inputs: {
provider: turn.llmIn?.provider,
model: turn.llmIn?.model,
...(shouldShipSystemPrompt
? { systemPrompt: truncate(turn.llmIn!.systemPrompt!, cfg.maxAttributeBytes) }
: {}),
prompt: truncate(turn.llmIn?.prompt, cfg.maxAttributeBytes),
...(historyToShip && historyToShip.length > 0
? { historyMessages: unwrapJsonStrings(historyToShip) }
: {}),
imagesCount: turn.llmIn?.imagesCount ?? 0,
},
});
llmSpan.end({
outputs: {
assistantTexts: turn.llmOut?.assistantTexts,
lastAssistant: unwrapJsonStrings(turn.llmOut?.lastAssistant),
usage: unwrapJsonStrings(turn.llmOut?.usage),
stopReason: turn.llmOut?.lastAssistant?.stopReason,
resolvedRef: turn.llmOut?.resolvedRef,
},
status: success ? SpanStatusCode.OK : SpanStatusCode.ERROR,
});
}
return {
runId,
sessionId,
userId,
channel: turn.channelId,
senderId: turn.senderId,
userMessage: turn.userMessage,
assistantText: turn.llmOut?.assistantTexts?.[0],
success,
realDurationMs,
};
},
{
name: "agent.turn",
spanType: SpanType.AGENT,
attributes: {
"openclaw.runId": runId,
"openclaw.sessionId": sessionId,
"openclaw.agentId": turn.agentId ?? "",
"openclaw.channelId": turn.channelId ?? "",
"openclaw.senderId": turn.senderId ?? "",
"openclaw.success": String(success),
"openclaw.realDurationMs": String(realDurationMs),
},
},
);
try {
await traced();
api.logger.info(`[kayba-tracing] emitted trace for runId=${runId} (real ${realDurationMs}ms)`);
} catch (err) {
api.logger.warn(`[kayba-tracing] trace emit failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
}
export default {
id: "kayba-tracing",
name: "Kayba Tracing",
description: "Captures every OpenClaw agent turn and ships it as a Kayba trace.",
register,
};
|