@mrclrchtr/supi-extras 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 (25) hide show
  1. package/README.md +1 -5
  2. package/node_modules/@mrclrchtr/supi-core/README.md +26 -34
  3. package/node_modules/@mrclrchtr/supi-core/package.json +4 -7
  4. package/node_modules/@mrclrchtr/supi-core/src/api.ts +4 -6
  5. package/node_modules/@mrclrchtr/supi-core/src/config/config.ts +0 -20
  6. package/node_modules/@mrclrchtr/supi-core/src/config/prompt-surface.ts +7 -1
  7. package/node_modules/@mrclrchtr/supi-core/src/config.ts +0 -1
  8. package/node_modules/@mrclrchtr/supi-core/src/context.ts +1 -9
  9. package/node_modules/@mrclrchtr/supi-core/src/index.ts +4 -6
  10. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +54 -28
  11. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-schema.ts +91 -125
  12. package/node_modules/@mrclrchtr/supi-core/src/settings.ts +10 -7
  13. package/package.json +2 -4
  14. package/src/index.ts +0 -2
  15. package/node_modules/@mrclrchtr/supi-core/src/context/context-messages.ts +0 -119
  16. package/node_modules/@mrclrchtr/supi-core/src/progress-widget.ts +0 -189
  17. package/node_modules/@mrclrchtr/supi-core/src/settings/scoped-settings-list.ts +0 -373
  18. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-action-menu.ts +0 -102
  19. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-command.ts +0 -15
  20. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-submenus.ts +0 -141
  21. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-ui.ts +0 -118
  22. package/node_modules/@mrclrchtr/supi-core/src/settings-ui.ts +0 -3
  23. package/node_modules/@mrclrchtr/supi-core/src/tool-framework.ts +0 -192
  24. package/src/api.ts +0 -1
  25. package/src/skill-shortcut.ts +0 -123
@@ -1,26 +1,19 @@
1
- // Declarative settings schema for SuPi extensions.
1
+ // Fixed SuPi-config adapter for the canonical settings module interface.
2
2
  //
3
- // Replaces the imperative config-backed buildItems/persistChange contribution
4
- // with a declarative field descriptor model. The shared settings module owns
5
- // scope inheritance, source-state resolution, value rendering, persistence,
6
- // and Inherit/Reset-to-default actions.
3
+ // Declarative field descriptors let the adapter own scope inheritance,
4
+ // source-state resolution, value rendering, persistence, and Unset actions.
7
5
  //
8
6
  // Custom fields remain for nested or unusual config; they report the same
9
7
  // source state as declarative flat fields.
10
8
 
11
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
9
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
12
10
  import type { Component } from "@earendil-works/pi-tui";
13
11
  import {
14
12
  loadSupiConfigSectionForScope,
15
13
  removeSupiConfigKey,
16
14
  writeSupiConfig,
17
15
  } from "../config/config.ts";
18
- import {
19
- isSettingsContributionCollector,
20
- type SettingsScope,
21
- type SettingsSection,
22
- SUPI_SETTINGS_COLLECT_EVENT,
23
- } from "./settings-registry.ts";
16
+ import type { SettingsApplyResult, SettingsModule, SettingsScope } from "./settings-registry.ts";
24
17
 
25
18
  // ── Types ──────────────────────────────────────────────────────────────────
26
19
 
@@ -52,10 +45,7 @@ export interface ConfigHelpers {
52
45
  // ── Field actions ─────────────────────────────────────────────────────────
53
46
 
54
47
  /** A user-initiated action on a settings row. */
55
- export type SettingsFieldAction =
56
- | { kind: "set"; value: string }
57
- | { kind: "inherit" }
58
- | { kind: "resetToDefault" };
48
+ export type SettingsAction = { kind: "set"; value: string } | { kind: "unset" };
59
49
 
60
50
  // ── Field descriptors ─────────────────────────────────────────────────────
61
51
 
@@ -153,15 +143,15 @@ export interface CustomField extends BaseField {
153
143
  ctx?: ExtensionContext,
154
144
  ) => Component;
155
145
  /**
156
- * Persist handler called on set/inherit/resetToDefault actions.
146
+ * Persist handler called on set or unset actions.
157
147
  * Required for custom fields so they can write their nested config.
158
148
  */
159
149
  persist: (
160
150
  scope: SettingsScope,
161
151
  cwd: string,
162
- action: SettingsFieldAction,
152
+ action: SettingsAction,
163
153
  helpers: ConfigHelpers,
164
- ) => void;
154
+ ) => void | Promise<void>;
165
155
  }
