@marcosgilf/pi-session 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Marcos Gil
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,17 @@
1
- # Temporary Holding Version
1
+ # pi-session
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Show context percentage/window in Pi's default footer and detailed token, cache, cost, and context usage in a modal.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pi install npm:@marcosgilf/pi-session
9
+ ```
10
+
11
+ - When installed alone, the default footer shows session context use.
12
+ - `/session-usage` opens detailed session information.
13
+ - Command+Shift+S (`super+shift+s`) opens the same modal.
14
+ - In modal: `c` copies full summary; Ctrl/Cmd+C copies selected text; click outside closes.
15
+ - Install `@marcosgilf/pi-footer` to place session context before skill statuses and Copilot usage beside the model. It loads this extension as a dependency; do not install both packages separately.
16
+
17
+ Pi extensions run with Pi's operating-system permissions. Review package source before installing.
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@marcosgilf/pi-session",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Session token, cost, cache, and context usage for Pi.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "private": false,
8
+ "keywords": [
9
+ "pi-package",
10
+ "pi-extension",
11
+ "pi",
12
+ "session",
13
+ "usage",
14
+ "tokens"
15
+ ],
16
+ "files": [
17
+ "src",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "exports": {
22
+ ".": "./src/index.ts",
23
+ "./core": "./src/core.ts",
24
+ "./events": "./src/events.ts"
25
+ },
26
+ "pi": {
27
+ "extensions": [
28
+ "./src/index.ts"
29
+ ]
30
+ },
31
+ "dependencies": {
32
+ "@marcosgilf/pi-modal": "^0.1.0"
33
+ },
34
+ "peerDependencies": {
35
+ "@earendil-works/pi-coding-agent": "*",
36
+ "@earendil-works/pi-tui": "*"
37
+ },
38
+ "scripts": {
39
+ "typecheck": "tsc --noEmit -p tsconfig.json"
40
+ }
41
+ }
package/src/core.ts ADDED
@@ -0,0 +1,124 @@
1
+ type Usage = {
2
+ input?: number;
3
+ output?: number;
4
+ cacheRead?: number;
5
+ cacheWrite?: number;
6
+ cost?: { total?: number };
7
+ };
8
+
9
+ type UsageEntry = {
10
+ type?: string;
11
+ provider?: string;
12
+ usage?: Usage;
13
+ message?: { role?: string; provider?: string; usage?: Usage };
14
+ };
15
+
16
+ export type SessionUsage = {
17
+ input: number;
18
+ output: number;
19
+ cacheRead: number;
20
+ cacheWrite: number;
21
+ cost: number;
22
+ latestCacheHitRate?: number;
23
+ };
24
+
25
+ export type ContextUsageStyle = "error" | "warning" | "text" | "dim";
26
+
27
+ export function formatTokens(tokens: number): string {
28
+ if (tokens < 1_000) return tokens.toString();
29
+ if (tokens < 10_000) return `${(tokens / 1_000).toFixed(1)}k`;
30
+ if (tokens < 1_000_000) return `${Math.round(tokens / 1_000)}k`;
31
+ if (tokens < 10_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
32
+ return `${Math.round(tokens / 1_000_000)}M`;
33
+ }
34
+
35
+ export function getContextUsageStyle(percent: number | null): ContextUsageStyle {
36
+ return percent === null ? "dim" : percent > 90 ? "error" : percent > 70 ? "warning" : "text";
37
+ }
38
+
39
+ export function formatContextUsageIndicator(
40
+ percent: number | null,
41
+ contextWindow: number,
42
+ ): {
43
+ text: string;
44
+ style: ContextUsageStyle;
45
+ } {
46
+ const label = percent === null ? "?" : `${percent.toFixed(1)}%`;
47
+ return { text: `${label}/${formatTokens(contextWindow)}`, style: getContextUsageStyle(percent) };
48
+ }
49
+
50
+ export function formatSessionUsageSummary(
51
+ stats: SessionUsage,
52
+ context?: { percent: number | null; contextWindow: number },
53
+ options: { subscription?: boolean; autoCompaction?: boolean } = {},
54
+ ): string[] {
55
+ const tokens = [
56
+ stats.input > 0 ? `↑${formatTokens(stats.input)}` : undefined,
57
+ stats.output > 0 ? `↓${formatTokens(stats.output)}` : undefined,
58
+ stats.cacheRead > 0 ? `R${formatTokens(stats.cacheRead)}` : undefined,
59
+ stats.cacheWrite > 0 ? `W${formatTokens(stats.cacheWrite)}` : undefined,
60
+ (stats.cacheRead > 0 || stats.cacheWrite > 0) && stats.latestCacheHitRate !== undefined
61
+ ? `CH${stats.latestCacheHitRate.toFixed(1)}%`
62
+ : undefined,
63
+ ]
64
+ .filter((part): part is string => part !== undefined)
65
+ .join(" ");
66
+ const lines = ["Session usage", tokens || "No token usage in this session"];
67
+ if (stats.cost > 0 || options.subscription) {
68
+ lines.push(`$${stats.cost.toFixed(3)}${options.subscription ? " (sub)" : ""}`);
69
+ }
70
+ const auto = options.autoCompaction === false ? "" : " (auto)";
71
+ lines.push(
72
+ context
73
+ ? `${context.percent === null ? "?" : `${context.percent.toFixed(1)}%`}/${formatTokens(context.contextWindow)}${auto}`
74
+ : `Context unavailable${auto}`,
75
+ );
76
+ return lines;
77
+ }
78
+
79
+ export function summarizeSession(entries: readonly unknown[], provider?: string): SessionUsage {
80
+ const total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
81
+ let latestCacheHitRate: number | undefined;
82
+ let sawAssistantUsage = false;
83
+ const add = (usage?: Usage) => {
84
+ if (!usage) return;
85
+ for (const key of ["input", "output", "cacheRead", "cacheWrite"] as const) {
86
+ const value = usage[key];
87
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) total[key] += value;
88
+ }
89
+ const cost = usage.cost?.total;
90
+ if (typeof cost === "number" && Number.isFinite(cost) && cost > 0) total.cost += cost;
91
+ };
92
+
93
+ for (const rawEntry of entries) {
94
+ if (!rawEntry || typeof rawEntry !== "object") continue;
95
+ const entry = rawEntry as UsageEntry;
96
+ if (
97
+ entry.type === "message" &&
98
+ entry.message?.role === "assistant" &&
99
+ (!provider || entry.message.provider === provider)
100
+ ) {
101
+ const usage = entry.message.usage;
102
+ add(usage);
103
+ if (usage) {
104
+ sawAssistantUsage = true;
105
+ const promptTokens = (usage.input ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
106
+ latestCacheHitRate = promptTokens > 0 ? ((usage.cacheRead ?? 0) / promptTokens) * 100 : undefined;
107
+ }
108
+ } else if (
109
+ entry.type === "message" &&
110
+ entry.message?.role === "toolResult" &&
111
+ (!provider || entry.message.provider === provider)
112
+ ) {
113
+ add(entry.message.usage);
114
+ } else if (entry.type === "usage" && (!provider || entry.provider === provider)) {
115
+ add(entry.usage);
116
+ } else if (!provider && (entry.type === "compaction" || entry.type === "branch_summary")) {
117
+ add(entry.usage);
118
+ }
119
+ }
120
+ return {
121
+ ...total,
122
+ ...(sawAssistantUsage ? { latestCacheHitRate } : {}),
123
+ };
124
+ }
package/src/events.ts ADDED
@@ -0,0 +1,2 @@
1
+ export const SESSION_USAGE_STATUS_KEY = "pi-session";
2
+ export const OPEN_SESSION_USAGE_EVENT = "pi-footer:open-session-usage";
package/src/index.ts ADDED
@@ -0,0 +1,86 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { type ModalContent, type ModalRow, showModal } from "@marcosgilf/pi-modal";
3
+ import { formatContextUsageIndicator, formatSessionUsageSummary, summarizeSession } from "./core.ts";
4
+ import { OPEN_SESSION_USAGE_EVENT, SESSION_USAGE_STATUS_KEY } from "./events.ts";
5
+
6
+ function buildSessionUsageModal(ctx: ExtensionContext, autoCompaction: boolean): ModalContent {
7
+ const stats = summarizeSession(ctx.sessionManager.getEntries());
8
+ const model = ctx.model;
9
+ const subscription =
10
+ model !== undefined &&
11
+ ctx.modelRegistry.getProvider(model.provider)?.auth.oauth?.isSubscription === true &&
12
+ ctx.modelRegistry.isUsingOAuth(model);
13
+ const summary = formatSessionUsageSummary(stats, ctx.getContextUsage(), { subscription, autoCompaction });
14
+ const rows: ModalRow[] = [
15
+ { text: summary[0], style: "accent" },
16
+ { text: "" },
17
+ ...summary.slice(1, -1).map((text) => ({ text })),
18
+ { text: "" },
19
+ { text: summary[summary.length - 1] },
20
+ ];
21
+ return { rows, clipboardText: summary.join("\n") };
22
+ }
23
+
24
+ function updateSessionStatus(ctx: ExtensionContext): void {
25
+ if (ctx.mode !== "tui") return;
26
+ const context = ctx.getContextUsage();
27
+ const contextWindow = context?.contextWindow ?? ctx.model?.contextWindow;
28
+ const status = contextWindow ? formatContextUsageIndicator(context?.percent ?? null, contextWindow).text : undefined;
29
+ ctx.ui.setStatus(SESSION_USAGE_STATUS_KEY, status);
30
+ }
31
+
32
+ async function showSessionUsage(ctx: ExtensionContext, autoCompaction: boolean): Promise<void> {
33
+ const unavailableMessage = "/session-usage requires Pi TUI mode.";
34
+ if (ctx.mode !== "tui") {
35
+ ctx.ui.notify(unavailableMessage, "warning");
36
+ return;
37
+ }
38
+ const build = () => buildSessionUsageModal(ctx, autoCompaction);
39
+ await showModal(ctx, build(), { refresh: async () => build() }, unavailableMessage);
40
+ }
41
+
42
+ export default function (pi: ExtensionAPI): void {
43
+ let currentContext: ExtensionContext | undefined;
44
+
45
+ const autoCompactionEnabled = () => pi.getSettings().compaction?.enabled ?? true;
46
+
47
+ pi.events.on(OPEN_SESSION_USAGE_EVENT, () => {
48
+ if (currentContext) void showSessionUsage(currentContext, autoCompactionEnabled());
49
+ });
50
+
51
+ pi.on("session_start", (_event, ctx) => {
52
+ currentContext = ctx;
53
+ updateSessionStatus(ctx);
54
+ });
55
+ pi.on("agent_end", (_event, ctx) => {
56
+ currentContext = ctx;
57
+ updateSessionStatus(ctx);
58
+ });
59
+ pi.on("turn_end", (_event, ctx) => {
60
+ currentContext = ctx;
61
+ updateSessionStatus(ctx);
62
+ });
63
+ pi.on("model_select", (_event, ctx) => {
64
+ currentContext = ctx;
65
+ updateSessionStatus(ctx);
66
+ });
67
+ pi.on("session_tree", (_event, ctx) => {
68
+ currentContext = ctx;
69
+ updateSessionStatus(ctx);
70
+ });
71
+ pi.on("session_compact", (_event, ctx) => updateSessionStatus(ctx));
72
+ pi.on("session_shutdown", (_event, ctx) => {
73
+ if (ctx.mode === "tui") ctx.ui.setStatus(SESSION_USAGE_STATUS_KEY, undefined);
74
+ currentContext = undefined;
75
+ });
76
+
77
+ pi.registerCommand("session-usage", {
78
+ description: "Show session token, cost, and context usage",
79
+ handler: (_args, ctx) => showSessionUsage(ctx, autoCompactionEnabled()),
80
+ });
81
+
82
+ pi.registerShortcut("super+shift+s", {
83
+ description: "Show session token, cost, and context usage",
84
+ handler: (ctx) => showSessionUsage(ctx, autoCompactionEnabled()),
85
+ });
86
+ }