@thehammer/danx-session-telemetry 0.1.14 → 0.1.16

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,466 @@
1
+ /**
2
+ * DX-2963 — a running dispatch's usage, worker side.
3
+ *
4
+ * The worker no longer sums anything. It feeds every transcript line into
5
+ * the ONE shared counter (`UsageLedgerCounter`, per-field maximum per reply)
6
+ * and ships the entries that are new or changed since the last acknowledged
7
+ * write to the server (`applyStats`), which derives every total from the
8
+ * ledger and hands them back. The worker's own view of the totals is what the
9
+ * server last returned — plus, for the token ceiling only, a local estimate of
10
+ * what it has read but the server has not acknowledged yet.
11
+ *
12
+ * Totals are taken from the server ONLY at process start (the first write,
13
+ * sent with no entries if there are none) and from each write's response —
14
+ * never seeded by hand (the reattach hand seeds this replaces).
15
+ *
16
+ * DB-free: runs in the DB-less worker. The sink decides the transport
17
+ * (HTTP on a registered worker, getPool-direct on the dashboard).
18
+ */
19
+ import { UsageLedgerCounter, ledgerLineFromLogEntry, excessUsage, syntheticMessageKey, } from "./usage-ledger.js";
20
+ import { ACTIVITY_BATCH_CAP, DispatchUsageTerminalError, chunkEntries, collapseActivityChanges, } from "./stats-wire.js";
21
+ import { createUsageWriteQueue } from "./write-queue.js";
22
+ import { createLogger } from "./internal-logger.js";
23
+ const log = createLogger("dispatch-usage");
24
+ export function zeroUsageTotals() {
25
+ return {
26
+ tokensIn: 0,
27
+ tokensOut: 0,
28
+ cacheRead: 0,
29
+ cacheWrite: 0,
30
+ tokensTotal: 0,
31
+ costUsd: 0,
32
+ turnCount: 0,
33
+ toolCallCount: 0,
34
+ };
35
+ }
36
+ /*
37
+ * DX-2954 — `isPreCardUsageRow` was DELETED here, along with
38
+ * `src/agent/pre-card-lineage.ts` and `markPreCardLineage` below.
39
+ *
40
+ * It answered "did this row count usage before the ledger existed?", which
41
+ * mattered only because a dispatch had nowhere to record HOW FAR it had read:
42
+ * the choice was between re-reading a file from 0 (double-counting) and skipping
43
+ * to its end (losing everything since the last write). `src/agent/start-cursors.ts`
44
+ * dissolves the question — a row WITH stored cursors resumes from them whatever
45
+ * its lineage, and a row WITHOUT any is exactly the case the start order's rule
46
+ * 4 covers. Nothing writes `usage_pre_card_lineage` any more.
47
+ */
48
+ export class DispatchUsage {
49
+ counter = new UsageLedgerCounter();
50
+ serverTotals = zeroUsageTotals();
51
+ acked = new Map();
52
+ healthy = true;
53
+ refused = false;
54
+ started = false;
55
+ queue = createUsageWriteQueue();
56
+ // ── DX-2954: the cursor half ──────────────────────────────────────────────
57
+ /** How to read the watcher's live per-source cursor state. */
58
+ readCursorState = null;
59
+ /**
60
+ * Per source, the `delivered` offset as of the last ACKNOWLEDGED write — which
61
+ * is precisely what `acked` means. Seeded from the cursors this process
62
+ * resumed from, so a restart that writes before reading anything re-reports
63
+ * its own resume point instead of regressing it.
64
+ */
65
+ ackedCursor = new Map();
66
+ /**
67
+ * DX-2954 (AC 34324) — the cursors this process STARTED from, reported
68
+ * verbatim for every source the watcher has not opened yet until one write
69
+ * carrying them has landed. See {@link DispatchUsage.buildCursorReports}.
70
+ */
71
+ startCursors = {};
72
+ startCursorsPersisted = false;
73
+ /** Past-EOF resets to report once, then forget. */
74
+ pastEof = [];
75
+ /**
76
+ * DX-2954 — replies this process read as REPLAYS. The server already counted
77
+ * them for THIS dispatch (they are below its stored `acked`), so they must not
78
+ * enter the unacknowledged excess the token-ceiling estimate adds on top of the
79
+ * server totals.
80
+ */
81
+ replayedMessageIds = new Set();
82
+ /** Running-set changes to report on the next write. */
83
+ pendingActivities = [];
84
+ /** The session transcript path — the ONE path field the wire carries. */
85
+ transcriptPath = null;
86
+ transcriptPathSent = false;
87
+ /**
88
+ * DX-2954 — wire the cursor half up at attach.
89
+ *
90
+ * `startCursors` are the cursors this process RESUMED from
91
+ * (`resolveStartCursors`); their `acked` values seed this collector's own
92
+ * acknowledged floor. `readCursorState` reads the watcher's live offsets at
93
+ * each write.
94
+ */
95
+ attachCursors(readCursorState, startCursors) {
96
+ this.readCursorState = readCursorState;
97
+ this.startCursors = startCursors;
98
+ for (const [source, cursor] of Object.entries(startCursors)) {
99
+ this.ackedCursor.set(source, cursor.acked);
100
+ }
101
+ }
102
+ /**
103
+ * DX-2954 — a stored cursor was past its file's end; report the reset on the
104
+ * next write so the server records a `transcript_cursor_past_eof` event and
105
+ * permits the one sanctioned backwards move of `acked`.
106
+ */
107
+ recordPastEof(info) {
108
+ this.pastEof.push(info);
109
+ // The acknowledged floor MUST drop with the file. Leaving it at the old
110
+ // offset would make the next write report `acked` above its own `delivered`
111
+ // — which `parseStatsPayload` refuses outright ("delivered is behind
112
+ // acked"), and which the getPool-direct sink would store as a cursor pair
113
+ // that can never be satisfied. The bytes we believed acknowledged do not
114
+ // exist any more, so claiming them is simply false.
115
+ this.ackedCursor.set(info.source, 0);
116
+ }
117
+ /**
118
+ * DX-2954 — queue running-set changes for the next write.
119
+ *
120
+ * Kept COLLAPSED (one entry per `(kind, activityId)`) rather than appended
121
+ * raw, so the queue is bounded by how many activities the dispatch has, not by
122
+ * how much they moved since the last write. A producer reports an activity's
123
+ * full current state every time anything about it changes, and a chatty
124
+ * sub-agent advances its `lastActivityAt` continuously — appending those would
125
+ * grow without bound, eventually exceed `ACTIVITY_BATCH_CAP` and take the
126
+ * WHOLE stats write down (not just its activity part) to describe a handful of
127
+ * activities.
128
+ *
129
+ * `collapseActivityChanges` applies the server's own merge rule, so collapsing
130
+ * here reaches the identical stored row; it is not a lossy summarisation.
131
+ */
132
+ recordActivities(changes) {
133
+ this.pendingActivities = collapseActivityChanges([
134
+ ...this.pendingActivities,
135
+ ...changes,
136
+ ]);
137
+ }
138
+ /**
139
+ * DX-2954 — the session's own transcript path, recorded on the dispatch's
140
+ * `jsonl_path`. Sent once, with the first stats write that carries it; the
141
+ * server also keeps only the first path it is given, so a repeat is harmless.
142
+ */
143
+ setTranscriptPath(path) {
144
+ this.transcriptPath = path;
145
+ }
146
+ /**
147
+ * DX-2954 — this write's cursor reports, plus the `delivered` value to promote
148
+ * to `acked` per source once the write is acknowledged.
149
+ *
150
+ * **`acked` deliberately LAGS `delivered` by one write.** A write reports the
151
+ * position it has read to (`delivered`) and the position whose entries a
152
+ * PREVIOUS write already had acknowledged (`acked`); only when THIS write
153
+ * succeeds does its own `delivered` become the next write's `acked`.
154
+ *
155
+ * The lag is not slack — it is what makes the pair safe. A reply's ledger entry
156
+ * can be RAISED after it was first reported (its usage grows as the reply
157
+ * streams), and a delivered line need not produce an entry at all (a
158
+ * `tool_result`), so "the server committed my last write" is NOT the same as
159
+ * "every line I have read is finally accounted for". Reporting `acked` one
160
+ * write behind is the conservative claim that is always true.
161
+ *
162
+ * What it costs: a restart re-reads the last write's window. That is exactly
163
+ * the window `EntryMeta.replay` covers — the ledger re-credits nothing (its
164
+ * excess rule) and every side-effecting subscriber skips it — so the cost is
165
+ * one window of re-read, never a double count or a duplicate side effect.
166
+ *
167
+ * ## The process-start write carries the STARTING cursors (AC 34324)
168
+ *
169
+ * `attachMonitoringStack` deliberately does NOT await `watcher.start()` —
170
+ * file discovery polls for up to 180 s and must not block the spawn — and the
171
+ * process-start stats write fires immediately after it. At that moment the
172
+ * watcher has opened no file, so its live `cursorState()` is empty.
173
+ *
174
+ * So every source in the cursors this process STARTED from that the watcher
175
+ * has not opened yet is reported VERBATIM — the exact `{acked, delivered}`
176
+ * pair it resumed from — until one write carrying them has landed. That is
177
+ * what makes "every attach persists its starting cursors" true on the FIRST
178
+ * write rather than one stats tick (15-30 s) later: a reattach of this row
179
+ * inside its first interval reads them back (start-order rule 1) and starts
180
+ * exactly where this process did, instead of finding no cursor, resolving
181
+ * rule 4 and skipping every line written since spawn. A fresh session's
182
+ * starting cursor is explicit too (`resolveStartCursors` rule 3 returns the
183
+ * main source at 0), and a `--resume`'s is its predecessor's (rule 2).
184
+ *
185
+ * Verbatim is the only honest claim for a source this process has not read:
186
+ * a higher `acked` would let a restart skip the replay window it has not
187
+ * re-credited, a lower one is refused as a regression. For the same reason
188
+ * the start write does not PROMOTE such a source's acknowledged floor — it
189
+ * delivered nothing there — so it stays out of `deliveredAtSend`.
190
+ *
191
+ * The one case with nothing to carry is rule 4 (a continuing dispatch with no
192
+ * cursor for ANY source): its start is "each existing file's end at
193
+ * discovery", which does not exist until discovery runs. Its cursors reach
194
+ * the server on the first write after discovery. Rule 4 is the pre-card
195
+ * deploy transition only — every dispatch since this card stores cursors on
196
+ * its first write — so that bounded window is the one the card accepts.
197
+ */
198
+ buildCursorReports() {
199
+ const reports = {};
200
+ const deliveredAtSend = new Map();
201
+ if (!this.readCursorState) {
202
+ return { reports, deliveredAtSend, reportedResets: [], carriesStartCursors: false };
203
+ }
204
+ const resetBySource = new Map(this.pastEof.map((p) => [p.source, p]));
205
+ const reportedResets = [];
206
+ const live = this.readCursorState();
207
+ let carriesStartCursors = false;
208
+ if (!this.startCursorsPersisted) {
209
+ for (const [source, start] of Object.entries(this.startCursors)) {
210
+ if (source in live)
211
+ continue; // the live state supersedes it once opened
212
+ reports[source] = { acked: start.acked, delivered: start.delivered };
213
+ carriesStartCursors = true;
214
+ }
215
+ }
216
+ for (const [source, state] of Object.entries(live)) {
217
+ // `acked` floors at the source's START offset: a source opened at EOF
218
+ // under rule 4 must never claim byte 0 as acknowledged, or the next
219
+ // restart would read the whole file and re-sum the history rule 4 skipped.
220
+ const acked = Math.max(this.ackedCursor.get(source) ?? 0, state.startOffset);
221
+ const report = { acked, delivered: state.delivered };
222
+ const reset = resetBySource.get(source);
223
+ if (reset) {
224
+ report.pastEof = { storedOffset: reset.storedOffset, fileSize: reset.fileSize };
225
+ reportedResets.push(reset);
226
+ }
227
+ reports[source] = report;
228
+ deliveredAtSend.set(source, state.delivered);
229
+ }
230
+ // Only the resets that actually reached a report are consumed. A reset for a
231
+ // source that has left `cursorState()` (its tail dropped on ENOENT) would
232
+ // otherwise be taken and forgotten, leaving the stored `acked` at a value the
233
+ // file can never satisfy.
234
+ return { reports, deliveredAtSend, reportedResets, carriesStartCursors };
235
+ }
236
+ /**
237
+ * DX-2954 — whether the cursor half has anything new to say. An IDLE dispatch
238
+ * (no new lines, no hook events) must still cost zero writes per tick, which
239
+ * is why a write is not forced merely because cursors EXIST.
240
+ */
241
+ cursorsMoved(reports) {
242
+ for (const [source, report] of Object.entries(reports)) {
243
+ if (report.pastEof !== undefined)
244
+ return true;
245
+ // A source whose `delivered` has not moved past its last acknowledged
246
+ // point has nothing to report. A source seen for the FIRST time has no
247
+ // entry in `ackedCursor` yet, so it always counts as moved — that is how a
248
+ // newly discovered sub-agent file gets its starting cursor persisted.
249
+ if (report.delivered !== this.ackedCursor.get(source))
250
+ return true;
251
+ }
252
+ return false;
253
+ }
254
+ /**
255
+ * Feed one watcher entry. Only assistant lines carry usage / tool ids.
256
+ *
257
+ * `replay` (DX-2954) marks a line re-read after a restart. The line STILL goes
258
+ * to the counter — the ledger is idempotent and dropping it would lose usage a
259
+ * restart is meant to recover — but its id is remembered so the local ceiling
260
+ * estimate does not count it twice (see {@link DispatchUsage.unacknowledged}).
261
+ */
262
+ observeEntry(entry, replay = false) {
263
+ const line = ledgerLineFromLogEntry(entry);
264
+ if (!line)
265
+ return;
266
+ // The counter's OWN key, not `line.messageId`: a usage line with no
267
+ // `message.id` is keyed by `syntheticMessageKey(source, byteOffset)`
268
+ // (`usage-ledger.ts`), and recording a different key here would leave that
269
+ // reply's replay unrecognised — the exact double-count this set prevents.
270
+ if (replay) {
271
+ this.replayedMessageIds.add(line.messageId ?? syntheticMessageKey(line.source, line.byteOffset));
272
+ }
273
+ this.counter.observe(line);
274
+ }
275
+ /**
276
+ * Ship every changed entry in capped batches, one after another. The first
277
+ * call always writes (even with nothing to send) so the process takes the
278
+ * server totals at start. A failed batch re-queues itself and every later
279
+ * batch; a refusal (the dispatch went terminal) stops all later writes.
280
+ *
281
+ * DX-2954 — the write also carries the cursor half. A write happens when there
282
+ * are entries, OR the cursors moved, OR there are activity changes, OR it is
283
+ * the process-start write; an idle dispatch still writes nothing. Cursors,
284
+ * activity changes and the transcript path ride the LAST batch only, so a
285
+ * multi-batch backlog does not repeat them and the cursor can never be
286
+ * acknowledged ahead of the entries it covers.
287
+ */
288
+ flush(sink, dispatchId) {
289
+ return this.queue(async () => {
290
+ if (this.refused)
291
+ return "refused";
292
+ const changed = this.counter.takeChanged();
293
+ const batches = chunkEntries(changed);
294
+ const { reports, deliveredAtSend, reportedResets, carriesStartCursors } = this.buildCursorReports();
295
+ // TAKE the queued side data, exactly as `counter.takeChanged()` does, so a
296
+ // hook that fires during the await lands in the NEXT write rather than
297
+ // being silently dropped by a post-write reset of the live array.
298
+ // Take at most one batch's worth and LEAVE the rest queued. The cap is
299
+ // enforced server-side by the strict parser, and an over-cap payload comes
300
+ // back as a 400 — which is not a `DispatchUsageTerminalError`, so `flush`
301
+ // re-queues it and retries the identical over-cap payload forever. That
302
+ // wedges the dispatch's stats writes PERMANENTLY, entries and cursors
303
+ // included, not just its activity rows. The collapse in `recordActivities`
304
+ // makes crossing the cap unlikely (one entry per distinct activity, not per
305
+ // change), but nothing bounds how many distinct activities a dispatch
306
+ // starts, so the cap is respected here rather than merely made improbable.
307
+ // Splitting across writes is lossless: each row is a full-state idempotent
308
+ // upsert.
309
+ const activities = this.pendingActivities.slice(0, ACTIVITY_BATCH_CAP);
310
+ this.pendingActivities = this.pendingActivities.slice(ACTIVITY_BATCH_CAP);
311
+ // Consume only the resets that reached a report (see `buildCursorReports`).
312
+ const pastEofSent = reportedResets;
313
+ const sentResets = new Set(reportedResets);
314
+ this.pastEof = this.pastEof.filter((p) => !sentResets.has(p));
315
+ // `carriesStartCursors` forces the write on its own: a starting pair like
316
+ // `{acked: 0, delivered: 0}` never looks "moved", and a process-start write
317
+ // whose last batch failed must still deliver it on a later, otherwise idle
318
+ // tick.
319
+ const haveSideData = carriesStartCursors ||
320
+ this.cursorsMoved(reports) ||
321
+ activities.length > 0 ||
322
+ (this.transcriptPath !== null && !this.transcriptPathSent);
323
+ if (batches.length === 0 && (!this.started || haveSideData))
324
+ batches.push([]);
325
+ for (let i = 0; i < batches.length; i++) {
326
+ const payload = { entries: batches[i] };
327
+ const isLast = i === batches.length - 1;
328
+ if (isLast) {
329
+ if (Object.keys(reports).length > 0)
330
+ payload.sourceCursors = reports;
331
+ if (activities.length > 0)
332
+ payload.activities = activities;
333
+ if (this.transcriptPath !== null && !this.transcriptPathSent) {
334
+ payload.transcriptPath = this.transcriptPath;
335
+ }
336
+ }
337
+ try {
338
+ const res = await sink.applyStats(dispatchId, payload);
339
+ this.started = true;
340
+ this.serverTotals = res.totals;
341
+ for (const [id, u] of Object.entries(res.perMessage))
342
+ this.acked.set(id, u);
343
+ if (isLast) {
344
+ // The write landed, so every line up to the `delivered` we SENT is
345
+ // now acknowledged — that is what makes the next restart resume
346
+ // there. A source the server REFUSED as a regression keeps its own
347
+ // stored value, so we must not promote ours past it.
348
+ const refused = new Set(res.cursorRegressions);
349
+ // A source whose file was found truncated WHILE this write was in
350
+ // flight must NOT have its floor promoted. `recordPastEof` dropped
351
+ // that floor to 0 on purpose; re-raising it here would make the next
352
+ // report claim `acked` above its own `delivered`, which
353
+ // `parseStatsPayload` refuses outright — wedging every later write
354
+ // for this dispatch, since nothing lowers `acked` again.
355
+ const resetMidFlight = new Set(this.pastEof.map((p) => p.source));
356
+ for (const [source, delivered] of deliveredAtSend) {
357
+ if (refused.has(source) || resetMidFlight.has(source))
358
+ continue;
359
+ this.ackedCursor.set(source, delivered);
360
+ }
361
+ if (payload.transcriptPath !== undefined)
362
+ this.transcriptPathSent = true;
363
+ this.startCursorsPersisted = true;
364
+ }
365
+ }
366
+ catch (err) {
367
+ if (err instanceof DispatchUsageTerminalError) {
368
+ this.refused = true;
369
+ return "refused";
370
+ }
371
+ this.healthy = false;
372
+ this.counter.requeue(batches.slice(i).flat().map((e) => e.messageId));
373
+ // Re-queue the side data at the FRONT, and leave `ackedCursor` where it
374
+ // was: the next write re-reports all three. Advancing an
375
+ // unacknowledged cursor would skip those lines permanently, and
376
+ // dropping a past-EOF reset would leave the server refusing the
377
+ // eventual lower `acked` as a regression forever.
378
+ // Collapsed on the way back in, so the re-queue keeps the invariant
379
+ // `recordActivities` maintains — and so a failed write followed by
380
+ // fresh changes for the same activity does not double the queue.
381
+ this.pendingActivities = collapseActivityChanges([
382
+ ...activities,
383
+ ...this.pendingActivities,
384
+ ]);
385
+ this.pastEof = [...pastEofSent, ...this.pastEof];
386
+ log.error(`[Dispatch ${dispatchId}] stats write failed — entries re-queued for the next write`, err);
387
+ return "failed";
388
+ }
389
+ }
390
+ this.healthy = true;
391
+ return "ok";
392
+ });
393
+ }
394
+ /** The dispatch's totals as the server last returned them. */
395
+ totals() {
396
+ return this.serverTotals;
397
+ }
398
+ /** Window tokens (input + output + cache writes) of the server totals. */
399
+ serverWindowTokens() {
400
+ const t = this.serverTotals;
401
+ return t.tokensIn + t.tokensOut + t.cacheWrite;
402
+ }
403
+ /** Whether the most recent stats write succeeded. */
404
+ statsHealthy() {
405
+ return this.healthy;
406
+ }
407
+ /**
408
+ * The per-field excess of each local reply's maximum over what the server
409
+ * last acknowledged for it.
410
+ *
411
+ * DX-2954 — REPLAYED replies are excluded. The pre-DX-2954 comment here
412
+ * asserted that "every id this process observed was read at or after its
413
+ * starting cursor … so lines re-read on a restart never enter the estimate",
414
+ * which stopped being true the moment replays became a deliberate input: a
415
+ * replayed reply has no entry in `this.acked` at process start, so its FULL
416
+ * usage would be added on top of `serverTotals` that already contain it. That
417
+ * feeds a fabricated total to the token ceiling (`agent-status.ts` uses this
418
+ * estimate precisely when a write did NOT land) and to the context-overflow
419
+ * decision — either can stop a healthy dispatch.
420
+ */
421
+ unacknowledged() {
422
+ return this.counter
423
+ .all()
424
+ .filter((e) => !this.replayedMessageIds.has(e.messageId))
425
+ .map((e) => excessUsage(e.usage, this.acked.get(e.messageId) ?? {
426
+ input: 0,
427
+ output: 0,
428
+ cacheRead: 0,
429
+ cacheWrite5m: 0,
430
+ cacheWrite1h: 0,
431
+ }));
432
+ }
433
+ /**
434
+ * The dispatch's usage as far as this process knows it: the server totals
435
+ * plus the per-field excess this process has read but the server has not
436
+ * acknowledged. A replay block adds nothing (its excess over the
437
+ * acknowledged total is zero). For a job with no dispatch row (nothing is
438
+ * ever acknowledged) this is exactly the local counter's total.
439
+ */
440
+ estimate() {
441
+ const t = this.serverTotals;
442
+ const out = {
443
+ tokensIn: t.tokensIn,
444
+ tokensOut: t.tokensOut,
445
+ cacheRead: t.cacheRead,
446
+ cacheWrite: t.cacheWrite,
447
+ };
448
+ for (const u of this.unacknowledged()) {
449
+ out.tokensIn += u.input;
450
+ out.tokensOut += u.output;
451
+ out.cacheRead += u.cacheRead;
452
+ out.cacheWrite += u.cacheWrite5m + u.cacheWrite1h;
453
+ }
454
+ return out;
455
+ }
456
+ /** Token-ceiling input: window tokens (input + output + cache writes) of {@link estimate}. */
457
+ windowTokensEstimate() {
458
+ const e = this.estimate();
459
+ return e.tokensIn + e.tokensOut + e.cacheWrite;
460
+ }
461
+ /** All-field total of {@link estimate}. */
462
+ totalTokensEstimate() {
463
+ const e = this.estimate();
464
+ return e.tokensIn + e.tokensOut + e.cacheRead + e.cacheWrite;
465
+ }
466
+ }
package/dist/index.d.ts CHANGED
@@ -14,9 +14,13 @@
14
14
  * — the dashboard server, the dashboard SPA, and any future browser-side
