@lysyi3m/sidecar 0.0.0-stage → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +295 -2
  3. package/dist/bin/sidecar-dashboard.js +27 -0
  4. package/dist/bin/sidecar-mcp.js +35 -0
  5. package/dist/bin/sidecar.js +70 -0
  6. package/dist/src/adapters/claude-code.js +333 -0
  7. package/dist/src/adapters/claude-desktop.js +184 -0
  8. package/dist/src/adapters/codex.js +383 -0
  9. package/dist/src/adapters/index.js +38 -0
  10. package/dist/src/adapters/installed.js +25 -0
  11. package/dist/src/adapters/outcome.js +30 -0
  12. package/dist/src/adapters/registration.js +69 -0
  13. package/dist/src/adapters/types.js +1 -0
  14. package/dist/src/cases/events.js +9 -0
  15. package/dist/src/cases/items.js +120 -0
  16. package/dist/src/cases/lock.js +80 -0
  17. package/dist/src/cases/opinion.js +58 -0
  18. package/dist/src/cases/state.js +121 -0
  19. package/dist/src/cases/store.js +181 -0
  20. package/dist/src/cases/usage.js +36 -0
  21. package/dist/src/cli/deps.js +18 -0
  22. package/dist/src/cli/lines.js +11 -0
  23. package/dist/src/cli/list.js +44 -0
  24. package/dist/src/cli/setup.js +202 -0
  25. package/dist/src/cli/status.js +111 -0
  26. package/dist/src/cli/style.js +26 -0
  27. package/dist/src/cli/ui.js +170 -0
  28. package/dist/src/cli/uninstall.js +73 -0
  29. package/dist/src/config.js +108 -0
  30. package/dist/src/dashboard/cases.js +109 -0
  31. package/dist/src/dashboard/html.js +31 -0
  32. package/dist/src/dashboard/links.js +35 -0
  33. package/dist/src/dashboard/marks.js +16 -0
  34. package/dist/src/dashboard/pages.js +516 -0
  35. package/dist/src/dashboard/server.js +305 -0
  36. package/dist/src/dashboard/service.js +138 -0
  37. package/dist/src/dashboard/static/agents/NOTICE +32 -0
  38. package/dist/src/dashboard/static/agents/claude-code.svg +1 -0
  39. package/dist/src/dashboard/static/agents/claude-desktop.svg +1 -0
  40. package/dist/src/dashboard/static/agents/codex.svg +1 -0
  41. package/dist/src/dashboard/static/app.css +1121 -0
  42. package/dist/src/dashboard/static/app.js +256 -0
  43. package/dist/src/dashboard/static/times.js +44 -0
  44. package/dist/src/dashboard/view.js +25 -0
  45. package/dist/src/lib/agent-process.js +57 -0
  46. package/dist/src/lib/atomic-write.js +35 -0
  47. package/dist/src/lib/command.js +20 -0
  48. package/dist/src/lib/failpoint.js +14 -0
  49. package/dist/src/lib/git.js +14 -0
  50. package/dist/src/lib/json.js +2 -0
  51. package/dist/src/lib/paths.js +19 -0
  52. package/dist/src/lib/proc.js +80 -0
  53. package/dist/src/lib/version.js +43 -0
  54. package/dist/src/mcp/server.js +800 -0
  55. package/dist/src/mcp/stdio.js +31 -0
  56. package/dist/src/mcp/tools.js +180 -0
  57. package/dist/src/turns/dispatch.js +188 -0
  58. package/dist/src/turns/knobs.js +14 -0
  59. package/dist/src/turns/prompt.js +284 -0
  60. package/dist/src/turns/runner.js +283 -0
  61. package/package.json +44 -4
