@mrclrchtr/supi-prompt-suggestions 1.16.1

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 (48) hide show
  1. package/README.md +62 -0
  2. package/node_modules/@mrclrchtr/supi-core/README.md +113 -0
  3. package/node_modules/@mrclrchtr/supi-core/package.json +79 -0
  4. package/node_modules/@mrclrchtr/supi-core/src/abort-utils.ts +31 -0
  5. package/node_modules/@mrclrchtr/supi-core/src/api.ts +44 -0
  6. package/node_modules/@mrclrchtr/supi-core/src/config/config-settings.ts +188 -0
  7. package/node_modules/@mrclrchtr/supi-core/src/config/config.ts +207 -0
  8. package/node_modules/@mrclrchtr/supi-core/src/config.ts +12 -0
  9. package/node_modules/@mrclrchtr/supi-core/src/context/context-messages.ts +119 -0
  10. package/node_modules/@mrclrchtr/supi-core/src/context/context-provider-registry.ts +36 -0
  11. package/node_modules/@mrclrchtr/supi-core/src/context/context-tag.ts +31 -0
  12. package/node_modules/@mrclrchtr/supi-core/src/context.ts +16 -0
  13. package/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +255 -0
  14. package/node_modules/@mrclrchtr/supi-core/src/footer-registry.ts +57 -0
  15. package/node_modules/@mrclrchtr/supi-core/src/index.ts +40 -0
  16. package/node_modules/@mrclrchtr/supi-core/src/llm.ts +211 -0
  17. package/node_modules/@mrclrchtr/supi-core/src/model-selection.ts +134 -0
  18. package/node_modules/@mrclrchtr/supi-core/src/path-utils.ts +40 -0
  19. package/node_modules/@mrclrchtr/supi-core/src/path.ts +2 -0
  20. package/node_modules/@mrclrchtr/supi-core/src/progress-widget.ts +189 -0
  21. package/node_modules/@mrclrchtr/supi-core/src/project-roots.ts +170 -0
  22. package/node_modules/@mrclrchtr/supi-core/src/project.ts +15 -0
  23. package/node_modules/@mrclrchtr/supi-core/src/registry-utils.ts +93 -0
  24. package/node_modules/@mrclrchtr/supi-core/src/report.ts +121 -0
  25. package/node_modules/@mrclrchtr/supi-core/src/session-utils.ts +29 -0
  26. package/node_modules/@mrclrchtr/supi-core/src/session.ts +4 -0
  27. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-command.ts +15 -0
  28. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +48 -0
  29. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-ui.ts +331 -0
  30. package/node_modules/@mrclrchtr/supi-core/src/settings-ui.ts +6 -0
  31. package/node_modules/@mrclrchtr/supi-core/src/settings.ts +9 -0
  32. package/node_modules/@mrclrchtr/supi-core/src/spinner-frames.ts +11 -0
  33. package/node_modules/@mrclrchtr/supi-core/src/status-spinner.ts +68 -0
  34. package/node_modules/@mrclrchtr/supi-core/src/substrate-types.ts +11 -0
  35. package/node_modules/@mrclrchtr/supi-core/src/terminal.ts +60 -0
  36. package/node_modules/@mrclrchtr/supi-core/src/tool-framework.ts +182 -0
  37. package/node_modules/@mrclrchtr/supi-core/src/types.ts +2 -0
  38. package/package.json +39 -0
  39. package/src/api.ts +8 -0
  40. package/src/config/config.ts +16 -0
  41. package/src/config/settings.ts +44 -0
  42. package/src/editor/editor.ts +138 -0
  43. package/src/extension.ts +26 -0
  44. package/src/generation/client.ts +122 -0
  45. package/src/generation/generator.ts +225 -0
  46. package/src/generation/model-resolution.ts +72 -0
  47. package/src/generation/normalize.ts +50 -0
  48. package/src/session.ts +168 -0
