noctrace 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Claude Code provider implementation.
3
+ * Wraps the existing parseJsonlContent / parseSubAgentContent logic and the
4
+ * ~/.claude/projects directory structure into the Provider interface.
5
+ *
6
+ * Session id format: '<projectSlug>/<sessionId>'
7
+ * e.g. '-Users-lam-dev-noctrace/abc123def456'
8
+ *
9
+ * Phase A note: watch() returns a no-op unsubscribe. Real-time chokidar
10
+ * integration is deferred to Phase B when the server wires it up.
11
+ */
12
+ import fs from 'node:fs/promises';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import chokidar from 'chokidar';
16
+ import { parseJsonlContent, extractSessionId } from '../parser.js';
17
+ // ---------------------------------------------------------------------------
18
+ // Helpers
19
+ // ---------------------------------------------------------------------------
20
+ /**
21
+ * Resolve the Claude home directory.
22
+ * Prefers the CLAUDE_HOME environment variable, falls back to ~/.claude.
23
+ */
24
+ function resolveClaudeHome(override) {
25
+ if (override)
26
+ return override;
27
+ return process.env['CLAUDE_HOME'] ?? path.join(os.homedir(), '.claude');
28
+ }
29
+ /**
30
+ * Convert a project directory slug back to a human-readable path.
31
+ * '-Users-lam-dev-noctrace' → '/Users/lam/dev/noctrace'
32
+ * The result is then replaced with '~' when it starts with the home directory.
33
+ */
34
+ function deSlugifyProject(slug) {
35
+ const rawPath = slug.replace(/-/g, '/');
36
+ const home = os.homedir();
37
+ if (rawPath.startsWith(home)) {
38
+ return '~' + rawPath.slice(home.length);
39
+ }
40
+ return rawPath;
41
+ }
42
+ /**
43
+ * Read the mtime of a file; returns null on error.
44
+ */
45
+ async function safeStatMtime(filePath) {
46
+ try {
47
+ const stat = await fs.stat(filePath);
48
+ return stat.mtime;
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ // ---------------------------------------------------------------------------
55
+ // Provider factory
56
+ // ---------------------------------------------------------------------------
57
+ const CLAUDE_CODE_CAPABILITIES = {
58
+ toolCallGranularity: 'full',
59
+ contextTracking: true,
60
+ subAgents: true,
61
+ realtime: true,
62
+ tokenAccounting: 'per-turn',
63
+ };
64
+ /**
65
+ * Create a Claude Code provider instance.
66
+ *
67
+ * @param claudeHome - Override path to the Claude home directory.
68
+ * Defaults to CLAUDE_HOME env var or ~/.claude.
69
+ */
70
+ export function createClaudeCodeProvider(claudeHome) {
71
+ const home = resolveClaudeHome(claudeHome);
72
+ const projectsDir = path.join(home, 'projects');
73
+ return {
74
+ id: 'claude-code',
75
+ displayName: 'Claude Code',
76
+ capabilities: CLAUDE_CODE_CAPABILITIES,
77
+ async listSessions(window) {
78
+ const results = [];
79
+ let slugs;
80
+ try {
81
+ slugs = await fs.readdir(projectsDir);
82
+ }
83
+ catch {
84
+ // Projects directory doesn't exist — return empty list gracefully
85
+ return results;
86
+ }
87
+ for (const slug of slugs) {
88
+ const projectDir = path.join(projectsDir, slug);
89
+ let dirStat;
90
+ try {
91
+ dirStat = await fs.stat(projectDir);
92
+ }
93
+ catch {
94
+ continue;
95
+ }
96
+ if (!dirStat.isDirectory())
97
+ continue;
98
+ let files;
99
+ try {
100
+ files = await fs.readdir(projectDir);
101
+ }
102
+ catch {
103
+ continue;
104
+ }
105
+ for (const file of files) {
106
+ if (!file.endsWith('.jsonl'))
107
+ continue;
108
+ const sessionId = file.replace(/\.jsonl$/, '');
109
+ const filePath = path.join(projectDir, file);
110
+ const mtime = await safeStatMtime(filePath);
111
+ if (!mtime)
112
+ continue;
113
+ const mtimeMs = mtime.getTime();
114
+ // Filter by window: use mtime as endMs heuristic
115
+ if (mtimeMs < window.startMs || mtimeMs >= window.endMs)
116
+ continue;
117
+ // Extract start time from first record (best-effort, fall back to mtime)
118
+ let startMs = mtimeMs;
119
+ try {
120
+ const firstChunk = await readFirstChunk(filePath, 4096);
121
+ const firstTs = extractFirstTimestamp(firstChunk);
122
+ if (firstTs !== null)
123
+ startMs = firstTs;
124
+ }
125
+ catch {
126
+ // Leave startMs as mtime
127
+ }
128
+ results.push({
129
+ provider: 'claude-code',
130
+ sessionId,
131
+ projectContext: deSlugifyProject(slug),
132
+ rawSlug: `${slug}/${sessionId}`,
133
+ startMs,
134
+ endMs: mtimeMs,
135
+ });
136
+ }
137
+ }
138
+ return results;
139
+ },
140
+ async readSession(id) {
141
+ // id format: '<projectSlug>/<sessionId>'
142
+ const slashIdx = id.indexOf('/');
143
+ if (slashIdx === -1) {
144
+ throw new Error(`Invalid Claude Code session id: "${id}". Expected "<projectSlug>/<sessionId>".`);
145
+ }
146
+ const projectSlug = id.slice(0, slashIdx);
147
+ const sessionId = id.slice(slashIdx + 1);
148
+ const filePath = path.join(projectsDir, projectSlug, `${sessionId}.jsonl`);
149
+ let content;
150
+ try {
151
+ content = await fs.readFile(filePath, 'utf8');
152
+ }
153
+ catch {
154
+ throw new Error(`Claude Code session not found: ${id}`);
155
+ }
156
+ const rows = parseJsonlContent(content);
157
+ const canonicalSessionId = extractSessionId(content) ?? sessionId;
158
+ // Extract mtime for endMs
159
+ const mtime = await safeStatMtime(filePath);
160
+ // Extract start time
161
+ const firstTs = extractFirstTimestamp(content.slice(0, 4096));
162
+ const startMs = firstTs ?? (mtime?.getTime() ?? Date.now());
163
+ const meta = {
164
+ provider: 'claude-code',
165
+ sessionId: canonicalSessionId,
166
+ projectContext: deSlugifyProject(projectSlug),
167
+ rawSlug: `${projectSlug}/${sessionId}`,
168
+ startMs,
169
+ endMs: mtime?.getTime() ?? null,
170
+ };
171
+ return { meta, native: rows };
172
+ },
173
+ watch(onEvent) {
174
+ // Phase B: real chokidar integration.
175
+ // Watches the projects directory for added and changed .jsonl files.
176
+ // Emits session-added for new files and session-updated for changed files.
177
+ // Uses persistent:true, ignoreInitial:true per architecture constraints.
178
+ let watcher = null;
179
+ try {
180
+ watcher = chokidar.watch(projectsDir, {
181
+ persistent: true,
182
+ ignoreInitial: true,
183
+ depth: 2,
184
+ });
185
+ watcher.on('add', (filePath) => {
186
+ if (!filePath.endsWith('.jsonl'))
187
+ return;
188
+ const relative = path.relative(projectsDir, filePath);
189
+ const parts = relative.split(path.sep);
190
+ if (parts.length < 2)
191
+ return;
192
+ const slug = parts[0];
193
+ const sessionId = parts[1].replace(/\.jsonl$/, '');
194
+ const id = `${slug}/${sessionId}`;
195
+ onEvent({ kind: 'session-added', provider: 'claude-code', sessionId: id });
196
+ });
197
+ watcher.on('change', (filePath) => {
198
+ if (!filePath.endsWith('.jsonl'))
199
+ return;
200
+ const relative = path.relative(projectsDir, filePath);
201
+ const parts = relative.split(path.sep);
202
+ if (parts.length < 2)
203
+ return;
204
+ const slug = parts[0];
205
+ const sessionId = parts[1].replace(/\.jsonl$/, '');
206
+ const id = `${slug}/${sessionId}`;
207
+ onEvent({ kind: 'session-updated', provider: 'claude-code', sessionId: id });
208
+ });
209
+ watcher.on('error', (err) => {
210
+ console.warn('[noctrace] claude-code provider watcher error:', err instanceof Error ? err.message : String(err));
211
+ });
212
+ }
213
+ catch (err) {
214
+ // If the projects directory doesn't exist, chokidar may throw — degrade gracefully
215
+ console.warn('[noctrace] claude-code provider: could not start watcher:', err instanceof Error ? err.message : String(err));
216
+ }
217
+ return () => {
218
+ watcher?.close().catch(() => { });
219
+ };
220
+ },
221
+ };
222
+ }
223
+ // ---------------------------------------------------------------------------
224
+ // Internal helpers
225
+ // ---------------------------------------------------------------------------
226
+ /**
227
+ * Read the first `maxBytes` of a file as a UTF-8 string.
228
+ * Used for fast timestamp extraction without loading the full file.
229
+ */
230
+ async function readFirstChunk(filePath, maxBytes) {
231
+ const fh = await fs.open(filePath, 'r');
232
+ try {
233
+ const buf = Buffer.alloc(maxBytes);
234
+ const { bytesRead } = await fh.read(buf, 0, maxBytes, 0);
235
+ return buf.slice(0, bytesRead).toString('utf8');
236
+ }
237
+ finally {
238
+ await fh.close();
239
+ }
240
+ }
241
+ /**
242
+ * Extract the Unix-ms timestamp from the first valid JSON record in a string.
243
+ * Returns null when no timestamp can be found.
244
+ */
245
+ function extractFirstTimestamp(chunk) {
246
+ const lines = chunk.split('\n');
247
+ for (const line of lines) {
248
+ const t = line.trim();
249
+ if (!t)
250
+ continue;
251
+ let parsed;
252
+ try {
253
+ parsed = JSON.parse(t);
254
+ }
255
+ catch {
256
+ continue;
257
+ }
258
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
259
+ continue;
260
+ const ts = parsed['timestamp'];
261
+ if (typeof ts === 'string') {
262
+ const ms = new Date(ts).getTime();
263
+ if (!isNaN(ms))
264
+ return ms;
265
+ }
266
+ }
267
+ return null;
268
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Provider registry for Noctrace multi-provider support.
3
+ * Phase A: registers the 'claude-code' provider by default.
4
+ * Additional providers (Codex, Copilot, etc.) will be registered in Phase B/C.
5
+ */
6
+ import { createClaudeCodeProvider } from './claude-code.js';
7
+ // ---------------------------------------------------------------------------
8
+ // Registry
9
+ // ---------------------------------------------------------------------------
10
+ const _registry = new Map();
11
+ /**
12
+ * Register a provider in the global registry.
13
+ * Overwrites any existing provider with the same id.
14
+ * Use this in tests to inject mock or fixture-backed providers.
15
+ */
16
+ export function registerProvider(provider) {
17
+ _registry.set(provider.id, provider);
18
+ }
19
+ /**
20
+ * Retrieve a provider by its stable id.
21
+ * Returns undefined when no provider with that id is registered.
22
+ */
23
+ export function getProvider(id) {
24
+ return _registry.get(id);
25
+ }
26
+ /**
27
+ * Return all currently registered providers as an array.
28
+ */
29
+ export function listProviders() {
30
+ return Array.from(_registry.values());
31
+ }
32
+ // ---------------------------------------------------------------------------
33
+ // Default registration
34
+ // ---------------------------------------------------------------------------
35
+ // Register the Claude Code provider with default settings.
36
+ // The claudeHome path is resolved from CLAUDE_HOME env var or ~/.claude.
37
+ registerProvider(createClaudeCodeProvider());
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Core Provider interface and supporting types for the multi-provider abstraction.
3
+ * Phase A: defines the contract that all agent-log providers must implement.
4
+ */
5
+ export {};
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Normalised session schema shared across all providers.
3
+ * Phase A: minimal contract — providers pass rich data through `native`.
4
+ * Phase B/C may introduce richer normalised fields on AgentSession.
5
+ */
6
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "noctrace",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Claude Code observability — DevTools-style waterfall visualizer for AI agent workflows, token tracking, and context health monitoring",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -61,6 +61,8 @@
61
61
  "test:smoke": "npm run build && vitest run tests/smoke/",
62
62
  "lint": "eslint src/",
63
63
  "typecheck": "tsc -p tsconfig.server.json --noEmit && tsc -p tsconfig.client.json --noEmit",
64
+ "version:check": "node scripts/check-version.mjs",
65
+ "version:bump": "node scripts/bump-version.mjs",
64
66
  "postinstall": "node bin/postinstall.js",
65
67
  "preuninstall": "node bin/preuninstall.js"
66
68
  },