@tokentop/ttop 0.7.0 → 0.8.1

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
@@ -46,7 +46,7 @@ That's tokentop.
46
46
 
47
47
  - **Real-time dashboard** — Live token counts, costs, burn rate, and activity sparklines
48
48
  - **11 providers** — Anthropic, OpenAI, Google Gemini, GitHub Copilot, Codex, Perplexity, Antigravity, MiniMax, Zai, OpenCode Zen, Chutes
49
- - **7 coding agents** — Claude Code, OpenCode, Cursor, Copilot CLI, Gemini CLI, Antigravity, and Windsurf. See every session with model, tokens, cost, and duration
49
+ - **8 coding agents** — Claude Code, OpenCode, Cursor, Copilot CLI, Gemini CLI, Antigravity, Windsurf, and Pi. See every session with model, tokens, cost, and duration
50
50
  - **Budget guardrails** — Daily, weekly, and monthly limits with visual warnings at limit percentages you set
51
51
  - **Smart sidebar** — Adaptive panel that breaks down spending by model, project, or agent
52
52
  - **Efficiency insights** — Cache leverage, output verbosity, and cost-per-request analysis to help you spend less
@@ -144,7 +144,7 @@ tokentop has 4 main views, switchable with `1`–`4`:
144
144
 
145
145
  ## Agents
146
146
 
147
- tokentop tracks sessions from 7 coding agents. Each agent is a standalone plugin — built-in agents ship with the app, community agents install from npm.
147
+ tokentop tracks sessions from 8 coding agents. Each agent is a standalone plugin — built-in agents ship with the app, community agents install from npm.
148
148
 
149
149
  | Agent | What it tracks | Plugin |
150
150
  |-------|---------------|--------|