166
156
 
167
157
  /** Union of all supported field kinds. */
@@ -176,8 +166,8 @@ export type SettingsField =
176
166
 
177
167
  // ── Contribution options ──────────────────────────────────────────────────
178
168
 
179
- /** Options for registerDeclarativeSettings. */
180
- export interface DeclarativeSettingsOptions {
169
+ /** Options for the fixed SuPi-config settings adapter. */
170
+ export interface ConfigSettingsOptions {
181
171
  /** Stable contribution identifier — e.g. "lsp", "claude-md". */
182
172
  id: string;
183
173
  /** Human-readable label shown in the UI. */
@@ -194,7 +184,7 @@ export interface DeclarativeSettingsOptions {
194
184
  homeDir?: string;
195
185
  }
196
186
 
197
- // ── Scoped section interface ─────────────────────────────────────────────
187
+ // ── Source-aware row interface ───────────────────────────────────────────
198
188
 
199
189
  /** Resolved value for one field in one scope. */
200
190
  export interface ScopedFieldValue {
@@ -305,14 +295,14 @@ function createConfigHelpers(
305
295
  };
306
296
  }
307
297
 
308
- // ── Scoped section factory ────────────────────────────────────────────────
298
+ // ── Fixed config adapter ─────────────────────────────────────────────────
309
299
 
310
300
  interface NotifyAfterPersistInput {
311
- options: DeclarativeSettingsOptions;
301
+ options: ConfigSettingsOptions;
312
302
  field: SettingsField;
313
303
  scope: SettingsScope;
314
304
  cwd: string;
315
- action: SettingsFieldAction;
305
+ action: SettingsAction;
316
306
  storedValue: unknown;
317
307
  ctx?: ExtensionContext;
318
308
  }
@@ -354,86 +344,86 @@ function notifyAfterPersist(input: NotifyAfterPersistInput): void {
354
344
  options.afterPersist(change);
355
345
  }
356
346
 
357
- function toDeclarativeSection(options: DeclarativeSettingsOptions): SettingsSection {
347
+ function resolveConfigRows(
348
+ options: ConfigSettingsOptions,
349
+ scope: SettingsScope,
350
+ cwd: string,
351
+ ctx?: ExtensionContext,
352
+ ): ScopedFieldValue[] {
358
353
  const defaults = options.defaults as Record<string, unknown>;
354
+ const projectRaw = loadSupiConfigSectionForScope(options.section, cwd, {
355
+ scope: "project",
356
+ homeDir: options.homeDir,
357
+ });
358
+ const globalRaw = loadSupiConfigSectionForScope(options.section, cwd, {
359
+ scope: "global",
360
+ homeDir: options.homeDir,
361
+ });
362
+
363
+ return options.fields.map((field) => {
364
+ if (field.kind === "custom") {
365
+ const resolved = field.resolve(scope, cwd, ctx);
366
+ return {
367
+ field,
368
+ displayValue: resolved.displayValue
369
+ ? sourceBadge(resolved.displayValue, resolved.source)
370
+ : "",
371
+ editValue: resolved.editValue ?? resolved.displayValue,
372
+ source: resolved.source,
373
+ inheritanceSource: resolved.inheritanceSource,
374
+ };
375
+ }
376
+
377
+ const { value, source } = resolveValue(field.key, defaults, projectRaw, globalRaw, scope);
378
+ const displayValue = formatValue(value, field);
379
+ const inheritanceSource =
380
+ scope === "project" && source === "project"
381
+ ? globalRaw && field.key in globalRaw
382
+ ? "global"
383
+ : "default"
384
+ : undefined;
385
+
386
+ return {
387
+ field,
388
+ displayValue: sourceBadge(displayValue, source),
389
+ editValue: formatEditValue(value, field),
390
+ source,
391
+ inheritanceSource,
392
+ };
393
+ });
394
+ }
395
+
396
+ async function applyConfigAction(
397
+ options: ConfigSettingsOptions,
398
+ request: Parameters<SettingsModule["apply"]>[0],
399
+ ): Promise<SettingsApplyResult> {
400
+ const { scope, cwd, fieldKey, action, ctx } = request;
401
+ const field = options.fields.find((candidate) => candidate.key === fieldKey);
402
+ if (!field) return {};
403
+
404
+ const helpers = createConfigHelpers(options.section, scope, cwd, options.homeDir);
405
+ let storedValue: unknown;
406
+ if (field.kind === "custom") {
407
+ await field.persist(scope, cwd, action, helpers);
408
+ storedValue = action.kind === "set" ? action.value : undefined;
409
+ } else if (action.kind === "set") {
410
+ storedValue = parseTypedValue(action.value, field);
411
+ helpers.set(field.key, storedValue);
412
+ } else {
413
+ helpers.unset(field.key);
414
+ }
415
+ notifyAfterPersist({ options, field, scope, cwd, action, storedValue, ctx });
416
+ return {};
417
+ }
418
+
419
+ /** Adapt one fixed SuPi config section to the canonical settings interface. */
420
+ export function defineConfigSettings(options: ConfigSettingsOptions): SettingsModule {
359
421
  return {
360
422
  id: options.id,
361
423
  label: options.label,
362
- loadValues: (scope, cwd, ctx) => {
363
- // Load raw section data for both scopes (no defaults)
364
- const projectRaw = loadSupiConfigSectionForScope(options.section, cwd, {
365
- scope: "project",
366
- homeDir: options.homeDir,
367
- });
368
- const globalRaw = loadSupiConfigSectionForScope(options.section, cwd, {
369
- scope: "global",
370
- homeDir: options.homeDir,
371
- });
372
-
373
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: natural discriminator on field kind and source
374
- return options.fields.map((field) => {
375
- if (field.kind === "custom") {
376
- const resolved = field.resolve(scope, cwd, ctx);
377
- return {
378
- field,
379
- displayValue: resolved.displayValue
380
- ? sourceBadge(resolved.displayValue, resolved.source)
381
- : "",
382
- editValue: resolved.editValue ?? resolved.displayValue,
383
- source: resolved.source,
384
- inheritanceSource: resolved.inheritanceSource,
385
- };
386
- }
387
-
388
- const { value, source } = resolveValue(field.key, defaults, projectRaw, globalRaw, scope);
389
- const displayValue = formatValue(value, field);
390
-
391
- // Compute inheritanceSource for project-scope overrides
392
- let inheritanceSource: "global" | "default" | undefined;
393
- if (scope === "project" && source === "project") {
394
- inheritanceSource = globalRaw && field.key in globalRaw ? "global" : "default";
395
- }
396
-
397
- return {
398
- field,
399
- displayValue: sourceBadge(displayValue, source),
400
- editValue: formatEditValue(value, field),
401
- source,
402
- inheritanceSource,
403
- };
404
- });
405
- },
406
- // biome-ignore lint/complexity/useMaxParams: SettingsSection action handlers receive scope, cwd, field, action, and optional context
407
- handleAction: (scope, cwd, fieldKey, action, ctx) => {
408
- const field = options.fields.find((f) => f.key === fieldKey);
409
- if (!field) return;
410
-
411
- const section = options.section;
412
- const helpers = createConfigHelpers(section, scope, cwd, options.homeDir);
413
- let storedValue: unknown;
414
-
415
- if (field.kind === "custom") {
416
- field.persist(scope, cwd, action, helpers);
417
- storedValue = action.kind === "set" ? action.value : undefined;
418
- notifyAfterPersist({ options, field, scope, cwd, action, storedValue, ctx });
419
- return;
420
- }
421
-
422
- switch (action.kind) {
423
- case "set": {
424
- storedValue = parseTypedValue(action.value, field);
425
- helpers.set(field.key, storedValue);
426
- break;
427
- }
428
- case "inherit":
429
- case "resetToDefault": {
430
- helpers.unset(field.key);
431
- break;
432
- }
433
- }
434
-
435
- notifyAfterPersist({ options, field, scope, cwd, action, storedValue, ctx });
436
- },
424
+ read: ({ scope, cwd, ctx }) =>
425
+ Promise.resolve({ rows: resolveConfigRows(options, scope, cwd, ctx) }),
426
+ apply: (request) => applyConfigAction(options, request),
437
427
  };
438
428
  }
439
429
 
@@ -461,27 +451,3 @@ export function parseTypedValue(value: string, field: SettingsField): unknown {
461
451
  return value;
462
452
  }
463
453
  }
464
-
465
- // ── Registration ──────────────────────────────────────────────────────────
466
-
467
- /**
468
- * Register a declarative settings contribution for `/supi-settings`.
469
- *
470
- * Contributions are collected through PI's process-local event bus. Call this
471
- * during the extension factory function, not in async session handlers.
472
- */
473
- export function registerDeclarativeSettings(
474
- pi: ExtensionAPI,
475
- options: DeclarativeSettingsOptions,
476
- ): void {
477
- const section = toDeclarativeSection(options);
478
- const dispose = pi.events.on(SUPI_SETTINGS_COLLECT_EVENT, (collector) => {
479
- if (isSettingsContributionCollector(collector)) {
480
- collector.add(section);
481
- }
482
- });
483
-
484
- pi.on("session_shutdown", () => {
485
- dispose();
486
- });
487
- }
@@ -1,33 +1,36 @@
1
- // supi-core settings domain — event-backed declarative settings contributions and command wiring.
2
-
3
- export { registerSettingsCommand } from "./settings/settings-command.ts";
1
+ // supi-core settings domain — settings modules and fixed-config adapters.
4
2
  export type {
3
+ SettingsActionRequest,
4
+ SettingsApplyResult,
5
5
  SettingsCollectionDiagnostic,
6
6
  SettingsCollectionResult,
7
+ SettingsContext,
7
8
  SettingsContributionCollector,
9
+ SettingsModule,
8
10
  SettingsScope,
9
- SettingsSection,
11
+ SettingsSnapshot,
10
12
  } from "./settings/settings-registry.ts";
11
13
  export {
12
14
  createSettingsContributionCollector,
13
15
  isSettingsContributionCollector,
16
+ registerSettings,
14
17
  SUPI_SETTINGS_COLLECT_EVENT,
15
18
  } from "./settings/settings-registry.ts";
16
19
  export type {
17
20
  BoolField,
18
21
  ConfigHelpers,
22
+ ConfigSettingsOptions,
19
23
  CustomField,
20
- DeclarativeSettingsOptions,
21
24
  EnumField,
22
25
  ModelPickerField,
23
26
  ModelPickerStaticOption,
24
27
  NumberField,
25
28
  ScopedFieldValue,
29
+ SettingsAction,
26
30
  SettingsField,
27
- SettingsFieldAction,
28
31
  SettingsPersistedChange,
29
32
  StringField,
30
33
  StringListField,
31
34
  ValueSource,
32
35
  } from "./settings/settings-schema.ts";
33
- export { registerDeclarativeSettings } from "./settings/settings-schema.ts";
36
+ export { defineConfigSettings } from "./settings/settings-schema.ts";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrclrchtr/supi-extras",
3
- "version": "4.7.0",
3
+ "version": "4.8.0",
4
4
  "description": "Shortcuts, prompt stash, activity indicators, and small session helpers",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -33,7 +33,7 @@
33
33
  ],
34
34
  "dependencies": {
35
35
  "clipboardy": "^5.3.1",
36
- "@mrclrchtr/supi-core": "4.7.0"
36
+ "@mrclrchtr/supi-core": "4.8.0"
37
37
  },
38
38
  "bundledDependencies": [
39
39
  "@mrclrchtr/supi-core"
@@ -56,9 +56,7 @@
56
56
  ],
57
57
  "image": "https://raw.githubusercontent.com/mrclrchtr/supi/main/packages/supi-extras/assets/social-preview.png"
58
58
  },
