@giladbarnea/pi-custom-footer 0.1.7 → 0.1.9

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
@@ -1,5 +1,5 @@
1
1
  ---
2
- last_updated: 2026-10-29T12-05
2
+ last_updated: 2026-11-07T17-30
3
3
  ---
4
4
 
5
5
  <div align="center">
@@ -20,7 +20,9 @@ A Pi footer that puts your session’s context, cache usage, cost, and loaded sk
20
20
  pi install npm:@giladbarnea/pi-custom-footer
21
21
  ```
22
22
 
23
- Above the editor, see your model, thinking level, session name and ID. Loaded skills get their own row, with token ages.
23
+ Supports Pi 1.4.x and 1.5.x, the latest stable minor and its predecessor.
24
+
25
+ Above the editor, see your model, thinking level, session name and ID. Loaded skills get their own row, with token ages. Compaction and context edits remove skills whose loaded text is no longer present verbatim. Restoring that text restores the skill. A skill read inside a codemode script counts when the script output carries that read verbatim. Pi does not keep nested read results, so the footer records the read text in a custom session entry that is never sent to the model.
24
26
 
25
27
  Below the editor, see:
26
28
 
@@ -45,4 +47,4 @@ npm test
45
47
  npm run check
46
48
  ```
47
49
 
48
- Tests cover rendered values, skill tracking, cache reuse, session changes, and forks. They make no model calls.
50
+ Tests cover rendered values, skill tracking, cache reuse, session changes, forks, compaction, and native context edits. SDK tests use a local scripted provider, with no external model calls.
package/index.ts CHANGED
@@ -19,16 +19,20 @@
19
19
  *
20
20
  * Known gaps reviewed September 30, 2026, against Pi 0.99.0:
21
21
  * - Costs omit codemode and nested-model usage recorded on tool results.
22
- * - Loaded skills omit successful reads recorded in tool-result nestedCalls.
22
+ * - Loaded skills omit successful reads recorded in tool-result nestedCalls
23
+ * that ran without this extension, which records their returned text.
23
24
  * - The header omits the routed physical model and thinking level.
24
25
  * - After compaction, unknown usage falls back to the selected model's window
25
26
  * or 200k, ignoring the known physical window from getContextUsage().
26
27
  */
27
28
  import type { AssistantMessage } from "@earendil-works/pi-ai";
28
- import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
29
+ import type { ExtensionAPI, ExtensionContext, SessionEntry, Theme } from "@earendil-works/pi-coding-agent";
29
30
  import { truncateToWidth, visibleWidth, type TUI } from "@earendil-works/pi-tui";
30
31
 
31
- import { getLoadedSkills, type SkillLocation } from "./skill-tracker.ts";
32
+ import {
33
+ getLoadedSkills, isNestedSkillRead, NESTED_SKILL_READ_ENTRY, nestedReadText, nestedSkillReadTexts,
34
+ type NestedSkillRead, type SkillLocation,
35
+ } from "./skill-tracker.ts";
32
36
 
33
37
  // ── Layout constants ────────────────────────────────────────────────────────
34
38
 
@@ -489,7 +493,7 @@ interface SessionStats {
489
493
  lastContextTokens: number; // input+output+cacheRead+cacheWrite of the last valid turn
490
494
  }
491
495
 
