@0xkahi/pi-qol 1.0.5 → 1.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.
Files changed (33) hide show
  1. package/README.md +35 -5
  2. package/assets/config.schema.json +18 -3
  3. package/package.json +5 -5
  4. package/src/constants.ts +1 -0
  5. package/src/extensions/context-view/capture.ts +311 -83
  6. package/src/extensions/context-view/codemap.md +111 -48
  7. package/src/extensions/context-view/context-view-controller.ts +65 -27
  8. package/src/extensions/context-view/index.ts +22 -6
  9. package/src/extensions/context-view/measure.ts +713 -78
  10. package/src/extensions/context-view/model.ts +132 -14
  11. package/src/extensions/context-view/probe-token.ts +28 -0
  12. package/src/extensions/context-view/prompt-additions.ts +174 -0
  13. package/src/extensions/context-view/prompt-blocks.ts +204 -0
  14. package/src/extensions/context-view/settings.ts +43 -0
  15. package/src/extensions/context-view/text.ts +48 -0
  16. package/src/extensions/context-view/transcript.ts +62 -0
  17. package/src/extensions/context-view/ui/codemap.md +28 -13
  18. package/src/extensions/context-view/ui/context-view-dialog.ts +6 -1
  19. package/src/extensions/context-view/ui/injections-model.ts +13 -28
  20. package/src/extensions/context-view/ui/injections-view.ts +82 -21
  21. package/src/extensions/context-view/ui/json-preview.ts +41 -0
  22. package/src/extensions/context-view/ui/markers.ts +96 -0
  23. package/src/extensions/context-view/ui/section-preview.ts +188 -10
  24. package/src/extensions/context-view/ui/usage-block-layer.ts +9 -4
  25. package/src/extensions/context-view/ui/usage-view.ts +70 -17
  26. package/src/extensions/context-view/ui/wheel-preview-layer.ts +104 -0
  27. package/src/extensions/context-view/ui/wheel.ts +66 -0
  28. package/src/extensions/context-view/usage.ts +64 -26
  29. package/src/extensions/custom-footer/agent-display-state.ts +60 -0
  30. package/src/extensions/custom-footer/footer-component.ts +22 -0
  31. package/src/extensions/custom-footer/index.ts +17 -1
  32. package/src/extensions/custom-footer/types.ts +3 -1
  33. package/src/schemas/custom-footer-config.schema.ts +11 -0
@@ -1,6 +1,5 @@
1
- /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
1
  /**
3
- * Pure context-usage classification: combine the frozen Initial snapshot's
2
+ * Pure context-usage classification: combine the current branch's measured
4
3
  * prompt/tool decomposition with the live session messages into estimated
5
4
  * category totals. No pi API access — unit-testable.
6
5
  */
