scorpiox-bot-plugin-sessionstats
←plugin_sessionstats.cc
1278 lines · 48 KBHEADBlameDownload
1/*
2 * plugin_sessionstats - SCORPIOX BOT open-source session runtime & turn analytics
3 *
4 * A single clean-room C99 binary that serves THREE modes:
5 * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata
6 * 2. ?action=summary | ?action=session&sid=... | ?format=json -> JSON node API
7 * 3. GET (default) -> responsive HTML analytics UI
8 *
9 * Everything it reads is LOCAL to the node and read-only: the per-session
10 * directories under the ScorpioX sessions root (meta.json, stats.json,
11 * events.jsonl, and the optional "thinking" marker). Nothing is ever written,
12 * renamed or deleted. There is no parameter anywhere in this file that can
13 * point it at another host or another path outside the sessions root.
14 *
15 * Every timestamp in the session files is local wall-clock text
16 * ("YYYY-MM-DD HH:MM:SS"). Only differences between timestamps are used, so a
17 * single deterministic civil-days conversion is sufficient and no timezone
18 * database is required.
19 *
20 * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and
21 * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under
22 * scorpiox-server on the node.
23 *
24 * MIT License. Copyright (c) 2026 SCORPIOX INC.
25 */
26
27#if defined(_WIN32) && !defined(_WIN32_WINNT)
28# define _WIN32_WINNT 0x0601
29#endif
30
31#if !defined(_WIN32)
32# define _POSIX_C_SOURCE 200809L
33# define _DEFAULT_SOURCE 1
34# if defined(__APPLE__)
35# define _DARWIN_C_SOURCE 1
36# endif
37#endif
38
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#include <ctype.h>
43#include <time.h>
44#include <errno.h>
45
46#if defined(_WIN32)
47# define WIN32_LEAN_AND_MEAN
48# include <windows.h>
49# include <direct.h>
50# define SX_PATHSEP '\\'
51#else
52# include <unistd.h>
53# include <dirent.h>
54# include <sys/stat.h>
55# include <sys/types.h>
56# define SX_PATHSEP '/'
57#endif
58
59#include "bot_theme_plugin.h"
60
61#define PLUGIN_SLUG "sessionstats"
62#define PLUGIN_ID "plugin_sessionstats"
63#define PLUGIN_VER "1.0.1"
64
65#define NAME_SZ 128
66#define MAX_SESSIONS 256
67#define MAX_TOOLS 48
68#define MAX_ROOTS 4
69#define LINE_SZ 4096
70#define FILE_SZ 16384
71#define PATH_SZ 1024
72
73/* ------------------------------------------------------------------ */
74/* Small string helpers */
75/* ------------------------------------------------------------------ */
76
77static void str_copy(char *dst, size_t sz, const char *src)
78{
79 size_t i = 0;
80 if (!dst || sz == 0) return;
81 if (!src) { dst[0] = '\0'; return; }
82 while (i + 1 < sz && src[i]) { dst[i] = src[i]; i++; }
83 dst[i] = '\0';
84}
85
86static void url_decode(char *s)
87{
88 char *o = s;
89 if (!s) return;
90 while (*s) {
91 if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
92 int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
93 int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
94 *o++ = (char)((hi << 4) | lo);
95 s += 3;
96 } else if (*s == '+') {
97 *o++ = ' ';
98 s++;
99 } else {
100 *o++ = *s++;
101 }
102 }
103 *o = '\0';
104}
105
106/* Read one query parameter, percent-decoded. Returns 1 when present. */
107static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
108{
109 size_t klen;
110 const char *p;
111
112 if (!out || outsz == 0) return 0;
113 out[0] = '\0';
114 if (!qs || !key) return 0;
115 klen = strlen(key);
116
117 for (p = qs; *p; ) {
118 if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
119 const char *v = p + klen + 1;
120 size_t i = 0;
121 while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++;
122 out[i] = '\0';
123 url_decode(out);
124 return 1;
125 }
126 p = strchr(p, '&');
127 if (!p) break;
128 p++;
129 }
130 return 0;
131}
132
133static void json_str(const char *s)
134{
135 fputc('"', stdout);
136 for (; s && *s; s++) {
137 unsigned char c = (unsigned char)*s;
138 if (c == '"' || c == '\\') { fputc('\\', stdout); fputc((char)c, stdout); }
139 else if (c == '\n') fputs("\\n", stdout);
140 else if (c == '\r') fputs("\\r", stdout);
141 else if (c == '\t') fputs("\\t", stdout);
142 else if (c >= 0x20 && c != 0x7f) fputc((char)c, stdout);
143 }
144 fputc('"', stdout);
145}
146
147/* ------------------------------------------------------------------ */
148/* Node security */
149/* ------------------------------------------------------------------ */
150
151static void require_node_auth(void)
152{
153 const char *np = getenv("BOT_PASSWORD");
154 const char *xp, *auth;
155 char qpwd[128] = {0};
156
157 if (!np || !*np) return;
158
159 xp = getenv("HTTP_X_BOT_PASSWORD");
160 if (xp && strcmp(xp, np) == 0) return;
161
162 auth = getenv("HTTP_AUTHORIZATION");
163 if (auth) {
164 while (*auth == ' ') auth++;
165 if (strncasecmp(auth, "Bearer ", 7) == 0) {
166 auth += 7;
167 while (*auth == ' ') auth++;
168 if (strcmp(auth, np) == 0) return;
169 }
170 }
171
172 if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof qpwd)
173 && strcmp(qpwd, np) == 0) return;
174
175 fputs("Status: 401 Unauthorized\r\n"
176 "Content-Type: application/json; charset=utf-8\r\n\r\n"
177 "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
178 exit(0);
179}
180
181/* ------------------------------------------------------------------ */
182/* Time helpers */
183/* ------------------------------------------------------------------ */
184
185/* Days since 1970-01-01 for a proleptic Gregorian civil date. */
186static long long days_from_civil(int y, int m, int d)
187{
188 long long era, yoe, doy, doe;
189 y -= (m <= 2);
190 era = (y >= 0 ? y : y - 399) / 400;
191 yoe = (long long)(y - era * 400);
192 doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
193 doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
194 return era * 146097 + doe - 719468;
195}
196
197/* Parse "YYYY-MM-DD HH:MM:SS". Returns 0 when unparseable. */
198static long long parse_ts(const char *ts)
199{
200 int Y, M, D, h, mi, s;
201 if (!ts || strlen(ts) < 19) return 0;
202 if (sscanf(ts, "%d-%d-%d %d:%d:%d", &Y, &M, &D, &h, &mi, &s) != 6) return 0;
203 if (M < 1 || M > 12 || D < 1 || D > 31) return 0;
204 return days_from_civil(Y, M, D) * 86400LL + h * 3600LL + mi * 60LL + s;
205}
206
207static void format_duration(long long sec, char *out, size_t outsz)
208{
209 long long d, h, m, s;
210 if (sec < 0) sec = 0;
211 d = sec / 86400;
212 sec %= 86400;
213 h = sec / 3600;
214 sec %= 3600;
215 m = sec / 60;
216 s = sec % 60;
217 if (d > 0) snprintf(out, outsz, "%lldd %02lldh %02lldm", d, h, m);
218 else if (h > 0) snprintf(out, outsz, "%02lldh %02lldm %02llds", h, m, s);
219 else if (m > 0) snprintf(out, outsz, "%02lldm %02llds", m, s);
220 else snprintf(out, outsz, "%llds", s);
221}
222
223/* ------------------------------------------------------------------ */
224/* File helpers */
225/* ------------------------------------------------------------------ */
226
227/* Read at most sz-1 bytes of a file into buf. Returns bytes read, -1 if absent. */
228static int read_file(const char *path, char *buf, size_t sz)
229{
230 FILE *f;
231 size_t n;
232 if (!buf || sz == 0) return -1;
233 buf[0] = '\0';
234 f = fopen(path, "rb");
235 if (!f) return -1;
236 n = fread(buf, 1, sz - 1, f);
237 buf[n] = '\0';
238 fclose(f);
239 return (int)n;
240}
241
242static int path_exists(const char *path)
243{
244 FILE *f = fopen(path, "rb");
245 if (f) { fclose(f); return 1; }
246 return 0;
247}
248
249/* Directory test, portable: fopen() on a directory succeeds on glibc, so a
250 * real stat-equivalent is needed to answer "is this a sessions root?". */
251static int sx_is_dir(const char *path)
252{
253#if defined(_WIN32)
254 DWORD a = GetFileAttributesA(path);
255 return (a != INVALID_FILE_ATTRIBUTES) && (a & FILE_ATTRIBUTE_DIRECTORY);
256#else
257 struct stat st;
258 return (stat(path, &st) == 0) && S_ISDIR(st.st_mode);
259#endif
260}
261
262/* Extract a JSON string value for an exact top-level key name. */
263static int json_get_str(const char *json, const char *key, char *out, size_t outsz)
264{
265 char needle[96];
266 const char *p;
267 size_t i = 0;
268
269 if (!json || !key || !out || outsz == 0) return 0;
270 out[0] = '\0';
271 if (strlen(key) + 3 >= sizeof needle) return 0;
272 snprintf(needle, sizeof needle, "\"%s\"", key);
273
274 p = strstr(json, needle);
275 if (!p) return 0;
276 p += strlen(needle);
277 while (*p && (*p == ' ' || *p == ':' || *p == '\t')) p++;
278 if (*p != '"') return 0;
279 p++;
280 while (*p && *p != '"' && i + 1 < outsz) {
281 if (*p == '\\' && p[1]) {
282 p++;
283 switch (*p) {
284 case 'n': out[i++] = '\n'; break;
285 case 't': out[i++] = '\t'; break;
286 case 'r': out[i++] = '\r'; break;
287 default: out[i++] = *p; break;
288 }
289 p++;
290 continue;
291 }
292 out[i++] = *p++;
293 }
294 out[i] = '\0';
295 return 1;
296}
297
298/* Extract a numeric JSON value for an exact key name. */
299static int json_get_num(const char *json, const char *key, double *out)
300{
301 char needle[96];
302 const char *p;
303 char *end = NULL;
304
305 if (!json || !key || !out) return 0;
306 if (strlen(key) + 3 >= sizeof needle) return 0;
307 snprintf(needle, sizeof needle, "\"%s\"", key);
308
309 p = strstr(json, needle);
310 if (!p) return 0;
311 p += strlen(needle);
312 while (*p && (*p == ' ' || *p == ':' || *p == '\t')) p++;
313 if (*p != '-' && !isdigit((unsigned char)*p)) return 0;
314 *out = strtod(p, &end);
315 return (end != p);
316}
317
318/* ------------------------------------------------------------------ */
319/* Directory listing (portable, directories only, dotfiles skipped) */
320/* ------------------------------------------------------------------ */
321
322#if defined(_WIN32)
323static int sx_list_dirs(const char *parent, char names[][NAME_SZ], int max)
324{
325 char pattern[PATH_SZ + 8];
326 WIN32_FIND_DATAA fd;
327 HANDLE h;
328 int n = 0;
329
330 snprintf(pattern, sizeof pattern, "%s/*", parent);
331 h = FindFirstFileA(pattern, &fd);
332 if (h == INVALID_HANDLE_VALUE) return 0;
333 do {
334 if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue;
335 if (fd.cFileName[0] == '.') continue;
336 if (n < max) str_copy(names[n++], NAME_SZ, fd.cFileName);
337 } while (FindNextFileA(h, &fd));
338 FindClose(h);
339 return n;
340}
341#else
342static int sx_list_dirs(const char *parent, char names[][NAME_SZ], int max)
343{
344 DIR *d;
345 struct dirent *de;
346 int n = 0;
347
348 d = opendir(parent);
349 if (!d) return 0;
350 while ((de = readdir(d)) != NULL) {
351 char full[PATH_SZ];
352 struct stat st;
353 if (de->d_name[0] == '.') continue;
354 snprintf(full, sizeof full, "%s/%s", parent, de->d_name);
355 if (stat(full, &st) != 0 || !S_ISDIR(st.st_mode)) continue;
356 if (n < max) str_copy(names[n++], NAME_SZ, de->d_name);
357 }
358 closedir(d);
359 return n;
360}
361#endif
362
363/* ------------------------------------------------------------------ */
364/* Sessions root discovery */
365/* ------------------------------------------------------------------ */
366
367/*
368 * Resolve the sessions root. SX_SESSIONS_DIR always wins, which is what makes
369 * the offline test suite possible and also what lets an operator point the
370 * plugin at a relocated state directory. Otherwise the standard per-node
371 * locations are tried in order.
372 */
373static int resolve_sessions_root(char *out, size_t outsz)
374{
375 const char *env = getenv("SX_SESSIONS_DIR");
376#if !defined(_WIN32)
377 const char *home;
378#endif
379 char cand[PATH_SZ];
380
381 if (env && *env) {
382 str_copy(out, outsz, env);
383 return sx_is_dir(env);
384 }
385
386#if defined(_WIN32)
387 const char *localappdata = getenv("LOCALAPPDATA");
388 const char *userprofile = getenv("USERPROFILE");
389 if (localappdata && *localappdata) {
390 snprintf(cand, sizeof cand, "%s\\scorpiox\\sessions", localappdata);
391 if (sx_is_dir(cand)) { str_copy(out, outsz, cand); return 1; }
392 }
393 if (userprofile && *userprofile) {
394 snprintf(cand, sizeof cand, "%s\\.scorpiox\\sessions", userprofile);
395 if (sx_is_dir(cand)) { str_copy(out, outsz, cand); return 1; }
396 }
397#else
398 home = getenv("HOME");
399 if (home && *home) {
400 snprintf(cand, sizeof cand, "%s/.scorpiox/sessions", home);
401 if (sx_is_dir(cand)) { str_copy(out, outsz, cand); return 1; }
402 }
403 if (sx_is_dir("/workspace/.scorpiox/sessions")) {
404 str_copy(out, outsz, "/workspace/.scorpiox/sessions");
405 return 1;
406 }
407#endif
408
409 /* Not found: report the most natural path so the UI can say what is missing. */
410#if defined(_WIN32)
411 if (localappdata && *localappdata)
412 snprintf(out, outsz, "%s\\scorpiox\\sessions", localappdata);
413 else
414 str_copy(out, outsz, "scorpiox\\sessions");
415#else
416 if (home && *home) snprintf(out, outsz, "%s/.scorpiox/sessions", home);
417 else str_copy(out, outsz, ".scorpiox/sessions");
418#endif
419 return 0;
420}
421
422/* ------------------------------------------------------------------ */
423/* One session */
424/* ------------------------------------------------------------------ */
425
426typedef struct {
427 char name[NAME_SZ];
428} tool_use_t;
429
430typedef struct {
431 char id[NAME_SZ]; /* directory name */
432 char session_id[NAME_SZ];
433 char start_time[40];
434 long long start_epoch; /* from meta.json when present */
435 long long first_ts; /* first event timestamp */
436 long long last_ts; /* last event timestamp */
437 long long total_sec;
438 long long active_sec;
439 long long idle_sec;
440 double duty_pct;
441 int turns;
442 int is_active;
443 char model[64];
444 char provider[64];
445 char profile[64];
446 char branch[128];
447 char cwd[512];
448 char thread_guid[64];
449 long long in_tokens;
450 long long out_tokens;
451 long long cache_read;
452 long long cache_write;
453 tool_use_t tools[MAX_TOOLS];
454 int tool_count;
455 int tool_hits[MAX_TOOLS];
456} session_t;
457
458/* Record (and count) one tool name for this session. */
459static void note_tool(session_t *s, const char *name)
460{
461 int i;
462 if (!name || !*name) return;
463 for (i = 0; i < s->tool_count; i++) {
464 if (strcmp(s->tools[i].name, name) == 0) { s->tool_hits[i]++; return; }
465 }
466 if (s->tool_count >= MAX_TOOLS) return;
467 str_copy(s->tools[s->tool_count].name, NAME_SZ, name);
468 s->tool_hits[s->tool_count] = 1;
469 s->tool_count++;
470}
471
472/*
473 * Parse one session directory. Read-only: opens meta.json, stats.json,
474 * events.jsonl and probes for the "thinking" marker. Any missing file simply
475 * contributes nothing.
476 */
477static int load_session(const char *root, const char *name, session_t *s)
478{
479 char path[PATH_SZ];
480 char buf[FILE_SZ];
481 double num;
482
483 memset(s, 0, sizeof *s);
484 str_copy(s->id, sizeof s->id, name);
485 str_copy(s->session_id, sizeof s->session_id, name);
486
487 /* Refuse a directory name that is not actually present: the caller uses
488 * this return value to answer "session not found". */
489 snprintf(path, sizeof path, "%s/%s", root, name);
490 if (!sx_is_dir(path)) return 0;
491
492 /* --- meta.json --- */
493 snprintf(path, sizeof path, "%s/%s/meta.json", root, name);
494 if (read_file(path, buf, sizeof buf) > 0) {
495 char tmp[NAME_SZ];
496 if (json_get_str(buf, "id", tmp, sizeof tmp)) str_copy(s->session_id, sizeof s->session_id, tmp);
497 json_get_str(buf, "start_time", s->start_time, sizeof s->start_time);
498 json_get_str(buf, "model", s->model, sizeof s->model);
499 json_get_str(buf, "provider", s->provider, sizeof s->provider);
500 json_get_str(buf, "profile", s->profile, sizeof s->profile);
501 json_get_str(buf, "cwd", s->cwd, sizeof s->cwd);
502 json_get_str(buf, "thread_guid", s->thread_guid, sizeof s->thread_guid);
503 if (json_get_num(buf, "start_epoch", &num)) s->start_epoch = (long long)num;
504 }
505
506 /* --- stats.json (optional usage block) --- */
507 snprintf(path, sizeof path, "%s/%s/stats.json", root, name);
508 if (read_file(path, buf, sizeof buf) > 0) {
509 if (!s->model[0]) json_get_str(buf, "model", s->model, sizeof s->model);
510 if (!s->cwd[0]) json_get_str(buf, "cwd", s->cwd, sizeof s->cwd);
511 json_get_str(buf, "branch", s->branch, sizeof s->branch);
512 if (json_get_num(buf, "input_tokens", &num)) s->in_tokens = (long long)num;
513 if (json_get_num(buf, "output_tokens", &num)) s->out_tokens = (long long)num;
514 if (json_get_num(buf, "cache_read_tokens", &num)) s->cache_read = (long long)num;
515 if (json_get_num(buf, "cache_creation_tokens", &num))s->cache_write = (long long)num;
516 }
517
518 /* --- thinking / active marker --- */
519 snprintf(path, sizeof path, "%s/%s/thinking", root, name);
520 if (path_exists(path)) s->is_active = 1;
521
522 /* --- events.jsonl: single streaming pass --- */
523 snprintf(path, sizeof path, "%s/%s/events.jsonl", root, name);
524 {
525 FILE *f = fopen(path, "rb");
526 char line[LINE_SZ];
527 long long run_start = 0;
528 int in_run = 0;
529
530 if (f) {
531 while (fgets(line, sizeof line, f)) {
532 char ts[40] = {0};
533 char ev[48] = {0};
534 long long t;
535
536 if (!json_get_str(line, "ts", ts, sizeof ts)) continue;
537 t = parse_ts(ts);
538 if (t <= 0) continue;
539 json_get_str(line, "event", ev, sizeof ev);
540
541 if (!s->first_ts) s->first_ts = t;
542 s->last_ts = t;
543
544 if (strcmp(ev, "session_start") == 0) {
545 if (!s->start_time[0]) str_copy(s->start_time, sizeof s->start_time, ts);
546 if (!s->model[0]) json_get_str(line, "model", s->model, sizeof s->model);
547 if (!s->provider[0]) json_get_str(line, "provider", s->provider, sizeof s->provider);
548 if (!s->profile[0]) json_get_str(line, "profile", s->profile, sizeof s->profile);
549 } else if (strcmp(ev, "agent_run_start") == 0) {
550 if (!in_run) { in_run = 1; run_start = t; s->turns++; }
551 } else if (strcmp(ev, "agent_idle") == 0
552 || strcmp(ev, "agent_complete") == 0
553 || strcmp(ev, "session_end") == 0
554 || strcmp(ev, "session_compact") == 0) {
555 if (in_run) {
556 if (t > run_start) s->active_sec += (t - run_start);
557 in_run = 0;
558 }
559 if (strcmp(ev, "agent_complete") == 0) s->is_active = 0;
560 } else if (strcmp(ev, "user_message") == 0) {
561 /* A user message ends idleness; the run starts right after. */
562 if (in_run) {
563 if (t > run_start) s->active_sec += (t - run_start);
564 in_run = 0;
565 }
566 } else if (strcmp(ev, "tool_use") == 0) {
567 char tool[NAME_SZ] = {0};
568 if (json_get_str(line, "tool", tool, sizeof tool)) note_tool(s, tool);
569 }
570 }
571 fclose(f);
572
573 /* A run that never closed is still running: count up to the last event. */
574 if (in_run && s->last_ts > run_start) s->active_sec += (s->last_ts - run_start);
575 }
576 }
577
578 if (!s->start_time[0] && s->first_ts) {
579 /* Fall back to the first event timestamp rendered as text is unnecessary:
580 * we only need a numeric base below. */
581 }
582 if (!s->start_epoch) s->start_epoch = s->first_ts;
583
584 /* --- durations --- */
585 if (s->start_epoch > 0) {
586 long long end = s->last_ts > 0 ? s->last_ts : s->start_epoch;
587 s->total_sec = end - s->start_epoch;
588 if (s->total_sec < 0) s->total_sec = 0;
589 }
590 if (s->last_ts > s->first_ts && s->last_ts - s->first_ts > s->total_sec)
591 s->total_sec = s->last_ts - s->first_ts;
592
593 if (s->active_sec > s->total_sec) s->active_sec = s->total_sec;
594 s->idle_sec = s->total_sec - s->active_sec;
595 s->duty_pct = s->total_sec > 0 ? (100.0 * (double)s->active_sec / (double)s->total_sec) : 0.0;
596
597 return 1;
598}
599
600/* Scan every root we were given and append sessions. Returns count. */
601static int scan_sessions(const char *root, session_t *out, int max)
602{
603 static char names[1024][NAME_SZ];
604 int n = sx_list_dirs(root, names, 1024);
605 int i, kept = 0;
606
607 for (i = 0; i < n && kept < max; i++) {
608 session_t s;
609 if (!load_session(root, names[i], &s)) continue;
610 out[kept++] = s;
611 }
612 return kept;
613}
614
615/* ------------------------------------------------------------------ */
616/* Profile / model aggregation */
617/* ------------------------------------------------------------------ */
618
619typedef struct {
620 char label[64];
621 int sessions;
622 long long active_sec;
623 int turns;
624} bucket_t;
625
626static void bucket_add(bucket_t *b, int *count, int max, const char *label,
627 long long active_sec, int turns)
628{
629 int i;
630 const char *key = (label && *label) ? label : "unknown";
631
632 for (i = 0; i < *count; i++) {
633 if (strcmp(b[i].label, key) == 0) {
634 b[i].sessions++;
635 b[i].active_sec += active_sec;
636 b[i].turns += turns;
637 return;
638 }
639 }
640 if (*count >= max) return;
641 str_copy(b[*count].label, sizeof b[*count].label, key);
642 b[*count].sessions = 1;
643 b[*count].active_sec = active_sec;
644 b[*count].turns = turns;
645 (*count)++;
646}
647
648/* ------------------------------------------------------------------ */
649/* Sorting */
650/* ------------------------------------------------------------------ */
651
652static int cmp_session_desc(const void *a, const void *b)
653{
654 const session_t *x = (const session_t *)a;
655 const session_t *y = (const session_t *)b;
656 if (x->last_ts != y->last_ts) return x->last_ts < y->last_ts ? 1 : -1;
657 return strcmp(x->id, y->id);
658}
659
660static int cmp_bucket_desc(const void *a, const void *b)
661{
662 const bucket_t *x = (const bucket_t *)a;
663 const bucket_t *y = (const bucket_t *)b;
664 if (x->active_sec != y->active_sec) return x->active_sec < y->active_sec ? 1 : -1;
665 return strcmp(x->label, y->label);
666}
667
668/* Sort tools by hit count while keeping the hits array aligned. */
669static void sort_tools(session_t *s)
670{
671 int i, j;
672 for (i = 1; i < s->tool_count; i++) {
673 tool_use_t key = s->tools[i];
674 int keyhits = s->tool_hits[i];
675 j = i - 1;
676 while (j >= 0 && s->tool_hits[j] < keyhits) {
677 s->tools[j + 1] = s->tools[j];
678 s->tool_hits[j + 1] = s->tool_hits[j];
679 j--;
680 }
681 s->tools[j + 1] = key;
682 s->tool_hits[j + 1] = keyhits;
683 }
684}
685
686/* ------------------------------------------------------------------ */
687/* Aggregates */
688/* ------------------------------------------------------------------ */
689
690typedef struct {
691 char root[PATH_SZ];
692 int root_ok;
693 int count;
694 long long total_sec;
695 long long active_sec;
696 long long idle_sec;
697 double duty_pct;
698 int turns;
699 int active_now;
700 int tool_events;
701 session_t *sessions;
702} summary_t;
703
704static void build_summary(summary_t *sum, session_t *buf, int n)
705{
706 int i, j;
707 memset(sum, 0, sizeof *sum);
708 sum->sessions = buf;
709 sum->count = n;
710
711 for (i = 0; i < n; i++) {
712 session_t *s = &buf[i];
713 sum->total_sec += s->total_sec;
714 sum->active_sec += s->active_sec;
715 sum->turns += s->turns;
716 if (s->is_active) sum->active_now++;
717 sort_tools(s);
718 for (j = 0; j < s->tool_count; j++) sum->tool_events += s->tool_hits[j];
719 }
720 sum->idle_sec = sum->total_sec - sum->active_sec;
721 if (sum->idle_sec < 0) sum->idle_sec = 0;
722 sum->duty_pct = sum->total_sec > 0
723 ? (100.0 * (double)sum->active_sec / (double)sum->total_sec) : 0.0;
724}
725
726/* ------------------------------------------------------------------ */
727/* JSON output */
728/* ------------------------------------------------------------------ */
729
730static void json_header(void)
731{
732 fputs("Content-Type: application/json; charset=utf-8\r\n"
733 "Cache-Control: no-store\r\n"
734 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
735}
736
737static void print_session_obj(const session_t *s, int with_tools)
738{
739 char tot[64], act[64], idl[64];
740 int i;
741
742 format_duration(s->total_sec, tot, sizeof tot);
743 format_duration(s->active_sec, act, sizeof act);
744 format_duration(s->idle_sec, idl, sizeof idl);
745
746 printf("{");
747 printf("\"id\":"); json_str(s->session_id);
748 printf(",\"dir\":"); json_str(s->id);
749 printf(",\"model\":"); json_str(s->model);
750 printf(",\"provider\":"); json_str(s->provider);
751 printf(",\"profile\":"); json_str(s->profile);
752 printf(",\"branch\":"); json_str(s->branch);
753 printf(",\"cwd\":"); json_str(s->cwd);
754 printf(",\"start_time\":"); json_str(s->start_time);
755 printf(",\"first_epoch\":%lld", s->first_ts);
756 printf(",\"last_epoch\":%lld", s->last_ts);
757 printf(",\"is_active\":%s", s->is_active ? "true" : "false");
758 printf(",\"total_sec\":%lld", s->total_sec);
759 printf(",\"total_fmt\":"); json_str(tot);
760 printf(",\"active_sec\":%lld", s->active_sec);
761 printf(",\"active_fmt\":"); json_str(act);
762 printf(",\"idle_sec\":%lld", s->idle_sec);
763 printf(",\"idle_fmt\":"); json_str(idl);
764 printf(",\"duty_cycle_pct\":%.2f", s->duty_pct);
765 printf(",\"turns\":%d", s->turns);
766 printf(",\"avg_turn_sec\":%.1f",
767 s->turns > 0 ? ((double)s->active_sec / (double)s->turns) : 0.0);
768 printf(",\"tokens\":{\"in\":%lld,\"out\":%lld,\"cache_read\":%lld,\"cache_write\":%lld}",
769 s->in_tokens, s->out_tokens, s->cache_read, s->cache_write);
770 if (with_tools) {
771 printf(",\"tools\":[");
772 for (i = 0; i < s->tool_count; i++) {
773 if (i) printf(",");
774 printf("{\"name\":"); json_str(s->tools[i].name);
775 printf(",\"calls\":%d}", s->tool_hits[i]);
776 }
777 printf("]");
778 }
779 printf("}");
780}
781
782static void print_summary_json(const summary_t *sum)
783{
784 bucket_t profiles[64], models[64];
785 int np = 0, nm = 0, i;
786 char tot[64], act[64], idl[64];
787
788 for (i = 0; i < sum->count; i++) {
789 const session_t *s = &sum->sessions[i];
790 bucket_add(profiles, &np, 64, s->profile[0] ? s->profile : "unknown",
791 s->active_sec, s->turns);
792 bucket_add(models, &nm, 64, s->model[0] ? s->model : "unknown",
793 s->active_sec, s->turns);
794 }
795 qsort(profiles, (size_t)np, sizeof profiles[0], cmp_bucket_desc);
796 qsort(models, (size_t)nm, sizeof models[0], cmp_bucket_desc);
797
798 format_duration(sum->total_sec, tot, sizeof tot);
799 format_duration(sum->active_sec, act, sizeof act);
800 format_duration(sum->idle_sec, idl, sizeof idl);
801
802 json_header();
803 printf("{");
804 printf("\"ok\":true");
805 printf(",\"plugin\":\"%s\"", PLUGIN_ID);
806 printf(",\"version\":\"%s\"", PLUGIN_VER);
807 printf(",\"sessions_root\":"); json_str(sum->root);
808 printf(",\"root_found\":%s", sum->root_ok ? "true" : "false");
809 printf(",\"count\":%d", sum->count);
810 printf(",\"active_now\":%d", sum->active_now);
811 printf(",\"total_sec\":%lld", sum->total_sec);
812 printf(",\"total_fmt\":"); json_str(tot);
813 printf(",\"active_sec\":%lld", sum->active_sec);
814 printf(",\"active_fmt\":"); json_str(act);
815 printf(",\"idle_sec\":%lld", sum->idle_sec);
816 printf(",\"idle_fmt\":"); json_str(idl);
817 printf(",\"duty_cycle_pct\":%.2f", sum->duty_pct);
818 printf(",\"turns\":%d", sum->turns);
819 printf(",\"tool_events\":%d", sum->tool_events);
820
821 printf(",\"profiles\":[");
822 for (i = 0; i < np; i++) {
823 if (i) printf(",");
824 printf("{\"profile\":"); json_str(profiles[i].label);
825 printf(",\"sessions\":%d,\"active_sec\":%lld,\"turns\":%d}",
826 profiles[i].sessions, profiles[i].active_sec, profiles[i].turns);
827 }
828 printf("]");
829
830 printf(",\"models\":[");
831 for (i = 0; i < nm; i++) {
832 if (i) printf(",");
833 printf("{\"model\":"); json_str(models[i].label);
834 printf(",\"sessions\":%d,\"active_sec\":%lld,\"turns\":%d}",
835 models[i].sessions, models[i].active_sec, models[i].turns);
836 }
837 printf("]");
838
839 printf(",\"sessions\":[");
840 for (i = 0; i < sum->count; i++) {
841 if (i) printf(",");
842 print_session_obj(&sum->sessions[i], 1);
843 }
844 printf("]}\n");
845}
846
847static void print_session_json(const session_t *s, const char *root)
848{
849 char tot[64], act[64], idl[64];
850 format_duration(s->total_sec, tot, sizeof tot);
851 format_duration(s->active_sec, act, sizeof act);
852 format_duration(s->idle_sec, idl, sizeof idl);
853
854 json_header();
855 printf("{\"ok\":true,\"plugin\":\"%s\",\"version\":\"%s\"", PLUGIN_ID, PLUGIN_VER);
856 printf(",\"sessions_root\":"); json_str(root);
857 printf(",\"session\":"); print_session_obj(s, 1);
858 printf(",\"summary\":{\"total_sec\":%lld,\"total_fmt\":", s->total_sec);
859 json_str(tot);
860 printf(",\"active_sec\":%lld,\"active_fmt\":", s->active_sec);
861 json_str(act);
862 printf(",\"idle_sec\":%lld,\"idle_fmt\":", s->idle_sec);
863 json_str(idl);
864 printf(",\"duty_cycle_pct\":%.2f,\"turns\":%d}}\n", s->duty_pct, s->turns);
865}
866
867/* ------------------------------------------------------------------ */
868/* HTML UI */
869/* ------------------------------------------------------------------ */
870
871static void html_head(int embed, const char *initial_id)
872{
873 (void)embed;
874 (void)initial_id;
875 fputs(
876 "Content-Type: text/html; charset=utf-8\r\n"
877 "Cache-Control: no-store\r\n"
878 "X-Content-Type-Options: nosniff\r\n"
879 "\r\n"
880 "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'>"
881 "<meta name='viewport' content='width=device-width,initial-scale=1'>"
882 "<title>Session Analytics</title>"
883 SX_BOT_THEME_PREPAINT
884 "<style>" SX_BOT_THEME_TOKENS
885 "*{box-sizing:border-box}"
886 "body{margin:0;padding:14px;background:var(--bg);color:var(--text);"
887 "font-family:-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',Roboto,sans-serif;"
888 "-webkit-font-smoothing:antialiased;font-size:13px;line-height:1.45}"
889 ".wrap{max-width:1000px;margin:0 auto}"
890 ".head{display:flex;align-items:center;justify-content:space-between;gap:10px;"
891 "flex-wrap:wrap;padding-bottom:12px;margin-bottom:14px;border-bottom:1px solid var(--line)}"
892 ".brand{display:flex;align-items:center;gap:8px;font-size:15px;font-weight:700}"
893 ".brand svg{width:20px;height:20px;flex:0 0 auto}"
894 ".pill{font-size:10px;font-weight:700;letter-spacing:.4px;text-transform:uppercase;"
895 "padding:2px 8px;border-radius:999px;border:1px solid var(--line);color:var(--muted)}"
896 ".pill.on{color:var(--green);border-color:rgba(48,209,88,.4);background:rgba(48,209,88,.12)}"
897 ".actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}"
898 "button,select{background:var(--surface);color:var(--text);border:1px solid var(--line);"
899 "border-radius:8px;padding:6px 11px;font-size:12px;font-weight:600;cursor:pointer;"
900 "font-family:inherit;outline:none}"
901 "button:hover{background:var(--surface2)}"
902 "button.primary{background:var(--blue);border-color:var(--blue);color:#fff}"
903 ".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:10px;margin-bottom:12px}"
904 ".card{background:var(--surface);border:1px solid var(--line);border-radius:12px;padding:13px}"
905 ".k{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;"
906 "color:var(--muted);margin-bottom:5px}"
907 ".v{font-size:22px;font-weight:700;letter-spacing:-.4px;font-variant-numeric:tabular-nums;"
908 "overflow:hidden;text-overflow:ellipsis;white-space:nowrap}"
909 ".v.blue{color:var(--blue)}.v.green{color:var(--green)}.v.orange{color:var(--orange)}"
910 ".v.purple{color:var(--purple)}"
911 ".sub{font-size:11px;color:var(--muted);margin-top:3px}"
912 ".panel{background:var(--surface);border:1px solid var(--line);border-radius:12px;"
913 "padding:13px;margin-bottom:12px}"
914 ".panel h2{margin:0 0 9px;font-size:12px;font-weight:700;text-transform:uppercase;"
915 "letter-spacing:.5px;color:var(--muted)}"
916 ".rail{height:12px;border-radius:999px;background:var(--surface2);"
917 "border:1px solid var(--line);overflow:hidden;display:flex}"
918 ".rail .on{background:linear-gradient(90deg,var(--blue),var(--green));height:100%}"
919 ".legend{display:flex;gap:14px;flex-wrap:wrap;margin-top:8px;font-size:11px;color:var(--muted)}"
920 ".legend i{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:5px}"
921 ".bars{display:flex;flex-direction:column;gap:7px}"
922 ".row{display:grid;grid-template-columns:150px 1fr 78px;align-items:center;gap:9px;font-size:12px}"
923 ".row .nm{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--muted)}"
924 ".track{display:block;height:9px;border-radius:999px;background:var(--surface2);overflow:hidden}"
925 ".fill{display:block;height:100%;border-radius:999px;background:linear-gradient(90deg,var(--blue),var(--purple));min-width:3px}"
926 ".val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--muted)}"
927 ".tbl{width:100%;border-collapse:collapse;font-size:12px}"
928 ".tbl th{text-align:left;font-size:10px;text-transform:uppercase;letter-spacing:.5px;"
929 "color:var(--muted);font-weight:700;padding:6px 8px;border-bottom:1px solid var(--line);"
930 "cursor:pointer;white-space:nowrap;user-select:none}"
931 ".tbl th:hover{color:var(--text)}"
932 ".tbl td{padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:top}"
933 ".tbl tr:last-child td{border-bottom:0}"
934 ".tbl tr.sel td{background:var(--surface2)}"
935 ".tbl tr:hover td{background:var(--surface2);cursor:pointer}"
936 ".mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px}"
937 ".nowrap{white-space:nowrap}"
938 ".tag{display:inline-block;padding:1px 6px;border-radius:999px;font-size:10px;"
939 "font-weight:700;border:1px solid var(--line);color:var(--muted)}"
940 ".tag.on{color:var(--green);border-color:rgba(48,209,88,.4);background:rgba(48,209,88,.12)}"
941 ".scroll{overflow-x:auto;-webkit-overflow-scrolling:touch}"
942 ".empty{padding:26px 12px;text-align:center;color:var(--muted);font-size:12px}"
943 ".err{color:var(--red)}"
944 "@media(max-width:640px){"
945 ".v{font-size:19px}"
946 ".row{grid-template-columns:100px 1fr 62px}"
947 ".tbl th:nth-child(4),.tbl td:nth-child(4),"
948 ".tbl th:nth-child(5),.tbl td:nth-child(5){display:none}"
949 "body{padding:10px}}"
950 "@media(max-width:400px){.row{grid-template-columns:80px 1fr 54px}.grid{grid-template-columns:1fr 1fr}}"
951 "</style></head>" SX_BOT_THEME_HANDOFF "<body><div class='wrap'>"
952 "<div class='head'>"
953 "<div class='brand'>"
954 "<svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='1.8' "
955 "stroke-linecap='round' stroke-linejoin='round' aria-hidden='true'>"
956 "<circle cx='12' cy='12' r='9'></circle><path d='M12 7v5l3.5 2'></path></svg>"
957 "<span>Session Analytics</span>"
958 "<span class='pill' id='livePill'>idle</span>"
959 "</div>"
960 "<div class='actions'>"
961 "<select id='sortSel' aria-label='Sort sessions'>"
962 "<option value='recent'>Recent first</option>"
963 "<option value='active'>Most active</option>"
964 "<option value='turns'>Most turns</option>"
965 "<option value='duty'>Highest duty cycle</option>"
966 "</select>"
967 "<button id='btnReload' type='button'>Refresh</button>"
968 "<button class='embed-hide' id='btnTheme' type='button' aria-label='Toggle theme'>Theme</button>"
969 "</div></div>"
970 "<div id='err' class='err'></div>"
971 "<div class='grid'>"
972 "<div class='card'><div class='k'>Sessions</div><div class='v blue' id='kSessions'>-</div>"
973 "<div class='sub' id='kSessionsSub'>&nbsp;</div></div>"
974 "<div class='card'><div class='k'>Wall clock</div><div class='v' id='kTotal'>-</div>"
975 "<div class='sub'>All sessions combined</div></div>"
976 "<div class='card'><div class='k'>Active work</div><div class='v green' id='kActive'>-</div>"
977 "<div class='sub' id='kActiveSub'>&nbsp;</div></div>"
978 "<div class='card'><div class='k'>Duty cycle</div><div class='v orange' id='kDuty'>-</div>"
979 "<div class='sub' id='kDutySub'>&nbsp;</div></div>"
980 "<div class='card'><div class='k'>Turns</div><div class='v purple' id='kTurns'>-</div>"
981 "<div class='sub' id='kTurnsSub'>&nbsp;</div></div>"
982 "</div>"
983 "<div class='panel'>"
984 "<h2>Active versus idle</h2>"
985 "<div class='rail'><div class='on' id='railOn' style='width:0%'></div></div>"
986 "<div class='legend'>"
987 "<span><i style='background:var(--green)'></i>Active (agent run)</span>"
988 "<span><i style='background:var(--surface2);border:1px solid var(--line)'></i>Idle (waiting)</span>"
989 "<span id='railText'></span>"
990 "</div></div>"
991 "<div class='panel'><h2>Profile usage by active time</h2>"
992 "<div class='bars' id='profBars'><div class='empty'>No data</div></div></div>"
993 "<div class='panel'><h2>Model usage by active time</h2>"
994 "<div class='bars' id='modelBars'><div class='empty'>No data</div></div></div>"
995 "<div class='panel'><h2>Sessions</h2><div class='scroll'>"
996 "<table class='tbl' id='tbl'><thead><tr>"
997 "<th data-key='id'>Session</th>"
998 "<th data-key='profile'>Profile / model</th>"
999 "<th data-key='active'>Active</th>"
1000 "<th data-key='total'>Wall</th>"
1001 "<th data-key='duty'>Duty</th>"
1002 "<th data-key='turns'>Turns</th>"
1003 "</tr></thead><tbody id='tbody'></tbody></table>"
1004 "</div><div class='empty' id='tblEmpty' style='display:none'>No session directories found</div></div>"
1005 "<div class='panel'><h2>Selected session</h2>"
1006 "<div id='detail' class='sub'>Select a row above to inspect tool usage.</div></div>"
1007 "</div>"
1008 "<script>", stdout);
1009}
1010
1011static void html_script(const char *initial_id)
1012{
1013 fputs(
1014 "var q=new URLSearchParams(location.search);"
1015 "var node=q.get('node')||'';"
1016 "var pretty=q.get('plugin')||'';"
1017 "var sel=q.get('id')||'", stdout);
1018 if (initial_id && *initial_id) {
1019 const char *p;
1020 for (p = initial_id; *p; p++) {
1021 if (*p == '\'' || *p == '\\') putchar('\\');
1022 putchar(*p);
1023 }
1024 }
1025 fputs("';"
1026 "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))"
1027 "||localStorage.getItem('bot_active_pwd')||'';"
1028 "var DATA=null,SORT='recent';"
1029
1030 "function api(u){"
1031 " return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{},cache:'no-store'})"
1032 " .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); });"
1033 "}"
1034
1035 /* Two routes: hub proxy when served through bot.scorpiox.net, direct plugin
1036 route when the page was opened straight from the node. */
1037 "function url(action,extra){"
1038 " var base=pretty?('/plugins?plugin='+encodeURIComponent(pretty)+'&action='+encodeURIComponent(action))"
1039 " :('/plugin_sessionstats?action='+encodeURIComponent(action));"
1040 " if(extra)base+='&'+extra;"
1041 " if(node)base+='&node='+encodeURIComponent(node);"
1042 " if(pwd)base+='&pwd='+encodeURIComponent(pwd);"
1043 " return base;"
1044 "}"
1045
1046 "function esc(s){return String(s==null?'':s).replace(/[&<>\"]/g,function(c){"
1047 " return c==='&'?'&amp;':c==='<'?'&lt;':c==='>'?'&gt;':'&quot;';});}"
1048
1049 "function fmt(sec){"
1050 " sec=Math.max(0,Math.floor(sec||0));"
1051 " var d=Math.floor(sec/86400),r=sec%86400,h=Math.floor(r/3600);"
1052 " r%=3600;var m=Math.floor(r/60),s=r%60;var p=function(n){return (n<10?'0':'')+n;};"
1053 " if(d>0)return d+'d '+p(h)+'h '+p(m)+'m';"
1054 " if(h>0)return p(h)+'h '+p(m)+'m '+p(s)+'s';"
1055 " if(m>0)return p(m)+'m '+p(s)+'s';"
1056 " return s+'s';"
1057 "}"
1058
1059 "document.getElementById('btnTheme').onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};"
1060
1061 "function bars(el,arr,key){"
1062 " if(!arr||!arr.length){el.innerHTML='<div class=\"empty\">No data</div>';return;}"
1063 " var max=0,i;"
1064 " for(i=0;i<arr.length;i++)if(arr[i].active_sec>max)max=arr[i].active_sec;"
1065 " if(max<=0)max=1;"
1066 " var out='';"
1067 " for(i=0;i<arr.length;i++){"
1068 " var r=arr[i],w=Math.max(1,Math.round(100*r.active_sec/max));"
1069 " out+='<div class=\"row\"><span class=\"nm\" title=\"'+esc(r[key])+'\">'+esc(r[key])+'</span>'"
1070 " +'<span class=\"track\"><span class=\"fill\" style=\"width:'+w+'%\"></span></span>'"
1071 " +'<span class=\"val\">'+fmt(r.active_sec)+'</span></div>';"
1072 " }"
1073 " el.innerHTML=out;"
1074 "}"
1075
1076 "function rows(){"
1077 " var a=(DATA&&DATA.sessions)||[];"
1078 " a=a.slice();"
1079 " var cmp={"
1080 " recent:function(x,y){return (y.last_epoch||0)-(x.last_epoch||0);},"
1081 " active:function(x,y){return (y.active_sec||0)-(x.active_sec||0);},"
1082 " turns:function(x,y){return (y.turns||0)-(x.turns||0);},"
1083 " duty:function(x,y){return (y.duty_cycle_pct||0)-(x.duty_cycle_pct||0);}"
1084 " }[SORT];"
1085 " a.sort(cmp);"
1086 " return a;"
1087 "}"
1088
1089 "function render(){"
1090 " if(!DATA)return;"
1091 " var d=DATA,s=d.sessions||[];"
1092 " document.getElementById('kSessions').textContent=d.count;"
1093 " document.getElementById('kSessionsSub').textContent=(d.active_now||0)+' active now';"
1094 " document.getElementById('kTotal').textContent=fmt(d.total_sec);"
1095 " document.getElementById('kTotal').className='v';"
1096 " document.getElementById('kActive').textContent=fmt(d.active_sec);"
1097 " document.getElementById('kActiveSub').textContent=fmt(d.idle_sec)+' idle';"
1098 " document.getElementById('kDuty').textContent=(d.duty_cycle_pct||0).toFixed(1)+'%';"
1099 " document.getElementById('kDutySub').textContent=(d.tool_events||0)+' tool calls';"
1100 " document.getElementById('kTurns').textContent=d.turns;"
1101 " document.getElementById('kTurnsSub').textContent="
1102 " d.turns>0?((d.active_sec/d.turns).toFixed(1)+'s per turn'):'-';"
1103 " var pct=d.total_sec>0?(100*d.active_sec/d.total_sec):0;"
1104 " document.getElementById('railOn').style.width=Math.max(0,Math.min(100,pct))+'%';"
1105 " document.getElementById('railText').textContent="
1106 " fmt(d.active_sec)+' active of '+fmt(d.total_sec);"
1107 " bars(document.getElementById('profBars'),d.profiles,'profile');"
1108 " bars(document.getElementById('modelBars'),d.models,'model');"
1109
1110 " var list=rows(),html='',i;"
1111 " for(i=0;i<list.length;i++){"
1112 " var x=list[i];"
1113 " var tag=x.is_active?'<span class=\"tag on\">live</span>':'<span class=\"tag\">idle</span>';"
1114 " html+='<tr data-dir=\"'+esc(x.dir)+'\" class=\"'+(x.dir===sel?'sel':'')+'\">'"
1115 " +'<td><div class=\"mono\">'+esc(x.id)+'</div>"
1116 " <div class=\"sub\">'+esc(x.start_time||'')+' '+tag+'</div></td>'"
1117 " +'<td><div>'+esc(x.profile||'-')+'</div>"
1118 " <div class=\"sub mono\">'+esc(x.model||'-')+'</div></td>'"
1119 " +'<td class=\"nowrap\">'+esc(x.active_fmt)+'</td>'"
1120 " +'<td class=\"nowrap\">'+esc(x.total_fmt)+'</td>'"
1121 " +'<td class=\"nowrap\">'+(x.duty_cycle_pct||0).toFixed(0)+'%</td>'"
1122 " +'<td class=\"nowrap\">'+x.turns+'</td></tr>';"
1123 " }"
1124 " document.getElementById('tbody').innerHTML=html;"
1125 " document.getElementById('tblEmpty').style.display=list.length?'none':'block';"
1126 " var trs=document.querySelectorAll('#tbody tr');"
1127 " for(i=0;i<trs.length;i++){"
1128 " trs[i].onclick=function(){ select(this.getAttribute('data-dir')); };"
1129 " }"
1130 " if(!d.root_found){"
1131 " document.getElementById('err').textContent="
1132 " 'Sessions root not found: '+d.sessions_root;"
1133 " } else { document.getElementById('err').textContent=''; }"
1134 "}"
1135
1136 "function select(dir){"
1137 " sel=dir;"
1138 " render();"
1139 " var el=document.getElementById('detail');"
1140 " el.innerHTML='<div class=\"empty\">Loading...</div>';"
1141 " api(url('session','sid='+encodeURIComponent(dir))).then(function(r){"
1142 " if(!r.ok||!r.session){el.innerHTML='<div class=\"empty\">Session not found</div>';return;}"
1143 " var s=r.session;"
1144 " var t='<div class=\"mono\">'+esc(s.id)+'</div>';"
1145 " t+='<div class=\"sub\">'+esc(s.profile||'-')+' / '+esc(s.model||'-')"
1146 " +' / '+esc(s.branch||'-')+'</div>';"
1147 " t+='<div class=\"sub mono\" style=\"word-break:break-all\">'+esc(s.cwd||'')+'</div>';"
1148 " t+='<div style=\"margin-top:8px\">'+esc(s.active_fmt)+' active, '"
1149 " +esc(s.idle_fmt)+' idle, duty '+(s.duty_cycle_pct||0).toFixed(1)+'% over '"
1150 " +s.turns+' turns</div>';"
1151 " if(s.tools&&s.tools.length){"
1152 " t+='<div style=\"margin-top:8px\">';"
1153 " for(var i=0;i<s.tools.length;i++){"
1154 " t+='<span class=\"tag\" style=\"margin:0 4px 4px 0\">'+esc(s.tools[i].name)"
1155 " +' x'+s.tools[i].calls+'</span>';"
1156 " }"
1157 " t+='</div>';"
1158 " } else { t+='<div class=\"sub\">No tool calls recorded</div>'; }"
1159 " el.innerHTML=t;"
1160 " }).catch(function(e){ el.innerHTML='<div class=\"empty err\">'+esc(e.message)+'</div>'; });"
1161 "}"
1162
1163 "document.getElementById('sortSel').onchange=function(){SORT=this.value;render();};"
1164 "document.getElementById('btnReload').onclick=function(){load();};"
1165 "function load(){"
1166 " var pill=document.getElementById('livePill');"
1167 " api(url('summary')).then(function(d){"
1168 " DATA=d;"
1169 " pill.textContent=(d.active_now>0?'live':'idle');"
1170 " pill.className='pill'+(d.active_now>0?' on':'');"
1171 " render();"
1172 " if(sel)select(sel);"
1173 " }).catch(function(e){"
1174 " document.getElementById('err').textContent='Failed to load: '+e.message;"
1175 " });"
1176 "}"
1177 "load();"
1178 "setInterval(load,20000);"
1179 "</script></body></html>\n", stdout);
1180}
1181
1182/* ------------------------------------------------------------------ */
1183/* main */
1184/* ------------------------------------------------------------------ */
1185
1186int main(int argc, char **argv)
1187{
1188 static session_t buf[MAX_SESSIONS];
1189 static char names_big[1024][NAME_SZ];
1190 summary_t sum;
1191 char root[PATH_SZ] = {0};
1192 char action[32] = {0};
1193 char sid[NAME_SZ] = {0};
1194 const char *qs;
1195 int n, i;
1196 int root_ok;
1197
1198 if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1199 puts("{\"name\":\"sessions\",\"desc\":\"Turn metrics\"}");
1200 return 0;
1201 }
1202
1203 require_node_auth();
1204
1205 qs = getenv("QUERY_STRING");
1206 if (!qs) qs = "";
1207 get_query_val(qs, "action", action, sizeof action);
1208 get_query_val(qs, "sid", sid, sizeof sid);
1209 if (!sid[0]) get_query_val(qs, "id", sid, sizeof sid);
1210
1211 root_ok = resolve_sessions_root(root, sizeof root);
1212
1213 /* ---------------- JSON modes ---------------- */
1214 {
1215 char fmt[16] = {0};
1216 int have_action = action[0] != '\0';
1217 int have_format = get_query_val(qs, "format", fmt, sizeof fmt);
1218
1219 if (have_action || have_format) {
1220 n = root_ok ? scan_sessions(root, buf, MAX_SESSIONS) : 0;
1221 (void)names_big;
1222
1223 if (have_action && strcmp(action, "session") == 0) {
1224 session_t one;
1225 int found = 0;
1226 for (i = 0; i < n; i++) {
1227 if (strcmp(buf[i].id, sid) == 0 || strcmp(buf[i].session_id, sid) == 0) {
1228 found = 1;
1229 break;
1230 }
1231 }
1232 if (found) {
1233 one = buf[i];
1234 sort_tools(&one);
1235 print_session_json(&one, root);
1236 } else if (sid[0]) {
1237 /* Allow inspecting a session older than the scan window. */
1238 if (load_session(root, sid, &one)) {
1239 sort_tools(&one);
1240 print_session_json(&one, root);
1241 } else {
1242 json_header();
1243 printf("{\"ok\":false,\"error\":\"session not found\",\"sid\":");
1244 json_str(sid);
1245 printf(",\"sessions_root\":");
1246 json_str(root);
1247 printf("}\n");
1248 }
1249 } else {
1250 json_header();
1251 printf("{\"ok\":false,\"error\":\"missing sid parameter\",\"sessions_root\":");
1252 json_str(root);
1253 printf("}\n");
1254 }
1255 return 0;
1256 }
1257
1258 qsort(buf, (size_t)n, sizeof buf[0], cmp_session_desc);
1259 build_summary(&sum, buf, n);
1260 str_copy(sum.root, sizeof sum.root, root);
1261 sum.root_ok = root_ok;
1262 print_summary_json(&sum);
1263 return 0;
1264 }
1265 }
1266
1267 /* ---------------- HTML ---------------- */
1268 {
1269 int embed = 0;
1270 char ev[16] = {0};
1271 if (get_query_val(qs, "embed", ev, sizeof ev)) {
1272 if (!strcmp(ev, "1") || !strcmp(ev, "true")) embed = 1;
1273 }
1274 html_head(embed, sid);
1275 html_script(sid);
1276 }
1277 return 0;
1278}