@mrclrchtr/supi-lsp 4.7.0 → 4.8.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.
Files changed (72) hide show
  1. package/node_modules/@mrclrchtr/supi-code-runtime/README.md +1 -1
  2. package/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -15
  3. package/node_modules/@mrclrchtr/supi-code-runtime/src/api.ts +1 -6
  4. package/node_modules/@mrclrchtr/supi-core/README.md +26 -34
  5. package/node_modules/@mrclrchtr/supi-core/package.json +4 -7
  6. package/node_modules/@mrclrchtr/supi-core/src/api.ts +4 -6
  7. package/node_modules/@mrclrchtr/supi-core/src/config/config.ts +0 -20
  8. package/node_modules/@mrclrchtr/supi-core/src/config/prompt-surface.ts +7 -1
  9. package/node_modules/@mrclrchtr/supi-core/src/config.ts +0 -1
  10. package/node_modules/@mrclrchtr/supi-core/src/context.ts +1 -9
  11. package/node_modules/@mrclrchtr/supi-core/src/index.ts +4 -6
  12. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +54 -28
  13. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-schema.ts +91 -125
  14. package/node_modules/@mrclrchtr/supi-core/src/settings.ts +10 -7
  15. package/package.json +3 -3
  16. package/src/client/client-diagnostics.ts +361 -0
  17. package/src/client/client.ts +46 -238
  18. package/src/manager/manager.ts +25 -33
  19. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/README.md +0 -120
  20. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/package.json +0 -75
  21. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/api.ts +0 -42
  22. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/config/config.ts +0 -221
  23. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/config/prompt-surface.ts +0 -357
  24. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/config.ts +0 -11
  25. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/context/context-messages.ts +0 -119
  26. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/context/context-provider-registry.ts +0 -36
  27. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/context/context-tag.ts +0 -31
  28. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/context.ts +0 -16
  29. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +0 -287
  30. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/evidence-badge.ts +0 -41
  31. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/footer-registry.ts +0 -57
  32. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/index.ts +0 -36
  33. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/llm.ts +0 -201
  34. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/model-selection.ts +0 -134
  35. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/path-utils.ts +0 -44
  36. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/path.ts +0 -2
  37. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/progress-widget.ts +0 -189
  38. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/project-roots.ts +0 -170
  39. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/project.ts +0 -15
  40. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/prompt-surface.ts +0 -4
  41. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/registry-utils.ts +0 -93
  42. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/report.ts +0 -121
  43. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/session-utils.ts +0 -71
  44. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/session.ts +0 -8
  45. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings/scoped-settings-list.ts +0 -373
  46. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings/settings-action-menu.ts +0 -102
  47. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings/settings-command.ts +0 -15
  48. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +0 -76
  49. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings/settings-schema.ts +0 -487
  50. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings/settings-submenus.ts +0 -141
  51. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings/settings-ui.ts +0 -118
  52. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings-ui.ts +0 -3
  53. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings.ts +0 -33
  54. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/spinner-frames.ts +0 -11
  55. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/status-spinner.ts +0 -68
  56. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/terminal.ts +0 -60
  57. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/tool-framework.ts +0 -192
  58. package/node_modules/@mrclrchtr/supi-code-runtime/src/index.ts +0 -42
  59. package/node_modules/@mrclrchtr/supi-code-runtime/src/workspace/context.ts +0 -45
  60. package/node_modules/@mrclrchtr/supi-core/src/context/context-messages.ts +0 -119
  61. package/node_modules/@mrclrchtr/supi-core/src/progress-widget.ts +0 -189
  62. package/node_modules/@mrclrchtr/supi-core/src/settings/scoped-settings-list.ts +0 -373
  63. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-action-menu.ts +0 -102
  64. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-command.ts +0 -15
  65. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-submenus.ts +0 -141
  66. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-ui.ts +0 -118
  67. package/node_modules/@mrclrchtr/supi-core/src/settings-ui.ts +0 -3
  68. package/node_modules/@mrclrchtr/supi-core/src/tool-framework.ts +0 -192
  69. package/src/client/client-refresh.ts +0 -234
  70. package/src/diagnostics/diagnostics.ts +0 -99
  71. package/src/diagnostics/suppression-diagnostics.ts +0 -60
  72. package/src/index.ts +0 -41
