@erichll/pi-statusline 0.4.1 → 0.6.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/CHANGELOG.md +80 -0
- package/README.md +152 -296
- package/examples/statusline.json +10 -1
- package/package.json +1 -1
- package/src/config.ts +14 -4
- package/src/index.ts +10 -3
- package/src/panel.ts +6 -6
- package/src/quota.ts +186 -0
- package/src/render.ts +75 -12
- package/src/runtime-render.ts +114 -41
- package/src/runtime.ts +25 -7
- package/src/session.ts +26 -5
- package/src/tools.ts +43 -0
- package/src/types.ts +6 -1
package/src/config.ts
CHANGED
|
@@ -10,12 +10,12 @@ export function validColor(value: unknown): value is ColorValue {
|
|
|
10
10
|
return typeof value === "string" && (/^#[\da-f]{6}$/i.test(value) || (COLORS as readonly string[]).includes(value));
|
|
11
11
|
}
|
|
12
12
|
export function presetConfig(): StatuslineConfig {
|
|
13
|
-
const enabled = new Set<string>(["model", "thinking", "directory", "git", "context", "tokens", "statuses"]);
|
|
13
|
+
const enabled = new Set<string>(["model", "thinking", "directory", "git", "context", "quota", "session", "tokens", "statuses"]);
|
|
14
14
|
return {
|
|
15
15
|
version: 1, enabled: true, preset: "powerline", icons: "nerd",
|
|
16
16
|
separator: "powerline", pathMode: "basename", modelDisplay: "name", contextDisplay: "bar", spacing: 1,
|
|
17
17
|
segments: SEGMENT_IDS.map((id) => ({ id, enabled: enabled.has(id) })),
|
|
18
|
-
runtime: { enabled: true, status: true, tools: true, noContent: true, noContentSeconds: 10, avg: true, cache: true, counts: true, retainSummary: true },
|
|
18
|
+
runtime: { enabled: true, status: true, tools: true, noContent: true, noContentSeconds: 10, avg: true, cache: true, counts: true, retainSummary: true, toolsMaxVisible: 4 },
|
|
19
19
|
};
|
|
20
20
|
}
|
|
21
21
|
function record(value: unknown): value is Record<string, unknown> {
|
|
@@ -54,7 +54,8 @@ export function parseConfig(raw: unknown): StatuslineConfig {
|
|
|
54
54
|
if (key === "noContentSeconds") {
|
|
55
55
|
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 3600) throw new Error("Invalid runtime.noContentSeconds (1–3600)");
|
|
56
56
|
config.runtime.noContentSeconds = value;
|
|
57
|
-
} else (
|
|
57
|
+
} else if (key === "toolsMaxVisible") config.runtime.toolsMaxVisible = integer(value, 1, 8, "runtime.toolsMaxVisible");
|
|
58
|
+
else (config[group] as unknown as Record<string, unknown>)[key] = boolean(value, `${group}.${key}`);
|
|
58
59
|
}
|
|
59
60
|
}
|
|
60
61
|
if (raw.segments !== undefined) {
|
|
@@ -78,7 +79,16 @@ export function parseConfig(raw: unknown): StatuslineConfig {
|
|
|
78
79
|
}
|
|
79
80
|
return result;
|
|
80
81
|
});
|
|
81
|
-
//
|
|
82
|
+
// Upgrade older lists once with segments added later; an explicit entry (including disabled) wins.
|
|
83
|
+
const insert = (id: "quota" | "session", index: number) => {
|
|
84
|
+
if (seen.has(id)) return;
|
|
85
|
+
config.segments.splice(index < 0 ? config.segments.length : index, 0, { id, enabled: true });
|
|
86
|
+
seen.add(id);
|
|
87
|
+
};
|
|
88
|
+
const contextIndex = config.segments.findIndex((segment) => segment.id === "context");
|
|
89
|
+
insert("quota", contextIndex < 0 ? -1 : contextIndex + 1);
|
|
90
|
+
insert("session", config.segments.findIndex((segment) => segment.id === "tokens"));
|
|
91
|
+
// All other omissions remain editable but disabled.
|
|
82
92
|
for (const id of SEGMENT_IDS) if (!seen.has(id)) config.segments.push({ id, enabled: false });
|
|
83
93
|
}
|
|
84
94
|
return config;
|
package/src/index.ts
CHANGED
|
@@ -24,13 +24,20 @@ export default function statusline(pi: ExtensionAPI): void {
|
|
|
24
24
|
session.install();
|
|
25
25
|
});
|
|
26
26
|
pi.on("session_shutdown", () => { generation++; session?.dispose(); session = undefined; });
|
|
27
|
+
pi.on("before_provider_request", (_event, ctx) => { session?.setContext(ctx); session?.beginProviderRequest(); });
|
|
28
|
+
pi.on("after_provider_response", (event, ctx) => { session?.setContext(ctx); session?.observeProviderResponse(event.headers); });
|
|
29
|
+
pi.on("provider_stream_event", (event, ctx) => {
|
|
30
|
+
if (!session?.active) return;
|
|
31
|
+
// Observe native quota events as well as disqualifying routed/mismatched requests.
|
|
32
|
+
if (session.quota.observeStream(event.provider, event.model, event.api, ctx.model, event.data)) session.schedule(true);
|
|
33
|
+
});
|
|
27
34
|
pi.on("agent_start", (_event, ctx) => { session?.setContext(ctx); session?.startRun(); session?.schedule(true); });
|
|
28
35
|
pi.on("turn_start", (_event, ctx) => { session?.setContext(ctx); session?.startTurn(); session?.schedule(true); });
|
|
29
36
|
pi.on("agent_before_settle", (event) => { session?.runtime.beforeSettle(event.outcome); });
|
|
30
37
|
pi.on("agent_settled", (_event, ctx) => { session?.setContext(ctx); session?.settle(); session?.schedule(true); });
|
|
31
38
|
pi.on("ui_prompt_start", () => { session?.runtime.uiStart(); session?.schedule(true); });
|
|
32
39
|
pi.on("ui_prompt_end", () => { session?.runtime.uiEnd(); session?.schedule(true); });
|
|
33
|
-
pi.on("tool_execution_start", (event, ctx) => { session?.setContext(ctx); session?.runtime.toolStart(event.toolCallId, event.toolName); session?.schedule(true); });
|
|
40
|
+
pi.on("tool_execution_start", (event, ctx) => { session?.setContext(ctx); session?.runtime.toolStart(event.toolCallId, event.toolName, event.args, event.parentToolCallId); session?.schedule(true); });
|
|
34
41
|
pi.on("session_before_compact", (_event, ctx) => {
|
|
35
42
|
session?.setContext(ctx); session?.compaction.start(); session?.runtime.compaction(true); session?.schedule(true);
|
|
36
43
|
});
|
|
@@ -53,7 +60,7 @@ export default function statusline(pi: ExtensionAPI): void {
|
|
|
53
60
|
const resetLive = (event: unknown, ctx: ExtensionContext) => { session?.setLive(undefined); refresh(event, ctx); };
|
|
54
61
|
pi.on("agent_end", resetLive);
|
|
55
62
|
pi.on("turn_end", (event, ctx) => { if (event.message.role === "assistant") session?.runtime.message(event.message, true); session?.runtime.turnEnd(); refresh(event, ctx); });
|
|
56
|
-
pi.on("model_select", refresh);
|
|
63
|
+
pi.on("model_select", (event, ctx) => { session?.quota.clear(); refresh(event, ctx); });
|
|
57
64
|
pi.on("thinking_level_select", refresh);
|
|
58
65
|
pi.on("session_compact", (event, ctx) => {
|
|
59
66
|
session?.compaction.finish("success", event.compactionEntry.id); session?.runtime.compaction(false); resetLive(event, ctx);
|
|
@@ -62,7 +69,7 @@ export default function statusline(pi: ExtensionAPI): void {
|
|
|
62
69
|
session?.compaction.finish(event.aborted ? "cancelled" : "failed", undefined, event.errorMessage); session?.runtime.compaction(false); refresh(event, ctx);
|
|
63
70
|
});
|
|
64
71
|
pi.on("session_tree", resetLive);
|
|
65
|
-
pi.on("tool_execution_end", (event, ctx) => { session?.setContext(ctx); session?.runtime.toolEnd(event.toolCallId); session?.requestGit(); session?.schedule(true); });
|
|
72
|
+
pi.on("tool_execution_end", (event, ctx) => { session?.setContext(ctx); session?.runtime.toolEnd(event.toolCallId, event.isError); session?.requestGit(); session?.schedule(true); });
|
|
66
73
|
pi.on("user_bash", (_event, ctx) => { session?.setContext(ctx); session?.requestGit(); });
|
|
67
74
|
|
|
68
75
|
pi.registerCommand("statusline", {
|
package/src/panel.ts
CHANGED
|
@@ -41,7 +41,7 @@ export class StatuslinePanel implements Component, Focusable {
|
|
|
41
41
|
}
|
|
42
42
|
private items(): SelectItem[] {
|
|
43
43
|
if (this.section) {
|
|
44
|
-
const labels: Record<string, string> = { enabled: "Runtime metrics", status: "
|
|
44
|
+
const labels: Record<string, string> = { enabled: "Runtime metrics", status: "Run status, elapsed and compaction status", tools: "Tool activity row", noContent: "No content warning", noContentSeconds: "No content threshold (seconds)", avg: "Average output speed", cache: "Cache read ratio", counts: "Turns and compactions", retainSummary: "Retain last run summary", toolsMaxVisible: "Completed tool kinds shown" };
|
|
45
45
|
return [...Object.entries(this.draft[this.section]).map(([key, value]) => ({ value: `option:${key}`, label: `${labels[key] ?? key}: ${value}` })), { value: "back", label: "Back to settings" }];
|
|
46
46
|
}
|
|
47
47
|
if (this.editing) {
|
|
@@ -64,7 +64,7 @@ export class StatuslinePanel implements Component, Focusable {
|
|
|
64
64
|
{ value: "modelDisplay", label: `Model display: ${this.draft.modelDisplay}`, description: "name: display name · last: final model ID component" },
|
|
65
65
|
{ value: "contextDisplay", label: `Context display: ${this.draft.contextDisplay}`, description: "text: tokens/capacity(percent) · bar: progress and percent" },
|
|
66
66
|
{ value: "spacing", label: `Spacing above statusline: ${this.draft.spacing}`, description: "Blank lines between the input box and the statusline (0–3)" },
|
|
67
|
-
...this.draft.segments.filter((segment) => segment.id !== "thinking").map((segment) => ({ value: `segment:${segment.id}`, label: `[${segment.enabled ? "x" : " "}] ${segment.id}`, description: segment.id === "statuses" ? "
|
|
67
|
+
...this.draft.segments.filter((segment) => segment.id !== "thinking").map((segment) => ({ value: `segment:${segment.id}`, label: `[${segment.enabled ? "x" : " "}] ${segment.id}`, description: segment.id === "statuses" || segment.id === "session" || segment.id === "tokens" ? "Runtime row · Space toggles, Enter edits" : segment.id === "quota" ? "Subscription Usage · passive headers/events; hidden without data" : "Space toggles · Alt+Up/Down reorders · Enter edits" })),
|
|
68
68
|
{ value: "runtime", label: "Runtime options" },
|
|
69
69
|
{ value: "save", label: "Save and apply globally" },
|
|
70
70
|
{ value: "reset", label: "Restore defaults in preview" },
|
|
@@ -93,12 +93,12 @@ export class StatuslinePanel implements Component, Focusable {
|
|
|
93
93
|
if (this.section) {
|
|
94
94
|
if (value === "back") { this.cancel(); return; }
|
|
95
95
|
const key = value.slice("option:".length);
|
|
96
|
-
if (key === "noContentSeconds") {
|
|
97
|
-
this.input = new Input(); this.input.focused = this.hasFocus; this.input.setValue(String(this.draft.runtime
|
|
98
|
-
this.inputLabel = "No content threshold (1–3600 seconds)";
|
|
96
|
+
if (key === "noContentSeconds" || key === "toolsMaxVisible") {
|
|
97
|
+
this.input = new Input(); this.input.focused = this.hasFocus; this.input.setValue(String(this.draft.runtime[key]));
|
|
98
|
+
this.inputLabel = key === "noContentSeconds" ? "No content threshold (1–3600 seconds)" : "Completed tool kinds shown before +N (1–8)";
|
|
99
99
|
this.input.onEscape = () => this.cancel();
|
|
100
100
|
this.input.onSubmit = (text) => {
|
|
101
|
-
try { this.draft = parseConfig({ ...this.draft, runtime: { ...this.draft.runtime,
|
|
101
|
+
try { this.draft = parseConfig({ ...this.draft, runtime: { ...this.draft.runtime, [key]: Number(text) } }); this.input = undefined; this.error = ""; this.rebuild(value); }
|
|
102
102
|
catch (error) { this.error = error instanceof Error ? error.message : String(error); }
|
|
103
103
|
};
|
|
104
104
|
} else {
|
package/src/quota.ts
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
interface QuotaModel { provider: string; id: string; api: string; baseUrl: string; }
|
|
2
|
+
|
|
3
|
+
export interface QuotaWindow {
|
|
4
|
+
usedPercent: number;
|
|
5
|
+
resetAtSeconds: number;
|
|
6
|
+
/** Window length reported upstream; optional, and never guessed. */
|
|
7
|
+
windowMinutes?: number;
|
|
8
|
+
}
|
|
9
|
+
export interface SubscriptionQuota {
|
|
10
|
+
primary?: QuotaWindow;
|
|
11
|
+
secondary?: QuotaWindow;
|
|
12
|
+
}
|
|
13
|
+
export interface QuotaSnapshot {
|
|
14
|
+
primary?: QuotaWindow & { resetInMinutes: number };
|
|
15
|
+
secondary?: QuotaWindow & { resetInMinutes: number };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function headerNumber(value: unknown): number | undefined {
|
|
19
|
+
if (typeof value !== "string" || !/^\d+(?:\.\d+)?$/.test(value)) return undefined;
|
|
20
|
+
const number = Number(value);
|
|
21
|
+
return Number.isFinite(number) && number >= 0 ? number : undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function validatedWindow(usedPercent: unknown, resetAtSeconds: unknown, windowMinutes?: unknown): QuotaWindow | undefined {
|
|
25
|
+
if (typeof usedPercent !== "number" || !Number.isFinite(usedPercent) || usedPercent < 0 || usedPercent > 100) return undefined;
|
|
26
|
+
if (typeof resetAtSeconds !== "number" || !Number.isFinite(resetAtSeconds) || resetAtSeconds <= 0 || resetAtSeconds > 8.64e12) return undefined;
|
|
27
|
+
// A bad length only loses the label; the usage itself is still valid.
|
|
28
|
+
const minutes = typeof windowMinutes === "number" && Number.isFinite(windowMinutes) && windowMinutes > 0 && windowMinutes <= 5256000 ? windowMinutes : undefined;
|
|
29
|
+
return { usedPercent, resetAtSeconds, ...(minutes ? { windowMinutes: minutes } : {}) };
|
|
30
|
+
}
|
|
31
|
+
function record(value: unknown): value is Record<string, unknown> {
|
|
32
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
33
|
+
}
|
|
34
|
+
function defaultQuotaEvent(data: Record<string, unknown>): boolean {
|
|
35
|
+
if (data.type !== "codex.rate_limits") return false;
|
|
36
|
+
// Other metered buckets are independent limits, not this default Codex allowance.
|
|
37
|
+
const limit = data.metered_limit_name ?? data.limit_name;
|
|
38
|
+
return limit == null || typeof limit === "string" && limit.trim().toLowerCase() === "codex";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Native WebSocket quota payload; read only known numeric fields, never account/credit data. */
|
|
42
|
+
export function readQuotaEvent(data: unknown): SubscriptionQuota | undefined {
|
|
43
|
+
if (!record(data) || !defaultQuotaEvent(data) || !record(data.rate_limits)) return undefined;
|
|
44
|
+
const quota: SubscriptionQuota = {};
|
|
45
|
+
for (const key of ["primary", "secondary"] as const) {
|
|
46
|
+
const value = data.rate_limits[key];
|
|
47
|
+
if (!record(value)) continue;
|
|
48
|
+
const window = validatedWindow(value.used_percent, value.reset_at, value.window_minutes);
|
|
49
|
+
if (window) quota[key] = window;
|
|
50
|
+
}
|
|
51
|
+
return quota.primary || quota.secondary ? quota : undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Read only Codex usage/reset/window headers, never credentials or full responses. */
|
|
55
|
+
export function readQuotaHeaders(headers: Record<string, string>): SubscriptionQuota | undefined {
|
|
56
|
+
const fields = new Map<string, string>();
|
|
57
|
+
for (const name of Object.keys(headers)) {
|
|
58
|
+
const lower = name.toLowerCase();
|
|
59
|
+
if (/^x-codex-(primary|secondary)-(used-percent|reset-at|window-minutes)$/.test(lower)) fields.set(lower, headers[name]!);
|
|
60
|
+
}
|
|
61
|
+
const quota: SubscriptionQuota = {};
|
|
62
|
+
for (const window of ["primary", "secondary"] as const) {
|
|
63
|
+
const prefix = `x-codex-${window}-`;
|
|
64
|
+
const usedPercent = headerNumber(fields.get(`${prefix}used-percent`));
|
|
65
|
+
const resetAtSeconds = headerNumber(fields.get(`${prefix}reset-at`));
|
|
66
|
+
// A percentage without a valid reset time cannot yield a trustworthy countdown.
|
|
67
|
+
const value = validatedWindow(usedPercent, resetAtSeconds, headerNumber(fields.get(`${prefix}window-minutes`)));
|
|
68
|
+
if (value) quota[window] = value;
|
|
69
|
+
}
|
|
70
|
+
return quota.primary || quota.secondary ? quota : undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function modelKey(model: QuotaModel | undefined): string | undefined {
|
|
74
|
+
return model ? JSON.stringify([model.provider, model.id, model.api, model.baseUrl]) : undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Session-local response snapshot; never merge windows across requests or persist accounts. */
|
|
78
|
+
export class QuotaState {
|
|
79
|
+
private responseReceived = false;
|
|
80
|
+
private streamQuotaReceived = false;
|
|
81
|
+
private selected: string | undefined;
|
|
82
|
+
private request: string | undefined;
|
|
83
|
+
private quota: SubscriptionQuota | undefined;
|
|
84
|
+
|
|
85
|
+
select(model: QuotaModel | undefined): void {
|
|
86
|
+
const key = modelKey(model);
|
|
87
|
+
if (key !== this.selected) { this.clear(); this.selected = key; }
|
|
88
|
+
}
|
|
89
|
+
clear(): void {
|
|
90
|
+
this.request = undefined; this.quota = undefined;
|
|
91
|
+
this.responseReceived = false; this.streamQuotaReceived = false;
|
|
92
|
+
}
|
|
93
|
+
beginRequest(model: QuotaModel | undefined): void {
|
|
94
|
+
this.select(model);
|
|
95
|
+
this.responseReceived = false; this.streamQuotaReceived = false;
|
|
96
|
+
this.request = modelKey(model);
|
|
97
|
+
}
|
|
98
|
+
response(headers: Record<string, string>, model: QuotaModel | undefined): void {
|
|
99
|
+
this.select(model);
|
|
100
|
+
if (!this.request || this.request !== modelKey(model)) return;
|
|
101
|
+
this.responseReceived = true;
|
|
102
|
+
// Missing/malformed headers on a later response invalidate the old account snapshot.
|
|
103
|
+
this.quota = readQuotaHeaders(headers);
|
|
104
|
+
}
|
|
105
|
+
/** Returns true when the footer needs repainting; raw events are never retained. */
|
|
106
|
+
observeStream(provider: string, id: string, api: string, model: QuotaModel | undefined, data?: unknown): boolean {
|
|
107
|
+
this.select(model);
|
|
108
|
+
if (model && (provider !== model.provider || id !== model.id || api !== model.api)) {
|
|
109
|
+
this.clear();
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
if (!this.request || this.request !== modelKey(model)) return false;
|
|
113
|
+
if (record(data) && defaultQuotaEvent(data)) {
|
|
114
|
+
this.streamQuotaReceived = true;
|
|
115
|
+
// Replace the whole event snapshot; never merge two credentials' windows.
|
|
116
|
+
this.quota = readQuotaEvent(data);
|
|
117
|
+
return true; // A quota update (including invalidation) needs a repaint.
|
|
118
|
+
}
|
|
119
|
+
if (!this.streamQuotaReceived && !this.responseReceived) {
|
|
120
|
+
// WebSocket requests can stream successfully without an HTTP response hook.
|
|
121
|
+
// Never carry a previous SSE/account snapshot into that request.
|
|
122
|
+
const hadQuota = !!this.quota;
|
|
123
|
+
this.quota = undefined;
|
|
124
|
+
return hadQuota;
|
|
125
|
+
}
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
snapshot(model: QuotaModel | undefined, now = Date.now()): QuotaSnapshot | undefined {
|
|
129
|
+
this.select(model);
|
|
130
|
+
if (!this.quota) return undefined;
|
|
131
|
+
const result: QuotaSnapshot = {};
|
|
132
|
+
for (const window of ["primary", "secondary"] as const) {
|
|
133
|
+
const value = this.quota[window];
|
|
134
|
+
if (!value || value.resetAtSeconds * 1000 <= now) continue;
|
|
135
|
+
result[window] = { ...value, resetInMinutes: Math.ceil((value.resetAtSeconds * 1000 - now) / 60000) };
|
|
136
|
+
}
|
|
137
|
+
// Do not turn an expired sample into a made-up zero-usage window.
|
|
138
|
+
return result.primary || result.secondary ? result : undefined;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function formatReset(minutes: number): string {
|
|
143
|
+
if (minutes >= 1440) return `${Math.floor(minutes / 1440)}d${Math.floor(minutes % 1440 / 60)}h`;
|
|
144
|
+
if (minutes >= 60) return `${Math.floor(minutes / 60)}h${minutes % 60}m`;
|
|
145
|
+
return `${minutes}m`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const STANDARD_WINDOWS = [[300, "5h"], [1440, "1d"], [10080, "7d"], [43200, "30d"]] as const;
|
|
149
|
+
/** `300` → `5h`, `10080` → `7d`; other lengths print exactly (`90` → `1h30m`). */
|
|
150
|
+
export function windowLabel(minutes: number | undefined): string | undefined {
|
|
151
|
+
if (!minutes) return undefined;
|
|
152
|
+
// Codex itself treats lengths within 5% of a standard window as that window.
|
|
153
|
+
for (const [expected, label] of STANDARD_WINDOWS) if (minutes >= expected * 0.95 && minutes <= expected * 1.05) return label;
|
|
154
|
+
const total = Math.max(1, Math.round(minutes));
|
|
155
|
+
const parts = [[Math.floor(total / 1440), "d"], [Math.floor(total % 1440 / 60), "h"], [total % 60, "m"]] as const;
|
|
156
|
+
return parts.filter(([value]) => value > 0).map(([value, unit]) => `${value}${unit}`).join("");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export type QuotaDetail = "full" | "bars" | "percent";
|
|
160
|
+
export interface QuotaPiece { usedPercent: number; label?: string; bar?: string; percent: string; reset?: string }
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Windows in display order. Narrower details drop the countdown, then the bar; an
|
|
164
|
+
* unlabeled window keeps its countdown instead, since that is all that tells it apart.
|
|
165
|
+
*/
|
|
166
|
+
export function quotaPieces(quota: QuotaSnapshot | undefined, ascii: boolean, detail: QuotaDetail = "full"): QuotaPiece[] | undefined {
|
|
167
|
+
const windows = quota ? [quota.primary, quota.secondary].filter((window) => window !== undefined) : [];
|
|
168
|
+
if (!windows.length) return undefined;
|
|
169
|
+
return windows.map((window) => {
|
|
170
|
+
const label = windowLabel(window.windowMinutes);
|
|
171
|
+
const full = window.usedPercent > 0 ? Math.max(1, Math.round(window.usedPercent / 10)) : 0;
|
|
172
|
+
const bar = (ascii ? "#" : "█").repeat(full) + (ascii ? "-" : "░").repeat(10 - full);
|
|
173
|
+
const reset = formatReset(window.resetInMinutes);
|
|
174
|
+
return {
|
|
175
|
+
usedPercent: window.usedPercent, percent: `${Number(window.usedPercent.toFixed(1))}%`,
|
|
176
|
+
...(label ? { label } : {}),
|
|
177
|
+
...(detail === "full" || detail === "bars" && label ? { bar } : {}),
|
|
178
|
+
...(detail === "full" || !label ? { reset } : {}),
|
|
179
|
+
};
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
export function quotaSeparator(ascii: boolean): string { return ascii ? " / " : " · "; }
|
|
183
|
+
|
|
184
|
+
export function renderQuota(quota: QuotaSnapshot | undefined, ascii: boolean, detail: QuotaDetail = "full"): string | undefined {
|
|
185
|
+
return quotaPieces(quota, ascii, detail)?.map((piece) => [piece.label, piece.bar, piece.percent, piece.reset].filter(Boolean).join(" ")).join(quotaSeparator(ascii));
|
|
186
|
+
}
|
package/src/render.ts
CHANGED
|
@@ -6,31 +6,39 @@ export { cleanText } from "./text.ts";
|
|
|
6
6
|
import type { ColorValue, SegmentConfig, SegmentId, StatuslineConfig, StatuslineSnapshot } from "./types.ts";
|
|
7
7
|
import { emptyGit } from "./git.ts";
|
|
8
8
|
import { emptyUsage } from "./usage.ts";
|
|
9
|
-
import { renderRuntime } from "./runtime-render.ts";
|
|
9
|
+
import { renderRuntime, renderTools } from "./runtime-render.ts";
|
|
10
|
+
import { quotaPieces, quotaSeparator, renderQuota, type QuotaDetail } from "./quota.ts";
|
|
10
11
|
|
|
11
12
|
export type RenderTheme = Pick<Theme, "style" | "colors" | "appearance">;
|
|
12
13
|
// Keep rainbow hues independent of semantic theme colors, which can repeat.
|
|
13
14
|
const THINKING_RAINBOW = ["#c084fc", "#f472b6", "#fb923c", "#facc15", "#4ade80", "#22d3ee", "#60a5fa"].map((value) => parseColor(value));
|
|
14
15
|
const ICONS: Record<StatuslineConfig["icons"], Partial<Record<SegmentId, string>>> = {
|
|
15
|
-
unicode: { model: "", directory: "▸", git: "⑂", context: "◉", cost: "$", input: "↑", output: "↓", tokens: "Σ", cacheRead: "R", cacheWrite: "W" },
|
|
16
|
-
nerd: { model: "", directory: "", git: "", context: "", cost: "$", input: "↑", output: "↓", tokens: "", cacheRead: "R", cacheWrite: "W" },
|
|
17
|
-
ascii: { model: "", directory: "", git: "git:", context: "ctx:", cost: "$", input: "in:", output: "out:", tokens: "tok:", cacheRead: "R:", cacheWrite: "W:" },
|
|
16
|
+
unicode: { model: "", directory: "▸", git: "⑂", context: "◉", cost: "$", input: "↑", output: "↓", session: "◷", tokens: "Σ", cacheRead: "R", cacheWrite: "W" },
|
|
17
|
+
nerd: { model: "", directory: "", git: "", context: "", quota: "", cost: "$", input: "↑", output: "↓", session: "", tokens: "", cacheRead: "R", cacheWrite: "W" },
|
|
18
|
+
ascii: { model: "", directory: "", git: "git:", context: "ctx:", cost: "$", input: "in:", output: "out:", session: "ses:", tokens: "tok:", cacheRead: "R:", cacheWrite: "W:" },
|
|
18
19
|
};
|
|
19
|
-
const DROP_ORDER: SegmentId[] = ["cost", "cacheWrite", "cacheRead", "
|
|
20
|
+
const DROP_ORDER: SegmentId[] = ["cost", "cacheWrite", "cacheRead", "output", "input", "thinking", "git", "directory"];
|
|
20
21
|
export function formatTokens(value: number): string {
|
|
21
22
|
if (value < 1000) return String(Math.round(value));
|
|
22
23
|
const divisor = value >= 1e6 ? 1e6 : 1000;
|
|
23
24
|
return `${Number((value / divisor).toFixed(1))}${divisor === 1e6 ? "M" : "k"}`;
|
|
24
25
|
}
|
|
26
|
+
/** Session age to the minute: `<1m`, `35m`, `2h 6m`, `3d 2h`. */
|
|
27
|
+
export function formatSessionAge(minutes: number): string {
|
|
28
|
+
if (minutes < 1) return "<1m";
|
|
29
|
+
if (minutes < 60) return `${minutes}m`;
|
|
30
|
+
if (minutes < 1440) return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
|
|
31
|
+
return `${Math.floor(minutes / 1440)}d ${Math.floor(minutes % 1440 / 60)}h`;
|
|
32
|
+
}
|
|
25
33
|
function contextBar(percent: number | null, ascii: boolean): string {
|
|
26
34
|
const width = 10;
|
|
27
|
-
if (percent === null || !Number.isFinite(percent)) return
|
|
35
|
+
if (percent === null || !Number.isFinite(percent)) return `${"?".repeat(width)} ?%`;
|
|
28
36
|
const fill = Math.max(0, Math.min(100, percent)) / 100 * width;
|
|
29
37
|
// Whole cells avoid the blank right side of fractional glyphs such as ▌.
|
|
30
38
|
// Keep small, non-zero usage visible; the percentage gives the precise value.
|
|
31
39
|
const full = fill > 0 ? Math.max(1, Math.round(fill)) : 0;
|
|
32
40
|
const bar = (ascii ? "#" : "█").repeat(full) + (ascii ? "-" : "░").repeat(width - full);
|
|
33
|
-
return
|
|
41
|
+
return `${bar} ${Number(percent.toFixed(1))}%`;
|
|
34
42
|
}
|
|
35
43
|
function displayPath(data: StatuslineSnapshot, mode: StatuslineConfig["pathMode"]): string {
|
|
36
44
|
if (mode === "basename") return basename(data.cwd) || data.cwd;
|
|
@@ -69,6 +77,8 @@ function segmentText(id: SegmentId, data: StatuslineSnapshot, config: Statusline
|
|
|
69
77
|
const capacity = contextWindow > 0 ? formatTokens(contextWindow) : "?";
|
|
70
78
|
return `${tokens === null ? "?" : formatTokens(tokens)}/${capacity}(${percent === null ? "?" : Number(percent.toFixed(1))}%)`;
|
|
71
79
|
}
|
|
80
|
+
case "quota": return renderQuota(data.quota, config.icons === "ascii");
|
|
81
|
+
case "session": return data.sessionMinutes === null ? undefined : formatSessionAge(data.sessionMinutes);
|
|
72
82
|
case "cost": return usage.cost.toFixed(3);
|
|
73
83
|
case "input": return formatTokens(usage.input);
|
|
74
84
|
case "output": return formatTokens(usage.output);
|
|
@@ -78,11 +88,15 @@ function segmentText(id: SegmentId, data: StatuslineSnapshot, config: Statusline
|
|
|
78
88
|
case "statuses": return [...data.statuses.values()].map(cleanText).filter(Boolean).join(" · ") || undefined;
|
|
79
89
|
}
|
|
80
90
|
}
|
|
91
|
+
function usageColor(percent: number): ColorValue { return percent > 90 ? "error" : percent > 70 ? "warning" : "accent"; }
|
|
81
92
|
function defaultColor(id: SegmentId, data: StatuslineSnapshot): ColorValue {
|
|
82
93
|
if (id === "context") {
|
|
83
94
|
if ((data.context.percent ?? 0) > 90) return "error";
|
|
84
95
|
if ((data.context.percent ?? 0) > 70) return "warning";
|
|
85
96
|
}
|
|
97
|
+
if (id === "quota") {
|
|
98
|
+
return usageColor(Math.max(data.quota?.primary?.usedPercent ?? 0, data.quota?.secondary?.usedPercent ?? 0));
|
|
99
|
+
}
|
|
86
100
|
if (id === "git") {
|
|
87
101
|
if (data.git.conflicts) return "error";
|
|
88
102
|
if (data.git.kind === "unknown" || data.git.staged + data.git.unstaged + data.git.untracked) return "warning";
|
|
@@ -108,12 +122,14 @@ interface Part {
|
|
|
108
122
|
foreground: ColorValue;
|
|
109
123
|
background?: ColorValue;
|
|
110
124
|
thinking?: { text: string; foreground: ColorValue | "rainbow" };
|
|
125
|
+
/** Multi-colored body; `text` remains its plain equivalent. */
|
|
126
|
+
content?: (style: { fg: ReturnType<typeof color>; bg?: ReturnType<typeof color> }) => string;
|
|
111
127
|
}
|
|
112
128
|
function renderPart(part: Part, theme: RenderTheme): string {
|
|
113
129
|
const bg = part.background ? color(part.background, theme) : undefined;
|
|
114
130
|
const style = { fg: color(part.foreground, theme), ...(bg ? { bg } : {}) };
|
|
115
131
|
const icon = part.icon ? theme.style(`${part.icon} `, { ...style, fg: color(part.config.iconColor ?? part.foreground, theme) }) : "";
|
|
116
|
-
const text = theme.style(part.text, style);
|
|
132
|
+
const text = part.content ? part.content(style) : theme.style(part.text, style);
|
|
117
133
|
let suffix = "";
|
|
118
134
|
if (part.thinking) {
|
|
119
135
|
const { text: level, foreground } = part.thinking;
|
|
@@ -148,12 +164,38 @@ function joinParts(parts: Part[], config: StatuslineConfig, theme: RenderTheme):
|
|
|
148
164
|
}).join("");
|
|
149
165
|
}
|
|
150
166
|
|
|
167
|
+
/** Each window colors its own bar and percentage; labels, countdowns and separators recede. */
|
|
168
|
+
function setQuota(part: Part, data: StatuslineSnapshot, config: StatuslineConfig, theme: RenderTheme, detail: QuotaDetail): void {
|
|
169
|
+
const ascii = config.icons === "ascii";
|
|
170
|
+
const pieces = quotaPieces(data.quota, ascii, detail) ?? [];
|
|
171
|
+
part.text = renderQuota(data.quota, ascii, detail) ?? "";
|
|
172
|
+
part.content = (style) => {
|
|
173
|
+
const paint = (text: string, value: ColorValue) => theme.style(text, { ...style, fg: color(value, theme) });
|
|
174
|
+
return pieces.map((piece) => {
|
|
175
|
+
const used = part.config.color ?? usageColor(piece.usedPercent);
|
|
176
|
+
return [
|
|
177
|
+
piece.label && paint(piece.label, "dim"), piece.bar && paint(piece.bar, used),
|
|
178
|
+
paint(piece.percent, used), piece.reset && paint(piece.reset, "muted"),
|
|
179
|
+
].filter(Boolean).join(theme.style(" ", style));
|
|
180
|
+
}).join(paint(quotaSeparator(ascii), "dim"));
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
/** Session-wide values for the runtime row: dim icon, plain value. */
|
|
184
|
+
function sessionText(segment: SegmentConfig, data: StatuslineSnapshot, config: StatuslineConfig, theme: RenderTheme): string | undefined {
|
|
185
|
+
const icon = cleanText(segment.icon ?? ICONS[config.icons][segment.id] ?? "");
|
|
186
|
+
const value = segmentText(segment.id, data, config);
|
|
187
|
+
if (value === undefined) return undefined;
|
|
188
|
+
const styled = theme.style(value, { fg: color(segment.color ?? "text", theme) });
|
|
189
|
+
return icon ? `${theme.style(icon, { fg: color(segment.iconColor ?? "dim", theme) })} ${styled}` : styled;
|
|
190
|
+
}
|
|
191
|
+
|
|
151
192
|
/** Pure terminal rendering: no disk reads, processes or session traversal. */
|
|
152
193
|
export function renderFooter(width: number, data: StatuslineSnapshot, config: StatuslineConfig, theme: RenderTheme): string[] {
|
|
153
194
|
width = Math.max(0, Math.floor(width));
|
|
154
195
|
if (width === 0) return [];
|
|
155
196
|
const parts: Part[] = [];
|
|
156
197
|
let secondary: Part | undefined;
|
|
198
|
+
const sessionRow: Partial<Record<"session" | "tokens", string>> = {};
|
|
157
199
|
// CLIProxyAPI's published `tps` status is display text only.
|
|
158
200
|
const tps = cleanText(data.statuses.get("tps") ?? "");
|
|
159
201
|
const elapsedStatus = config.segments.some((s) => s.id === "statuses" && s.enabled) && /^Elapsed \d+[dhms](?: \d+[hms])*$/.test(tps) ? tps : undefined;
|
|
@@ -161,6 +203,7 @@ export function renderFooter(width: number, data: StatuslineSnapshot, config: St
|
|
|
161
203
|
const thinking = config.segments.find((segment) => segment.id === "thinking");
|
|
162
204
|
for (const segment of config.segments) {
|
|
163
205
|
if (!segment.enabled) continue;
|
|
206
|
+
if (segment.id === "session" || segment.id === "tokens") { sessionRow[segment.id] = sessionText(segment, data, config, theme); continue; }
|
|
164
207
|
const raw = segmentText(segment.id, segment.id === "statuses" ? { ...data, statuses } : data, config);
|
|
165
208
|
if (raw === undefined) continue;
|
|
166
209
|
let text = cleanText(raw);
|
|
@@ -173,6 +216,7 @@ export function renderFooter(width: number, data: StatuslineSnapshot, config: St
|
|
|
173
216
|
foreground: thinking.color ?? (["high", "xhigh", "max"].includes(data.thinking) ? "rainbow" : defaultColor("thinking", data)),
|
|
174
217
|
};
|
|
175
218
|
}
|
|
219
|
+
if (segment.id === "quota") setQuota(part, data, config, theme, "full");
|
|
176
220
|
if (segment.id === "statuses") secondary = part;
|
|
177
221
|
else parts.push(part);
|
|
178
222
|
}
|
|
@@ -196,10 +240,25 @@ export function renderFooter(width: number, data: StatuslineSnapshot, config: St
|
|
|
196
240
|
line = joinParts(parts, config, theme);
|
|
197
241
|
}
|
|
198
242
|
}
|
|
243
|
+
// Keep model/context readable; never leave a half-truncated quota window.
|
|
244
|
+
const quota = parts.find((part) => part.config.id === "quota");
|
|
245
|
+
if (quota && visibleWidth(line) > width) {
|
|
246
|
+
for (const detail of ["bars", "percent"] as const) {
|
|
247
|
+
setQuota(quota, data, config, theme, detail);
|
|
248
|
+
line = joinParts(parts, config, theme);
|
|
249
|
+
if (visibleWidth(line) <= width) break;
|
|
250
|
+
}
|
|
251
|
+
if (visibleWidth(line) > width) {
|
|
252
|
+
parts.splice(parts.indexOf(quota), 1);
|
|
253
|
+
line = joinParts(parts, config, theme);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
199
256
|
const lines: string[] = [];
|
|
200
257
|
if (parts.length) lines.push(truncateToWidth(line, width, ellipsis));
|
|
201
|
-
const
|
|
202
|
-
if (
|
|
258
|
+
const tools = renderTools(width, data, config, theme);
|
|
259
|
+
if (tools) lines.push(tools);
|
|
260
|
+
const runtime = renderRuntime(width, data, config, theme, { statuses: secondary ? renderPart(secondary, theme) : undefined, ...sessionRow, elapsedStatus });
|
|
261
|
+
if (runtime) lines.push(runtime);
|
|
203
262
|
return lines;
|
|
204
263
|
}
|
|
205
264
|
|
|
@@ -219,8 +278,12 @@ export function sampleSnapshot(): StatuslineSnapshot {
|
|
|
219
278
|
context: { tokens: 23800, contextWindow: 200000, percent: 11.9 },
|
|
220
279
|
usage: { ...emptyUsage(), input: 32000, output: 5400, cacheRead: 12000, cost: 0.12 },
|
|
221
280
|
git: { ...emptyGit("repository"), branch: "main", unstaged: 2, ahead: 2 },
|
|
222
|
-
statuses: new Map([["example", "Example extension status"]]),
|
|
223
|
-
runtime: {
|
|
281
|
+
statuses: new Map([["example", "Example extension status"]]), sessionMinutes: 126,
|
|
282
|
+
runtime: {
|
|
283
|
+
runId: "example", status: "Running", elapsedMs: 28000, turns: 3, toolCalls: 8, awaitingInput: false, noContentMs: null, usage: { ...emptyUsage(), output: 1260 }, avg: 45, cache: 0.86,
|
|
284
|
+
tools: [{ name: "bash", target: "npm test", elapsedMs: 12000 }],
|
|
285
|
+
completed: [{ name: "read", ok: 5, failed: 0 }, { name: "edit", ok: 2, failed: 0 }],
|
|
286
|
+
},
|
|
224
287
|
compaction: { active: false, elapsedMs: 0, count: 1, showFailure: false },
|
|
225
288
|
};
|
|
226
289
|
}
|