shadok-ai 0.17.77 → 0.17.79

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/README.md CHANGED
@@ -185,6 +185,19 @@ Enter to skip; you can add it later from the web UI).
185
185
  nothing most of the day. The guard runs with the target agent's profile
186
186
  secrets, so an agent may put one only on itself (a person may guard any agent
187
187
  they can drive).
188
+ - **Per-agent stats** — the agent's ⋯ menu has a **📊 Stats** view: token usage
189
+ over the last hour / 24 h / 7 days / 30 days, split in a tooltip into input,
190
+ output, cache-write and cache-read, with a **notional cost** beside each window.
191
+ That cost is *notional* — shadok runs on your Claude **subscription**, not the
192
+ API, so nothing is billed per token; the figure is what those tokens would cost
193
+ at Anthropic API list prices, a way to compare agents rather than an invoice. It
194
+ also shows how long the agent has been **up** (session age, which survives
195
+ restarts) and when it **last respawned** (the running process's start). Scope is
196
+ the current session's transcript, read once, so opening it never drags. The
197
+ header **⋯** menu has the **instance-wide total** — the same windows summed over
198
+ every agent you can see (a member → their groups, admin → all). Running agents
199
+ are summed from memory and a dormant agent's transcript is read once and cached,
200
+ so the fleet total doesn't stall the cockpit either.
188
201
  - **Agents that report back** — an agent that launches other agents is told when
189
202
  each one finishes, blocks on a question, or dies. It hears about **its own**
190
203
  children and nothing else, so a busy channel never wakes it. What arrives is
package/dist/server.js CHANGED
@@ -43,8 +43,9 @@ import { relayOAuthCallback } from "./oauth-relay.js";
43
43
  import { openBrowser } from "./open-browser.js";
44
44
  import { parseSkillMeta, prepromptParts, prepromptFingerprint, stalenessReasons, LEGACY_FINGERPRINT, } from "./preprompt.js";
45
45
  import { ensureSpawnHelperExecutable } from "./node-pty-fix.js";
46
- import { TmuxPilot, tmuxAvailable, tmuxHasSession, tmuxKillSession, tmuxPaneCwd } from "./tmux.js";
47
- import { scanUsage, sessionFilePath, tailSession, clearTailPos, seedTailPos, isNothingToShow, newestTranscriptById } from "./tail.js";
46
+ import { TmuxPilot, tmuxAvailable, tmuxHasSession, tmuxKillSession, tmuxPaneCwd, tmuxSessionCreated } from "./tmux.js";
47
+ import { scanUsageSamples, scanUsageSamplesAsync, sessionFilePath, tailSession, clearTailPos, seedTailPos, isNothingToShow, newestTranscriptById } from "./tail.js";
48
+ import { windowStats } from "./token-stats.js";
48
49
  import { strandedWorktreePlan } from "./worktree-relocate.js";
49
50
  import { detectFork, rootIdOfFile } from "./forktrace.js";
50
51
  import { computePace, paceBlock, WINDOW_SEC } from "./pace.js";
@@ -2510,6 +2511,96 @@ app.get("/channels/glance", async (req, res) => {
2510
2511
  }));
2511
2512
  res.json(rows);
2512
2513
  });
