skillar 0.0.0 → 0.2.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.
Files changed (114) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +193 -1
  3. package/dist/analysis/finding.js +190 -0
  4. package/dist/analysis/tree.js +157 -0
  5. package/dist/analysis/usage.js +394 -0
  6. package/dist/api/flows.js +285 -0
  7. package/dist/api/routes.js +192 -0
  8. package/dist/api/security.js +86 -0
  9. package/dist/api/sse.js +55 -0
  10. package/dist/api/static.js +33 -0
  11. package/dist/catalog/fields.js +159 -0
  12. package/dist/catalog/index.js +133 -0
  13. package/dist/catalog/scanner.js +204 -0
  14. package/dist/catalog/uri.js +43 -0
  15. package/dist/catalog/watcher.js +59 -0
  16. package/dist/cli/config-writer.js +255 -0
  17. package/dist/cli/doctor.js +268 -0
  18. package/dist/cli/eval.js +64 -0
  19. package/dist/cli/export-import.js +68 -0
  20. package/dist/cli/init.js +272 -0
  21. package/dist/cli/main.js +165 -0
  22. package/dist/cli/open.js +24 -0
  23. package/dist/cli/serve.js +147 -0
  24. package/dist/config.js +92 -0
  25. package/dist/dashboard/assets/app.js +354 -0
  26. package/dist/dashboard/assets/chunk-5DFWNJC2.js +1 -0
  27. package/dist/dashboard/assets/chunk-S6B2HJQA.js +17 -0
  28. package/dist/dashboard/assets/styles.css +542 -0
  29. package/dist/dashboard/index.html +15 -0
  30. package/dist/fs-watchdog.js +35 -0
  31. package/dist/herdr/client.js +205 -0
  32. package/dist/herdr/sync.js +342 -0
  33. package/dist/ingest/attribution.js +80 -0
  34. package/dist/ingest/hooks.js +168 -0
  35. package/dist/ingest/identity.js +4 -0
  36. package/dist/ingest/mcp-recorder.js +41 -0
  37. package/dist/ingest/otlp-traces.js +106 -0
  38. package/dist/ingest/otlp.js +314 -0
  39. package/dist/ingest/pipeline.js +119 -0
  40. package/dist/ingest/redact.js +36 -0
  41. package/dist/ingest/runtimes.js +25 -0
  42. package/dist/mcp/dispatch.js +54 -0
  43. package/dist/mcp/http.js +112 -0
  44. package/dist/mcp/legacy.js +61 -0
  45. package/dist/mcp/pagination.js +17 -0
  46. package/dist/mcp/protocol.js +121 -0
  47. package/dist/mcp/skills-extension.js +77 -0
  48. package/dist/mcp/stdio-proxy.js +108 -0
  49. package/dist/mcp/tools.js +59 -0
  50. package/dist/packs/claude-code.js +176 -0
  51. package/dist/packs/codex.js +207 -0
  52. package/dist/packs/cursor.js +97 -0
  53. package/dist/packs/gajae.js +7 -0
  54. package/dist/packs/gemini.js +90 -0
  55. package/dist/packs/json-config.js +55 -0
  56. package/dist/packs/omo.js +154 -0
  57. package/dist/packs/openclaw.js +132 -0
  58. package/dist/packs/registry.js +13 -0
  59. package/dist/search/fts.js +61 -0
  60. package/dist/search/fusion.js +50 -0
  61. package/dist/search/guidance.js +7 -0
  62. package/dist/search/index.js +74 -0
  63. package/dist/search/lexical.js +69 -0
  64. package/dist/server.js +267 -0
  65. package/dist/store/automation.js +18 -0
  66. package/dist/store/db.js +134 -0
  67. package/dist/store/execution.js +157 -0
  68. package/dist/store/export.js +269 -0
  69. package/dist/store/index.js +14 -0
  70. package/dist/store/migrations/002_tracing.sql +94 -0
  71. package/dist/store/migrations/003_tracing_indexes.sql +11 -0
  72. package/dist/store/migrations/004_load_reconciliation.sql +50 -0
  73. package/dist/store/migrations/005_execution_boundaries.sql +6 -0
  74. package/dist/store/migrations/006_recording_order.sql +72 -0
  75. package/dist/store/queries.js +643 -0
  76. package/dist/store/schema.sql +96 -0
  77. package/dist/store/workflow.js +250 -0
  78. package/dist/store/writes.js +315 -0
  79. package/dist/types.js +1 -0
  80. package/dist/version.js +19 -0
  81. package/dist/workflow/compare.js +68 -0
  82. package/dist/workflow/routes.js +100 -0
  83. package/dist/workflow/spec.js +40 -0
  84. package/docs/execution-ownership.md +98 -0
  85. package/docs/mcp-conformance.md +156 -0
  86. package/docs/skill-tracing.md +294 -0
  87. package/package.json +46 -3
  88. package/packs/claude-code/README.md +5 -0
  89. package/packs/claude-code/settings.template.json +34 -0
  90. package/packs/codex/README.md +8 -0
  91. package/packs/codex/config.template.toml +12 -0
  92. package/packs/cursor/hooks.example.json +8 -0
  93. package/packs/cursor/mcp.example.json +8 -0
  94. package/packs/gajae/extension/discovery.md +5 -0
  95. package/packs/gajae/extension/index.js +52 -0
  96. package/packs/gemini/settings.example.json +16 -0
  97. package/packs/hook-post.mjs +37 -0
  98. package/packs/omo/extension/discovery.md +5 -0
  99. package/packs/omo/extension/index.js +52 -0
  100. package/packs/openclaw/.codex-plugin/plugin.json +11 -0
  101. package/packs/openclaw/.mcp.json +12 -0
  102. package/packs/openclaw/hooks/skillar-discovery/HOOK.md +8 -0
  103. package/packs/openclaw/hooks/skillar-discovery/handler.js +30 -0
  104. package/packs/openclaw/index.mjs +55 -0
  105. package/packs/openclaw/openclaw.plugin.json +22 -0
  106. package/packs/openclaw/package.json +11 -0
  107. package/packs/openclaw/skillar.json +1 -0
  108. package/src/store/migrations/002_tracing.sql +94 -0
  109. package/src/store/migrations/003_tracing_indexes.sql +11 -0
  110. package/src/store/migrations/004_load_reconciliation.sql +50 -0
  111. package/src/store/migrations/005_execution_boundaries.sql +6 -0
  112. package/src/store/migrations/006_recording_order.sql +72 -0
  113. package/src/store/schema.sql +96 -0
  114. package/src/store/task-types.json +15 -0
