@herbertgao/pi-extensions 2026.10.9 → 2026.10.10

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 (26) hide show
  1. package/README.md +4 -2
  2. package/node_modules/@dietrichgebert/ponytail/.qoder-plugin/plugin.json +1 -1
  3. package/node_modules/@dietrichgebert/ponytail/README.md +16 -0
  4. package/node_modules/@dietrichgebert/ponytail/hooks/band/board.ts +560 -0
  5. package/node_modules/@dietrichgebert/ponytail/hooks/band/logo.ts +3 -0
  6. package/node_modules/@dietrichgebert/ponytail/hooks/band/metrics.ts +317 -0
  7. package/node_modules/@dietrichgebert/ponytail/hooks/band/register.tsx +472 -0
  8. package/node_modules/@dietrichgebert/ponytail/hooks/band/types.d.ts +35 -0
  9. package/node_modules/@dietrichgebert/ponytail/hooks/claude-band.json +6 -0
  10. package/node_modules/@dietrichgebert/ponytail/hooks/ponytail-band-import.js +274 -0
  11. package/node_modules/@dietrichgebert/ponytail/hooks/ponytail-mode-tracker.js +43 -5
  12. package/node_modules/@dietrichgebert/ponytail/package.json +1 -1
  13. package/node_modules/@dietrichgebert/ponytail/skills/ponytail/SKILL.md +1 -1
  14. package/node_modules/@dietrichgebert/ponytail/skills/ponytail-debt/SKILL.md +1 -2
  15. package/node_modules/@dietrichgebert/ponytail/skills/ponytail-gain/SKILL.md +0 -1
  16. package/node_modules/@dietrichgebert/ponytail/skills/ponytail-help/SKILL.md +6 -0
  17. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +7 -5
  18. package/node_modules/@herbertgao/pi-cc-extensions/README.md +3 -1
  19. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +5 -0
  20. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +11 -0
  21. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/token-rate.ts +21 -5
  22. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/working-message.ts +23 -4
  23. package/node_modules/@herbertgao/pi-cc-extensions/extensions/index.ts +1 -1
  24. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/markdown-enhance.ts +4 -128
  25. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  26. package/package.json +3 -3
