@scrylog/cli 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/LICENSE +21 -0
- package/README.md +836 -0
- package/package.json +75 -0
- package/src/api/docs/sessions.keys.ts +6 -0
- package/src/api/docs/sessions.ts +81 -0
- package/src/api/docs/system.keys.ts +5 -0
- package/src/api/docs/system.ts +66 -0
- package/src/api/docs/usage.keys.ts +3 -0
- package/src/api/docs/usage.ts +24 -0
- package/src/api/docs/webhooks.keys.ts +5 -0
- package/src/api/docs/webhooks.ts +78 -0
- package/src/api/index.ts +18 -0
- package/src/api/lib/auth.ts +43 -0
- package/src/api/lib/errors.ts +28 -0
- package/src/api/lib/route.ts +18 -0
- package/src/api/models/claude.ts +4 -0
- package/src/api/models/codex.ts +4 -0
- package/src/api/models/opencode.ts +11 -0
- package/src/api/routes/sessions.ts +47 -0
- package/src/api/routes/system.ts +103 -0
- package/src/api/routes/usage.ts +15 -0
- package/src/api/routes/webhooks/claude.ts +161 -0
- package/src/api/routes/webhooks/codex.ts +175 -0
- package/src/api/routes/webhooks/opencode.ts +107 -0
- package/src/api/routes.ts +93 -0
- package/src/api/schemas/common.ts +21 -0
- package/src/api/schemas/sessions.ts +72 -0
- package/src/api/schemas/usage.ts +50 -0
- package/src/api/schemas/webhooks/claude.ts +32 -0
- package/src/api/schemas/webhooks/codex.ts +34 -0
- package/src/api/schemas/webhooks/opencode.ts +29 -0
- package/src/api/services/claude-session.ts +9 -0
- package/src/api/services/codex-session.ts +8 -0
- package/src/api/services/opencode-session.ts +73 -0
- package/src/classifier.ts +206 -0
- package/src/cli/commands.ts +498 -0
- package/src/cli/prompt.ts +44 -0
- package/src/daemon/cli.ts +27 -0
- package/src/daemon/collectors/claude/README.md +108 -0
- package/src/daemon/collectors/claude/collector.ts +413 -0
- package/src/daemon/collectors/claude/discovery.ts +148 -0
- package/src/daemon/collectors/claude/hooks.ts +181 -0
- package/src/daemon/collectors/claude/index.ts +8 -0
- package/src/daemon/collectors/claude/jsonl.ts +85 -0
- package/src/daemon/collectors/claude/transcript.ts +246 -0
- package/src/daemon/collectors/codex/README.md +147 -0
- package/src/daemon/collectors/codex/collector.ts +661 -0
- package/src/daemon/collectors/codex/discovery.ts +104 -0
- package/src/daemon/collectors/codex/hooks.ts +179 -0
- package/src/daemon/collectors/codex/index.ts +7 -0
- package/src/daemon/collectors/codex/jsonl.ts +108 -0
- package/src/daemon/collectors/codex/transcript.ts +299 -0
- package/src/daemon/collectors/git.ts +295 -0
- package/src/daemon/collectors/opencode/README.md +106 -0
- package/src/daemon/collectors/opencode/collector.ts +543 -0
- package/src/daemon/collectors/opencode/discovery.ts +257 -0
- package/src/daemon/collectors/opencode/index.ts +5 -0
- package/src/daemon/collectors/opencode/session-builder.ts +59 -0
- package/src/daemon/collectors/opencode-db.ts +282 -0
- package/src/daemon/collectors/process.ts +201 -0
- package/src/daemon/collectors/tmux/README.md +128 -0
- package/src/daemon/collectors/tmux/collector.ts +472 -0
- package/src/daemon/collectors/tmux/enrichment.ts +241 -0
- package/src/daemon/collectors/tmux/index.ts +4 -0
- package/src/daemon/collectors/tmux/parse.ts +128 -0
- package/src/daemon/collectors/usage.ts +193 -0
- package/src/daemon/index.ts +207 -0
- package/src/daemon/scheduler.ts +86 -0
- package/src/daemon/store.ts +535 -0
- package/src/detect.ts +143 -0
- package/src/hooks/claude.ts +596 -0
- package/src/hooks/codex.ts +517 -0
- package/src/legacy/classifier.ts +215 -0
- package/src/legacy/detect.ts +143 -0
- package/src/mcp/client-server.ts +21 -0
- package/src/mcp/http-handler.ts +126 -0
- package/src/mcp/index.ts +61 -0
- package/src/mcp/resources/config-current.ts +19 -0
- package/src/mcp/resources/index.ts +11 -0
- package/src/mcp/resources/sessions-active.ts +19 -0
- package/src/mcp/resources/sessions-all.ts +19 -0
- package/src/mcp/schemas/sessions.ts +3 -0
- package/src/mcp/server.ts +17 -0
- package/src/mcp/services/api-adapter.ts +48 -0
- package/src/mcp/services/data-source.ts +22 -0
- package/src/mcp/services/store-adapter.ts +40 -0
- package/src/mcp/tools/get-active-sessions.ts +16 -0
- package/src/mcp/tools/get-session-children.ts +24 -0
- package/src/mcp/tools/get-session-messages.ts +24 -0
- package/src/mcp/tools/get-session.ts +23 -0
- package/src/mcp/tools/index.ts +15 -0
- package/src/mcp/tools/list-sessions.ts +16 -0
- package/src/neo-blessed.d.ts +4 -0
- package/src/oc/index.ts +302 -0
- package/src/service/manager.ts +242 -0
- package/src/shared/config.ts +478 -0
- package/src/shared/ipc.ts +80 -0
- package/src/shared/logger.ts +248 -0
- package/src/shared/paths.ts +73 -0
- package/src/shared/platform.ts +110 -0
- package/src/shared/session-view.ts +241 -0
- package/src/shared/types.ts +299 -0
- package/src/shared/utils.ts +339 -0
- package/src/tui/app.ts +920 -0
- package/src/tui/client.ts +149 -0
- package/src/tui/index.ts +181 -0
- package/src/types.ts +113 -0
- package/src/usage/README.md +323 -0
- package/src/usage/api.ts +99 -0
- package/src/usage/client.ts +3 -0
- package/src/usage/clients/anthropic-oauth-usage.ts +178 -0
- package/src/usage/clients/anthropic-web-usage.ts +245 -0
- package/src/usage/clients/claude-cli-probe.ts +187 -0
- package/src/usage/clients/codex-oauth-usage.ts +113 -0
- package/src/usage/clients/opencode-go-usage.ts +441 -0
- package/src/usage/index.ts +19 -0
- package/src/usage/mappers.ts +273 -0
- package/src/usage/planner.ts +54 -0
- package/src/usage/providers/claude.ts +113 -0
- package/src/usage/providers/codex.ts +34 -0
- package/src/usage/providers/opencode-go.ts +37 -0
- package/src/usage/resolver.ts +4 -0
- package/src/usage/resolvers/browser-cookies.ts +198 -0
- package/src/usage/resolvers/claude-auth.ts +99 -0
- package/src/usage/resolvers/claude-cli.ts +24 -0
- package/src/usage/resolvers/claude-web.ts +16 -0
- package/src/usage/resolvers/codex-auth.ts +117 -0
- package/src/usage/resolvers/opencode-go-web.ts +14 -0
- package/src/usage/types.ts +190 -0
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
import { existsSync, statSync, unwatchFile, watch, watchFile } from "node:fs";
|
|
2
|
+
import type { FSWatcher } from "node:fs";
|
|
3
|
+
import { join, basename, dirname } from "node:path";
|
|
4
|
+
import type { ScrylogConfig } from "../../../shared/config";
|
|
5
|
+
import type { SessionModel } from "../../../shared/types";
|
|
6
|
+
import type { DaemonStore } from "../../store";
|
|
7
|
+
import type { Collector } from "../../scheduler";
|
|
8
|
+
import type { Logger } from "../../../shared/logger";
|
|
9
|
+
import { NOOP_LOGGER } from "../../../shared/logger";
|
|
10
|
+
import { ensureHooksDirSafe } from "../../../shared/platform";
|
|
11
|
+
import type { GitCollector } from "../git";
|
|
12
|
+
import { parseJsonlFile, parseJsonlHead } from "./jsonl";
|
|
13
|
+
import { inferState, extractSummary, extractTitle, isLocalCommandTranscript } from "./transcript";
|
|
14
|
+
import { ClaudeHookFileData, isValidHookData, readHookData, isHookNewer, getHookTime, getExistingHookData, mergeHookIntoModel, mergeClaudeMeta, hasClaudePermissionPrompt } from "./hooks";
|
|
15
|
+
import { discoverTranscripts, getClaudeDir, decodeClaudeProjectSlug, getClaudeProcessPids } from "./discovery";
|
|
16
|
+
|
|
17
|
+
interface WatchedTranscript {
|
|
18
|
+
sessionId: string;
|
|
19
|
+
path: string;
|
|
20
|
+
lastModified: number;
|
|
21
|
+
size: number;
|
|
22
|
+
processedLastModified?: number;
|
|
23
|
+
processedSize?: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class ClaudeCollector implements Collector {
|
|
27
|
+
name = "claude";
|
|
28
|
+
private store?: DaemonStore;
|
|
29
|
+
private config?: ScrylogConfig;
|
|
30
|
+
private logger: Logger = NOOP_LOGGER;
|
|
31
|
+
private watched = new Map<string, WatchedTranscript>();
|
|
32
|
+
private hookWatched = new Set<string>();
|
|
33
|
+
private hookDirWatcher?: FSWatcher;
|
|
34
|
+
private lastProcessedSeq = new Map<string, number>();
|
|
35
|
+
private discoveryTimer?: ReturnType<typeof setInterval>;
|
|
36
|
+
private fallbackTimer?: ReturnType<typeof setInterval>;
|
|
37
|
+
|
|
38
|
+
constructor(private readonly gitCollector?: GitCollector) {}
|
|
39
|
+
|
|
40
|
+
async start(store: DaemonStore, config: ScrylogConfig, logger: Logger): Promise<void> {
|
|
41
|
+
this.store = store;
|
|
42
|
+
this.config = config;
|
|
43
|
+
this.logger = logger;
|
|
44
|
+
|
|
45
|
+
const claudeDir = getClaudeDir(config);
|
|
46
|
+
logger.info("claude", "Collector started", { event: "collector.started", collector: this.name, claudeDir, hooksEnabled: config.claude.hooksEnabled });
|
|
47
|
+
|
|
48
|
+
if (config.claude.hooksEnabled) {
|
|
49
|
+
this.startHooksDirWatcher(config.claude.hooksDir);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
this.run();
|
|
53
|
+
this.discoveryTimer = setInterval(() => this.run(), 30_000);
|
|
54
|
+
this.fallbackTimer = setInterval(() => this.rereadWatched(), 5_000);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async stop(): Promise<void> {
|
|
58
|
+
if (this.discoveryTimer) clearInterval(this.discoveryTimer);
|
|
59
|
+
if (this.fallbackTimer) clearInterval(this.fallbackTimer);
|
|
60
|
+
|
|
61
|
+
for (const { path } of this.watched.values()) {
|
|
62
|
+
try { unwatchFile(path); } catch { /* ignore */ }
|
|
63
|
+
}
|
|
64
|
+
this.watched.clear();
|
|
65
|
+
|
|
66
|
+
for (const hookFile of this.hookWatched) {
|
|
67
|
+
try { unwatchFile(hookFile); } catch { /* ignore */ }
|
|
68
|
+
}
|
|
69
|
+
this.hookWatched.clear();
|
|
70
|
+
this.lastProcessedSeq.clear();
|
|
71
|
+
|
|
72
|
+
if (this.hookDirWatcher) {
|
|
73
|
+
try { this.hookDirWatcher.close(); } catch { /* ignore */ }
|
|
74
|
+
this.hookDirWatcher = undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
this.logger.info("claude", "Collector stopped", { event: "collector.stopped", collector: this.name });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ── Internal ───────────────────────────────────────────────────────────────
|
|
81
|
+
|
|
82
|
+
private run(): void {
|
|
83
|
+
const store = this.store!;
|
|
84
|
+
const config = this.config!;
|
|
85
|
+
const claudeDir = getClaudeDir(config);
|
|
86
|
+
|
|
87
|
+
// Build set of session IDs that are hook-managed, so discoverTranscripts
|
|
88
|
+
// can include their transcripts even past the 24h cutoff.
|
|
89
|
+
const hookManagedIds = new Set<string>();
|
|
90
|
+
for (const session of store.getSessions()) {
|
|
91
|
+
if (session.detectionSource === "claude-hook" && session.tool === "claude") {
|
|
92
|
+
hookManagedIds.add(session.claude?.sessionId ?? session.id.replace(/^claude:/, ""));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const transcripts = discoverTranscripts(claudeDir, hookManagedIds);
|
|
97
|
+
const processSnapshot = this.store?.getCollectorProcessSnapshot?.() ?? [];
|
|
98
|
+
const runningPids = getClaudeProcessPids(this.logger, config.daemon?.commandTimeoutMs, processSnapshot);
|
|
99
|
+
const hasRunning = runningPids.length > 0;
|
|
100
|
+
|
|
101
|
+
this.logger.debug("claude", "Discovery cycle", {
|
|
102
|
+
event: "collector.discovery_completed",
|
|
103
|
+
collector: this.name,
|
|
104
|
+
claudeDir,
|
|
105
|
+
transcripts: transcripts.length,
|
|
106
|
+
runningPids: runningPids.length,
|
|
107
|
+
hasRunning,
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
for (const transcript of transcripts) {
|
|
111
|
+
this.processTranscript(transcript, hasRunning);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const trackedPaths = new Set(transcripts.map((t) => t.path));
|
|
115
|
+
for (const path of trackedPaths) {
|
|
116
|
+
if (!this.watched.has(path)) {
|
|
117
|
+
const transcript = transcripts.find((t) => t.path === path);
|
|
118
|
+
if (!transcript) continue;
|
|
119
|
+
this.watched.set(path, transcript);
|
|
120
|
+
this.logger.debug("claude", "Watching transcript", { sessionId: transcript.sessionId, path });
|
|
121
|
+
watchFile(path, { interval: 2000 }, () => {
|
|
122
|
+
const t = this.watched.get(path);
|
|
123
|
+
if (t) this.processTranscript(t, true);
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
for (const [path, transcript] of this.watched) {
|
|
129
|
+
if (!trackedPaths.has(path)) {
|
|
130
|
+
try { unwatchFile(path); } catch { /* ignore */ }
|
|
131
|
+
this.watched.delete(path);
|
|
132
|
+
this.logger.debug("claude", "Stopped watching transcript", { sessionId: transcript.sessionId });
|
|
133
|
+
// Don't remove hook-managed sessions — they have an authoritative lifecycle
|
|
134
|
+
// managed by hooks (SessionEnd). Only remove transcript-sourced sessions.
|
|
135
|
+
const existingSession = store.getSession(`claude:${transcript.sessionId}`);
|
|
136
|
+
if (existingSession?.detectionSource !== "claude-hook") {
|
|
137
|
+
store.removeSession(`claude:${transcript.sessionId}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
store.setCollectorStatus(this.name, { running: true, lastRunAt: Date.now() });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private processTranscript(transcript: import("./discovery").DiscoveredTranscript, _hasRunning: boolean): void {
|
|
146
|
+
const store = this.store!;
|
|
147
|
+
const config = this.config!;
|
|
148
|
+
const existingSession = store.getSession(`claude:${transcript.sessionId}`);
|
|
149
|
+
const watched = this.watched.get(transcript.path);
|
|
150
|
+
if (
|
|
151
|
+
watched?.processedLastModified === transcript.lastModified
|
|
152
|
+
&& watched.processedSize === transcript.size
|
|
153
|
+
&& existingSession
|
|
154
|
+
) {
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const transcriptMaxBytes = config.retention?.transcriptMaxBytes;
|
|
159
|
+
const entries = parseJsonlFile(transcript.path, transcriptMaxBytes);
|
|
160
|
+
const localCommandEntries = transcriptMaxBytes && transcript.size > transcriptMaxBytes
|
|
161
|
+
? parseJsonlHead(transcript.path, Math.min(transcriptMaxBytes, 64 * 1024))
|
|
162
|
+
: entries;
|
|
163
|
+
|
|
164
|
+
// Skip headless batch runs — they are not interactive sessions
|
|
165
|
+
if (isLocalCommandTranscript(localCommandEntries)) {
|
|
166
|
+
this.logger.debug("claude", "Skipping local-command transcript", { sessionId: transcript.sessionId });
|
|
167
|
+
store.removeSession(`claude:${transcript.sessionId}`);
|
|
168
|
+
store.markLocalCommand(transcript.sessionId);
|
|
169
|
+
this.lastProcessedSeq.delete(transcript.sessionId);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const state = inferState(entries);
|
|
174
|
+
const summary = extractSummary(entries);
|
|
175
|
+
const title = extractTitle(entries);
|
|
176
|
+
|
|
177
|
+
let model: SessionModel = {
|
|
178
|
+
id: `claude:${transcript.sessionId}`,
|
|
179
|
+
source: "standalone",
|
|
180
|
+
tool: "claude",
|
|
181
|
+
state,
|
|
182
|
+
// Use first user message as title when available, falling back to summary
|
|
183
|
+
summary: title ?? summary,
|
|
184
|
+
lastActivity: transcript.lastModified,
|
|
185
|
+
claude: {
|
|
186
|
+
sessionId: transcript.sessionId,
|
|
187
|
+
transcriptPath: transcript.path,
|
|
188
|
+
},
|
|
189
|
+
hasAttention: state === "waiting-input",
|
|
190
|
+
detectionSource: "claude-transcript",
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
// If the session is already managed by hooks, the transcript must never
|
|
194
|
+
// overwrite state, hasAttention, or activeTool. It can only fill missing
|
|
195
|
+
// metadata (e.g. transcriptPath).
|
|
196
|
+
if (existingSession?.detectionSource === "claude-hook") {
|
|
197
|
+
model = {
|
|
198
|
+
...model,
|
|
199
|
+
state: existingSession.state,
|
|
200
|
+
hasAttention: existingSession.hasAttention,
|
|
201
|
+
summary: existingSession.summary || model.summary,
|
|
202
|
+
activeTool: existingSession.activeTool,
|
|
203
|
+
detectionSource: "claude-hook",
|
|
204
|
+
claude: mergeClaudeMeta(
|
|
205
|
+
{
|
|
206
|
+
sessionId: existingSession.claude?.sessionId ?? transcript.sessionId,
|
|
207
|
+
transcriptPath: existingSession.claude?.transcriptPath || transcript.path,
|
|
208
|
+
},
|
|
209
|
+
existingSession.claude ?? {},
|
|
210
|
+
),
|
|
211
|
+
lastActivity: existingSession.lastActivity,
|
|
212
|
+
};
|
|
213
|
+
} else if (config.claude.hooksEnabled) {
|
|
214
|
+
// Hooks are authoritative for live session state. The transcript is only
|
|
215
|
+
// used for discovery and to fill metadata hooks do not provide.
|
|
216
|
+
const fileHookData = readHookData(config.claude.hooksDir, transcript.sessionId);
|
|
217
|
+
const storeHookData = getExistingHookData(existingSession);
|
|
218
|
+
const preferredHookData = [fileHookData, storeHookData]
|
|
219
|
+
.filter((value): value is Partial<SessionModel> => value !== null)
|
|
220
|
+
.sort((a, b) => getHookTime(b) - getHookTime(a))[0];
|
|
221
|
+
|
|
222
|
+
if (preferredHookData && getHookTime(preferredHookData) >= transcript.lastModified && isHookNewer(existingSession, preferredHookData)) {
|
|
223
|
+
model = mergeHookIntoModel(model, preferredHookData, transcript.path);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Apply tmux-based permission prompt detection only for sessions NOT
|
|
228
|
+
// managed by hooks, since hook-managed sessions get authoritative state
|
|
229
|
+
// from the PermissionRequest event.
|
|
230
|
+
if (model.detectionSource !== "claude-hook" && hasClaudePermissionPrompt(existingSession?.sample)) {
|
|
231
|
+
model = { ...model, state: "waiting-input", hasAttention: true, summary: "Do you want to proceed?" };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// Resolve git project info from currentPath (populated by hooks or transcript)
|
|
235
|
+
// Fallback: decode the project path from the transcript directory slug when hooks
|
|
236
|
+
// have not provided a currentPath (e.g. transcript-only sessions or sessions whose
|
|
237
|
+
// hook file is absent).
|
|
238
|
+
if (!model.currentPath) {
|
|
239
|
+
const slug = basename(dirname(transcript.path));
|
|
240
|
+
const decoded = decodeClaudeProjectSlug(slug);
|
|
241
|
+
if (decoded) model = { ...model, currentPath: decoded };
|
|
242
|
+
}
|
|
243
|
+
if (this.gitCollector && model.currentPath && !model.project) {
|
|
244
|
+
const project = this.gitCollector.resolve(model.currentPath);
|
|
245
|
+
if (project) model = { ...model, project };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
store.upsertSession(model);
|
|
249
|
+
const currentWatched = this.watched.get(transcript.path);
|
|
250
|
+
if (currentWatched) {
|
|
251
|
+
this.watched.set(transcript.path, {
|
|
252
|
+
...currentWatched,
|
|
253
|
+
lastModified: transcript.lastModified,
|
|
254
|
+
size: transcript.size,
|
|
255
|
+
processedLastModified: transcript.lastModified,
|
|
256
|
+
processedSize: transcript.size,
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
this.logger.debug("claude", "Processed transcript", { event: "transcript.processed", sessionId: transcript.sessionId, state, detectionSource: model.detectionSource, path: transcript.path });
|
|
260
|
+
|
|
261
|
+
this.syncChildSessionIds();
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Re-process all watched transcripts (fallback polling) */
|
|
265
|
+
private rereadWatched(): void {
|
|
266
|
+
for (const transcript of this.watched.values()) {
|
|
267
|
+
try {
|
|
268
|
+
const stat = statSync(transcript.path);
|
|
269
|
+
this.processTranscript({ ...transcript, lastModified: stat.mtimeMs, size: stat.size }, true);
|
|
270
|
+
} catch {
|
|
271
|
+
// File may have been removed
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Watch the hooks directory for new/changed files so state updates are near-immediate */
|
|
277
|
+
private startHooksDirWatcher(hooksDir: string): void {
|
|
278
|
+
try {
|
|
279
|
+
ensureHooksDirSafe(hooksDir);
|
|
280
|
+
} catch {
|
|
281
|
+
// Directory may be unwritable or fail ownership/permission validation — handled below
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
if (!existsSync(hooksDir)) {
|
|
285
|
+
this.logger.debug("claude", "Hooks dir not found — skipping watcher", { hooksDir });
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// Watch for new files appearing in the hooks dir
|
|
290
|
+
try {
|
|
291
|
+
this.hookDirWatcher = watch(hooksDir, (eventType, filename) => {
|
|
292
|
+
if (!filename || !filename.endsWith(".json")) return;
|
|
293
|
+
const sessionId = basename(filename, ".json");
|
|
294
|
+
this.onHookFileChanged(hooksDir, sessionId, filename);
|
|
295
|
+
});
|
|
296
|
+
} catch {
|
|
297
|
+
this.logger.debug("claude", "Could not watch hooks dir", { hooksDir });
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Called when a hook file is created or modified */
|
|
302
|
+
private onHookFileChanged(hooksDir: string, sessionId: string, filename: string): void {
|
|
303
|
+
const hookFile = join(hooksDir, filename);
|
|
304
|
+
|
|
305
|
+
// Start watching this specific file if not already
|
|
306
|
+
if (!this.hookWatched.has(hookFile)) {
|
|
307
|
+
this.hookWatched.add(hookFile);
|
|
308
|
+
watchFile(hookFile, { interval: 500 }, () => {
|
|
309
|
+
this.onHookFileChanged(hooksDir, sessionId, filename);
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// Skip duplicate processing: if the hookSeq hasn't changed, this is a
|
|
314
|
+
// redundant event from the directory watcher and per-file watchFile.
|
|
315
|
+
const hookData = readHookData(hooksDir, sessionId);
|
|
316
|
+
if (!hookData) {
|
|
317
|
+
// Hook file was deleted (SessionEnd) — clean up watcher
|
|
318
|
+
this.unwatchHookFile(hookFile);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
const incomingSeq = hookData.claude?.hookSeq ?? 0;
|
|
322
|
+
const lastSeq = this.lastProcessedSeq.get(sessionId) ?? -1;
|
|
323
|
+
if (incomingSeq <= lastSeq) return;
|
|
324
|
+
this.lastProcessedSeq.set(sessionId, incomingSeq);
|
|
325
|
+
|
|
326
|
+
this.logger.debug("claude", "Hook received — refreshing session", { event: "integration.event_received", sessionId, hookSeq: incomingSeq });
|
|
327
|
+
|
|
328
|
+
// Find the corresponding transcript to re-process
|
|
329
|
+
const transcriptEntry = [...this.watched.values()].find((t) => t.sessionId === sessionId);
|
|
330
|
+
if (transcriptEntry) {
|
|
331
|
+
try {
|
|
332
|
+
const stat = statSync(transcriptEntry.path);
|
|
333
|
+
this.processTranscript({ ...transcriptEntry, lastModified: stat.mtimeMs, size: stat.size }, true);
|
|
334
|
+
} catch {
|
|
335
|
+
// Transcript may have been removed
|
|
336
|
+
}
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// The transcript may not be watched yet (e.g. a sub-agent session created by SubagentStop hook).
|
|
341
|
+
// hookData was already read above for dedup — use it to create a minimal session entry.
|
|
342
|
+
|
|
343
|
+
const existing = this.store!.getSession(`claude:${sessionId}`);
|
|
344
|
+
if (existing && !isHookNewer(existing, hookData)) {
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
if (existing) {
|
|
348
|
+
// Merge hook data into existing session
|
|
349
|
+
const mergedSummary = hookData.summary ?? existing.summary;
|
|
350
|
+
this.store!.upsertSession({
|
|
351
|
+
...existing,
|
|
352
|
+
...hookData,
|
|
353
|
+
id: existing.id,
|
|
354
|
+
source: existing.source,
|
|
355
|
+
summary: mergedSummary,
|
|
356
|
+
lastActivity: (hookData.lastActivity as number | undefined) ?? existing.lastActivity,
|
|
357
|
+
activeTool: hookData.activeTool ?? existing.activeTool,
|
|
358
|
+
claude: mergeClaudeMeta(
|
|
359
|
+
{
|
|
360
|
+
sessionId,
|
|
361
|
+
transcriptPath: (hookData.claude?.transcriptPath || existing.claude?.transcriptPath || "") as string,
|
|
362
|
+
},
|
|
363
|
+
hookData.claude ?? {},
|
|
364
|
+
),
|
|
365
|
+
});
|
|
366
|
+
this.logger.debug("claude", "Hook merged into session (no transcript)", { event: "session.upsert_from_hook", sessionId, state: hookData.state });
|
|
367
|
+
} else {
|
|
368
|
+
// Minimal stub for a sub-agent session discovered only via hook (e.g. SubagentStop)
|
|
369
|
+
const currentPath = hookData.currentPath as string | undefined;
|
|
370
|
+
const project = (this.gitCollector && currentPath)
|
|
371
|
+
? this.gitCollector.resolve(currentPath) ?? undefined
|
|
372
|
+
: undefined;
|
|
373
|
+
const stub: SessionModel = {
|
|
374
|
+
id: `claude:${sessionId}`,
|
|
375
|
+
source: "standalone",
|
|
376
|
+
tool: "claude",
|
|
377
|
+
state: (hookData.state as SessionModel["state"]) ?? "idle",
|
|
378
|
+
summary: hookData.summary ?? "Claude sub-agent",
|
|
379
|
+
lastActivity: (hookData.lastActivity as number) ?? Date.now(),
|
|
380
|
+
hasAttention: hookData.hasAttention,
|
|
381
|
+
activeTool: hookData.activeTool,
|
|
382
|
+
currentPath,
|
|
383
|
+
project,
|
|
384
|
+
parentSessionId: hookData.parentSessionId,
|
|
385
|
+
detectionSource: "claude-hook",
|
|
386
|
+
claude: mergeClaudeMeta(
|
|
387
|
+
{
|
|
388
|
+
sessionId,
|
|
389
|
+
transcriptPath: (hookData.claude?.transcriptPath ?? "") as string,
|
|
390
|
+
},
|
|
391
|
+
hookData.claude ?? {},
|
|
392
|
+
),
|
|
393
|
+
};
|
|
394
|
+
this.store!.upsertSession(stub);
|
|
395
|
+
this.logger.debug("claude", "Sub-agent session created from hook", { event: "session.upsert_from_hook", sessionId, parentSessionId: hookData.parentSessionId, state: stub.state });
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
this.syncChildSessionIds();
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** Stop watching a per-file watcher and clean up tracking state */
|
|
402
|
+
private unwatchHookFile(hookFile: string): void {
|
|
403
|
+
if (this.hookWatched.has(hookFile)) {
|
|
404
|
+
this.hookWatched.delete(hookFile);
|
|
405
|
+
try { unwatchFile(hookFile); } catch { /* ignore */ }
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Rebuild childSessionIds on parent sessions after any session upsert */
|
|
410
|
+
private syncChildSessionIds(): void {
|
|
411
|
+
this.store!.syncChildSessionIds();
|
|
412
|
+
}
|
|
413
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join, basename, dirname } from "node:path";
|
|
4
|
+
import type { ScrylogConfig } from "../../../shared/config";
|
|
5
|
+
import type { Logger } from "../../../shared/logger";
|
|
6
|
+
import { maybeRunCommand } from "../../../shared/utils";
|
|
7
|
+
import { IS_WINDOWS } from "../../../shared/platform";
|
|
8
|
+
|
|
9
|
+
export interface DiscoveredTranscript {
|
|
10
|
+
sessionId: string;
|
|
11
|
+
path: string;
|
|
12
|
+
lastModified: number;
|
|
13
|
+
size: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function getClaudeDir(config: ScrylogConfig): string {
|
|
17
|
+
return config.claude.claudeDir ?? join(homedir(), ".claude");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Internal: project slugs known to generate headless probe transcripts.
|
|
21
|
+
// Third-party tools (e.g. CodexBar's ClaudeProbe on macOS) launch `claude`
|
|
22
|
+
// periodically to run slash commands like `/usage` for their own telemetry.
|
|
23
|
+
// Each run leaves a tiny transcript that scrylog misreads as an interactive
|
|
24
|
+
// "working" session, cluttering the TUI with ghosts.
|
|
25
|
+
// Not user-configurable — extend here when new probe sources are identified.
|
|
26
|
+
// Patterns are matched case-insensitively with `*` wildcards; on tiers where
|
|
27
|
+
// these tools do not run (Linux/WSL 2, Windows native) the list is a no-op.
|
|
28
|
+
const KNOWN_PROBE_SLUG_GLOBS: readonly string[] = ["*CodexBar-ClaudeProbe*"];
|
|
29
|
+
|
|
30
|
+
function matchesGlob(value: string, pattern: string): boolean {
|
|
31
|
+
const re = new RegExp(
|
|
32
|
+
"^" + pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$",
|
|
33
|
+
"i",
|
|
34
|
+
);
|
|
35
|
+
return re.test(value);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function isKnownProbeSlug(slug: string): boolean {
|
|
39
|
+
return KNOWN_PROBE_SLUG_GLOBS.some((pattern) => matchesGlob(slug, pattern));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Decodes a Claude project slug (e.g. "-Volumes-Files-Workspace-Projects-other-scrylog-feature-daemon")
|
|
44
|
+
* back to an absolute filesystem path ("/Volumes/Files/Workspace/Projects/other/scrylog-feature-daemon").
|
|
45
|
+
*
|
|
46
|
+
* Claude encodes project paths by replacing each "/" with "-", producing an ambiguous slug when
|
|
47
|
+
* directory names themselves contain hyphens. This function resolves the ambiguity by greedily
|
|
48
|
+
* walking the real filesystem: at each level it tries consuming 1, 2, 3… hyphen-separated parts
|
|
49
|
+
* as a single directory name, choosing the first candidate that exists on disk.
|
|
50
|
+
*
|
|
51
|
+
* Returns null if the slug does not start with "-" or no matching path is found.
|
|
52
|
+
*/
|
|
53
|
+
export function decodeClaudeProjectSlug(slug: string): string | null {
|
|
54
|
+
if (!slug.startsWith("-")) return null;
|
|
55
|
+
const parts = slug.slice(1).split("-");
|
|
56
|
+
|
|
57
|
+
function walk(current: string, remaining: string[]): string | null {
|
|
58
|
+
if (remaining.length === 0) return existsSync(current) ? current : null;
|
|
59
|
+
for (let i = 1; i <= remaining.length; i++) {
|
|
60
|
+
const name = remaining.slice(0, i).join("-");
|
|
61
|
+
const candidate = join(current, name);
|
|
62
|
+
if (i === remaining.length) {
|
|
63
|
+
// Last possible split — accept if exists
|
|
64
|
+
if (existsSync(candidate)) return candidate;
|
|
65
|
+
} else if (existsSync(candidate) && statSync(candidate).isDirectory()) {
|
|
66
|
+
const result = walk(candidate, remaining.slice(i));
|
|
67
|
+
if (result !== null) return result;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const root = IS_WINDOWS ? `${process.env.SYSTEMDRIVE ?? "C:"}\\` : "/";
|
|
74
|
+
return walk(root, parts);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function discoverTranscripts(claudeDir: string, hookManagedIds?: ReadonlySet<string>): DiscoveredTranscript[] {
|
|
78
|
+
const projectsDir = join(claudeDir, "projects");
|
|
79
|
+
const results: DiscoveredTranscript[] = [];
|
|
80
|
+
|
|
81
|
+
if (!existsSync(projectsDir)) return results;
|
|
82
|
+
|
|
83
|
+
const cutoff = Date.now() - 24 * 60 * 60 * 1000;
|
|
84
|
+
|
|
85
|
+
try {
|
|
86
|
+
for (const projectSlug of readdirSync(projectsDir)) {
|
|
87
|
+
// Skip project directories emitted by known headless probe tools
|
|
88
|
+
// (e.g. CodexBar's ClaudeProbe). Their transcripts are not interactive
|
|
89
|
+
// sessions and would otherwise show as permanent "working" ghosts.
|
|
90
|
+
if (isKnownProbeSlug(projectSlug)) continue;
|
|
91
|
+
const projectPath = join(projectsDir, projectSlug);
|
|
92
|
+
try {
|
|
93
|
+
if (!statSync(projectPath).isDirectory()) continue;
|
|
94
|
+
for (const file of readdirSync(projectPath)) {
|
|
95
|
+
if (!file.endsWith(".jsonl")) continue;
|
|
96
|
+
const fullPath = join(projectPath, file);
|
|
97
|
+
try {
|
|
98
|
+
const stat = statSync(fullPath);
|
|
99
|
+
const sessionId = basename(file, ".jsonl");
|
|
100
|
+
// Include transcripts beyond the cutoff if the session is hook-managed,
|
|
101
|
+
// since hooks provide authoritative lifecycle and may keep a session
|
|
102
|
+
// alive beyond 24 hours of inactivity in the transcript file.
|
|
103
|
+
if (stat.mtimeMs < cutoff && !hookManagedIds?.has(sessionId)) continue;
|
|
104
|
+
results.push({
|
|
105
|
+
sessionId,
|
|
106
|
+
path: fullPath,
|
|
107
|
+
lastModified: stat.mtimeMs,
|
|
108
|
+
size: stat.size,
|
|
109
|
+
});
|
|
110
|
+
} catch {
|
|
111
|
+
// Skip unreadable files
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
} catch {
|
|
115
|
+
// Skip unreadable project directories
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
} catch {
|
|
119
|
+
// projects dir not accessible
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return results;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function getClaudeProcessPids(logger: Logger, timeoutMs?: number, processes?: { pid: number; command: string }[]): number[] {
|
|
126
|
+
const result = maybeRunCommand(["pgrep", "-f", "claude"], timeoutMs);
|
|
127
|
+
if (result.ok) {
|
|
128
|
+
return result.output
|
|
129
|
+
.split(/\r?\n/)
|
|
130
|
+
.filter(Boolean)
|
|
131
|
+
.map((s) => Number.parseInt(s, 10))
|
|
132
|
+
.filter((n) => !Number.isNaN(n));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
logger.debug("claude", "pgrep failed — falling back to process collector data", { error: result.error });
|
|
136
|
+
|
|
137
|
+
if (processes && processes.length > 0) {
|
|
138
|
+
return processes
|
|
139
|
+
.filter((p) => isClaudeProcessCommand(p.command))
|
|
140
|
+
.map((p) => p.pid);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return [];
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function isClaudeProcessCommand(command: string): boolean {
|
|
147
|
+
return /(?:^|[\\/])claude(?:\.exe)?(?:\s|$)/i.test(command) && !/(scrylog|hook)/i.test(command);
|
|
148
|
+
}
|