2514
+ // ── Per-agent token + notional cost stats (the menu's "stats" view) ──────────
2515
+ // Rolling windows (1h/24h/7d/30d) of token usage and a NOTIONAL cost (API list
2516
+ // prices — shadok runs on the subscription, so nothing is billed per token; the
2517
+ // UI says so), plus "up since" (session age) and "last respawn" (the running
2518
+ // process's start). Served from the live `usageSamples` (no file read) when the
2519
+ // agent is loaded; otherwise scanned once from its transcript — scope stays the
2520
+ // CURRENT session file either way, which is why it cannot drag (no cross-session
2521
+ // sweep). Same per-session ACL as /crons.
2522
+ app.get("/channels/stats", (req, res) => {
2523
+ const id = String(req.query.id ?? "");
2524
+ if (!id)
2525
+ return res.status(400).json({ error: "id required" });
2526
+ if (!mayActFor(req, id))
2527
+ return res.status(403).json({ error: "forbidden" });
2528
+ const live = sessions.get(id);
2529
+ let samples;
2530
+ let upSince;
2531
+ let model;
2532
+ let lastRespawn;
2533
+ if (live) {
2534
+ samples = live.usageSamples.values();
2535
+ upSince = live.firstMessageAt;
2536
+ model = live.model ?? "";
2537
+ // A tmux pane's own creation time survives a server restart (true process
2538
+ // age); node-pty dies with the server, so the Live's build time is right.
2539
+ lastRespawn =
2540
+ live.pilot instanceof TmuxPilot ? (tmuxSessionCreated("sk-" + id) ?? live.spawnedAt) : live.spawnedAt;
2541
+ }
2542
+ else {
2543
+ const ch = loadChannels().find((c) => c.sessionId === id);
2544
+ if (!ch)
2545
+ return res.status(404).json({ error: "unknown session" });
2546
+ const scan = scanUsageSamples(sessionFilePath(ch.cwd, id, channelStateHome(ch)));
2547
+ samples = scan.samples.values();
2548
+ upSince = scan.firstAt;
2549
+ model = ch.model ?? "";
2550
+ lastRespawn = null; // not running — there is no live process to date
2551
+ }
2552
+ const windows = windowStats(samples, Date.now());
2553
+ res.json({ windows, upSince, lastRespawn, model });
2554
+ });
2555
+ // The instance-wide total, for the header ⋯ menu's "Instance stats". A dormant
2556
+ // agent's scan is cached by (mtime,size), so re-opening only stat()s unchanged
2557
+ // files; a LIVE agent is read from memory. Invalidated when the transcript grows.
2558
+ const statsScanCache = new Map();
2559
+ // Bounded on purpose: the entries hold one object PER MESSAGE of a transcript,
2560
+ // the server runs for weeks, and nothing ever removed a file that stopped
2561
+ // existing (a closed agent, a pruned worktree) — so an unbounded map here grows
2562
+ // with every agent that ever lived on the instance. Insertion order gives a
2563
+ // plain FIFO eviction; an evicted file is simply re-scanned next time.
2564
+ const STATS_CACHE_MAX = 64;
2565
+ async function channelStatsSamples(ch) {
2566
+ const live = sessions.get(ch.sessionId);
2567
+ if (live)
2568
+ return live.usageSamples.values(); // in memory — no I/O
2569
+ const file = sessionFilePath(ch.cwd, ch.sessionId, channelStateHome(ch));
2570
+ let st;
2571
+ try {
2572
+ st = await fs.promises.stat(file);
2573
+ }
2574
+ catch {
2575
+ return [];
2576
+ }
2577
+ const cached = statsScanCache.get(file);
2578
+ if (cached && cached.mtime === st.mtimeMs && cached.size === st.size)
2579
+ return cached.samples.values();
2580
+ const { samples } = await scanUsageSamplesAsync(file);
2581
+ statsScanCache.delete(file); // re-insert, so a refreshed file is the newest entry
2582
+ if (statsScanCache.size >= STATS_CACHE_MAX) {
2583
+ const oldest = statsScanCache.keys().next();
2584
+ if (!oldest.done)
2585
+ statsScanCache.delete(oldest.value);
2586
+ }
2587
+ statsScanCache.set(file, { mtime: st.mtimeMs, size: st.size, samples });
2588
+ return samples.values();
2589
+ }
2590
+ // Sum of every agent the caller may SEE (a member → their groups; admin → all) —
2591
+ // so the total means the same thing per viewer. Reads happen async and one agent
2592
+ // at a time, so the single-threaded server stays responsive even on a big fleet;
2593
+ // the per-file cache makes a repeat open cheap.
2594
+ app.get("/instance/stats", async (req, res) => {
2595
+ const box = restrictedBoxOf(req);
2596
+ const visible = visibleChannels(loadChannels(), loadGroups(), viewerFor(currentAccount(req))).filter((ch) => !box || ownedByPeer(ch, box));
2597
+ const all = [];
2598
+ for (const ch of visible) {
2599
+ for (const s of await channelStatsSamples(ch))
2600
+ all.push(s);
2601
+ }
2602
+ res.json({ windows: windowStats(all, Date.now()), agents: visible.length });
2603
+ });
2513
2604
  // ── Crons (scheduled channel prompts) ───────────────────────────────────────
