@tokentop/ttop 0.8.0 → 0.9.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokentop/ttop",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
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",
@@ -41,7 +41,7 @@
41
41
  "@tokentop/agent-copilot-cli": "^1.0.0",
42
42
  "@tokentop/agent-cursor": "^1.2.0",
43
43
  "@tokentop/agent-gemini": "^1.0.0",
44
- "@tokentop/agent-opencode": "^1.0.0",
44
+ "@tokentop/agent-opencode": "^1.1.0",
45
45
  "@tokentop/agent-pi": "^0.2.0",
46
46
  "@tokentop/plugin-sdk": "^1.5.0",
47
47
  "react": "^19.0.0",
@@ -52,7 +52,8 @@
52
52
  "devDependencies": {
53
53
  "@biomejs/biome": "^2.4.2",
54
54
  "@types/bun": "latest",
55
- "@types/react": "^19.0.0"
55
+ "@types/react": "^19.0.0",
56
+ "typescript": "^5.9.3"
56
57
  },
57
58
  "keywords": [
58
59
  "ai",
@@ -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.8.0"; // x-release-please-version
1
+ export const VERSION = "0.9.0"; // x-release-please-version