15
15
  * usage display.
16
16
  */
17
- export { SessionLogWatcher, DISPATCH_TAG_PREFIX, encodeClaudeProjectsCwd, deriveSessionDir, sessionUuidExistsInCleanRoom, findNewestJsonlFile, findSessionFileByDispatchId, convertJsonlEntry, } from "./session-log-watcher.js";
18
- export type { EntryConsumer, SessionLogWatcherOptions, } from "./session-log-watcher.js";
17
+ export { SessionLogWatcher, DISPATCH_TAG_PREFIX, encodeClaudeProjectsCwd, deriveSessionDir, sessionUuidExistsInCleanRoom, findNewestJsonlFile, findSessionFileByDispatchId, convertJsonlEntry, skipReplays, } from "./session-log-watcher.js";
18
+ export type { EntryConsumer, SessionLogWatcherOptions, SourceCursorStart, CursorPastEofInfo, SourceDiscoveredInfo, EntryMeta, } from "./session-log-watcher.js";
19
19
  export type { AgentLogEntry, AgentLineage } from "./types.js";
20
20
  export { truncStr, summarizeToolInput, buildAssistantSummary, buildToolResultSummary, } from "./tool-summary.js";
21
21
  export * from "./usage-ledger.js";
22
22
  export * from "./pricing.js";