@@ -29,14 +28,16 @@ export interface UsageInputs {
29
28
 
30
29
  /**
31
30
  * Estimate the current/next-request context composition. Prompt and tool
32
- * categories come from the frozen Initial snapshot; message categories are
33
- * classified from the live session context. Empty categories are dropped and
31
+ * categories come from the caller's current-state snapshot; message categories are
32
+ * classified from the live session context. System messages have already been
33
+ * replayed into that snapshot and must not count again. Empty categories are dropped and
34
34
  * every aggregate equals the exact sum of its children.
35
35
  */
36
36
  export function computeUsage(inputs: UsageInputs): ContextUsageSnapshot {
37
+ const prompt = classifyPromptCategories(inputs.snapshot);
37
38
  const categories = [
38
- ...classifyPromptCategories(inputs.snapshot),
39
- ...classifyMessages(inputs.messages, contextOnlyMessages(inputs.snapshot)),
39
+ ...prompt.categories,
40
+ ...classifyMessages(inputs.messages, requestOnlyMessages(inputs.snapshot), prompt.promptAdditions),
40
41
  ].filter(category => category.tokens > 0);
41
42
  return {
42
43
  computedAt: inputs.computedAt ?? new Date(),
@@ -76,9 +77,17 @@ export function toReportedUsage(usage: ContextUsage | undefined): ReportedContex
76
77
  };
77
78
  }
78
79
 
79
- /** Map frozen snapshot items to prompt/tool/memory/skill categories. */
80
- function classifyPromptCategories(snapshot: InitialSnapshot): UsageCategory[] {
80
+ /** Prompt-derived categories, plus the additions the Extensions category adopts. */
81
+ interface PromptCategories {
82
+ readonly categories: UsageCategory[];
83
+ /** Prompt text appended by extensions, kept out of pi's own System Prompt total. */
84
+ readonly promptAdditions: UsageCategory[];
85
+ }
86
+
87
+ /** Map frozen snapshot items to prompt/tool/instruction/skill categories. */
88
+ function classifyPromptCategories(snapshot: InitialSnapshot): PromptCategories {
81
89
  const systemPrompt: UsageCategory[] = [];
90
+ const promptAdditions: UsageCategory[] = [];
82
91
  const systemTools: UsageCategory[] = [];
83
92
  const customTools: UsageCategory[] = [];
84
93
  const mcpTools: UsageCategory[] = [];
@@ -89,16 +98,19 @@ function classifyPromptCategories(snapshot: InitialSnapshot): UsageCategory[] {
89
98
  switch (item.kind) {
90
99
  case 'base-prompt':
91
100
  case 'append-prompt':
92
- case 'prompt-addition':
93
101
  systemPrompt.push(leafFromItem(item));
94
102
  break;
103
+ case 'prompt-addition':
104
+ // Named by owner, because Extensions groups contributors rather than content.
105
+ promptAdditions.push({ ...leafFromItem(item), label: item.source.label });
106
+ break;
95
107
  case 'tool':
96
108
  if (item.source.native) systemTools.push(...breakdownFromItem(item));
97
109
  else if (isMcpTool(item)) mcpTools.push(leafFromItem(item));
98
110
  else customTools.push(leafFromItem(item));
99
111
  break;
100
112
  case 'context-file':
101
- contextFiles.push(leafFromItem(item));
113
+ contextFiles.push(...breakdownFromItem(item));
102
114
  break;
103
115
  case 'skills':
104
116
  skills.push(...breakdownFromItem(item));
@@ -109,14 +121,18 @@ function classifyPromptCategories(snapshot: InitialSnapshot): UsageCategory[] {
109
121
  }
110
122
  }
111
123
  }
112
- return withoutEmpty([
113
- aggregate('system-prompt', 'System Prompt', systemPrompt),
114
- aggregate('system-tools', 'System Tools', systemTools),
115
- aggregate('custom-tools', 'Custom Tools', customTools),
116
- aggregate('mcp-tools', 'MCP Tools', mcpTools),
117
- aggregate('context-files', 'Memory (AGENTS.md)', contextFiles),
118
- aggregate('skills', 'Skills', skills),
119
- ]);
124
+ // Local layer keeps pi-qol's stable category order, ids, and labels.
125
+ return {
126
+ categories: withoutEmpty([
127
+ aggregate('system-prompt', 'System Prompt', systemPrompt),
128
+ aggregate('system-tools', 'System Tools', systemTools),
129
+ aggregate('custom-tools', 'Custom Tools', customTools),
130
+ aggregate('mcp-tools', 'MCP Tools', mcpTools),
131
+ aggregate('context-files', 'Memory (AGENTS.md)', contextFiles),
132
+ aggregate('skills', 'Skills', skills),
133
+ ]),
134
+ promptAdditions,
135
+ };
120
136
  }
121
137
 
122
138
  /** Best-effort MCP attribution from the only public provenance field available. */
@@ -124,13 +140,19 @@ function isMcpTool(item: InjectionItem): boolean {
124
140
  return /(^|[^a-z])mcp([^a-z]|$)/i.test(`${item.source.id} ${item.source.label}`);
125
141
  }
126
142
 
127
- /** Collect frozen messages that existed only in the transformed provider context. */
128
- function contextOnlyMessages(snapshot: InitialSnapshot): InjectionItem[] {
129
- return snapshot.groups.flatMap(group => group.items.filter(item => item.kind === 'message' && item.contextOnly === true));
143
+ /** Collect frozen messages that existed only in the captured outgoing request. */
144
+ function requestOnlyMessages(snapshot: InitialSnapshot): InjectionItem[] {
145
+ return snapshot.groups.flatMap(group =>
146
+ group.items.filter(item => item.kind === 'message' && item.requestOnly === true && item.systemMessage === undefined),
147
+ );
130
148
  }
131
149
 
132
- /** Classify live session messages and frozen context-only injections with preview entries. */
133
- function classifyMessages(messages: ContextEvent['messages'], contextOnly: readonly InjectionItem[]): UsageCategory[] {
150
+ /** Classify live session messages and frozen request-only injections with preview entries. */
151
+ function classifyMessages(
152
+ messages: ContextEvent['messages'],
153
+ requestOnly: readonly InjectionItem[],
154
+ promptAdditions: readonly UsageCategory[],
155
+ ): UsageCategory[] {
134
156
  const user: UsagePreviewEntry[] = [];
135
157
  const agentText: UsagePreviewEntry[] = [];
136
158
  const agentThinking: UsagePreviewEntry[] = [];
@@ -140,15 +162,19 @@ function classifyMessages(messages: ContextEvent['messages'], contextOnly: reado
140
162
  const toolResults = new Map<string, UsagePreviewEntry[]>();
141
163
  const customMessages = new Map<string, UsagePreviewEntry[]>();
142
164
 
143
- for (const item of contextOnly) {
165
+ for (const item of requestOnly) {
144
166
  appendEntry(customMessages, item.source.label, {
145
167
  breadcrumb: [item.label],
146
168
  tokens: item.tokens,
147
169
  text: item.text,
170
+ jsonSpan: item.jsonSpan,
148
171
  });
149
172
  }
150
173
  for (const message of messages) {
151
174
  switch (message.role) {
175
+ case 'system':
176
+ // Sections and tool deltas already contribute through the replayed snapshot.
177
+ break;
152
178
  case 'user':
153
179
  user.push({
154
180
  timestamp: message.timestamp,
@@ -169,6 +195,8 @@ function classifyMessages(messages: ContextEvent['messages'], contextOnly: reado
169
195
  breadcrumb: ['assistant', block.name],
170
196
  tokens: textTokens(block.name.length + args.length),
171
197
  text: `${block.name}(${args})`,
198
+ // The arguments sit between the call parentheses this entry adds around them.
199
+ jsonSpan: { start: block.name.length + 1, end: block.name.length + 1 + args.length },
172
200
  });
173
201
  }
174
202
  break;
@@ -232,7 +260,8 @@ function classifyMessages(messages: ContextEvent['messages'], contextOnly: reado
232
260
  leaf('agent-thinking-messages', 'Agent Thinking Messages', agentThinking),
233
261
  leaf('agent-tool-call-messages', 'Agent Tool Call Messages', agentToolCalls),
234
262
  toolOutput,
235
- aggregate('extension-messages', 'Extensions', leavesFromMap('custom-message', customMessages)),
263
+ // One category per contributing extension, whether it sent messages or appended prompt text.
264
+ aggregate('extension-messages', 'Extensions', [...promptAdditions, ...leavesFromMap('custom-message', customMessages)]),
236
265
  leaf('compacted-data', 'Compacted Data', compacted),
237
266
  ]);
238
267
  }
@@ -253,7 +282,16 @@ function leafFromItem(item: InjectionItem): UsageCategory {
253
282
  id: `item:${item.id}`,
254
283
  label: item.label,
255
284
  tokens: item.tokens,
256
- entries: [{ breadcrumb: [item.label], tokens: item.tokens, text: item.text, sections: item.sections?.map(section => ({ ...section })) }],
285
+ entries: [
286
+ {
287
+ breadcrumb: [item.label],
288
+ tokens: item.tokens,
289
+ text: item.text,
290
+ jsonSpan: item.jsonSpan,
291
+ // Tool parts stay a preview breakdown of the same estimate, never separate entries.
292
+ sections: item.sections,
293
+ },
294
+ ],
257
295
  };
258
296
  }
259
297
 
@@ -0,0 +1,60 @@
1
+ import { sliceByColumn, stripTerminalSequences, visibleWidth } from '@earendil-works/pi-tui';
2
+ import { COLOR_HEX_REGEX } from '../../constants';
3
+
4
+ const MAX_AGENT_NAME_WIDTH = 10;
5
+
6
+ function normalizeAgentName(value: string): string {
7
+ const sanitized = stripTerminalSequences(value)
8
+ .replace(/\p{Cc}/gu, '')
9
+ .trim();
10
+ return visibleWidth(sanitized) > MAX_AGENT_NAME_WIDTH ? `${sliceByColumn(sanitized, 0, MAX_AGENT_NAME_WIDTH, true)}...` : sanitized;
11
+ }
12
+
13
+ export type AgentDisplay = {
14
+ name: string;
15
+ eventColor?: string;
16
+ };
17
+
18
+ export class AgentDisplayState {
19
+ private current: AgentDisplay;
20
+ private readonly listeners = new Set<() => void>();
21
+
22
+ constructor(defaultName: string) {
23
+ this.current = { name: normalizeAgentName(defaultName) };
24
+ }
25
+
26
+ snapshot(): Readonly<AgentDisplay> {
27
+ return this.current;
28
+ }
29
+
30
+ reset(defaultName: string): void {
31
+ this.current = { name: normalizeAgentName(defaultName) };
32
+ this.notify();
33
+ }
34
+
35
+ update(payload: unknown): boolean {
36
+ if (!payload || typeof payload !== 'object') return false;
37
+
38
+ const { agentName, color } = payload as Record<string, unknown>;
39
+ if (typeof agentName !== 'string') return false;
40
+
41
+ const name = normalizeAgentName(agentName);
42
+ if (!name) return false;
43
+
44
+ this.current = {
45
+ name,
46
+ eventColor: typeof color === 'string' && COLOR_HEX_REGEX.test(color) ? color : undefined,
47
+ };
48
+ this.notify();
49
+ return true;
50
+ }
51
+
52
+ onChange(listener: () => void): () => void {
53
+ this.listeners.add(listener);
54
+ return () => this.listeners.delete(listener);
55
+ }
56
+
57
+ private notify(): void {
58
+ for (const listener of this.listeners) listener();
59
+ }
60
+ }
@@ -18,6 +18,7 @@ function sanitizeStatusText(text: string): string {
18
18
  export class CustomFooterComponent implements Component {
19
19
  private readonly usageManager: SubscriptionUsageManager;
20
20
  private readonly unsubscribeBranch: () => void;
21
+ private readonly unsubscribeAgentDisplay: () => void;
21
22
  private restoredDefaultFooter = false;
22
23
  private disposed = false;
23
24
 
@@ -26,6 +27,9 @@ export class CustomFooterComponent implements Component {
26
27
  if (!this.disposed) deps.tui.requestRender();
27
28
  });
28
29
  this.unsubscribeBranch = deps.footerData.onBranchChange(() => deps.tui.requestRender());
30
+ this.unsubscribeAgentDisplay = deps.agentDisplayState.onChange(() => {
31
+ if (!this.disposed) deps.tui.requestRender();
32
+ });
29
33
  }
30
34
 
31
35
  invalidate(): void {
@@ -35,6 +39,7 @@ export class CustomFooterComponent implements Component {
35
39
  dispose(): void {
36
40
  this.disposed = true;
37
41
  this.unsubscribeBranch();
42
+ this.unsubscribeAgentDisplay();
38
43
  }
39
44
 
40
45
  render(width: number): string[] {
@@ -84,9 +89,26 @@ export class CustomFooterComponent implements Component {
84
89
  line = this.deps.theme.fg('dim', rawLine);
85
90
  }
86
91
 
92
+ if (config.display.agentName) {
93
+ line = `${this.renderAgentBadge(config)} ${line}`;
94
+ }
95
+
87
96
  return truncateToWidth(line, width, this.deps.theme.fg('dim', '...'));
88
97
  }
89
98
 
99
+ private renderAgentBadge(config: CustomFooterConfig): string {
100
+ const agentDisplay = this.deps.agentDisplayState.snapshot();
101
+ const badgeText = ` ${agentDisplay.name} `;
102
+ const color = agentDisplay.eventColor ?? config.colors.agentName;
103
+ if (color) {
104
+ return dye
105
+ .colorize({ fg: dye.hex(color) })
106
+ .bold()
107
+ .inverse(badgeText);
108
+ }
109
+ return dye.inverse(dye.bold(this.deps.theme.fg('accent', badgeText)));
110
+ }
111
+
90
112
  private renderStatsLine(width: number, config: CustomFooterConfig): string {
91
113
  const model = this.deps.ctx.model;
92
114
  const usingSubscription = model ? this.deps.ctx.modelRegistry.isUsingOAuth(model) : false;
@@ -1,17 +1,33 @@
1
1
  import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
2
  import type { ConfigLoader } from '../../config-loader';
3
+ import { SET_AGENT_NAME_EVENT_ID } from '../../constants';
4
+ import { AgentDisplayState } from './agent-display-state';
3
5
  import { CustomFooterComponent } from './footer-component';
4
6
 
5
7
  export function registerCustomFooter(pi: ExtensionAPI, deps: { config: ConfigLoader }): void {
6
8
  let installed = false;
9
+ const agentDisplayState = new AgentDisplayState('DEFAULT');
10
+
11
+ pi.events.on(SET_AGENT_NAME_EVENT_ID, payload => {
12
+ agentDisplayState.update(payload);
13
+ });
7
14
 
8
15
  pi.on('session_start', (_event, ctx) => {
16
+ agentDisplayState.reset(deps.config.getCustomFooter().defaultAgentName);
9
17
  if (!deps.config.isEnabled('custom_footer')) return;
10
18
  if (installed) return;
11
19
 
12
20
  ctx.ui.setFooter(
13
21
  (tui, theme, footerData) =>
14
- new CustomFooterComponent({ tui, theme, footerData, ctx, config: deps.config, getThinkingLevel: () => pi.getThinkingLevel() }),
22
+ new CustomFooterComponent({
23
+ tui,
24
+ theme,
25
+ footerData,
26
+ ctx,
27
+ config: deps.config,
28
+ agentDisplayState,
29
+ getThinkingLevel: () => pi.getThinkingLevel(),
30
+ }),
15
31
  );
16
32
  installed = true;
17
33
  });
@@ -2,6 +2,7 @@ import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
2
2
  import type { TUI } from '@earendil-works/pi-tui';
3
3
  import type { ConfigLoader } from '../../config-loader';
4
4
  import type { Config } from '../../schemas/config.schema';
5
+ import type { AgentDisplayState } from './agent-display-state';
5
6
 
6
7
  export type SupportedProvider = 'anthropic' | 'openai-codex';
7
8
 
@@ -11,7 +12,7 @@ export type CustomFooterDisplay = CustomFooterConfig['display'];
11
12
  export type CustomFooterIcons = CustomFooterConfig['icons'];
12
13
 
13
14
  export type FooterTheme = {
14
- fg(color: 'dim' | 'error' | 'warning', text: string): string;
15
+ fg(color: 'accent' | 'dim' | 'error' | 'warning', text: string): string;
15
16
  };
16
17
 
17
18
  export type FooterDataProvider = {
@@ -27,6 +28,7 @@ export type CustomFooterComponentDeps = {
27
28
  footerData: FooterDataProvider;
28
29
  ctx: ExtensionContext;
29
30
  config: ConfigLoader;
31
+ agentDisplayState: AgentDisplayState;
30
32
  getThinkingLevel: () => string;
31
33
  };
32
34
 
@@ -1,9 +1,15 @@
1
1
  import z from 'zod';
2
2
  import { ColorHexSchema } from './shared-config.schema';
3
3
 
4
+ const AgentNameSchema = z
5
+ .string()
6
+ .refine(value => value.trim().length > 0, { message: 'Agent name must not be empty' })
7
+ .default('DEFAULT');
8
+
4
9
  const CustomFooterColorsSchema = z.object({
5
10
  directory: ColorHexSchema.optional(),
6
11
  modelName: ColorHexSchema.optional(),
12
+ agentName: ColorHexSchema.optional(),
7
13
  anthropicUsage: ColorHexSchema.optional().default('#D97706'),
8
14
  codexUsage: ColorHexSchema.optional().default('#10B981'),
9
15
  });
@@ -19,6 +25,7 @@ const CustomFooterIconsSchema = z.object({
19
25
  const CustomFooterDisplaySchema = z.object({
20
26
  tokens: z.boolean().optional().default(true),
21
27
  cache: z.boolean().optional().default(true),
28
+ agentName: z.boolean().optional().default(false),
22
29
  });
23
30
 
24
31
  const DEFAULT_CUSTOM_FOOTER_COLORS = CustomFooterColorsSchema.parse({});
@@ -30,6 +37,7 @@ export const CustomFooterConfigSchema = z.object({
30
37
  colors: CustomFooterColorsSchema.default(DEFAULT_CUSTOM_FOOTER_COLORS),
31
38
  icons: CustomFooterIconsSchema.default(DEFAULT_CUSTOM_FOOTER_ICONS),
32
39
  display: CustomFooterDisplaySchema.default(DEFAULT_CUSTOM_FOOTER_DISPLAY),
40
+ defaultAgentName: AgentNameSchema,
33
41
  });
34
42
  export type CustomFooterConfig = z.infer<typeof CustomFooterConfigSchema>;
35
43
 
@@ -41,6 +49,7 @@ export const PartialCustomFooterConfigSchema = z.object({
41
49
  .object({
42
50
  directory: ColorHexSchema.optional(),
43
51
  modelName: ColorHexSchema.optional(),
52
+ agentName: ColorHexSchema.optional(),
44
53
  anthropicUsage: ColorHexSchema.optional(),
45
54
  codexUsage: ColorHexSchema.optional(),
46
55
  })
@@ -58,7 +67,9 @@ export const PartialCustomFooterConfigSchema = z.object({
58
67
  .object({
59
68
  tokens: z.boolean().optional(),
60
69
  cache: z.boolean().optional(),
70
+ agentName: z.boolean().optional(),
61
71
  })
62
72
  .optional(),
73
+ defaultAgentName: AgentNameSchema.optional(),
63
74
  });
64
75
  export type PartialCustomFooterConfig = z.infer<typeof PartialCustomFooterConfigSchema>;