59
- "main": "src/api.ts",
60
59
  "exports": {
61
- "./api": "./src/api.ts",
62
60
  "./extension": "./src/extension.ts",
63
61
  "./package.json": "./package.json"
64
62
  }
package/src/index.ts CHANGED
@@ -3,7 +3,6 @@ import cloneSession from "./clone-session.ts";
3
3
  import copyPrompt from "./copy-prompt.ts";
4
4
  import gitEditor from "./git-editor.ts";
5
5
  import promptStash from "./prompt-stash.ts";
6
- import skillShortcut from "./skill-shortcut.ts";
7
6
  import supiFooter from "./supi-footer.ts";
8
7
  import tabSpinner from "./tab-spinner.ts";
9
8
 
@@ -23,6 +22,5 @@ export default function (pi: Parameters<typeof tabSpinner>[0]) {
23
22
  cloneSession(pi);
24
23
  gitEditor(pi);
25
24
  aliases(pi);
26
- skillShortcut(pi);
27
25
  supiFooter(pi);
28
26
  }
@@ -1,119 +0,0 @@
1
- // Shared context-message utilities for SuPi extensions.
2
- //
3
- // Provides a generic prune-and-reorder pattern for extensions that inject
4
- // managed context messages (via `before_agent_start` with a `customType` and
5
- // `contextToken`) and maintain them via the `context` event.
6
-
7
- /**
8
- * Minimal message shape needed for context-message operations.
9
- * Extensions cast their event.messages entries to this type.
10
- */
11
- export type ContextMessageLike = {
12
- role?: string;
13
- customType?: string;
14
- content?: unknown;
15
- details?: unknown;
16
- };
17
-
18
- /**
19
- * Extract the `contextToken` string from a message's `details` object.
20
- * Returns `null` when the token is absent or not a string.
21
- */
22
- export function getContextToken(details: unknown): string | null {
23
- if (!details || typeof details !== "object") return null;
24
- const token = (details as { contextToken?: unknown }).contextToken;
25
- return typeof token === "string" ? token : null;
26
- }
27
-
28
- /**
29
- * Find the index of the last message with `role: "user"`.
30
- * Returns `-1` when no user message exists.
31
- */
32
- export function findLastUserMessageIndex<T extends ContextMessageLike>(messages: T[]): number {
33
- for (let index = messages.length - 1; index >= 0; index--) {
34
- if (messages[index]?.role === "user") return index;
35
- }
36
- return -1;
37
- }
38
-
39
- /**
40
- * Filter stale context messages and reorder the active one before the last user message.
41
- *
42
- * - Removes all messages matching `customType` whose token differs from `activeToken`.
43
- * - When `activeToken` is `null`, removes **all** messages of that `customType`.
44
- * - If the active context message is after the last user message, moves it before.
45
- *
46
- * Returns the modified array, or the original reference when no changes were needed.
47
- */
48
- export function pruneAndReorderContextMessages<T extends ContextMessageLike>(
49
- messages: T[],
50
- customType: string,
51
- activeToken: string | null,
52
- ): T[] {
53
- // Remove stale messages of the target customType
54
- const filtered = messages.filter((message) => {
55
- if (message.customType !== customType) return true;
56
- if (!activeToken) return false;
57
- return getContextToken(message.details) === activeToken;
58
- });
59
-
60
- if (!activeToken) return filtered;
61
-
62
- // Find the active context message
63
- const contextIndex = filtered.findIndex(
64
- (message) =>
65
- message.customType === customType && getContextToken(message.details) === activeToken,
66
- );
67
- if (contextIndex === -1) return filtered;
68
-
69
- // Find the last user message
70
- const userIndex = findLastUserMessageIndex(filtered);
71
- if (userIndex === -1 || contextIndex < userIndex) return filtered;
72
-
73
- // Move context message before last user message
74
- const next = [...filtered];
75
- const [contextMessage] = next.splice(contextIndex, 1);
76
- if (!contextMessage) return filtered;
77
- next.splice(userIndex, 0, contextMessage);
78
- return next;
79
- }
80
-
81
- /**
82
- * Restore the raw prompt content on a context message that was swapped for display text.
83
- *
84
- * Extensions using `registerMessageRenderer` store their LLM-facing content in
85
- * `details.promptContent` and put a human-readable summary in `content`. This function
86
- * reverses the swap so the model sees the original prompt content.
87
- *
88
- * Returns the original array reference when no change is needed.
89
- */
90
- export function restorePromptContent<T extends ContextMessageLike>(
91
- messages: T[],
92
- customType: string,
93
- activeToken: string | null,
94
- ): T[] {
95
- if (!activeToken) return messages;
96
-
97
- const index = messages.findIndex(
98
- (message) =>
99
- message.customType === customType && getContextToken(message.details) === activeToken,
100
- );
101
- if (index === -1) return messages;
102
-
103
- const promptContent = getPromptContent(messages[index]?.details);
104
- if (!promptContent || messages[index]?.content === promptContent) return messages;
105
-
106
- const next = [...messages];
107
- next[index] = { ...next[index], content: promptContent };
108
- return next;
109
- }
110
-
111
- /**
112
- * Extract the `promptContent` string from a message's `details` object.
113
- * Returns `null` when absent or not a string.
114
- */
115
- export function getPromptContent(details: unknown): string | null {
116
- if (!details || typeof details !== "object") return null;
117
- const promptContent = (details as { promptContent?: unknown }).promptContent;
118
- return typeof promptContent === "string" ? promptContent : null;
119
- }
@@ -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
- }