@@ -155,6 +155,7 @@ tokentop tracks sessions from 7 coding agents. Each agent is a standalone plugin
155
155
  | [Gemini CLI](https://tokentop.app/docs/agents/gemini-cli/) | Sessions, Google OAuth | [`@tokentop/agent-gemini`](https://github.com/tokentopapp/agent-gemini) |
156
156
  | [Antigravity](https://tokentop.app/docs/agents/antigravity/) | Sessions, Google OAuth | [`@tokentop/agent-gemini`](https://github.com/tokentopapp/agent-gemini) |
157
157
  | [Windsurf](https://tokentop.app/docs/agents/windsurf/) | Sessions, Codeium auth | [`@tokentop/agent-windsurf`](https://github.com/tokentopapp/agent-windsurf) |
158
+ | [Pi](https://github.com/tokentopapp/agent-pi) | Sessions, subagent usage, Pi-based agents such as Prime | [`@tokentop/agent-pi`](https://github.com/tokentopapp/agent-pi) |
158
159
 
159
160
  All agents are auto-discovered — if you have the tool installed, tokentop finds it. See the [agent docs](https://tokentop.app/docs/agents/) for details.
160
161
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokentop/ttop",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "description": "Real-time AI token usage monitor - htop for your API costs",
5
5
  "author": "Nigel Bazzeghin <nbazzeghin@gmail.com>",
6
6
  "license": "MIT",
@@ -11,6 +11,7 @@
11
11
  "files": [
12
12
  "bin/",
13
13
  "src/",
14
+ "tsconfig.json",
14
15
  "package.json",
15
16
  "README.md",
16
17
  "LICENSE"
@@ -34,16 +35,18 @@
34
35
  "analytics": "bun .opencode/skills/analytics/scripts/analytics.ts"
35
36
  },
36
37
  "dependencies": {
37
- "@opentui/core": "0.1.98",
38
- "@opentui/react": "0.1.98",
38
+ "@opentui/core": "0.5.14",
39
+ "@opentui/react": "0.5.14",
39
40
  "@tokentop/agent-claude-code": "^1.1.0",
40
41
  "@tokentop/agent-copilot-cli": "^1.0.0",
41
42
  "@tokentop/agent-cursor": "^1.2.0",
42
43
  "@tokentop/agent-gemini": "^1.0.0",
43
44
  "@tokentop/agent-opencode": "^1.0.0",
45
+ "@tokentop/agent-pi": "^0.2.0",
44
46
  "@tokentop/plugin-sdk": "^1.5.0",
45
47
  "react": "^19.0.0",
46
- "react-devtools-core": "^7.0.1",
48
+ "react-devtools-core": "^8.0.0",
49
+ "web-tree-sitter": "0.25.10",
47
50
  "zod": "^4.0.0"
48
51
  },
49
52
  "devDependencies": {
@@ -73,6 +76,6 @@
73
76
  "bun": ">=1.0.0"
74
77
  },
75
78
  "overrides": {
76
- "@types/node": "^25.0.0"
79
+ "@types/node": "^26.0.0"
77
80
  }
78
81
  }
@@ -3,3 +3,4 @@ export { default as copilotCliAgentPlugin } from "@tokentop/agent-copilot-cli";
3
3
  export { default as cursorAgentPlugin } from "@tokentop/agent-cursor";
4
4
  export { default as geminiAgentPlugin } from "@tokentop/agent-gemini";
5
5
  export { default as opencodeAgentPlugin } from "@tokentop/agent-opencode";
6
+ export { default as piAgentPlugin } from "@tokentop/agent-pi";
@@ -0,0 +1,24 @@
1
+ import { expect, test } from "bun:test";
2
+ import type { PluginHttpClient, ProviderFetchContext } from "@tokentop/plugin-sdk";
3
+ import { perplexityPlugin } from "./perplexity.ts";
4
+
5
+ test("attributes Perplexity API requests", async () => {
6
+ let requestHeaders = new Headers();
7
+ const http: PluginHttpClient = {
8
+ fetch: async (_url, init) => {
9
+ requestHeaders = new Headers(init?.headers);
10
+ return new Response(null, { status: 401 });
11
+ },
12
+ };
13
+ const context = {
14
+ credentials: { apiKey: "test-key", source: "env" },
15
+ http,
16
+ logger: { debug() {}, info() {}, warn() {}, error() {} },
17
+ config: {},
18
+ signal: AbortSignal.timeout(5000),
19
+ } satisfies ProviderFetchContext;
20
+
21
+ await perplexityPlugin.fetchUsage(context);
22
+
23
+ expect(requestHeaders.get("x-pplx-integration")).toBe("tokentop");
24
+ });
@@ -105,6 +105,7 @@ export const perplexityPlugin: ProviderPlugin = {
105
105
  headers: {
106
106
  Authorization: `Bearer ${credentials.apiKey}`,
107
107
  "Content-Type": "application/json",
108
+ "X-Pplx-Integration": "tokentop",
108
109
  },
109
110
  body: JSON.stringify({
110
111
  model: "sonar",
@@ -1,21 +1,41 @@
1
1
  import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
2
  import { PluginPermissionError } from "@tokentop/plugin-sdk";
3
+ import { clearCache, getModelPricing } from "../pricing/models-dev.ts";
3
4
  import {
4
5
  deepFreeze,
5
6
  getActivePluginGuard,
6
7
  installGlobalFetchGuard,
7
8
  runInPluginGuard,
9
+ runOutsidePluginGuard,
8
10
  } from "./sandbox-guard.ts";
9
11
 
10
12
  const originalFetch = globalThis.fetch;
11
13
  const fetchCalls: string[] = [];
14
+ let mockResponseBody = "ok";
15
+
16
+ function makeModelsDevResponse() {
17
+ return {
18
+ anthropic: {
19
+ id: "anthropic",
20
+ name: "Anthropic",
21
+ models: {
22
+ "claude-sonnet-4-20250514": {
23
+ id: "claude-sonnet-4-20250514",
24
+ name: "Claude Sonnet 4",
25
+ family: "claude",
26
+ cost: { input: 3, output: 15 },
27
+ },
28
+ },
29
+ },
30
+ };
31
+ }
12
32
 
13
33
  const mockFetch: typeof fetch = Object.assign(
14
34
  (input: string | URL | Request, _init?: RequestInit): Promise<Response> => {
15
35
  const url =
16
36
  typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
17
37
  fetchCalls.push(url);
18
- return Promise.resolve(new Response("ok", { status: 200 }));
38
+ return Promise.resolve(new Response(mockResponseBody, { status: 200 }));
19
39
  },
20
40
  { preconnect: originalFetch.preconnect },
21
41
  );
@@ -115,6 +135,22 @@ describe("runInPluginGuard and getActivePluginGuard", () => {
115
135
  expect(contexts.inner?.pluginId).toBe("inner-plugin");
116
136
  expect(contexts.outerAfter?.pluginId).toBe("outer-plugin");
117
137
  });
138
+
139
+ test("trusted host work temporarily exits and restores plugin context", async () => {
140
+ const contexts = await runInPluginGuard("outer-plugin", {}, async () => {
141
+ const before = getActivePluginGuard();
142
+ const outside = await runOutsidePluginGuard(async () => {
143
+ await Promise.resolve();
144
+ return getActivePluginGuard();
145
+ });
146
+
147
+ return { before, outside, after: getActivePluginGuard() };
148
+ });
149
+
150
+ expect(contexts.before?.pluginId).toBe("outer-plugin");
151
+ expect(contexts.outside).toBeUndefined();
152
+ expect(contexts.after?.pluginId).toBe("outer-plugin");
153
+ });
118
154
  });
119
155
 
120
156
  describe("installGlobalFetchGuard", () => {
@@ -185,4 +221,89 @@ describe("installGlobalFetchGuard", () => {
185
221
  expect(fetchCalls[0]).toContain("allowed.example/path");
186
222
  expect(fetchCalls[1]).toContain("api.allowed.example/path");
187
223
  });
224
+
225
+ test("direct plugin requests to models.dev remain blocked", () => {
226
+ fetchCalls.length = 0;
227
+
228
+ expect(() => {
229
+ runInPluginGuard(
230
+ "anthropic",
231
+ {
232
+ network: {
233
+ enabled: true,
234
+ allowedDomains: ["api.anthropic.com"],
235
+ },
236
+ },
237
+ () => {
238
+ void fetch("https://models.dev/api.json");
239
+ },
240
+ );
241
+ }).toThrow(PluginPermissionError);
242
+
243
+ expect(fetchCalls).toHaveLength(0);
244
+ });
245
+
246
+ test("host pricing refresh bypasses plugin restrictions without logging a denial", async () => {
247
+ clearCache();
248
+ fetchCalls.length = 0;
249
+ const originalResponseBody = mockResponseBody;
250
+ mockResponseBody = JSON.stringify(makeModelsDevResponse());
251
+ const errors: Parameters<typeof console.error>[] = [];
252
+ const originalError = console.error;
253
+ console.error = (...args: Parameters<typeof console.error>) => {
254
+ errors.push(args);
255
+ };
256
+
257
+ try {
258
+ const result = await runInPluginGuard(
259
+ "anthropic",
260
+ {
261
+ network: {
262
+ enabled: true,
263
+ allowedDomains: ["api.anthropic.com"],
264
+ },
265
+ },
266
+ () => getModelPricing("anthropic", "claude-sonnet-4-20250514"),
267
+ );
268
+
269
+ expect(result?.input).toBe(3);
270
+ expect(result?.output).toBe(15);
271
+ expect(fetchCalls).toEqual(["https://models.dev/api.json"]);
272
+ expect(errors).toHaveLength(0);
273
+ } finally {
274
+ console.error = originalError;
275
+ mockResponseBody = originalResponseBody;
276
+ clearCache();
277
+ }
278
+ });
279
+
280
+ test("concurrent pricing refreshes share one models.dev request", async () => {
281
+ clearCache();
282
+ fetchCalls.length = 0;
283
+ const originalResponseBody = mockResponseBody;
284
+ mockResponseBody = JSON.stringify(makeModelsDevResponse());
285
+
286
+ try {
287
+ const results = await runInPluginGuard(
288
+ "anthropic",
289
+ {
290
+ network: {
291
+ enabled: true,
292
+ allowedDomains: ["api.anthropic.com"],
293
+ },
294
+ },
295
+ () =>
296
+ Promise.all([
297
+ getModelPricing("anthropic", "claude-sonnet-4-20250514"),
298
+ getModelPricing("anthropic", "claude-sonnet-4-20250514"),
299
+ ]),
300
+ );
301
+
302
+ expect(results.map((pricing) => pricing?.input)).toEqual([3, 3]);
303
+ expect(fetchCalls).toEqual(["https://models.dev/api.json"]);
304
+ } finally {
305
+ mockResponseBody = originalResponseBody;
306
+ clearCache();
307
+ }
308
+ });
188
309
  });
@@ -47,6 +47,15 @@ export function runInPluginGuard<T>(
47
47
  return pluginGuardStorage.run({ pluginId, permissions }, fn);
48
48
  }
49
49
 
50
+ /**
51
+ * Run trusted host code outside the active plugin permission context.
52
+ *
53
+ * @internal Only call from application-owned code; never expose this to plugins.
54
+ */
55
+ export function runOutsidePluginGuard<T>(fn: () => T): T {
56
+ return pluginGuardStorage.exit(fn);
57
+ }
58
+
50
59
  // ---------------------------------------------------------------------------
51
60
  // Global fetch guard
52
61
  // ---------------------------------------------------------------------------
@@ -1,9 +1,14 @@
1
- import { afterEach, describe, expect, mock, test } from "bun:test";
1
+ import { afterAll, afterEach, describe, expect, mock, test } from "bun:test";
2
2
  import { clearCache, getModelPricing, getProviderModels } from "./models-dev.ts";
3
3
 
4
+ const originalFetch = globalThis.fetch;
4
5
  const mockFetch = mock(() => Promise.resolve(new Response("null")));
5
6
  globalThis.fetch = mockFetch as unknown as typeof fetch;
6
7
 
8
+ afterAll(() => {
9
+ globalThis.fetch = originalFetch;
10
+ });
11
+
7
12
  function makeApiResponse(costOverride?: Record<string, unknown>) {
8
13
  return {
9
14
  anthropic: {
@@ -1,4 +1,5 @@
1
1
  import type { ModelPricing } from "@tokentop/plugin-sdk";
2
+ import { runOutsidePluginGuard } from "../plugins/sandbox-guard.ts";
2
3
 
3
4
  const MODELS_DEV_API = "https://models.dev/api.json";
4
5
  const CACHE_TTL_MS = 3600000;
@@ -37,23 +38,39 @@ interface CachedData {
37
38
  }
38
39
 
39
40
  let cache: CachedData | null = null;
41
+ let inFlightFetch: Promise<ModelsDevResponse | null> | null = null;
40
42
 
41
43
  export async function fetchModelsDevData(): Promise<ModelsDevResponse | null> {
42
44
  if (cache && Date.now() - cache.fetchedAt < CACHE_TTL_MS) {
43
45
  return cache.data;
44
46
  }
45
47
 
46
- try {
47
- const response = await fetch(MODELS_DEV_API);
48
- if (!response.ok) {
48
+ if (inFlightFetch) {
49
+ return inFlightFetch;
50
+ }
51
+
52
+ const request = (async (): Promise<ModelsDevResponse | null> => {
53
+ try {
54
+ const response = await runOutsidePluginGuard(() => fetch(MODELS_DEV_API));
55
+ if (!response.ok) {
56
+ return cache?.data ?? null;
57
+ }
58
+
59
+ const data = (await response.json()) as ModelsDevResponse;
60
+ cache = { data, fetchedAt: Date.now() };
61
+ return data;
62
+ } catch {
49
63
  return cache?.data ?? null;
50
64
  }
65
+ })();
66
+ inFlightFetch = request;
51
67
 
52
- const data = (await response.json()) as ModelsDevResponse;
53
- cache = { data, fetchedAt: Date.now() };
54
- return data;
55
- } catch {
56
- return cache?.data ?? null;
68
+ try {
69
+ return await request;
70
+ } finally {
71
+ if (inFlightFetch === request) {
72
+ inFlightFetch = null;
73
+ }
57
74
  }
58
75
  }
59
76
 
@@ -1,10 +1,10 @@
1
1
  import type { ScrollBoxRenderable } from "@opentui/core";
2
2
  import { useTerminalDimensions } from "@opentui/react";
3
- import { forwardRef, memo, type Ref, useCallback, useRef } from "react";
3
+ import { forwardRef, memo, type Ref, useCallback } from "react";
4
4
  import type { AgentSessionAggregate } from "../../agents/types.ts";
5
5
  import { useColors } from "../contexts/ThemeContext.tsx";
6
6
  import { useAnimatedValue } from "../hooks/useAnimatedValue.ts";
7
- import { applyEntranceFade, useEntranceAnimation } from "../hooks/useEntranceAnimation.ts";
7
+ import { applyEntranceFade } from "../hooks/useEntranceAnimation.ts";
8
8
  import { useExitAnimation } from "../hooks/useExitAnimation.ts";
9
9
  import { interpolateColor, useValueFlash } from "../hooks/useValueFlash.ts";
10
10
  import type { SortDirection, SortField } from "../types/sort.ts";
@@ -124,7 +124,6 @@ interface SessionRowProps {
124
124
  getProviderColor: (id: string) => string;
125
125
  isExiting?: boolean;
126
126
  exitIntensity?: number;
127
- skipEntrance?: boolean;
128
127
  terminalWidth: number;
129
128
  }
130
129
 
@@ -144,18 +143,11 @@ const SessionRow = memo(function SessionRow({
144
143
  getProviderColor,
145
144
  isExiting,
146
145
  exitIntensity,
147
- skipEntrance,
148
146
  terminalWidth,
149
147
  }: SessionRowProps) {
150
148
  const colors = useColors();
151
149
  const isActive = session.status === "active";
152
- const entranceIntensity = useEntranceAnimation({ durationMs: 500 });
153
- const skipRef = useRef(skipEntrance);
154
- const currentIntensity = isExiting
155
- ? (exitIntensity ?? 0)
156
- : skipRef.current
157
- ? 1
158
- : entranceIntensity;
150
+ const currentIntensity = isExiting ? (exitIntensity ?? 0) : 1;
159
151
 
160
152
  const effectiveTokens = session.totals.input + session.totals.output;
161
153
  const cacheRead = session.totals.cacheRead ?? 0;
@@ -399,7 +391,7 @@ export const SessionsTable = forwardRef(function SessionsTable(
399
391
  : Math.max(1, tableInner - narrowFixed);
400
392
 
401
393
  const getSessionKey = useCallback((s: AgentSessionAggregate) => s.sessionId, []);
402
- const { items: animatedSessions, isBulkChange } = useExitAnimation(sessions, {
394
+ const { items: animatedSessions } = useExitAnimation(sessions, {
403
395
  durationMs: 500,
404
396
  getKey: getSessionKey,
405
397
  bulkThreshold: 100,
@@ -556,7 +548,6 @@ export const SessionsTable = forwardRef(function SessionsTable(
556
548
  getProviderColor={getProviderColor}
557
549
  isExiting={entry.isExiting}
558
550
  exitIntensity={entry.exitIntensity}
559
- skipEntrance={isBulkChange}
560
551
  terminalWidth={terminalWidth}
561
552
  />
562
553
  );
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const VERSION = "0.7.0"; // x-release-please-version
1
+ export const VERSION = "0.8.1"; // x-release-please-version
package/tsconfig.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "compilerOptions": {
3
+ // Environment setup
4
+ "lib": ["ESNext"],
5
+ "target": "ESNext",
6
+ "module": "ESNext",
7
+ "moduleDetection": "force",
8
+
9
+ // OpenTUI React JSX configuration
10
+ "jsx": "react-jsx",
11
+ "jsxImportSource": "@opentui/react",
12
+
13
+ // Bundler mode
14
+ "moduleResolution": "bundler",
15
+ "allowImportingTsExtensions": true,
16
+ "verbatimModuleSyntax": true,
17
+ "noEmit": true,
18
+ "allowJs": true,
19
+
20
+ // Strict mode
21
+ "strict": true,
22
+ "skipLibCheck": true,
23
+ "noFallthroughCasesInSwitch": true,
24
+ "noUncheckedIndexedAccess": true,
25
+ "noImplicitOverride": true,
26
+
27
+ // Path mapping
28
+ "paths": {
29
+ "@/*": ["./src/*"],
30
+ "@plugins/*": ["./src/plugins/*"],
31
+ "@tui/*": ["./src/tui/*"],
32
+ "@utils/*": ["./src/utils/*"]
33
+ },
34
+
35
+ // Additional checks
36
+ "noUnusedLocals": true,
37
+ "noUnusedParameters": true,
38
+ "exactOptionalPropertyTypes": true,
39
+ "noPropertyAccessFromIndexSignature": false
40
+ },
41
+ "include": ["src/**/*", "templates/**/*"],
42
+ "exclude": ["dist", "node_modules"]
43
+ }