492
- function getSessionStats(ctx: any): SessionStats {
496
+ function getSessionStats(branch: readonly SessionEntry[]): SessionStats {
493
497
  let turnCount = 0;
494
498
  let totalCost = 0;
495
499
  let totalReused = 0;
@@ -499,7 +503,7 @@ function getSessionStats(ctx: any): SessionStats {
499
503
  let cacheWasReported = false;
500
504
  let latestCacheHitRate: number | null = null;
501
505
  let latestCacheMissTokens: number | null = null;
502
- for (const entry of ctx.sessionManager?.getBranch?.() ?? []) {
506
+ for (const entry of branch) {
503
507
  if (entry.type === "compaction" || entry.type === "branch_summary") {
504
508
  previousPromptTokens = null;
505
509
  cacheWasReported = false;
@@ -586,16 +590,19 @@ export default function (pi: ExtensionAPI) {
586
590
  let gitDirty = false;
587
591
  let thinkingLevel = "off";
588
592
  let loadedSkills: Array<{ name: string; tokenAge: number | null }> = [];
593
+ const runningNestedSkillReads = new Set<string>();
589
594
  let skillsDirty = true;
595
+ let skillContextChangeId: string | undefined;
590
596
  let snapshot: FooterSnapshot | undefined;
591
597
 
592
598
  // ── Rendering ────────────────────────────────────────────────────────
593
599
 
594
- function refreshLoadedSkills(ctx: any, currentContextTokens: number | null): void {
600
+ function refreshLoadedSkills(ctx: ExtensionContext, branch: readonly SessionEntry[], currentContextTokens: number | null): void {
595
601
  loadedSkills = getLoadedSkills(
596
- ctx.sessionManager.buildSessionContext().messages,
602
+ ctx.sessionManager.buildSessionProjection().entries,
597
603
  getSkillLocations(pi),
598
604
  ctx.cwd,
605
+ nestedSkillReadTexts(branch),
599
606
  ).map(({ name, loadedAtTokens }) => ({
600
607
  name,
601
608
  tokenAge:
@@ -611,9 +618,14 @@ export default function (pi: ExtensionAPI) {
611
618
  const leafId = manager.getLeafId();
612
619
  const model: ExtensionContext["model"] = currentCtx.model;
613
620
  if (snapshot && snapshot.manager === manager && snapshot.sessionId === sessionId && snapshot.leafId === leafId && snapshot.model === model) return snapshot;
614
- const stats = getSessionStats(currentCtx);
621
+ const branch = manager.getBranch();
622
+ const stats = getSessionStats(branch);
615
623
  const usage = currentCtx.getContextUsage();
616
- if (skillsDirty) refreshLoadedSkills(currentCtx, usage?.tokens ?? null);
624
+ // Boundary edits commit after turn_end, which may already have rendered the old projection.
625
+ const contextChangeId = branch.reduce<string | undefined>((latest, entry) =>
626
+ entry.type === "context_edit" || entry.type === "compaction" ? entry.id : latest, undefined);
627
+ if (skillsDirty || contextChangeId !== skillContextChangeId) refreshLoadedSkills(currentCtx, branch, usage?.tokens ?? null);
628
+ skillContextChangeId = contextChangeId;
617
629
  skillsDirty = false;
618
630
  snapshot = {
619
631
  manager, sessionId, leafId, model, stats,
@@ -798,10 +810,20 @@ export default function (pi: ExtensionAPI) {
798
810
  gitBranch = null;
799
811
  gitDirty = false;
800
812
  loadedSkills = [];
813
+ runningNestedSkillReads.clear();
801
814
  snapshot = undefined;
802
815
  skillsDirty = true;
803
816
  });
804
817
 
818
+ pi.on("tool_execution_start", async (event, ctx) => {
819
+ if (isNestedSkillRead(event, getSkillLocations(pi), ctx.cwd)) runningNestedSkillReads.add(event.toolCallId);
820
+ });
821
+ pi.on("tool_execution_end", async (event) => {
822
+ if (!runningNestedSkillReads.delete(event.toolCallId)) return;
823
+ const readText = nestedReadText(event);
824
+ if (readText !== null) pi.appendEntry<NestedSkillRead>(NESTED_SKILL_READ_ENTRY, { toolCallId: event.toolCallId, text: readText });
825
+ });
826
+
805
827
  pi.on("model_select", async (_event: any, ctx: any) => updateCtx(ctx));
806
828
  pi.on("thinking_level_select", async (event: any) => {
807
829
  thinkingLevel = event.level;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-custom-footer",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "Context, cache, cost, and loaded skills at a glance in Pi.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -28,16 +28,16 @@
28
28
  "LICENSE"
29
29
  ],
30
30
  "scripts": {
31
- "test": "node tests/skills.mjs && node tests/cache.mjs && node tests/layout.mjs && node tests/load.mjs",
31
+ "test": "node tests/skills.mjs && node tests/cache.mjs && node tests/layout.mjs && node tests/load.mjs && node --test tests/context.mjs",
32
32
  "check": "tsc --noEmit"
33
33
  },
34
34
  "engines": {
35
35
  "node": ">=22.19.0"
36
36
  },
37
37
  "peerDependencies": {
38
- "@earendil-works/pi-ai": ">=0.84.2",
39
- "@earendil-works/pi-coding-agent": ">=0.84.2",
40
- "@earendil-works/pi-tui": ">=0.84.2"
38
+ "@earendil-works/pi-ai": ">=1.4.0",
39
+ "@earendil-works/pi-coding-agent": ">=1.4.0",
40
+ "@earendil-works/pi-tui": ">=1.4.0"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@earendil-works/pi-ai": "1.4.0",
package/skill-tracker.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ProjectedSessionEntry, SessionEntry, ToolExecutionEndEvent, ToolExecutionStartEvent } from "@earendil-works/pi-coding-agent";
1
2
  import { homedir } from "node:os";
2
3
  import { resolve } from "node:path";
3
4
 
@@ -11,6 +12,14 @@ export type LoadedSkill = {
11
12
  name: string;
12
13
  };
13
14
 
15
+ /** A successful nested skill read's returned text, kept as a custom session entry because Pi does not persist nested results. */
16
+ export type NestedSkillRead = {
17
+ toolCallId: string;
18
+ text: string;
19
+ };
20
+
21
+ export const NESTED_SKILL_READ_ENTRY = "custom-footer-nested-skill-read";
22
+
14
23
  type UnknownRecord = Record<string, unknown>;
15
24
 
16
25
  const MAX_SKILL_NAME_LENGTH = 64;
@@ -37,8 +46,10 @@ function isValidSkillName(name: string): boolean {
37
46
  return name.length <= MAX_SKILL_NAME_LENGTH && SKILL_NAME_PATTERN.test(name);
38
47
  }
39
48
 
40
- function expandedSkillNames(content: unknown): string[] {
41
- return [...textFromContent(content).matchAll(/<skill name="([^"]+)" location="[^"]+">/g)]
49
+ function expandedSkillNames(content: unknown, originalContent: unknown): string[] {
50
+ const text = textFromContent(content);
51
+ return [...textFromContent(originalContent).matchAll(/<skill name="([^"]+)" location="[^"]+">[\s\S]*?<\/skill>/g)]
52
+ .filter((match) => text.includes(match[0]))
42
53
  .map((match) => match[1]!)
43
54
  .filter(isValidSkillName);
44
55
  }
@@ -56,6 +67,57 @@ function skillNamesForReadPath(rawPath: string, skills: readonly SkillLocation[]
56
67
  return skills.flatMap((skill) => path === resolvePath(cwd, skill.filePath) ? [skill.name] : []);
57
68
  }
58
69
 
70
+ /**
71
+ * Whether a starting tool call is a nested skill read, such as one from a codemode script.
72
+ *
73
+ * @example
74
+ * isNestedSkillRead({ type: "tool_execution_start", toolCallId: "c/1", toolName: "read", args: { path: "/s/SKILL.md" }, parentToolCallId: "c" }, [{ name: "s", filePath: "/s/SKILL.md" }], "/") // true
75
+ */
76
+ export function isNestedSkillRead(event: ToolExecutionStartEvent, skills: readonly SkillLocation[], cwd: string): boolean {
77
+ return event.parentToolCallId !== undefined && readPaths({ name: event.toolName, arguments: event.args })
78
+ .some((path) => skillNamesForReadPath(path, skills, cwd).length > 0);
79
+ }
80
+
81
+ /**
82
+ * The text a successful nested read returned to its caller, to match against the parent result later.
83
+ *
84
+ * @example
85
+ * nestedReadText({ type: "tool_execution_end", toolCallId: "c/1", toolName: "read", result: { content: [{ type: "text", text: "Body." }] }, isError: false }) // "Body."
86
+ */
87
+ export function nestedReadText(event: ToolExecutionEndEvent): string | null {
88
+ return event.isError ? null : textFromContent(event.result?.content);
89
+ }
90
+
91
+ /**
92
+ * Nested read texts recorded on a session branch, by nested tool call id.
93
+ *
94
+ * @example
95
+ * nestedSkillReadTexts([]) // Map(0) {}
96
+ */
97
+ export function nestedSkillReadTexts(branch: readonly SessionEntry[]): Map<string, string> {
98
+ return new Map(branch.flatMap((entry) => {
99
+ if (entry.type !== "custom" || entry.customType !== NESTED_SKILL_READ_ENTRY) return [];
100
+ const { toolCallId, text } = entry.data as NestedSkillRead;
101
+ return [[toolCallId, text]];
102
+ }));
103
+ }
104
+
105
+ /** Skills whose nested read text, captured when the read succeeded, survives verbatim in the projected parent result. */
106
+ function deliveredNestedSkillNames(
107
+ message: UnknownRecord,
108
+ skills: readonly SkillLocation[],
109
+ cwd: string,
110
+ nestedReadTexts: ReadonlyMap<string, string>,
111
+ ): string[] {
112
+ if (!isRecord(message.nestedCalls) || !Array.isArray(message.nestedCalls.calls)) return [];
113
+ const deliveredText = textFromContent(message.content);
114
+ return message.nestedCalls.calls.filter(isRecord).flatMap((call) => {
115
+ const readText = typeof call.id === "string" ? nestedReadTexts.get(call.id) : undefined;
116
+ if (readText === undefined || !deliveredText.includes(readText)) return [];
117
+ return readPaths(call).flatMap((path) => skillNamesForReadPath(path, skills, cwd));
118
+ });
119
+ }
120
+
59
121
  function assistantPromptTokens(message: UnknownRecord, compactionTimestamp: number | null): number | null {
60
122
  if (message.role !== "assistant" || message.stopReason === "error" || message.stopReason === "aborted") return null;
61
123
  if (compactionTimestamp !== null && (typeof message.timestamp !== "number" || message.timestamp <= compactionTimestamp)) return null;
@@ -74,17 +136,22 @@ function latestCompactionTimestamp(history: readonly unknown[]): number | null {
74
136
  }
75
137
 
76
138
  /**
77
- * Return skills in the effective model history with their first valid post-load prompt size.
139
+ * Return skills whose loaded text survives verbatim in Pi's projection, with their first valid post-load prompt size.
78
140
  *
79
141
  * @example
80
- * getLoadedSkills([], [], "/workspace") // []
142
+ * getLoadedSkills([], [], "/workspace", new Map()) // []
81
143
  */
82
144
  export function getLoadedSkills(
83
- history: readonly unknown[],
145
+ entries: readonly ProjectedSessionEntry[],
84
146
  skills: readonly SkillLocation[],
85
147
  cwd: string,
148
+ nestedReadTexts: ReadonlyMap<string, string>,
86
149
  ): LoadedSkill[] {
87
- const compactionTimestamp = latestCompactionTimestamp(history);
150
+ const history: Array<{ message: unknown; originalContent: unknown }> = entries.flatMap(({ sourceEntry, messages }) => messages.map((message) => ({
151
+ message,
152
+ originalContent: sourceEntry.type === "message" && "content" in sourceEntry.message ? sourceEntry.message.content : undefined,
153
+ })));
154
+ const compactionTimestamp = latestCompactionTimestamp(history.map(({ message }) => message));
88
155
  const loadedSkills = new Map<string, number | null>();
89
156
  const pendingBaselines = new Set<string>();
90
157
  const skillNamesByToolCall = new Map<string, string[]>();
@@ -94,16 +161,18 @@ export function getLoadedSkills(
94
161
  pendingBaselines.add(skillName);
95
162
  };
96
163
 
97
- for (const message of history) {
164
+ for (const { message, originalContent } of history) {
98
165
  if (!isRecord(message)) continue;
99
166
 
100
167
  if (message.role === "user") {
101
- for (const skillName of expandedSkillNames(message.content)) markLoaded(skillName);
168
+ for (const skillName of expandedSkillNames(message.content, originalContent)) markLoaded(skillName);
102
169
  continue;
103
170
  }
104
171
 
105
172
  if (message.role === "toolResult") {
173
+ for (const skillName of deliveredNestedSkillNames(message, skills, cwd, nestedReadTexts)) markLoaded(skillName);
106
174
  if (message.isError !== false || typeof message.toolCallId !== "string") continue;
175
+ if (!textFromContent(message.content).includes(textFromContent(originalContent))) continue;
107
176
  for (const skillName of skillNamesByToolCall.get(message.toolCallId) ?? []) markLoaded(skillName);
108
177
  continue;
109
178
  }