@@ -0,0 +1,202 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { isIP } from "node:net";
4
+ import { labelIn } from "../adapters/index.js";
5
+ import { register, serverFor } from "../adapters/registration.js";
6
+ import { checkSetting, configPath, loadConfig, saveConfig } from "../config.js";
7
+ import { dashboardLinks, isLoopbackHost } from "../dashboard/links.js";
8
+ import { withDefaults } from "./deps.js";
9
+ import { agentsLine, targetLine } from "./lines.js";
10
+ import { bold, dim, link, pad, red } from "./style.js";
11
+ const OTHER = "\u0000other";
12
+ const LOOPBACK = "127.0.0.1";
13
+ const ANY = "0.0.0.0";
14
+ /** Typed digits as a number; anything else, such as "0x10" or "1e3", as NaN, which no setting takes. */
15
+ const whole = (value) => (/^\d+$/.test(value.trim()) ? Number(value) : Number.NaN);
16
+ /** Checks typed text against a numeric setting's own rule. */
17
+ const checkNumber = (key) => (value) => checkSetting(key, whole(value));
18
+ /** IPv4-mapped in any spelling: URL gives the canonical form, as a browser writes it in Host. */
19
+ const mapped = (address) => isIP(address) === 6 && new URL(`http://[${address}]`).hostname.startsWith("[::ffff:");
20
+ /** A browser writes an IPv4-mapped address in another form than the bind, so the Host check would refuse it. */
21
+ const checkHost = (value) => (isIP(value.trim()) !== 0 && !mapped(value.trim())) || value.trim() === "localhost"
22
+ ? undefined
23
+ : "an IP address to bind, e.g. 127.0.0.1, 0.0.0.0 or one interface's address";
24
+ const checkToken = (value) => checkSetting("dashboardToken", value.trim());
25
+ /** host:port as a URL writes it. */
26
+ const address = (host, port) => `${isIP(host) === 6 ? `[${host}]` : host}:${port}`;
27
+ /**
28
+ * Resolves to whether every step succeeded: a failed registration or service step is reported, and
29
+ * setup goes on with the rest, then saves the config. With no agent installed, or when the user
30
+ * does not apply the choices, nothing changes.
31
+ */
32
+ export async function runSetup(deps) {
33
+ const { ui, home } = deps;
34
+ const { all, found, run, service } = withDefaults(deps);
35
+ const started = Date.now();
36
+ // No config yet means a first setup; after it, even a setup that registered nothing has one.
37
+ const firstSetup = !existsSync(configPath(home));
38
+ const current = loadConfig(home);
39
+ const config = { ...current, navigators: { ...current.navigators } };
40
+ ui.intro("sidecar setup");
41
+ const { navigators, drivers } = await ui.task("Checking agents", () => ({
42
+ navigators: all.filter((a) => a.navigator && found(a, a.navigator)),
43
+ drivers: all.filter((a) => a.driver && found(a, a.driver)),
44
+ }));
45
+ const installed = all.filter((a) => navigators.includes(a) || drivers.includes(a));
46
+ if (installed.length === 0) {
47
+ ui.section("Agents detected", [`none of ${all.map((a) => a.id).join(", ")} is installed`], true);
48
+ ui.outro(red("Nothing to set up"));
49
+ return false;
50
+ }
51
+ ui.section("Agents detected", [agentsLine(all, installed)]);
52
+ const targets = drivers.flatMap((adapter) => adapter.driver.targets().map((target) => ({
53
+ key: `${adapter.id}:${target.configDir ?? ""}`,
54
+ adapter,
55
+ target,
56
+ })));
57
+ // A re-run keeps the earlier choice: the targets that hold a registration, so `--yes` never
58
+ // registers a profile the user left out. A first setup preselects every target.
59
+ const held = targets.filter(({ adapter, target }) => ["current", "stale", "no-driver"].includes(adapter.driver.read(target, run, serverFor(adapter.id, home)).state));
60
+ let chosen = [];
61
+ if (targets.length) {
62
+ const fold = ui.fold("Register");
63
+ chosen = await ui.multiselect("Register the sidecar MCP server with", targets.map((t) => {
64
+ const [name, where] = t.target.label.split(" — ");
65
+ return { value: t.key, label: name, ...(where ? { hint: where } : {}) };
66
+ }), (firstSetup ? targets : held).map((t) => t.key));
67
+ fold.set(chosen.length
68
+ ? targets.filter((t) => chosen.includes(t.key)).map((t) => targetLine(t.target.label))
69
+ : [dim("nowhere")]);
70
+ fold.end();
71
+ }
72
+ // No default navigator: each case asks the user, with another agent than the driver preselected.
73
+ const navigatorLines = [];
74
+ const navigatorFold = ui.fold("Navigators");
75
+ for (const { id, labels, navigator } of navigators) {
76
+ const choices = deps.models ? deps.models(id) : navigator.models();
77
+ const previous = current.navigators[id] ?? {};
78
+ const known = choices.map((c) => c.model);
79
+ const initialModel = previous.model && !known.includes(previous.model)
80
+ ? OTHER
81
+ : (previous.model ?? known[0] ?? OTHER);
82
+ const modelLabel = (m) => labelIn(labels.models, m);
83
+ const effortLabel = (e) => labelIn(labels.efforts, e);
84
+ let model = await ui.select(`Default ${id} navigator model`, [
85
+ ...known.map((m) => ({
86
+ value: m,
87
+ ...(modelLabel(m) !== m ? { label: modelLabel(m), hint: m } : {}),
88
+ })),
89
+ { value: OTHER, label: "other…", hint: "type a model id" },
90
+ ], initialModel);
91
+ if (model === OTHER)
92
+ model = await ui.text(`Default ${id} navigator model id`, previous.model ?? "", (v) => v.trim() ? undefined : "a model id");
93
+ navigatorLines.push(pad(id, 16) + modelLabel(model));
94
+ navigatorFold.set(navigatorLines);
95
+ // An unlisted model has no known efforts: the saved one stays on offer, so `--yes` keeps it.
96
+ const efforts = choices.find((c) => c.model === model)?.efforts ?? (previous.effort ? [previous.effort] : []);
97
+ const effort = await ui.select(`Default ${id} navigator effort`, [
98
+ { value: "", label: "the CLI's default" },
99
+ ...efforts.map((e) => ({ value: e, label: effortLabel(e) })),
100
+ ], previous.effort && efforts.includes(previous.effort) ? previous.effort : "");
101
+ navigatorLines[navigatorLines.length - 1] +=
102
+ ` ${dim("·")} ${effort ? effortLabel(effort) : dim("CLI default")}`;
103
+ navigatorFold.set(navigatorLines);
104
+ config.navigators[id] = { model, ...(effort ? { effort } : {}) };
105
+ }
106
+ navigatorFold.end();
107
+ // How far the navigator goes to confirm how its points were settled (docs/design.md → Review).
108
+ const reviews = ui.fold("Review budget");
109
+ config.reviewBudget = whole(await ui.text("Max rounds before handover", String(current.reviewBudget), checkNumber("reviewBudget")));
110
+ reviews.set([`${config.reviewBudget} ${dim("max review rounds before handover")}`]);
111
+ reviews.end();
112
+ const dashboard = ui.fold("Dashboard");
113
+ const reach = await ui.select("Dashboard reachable from", [
114
+ { value: LOOPBACK, label: "this machine", hint: `${LOOPBACK} · no token` },
115
+ { value: ANY, label: "my network", hint: `${ANY} · token required` },
116
+ { value: OTHER, label: "one address…", hint: "type an IP address to bind" },
117
+ ],
118
+ // `--yes` keeps any other saved host: it is offered as the typed address.
119
+ current.dashboardHost === LOOPBACK || current.dashboardHost === ANY
120
+ ? current.dashboardHost
121
+ : OTHER);
122
+ config.dashboardHost =
123
+ reach === OTHER
124
+ ? (await ui.text("Dashboard host", current.dashboardHost, checkHost)).trim()
125
+ : reach;
126
+ dashboard.set([config.dashboardHost]);
127
+ config.dashboardPort = whole(await ui.text("Dashboard port", String(current.dashboardPort), (v) => checkNumber("dashboardPort")(v) ??
128
+ (whole(v) === config.lockPort ? "must not be the store lock port" : undefined)));
129
+ const reached = address(config.dashboardHost, config.dashboardPort);
130
+ dashboard.set([reached]);
131
+ // Loopback clients never need the token, so it is asked for only beyond loopback, where it is required.
132
+ if (isLoopbackHost(config.dashboardHost)) {
133
+ delete config.dashboardToken;
134
+ }
135
+ else {
136
+ const initial = current.dashboardToken ?? randomBytes(24).toString("base64url");
137
+ config.dashboardToken = (await ui.text("Dashboard access token", initial, checkToken)).trim();
138
+ }
139
+ dashboard.set([`${reached} ${dim(config.dashboardToken ? "· token" : "· this machine only")}`]);
140
+ dashboard.end();
141
+ // An empty fold: the answered prompt leaves nothing behind.
142
+ const apply = ui.fold("Apply");
143
+ const applying = await ui.confirm("Apply?", true);
144
+ apply.end();
145
+ if (!applying) {
146
+ ui.outro("Nothing was changed.");
147
+ return true;
148
+ }
149
+ let ok = true;
150
+ const applied = [];
151
+ const registered = new Set();
152
+ // The results print on every way out: a config that cannot be saved still shows the steps before it.
153
+ let finished = false;
154
+ try {
155
+ await ui.task("Applying", () => {
156
+ for (const { adapter, target } of targets.filter((t) => chosen.includes(t.key))) {
157
+ try {
158
+ register(adapter.driver, target, serverFor(adapter.id, home), run);
159
+ registered.add(adapter);
160
+ }
161
+ catch (err) {
162
+ ok = false;
163
+ applied.push(red(`✗ ${target.label}: ${err.message}`));
164
+ }
165
+ }
166
+ try {
167
+ saveConfig(config, home);
168
+ }
169
+ catch (err) {
170
+ // Shown in the section too; rethrown, since nothing after it can run on an unsaved config.
171
+ applied.push(red(`✗ config: ${err.message}`));
172
+ throw err;
173
+ }
174
+ applied.push(`${dim("✓")} ${pad("config", 12)}${dim(configPath(home))}`);
175
+ });
176
+ // After saving: the service reads its settings from config.json when it starts.
177
+ try {
178
+ await ui.task("Installing the dashboard service", () => service.install());
179
+ const links = dashboardLinks(config.dashboardPort, config.dashboardHost, config.dashboardToken);
180
+ applied.push(...links.map((url, i) => `${i === 0 ? `${dim("✓")} ${pad("dashboard", 12)}` : pad("", 14)}${link(url)}`));
181
+ }
182
+ catch (err) {
183
+ ok = false;
184
+ applied.push(red(`✗ dashboard service: ${err.message}`));
185
+ }
186
+ finished = true;
187
+ }
188
+ finally {
189
+ ui.section("Applied", applied, !ok || !finished, true);
190
+ }
191
+ // A tip follows a registration that happened: after a refusal, it would contradict the error.
192
+ const steps = [...registered].flatMap((adapter) => adapter.driver.tip ?? []);
193
+ if (config.dashboardToken)
194
+ steps.push(`A host firewall may still block port ${config.dashboardPort}`);
195
+ if (steps.length)
196
+ ui.steps(steps);
197
+ const seconds = ((Date.now() - started) / 1000).toFixed(1);
198
+ ui.outro(ok
199
+ ? `${bold("Done")} ${dim(`in ${seconds}s`)}`
200
+ : `${red("Setup incomplete")} ${dim("· re-run setup to retry")}`);
201
+ return ok;
202
+ }
@@ -0,0 +1,111 @@
1
+ import { existsSync } from "node:fs";
2
+ import { serverFor } from "../adapters/registration.js";
3
+ import { caseStatus, fold } from "../cases/state.js";
4
+ import { Store } from "../cases/store.js";
5
+ import { configPath, DEFAULTS, loadConfig } from "../config.js";
6
+ import { dashboardLinks } from "../dashboard/links.js";
7
+ import { withDefaults } from "./deps.js";
8
+ import { agentsLine, targetLine } from "./lines.js";
9
+ import { bold, dim, link, red } from "./style.js";
10
+ // `sidecar status`: what is installed and whether it still works. It changes nothing.
11
+ // `sidecar setup` repairs a stale registration or service.
12
+ /** Resolves to whether everything is in order. */
13
+ export async function runStatus(deps) {
14
+ const { ui, home } = deps;
15
+ const { all, found, run, service } = withDefaults(deps);
16
+ let healthy = true;
17
+ /** A section's lines and whether one of them is a problem. */
18
+ const section = () => {
19
+ const lines = [];
20
+ let failed = false;
21
+ return {
22
+ lines,
23
+ ok: (line) => lines.push(line),
24
+ problem: (line) => {
25
+ failed = true;
26
+ healthy = false;
27
+ lines.push(red(`✗ ${line}`));
28
+ },
29
+ show: (label) => ui.section(label, lines, failed),
30
+ };
31
+ };
32
+ ui.intro("sidecar status");
33
+ const config = section();
34
+ const configured = existsSync(configPath(home));
35
+ if (configured)
36
+ config.ok(dim(configPath(home)));
37
+ else
38
+ config.problem(`not installed: no ${configPath(home)}`);
39
+ // An invalid config is the likeliest problem to diagnose: report it, and check the rest as defaults.
40
+ let settings = DEFAULTS;
41
+ try {
42
+ settings = loadConfig(home);
43
+ }
44
+ catch (err) {
45
+ config.problem(err.message);
46
+ }
47
+ config.show("Config");
48
+ const drivers = all.filter((a) => a.driver && found(a, a.driver));
49
+ const installed = all.filter((a) => drivers.includes(a) || (a.navigator && found(a, a.navigator)));
50
+ ui.section("Agents detected", [agentsLine(all, installed)]);
51
+ const mcp = section();
52
+ const registrations = drivers.flatMap(({ id, driver }) => driver
53
+ .targets()
54
+ .map((t) => [
55
+ t.label,
56
+ driver.read(t, run, serverFor(id, home)),
57
+ id,
58
+ ]));
59
+ for (const [label, r, id] of registrations) {
60
+ if (r.state === "current")
61
+ mcp.ok(`${dim("✓")} ${targetLine(label)}`);
62
+ else if (r.state === "missing")
63
+ mcp.ok(dim(`${label} not registered`));
64
+ else if (r.state === "stale")
65
+ mcp.problem(`${label} runs another Node, entry or store home: ${r.command.join(" ")}`);
66
+ else if (r.state === "no-driver")
67
+ mcp.problem(`${label} without --driver ${id}: ${r.command.join(" ")}`);
68
+ else
69
+ mcp.problem(`${label} unreadable: ${r.detail}`);
70
+ }
71
+ if (configured && !registrations.some(([, r]) => r.state === "current"))
72
+ mcp.problem("registered with no agent");
73
+ if (mcp.lines.length)
74
+ mcp.show("MCP server");
75
+ const dashboard = section();
76
+ const s = service.status();
77
+ if (!s.installed)
78
+ dashboard.problem("service not installed");
79
+ else if (!s.current)
80
+ dashboard.problem("service runs another Node or entry");
81
+ else if (!s.running)
82
+ dashboard.problem("service not running");
83
+ else
84
+ for (const url of dashboardLinks(settings.dashboardPort, settings.dashboardHost, settings.dashboardToken))
85
+ dashboard.ok(link(url));
86
+ dashboard.show("Dashboard");
87
+ const store = new Store({ home, lockPort: settings.lockPort });
88
+ const counts = new Map();
89
+ for (const caseId of store.listCaseIds()) {
90
+ let state = "unreadable";
91
+ try {
92
+ state = caseStatus(fold(await store.read(caseId)));
93
+ }
94
+ catch { }
95
+ counts.set(state, (counts.get(state) ?? 0) + 1);
96
+ }
97
+ const cases = section();
98
+ const summary = ["open", "closed"]
99
+ .filter((state) => counts.has(state))
100
+ .map((state) => `${counts.get(state)} ${state}`)
101
+ .join(` ${dim("·")} `);
102
+ if (summary || !counts.has("unreadable"))
103
+ cases.ok(summary || "none");
104
+ if (counts.has("unreadable"))
105
+ cases.problem(`${counts.get("unreadable")} unreadable`);
106
+ cases.show("Cases");
107
+ ui.outro(healthy
108
+ ? bold("All good")
109
+ : `${red("Problems found")} ${dim("· `sidecar setup` repairs registrations and the dashboard service")}`);
110
+ return healthy;
111
+ }
@@ -0,0 +1,26 @@
1
+ import measure from "fast-string-truncated-width";
2
+ // Terminal styling for the CLI. Colour only carries meaning: red for a failure, blue for a link to
3
+ // open; everything else is plain, bold or dim. All of it is off when stdout is not a terminal or
4
+ // NO_COLOR is set (https://no-color.org), so piped output and tests see plain text.
5
+ const on = process.stdout.isTTY === true && !process.env.NO_COLOR;
6
+ const sgr = (open, close) => (text) => on ? `\x1b[${open}m${text}\x1b[${close}m` : text;
7
+ export const bold = sgr("1", "22");
8
+ export const dim = sgr("2", "22");
9
+ export const red = sgr("38;2;240;120;120", "39");
10
+ const blue = sgr("38;2;138;166;255", "39");
11
+ /** A clickable link (OSC 8) in blue; terminals without OSC 8 show the text. */
12
+ export const link = (url) => (on ? blue(`\x1b]8;;${url}\x1b\\${url}\x1b]8;;\x1b\\`) : url);
13
+ /** The cells styled text takes in a terminal: escapes and links none, wide characters and emoji two. */
14
+ export const width = (text) => measure(text).width;
15
+ /** Pads styled text with spaces to `n` cells. */
16
+ export const pad = (text, n) => text + " ".repeat(Math.max(0, n - width(text)));
17
+ /**
18
+ * Cuts styled text to at most `max` cells, ending in "…", and closes any open style or link, so a
19
+ * line never wraps.
20
+ */
21
+ export function fit(text, max) {
22
+ if (max < 1)
23
+ return width(text) === 0 ? text : "";
24
+ const { truncated, index } = measure(text, { limit: max, ellipsis: "…", ellipsisWidth: 1 });
25
+ return truncated ? `${text.slice(0, index)}…${on ? "\x1b]8;;\x1b\\\x1b[0m" : ""}` : text;
26
+ }
@@ -0,0 +1,170 @@
1
+ import { Writable } from "node:stream";
2
+ import { styleText } from "node:util";
3
+ import * as p from "@clack/prompts";
4
+ import { SIDECAR_VERSION } from "../lib/version.js";
5
+ import { bold, dim, fit, pad, red } from "./style.js";
6
+ /** Label column width: the longest label, "Agents detected", and two spaces. */
7
+ const LABEL = 17;
8
+ /** The cells clack puts before a log line: its symbol and two spaces. */
9
+ const GUTTER = 3;
10
+ const FRAMES = ["◒", "◐", "◓", "◑"];
11
+ /**
12
+ * Forwards everything to stdout and tracks the cursor's row relative to the start, so a fold can
13
+ * move back to its first row and redraw. Clack moves the cursor only with \n and CSI A/B, and wraps
14
+ * its own frames; the lines this UI draws inside a fold are cut to the width, so none of them wraps.
15
+ * The highest row reached since the last redraw tells whether the fold's first row scrolled away.
16
+ */
17
+ class Screen extends Writable {
18
+ row = 0;
19
+ peak = 0;
20
+ /** Whether a fold may move the cursor back. Off for good once the terminal is resized. */
21
+ live = process.stdout.isTTY === true && !p.isCI();
22
+ isTTY = process.stdout.isTTY === true;
23
+ constructor() {
24
+ super();
25
+ process.stdout.on("resize", () => {
26
+ // A reflow moves earlier rows by an amount the count cannot know.
27
+ this.live = false;
28
+ this.emit("resize");
29
+ });
30
+ }
31
+ get columns() {
32
+ return process.stdout.columns ?? 80;
33
+ }
34
+ get rows() {
35
+ return process.stdout.rows ?? 24;
36
+ }
37
+ _write(chunk, _encoding, done) {
38
+ const text = chunk.toString();
39
+ this.row += text.split("\n").length - 1;
40
+ // oxlint-disable-next-line no-control-regex -- matches cursor-up and cursor-down sequences
41
+ for (const [, n, way] of text.matchAll(/\x1b\[(\d*)([AB])/g))
42
+ this.row += (way === "A" ? -1 : 1) * Number(n || 1);
43
+ this.peak = Math.max(this.peak, this.row);
44
+ process.stdout.write(chunk);
45
+ // At once: a deferred callback makes Writable queue later writes, so the count would lag.
46
+ done();
47
+ }
48
+ /** Erases everything from `row` down and moves there. */
49
+ rewind(row) {
50
+ if (this.row > row)
51
+ this.write(`\x1b[${this.row - row}A`);
52
+ this.write("\x1b[G\x1b[J");
53
+ this.row = row;
54
+ this.peak = row;
55
+ }
56
+ }
57
+ function answered(value, output) {
58
+ if (p.isCancel(value)) {
59
+ p.cancel("Cancelled. Nothing was changed.", { output });
60
+ process.exit(130);
61
+ }
62
+ return value;
63
+ }
64
+ export function clackUI() {
65
+ const screen = new Screen();
66
+ const io = { output: screen };
67
+ let open;
68
+ const draw = (label, lines, failed = false, cut = false, gap = false) => {
69
+ const max = screen.columns - GUTTER;
70
+ const body = lines.map((line, i) => pad(i === 0 ? label : "", LABEL) + line);
71
+ p.log.message((cut ? body.map((line) => fit(line, max)) : body).join("\n"), {
72
+ symbol: failed ? red("■") : dim("◆"),
73
+ spacing: gap ? 1 : 0,
74
+ ...io,
75
+ });
76
+ };
77
+ /** After every answer, the open fold replaces the prompt with its lines. */
78
+ const ask = async (prompt) => {
79
+ const value = answered(await prompt, screen);
80
+ open?.redraw();
81
+ return value;
82
+ };
83
+ return {
84
+ intro: (title) => {
85
+ p.intro(`${bold(title)} ${dim(`v${SIDECAR_VERSION}`)}`, io);
86
+ screen.write(`${styleText("gray", p.S_BAR)}\n`);
87
+ },
88
+ outro: (message) => p.outro(message, io),
89
+ section: (label, lines, failed, gap) => draw(label, lines, failed, false, gap),
90
+ fold: (label) => {
91
+ // One fold at a time: a fold rewinds to its own first row, which would erase another's.
92
+ if (open)
93
+ throw new Error(`fold "${label}" started while another fold is open`);
94
+ const start = screen.row;
95
+ screen.peak = start;
96
+ let lines = [];
97
+ // Folding stops for good once the first row may be gone: after a resize, or once the
98
+ // cursor reached the terminal's last row, where one more line scrolls it away.
99
+ let folding = screen.live;
100
+ const fold = {
101
+ redraw() {
102
+ if (!folding)
103
+ return;
104
+ if (!screen.live || screen.peak - start >= screen.rows - 1) {
105
+ folding = false;
106
+ return;
107
+ }
108
+ screen.rewind(start);
109
+ if (lines.length)
110
+ draw(label, lines, false, true);
111
+ screen.peak = screen.row;
112
+ },
113
+ };
114
+ open = fold;
115
+ return {
116
+ set: (next) => {
117
+ lines = next;
118
+ fold.redraw();
119
+ },
120
+ end: () => {
121
+ open = undefined;
122
+ if (!folding && lines.length)
123
+ draw(label, lines);
124
+ },
125
+ };
126
+ },
127
+ steps: (lines) => p.log.message([bold("Next steps"), ...lines.map((line, i) => `${dim(String(i + 1))} ${line}`)].join("\n"), { symbol: dim("▲"), ...io }),
128
+ confirm: (message, initial) => ask(p.confirm({ message, initialValue: initial, ...io })),
129
+ select: (message, choices, initial) => ask(p.select({ message, options: choices, initialValue: initial, ...io })),
130
+ multiselect: (message, choices, initial) => ask(p.multiselect({
131
+ message,
132
+ options: choices,
133
+ initialValues: initial,
134
+ required: false,
135
+ ...io,
136
+ })),
137
+ text: (message, initial, validate) => ask(p.text({
138
+ message,
139
+ initialValue: initial,
140
+ ...(validate ? { validate: (value) => validate(value ?? "") } : {}),
141
+ ...io,
142
+ })),
143
+ task: async (message, work) => {
144
+ // One row, cut to the width and redrawn in place: it never moves the tracked row.
145
+ if (!screen.live)
146
+ return work();
147
+ let frame = 0;
148
+ const spin = () => screen.write(`\r\x1b[2K${fit(`${dim(FRAMES[frame++ % FRAMES.length])} ${message}`, screen.columns - 1)}`);
149
+ spin();
150
+ const timer = setInterval(spin, 120);
151
+ try {
152
+ return await work();
153
+ }
154
+ finally {
155
+ clearInterval(timer);
156
+ screen.write("\r\x1b[2K");
157
+ }
158
+ },
159
+ };
160
+ }
161
+ /** Answers every prompt with its default; output still renders. */
162
+ export function acceptDefaults(base) {
163
+ return {
164
+ ...base,
165
+ confirm: async (_message, initial) => initial,
166
+ select: async (_message, _choices, initial) => initial,
167
+ multiselect: async (_message, _choices, initial) => initial,
168
+ text: async (_message, initial) => initial,
169
+ };
170
+ }
@@ -0,0 +1,73 @@
1
+ import { existsSync, rmSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { unregister } from "../adapters/registration.js";
4
+ import { configPath } from "../config.js";
5
+ import { withDefaults } from "./deps.js";
6
+ import { targetLine } from "./lines.js";
7
+ import { bold, dim, red } from "./style.js";
8
+ // `sidecar uninstall`: undoes `sidecar setup` — the MCP registrations, the dashboard service and
9
+ // the config. Cases stay.
10
+ /** Resolves to false when a step failed. A decline changes nothing and is not a failure. */
11
+ export async function runUninstall(deps) {
12
+ const { ui, home } = deps;
13
+ const { all, found, run, service } = withDefaults(deps);
14
+ ui.intro("sidecar uninstall");
15
+ if (!(await ui.confirm("Remove the MCP registrations, the dashboard service and the config?", true))) {
16
+ ui.outro("Nothing was changed.");
17
+ return true;
18
+ }
19
+ let ok = true;
20
+ const removed = [];
21
+ const done = (line) => removed.push(`${dim("✓")} ${line}`);
22
+ const failed = (line) => {
23
+ ok = false;
24
+ removed.push(red(`✗ ${line}`));
25
+ };
26
+ // The results print on every way out: a config that cannot be removed still shows the steps before it.
27
+ let finished = false;
28
+ try {
29
+ await ui.task("Removing", () => {
30
+ // An agent that is not installed holds no registration that sidecar could remove.
31
+ for (const adapter of all) {
32
+ const { driver } = adapter;
33
+ if (!driver || !found(adapter, driver))
34
+ continue;
35
+ for (const target of driver.targets()) {
36
+ const removal = unregister(driver, target, run);
37
+ if (removal.state === "removed")
38
+ done(targetLine(target.label));
39
+ if (removal.state === "failed")
40
+ failed(`${target.label}: ${removal.detail}`);
41
+ }
42
+ }
43
+ // A service file it cannot read is reported; the config is still removed.
44
+ try {
45
+ if (service.status().installed) {
46
+ service.uninstall();
47
+ done("dashboard service");
48
+ }
49
+ }
50
+ catch (err) {
51
+ failed(`dashboard service: ${err.message}`);
52
+ }
53
+ if (existsSync(configPath(home))) {
54
+ try {
55
+ rmSync(configPath(home));
56
+ }
57
+ catch (err) {
58
+ // Shown in the section too; rethrown, so the command fails with the reason.
59
+ failed(`config: ${err.message}`);
60
+ throw err;
61
+ }
62
+ done(dim(configPath(home)));
63
+ }
64
+ });
65
+ finished = true;
66
+ }
67
+ finally {
68
+ ui.section("Removed", removed.length ? removed : [dim("nothing was installed")], !ok || !finished);
69
+ }
70
+ const kept = dim(`· cases are kept in ${join(home, "cases")}`);
71
+ ui.outro(ok ? `${bold("Done")} ${kept}` : `${red("Problems found")} ${kept}`);
72
+ return ok;
73
+ }