@@ -0,0 +1,57 @@
1
+ // Shared footer contribution registry for SuPi extensions.
2
+ //
3
+ // Extensions register pre-styled text chunks with a placement hint
4
+ // ("stats" for the metrics line, "status" for the extension status line).
5
+ // The custom footer in supi-extras (or PI's built-in footer) reads these
6
+ // contributions and renders them alongside the built-in metrics.
7
+
8
+ import { createRegistry } from "./registry-utils.ts";
9
+
10
+ /** Where the contribution should appear in the footer. */
11
+ export type FooterPlacement = "stats" | "stats-end" | "status";
12
+
13
+ /** A single footer contribution registered by an extension. */
14
+ export interface FooterContribution {
15
+ /** Unique key for this contribution. Re-registering with the same key replaces it. */
16
+ key: string;
17
+ /** Which footer line this belongs on. */
18
+ placement: FooterPlacement;
19
+ /**
20
+ * Sort order within the placement (lower values render further left). Default: 100.
21
+ * Priority 0 is reserved for the turn cache-hit part so it stays adjacent to CH.
22
+ */
23
+ priority?: number;
24
+ /** Return the pre-styled text for this contribution. Called on every render. */
25
+ render: () => string;
26
+ }
27
+
28
+ const registry = createRegistry<FooterContribution>("footer-contributions");
29
+
30
+ function sortByPriority(a: FooterContribution, b: FooterContribution): number {
31
+ return (a.priority ?? 100) - (b.priority ?? 100);
32
+ }
33
+
34
+ export const footerContributions = {
35
+ /** Register or replace a footer contribution. */
36
+ register(contribution: FooterContribution): void {
37
+ registry.register(contribution.key, contribution);
38
+ },
39
+
40
+ /** Remove a contribution (e.g. on session_shutdown or when disabled). */
41
+ unregister(key: string): void {
42
+ registry.unregister(key);
43
+ },
44
+
45
+ /** Get contributions for a specific placement, sorted by priority. */
46
+ getByPlacement(placement: FooterPlacement): FooterContribution[] {
47
+ return registry
48
+ .getAll()
49
+ .filter((c) => c.placement === placement)
50
+ .sort(sortByPriority);
51
+ },
52
+
53
+ /** Remove all contributions (primarily for tests). */
54
+ clear(): void {
55
+ registry.clear();
56
+ },
57
+ };
@@ -0,0 +1,40 @@
1
+ // supi-core — shared infrastructure for SuPi extensions.
2
+ // Provides XML context tag wrapping, unified config system, context-message utilities,
3
+ // settings registry for supi-wide TUI settings, and a shared tool-spec/registration framework.
4
+ //
5
+ // Convenience barrel — re-exports all domain entry points.
6
+ // For lighter imports, use one of the domain subpaths directly
7
+ // (e.g. @mrclrchtr/supi-core/config, @mrclrchtr/supi-core/context).
8
+
9
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
10
+ export * from "./abort-utils.ts";
11
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
12
+ export * from "./config.ts";
13
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
14
+ export * from "./context.ts";
15
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
16
+ export * from "./debug-registry.ts";
17
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
18
+ export * from "./footer-registry.ts";
19
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
20
+ export * from "./model-selection.ts";
21
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
22
+ export * from "./path.ts";
23
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
24
+ export * from "./project.ts";
25
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
26
+ export * from "./report.ts";
27
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
28
+ export * from "./session.ts";
29
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
30
+ export * from "./settings.ts";
31
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
32
+ export * from "./settings-ui.ts";
33
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
34
+ export * from "./status-spinner.ts";
35
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
36
+ export * from "./terminal.ts";
37
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
38
+ export * from "./tool-framework.ts";
39
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
40
+ export * from "./types.ts";
@@ -0,0 +1,211 @@
1
+ import { complete } from "@earendil-works/pi-ai";
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
+ * Attempt an async operation with retries and exponential backoff.
29
+ *
30
+ * If the signal is already aborted on entry, the operation is skipped entirely.
31
+ * If the signal aborts during a delay, the delay is cancelled immediately.
32
+ *
33
+ * @param fn - The async operation to retry.
34
+ * @param options - Optional configuration for retries, backoff, signal, and callbacks.
35
+ * @returns The result on success, or `null` if all attempts fail or the signal aborts.
36
+ */
37
+ /**
38
+ * Create a promise that resolves after `ms` milliseconds, or rejects if
39
+ * the signal fires before the timeout elapses.
40
+ */
41
+ function delay(ms: number, signal?: AbortSignal): Promise<void> {
42
+ return new Promise<void>((resolve, reject) => {
43
+ const timer = setTimeout(resolve, ms);
44
+ if (signal) {
45
+ const onAbort = () => {
46
+ clearTimeout(timer);
47
+ reject(new DOMException("Aborted", "AbortError"));
48
+ };
49
+ signal.addEventListener("abort", onAbort, { once: true });
50
+ }
51
+ });
52
+ }
53
+
54
+ /**
55
+ * Attempt an async operation with retries and exponential backoff.
56
+ *
57
+ * If the signal is already aborted on entry, the operation is skipped entirely.
58
+ * If the signal aborts during a delay, the delay is cancelled immediately.
59
+ *
60
+ * @param fn - The async operation to retry.
61
+ * @param options - Optional configuration for retries, backoff, signal, and callbacks.
62
+ * @returns The result on success, or `null` if all attempts fail or the signal aborts.
63
+ */
64
+ export async function withRetry<T>(
65
+ fn: () => Promise<T>,
66
+ options?: WithRetryOptions,
67
+ ): Promise<T | null> {
68
+ const { retries = 2, baseDelayMs = 1000, signal, logger, onRetry } = options ?? {};
69
+
70
+ if (signal?.aborted) return null;
71
+
72
+ for (let attempt = 0; attempt <= retries; attempt++) {
73
+ try {
74
+ return await fn();
75
+ } catch (err) {
76
+ logger?.(attempt, err);
77
+ if (attempt >= retries || signal?.aborted) continue;
78
+
79
+ const delayMs = baseDelayMs * 2 ** attempt;
80
+ onRetry?.(attempt, delayMs);
81
+
82
+ try {
83
+ await delay(delayMs, signal);
84
+ } catch {
85
+ // delay() only rejects on abort
86
+ return null;
87
+ }
88
+ }
89
+ }
90
+
91
+ return null;
92
+ }
93
+
94
+ /**
95
+ * Extract and validate JSON from LLM response content blocks.
96
+ *
97
+ * Finds the first JSON object `{...}` in the combined text content,
98
+ * parses it, and validates against a TypeBox schema.
99
+ *
100
+ * @param content - The LLM response content blocks.
101
+ * @param schema - TypeBox schema to validate against.
102
+ * @returns The parsed and validated result, or `null` if extraction or validation fails.
103
+ */
104
+ export function extractJsonFromResponse<T extends TSchema>(
105
+ content: ReadonlyArray<{ type: string; text?: string }>,
106
+ schema: T,
107
+ ): { parsed: import("typebox").Static<T> } | null {
108
+ const text = content
109
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
110
+ .map((c) => c.text)
111
+ .join("");
112
+
113
+ const jsonMatch = text.match(/\{[\s\S]*\}/);
114
+ if (!jsonMatch) return null;
115
+
116
+ try {
117
+ const parsed = JSON.parse(jsonMatch[0]);
118
+ if (Value.Check(schema, parsed)) {
119
+ return { parsed } as { parsed: import("typebox").Static<T> };
120
+ }
121
+ return null;
122
+ } catch {
123
+ return null;
124
+ }
125
+ }
126
+
127
+ // ── callWithJsonResponse ───────────────────────────────────────────────────
128
+
129
+ /**
130
+ * Options for {@link callWithJsonResponse}.
131
+ */
132
+ export interface CallWithJsonResponseOptions {
133
+ /** The prompt to send to the LLM. */
134
+ prompt: string;
135
+ /** Optional data context appended to the prompt. */
136
+ dataContext?: string;
137
+ /** Maximum tokens for the response. Default: 4096 */
138
+ maxTokens?: number;
139
+ /** System prompt for the LLM call. Default: "" */
140
+ systemPrompt?: string;
141
+ /** Number of retries for the LLM call. Default: 2 */
142
+ retries?: number;
143
+ }
144
+
145
+ /**
146
+ * Call the LLM with a prompt and validate the JSON response against a TypeBox schema.
147
+ *
148
+ * Handles model resolution, auth, retry via `withRetry`, text extraction,
149
+ * JSON regex matching, and TypeBox validation.
150
+ *
151
+ * Returns `null` when:
152
+ * - No model is available
153
+ * - All retries fail
154
+ * - Response contains no valid JSON
155
+ * - JSON doesn't match the schema
156
+ * - The request is aborted
157
+ *
158
+ * @param ctx - The extension context for model resolution and auth.
159
+ * @param options - Call options including prompt, schema, and retry config.
160
+ * @param schema - TypeBox schema to validate the JSON response against.
161
+ * @returns The parsed and validated result, or `null`.
162
+ */
163
+ export async function callWithJsonResponse<T extends TSchema>(
164
+ ctx: ExtensionContext,
165
+ options: CallWithJsonResponseOptions,
166
+ schema: T,
167
+ ): Promise<{ parsed: import("typebox").Static<T> } | null> {
168
+ const { prompt, dataContext, maxTokens = 4096, systemPrompt = "", retries = 2 } = options;
169
+
170
+ const model = ctx.model ?? ctx.modelRegistry.getAvailable()[0] ?? null;
171
+ if (!model) return null;
172
+
173
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
174
+ if (!auth.ok || !auth.apiKey) return null;
175
+
176
+ const fullPrompt = dataContext
177
+ ? `${prompt}
178
+
179
+ DATA:
180
+ ${dataContext}`
181
+ : prompt;
182
+
183
+ const response = await withRetry(
184
+ async () => {
185
+ return complete(
186
+ model,
187
+ {
188
+ systemPrompt,
189
+ messages: [
190
+ {
191
+ role: "user",
192
+ content: [{ type: "text", text: fullPrompt }],
193
+ timestamp: Date.now(),
194
+ },
195
+ ],
196
+ },
197
+ {
198
+ apiKey: auth.apiKey,
199
+ headers: auth.headers,
200
+ signal: ctx.signal,
201
+ maxTokens,
202
+ },
203
+ );
204
+ },
205
+ { retries, baseDelayMs: 1000, signal: ctx.signal },
206
+ );
207
+
208
+ if (!response) return null;
209
+
210
+ return extractJsonFromResponse(response.content, schema);
211
+ }
@@ -0,0 +1,134 @@
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";
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
+ }
@@ -0,0 +1,40 @@
1
+ import * as path from "node:path";
2
+
3
+ /** Strip pi's optional leading `@` file-path prefix from a tool input. */
4
+ export function stripToolPathPrefix(target: string): string {
5
+ return target.startsWith("@") ? target.slice(1) : target;
6
+ }
7
+
8
+ /**
9
+ * Resolve a tool-style file path from a session cwd.
10
+ *
11
+ * Built-in pi file tools accept a leading `@` prefix in path arguments, so
12
+ * shared SuPi path helpers normalize that prefix before resolving relative
13
+ * paths.
14
+ */
15
+ export function resolveToolPath(cwd: string, target: string): string {
16
+ return path.resolve(cwd, stripToolPathPrefix(target));
17
+ }
18
+
19
+ /** Convert a file path to a file:// URI. */
20
+ export function fileToUri(filePath: string): string {
21
+ const resolved = path.resolve(filePath);
22
+ if (process.platform === "win32") {
23
+ return `file:///${resolved.replace(/\\/g, "/")}`;
24
+ }
25
+ return `file://${resolved}`;
26
+ }
27
+
28
+ /** Convert a file:// URI to a file path. */
29
+ export function uriToFile(uri: string): string {
30
+ if (!uri.startsWith("file://")) return uri;
31
+ let filePath = decodeURIComponent(uri.slice(7));
32
+ if (
33
+ process.platform === "win32" &&
34
+ filePath.startsWith("/") &&
35
+ /^[A-Za-z]:/.test(filePath.slice(1))
36
+ ) {
37
+ filePath = filePath.slice(1);
38
+ }
39
+ return filePath;
40
+ }
@@ -0,0 +1,2 @@
1
+ // supi-core path domain — file and URI path utilities.
2
+ export { fileToUri, resolveToolPath, stripToolPathPrefix, uriToFile } from "./path-utils.ts";
@@ -0,0 +1,189 @@
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
+ }