@@ -1,201 +0,0 @@
1
- import { complete } from "@earendil-works/pi-ai/compat";
2
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import type { TSchema } from "typebox";
4
- import { Value } from "typebox/value";
5
-
6
- // Shared LLM utilities for SuPi extensions.
7
- //
8
- // Provides retry logic, structured LLM call helpers, and other
9
- // common patterns for extensions that interact with AI models.
10
-
11
- /**
12
- * Options for {@link withRetry}.
13
- */
14
- export interface WithRetryOptions {
15
- /** Maximum number of retry attempts after the initial call. Default: 2 */
16
- retries?: number;
17
- /** Base delay in milliseconds for exponential backoff. Default: 1000 */
18
- baseDelayMs?: number;
19
- /** AbortSignal to cancel retry loops. */
20
- signal?: AbortSignal;
21
- /** Called with each failed attempt's attempt index and error. */
22
- logger?: (attempt: number, error: unknown) => void;
23
- /** Called before each retry delay with attempt index and computed delay. */
24
- onRetry?: (attempt: number, delayMs: number) => void;
25
- }
26
-
27
- /**
28
- * Create a promise that resolves after `ms` milliseconds, or rejects if
29
- * the signal fires before the timeout elapses.
30
- */
31
- function delay(ms: number, signal?: AbortSignal): Promise<void> {
32
- return new Promise<void>((resolve, reject) => {
33
- const timer = setTimeout(resolve, ms);
34
- if (signal) {
35
- const onAbort = () => {
36
- clearTimeout(timer);
37
- reject(new DOMException("Aborted", "AbortError"));
38
- };
39
- signal.addEventListener("abort", onAbort, { once: true });
40
- }
41
- });
42
- }
43
-
44
- /**
45
- * Attempt an async operation with retries and exponential backoff.
46
- *
47
- * If the signal is already aborted on entry, the operation is skipped entirely.
48
- * If the signal aborts during a delay, the delay is cancelled immediately.
49
- *
50
- * @param fn - The async operation to retry.
51
- * @param options - Optional configuration for retries, backoff, signal, and callbacks.
52
- * @returns The result on success, or `null` if all attempts fail or the signal aborts.
53
- */
54
- export async function withRetry<T>(
55
- fn: () => Promise<T>,
56
- options?: WithRetryOptions,
57
- ): Promise<T | null> {
58
- const { retries = 2, baseDelayMs = 1000, signal, logger, onRetry } = options ?? {};
59
-
60
- if (signal?.aborted) return null;
61
-
62
- for (let attempt = 0; attempt <= retries; attempt++) {
63
- try {
64
- return await fn();
65
- } catch (err) {
66
- logger?.(attempt, err);
67
- if (attempt >= retries || signal?.aborted) continue;
68
-
69
- const delayMs = baseDelayMs * 2 ** attempt;
70
- onRetry?.(attempt, delayMs);
71
-
72
- try {
73
- await delay(delayMs, signal);
74
- } catch {
75
- // delay() only rejects on abort
76
- return null;
77
- }
78
- }
79
- }
80
-
81
- return null;
82
- }
83
-
84
- /**
85
- * Extract and validate JSON from LLM response content blocks.
86
- *
87
- * Finds the first JSON object `{...}` in the combined text content,
88
- * parses it, and validates against a TypeBox schema.
89
- *
90
- * @param content - The LLM response content blocks.
91
- * @param schema - TypeBox schema to validate against.
92
- * @returns The parsed and validated result, or `null` if extraction or validation fails.
93
- */
94
- export function extractJsonFromResponse<T extends TSchema>(
95
- content: ReadonlyArray<{ type: string; text?: string }>,
96
- schema: T,
97
- ): { parsed: import("typebox").Static<T> } | null {
98
- const text = content
99
- .filter((c): c is { type: "text"; text: string } => c.type === "text")
100
- .map((c) => c.text)
101
- .join("");
102
-
103
- const jsonMatch = text.match(/\{[\s\S]*\}/);
104
- if (!jsonMatch) return null;
105
-
106
- try {
107
- const parsed = JSON.parse(jsonMatch[0]);
108
- if (Value.Check(schema, parsed)) {
109
- return { parsed } as { parsed: import("typebox").Static<T> };
110
- }
111
- return null;
112
- } catch {
113
- return null;
114
- }
115
- }
116
-
117
- // ── callWithJsonResponse ───────────────────────────────────────────────────
118
-
119
- /**
120
- * Options for {@link callWithJsonResponse}.
121
- */
122
- export interface CallWithJsonResponseOptions {
123
- /** The prompt to send to the LLM. */
124
- prompt: string;
125
- /** Optional data context appended to the prompt. */
126
- dataContext?: string;
127
- /** Maximum tokens for the response. Default: 4096 */
128
- maxTokens?: number;
129
- /** System prompt for the LLM call. Default: "" */
130
- systemPrompt?: string;
131
- /** Number of retries for the LLM call. Default: 2 */
132
- retries?: number;
133
- }
134
-
135
- /**
136
- * Call the LLM with a prompt and validate the JSON response against a TypeBox schema.
137
- *
138
- * Handles model resolution, auth, retry via `withRetry`, text extraction,
139
- * JSON regex matching, and TypeBox validation.
140
- *
141
- * Returns `null` when:
142
- * - No model is available
143
- * - All retries fail
144
- * - Response contains no valid JSON
145
- * - JSON doesn't match the schema
146
- * - The request is aborted
147
- *
148
- * @param ctx - The extension context for model resolution and auth.
149
- * @param options - Call options including prompt, schema, and retry config.
150
- * @param schema - TypeBox schema to validate the JSON response against.
151
- * @returns The parsed and validated result, or `null`.
152
- */
153
- export async function callWithJsonResponse<T extends TSchema>(
154
- ctx: ExtensionContext,
155
- options: CallWithJsonResponseOptions,
156
- schema: T,
157
- ): Promise<{ parsed: import("typebox").Static<T> } | null> {
158
- const { prompt, dataContext, maxTokens = 4096, systemPrompt = "", retries = 2 } = options;
159
-
160
- const model = ctx.model ?? ctx.modelRegistry.getAvailable()[0] ?? null;
161
- if (!model) return null;
162
-
163
- const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
164
- if (!auth.ok || !auth.apiKey) return null;
165
-
166
- const fullPrompt = dataContext
167
- ? `${prompt}
168
-
169
- DATA:
170
- ${dataContext}`
171
- : prompt;
172
-
173
- const response = await withRetry(
174
- async () => {
175
- return complete(
176
- model,
177
- {
178
- systemPrompt,
179
- messages: [
180
- {
181
- role: "user",
182
- content: [{ type: "text", text: fullPrompt }],
183
- timestamp: Date.now(),
184
- },
185
- ],
186
- },
187
- {
188
- apiKey: auth.apiKey,
189
- headers: auth.headers,
190
- signal: ctx.signal,
191
- maxTokens,
192
- },
193
- );
194
- },
195
- { retries, baseDelayMs: 1000, signal: ctx.signal },
196
- );
197
-
198
- if (!response) return null;
199
-
200
- return extractJsonFromResponse(response.content, schema);
201
- }
@@ -1,134 +0,0 @@
1
- /**
2
- * Shared model-selection helpers for SuPi extensions.
3
- *
4
- * Provides scoped-model listing using PI's `enabledModels` configuration,
5
- * matching the same semantics as the `@mrclrchtr/supi-review` model picker.
6
- *
7
- * @module
8
- */
9
-
10
- import type { Model } from "@earendil-works/pi-ai/compat";
11
- import { type ExtensionContext, SettingsManager } from "@earendil-works/pi-coding-agent";
12
-
13
- // ── Types ──────────────────────────────────────────────────────────────────
14
-
15
- /** A selectable model entry with display metadata. */
16
- export interface ModelSelection {
17
- /** Canonical `provider/model-id` string. */
18
- canonicalId: string;
19
- /** Provider name, e.g. `"anthropic"`. */
20
- provider: string;
21
- /** Model id, e.g. `"claude-sonnet-4-5"`. */
22
- id: string;
23
- // biome-ignore lint/suspicious/noExplicitAny: Model<any> is pi's canonical type
24
- model: Model<any>;
25
- /** Human-readable label (model name or canonicalId). */
26
- label: string;
27
- /** Optional description (canonicalId when different from label). */
28
- description?: string;
29
- /** Whether this model is the current session model. */
30
- isCurrent: boolean;
31
- }
32
-
33
- // ── Helpers ────────────────────────────────────────────────────────────────
34
-
35
- /** Build the canonical `provider/model-id` string. */
36
- export function toCanonicalModelId(
37
- model: Pick<NonNullable<ExtensionContext["model"]>, "provider" | "id">,
38
- ): string {
39
- return `${model.provider}/${model.id}`;
40
- }
41
-
42
- /**
43
- * List selectable models from PI's scoped model configuration.
44
- *
45
- * Only models that match the configured `enabledModels` patterns are offered.
46
- * The current session model is included only when it is inside that scoped set.
47
- * Returns an empty array when no scoped model patterns are configured.
48
- */
49
- export function getSelectableModels(
50
- ctx: Pick<ExtensionContext, "cwd" | "modelRegistry" | "model">,
51
- enabledModelPatterns = SettingsManager.create(ctx.cwd).getEnabledModels(),
52
- ): ModelSelection[] {
53
- if (!enabledModelPatterns || enabledModelPatterns.length === 0) {
54
- return [];
55
- }
56
-
57
- const byCanonicalId = new Map<string, ModelSelection>();
58
- const availableModels = filterByEnabledModels(
59
- enabledModelPatterns,
60
- ctx.modelRegistry.getAvailable(),
61
- );
62
-
63
- const addModel = (
64
- // biome-ignore lint/suspicious/noExplicitAny: Model<any> is pi's canonical type
65
- model: Model<any>,
66
- isCurrent: boolean,
67
- ) => {
68
- const canonicalId = toCanonicalModelId(model);
69
- const existing = byCanonicalId.get(canonicalId);
70
- if (existing) {
71
- if (isCurrent) existing.isCurrent = true;
72
- return;
73
- }
74
-
75
- byCanonicalId.set(canonicalId, {
76
- canonicalId,
77
- provider: model.provider,
78
- id: model.id,
79
- model,
80
- label: model.name ?? canonicalId,
81
- description: canonicalId,
82
- isCurrent,
83
- });
84
- };
85
-
86
- if (ctx.model && matchModelPatterns(ctx.model, enabledModelPatterns)) {
87
- addModel(ctx.model, true);
88
- }
89
-
90
- for (const model of availableModels) {
91
- addModel(
92
- model,
93
- ctx.model ? toCanonicalModelId(model) === toCanonicalModelId(ctx.model) : false,
94
- );
95
- }
96
-
97
- return Array.from(byCanonicalId.values()).sort((a, b) => {
98
- if (a.isCurrent !== b.isCurrent) return a.isCurrent ? -1 : 1;
99
- return a.canonicalId.localeCompare(b.canonicalId);
100
- });
101
- }
102
-
103
- // ── Private helpers ────────────────────────────────────────────────────────
104
-
105
- function filterByEnabledModels<T extends { provider: string; id: string }>(
106
- patterns: string[],
107
- models: T[],
108
- ): T[] {
109
- return models.filter((model) => matchModelPatterns(model, patterns));
110
- }
111
-
112
- function matchModelPatterns(model: { provider: string; id: string }, patterns: string[]): boolean {
113
- return patterns.some((pattern) => matchModelPattern(model, pattern));
114
- }
115
-
116
- function matchModelPattern(model: { provider: string; id: string }, pattern: string): boolean {
117
- const canonicalId = `${model.provider}/${model.id}`;
118
- if (pattern.includes("/")) {
119
- return simpleGlobMatch(canonicalId, pattern);
120
- }
121
- return simpleGlobMatch(model.id, pattern) || simpleGlobMatch(canonicalId, pattern);
122
- }
123
-
124
- function simpleGlobMatch(text: string, pattern: string): boolean {
125
- if (!pattern.includes("*") && !pattern.includes("?")) {
126
- return text.toLowerCase() === pattern.toLowerCase();
127
- }
128
-
129
- const regex = pattern
130
- .replace(/[.+^${}()|[\]\\]/g, "\\$&")
131
- .replace(/\*/g, ".*")
132
- .replace(/\?/g, ".");
133
- return new RegExp(`^${regex}$`, "i").test(text);
134
- }
@@ -1,44 +0,0 @@
1
- import * as path from "node:path";
2
- import { fileURLToPath, pathToFileURL } from "node:url";
3
-
4
- /** Strip pi's optional leading `@` file-path prefix from a tool input. */
5
- export function stripToolPathPrefix(target: string): string {
6
- return target.startsWith("@") ? target.slice(1) : target;
7
- }
8
-
9
- /**
10
- * Resolve a tool-style file path from a session cwd.
11
- *
12
- * Built-in pi file tools accept a leading `@` prefix in path arguments, so
13
- * shared SuPi path helpers normalize that prefix before resolving relative
14
- * paths.
15
- */
16
- export function resolveToolPath(cwd: string, target: string): string {
17
- return path.resolve(cwd, stripToolPathPrefix(target));
18
- }
19
-
20
- /**
21
- * Convert a file path to a file:// URI.
22
- *
23
- * Uses Node's `pathToFileURL` to produce a standards-compliant URI with
24
- * proper percent-encoding of spaces, hashes, and other special characters.
25
- */
26
- export function fileToUri(filePath: string): string {
27
- return pathToFileURL(filePath).href;
28
- }
29
-
30
- /**
31
- * Convert a file:// URI to a file path.
32
- *
33
- * Uses Node's `fileURLToPath` for standards-compliant decoding. Non-file
34
- * URIs are passed through unchanged so consumers (such as LSP diagnostic
35
- * handling) remain compatible with non-file URI schemes.
36
- */
37
- export function uriToFile(uri: string): string {
38
- if (!uri.startsWith("file://")) return uri;
39
- try {
40
- return fileURLToPath(uri);
41
- } catch {
42
- return uri;
43
- }
44
- }
@@ -1,2 +0,0 @@
1
- // supi-core path domain — file and URI path utilities.
2
- export { fileToUri, resolveToolPath, stripToolPathPrefix, uriToFile } from "./path-utils.ts";
@@ -1,189 +0,0 @@
1
- // Generic progress widget for SuPi long-running operations.
2
- //
3
- // Provides a TUI-based progress display with animated loader, turn counts,
4
- // tool usage, and activity descriptions.
5
-
6
- import type { Theme } from "@earendil-works/pi-coding-agent";
7
- import { CancellableLoader, Container, Text } from "@earendil-works/pi-tui";
8
-
9
- // ── Types ──────────────────────────────────────────────────────────────────
10
-
11
- /** What the reviewer is currently doing and on what. */
12
- export interface CurrentFocus {
13
- /** Display label for the active tool (e.g. "Reading", "Searching", "Finding"). */
14
- label: string;
15
- /** Context detail (e.g. file path, search pattern, directory). */
16
- detail: string;
17
- }
18
-
19
- /** Progress state for widget display, compatible with child-session updates. */
20
- export interface WidgetProgress {
21
- /** Number of agent turns completed. */
22
- turns: number;
23
- /** Number of tool executions started. */
24
- toolUses: number;
25
- /** Token usage stats, if available. */
26
- tokens?: {
27
- input: number;
28
- output: number;
29
- total: number;
30
- cacheRead?: number;
31
- cacheWrite?: number;
32
- };
33
- /** Per-tool execution counts keyed by short display label (e.g. "diffs", "reads", "greps"). */
34
- toolCounts?: Record<string, number>;
35
- /** Number of distinct files inspected so far (via read_snapshot_diff / read_snapshot_file). */
36
- filesInspected?: number;
37
- /** Total files in the review snapshot. */
38
- filesTotal?: number;
39
- /** Current tool + context for the progress narrative line. */
40
- currentFocus?: CurrentFocus;
41
- /** Elapsed time in milliseconds since the operation started. */
42
- elapsedMs?: number;
43
- }
44
-
45
- // ── Widget ─────────────────────────────────────────────────────────────────
46
-
47
- /**
48
- * TUI progress widget for long-running operations.
49
- *
50
- * Two-line layout: top line shows the narrative (current focus + file progress),
51
- * bottom line shows stats (tokens, elapsed time, turns, tool counts).
52
- */
53
- export class ProgressWidget extends Container {
54
- private message: string;
55
- private progress: WidgetProgress = { turns: 0, toolUses: 0 };
56
- private loader: CancellableLoader;
57
- private tui: { requestRender(): void };
58
- private theme: Theme;
59
-
60
- constructor(tui: { requestRender(): void }, theme: Theme, message: string) {
61
- super();
62
- this.tui = tui;
63
- this.theme = theme;
64
- this.message = message;
65
- this.loader = new CancellableLoader(
66
- tui as ConstructorParameters<typeof CancellableLoader>[0],
67
- (text: string) => theme.fg("accent", text),
68
- (text: string) => theme.fg("muted", text),
69
- message,
70
- );
71
-
72
- this.renderContent();
73
- }
74
-
75
- /** AbortSignal that fires when the user presses Escape. */
76
- get signal(): AbortSignal {
77
- return this.loader.signal;
78
- }
79
-
80
- /** Callback invoked when the user presses Escape. */
81
- set onAbort(fn: (() => void) | undefined) {
82
- this.loader.onAbort = fn;
83
- }
84
-
85
- /** Delegate keyboard input to the loader. */
86
- handleInput(data: string): void {
87
- this.loader.handleInput(data);
88
- }
89
-
90
- /** Update progress state and request a re-render. */
91
- updateProgress(progress: WidgetProgress): void {
92
- this.progress = progress;
93
- this.renderContent();
94
- this.tui.requestRender();
95
- }
96
-
97
- /** Clean up the widget. */
98
- dispose(): void {
99
- this.loader.dispose();
100
- }
101
-
102
- private renderContent(): void {
103
- this.clear();
104
- this.renderTopLine();
105
- this.renderBottomLine();
106
- }
107
-
108
- private renderTopLine(): void {
109
- const topParts: string[] = [];
110
-
111
- if (this.progress.currentFocus) {
112
- const { label, detail } = this.progress.currentFocus;
113
- topParts.push(detail ? `${label}: ${detail}` : label);
114
- }
115
-
116
- if (this.progress.filesTotal && this.progress.filesTotal > 0) {
117
- const inspected = this.progress.filesInspected ?? 0;
118
- topParts.push(`${inspected}/${this.progress.filesTotal} files`);
119
- }
120
-
121
- const loaderMessage =
122
- topParts.length > 0 ? `${this.message} · ${topParts.join(" · ")}` : this.message;
123
- this.loader.setMessage(loaderMessage);
124
- this.addChild(this.loader);
125
- }
126
-
127
- private renderBottomLine(): void {
128
- const stats: string[] = [];
129
-
130
- this.appendTokenStats(stats);
131
-
132
- if (this.progress.elapsedMs !== undefined && this.progress.elapsedMs >= 1000) {
133
- stats.push(formatElapsed(this.progress.elapsedMs));
134
- }
135
-
136
- if (this.progress.turns > 0) {
137
- stats.push(`⟳ ${this.progress.turns}`);
138
- }
139
-
140
- if (this.progress.toolCounts) {
141
- const parts = Object.entries(this.progress.toolCounts)
142
- .filter(([, count]) => count > 0)
143
- .sort(([, a], [, b]) => b - a)
144
- .map(([label, count]) => `${count} ${label}`);
145
- if (parts.length > 0) stats.push(parts.join(" · "));
146
- }
147
-
148
- if (stats.length > 0) {
149
- this.addChild(new Text(this.theme.fg("dim", ` ${stats.join(" · ")}`), 1, 0));
150
- }
151
- }
152
-
153
- private appendTokenStats(stats: string[]): void {
154
- const tokens = this.progress.tokens;
155
- if (!tokens) return;
156
-
157
- stats.push(`↑ ${formatTokens(tokens.input)}`);
158
- if (tokens.cacheRead !== undefined && tokens.cacheRead > 0) {
159
- stats.push(`↲ ${formatTokens(tokens.cacheRead)}`);
160
- }
161
- if (tokens.cacheWrite !== undefined && tokens.cacheWrite > 0) {
162
- stats.push(`↱ ${formatTokens(tokens.cacheWrite)}`);
163
- }
164
- stats.push(`↓ ${formatTokens(tokens.output)}`);
165
- }
166
- }
167
-
168
- // ── Helpers ────────────────────────────────────────────────────────────────
169
-
170
- export function formatTokens(count: number): string {
171
- if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
172
- if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`;
173
- return String(count);
174
- }
175
-
176
- export function formatElapsed(ms: number): string {
177
- const totalSec = Math.floor(ms / 1000);
178
- const hours = Math.floor(totalSec / 3600);
179
- const minutes = Math.floor((totalSec % 3600) / 60);
180
- const seconds = totalSec % 60;
181
-
182
- if (hours > 0) {
183
- return `${hours}h ${minutes}m ${seconds}s`;
184
- }
185
- if (minutes > 0) {
186
- return `${minutes}m ${seconds}s`;
187
- }
188
- return `${seconds}s`;
189
- }