/* * plugin_sessionstats - SCORPIOX BOT open-source session runtime & turn analytics * * A single clean-room C99 binary that serves THREE modes: * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata * 2. ?action=summary | ?action=session&sid=... | ?format=json -> JSON node API * 3. GET (default) -> responsive HTML analytics UI * * Everything it reads is LOCAL to the node and read-only: the per-session * directories under the ScorpioX sessions root (meta.json, stats.json, * events.jsonl, and the optional "thinking" marker). Nothing is ever written, * renamed or deleted. There is no parameter anywhere in this file that can * point it at another host or another path outside the sessions root. * * Every timestamp in the session files is local wall-clock text * ("YYYY-MM-DD HH:MM:SS"). Only differences between timestamps are used, so a * single deterministic civil-days conversion is sufficient and no timezone * database is required. * * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under * scorpiox-server on the node. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if !defined(_WIN32) # define _POSIX_C_SOURCE 200809L # define _DEFAULT_SOURCE 1 # if defined(__APPLE__) # define _DARWIN_C_SOURCE 1 # endif #endif #include #include #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include # include # define SX_PATHSEP '\\' #else # include # include # include # include # define SX_PATHSEP '/' #endif #include "bot_theme_plugin.h" #define PLUGIN_SLUG "sessionstats" #define PLUGIN_ID "plugin_sessionstats" #define PLUGIN_VER "1.0.1" #define NAME_SZ 128 #define MAX_SESSIONS 256 #define MAX_TOOLS 48 #define MAX_ROOTS 4 #define LINE_SZ 4096 #define FILE_SZ 16384 #define PATH_SZ 1024 /* ------------------------------------------------------------------ */ /* Small string helpers */ /* ------------------------------------------------------------------ */ static void str_copy(char *dst, size_t sz, const char *src) { size_t i = 0; if (!dst || sz == 0) return; if (!src) { dst[0] = '\0'; return; } while (i + 1 < sz && src[i]) { dst[i] = src[i]; i++; } dst[i] = '\0'; } static void url_decode(char *s) { char *o = s; if (!s) return; while (*s) { if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); *o++ = (char)((hi << 4) | lo); s += 3; } else if (*s == '+') { *o++ = ' '; s++; } else { *o++ = *s++; } } *o = '\0'; } /* Read one query parameter, percent-decoded. Returns 1 when present. */ static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (!out || outsz == 0) return 0; out[0] = '\0'; if (!qs || !key) return 0; klen = strlen(key); for (p = qs; *p; ) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { const char *v = p + klen + 1; size_t i = 0; while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++; out[i] = '\0'; url_decode(out); return 1; } p = strchr(p, '&'); if (!p) break; p++; } return 0; } static void json_str(const char *s) { fputc('"', stdout); for (; s && *s; s++) { unsigned char c = (unsigned char)*s; if (c == '"' || c == '\\') { fputc('\\', stdout); fputc((char)c, stdout); } else if (c == '\n') fputs("\\n", stdout); else if (c == '\r') fputs("\\r", stdout); else if (c == '\t') fputs("\\t", stdout); else if (c >= 0x20 && c != 0x7f) fputc((char)c, stdout); } fputc('"', stdout); } /* ------------------------------------------------------------------ */ /* Node security */ /* ------------------------------------------------------------------ */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp, *auth; char qpwd[128] = {0}; if (!np || !*np) return; xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (strncasecmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); exit(0); } /* ------------------------------------------------------------------ */ /* Time helpers */ /* ------------------------------------------------------------------ */ /* Days since 1970-01-01 for a proleptic Gregorian civil date. */ static long long days_from_civil(int y, int m, int d) { long long era, yoe, doy, doe; y -= (m <= 2); era = (y >= 0 ? y : y - 399) / 400; yoe = (long long)(y - era * 400); doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; return era * 146097 + doe - 719468; } /* Parse "YYYY-MM-DD HH:MM:SS". Returns 0 when unparseable. */ static long long parse_ts(const char *ts) { int Y, M, D, h, mi, s; if (!ts || strlen(ts) < 19) return 0; if (sscanf(ts, "%d-%d-%d %d:%d:%d", &Y, &M, &D, &h, &mi, &s) != 6) return 0; if (M < 1 || M > 12 || D < 1 || D > 31) return 0; return days_from_civil(Y, M, D) * 86400LL + h * 3600LL + mi * 60LL + s; } static void format_duration(long long sec, char *out, size_t outsz) { long long d, h, m, s; if (sec < 0) sec = 0; d = sec / 86400; sec %= 86400; h = sec / 3600; sec %= 3600; m = sec / 60; s = sec % 60; if (d > 0) snprintf(out, outsz, "%lldd %02lldh %02lldm", d, h, m); else if (h > 0) snprintf(out, outsz, "%02lldh %02lldm %02llds", h, m, s); else if (m > 0) snprintf(out, outsz, "%02lldm %02llds", m, s); else snprintf(out, outsz, "%llds", s); } /* ------------------------------------------------------------------ */ /* File helpers */ /* ------------------------------------------------------------------ */ /* Read at most sz-1 bytes of a file into buf. Returns bytes read, -1 if absent. */ static int read_file(const char *path, char *buf, size_t sz) { FILE *f; size_t n; if (!buf || sz == 0) return -1; buf[0] = '\0'; f = fopen(path, "rb"); if (!f) return -1; n = fread(buf, 1, sz - 1, f); buf[n] = '\0'; fclose(f); return (int)n; } static int path_exists(const char *path) { FILE *f = fopen(path, "rb"); if (f) { fclose(f); return 1; } return 0; } /* Directory test, portable: fopen() on a directory succeeds on glibc, so a * real stat-equivalent is needed to answer "is this a sessions root?". */ static int sx_is_dir(const char *path) { #if defined(_WIN32) DWORD a = GetFileAttributesA(path); return (a != INVALID_FILE_ATTRIBUTES) && (a & FILE_ATTRIBUTE_DIRECTORY); #else struct stat st; return (stat(path, &st) == 0) && S_ISDIR(st.st_mode); #endif } /* Extract a JSON string value for an exact top-level key name. */ static int json_get_str(const char *json, const char *key, char *out, size_t outsz) { char needle[96]; const char *p; size_t i = 0; if (!json || !key || !out || outsz == 0) return 0; out[0] = '\0'; if (strlen(key) + 3 >= sizeof needle) return 0; snprintf(needle, sizeof needle, "\"%s\"", key); p = strstr(json, needle); if (!p) return 0; p += strlen(needle); while (*p && (*p == ' ' || *p == ':' || *p == '\t')) p++; if (*p != '"') return 0; p++; while (*p && *p != '"' && i + 1 < outsz) { if (*p == '\\' && p[1]) { p++; switch (*p) { case 'n': out[i++] = '\n'; break; case 't': out[i++] = '\t'; break; case 'r': out[i++] = '\r'; break; default: out[i++] = *p; break; } p++; continue; } out[i++] = *p++; } out[i] = '\0'; return 1; } /* Extract a numeric JSON value for an exact key name. */ static int json_get_num(const char *json, const char *key, double *out) { char needle[96]; const char *p; char *end = NULL; if (!json || !key || !out) return 0; if (strlen(key) + 3 >= sizeof needle) return 0; snprintf(needle, sizeof needle, "\"%s\"", key); p = strstr(json, needle); if (!p) return 0; p += strlen(needle); while (*p && (*p == ' ' || *p == ':' || *p == '\t')) p++; if (*p != '-' && !isdigit((unsigned char)*p)) return 0; *out = strtod(p, &end); return (end != p); } /* ------------------------------------------------------------------ */ /* Directory listing (portable, directories only, dotfiles skipped) */ /* ------------------------------------------------------------------ */ #if defined(_WIN32) static int sx_list_dirs(const char *parent, char names[][NAME_SZ], int max) { char pattern[PATH_SZ + 8]; WIN32_FIND_DATAA fd; HANDLE h; int n = 0; snprintf(pattern, sizeof pattern, "%s/*", parent); h = FindFirstFileA(pattern, &fd); if (h == INVALID_HANDLE_VALUE) return 0; do { if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue; if (fd.cFileName[0] == '.') continue; if (n < max) str_copy(names[n++], NAME_SZ, fd.cFileName); } while (FindNextFileA(h, &fd)); FindClose(h); return n; } #else static int sx_list_dirs(const char *parent, char names[][NAME_SZ], int max) { DIR *d; struct dirent *de; int n = 0; d = opendir(parent); if (!d) return 0; while ((de = readdir(d)) != NULL) { char full[PATH_SZ]; struct stat st; if (de->d_name[0] == '.') continue; snprintf(full, sizeof full, "%s/%s", parent, de->d_name); if (stat(full, &st) != 0 || !S_ISDIR(st.st_mode)) continue; if (n < max) str_copy(names[n++], NAME_SZ, de->d_name); } closedir(d); return n; } #endif /* ------------------------------------------------------------------ */ /* Sessions root discovery */ /* ------------------------------------------------------------------ */ /* * Resolve the sessions root. SX_SESSIONS_DIR always wins, which is what makes * the offline test suite possible and also what lets an operator point the * plugin at a relocated state directory. Otherwise the standard per-node * locations are tried in order. */ static int resolve_sessions_root(char *out, size_t outsz) { const char *env = getenv("SX_SESSIONS_DIR"); #if !defined(_WIN32) const char *home; #endif char cand[PATH_SZ]; if (env && *env) { str_copy(out, outsz, env); return sx_is_dir(env); } #if defined(_WIN32) const char *localappdata = getenv("LOCALAPPDATA"); const char *userprofile = getenv("USERPROFILE"); if (localappdata && *localappdata) { snprintf(cand, sizeof cand, "%s\\scorpiox\\sessions", localappdata); if (sx_is_dir(cand)) { str_copy(out, outsz, cand); return 1; } } if (userprofile && *userprofile) { snprintf(cand, sizeof cand, "%s\\.scorpiox\\sessions", userprofile); if (sx_is_dir(cand)) { str_copy(out, outsz, cand); return 1; } } #else home = getenv("HOME"); if (home && *home) { snprintf(cand, sizeof cand, "%s/.scorpiox/sessions", home); if (sx_is_dir(cand)) { str_copy(out, outsz, cand); return 1; } } if (sx_is_dir("/workspace/.scorpiox/sessions")) { str_copy(out, outsz, "/workspace/.scorpiox/sessions"); return 1; } #endif /* Not found: report the most natural path so the UI can say what is missing. */ #if defined(_WIN32) if (localappdata && *localappdata) snprintf(out, outsz, "%s\\scorpiox\\sessions", localappdata); else str_copy(out, outsz, "scorpiox\\sessions"); #else if (home && *home) snprintf(out, outsz, "%s/.scorpiox/sessions", home); else str_copy(out, outsz, ".scorpiox/sessions"); #endif return 0; } /* ------------------------------------------------------------------ */ /* One session */ /* ------------------------------------------------------------------ */ typedef struct { char name[NAME_SZ]; } tool_use_t; typedef struct { char id[NAME_SZ]; /* directory name */ char session_id[NAME_SZ]; char start_time[40]; long long start_epoch; /* from meta.json when present */ long long first_ts; /* first event timestamp */ long long last_ts; /* last event timestamp */ long long total_sec; long long active_sec; long long idle_sec; double duty_pct; int turns; int is_active; char model[64]; char provider[64]; char profile[64]; char branch[128]; char cwd[512]; char thread_guid[64]; long long in_tokens; long long out_tokens; long long cache_read; long long cache_write; tool_use_t tools[MAX_TOOLS]; int tool_count; int tool_hits[MAX_TOOLS]; } session_t; /* Record (and count) one tool name for this session. */ static void note_tool(session_t *s, const char *name) { int i; if (!name || !*name) return; for (i = 0; i < s->tool_count; i++) { if (strcmp(s->tools[i].name, name) == 0) { s->tool_hits[i]++; return; } } if (s->tool_count >= MAX_TOOLS) return; str_copy(s->tools[s->tool_count].name, NAME_SZ, name); s->tool_hits[s->tool_count] = 1; s->tool_count++; } /* * Parse one session directory. Read-only: opens meta.json, stats.json, * events.jsonl and probes for the "thinking" marker. Any missing file simply * contributes nothing. */ static int load_session(const char *root, const char *name, session_t *s) { char path[PATH_SZ]; char buf[FILE_SZ]; double num; memset(s, 0, sizeof *s); str_copy(s->id, sizeof s->id, name); str_copy(s->session_id, sizeof s->session_id, name); /* Refuse a directory name that is not actually present: the caller uses * this return value to answer "session not found". */ snprintf(path, sizeof path, "%s/%s", root, name); if (!sx_is_dir(path)) return 0; /* --- meta.json --- */ snprintf(path, sizeof path, "%s/%s/meta.json", root, name); if (read_file(path, buf, sizeof buf) > 0) { char tmp[NAME_SZ]; if (json_get_str(buf, "id", tmp, sizeof tmp)) str_copy(s->session_id, sizeof s->session_id, tmp); json_get_str(buf, "start_time", s->start_time, sizeof s->start_time); json_get_str(buf, "model", s->model, sizeof s->model); json_get_str(buf, "provider", s->provider, sizeof s->provider); json_get_str(buf, "profile", s->profile, sizeof s->profile); json_get_str(buf, "cwd", s->cwd, sizeof s->cwd); json_get_str(buf, "thread_guid", s->thread_guid, sizeof s->thread_guid); if (json_get_num(buf, "start_epoch", &num)) s->start_epoch = (long long)num; } /* --- stats.json (optional usage block) --- */ snprintf(path, sizeof path, "%s/%s/stats.json", root, name); if (read_file(path, buf, sizeof buf) > 0) { if (!s->model[0]) json_get_str(buf, "model", s->model, sizeof s->model); if (!s->cwd[0]) json_get_str(buf, "cwd", s->cwd, sizeof s->cwd); json_get_str(buf, "branch", s->branch, sizeof s->branch); if (json_get_num(buf, "input_tokens", &num)) s->in_tokens = (long long)num; if (json_get_num(buf, "output_tokens", &num)) s->out_tokens = (long long)num; if (json_get_num(buf, "cache_read_tokens", &num)) s->cache_read = (long long)num; if (json_get_num(buf, "cache_creation_tokens", &num))s->cache_write = (long long)num; } /* --- thinking / active marker --- */ snprintf(path, sizeof path, "%s/%s/thinking", root, name); if (path_exists(path)) s->is_active = 1; /* --- events.jsonl: single streaming pass --- */ snprintf(path, sizeof path, "%s/%s/events.jsonl", root, name); { FILE *f = fopen(path, "rb"); char line[LINE_SZ]; long long run_start = 0; int in_run = 0; if (f) { while (fgets(line, sizeof line, f)) { char ts[40] = {0}; char ev[48] = {0}; long long t; if (!json_get_str(line, "ts", ts, sizeof ts)) continue; t = parse_ts(ts); if (t <= 0) continue; json_get_str(line, "event", ev, sizeof ev); if (!s->first_ts) s->first_ts = t; s->last_ts = t; if (strcmp(ev, "session_start") == 0) { if (!s->start_time[0]) str_copy(s->start_time, sizeof s->start_time, ts); if (!s->model[0]) json_get_str(line, "model", s->model, sizeof s->model); if (!s->provider[0]) json_get_str(line, "provider", s->provider, sizeof s->provider); if (!s->profile[0]) json_get_str(line, "profile", s->profile, sizeof s->profile); } else if (strcmp(ev, "agent_run_start") == 0) { if (!in_run) { in_run = 1; run_start = t; s->turns++; } } else if (strcmp(ev, "agent_idle") == 0 || strcmp(ev, "agent_complete") == 0 || strcmp(ev, "session_end") == 0 || strcmp(ev, "session_compact") == 0) { if (in_run) { if (t > run_start) s->active_sec += (t - run_start); in_run = 0; } if (strcmp(ev, "agent_complete") == 0) s->is_active = 0; } else if (strcmp(ev, "user_message") == 0) { /* A user message ends idleness; the run starts right after. */ if (in_run) { if (t > run_start) s->active_sec += (t - run_start); in_run = 0; } } else if (strcmp(ev, "tool_use") == 0) { char tool[NAME_SZ] = {0}; if (json_get_str(line, "tool", tool, sizeof tool)) note_tool(s, tool); } } fclose(f); /* A run that never closed is still running: count up to the last event. */ if (in_run && s->last_ts > run_start) s->active_sec += (s->last_ts - run_start); } } if (!s->start_time[0] && s->first_ts) { /* Fall back to the first event timestamp rendered as text is unnecessary: * we only need a numeric base below. */ } if (!s->start_epoch) s->start_epoch = s->first_ts; /* --- durations --- */ if (s->start_epoch > 0) { long long end = s->last_ts > 0 ? s->last_ts : s->start_epoch; s->total_sec = end - s->start_epoch; if (s->total_sec < 0) s->total_sec = 0; } if (s->last_ts > s->first_ts && s->last_ts - s->first_ts > s->total_sec) s->total_sec = s->last_ts - s->first_ts; if (s->active_sec > s->total_sec) s->active_sec = s->total_sec; s->idle_sec = s->total_sec - s->active_sec; s->duty_pct = s->total_sec > 0 ? (100.0 * (double)s->active_sec / (double)s->total_sec) : 0.0; return 1; } /* Scan every root we were given and append sessions. Returns count. */ static int scan_sessions(const char *root, session_t *out, int max) { static char names[1024][NAME_SZ]; int n = sx_list_dirs(root, names, 1024); int i, kept = 0; for (i = 0; i < n && kept < max; i++) { session_t s; if (!load_session(root, names[i], &s)) continue; out[kept++] = s; } return kept; } /* ------------------------------------------------------------------ */ /* Profile / model aggregation */ /* ------------------------------------------------------------------ */ typedef struct { char label[64]; int sessions; long long active_sec; int turns; } bucket_t; static void bucket_add(bucket_t *b, int *count, int max, const char *label, long long active_sec, int turns) { int i; const char *key = (label && *label) ? label : "unknown"; for (i = 0; i < *count; i++) { if (strcmp(b[i].label, key) == 0) { b[i].sessions++; b[i].active_sec += active_sec; b[i].turns += turns; return; } } if (*count >= max) return; str_copy(b[*count].label, sizeof b[*count].label, key); b[*count].sessions = 1; b[*count].active_sec = active_sec; b[*count].turns = turns; (*count)++; } /* ------------------------------------------------------------------ */ /* Sorting */ /* ------------------------------------------------------------------ */ static int cmp_session_desc(const void *a, const void *b) { const session_t *x = (const session_t *)a; const session_t *y = (const session_t *)b; if (x->last_ts != y->last_ts) return x->last_ts < y->last_ts ? 1 : -1; return strcmp(x->id, y->id); } static int cmp_bucket_desc(const void *a, const void *b) { const bucket_t *x = (const bucket_t *)a; const bucket_t *y = (const bucket_t *)b; if (x->active_sec != y->active_sec) return x->active_sec < y->active_sec ? 1 : -1; return strcmp(x->label, y->label); } /* Sort tools by hit count while keeping the hits array aligned. */ static void sort_tools(session_t *s) { int i, j; for (i = 1; i < s->tool_count; i++) { tool_use_t key = s->tools[i]; int keyhits = s->tool_hits[i]; j = i - 1; while (j >= 0 && s->tool_hits[j] < keyhits) { s->tools[j + 1] = s->tools[j]; s->tool_hits[j + 1] = s->tool_hits[j]; j--; } s->tools[j + 1] = key; s->tool_hits[j + 1] = keyhits; } } /* ------------------------------------------------------------------ */ /* Aggregates */ /* ------------------------------------------------------------------ */ typedef struct { char root[PATH_SZ]; int root_ok; int count; long long total_sec; long long active_sec; long long idle_sec; double duty_pct; int turns; int active_now; int tool_events; session_t *sessions; } summary_t; static void build_summary(summary_t *sum, session_t *buf, int n) { int i, j; memset(sum, 0, sizeof *sum); sum->sessions = buf; sum->count = n; for (i = 0; i < n; i++) { session_t *s = &buf[i]; sum->total_sec += s->total_sec; sum->active_sec += s->active_sec; sum->turns += s->turns; if (s->is_active) sum->active_now++; sort_tools(s); for (j = 0; j < s->tool_count; j++) sum->tool_events += s->tool_hits[j]; } sum->idle_sec = sum->total_sec - sum->active_sec; if (sum->idle_sec < 0) sum->idle_sec = 0; sum->duty_pct = sum->total_sec > 0 ? (100.0 * (double)sum->active_sec / (double)sum->total_sec) : 0.0; } /* ------------------------------------------------------------------ */ /* JSON output */ /* ------------------------------------------------------------------ */ static void json_header(void) { fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); } static void print_session_obj(const session_t *s, int with_tools) { char tot[64], act[64], idl[64]; int i; format_duration(s->total_sec, tot, sizeof tot); format_duration(s->active_sec, act, sizeof act); format_duration(s->idle_sec, idl, sizeof idl); printf("{"); printf("\"id\":"); json_str(s->session_id); printf(",\"dir\":"); json_str(s->id); printf(",\"model\":"); json_str(s->model); printf(",\"provider\":"); json_str(s->provider); printf(",\"profile\":"); json_str(s->profile); printf(",\"branch\":"); json_str(s->branch); printf(",\"cwd\":"); json_str(s->cwd); printf(",\"start_time\":"); json_str(s->start_time); printf(",\"first_epoch\":%lld", s->first_ts); printf(",\"last_epoch\":%lld", s->last_ts); printf(",\"is_active\":%s", s->is_active ? "true" : "false"); printf(",\"total_sec\":%lld", s->total_sec); printf(",\"total_fmt\":"); json_str(tot); printf(",\"active_sec\":%lld", s->active_sec); printf(",\"active_fmt\":"); json_str(act); printf(",\"idle_sec\":%lld", s->idle_sec); printf(",\"idle_fmt\":"); json_str(idl); printf(",\"duty_cycle_pct\":%.2f", s->duty_pct); printf(",\"turns\":%d", s->turns); printf(",\"avg_turn_sec\":%.1f", s->turns > 0 ? ((double)s->active_sec / (double)s->turns) : 0.0); printf(",\"tokens\":{\"in\":%lld,\"out\":%lld,\"cache_read\":%lld,\"cache_write\":%lld}", s->in_tokens, s->out_tokens, s->cache_read, s->cache_write); if (with_tools) { printf(",\"tools\":["); for (i = 0; i < s->tool_count; i++) { if (i) printf(","); printf("{\"name\":"); json_str(s->tools[i].name); printf(",\"calls\":%d}", s->tool_hits[i]); } printf("]"); } printf("}"); } static void print_summary_json(const summary_t *sum) { bucket_t profiles[64], models[64]; int np = 0, nm = 0, i; char tot[64], act[64], idl[64]; for (i = 0; i < sum->count; i++) { const session_t *s = &sum->sessions[i]; bucket_add(profiles, &np, 64, s->profile[0] ? s->profile : "unknown", s->active_sec, s->turns); bucket_add(models, &nm, 64, s->model[0] ? s->model : "unknown", s->active_sec, s->turns); } qsort(profiles, (size_t)np, sizeof profiles[0], cmp_bucket_desc); qsort(models, (size_t)nm, sizeof models[0], cmp_bucket_desc); format_duration(sum->total_sec, tot, sizeof tot); format_duration(sum->active_sec, act, sizeof act); format_duration(sum->idle_sec, idl, sizeof idl); json_header(); printf("{"); printf("\"ok\":true"); printf(",\"plugin\":\"%s\"", PLUGIN_ID); printf(",\"version\":\"%s\"", PLUGIN_VER); printf(",\"sessions_root\":"); json_str(sum->root); printf(",\"root_found\":%s", sum->root_ok ? "true" : "false"); printf(",\"count\":%d", sum->count); printf(",\"active_now\":%d", sum->active_now); printf(",\"total_sec\":%lld", sum->total_sec); printf(",\"total_fmt\":"); json_str(tot); printf(",\"active_sec\":%lld", sum->active_sec); printf(",\"active_fmt\":"); json_str(act); printf(",\"idle_sec\":%lld", sum->idle_sec); printf(",\"idle_fmt\":"); json_str(idl); printf(",\"duty_cycle_pct\":%.2f", sum->duty_pct); printf(",\"turns\":%d", sum->turns); printf(",\"tool_events\":%d", sum->tool_events); printf(",\"profiles\":["); for (i = 0; i < np; i++) { if (i) printf(","); printf("{\"profile\":"); json_str(profiles[i].label); printf(",\"sessions\":%d,\"active_sec\":%lld,\"turns\":%d}", profiles[i].sessions, profiles[i].active_sec, profiles[i].turns); } printf("]"); printf(",\"models\":["); for (i = 0; i < nm; i++) { if (i) printf(","); printf("{\"model\":"); json_str(models[i].label); printf(",\"sessions\":%d,\"active_sec\":%lld,\"turns\":%d}", models[i].sessions, models[i].active_sec, models[i].turns); } printf("]"); printf(",\"sessions\":["); for (i = 0; i < sum->count; i++) { if (i) printf(","); print_session_obj(&sum->sessions[i], 1); } printf("]}\n"); } static void print_session_json(const session_t *s, const char *root) { char tot[64], act[64], idl[64]; format_duration(s->total_sec, tot, sizeof tot); format_duration(s->active_sec, act, sizeof act); format_duration(s->idle_sec, idl, sizeof idl); json_header(); printf("{\"ok\":true,\"plugin\":\"%s\",\"version\":\"%s\"", PLUGIN_ID, PLUGIN_VER); printf(",\"sessions_root\":"); json_str(root); printf(",\"session\":"); print_session_obj(s, 1); printf(",\"summary\":{\"total_sec\":%lld,\"total_fmt\":", s->total_sec); json_str(tot); printf(",\"active_sec\":%lld,\"active_fmt\":", s->active_sec); json_str(act); printf(",\"idle_sec\":%lld,\"idle_fmt\":", s->idle_sec); json_str(idl); printf(",\"duty_cycle_pct\":%.2f,\"turns\":%d}}\n", s->duty_pct, s->turns); } /* ------------------------------------------------------------------ */ /* HTML UI */ /* ------------------------------------------------------------------ */ static void html_head(int embed, const char *initial_id) { (void)embed; (void)initial_id; fputs( "Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n" "\r\n" "" "" "Session Analytics" SX_BOT_THEME_PREPAINT "" SX_BOT_THEME_HANDOFF "
" "
" "
" "" "Session Analytics" "idle" "
" "
" "" "" "" "
" "
" "
" "
Sessions
-
" "
 
" "
Wall clock
-
" "
All sessions combined
" "
Active work
-
" "
 
" "
Duty cycle
-
" "
 
" "
Turns
-
" "
 
" "
" "
" "

Active versus idle

" "
" "
" "Active (agent run)" "Idle (waiting)" "" "
" "

Profile usage by active time

" "
No data
" "

Model usage by active time

" "
No data
" "

Sessions

" "" "" "" "" "" "" "" "
SessionProfile / modelActiveWallDutyTurns
" "
" "

Selected session

" "
Select a row above to inspect tool usage.
" "
" "\n", stdout); } /* ------------------------------------------------------------------ */ /* main */ /* ------------------------------------------------------------------ */ int main(int argc, char **argv) { static session_t buf[MAX_SESSIONS]; static char names_big[1024][NAME_SZ]; summary_t sum; char root[PATH_SZ] = {0}; char action[32] = {0}; char sid[NAME_SZ] = {0}; const char *qs; int n, i; int root_ok; if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { puts("{\"name\":\"sessions\",\"desc\":\"Turn metrics\"}"); return 0; } require_node_auth(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; get_query_val(qs, "action", action, sizeof action); get_query_val(qs, "sid", sid, sizeof sid); if (!sid[0]) get_query_val(qs, "id", sid, sizeof sid); root_ok = resolve_sessions_root(root, sizeof root); /* ---------------- JSON modes ---------------- */ { char fmt[16] = {0}; int have_action = action[0] != '\0'; int have_format = get_query_val(qs, "format", fmt, sizeof fmt); if (have_action || have_format) { n = root_ok ? scan_sessions(root, buf, MAX_SESSIONS) : 0; (void)names_big; if (have_action && strcmp(action, "session") == 0) { session_t one; int found = 0; for (i = 0; i < n; i++) { if (strcmp(buf[i].id, sid) == 0 || strcmp(buf[i].session_id, sid) == 0) { found = 1; break; } } if (found) { one = buf[i]; sort_tools(&one); print_session_json(&one, root); } else if (sid[0]) { /* Allow inspecting a session older than the scan window. */ if (load_session(root, sid, &one)) { sort_tools(&one); print_session_json(&one, root); } else { json_header(); printf("{\"ok\":false,\"error\":\"session not found\",\"sid\":"); json_str(sid); printf(",\"sessions_root\":"); json_str(root); printf("}\n"); } } else { json_header(); printf("{\"ok\":false,\"error\":\"missing sid parameter\",\"sessions_root\":"); json_str(root); printf("}\n"); } return 0; } qsort(buf, (size_t)n, sizeof buf[0], cmp_session_desc); build_summary(&sum, buf, n); str_copy(sum.root, sizeof sum.root, root); sum.root_ok = root_ok; print_summary_json(&sum); return 0; } } /* ---------------- HTML ---------------- */ { int embed = 0; char ev[16] = {0}; if (get_query_val(qs, "embed", ev, sizeof ev)) { if (!strcmp(ev, "1") || !strcmp(ev, "true")) embed = 1; } html_head(embed, sid); html_script(sid); } return 0; }