@@ -0,0 +1,168 @@
1
+ import { randomUUID } from "node:crypto";
2
+ const SKILL_FILE_IN_PATH = /[\\/]([^\\/]+)[\\/]SKILL\.md$/;
3
+ const SKILL_FILE_IN_COMMAND = /[\\/]([^\\/\s'"`]+)[\\/]SKILL\.md(?![\w.])/g;
4
+ export function str(value) {
5
+ return typeof value === "string" && value.length > 0 ? value : undefined;
6
+ }
7
+ function obj(value) {
8
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
9
+ }
10
+ export function skillNameFromPath(path) {
11
+ return path ? SKILL_FILE_IN_PATH.exec(path)?.[1] : undefined;
12
+ }
13
+ export function skillNamesInCommand(command) {
14
+ if (!command)
15
+ return [];
16
+ const names = new Set();
17
+ for (const match of command.matchAll(SKILL_FILE_IN_COMMAND))
18
+ names.add(match[1]);
19
+ return [...names];
20
+ }
21
+ function commandText(value) {
22
+ if (Array.isArray(value))
23
+ return value.filter((v) => typeof v === "string").join(" ");
24
+ return str(value);
25
+ }
26
+ export function makeEvent(kind, source, ref, ts, extra = {}) {
27
+ return { id: randomUUID(), ts, kind, source, ref, data: {}, ...extra };
28
+ }
29
+ function promptEvent(ref, ts, prompt, data = {}) {
30
+ const text = typeof prompt === "string" ? prompt : undefined;
31
+ return makeEvent("prompt", "hook", ref, ts, text === undefined ? { data: { ...data, promptUnavailable: true } } : { text, data });
32
+ }
33
+ function nativeSkill(ref, ts, name, via, extra = {}, data = {}) {
34
+ return makeEvent("native_skill", "hook", ref, ts, { ...extra, data: { ...data, name, via } });
35
+ }
36
+ function fileReadSkills(ref, ts, toolName, input, toolUseId) {
37
+ const extra = toolUseId ? { toolUseId } : {};
38
+ if (toolName === "Read") {
39
+ const filePath = str(input?.file_path);
40
+ const name = skillNameFromPath(filePath);
41
+ return name ? [nativeSkill(ref, ts, name, "file_read", extra, { path: filePath, tool: "Read" })] : [];
42
+ }
43
+ if (toolName === "Bash" || toolName === "shell" || toolName === "local_shell") {
44
+ return skillNamesInCommand(commandText(input?.command)).map((name) => nativeSkill(ref, ts, name, "file_read", extra, { tool: toolName }));
45
+ }
46
+ return [];
47
+ }
48
+ function claudeCode(p, ts) {
49
+ const ref = { runtime: "claude-code", runtimeSessionId: str(p.session_id), cwd: str(p.cwd) };
50
+ const events = [];
51
+ const bindings = [];
52
+ switch (p.hook_event_name) {
53
+ case "UserPromptSubmit":
54
+ events.push(promptEvent(ref, ts, p.prompt, str(p.prompt_id) ? { promptId: p.prompt_id } : {}));
55
+ break;
56
+ case "SessionStart":
57
+ events.push(makeEvent("session_start", "hook", ref, ts, { data: { source: p.source } }));
58
+ break;
59
+ case "SessionEnd":
60
+ events.push(makeEvent("session_end", "hook", ref, ts, { data: { reason: p.reason } }));
61
+ break;
62
+ case "UserPromptExpansion": {
63
+ const name = str(p.command_name);
64
+ if (name && p.expansion_type === "slash_command")
65
+ events.push(nativeSkill(ref, ts, name, "expansion", {}, { commandSource: p.command_source }));
66
+ break;
67
+ }
68
+ case "PostToolUse": {
69
+ const toolName = str(p.tool_name);
70
+ const input = obj(p.tool_input);
71
+ const toolUseId = str(p.tool_use_id);
72
+ if ((toolName?.startsWith("mcp__skillar__") || toolName?.startsWith("mcp__gisool__"))) {
73
+ if (toolUseId && ref.runtimeSessionId)
74
+ bindings.push({ toolUseId, ref });
75
+ }
76
+ else if (toolName === "Skill") {
77
+ const name = str(input?.skill) ?? str(input?.skill_name) ?? str(input?.name);
78
+ if (name)
79
+ events.push(nativeSkill(ref, ts, name, "tool", toolUseId ? { toolUseId } : {}));
80
+ }
81
+ else {
82
+ events.push(...fileReadSkills(ref, ts, toolName, input, toolUseId));
83
+ }
84
+ break;
85
+ }
86
+ }
87
+ return { events, bindings };
88
+ }
89
+ function codex(p, ts) {
90
+ const ref = { runtime: "codex", runtimeSessionId: str(p.session_id), cwd: str(p.cwd) };
91
+ const events = [];
92
+ if (p.hook_event_name === "UserPromptSubmit")
93
+ events.push(promptEvent(ref, ts, p.prompt, str(p.turn_id) ? { turnId: p.turn_id } : {}));
94
+ else if (p.hook_event_name === "PostToolUse" && p.tool_name === "Bash")
95
+ events.push(...fileReadSkills(ref, ts, "Bash", obj(p.tool_input)));
96
+ else if (p.hook_event_name === "SessionStart")
97
+ events.push(makeEvent("session_start", "hook", ref, ts));
98
+ return { events, bindings: [] };
99
+ }
100
+ function gemini(p, ts) {
101
+ const ref = { runtime: "gemini", runtimeSessionId: str(p.session_id), cwd: str(p.cwd) };
102
+ const events = [];
103
+ switch (p.hook_event_name) {
104
+ case "BeforeAgent":
105
+ events.push(promptEvent(ref, ts, p.prompt));
106
+ break;
107
+ case "AfterTool": {
108
+ const input = obj(p.tool_input);
109
+ const name = p.tool_name === "activate_skill" ? str(input?.name) ?? str(input?.skill) : undefined;
110
+ if (name)
111
+ events.push(nativeSkill(ref, ts, name, "tool"));
112
+ break;
113
+ }
114
+ case "SessionStart":
115
+ events.push(makeEvent("session_start", "hook", ref, ts));
116
+ break;
117
+ case "SessionEnd":
118
+ events.push(makeEvent("session_end", "hook", ref, ts));
119
+ break;
120
+ }
121
+ return { events, bindings: [] };
122
+ }
123
+ function cursor(p, ts) {
124
+ const roots = Array.isArray(p.workspace_roots) ? p.workspace_roots : [];
125
+ const ref = { runtime: "cursor", conversationId: str(p.conversation_id), cwd: str(roots[0]) ?? str(p.cwd) };
126
+ const events = [];
127
+ if (p.hook_event_name === "beforeSubmitPrompt")
128
+ events.push(promptEvent(ref, ts, p.prompt, str(p.generation_id) ? { generationId: p.generation_id } : {}));
129
+ else if (p.hook_event_name === "sessionStart")
130
+ events.push(makeEvent("session_start", "hook", ref, ts));
131
+ else if (p.hook_event_name === "sessionEnd")
132
+ events.push(makeEvent("session_end", "hook", ref, ts));
133
+ return { events, bindings: [] };
134
+ }
135
+ function piForwarder(runtime, p, ts) {
136
+ if (p.event !== "before_agent_start")
137
+ return { events: [], bindings: [] };
138
+ const ref = { runtime, runtimeSessionId: str(p.sessionId), cwd: str(p.cwd) };
139
+ return { events: [promptEvent(ref, ts, p.prompt)], bindings: [] };
140
+ }
141
+ function openclaw(p, ts) {
142
+ if (p.event !== "before_agent_run" && p.event !== "message_received")
143
+ return { events: [], bindings: [] };
144
+ const sessionKey = str(p.sessionKey);
145
+ const ref = { runtime: "openclaw", runtimeSessionId: str(p.sessionId) ?? sessionKey };
146
+ return { events: [promptEvent(ref, ts, p.prompt, { hook: p.event, ...(sessionKey ? { sessionKey } : {}) })], bindings: [] };
147
+ }
148
+ /** Normalizes one raw hook payload; unrecognized events yield no events (the pipeline counts them as dropped). */
149
+ export function normalizeHook(runtime, payload, now) {
150
+ const p = payload;
151
+ switch (runtime) {
152
+ case "claude-code":
153
+ return claudeCode(p, now);
154
+ case "codex":
155
+ return codex(p, now);
156
+ case "gemini":
157
+ return gemini(p, now);
158
+ case "cursor":
159
+ return cursor(p, now);
160
+ case "omo":
161
+ case "gajae":
162
+ return piForwarder(runtime, p, now);
163
+ case "openclaw":
164
+ return openclaw(p, now);
165
+ case "unknown":
166
+ return { events: [], bindings: [] };
167
+ }
168
+ }
@@ -0,0 +1,4 @@
1
+ /** Persisted payloads are immutable; old rows keep their original field name. */
2
+ export function isSkillarMcpData(data) {
3
+ return (data.skillarMcp ?? data.gisoolMcp) === true;
4
+ }
@@ -0,0 +1,41 @@
1
+ import { makeEvent, str } from "./hooks.js";
2
+ import { runtimeFromClientName } from "./runtimes.js";
3
+ /**
4
+ * Vendor _meta keys: Codex sends unprefixed `threadId` (-> conversationId) and `sessionId` (-> runtimeSessionId);
5
+ * Claude Code sends `claudecode/toolUseId`; OpenCode dev builds send `ai.opencode/sessionID`.
6
+ */
7
+ export function mcpBase(ctx) {
8
+ const meta = ctx.meta ?? {};
9
+ const ref = { runtime: runtimeFromClientName(ctx.clientName) };
10
+ if (ctx.clientName)
11
+ ref.clientName = ctx.clientName;
12
+ const runtimeSessionId = str(meta.sessionId) ?? str(meta["ai.opencode/sessionID"]);
13
+ const conversationId = str(meta.threadId);
14
+ if (runtimeSessionId)
15
+ ref.runtimeSessionId = runtimeSessionId;
16
+ if (conversationId)
17
+ ref.conversationId = conversationId;
18
+ const toolUseId = str(meta["claudecode/toolUseId"]);
19
+ const data = {};
20
+ return toolUseId ? { ref, toolUseId, data } : { ref, data };
21
+ }
22
+ function build(kind, ctx, ts, extra, data) {
23
+ const base = mcpBase(ctx);
24
+ return makeEvent(kind, "mcp", base.ref, ts, { ...(base.toolUseId ? { toolUseId: base.toolUseId } : {}), ...extra, data: { ...base.data, ...data } });
25
+ }
26
+ export function searchEvent(ctx, outcome, opts, ts) {
27
+ const data = {
28
+ query: outcome.query, mode: outcome.mode, candidates: outcome.candidates, elapsedMs: outcome.elapsedMs, total: opts.total, chosen: opts.chosen ?? [],
29
+ ...(outcome.abstained ? { abstained: outcome.abstained } : {}),
30
+ };
31
+ return build("search", ctx, ts, { traceId: outcome.traceId, text: outcome.query }, data);
32
+ }
33
+ export function loadEvent(ctx, load, ts) {
34
+ return build("load", ctx, ts, { skillUri: load.uri, loadId: load.loadId, ...(load.traceId ? { traceId: load.traceId } : {}) }, { uri: load.uri, loadId: load.loadId, manifestDigest: load.manifestDigest, observationOnly: true });
35
+ }
36
+ export function readFileEvent(ctx, read, ts) {
37
+ return build("read_file", ctx, ts, { skillUri: read.skillUri, ...(read.loadId ? { loadId: read.loadId } : {}), ...(read.traceId ? { traceId: read.traceId } : {}) }, { skillUri: read.skillUri, uri: read.uri, bytes: read.bytes });
38
+ }
39
+ export function errorEvent(ctx, err, ts) {
40
+ return build("error", ctx, ts, { ...(err.traceId ? { traceId: err.traceId } : {}), ...(err.skillUri ? { skillUri: err.skillUri } : {}), ...(err.loadId ? { loadId: err.loadId } : {}) }, { code: err.code, message: err.message, ...(err.tool ? { tool: err.tool } : {}) });
41
+ }
@@ -0,0 +1,106 @@
1
+ function nonEmpty(value) {
2
+ return typeof value === "string" && value.length > 0 ? value : undefined;
3
+ }
4
+ /** Join keys and ids are strings; an exporter that sends one as an int64 AnyValue still joins, so it is normalized. */
5
+ function attrString(list, key) {
6
+ if (!Array.isArray(list))
7
+ return undefined;
8
+ for (const kv of list) {
9
+ if (!kv || typeof kv !== "object" || kv.key !== key)
10
+ continue;
11
+ const value = kv.value;
12
+ if (!value || typeof value !== "object")
13
+ return undefined;
14
+ if (typeof value.stringValue === "string")
15
+ return nonEmpty(value.stringValue);
16
+ if (typeof value.intValue === "string" || typeof value.intValue === "number")
17
+ return nonEmpty(String(value.intValue));
18
+ return undefined;
19
+ }
20
+ return undefined;
21
+ }
22
+ function msOf(nanos) {
23
+ const n = typeof nanos === "string" || typeof nanos === "number" ? Number(nanos) : NaN;
24
+ return Number.isFinite(n) && n > 0 ? Math.floor(n / 1e6) : undefined;
25
+ }
26
+ function runtimeOf(serviceName) {
27
+ const name = serviceName.toLowerCase();
28
+ if (name.includes("codex"))
29
+ return "codex";
30
+ if (name.includes("claude"))
31
+ return "claude-code";
32
+ return "unknown";
33
+ }
34
+ /**
35
+ * Keeps a span only when it can be joined later: it carries `turn_id`, `turn.id` or `call_id`, and the ids the join
36
+ * itself runs on (trace id, span id, name). Everything else is dropped here - one small Codex turn exports ~1,885
37
+ * spans, almost all of them runtime internals (fs.read_file, auth, …) that answer no question about skill use.
38
+ */
39
+ function rowOf(span, runtime, now) {
40
+ if (!span || typeof span !== "object")
41
+ return undefined;
42
+ const attrs = span.attributes;
43
+ const turnKey = attrString(attrs, "turn_id") ?? attrString(attrs, "turn.id");
44
+ const callId = attrString(attrs, "call_id");
45
+ if (turnKey === undefined && callId === undefined)
46
+ return undefined;
47
+ const traceId = nonEmpty(span.traceId);
48
+ const spanId = nonEmpty(span.spanId);
49
+ const name = nonEmpty(span.name);
50
+ if (traceId === undefined || spanId === undefined || name === undefined)
51
+ return undefined;
52
+ const parentSpanId = nonEmpty(span.parentSpanId);
53
+ const conversationId = attrString(attrs, "conversation.id");
54
+ const startMs = msOf(span.startTimeUnixNano);
55
+ const endMs = msOf(span.endTimeUnixNano);
56
+ return {
57
+ traceId, spanId, name, runtime, receivedAt: now,
58
+ ...(parentSpanId !== undefined ? { parentSpanId } : {}),
59
+ ...(conversationId !== undefined ? { conversationId } : {}),
60
+ ...(turnKey !== undefined ? { turnKey } : {}),
61
+ ...(callId !== undefined ? { callId } : {}),
62
+ ...(startMs !== undefined ? { startMs } : {}),
63
+ ...(endMs !== undefined ? { endMs } : {}),
64
+ };
65
+ }
66
+ function badOtlp(message) {
67
+ return { ok: false, status: 400, error: { code: "bad_otlp", message } };
68
+ }
69
+ /** Parses an OTLP/HTTP JSON traces export into the joinable spans; every other span is counted as dropped. */
70
+ export function parseOtlpTraces(body, now) {
71
+ if (body === null || typeof body !== "object" || Array.isArray(body))
72
+ return badOtlp("body must be an ExportTraceServiceRequest JSON object");
73
+ const resourceSpans = body.resourceSpans;
74
+ if (!Array.isArray(resourceSpans))
75
+ return badOtlp("resourceSpans must be an array");
76
+ const spans = [];
77
+ let dropped = 0;
78
+ for (const rs of resourceSpans) {
79
+ const runtime = runtimeOf(attrString(rs?.resource?.attributes, "service.name") ?? "");
80
+ const scopeSpans = Array.isArray(rs?.scopeSpans) ? rs.scopeSpans : [];
81
+ for (const ss of scopeSpans) {
82
+ const list = Array.isArray(ss?.spans) ? ss.spans : [];
83
+ for (const span of list) {
84
+ const row = rowOf(span, runtime, now);
85
+ if (row)
86
+ spans.push(row);
87
+ else
88
+ dropped += 1;
89
+ }
90
+ }
91
+ }
92
+ return { ok: true, spans, dropped, response: { partialSuccess: {} } };
93
+ }
94
+ /**
95
+ * Parses a traces batch and stores the joinable spans, counting kept and dropped spans with the ingest counters.
96
+ * A store failure propagates: the caller runs after the 202 was sent and owns the logging.
97
+ */
98
+ export function ingestOtlpTraces(body, store, now) {
99
+ const parsed = parseOtlpTraces(body, now);
100
+ if (!parsed.ok) {
101
+ store.countIngest("rejected", parsed.error.code);
102
+ return { status: 400, body: parsed.error };
103
+ }
104
+ const kept = store.putSpans(parsed.spans, parsed.dropped);
105
+ return { status: 200, body: parsed.response, kept, dropped: parsed.dropped };
106
+ }
@@ -0,0 +1,314 @@
1
+ import { makeEvent, skillNameFromPath, skillNamesInCommand, str } from "./hooks.js";
2
+ import { sha256Hex } from "./redact.js";
3
+ /**
4
+ * Known event names skillar deliberately does not store: they carry no model call, tool run or skill signal.
5
+ * They count as `ignored`, never as `unknown`, so `ingest.dropped` keeps meaning "skillar did not understand this".
6
+ * `codex.api_request` belongs here because it carries neither a session nor a timestamp id and cannot be attributed.
7
+ */
8
+ const IGNORED_NAMES = new Set([
9
+ "claude_code.tool_decision", "claude_code.mcp_server_connection", "claude_code.plugin_loaded", "claude_code.assistant_response",
10
+ "codex.startup_phase", "codex.turn_ttft", "codex.tool_decision", "codex.api_request",
11
+ ]);
12
+ const IGNORED_PREFIXES = ["claude_code.hook_", "codex.websocket_"];
13
+ function decode(value) {
14
+ if (!value || typeof value !== "object")
15
+ return undefined;
16
+ if (value.stringValue !== undefined)
17
+ return value.stringValue;
18
+ if (value.boolValue !== undefined)
19
+ return value.boolValue;
20
+ if (value.intValue !== undefined)
21
+ return Number(value.intValue);
22
+ if (value.doubleValue !== undefined)
23
+ return value.doubleValue;
24
+ if (value.arrayValue)
25
+ return (value.arrayValue.values ?? []).map(decode);
26
+ if (value.kvlistValue)
27
+ return toAttrs(value.kvlistValue.values);
28
+ if (value.bytesValue !== undefined)
29
+ return value.bytesValue;
30
+ return undefined;
31
+ }
32
+ function toAttrs(list) {
33
+ const out = {};
34
+ if (!Array.isArray(list))
35
+ return out;
36
+ for (const kv of list)
37
+ if (kv && typeof kv.key === "string")
38
+ out[kv.key] = decode(kv.value);
39
+ return out;
40
+ }
41
+ /** Numeric attributes arrive as intValue (decimal string), doubleValue or stringValue depending on the agent and the field. */
42
+ function num(value) {
43
+ if (typeof value === "number")
44
+ return Number.isFinite(value) ? value : undefined;
45
+ if (typeof value === "string" && value.trim() !== "") {
46
+ const parsed = Number(value);
47
+ return Number.isFinite(parsed) ? parsed : undefined;
48
+ }
49
+ return undefined;
50
+ }
51
+ /** `success` arrives as boolValue from Codex and as the string "true"/"false" from Claude Code. */
52
+ function bool(value) {
53
+ if (typeof value === "boolean")
54
+ return value;
55
+ if (value === "true")
56
+ return true;
57
+ if (value === "false")
58
+ return false;
59
+ return undefined;
60
+ }
61
+ function compact(data) {
62
+ const out = {};
63
+ for (const [key, value] of Object.entries(data))
64
+ if (value !== undefined)
65
+ out[key] = value;
66
+ return out;
67
+ }
68
+ function derive(event, discriminator = "") {
69
+ return { event, discriminator };
70
+ }
71
+ function parseJsonObject(value) {
72
+ if (typeof value !== "string")
73
+ return undefined;
74
+ try {
75
+ const parsed = JSON.parse(value);
76
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
77
+ }
78
+ catch {
79
+ return undefined; // tool_input is truncated at ~4 KB by Claude Code, so unparseable JSON is expected and simply carries no path.
80
+ }
81
+ }
82
+ function tsOf(record, now) {
83
+ const nanos = Number(record.timeUnixNano ?? 0) || Number(record.observedTimeUnixNano ?? 0);
84
+ return nanos > 0 ? Math.floor(nanos / 1e6) : now;
85
+ }
86
+ function runtimeOf(name) {
87
+ return name.startsWith("codex.") ? "codex" : "claude-code";
88
+ }
89
+ function eventNameOf(record, attrs, serviceHint) {
90
+ const candidates = [record.eventName, attrs["event.name"], decode(record.body)].filter((v) => typeof v === "string" && v.length > 0);
91
+ const prefixed = candidates.find((n) => n.startsWith("claude_code.") || n.startsWith("codex."));
92
+ if (prefixed)
93
+ return prefixed;
94
+ const bare = candidates[0];
95
+ if (!bare)
96
+ return undefined;
97
+ return serviceHint.includes("codex") ? `codex.${bare}` : `claude_code.${bare}`;
98
+ }
99
+ function promptText(attrs) {
100
+ const text = str(attrs.prompt) ?? str(attrs.prompt_text);
101
+ return text === "<REDACTED>" ? undefined : text;
102
+ }
103
+ /**
104
+ * Identifies the agent record an event was derived from:
105
+ * `runtime|event.name|event.timestamp|event.sequence|session id|call or tool id|sha256(record JSON)`.
106
+ * The record hash keeps two otherwise identical-looking records apart; the named parts keep the key stable
107
+ * for the same record re-sent in a retried batch.
108
+ */
109
+ function recordKeyOf(name, attrs, record) {
110
+ const timestamp = str(attrs["event.timestamp"]) ?? String(record.timeUnixNano ?? record.observedTimeUnixNano ?? "");
111
+ const sequence = attrs["event.sequence"] === undefined ? "" : String(attrs["event.sequence"]);
112
+ const sessionId = str(attrs["session.id"]) ?? str(attrs["conversation.id"]) ?? "";
113
+ const callId = str(attrs.tool_use_id) ?? str(attrs.call_id) ?? "";
114
+ return [runtimeOf(name), name, timestamp, sequence, sessionId, callId, sha256Hex(JSON.stringify(record ?? null))].join("|");
115
+ }
116
+ /** sha256(recordKey|derivedKind|discriminator|index): unique per derived event, identical when the agent replays the record. */
117
+ function sourceKeyOf(recordKey, kind, discriminator, index) {
118
+ return sha256Hex(`${recordKey}|${kind}|${discriminator}|${index}`);
119
+ }
120
+ // Claude Code tool_result attributes (https://code.claude.com/docs/en/monitoring-usage.md, "Tool result event"):
121
+ // `tool_name`, `tool_use_id`, `success`, `duration_ms`, `tool_input_size_bytes`, `tool_result_size_bytes`, and with
122
+ // OTEL_LOG_TOOL_DETAILS=1 `tool_parameters` (JSON string: Bash `bash_command`/`full_command`, MCP `mcp_server_name`/`mcp_tool_name`,
123
+ // Skill `skill_name`) and `tool_input` (JSON-serialized arguments, e.g. Read `file_path`).
124
+ function claudeSkillReads(attrs, ref, ts, extra) {
125
+ const toolName = str(attrs.tool_name);
126
+ const params = parseJsonObject(attrs.tool_parameters) ?? {};
127
+ const input = parseJsonObject(attrs.tool_input) ?? {};
128
+ if (toolName === "Read") {
129
+ const filePath = str(input.file_path) ?? str(params.file_path);
130
+ const name = skillNameFromPath(filePath);
131
+ return name ? [derive(makeEvent("native_skill", "otel", ref, ts, { ...extra, data: { name, via: "file_read", path: filePath, tool: "Read" } }), name)] : [];
132
+ }
133
+ if (toolName === "Bash") {
134
+ const command = str(params.full_command) ?? str(params.bash_command) ?? str(input.command);
135
+ return skillNamesInCommand(command).map((name) => derive(makeEvent("native_skill", "otel", ref, ts, { ...extra, data: { name, via: "file_read", tool: "Bash" } }), name));
136
+ }
137
+ return [];
138
+ }
139
+ function claudeToolResult(attrs, ref, ts, turnKey) {
140
+ const toolName = str(attrs.tool_name);
141
+ const params = parseJsonObject(attrs.tool_parameters) ?? {};
142
+ const input = parseJsonObject(attrs.tool_input) ?? {};
143
+ const mcpServer = str(attrs.mcp_server_name) ?? str(params.mcp_server_name) ?? "";
144
+ const skillarMcp = ["skillar", "gisool"].includes(mcpServer.toLowerCase()) || isSkillarCall(toolName, input) || isSkillarCall(toolName, params);
145
+ const toolUseId = str(attrs.tool_use_id);
146
+ const extra = { ...(toolUseId ? { toolUseId } : {}), ...(turnKey ? { turnKey } : {}) };
147
+ // The arguments go in `text` so applyCapture, redaction and retention treat them exactly like prompt content.
148
+ const args = str(attrs.tool_input) ?? str(attrs.tool_parameters);
149
+ const call = makeEvent("tool_call", "otel", ref, ts, {
150
+ ...extra,
151
+ ...(args !== undefined ? { text: args } : {}),
152
+ data: compact({
153
+ toolName: toolName ?? "unknown", success: bool(attrs.success), durationMs: num(attrs.duration_ms), toolUseId,
154
+ inputBytes: num(attrs.tool_input_size_bytes), resultBytes: num(attrs.tool_result_size_bytes), ...(skillarMcp ? { skillarMcp: true } : {}),
155
+ }),
156
+ });
157
+ // A skillar MCP call is recorded in full by the MCP recorder (search/load/read_file); this row is only the
158
+ // Claude-side view of that tool run and derives no skill reads of its own.
159
+ if (skillarMcp)
160
+ return [derive(call)];
161
+ return [derive(call), ...claudeSkillReads(attrs, ref, ts, extra)];
162
+ }
163
+ function isSkillarCall(toolName, args) {
164
+ return ((toolName?.startsWith("mcp__skillar__") || toolName?.startsWith("mcp__gisool__")) ?? false) || ["skillar", "gisool"].includes(str(args.server)?.toLowerCase() ?? "");
165
+ }
166
+ function claudeRecord(name, attrs, ts) {
167
+ const ref = { runtime: "claude-code", runtimeSessionId: str(attrs["session.id"]) };
168
+ const turnKey = str(attrs["prompt.id"]);
169
+ const turn = turnKey ? { turnKey } : {};
170
+ switch (name) {
171
+ case "claude_code.user_prompt": {
172
+ const text = promptText(attrs);
173
+ const promptLength = typeof attrs.prompt_length === "number" ? attrs.prompt_length : undefined;
174
+ const data = { promptId: turnKey };
175
+ if (text === undefined)
176
+ Object.assign(data, { promptUnavailable: true, promptLength });
177
+ return [derive(makeEvent("prompt", "otel", ref, ts, { ...turn, ...(text !== undefined ? { text } : {}), data }))];
178
+ }
179
+ case "claude_code.api_request":
180
+ return [derive(makeEvent("llm_call", "otel", ref, ts, {
181
+ ...turn,
182
+ data: compact({
183
+ model: str(attrs.model), inputTokens: num(attrs.input_tokens), outputTokens: num(attrs.output_tokens),
184
+ cacheReadTokens: num(attrs.cache_read_tokens), cacheCreationTokens: num(attrs.cache_creation_tokens),
185
+ // Claude reports input_tokens without the cached ones, so the buckets add up; Codex reports them included.
186
+ inputIncludesCache: false, costUsd: num(attrs.cost_usd), durationMs: num(attrs.duration_ms), ttftMs: num(attrs.ttft_ms),
187
+ requestId: str(attrs.request_id), skillName: str(attrs["skill.name"]),
188
+ }),
189
+ }))];
190
+ case "claude_code.skill_activated": {
191
+ const skill = str(attrs["skill.name"]);
192
+ if (!skill)
193
+ return "ignored";
194
+ return [derive(makeEvent("native_skill", "otel", ref, ts, {
195
+ ...turn, data: { name: skill, via: "otel", trigger: str(attrs.invocation_trigger), source: str(attrs["skill.source"]) },
196
+ }), skill)];
197
+ }
198
+ case "claude_code.tool_result":
199
+ return claudeToolResult(attrs, ref, ts, turnKey);
200
+ default:
201
+ return "unknown";
202
+ }
203
+ }
204
+ function codexRecord(name, attrs, ts) {
205
+ const ref = { runtime: "codex", conversationId: str(attrs["conversation.id"]) };
206
+ const turnKey = str(attrs["turn.id"]) ?? str(attrs.turn_id);
207
+ const turn = turnKey ? { turnKey } : {};
208
+ switch (name) {
209
+ case "codex.user_prompt": {
210
+ const text = promptText(attrs);
211
+ return [derive(makeEvent("prompt", "otel", ref, ts, { ...turn, ...(text !== undefined ? { text } : { data: { promptUnavailable: true } }) }))];
212
+ }
213
+ case "codex.sse_event": {
214
+ // Only the completion event carries the turn's usage; every other SSE kind is noise for skillar.
215
+ if (str(attrs["event.kind"]) !== "response.completed")
216
+ return "ignored";
217
+ return [derive(makeEvent("llm_call", "otel", ref, ts, {
218
+ ...turn,
219
+ data: compact({
220
+ model: str(attrs.model), inputTokens: num(attrs.input_token_count), outputTokens: num(attrs.output_token_count),
221
+ cacheReadTokens: num(attrs.cached_token_count), cacheWriteTokens: num(attrs.cache_write_token_count),
222
+ reasoningTokens: num(attrs.reasoning_token_count), totalTokens: num(attrs.tool_token_count),
223
+ // Codex counts cached tokens inside input_token_count (non-cached = input - cached).
224
+ inputIncludesCache: true, ttftMs: num(attrs.ttft_ms),
225
+ }),
226
+ }))];
227
+ }
228
+ case "codex.tool_result": {
229
+ const callId = str(attrs.call_id);
230
+ const args = str(attrs.arguments);
231
+ const toolName = str(attrs.tool_name);
232
+ const skillarMcp = isSkillarCall(toolName, parseJsonObject(args) ?? {})
233
+ || ["skillar", "gisool"].includes(str(attrs.mcp_server_name)?.toLowerCase() ?? "");
234
+ return [derive(makeEvent("tool_call", "otel", ref, ts, {
235
+ ...turn, ...(callId ? { callId } : {}), ...(args !== undefined ? { text: args } : {}),
236
+ data: compact({ toolName: toolName ?? "unknown", success: bool(attrs.success), durationMs: num(attrs.duration_ms),
237
+ ...(skillarMcp ? { skillarMcp: true } : {}) }),
238
+ }))];
239
+ }
240
+ case "codex.skill_invocation": {
241
+ const skill = str(attrs["skill.name"]);
242
+ if (!skill)
243
+ return "ignored";
244
+ return [derive(makeEvent("native_skill", "otel", ref, ts, {
245
+ ...turn, data: { name: skill, via: "otel", scope: str(attrs["skill.scope"]), invocationType: str(attrs["skill.invocation_type"]) },
246
+ }), skill)];
247
+ }
248
+ case "codex.conversation_starts":
249
+ return [derive(makeEvent("session_start", "otel", ref, ts))];
250
+ default:
251
+ return "unknown";
252
+ }
253
+ }
254
+ function mapRecord(name, attrs, ts) {
255
+ if (IGNORED_NAMES.has(name) || IGNORED_PREFIXES.some((prefix) => name.startsWith(prefix)))
256
+ return "ignored";
257
+ if (name.startsWith("claude_code."))
258
+ return claudeRecord(name, attrs, ts);
259
+ if (name.startsWith("codex."))
260
+ return codexRecord(name, attrs, ts);
261
+ return "unknown";
262
+ }
263
+ function badOtlp(message) {
264
+ return { ok: false, status: 400, error: { code: "bad_otlp", message } };
265
+ }
266
+ /** Parses an OTLP/HTTP JSON logs export into CanonicalEvents; unknown event names are counted, not stored. */
267
+ export function parseOtlpLogs(body, now) {
268
+ if (body === null || typeof body !== "object" || Array.isArray(body))
269
+ return badOtlp("body must be an ExportLogsServiceRequest JSON object");
270
+ const resourceLogs = body.resourceLogs;
271
+ if (!Array.isArray(resourceLogs))
272
+ return badOtlp("resourceLogs must be an array");
273
+ const events = [];
274
+ let unknown = 0;
275
+ let ignored = 0;
276
+ for (const rl of resourceLogs) {
277
+ const resourceAttrs = toAttrs(rl?.resource?.attributes);
278
+ const scopeLogs = Array.isArray(rl?.scopeLogs) ? rl.scopeLogs : [];
279
+ for (const sl of scopeLogs) {
280
+ const serviceHint = `${String(resourceAttrs["service.name"] ?? "")} ${sl?.scope?.name ?? ""}`.toLowerCase();
281
+ const records = Array.isArray(sl?.logRecords) ? sl.logRecords : [];
282
+ for (const record of records) {
283
+ const attrs = { ...resourceAttrs, ...toAttrs(record?.attributes) };
284
+ const name = record ? eventNameOf(record, attrs, serviceHint) : undefined;
285
+ const mapped = name ? mapRecord(name, attrs, tsOf(record, now)) : "unknown";
286
+ if (mapped === "unknown") {
287
+ unknown += 1;
288
+ continue;
289
+ }
290
+ if (mapped === "ignored") {
291
+ ignored += 1;
292
+ continue;
293
+ }
294
+ const recordKey = recordKeyOf(name, attrs, record);
295
+ const spanId = str(record.spanId);
296
+ const otelTraceId = str(record.traceId);
297
+ const seen = new Map();
298
+ for (const { event, discriminator } of mapped) {
299
+ const slot = `${event.kind}|${discriminator}`;
300
+ const index = seen.get(slot) ?? 0;
301
+ seen.set(slot, index + 1);
302
+ event.sourceKey = sourceKeyOf(recordKey, event.kind, discriminator, index);
303
+ // The log's own span context is what joins a Codex tool run to the execution span that carries its turn id.
304
+ if (spanId)
305
+ event.spanId = spanId;
306
+ if (otelTraceId)
307
+ event.data = { ...event.data, otelTraceId };
308
+ events.push(event);
309
+ }
310
+ }
311
+ }
312
+ }
313
+ return { ok: true, events, unknown, ignored, response: { partialSuccess: {} } };
314
+ }