@diousk/pi-usage-fast 0.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.
@@ -0,0 +1,152 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import { type ExtensionCommandContext, getSettingsListTheme } from "@earendil-works/pi-coding-agent";
3
+ import { Key, matchesKey, type SettingItem, SettingsList, Text } from "@earendil-works/pi-tui";
4
+ import { errorMessage } from "./core.js";
5
+ import type { UsageSettings, UsageSettingsRuntime } from "./settings.js";
6
+
7
+ const OFF = "Off";
8
+ const ON = "On";
9
+ const REMAINING = "Remaining";
10
+ const USED = "Used";
11
+
12
+ type UsageSettingId = "codexFastMode" | "codexStatusResetCountdown" | "codexStatusPercentage";
13
+
14
+ function settingValueLabel(id: UsageSettingId, value: UsageSettings[UsageSettingId]): string {
15
+ if (id === "codexStatusPercentage") return value === "used" ? USED : REMAINING;
16
+ return value === true ? ON : OFF;
17
+ }
18
+
19
+ export async function showUsageSettings(
20
+ ctx: ExtensionCommandContext,
21
+ settingsRuntime: UsageSettingsRuntime,
22
+ parentSignal: AbortSignal,
23
+ isCurrent: () => boolean,
24
+ onApplied: (id: UsageSettingId) => void,
25
+ ): Promise<boolean> {
26
+ if (ctx.mode !== "tui") {
27
+ if (ctx.hasUI) ctx.ui.notify(`Edit settings manually: ${settingsRuntime.get().path}`, "info");
28
+ return false;
29
+ }
30
+ const { HorizontalRule, renderBoundedFrame } = await import("@narumitw/pi-tui-kit");
31
+ if (parentSignal.aborted || !isCurrent()) return false;
32
+ return (
33
+ (await ctx.ui.custom<boolean>((tui, theme, _keybindings, done) => {
34
+ const localController = new AbortController();
35
+ const signal = AbortSignal.any([parentSignal, localController.signal]);
36
+ let changed = false;
37
+ let closing = false;
38
+ let saveQueue = Promise.resolve();
39
+ const state = settingsRuntime.get();
40
+ const items: SettingItem[] = [
41
+ {
42
+ id: "codexFastMode",
43
+ label: "Codex Fast mode",
44
+ description: "Use faster Codex routing at increased plan allowance consumption.",
45
+ currentValue: state.settings.codexFastMode ? ON : OFF,
46
+ values: [OFF, ON],
47
+ },
48
+ {
49
+ id: "codexStatusResetCountdown",
50
+ label: "Codex reset countdown",
51
+ description: "Show time remaining until each Codex usage limit resets.",
52
+ currentValue: state.settings.codexStatusResetCountdown ? ON : OFF,
53
+ values: [OFF, ON],
54
+ },
55
+ {
56
+ id: "codexStatusPercentage",
57
+ label: "Codex percentage",
58
+ description: "Show remaining or used Codex quota in the statusline.",
59
+ currentValue: settingValueLabel("codexStatusPercentage", state.settings.codexStatusPercentage),
60
+ values: [REMAINING, USED],
61
+ },
62
+ ];
63
+ const rule = new HorizontalRule({ ruleStyle: (text) => theme.fg("border", text) });
64
+
65
+ let settingsList: SettingsList;
66
+ const cancel = () => {
67
+ if (closing) return;
68
+ closing = true;
69
+ localController.abort();
70
+ done(changed);
71
+ };
72
+ const queueUpdate = <Id extends UsageSettingId>(id: Id, requested: UsageSettings[Id], display: string) => {
73
+ saveQueue = saveQueue.then(async () => {
74
+ const previous = settingsRuntime.get().settings[id];
75
+ if (settingsRuntime.get().kind === "invalid") {
76
+ settingsList.updateValue(id, settingValueLabel(id, previous));
77
+ if (!signal.aborted && isCurrent()) {
78
+ ctx.ui.notify("Repair pi-usage.json and reload before changing settings.", "error");
79
+ tui.requestRender();
80
+ }
81
+ return;
82
+ }
83
+ try {
84
+ const patch: Partial<UsageSettings> = {};
85
+ patch[id] = requested;
86
+ await settingsRuntime.update(patch, signal);
87
+ } catch (error) {
88
+ if (signal.aborted || !isCurrent()) return;
89
+ settingsList.updateValue(id, settingValueLabel(id, previous));
90
+ ctx.ui.notify(`Could not save pi-usage.json: ${errorMessage(error)}`, "error");
91
+ tui.requestRender();
92
+ return;
93
+ }
94
+ if (previous !== requested) {
95
+ changed = true;
96
+ onApplied(id);
97
+ }
98
+ if (signal.aborted || !isCurrent()) return;
99
+ settingsList.updateValue(id, display);
100
+ tui.requestRender();
101
+ });
102
+ };
103
+ settingsList = new SettingsList(
104
+ items,
105
+ items.length + 2,
106
+ getSettingsListTheme(),
107
+ (id, value) => {
108
+ if (closing || signal.aborted || !isCurrent()) return;
109
+ if (id === "codexStatusPercentage") {
110
+ queueUpdate(id, value === USED ? "used" : "remaining", value);
111
+ } else if (id === "codexFastMode" || id === "codexStatusResetCountdown") {
112
+ queueUpdate(id, value === ON, value);
113
+ }
114
+ },
115
+ cancel,
116
+ );
117
+
118
+ parentSignal.addEventListener("abort", cancel, { once: true });
119
+ return {
120
+ render(width: number) {
121
+ // Compatibility: Kit puts the title directly below the top rule and keeps compact
122
+ // rules when at least five rows fit; both replace the legacy wrapper layout.
123
+ const title = new Text(theme.fg("accent", theme.bold("pi-usage Settings")), 1, 0).render(width);
124
+ const content = settingsList.render(width);
125
+ const focusedRow = content.findIndex((line) => /^[→›]\s/u.test(stripVTControlCharacters(line)));
126
+ const terminalRows = Number.isFinite(tui.terminal?.rows) ? Math.floor(tui.terminal.rows) : 24;
127
+ const [ruleLine = ""] = rule.render(width);
128
+ return renderBoundedFrame({
129
+ width,
130
+ maxRows: Math.max(1, terminalRows - 3),
131
+ rule: ruleLine,
132
+ title,
133
+ content,
134
+ priorityRows: focusedRow < 0 ? [] : [focusedRow],
135
+ focusedRow,
136
+ });
137
+ },
138
+ invalidate: () => settingsList.invalidate(),
139
+ handleInput(data: string) {
140
+ if (closing) return;
141
+ if (matchesKey(data, Key.ctrl("c"))) cancel();
142
+ else settingsList.handleInput(data);
143
+ tui.requestRender();
144
+ },
145
+ dispose() {
146
+ localController.abort();
147
+ parentSignal.removeEventListener("abort", cancel);
148
+ },
149
+ };
150
+ })) ?? false
151
+ );
152
+ }
@@ -0,0 +1,127 @@
1
+ import { sanitizeDisplayText } from "./core.js";
2
+ import type { ResolvedUsageAuth, UsageProviderAdapter, UsageProviderTarget, UsageRequestGuard } from "./types.js";
3
+
4
+ const MAX_TARGETS = 1_000;
5
+ const MAX_TARGET_ID_CHARS = 256;
6
+ const MAX_TARGET_LABEL_CHARS = 120;
7
+ const MAX_TARGET_DESCRIPTION_CHARS = 180;
8
+
9
+ export type UsageTargetResolution =
10
+ | { kind: "selected"; targetId?: string }
11
+ | {
12
+ kind: "selection-required";
13
+ choices: readonly UsageProviderTarget[];
14
+ };
15
+
16
+ export interface UsageTargetSelectOptions {
17
+ options: readonly string[];
18
+ targetIdFor(option: string): string | undefined;
19
+ }
20
+
21
+ export async function resolveUsageTarget(
22
+ adapter: UsageProviderAdapter,
23
+ auth: ResolvedUsageAuth,
24
+ rememberedTargetId: string | undefined,
25
+ signal: AbortSignal,
26
+ timeoutMs: number,
27
+ guard: UsageRequestGuard,
28
+ ): Promise<UsageTargetResolution> {
29
+ if (!adapter.targets) return { kind: "selected" };
30
+ if (rememberedTargetId !== undefined && !isBoundedTargetId(rememberedTargetId)) {
31
+ throw new Error(`The remembered ${adapter.targets.singularLabel} identifier was invalid.`);
32
+ }
33
+ const choices = await listUsageTargets(adapter, auth, signal, timeoutMs, guard);
34
+ if (rememberedTargetId) {
35
+ return choices.some((choice) => choice.id === rememberedTargetId)
36
+ ? { kind: "selected", targetId: rememberedTargetId }
37
+ : { kind: "selection-required", choices };
38
+ }
39
+ if (choices.length === 1) return { kind: "selected", targetId: choices[0]?.id };
40
+ return { kind: "selection-required", choices };
41
+ }
42
+
43
+ export async function listUsageTargets(
44
+ adapter: UsageProviderAdapter,
45
+ auth: ResolvedUsageAuth,
46
+ signal: AbortSignal,
47
+ timeoutMs: number,
48
+ guard: UsageRequestGuard,
49
+ ): Promise<readonly UsageProviderTarget[]> {
50
+ if (!adapter.targets) return [];
51
+ const startedAt = Date.now();
52
+ await guard();
53
+ const listed = await adapter.targets.list(auth, signal, remainingTargetTimeout(timeoutMs, startedAt), guard);
54
+ await guard();
55
+ remainingTargetTimeout(timeoutMs, startedAt);
56
+ const choices = normalizeUsageTargets(listed);
57
+ if (choices.length === 0) {
58
+ throw new Error(`${adapter.targets.pluralLabel} discovery returned no choices.`);
59
+ }
60
+ return choices;
61
+ }
62
+
63
+ export function normalizeUsageTargets(targets: readonly UsageProviderTarget[]): readonly UsageProviderTarget[] {
64
+ if (!Array.isArray(targets)) throw new Error("Target discovery did not return a choices array.");
65
+ if (targets.length > MAX_TARGETS) {
66
+ throw new Error(`Target discovery exceeded ${MAX_TARGETS} choices.`);
67
+ }
68
+ const seen = new Set<string>();
69
+ return targets.map((target) => {
70
+ if (!target || typeof target !== "object" || Array.isArray(target)) {
71
+ throw new Error("Target discovery returned an invalid choice.");
72
+ }
73
+ const { id, label, description } = target as Partial<UsageProviderTarget>;
74
+ if (!isBoundedTargetId(id)) throw new Error("Target discovery returned an invalid ID.");
75
+ if (seen.has(id)) throw new Error(`Target discovery repeated ${id}.`);
76
+ seen.add(id);
77
+ if (typeof label !== "string") {
78
+ throw new Error("Target discovery returned an invalid display label.");
79
+ }
80
+ if (description !== undefined && typeof description !== "string") {
81
+ throw new Error("Target discovery returned an invalid description.");
82
+ }
83
+ const safeLabel = sanitizeDisplayText(label, MAX_TARGET_LABEL_CHARS);
84
+ if (!safeLabel) throw new Error("Target discovery returned an empty display label.");
85
+ const safeDescription = description ? sanitizeDisplayText(description, MAX_TARGET_DESCRIPTION_CHARS) : undefined;
86
+ return { id, label: safeLabel, ...(safeDescription ? { description: safeDescription } : {}) };
87
+ });
88
+ }
89
+
90
+ export function createUsageTargetSelectOptions(targets: readonly UsageProviderTarget[]): UsageTargetSelectOptions {
91
+ const normalized = normalizeUsageTargets(targets);
92
+ const ids = new Map<string, string>();
93
+ const options = normalized.map((target) => {
94
+ const base = target.description ? `${target.label} — ${target.description}` : target.label;
95
+ let option = base;
96
+ if (ids.has(option)) {
97
+ const safeId = sanitizeDisplayText(target.id, 80) || "target";
98
+ option = `${base} · ${safeId}`;
99
+ let duplicate = 2;
100
+ while (ids.has(option)) {
101
+ option = `${base} · ${safeId} (${duplicate})`;
102
+ duplicate += 1;
103
+ }
104
+ }
105
+ ids.set(option, target.id);
106
+ return option;
107
+ });
108
+ return { options, targetIdFor: (option) => ids.get(option) };
109
+ }
110
+
111
+ function remainingTargetTimeout(timeoutMs: number, startedAt: number): number {
112
+ const remaining = timeoutMs - (Date.now() - startedAt);
113
+ if (remaining <= 0) throw new Error("Timed out while discovering provider targets.");
114
+ return remaining;
115
+ }
116
+
117
+ export function isBoundedTargetId(value: unknown): value is string {
118
+ return (
119
+ typeof value === "string" &&
120
+ value.length > 0 &&
121
+ value.length <= MAX_TARGET_ID_CHARS &&
122
+ ![...value].some((character) => {
123
+ const codePoint = character.codePointAt(0) ?? 0;
124
+ return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
125
+ })
126
+ );
127
+ }