docks-kit 0.21.0 → 0.22.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.
@@ -0,0 +1,464 @@
1
+ import { Effect, Terminal } from "effect";
2
+ import { Prompt } from "effect/unstable/cli";
3
+ import { terminalCells, terminalRows } from "./terminalCells";
4
+
5
+ /** One row of a checklist. The label and the description are each one line of text. */
6
+ export interface ChecklistItem<A> {
7
+ readonly value: A;
8
+ readonly label: string;
9
+ readonly description: string;
10
+ readonly checked: boolean;
11
+ }
12
+
13
+ export interface ChecklistOptions<A> {
14
+ /** The text in the top border of the panel. */
15
+ readonly title: string;
16
+ readonly message: string;
17
+ /** A dimmed text under the message. */
18
+ readonly note?: string;
19
+ readonly items: ReadonlyArray<ChecklistItem<A>>;
20
+ /** The text on the Save row after a save with no ticked item. */
21
+ readonly emptySelectionError: string;
22
+ }
23
+
24
+ /** `Saved` lists the ticked values in item order. */
25
+ export type ChecklistResult<A> =
26
+ | { readonly _tag: "Saved"; readonly values: ReadonlyArray<A> }
27
+ | { readonly _tag: "Cancelled" };
28
+
29
+ interface ChecklistState {
30
+ /** An item index, or the item count for the Save row. */
31
+ readonly cursor: number;
32
+ readonly checked: ReadonlyArray<boolean>;
33
+ /** A save with no ticked item sets it; the next toggle clears it. */
34
+ readonly showError: boolean;
35
+ }
36
+
37
+ type ChecklistAction<A> = Prompt.Action<ChecklistState, ChecklistResult<A>>;
38
+
39
+ type Style = "plain" | "bold" | "dim" | "accent" | "accentBold" | "green" | "red";
40
+
41
+ interface Span {
42
+ readonly text: string;
43
+ readonly style: Style;
44
+ }
45
+
46
+ type Line = ReadonlyArray<Span>;
47
+
48
+ interface Glyphs {
49
+ readonly pointer: string;
50
+ readonly ticked: string;
51
+ readonly unticked: string;
52
+ readonly ellipsis: string;
53
+ readonly topLeft: string;
54
+ readonly topRight: string;
55
+ readonly bottomLeft: string;
56
+ readonly bottomRight: string;
57
+ readonly horizontal: string;
58
+ readonly vertical: string;
59
+ readonly hint: ReadonlyArray<string>;
60
+ readonly hintSeparator: string;
61
+ }
62
+
63
+ const UNICODE: Glyphs = {
64
+ pointer: "❯",
65
+ ticked: "●",
66
+ unticked: "○",
67
+ ellipsis: "…",
68
+ topLeft: "╭",
69
+ topRight: "╮",
70
+ bottomLeft: "╰",
71
+ bottomRight: "╯",
72
+ horizontal: "─",
73
+ vertical: "│",
74
+ hint: ["↑↓ move", "enter/space toggle", "enter on Save saves", "esc cancel"],
75
+ hintSeparator: " · ",
76
+ };
77
+
78
+ // The legacy Windows console can show the Unicode glyphs as boxes.
79
+ const ASCII: Glyphs = {
80
+ pointer: ">",
81
+ ticked: "[x]",
82
+ unticked: "[ ]",
83
+ ellipsis: "...",
84
+ topLeft: "+",
85
+ topRight: "+",
86
+ bottomLeft: "+",
87
+ bottomRight: "+",
88
+ horizontal: "-",
89
+ vertical: "|",
90
+ hint: ["up/down move", "enter/space toggle", "enter on Save saves", "esc cancel"],
91
+ hintSeparator: " - ",
92
+ };
93
+
94
+ const SGR: Record<Style, string> = {
95
+ plain: "",
96
+ bold: "\u001b[1m",
97
+ dim: "\u001b[2m",
98
+ accent: "\u001b[36m",
99
+ accentBold: "\u001b[1;36m",
100
+ green: "\u001b[32m",
101
+ red: "\u001b[31m",
102
+ };
103
+ const SGR_RESET = "\u001b[0m";
104
+ const CURSOR_HIDE = "\u001b[?25l";
105
+ const ERASE_LINE = "\u001b[2K";
106
+ const CURSOR_UP = "\u001b[1A";
107
+ const CURSOR_COLUMN_ONE = "\u001b[G";
108
+
109
+ /** A terminal that reports 0 columns does not know its width. */
110
+ const DEFAULT_COLUMNS = 80;
111
+ /** Below this width, the border takes too much of each line. */
112
+ const BORDER_MIN_COLUMNS = 40;
113
+ /** The columns of "│ " and " │" around the panel content. */
114
+ const BORDER_COLUMNS = 4;
115
+ /** The hint starts in the column of the panel content. */
116
+ const BORDERED_HINT_INDENT = 2;
117
+ const GAP = " ";
118
+ const SAVE_LABEL = "Save";
119
+
120
+ const CANCELLED = { _tag: "Submit", value: { _tag: "Cancelled" } } as const;
121
+ const IGNORED = { _tag: "Beep" } as const;
122
+
123
+ /**
124
+ * A checklist in a panel. Enter or Space toggles the item under the cursor and
125
+ * saves on the Save row; Escape, Ctrl+C, and Ctrl+D cancel.
126
+ */
127
+ export function checklistPrompt<A>(
128
+ options: ChecklistOptions<A>,
129
+ ): Prompt.Prompt<ChecklistResult<A>> {
130
+ const initial: ChecklistState = {
131
+ cursor: 0,
132
+ checked: options.items.map((item) => item.checked),
133
+ showError: false,
134
+ };
135
+ // The ANSI-free text of the lines on screen. `clear` erases these lines and
136
+ // not a frame that it builds again: the terminal width can change between
137
+ // the two calls, and then a new frame has a different number of lines. The
138
+ // first frame of a run always comes from `render`, so a reused prompt starts
139
+ // clean.
140
+ let shown: ReadonlyArray<string> = [];
141
+ return Prompt.Custom<ChecklistState, ChecklistResult<A>>(initial, {
142
+ render: (state, action) => {
143
+ // Beep shows no bell and no change. Submit leaves the panel erased, so
144
+ // the caller prints the result in its place.
145
+ if (action._tag !== "NextFrame") return Effect.succeed("");
146
+ // https://no-color.org: a NO_COLOR value that is set and not empty turns color off.
147
+ const color = (process.env.NO_COLOR ?? "") === "";
148
+ return Effect.map(frameOf(options, state), (frame) => {
149
+ shown = frame.map((line) => line.map((part) => part.text).join(""));
150
+ const lines = frame.map((line) => paint(line, color));
151
+ return CURSOR_HIDE + lines.join("\n");
152
+ });
153
+ },
154
+ process: (input, state) => Effect.succeed(nextAction(options.items, input.key, state)),
155
+ clear: () =>
156
+ Effect.gen(function* () {
157
+ const terminal = yield* Terminal.Terminal;
158
+ const reported = yield* terminal.columns;
159
+ const columns = reported > 0 ? reported : DEFAULT_COLUMNS;
160
+ // A terminal that reflows wraps a long line into more rows when it
161
+ // narrows. It never splits a character: a wide character that does not
162
+ // fit in the rest of a row moves to the next row.
163
+ const rows = shown.reduce((sum, line) => sum + terminalRows(line, columns), 0);
164
+ // The cursor stays on the last row of the frame: erase each row from
165
+ // there up to the first row.
166
+ const above = `${CURSOR_UP}${ERASE_LINE}`.repeat(Math.max(0, rows - 1));
167
+ return `${ERASE_LINE}${above}${CURSOR_COLUMN_ONE}`;
168
+ }),
169
+ });
170
+ }
171
+
172
+ function nextAction<A>(
173
+ items: ReadonlyArray<ChecklistItem<A>>,
174
+ key: Terminal.Key,
175
+ state: ChecklistState,
176
+ ): ChecklistAction<A> {
177
+ const saveRow = items.length;
178
+ const rows = saveRow + 1;
179
+ // The cursor wraps over the items and the Save row.
180
+ const moveBy = (step: number): ChecklistAction<A> => ({
181
+ _tag: "NextFrame",
182
+ state: { ...state, cursor: (state.cursor + step + rows) % rows },
183
+ });
184
+ switch (key.name) {
185
+ case "up":
186
+ case "k":
187
+ return moveBy(-1);
188
+ case "down":
189
+ case "j":
190
+ return moveBy(1);
191
+ case "tab":
192
+ return moveBy(key.shift ? -1 : 1);
193
+ case "home":
194
+ return { _tag: "NextFrame", state: { ...state, cursor: 0 } };
195
+ case "end":
196
+ return { _tag: "NextFrame", state: { ...state, cursor: saveRow } };
197
+ case "return":
198
+ case "enter":
199
+ case "space": {
200
+ if (state.cursor === saveRow) return save(items, state);
201
+ const checked = state.checked.map((on, row) => (row === state.cursor ? !on : on));
202
+ return { _tag: "NextFrame", state: { ...state, checked, showError: false } };
203
+ }
204
+ case "escape":
205
+ return CANCELLED;
206
+ // Ctrl+C and Ctrl+D also end the terminal input: they must give a result
207
+ // here, or the prompt fails with a QuitError.
208
+ case "c":
209
+ case "d":
210
+ return key.ctrl ? CANCELLED : IGNORED;
211
+ default:
212
+ return IGNORED;
213
+ }
214
+ }
215
+
216
+ function save<A>(
217
+ items: ReadonlyArray<ChecklistItem<A>>,
218
+ state: ChecklistState,
219
+ ): ChecklistAction<A> {
220
+ const values = items.filter((_item, index) => state.checked[index]).map((item) => item.value);
221
+ return values.length === 0
222
+ ? { _tag: "NextFrame", state: { ...state, showError: true } }
223
+ : { _tag: "Submit", value: { _tag: "Saved", values } };
224
+ }
225
+
226
+ // Read the host when the prompt renders, so that the values in effect at that
227
+ // time apply.
228
+ function frameOf<A>(options: ChecklistOptions<A>, state: ChecklistState) {
229
+ return Effect.gen(function* () {
230
+ const terminal = yield* Terminal.Terminal;
231
+ const columns = yield* terminal.columns;
232
+ // Windows Terminal sets WT_SESSION and shows the Unicode glyphs.
233
+ const glyphs =
234
+ process.platform === "win32" && (process.env.WT_SESSION ?? "") === "" ? ASCII : UNICODE;
235
+ return frameLines(options, state, columns, glyphs);
236
+ });
237
+ }
238
+
239
+ function paint(line: Line, color: boolean): string {
240
+ let text = "";
241
+ for (const part of line) {
242
+ const code = color ? SGR[part.style] : "";
243
+ text += code === "" ? part.text : `${code}${part.text}${SGR_RESET}`;
244
+ }
245
+ return text;
246
+ }
247
+
248
+ interface Layout {
249
+ /** The most columns that one line can use. */
250
+ readonly width: number;
251
+ readonly bordered: boolean;
252
+ /** The columns of the panel content. */
253
+ readonly inner: number;
254
+ /** The columns of the marker, the label, and their padding, or of the Save label. */
255
+ readonly nameWidth: number;
256
+ /** The column where the descriptions and the Save status start. */
257
+ readonly statusColumn: number;
258
+ }
259
+
260
+ function measure<A>(options: ChecklistOptions<A>, columns: number, glyphs: Glyphs): Layout {
261
+ const known = columns > 0 ? columns : DEFAULT_COLUMNS;
262
+ // A line that fills the last column can wrap, and then `clear` erases too
263
+ // few lines.
264
+ const width = known - 1;
265
+ const bordered = known >= BORDER_MIN_COLUMNS;
266
+ const total = options.items.length;
267
+ const markerWidth = Math.max(terminalCells(glyphs.ticked), terminalCells(glyphs.unticked));
268
+ const labelWidth = Math.max(0, ...options.items.map((item) => terminalCells(item.label)));
269
+ const nameWidth = Math.max(markerWidth + 1 + labelWidth, terminalCells(SAVE_LABEL));
270
+ const statusColumn = terminalCells(glyphs.pointer) + 1 + nameWidth + GAP.length;
271
+ // Size the panel for its widest content in all states, so that its width
272
+ // stays the same when the error shows. The top border needs two columns
273
+ // more than the title.
274
+ const natural = Math.max(
275
+ terminalCells(options.title) + 2,
276
+ terminalCells(options.message),
277
+ terminalCells(options.note ?? ""),
278
+ ...options.items.map((item) => statusColumn + terminalCells(item.description)),
279
+ statusColumn + terminalCells(`${total} of ${total} selected`),
280
+ statusColumn + terminalCells(options.emptySelectionError),
281
+ );
282
+ return {
283
+ width,
284
+ bordered,
285
+ inner: bordered ? Math.min(natural, width - BORDER_COLUMNS) : width,
286
+ nameWidth,
287
+ statusColumn,
288
+ };
289
+ }
290
+
291
+ function frameLines<A>(
292
+ options: ChecklistOptions<A>,
293
+ state: ChecklistState,
294
+ columns: number,
295
+ glyphs: Glyphs,
296
+ ): Array<Line> {
297
+ const layout = measure(options, columns, glyphs);
298
+ const note: Array<string> =
299
+ options.note === undefined ? [] : pack(words(options.note), " ", layout.inner);
300
+ const body: Array<Line> = [
301
+ ...pack(words(options.message), " ", layout.inner).map((text) => [span(text)]),
302
+ ...note.map((text) => [span(text, "dim")]),
303
+ [],
304
+ ...options.items.map((item, index) =>
305
+ itemRow(item, state.checked[index], state.cursor === index, layout, glyphs),
306
+ ),
307
+ [],
308
+ ...saveRows(options, state, layout, glyphs),
309
+ ];
310
+ const hintIndent = layout.bordered ? BORDERED_HINT_INDENT : 0;
311
+ const hint = pack(glyphs.hint, glyphs.hintSeparator, layout.width - hintIndent).map((text) =>
312
+ fit([span(" ".repeat(hintIndent)), span(text, "dim")], layout.width, glyphs.ellipsis),
313
+ );
314
+ if (!layout.bordered) {
315
+ return [
316
+ fit([span(options.title, "bold")], layout.width, glyphs.ellipsis),
317
+ ...body.map((line) => fit(line, layout.width, glyphs.ellipsis)),
318
+ [],
319
+ ...hint,
320
+ ];
321
+ }
322
+ return [
323
+ topBorder(options.title, layout.inner, glyphs),
324
+ ...body.map((line) => boxed(line, layout.inner, glyphs)),
325
+ [
326
+ span(
327
+ `${glyphs.bottomLeft}${glyphs.horizontal.repeat(layout.inner + 2)}${glyphs.bottomRight}`,
328
+ "dim",
329
+ ),
330
+ ],
331
+ ...hint,
332
+ ];
333
+ }
334
+
335
+ function itemRow<A>(
336
+ item: ChecklistItem<A>,
337
+ ticked: boolean,
338
+ current: boolean,
339
+ layout: Layout,
340
+ glyphs: Glyphs,
341
+ ): Line {
342
+ const marker = ticked ? span(glyphs.ticked, "green") : span(glyphs.unticked, "dim");
343
+ const padding = layout.nameWidth - terminalCells(marker.text) - 1 - terminalCells(item.label);
344
+ return [
345
+ current ? span(glyphs.pointer, "accent") : span(" ".repeat(terminalCells(glyphs.pointer))),
346
+ span(" "),
347
+ marker,
348
+ span(" "),
349
+ span(item.label, current ? "bold" : "plain"),
350
+ span(" ".repeat(padding) + GAP),
351
+ span(item.description, "dim"),
352
+ ];
353
+ }
354
+
355
+ function saveRows<A>(
356
+ options: ChecklistOptions<A>,
357
+ state: ChecklistState,
358
+ layout: Layout,
359
+ glyphs: Glyphs,
360
+ ): Array<Line> {
361
+ const current = state.cursor === options.items.length;
362
+ const count = state.checked.filter((ticked) => ticked).length;
363
+ const status = state.showError
364
+ ? span(options.emptySelectionError, "red")
365
+ : span(`${count} of ${options.items.length} selected`, "dim");
366
+ // Wrap the status below its start column, so that a long error stays readable.
367
+ const [first = "", ...rest] = pack(words(status.text), " ", layout.inner - layout.statusColumn);
368
+ return [
369
+ [
370
+ current ? span(glyphs.pointer, "accent") : span(" ".repeat(terminalCells(glyphs.pointer))),
371
+ span(" "),
372
+ span(SAVE_LABEL, current ? "accentBold" : "plain"),
373
+ span(" ".repeat(layout.nameWidth - terminalCells(SAVE_LABEL)) + GAP),
374
+ span(first, status.style),
375
+ ],
376
+ ...rest.map((text) => [span(" ".repeat(layout.statusColumn)), span(text, status.style)]),
377
+ ];
378
+ }
379
+
380
+ function topBorder(title: string, inner: number, glyphs: Glyphs): Line {
381
+ // Keep at least one horizontal glyph between the title and the corner.
382
+ const shown = fit([span(title, "bold")], inner - 2, glyphs.ellipsis);
383
+ const fill = inner - 1 - lineWidth(shown);
384
+ return [
385
+ span(`${glyphs.topLeft}${glyphs.horizontal} `, "dim"),
386
+ ...shown,
387
+ span(` ${glyphs.horizontal.repeat(fill)}${glyphs.topRight}`, "dim"),
388
+ ];
389
+ }
390
+
391
+ function boxed(line: Line, inner: number, glyphs: Glyphs): Line {
392
+ const content = fit(line, inner, glyphs.ellipsis);
393
+ return [
394
+ span(`${glyphs.vertical} `, "dim"),
395
+ ...content,
396
+ span(" ".repeat(inner - lineWidth(content))),
397
+ span(` ${glyphs.vertical}`, "dim"),
398
+ ];
399
+ }
400
+
401
+ function span(text: string, style: Style = "plain"): Span {
402
+ return { text, style };
403
+ }
404
+
405
+ /** The longest start of `text` that uses at most `cells` cells. */
406
+ function cutCells(text: string, cells: number): string {
407
+ let kept = "";
408
+ let used = 0;
409
+ for (const char of text) {
410
+ const next = used + terminalCells(char);
411
+ // A wide character that does not fit stops the cut: it never crosses the width.
412
+ if (next > cells) break;
413
+ kept += char;
414
+ used = next;
415
+ }
416
+ return kept;
417
+ }
418
+
419
+ function lineWidth(line: Line): number {
420
+ return line.reduce((sum, part) => sum + terminalCells(part.text), 0);
421
+ }
422
+
423
+ /** Cuts `line` to `width` cells and ends a cut line with the ellipsis. */
424
+ function fit(line: Line, width: number, ellipsis: string): Line {
425
+ if (lineWidth(line) <= width) return line;
426
+ const room = width - terminalCells(ellipsis);
427
+ if (room < 0) return [span(cutCells(ellipsis, Math.max(width, 0)))];
428
+ const kept: Array<Span> = [];
429
+ let used = 0;
430
+ for (const part of line) {
431
+ const cells = terminalCells(part.text);
432
+ if (used + cells > room) {
433
+ kept.push(span(cutCells(part.text, room - used).trimEnd() + ellipsis, part.style));
434
+ break;
435
+ }
436
+ kept.push(part);
437
+ used += cells;
438
+ }
439
+ return kept;
440
+ }
441
+
442
+ function words(text: string): Array<string> {
443
+ return text.split(/\s+/).filter((word) => word !== "");
444
+ }
445
+
446
+ /**
447
+ * Joins `parts` with `separator` into lines of at most `width` columns. A part
448
+ * never breaks; `fit` cuts a part that is wider than `width`.
449
+ */
450
+ function pack(parts: ReadonlyArray<string>, separator: string, width: number): Array<string> {
451
+ const lines: Array<string> = [];
452
+ let current = "";
453
+ for (const part of parts) {
454
+ const joined = current === "" ? part : `${current}${separator}${part}`;
455
+ if (current !== "" && terminalCells(joined) > width) {
456
+ lines.push(current);
457
+ current = part;
458
+ } else {
459
+ current = joined;
460
+ }
461
+ }
462
+ lines.push(current);
463
+ return lines;
464
+ }
@@ -39,7 +39,7 @@ const TOPICS: Record<string, { summary: string; body: string }> = {
39
39
  body: install,
40
40
  },