23
+ export * from "./stats-wire.js";
24
+ export * from "./dispatch-usage.js";
25
+ export * from "./activity-observer.js";
26
+ export * from "./write-queue.js";
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@
14
14
  * — the dashboard server, the dashboard SPA, and any future browser-side
15
15
  * usage display.
16
16
  */
17
- export { SessionLogWatcher, DISPATCH_TAG_PREFIX, encodeClaudeProjectsCwd, deriveSessionDir, sessionUuidExistsInCleanRoom, findNewestJsonlFile, findSessionFileByDispatchId, convertJsonlEntry, } from "./session-log-watcher.js";
17
+ export { SessionLogWatcher, DISPATCH_TAG_PREFIX, encodeClaudeProjectsCwd, deriveSessionDir, sessionUuidExistsInCleanRoom, findNewestJsonlFile, findSessionFileByDispatchId, convertJsonlEntry, skipReplays, } from "./session-log-watcher.js";
18
18
  // `truncStr` is a generic, dependency-free string helper that moved here
19
19
  // alongside the rest of `tool-summary.ts` (it has no other home now that
20
20
  // file is gone from root) — re-exported for danxbot root consumers that
@@ -25,3 +25,13 @@ export { truncStr, summarizeToolInput, buildAssistantSummary, buildToolResultSum
25
25
  // browser-safe `./browser` subpath; both are pure arithmetic).
26
26
  export * from "./usage-ledger.js";
27
27
  export * from "./pricing.js";
28
+ // DX-2954 — the ONE stats collector and its wire, shared by the danxbot worker
29
+ // and the desktop bridge (operator sessions) so both report the same stats the
30
+ // same way (epic DX-2958): the stats payload/response schema and its strict
31
+ // parser, the collector that ships ledger entries + transcript cursors +
32
+ // running-set changes, the transcript-side running-set producer, and the FIFO
33
+ // that orders a dispatch's writes.
34
+ export * from "./stats-wire.js";
35
+ export * from "./dispatch-usage.js";
36
+ export * from "./activity-observer.js";
37
+ export * from "./write-queue.js";
@@ -12,8 +12,11 @@ function emit(level, component, message, error) {
12
12
  else if (error !== undefined) {
13
13
  entry.error = String(error);
14
14
  }
15
- const writer = level === "info" ? console.log : console.error;
16
- writer(JSON.stringify(entry));
15
+ // DX-2954 — every level goes to STDERR. The desktop bridge
16
+ // (`danx-dashboard-mcp bridge`) now runs this collector, and its STDOUT is a
17
+ // JSON Lines protocol channel the plugin parses record by record; a log line
18
+ // there would be read as a bridge record. The worker captures both streams.
19
+ console.error(JSON.stringify(entry));
17
20
  }
18
21
  export function createLogger(component) {
19
22
  return {