@linxiraos/pi-stats 1.4.6 → 1.4.9
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/CHANGELOG.md +15 -1
- package/README.md +18 -18
- package/dist/client/index.js +86 -86
- package/dist/types/chunked-insert.d.ts +32 -0
- package/dist/types/client/api.d.ts +4 -0
- package/dist/types/client/app/CloseButton.d.ts +7 -0
- package/dist/types/client/app/keys.d.ts +9 -0
- package/dist/types/client/traces/SpanDrawer.d.ts +9 -3
- package/dist/types/client/traces/TimelineCanvas.d.ts +3 -1
- package/dist/types/client/traces/TraceView.d.ts +13 -0
- package/dist/types/client/traces/index.d.ts +5 -0
- package/dist/types/client/traces/trace-colors.d.ts +3 -1
- package/dist/types/client/ui/SearchInput.d.ts +2 -1
- package/dist/types/db.d.ts +5 -5
- package/dist/types/index.d.ts +1 -1
- package/dist/types/parser.d.ts +1 -1
- package/dist/types/port-conflict.d.ts +9 -3
- package/dist/types/server.d.ts +14 -3
- package/dist/types/shared-types.d.ts +3 -2
- package/dist/types/trace.d.ts +27 -1
- package/dist/types/types.d.ts +6 -1
- package/package.json +12 -10
- package/src/chunked-insert.ts +89 -0
- package/src/client/api.ts +13 -0
- package/src/client/app/CloseButton.tsx +56 -0
- package/src/client/app/Shell.tsx +4 -11
- package/src/client/app/keys.ts +21 -0
- package/src/client/data/query.ts +12 -4
- package/src/client/react-css.d.ts +8 -0
- package/src/client/traces/SpanDrawer.tsx +58 -10
- package/src/client/traces/TimelineCanvas.tsx +13 -4
- package/src/client/traces/TraceView.tsx +171 -153
- package/src/client/traces/TranscriptList.tsx +1 -1
- package/src/client/traces/index.ts +5 -0
- package/src/client/traces/trace-colors.ts +14 -10
- package/src/client/ui/Card.tsx +2 -2
- package/src/client/ui/Drawer.tsx +2 -2
- package/src/client/ui/SearchInput.tsx +9 -1
- package/src/client/ui/Stat.tsx +2 -5
- package/src/db.ts +203 -151
- package/src/index.ts +1 -1
- package/src/parser.ts +22 -6
- package/src/port-conflict.ts +67 -30
- package/src/server.ts +63 -31
- package/src/shared-types.ts +3 -2
- package/src/trace.ts +119 -35
- package/src/types.ts +6 -1
package/src/port-conflict.ts
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import type { Dirent } from "node:fs";
|
|
2
2
|
import * as fs from "node:fs/promises";
|
|
3
3
|
import * as path from "node:path";
|
|
4
|
-
import { $which } from "@linxiraos/pi-utils";
|
|
4
|
+
import { $which, logger } from "@linxiraos/pi-utils";
|
|
5
5
|
import { $ } from "bun";
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Upper bound on the identity probe. A live dashboard ingests on its main thread
|
|
9
|
+
* (serially on macOS), which stalls its responses for over a second on large
|
|
10
|
+
* histories; giving up sooner mistakes a busy dashboard for a hung listener.
|
|
11
|
+
*/
|
|
12
|
+
const STATS_PROBE_TIMEOUT_MS = 3_000;
|
|
8
13
|
const PROCESS_EXIT_POLL_MS = 50;
|
|
9
14
|
const PROCESS_EXIT_POLLS = 10;
|
|
10
15
|
const STATS_RUNTIME_IMAGES: Record<string, true> = {
|
|
@@ -35,15 +40,29 @@ export const STATS_DASHBOARD_SECURITY_VERSION = "3";
|
|
|
35
40
|
/** IPv4 loopback address shared by the dashboard server and reuse probe. */
|
|
36
41
|
export const STATS_DASHBOARD_HOSTNAME = "127.0.0.1";
|
|
37
42
|
|
|
38
|
-
|
|
43
|
+
/**
|
|
44
|
+
* What answers on the dashboard port:
|
|
45
|
+
* - `reusable`: a current dashboard bound to the requested host.
|
|
46
|
+
* - `replaceable`: an older dashboard this version may upgrade.
|
|
47
|
+
* - `occupied`: any other HTTP answer.
|
|
48
|
+
* - `unresponsive`: accepted the connection but did not answer in time (busy or hung).
|
|
49
|
+
* - `unreachable`: the connection failed, typically because nothing listens there.
|
|
50
|
+
*/
|
|
51
|
+
type StatsDashboardProbe = "reusable" | "replaceable" | "occupied" | "unresponsive" | "unreachable";
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* How {@link startServer} proceeds with the requested port: bind it, reuse the
|
|
55
|
+
* dashboard already serving it, or fall back to an ephemeral port because the
|
|
56
|
+
* holder is neither reusable nor safe to stop.
|
|
57
|
+
*/
|
|
58
|
+
export type StatsPortClaim = "bind" | "reuse" | "fallback";
|
|
39
59
|
|
|
40
60
|
async function probeStatsDashboard(port: number, hostname: string): Promise<StatsDashboardProbe> {
|
|
41
61
|
const probeHostname = hostname === "0.0.0.0" ? STATS_DASHBOARD_HOSTNAME : hostname === "::" ? "::1" : hostname;
|
|
42
62
|
const urlHostname = probeHostname.includes(":") ? `[${probeHostname}]` : probeHostname;
|
|
63
|
+
const signal = AbortSignal.timeout(STATS_PROBE_TIMEOUT_MS);
|
|
43
64
|
try {
|
|
44
|
-
const response = await fetch(`http://${urlHostname}:${port}/api/stats/models`, {
|
|
45
|
-
signal: AbortSignal.timeout(STATS_PROBE_TIMEOUT_MS),
|
|
46
|
-
});
|
|
65
|
+
const response = await fetch(`http://${urlHostname}:${port}/api/stats/models`, { signal });
|
|
47
66
|
const dashboardVersionHeader = response.headers.get(STATS_DASHBOARD_HEADER);
|
|
48
67
|
const dashboardVersion = dashboardVersionHeader === null ? Number.NaN : Number(dashboardVersionHeader);
|
|
49
68
|
// Never replace a newer dashboard: an older CLI must not downgrade it.
|
|
@@ -61,7 +80,7 @@ async function probeStatsDashboard(port: number, hostname: string): Promise<Stat
|
|
|
61
80
|
if (reusable) return "reusable";
|
|
62
81
|
return replaceable ? "replaceable" : "occupied";
|
|
63
82
|
} catch {
|
|
64
|
-
return "unreachable";
|
|
83
|
+
return signal.aborted ? "unresponsive" : "unreachable";
|
|
65
84
|
}
|
|
66
85
|
}
|
|
67
86
|
|
|
@@ -236,13 +255,16 @@ async function terminatePortHolder(holder: PortHolder): Promise<void> {
|
|
|
236
255
|
await Bun.sleep(PROCESS_EXIT_POLL_MS);
|
|
237
256
|
}
|
|
238
257
|
|
|
239
|
-
|
|
258
|
+
/**
|
|
259
|
+
* Stop the stats dashboard answering `probe` on `port` so it can be rebound.
|
|
260
|
+
* Holders that cannot be positively identified as a zeta stats dashboard, or
|
|
261
|
+
* that refuse to stop, are left running and yield `"fallback"`.
|
|
262
|
+
*/
|
|
263
|
+
async function reclaimStatsPort(port: number, probe: "replaceable" | "occupied"): Promise<StatsPortClaim> {
|
|
240
264
|
const holder = await findPortHolder(port);
|
|
241
|
-
if (!holder) {
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
if (holder.pid === process.pid) {
|
|
245
|
-
throw new Error(`Port ${port} is held by the current process (${holder.image}, PID ${holder.pid}).`);
|
|
265
|
+
if (!holder || holder.pid === process.pid) {
|
|
266
|
+
logger.debug("Stats dashboard port holder not reclaimable", { port, holder });
|
|
267
|
+
return "fallback";
|
|
246
268
|
}
|
|
247
269
|
|
|
248
270
|
const normalizedImage = holder.image
|
|
@@ -258,33 +280,48 @@ async function reclaimStatsPort(port: number, hasDashboardIdentity = false): Pro
|
|
|
258
280
|
((normalizedImage === "zetacode" || normalizedImage === "omp") &&
|
|
259
281
|
/(?:^|\s)stats(?:\s|$)/.test(normalizedCommand)) ||
|
|
260
282
|
/(?:^|\/)(?:zetacode|omp)(?:\.exe)?["'\s]+stats(?:["'\s]|$)/.test(normalizedCommand);
|
|
283
|
+
const hasDashboardIdentity = probe === "replaceable";
|
|
261
284
|
if (!STATS_RUNTIME_IMAGES[normalizedImage] || (!hasStatsIdentity && !hasDashboardIdentity)) {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
);
|
|
285
|
+
logger.debug("Stats dashboard port held by an unidentified process", { port, holder });
|
|
286
|
+
return "fallback";
|
|
265
287
|
}
|
|
266
288
|
|
|
267
|
-
|
|
268
|
-
|
|
289
|
+
try {
|
|
290
|
+
await terminatePortHolder(holder);
|
|
291
|
+
} catch (error) {
|
|
292
|
+
logger.warn("Failed to stop stale stats dashboard", { port, pid: holder.pid, error: String(error) });
|
|
293
|
+
return "fallback";
|
|
294
|
+
}
|
|
295
|
+
return "bind";
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async function claimStatsPort(port: number, hostname: string, ifUnreachable: StatsPortClaim): Promise<StatsPortClaim> {
|
|
299
|
+
const probe = await probeStatsDashboard(port, hostname);
|
|
300
|
+
switch (probe) {
|
|
301
|
+
case "reusable":
|
|
302
|
+
return "reuse";
|
|
303
|
+
case "replaceable":
|
|
304
|
+
case "occupied":
|
|
305
|
+
return reclaimStatsPort(port, probe);
|
|
306
|
+
case "unresponsive":
|
|
307
|
+
// Busy or hung: a dashboard stalled mid-ingest must never be stopped.
|
|
308
|
+
return "fallback";
|
|
309
|
+
case "unreachable":
|
|
310
|
+
return ifUnreachable;
|
|
311
|
+
}
|
|
269
312
|
}
|
|
270
313
|
|
|
271
314
|
/**
|
|
272
|
-
* Reuse a
|
|
315
|
+
* Reuse a current dashboard, or upgrade an older one, before binding.
|
|
273
316
|
* The preflight is needed on platforms that permit wildcard and loopback-specific
|
|
274
317
|
* listeners to coexist on one port.
|
|
275
318
|
*/
|
|
276
|
-
export async function prepareStatsPort(port: number, hostname = STATS_DASHBOARD_HOSTNAME): Promise<
|
|
277
|
-
if (port === 0) return "
|
|
278
|
-
|
|
279
|
-
if (probe === "reusable") return "reuse";
|
|
280
|
-
if (probe === "replaceable") return reclaimStatsPort(port, true);
|
|
281
|
-
if (probe === "occupied") return reclaimStatsPort(port);
|
|
282
|
-
return "retry";
|
|
319
|
+
export async function prepareStatsPort(port: number, hostname = STATS_DASHBOARD_HOSTNAME): Promise<StatsPortClaim> {
|
|
320
|
+
if (port === 0) return "bind";
|
|
321
|
+
return claimStatsPort(port, hostname, "bind");
|
|
283
322
|
}
|
|
284
323
|
|
|
285
324
|
/** Reuse or reclaim a listener found after the server bind reports EADDRINUSE. */
|
|
286
|
-
export async function recoverStatsPort(port: number, hostname = STATS_DASHBOARD_HOSTNAME): Promise<
|
|
287
|
-
|
|
288
|
-
if (probe === "reusable") return "reuse";
|
|
289
|
-
return reclaimStatsPort(port, probe === "replaceable");
|
|
325
|
+
export async function recoverStatsPort(port: number, hostname = STATS_DASHBOARD_HOSTNAME): Promise<StatsPortClaim> {
|
|
326
|
+
return claimStatsPort(port, hostname, "fallback");
|
|
290
327
|
}
|
package/src/server.ts
CHANGED
|
@@ -167,6 +167,19 @@ const ensureClientBuild = async () => {
|
|
|
167
167
|
*/
|
|
168
168
|
const STATS_ACTION_HEADER = "X-Zeta-Stats-Action";
|
|
169
169
|
|
|
170
|
+
/** What the page's Close calls; unset, the page offers none. */
|
|
171
|
+
let closeHandler: (() => void) | undefined;
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Let the page close the dashboard: while `close` is set, it shows a Close
|
|
175
|
+
* button (and takes Esc and Ctrl+C) that calls it. `zetacode stats` sets it while
|
|
176
|
+
* Tern shows the page in place of the block it runs in, where the page has no
|
|
177
|
+
* way out of its own; `undefined` takes Close away again.
|
|
178
|
+
*/
|
|
179
|
+
export function setStatsCloseHandler(close: (() => void) | undefined): void {
|
|
180
|
+
closeHandler = close;
|
|
181
|
+
}
|
|
182
|
+
|
|
170
183
|
/**
|
|
171
184
|
* Handle API requests.
|
|
172
185
|
*/
|
|
@@ -272,6 +285,17 @@ export async function handleApi(req: Request): Promise<Response> {
|
|
|
272
285
|
return Response.json(details);
|
|
273
286
|
}
|
|
274
287
|
|
|
288
|
+
if (path === "/api/close") {
|
|
289
|
+
if (req.method === "GET") return Response.json({ closable: closeHandler !== undefined });
|
|
290
|
+
if (req.method !== "POST") return Response.json({ error: "GET or POST required" }, { status: 405 });
|
|
291
|
+
if (req.headers.get(STATS_ACTION_HEADER) !== "1") {
|
|
292
|
+
return Response.json({ error: `${STATS_ACTION_HEADER}: 1 header required` }, { status: 403 });
|
|
293
|
+
}
|
|
294
|
+
if (!closeHandler) return Response.json({ error: "this dashboard is not closed from its page" }, { status: 404 });
|
|
295
|
+
closeHandler();
|
|
296
|
+
return new Response(null, { status: 202 });
|
|
297
|
+
}
|
|
298
|
+
|
|
275
299
|
if (path === "/api/sync") {
|
|
276
300
|
if (req.method !== "POST") return Response.json({ error: "POST required" }, { status: 405 });
|
|
277
301
|
statsLive().requestSync();
|
|
@@ -493,19 +517,18 @@ function liveEventStream(headers: Record<string, string>, signal: AbortSignal):
|
|
|
493
517
|
});
|
|
494
518
|
}
|
|
495
519
|
|
|
496
|
-
/**
|
|
497
|
-
* Start the HTTP server, reusing a live dashboard or reclaiming a stale omp listener.
|
|
498
|
-
*/
|
|
520
|
+
/** A dashboard this process started or found; `port` is where it listens, which may differ from the one requested. */
|
|
499
521
|
export interface StatsServerHandle {
|
|
500
522
|
hostname: string;
|
|
501
523
|
port: number;
|
|
502
524
|
stop: () => void;
|
|
503
525
|
}
|
|
504
526
|
|
|
505
|
-
// Dashboards this process already bound, keyed by requested
|
|
506
|
-
// A second in-process start (e.g. `/trace` twice in one
|
|
507
|
-
//
|
|
508
|
-
//
|
|
527
|
+
// Dashboards this process already bound, keyed by requested and bound
|
|
528
|
+
// `hostname:port`. A second in-process start (e.g. `/trace` twice in one
|
|
529
|
+
// session, or a caller passing back a fallback port) must return the live
|
|
530
|
+
// handle: probing our own port can time out under load and would then start
|
|
531
|
+
// yet another dashboard on a fallback port.
|
|
509
532
|
const activeServers = new Map<string, StatsServerHandle>();
|
|
510
533
|
/** Dashboards bound by this process (any port); background ingest stops when the last one does. */
|
|
511
534
|
let liveServers = 0;
|
|
@@ -521,6 +544,12 @@ export interface StartServerOptions {
|
|
|
521
544
|
language?: string;
|
|
522
545
|
}
|
|
523
546
|
|
|
547
|
+
/**
|
|
548
|
+
* Start the dashboard on `port`, or reuse the current dashboard already serving it.
|
|
549
|
+
* An older dashboard there is stopped and replaced; any other holder (a foreign
|
|
550
|
+
* program, or a dashboard too busy to answer the identity probe) is left running
|
|
551
|
+
* and the dashboard binds an ephemeral port instead.
|
|
552
|
+
*/
|
|
524
553
|
export async function startServer(
|
|
525
554
|
port = ZETA_STATS_PORT,
|
|
526
555
|
hostname = STATS_DASHBOARD_HOSTNAME,
|
|
@@ -528,24 +557,22 @@ export async function startServer(
|
|
|
528
557
|
): Promise<StatsServerHandle> {
|
|
529
558
|
if (options.judge) setStatsJudgeProvider(options.judge);
|
|
530
559
|
dashboardLocale = resolveLocaleTag(options.language);
|
|
531
|
-
const
|
|
560
|
+
const requestedKey = `${hostname}:${port}`;
|
|
532
561
|
if (port !== 0) {
|
|
533
|
-
const active = activeServers.get(
|
|
562
|
+
const active = activeServers.get(requestedKey);
|
|
534
563
|
if (active) return active;
|
|
535
564
|
}
|
|
536
565
|
await ensureClientBuild();
|
|
537
|
-
const preparation = await prepareStatsPort(port, hostname);
|
|
538
|
-
if (preparation === "reuse") {
|
|
539
|
-
return { hostname, port, stop: () => {} };
|
|
540
|
-
}
|
|
541
566
|
const register = (server: Server<undefined>): StatsServerHandle => {
|
|
542
567
|
liveServers++;
|
|
543
568
|
let stopped = false;
|
|
569
|
+
const boundPort = server.port ?? port;
|
|
570
|
+
const keys = port === 0 ? [`${hostname}:${boundPort}`] : [requestedKey, `${hostname}:${boundPort}`];
|
|
544
571
|
const handle: StatsServerHandle = {
|
|
545
572
|
hostname,
|
|
546
|
-
port:
|
|
573
|
+
port: boundPort,
|
|
547
574
|
stop: () => {
|
|
548
|
-
activeServers.delete(
|
|
575
|
+
for (const key of keys) activeServers.delete(key);
|
|
549
576
|
server.stop(true);
|
|
550
577
|
if (stopped) return;
|
|
551
578
|
stopped = true;
|
|
@@ -553,26 +580,31 @@ export async function startServer(
|
|
|
553
580
|
if (--liveServers === 0) statsLive().stop();
|
|
554
581
|
},
|
|
555
582
|
};
|
|
556
|
-
|
|
583
|
+
for (const key of keys) activeServers.set(key, handle);
|
|
557
584
|
return handle;
|
|
558
585
|
};
|
|
559
586
|
|
|
587
|
+
let claim = await prepareStatsPort(port, hostname);
|
|
588
|
+
if (claim === "bind") {
|
|
589
|
+
const server = bindDashboardServer(port, hostname);
|
|
590
|
+
if (server) return register(server);
|
|
591
|
+
claim = await recoverStatsPort(port, hostname);
|
|
592
|
+
}
|
|
593
|
+
if (claim === "reuse") return { hostname, port, stop: () => {} };
|
|
594
|
+
if (claim === "bind") {
|
|
595
|
+
const server = bindDashboardServer(port, hostname);
|
|
596
|
+
if (server) return register(server);
|
|
597
|
+
}
|
|
598
|
+
logger.warn("Stats dashboard port is held by another process; serving on an ephemeral port", { hostname, port });
|
|
599
|
+
return register(createDashboardServer(0, hostname));
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/** {@link createDashboardServer}, or null when the port is already in use. */
|
|
603
|
+
function bindDashboardServer(port: number, hostname: string): Server<undefined> | null {
|
|
560
604
|
try {
|
|
561
|
-
return
|
|
605
|
+
return createDashboardServer(port, hostname);
|
|
562
606
|
} catch (error) {
|
|
563
|
-
if (
|
|
564
|
-
|
|
565
|
-
const recovery = await recoverStatsPort(port, hostname);
|
|
566
|
-
if (recovery === "reuse") {
|
|
567
|
-
return { hostname, port, stop: () => {} };
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
try {
|
|
571
|
-
return register(createDashboardServer(port, hostname));
|
|
572
|
-
} catch (retryError) {
|
|
573
|
-
throw new Error(`Failed to start stats dashboard on ${hostname}:${port} after reclaiming it.`, {
|
|
574
|
-
cause: retryError,
|
|
575
|
-
});
|
|
576
|
-
}
|
|
607
|
+
if (error instanceof Error && "code" in error && error.code === "EADDRINUSE") return null;
|
|
608
|
+
throw error;
|
|
577
609
|
}
|
|
578
610
|
}
|
package/src/shared-types.ts
CHANGED
|
@@ -704,7 +704,7 @@ export interface TraceTrack {
|
|
|
704
704
|
agent: string | null;
|
|
705
705
|
/** session_init.resolvedModel ?? first assistant model. */
|
|
706
706
|
model: string | null;
|
|
707
|
-
/** Absolute transcript path
|
|
707
|
+
/** Absolute transcript path for live entry fetch, or the embedded snapshot key. */
|
|
708
708
|
file: string;
|
|
709
709
|
/** Sorted by start. */
|
|
710
710
|
spans: TraceSpan[];
|
|
@@ -748,12 +748,13 @@ export interface SessionTrace {
|
|
|
748
748
|
cwd: string | null;
|
|
749
749
|
startedAt: number;
|
|
750
750
|
endedAt: number;
|
|
751
|
-
/** Root transcript mtime
|
|
751
|
+
/** Root transcript mtime, or recorded root activity/header time for offline snapshots. */
|
|
752
752
|
mtimeMs: number;
|
|
753
753
|
/**
|
|
754
754
|
* Conditional-request fingerprint `"<rootMs>:<childHighMs>"` (see
|
|
755
755
|
* traceFingerprintForEtag): the server ETag is built from this, so a
|
|
756
756
|
* subagent-only append changes the ETag even when the root is untouched.
|
|
757
|
+
* Offline snapshots use "snapshot" and do not support HTTP revalidation.
|
|
757
758
|
*/
|
|
758
759
|
etag: string;
|
|
759
760
|
/** DFS order, main first. */
|
package/src/trace.ts
CHANGED
|
@@ -35,7 +35,7 @@ export class TracePathError extends Error {}
|
|
|
35
35
|
* span assembly changes so browsers don't revalidate stale cached bodies
|
|
36
36
|
* against an unchanged transcript mtime.
|
|
37
37
|
*/
|
|
38
|
-
export const TRACE_ETAG_VERSION =
|
|
38
|
+
export const TRACE_ETAG_VERSION = 4;
|
|
39
39
|
|
|
40
40
|
const MAX_TRACK_DEPTH = 6;
|
|
41
41
|
const LABEL_MAX = 80;
|
|
@@ -230,7 +230,7 @@ function unionLength(intervals: Array<[number, number]>): number {
|
|
|
230
230
|
// Single-transcript scan
|
|
231
231
|
|
|
232
232
|
/** Keep only the active branch: the parentId chain walked back from the last entry. */
|
|
233
|
-
function activeChain(views: EntryView[]): EntryView[] {
|
|
233
|
+
function activeChain(views: readonly EntryView[]): EntryView[] {
|
|
234
234
|
const byId = new Map<string, EntryView>();
|
|
235
235
|
let last: EntryView | undefined;
|
|
236
236
|
for (const entry of views) {
|
|
@@ -278,13 +278,14 @@ function argsPreview(args: unknown): string | undefined {
|
|
|
278
278
|
* markers, and the cross-track facts (task results, request counts).
|
|
279
279
|
*/
|
|
280
280
|
function scanTranscript(
|
|
281
|
-
entries: SessionEntry[],
|
|
281
|
+
entries: readonly SessionEntry[],
|
|
282
282
|
trackId: string,
|
|
283
283
|
parentTrackId: string | null,
|
|
284
284
|
file: string,
|
|
285
|
+
header?: TraceSnapshotHeader | null,
|
|
285
286
|
): TrackScan {
|
|
286
287
|
// Boundary cast: persisted JSONL entries are re-validated field-by-field below.
|
|
287
|
-
const views = entries as EntryView[];
|
|
288
|
+
const views = entries as readonly EntryView[];
|
|
288
289
|
const chain = activeChain(views);
|
|
289
290
|
const spans: TraceSpan[] = [];
|
|
290
291
|
const markers: TraceMarker[] = [];
|
|
@@ -297,9 +298,9 @@ function scanTranscript(
|
|
|
297
298
|
const taskResults: TaskResultFact[] = [];
|
|
298
299
|
|
|
299
300
|
let sessionExit: { recordedAt: number; pendingIds: Set<string> } | undefined;
|
|
300
|
-
let cwd
|
|
301
|
-
let headerTitle
|
|
302
|
-
let headerTs
|
|
301
|
+
let cwd = typeof header?.cwd === "string" ? header.cwd : null;
|
|
302
|
+
let headerTitle = typeof header?.title === "string" ? header.title : null;
|
|
303
|
+
let headerTs = toMs(header?.timestamp);
|
|
303
304
|
let slotTitle: string | null = null;
|
|
304
305
|
let initAgent: string | null = null;
|
|
305
306
|
let initModel: string | null = null;
|
|
@@ -689,7 +690,7 @@ async function buildTrackTree(
|
|
|
689
690
|
const childTrackId = trackId === "main" ? stem : `${trackId}/${stem}`;
|
|
690
691
|
const childScan = await buildTrackTree(childFile, childTrackId, trackId, depth + 1, visited, out, scans);
|
|
691
692
|
if (!childScan) continue;
|
|
692
|
-
const isAdvisor =
|
|
693
|
+
const isAdvisor = stem === "__advisor" || stem.startsWith("__advisor.");
|
|
693
694
|
childScan.track.label = isAdvisor
|
|
694
695
|
? "Advisor"
|
|
695
696
|
: headText(`${childScan.track.agent ?? "agent"} ${stem}`, LABEL_MAX);
|
|
@@ -697,6 +698,13 @@ async function buildTrackTree(
|
|
|
697
698
|
}
|
|
698
699
|
}
|
|
699
700
|
|
|
701
|
+
linkChildTracks(scan, childrenById);
|
|
702
|
+
return scan;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/** Place child activity and structured task-result spans on their parent track. */
|
|
706
|
+
function linkChildTracks(scan: TrackScan, childrenById: ReadonlyMap<string, TrackScan>): void {
|
|
707
|
+
const trackId = scan.track.id;
|
|
700
708
|
// Subagent spans on this track, one per task SingleResult.
|
|
701
709
|
const linkedChildren = new Set<string>();
|
|
702
710
|
for (const result of scan.taskResults) {
|
|
@@ -746,8 +754,6 @@ async function buildTrackTree(
|
|
|
746
754
|
scan.track.spans.push(span);
|
|
747
755
|
}
|
|
748
756
|
scan.track.spans.sort((a, b) => a.start - b.start || a.end - b.end);
|
|
749
|
-
|
|
750
|
-
return scan;
|
|
751
757
|
}
|
|
752
758
|
|
|
753
759
|
// ---------------------------------------------------------------------------
|
|
@@ -863,6 +869,106 @@ export async function buildSessionTrace(fileParam: string, fingerprint?: TraceFi
|
|
|
863
869
|
if (!rootScan) {
|
|
864
870
|
throw Object.assign(new Error(`ENOENT: session not found: ${resolved}`), { code: "ENOENT" });
|
|
865
871
|
}
|
|
872
|
+
// Re-collect the fingerprint AFTER the parse: a child append landing
|
|
873
|
+
// between the pre-build check and now would otherwise be baked into
|
|
874
|
+
// neither the trace nor the key.
|
|
875
|
+
const childFingerprint = await childTranscriptsFingerprint(resolved);
|
|
876
|
+
// Root rewritten mid-build: same no-cache rule as the child race below.
|
|
877
|
+
const rootChanged = (await fs.stat(resolved).catch(() => null))?.mtimeMs !== rootMtimeMs;
|
|
878
|
+
const raced = childFingerprint !== preChildFingerprint;
|
|
879
|
+
// Raced builds keep the PRE-build fingerprint as their ETag: the parsed
|
|
880
|
+
// bytes predate the racy write, so claiming the post-write state would
|
|
881
|
+
// 304 stale forever when that write was the child's last. The pre-build
|
|
882
|
+
// key guarantees the next conditional poll misses (filesystem moved on)
|
|
883
|
+
// and rebuilds — at most one stale response per race, never an
|
|
884
|
+
// indefinitely cached one. Unraced builds use the post-build key, which
|
|
885
|
+
// equals the pre-build key by construction.
|
|
886
|
+
const etagFingerprint = raced || rootChanged ? preChildFingerprint : childFingerprint;
|
|
887
|
+
const trace = assembleSessionTrace(rootScan, tracks, scans, rootMtimeMs, `${rootMtimeMs}:${etagFingerprint}`);
|
|
888
|
+
if (!raced && !rootChanged) {
|
|
889
|
+
traceMemo = {
|
|
890
|
+
file: resolved,
|
|
891
|
+
entry: { mtimeMs: rootMtimeMs, childFingerprint, trace },
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
return trace;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
/** Header metadata used by snapshot traces, including journals without a schema version. */
|
|
898
|
+
export interface TraceSnapshotHeader {
|
|
899
|
+
timestamp?: string;
|
|
900
|
+
cwd?: string;
|
|
901
|
+
title?: string;
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
/** The journal data for one embedded transcript; its header may be stored separately. */
|
|
905
|
+
export interface SessionTraceSnapshot {
|
|
906
|
+
header?: TraceSnapshotHeader | null;
|
|
907
|
+
entries: readonly SessionEntry[];
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
/** A collected child transcript, keyed by its slash-joined path from the root. */
|
|
911
|
+
export interface SubSessionTraceSnapshot extends SessionTraceSnapshot {
|
|
912
|
+
parent: string | null;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/**
|
|
916
|
+
* Assemble an offline trace using the same timing joins and rollups as the live
|
|
917
|
+
* filesystem builder. Only supplied snapshots participate: no filesystem, DB,
|
|
918
|
+
* network, or wall-clock reads. Track files are snapshot keys, never disk paths.
|
|
919
|
+
*
|
|
920
|
+
* Missing parent transcripts attach their readable descendants to main. Unlike
|
|
921
|
+
* filesystem discovery, already-collected snapshots need no depth limit.
|
|
922
|
+
* `mtimeMs` is the root's last activity (or header time, then 0); the constant
|
|
923
|
+
* `etag` identifies a snapshot, not a conditional HTTP response.
|
|
924
|
+
*/
|
|
925
|
+
export function buildSessionTraceFromSnapshots(
|
|
926
|
+
root: SessionTraceSnapshot,
|
|
927
|
+
subSessions?: Readonly<Record<string, SubSessionTraceSnapshot>>,
|
|
928
|
+
): SessionTrace {
|
|
929
|
+
const children = new Map<string | null, Array<[string, SubSessionTraceSnapshot]>>();
|
|
930
|
+
if (subSessions) {
|
|
931
|
+
for (const key of Object.keys(subSessions).sort()) {
|
|
932
|
+
const snapshot = subSessions[key];
|
|
933
|
+
const parent =
|
|
934
|
+
snapshot.parent !== null && Object.hasOwn(subSessions, snapshot.parent) ? snapshot.parent : null;
|
|
935
|
+
const siblings = children.get(parent);
|
|
936
|
+
if (siblings) siblings.push([key, snapshot]);
|
|
937
|
+
else children.set(parent, [[key, snapshot]]);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
const tracks: TraceTrack[] = [];
|
|
942
|
+
const scans: TrackScan[] = [];
|
|
943
|
+
const visit = (snapshot: SessionTraceSnapshot, key: string, parentId: string | null): TrackScan => {
|
|
944
|
+
const scan = scanTranscript(snapshot.entries, key, parentId, key, snapshot.header);
|
|
945
|
+
tracks.push(scan.track);
|
|
946
|
+
scans.push(scan);
|
|
947
|
+
const childrenById = new Map<string, TrackScan>();
|
|
948
|
+
for (const [childKey, childSnapshot] of children.get(parentId === null ? null : key) ?? []) {
|
|
949
|
+
const child = visit(childSnapshot, childKey, key);
|
|
950
|
+
const stem = childKey.slice(childKey.lastIndexOf("/") + 1);
|
|
951
|
+
child.track.label =
|
|
952
|
+
stem === "__advisor" || stem.startsWith("__advisor.")
|
|
953
|
+
? "Advisor"
|
|
954
|
+
: headText(`${child.track.agent ?? "agent"} ${stem}`, LABEL_MAX);
|
|
955
|
+
childrenById.set(stem, child);
|
|
956
|
+
}
|
|
957
|
+
linkChildTracks(scan, childrenById);
|
|
958
|
+
return scan;
|
|
959
|
+
};
|
|
960
|
+
const rootScan = visit(root, "main", null);
|
|
961
|
+
return assembleSessionTrace(rootScan, tracks, scans, rootScan.lastActivity ?? rootScan.headerTs ?? 0, "snapshot");
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
/** Shared aggregation after either filesystem discovery or snapshot traversal. */
|
|
965
|
+
function assembleSessionTrace(
|
|
966
|
+
rootScan: TrackScan,
|
|
967
|
+
tracks: TraceTrack[],
|
|
968
|
+
scans: TrackScan[],
|
|
969
|
+
rootMtimeMs: number,
|
|
970
|
+
etag: string,
|
|
971
|
+
): SessionTrace {
|
|
866
972
|
rootScan.track.label = "Main";
|
|
867
973
|
|
|
868
974
|
let startedAt: number | undefined;
|
|
@@ -935,39 +1041,17 @@ export async function buildSessionTrace(fileParam: string, fingerprint?: TraceFi
|
|
|
935
1041
|
toolStats: [...toolStats.values()].sort((a, b) => b.totalMs - a.totalMs),
|
|
936
1042
|
};
|
|
937
1043
|
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
// neither the trace nor the key.
|
|
941
|
-
const childFingerprint = await childTranscriptsFingerprint(resolved);
|
|
942
|
-
// Root rewritten mid-build: same no-cache rule as the child race below.
|
|
943
|
-
const rootChanged = (await fs.stat(resolved).catch(() => null))?.mtimeMs !== rootMtimeMs;
|
|
944
|
-
const raced = childFingerprint !== preChildFingerprint;
|
|
945
|
-
// Raced builds keep the PRE-build fingerprint as their ETag: the parsed
|
|
946
|
-
// bytes predate the racy write, so claiming the post-write state would
|
|
947
|
-
// 304 stale forever when that write was the child's last. The pre-build
|
|
948
|
-
// key guarantees the next conditional poll misses (filesystem moved on)
|
|
949
|
-
// and rebuilds — at most one stale response per race, never an
|
|
950
|
-
// indefinitely cached one. Unraced builds use the post-build key, which
|
|
951
|
-
// equals the pre-build key by construction.
|
|
952
|
-
const etagFingerprint = raced || rootChanged ? preChildFingerprint : childFingerprint;
|
|
953
|
-
const trace: SessionTrace = {
|
|
954
|
-
file: resolved,
|
|
1044
|
+
return {
|
|
1045
|
+
file: rootScan.track.file,
|
|
955
1046
|
title: rootScan.title,
|
|
956
1047
|
cwd: rootScan.cwd,
|
|
957
1048
|
startedAt: start,
|
|
958
1049
|
endedAt: end,
|
|
959
1050
|
mtimeMs: rootMtimeMs,
|
|
960
|
-
etag
|
|
1051
|
+
etag,
|
|
961
1052
|
tracks,
|
|
962
1053
|
summary,
|
|
963
1054
|
};
|
|
964
|
-
if (!raced && !rootChanged) {
|
|
965
|
-
traceMemo = {
|
|
966
|
-
file: resolved,
|
|
967
|
-
entry: { mtimeMs: rootMtimeMs, childFingerprint, trace },
|
|
968
|
-
};
|
|
969
|
-
}
|
|
970
|
-
return trace;
|
|
971
1055
|
}
|
|
972
1056
|
|
|
973
1057
|
/** Fetch one full journal entry by id from a transcript, for the span drawer. */
|
package/src/types.ts
CHANGED
|
@@ -282,12 +282,17 @@ export interface ToolCallStats {
|
|
|
282
282
|
callsInTurn: number;
|
|
283
283
|
/** Serialized argument characters */
|
|
284
284
|
argsChars: number;
|
|
285
|
+
/** Result text characters, when the same parse also read the call's `toolResult` */
|
|
286
|
+
resultChars?: number;
|
|
287
|
+
/** Result error flag, set together with `resultChars` */
|
|
288
|
+
isError?: boolean;
|
|
285
289
|
}
|
|
286
290
|
|
|
287
291
|
/**
|
|
288
292
|
* Result linkage emitted when the parser sees a `toolResult` message entry.
|
|
289
293
|
* Applied as an UPDATE on the persisted tool-call row — results can land in a
|
|
290
|
-
* later incremental sync pass than the call that produced them
|
|
294
|
+
* later incremental sync pass than the call that produced them (calls parsed
|
|
295
|
+
* in the same pass already carry the result, so their UPDATE is a no-op).
|
|
291
296
|
*/
|
|
292
297
|
export interface ToolResultLink {
|
|
293
298
|
sessionFile: string;
|