agent-run-inspector 0.0.0-stage → 0.8.2
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.ko.md +158 -0
- package/README.md +157 -2
- package/THIRD_PARTY_NOTICES.md +49 -0
- package/bin/cli.js +245 -0
- package/brand-map.json +51 -0
- package/package.json +44 -4
- package/prices.json +405 -0
- package/src/adapters/claude-code/agents.js +272 -0
- package/src/adapters/claude-code/index.js +246 -0
- package/src/adapters/claude-code/llm.js +160 -0
- package/src/adapters/claude-code/tools.js +116 -0
- package/src/adapters/codex/agents.js +91 -0
- package/src/adapters/codex/index.js +217 -0
- package/src/adapters/codex/llm.js +91 -0
- package/src/adapters/codex/tools.js +132 -0
- package/src/app.js +59 -0
- package/src/config.js +43 -0
- package/src/cost.js +104 -0
- package/src/dock.js +62 -0
- package/src/files.js +143 -0
- package/src/groups.js +53 -0
- package/src/index/index.js +73 -0
- package/src/index/scan.js +339 -0
- package/src/index/summary.js +265 -0
- package/src/live/sse.js +202 -0
- package/src/live/tail.js +98 -0
- package/src/live/watch.js +216 -0
- package/src/macos/AppIcon.icns +0 -0
- package/src/macos/app.js +324 -0
- package/src/model/detail.js +142 -0
- package/src/model/provider.js +30 -0
- package/src/model/redact.js +94 -0
- package/src/model/roles.js +23 -0
- package/src/model/tool-brand.js +52 -0
- package/src/model/tool-category.js +28 -0
- package/src/model/totals.js +87 -0
- package/src/model/types.js +72 -0
- package/src/open.js +74 -0
- package/src/roots.js +47 -0
- package/src/server/api-detail.js +40 -0
- package/src/server/api.js +125 -0
- package/src/server/auth.js +46 -0
- package/src/server/http.js +86 -0
- package/src/server/static.js +68 -0
- package/src/service.js +178 -0
- package/src/strings.js +76 -0
- package/src/update-check.js +44 -0
- package/web/agent-panel.js +125 -0
- package/web/api.js +116 -0
- package/web/app.css +453 -0
- package/web/app.js +302 -0
- package/web/call-detail.js +181 -0
- package/web/card.js +286 -0
- package/web/format.js +34 -0
- package/web/graph-layout.js +343 -0
- package/web/graph.js +295 -0
- package/web/groups.js +171 -0
- package/web/icon-192.png +0 -0
- package/web/icon-32.png +0 -0
- package/web/icon-512.png +0 -0
- package/web/icons.js +30 -0
- package/web/index.html +28 -0
- package/web/list-resize.js +43 -0
- package/web/live-follow.js +32 -0
- package/web/manifest.webmanifest +15 -0
- package/web/mini.js +167 -0
- package/web/run-header.js +230 -0
- package/web/session-list.js +378 -0
- package/web/state.js +26 -0
- package/web/strings.js +190 -0
- package/web/timeline-group.js +44 -0
- package/web/timeline-scale.js +146 -0
- package/web/timeline.js +499 -0
package/src/live/sse.js
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// Server-sent events: pushes session-list and per-session span changes to open screens.
|
|
2
|
+
// - The server numbers every event (`seq`, one monotonic counter for the whole hub) and sends it as `id:`.
|
|
3
|
+
// - Each feed (the list, and one per opened session) keeps a short buffer. A client that reconnects with
|
|
4
|
+
// Last-Event-ID gets what it missed; if the buffer no longer reaches back that far (or the id is from a
|
|
5
|
+
// previous server run) it gets one `resync` event and must reload the full session.
|
|
6
|
+
// - Buffers hold raw events; the redactor is applied when an event is written, so a mode change takes
|
|
7
|
+
// effect for everything sent afterwards and nothing unredacted ever leaves the process.
|
|
8
|
+
// - Child files are not tied to a parent session by the watcher: after each batch the hub asks
|
|
9
|
+
// index.list() again, and index.open() re-parses a session whose files changed.
|
|
10
|
+
import { TotalsTree } from '../model/totals.js';
|
|
11
|
+
|
|
12
|
+
export const PING_MS = 15000;
|
|
13
|
+
export const SWEEP_MS = 30000; // how often to re-check whether a running session has gone quiet
|
|
14
|
+
const BUFFER_MAX = 500;
|
|
15
|
+
const STATE_MAX = 32;
|
|
16
|
+
const SLOW_CLIENT_BYTES = 4 * 1024 * 1024;
|
|
17
|
+
|
|
18
|
+
class Feed {
|
|
19
|
+
constructor(floor) {
|
|
20
|
+
this.floor = floor; // every event with seq > floor is in `buf` (until trimmed)
|
|
21
|
+
this.buf = [];
|
|
22
|
+
this.clients = new Set();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
push(ev) {
|
|
26
|
+
this.buf.push(ev);
|
|
27
|
+
while (this.buf.length > BUFFER_MAX) this.floor = this.buf.shift().seq;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param {{ index: { list(): object[], open(id: string): object }, redactor: { apply(kind: string, body: object): object },
|
|
33
|
+
* pingMs?: number, sweepMs?: number, seqBase?: number }} opts
|
|
34
|
+
*/
|
|
35
|
+
export function createLiveHub({ index, redactor, pingMs = PING_MS, sweepMs = SWEEP_MS, seqBase = Date.now() }) {
|
|
36
|
+
// Starting from the clock keeps ids of a restarted server above the ones clients remember.
|
|
37
|
+
let seq = seqBase;
|
|
38
|
+
const listFeed = new Feed(seq);
|
|
39
|
+
const listSeen = new Map(); // session id -> JSON of the last summary sent
|
|
40
|
+
const states = new Map(); // session id -> { feed, tree, spans: Map(id -> { json, seq }), totalsJson, reportedUsd }
|
|
41
|
+
let closed = false;
|
|
42
|
+
|
|
43
|
+
const write = (res, ev) => {
|
|
44
|
+
const body = redactor.apply('event', ev.data);
|
|
45
|
+
res.write(`id: ${ev.seq}\ndata: ${JSON.stringify(body)}\n\n`);
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
function emit(feed, data) {
|
|
49
|
+
const ev = { seq: ++seq, data };
|
|
50
|
+
feed.push(ev);
|
|
51
|
+
for (const res of feed.clients) {
|
|
52
|
+
try {
|
|
53
|
+
write(res, ev);
|
|
54
|
+
if (res.writableLength > SLOW_CLIENT_BYTES) res.destroy();
|
|
55
|
+
} catch {
|
|
56
|
+
feed.clients.delete(res);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return ev.seq;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Brings a session's state up to date with an opened session; emits one event per changed span.
|
|
63
|
+
function sync(id, opened) {
|
|
64
|
+
let st = states.get(id);
|
|
65
|
+
const fresh = !st;
|
|
66
|
+
if (fresh) {
|
|
67
|
+
st = { feed: new Feed(seq), tree: new TotalsTree(), spans: new Map(), totalsJson: null, reportedUsd: null };
|
|
68
|
+
states.set(id, st);
|
|
69
|
+
while (states.size > STATE_MAX) {
|
|
70
|
+
const oldest = [...states].find(([, s]) => s.feed.clients.size === 0);
|
|
71
|
+
if (!oldest) break;
|
|
72
|
+
states.delete(oldest[0]);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
st.reportedUsd = opened.reportedUsd ?? null;
|
|
76
|
+
for (const span of opened.spans) {
|
|
77
|
+
const json = JSON.stringify(span);
|
|
78
|
+
const prev = st.spans.get(span.id);
|
|
79
|
+
if (prev && prev.json === json) continue;
|
|
80
|
+
st.tree.upsert(span);
|
|
81
|
+
if (fresh) {
|
|
82
|
+
st.spans.set(span.id, { json, seq: 0 });
|
|
83
|
+
} else {
|
|
84
|
+
const n = emit(st.feed, { type: 'span', span: { ...span, seq: seq + 1 } });
|
|
85
|
+
st.spans.set(span.id, { json, seq: n });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const totals = st.tree.snapshot({ reportedUsd: st.reportedUsd });
|
|
89
|
+
const totalsJson = JSON.stringify(totals);
|
|
90
|
+
if (totalsJson !== st.totalsJson) {
|
|
91
|
+
if (!fresh && st.totalsJson !== null) emit(st.feed, { type: 'totals', totals });
|
|
92
|
+
st.totalsJson = totalsJson;
|
|
93
|
+
}
|
|
94
|
+
return st;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Current seq of a session after syncing it, and its spans stamped with the seq of their last change. */
|
|
98
|
+
function track(id, opened) {
|
|
99
|
+
const st = sync(id, opened);
|
|
100
|
+
return {
|
|
101
|
+
seq,
|
|
102
|
+
spans: opened.spans.map((s) => ({ ...s, seq: st.spans.get(s.id)?.seq ?? 0 })),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
let hasRunning = false;
|
|
107
|
+
// The index drops a session from "running" by the clock, so no file change announces it.
|
|
108
|
+
const sweep = setInterval(() => {
|
|
109
|
+
if (!closed && hasRunning && listFeed.clients.size) {
|
|
110
|
+
try { diffList(); } catch { /* the next tick tries again */ }
|
|
111
|
+
}
|
|
112
|
+
}, sweepMs);
|
|
113
|
+
sweep.unref?.();
|
|
114
|
+
|
|
115
|
+
function diffList() {
|
|
116
|
+
const summaries = index.list();
|
|
117
|
+
const first = listSeen.size === 0;
|
|
118
|
+
const now = new Set();
|
|
119
|
+
hasRunning = false;
|
|
120
|
+
for (const summary of summaries) {
|
|
121
|
+
now.add(summary.id);
|
|
122
|
+
if (summary.status === 'running') hasRunning = true;
|
|
123
|
+
const json = JSON.stringify(summary);
|
|
124
|
+
if (listSeen.get(summary.id) === json) continue;
|
|
125
|
+
listSeen.set(summary.id, json);
|
|
126
|
+
if (!first) emit(listFeed, { type: 'session', summary });
|
|
127
|
+
}
|
|
128
|
+
for (const id of listSeen.keys()) if (!now.has(id)) listSeen.delete(id);
|
|
129
|
+
return summaries;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Feed this to createWatcher({ onBatch }). Works from what the index sees, not from the batch lines. */
|
|
133
|
+
function onBatch() {
|
|
134
|
+
if (closed) return;
|
|
135
|
+
const before = new Map(listSeen);
|
|
136
|
+
const summaries = diffList();
|
|
137
|
+
for (const summary of summaries) {
|
|
138
|
+
if (!states.has(summary.id) || before.get(summary.id) === listSeen.get(summary.id)) continue;
|
|
139
|
+
try {
|
|
140
|
+
sync(summary.id, index.open(summary.id));
|
|
141
|
+
} catch {
|
|
142
|
+
// the session vanished or cannot be parsed right now; the next batch tries again
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function startStream(req, res, feed) {
|
|
148
|
+
res.statusCode = 200;
|
|
149
|
+
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
|
150
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
151
|
+
res.setHeader('Connection', 'keep-alive');
|
|
152
|
+
res.setHeader('X-Accel-Buffering', 'no');
|
|
153
|
+
res.flushHeaders?.();
|
|
154
|
+
const raw = req.headers['last-event-id'];
|
|
155
|
+
const last = raw === undefined ? null : Number(raw);
|
|
156
|
+
let replay = [];
|
|
157
|
+
let resync = false;
|
|
158
|
+
if (last !== null) {
|
|
159
|
+
if (!Number.isInteger(last) || last > seq || last < feed.floor) resync = true;
|
|
160
|
+
else replay = feed.buf.filter((e) => e.seq > last);
|
|
161
|
+
}
|
|
162
|
+
res.write(': ok\n\n');
|
|
163
|
+
if (resync) res.write('data: {"type":"resync"}\n\n');
|
|
164
|
+
for (const ev of replay) write(res, ev);
|
|
165
|
+
feed.clients.add(res);
|
|
166
|
+
const ping = setInterval(() => {
|
|
167
|
+
try { res.write(': ping\n\n'); } catch { cleanup(); }
|
|
168
|
+
}, pingMs);
|
|
169
|
+
ping.unref?.();
|
|
170
|
+
function cleanup() {
|
|
171
|
+
clearInterval(ping);
|
|
172
|
+
feed.clients.delete(res);
|
|
173
|
+
}
|
|
174
|
+
res.on('close', cleanup);
|
|
175
|
+
res.on('error', cleanup);
|
|
176
|
+
req.on('close', cleanup);
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** GET /api/sessions/stream */
|
|
181
|
+
function streamList(req, res) {
|
|
182
|
+
diffList(); // learn the current state so the first change shows up as a change
|
|
183
|
+
return startStream(req, res, listFeed);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** GET /api/sessions/:id/stream; `opened` is the result of index.open(id). */
|
|
187
|
+
function streamSession(req, res, id, opened) {
|
|
188
|
+
return startStream(req, res, sync(id, opened).feed);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function close() {
|
|
192
|
+
closed = true;
|
|
193
|
+
clearInterval(sweep);
|
|
194
|
+
for (const feed of [listFeed, ...[...states.values()].map((s) => s.feed)]) {
|
|
195
|
+
for (const res of feed.clients) res.end();
|
|
196
|
+
feed.clients.clear();
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const clientCount = () => listFeed.clients.size + [...states.values()].reduce((n, s) => n + s.feed.clients.size, 0);
|
|
201
|
+
return { onBatch, streamList, streamSession, track, close, clientCount, currentSeq: () => seq };
|
|
202
|
+
}
|
package/src/live/tail.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Follows appended lines of run-log files through the file store (read-only).
|
|
2
|
+
// Per file it keeps: size, mtime, inode, the byte offset just past the last complete line, and the
|
|
3
|
+
// number of lines handed out. An unfinished last line is simply not consumed: the offset stays
|
|
4
|
+
// before it, so the next poll re-reads it once the newline has arrived.
|
|
5
|
+
// If the file got smaller or its inode changed, reading restarts from byte 0 and the callback is
|
|
6
|
+
// told with `reset: true` (the consumer must drop its parser state for that file).
|
|
7
|
+
|
|
8
|
+
// spec §11-7 (cc-file-rotation, real logs, counts only): 14 of 397 main files contain a
|
|
9
|
+
// compact_boundary, none changes sessionId afterwards and no sessionId spans two files, so
|
|
10
|
+
// compaction does not rotate files. The reset path stays as a safeguard.
|
|
11
|
+
|
|
12
|
+
export const TAIL_MAX_AGE_MS = 24 * 3600e3;
|
|
13
|
+
const READ_CHUNK = 1024 * 1024;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {{ store: { stat(id:number):{size:number,mtimeMs:number,ino?:number}, readRange(id:number,o:number,l:number):Buffer },
|
|
17
|
+
* onLines?: (fileId:number, ev:{ lines:string[], firstLine:number, reset:boolean }) => void,
|
|
18
|
+
* maxAgeMs?: number, now?: () => number }} opts
|
|
19
|
+
*/
|
|
20
|
+
export function createTail({ store, onLines, maxAgeMs = TAIL_MAX_AGE_MS, now = Date.now }) {
|
|
21
|
+
let handler = onLines ?? (() => {});
|
|
22
|
+
const files = new Map(); // fileId -> { size, mtimeMs, ino, offset, lineNo }
|
|
23
|
+
|
|
24
|
+
function setHandler(fn) {
|
|
25
|
+
handler = fn;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Starts following a file. Returns false when it was not modified within `maxAgeMs`. */
|
|
29
|
+
function track(fileId, { offset = 0, lineNo = 0 } = {}) {
|
|
30
|
+
if (files.has(fileId)) return true;
|
|
31
|
+
const st = store.stat(fileId);
|
|
32
|
+
if (now() - st.mtimeMs > maxAgeMs) return false;
|
|
33
|
+
files.set(fileId, { size: -1, mtimeMs: -1, ino: st.ino, offset, lineNo });
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function untrack(fileId) {
|
|
38
|
+
files.delete(fileId);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const tracked = () => [...files.keys()];
|
|
42
|
+
|
|
43
|
+
/** Reads what was appended since the last poll. Returns the number of lines emitted. */
|
|
44
|
+
function poll(fileId) {
|
|
45
|
+
const f = files.get(fileId);
|
|
46
|
+
if (!f) return 0;
|
|
47
|
+
let st;
|
|
48
|
+
try {
|
|
49
|
+
st = store.stat(fileId);
|
|
50
|
+
} catch {
|
|
51
|
+
return 0; // gone for now; a later poll may find it again
|
|
52
|
+
}
|
|
53
|
+
let reset = false;
|
|
54
|
+
if (st.size < f.offset || (f.ino !== undefined && st.ino !== undefined && st.ino !== f.ino)) {
|
|
55
|
+
reset = true;
|
|
56
|
+
f.offset = 0;
|
|
57
|
+
f.lineNo = 0;
|
|
58
|
+
} else if (st.size === f.size && st.mtimeMs === f.mtimeMs) {
|
|
59
|
+
return 0;
|
|
60
|
+
}
|
|
61
|
+
f.size = st.size;
|
|
62
|
+
f.mtimeMs = st.mtimeMs;
|
|
63
|
+
f.ino = st.ino;
|
|
64
|
+
|
|
65
|
+
const lines = [];
|
|
66
|
+
let carry = Buffer.alloc(0);
|
|
67
|
+
let pos = f.offset;
|
|
68
|
+
while (pos < st.size) {
|
|
69
|
+
const buf = store.readRange(fileId, pos, Math.min(READ_CHUNK, st.size - pos));
|
|
70
|
+
if (!buf.length) break;
|
|
71
|
+
pos += buf.length;
|
|
72
|
+
let data = carry.length ? Buffer.concat([carry, buf]) : buf;
|
|
73
|
+
let start = 0;
|
|
74
|
+
let nl;
|
|
75
|
+
while ((nl = data.indexOf(0x0a, start)) !== -1) {
|
|
76
|
+
let text = data.toString('utf8', start, nl);
|
|
77
|
+
if (text.endsWith('\r')) text = text.slice(0, -1);
|
|
78
|
+
lines.push(text);
|
|
79
|
+
f.offset += nl + 1 - start;
|
|
80
|
+
start = nl + 1;
|
|
81
|
+
}
|
|
82
|
+
carry = data.subarray(start);
|
|
83
|
+
}
|
|
84
|
+
if (!lines.length && !reset) return 0;
|
|
85
|
+
const firstLine = f.lineNo + 1;
|
|
86
|
+
f.lineNo += lines.length;
|
|
87
|
+
handler(fileId, { lines, firstLine, reset });
|
|
88
|
+
return lines.length;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function pollAll() {
|
|
92
|
+
let n = 0;
|
|
93
|
+
for (const id of files.keys()) n += poll(id);
|
|
94
|
+
return n;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return { track, untrack, tracked, poll, pollAll, setHandler };
|
|
98
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// Watches the registered log folders and turns file changes into batches of new lines.
|
|
2
|
+
// Primary signal: fs.watch(recursive), collected for 200 ms. fs.watch can miss events (macOS and
|
|
3
|
+
// Linux both), so a slow sweep (stat of every recent .jsonl) always runs as a backstop; if
|
|
4
|
+
// fs.watch is unsupported or errors, or `usePolling` is set, the sweep runs fast (2 s) instead.
|
|
5
|
+
// New files (including sub-agent / child rollouts) are registered in the file store and followed
|
|
6
|
+
// from line 1; mapping a file to its parent session is the index's job (call index.list() after
|
|
7
|
+
// a batch: it groups children by folder / thread id).
|
|
8
|
+
import { readdirSync, statSync, watch as fsWatch } from 'node:fs';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { createTail, TAIL_MAX_AGE_MS } from './tail.js';
|
|
11
|
+
|
|
12
|
+
export const DEBOUNCE_MS = 200;
|
|
13
|
+
export const POLL_MS = 2000;
|
|
14
|
+
export const SAFETY_SWEEP_MS = 10000;
|
|
15
|
+
|
|
16
|
+
function walk(dir, visit) {
|
|
17
|
+
let list;
|
|
18
|
+
try {
|
|
19
|
+
list = readdirSync(dir, { withFileTypes: true });
|
|
20
|
+
} catch {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
for (const d of list) {
|
|
24
|
+
if (d.isSymbolicLink()) continue;
|
|
25
|
+
const p = join(dir, d.name);
|
|
26
|
+
if (d.isDirectory()) walk(p, visit);
|
|
27
|
+
else if (d.isFile() && d.name.endsWith('.jsonl')) visit(p);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* onBatch receives events: `{ fileId, isNew, reset, firstLine, lines }`. `isNew` = the file did not
|
|
33
|
+
* exist when the watcher started (or was never seen). `firstLine === 1` means "from the start of the file".
|
|
34
|
+
* @param {{ roots: string[], store: object, onBatch: (events: object[]) => void,
|
|
35
|
+
* usePolling?: boolean, debounceMs?: number, pollMs?: number, safetySweepMs?: number,
|
|
36
|
+
* maxAgeMs?: number, now?: () => number, onError?: (kind: string) => void }} opts
|
|
37
|
+
*/
|
|
38
|
+
export function createWatcher({
|
|
39
|
+
roots,
|
|
40
|
+
store,
|
|
41
|
+
onBatch,
|
|
42
|
+
usePolling = false,
|
|
43
|
+
debounceMs = DEBOUNCE_MS,
|
|
44
|
+
pollMs = POLL_MS,
|
|
45
|
+
safetySweepMs = SAFETY_SWEEP_MS,
|
|
46
|
+
maxAgeMs = TAIL_MAX_AGE_MS,
|
|
47
|
+
now = Date.now,
|
|
48
|
+
onError = () => {},
|
|
49
|
+
}) {
|
|
50
|
+
let events = [];
|
|
51
|
+
const tail = createTail({
|
|
52
|
+
store,
|
|
53
|
+
maxAgeMs,
|
|
54
|
+
now,
|
|
55
|
+
onLines: (fileId, ev) => events.push({ fileId, isNew: newIds.has(fileId), ...ev }),
|
|
56
|
+
});
|
|
57
|
+
const seen = new Map(); // path -> "size:mtime:ino" at last sweep
|
|
58
|
+
const known = new Set(); // paths present at start
|
|
59
|
+
const newIds = new Set();
|
|
60
|
+
const dirty = new Set();
|
|
61
|
+
const watchers = [];
|
|
62
|
+
let mode = 'stopped';
|
|
63
|
+
let debounce = null;
|
|
64
|
+
let sweepTimer = null;
|
|
65
|
+
|
|
66
|
+
function stamp(path) {
|
|
67
|
+
try {
|
|
68
|
+
const st = statSync(path);
|
|
69
|
+
return st.isFile() ? { key: `${st.size}:${st.mtimeMs}:${st.ino}`, mtimeMs: st.mtimeMs } : null;
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Looks at every recent .jsonl; marks the ones that differ from the last look as dirty.
|
|
76
|
+
function sweep({ baseline = false } = {}) {
|
|
77
|
+
for (const root of roots) {
|
|
78
|
+
walk(root, (p) => {
|
|
79
|
+
const s = stamp(p);
|
|
80
|
+
if (!s) return;
|
|
81
|
+
if (baseline) {
|
|
82
|
+
known.add(p);
|
|
83
|
+
seen.set(p, s.key);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (now() - s.mtimeMs > maxAgeMs) return;
|
|
87
|
+
if (seen.get(p) !== s.key) {
|
|
88
|
+
seen.set(p, s.key);
|
|
89
|
+
dirty.add(p);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function handlePath(p) {
|
|
96
|
+
let fileId;
|
|
97
|
+
try {
|
|
98
|
+
fileId = store.add(p);
|
|
99
|
+
} catch {
|
|
100
|
+
return; // not a regular file inside a root (gone, symlink out, ...)
|
|
101
|
+
}
|
|
102
|
+
if (!known.has(p)) {
|
|
103
|
+
newIds.add(fileId);
|
|
104
|
+
known.add(p);
|
|
105
|
+
}
|
|
106
|
+
tail.track(fileId); // false when older than 24 h: not followed
|
|
107
|
+
tail.poll(fileId);
|
|
108
|
+
if (newIds.has(fileId) && !events.some((e) => e.fileId === fileId)) {
|
|
109
|
+
events.push({ fileId, isNew: true, reset: false, firstLine: 1, lines: [] });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Processes everything marked dirty and delivers one batch. Synchronous. */
|
|
114
|
+
function flush() {
|
|
115
|
+
if (debounce) {
|
|
116
|
+
clearTimeout(debounce);
|
|
117
|
+
debounce = null;
|
|
118
|
+
}
|
|
119
|
+
const paths = [...dirty];
|
|
120
|
+
dirty.clear();
|
|
121
|
+
for (const p of paths) {
|
|
122
|
+
if (!p.endsWith('.jsonl')) continue;
|
|
123
|
+
const s = stamp(p);
|
|
124
|
+
if (s) seen.set(p, s.key);
|
|
125
|
+
handlePath(p);
|
|
126
|
+
}
|
|
127
|
+
// Followed files can also have grown without an event.
|
|
128
|
+
tail.pollAll();
|
|
129
|
+
const out = events;
|
|
130
|
+
events = [];
|
|
131
|
+
if (out.length) {
|
|
132
|
+
try {
|
|
133
|
+
onBatch(out);
|
|
134
|
+
} catch {
|
|
135
|
+
onError('batch-handler');
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function schedule() {
|
|
142
|
+
if (debounce) return;
|
|
143
|
+
debounce = setTimeout(flush, debounceMs);
|
|
144
|
+
debounce.unref?.();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function startSweepTimer(ms) {
|
|
148
|
+
sweepTimer = setInterval(() => {
|
|
149
|
+
sweep();
|
|
150
|
+
if (dirty.size) schedule();
|
|
151
|
+
}, ms);
|
|
152
|
+
sweepTimer.unref?.();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function fallBackToPolling(kind) {
|
|
156
|
+
onError(kind);
|
|
157
|
+
for (const w of watchers.splice(0)) {
|
|
158
|
+
try {
|
|
159
|
+
w.close();
|
|
160
|
+
} catch {
|
|
161
|
+
// already closed
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (sweepTimer) clearInterval(sweepTimer);
|
|
165
|
+
mode = 'poll';
|
|
166
|
+
startSweepTimer(pollMs);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function start() {
|
|
170
|
+
if (mode !== 'stopped') return;
|
|
171
|
+
sweep({ baseline: true });
|
|
172
|
+
if (usePolling) {
|
|
173
|
+
mode = 'poll';
|
|
174
|
+
startSweepTimer(pollMs);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
mode = 'watch';
|
|
178
|
+
for (const root of roots) {
|
|
179
|
+
try {
|
|
180
|
+
const w = fsWatch(root, { recursive: true, persistent: false }, (_type, name) => {
|
|
181
|
+
if (name === null || name === undefined) {
|
|
182
|
+
sweep();
|
|
183
|
+
} else if (String(name).endsWith('.jsonl')) {
|
|
184
|
+
dirty.add(join(root, String(name)));
|
|
185
|
+
} else {
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
schedule();
|
|
189
|
+
});
|
|
190
|
+
w.on('error', () => fallBackToPolling('watch-error'));
|
|
191
|
+
watchers.push(w);
|
|
192
|
+
} catch {
|
|
193
|
+
fallBackToPolling('watch-unsupported');
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
startSweepTimer(safetySweepMs);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function stop() {
|
|
201
|
+
for (const w of watchers.splice(0)) {
|
|
202
|
+
try {
|
|
203
|
+
w.close();
|
|
204
|
+
} catch {
|
|
205
|
+
// already closed
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (debounce) clearTimeout(debounce);
|
|
209
|
+
if (sweepTimer) clearInterval(sweepTimer);
|
|
210
|
+
debounce = null;
|
|
211
|
+
sweepTimer = null;
|
|
212
|
+
mode = 'stopped';
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
return { start, stop, flush, sweep, tail, get mode() { return mode; } };
|
|
216
|
+
}
|
|
Binary file
|