41
41
  platforms: {
42
- summary: "Platform support: Linux, macOS, and Windows on x64 and arm64",
42
+ summary: "Platform support: Linux on x64 and arm64, macOS on arm64, Windows on x64",
43
43
  body: platforms,
44
44
  },
45
45
  "omp-models": {
@@ -1,5 +1,6 @@
1
- import { Command, Prompt } from "effect/unstable/cli";
1
+ import { Command } from "effect/unstable/cli";
2
2
  import { Console, Effect } from "effect";
3
+ import { checklistPrompt } from "../checklistPrompt";
3
4
  import { bail } from "../engine";
4
5
  import {
5
6
  engineHome,
@@ -14,7 +15,7 @@ import { kitDbFile } from "../engine-native/kitDb";
14
15
  const DESCRIPTIONS: Record<Harness, string> = {
15
16
  claude: "Claude Code user configuration",
16
17
  codex: "Codex user configuration",
17
- agents: "universal agent skills",
18
+ agents: "Universal agent skills",
18
19
  omp: "Oh My Pi user configuration",
19
20
  };
20
21
 
@@ -39,32 +40,40 @@ export const harnessesCommand = Command.make("harnesses", {}, () =>
39
40
 
40
41
  if (!process.stdin.isTTY || !process.stdout.isTTY) return;
41
42
 
42
- const answer = yield* Prompt.MultiSelect({
43
- message: "Choose the harnesses for a flag-less docks-kit sync",
44
- choices: HARNESSES.map((harness) => ({
45
- title: harness,
43
+ const result = yield* checklistPrompt({
44
+ title: "Harnesses",
45
+ message: "Choose what a plain docks-kit sync sets up.",
46
+ note:
47
+ stored === undefined
48
+ ? "Every harness starts ticked. Nothing is stored until you save."
49
+ : undefined,
50
+ items: HARNESSES.map((harness) => ({
46
51
  value: harness,
52
+ label: harness,
47
53
  description: DESCRIPTIONS[harness],
48
54
  // With no stored selection, pre-tick every harness, omp included, so a
49
55
  // new machine opts out of omp instead of opting in. A flag-less sync
50
56
  // keeps LEGACY_SELECTION until this picker saves a selection.
51
- selected: (stored ?? HARNESSES).includes(harness),
57
+ checked: (stored ?? HARNESSES).includes(harness),
52
58
  })),
59
+ emptySelectionError: "Tick at least one harness.",
53
60
  });
54
61
 
55
- if (answer.length === 0) {
56
- return yield* bail("Select at least one harness. The stored selection was not changed.");
62
+ if (result._tag === "Cancelled") {
63
+ yield* Console.log("Harness selection unchanged.");
64
+ return;
57
65
  }
58
66
 
59
67
  yield* Effect.try({
60
- try: () => writeHarnessSelection(home, answer),
68
+ try: () => writeHarnessSelection(home, result.values),
61
69
  catch: (error) => (error instanceof Error ? error.message : String(error)),
62
70
  }).pipe(
63
71
  Effect.catch((reason) =>
64
72
  bail(`Cannot save the harness selection to ${kitDbFile(home)}: ${reason}`, 1),
65
73
  ),
66
74
  );
67
- yield* Console.log(`Saved harness selection: ${answer.join(", ")} (${kitDbFile(home)})`);
75
+ const saved = result.values.join(", ");
76
+ yield* Console.log(`Saved harness selection: ${saved} (${kitDbFile(home)})`);
68
77
  }),
69
78
  ).pipe(
70
79
  Command.withDescription("Choose the harness selection that drives a flag-less docks-kit sync."),