@leolastforce/chalice-shared 0.0.0-stage → 0.1.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 (3) hide show
  1. package/README.md +2 -2
  2. package/package.json +24 -5
  3. package/settings.ts +489 -0
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # Temporary Holding Version
1
+ > This is a chalice library, check out github.com/leolastforce/Chalice
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ This is a library, not an extension. github.com/leolastforce/chalice for monorepo
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
- "name": "@leolastforce/chalice-shared",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@leolastforce/chalice-shared",
3
+ "version": "0.1.0",
4
+ "description": "Chalice lib for settings storage and shared helpers used by Chalice modules.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": "./settings.ts"
9
+ },
10
+ "types": "./settings.ts",
11
+ "files": [
12
+ "settings.ts"
13
+ ],
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "peerDependencies": {
18
+ "@earendil-works/pi-coding-agent": "*"
19
+ },
20
+ "peerDependenciesMeta": {
21
+ "@earendil-works/pi-coding-agent": {
22
+ "optional": true
23
+ }
24
+ }
25
+ }
package/settings.ts ADDED
@@ -0,0 +1,489 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import {
4
+ getAgentDir,
5
+ SettingsManager,
6
+ type ExtensionAPI,
7
+ type ExtensionContext,
8
+ } from "@earendil-works/pi-coding-agent";
9
+
10
+ /** Emitted after Chalice settings are written. */
11
+ export const CHALICE_SETTINGS_EVENT = "chalice:settings-changed";
12
+ /** Extensions announce their settings sections on this channel. */
13
+ export const CHALICE_SETTINGS_COLLECT_EVENT = "chalice:settings:collect";
14
+
15
+ export type HeaderBannerMode = "full" | "simple" | "compact" | "none";
16
+ /** How the header logo is colored: accent gradient, flat accent, white, or Pi's brand ramp. */
17
+ export type LogoColorMode = "gradient" | "accent" | "white" | "pi";
18
+ /** Which art the header logo uses. */
19
+ export type LogoTypeMode = "square" | "pi";
20
+ export type StatusLineLayout = "left" | "center" | "right";
21
+
22
+ export interface StatusLineSettings {
23
+ /** Set to false to hide the line entirely. */
24
+ enabled?: boolean;
25
+ /** Where the stats sit on the line. "center" pins the model segment in the middle. */
26
+ layout?: StatusLineLayout;
27
+ /** Per-segment visibility. Omitted segments stay visible. */
28
+ segments?: Record<string, boolean>;
29
+ /** Keep Pi's built-in footer. Default false: only extension statuses render. */
30
+ defaultFooter?: boolean;
31
+ }
32
+
33
+ export interface ChaliceSettings {
34
+ username?: string;
35
+ usernameEnabled?: boolean;
36
+ headerBanner?: HeaderBannerMode;
37
+ logoColor?: LogoColorMode;
38
+ logoType?: LogoTypeMode;
39
+ memorySaving?: boolean;
40
+ conversationSearch?: boolean;
41
+ statusLine?: StatusLineSettings;
42
+ }
43
+
44
+ export interface ResolvedStatusLineSettings {
45
+ enabled: boolean;
46
+ layout: StatusLineLayout;
47
+ segments: Record<string, boolean>;
48
+ defaultFooter: boolean;
49
+ }
50
+
51
+ export interface ResolvedChaliceSettings {
52
+ username: string | undefined;
53
+ usernameEnabled: boolean;
54
+ headerBanner: HeaderBannerMode;
55
+ logoColor: LogoColorMode;
56
+ logoType: LogoTypeMode;
57
+ memorySaving: boolean;
58
+ conversationSearch: boolean;
59
+ statusLine: ResolvedStatusLineSettings;
60
+ }
61
+
62
+ export interface ChaliceSettingsChangedEvent {
63
+ settings: ResolvedChaliceSettings;
64
+ patch: Record<string, unknown>;
65
+ }
66
+
67
+ export interface ChaliceSettingsCollectEvent {
68
+ add(section: ChaliceSettingsSection): void;
69
+ }
70
+
71
+ export interface ChaliceBooleanSetting {
72
+ id: string;
73
+ type: "boolean";
74
+ key: string;
75
+ label: string;
76
+ description?: string;
77
+ defaultValue: boolean;
78
+ }
79
+
80
+ export interface ChaliceEnumSetting {
81
+ id: string;
82
+ type: "enum";
83
+ key: string;
84
+ label: string;
85
+ description?: string;
86
+ options: ReadonlyArray<{ value: string; label: string }>;
87
+ defaultValue: string;
88
+ }
89
+
90
+ export interface ChaliceStringSetting {
91
+ id: string;
92
+ type: "string";
93
+ key: string;
94
+ label: string;
95
+ description?: string;
96
+ defaultValue?: string;
97
+ placeholder?: string;
98
+ }
99
+
100
+ /**
101
+ * Setting whose storage lives outside the `chalice.*` namespace, such as a module's own config
102
+ * file. `get` must be synchronous because settings rows render in a single frame; `set` may be
103
+ * asynchronous and returns an error message to reject the change.
104
+ */
105
+ export interface ChaliceCustomSetting {
106
+ id: string;
107
+ type: "custom";
108
+ label: string;
109
+ description?: string;
110
+ /** "input" opens a text field, "select" picks one of `values`. */
111
+ edit: "input" | "select";
112
+ values?: readonly string[];
113
+ placeholder?: string;
114
+ get(ctx: ExtensionContext): string;
115
+ set(ctx: ExtensionContext, pi: ExtensionAPI, display: string): string | undefined | Promise<string | undefined>;
116
+ }
117
+
118
+ export type ChaliceSettingItem =
119
+ | ChaliceBooleanSetting
120
+ | ChaliceEnumSetting
121
+ | ChaliceStringSetting
122
+ | ChaliceCustomSetting;
123
+
124
+ export interface ChaliceSettingsSection {
125
+ id: string;
126
+ title: string;
127
+ description?: string;
128
+ /** Lower numbers appear first. Sections without an order sort by title. */
129
+ order?: number;
130
+ items: readonly ChaliceSettingItem[];
131
+ }
132
+
133
+ export const STATUS_LINE_SEGMENTS = [
134
+ "mode",
135
+ "cwd",
136
+ "branch",
137
+ "model",
138
+ "cost",
139
+ "context",
140
+ "contextWindow",
141
+ "index",
142
+ ] as const;
143
+
144
+ export type StatusLineSegmentKey = (typeof STATUS_LINE_SEGMENTS)[number];
145
+
146
+ const DEFAULT_SEGMENTS: Record<StatusLineSegmentKey, boolean> = {
147
+ mode: true,
148
+ cwd: true,
149
+ branch: true,
150
+ model: true,
151
+ cost: true,
152
+ context: true,
153
+ contextWindow: true,
154
+ index: true,
155
+ };
156
+
157
+ export const CHALICE_DEFAULTS: ResolvedChaliceSettings = {
158
+ username: undefined,
159
+ usernameEnabled: true,
160
+ headerBanner: "full",
161
+ logoColor: "gradient",
162
+ logoType: "square",
163
+ memorySaving: true,
164
+ conversationSearch: true,
165
+ statusLine: {
166
+ enabled: true,
167
+ layout: "left",
168
+ segments: { ...DEFAULT_SEGMENTS },
169
+ defaultFooter: false,
170
+ },
171
+ };
172
+
173
+ const LEGACY_STATUS_LINE_FILE = "chalice-settings.json";
174
+
175
+ function isRecord(value: unknown): value is Record<string, unknown> {
176
+ return typeof value === "object" && value !== null && !Array.isArray(value);
177
+ }
178
+
179
+ function stringValue(value: unknown): string | undefined {
180
+ return typeof value === "string" ? value : undefined;
181
+ }
182
+
183
+ function booleanValue(value: unknown, fallback: boolean): boolean {
184
+ return typeof value === "boolean" ? value : fallback;
185
+ }
186
+
187
+ function normalizeBanner(value: unknown): HeaderBannerMode {
188
+ return value === "full" || value === "simple" || value === "compact" || value === "none"
189
+ ? value
190
+ : CHALICE_DEFAULTS.headerBanner;
191
+ }
192
+
193
+ function normalizeLogoColor(value: unknown): LogoColorMode {
194
+ return value === "gradient" || value === "accent" || value === "white" || value === "pi"
195
+ ? value
196
+ : CHALICE_DEFAULTS.logoColor;
197
+ }
198
+
199
+ function normalizeLogoType(value: unknown): LogoTypeMode {
200
+ return value === "square" || value === "pi" ? value : CHALICE_DEFAULTS.logoType;
201
+ }
202
+
203
+ function normalizeLayout(value: unknown): StatusLineLayout {
204
+ if (value === "middle") return "center";
205
+ return value === "left" || value === "center" || value === "right" ? value : CHALICE_DEFAULTS.statusLine.layout;
206
+ }
207
+
208
+ function normalizeSegments(value: unknown): Record<string, boolean> {
209
+ const segments: Record<string, boolean> = { ...DEFAULT_SEGMENTS };
210
+ if (!isRecord(value)) return segments;
211
+ for (const key of STATUS_LINE_SEGMENTS) {
212
+ const entry = value[key];
213
+ if (typeof entry === "boolean") segments[key] = entry;
214
+ }
215
+ return segments;
216
+ }
217
+
218
+ /** Read the pre-namespace StatusLine settings file, if it exists. */
219
+ function readLegacyStatusLine(): Record<string, unknown> | undefined {
220
+ try {
221
+ const parsed: unknown = JSON.parse(readFileSync(join(getAgentDir(), LEGACY_STATUS_LINE_FILE), "utf8"));
222
+ if (!isRecord(parsed)) return undefined;
223
+ return isRecord(parsed.statusLine) ? parsed.statusLine : undefined;
224
+ } catch {
225
+ return undefined;
226
+ }
227
+ }
228
+
229
+ /** Map the fork's `ribbon` settings onto the distro status line shape. */
230
+ function ribbonToStatusLine(value: unknown): Record<string, unknown> | undefined {
231
+ if (!isRecord(value)) return undefined;
232
+ const segments: Record<string, boolean> = {};
233
+ const map: Array<[string, string]> = [
234
+ ["mode", "mode"],
235
+ ["directory", "cwd"],
236
+ ["branch", "branch"],
237
+ ["model", "model"],
238
+ ["cost", "cost"],
239
+ ["contextPercent", "context"],
240
+ ["contextWindow", "contextWindow"],
241
+ ];
242
+ for (const [from, to] of map) {
243
+ const entry = value[from];
244
+ if (typeof entry === "boolean") segments[to] = entry;
245
+ }
246
+ return {
247
+ enabled: true,
248
+ layout: value.layout,
249
+ segments,
250
+ defaultFooter: false,
251
+ };
252
+ }
253
+
254
+ /** Merge the `chalice` namespace with legacy top-level keys and the old StatusLine file. */
255
+ export function resolveChaliceSettings(settings: Record<string, unknown>): ResolvedChaliceSettings {
256
+ const raw = isRecord(settings.chalice) ? settings.chalice : {};
257
+ const ribbonStatusLine = ribbonToStatusLine(settings.ribbon);
258
+ const legacyStatusLine = readLegacyStatusLine();
259
+ const currentStatusLine = isRecord(raw.statusLine) ? raw.statusLine : {};
260
+ const statusLineRaw = { ...(ribbonStatusLine ?? {}), ...(legacyStatusLine ?? {}), ...currentStatusLine };
261
+ const mergedSegments = {
262
+ ...(isRecord(ribbonStatusLine?.segments) ? ribbonStatusLine.segments : {}),
263
+ ...(isRecord(legacyStatusLine?.segments) ? legacyStatusLine.segments : {}),
264
+ ...(isRecord(currentStatusLine.segments) ? currentStatusLine.segments : {}),
265
+ };
266
+
267
+ return {
268
+ username: stringValue(raw.username) ?? stringValue(settings.username),
269
+ usernameEnabled: booleanValue(
270
+ raw.usernameEnabled,
271
+ booleanValue(settings.usernameEnabled, CHALICE_DEFAULTS.usernameEnabled),
272
+ ),
273
+ headerBanner: normalizeBanner(raw.headerBanner ?? settings.headerBanner),
274
+ logoColor: normalizeLogoColor(raw.logoColor ?? settings.logoColor),
275
+ logoType: normalizeLogoType(raw.logoType ?? settings.logoType),
276
+ memorySaving: booleanValue(
277
+ raw.memorySaving,
278
+ booleanValue(settings.chaliceMemorySaving, CHALICE_DEFAULTS.memorySaving),
279
+ ),
280
+ conversationSearch: booleanValue(
281
+ raw.conversationSearch,
282
+ booleanValue(settings.chaliceConversationSearch, CHALICE_DEFAULTS.conversationSearch),
283
+ ),
284
+ statusLine: {
285
+ enabled: booleanValue(statusLineRaw.enabled, CHALICE_DEFAULTS.statusLine.enabled),
286
+ layout: normalizeLayout(statusLineRaw.layout),
287
+ segments: normalizeSegments(mergedSegments),
288
+ defaultFooter: booleanValue(statusLineRaw.defaultFooter, CHALICE_DEFAULTS.statusLine.defaultFooter),
289
+ },
290
+ };
291
+ }
292
+
293
+ /** Effective Chalice settings (global + trusted project), with defaults applied. */
294
+ export function readChaliceSettings(ctx: ExtensionContext): ResolvedChaliceSettings {
295
+ const settings = SettingsManager.create(ctx.cwd, getAgentDir(), {
296
+ projectTrusted: ctx.isProjectTrusted(),
297
+ }).getSettings() as Record<string, unknown>;
298
+ return resolveChaliceSettings(settings);
299
+ }
300
+
301
+ function getAtPath(value: unknown, path: string): unknown {
302
+ let current: unknown = value;
303
+ for (const part of path.split(".")) {
304
+ if (!isRecord(current)) return undefined;
305
+ current = current[part];
306
+ }
307
+ return current;
308
+ }
309
+
310
+ function patchAtPath(path: string, value: unknown): Record<string, unknown> {
311
+ const parts = path.split(".").filter((part) => part.length > 0);
312
+ const root: Record<string, unknown> = {};
313
+ let current = root;
314
+ for (const [index, part] of parts.entries()) {
315
+ if (index === parts.length - 1) {
316
+ current[part] = value;
317
+ } else {
318
+ const next: Record<string, unknown> = {};
319
+ current[part] = next;
320
+ current = next;
321
+ }
322
+ }
323
+ return root;
324
+ }
325
+
326
+ /** Read one dotted path under the `chalice` namespace, including legacy fallbacks for core keys. */
327
+ export function readChaliceSetting(ctx: ExtensionContext, path: string): unknown {
328
+ const settings = SettingsManager.create(ctx.cwd, getAgentDir(), {
329
+ projectTrusted: ctx.isProjectTrusted(),
330
+ }).getSettings() as Record<string, unknown>;
331
+ const raw = isRecord(settings.chalice) ? settings.chalice : {};
332
+ const direct = getAtPath(raw, path);
333
+ if (direct !== undefined) return direct;
334
+ return getAtPath(resolveChaliceSettings(settings) as unknown as Record<string, unknown>, path);
335
+ }
336
+
337
+ /** Register a settings section. No-op when the `/chalicesettings` UI is not installed. */
338
+ export function registerChaliceSettingsSection(pi: ExtensionAPI, section: ChaliceSettingsSection): void {
339
+ pi.events.on(CHALICE_SETTINGS_COLLECT_EVENT, (event) => {
340
+ if (!isRecord(event) || typeof event.add !== "function") return;
341
+ (event.add as (section: ChaliceSettingsSection) => void)(section);
342
+ });
343
+ }
344
+
345
+ /** Collect registered sections for the `/chalicesettings` UI. */
346
+ export function collectChaliceSettingsSections(pi: ExtensionAPI): ChaliceSettingsSection[] {
347
+ const sections: ChaliceSettingsSection[] = [];
348
+ pi.events.emit(CHALICE_SETTINGS_COLLECT_EVENT, {
349
+ add: (section: ChaliceSettingsSection) => sections.push(section),
350
+ } satisfies ChaliceSettingsCollectEvent);
351
+ const seen = new Set<string>();
352
+ return sections
353
+ .filter((section) => {
354
+ if (seen.has(section.id)) return false;
355
+ seen.add(section.id);
356
+ return true;
357
+ })
358
+ .sort((left, right) => (left.order ?? 0) - (right.order ?? 0) || left.title.localeCompare(right.title));
359
+ }
360
+
361
+ export function getUsername(settings: ResolvedChaliceSettings): string | undefined {
362
+ const username = settings.username;
363
+ return typeof username === "string" && username.trim() !== "" ? username.trim() : undefined;
364
+ }
365
+
366
+ export function isUsernameEnabled(settings: ResolvedChaliceSettings): boolean {
367
+ return settings.usernameEnabled;
368
+ }
369
+
370
+ export function globalSettingsPath(): string {
371
+ return join(getAgentDir(), "settings.json");
372
+ }
373
+
374
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
375
+
376
+ function sleepSync(ms: number): void {
377
+ Atomics.wait(sleeper, 0, 0, ms);
378
+ }
379
+
380
+ /**
381
+ * Lock compatible with Pi's settings storage (proper-lockfile creates a
382
+ * `<path>.lock` directory, which this replicates), so a write here cannot
383
+ * interleave with a concurrent Pi settings save.
384
+ */
385
+ function acquireLock(lockPath: string): void {
386
+ for (let attempt = 0; attempt < 100; attempt += 1) {
387
+ try {
388
+ mkdirSync(lockPath);
389
+ return;
390
+ } catch (error) {
391
+ const code = (error as NodeJS.ErrnoException).code;
392
+ if (code !== "EEXIST") throw error;
393
+ sleepSync(20);
394
+ }
395
+ }
396
+ throw new Error(`Timed out waiting for settings lock: ${lockPath}`);
397
+ }
398
+
399
+ function readSettingsFile(path: string): Record<string, unknown> {
400
+ let raw: string;
401
+ try {
402
+ raw = readFileSync(path, "utf8");
403
+ } catch (error) {
404
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
405
+ throw error;
406
+ }
407
+ let parsed: unknown;
408
+ try {
409
+ parsed = JSON.parse(raw);
410
+ } catch (error) {
411
+ const message = error instanceof Error ? error.message : String(error);
412
+ throw new Error(`Cannot update ${path}: invalid JSON (${message})`);
413
+ }
414
+ if (!isRecord(parsed)) throw new Error(`Cannot update ${path}: expected a JSON object`);
415
+ return parsed;
416
+ }
417
+
418
+ /** Recursively apply a patch. `undefined` deletes the key; plain objects merge. */
419
+ function applyPatch(target: Record<string, unknown>, patch: Record<string, unknown>): void {
420
+ for (const [key, value] of Object.entries(patch)) {
421
+ if (value === undefined) {
422
+ delete target[key];
423
+ continue;
424
+ }
425
+ const existing = target[key];
426
+ if (isRecord(value) && isRecord(existing)) {
427
+ applyPatch(existing, value);
428
+ } else {
429
+ target[key] = value;
430
+ }
431
+ }
432
+ }
433
+
434
+ const LEGACY_TOP_LEVEL_KEYS: Record<string, string> = {
435
+ username: "username",
436
+ usernameEnabled: "usernameEnabled",
437
+ headerBanner: "headerBanner",
438
+ logoColor: "logoColor",
439
+ logoType: "logoType",
440
+ memorySaving: "chaliceMemorySaving",
441
+ conversationSearch: "chaliceConversationSearch",
442
+ };
443
+
444
+ /**
445
+ * Write Chalice settings into the global `settings.json` under `chalice`, preserving every other
446
+ * key. Pi's SettingsManager reads unknown keys and only rewrites fields it modified, so this stays
447
+ * compatible with Pi's own saves.
448
+ */
449
+ function writeChaliceSettings(pi: ExtensionAPI, patch: Record<string, unknown>): ResolvedChaliceSettings {
450
+ const path = globalSettingsPath();
451
+ if (!existsSync(dirname(path))) mkdirSync(dirname(path), { recursive: true });
452
+
453
+ const lockPath = `${path}.lock`;
454
+ acquireLock(lockPath);
455
+ let resolved: ResolvedChaliceSettings;
456
+ try {
457
+ const current = readSettingsFile(path);
458
+ const existing = isRecord(current.chalice) ? current.chalice : {};
459
+ applyPatch(existing, patch);
460
+ current.chalice = existing;
461
+ // The new namespace wins from now on; drop the legacy key so deleting a value does not
462
+ // resurrect the old one.
463
+ for (const key of Object.keys(patch)) {
464
+ const legacy = LEGACY_TOP_LEVEL_KEYS[key];
465
+ if (legacy) delete current[legacy];
466
+ }
467
+ writeFileSync(path, `${JSON.stringify(current, null, 2)}\n`, "utf8");
468
+ resolved = resolveChaliceSettings(current);
469
+ } finally {
470
+ try {
471
+ rmSync(lockPath, { recursive: true, force: true });
472
+ } catch {
473
+ // Lock cleanup is best-effort; a stale lock only delays the next write.
474
+ }
475
+ }
476
+ // Emit after releasing the lock: listeners re-read settings and would otherwise deadlock.
477
+ pi.events.emit(CHALICE_SETTINGS_EVENT, { settings: resolved, patch } satisfies ChaliceSettingsChangedEvent);
478
+ return resolved;
479
+ }
480
+
481
+ /** Merge a typed patch into `chalice.*` and persist it. */
482
+ export function updateChaliceSettings(pi: ExtensionAPI, patch: ChaliceSettings): ResolvedChaliceSettings {
483
+ return writeChaliceSettings(pi, patch as unknown as Record<string, unknown>);
484
+ }
485
+
486
+ /** Write one dotted path under `chalice.*`. Pass `undefined` to delete the key. */
487
+ export function updateChaliceSetting(pi: ExtensionAPI, path: string, value: unknown): ResolvedChaliceSettings {
488
+ return writeChaliceSettings(pi, patchAtPath(path, value));
489
+ }