@leolastforce/chalice-welcome-screen 0.0.0-stage → 0.1.10
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/LICENSE +21 -0
- package/README.md +140 -2
- package/package.json +62 -4
- package/src/index.ts +1989 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,1989 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getAgentDir,
|
|
3
|
+
SessionManager,
|
|
4
|
+
VERSION,
|
|
5
|
+
type ExtensionAPI,
|
|
6
|
+
type ExtensionContext,
|
|
7
|
+
type SessionInfo,
|
|
8
|
+
type Theme,
|
|
9
|
+
} from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { isAbsolute, join } from "node:path";
|
|
12
|
+
import {
|
|
13
|
+
type Component,
|
|
14
|
+
type Container,
|
|
15
|
+
Spacer,
|
|
16
|
+
type TUI,
|
|
17
|
+
truncateToWidth,
|
|
18
|
+
visibleWidth,
|
|
19
|
+
wrapTextWithAnsi,
|
|
20
|
+
} from "@earendil-works/pi-tui";
|
|
21
|
+
import {
|
|
22
|
+
CHALICE_SETTINGS_EVENT,
|
|
23
|
+
type ChaliceSettingsSection,
|
|
24
|
+
type LogoColorMode,
|
|
25
|
+
type LogoTypeMode,
|
|
26
|
+
getUsername as readUsername,
|
|
27
|
+
readChaliceSettings,
|
|
28
|
+
registerChaliceSettingsSection,
|
|
29
|
+
} from "@leolastforce/chalice-shared";
|
|
30
|
+
|
|
31
|
+
export const WELCOME_SIDE_PADDING = 4;
|
|
32
|
+
type HeaderBannerMode = "full" | "simple" | "compact" | "none";
|
|
33
|
+
const MAX_STACKED_COLUMN_WIDTH = 80;
|
|
34
|
+
/** Narrowest resource column worth placing beside the brand block. */
|
|
35
|
+
const MIN_RESOURCE_COLUMN_WIDTH = 28;
|
|
36
|
+
/** Widest the resource column may grow; this is what keeps the frame narrow. */
|
|
37
|
+
const MAX_RESOURCE_COLUMN_WIDTH = 52;
|
|
38
|
+
const GRID_INNER_PADDING = 3;
|
|
39
|
+
/** Columns the frame burns on its two borders and its inner padding. */
|
|
40
|
+
const FRAME_OVERHEAD = 2 + GRID_INNER_PADDING * 2;
|
|
41
|
+
/** Drawn between the brand block and the resource column. */
|
|
42
|
+
const COLUMN_DIVIDER = " │ ";
|
|
43
|
+
const COLUMN_DIVIDER_WIDTH = visibleWidth(COLUMN_DIVIDER);
|
|
44
|
+
const FRAME_VERTICAL_PADDING = 4;
|
|
45
|
+
const RESOURCE_POLL_INTERVAL_MS = 50;
|
|
46
|
+
const MAX_RESOURCE_RETRIES = 3;
|
|
47
|
+
const RECENT_SESSION_LIMIT = 3;
|
|
48
|
+
const LAYOUT_NOTICE = "Chalice welcome screen: layout unrecognized (and it's now set to show the native panel instead)";
|
|
49
|
+
const RESOURCE_PANEL_INDEX = 1;
|
|
50
|
+
const WELCOME_CONFIG_FILE = "welcome.json";
|
|
51
|
+
|
|
52
|
+
function getModeConfigDir(): string {
|
|
53
|
+
return join(getAgentDir(), "extensions", "welcome-screen");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function getModeConfigPath(): string {
|
|
57
|
+
return join(getModeConfigDir(), WELCOME_CONFIG_FILE);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Tips rendered as a `Tip:` line in the banner. The banner shows one tip per
|
|
62
|
+
* startup, cycling through the list in order. Edit this list, or override it
|
|
63
|
+
* with a `tips` string array in the welcome-screen `welcome.json` config file.
|
|
64
|
+
*/
|
|
65
|
+
const DEFAULT_TIPS: readonly string[] = [
|
|
66
|
+
"Do not take random tips from a startup screen too seriously. Except this one",
|
|
67
|
+
"*Insert tip here*",
|
|
68
|
+
"If you were hoping you could uninstall me, I have bad news. Probably.",
|
|
69
|
+
"Be kind to food workers. You've heard of how many kings got poisoned, right?",
|
|
70
|
+
"Cheh tahh sehh kee gah... Pess kahh tahh... Hm? Oh, sorry.",
|
|
71
|
+
"So... come here often?",
|
|
72
|
+
"Yea, you DEFINITELY come here often.",
|
|
73
|
+
"..",
|
|
74
|
+
"no tip for you today",
|
|
75
|
+
"Alright, so you've been here for a while, maybe you don't need the tips anymore..?",
|
|
76
|
+
];
|
|
77
|
+
|
|
78
|
+
interface WelcomeConfig {
|
|
79
|
+
tips: readonly string[];
|
|
80
|
+
/** Next tip to show; persisted so startups cycle through the pool. */
|
|
81
|
+
tipIndex: number;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function readWelcomeConfigFile(): Record<string, unknown> {
|
|
85
|
+
try {
|
|
86
|
+
const parsed = JSON.parse(readFileSync(getModeConfigPath(), "utf8")) as unknown;
|
|
87
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
88
|
+
return parsed as Record<string, unknown>;
|
|
89
|
+
}
|
|
90
|
+
} catch {
|
|
91
|
+
// Missing or malformed config falls back to the defaults.
|
|
92
|
+
}
|
|
93
|
+
return {};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function parseTips(value: unknown): string[] | undefined {
|
|
97
|
+
if (!Array.isArray(value)) return undefined;
|
|
98
|
+
const items: readonly unknown[] = value;
|
|
99
|
+
const tips = items.filter(
|
|
100
|
+
(tip): tip is string => typeof tip === "string" && tip.trim().length > 0,
|
|
101
|
+
);
|
|
102
|
+
return tips.length > 0 ? tips : undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function loadWelcomeConfig(): WelcomeConfig {
|
|
106
|
+
const parsed = readWelcomeConfigFile();
|
|
107
|
+
const tipIndex = parsed.tipIndex;
|
|
108
|
+
return {
|
|
109
|
+
tips: parseTips(parsed.tips) ?? DEFAULT_TIPS,
|
|
110
|
+
tipIndex:
|
|
111
|
+
typeof tipIndex === "number" && Number.isInteger(tipIndex) && tipIndex >= 0
|
|
112
|
+
? tipIndex
|
|
113
|
+
: 0,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Writes fields into the config file, keeping anything already stored there
|
|
119
|
+
* (like a custom `tips` list) when only one field changes.
|
|
120
|
+
*/
|
|
121
|
+
function writeWelcomeConfigFile(fields: Record<string, unknown>): void {
|
|
122
|
+
const dir = getModeConfigDir();
|
|
123
|
+
mkdirSync(dir, { recursive: true });
|
|
124
|
+
writeFileSync(
|
|
125
|
+
getModeConfigPath(),
|
|
126
|
+
`${JSON.stringify({ ...readWelcomeConfigFile(), ...fields }, null, 2)}\n`,
|
|
127
|
+
"utf8",
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Shows the next tip in the pool and advances the persisted cursor.
|
|
133
|
+
*/
|
|
134
|
+
function takeNextTip(config: WelcomeConfig): string {
|
|
135
|
+
const { tips } = config;
|
|
136
|
+
if (tips.length === 0) return "";
|
|
137
|
+
const index = config.tipIndex % tips.length;
|
|
138
|
+
writeWelcomeConfigFile({ tipIndex: (index + 1) % tips.length });
|
|
139
|
+
return tips[index] ?? "";
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Reads the Welcome/Header banner type from Chalice settings. A fresh read is
|
|
144
|
+
* made every time so a `/chalicesettings` change applies when the header is recreated.
|
|
145
|
+
*/
|
|
146
|
+
function loadHeaderBannerMode(ctx: ExtensionContext): HeaderBannerMode {
|
|
147
|
+
return readChaliceSettings(ctx).headerBanner;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function loadLogoType(ctx: ExtensionContext): LogoTypeMode {
|
|
151
|
+
return readChaliceSettings(ctx).logoType;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function loadLogoColor(ctx: ExtensionContext): LogoColorMode {
|
|
155
|
+
return readChaliceSettings(ctx).logoColor;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function loadUsername(ctx: ExtensionContext): string | undefined {
|
|
159
|
+
return readUsername(readChaliceSettings(ctx));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const HEADER_SECTION: ChaliceSettingsSection = {
|
|
163
|
+
id: "header",
|
|
164
|
+
title: "Header",
|
|
165
|
+
description: "The welcome banner shown above the chat at startup.",
|
|
166
|
+
order: 10,
|
|
167
|
+
items: [
|
|
168
|
+
{
|
|
169
|
+
id: "banner",
|
|
170
|
+
type: "enum",
|
|
171
|
+
key: "headerBanner",
|
|
172
|
+
label: "Banner",
|
|
173
|
+
options: [
|
|
174
|
+
{ value: "full", label: "Full" },
|
|
175
|
+
{ value: "simple", label: "Simple" },
|
|
176
|
+
{ value: "compact", label: "Compact" },
|
|
177
|
+
{ value: "none", label: "None" },
|
|
178
|
+
],
|
|
179
|
+
defaultValue: "full",
|
|
180
|
+
},
|
|
181
|
+
{
|
|
182
|
+
id: "logo-type",
|
|
183
|
+
type: "enum",
|
|
184
|
+
key: "logoType",
|
|
185
|
+
label: "Logo",
|
|
186
|
+
options: [
|
|
187
|
+
{ value: "square", label: "Square" },
|
|
188
|
+
{ value: "pi", label: "Pi" },
|
|
189
|
+
],
|
|
190
|
+
defaultValue: "square",
|
|
191
|
+
},
|
|
192
|
+
{
|
|
193
|
+
id: "logo-color",
|
|
194
|
+
type: "enum",
|
|
195
|
+
key: "logoColor",
|
|
196
|
+
label: "Logo color",
|
|
197
|
+
options: [
|
|
198
|
+
{ value: "gradient", label: "Gradient" },
|
|
199
|
+
{ value: "accent", label: "Accent" },
|
|
200
|
+
{ value: "white", label: "White" },
|
|
201
|
+
{ value: "pi", label: "Pi" },
|
|
202
|
+
],
|
|
203
|
+
defaultValue: "gradient",
|
|
204
|
+
},
|
|
205
|
+
],
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
const SQUARE_BANNER = [
|
|
209
|
+
"████████████",
|
|
210
|
+
"██ ██",
|
|
211
|
+
"██ ██",
|
|
212
|
+
"██ ██",
|
|
213
|
+
"██ ██",
|
|
214
|
+
"████████████",
|
|
215
|
+
];
|
|
216
|
+
|
|
217
|
+
const PI_BANNER = [
|
|
218
|
+
"██████ ",
|
|
219
|
+
"██ ██ ",
|
|
220
|
+
"████ ██",
|
|
221
|
+
"██ ██",
|
|
222
|
+
];
|
|
223
|
+
|
|
224
|
+
const LOGO_BANNERS: Record<LogoTypeMode, readonly string[]> = {
|
|
225
|
+
square: SQUARE_BANNER,
|
|
226
|
+
pi: PI_BANNER,
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
function getBannerLines(logoType: LogoTypeMode): readonly string[] {
|
|
230
|
+
return LOGO_BANNERS[logoType];
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function getBannerWidth(logoType: LogoTypeMode): number {
|
|
234
|
+
return Math.max(...getBannerLines(logoType).map((line) => visibleWidth(line)));
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
type Rgb = readonly [number, number, number];
|
|
238
|
+
/** Pi's brand colors, fixed across themes like Pi's own logo. */
|
|
239
|
+
const PI_LOGO_CORAL: Rgb = [228, 138, 122];
|
|
240
|
+
const PI_LOGO_BLUE: Rgb = [79, 142, 179];
|
|
241
|
+
const PI_LOGO_YELLOW: Rgb = [234, 182, 93];
|
|
242
|
+
const WHITE: Rgb = [246, 246, 246];
|
|
243
|
+
|
|
244
|
+
/** Blend two colors; `t` runs 0 (from) to 1 (to). */
|
|
245
|
+
function blendRgb(from: Rgb, to: Rgb, t: number): Rgb {
|
|
246
|
+
return [
|
|
247
|
+
Math.round(from[0] + (to[0] - from[0]) * t),
|
|
248
|
+
Math.round(from[1] + (to[1] - from[1]) * t),
|
|
249
|
+
Math.round(from[2] + (to[2] - from[2]) * t),
|
|
250
|
+
];
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Pi's brand ramp: coral, blue, yellow with blue pinned at the halfway point.
|
|
255
|
+
* `t` runs 0 (coral) through 0.5 (blue) to 1 (yellow).
|
|
256
|
+
*/
|
|
257
|
+
function piBrandRgb(t: number): Rgb {
|
|
258
|
+
const clamped = Math.min(1, Math.max(0, t));
|
|
259
|
+
return clamped <= 0.5
|
|
260
|
+
? blendRgb(PI_LOGO_CORAL, PI_LOGO_BLUE, clamped * 2)
|
|
261
|
+
: blendRgb(PI_LOGO_BLUE, PI_LOGO_YELLOW, (clamped - 0.5) * 2);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function rgbFgAnsi(rgb: Rgb, text: string): string {
|
|
265
|
+
return `\x1b[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m${text}\x1b[39m`;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** The theme accent as RGB, or undefined when the terminal theme is not 24-bit. */
|
|
269
|
+
function accentRgb(theme: Theme): Rgb | undefined {
|
|
270
|
+
const match = theme.getFgAnsi("accent").match(/^\x1b\[38;2;(\d+);(\d+);(\d+)m$/);
|
|
271
|
+
if (!match) return undefined;
|
|
272
|
+
return [Number(match[1]), Number(match[2]), Number(match[3])];
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Tint one banner line according to the `logoColor` setting. */
|
|
276
|
+
function colorizeBannerLine(
|
|
277
|
+
theme: Theme,
|
|
278
|
+
text: string,
|
|
279
|
+
index: number,
|
|
280
|
+
lineCount: number,
|
|
281
|
+
bannerWidth: number,
|
|
282
|
+
logoColor: LogoColorMode,
|
|
283
|
+
): string {
|
|
284
|
+
if (logoColor === "white") return rgbFgAnsi(WHITE, text);
|
|
285
|
+
const progress = lineCount <= 1 ? 0.5 : index / (lineCount - 1);
|
|
286
|
+
if (logoColor === "pi") {
|
|
287
|
+
// Follow the main diagonal instead of dropping straight down, so the three
|
|
288
|
+
// brand colors split the logo into triangles with blue on the anti-diagonal.
|
|
289
|
+
const vertical = lineCount <= 1 ? 0.5 : index / (lineCount - 1) / 2;
|
|
290
|
+
let line = "";
|
|
291
|
+
for (let column = 0; column < text.length; column += 1) {
|
|
292
|
+
const character = text[column] ?? " ";
|
|
293
|
+
if (character === " ") {
|
|
294
|
+
line += character;
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
const diagonal = vertical + column / Math.max(1, bannerWidth - 1) / 2;
|
|
298
|
+
line += rgbFgAnsi(piBrandRgb(diagonal), character);
|
|
299
|
+
}
|
|
300
|
+
return line;
|
|
301
|
+
}
|
|
302
|
+
const accent = accentRgb(theme);
|
|
303
|
+
if (logoColor === "accent" || !accent) return theme.fg("accent", text);
|
|
304
|
+
|
|
305
|
+
const centerDistance = Math.abs(progress * 2 - 1);
|
|
306
|
+
const brightness = 0.72 + (1 - centerDistance) * 0.25;
|
|
307
|
+
const tint = (channel: number) =>
|
|
308
|
+
Math.round(
|
|
309
|
+
brightness <= 1
|
|
310
|
+
? channel * brightness
|
|
311
|
+
: channel + (255 - channel) * (brightness - 1),
|
|
312
|
+
);
|
|
313
|
+
return rgbFgAnsi([tint(accent[0]), tint(accent[1]), tint(accent[2])], text);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
type WelcomeSection = "Context" | "Skills" | "Prompts" | "Extensions";
|
|
317
|
+
const WELCOME_SECTIONS: readonly WelcomeSection[] = [
|
|
318
|
+
"Context",
|
|
319
|
+
"Skills",
|
|
320
|
+
"Prompts",
|
|
321
|
+
"Extensions",
|
|
322
|
+
];
|
|
323
|
+
const LINE_OPERATORS = [
|
|
324
|
+
["/", "commands, skills, and prompt templates"],
|
|
325
|
+
["@", "reference or attach a file"],
|
|
326
|
+
["!", "run a shell command and send its output to the model"],
|
|
327
|
+
["!!", "run a shell command without sending its output"],
|
|
328
|
+
] as const;
|
|
329
|
+
|
|
330
|
+
/** One row of the `[Recent Sessions]` section. */
|
|
331
|
+
export interface RecentSession {
|
|
332
|
+
/** Session name, or the first message when the session has no name. */
|
|
333
|
+
title: string;
|
|
334
|
+
/** Compact age of the last activity, e.g. `3h`. */
|
|
335
|
+
age: string;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Everything the header renders besides the brand block. */
|
|
339
|
+
interface WelcomeContent {
|
|
340
|
+
tip: string;
|
|
341
|
+
username?: string;
|
|
342
|
+
notice?: string;
|
|
343
|
+
sessions: readonly RecentSession[];
|
|
344
|
+
logoType: LogoTypeMode;
|
|
345
|
+
logoColor: LogoColorMode;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export interface WelcomeResources {
|
|
349
|
+
context: string[];
|
|
350
|
+
skills: string[];
|
|
351
|
+
prompts: string[];
|
|
352
|
+
extensions: string[];
|
|
353
|
+
/** Context files inside the working directory; rendered one step brighter. */
|
|
354
|
+
projectContext?: string[];
|
|
355
|
+
/** Skill names loaded from the project scope; rendered one step brighter. */
|
|
356
|
+
projectSkills?: string[];
|
|
357
|
+
/** Prompt names loaded from the project scope; rendered one step brighter. */
|
|
358
|
+
projectPrompts?: string[];
|
|
359
|
+
/** Extensions loaded from npm or git packages. */
|
|
360
|
+
packageExtensions?: string[];
|
|
361
|
+
/** Local extension entry points outside Pi's extension directories. */
|
|
362
|
+
sourceExtensions?: string[];
|
|
363
|
+
/** @deprecated Use packageExtensions. */
|
|
364
|
+
vendoredExtensions?: string[];
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Health assessment for npm-installed package extensions, gathered
|
|
369
|
+
* asynchronously once the welcome header has rendered its first snapshot.
|
|
370
|
+
* Local and source-path extensions are skipped: they have no registry or
|
|
371
|
+
* store manifest to compare against.
|
|
372
|
+
*/
|
|
373
|
+
export type ExtensionHealthSeverity = "ok" | "behind" | "blocked" | "odd";
|
|
374
|
+
|
|
375
|
+
export interface ExtensionHealth {
|
|
376
|
+
/** Installed version read from the agent npm store manifest. */
|
|
377
|
+
installed?: string;
|
|
378
|
+
/** Range the package is pinned to in the agent npm store's package.json. */
|
|
379
|
+
declaredRange?: string;
|
|
380
|
+
/** Latest published version from the npm registry, when reachable. */
|
|
381
|
+
latest?: string;
|
|
382
|
+
/** Bare import specifiers not covered by the package's declared deps/peers. */
|
|
383
|
+
undeclaredImports?: string[];
|
|
384
|
+
/** Direct dependencies whose package directory is absent from the store. */
|
|
385
|
+
missingDeps?: string[];
|
|
386
|
+
severity: ExtensionHealthSeverity;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
export type ExtensionHealthMap = ReadonlyMap<string, ExtensionHealth>;
|
|
390
|
+
|
|
391
|
+
// Pi's extension loader makes the SDK scope importable without those packages
|
|
392
|
+
// being materialized in the npm store, so they never count as oddities.
|
|
393
|
+
const LOADER_BACKED_SCOPES = ["@earendil-works"];
|
|
394
|
+
|
|
395
|
+
const NPM_PACKAGE_NAME = /^(?:@[^/]+\/)?[^/@\s]+$/;
|
|
396
|
+
|
|
397
|
+
export function compareVersions(left: string, right: string): number {
|
|
398
|
+
const parse = (version: string) =>
|
|
399
|
+
(version.split("-", 1)[0] ?? "")
|
|
400
|
+
.split(".")
|
|
401
|
+
.map((part) => Number.parseInt(part, 10) || 0);
|
|
402
|
+
const a = parse(left);
|
|
403
|
+
const b = parse(right);
|
|
404
|
+
const length = Math.max(a.length, b.length);
|
|
405
|
+
for (let index = 0; index < length; index += 1) {
|
|
406
|
+
const leftPart = a[index] ?? 0;
|
|
407
|
+
const rightPart = b[index] ?? 0;
|
|
408
|
+
if (leftPart !== rightPart) return leftPart < rightPart ? -1 : 1;
|
|
409
|
+
}
|
|
410
|
+
return 0;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* True when the store's declared range cannot reach the latest published
|
|
415
|
+
* major — the `^1.20.0` pinned against `2.7.1` rpiv-todo shape.
|
|
416
|
+
*/
|
|
417
|
+
export function rangeBlocksMajor(
|
|
418
|
+
range: string | undefined,
|
|
419
|
+
latest: string | undefined,
|
|
420
|
+
): boolean {
|
|
421
|
+
if (!range || !latest) return false;
|
|
422
|
+
const normalized = range.trim();
|
|
423
|
+
if (normalized === "*" || normalized === "latest") return false;
|
|
424
|
+
const pinnedMajor = /^[\^~]?(\d+)(?:\.|$)/.exec(normalized)?.[1];
|
|
425
|
+
const latestMajor = /^(\d+)/.exec(latest)?.[1];
|
|
426
|
+
if (!pinnedMajor || !latestMajor) return false;
|
|
427
|
+
return Number.parseInt(pinnedMajor, 10) < Number.parseInt(latestMajor, 10);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Import specifiers in source, with comments stripped so strings inside them
|
|
432
|
+
* do not match.
|
|
433
|
+
*/
|
|
434
|
+
export function extractImportSpecifiers(source: string): string[] {
|
|
435
|
+
const withoutComments = source
|
|
436
|
+
.replace(/\/\*[\s\S]*?\*\//g, "")
|
|
437
|
+
.split("\n")
|
|
438
|
+
.map((line) => line.replace(/\/\/.*$/, ""))
|
|
439
|
+
.join("\n");
|
|
440
|
+
const specifiers: string[] = [];
|
|
441
|
+
const staticImport = /\bfrom\s*["']([^"']+)["']/g;
|
|
442
|
+
let match: RegExpExecArray | null;
|
|
443
|
+
while ((match = staticImport.exec(withoutComments))) {
|
|
444
|
+
specifiers.push(match[1] ?? "");
|
|
445
|
+
}
|
|
446
|
+
const dynamicImport = /\bimport\s*\(\s*["']([^"']+)["']\s*\)/g;
|
|
447
|
+
while ((match = dynamicImport.exec(withoutComments))) {
|
|
448
|
+
specifiers.push(match[1] ?? "");
|
|
449
|
+
}
|
|
450
|
+
return specifiers;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function isRelativeSpecifier(specifier: string): boolean {
|
|
454
|
+
return /^(?:\.\.?\/|\/|~\/|[A-Za-z]:\\)/.test(specifier);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** Bare specifiers neither relative, node builtins, loader-backed, nor declared. */
|
|
458
|
+
export function findUndeclaredImports(
|
|
459
|
+
source: string,
|
|
460
|
+
declared: ReadonlySet<string>,
|
|
461
|
+
): string[] {
|
|
462
|
+
return unique(
|
|
463
|
+
extractImportSpecifiers(source).filter((specifier) => {
|
|
464
|
+
if (specifier.startsWith("node:")) return false;
|
|
465
|
+
if (isRelativeSpecifier(specifier)) return false;
|
|
466
|
+
if (
|
|
467
|
+
LOADER_BACKED_SCOPES.some(
|
|
468
|
+
(scope) => specifier === scope || specifier.startsWith(`${scope}/`),
|
|
469
|
+
)
|
|
470
|
+
)
|
|
471
|
+
return false;
|
|
472
|
+
const isDeclared = [...declared].some(
|
|
473
|
+
(dependency) =>
|
|
474
|
+
specifier === dependency || specifier.startsWith(`${dependency}/`),
|
|
475
|
+
);
|
|
476
|
+
return !isDeclared;
|
|
477
|
+
}),
|
|
478
|
+
);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** Injectable runtime for health collection so tests never touch disk or network. */
|
|
482
|
+
export interface ExtensionHealthEnvironment {
|
|
483
|
+
/** Agent npm store root (holds the store's package.json). */
|
|
484
|
+
storeRoot: string;
|
|
485
|
+
/** Installed package manifest directory (store/node_modules). */
|
|
486
|
+
storeModules: string;
|
|
487
|
+
readJson: (path: string) => unknown | undefined;
|
|
488
|
+
readText: (path: string) => string | undefined;
|
|
489
|
+
exists: (path: string) => boolean;
|
|
490
|
+
fetchLatestVersion: (
|
|
491
|
+
name: string,
|
|
492
|
+
signal: AbortSignal,
|
|
493
|
+
) => Promise<string | undefined>;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
interface PackageManifest {
|
|
497
|
+
version?: unknown;
|
|
498
|
+
main?: unknown;
|
|
499
|
+
exports?: unknown;
|
|
500
|
+
dependencies?: Record<string, string>;
|
|
501
|
+
peerDependencies?: Record<string, string>;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
export function createHealthEnvironment(
|
|
505
|
+
baseDir: string,
|
|
506
|
+
): ExtensionHealthEnvironment {
|
|
507
|
+
const storeRoot = join(baseDir, "npm");
|
|
508
|
+
return {
|
|
509
|
+
storeRoot,
|
|
510
|
+
storeModules: join(storeRoot, "node_modules"),
|
|
511
|
+
readJson(path) {
|
|
512
|
+
try {
|
|
513
|
+
return JSON.parse(readFileSync(path, "utf8")) as unknown;
|
|
514
|
+
} catch {
|
|
515
|
+
return undefined;
|
|
516
|
+
}
|
|
517
|
+
},
|
|
518
|
+
readText(path) {
|
|
519
|
+
try {
|
|
520
|
+
return readFileSync(path, "utf8");
|
|
521
|
+
} catch {
|
|
522
|
+
return undefined;
|
|
523
|
+
}
|
|
524
|
+
},
|
|
525
|
+
exists: existsSync,
|
|
526
|
+
fetchLatestVersion: fetchNpmLatestVersion,
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Latest published version for a package, or undefined when the registry is
|
|
532
|
+
* unreachable. Honors the caller's abort signal and adds its own timeout so a
|
|
533
|
+
* stalled network never blocks the welcome render.
|
|
534
|
+
*/
|
|
535
|
+
export async function fetchNpmLatestVersion(
|
|
536
|
+
name: string,
|
|
537
|
+
signal: AbortSignal,
|
|
538
|
+
fetcher: typeof fetch = fetch,
|
|
539
|
+
timeoutMs = 3000,
|
|
540
|
+
): Promise<string | undefined> {
|
|
541
|
+
const controller = new AbortController();
|
|
542
|
+
const abort = () => controller.abort();
|
|
543
|
+
signal.addEventListener("abort", abort);
|
|
544
|
+
const timer = setTimeout(abort, timeoutMs);
|
|
545
|
+
try {
|
|
546
|
+
const encoded = name.split("/").map(encodeURIComponent).join("/");
|
|
547
|
+
const response = await fetcher(
|
|
548
|
+
`https://registry.npmjs.org/${encoded}/latest`,
|
|
549
|
+
{ signal: controller.signal, headers: { accept: "application/json" } },
|
|
550
|
+
);
|
|
551
|
+
if (!response.ok) return undefined;
|
|
552
|
+
const body = (await response.json()) as { version?: unknown };
|
|
553
|
+
return typeof body.version === "string" ? body.version : undefined;
|
|
554
|
+
} catch {
|
|
555
|
+
return undefined;
|
|
556
|
+
} finally {
|
|
557
|
+
clearTimeout(timer);
|
|
558
|
+
signal.removeEventListener("abort", abort);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function resolveEntryFile(
|
|
563
|
+
name: string,
|
|
564
|
+
manifest: PackageManifest,
|
|
565
|
+
env: ExtensionHealthEnvironment,
|
|
566
|
+
): string | undefined {
|
|
567
|
+
const candidates: string[] = [];
|
|
568
|
+
const exportsField = manifest.exports;
|
|
569
|
+
if (typeof exportsField === "string") {
|
|
570
|
+
candidates.push(exportsField);
|
|
571
|
+
} else if (exportsField && typeof exportsField === "object") {
|
|
572
|
+
const entryPoint = (exportsField as Record<string, unknown>)["."];
|
|
573
|
+
if (typeof entryPoint === "string") {
|
|
574
|
+
candidates.push(entryPoint);
|
|
575
|
+
} else if (entryPoint && typeof entryPoint === "object") {
|
|
576
|
+
const importTarget = (entryPoint as Record<string, unknown>)["import"];
|
|
577
|
+
const defaultTarget = (entryPoint as Record<string, unknown>)["default"];
|
|
578
|
+
if (typeof importTarget === "string") candidates.push(importTarget);
|
|
579
|
+
else if (typeof defaultTarget === "string")
|
|
580
|
+
candidates.push(defaultTarget);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
if (typeof manifest.main === "string") candidates.push(manifest.main);
|
|
584
|
+
candidates.push("./src/index.ts", "./index.ts");
|
|
585
|
+
|
|
586
|
+
for (const candidate of candidates) {
|
|
587
|
+
if (env.exists(join(env.storeModules, name, candidate))) return candidate;
|
|
588
|
+
}
|
|
589
|
+
return undefined;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
export function assessHealthSeverity(health: {
|
|
593
|
+
installed?: string | undefined;
|
|
594
|
+
declaredRange?: string | undefined;
|
|
595
|
+
latest?: string | undefined;
|
|
596
|
+
undeclaredImports?: string[] | undefined;
|
|
597
|
+
missingDeps?: string[] | undefined;
|
|
598
|
+
}): ExtensionHealthSeverity {
|
|
599
|
+
const blockedPin = rangeBlocksMajor(health.declaredRange, health.latest);
|
|
600
|
+
if (blockedPin || (health.missingDeps?.length ?? 0) > 0) return "blocked";
|
|
601
|
+
if (
|
|
602
|
+
health.installed !== undefined &&
|
|
603
|
+
health.latest !== undefined &&
|
|
604
|
+
compareVersions(health.installed, health.latest) < 0
|
|
605
|
+
)
|
|
606
|
+
return "behind";
|
|
607
|
+
if ((health.undeclaredImports?.length ?? 0) > 0) return "odd";
|
|
608
|
+
return "ok";
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
async function assessPackageHealth(
|
|
612
|
+
name: string,
|
|
613
|
+
env: ExtensionHealthEnvironment,
|
|
614
|
+
signal: AbortSignal,
|
|
615
|
+
): Promise<ExtensionHealth | undefined> {
|
|
616
|
+
const manifest = env.readJson(
|
|
617
|
+
join(env.storeModules, name, "package.json"),
|
|
618
|
+
) as PackageManifest | undefined;
|
|
619
|
+
if (!manifest || typeof manifest.version !== "string") return undefined;
|
|
620
|
+
|
|
621
|
+
const storeManifest = env.readJson(join(env.storeRoot, "package.json")) as
|
|
622
|
+
{ dependencies?: Record<string, string> } | undefined;
|
|
623
|
+
const declaredRange = storeManifest?.dependencies?.[name];
|
|
624
|
+
|
|
625
|
+
const declared = new Set([
|
|
626
|
+
...Object.keys(manifest.dependencies ?? {}),
|
|
627
|
+
...Object.keys(manifest.peerDependencies ?? {}),
|
|
628
|
+
]);
|
|
629
|
+
const missingDeps = Object.keys(manifest.dependencies ?? {}).filter(
|
|
630
|
+
(dependency) => !env.exists(join(env.storeModules, dependency)),
|
|
631
|
+
);
|
|
632
|
+
const entry = resolveEntryFile(name, manifest, env);
|
|
633
|
+
const source = entry
|
|
634
|
+
? (env.readText(join(env.storeModules, name, entry)) ?? "")
|
|
635
|
+
: "";
|
|
636
|
+
const undeclaredImports =
|
|
637
|
+
source.length > 0 ? findUndeclaredImports(source, declared) : undefined;
|
|
638
|
+
|
|
639
|
+
const latest = await env.fetchLatestVersion(name, signal);
|
|
640
|
+
const installed = manifest.version;
|
|
641
|
+
const severity = assessHealthSeverity({
|
|
642
|
+
installed,
|
|
643
|
+
declaredRange,
|
|
644
|
+
latest,
|
|
645
|
+
undeclaredImports,
|
|
646
|
+
missingDeps,
|
|
647
|
+
});
|
|
648
|
+
return {
|
|
649
|
+
severity,
|
|
650
|
+
...(installed !== undefined ? { installed } : {}),
|
|
651
|
+
...(declaredRange !== undefined ? { declaredRange } : {}),
|
|
652
|
+
...(latest !== undefined ? { latest } : {}),
|
|
653
|
+
...(undeclaredImports !== undefined && undeclaredImports.length > 0
|
|
654
|
+
? { undeclaredImports }
|
|
655
|
+
: {}),
|
|
656
|
+
...(missingDeps.length > 0 ? { missingDeps } : {}),
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
export async function collectExtensionHealth(
|
|
661
|
+
names: readonly string[],
|
|
662
|
+
env: ExtensionHealthEnvironment,
|
|
663
|
+
signal: AbortSignal,
|
|
664
|
+
): Promise<ExtensionHealthMap> {
|
|
665
|
+
const results = await Promise.allSettled(
|
|
666
|
+
names.map((name) => assessPackageHealth(name, env, signal)),
|
|
667
|
+
);
|
|
668
|
+
const health = new Map<string, ExtensionHealth>();
|
|
669
|
+
results.forEach((result, index) => {
|
|
670
|
+
const name = names[index];
|
|
671
|
+
if (name && result.status === "fulfilled" && result.value) {
|
|
672
|
+
health.set(name, result.value);
|
|
673
|
+
}
|
|
674
|
+
});
|
|
675
|
+
return health;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
export function describeHealthIssue(
|
|
679
|
+
name: string,
|
|
680
|
+
health: ExtensionHealth,
|
|
681
|
+
): string {
|
|
682
|
+
if (health.severity === "blocked") {
|
|
683
|
+
if (health.declaredRange && health.latest) {
|
|
684
|
+
return `${name} pinned ${health.declaredRange} — ${health.latest} available`;
|
|
685
|
+
}
|
|
686
|
+
if ((health.missingDeps?.length ?? 0) > 0) {
|
|
687
|
+
return `${name}: missing ${health.missingDeps?.join(", ")}`;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
if (health.severity === "behind" && health.installed && health.latest) {
|
|
691
|
+
return `${name} ${health.installed} → ${health.latest}`;
|
|
692
|
+
}
|
|
693
|
+
if ((health.undeclaredImports?.length ?? 0) > 0) {
|
|
694
|
+
const count = health.undeclaredImports?.length ?? 0;
|
|
695
|
+
return `${name}: ${count} undeclared import${count === 1 ? "" : "s"}`;
|
|
696
|
+
}
|
|
697
|
+
return `${name}: ${health.severity}`;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
interface CollapsedTextComponent extends Component {
|
|
701
|
+
getCollapsedText?: () => string;
|
|
702
|
+
getExpandedText?: () => string;
|
|
703
|
+
setExpanded?: (expanded: boolean) => void;
|
|
704
|
+
state?: { expanded?: boolean };
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
interface ResourcePanel extends Component {
|
|
708
|
+
children: Component[];
|
|
709
|
+
addChild(component: Component): void;
|
|
710
|
+
removeChild(component: Component): void;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
interface RemovedResourceChild {
|
|
714
|
+
component: Component;
|
|
715
|
+
originalIndex: number;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
interface ResourceBridge {
|
|
719
|
+
panel: ResourcePanel;
|
|
720
|
+
removedChildren: RemovedResourceChild[];
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
interface ResourcePanelSnapshot {
|
|
724
|
+
resourceText: string;
|
|
725
|
+
expandedExtensionsText?: string;
|
|
726
|
+
expandedSkillsText?: string;
|
|
727
|
+
expandedPromptsText?: string;
|
|
728
|
+
knownChildren: Component[];
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
function stripAnsi(text: string): string {
|
|
732
|
+
return text.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
function isResourcePanel(
|
|
736
|
+
component: Component | undefined,
|
|
737
|
+
): component is ResourcePanel {
|
|
738
|
+
if (!component || typeof component !== "object") return false;
|
|
739
|
+
const candidate = component as Partial<Container>;
|
|
740
|
+
return (
|
|
741
|
+
Array.isArray(candidate.children) &&
|
|
742
|
+
typeof candidate.addChild === "function" &&
|
|
743
|
+
typeof candidate.removeChild === "function"
|
|
744
|
+
);
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
function getSectionHeading(text: string): string | undefined {
|
|
748
|
+
return stripAnsi(text.split("\n", 1)[0] ?? "")
|
|
749
|
+
.trim()
|
|
750
|
+
.match(/^\[([^\]]+)\]$/)?.[1];
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/** Read a startup resource section wide enough that its text never wraps. */
|
|
754
|
+
const RESOURCE_TEXT_WIDTH = 4096;
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* Pi 0.80-0.84 exposed getCollapsedText/getExpandedText on startup resource sections. Pi 1.5+
|
|
758
|
+
* renders them through an ExpandableText that only exposes render() plus an expansion flag, so read
|
|
759
|
+
* the text back out of the component and restore the flag afterwards.
|
|
760
|
+
*/
|
|
761
|
+
function readSectionText(child: Component, expanded: boolean): string | undefined {
|
|
762
|
+
const component = child as CollapsedTextComponent;
|
|
763
|
+
const direct = expanded ? component.getExpandedText : component.getCollapsedText;
|
|
764
|
+
if (typeof direct === "function") return direct.call(child);
|
|
765
|
+
const setExpanded = component.setExpanded;
|
|
766
|
+
if (typeof setExpanded !== "function") {
|
|
767
|
+
return expanded ? undefined : component.render(RESOURCE_TEXT_WIDTH).join("\n");
|
|
768
|
+
}
|
|
769
|
+
const previous = component.state?.expanded;
|
|
770
|
+
if (previous === expanded) {
|
|
771
|
+
return component.render(RESOURCE_TEXT_WIDTH).join("\n");
|
|
772
|
+
}
|
|
773
|
+
setExpanded.call(child, expanded);
|
|
774
|
+
const text = component.render(RESOURCE_TEXT_WIDTH).join("\n");
|
|
775
|
+
if (typeof previous === "boolean") setExpanded.call(child, previous);
|
|
776
|
+
return text;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
function inspectResourcePanel(panel: ResourcePanel): ResourcePanelSnapshot {
|
|
780
|
+
const sections: string[] = [];
|
|
781
|
+
const knownChildren: Component[] = [];
|
|
782
|
+
let expandedExtensionsText: string | undefined;
|
|
783
|
+
let expandedSkillsText: string | undefined;
|
|
784
|
+
let expandedPromptsText: string | undefined;
|
|
785
|
+
|
|
786
|
+
for (const child of panel.children) {
|
|
787
|
+
const text = readSectionText(child, false);
|
|
788
|
+
if (text === undefined) continue;
|
|
789
|
+
|
|
790
|
+
const heading = getSectionHeading(text);
|
|
791
|
+
if (WELCOME_SECTIONS.some((section) => section === heading)) {
|
|
792
|
+
knownChildren.push(child);
|
|
793
|
+
sections.push(text);
|
|
794
|
+
if (
|
|
795
|
+
heading === "Extensions" ||
|
|
796
|
+
/(?:^|\n)\s*\[Extensions\]\s*(?:\n|$)/.test(stripAnsi(text))
|
|
797
|
+
) {
|
|
798
|
+
expandedExtensionsText =
|
|
799
|
+
readSectionText(child, true) ?? expandedExtensionsText;
|
|
800
|
+
} else if (heading === "Skills") {
|
|
801
|
+
expandedSkillsText = readSectionText(child, true);
|
|
802
|
+
} else if (heading === "Prompts") {
|
|
803
|
+
expandedPromptsText = readSectionText(child, true);
|
|
804
|
+
}
|
|
805
|
+
} else if (heading === "Themes") {
|
|
806
|
+
knownChildren.push(child);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
return {
|
|
811
|
+
resourceText: sections.join("\n"),
|
|
812
|
+
...(expandedExtensionsText ? { expandedExtensionsText } : {}),
|
|
813
|
+
...(expandedSkillsText ? { expandedSkillsText } : {}),
|
|
814
|
+
...(expandedPromptsText ? { expandedPromptsText } : {}),
|
|
815
|
+
knownChildren,
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
function splitList(body: string[]): string[] {
|
|
820
|
+
return body
|
|
821
|
+
.join(" ")
|
|
822
|
+
.split(",")
|
|
823
|
+
.map((item) => item.trim())
|
|
824
|
+
.filter(Boolean);
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
export function normalizeExtensionName(label: string): string {
|
|
828
|
+
let name = label.trim().replace(/^npm:/, "").replace(/\\/g, "/");
|
|
829
|
+
// Windows drive letters use a colon as part of the path, not as the
|
|
830
|
+
// separator between a package name and its extension entry point.
|
|
831
|
+
const packageSeparator = /^[A-Za-z]:\//.test(name) ? -1 : name.indexOf(":");
|
|
832
|
+
const isPackageLabel = packageSeparator !== -1;
|
|
833
|
+
if (isPackageLabel) name = name.slice(0, packageSeparator);
|
|
834
|
+
|
|
835
|
+
name = name.replace(/\/$/, "");
|
|
836
|
+
if (!isPackageLabel && !name.startsWith("@")) {
|
|
837
|
+
if (/\/(?:index)\.(?:[cm]?[jt]s)$/.test(name)) return name;
|
|
838
|
+
const segments = name.split("/").filter(Boolean);
|
|
839
|
+
const fileName = segments.pop() ?? name;
|
|
840
|
+
name = fileName;
|
|
841
|
+
}
|
|
842
|
+
return name.replace(/\.(?:[cm]?[jt]s)$/, "");
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
function isWelcomeScreenExtension(name: string): boolean {
|
|
846
|
+
const normalized = name.replace(/\\/g, "/");
|
|
847
|
+
return (
|
|
848
|
+
normalized === "HeaderFull" ||
|
|
849
|
+
/(?:^|\/)HeaderFull(?:\/|$)/.test(normalized)
|
|
850
|
+
);
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
export function sortExtensionNames(names: string[]): string[] {
|
|
854
|
+
return [...names].sort((left, right) => {
|
|
855
|
+
const scopeOrder =
|
|
856
|
+
Number(left.startsWith("@")) - Number(right.startsWith("@"));
|
|
857
|
+
return scopeOrder || left.localeCompare(right);
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
function unique(items: string[]): string[] {
|
|
862
|
+
return [...new Set(items.filter(Boolean))];
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
interface ExtensionGroups {
|
|
866
|
+
localExtensions: string[];
|
|
867
|
+
packageExtensions: string[];
|
|
868
|
+
sourceExtensions: string[];
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function isPackageSource(label: string): boolean {
|
|
872
|
+
return label.startsWith("npm:") || label.startsWith("git:");
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
function normalizePackageSource(label: string): string {
|
|
876
|
+
return label.replace(/^(?:npm|git):/, "");
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
interface GitPackageSource {
|
|
880
|
+
label: string;
|
|
881
|
+
revision: string | undefined;
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
function splitGitRevision(pathWithRevision: string): {
|
|
885
|
+
path: string;
|
|
886
|
+
revision: string | undefined;
|
|
887
|
+
} {
|
|
888
|
+
const separator = pathWithRevision.indexOf("@");
|
|
889
|
+
if (separator === -1) return { path: pathWithRevision, revision: undefined };
|
|
890
|
+
return {
|
|
891
|
+
path: pathWithRevision.slice(0, separator),
|
|
892
|
+
revision: pathWithRevision.slice(separator + 1),
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
function parseGitPackageSource(source: string): GitPackageSource {
|
|
897
|
+
const value = source.replace(/^git:/, "");
|
|
898
|
+
const scpMatch = value.match(/^git@([^:]+):(.+)$/);
|
|
899
|
+
if (scpMatch) {
|
|
900
|
+
const { path, revision } = splitGitRevision(scpMatch[2] ?? "");
|
|
901
|
+
return {
|
|
902
|
+
label: `${scpMatch[1] ?? ""}/${path}`.replace(/\.git$/, ""),
|
|
903
|
+
revision,
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
if (value.includes("://")) {
|
|
908
|
+
try {
|
|
909
|
+
const url = new URL(value);
|
|
910
|
+
const { path, revision } = splitGitRevision(
|
|
911
|
+
url.pathname.replace(/^\/+/, ""),
|
|
912
|
+
);
|
|
913
|
+
return {
|
|
914
|
+
label: `${url.hostname}/${path}`.replace(/\.git$/, ""),
|
|
915
|
+
revision,
|
|
916
|
+
};
|
|
917
|
+
} catch {
|
|
918
|
+
return { label: value, revision: undefined };
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
const slash = value.indexOf("/");
|
|
923
|
+
if (slash === -1) return { label: value, revision: undefined };
|
|
924
|
+
const { path, revision } = splitGitRevision(value.slice(slash + 1));
|
|
925
|
+
return {
|
|
926
|
+
label: `${value.slice(0, slash)}/${path}`.replace(/\.git$/, ""),
|
|
927
|
+
revision,
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
function formatPackageExtensionLabel(
|
|
932
|
+
source: string,
|
|
933
|
+
extensionPaths: string[],
|
|
934
|
+
): string {
|
|
935
|
+
const extensionNames = unique(
|
|
936
|
+
extensionPaths
|
|
937
|
+
.map((path) => path.replace(/\\/g, "/").split("/").pop() ?? "")
|
|
938
|
+
.filter((name) => /\.[cm]?[jt]s$/.test(name)),
|
|
939
|
+
);
|
|
940
|
+
if (!source.startsWith("git:")) {
|
|
941
|
+
return [normalizePackageSource(source), ...extensionNames].join(" ");
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
const { label, revision } = parseGitPackageSource(source);
|
|
945
|
+
return [
|
|
946
|
+
label,
|
|
947
|
+
...extensionNames,
|
|
948
|
+
...(revision ? [`@${revision.slice(0, 6)}`] : []),
|
|
949
|
+
].join(" ");
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
function isExplicitSourcePath(label: string): boolean {
|
|
953
|
+
const normalized = label.replace(/\\/g, "/");
|
|
954
|
+
return (
|
|
955
|
+
normalized.startsWith("/") ||
|
|
956
|
+
normalized.startsWith("~/") ||
|
|
957
|
+
normalized.startsWith("./") ||
|
|
958
|
+
normalized.startsWith("../") ||
|
|
959
|
+
/^[A-Za-z]:\//.test(normalized) ||
|
|
960
|
+
/\/(?:index)\.(?:[cm]?[jt]s)$/.test(normalized)
|
|
961
|
+
);
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
function parseExpandedExtensionGroups(
|
|
965
|
+
text: string | undefined,
|
|
966
|
+
localExtensionNames: Set<string>,
|
|
967
|
+
): ExtensionGroups | undefined {
|
|
968
|
+
if (!text || getSectionHeading(text) !== "Extensions") return undefined;
|
|
969
|
+
|
|
970
|
+
const localExtensions: string[] = [];
|
|
971
|
+
const packageExtensions: string[] = [];
|
|
972
|
+
const sourceExtensions: string[] = [];
|
|
973
|
+
let foundItem = false;
|
|
974
|
+
let currentPackageSource: string | undefined;
|
|
975
|
+
let currentPackagePaths: string[] = [];
|
|
976
|
+
const flushPackage = () => {
|
|
977
|
+
if (!currentPackageSource) return;
|
|
978
|
+
packageExtensions.push(
|
|
979
|
+
formatPackageExtensionLabel(currentPackageSource, currentPackagePaths),
|
|
980
|
+
);
|
|
981
|
+
currentPackageSource = undefined;
|
|
982
|
+
currentPackagePaths = [];
|
|
983
|
+
};
|
|
984
|
+
|
|
985
|
+
for (const rawLine of text.split("\n").slice(1)) {
|
|
986
|
+
const line = stripAnsi(rawLine).replace(/\s+$/, "");
|
|
987
|
+
const packageSource = line.match(/^ {4}((?:npm|git):.+)$/)?.[1];
|
|
988
|
+
if (packageSource) {
|
|
989
|
+
flushPackage();
|
|
990
|
+
currentPackageSource = packageSource;
|
|
991
|
+
foundItem = true;
|
|
992
|
+
continue;
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
const packagePath = line.match(/^ {6}(\S.*)$/)?.[1];
|
|
996
|
+
if (packagePath && currentPackageSource) {
|
|
997
|
+
currentPackagePaths.push(packagePath);
|
|
998
|
+
continue;
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
flushPackage();
|
|
1002
|
+
const path = line.match(/^ {4}(\S.*)$/)?.[1];
|
|
1003
|
+
if (!path || /^(?:project|user|path)$/.test(path)) continue;
|
|
1004
|
+
|
|
1005
|
+
const name = normalizeExtensionName(path);
|
|
1006
|
+
if (
|
|
1007
|
+
localExtensionNames.has(name) ||
|
|
1008
|
+
/(?:^|\/)\.pi\/(?:agent\/)?extensions(?:\/|$)/.test(
|
|
1009
|
+
path.replace(/\\/g, "/"),
|
|
1010
|
+
)
|
|
1011
|
+
) {
|
|
1012
|
+
localExtensions.push(name);
|
|
1013
|
+
} else {
|
|
1014
|
+
sourceExtensions.push(path.replace(/\\/g, "/"));
|
|
1015
|
+
}
|
|
1016
|
+
foundItem = true;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
flushPackage();
|
|
1020
|
+
|
|
1021
|
+
if (!foundItem) return undefined;
|
|
1022
|
+
return {
|
|
1023
|
+
localExtensions: sortExtensionNames(unique(localExtensions)),
|
|
1024
|
+
packageExtensions: sortExtensionNames(unique(packageExtensions)),
|
|
1025
|
+
sourceExtensions: sortExtensionNames(unique(sourceExtensions)),
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
function classifyCompactExtensionLabels(
|
|
1030
|
+
labels: string[],
|
|
1031
|
+
localExtensionNames: Set<string>,
|
|
1032
|
+
): ExtensionGroups {
|
|
1033
|
+
const localExtensions: string[] = [];
|
|
1034
|
+
const packageExtensions: string[] = [];
|
|
1035
|
+
const sourceExtensions: string[] = [];
|
|
1036
|
+
|
|
1037
|
+
for (const label of labels) {
|
|
1038
|
+
const name = normalizeExtensionName(label);
|
|
1039
|
+
const indexParent = label
|
|
1040
|
+
.replace(/\\/g, "/")
|
|
1041
|
+
.match(/(?:^|\/)([^/]+)\/index\.(?:[cm]?[jt]s)$/)?.[1];
|
|
1042
|
+
if (
|
|
1043
|
+
localExtensionNames.has(name) ||
|
|
1044
|
+
localExtensionNames.has(indexParent ?? "")
|
|
1045
|
+
)
|
|
1046
|
+
localExtensions.push(name);
|
|
1047
|
+
else if (isPackageSource(label) || name.startsWith("@"))
|
|
1048
|
+
packageExtensions.push(
|
|
1049
|
+
isPackageSource(label) ? normalizePackageSource(label) : name,
|
|
1050
|
+
);
|
|
1051
|
+
else if (isExplicitSourcePath(label)) sourceExtensions.push(name);
|
|
1052
|
+
else packageExtensions.push(name);
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
return {
|
|
1056
|
+
localExtensions: sortExtensionNames(unique(localExtensions)),
|
|
1057
|
+
packageExtensions: sortExtensionNames(unique(packageExtensions)),
|
|
1058
|
+
sourceExtensions: sortExtensionNames(unique(sourceExtensions)),
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
function getLocalExtensionNames(): Set<string> {
|
|
1063
|
+
const extensionsDir = join(getAgentDir(), "extensions");
|
|
1064
|
+
try {
|
|
1065
|
+
return new Set(
|
|
1066
|
+
readdirSync(extensionsDir, { withFileTypes: true }).flatMap((entry) => {
|
|
1067
|
+
if (/\.[cm]?[jt]s$/.test(entry.name))
|
|
1068
|
+
return normalizeExtensionName(entry.name);
|
|
1069
|
+
if (
|
|
1070
|
+
entry.isDirectory() &&
|
|
1071
|
+
existsSync(join(extensionsDir, entry.name, "index.ts"))
|
|
1072
|
+
) {
|
|
1073
|
+
return entry.name;
|
|
1074
|
+
}
|
|
1075
|
+
return [];
|
|
1076
|
+
}),
|
|
1077
|
+
);
|
|
1078
|
+
} catch {
|
|
1079
|
+
return new Set();
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
/** Skill name for a displayed path; frontmatter names may differ from the directory. */
|
|
1084
|
+
function skillNameFromPath(path: string): string {
|
|
1085
|
+
const segments = path.replace(/\\/g, "/").split("/").filter(Boolean);
|
|
1086
|
+
const file = segments[segments.length - 1] ?? "";
|
|
1087
|
+
if (/^SKILL\.md$/i.test(file)) return segments[segments.length - 2] ?? "";
|
|
1088
|
+
return file.replace(/\.md$/i, "");
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
/**
|
|
1092
|
+
* Visits the direct entries Pi lists under a `project` scope header in an
|
|
1093
|
+
* expanded resource listing. Package skills or prompts nested under an
|
|
1094
|
+
* `npm:`/`git:` source are not project entries.
|
|
1095
|
+
*/
|
|
1096
|
+
function forEachExpandedProjectEntry(
|
|
1097
|
+
text: string | undefined,
|
|
1098
|
+
heading: string,
|
|
1099
|
+
visit: (entry: string) => void,
|
|
1100
|
+
): void {
|
|
1101
|
+
if (!text || getSectionHeading(text) !== heading) return;
|
|
1102
|
+
|
|
1103
|
+
let inProjectGroup = false;
|
|
1104
|
+
|
|
1105
|
+
for (const rawLine of text.split("\n").slice(1)) {
|
|
1106
|
+
const line = stripAnsi(rawLine).replace(/\s+$/, "");
|
|
1107
|
+
if (!line.trim()) continue;
|
|
1108
|
+
|
|
1109
|
+
if (/^ {2}\S/.test(line)) {
|
|
1110
|
+
inProjectGroup = line.trim() === "project";
|
|
1111
|
+
continue;
|
|
1112
|
+
}
|
|
1113
|
+
if (!inProjectGroup) continue;
|
|
1114
|
+
|
|
1115
|
+
const entry = /^ {4}(\S.*)$/.exec(line)?.[1];
|
|
1116
|
+
if (!entry || isPackageSource(entry)) continue;
|
|
1117
|
+
visit(entry);
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
/**
|
|
1122
|
+
* Skill names Pi loaded from the project scope. Pi renders paths rather
|
|
1123
|
+
* than names, so a frontmatter name that differs from its directory keeps
|
|
1124
|
+
* the dim default instead of guessing.
|
|
1125
|
+
*/
|
|
1126
|
+
function parseExpandedProjectSkills(text: string | undefined): string[] {
|
|
1127
|
+
const names: string[] = [];
|
|
1128
|
+
forEachExpandedProjectEntry(text, "Skills", (entry) => {
|
|
1129
|
+
const name = skillNameFromPath(entry);
|
|
1130
|
+
if (name) names.push(name);
|
|
1131
|
+
});
|
|
1132
|
+
return unique(names);
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
/** Prompt names (`/name`) Pi loaded from the project scope. */
|
|
1136
|
+
function parseExpandedProjectPrompts(
|
|
1137
|
+
text: string | undefined,
|
|
1138
|
+
knownPrompts: readonly string[],
|
|
1139
|
+
): string[] {
|
|
1140
|
+
const known = new Set(knownPrompts);
|
|
1141
|
+
const names: string[] = [];
|
|
1142
|
+
forEachExpandedProjectEntry(text, "Prompts", (entry) => {
|
|
1143
|
+
// Pi renders templates as `/name`; unmatched display paths never equal
|
|
1144
|
+
// a collapsed `/name` entry, so the known set filters them out.
|
|
1145
|
+
if (known.has(entry)) names.push(entry);
|
|
1146
|
+
});
|
|
1147
|
+
return unique(names);
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
/**
|
|
1151
|
+
* Pi renders context files inside the working directory as cwd-relative
|
|
1152
|
+
* paths and everything else as home-abbreviated or absolute paths, so the
|
|
1153
|
+
* display shape alone distinguishes project context from global context.
|
|
1154
|
+
*/
|
|
1155
|
+
function isProjectContextEntry(entry: string): boolean {
|
|
1156
|
+
return !entry.startsWith("~") && !isAbsolute(entry);
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
export function parseWelcomeResources(
|
|
1160
|
+
text: string,
|
|
1161
|
+
localExtensionNames = getLocalExtensionNames(),
|
|
1162
|
+
expandedExtensionsText?: string,
|
|
1163
|
+
expandedSkillsText?: string,
|
|
1164
|
+
expandedPromptsText?: string,
|
|
1165
|
+
): WelcomeResources {
|
|
1166
|
+
const bodies = new Map<WelcomeSection, string[]>();
|
|
1167
|
+
let currentSection: WelcomeSection | undefined;
|
|
1168
|
+
|
|
1169
|
+
for (const rawLine of text.split("\n")) {
|
|
1170
|
+
const line = stripAnsi(rawLine).trim();
|
|
1171
|
+
const header = line.match(/^\[([^\]]+)\]$/)?.[1];
|
|
1172
|
+
if (header) {
|
|
1173
|
+
currentSection = WELCOME_SECTIONS.find((section) => section === header);
|
|
1174
|
+
if (currentSection && !bodies.has(currentSection))
|
|
1175
|
+
bodies.set(currentSection, []);
|
|
1176
|
+
continue;
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
if (line && currentSection) bodies.get(currentSection)?.push(line);
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
const context = unique(splitList(bodies.get("Context") ?? []));
|
|
1183
|
+
const skills = unique(splitList(bodies.get("Skills") ?? []));
|
|
1184
|
+
const prompts = unique(splitList(bodies.get("Prompts") ?? []));
|
|
1185
|
+
const extensionLabels = unique(splitList(bodies.get("Extensions") ?? []));
|
|
1186
|
+
const groups =
|
|
1187
|
+
parseExpandedExtensionGroups(expandedExtensionsText, localExtensionNames) ??
|
|
1188
|
+
classifyCompactExtensionLabels(extensionLabels, localExtensionNames);
|
|
1189
|
+
const extensions = [
|
|
1190
|
+
...groups.localExtensions,
|
|
1191
|
+
...groups.packageExtensions,
|
|
1192
|
+
...groups.sourceExtensions,
|
|
1193
|
+
];
|
|
1194
|
+
|
|
1195
|
+
return {
|
|
1196
|
+
context,
|
|
1197
|
+
skills,
|
|
1198
|
+
prompts,
|
|
1199
|
+
extensions,
|
|
1200
|
+
projectContext: context.filter(isProjectContextEntry),
|
|
1201
|
+
projectSkills: parseExpandedProjectSkills(expandedSkillsText),
|
|
1202
|
+
projectPrompts: parseExpandedProjectPrompts(expandedPromptsText, prompts),
|
|
1203
|
+
packageExtensions: groups.packageExtensions,
|
|
1204
|
+
sourceExtensions: groups.sourceExtensions,
|
|
1205
|
+
};
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
function findResourcePanel(tui: TUI): ResourcePanel | undefined {
|
|
1209
|
+
// TODO: Replace this bridge when Pi exposes structured startup resources
|
|
1210
|
+
// through its custom-header API.
|
|
1211
|
+
//
|
|
1212
|
+
// Pi 0.84 mounts one stable document in both regular and fullscreen modes:
|
|
1213
|
+
// [header, loaded-resources, chat]. Fullscreen scrolls that document without
|
|
1214
|
+
// changing the mounted TUI children, so keep both containers mounted.
|
|
1215
|
+
const documentContainer = tui.children[0];
|
|
1216
|
+
if (isResourcePanel(documentContainer)) {
|
|
1217
|
+
const [header, panel, chat] = documentContainer.children;
|
|
1218
|
+
if (
|
|
1219
|
+
isResourcePanel(header) &&
|
|
1220
|
+
isResourcePanel(panel) &&
|
|
1221
|
+
isResourcePanel(chat)
|
|
1222
|
+
) {
|
|
1223
|
+
return panel;
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
// Pi 0.80–0.83 place the loaded-resources container directly after the
|
|
1228
|
+
// header. Keep the old full-shape guard so an unknown layout stays untouched.
|
|
1229
|
+
if (
|
|
1230
|
+
tui.children.length >= 8 &&
|
|
1231
|
+
isResourcePanel(tui.children[0]) &&
|
|
1232
|
+
isResourcePanel(tui.children[RESOURCE_PANEL_INDEX])
|
|
1233
|
+
) {
|
|
1234
|
+
return tui.children[RESOURCE_PANEL_INDEX];
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
return undefined;
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
function removeKnownResourceChildren(
|
|
1241
|
+
panel: ResourcePanel,
|
|
1242
|
+
knownChildren: Component[],
|
|
1243
|
+
): ResourceBridge {
|
|
1244
|
+
const currentChildren = [...panel.children];
|
|
1245
|
+
const known = new Set(
|
|
1246
|
+
knownChildren.filter((child) => currentChildren.includes(child)),
|
|
1247
|
+
);
|
|
1248
|
+
const removedChildren = currentChildren.flatMap(
|
|
1249
|
+
(component, originalIndex) => {
|
|
1250
|
+
const previous = currentChildren[originalIndex - 1];
|
|
1251
|
+
const next = currentChildren[originalIndex + 1];
|
|
1252
|
+
const remove =
|
|
1253
|
+
known.has(component) ||
|
|
1254
|
+
(component instanceof Spacer &&
|
|
1255
|
+
Boolean(
|
|
1256
|
+
(previous && known.has(previous)) || (next && known.has(next)),
|
|
1257
|
+
));
|
|
1258
|
+
return remove ? [{ component, originalIndex }] : [];
|
|
1259
|
+
},
|
|
1260
|
+
);
|
|
1261
|
+
|
|
1262
|
+
for (const { component } of removedChildren) panel.removeChild(component);
|
|
1263
|
+
return { panel, removedChildren };
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
function restoreResourcePanel(bridge: ResourceBridge): void {
|
|
1267
|
+
for (const { component, originalIndex } of bridge.removedChildren) {
|
|
1268
|
+
if (bridge.panel.children.includes(component)) continue;
|
|
1269
|
+
const index = Math.min(originalIndex, bridge.panel.children.length);
|
|
1270
|
+
bridge.panel.children.splice(index, 0, component);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
function centerBlockLine(
|
|
1275
|
+
line: string,
|
|
1276
|
+
blockWidth: number,
|
|
1277
|
+
width: number,
|
|
1278
|
+
): string {
|
|
1279
|
+
const clipped = truncateToWidth(line, width, "");
|
|
1280
|
+
return (
|
|
1281
|
+
" ".repeat(Math.max(0, Math.floor((width - blockWidth) / 2))) + clipped
|
|
1282
|
+
);
|
|
1283
|
+
}
|
|
1284
|
+
function rightAlignToWidth(text: string, width: number): string {
|
|
1285
|
+
const clipped = truncateToWidth(text, width, "");
|
|
1286
|
+
return " ".repeat(Math.max(0, width - visibleWidth(clipped))) + clipped;
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
function wrapPrefixed(prefix: string, text: string, width: number): string[] {
|
|
1290
|
+
const prefixWidth = visibleWidth(prefix);
|
|
1291
|
+
if (width <= prefixWidth) return [truncateToWidth(prefix, width, "")];
|
|
1292
|
+
|
|
1293
|
+
const wrapped = wrapTextWithAnsi(text, width - prefixWidth);
|
|
1294
|
+
const continuation = " ".repeat(prefixWidth);
|
|
1295
|
+
return wrapped.map(
|
|
1296
|
+
(line, index) => `${index === 0 ? prefix : continuation}${line}`,
|
|
1297
|
+
);
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
function appendLineOperatorsSection(
|
|
1301
|
+
lines: string[],
|
|
1302
|
+
theme: Theme,
|
|
1303
|
+
columnWidth: number,
|
|
1304
|
+
): void {
|
|
1305
|
+
if (lines.length > 0) lines.push("");
|
|
1306
|
+
lines.push(theme.fg("mdHeading", "[Line Operators]"));
|
|
1307
|
+
for (const [operator, description] of LINE_OPERATORS) {
|
|
1308
|
+
lines.push(
|
|
1309
|
+
...wrapPrefixed(
|
|
1310
|
+
theme.fg("accent", ` ${operator} `),
|
|
1311
|
+
theme.fg("dim", description),
|
|
1312
|
+
columnWidth,
|
|
1313
|
+
),
|
|
1314
|
+
);
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
/** Lines printed under the logo, which is usually narrower than they are. */
|
|
1319
|
+
function getBrandHeadlines(theme: Theme, username?: string): string[] {
|
|
1320
|
+
const versionSummary = theme.fg(
|
|
1321
|
+
"dim",
|
|
1322
|
+
theme.name ? `v${VERSION} [${theme.name}]` : `v${VERSION}`,
|
|
1323
|
+
);
|
|
1324
|
+
if (!username) return [versionSummary];
|
|
1325
|
+
return [versionSummary, theme.fg("accent", `Welcome back, ${username}`)];
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
/**
|
|
1329
|
+
* Width of the brand block: the logo column plus whatever the version and
|
|
1330
|
+
* welcome lines need, since those are usually wider than the logo and would
|
|
1331
|
+
* otherwise be clipped to the logo width by the grid.
|
|
1332
|
+
*/
|
|
1333
|
+
function getBrandColumnWidth(
|
|
1334
|
+
theme: Theme,
|
|
1335
|
+
logoType: LogoTypeMode,
|
|
1336
|
+
username?: string,
|
|
1337
|
+
): number {
|
|
1338
|
+
return Math.max(
|
|
1339
|
+
getBannerWidth(logoType),
|
|
1340
|
+
...getBrandHeadlines(theme, username).map((line) => visibleWidth(line)),
|
|
1341
|
+
);
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
function renderBrandColumn(
|
|
1345
|
+
theme: Theme,
|
|
1346
|
+
columnWidth: number,
|
|
1347
|
+
logoType: LogoTypeMode,
|
|
1348
|
+
logoColor: LogoColorMode,
|
|
1349
|
+
username?: string,
|
|
1350
|
+
): string[] {
|
|
1351
|
+
const lines: string[] = [];
|
|
1352
|
+
const banner = getBannerLines(logoType);
|
|
1353
|
+
const bannerWidth = getBannerWidth(logoType);
|
|
1354
|
+
for (const [index, bannerLine] of banner.entries()) {
|
|
1355
|
+
const logo = theme.bold(
|
|
1356
|
+
colorizeBannerLine(
|
|
1357
|
+
theme,
|
|
1358
|
+
bannerLine,
|
|
1359
|
+
index,
|
|
1360
|
+
banner.length,
|
|
1361
|
+
bannerWidth,
|
|
1362
|
+
logoColor,
|
|
1363
|
+
),
|
|
1364
|
+
);
|
|
1365
|
+
lines.push(centerBlockLine(logo, visibleWidth(logo), columnWidth));
|
|
1366
|
+
}
|
|
1367
|
+
lines.push("");
|
|
1368
|
+
for (const headline of getBrandHeadlines(theme, username)) {
|
|
1369
|
+
lines.push(centerBlockLine(headline, visibleWidth(headline), columnWidth));
|
|
1370
|
+
}
|
|
1371
|
+
return lines;
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
function appendRecentSessionsSection(
|
|
1375
|
+
lines: string[],
|
|
1376
|
+
theme: Theme,
|
|
1377
|
+
columnWidth: number,
|
|
1378
|
+
sessions: readonly RecentSession[],
|
|
1379
|
+
): void {
|
|
1380
|
+
if (sessions.length === 0) return;
|
|
1381
|
+
if (lines.length > 0) lines.push("");
|
|
1382
|
+
lines.push(theme.fg("mdHeading", "[Recent Sessions]"));
|
|
1383
|
+
for (const session of sessions) {
|
|
1384
|
+
const age = theme.fg("dim", ` · ${session.age}`);
|
|
1385
|
+
const titleWidth = Math.max(8, columnWidth - 2 - visibleWidth(age));
|
|
1386
|
+
const title = theme.fg(
|
|
1387
|
+
"muted",
|
|
1388
|
+
truncateToWidth(session.title, titleWidth, "…"),
|
|
1389
|
+
);
|
|
1390
|
+
lines.push(` ${title}${age}`);
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
function renderResourceColumn(
|
|
1395
|
+
theme: Theme,
|
|
1396
|
+
columnWidth: number,
|
|
1397
|
+
content: WelcomeContent,
|
|
1398
|
+
): string[] {
|
|
1399
|
+
const lines: string[] = [];
|
|
1400
|
+
appendLineOperatorsSection(lines, theme, columnWidth);
|
|
1401
|
+
appendRecentSessionsSection(lines, theme, columnWidth, content.sessions);
|
|
1402
|
+
if (content.tip) {
|
|
1403
|
+
lines.push("");
|
|
1404
|
+
lines.push(
|
|
1405
|
+
...wrapPrefixed(
|
|
1406
|
+
theme.fg("accent", "Tip: "),
|
|
1407
|
+
theme.fg("dim", content.tip),
|
|
1408
|
+
columnWidth,
|
|
1409
|
+
),
|
|
1410
|
+
);
|
|
1411
|
+
}
|
|
1412
|
+
if (content.notice) {
|
|
1413
|
+
lines.push("", ...wrapTextWithAnsi(theme.fg("dim", content.notice), columnWidth));
|
|
1414
|
+
}
|
|
1415
|
+
return lines;
|
|
1416
|
+
}
|
|
1417
|
+
function renderInfoFrame(
|
|
1418
|
+
content: string[],
|
|
1419
|
+
theme: Theme,
|
|
1420
|
+
width: number,
|
|
1421
|
+
): string[] {
|
|
1422
|
+
const innerWidth = Math.max(1, width - 2);
|
|
1423
|
+
const horizontal = () => theme.fg("accent", "─".repeat(innerWidth));
|
|
1424
|
+
const vertical = () => `${theme.fg("accent", "│")}${" ".repeat(innerWidth)}${theme.fg("accent", "│")}`;
|
|
1425
|
+
const padding = Array.from({ length: FRAME_VERTICAL_PADDING }, vertical);
|
|
1426
|
+
return [
|
|
1427
|
+
`${theme.fg("accent", "╭")}${horizontal()}${theme.fg("accent", "╮")}`,
|
|
1428
|
+
...padding,
|
|
1429
|
+
...content.map(
|
|
1430
|
+
(line) =>
|
|
1431
|
+
`${theme.fg("accent", "│")}${padToWidth(line, innerWidth)}${theme.fg("accent", "│")}`,
|
|
1432
|
+
),
|
|
1433
|
+
...padding,
|
|
1434
|
+
`${theme.fg("accent", "╰")}${horizontal()}${theme.fg("accent", "╯")}`,
|
|
1435
|
+
];
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
/**
|
|
1439
|
+
* Brand block on the left, resource column on the right, `│` between them.
|
|
1440
|
+
* The brand block is centered vertically against the taller column.
|
|
1441
|
+
*/
|
|
1442
|
+
function renderColumnLayout(
|
|
1443
|
+
theme: Theme,
|
|
1444
|
+
brandWidth: number,
|
|
1445
|
+
resourceLines: readonly string[],
|
|
1446
|
+
resourceWidth: number,
|
|
1447
|
+
content: WelcomeContent,
|
|
1448
|
+
): string[] {
|
|
1449
|
+
const brand = renderBrandColumn(
|
|
1450
|
+
theme,
|
|
1451
|
+
brandWidth,
|
|
1452
|
+
content.logoType,
|
|
1453
|
+
content.logoColor,
|
|
1454
|
+
content.username,
|
|
1455
|
+
);
|
|
1456
|
+
const rowCount = Math.max(brand.length, resourceLines.length);
|
|
1457
|
+
const brandTop = Math.max(0, Math.floor((rowCount - brand.length) / 2));
|
|
1458
|
+
const divider = theme.fg("accent", COLUMN_DIVIDER);
|
|
1459
|
+
return Array.from({ length: rowCount }, (_, row) => {
|
|
1460
|
+
const index = row - brandTop;
|
|
1461
|
+
const brandLine = index >= 0 && index < brand.length ? (brand[index] ?? "") : "";
|
|
1462
|
+
return `${padToWidth(brandLine, brandWidth)}${divider}${resourceLines[row] ?? ""}`.trimEnd();
|
|
1463
|
+
});
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
/** Narrow terminals: brand block above the resource column, split by a rule. */
|
|
1467
|
+
function renderStackedLayout(
|
|
1468
|
+
theme: Theme,
|
|
1469
|
+
innerWidth: number,
|
|
1470
|
+
content: WelcomeContent,
|
|
1471
|
+
): string[] {
|
|
1472
|
+
const lines = renderBrandColumn(
|
|
1473
|
+
theme,
|
|
1474
|
+
innerWidth,
|
|
1475
|
+
content.logoType,
|
|
1476
|
+
content.logoColor,
|
|
1477
|
+
content.username,
|
|
1478
|
+
);
|
|
1479
|
+
lines.push(
|
|
1480
|
+
"",
|
|
1481
|
+
theme.fg("muted", "─".repeat(innerWidth)),
|
|
1482
|
+
"",
|
|
1483
|
+
...renderResourceColumn(theme, innerWidth, content),
|
|
1484
|
+
);
|
|
1485
|
+
return lines;
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
function padToWidth(text: string, width: number): string {
|
|
1489
|
+
const clipped = truncateToWidth(text, width, "");
|
|
1490
|
+
return clipped + " ".repeat(Math.max(0, width - visibleWidth(clipped)));
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
|
|
1494
|
+
export function renderCompactWelcome(
|
|
1495
|
+
theme: Theme,
|
|
1496
|
+
width: number,
|
|
1497
|
+
version: string,
|
|
1498
|
+
model: string | undefined,
|
|
1499
|
+
directory: string,
|
|
1500
|
+
): string[] {
|
|
1501
|
+
if (width <= 0) return [];
|
|
1502
|
+
|
|
1503
|
+
const accent = (text: string) => theme.fg("accent", text);
|
|
1504
|
+
const muted = (text: string) => theme.fg("muted", text);
|
|
1505
|
+
|
|
1506
|
+
const versionLabel = version.startsWith("v") ? version : `v${version}`;
|
|
1507
|
+
const ornament = "";
|
|
1508
|
+
const titleRow = `${accent(ornament)} ${accent("Chalice")} ${muted(versionLabel)}`;
|
|
1509
|
+
const modelRow = model ? `${muted("model: ")}${accent(model)}` : undefined;
|
|
1510
|
+
const directoryRow = `${muted("directory: ")}${accent(directory)}`;
|
|
1511
|
+
|
|
1512
|
+
const titleWidth = visibleWidth(`${ornament} Chalice ${versionLabel}`);
|
|
1513
|
+
const modelWidth = model ? visibleWidth(`model: ${model}`) : 0;
|
|
1514
|
+
const directoryWidth = visibleWidth(`directory: ${directory}`);
|
|
1515
|
+
const maxContentLength = Math.max(titleWidth, modelWidth, directoryWidth);
|
|
1516
|
+
|
|
1517
|
+
const boxWidth = Math.min(width, maxContentLength + 4);
|
|
1518
|
+
const inner = Math.max(0, boxWidth - 2);
|
|
1519
|
+
const pad = inner >= 2 ? 1 : 0;
|
|
1520
|
+
const contentWidth = Math.max(0, inner - pad * 2);
|
|
1521
|
+
const padStr = " ".repeat(pad);
|
|
1522
|
+
const rule = muted("─".repeat(inner));
|
|
1523
|
+
|
|
1524
|
+
const clamp = (text: string) => {
|
|
1525
|
+
const clipped = truncateToWidth(text, contentWidth, "");
|
|
1526
|
+
return clipped + " ".repeat(Math.max(0, contentWidth - visibleWidth(clipped)));
|
|
1527
|
+
};
|
|
1528
|
+
const row = (text?: string) =>
|
|
1529
|
+
muted("│") + padStr + clamp(text ?? "") + padStr + muted("│");
|
|
1530
|
+
|
|
1531
|
+
return [
|
|
1532
|
+
muted("╭") + rule + muted("╮"),
|
|
1533
|
+
row(titleRow),
|
|
1534
|
+
row(),
|
|
1535
|
+
...(modelRow ? [row(modelRow)] : []),
|
|
1536
|
+
row(directoryRow),
|
|
1537
|
+
row(),
|
|
1538
|
+
muted("╰") + rule + muted("╯"),
|
|
1539
|
+
];
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
/**
|
|
1543
|
+
* Banner, version, welcome, and the tip, all centered on the terminal with no
|
|
1544
|
+
* frame and no resource summary.
|
|
1545
|
+
*/
|
|
1546
|
+
export function renderSimpleWelcome(
|
|
1547
|
+
theme: Theme,
|
|
1548
|
+
width: number,
|
|
1549
|
+
tip: string,
|
|
1550
|
+
username?: string,
|
|
1551
|
+
logoType: LogoTypeMode = "square",
|
|
1552
|
+
logoColor: LogoColorMode = "gradient",
|
|
1553
|
+
): string[] {
|
|
1554
|
+
if (width <= 0) return [];
|
|
1555
|
+
const lines = renderBrandColumn(theme, width, logoType, logoColor, username);
|
|
1556
|
+
if (!tip) return lines;
|
|
1557
|
+
const tipLines = wrapPrefixed(
|
|
1558
|
+
theme.fg("accent", "Tip: "),
|
|
1559
|
+
theme.fg("dim", tip),
|
|
1560
|
+
Math.max(1, Math.min(width, MAX_STACKED_COLUMN_WIDTH)),
|
|
1561
|
+
);
|
|
1562
|
+
// Center the wrapped tip as one block so its hanging indent survives.
|
|
1563
|
+
const tipOffset = " ".repeat(
|
|
1564
|
+
Math.max(0, Math.floor((width - Math.max(...tipLines.map(visibleWidth))) / 2)),
|
|
1565
|
+
);
|
|
1566
|
+
return [...lines, "", ...tipLines.map((line) => tipOffset + line)];
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
/**
|
|
1570
|
+
* Frames the welcome content at exactly the width it needs and centers that
|
|
1571
|
+
* frame horizontally on the terminal.
|
|
1572
|
+
*/
|
|
1573
|
+
export function renderCenteredWelcome(
|
|
1574
|
+
theme: Theme,
|
|
1575
|
+
width: number,
|
|
1576
|
+
content: WelcomeContent,
|
|
1577
|
+
): string[] {
|
|
1578
|
+
if (width <= 0) return [];
|
|
1579
|
+
const sidePadding = Math.min(
|
|
1580
|
+
WELCOME_SIDE_PADDING,
|
|
1581
|
+
Math.max(0, Math.floor((width - 1) / 2)),
|
|
1582
|
+
);
|
|
1583
|
+
const contentWidth = width - sidePadding * 2;
|
|
1584
|
+
const availableWidth = Math.max(1, contentWidth - FRAME_OVERHEAD);
|
|
1585
|
+
const brandWidth = getBrandColumnWidth(theme, content.logoType, content.username);
|
|
1586
|
+
const resourceCap = Math.min(
|
|
1587
|
+
MAX_RESOURCE_COLUMN_WIDTH,
|
|
1588
|
+
availableWidth - brandWidth - COLUMN_DIVIDER_WIDTH,
|
|
1589
|
+
);
|
|
1590
|
+
|
|
1591
|
+
let innerLines: string[];
|
|
1592
|
+
let innerWidth: number;
|
|
1593
|
+
if (resourceCap >= MIN_RESOURCE_COLUMN_WIDTH) {
|
|
1594
|
+
const resourceLines = renderResourceColumn(theme, resourceCap, content);
|
|
1595
|
+
const resourceWidth = Math.max(1, ...resourceLines.map(visibleWidth));
|
|
1596
|
+
innerLines = renderColumnLayout(
|
|
1597
|
+
theme,
|
|
1598
|
+
brandWidth,
|
|
1599
|
+
resourceLines,
|
|
1600
|
+
resourceWidth,
|
|
1601
|
+
content,
|
|
1602
|
+
);
|
|
1603
|
+
innerWidth = brandWidth + COLUMN_DIVIDER_WIDTH + resourceWidth;
|
|
1604
|
+
} else {
|
|
1605
|
+
innerWidth = Math.min(MAX_STACKED_COLUMN_WIDTH, availableWidth);
|
|
1606
|
+
innerLines = renderStackedLayout(theme, innerWidth, content);
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
const layoutWidth = innerWidth + FRAME_OVERHEAD;
|
|
1610
|
+
const frame = renderInfoFrame(
|
|
1611
|
+
innerLines.map((line) => " ".repeat(GRID_INNER_PADDING) + line),
|
|
1612
|
+
theme,
|
|
1613
|
+
layoutWidth,
|
|
1614
|
+
);
|
|
1615
|
+
const horizontalOffset = Math.max(0, Math.floor((contentWidth - layoutWidth) / 2));
|
|
1616
|
+
const leftPadding = " ".repeat(sidePadding + horizontalOffset);
|
|
1617
|
+
return frame.map((line) =>
|
|
1618
|
+
line ? leftPadding + truncateToWidth(line, layoutWidth, "") : "",
|
|
1619
|
+
);
|
|
1620
|
+
}
|
|
1621
|
+
class WelcomeHeader implements Component {
|
|
1622
|
+
private resourceReadyTimer: ReturnType<typeof setTimeout> | undefined;
|
|
1623
|
+
private resources: WelcomeResources | undefined;
|
|
1624
|
+
private notice: string | undefined;
|
|
1625
|
+
private sessions: readonly RecentSession[] = [];
|
|
1626
|
+
private cachedWidth: number | undefined;
|
|
1627
|
+
private cachedLines: string[] | undefined;
|
|
1628
|
+
private readonly bridges = new Map<ResourcePanel, ResourceBridge>();
|
|
1629
|
+
private sawResourcePanel = false;
|
|
1630
|
+
private disposed = false;
|
|
1631
|
+
private readonly notify: (
|
|
1632
|
+
message: string,
|
|
1633
|
+
type?: "info" | "warning" | "error",
|
|
1634
|
+
) => void;
|
|
1635
|
+
private healthCheckStarted = false;
|
|
1636
|
+
private healthController: AbortController | undefined;
|
|
1637
|
+
private readonly hidden: boolean;
|
|
1638
|
+
private readonly compact: boolean;
|
|
1639
|
+
private readonly simple: boolean;
|
|
1640
|
+
private readonly directory: string;
|
|
1641
|
+
private readonly username: string | undefined;
|
|
1642
|
+
private readonly modelText: string | undefined;
|
|
1643
|
+
private readonly tip: string;
|
|
1644
|
+
private readonly logoType: LogoTypeMode;
|
|
1645
|
+
private readonly logoColor: LogoColorMode;
|
|
1646
|
+
|
|
1647
|
+
private readonly tui: TUI;
|
|
1648
|
+
private readonly theme: Theme;
|
|
1649
|
+
|
|
1650
|
+
constructor(
|
|
1651
|
+
tui: TUI,
|
|
1652
|
+
theme: Theme,
|
|
1653
|
+
forceInitialRender: boolean,
|
|
1654
|
+
notify: (message: string, type?: "info" | "warning" | "error") => void,
|
|
1655
|
+
hidden = false,
|
|
1656
|
+
compact = false,
|
|
1657
|
+
directory = "",
|
|
1658
|
+
modelText: string | undefined = undefined,
|
|
1659
|
+
username: string | undefined = undefined,
|
|
1660
|
+
simple = false,
|
|
1661
|
+
logoType: LogoTypeMode = "square",
|
|
1662
|
+
logoColor: LogoColorMode = "gradient",
|
|
1663
|
+
) {
|
|
1664
|
+
this.tui = tui;
|
|
1665
|
+
this.theme = theme;
|
|
1666
|
+
this.notify = notify;
|
|
1667
|
+
this.hidden = hidden;
|
|
1668
|
+
this.compact = compact;
|
|
1669
|
+
this.directory = directory;
|
|
1670
|
+
this.modelText = modelText;
|
|
1671
|
+
this.username = username;
|
|
1672
|
+
this.simple = simple;
|
|
1673
|
+
this.logoType = logoType;
|
|
1674
|
+
this.logoColor = logoColor;
|
|
1675
|
+
this.tip = hidden || compact ? "" : takeNextTip(loadWelcomeConfig());
|
|
1676
|
+
// Simple captures resources only to detach Pi's native zone; it renders no summary.
|
|
1677
|
+
// session_start runs just before Pi populates its loaded-resource panel.
|
|
1678
|
+
this.resourceReadyTimer = setTimeout(
|
|
1679
|
+
() => this.captureResourcesWhenReady(forceInitialRender, 0),
|
|
1680
|
+
0,
|
|
1681
|
+
);
|
|
1682
|
+
}
|
|
1683
|
+
private captureResourcesWhenReady(
|
|
1684
|
+
forceInitialRender: boolean,
|
|
1685
|
+
attempt: number,
|
|
1686
|
+
): void {
|
|
1687
|
+
if (this.disposed) return;
|
|
1688
|
+
|
|
1689
|
+
let panel: ResourcePanel | undefined;
|
|
1690
|
+
let snapshot: ResourcePanelSnapshot | undefined;
|
|
1691
|
+
try {
|
|
1692
|
+
panel = findResourcePanel(this.tui);
|
|
1693
|
+
if (panel) {
|
|
1694
|
+
this.sawResourcePanel = true;
|
|
1695
|
+
snapshot = inspectResourcePanel(panel);
|
|
1696
|
+
}
|
|
1697
|
+
} catch {
|
|
1698
|
+
panel = undefined;
|
|
1699
|
+
snapshot = undefined;
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
const {
|
|
1703
|
+
resourceText,
|
|
1704
|
+
expandedExtensionsText,
|
|
1705
|
+
expandedSkillsText,
|
|
1706
|
+
expandedPromptsText,
|
|
1707
|
+
} = snapshot ?? {
|
|
1708
|
+
resourceText: "",
|
|
1709
|
+
expandedExtensionsText: undefined,
|
|
1710
|
+
expandedSkillsText: undefined,
|
|
1711
|
+
expandedPromptsText: undefined,
|
|
1712
|
+
};
|
|
1713
|
+
const candidateResources = resourceText
|
|
1714
|
+
? parseWelcomeResources(
|
|
1715
|
+
resourceText,
|
|
1716
|
+
getLocalExtensionNames(),
|
|
1717
|
+
expandedExtensionsText,
|
|
1718
|
+
expandedSkillsText,
|
|
1719
|
+
expandedPromptsText,
|
|
1720
|
+
)
|
|
1721
|
+
: undefined;
|
|
1722
|
+
// Do not alter a partial panel: resource discovery may still be filling it.
|
|
1723
|
+
const resourcePanelIsComplete = Boolean(
|
|
1724
|
+
candidateResources?.extensions.some(isWelcomeScreenExtension),
|
|
1725
|
+
);
|
|
1726
|
+
if (resourcePanelIsComplete && panel && snapshot) {
|
|
1727
|
+
this.bridges.set(
|
|
1728
|
+
panel,
|
|
1729
|
+
removeKnownResourceChildren(panel, snapshot.knownChildren),
|
|
1730
|
+
);
|
|
1731
|
+
this.resources = candidateResources;
|
|
1732
|
+
if (candidateResources) this.startHealthCheck(candidateResources);
|
|
1733
|
+
this.notice = undefined;
|
|
1734
|
+
this.clearRenderCache();
|
|
1735
|
+
// The document height changed. Force a redraw so retained diagnostics or
|
|
1736
|
+
// third-party rows cannot leave stale content below the custom header.
|
|
1737
|
+
this.tui.requestRender(true);
|
|
1738
|
+
} else if (attempt === 0) {
|
|
1739
|
+
this.tui.requestRender(forceInitialRender);
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
// Keep watching briefly after capture. On /reload Pi can rebuild its native
|
|
1743
|
+
// resource children after session_start; a later snapshot must replace the
|
|
1744
|
+
// stale generation rather than appearing below the custom summary.
|
|
1745
|
+
if (attempt < MAX_RESOURCE_RETRIES) {
|
|
1746
|
+
this.resourceReadyTimer = setTimeout(
|
|
1747
|
+
() => this.captureResourcesWhenReady(false, attempt + 1),
|
|
1748
|
+
RESOURCE_POLL_INTERVAL_MS,
|
|
1749
|
+
);
|
|
1750
|
+
return;
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
this.resourceReadyTimer = undefined;
|
|
1754
|
+
if (!this.sawResourcePanel) {
|
|
1755
|
+
this.notice = LAYOUT_NOTICE;
|
|
1756
|
+
this.clearRenderCache();
|
|
1757
|
+
this.tui.requestRender(false);
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1761
|
+
private clearRenderCache(): void {
|
|
1762
|
+
this.cachedWidth = undefined;
|
|
1763
|
+
this.cachedLines = undefined;
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
private startHealthCheck(resources: WelcomeResources): void {
|
|
1767
|
+
if (this.healthCheckStarted) return;
|
|
1768
|
+
const names = unique(
|
|
1769
|
+
(resources.packageExtensions ?? []).filter((name) =>
|
|
1770
|
+
NPM_PACKAGE_NAME.test(name),
|
|
1771
|
+
),
|
|
1772
|
+
);
|
|
1773
|
+
if (names.length === 0) return;
|
|
1774
|
+
this.healthCheckStarted = true;
|
|
1775
|
+
this.healthController = new AbortController();
|
|
1776
|
+
void collectExtensionHealth(
|
|
1777
|
+
names,
|
|
1778
|
+
createHealthEnvironment(getAgentDir()),
|
|
1779
|
+
this.healthController.signal,
|
|
1780
|
+
)
|
|
1781
|
+
.then((health) => {
|
|
1782
|
+
if (this.disposed) return;
|
|
1783
|
+
this.announceHealth(health);
|
|
1784
|
+
})
|
|
1785
|
+
.catch(() => undefined);
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
private announceHealth(health: ExtensionHealthMap): void {
|
|
1789
|
+
const flagged = [...health.entries()].filter(
|
|
1790
|
+
([, entry]) => entry.severity !== "ok",
|
|
1791
|
+
);
|
|
1792
|
+
if (flagged.length === 0) return;
|
|
1793
|
+
const type = flagged.some(([, entry]) => entry.severity === "blocked")
|
|
1794
|
+
? "error"
|
|
1795
|
+
: "warning";
|
|
1796
|
+
this.notify(
|
|
1797
|
+
flagged
|
|
1798
|
+
.map(([name, entry]) => describeHealthIssue(name, entry))
|
|
1799
|
+
.join(" · ")
|
|
1800
|
+
.slice(0, 160),
|
|
1801
|
+
type,
|
|
1802
|
+
);
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
render(width: number): string[] {
|
|
1806
|
+
if (this.hidden) return [];
|
|
1807
|
+
if (this.simple) {
|
|
1808
|
+
return renderSimpleWelcome(
|
|
1809
|
+
this.theme,
|
|
1810
|
+
width,
|
|
1811
|
+
this.tip,
|
|
1812
|
+
this.username,
|
|
1813
|
+
this.logoType,
|
|
1814
|
+
this.logoColor,
|
|
1815
|
+
);
|
|
1816
|
+
}
|
|
1817
|
+
if (this.compact) {
|
|
1818
|
+
return renderCompactWelcome(
|
|
1819
|
+
this.theme,
|
|
1820
|
+
width,
|
|
1821
|
+
VERSION,
|
|
1822
|
+
this.modelText,
|
|
1823
|
+
this.directory,
|
|
1824
|
+
);
|
|
1825
|
+
}
|
|
1826
|
+
if (this.cachedLines && this.cachedWidth === width) {
|
|
1827
|
+
return this.cachedLines;
|
|
1828
|
+
}
|
|
1829
|
+
const lines = renderCenteredWelcome(this.theme, width, {
|
|
1830
|
+
tip: this.tip,
|
|
1831
|
+
username: this.username,
|
|
1832
|
+
notice: this.notice,
|
|
1833
|
+
sessions: this.sessions,
|
|
1834
|
+
logoType: this.logoType,
|
|
1835
|
+
logoColor: this.logoColor,
|
|
1836
|
+
});
|
|
1837
|
+
this.cachedWidth = width;
|
|
1838
|
+
this.cachedLines = lines;
|
|
1839
|
+
return lines;
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
/** Fills in the `[Recent Sessions]` section once Pi has listed them. */
|
|
1843
|
+
setRecentSessions(sessions: readonly RecentSession[]): void {
|
|
1844
|
+
if (this.disposed || sessions.length === 0) return;
|
|
1845
|
+
this.sessions = sessions;
|
|
1846
|
+
this.clearRenderCache();
|
|
1847
|
+
this.tui.requestRender(true);
|
|
1848
|
+
}
|
|
1849
|
+
|
|
1850
|
+
invalidate(): void {
|
|
1851
|
+
this.clearRenderCache();
|
|
1852
|
+
for (const bridge of this.bridges.values()) bridge.panel.invalidate();
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
|
|
1856
|
+
dispose(): void {
|
|
1857
|
+
if (this.disposed) return;
|
|
1858
|
+
this.disposed = true;
|
|
1859
|
+
this.healthController?.abort();
|
|
1860
|
+
if (this.resourceReadyTimer) clearTimeout(this.resourceReadyTimer);
|
|
1861
|
+
for (const bridge of this.bridges.values()) restoreResourcePanel(bridge);
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
function formatModelLabel(model: NonNullable<ExtensionContext["model"]>): string {
|
|
1866
|
+
return `${model.provider}/${model.id}`;
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
/** `3h`-style age for a recent-session row. */
|
|
1870
|
+
function formatSessionAge(date: Date): string {
|
|
1871
|
+
const minutes = Math.floor((Date.now() - date.getTime()) / 60_000);
|
|
1872
|
+
if (minutes < 1) return "now";
|
|
1873
|
+
if (minutes < 60) return `${minutes}m`;
|
|
1874
|
+
const hours = Math.floor(minutes / 60);
|
|
1875
|
+
if (hours < 24) return `${hours}h`;
|
|
1876
|
+
const days = Math.floor(hours / 24);
|
|
1877
|
+
if (days < 30) return `${days}d`;
|
|
1878
|
+
const months = Math.floor(days / 30);
|
|
1879
|
+
return months < 12 ? `${months}mo` : `${Math.floor(months / 12)}y`;
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
function sessionTitle(session: SessionInfo): string {
|
|
1883
|
+
const name = session.name?.trim();
|
|
1884
|
+
if (name) return name;
|
|
1885
|
+
const first = session.firstMessage.replace(/\s+/g, " ").trim();
|
|
1886
|
+
return first.length > 0 ? first : "untitled";
|
|
1887
|
+
}
|
|
1888
|
+
|
|
1889
|
+
/** Most recent sessions in this project, newest first, minus the current one. */
|
|
1890
|
+
async function loadRecentSessions(ctx: ExtensionContext): Promise<RecentSession[]> {
|
|
1891
|
+
try {
|
|
1892
|
+
const sessions = await SessionManager.list(
|
|
1893
|
+
ctx.cwd,
|
|
1894
|
+
ctx.sessionManager.getSessionDir(),
|
|
1895
|
+
);
|
|
1896
|
+
const currentId = ctx.sessionManager.getSessionId();
|
|
1897
|
+
return sessions
|
|
1898
|
+
.filter((session) => session.id !== currentId)
|
|
1899
|
+
.slice(0, RECENT_SESSION_LIMIT)
|
|
1900
|
+
.map((session) => ({
|
|
1901
|
+
title: sessionTitle(session),
|
|
1902
|
+
age: formatSessionAge(session.modified),
|
|
1903
|
+
}));
|
|
1904
|
+
} catch {
|
|
1905
|
+
return [];
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
function applyWelcomeMode(ctx: ExtensionContext, forceInitialRender: boolean): void {
|
|
1910
|
+
|
|
1911
|
+
const notify = (message: string, type?: "info" | "warning" | "error") =>
|
|
1912
|
+
ctx.ui.notify(message, type);
|
|
1913
|
+
// Capture startup values so the header snapshot never reads stale state later.
|
|
1914
|
+
const directory = ctx.cwd;
|
|
1915
|
+
const modelText = ctx.model ? formatModelLabel(ctx.model) : undefined;
|
|
1916
|
+
const username = loadUsername(ctx);
|
|
1917
|
+
const logoType = loadLogoType(ctx);
|
|
1918
|
+
const logoColor = loadLogoColor(ctx);
|
|
1919
|
+
// The factory reads the persisted Welcome/Header banner type at construction, so
|
|
1920
|
+
// recreating the header after a /chalicesettings change applies the new value without
|
|
1921
|
+
// waiting for the next session start.
|
|
1922
|
+
ctx.ui.setHeader((tui, theme) => {
|
|
1923
|
+
const mode = loadHeaderBannerMode(ctx);
|
|
1924
|
+
if (mode === "none") {
|
|
1925
|
+
return new WelcomeHeader(tui, theme, forceInitialRender, () => undefined, true);
|
|
1926
|
+
}
|
|
1927
|
+
if (mode === "simple") {
|
|
1928
|
+
return new WelcomeHeader(
|
|
1929
|
+
tui,
|
|
1930
|
+
theme,
|
|
1931
|
+
forceInitialRender,
|
|
1932
|
+
notify,
|
|
1933
|
+
false,
|
|
1934
|
+
false,
|
|
1935
|
+
"",
|
|
1936
|
+
undefined,
|
|
1937
|
+
username,
|
|
1938
|
+
true,
|
|
1939
|
+
logoType,
|
|
1940
|
+
logoColor,
|
|
1941
|
+
);
|
|
1942
|
+
}
|
|
1943
|
+
if (mode === "compact") {
|
|
1944
|
+
return new WelcomeHeader(
|
|
1945
|
+
tui,
|
|
1946
|
+
theme,
|
|
1947
|
+
forceInitialRender,
|
|
1948
|
+
notify,
|
|
1949
|
+
false,
|
|
1950
|
+
true,
|
|
1951
|
+
directory,
|
|
1952
|
+
modelText,
|
|
1953
|
+
);
|
|
1954
|
+
}
|
|
1955
|
+
const header = new WelcomeHeader(
|
|
1956
|
+
tui,
|
|
1957
|
+
theme,
|
|
1958
|
+
forceInitialRender,
|
|
1959
|
+
notify,
|
|
1960
|
+
false,
|
|
1961
|
+
false,
|
|
1962
|
+
"",
|
|
1963
|
+
undefined,
|
|
1964
|
+
username,
|
|
1965
|
+
false,
|
|
1966
|
+
logoType,
|
|
1967
|
+
logoColor,
|
|
1968
|
+
);
|
|
1969
|
+
void loadRecentSessions(ctx).then((sessions) => header.setRecentSessions(sessions));
|
|
1970
|
+
return header;
|
|
1971
|
+
});
|
|
1972
|
+
}
|
|
1973
|
+
|
|
1974
|
+
|
|
1975
|
+
export default function (pi: ExtensionAPI) {
|
|
1976
|
+
let latestCtx: ExtensionContext | undefined;
|
|
1977
|
+
|
|
1978
|
+
registerChaliceSettingsSection(pi, HEADER_SECTION);
|
|
1979
|
+
|
|
1980
|
+
pi.on("session_start", (event, ctx) => {
|
|
1981
|
+
latestCtx = ctx;
|
|
1982
|
+
if (ctx.mode !== "tui") return;
|
|
1983
|
+
applyWelcomeMode(ctx, event.reason === "startup");
|
|
1984
|
+
});
|
|
1985
|
+
|
|
1986
|
+
pi.events.on(CHALICE_SETTINGS_EVENT, () => {
|
|
1987
|
+
if (latestCtx?.mode === "tui") applyWelcomeMode(latestCtx, false);
|
|
1988
|
+
});
|
|
1989
|
+
}
|