@@ -0,0 +1,274 @@
1
+ #!/usr/bin/env node
2
+ // ponytail — imports past Claude Code sessions into the band's task ledger, so the board can
3
+ // compare them: cost, agent time, tokens, turns, name and model. Started in the background by
4
+ // `/ponytail band import`; also runs by hand. Sessions already in the ledger are left alone.
5
+
6
+ const fs = require('fs');
7
+ const os = require('os');
8
+ const path = require('path');
9
+ const { spawnSync } = require('child_process');
10
+ const { StringDecoder } = require('string_decoder');
11
+ const { getClaudeDir } = require('./ponytail-config');
12
+
13
+ // The band's columns (CSV_HEADER in hooks/band/metrics.ts; a test keeps the two equal).
14
+ const CSV_HEADER = 'key,started,project,name,cost_usd,turns,agent_minutes,tokens_total,tokens_output,reuse_pct,reused,new,callers_open,tests,level,model';
15
+
16
+ // USD per million tokens from https://platform.claude.com/docs/en/about-claude/pricing, checked
17
+ // 2026-10-17: [input, 5-minute cache write, 1-hour cache write, cache read, output]. Opus 5.5 and
18
+ // Fable 5.1 also match Claude Code's own totals in real transcripts. A model missing here, or a
19
+ // fast-mode reply, gets no estimate: an empty cost beats a guessed one.
20
+ const OPUS = [5, 6.25, 10, 0.5, 25];
21
+ const PRICES = {
22
+ 'claude-fable-5-1': [10, 12.5, 20, 0.25, 50],
23
+ 'claude-fable-5': [10, 12.5, 20, 1, 50],
24
+ 'claude-opus-5-5': [4, 5, 8, 0.2, 20],
25
+ 'claude-opus-5': OPUS,
26
+ 'claude-opus-4-8': OPUS,
27
+ 'claude-opus-4-7': OPUS,
28
+ 'claude-opus-4-6': OPUS,
29
+ 'claude-opus-4-5': OPUS,
30
+ 'claude-sonnet-5-5': [2, 2.5, 4, 0.1, 10],
31
+ 'claude-sonnet-5': [2, 2.5, 4, 0.2, 10],
32
+ 'claude-sonnet-4-6': [3, 3.75, 6, 0.3, 15],
33
+ 'claude-sonnet-4-5': [3, 3.75, 6, 0.3, 15],
34
+ 'claude-haiku-5-5': [0.1, 0.125, 0.2, 0.01, 0.5],
35
+ 'claude-haiku-4-5': [1, 1.25, 2, 0.1, 5],
36
+ };
37
+ // Haiku 5.5 bills a request whose prompt (input, cache reads and writes) is over 100,000 tokens higher.
38
+ const HAIKU_55_LONG = [0.5, 0.625, 1, 0.05, 2.5];
39
+ const WEB_SEARCH = 10 / 1000;
40
+ const IDLE_MS = 30 * 60000;
41
+ const modelId = m => m.replace(/\[.*\]$/, '').replace(/-\d{8}$/, '');
42
+
43
+ // One reply's price from its usage, or null when the price is not known.
44
+ function replyCost(model, u) {
45
+ let p = PRICES[modelId(model)];
46
+ if (!p || u.speed === 'fast') return null;
47
+ const cc = u.cache_creation || {};
48
+ const split = cc.ephemeral_5m_input_tokens !== undefined || cc.ephemeral_1h_input_tokens !== undefined;
49
+ const w5 = split ? cc.ephemeral_5m_input_tokens || 0 : u.cache_creation_input_tokens || 0;
50
+ const w1 = split ? cc.ephemeral_1h_input_tokens || 0 : 0;
51
+ const input = u.input_tokens || 0;
52
+ const read = u.cache_read_input_tokens || 0;
53
+ if (modelId(model) === 'claude-haiku-5-5' && input + read + w5 + w1 > 100000) p = HAIKU_55_LONG;
54
+ const searches = (u.server_tool_use && u.server_tool_use.web_search_requests) || 0;
55
+ return (input * p[0] + w5 * p[1] + w1 * p[2] + read * p[3] + (u.output_tokens || 0) * p[4]) / 1e6 + searches * WEB_SEARCH;
56
+ }
57
+
58
+ const human = r => r.type === 'user' && (r.turnOrigin === 'human' || (r.origin && r.origin.kind === 'human'));
59
+ const promptText = r => {
60
+ const c = r.message && r.message.content;
61
+ const t = typeof c === 'string' ? c : Array.isArray(c) ? (c.find(b => b && b.type === 'text') || {}).text || '' : '';
62
+ return t.trim();
63
+ };
64
+ const ms = r => (r.timestamp ? Date.parse(r.timestamp) : NaN);
65
+ const toolResult = r => (r.toolResult !== undefined ? r.toolResult
66
+ : Array.isArray(r.message && r.message.content) && r.message.content.some(b => b && b.type === 'tool_result'));
67
+
68
+ // Only what the numbers need from one record: a long session's transcript can pass 500 MB.
69
+ function slim(r) {
70
+ const m = r.message || {};
71
+ const c = human(r) ? m.content : undefined;
72
+ const text = typeof c === 'string' ? c.slice(0, 500)
73
+ : Array.isArray(c) ? c.filter(b => b && b.type === 'text').slice(0, 1).map(b => ({ type: 'text', text: String(b.text).slice(0, 500) })) : undefined;
74
+ return {
75
+ type: r.type, timestamp: r.timestamp, turnOrigin: r.turnOrigin, origin: r.origin && { kind: r.origin.kind },
76
+ isMeta: r.isMeta, toolResult: toolResult(r),
77
+ sessionId: r.sessionId, customTitle: r.customTitle, totalCostUSD: r.totalCostUSD,
78
+ message: { id: m.id, model: m.model, usage: m.usage, content: text },
79
+ };
80
+ }
81
+
82
+ // A JSONL file line by line, so no transcript is too big to read (one string stops at 512 MB).
83
+ function readRecords(file) {
84
+ const out = [];
85
+ const take = l => { if (l.startsWith('{')) try { out.push(slim(JSON.parse(l))); } catch (e) {} };
86
+ const fd = fs.openSync(file, 'r');
87
+ const buf = Buffer.alloc(1 << 20);
88
+ const dec = new StringDecoder('utf8');
89
+ let rest = '';
90
+ try {
91
+ for (let n; (n = fs.readSync(fd, buf, 0, buf.length, null)) > 0;) {
92
+ const parts = (rest + dec.write(buf.subarray(0, n))).split('\n');
93
+ rest = parts.pop();
94
+ parts.forEach(take);
95
+ }
96
+ take(rest + dec.end());
97
+ } finally {
98
+ fs.closeSync(fd);
99
+ }
100
+ return out;
101
+ }
102
+
103
+ // One session's numbers from its transcript records and its subagents' records. Null for a session
104
+ // nobody typed into (benchmarks, `claude -p`, scripts) or one without a model reply.
105
+ function sessionStats(records, subagentRecords = [], sessionId = '') {
106
+ const prompts = records.filter(human);
107
+ if (prompts.length === 0) return null;
108
+
109
+ // Usage repeats on every record of one message: count each message id once, subagents included.
110
+ const seen = new Set();
111
+ const replies = {};
112
+ let tokens = 0;
113
+ let output = 0;
114
+ let estimate = 0;
115
+ const reply = r => r.type === 'assistant' && r.message && r.message.model && r.message.model !== '<synthetic>';
116
+ for (const r of records) if (reply(r)) replies[r.message.model] = (replies[r.message.model] || 0) + 1;
117
+ for (const r of [...records, ...subagentRecords]) {
118
+ if (!reply(r)) continue;
119
+ const { id, model, usage } = r.message;
120
+ if (!usage || !id || seen.has(id)) continue;
121
+ seen.add(id);
122
+ tokens += (usage.input_tokens || 0) + (usage.output_tokens || 0) + (usage.cache_read_input_tokens || 0) + (usage.cache_creation_input_tokens || 0);
123
+ output += usage.output_tokens || 0;
124
+ const c = replyCost(model, usage);
125
+ estimate = estimate === null || c === null ? null : estimate + c;
126
+ }
127
+ const models = Object.keys(replies);
128
+ if (models.length === 0) return null;
129
+
130
+ // A turn starts with any new message: a typed prompt, a slash command (not marked as typed) or a
131
+ // background notification. It lasts until the model's last reply or tool result before the next
132
+ // one, so time waiting between messages, even days before a session is reopened, never counts.
133
+ let turns = 0;
134
+ let agentMs = 0;
135
+ const starts = r => r.type === 'user' && !toolResult(r) && !r.isMeta;
136
+ const at = records.map((r, i) => (starts(r) ? i : -1)).filter(i => i >= 0);
137
+ for (let k = 0; k < at.length; k++) {
138
+ const work = records.slice(at[k] + 1, k + 1 < at.length ? at[k + 1] : records.length)
139
+ .filter(r => r.type === 'assistant' || (r.type === 'user' && toolResult(r)));
140
+ if (!work.some(r => r.type === 'assistant')) continue;
141
+ turns++;
142
+ // A pause of over 30 minutes inside a turn is someone not answering a permission prompt, not work.
143
+ // shortcut: a single tool run over 30 minutes counts as zero; raise IDLE_MS if long builds go missing.
144
+ let prev = ms(records[at[k]]);
145
+ for (const t of work.map(ms).filter(Number.isFinite)) {
146
+ if (Number.isFinite(prev) && t > prev && t - prev <= IDLE_MS) agentMs += t - prev;
147
+ prev = Math.max(Number.isFinite(prev) ? prev : t, t);
148
+ }
149
+ }
150
+ if (turns === 0) return null;
151
+
152
+ // Two sources, and each can only miss calls: Claude Code's own total covers just its last
153
+ // process run (a reopened session can say $0), the estimate misses side calls the transcript
154
+ // does not log (titles, compaction, internal Haiku). So the larger one wins.
155
+ // shortcut: without an own total the estimate runs 0-15% low in real sessions; nothing better is logged.
156
+ const last = (a, f) => { for (let i = a.length - 1; i >= 0; i--) if (f(a[i])) return i; return -1; };
157
+ const costAt = last(records, r => r.type === 'cost-state' && (!sessionId || r.sessionId === sessionId));
158
+ const own = costAt >= 0 && last(records, r => r.type === 'assistant') < costAt ? records[costAt].totalCostUSD : null;
159
+ const known = [own, estimate].filter(v => typeof v === 'number' && Number.isFinite(v) && v > 0);
160
+ const cost = known.length ? Math.max(...known) : null;
161
+ const titled = records.filter(r => r.type === 'custom-title' && typeof r.customTitle === 'string' && r.customTitle.trim());
162
+ const first = prompts.map(promptText).find(t => t && !t.startsWith('<') && !t.startsWith('/')) || '';
163
+ const started = records.map(ms).find(Number.isFinite);
164
+ return {
165
+ startedMs: started,
166
+ name: (titled.length ? titled[titled.length - 1].customTitle.trim() : first.split('\n')[0]).slice(0, 60),
167
+ model: models.sort((a, b) => replies[b] - replies[a])[0],
168
+ cost,
169
+ own,
170
+ estimate,
171
+ turns,
172
+ agentMs,
173
+ tokens,
174
+ output,
175
+ };
176
+ }
177
+
178
+ // Same stamp and quoting as the band (hooks/band/metrics.ts), so the board reads both alike.
179
+ const two = n => String(n).padStart(2, '0');
180
+ const stamp = t => { const d = new Date(t); return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`; };
181
+ const field = v => { const s = v === null || v === undefined ? '' : String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; };
182
+
183
+ function csvRow(sessionId, project, s) {
184
+ return [`${sessionId.slice(0, 8)}-${s.startedMs}`, stamp(s.startedMs), project, s.name, s.cost === null ? '' : s.cost.toFixed(2), s.turns,
185
+ (s.agentMs / 60000).toFixed(1), s.tokens, s.output, '', '', '', '', '', 'import', s.model].map(field).join(',');
186
+ }
187
+
188
+ // New rows go in after the ledger's own: a newer header replaces an older one, and a session
189
+ // already recorded anywhere in the ledger (same session id prefix) is never imported twice.
190
+ const sessionOf = row => row.slice(0, 9);
191
+ function mergeRows(existing, rows, have = new Set()) {
192
+ const kept = existing.split('\n').filter(l => l !== '' && !l.startsWith('key,'));
193
+ const added = rows.filter(r => !have.has(sessionOf(r)) && !kept.some(l => sessionOf(l) === sessionOf(r)));
194
+ return { text: [CSV_HEADER, ...kept, ...added].join('\n') + '\n', added: added.length };
195
+ }
196
+
197
+ const TEMP = [os.tmpdir(), '/tmp/', '/private/tmp/', '/var/folders/', '/private/var/folders/'];
198
+ // A worktree counts for its main repo: the desktop app's <repo>/.claude/worktrees/<name> even
199
+ // after it is gone, and any git worktree through its common .git dir.
200
+ function projectOf(cwd, cache) {
201
+ if (!cache.has(cwd)) {
202
+ let root = cwd.split(/[\\/]\.claude[\\/]worktrees[\\/]/)[0];
203
+ if (fs.existsSync(root)) {
204
+ const git = spawnSync('git', ['-C', root, 'rev-parse', '--path-format=absolute', '--git-common-dir'], { encoding: 'utf8' });
205
+ if (git.status === 0 && /[\\/]\.git$/.test(git.stdout.trim())) root = path.dirname(git.stdout.trim());
206
+ }
207
+ cache.set(cwd, path.basename(root.replace(/[\\/]+$/, '')));
208
+ }
209
+ return cache.get(cwd);
210
+ }
211
+
212
+ function ledgerDir() {
213
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'ponytail', 'band');
214
+ }
215
+
216
+ function run() {
217
+ const root = path.join(getClaudeDir(), 'projects');
218
+ const byProject = new Map();
219
+ const roots = new Map();
220
+ let dirs = [];
221
+ try { dirs = fs.readdirSync(root); } catch (e) { return { sessions: 0, added: 0 }; }
222
+ let sessions = 0;
223
+ for (const dir of dirs) {
224
+ let files = [];
225
+ try { files = fs.readdirSync(path.join(root, dir)).filter(f => f.endsWith('.jsonl')); } catch (e) { continue; }
226
+ for (const file of files) {
227
+ const p = path.join(root, dir, file);
228
+ // The working dir sits in the first records; scratch and temp dirs are never real projects.
229
+ let head = '';
230
+ try { const fd = fs.openSync(p, 'r'); const b = Buffer.alloc(65536); head = b.toString('utf8', 0, fs.readSync(fd, b, 0, b.length, 0)); fs.closeSync(fd); } catch (e) { continue; }
231
+ const m = /"cwd":"((?:[^"\\]|\\.)*)"/.exec(head);
232
+ if (!m) continue;
233
+ const cwd = JSON.parse(`"${m[1]}"`);
234
+ if (TEMP.some(t => cwd.startsWith(t)) || cwd === '/tmp') continue;
235
+ // A session's first prompt is typed by a person; automated runs (benchmarks, `claude -p`) never are.
236
+ if (head.includes('"type":"user"') && !/"turnOrigin":"human"|"origin":\{"kind":"human"/.test(head)) continue;
237
+ const id = file.slice(0, -'.jsonl'.length);
238
+ let records;
239
+ try { records = readRecords(p); } catch (e) { continue; }
240
+ const sub = path.join(root, dir, id, 'subagents');
241
+ let subRecords = [];
242
+ try { subRecords = fs.readdirSync(sub).filter(f => /^agent-.*\.jsonl$/.test(f)).flatMap(f => readRecords(path.join(sub, f))); } catch (e) {}
243
+ const stats = sessionStats(records, subRecords, id);
244
+ if (!stats || !Number.isFinite(stats.startedMs)) continue;
245
+ sessions++;
246
+ const project = projectOf(cwd, roots);
247
+ if (!byProject.has(project)) byProject.set(project, []);
248
+ byProject.get(project).push(csvRow(id, project, stats));
249
+ }
250
+ }
251
+ const dir = ledgerDir();
252
+ fs.mkdirSync(dir, { recursive: true });
253
+ const have = new Set();
254
+ for (const f of fs.readdirSync(dir).filter(f => f.endsWith('.csv'))) {
255
+ try { fs.readFileSync(path.join(dir, f), 'utf8').split('\n').forEach(l => l && !l.startsWith('key,') && have.add(sessionOf(l))); } catch (e) {}
256
+ }
257
+ let added = 0;
258
+ for (const [project, rows] of byProject) {
259
+ const file = path.join(dir, `${project.replace(/[^\w.-]/g, '_')}.csv`);
260
+ let existing = '';
261
+ try { existing = fs.readFileSync(file, 'utf8'); } catch (e) {}
262
+ const merged = mergeRows(existing, rows, have);
263
+ if (merged.added > 0) fs.writeFileSync(file, merged.text);
264
+ added += merged.added;
265
+ }
266
+ return { sessions, added };
267
+ }
268
+
269
+ if (require.main === module) {
270
+ const { sessions, added } = run();
271
+ process.stdout.write(`ponytail band import: ${sessions} past sessions found, ${added} new rows in the board.\n`);
272
+ }
273
+
274
+ module.exports = { CSV_HEADER, PRICES, replyCost, sessionStats, csvRow, mergeRows, readRecords, run };
@@ -2,12 +2,17 @@
2
2
  // ponytail — UserPromptSubmit hook to track which ponytail mode is active
3
3
  // Inspects user input for /ponytail commands and writes mode to flag file
4
4
 
5
- const { getDefaultMode, isDeactivationCommand, writeDefaultMode } = require('./ponytail-config');
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { spawn } = require('child_process');
8
+ const { getClaudeDir, getDefaultMode, isDeactivationCommand, writeDefaultMode } = require('./ponytail-config');
6
9
  const {
7
10
  clearMode,
8
11
  cursorRuleNotice,
9
12
  cursorRulePath,
13
+ isCodeBuddy,
10
14
  isCodex,
15
+ isCopilot,
11
16
  isCursor,
12
17
  isQoder,
13
18
  readMode,
@@ -42,6 +47,7 @@ function finish() {
42
47
  // Match /ponytail commands
43
48
  let modeSwitched = false;
44
49
  let deactivated = false;
50
+ let defaultNotice = '';
45
51
  if (/^[/@$]ponytail/.test(prompt)) {
46
52
  const parts = prompt.split(/\s+/);
47
53
  const cmd = parts[0].replace(/^[@$]/, '/');
@@ -62,9 +68,39 @@ function finish() {
62
68
  const dmode = parts[2];
63
69
  if (dmode === 'off' || dmode === 'lite' || dmode === 'full' || dmode === 'ultra') {
64
70
  writeDefaultMode(dmode);
65
- writeHookOutput('UserPromptSubmit', dmode, 'PONYTAIL DEFAULT SET — new sessions start in ' + dmode + '.');
71
+ defaultNotice = 'PONYTAIL DEFAULT SET — new sessions start in ' + dmode + '.';
72
+ if (!isQoder) writeHookOutput('UserPromptSubmit', dmode, defaultNotice);
66
73
  }
67
- return; // don't fall through to the session-mode switch
74
+ // Qoder still needs this turn's ruleset: the block below folds the
75
+ // notice into it. mode stays null, so the session level is untouched.
76
+ if (!isQoder) return; // don't fall through to the session-mode switch
77
+ }
78
+ // `/ponytail band [on|off]` shows or hides the band above the Claude Code
79
+ // prompt (hooks/band reads this flag). It outlives the session; absent = shown.
80
+ // Other hosts have no band, so there the word stays an unknown argument.
81
+ if (arg === 'band' && !isCopilot && !isCodex && !isQoder && !isCodeBuddy && !isCursor) {
82
+ // `/ponytail band import`: past sessions into the board, in the background, so the prompt
83
+ // is answered right away while the transcripts are read. Detached, it outlives this hook's
84
+ // process.exit below.
85
+ if (parts[2] === 'import') {
86
+ spawn(process.execPath, [path.join(__dirname, 'ponytail-band-import.js')], { detached: true, stdio: 'ignore' });
87
+ writeHookOutput('UserPromptSubmit', readMode() || 'off', 'PONYTAIL BAND IMPORT: past Claude Code sessions (cost, agent time, tokens) are being added to the board in the background. Open the board in a minute. Confirm in one short line.');
88
+ return;
89
+ }
90
+ const flag = path.join(getClaudeDir(), '.ponytail-band');
91
+ let hidden = false;
92
+ try { hidden = fs.readFileSync(flag, 'utf8').trim() === 'off'; } catch (e) {}
93
+ const show = parts[2] === 'on' ? true : parts[2] === 'off' ? false : hidden;
94
+ if (show) {
95
+ try { fs.unlinkSync(flag); } catch (e) {}
96
+ } else {
97
+ fs.mkdirSync(path.dirname(flag), { recursive: true });
98
+ fs.writeFileSync(flag, 'off');
99
+ }
100
+ writeHookOutput('UserPromptSubmit', readMode() || 'off', show
101
+ ? 'PONYTAIL BAND ON: the band shows above the prompt again. The ponytail level is unchanged. Confirm in one short line.'
102
+ : 'PONYTAIL BAND OFF: the band above the prompt is hidden, `/ponytail band` brings it back. The ponytail level is unchanged. Confirm in one short line.');
103
+ return;
68
104
  }
69
105
  if (arg === 'lite') mode = 'lite';
70
106
  else if (arg === 'full') mode = 'full';
@@ -146,10 +182,12 @@ function finish() {
146
182
  if (currentMode && currentMode !== 'off') {
147
183
  // ponytail: one JSON per invocation — mode-switch confirmation is
148
184
  // folded into the ruleset header so Qoder gets both in one write.
149
- const header = modeSwitched
185
+ const header = (defaultNotice ? defaultNotice + '\n\n' : '') + (modeSwitched
150
186
  ? 'PONYTAIL MODE CHANGED — level: ' + currentMode + '\n\n'
151
- : '';
187
+ : '');
152
188
  writeHookOutput('UserPromptSubmit', currentMode, header + getPonytailInstructions(currentMode));
189
+ } else if (defaultNotice) {
190
+ writeHookOutput('UserPromptSubmit', currentMode, defaultNotice);
153
191
  }
154
192
  }
155
193
  } catch (e) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dietrichgebert/ponytail",
3
- "version": "5.2.0",
3
+ "version": "5.3.2",
4
4
  "description": "Lazy senior dev mode for AI agents. The best code is the code you never wrote.",
5
5
  "keywords": ["opencode-plugin", "opencode", "ponytail", "pi-package", "pi", "skills", "qoder"],
6
6
  "license": "MIT",
@@ -6,7 +6,7 @@ description: >
6
6
  fixing, refactoring, reviewing, choosing dependencies) and when the user says
7
7
  "ponytail", "be lazy", "simplest solution", "yagni", or complains about
8
8
  over-engineering or bloat. Levels: lite, full (default), ultra.
9
- argument-hint: "[lite|full|ultra]"
9
+ argument-hint: "[lite|full|ultra|off]"
10
10
  license: MIT
11
11
  ---
12
12
 
@@ -41,5 +41,4 @@ End with `<N> markers, <M> with no trigger.` Nothing found: `No shortcut debt. C
41
41
  ## Boundaries
42
42
 
43
43
  Reads and reports only, changes nothing. To persist it, ask and it writes the
44
- ledger to a file (e.g. `PONYTAIL-DEBT.md`). One-shot. "stop ponytail-debt" or
45
- "normal mode" to revert.
44
+ ledger to a file (e.g. `PONYTAIL-DEBT.md`). One-shot.
@@ -50,4 +50,3 @@ this card points there instead of inventing one.
50
50
  ## Boundaries
51
51
 
52
52
  One-shot display. Edits nothing, changes no mode.
53
- "stop ponytail" or "normal mode": revert.
@@ -40,6 +40,12 @@ slash-command forms above (OpenCode ships all six as slash commands).
40
40
  Say "stop ponytail" or "normal mode". Resume anytime with `/ponytail`.
41
41
  `/ponytail off` also works.
42
42
 
43
+ ## Band (Claude Code)
44
+
45
+ `/ponytail band` hides the band above the prompt, the same command brings it back.
46
+ `/ponytail band on` and `/ponytail band off` set it directly. The level stays.
47
+ `/ponytail band import` adds your past Claude Code sessions (cost, agent time, tokens) to the board.
48
+
43
49
  ## Configure Default Mode
44
50
 
45
51
  Default mode = `full`, auto-active every session. Change it:
@@ -28,7 +28,7 @@ Run `/reload` after installation.
28
28
  | Feature | Description | Entry point |
29
29
  | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
30
30
  | Claude Code UI | Tool summaries, expand/collapse, rich edit/write diffs, and `on` / `compact` / `off` modes | `/ccstyle` |
31
- | Markdown enhancements | Mermaid diagrams, admonitions, URL linking, and more | Automatic |
31
+ | Markdown enhancements | Mermaid dialects and circled-number conversion | Automatic; turn off with `enableMarkdownEnhance: false` |
32
32
  | Fullscreen mode | Tool card/group expand and collapse on click, previews, hover highlight, and a back-to-bottom button | `TUIMODE=fullscreen` or `--tui-mode fullscreen` |
33
33
  | Settings panel | `Style / Features / UI / Diff / Thinking / Footer` tabs | `/ccstyle` |
34
34
  | Context inspection | Usage breakdown and previews for the system prompt, memory, skills, tools definition, and messages | `/context` |
@@ -55,6 +55,7 @@ Renderer snapshots for `on` / `compact` modes: [default](./docs/tool-render-exam
55
55
  "enableAgentSummary": true, // per-turn tool summary
56
56
  "enableWorkingMessage": true, // Working... bottom token/elapsed
57
57
  "enableAliases": true, // /clear, /exit aliases
58
+ "enableMarkdownEnhance": true, // markdown pass: Mermaid dialects and circled-number conversion; false hands it to other extensions
58
59
  "enableEditorPrefix": true, // editor ❯ prefix
59
60
 
60
61
  // ui
@@ -117,10 +118,11 @@ pi -e . # one run, does not edit settings.json
117
118
 
118
119
  ## Recommended companions
119
120
 
120
- | Extension | Purpose |
121
- | ------------------------ | ----------------------------------------------------------- |
122
- | `npm:pi-web-access` | Web search, URL fetching, GitHub cloning, PDF/video parsing |
123
- | `npm:@narumitw/pi-usage` | Current-account usage for Codex / Copilot / OpenRouter |
121
+ | Extension | Purpose |
122
+ | ---------------------------------------- | ----------------------------------------------------------- |
123
+ | `npm:pi-web-access` | Web search, URL fetching, GitHub cloning, PDF/video parsing |
124
+ | `npm:@narumitw/pi-usage` | Current-account usage for Codex / Copilot / OpenRouter |
125
+ | `npm:@juicesharp/rpiv-ask-user-question` | Multiple-choice questionnaire the model can ask you |
124
126
 
125
127
  ## Credits
126
128
 
@@ -28,7 +28,7 @@ pi install git:github.com/HerbertGao/pi-extensions
28
28
  | 功能 | 说明 | 入口 |
29
29
  | --------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------- |
30
30
  | Claude Code UI | 工具摘要、折叠展开、rich edit/write diff,以及`on` / `compact` / `off` 三种模式 | `/ccstyle` |
31
- | Markdown 增强 | Mermaid 图、提示框、URL 链接化等 | 自动生效 |
31
+ | Markdown 增强 | Mermaid 方言渲染、圈数字转半角括号 | 自动生效;`enableMarkdownEnhance: false` 关闭 |
32
32
  | Fullscreen mode | 工具卡/group 单击展开与收起、预览、hover 高亮、回到底部按钮 | `TUIMODE=fullscreen` 或 `--tui-mode fullscreen` |
33
33
  | 配置面板 | `Style / Features / UI / Diff / Thinking / Footer` 六页签 | `/ccstyle` |
34
34
  | 上下文检查 | 查看上下文占用,并预览 System prompt、Memory、Skills、Tools definition 和消息内容 | `/context` |
@@ -55,6 +55,7 @@ pi install git:github.com/HerbertGao/pi-extensions
55
55
  "enableAgentSummary": true, // 每回合工具摘要
56
56
  "enableWorkingMessage": true, // Working... 底部 token/耗时
57
57
  "enableAliases": true, // /clear、/exit 别名
58
+ "enableMarkdownEnhance": true, // markdown 转换:Mermaid 方言渲染、圈数字转半角括号;false 让位给其他扩展
58
59
  "enableEditorPrefix": true, // 输入框 ❯ 前缀
59
60
 
60
61
  // ui
@@ -120,6 +121,7 @@ pi -e . # 只跑一次,不改 settings.json
120
121
  | ---------------------------------------- | ------------------------------------------------ |
121
122
  | `npm:pi-web-access` | 网页搜索、URL 抓取、GitHub 克隆、PDF/视频解析 |
122
123
  | `npm:@narumitw/pi-usage` | 查看当前账号用量(Codex / Copilot / OpenRouter) |
124
+ | `npm:@juicesharp/rpiv-ask-user-question` | 模型拿不准时向你提问的选择题面板 |
123
125
 
124
126
  ## 致谢
125
127
 
@@ -74,6 +74,8 @@ export type Config = {
74
74
  enableAgentSummary: boolean;
75
75
  enableWorkingMessage: boolean;
76
76
  enableAliases: boolean;
77
+ /** markdown 转换:Mermaid 方言渲染、圈数字转半角括号。关掉让位给其他扩展。 */
78
+ enableMarkdownEnhance: boolean;
77
79
  /** 输入框 `❯ ` 前缀(占左侧 2 列,颜色随 thinking/bash mode 联动)。 */
78
80
  enableEditorPrefix: boolean;
79
81
  enableCustomFooter: boolean;
@@ -157,6 +159,7 @@ export const DEFAULT_CONFIG: Config = {
157
159
  enableAgentSummary: true,
158
160
  enableWorkingMessage: true,
159
161
  enableAliases: true,
162
+ enableMarkdownEnhance: true,
160
163
  enableEditorPrefix: true,
161
164
  enableCustomFooter: true,
162
165
  footerTokenRate: true,
@@ -290,6 +293,7 @@ export function normalizeConfig(input: unknown): Config {
290
293
  enableAgentSummary: source.enableAgentSummary !== false,
291
294
  enableWorkingMessage: source.enableWorkingMessage !== false,
292
295
  enableAliases: source.enableAliases !== false,
296
+ enableMarkdownEnhance: source.enableMarkdownEnhance !== false,
293
297
  enableEditorPrefix: (source.enableEditorPrefix ?? source.enableInputPrompt) !== false, // 兼容旧配置键
294
298
  enableCustomFooter: source.enableCustomFooter !== false,
295
299
  footerTokenRate: source.footerTokenRate !== false,
@@ -361,6 +365,7 @@ export function formatConfigStatus(source: Config = config): string {
361
365
  `agentSummary=${source.enableAgentSummary ? "on" : "off"}`,
362
366
  `workingMsg=${source.enableWorkingMessage ? "on" : "off"}`,
363
367
  `aliases=${source.enableAliases ? "on" : "off"}`,
368
+ `markdownEnhance=${source.enableMarkdownEnhance ? "on" : "off"}`,
364
369
  `editorPrefix=${source.enableEditorPrefix ? "on" : "off"}`,
365
370
  `footer=${source.enableCustomFooter ? "on" : "off"}`,
366
371
  `footerTokenRate=${source.footerTokenRate ? "on" : "off"}`,
@@ -181,6 +181,7 @@ function buildFooterChipsSubmenu(
181
181
  () => onClose(),
182
182
  { enableSearch: false },
183
183
  );
184
+ // SAFETY: SettingsList stores these as plain fields; disabled search keeps indices in items.
184
185
  const listState = list as unknown as { selectedIndex: number; items: typeof items };
185
186
 
186
187
  const mutate = (transform: (layout: FooterChipLayout, key: string) => FooterChipLayout) => {
@@ -656,6 +657,13 @@ export async function showCcstylePanel(
656
657
  "Aliases disabled.",
657
658
  config.enableAliases,
658
659
  );
660
+ const markdownEnhanceToggle = featureToggleSetting(
661
+ "enableMarkdownEnhance",
662
+ "Markdown enhance",
663
+ "Mermaid dialects and circled-number conversion. Next restart applies.",
664
+ "Markdown enhancements off; another extension can own the markdown pass.",
665
+ config.enableMarkdownEnhance,
666
+ );
659
667
  const footerCurrencySetting = {
660
668
  id: "footerCurrency",
661
669
  label: "Cost currency",
@@ -798,6 +806,7 @@ export async function showCcstylePanel(
798
806
  enableAgentSummary: agentSummaryToggle,
799
807
  enableWorkingMessage: workingMessageToggle,
800
808
  enableAliases: aliasesToggle,
809
+ enableMarkdownEnhance: markdownEnhanceToggle,
801
810
  };
802
811
 
803
812
  const onSettingChange = (id: string, value: string) => {
@@ -1049,6 +1058,7 @@ export async function showCcstylePanel(
1049
1058
  agentSummaryToggle.setting,
1050
1059
  workingMessageToggle.setting,
1051
1060
  aliasesToggle.setting,
1061
+ markdownEnhanceToggle.setting,
1052
1062
  ],
1053
1063
  },
1054
1064
  {
@@ -1122,6 +1132,7 @@ export async function showCcstylePanel(
1122
1132
 
1123
1133
  /** 数值项:当前选中项有 submenu + values 时,Space 仅循环预设,不打开子面板。 */
1124
1134
  const cyclePresetInList = (list: InstanceType<typeof SettingsList>): boolean => {
1135
+ // SAFETY: SettingsList exposes these runtime fields, and these lists disable search.
1125
1136
  const internal = list as unknown as {
1126
1137
  submenuComponent: unknown;
1127
1138
  items: {
@@ -3,8 +3,10 @@
3
3
  *
4
4
  * average:一次用户指令的墙钟平均(工具等待计入分母),显示 `avg`。
5
5
  * live:最近 1 秒的瞬时速率,生成期暂停时钟,显示 `live`;指令结束定格为整段平均。
6
- * token 与 working-message 同源:优先 provider `usage.output`,否则按 delta 增量估算
7
- * (CJK 1 token,其余 chars/4)。provider 值回填到本段消息窗口。
6
+ * token 与 working-message 同源:变大的 provider `usage.output` 覆盖估算,否则按 delta 累加
7
+ * (CJK 1 token,其余 chars/4)。没有变大的 usage 不当作累计值:Anthropic 的 message_start
8
+ * 会给出一个很小的 output_tokens,并在每个 partial 上重复,直到最后的 message_delta。
9
+ * 消息结束时用 message_end 上的 usage 定格本段总量。
8
10
  * Pi 的 turn 是单次 assistant 消息,工具调用结束会开新 turn。token 跨 turn 累加,
9
11
  * 计时与 TTFT 直到下一条用户指令才重置。
10
12
  * TTFT:用户指令开始到第一个内容块(text/thinking/toolcall)开始的毫秒数,
@@ -120,15 +122,29 @@ export function sampleTokenDelta(delta: string, now = Date.now()): void {
120
122
  }
121
123
 
122
124
  /**
123
- * 记录本段 provider `usage.output`。usage 按锚点摊回窗口:
125
+ * 记录本段 provider `usage.output`。变大的 usage 按锚点摊回窗口:
124
126
  * 首次报告从消息起点铺到现在,之后每次把增量摊在上次报告之后。
127
+ * 没有变大的报告直接忽略,避免 message_start 的占位值反复覆盖 delta 累计。
128
+ * `final` 用于消息结束:以本次 output 为本段总量,估算偏高偏低都按它修正。
129
+ * 结束值含未逐字流出的思考 token,它们不属于最近一秒,所以窗口只整体平移,不回填。
125
130
  */
126
- export function recordProviderUsage(output: number, now = Date.now()): void {
131
+ export function recordProviderUsage(output: number, now = Date.now(), final = false): void {
127
132
  if (!runStartTime || output <= 0) return;
133
+ if (final) {
134
+ const shift = output - currentTokens;
135
+ for (const sample of samples) sample.cum += shift;
136
+ countedUsage = output;
137
+ currentTokens = output;
138
+ usageAnchorTime = now;
139
+ usageAnchorTokens = output;
140
+ updateRates(now);
141
+ return;
142
+ }
143
+ if (output <= countedUsage) return;
128
144
  const firstReport = countedUsage === 0;
129
145
  const jump = output - countedUsage;
130
146
  countedUsage = output;
131
- // provider 是权威计数;首次报告以它为准,之后增量接管。
147
+ // 变大的 provider 计数是权威值,覆盖本段估算。
132
148
  currentTokens = output;
133
149
  if (firstReport) {
134
150
  samples = samples.filter((sample) => sample.t < usageAnchorTime);
@@ -49,9 +49,9 @@ export default function (pi: ExtensionAPI): void {
49
49
  return totalTokens();
50
50
  }
51
51
 
52
- function updateProviderUsage(message: StreamMessage): void {
52
+ function updateProviderUsage(message: StreamMessage, final = false): void {
53
53
  const output = outputUsage(message);
54
- if (output > 0) recordProviderUsage(output);
54
+ if (output > 0) recordProviderUsage(output, Date.now(), final);
55
55
  }
56
56
 
57
57
  function buildWorkingMessage(): string {
@@ -171,13 +171,20 @@ export default function (pi: ExtensionAPI): void {
171
171
  // 分段锚点只在 turn_start 重置。这里再重置会把累计 usage.output 当成新的首报。
172
172
  markFirstToken();
173
173
  updateProviderUsage(evt.partial);
174
- } else if (evt.type === "thinking_delta" || evt.type === "text_delta") {
174
+ } else if (
175
+ evt.type === "thinking_delta" ||
176
+ evt.type === "text_delta" ||
177
+ evt.type === "toolcall_delta"
178
+ ) {
179
+ // 工具参数走 toolcall_delta;不计入的话,写长文件这类调用期间 token 一直不涨。
175
180
  if (typeof evt.delta === "string") sampleTokenDelta(evt.delta);
176
181
  updateProviderUsage(evt.partial);
177
182
  } else if (evt.type === "text_end" || evt.type === "thinking_end") {
178
183
  updateProviderUsage(evt.partial);
179
184
  } else if (evt.type === "done") {
180
- updateProviderUsage(evt.message);
185
+ // Pi 目前不会把 done/error 转成 message_update,定格在下面的 message_end 里做。
186
+ // 这两个分支只在宿主直接转发 done/error 时生效;同一个值重复定格不改变结果。
187
+ updateProviderUsage(evt.message, true);
181
188
  } else if (evt.type === "error") {
182
189
  updateProviderUsage(evt.error);
183
190
  } else {
@@ -188,6 +195,18 @@ export default function (pi: ExtensionAPI): void {
188
195
  scheduleRefreshTick();
189
196
  });
190
197
 
198
+ // message_delta 的累计 usage 只出现在 message_end 上,含未逐字流出的思考 token。
199
+ // message_end 在工具执行和 turn_end 之前,先于 carryTokenRate 结转。
200
+ pi.on("message_end", async (event, ctx) => {
201
+ const message = event?.message;
202
+ if (message?.role !== "assistant") return;
203
+ activeCtx = ctx;
204
+ // 出错/中断时 usage 可能还是 message_start 的占位值,只接受变大的值。
205
+ const failed = message.stopReason === "error" || message.stopReason === "aborted";
206
+ updateProviderUsage(message, !failed);
207
+ syncWorkingMessage();
208
+ });
209
+
191
210
  pi.on("tool_execution_start", async () => {
192
211
  pauseTokenRate();
193
212
  });