2514
2605
  // Scoped like every other per-session read (invariant 60): a cron carries its
2515
2606
  // prompt and its guard command, i.e. another group's monitoring logic.
@@ -7967,8 +8058,11 @@ group = null) {
7967
8058
  // server's — so the content tail / history must read from there (invariant:
7968
8059
  // all content comes from the .jsonl). `agentStateHome` is the one answer.
7969
8060
  const transcriptHome = agentStateHome(user);
7970
- // Resumed sessions start with what the transcript already consumed.
7971
- const seededUsage = scanUsage(sessionFilePath(cwd, id, transcriptHome));
8061
+ // Resumed sessions start with what the transcript already consumed. One scan
8062
+ // feeds both the context gauge (last message's usage) and the stats windows
8063
+ // (every message's usage + time + model), so a huge file is read once here.
8064
+ const { samples: seededSamples, firstAt: seededFirstAt } = scanUsageSamples(sessionFilePath(cwd, id, transcriptHome));
8065
+ const seededUsage = new Map([...seededSamples].map(([mid, s]) => [mid, s.usage]));
7972
8066
  const backend = sessionBackend(profile, group);
7973
8067
  const contextWindow = assumedContextWindow(profile, model, group);
7974
8068
  const s = {
@@ -8003,6 +8097,9 @@ group = null) {
8003
8097
  worktree,
8004
8098
  idleTimer: null,
8005
8099
  usage: seededUsage,
8100
+ usageSamples: seededSamples,
8101
+ firstMessageAt: seededFirstAt,
8102
+ spawnedAt: Date.now(),
8006
8103
  retryTimer: null,
8007
8104
  retryCount: 0,
8008
8105
  errorsAtTurnStart: [],
@@ -8094,6 +8191,22 @@ function startContentTail(s) {
8094
8191
  });
8095
8192
  else if (e.kind === "usage") {
8096
8193
  s.usage.set(e.messageId, e.usage);
8194
+ // Same message, richer record for the stats windows. The live `usage`
8195
+ // event carries no timestamp (unlike a seeded line), so a message seen for
8196
+ // the FIRST time is stamped "now" — it was just written; a growing partial
8197
+ // keeps that first instant and only refreshes its counts/model.
8198
+ // The model comes from the EVENT (the transcript's resolved name), never
8199
+ // from `s.model`: that field holds the model SETTING the process was given
8200
+ // ("opus", or null for the default), and `MODEL_PRICING` is keyed on
8201
+ // resolved names — so pricing from it left every message written by the
8202
+ // RUNNING process unpriced, i.e. exactly the 1h window a user looks at.
8203
+ // Invariant 22's lesson, one subsystem over. Falls back to the setting
8204
+ // only when a line carries no model at all.
8205
+ s.usageSamples.set(e.messageId, {
8206
+ at: s.usageSamples.get(e.messageId)?.at ?? Date.now(),
8207
+ model: e.model || s.model || "",
8208
+ usage: e.usage,
8209
+ });
8097
8210
  broadcast(s, { type: "tokens", tokens: tokenTotals(s) });
8098
8211
  // Context fill comes from THIS message, not from the running totals: the
8099
8212
  // window holds one request's prompt, while the totals accumulate the whole