@0xkahi/pi-qol 0.1.1 → 1.0.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/README.md +13 -0
- package/assets/config.schema.json +12 -0
- package/package.json +4 -4
- package/src/codemap.md +3 -2
- package/src/config-loader.ts +4 -0
- package/src/constants.ts +1 -0
- package/src/extensions/auto-session-name/title-generator.ts +1 -1
- package/src/extensions/codemap.md +9 -2
- package/src/extensions/context-view/capture.ts +394 -0
- package/src/extensions/context-view/codemap.md +28 -0
- package/src/extensions/context-view/constants.ts +4 -0
- package/src/extensions/context-view/context-view-controller.ts +67 -0
- package/src/extensions/context-view/index.ts +120 -0
- package/src/extensions/context-view/measure.ts +307 -0
- package/src/extensions/context-view/model.ts +207 -0
- package/src/extensions/context-view/ui/context-view-dialog.ts +81 -0
- package/src/extensions/context-view/ui/injections-model.ts +257 -0
- package/src/extensions/context-view/ui/injections-view.ts +396 -0
- package/src/extensions/context-view/ui/layout.ts +88 -0
- package/src/extensions/context-view/ui/navigation.ts +37 -0
- package/src/extensions/context-view/ui/skill-preview.ts +82 -0
- package/src/extensions/context-view/ui/usage-map.ts +133 -0
- package/src/extensions/context-view/ui/usage-view.ts +734 -0
- package/src/extensions/context-view/usage.ts +432 -0
- package/src/index.ts +2 -0
- package/src/schemas/codemap.md +2 -2
- package/src/schemas/config.schema.ts +3 -0
- package/src/schemas/context-view.config.schema.ts +13 -0
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
/** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
|
|
2
|
+
/**
|
|
3
|
+
* Pure context-usage classification: combine the frozen Initial snapshot's
|
|
4
|
+
* prompt/tool decomposition with the live session messages into estimated
|
|
5
|
+
* category totals. No pi API access — unit-testable.
|
|
6
|
+
*/
|
|
7
|
+
import { type ContextEvent, type ContextUsage, convertToLlm, estimateTokens } from '@earendil-works/pi-coding-agent';
|
|
8
|
+
|
|
9
|
+
import type {
|
|
10
|
+
ContextUsageSnapshot,
|
|
11
|
+
InitialSnapshot,
|
|
12
|
+
InjectionItem,
|
|
13
|
+
InvisibleReasoningEstimate,
|
|
14
|
+
ReportedContextUsage,
|
|
15
|
+
UsageCategory,
|
|
16
|
+
UsagePreviewEntry,
|
|
17
|
+
} from './model';
|
|
18
|
+
|
|
19
|
+
/** Everything computeUsage needs; messages must already be synthetic-filtered. */
|
|
20
|
+
export interface UsageInputs {
|
|
21
|
+
snapshot: InitialSnapshot;
|
|
22
|
+
messages: ContextEvent['messages'];
|
|
23
|
+
reported?: ReportedContextUsage;
|
|
24
|
+
modelLabel?: string;
|
|
25
|
+
computedAt?: Date;
|
|
26
|
+
/** Auto-compaction reserve (settings `reserveTokens`); omit when auto-compaction is disabled. */
|
|
27
|
+
autoCompactReserveTokens?: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 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
|
|
34
|
+
* every aggregate equals the exact sum of its children.
|
|
35
|
+
*/
|
|
36
|
+
export function computeUsage(inputs: UsageInputs): ContextUsageSnapshot {
|
|
37
|
+
const categories = [
|
|
38
|
+
...classifyPromptCategories(inputs.snapshot),
|
|
39
|
+
...classifyMessages(inputs.messages, contextOnlyMessages(inputs.snapshot)),
|
|
40
|
+
].filter(category => category.tokens > 0);
|
|
41
|
+
return {
|
|
42
|
+
computedAt: inputs.computedAt ?? new Date(),
|
|
43
|
+
modelLabel: inputs.modelLabel,
|
|
44
|
+
reported: inputs.reported,
|
|
45
|
+
categories,
|
|
46
|
+
estimatedTokens: categories.reduce((sum, category) => sum + category.tokens, 0),
|
|
47
|
+
autoCompactReserveTokens: inputs.autoCompactReserveTokens,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Flatten one category's preview entries across its breakdown, chronologically
|
|
53
|
+
* when every entry is message-backed. Raw entry text is process-local; the
|
|
54
|
+
* caller must sanitize before rendering and never log or persist it.
|
|
55
|
+
*/
|
|
56
|
+
export function collectPreviewEntries(category: UsageCategory): UsagePreviewEntry[] {
|
|
57
|
+
const entries: UsagePreviewEntry[] = [];
|
|
58
|
+
const visit = (node: UsageCategory): void => {
|
|
59
|
+
entries.push(...(node.entries ?? []));
|
|
60
|
+
for (const child of node.children ?? []) visit(child);
|
|
61
|
+
};
|
|
62
|
+
visit(category);
|
|
63
|
+
if (entries.length > 1 && entries.every(entry => entry.timestamp !== undefined)) {
|
|
64
|
+
entries.sort((a, b) => (a.timestamp ?? 0) - (b.timestamp ?? 0));
|
|
65
|
+
}
|
|
66
|
+
return entries;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Convert pi's nullable ContextUsage to the undefined-based model shape. */
|
|
70
|
+
export function toReportedUsage(usage: ContextUsage | undefined): ReportedContextUsage | undefined {
|
|
71
|
+
if (usage === undefined) return undefined;
|
|
72
|
+
return {
|
|
73
|
+
tokens: usage.tokens ?? undefined,
|
|
74
|
+
contextWindow: usage.contextWindow,
|
|
75
|
+
percent: usage.percent ?? undefined,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Map frozen snapshot items to prompt/tool/memory/skill categories. */
|
|
80
|
+
function classifyPromptCategories(snapshot: InitialSnapshot): UsageCategory[] {
|
|
81
|
+
const systemPrompt: UsageCategory[] = [];
|
|
82
|
+
const systemTools: UsageCategory[] = [];
|
|
83
|
+
const customTools: UsageCategory[] = [];
|
|
84
|
+
const mcpTools: UsageCategory[] = [];
|
|
85
|
+
const contextFiles: UsageCategory[] = [];
|
|
86
|
+
const skills: UsageCategory[] = [];
|
|
87
|
+
for (const group of snapshot.groups) {
|
|
88
|
+
for (const item of group.items) {
|
|
89
|
+
switch (item.kind) {
|
|
90
|
+
case 'base-prompt':
|
|
91
|
+
case 'append-prompt':
|
|
92
|
+
case 'prompt-addition':
|
|
93
|
+
systemPrompt.push(leafFromItem(item));
|
|
94
|
+
break;
|
|
95
|
+
case 'tool':
|
|
96
|
+
if (item.source.native) systemTools.push(...breakdownFromItem(item));
|
|
97
|
+
else if (isMcpTool(item)) mcpTools.push(leafFromItem(item));
|
|
98
|
+
else customTools.push(leafFromItem(item));
|
|
99
|
+
break;
|
|
100
|
+
case 'context-file':
|
|
101
|
+
contextFiles.push(leafFromItem(item));
|
|
102
|
+
break;
|
|
103
|
+
case 'skills':
|
|
104
|
+
skills.push(...breakdownFromItem(item));
|
|
105
|
+
break;
|
|
106
|
+
case 'message':
|
|
107
|
+
// Initial custom messages live in the session; classifyMessages counts them.
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
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
|
+
]);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Best-effort MCP attribution from the only public provenance field available. */
|
|
123
|
+
function isMcpTool(item: InjectionItem): boolean {
|
|
124
|
+
return /(^|[^a-z])mcp([^a-z]|$)/i.test(`${item.source.id} ${item.source.label}`);
|
|
125
|
+
}
|
|
126
|
+
|
|
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));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Classify live session messages and frozen context-only injections with preview entries. */
|
|
133
|
+
function classifyMessages(messages: ContextEvent['messages'], contextOnly: readonly InjectionItem[]): UsageCategory[] {
|
|
134
|
+
const user: UsagePreviewEntry[] = [];
|
|
135
|
+
const agentText: UsagePreviewEntry[] = [];
|
|
136
|
+
const agentThinking: UsagePreviewEntry[] = [];
|
|
137
|
+
const agentToolCalls: UsagePreviewEntry[] = [];
|
|
138
|
+
const bashExecutions: UsagePreviewEntry[] = [];
|
|
139
|
+
const compacted: UsagePreviewEntry[] = [];
|
|
140
|
+
const toolResults = new Map<string, UsagePreviewEntry[]>();
|
|
141
|
+
const customMessages = new Map<string, UsagePreviewEntry[]>();
|
|
142
|
+
|
|
143
|
+
for (const item of contextOnly) {
|
|
144
|
+
appendEntry(customMessages, item.source.label, {
|
|
145
|
+
breadcrumb: [item.label],
|
|
146
|
+
tokens: item.tokens,
|
|
147
|
+
text: item.text,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
for (const message of messages) {
|
|
151
|
+
switch (message.role) {
|
|
152
|
+
case 'user':
|
|
153
|
+
user.push({
|
|
154
|
+
timestamp: message.timestamp,
|
|
155
|
+
breadcrumb: ['user'],
|
|
156
|
+
tokens: estimateTokens(message),
|
|
157
|
+
text: contentToText(message.content),
|
|
158
|
+
});
|
|
159
|
+
break;
|
|
160
|
+
case 'assistant': {
|
|
161
|
+
const texts = message.content.flatMap(block => (block.type === 'text' ? [block.text] : []));
|
|
162
|
+
agentText.push(...blockEntries(message.timestamp, 'text', texts));
|
|
163
|
+
agentThinking.push(...thinkingEntries(message));
|
|
164
|
+
for (const block of message.content) {
|
|
165
|
+
if (block.type !== 'toolCall') continue;
|
|
166
|
+
const args = JSON.stringify(block.arguments);
|
|
167
|
+
agentToolCalls.push({
|
|
168
|
+
timestamp: message.timestamp,
|
|
169
|
+
breadcrumb: ['assistant', block.name],
|
|
170
|
+
tokens: textTokens(block.name.length + args.length),
|
|
171
|
+
text: `${block.name}(${args})`,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
case 'toolResult':
|
|
177
|
+
appendEntry(toolResults, message.toolName, {
|
|
178
|
+
timestamp: message.timestamp,
|
|
179
|
+
breadcrumb: [message.toolName],
|
|
180
|
+
tokens: estimateTokens(message),
|
|
181
|
+
text: contentToText(message.content),
|
|
182
|
+
});
|
|
183
|
+
break;
|
|
184
|
+
case 'custom':
|
|
185
|
+
appendEntry(customMessages, message.customType, {
|
|
186
|
+
timestamp: message.timestamp,
|
|
187
|
+
breadcrumb: [message.customType],
|
|
188
|
+
tokens: estimateTokens(message),
|
|
189
|
+
text: contentToText(message.content),
|
|
190
|
+
});
|
|
191
|
+
break;
|
|
192
|
+
case 'bashExecution': {
|
|
193
|
+
const tokens = transformedTokens(message);
|
|
194
|
+
// The transform drops `!!` bash executions: they never reach the provider.
|
|
195
|
+
if (tokens !== undefined) {
|
|
196
|
+
bashExecutions.push({
|
|
197
|
+
timestamp: message.timestamp,
|
|
198
|
+
breadcrumb: ['bash'],
|
|
199
|
+
tokens,
|
|
200
|
+
text: `$ ${message.command}\n${message.output}`,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
case 'branchSummary':
|
|
206
|
+
compacted.push({
|
|
207
|
+
timestamp: message.timestamp,
|
|
208
|
+
breadcrumb: ['branch'],
|
|
209
|
+
tokens: transformedTokens(message) ?? 0,
|
|
210
|
+
text: message.summary,
|
|
211
|
+
});
|
|
212
|
+
break;
|
|
213
|
+
case 'compactionSummary':
|
|
214
|
+
compacted.push({
|
|
215
|
+
timestamp: message.timestamp,
|
|
216
|
+
breadcrumb: ['compaction'],
|
|
217
|
+
tokens: transformedTokens(message) ?? 0,
|
|
218
|
+
text: message.summary,
|
|
219
|
+
});
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const toolOutput = aggregate(
|
|
225
|
+
'tool-output',
|
|
226
|
+
'Tool Output',
|
|
227
|
+
withoutEmpty([...leavesFromMap('tool-result', toolResults), leaf('bash-executions', 'Bash Executions', bashExecutions)]),
|
|
228
|
+
);
|
|
229
|
+
return withoutEmpty([
|
|
230
|
+
leaf('user-messages', 'User Messages', user),
|
|
231
|
+
leaf('agent-text-messages', 'Agent Text Messages', agentText),
|
|
232
|
+
leaf('agent-thinking-messages', 'Agent Thinking Messages', agentThinking),
|
|
233
|
+
leaf('agent-tool-call-messages', 'Agent Tool Call Messages', agentToolCalls),
|
|
234
|
+
toolOutput,
|
|
235
|
+
aggregate('extension-messages', 'Extensions', leavesFromMap('custom-message', customMessages)),
|
|
236
|
+
leaf('compacted-data', 'Compacted Data', compacted),
|
|
237
|
+
]);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** One category whose estimate is the exact sum of its preview entries. */
|
|
241
|
+
function leaf(id: string, label: string, entries: readonly UsagePreviewEntry[]): UsageCategory {
|
|
242
|
+
return {
|
|
243
|
+
id,
|
|
244
|
+
label,
|
|
245
|
+
tokens: entries.reduce((sum, entry) => sum + entry.tokens, 0),
|
|
246
|
+
entries,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Category carrying a snapshot item's label, estimate, and timeless content entry. */
|
|
251
|
+
function leafFromItem(item: InjectionItem): UsageCategory {
|
|
252
|
+
return {
|
|
253
|
+
id: `item:${item.id}`,
|
|
254
|
+
label: item.label,
|
|
255
|
+
tokens: item.tokens,
|
|
256
|
+
entries: [{ breadcrumb: [item.label], tokens: item.tokens, text: item.text }],
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Tokens for a message as pi's LLM transform actually sends it, so wrapper text
|
|
262
|
+
* `estimateTokens` alone cannot see (summary tags, `Ran ...` bash framing) is
|
|
263
|
+
* counted. Returns undefined for messages the transform excludes from context.
|
|
264
|
+
*/
|
|
265
|
+
function transformedTokens(message: ContextEvent['messages'][number]): number | undefined {
|
|
266
|
+
const converted = convertToLlm([message])[0];
|
|
267
|
+
return converted === undefined ? undefined : estimateTokens(converted);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Assistant-message shape narrowed out of the context event union. */
|
|
271
|
+
type AssistantContextMessage = Extract<ContextEvent['messages'][number], { role: 'assistant' }>;
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Build thinking previews while accounting once per assistant message. Provider-reported
|
|
275
|
+
* reasoning replaces a smaller visible-text estimate; signature-only estimates stay approximate metadata.
|
|
276
|
+
*/
|
|
277
|
+
function thinkingEntries(message: AssistantContextMessage): UsagePreviewEntry[] {
|
|
278
|
+
const texts = message.content.flatMap(block => (block.type === 'thinking' ? [block.thinking] : []));
|
|
279
|
+
const visibleTokens = textTokens(texts.reduce((sum, text) => sum + text.length, 0));
|
|
280
|
+
const reportedTokens = reportedReasoningTokens(message);
|
|
281
|
+
const countedTokens = Math.max(visibleTokens, reportedTokens ?? 0);
|
|
282
|
+
const signatureChars = message.content.reduce((sum, block) => {
|
|
283
|
+
if (block.type === 'thinking') return sum + stringLength(block.thinkingSignature);
|
|
284
|
+
if (block.type === 'toolCall') return sum + stringLength(block.thoughtSignature);
|
|
285
|
+
return sum;
|
|
286
|
+
}, 0);
|
|
287
|
+
const invisibleReasoning = createInvisibleReasoningEstimate(signatureChars, visibleTokens, reportedTokens);
|
|
288
|
+
|
|
289
|
+
if (texts.length === 0) {
|
|
290
|
+
if (countedTokens === 0 && invisibleReasoning === undefined) return [];
|
|
291
|
+
return [
|
|
292
|
+
{
|
|
293
|
+
timestamp: message.timestamp,
|
|
294
|
+
breadcrumb: ['assistant'],
|
|
295
|
+
tokens: countedTokens,
|
|
296
|
+
...(invisibleReasoning === undefined ? {} : { visibleTokens: 0, invisibleReasoning }),
|
|
297
|
+
text: '',
|
|
298
|
+
},
|
|
299
|
+
];
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const allocations = allocateTextTokens(texts);
|
|
303
|
+
const entries = texts.map(
|
|
304
|
+
(text, index): UsagePreviewEntry => ({
|
|
305
|
+
timestamp: message.timestamp,
|
|
306
|
+
breadcrumb: texts.length > 1 ? ['assistant', `thinking ${index + 1}/${texts.length}`] : ['assistant'],
|
|
307
|
+
tokens: allocations[index] ?? 0,
|
|
308
|
+
text,
|
|
309
|
+
}),
|
|
310
|
+
);
|
|
311
|
+
const first = entries[0];
|
|
312
|
+
if (first !== undefined) {
|
|
313
|
+
const countedInvisibleTokens = countedTokens - visibleTokens;
|
|
314
|
+
entries[0] = {
|
|
315
|
+
...first,
|
|
316
|
+
tokens: first.tokens + countedInvisibleTokens,
|
|
317
|
+
...(invisibleReasoning === undefined ? {} : { visibleTokens: first.tokens, invisibleReasoning }),
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
return entries;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Describe a positive invisible share or signature-size proxy without retaining its source bytes. */
|
|
324
|
+
function createInvisibleReasoningEstimate(
|
|
325
|
+
signatureChars: number,
|
|
326
|
+
visibleTokens: number,
|
|
327
|
+
reportedTokens: number | undefined,
|
|
328
|
+
): InvisibleReasoningEstimate | undefined {
|
|
329
|
+
if (reportedTokens !== undefined) {
|
|
330
|
+
const tokens = Math.max(0, reportedTokens - visibleTokens);
|
|
331
|
+
if (tokens === 0) return undefined;
|
|
332
|
+
return {
|
|
333
|
+
tokens,
|
|
334
|
+
basis: 'provider-reported',
|
|
335
|
+
encoded: signatureChars > 0,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
if (signatureChars === 0) return undefined;
|
|
339
|
+
// chars/4 over a signature is a rough proxy, not a bound: the server decrypts the
|
|
340
|
+
// envelope and counts the reconstructed thinking, at a model-dependent ratio that
|
|
341
|
+
// measured either side of 4. See doc/THINKING.md.
|
|
342
|
+
return {
|
|
343
|
+
tokens: textTokens(signatureChars),
|
|
344
|
+
basis: 'signature-proxy',
|
|
345
|
+
encoded: true,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** Accept only a finite, non-negative provider reasoning count from possibly old session data. */
|
|
350
|
+
function reportedReasoningTokens(message: AssistantContextMessage): number | undefined {
|
|
351
|
+
const usage: unknown = message.usage;
|
|
352
|
+
if (typeof usage !== 'object' || usage === null) return undefined;
|
|
353
|
+
const reasoning = (usage as { reasoning?: unknown }).reasoning;
|
|
354
|
+
return typeof reasoning === 'number' && Number.isFinite(reasoning) && reasoning >= 0 ? reasoning : undefined;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Pool chars/4 rounding across all blocks while retaining one preview entry per block. */
|
|
358
|
+
function allocateTextTokens(texts: readonly string[]): number[] {
|
|
359
|
+
const allocations = texts.map(text => Math.floor(text.length / 4));
|
|
360
|
+
const target = textTokens(texts.reduce((sum, text) => sum + text.length, 0));
|
|
361
|
+
let remainder = target - allocations.reduce((sum, tokens) => sum + tokens, 0);
|
|
362
|
+
const rankedIndexes = texts
|
|
363
|
+
.map((text, index) => ({ index, remainder: text.length % 4 }))
|
|
364
|
+
.filter(candidate => candidate.remainder > 0)
|
|
365
|
+
.sort((a, b) => b.remainder - a.remainder || a.index - b.index);
|
|
366
|
+
for (const candidate of rankedIndexes) {
|
|
367
|
+
if (remainder === 0) break;
|
|
368
|
+
allocations[candidate.index] = (allocations[candidate.index] ?? 0) + 1;
|
|
369
|
+
remainder--;
|
|
370
|
+
}
|
|
371
|
+
return allocations;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** String length from an optional or untyped signature field without exposing its contents. */
|
|
375
|
+
function stringLength(value: unknown): number {
|
|
376
|
+
return typeof value === 'string' ? value.length : 0;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Per-block entries; the block-index cell appears only for multi-block messages. */
|
|
380
|
+
function blockEntries(timestamp: number, kind: string, texts: readonly string[]): UsagePreviewEntry[] {
|
|
381
|
+
return texts.map((text, index) => ({
|
|
382
|
+
timestamp,
|
|
383
|
+
breadcrumb: texts.length > 1 ? ['assistant', `${kind} ${index + 1}/${texts.length}`] : ['assistant'],
|
|
384
|
+
tokens: textTokens(text.length),
|
|
385
|
+
text,
|
|
386
|
+
}));
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Text rendering of string-or-block message content; non-text blocks become placeholders. */
|
|
390
|
+
function contentToText(content: string | ReadonlyArray<{ type: string; text?: string }>): string {
|
|
391
|
+
if (typeof content === 'string') return content;
|
|
392
|
+
return content.map(block => (block.type === 'text' && block.text !== undefined ? block.text : `[${block.type}]`)).join('\n');
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Expand an aggregate snapshot item into its children, or itself when it has none. */
|
|
396
|
+
function breakdownFromItem(item: InjectionItem): UsageCategory[] {
|
|
397
|
+
if (item.children === undefined || item.children.length === 0) return [leafFromItem(item)];
|
|
398
|
+
return item.children.map(child => leafFromItem(child));
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** Parent category whose total is the exact sum of its children; undefined when empty. */
|
|
402
|
+
function aggregate(id: string, label: string, children: UsageCategory[]): UsageCategory | undefined {
|
|
403
|
+
if (children.length === 0) return undefined;
|
|
404
|
+
return {
|
|
405
|
+
id,
|
|
406
|
+
label,
|
|
407
|
+
tokens: children.reduce((sum, child) => sum + child.tokens, 0),
|
|
408
|
+
children: [...children].sort((a, b) => b.tokens - a.tokens),
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Keep only present categories with a non-zero estimate. */
|
|
413
|
+
function withoutEmpty(categories: Array<UsageCategory | undefined>): UsageCategory[] {
|
|
414
|
+
return categories.filter((category): category is UsageCategory => category !== undefined && category.tokens > 0);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Accumulate a preview entry under a map key. */
|
|
418
|
+
function appendEntry(totals: Map<string, UsagePreviewEntry[]>, key: string, entry: UsagePreviewEntry): void {
|
|
419
|
+
const entries = totals.get(key);
|
|
420
|
+
if (entries === undefined) totals.set(key, [entry]);
|
|
421
|
+
else entries.push(entry);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** Leaves from accumulated per-key preview entries. */
|
|
425
|
+
function leavesFromMap(idPrefix: string, totals: Map<string, UsagePreviewEntry[]>): UsageCategory[] {
|
|
426
|
+
return [...totals.entries()].map(([label, entries]) => leaf(`${idPrefix}:${label}`, label, entries));
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** Same chars/4 heuristic pi's estimateTokens uses for text content. */
|
|
430
|
+
function textTokens(chars: number): number {
|
|
431
|
+
return Math.ceil(chars / 4);
|
|
432
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import { ConfigLoader } from './config-loader';
|
|
3
3
|
import { registerAutoSessionName } from './extensions/auto-session-name';
|
|
4
|
+
import { registerContextView } from './extensions/context-view';
|
|
4
5
|
import { registerCustomFooter } from './extensions/custom-footer';
|
|
5
6
|
import { registerModelSelect } from './extensions/model-select';
|
|
6
7
|
|
|
@@ -15,4 +16,5 @@ export default function (pi: ExtensionAPI) {
|
|
|
15
16
|
registerAutoSessionName(pi, { config });
|
|
16
17
|
registerModelSelect(pi, { config });
|
|
17
18
|
registerCustomFooter(pi, { config });
|
|
19
|
+
registerContextView(pi, { config });
|
|
18
20
|
}
|
package/src/schemas/codemap.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Responsibility
|
|
4
4
|
|
|
5
|
-
This directory defines the Zod-based configuration schemas for the pi-qol plugin. It is the single source of truth for the shape, defaults, and validation rules of user-facing configuration. It covers the top-level config object and per-feature schemas for `auto-session-name`, `model-select` (including favourites, groups, tab visibility, provider filtering, and layout),
|
|
5
|
+
This directory defines the Zod-based configuration schemas for the pi-qol plugin. It is the single source of truth for the shape, defaults, and validation rules of user-facing configuration. It covers the top-level config object and per-feature schemas for `auto-session-name`, `model-select` (including favourites, groups, tab visibility, provider filtering, and layout), `custom-footer`, and disabled-by-default `context-view`, plus reusable shared schema building blocks.
|
|
6
6
|
|
|
7
7
|
## Design Patterns
|
|
8
8
|
|
|
@@ -17,7 +17,7 @@ This directory defines the Zod-based configuration schemas for the pi-qol plugin
|
|
|
17
17
|
|
|
18
18
|
1. **Input**: Raw JSON/user config enters the system.
|
|
19
19
|
2. **Validation**: The top-level `ConfigSchema.parse()` validates the whole object, falling back to per-field defaults for missing keys.
|
|
20
|
-
3. **Feature decomposition**: `ConfigSchema` delegates validation of each feature section to its dedicated schema (`AutoSessionNameConfigSchema`, `ModelSelectConfigSchema`, `CustomFooterConfigSchema`), which in turn use shared schemas (`ModelConfigSchema`, `ColorHexSchema`, `ReasoningLevelSchema`). `ModelSelectConfigSchema` also defines a `ModelSelectLayoutSchema` enum (`inline`/`overlay`) and `FavouriteModelSchema`, which omits `reasoning` from `ModelConfigSchema` and adds a `groups` array.
|
|
20
|
+
3. **Feature decomposition**: `ConfigSchema` delegates validation of each feature section to its dedicated schema (`AutoSessionNameConfigSchema`, `ModelSelectConfigSchema`, `CustomFooterConfigSchema`, `ContextViewConfigSchema`), which in turn use shared schemas (`ModelConfigSchema`, `ColorHexSchema`, `ReasoningLevelSchema`). `ModelSelectConfigSchema` also defines a `ModelSelectLayoutSchema` enum (`inline`/`overlay`) and `FavouriteModelSchema`, which omits `reasoning` from `ModelConfigSchema` and adds a `groups` array.
|
|
21
21
|
4. **Partial updates**: `PartialConfigSchema` and its feature-level partial variants allow validating incremental config changes without requiring a complete config object.
|
|
22
22
|
5. **Output**: Validated `Config` and `PartialConfig` types are exported for use by config loading, merging, and runtime feature code elsewhere in the plugin.
|
|
23
23
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import z from 'zod';
|
|
2
2
|
import { AutoSessionNameConfigSchema, PartialAutoSessionNameConfigSchema } from './auto-session-name.config.schema';
|
|
3
|
+
import { ContextViewConfigSchema, DEFAULT_CONTEXT_VIEW_CONFIG, PartialContextViewConfigSchema } from './context-view.config.schema';
|
|
3
4
|
import { CustomFooterConfigSchema, DEFAULT_CUSTOM_FOOTER_CONFIG, PartialCustomFooterConfigSchema } from './custom-footer-config.schema';
|
|
4
5
|
import { ModelSelectConfigSchema, PartialModelSelectConfigSchema } from './model-select.config.schema';
|
|
5
6
|
|
|
@@ -18,6 +19,7 @@ export const ConfigSchema = z.object({
|
|
|
18
19
|
layout: 'inline',
|
|
19
20
|
}),
|
|
20
21
|
custom_footer: CustomFooterConfigSchema.default(DEFAULT_CUSTOM_FOOTER_CONFIG),
|
|
22
|
+
context_view: ContextViewConfigSchema.default(DEFAULT_CONTEXT_VIEW_CONFIG),
|
|
21
23
|
});
|
|
22
24
|
export type Config = z.infer<typeof ConfigSchema>;
|
|
23
25
|
|
|
@@ -26,5 +28,6 @@ export const PartialConfigSchema = z.object({
|
|
|
26
28
|
auto_session_name: PartialAutoSessionNameConfigSchema.optional(),
|
|
27
29
|
model_select: PartialModelSelectConfigSchema.optional(),
|
|
28
30
|
custom_footer: PartialCustomFooterConfigSchema.optional(),
|
|
31
|
+
context_view: PartialContextViewConfigSchema.optional(),
|
|
29
32
|
});
|
|
30
33
|
export type PartialConfig = z.infer<typeof PartialConfigSchema>;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import z from 'zod';
|
|
2
|
+
|
|
3
|
+
export const ContextViewConfigSchema = z.object({
|
|
4
|
+
enabled: z.boolean().default(false),
|
|
5
|
+
});
|
|
6
|
+
export type ContextViewConfig = z.infer<typeof ContextViewConfigSchema>;
|
|
7
|
+
|
|
8
|
+
export const DEFAULT_CONTEXT_VIEW_CONFIG = ContextViewConfigSchema.parse({});
|
|
9
|
+
|
|
10
|
+
export const PartialContextViewConfigSchema = z.object({
|
|
11
|
+
enabled: z.boolean().optional(),
|
|
12
|
+
});
|
|
13
|
+
export type PartialContextViewConfig = z.infer<typeof PartialContextViewConfigSchema>;
|