@0xkahi/pi-qol 1.1.1 → 1.1.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xkahi/pi-qol",
3
- "version": "1.1.1",
3
+ "version": "1.1.3",
4
4
  "description": "quality of life pi extensions",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -111,7 +111,7 @@ export class CustomFooterComponent implements Component {
111
111
 
112
112
  private renderStatsLine(width: number, config: CustomFooterConfig): string {
113
113
  const model = this.deps.ctx.model;
114
- const usingSubscription = model ? this.deps.ctx.modelRegistry.isUsingOAuth(model) : false;
114
+ const usingSubscription = model ? this.isUsingSubscription(model) : false;
115
115
  const contextUsage = this.deps.ctx.getContextUsage();
116
116
  const contextWindow = contextUsage?.contextWindow ?? model?.contextWindow ?? 0;
117
117
  const subscriptionUsageSegment = this.renderSubscriptionUsageSegment(config, usingSubscription);
@@ -158,6 +158,14 @@ export class CustomFooterComponent implements Component {
158
158
  return `${statsLeft}${' '.repeat(Math.max(0, width - statsLeftWidth - truncatedRightWidth))}${truncatedRight}`;
159
159
  }
160
160
 
161
+ private isUsingSubscription(model: NonNullable<CustomFooterComponentDeps['ctx']['model']>): boolean {
162
+ if (model.provider === 'kimi-coding') return true;
163
+
164
+ return (
165
+ this.deps.ctx.modelRegistry.isUsingOAuth(model) && this.deps.ctx.modelRegistry.getProvider(model.provider)?.auth?.oauth?.isSubscription === true
166
+ );
167
+ }
168
+
161
169
  private buildModelNameSegment(config: CustomFooterConfig): string {
162
170
  const model = this.deps.ctx.model;
163
171
  const modelName = model?.id ?? 'no-model';
@@ -1,4 +1,5 @@
1
1
  import { dye } from '@0xkahi/cli-dye';
2
+ import type { Usage } from '@earendil-works/pi-ai';
2
3
  import type { ContextUsage, SessionEntry } from '@earendil-works/pi-coding-agent';
3
4
  import { clampPercent, renderProgressBar } from './progress-bar';
4
5
  import type { CustomFooterColors, CustomFooterDisplay, CustomFooterIcons, FooterTheme, SupportedProvider, UsageTotals } from './types';
@@ -40,22 +41,30 @@ export function calculateUsageTotals(entries: readonly SessionEntry[]): UsageTot
40
41
  };
41
42
 
42
43
  for (const entry of entries) {
43
- if (entry.type !== 'message' || entry.message.role !== 'assistant') continue;
44
-
45
- const usage = entry.message.usage;
46
- totals.totalInput += usage.input;
47
- totals.totalOutput += usage.output;
48
- totals.totalCacheRead += usage.cacheRead;
49
- totals.totalCacheWrite += usage.cacheWrite;
50
- totals.totalCost += usage.cost.total;
51
-
52
- const latestPromptTokens = usage.input + usage.cacheRead + usage.cacheWrite;
53
- totals.latestCacheHitRate = latestPromptTokens > 0 ? (usage.cacheRead / latestPromptTokens) * 100 : undefined;
44
+ if (entry.type === 'message' && entry.message.role === 'assistant') {
45
+ const usage = entry.message.usage;
46
+ addUsageToTotals(totals, usage);
47
+
48
+ const latestPromptTokens = usage.input + usage.cacheRead + usage.cacheWrite;
49
+ totals.latestCacheHitRate = latestPromptTokens > 0 ? (usage.cacheRead / latestPromptTokens) * 100 : undefined;
50
+ } else if (entry.type === 'message' && entry.message.role === 'toolResult' && entry.message.usage) {
51
+ addUsageToTotals(totals, entry.message.usage);
52
+ } else if ((entry.type === 'usage' || entry.type === 'branch_summary' || entry.type === 'compaction') && entry.usage) {
53
+ addUsageToTotals(totals, entry.usage);
54
+ }
54
55
  }
55
56
 
56
57
  return totals;
57
58
  }
58
59
 
60
+ function addUsageToTotals(totals: UsageTotals, usage: Usage): void {
61
+ totals.totalInput += usage.input;
62
+ totals.totalOutput += usage.output;
63
+ totals.totalCacheRead += usage.cacheRead;
64
+ totals.totalCacheWrite += usage.cacheWrite;
65
+ totals.totalCost += usage.cost.total;
66
+ }
67
+
59
68
  export function buildSubscriptionUsageSegment({
60
69
  colors,
61
70
  icons,
@@ -1,29 +1,56 @@
1
- import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
1
+ import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
2
2
  import type { ConfigLoader } from '../../config-loader';
3
3
 
4
- export function activateWorkmux(pi: ExtensionAPI) {
4
+ type AssistantState = { stopReason?: string; errorMessage?: string };
5
+
6
+ export function registerWorkmux(pi: ExtensionAPI, deps: { config: ConfigLoader }) {
7
+ let sessionActive = false;
8
+ let writes = Promise.resolve();
9
+
5
10
  function setStatus(status: string) {
6
- pi.exec('workmux', ['set-window-status', status]).catch(() => {});
11
+ writes = writes.then(async () => {
12
+ await pi.exec('workmux', ['set-window-status', status]).catch(() => {});
13
+ });
14
+ return writes;
15
+ }
16
+
17
+ function latestAssistantWasAborted(ctx: ExtensionContext) {
18
+ const branch = ctx.sessionManager.getBranch() as Array<{
19
+ type?: string;
20
+ message?: AssistantState & { role?: string };
21
+ }>;
22
+ for (let index = branch.length - 1; index >= 0; index--) {
23
+ const entry = branch[index];
24
+ if (entry?.type !== 'message' || entry.message?.role !== 'assistant') continue;
25
+ return (
26
+ entry.message.stopReason === 'aborted' ||
27
+ (entry.message.stopReason === 'error' && /\boperation was aborted\b/i.test(entry.message.errorMessage ?? ''))
28
+ );
29
+ }
30
+ return false;
7
31
  }
8
32
 
9
33
  pi.on('session_start', async () => {
10
- setStatus('waiting');
34
+ sessionActive = false;
35
+ await writes;
36
+ if (!deps.config.isEnabled('workmux')) return;
37
+ await pi.exec('workmux', ['register-agent']).catch(() => {});
38
+ sessionActive = true;
11
39
  });
12
40
 
13
41
  pi.on('agent_start', async () => {
14
- setStatus('working');
42
+ if (!sessionActive) return;
43
+ await setStatus('working');
15
44
  });
16
45
 
17
- pi.on('agent_end', async () => {
18
- setStatus('done');
46
+ pi.on('agent_settled', async (_event, ctx) => {
47
+ if (!sessionActive) return;
48
+ if (latestAssistantWasAborted(ctx)) return;
49
+ await setStatus('done');
19
50
  });
20
- }
21
51
 
22
- export function registerWorkmux(pi: ExtensionAPI, deps: { config: ConfigLoader }) {
23
- let registered = false;
24
- pi.on('session_start', (_event, _ctx) => {
25
- if (registered || !deps.config.isEnabled('workmux')) return;
26
- activateWorkmux(pi);
27
- registered = true;
52
+ pi.on('session_shutdown', async () => {
53
+ sessionActive = false;
54
+ await writes;
28
55
  });
29
56
  }
@@ -1,5 +1,10 @@
1
1
  import { RawDataParser } from '../../../utils/raw-data-parser.util';
2
- import type { ProviderAuth, RateWindow, SubscriptionUsageStrategy } from '../subscription-usage-api.util';
2
+ import {
3
+ type ProviderAuth,
4
+ type RateWindow,
5
+ SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS,
6
+ type SubscriptionUsageStrategy,
7
+ } from '../subscription-usage-api.util';
3
8
 
4
9
  export class AnthropicOauthUsageStrategy implements SubscriptionUsageStrategy {
5
10
  readonly provider = 'anthropic';
@@ -7,6 +12,8 @@ export class AnthropicOauthUsageStrategy implements SubscriptionUsageStrategy {
7
12
 
8
13
  async fetchUsage(auth: ProviderAuth) {
9
14
  const response = await fetch(this.request(auth));
15
+ if (!response.ok) return;
16
+
10
17
  const data = RawDataParser.asRecord(await response.json());
11
18
  if (!data) return;
12
19
 
@@ -26,12 +33,13 @@ export class AnthropicOauthUsageStrategy implements SubscriptionUsageStrategy {
26
33
  resetAt: resetDate && Number.isFinite(resetDate.getTime()) ? resetDate : undefined,
27
34
  });
28
35
  }
29
- return windows;
36
+ return windows.length > 0 ? windows : undefined;
30
37
  }
31
38
 
32
39
  private request(opts: ProviderAuth) {
33
40
  return new Request('https://api.anthropic.com/api/oauth/usage', {
34
41
  method: 'GET',
42
+ signal: AbortSignal.timeout(SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS),
35
43
  headers: {
36
44
  Authorization: `Bearer ${opts.token}`,
37
45
  'anthropic-beta': 'oauth-2025-04-20',
@@ -1,5 +1,10 @@
1
1
  import { RawDataParser } from '../../../utils/raw-data-parser.util';
2
- import type { ProviderAuth, RateWindow, SubscriptionUsageStrategy } from '../subscription-usage-api.util';
2
+ import {
3
+ type ProviderAuth,
4
+ type RateWindow,
5
+ SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS,
6
+ type SubscriptionUsageStrategy,
7
+ } from '../subscription-usage-api.util';
3
8
 
4
9
  const PRIMARY_WINDOW_FALLBACK_SECONDS = 10800;
5
10
  const SECONDARY_WINDOW_FALLBACK_SECONDS = 86400;
@@ -65,6 +70,7 @@ export class OpenAiCodexUsageStrategy implements SubscriptionUsageStrategy {
65
70
  private request(opts: ProviderAuth) {
66
71
  return new Request('https://chatgpt.com/backend-api/wham/usage', {
67
72
  method: 'GET',
73
+ signal: AbortSignal.timeout(SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS),
68
74
  headers: {
69
75
  Authorization: `Bearer ${opts.token}`,
70
76
  ...(opts?.accountId ? { 'ChatGPT-Account-Id': opts.accountId } : {}),
@@ -2,6 +2,8 @@ import { readFileSync } from 'node:fs';
2
2
  import { PathUtil } from '../../utils/path.util';
3
3
  import { RawDataParser } from '../../utils/raw-data-parser.util';
4
4
 
5
+ export const SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS = 10_000;
6
+
5
7
  export type ProviderAuth = {
6
8
  token: string;
7
9
  accountId?: string;