@0xkahi/pi-qol 1.0.6 → 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.
@@ -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