shadok-ai 0.17.76 → 0.17.78

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,15 @@ 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.
188
197
  - **Agents that report back** — an agent that launches other agents is told when
189
198
  each one finishes, blocks on a question, or dies. It hears about **its own**
190
199
  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, 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,47 @@ 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
+ });
2513
2555
  // ── Crons (scheduled channel prompts) ───────────────────────────────────────
2514
2556
  // Scoped like every other per-session read (invariant 60): a cron carries its
2515
2557
  // prompt and its guard command, i.e. another group's monitoring logic.
@@ -7967,8 +8009,11 @@ group = null) {
7967
8009
  // server's — so the content tail / history must read from there (invariant:
7968
8010
  // all content comes from the .jsonl). `agentStateHome` is the one answer.
7969
8011
  const transcriptHome = agentStateHome(user);
7970
- // Resumed sessions start with what the transcript already consumed.
7971
- const seededUsage = scanUsage(sessionFilePath(cwd, id, transcriptHome));
8012
+ // Resumed sessions start with what the transcript already consumed. One scan
8013
+ // feeds both the context gauge (last message's usage) and the stats windows
8014
+ // (every message's usage + time + model), so a huge file is read once here.
8015
+ const { samples: seededSamples, firstAt: seededFirstAt } = scanUsageSamples(sessionFilePath(cwd, id, transcriptHome));
8016
+ const seededUsage = new Map([...seededSamples].map(([mid, s]) => [mid, s.usage]));
7972
8017
  const backend = sessionBackend(profile, group);
7973
8018
  const contextWindow = assumedContextWindow(profile, model, group);
7974
8019
  const s = {
@@ -8003,6 +8048,9 @@ group = null) {
8003
8048
  worktree,
8004
8049
  idleTimer: null,
8005
8050
  usage: seededUsage,
8051
+ usageSamples: seededSamples,
8052
+ firstMessageAt: seededFirstAt,
8053
+ spawnedAt: Date.now(),
8006
8054
  retryTimer: null,
8007
8055
  retryCount: 0,
8008
8056
  errorsAtTurnStart: [],
@@ -8094,6 +8142,22 @@ function startContentTail(s) {
8094
8142
  });
8095
8143
  else if (e.kind === "usage") {
8096
8144
  s.usage.set(e.messageId, e.usage);
8145
+ // Same message, richer record for the stats windows. The live `usage`
8146
+ // event carries no timestamp (unlike a seeded line), so a message seen for
8147
+ // the FIRST time is stamped "now" — it was just written; a growing partial
8148
+ // keeps that first instant and only refreshes its counts/model.
8149
+ // The model comes from the EVENT (the transcript's resolved name), never
8150
+ // from `s.model`: that field holds the model SETTING the process was given
8151
+ // ("opus", or null for the default), and `MODEL_PRICING` is keyed on
8152
+ // resolved names — so pricing from it left every message written by the
8153
+ // RUNNING process unpriced, i.e. exactly the 1h window a user looks at.
8154
+ // Invariant 22's lesson, one subsystem over. Falls back to the setting
8155
+ // only when a line carries no model at all.
8156
+ s.usageSamples.set(e.messageId, {
8157
+ at: s.usageSamples.get(e.messageId)?.at ?? Date.now(),
8158
+ model: e.model || s.model || "",
8159
+ usage: e.usage,
8160
+ });
8097
8161
  broadcast(s, { type: "tokens", tokens: tokenTotals(s) });
8098
8162
  // Context fill comes from THIS message, not from the running totals: the
8099
8163
  // window holds one request's prompt, while the totals accumulate the whole