@caveman-ai/cli 2.1.0 → 4.0.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.
- package/README.md +3 -1
- package/dist/agents.generated.js +20 -20
- package/dist/binaries.generated.js +1 -1
- package/dist/caveman-pi-extension.mjs +66 -21
- package/dist/device-auth.generated.js +176 -0
- package/dist/home-acl.js +45 -0
- package/dist/index.js +2895 -622
- package/dist/learn-autopilot.js +2 -1
- package/dist/modules/apply.js +622 -0
- package/dist/modules/cloud.js +150 -0
- package/dist/modules/config-home.js +73 -0
- package/dist/modules/doctor.js +86 -0
- package/dist/modules/index-file.js +157 -0
- package/dist/modules/onboard.js +860 -0
- package/dist/modules/provider-logins.js +292 -0
- package/dist/modules/registry.js +96 -0
- package/dist/modules/status.js +71 -0
- package/dist/modules/stop.js +99 -0
- package/dist/native-hook-fast.js +15 -7
- package/dist/native-pipe.js +17 -0
- package/dist/portable-command.js +27 -4
- package/dist/portable-process.mjs +61 -11
- package/dist/reserved-verbs.generated.js +3 -0
- package/dist/stats-cli.js +2 -0
- package/package.json +4 -4
|
@@ -0,0 +1,860 @@
|
|
|
1
|
+
// First run: one screen says what was found and what setup will do, one key
|
|
2
|
+
// applies it (Customize and Details are a key away), then sign in only when
|
|
3
|
+
// routing is on, then offer to start the agent. `caveman setup`, bare `caveman` before any
|
|
4
|
+
// setup, `npx @caveman-ai/cli`, the end of install.sh and `caveman <agent>`
|
|
5
|
+
// before any setup all land here. Nothing is written before Continue.
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { sep } from "node:path";
|
|
9
|
+
import { emitKeypressEvents } from "node:readline";
|
|
10
|
+
import { applyModules, currentSelection, moduleHost, planModules, renderPlan } from "./apply.js";
|
|
11
|
+
import { ROUTING_ON_LINE, ROUTING_ON_SHORT } from "./cloud.js";
|
|
12
|
+
import { cloudConfigPath } from "./config-home.js";
|
|
13
|
+
import { MODULES, findModule } from "./registry.js";
|
|
14
|
+
const LEGACY_SETUP_FLAGS = new Set(["--json", "--install", "--remove", "--agent-native"]);
|
|
15
|
+
export const ONBOARD_USAGE = "setup [--yes] [--dry-run] [--only a,b] [--skip a,b] [--agents a,b|none]";
|
|
16
|
+
// parseOnboardArgs returns undefined when the argv belongs to the older setup
|
|
17
|
+
// verbs (--install, --json, --agent-native), which keep their own handler.
|
|
18
|
+
export function parseOnboardArgs(argv) {
|
|
19
|
+
if (argv.some((arg) => LEGACY_SETUP_FLAGS.has(arg.split("=", 1)[0])))
|
|
20
|
+
return undefined;
|
|
21
|
+
const opts = { yes: false, dryRun: false };
|
|
22
|
+
for (let i = 0; i < argv.length; i++) {
|
|
23
|
+
const arg = argv[i];
|
|
24
|
+
if (arg === "--yes" || arg === "-y") {
|
|
25
|
+
opts.yes = true;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (arg === "--dry-run") {
|
|
29
|
+
opts.dryRun = true;
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
const flag = arg.split("=", 1)[0];
|
|
33
|
+
if (flag !== "--only" && flag !== "--skip" && flag !== "--agents")
|
|
34
|
+
return { error: `unknown flag ${arg}` };
|
|
35
|
+
const value = arg.includes("=") ? arg.slice(flag.length + 1) : argv[++i];
|
|
36
|
+
if (!value || value.startsWith("-"))
|
|
37
|
+
return { error: `${flag} needs a comma-separated list` };
|
|
38
|
+
const ids = value.split(",").map((id) => id.trim()).filter(Boolean);
|
|
39
|
+
// `none`: no agent beyond the ones already wired (a list cannot be empty).
|
|
40
|
+
if (flag === "--agents") {
|
|
41
|
+
opts.agents = ids.filter((id) => id !== "none");
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
const unknown = ids.filter((id) => !findModule(id));
|
|
45
|
+
if (unknown.length)
|
|
46
|
+
return { error: `unknown module ${unknown.join(", ")} · modules: ${MODULES.map((m) => m.id).join(", ")}` };
|
|
47
|
+
opts[flag === "--only" ? "only" : "skip"] = ids;
|
|
48
|
+
}
|
|
49
|
+
return opts;
|
|
50
|
+
}
|
|
51
|
+
function storedConfig() {
|
|
52
|
+
try {
|
|
53
|
+
const parsed = JSON.parse(readFileSync(cloudConfigPath(), "utf8"));
|
|
54
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return {};
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
// Setup has run once the module state exists in the cloud config.
|
|
61
|
+
export function setupRan() {
|
|
62
|
+
const modules = storedConfig().modules;
|
|
63
|
+
return Boolean(modules) && typeof modules === "object" && !Array.isArray(modules);
|
|
64
|
+
}
|
|
65
|
+
export function setupDeclined() {
|
|
66
|
+
return typeof storedConfig().setupDeclinedAt === "string";
|
|
67
|
+
}
|
|
68
|
+
export function onboardInteractive() {
|
|
69
|
+
const ci = process.env.CI;
|
|
70
|
+
return Boolean(process.stdin.isTTY && process.stdout.isTTY)
|
|
71
|
+
&& !(ci && ci !== "0" && ci.toLowerCase() !== "false")
|
|
72
|
+
&& process.env.TERM !== "dumb";
|
|
73
|
+
}
|
|
74
|
+
export async function onboard(opts, deps) {
|
|
75
|
+
const out = deps.output ?? process.stdout;
|
|
76
|
+
const input = deps.input ?? process.stdin;
|
|
77
|
+
const c = colors(out);
|
|
78
|
+
const ask = deps.interactive && !opts.yes && !opts.dryRun;
|
|
79
|
+
const byId = new Map(deps.agents.map((agent) => [agent.id, agent]));
|
|
80
|
+
const usable = (agent) => agent.installed || agent.wired;
|
|
81
|
+
for (const id of opts.agents ?? []) {
|
|
82
|
+
const agent = byId.get(id);
|
|
83
|
+
if (!agent || !usable(agent)) {
|
|
84
|
+
throw new Error(`--agents: ${id} is not installed here · found: ${deps.agents.filter(usable).map((a) => a.id).join(", ") || "none"}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const found = deps.found ?? {};
|
|
88
|
+
// In a terminal the first run is a screen: padded, one accent colour, a row
|
|
89
|
+
// per fact. Everywhere else it stays the plain report scripts read.
|
|
90
|
+
if (ask)
|
|
91
|
+
out.write(`\n${PAD}${c.accent(c.bold("caveman"))} ${c.dim("make your coding agent cheaper")}\n\n${foundRows(deps.agents, found, c, out).join("\n")}\n\n`);
|
|
92
|
+
else
|
|
93
|
+
out.write(`${c.bold("caveman")} ${c.dim("· make your coding agent cheaper")}\n\n${foundBlock(deps.agents, found, c)}\n\n`);
|
|
94
|
+
let selection = initialSelection(opts);
|
|
95
|
+
// Re-runs keep what is wired; a first run takes what is installed. --agents
|
|
96
|
+
// adds to the wired ones: unwiring is `caveman off` or unticking here.
|
|
97
|
+
const wired = deps.agents.filter((agent) => agent.wired).map((agent) => agent.id);
|
|
98
|
+
let agents = [...new Set([...wired, ...(opts.agents ?? (wired.length ? [] : deps.agents.filter((agent) => agent.installed).map((agent) => agent.id)))])];
|
|
99
|
+
// Off until ticked: Auto can spend on a key it is given.
|
|
100
|
+
const keys = (deps.addKey ? found.keys ?? [] : []).filter((key) => !key.added).map((key) => ({ ...key, on: false }));
|
|
101
|
+
let plan;
|
|
102
|
+
if (ask) {
|
|
103
|
+
for (;;) {
|
|
104
|
+
plan = await planModules(selection, agents);
|
|
105
|
+
const rows = summaryRows(plan, selection, agents.map((id) => byId.get(id).name), found);
|
|
106
|
+
if (deps.installCli?.command)
|
|
107
|
+
rows.push(["Install", `the caveman command · ${deps.installCli.command}`]);
|
|
108
|
+
const moved = await portMove(selection, agents);
|
|
109
|
+
if (moved)
|
|
110
|
+
rows.push(["Port", `${moved.free} · ${moved.held.split(":").pop()} is in use by another program`]);
|
|
111
|
+
const pick = await choose(input, out, c, rows, keys, plan.lines.length > 0 ? "Set up" : "Continue");
|
|
112
|
+
if (pick === null)
|
|
113
|
+
return cancelled(out, c);
|
|
114
|
+
if (pick === "details") {
|
|
115
|
+
out.write(`${indent(plan.lines.length ? renderPlan(plan) : `This will\n ${c.dim("change nothing")}\n`)}\n`);
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (pick === "customize") {
|
|
119
|
+
const picked = await customize(input, out, c, selection, agents, keys, deps.agents.filter(usable), deps.agents.filter((a) => !usable(a)));
|
|
120
|
+
if (!picked)
|
|
121
|
+
return cancelled(out, c);
|
|
122
|
+
({ selection, agents } = picked);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
await deps.markFirstRun();
|
|
126
|
+
if (pick === "no") {
|
|
127
|
+
deps.markDeclined();
|
|
128
|
+
const session = deps.launching ? ` · ${deps.launching} runs this session only` : "";
|
|
129
|
+
out.write(`${PAD}${c.dim(`Nothing changed${session} · ${deps.cmd} setup when you want it`)}\n`);
|
|
130
|
+
return { confirmed: false, cancelled: false, ok: true, plan };
|
|
131
|
+
}
|
|
132
|
+
break;
|
|
133
|
+
}
|
|
134
|
+
out.write("\n");
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
out.write(`Modules ${MODULES.filter((m) => selection[m.id]).map((m) => m.title).join(" · ") || "none"}\n`);
|
|
138
|
+
out.write(`Agents ${agents.map((id) => byId.get(id).name).join(" · ") || "none"}\n\n`);
|
|
139
|
+
plan = await planModules(selection, agents);
|
|
140
|
+
out.write(plan.lines.length ? renderPlan(plan) : `This will\n ${c.dim("change nothing")}\n`);
|
|
141
|
+
if (deps.installCli?.command)
|
|
142
|
+
out.write(` ${"RUN".padEnd(9)} ${deps.installCli.command} the caveman command, kept after this run\n`);
|
|
143
|
+
const moved = await portMove(selection, agents);
|
|
144
|
+
if (moved)
|
|
145
|
+
out.write(` ${"RUN".padEnd(9)} local runtime on port ${moved.free} ${moved.held} is in use by another program\n`);
|
|
146
|
+
if (opts.dryRun) {
|
|
147
|
+
out.write(`${c.dim("Dry run: nothing was written.")}\n`);
|
|
148
|
+
return { confirmed: false, cancelled: false, ok: true, plan };
|
|
149
|
+
}
|
|
150
|
+
// Without a terminal to ask in (CI counts), only --yes applies.
|
|
151
|
+
if (!deps.interactive && !opts.yes) {
|
|
152
|
+
out.write(`Nothing changed: pass --yes to apply · ${deps.cmd} setup --yes\n`);
|
|
153
|
+
return { confirmed: false, cancelled: false, ok: true, plan };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
// One line that the download rewrites. In a terminal the finished steps are
|
|
157
|
+
// held and shown grouped once the work is done; elsewhere each prints as it ends.
|
|
158
|
+
const busy = spinner(out, c, ask, ask ? PAD : "");
|
|
159
|
+
let cmd = deps.cmd;
|
|
160
|
+
const done = [];
|
|
161
|
+
const progress = (line) => {
|
|
162
|
+
if (!ask)
|
|
163
|
+
return busy.say(line.replace(/^✓/, c.green("✓")).replace(/^○/, c.yellow("○")));
|
|
164
|
+
done.push(line);
|
|
165
|
+
// The step just finished is what the waiting line says meanwhile.
|
|
166
|
+
if (line.startsWith("✓ "))
|
|
167
|
+
busy.show(line.slice(2));
|
|
168
|
+
};
|
|
169
|
+
let result;
|
|
170
|
+
try {
|
|
171
|
+
if (ask)
|
|
172
|
+
busy.show("setting up");
|
|
173
|
+
if (deps.installCli) {
|
|
174
|
+
if (deps.installCli.command)
|
|
175
|
+
busy.show("installing the caveman command");
|
|
176
|
+
try {
|
|
177
|
+
cmd = await deps.installCli.run();
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
busy.stop();
|
|
181
|
+
out.write(`${ask ? PAD : ""}${c.red("✗")} ${error instanceof Error ? error.message : String(error)}\n${ask ? PAD : ""}${c.dim("Nothing else changed.")}\n`);
|
|
182
|
+
return { confirmed: true, cancelled: false, ok: false, plan };
|
|
183
|
+
}
|
|
184
|
+
const shadow = cmd === "caveman" ? undefined : deps.installCli.shadow?.();
|
|
185
|
+
if (deps.installCli.command)
|
|
186
|
+
progress(`✓ caveman command installed${cmd === "caveman" ? "" : ` at ${tilde(cmd)} · ${shadow ? `typing caveman runs another copy at ${tilde(shadow)}` : "not on your PATH"}`}`);
|
|
187
|
+
result = await deps.installCli.apply(selection, agents, (line) => line.startsWith("downloading ") ? busy.show(line) : progress(line));
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
// Before the first agent is wired: never to a port another program answers on.
|
|
191
|
+
const moved = await portMove(selection, agents);
|
|
192
|
+
if (moved) {
|
|
193
|
+
moduleHost().useRuntimePort(moved.free);
|
|
194
|
+
progress(`○ ${moved.held} is in use by another program · local runtime on port ${moved.free}`);
|
|
195
|
+
}
|
|
196
|
+
// The agents this setup chose: `caveman claude` re-wires Claude Code later
|
|
197
|
+
// only when it was one of them.
|
|
198
|
+
moduleHost().mutateConfig((out) => { out.setupAgents = [...agents]; });
|
|
199
|
+
result = await applyModules(plan, { yes: true, progress, downloading: (name) => busy.show(`downloading ${name}`) });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
finally {
|
|
203
|
+
// Whatever throws, the progress line never stays under the error.
|
|
204
|
+
busy.stop();
|
|
205
|
+
}
|
|
206
|
+
const added = [];
|
|
207
|
+
for (const key of keys.filter((item) => item.on)) {
|
|
208
|
+
try {
|
|
209
|
+
deps.addKey(key);
|
|
210
|
+
if (ask)
|
|
211
|
+
added.push(key);
|
|
212
|
+
else
|
|
213
|
+
out.write(`${c.green("✓")} ${key.name} key added for Auto ${c.dim(`· ${cmd} providers remove ${key.id} takes it back`)}\n`);
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
result.problems.push(`${key.name} key: ${error instanceof Error ? error.message.replace(/^caveman: /, "") : String(error)}`);
|
|
217
|
+
result.ok = false;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
busy.stop();
|
|
221
|
+
if (added.length)
|
|
222
|
+
done.push(`✓ keys: ${added.map((key) => key.name).join(" · ")} added for Auto · undo: ${added.map((key) => `${cmd} providers remove ${key.id}`).join(" · ")}`);
|
|
223
|
+
if (ask)
|
|
224
|
+
for (const line of stepRows(done, c))
|
|
225
|
+
out.write(`${line}\n`);
|
|
226
|
+
for (const problem of result.problems)
|
|
227
|
+
out.write(`${ask ? PAD : ""}${c.red("✗")} ${problem}\n`);
|
|
228
|
+
if (!ask)
|
|
229
|
+
out.write("\n");
|
|
230
|
+
const auto = !selection.routing ? false
|
|
231
|
+
: ask ? await signInStep({ ...deps, cmd }, input, out, c)
|
|
232
|
+
: await routingStep(opts, { ...deps, cmd }, input, out, c);
|
|
233
|
+
// Only an agent this setup wired: one left on its own endpoint is not.
|
|
234
|
+
const wiredNow = agents.filter((id) => moduleHost().nativeAgents().some((agent) => agent.id === id && agent.wired));
|
|
235
|
+
const tryAgent = ["claude", "codex"].find((id) => wiredNow.includes(id)) ?? wiredNow[0];
|
|
236
|
+
let launch;
|
|
237
|
+
// No agent set up means nothing to try: `caveman claude` would only fail.
|
|
238
|
+
const noAgent = `No agent set up yet · install one (for example Claude Code), then ${cmd} setup`;
|
|
239
|
+
if (ask) {
|
|
240
|
+
const hint = auto ? `\n${PAD}${" ".repeat(12)}${c.dim(`Auto is in the model picker${tryAgent === "claude" ? " · /model in Claude Code" : ""}`)}` : "";
|
|
241
|
+
out.write(!result.ok ? `\n${PAD}${c.red("✗")} Setup finished with problems. Fix them, then run ${cmd} setup again.\n`
|
|
242
|
+
: deps.launching ? `\n${PAD}${c.green("✓")} ${c.bold("Ready")} ${c.dim(`starting ${deps.launching}`)}\n`
|
|
243
|
+
: !agents.length ? `\n${PAD}${c.green("✓")} ${c.bold("Ready")} ${c.dim(noAgent)}\n`
|
|
244
|
+
: !tryAgent ? `\n${PAD}${c.green("✓")} ${c.bold("Ready")} ${c.cyan(`${cmd} status`)}\n`
|
|
245
|
+
: `\n${PAD}${c.green("✓")} ${c.bold("Ready")} ${c.cyan(`${cmd} ${tryAgent}`)} ${c.dim("·")} ${c.cyan(`${cmd} status`)}${hint}\n`);
|
|
246
|
+
}
|
|
247
|
+
else if (!result.ok) {
|
|
248
|
+
out.write(`${c.red("✗")} Setup finished with problems. Fix them, then run ${cmd} setup again.\n`);
|
|
249
|
+
}
|
|
250
|
+
else if (deps.launching) {
|
|
251
|
+
out.write(`${c.green("✓")} Ready. Starting ${deps.launching}.\n`);
|
|
252
|
+
}
|
|
253
|
+
else if (!agents.length) {
|
|
254
|
+
out.write(`${c.green("✓")} Ready. ${noAgent}\n`);
|
|
255
|
+
}
|
|
256
|
+
else if (!tryAgent) {
|
|
257
|
+
out.write(`${c.green("✓")} Ready. See it: ${c.cyan(`${cmd} status`)}\n`);
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
out.write(`${c.green("✓")} Ready. Try: ${c.cyan(`${cmd} ${tryAgent}`)} See it: ${c.cyan(`${cmd} status`)}\n`);
|
|
261
|
+
}
|
|
262
|
+
if (ask)
|
|
263
|
+
await deps.discloseTelemetry();
|
|
264
|
+
const startable = tryAgent ? byId.get(tryAgent) : undefined;
|
|
265
|
+
if (ask && result.ok && deps.offerLaunch && !deps.launching && startable?.installed) {
|
|
266
|
+
out.write("\n");
|
|
267
|
+
if (await confirm(input, out, c, `Start ${startable.name} now?`))
|
|
268
|
+
launch = tryAgent;
|
|
269
|
+
}
|
|
270
|
+
return { confirmed: true, cancelled: false, ok: result.ok, plan, ...(launch ? { launch } : {}) };
|
|
271
|
+
}
|
|
272
|
+
// The runtime's port matters only when this setup wires an agent through it
|
|
273
|
+
// (aider is wired without the runtime).
|
|
274
|
+
async function portMove(selection, agents) {
|
|
275
|
+
if (!MODULES.some((m) => m.wiresAgents && selection[m.id]) || !agents.some((id) => id !== "aider"))
|
|
276
|
+
return undefined;
|
|
277
|
+
return moduleHost().runtimePortTaken();
|
|
278
|
+
}
|
|
279
|
+
// currentSelection is the registry defaults on a fresh home, the stored state on
|
|
280
|
+
// a re-run, and off for a module whose key an older config already switched off.
|
|
281
|
+
function initialSelection(opts) {
|
|
282
|
+
const selection = currentSelection();
|
|
283
|
+
if (opts.only)
|
|
284
|
+
for (const m of MODULES)
|
|
285
|
+
selection[m.id] = opts.only.includes(m.id);
|
|
286
|
+
for (const id of opts.skip ?? [])
|
|
287
|
+
selection[id] = false;
|
|
288
|
+
return selection;
|
|
289
|
+
}
|
|
290
|
+
// Routing stays on whatever happens here; without an account it waits, and
|
|
291
|
+
// `caveman login` finishes it later (its sign-in says what routing sends).
|
|
292
|
+
// Already signed in, routing starts now, so this says it. True when Auto is
|
|
293
|
+
// live as setup ends.
|
|
294
|
+
async function routingStep(opts, deps, input, out, c) {
|
|
295
|
+
if (await deps.signedIn()) {
|
|
296
|
+
out.write(`${ROUTING_ON_LINE}\n\n`);
|
|
297
|
+
return true;
|
|
298
|
+
}
|
|
299
|
+
const waits = (why) => {
|
|
300
|
+
out.write(`${c.yellow("○")} routing is on and ${why} · ${c.cyan(`${deps.cmd} login`)}\n\n`);
|
|
301
|
+
return false;
|
|
302
|
+
};
|
|
303
|
+
if (!deps.interactive || opts.yes)
|
|
304
|
+
return waits("starts after you sign in");
|
|
305
|
+
out.write(`${c.bold("Sign in to switch on Auto")} ${c.dim("· free account · everything else already works without it")}\n`);
|
|
306
|
+
const skip = new AbortController();
|
|
307
|
+
const stop = keys(input, (key) => {
|
|
308
|
+
if (key.name === "escape" || key.name === "s" || key.name === "q" || (key.ctrl && key.name === "c"))
|
|
309
|
+
skip.abort();
|
|
310
|
+
});
|
|
311
|
+
const busy = spinner(out, c, true);
|
|
312
|
+
busy.show("reaching Caveman Cloud");
|
|
313
|
+
try {
|
|
314
|
+
const { email } = await deps.signIn({
|
|
315
|
+
signal: skip.signal,
|
|
316
|
+
code(url, userCode, opened) {
|
|
317
|
+
busy.say(` Open ${c.cyan(url)} and enter ${c.bold(userCode)} ${c.dim(opened ? "(browser opened · esc skips)" : "(esc skips)")}`);
|
|
318
|
+
busy.show("waiting for you to approve in the browser");
|
|
319
|
+
},
|
|
320
|
+
approved: () => busy.stop(),
|
|
321
|
+
});
|
|
322
|
+
busy.stop();
|
|
323
|
+
out.write(` ${c.green("✓")} signed in${email ? ` as ${email}` : ""}\n\n`);
|
|
324
|
+
return true;
|
|
325
|
+
}
|
|
326
|
+
catch (error) {
|
|
327
|
+
busy.stop();
|
|
328
|
+
// Esc during the receipt step, after the credentials were saved.
|
|
329
|
+
if (skip.signal.aborted && await deps.signedIn()) {
|
|
330
|
+
out.write(` ${c.green("✓")} signed in\n\n${ROUTING_ON_LINE}\n\n`);
|
|
331
|
+
return true;
|
|
332
|
+
}
|
|
333
|
+
if (skip.signal.aborted)
|
|
334
|
+
return waits("starts after you sign in");
|
|
335
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
336
|
+
const code = error.code;
|
|
337
|
+
if (code === "sign_in_closed") {
|
|
338
|
+
out.write(` ${c.yellow("!")} ${message}\n`);
|
|
339
|
+
return waits("starts once sign-in opens");
|
|
340
|
+
}
|
|
341
|
+
if (code === "cloud_unreachable") {
|
|
342
|
+
out.write(` ${c.yellow("!")} ${message}\n`);
|
|
343
|
+
return waits("starts after you sign in");
|
|
344
|
+
}
|
|
345
|
+
out.write(` ${c.red("✗")} sign-in failed: ${message}\n`);
|
|
346
|
+
return waits("starts after you sign in");
|
|
347
|
+
}
|
|
348
|
+
finally {
|
|
349
|
+
busy.stop();
|
|
350
|
+
stop();
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
function foundLine(agents) {
|
|
354
|
+
const found = agents.filter((a) => a.installed).map((a) => {
|
|
355
|
+
const version = a.version?.match(/\d+\.\d+/)?.[0];
|
|
356
|
+
return version ? `${a.name} ${version}` : a.name;
|
|
357
|
+
});
|
|
358
|
+
if (found.length === 0)
|
|
359
|
+
return "No coding agents found on this machine";
|
|
360
|
+
return `Found ${found.length === 1 ? found[0] : `${found.slice(0, -1).join(", ")} and ${found.at(-1)}`}`;
|
|
361
|
+
}
|
|
362
|
+
function tilde(path) {
|
|
363
|
+
const home = homedir();
|
|
364
|
+
return path === home || path.startsWith(home + sep) ? `~${path.slice(home.length)}` : path;
|
|
365
|
+
}
|
|
366
|
+
// The screen's left margin.
|
|
367
|
+
const PAD = " ";
|
|
368
|
+
function indent(text) {
|
|
369
|
+
return text.split("\n").map((line) => line ? `${PAD}${line}` : line).join("\n");
|
|
370
|
+
}
|
|
371
|
+
// What was found, a row per agent that has something to say (its logins, how
|
|
372
|
+
// it signs in), the rest on one row, then the keys.
|
|
373
|
+
function foundRows(agents, found, c, out) {
|
|
374
|
+
const installed = agents.filter((agent) => agent.installed);
|
|
375
|
+
if (installed.length === 0)
|
|
376
|
+
return [`${PAD}${c.dim("No coding agents found on this machine")}`];
|
|
377
|
+
const dot = c.green(glyphs().dot);
|
|
378
|
+
const width = Math.max(40, (out.columns || 80) - 1);
|
|
379
|
+
const told = [];
|
|
380
|
+
const rest = [];
|
|
381
|
+
for (const agent of installed) {
|
|
382
|
+
const version = agent.version?.match(/\d+\.\d+/)?.[0];
|
|
383
|
+
const name = version ? `${agent.name} ${version}` : agent.name;
|
|
384
|
+
const logins = agent.id === "claude" ? found.claudeLogins ?? [] : [];
|
|
385
|
+
if (logins.length > 1)
|
|
386
|
+
told.push([name, `${logins.length} logins`, logins.map(tilde).join(" · ")]);
|
|
387
|
+
else if (agent.id === "codex" && found.codexLogin)
|
|
388
|
+
told.push([name, found.codexLogin, ""]);
|
|
389
|
+
else
|
|
390
|
+
rest.push(name);
|
|
391
|
+
}
|
|
392
|
+
const keys = found.keys ?? [];
|
|
393
|
+
const keyLabel = `${keys.length} API ${keys.length === 1 ? "key" : "keys"}`;
|
|
394
|
+
const label = Math.max(0, ...told.map(([name]) => name.length), keys.length ? keyLabel.length : 0) + 3;
|
|
395
|
+
const lines = [`${PAD}${c.bold("Found")}`];
|
|
396
|
+
for (const [name, note, more] of told) {
|
|
397
|
+
const room = width - PAD.length - 4 - label - note.length - 2;
|
|
398
|
+
lines.push(`${PAD} ${dot} ${name.padEnd(label)}${note}${more && room > 8 ? ` ${c.dim(clip(more, room))}` : ""}`);
|
|
399
|
+
}
|
|
400
|
+
if (rest.length)
|
|
401
|
+
lines.push(`${PAD} ${dot} ${rest.join(` ${dot} `)}`);
|
|
402
|
+
if (keys.length) {
|
|
403
|
+
const names = keys.map((key) => key.added ? `${key.env} (in Auto's pool)` : key.env).join(" · ");
|
|
404
|
+
lines.push(`${PAD} ${c.yellow(glyphs().dot)} ${keyLabel.padEnd(label)}${c.dim(clip(names, Math.max(8, width - PAD.length - 4 - label)))}`);
|
|
405
|
+
}
|
|
406
|
+
return lines;
|
|
407
|
+
}
|
|
408
|
+
// The finished steps as rows: one for the runtime, one per thing done to the
|
|
409
|
+
// agents, then whatever else a step had to say, each under a short label.
|
|
410
|
+
function stepRows(lines, c) {
|
|
411
|
+
const home = homedir();
|
|
412
|
+
const rows = [];
|
|
413
|
+
const agents = new Map();
|
|
414
|
+
const runtime = [];
|
|
415
|
+
let runtimeMark = "✓";
|
|
416
|
+
for (const raw of lines) {
|
|
417
|
+
const line = raw.split(home + sep).join(`~${sep}`);
|
|
418
|
+
const mark = line[0];
|
|
419
|
+
const text = line.slice(2);
|
|
420
|
+
const agent = text.match(/^(.+) (wired|unwired|hooks refreshed)$/);
|
|
421
|
+
const named = text.match(/^([a-z][a-z -]*): (.+)$/);
|
|
422
|
+
const moved = text.match(/^(\S+) is in use by another program · local runtime on port (\d+)$/);
|
|
423
|
+
if (mark === "✓" && agent)
|
|
424
|
+
agents.set(agent[2], [...(agents.get(agent[2]) ?? []), agent[1]]);
|
|
425
|
+
else if (text.startsWith("downloaded "))
|
|
426
|
+
runtime.push(`${text.slice(11).split(", ").length} binaries downloaded`);
|
|
427
|
+
else if (text === "local runtime started")
|
|
428
|
+
runtime.push("started");
|
|
429
|
+
else if (text === "local runtime starts with your next agent session") {
|
|
430
|
+
runtime.push("starts with your next agent session");
|
|
431
|
+
runtimeMark = "○";
|
|
432
|
+
}
|
|
433
|
+
// Why it moved is on the screen above already.
|
|
434
|
+
else if (moved)
|
|
435
|
+
runtime.push(`port ${moved[2]}`);
|
|
436
|
+
else if (text.startsWith("caveman command installed"))
|
|
437
|
+
rows.push([mark, "Command", `caveman installed${text.slice(25)}`]);
|
|
438
|
+
else if (named)
|
|
439
|
+
rows.push([mark, `${named[1][0].toUpperCase()}${named[1].slice(1)}`, named[2]]);
|
|
440
|
+
else
|
|
441
|
+
rows.push([mark, "", text]);
|
|
442
|
+
}
|
|
443
|
+
for (const [verb, names] of agents)
|
|
444
|
+
rows.unshift(["✓", "Agents", `${names.join(" · ")} ${verb === "hooks refreshed" ? "refreshed" : verb}`]);
|
|
445
|
+
if (runtime.length)
|
|
446
|
+
rows.unshift([runtimeMark, "Runtime", runtime.join(" · ")]);
|
|
447
|
+
return rows.map(([mark, label, text]) => `${PAD}${mark === "✓" ? c.green(mark) : c.yellow(mark)} ${label ? `${label.padEnd(10)}${c.dim(text)}` : text}`);
|
|
448
|
+
}
|
|
449
|
+
// Sign-in on the screen: a heading, where to go and the code, one waiting
|
|
450
|
+
// line; all of it gives way to a single Auto row once it ends. True when Auto
|
|
451
|
+
// is live as setup ends.
|
|
452
|
+
async function signInStep(deps, input, out, c) {
|
|
453
|
+
const row = (mark, text) => out.write(`${PAD}${mark} ${"Auto".padEnd(10)}${text}\n`);
|
|
454
|
+
const said = () => out.write(`${ROUTING_ON_SHORT.map((line) => `${PAD}${" ".repeat(12)}${c.dim(line)}`).join("\n")}\n`);
|
|
455
|
+
const later = (why) => {
|
|
456
|
+
row(c.yellow("○"), `${c.dim(`${why} ·`)} ${c.cyan(`${deps.cmd} login`)}`);
|
|
457
|
+
return false;
|
|
458
|
+
};
|
|
459
|
+
if (await deps.signedIn()) {
|
|
460
|
+
row(c.green("✓"), c.dim("on · signed in"));
|
|
461
|
+
said();
|
|
462
|
+
return true;
|
|
463
|
+
}
|
|
464
|
+
const columns = out.columns || 80;
|
|
465
|
+
out.write(`\n${PAD}${c.bold("Sign in to switch on Auto")}${columns >= 76 ? ` ${c.dim("free account · everything else already works")}` : ""}\n`);
|
|
466
|
+
// Rows this step has drawn below the blank line; the result replaces them.
|
|
467
|
+
let drawn = 1;
|
|
468
|
+
const skip = new AbortController();
|
|
469
|
+
const stop = keys(input, (key) => {
|
|
470
|
+
if (key.name === "escape" || key.name === "s" || key.name === "q" || (key.ctrl && key.name === "c"))
|
|
471
|
+
skip.abort();
|
|
472
|
+
});
|
|
473
|
+
const busy = spinner(out, c, true, `${PAD} `);
|
|
474
|
+
// Back over what was drawn, so the step ends as one row. Only where rewinding
|
|
475
|
+
// is exact: a real terminal, and no row long enough to have wrapped.
|
|
476
|
+
let wrapped = false;
|
|
477
|
+
const settle = () => {
|
|
478
|
+
busy.stop();
|
|
479
|
+
if (out.isTTY && !wrapped)
|
|
480
|
+
out.write(`\x1b[${drawn + 1}A\x1b[J`);
|
|
481
|
+
drawn = 0;
|
|
482
|
+
};
|
|
483
|
+
let extra = [];
|
|
484
|
+
busy.show("reaching Caveman Cloud");
|
|
485
|
+
try {
|
|
486
|
+
const { email } = await deps.signIn({
|
|
487
|
+
signal: skip.signal,
|
|
488
|
+
code(url, userCode, opened) {
|
|
489
|
+
busy.stop();
|
|
490
|
+
wrapped = PAD.length + 8 + url.length >= columns;
|
|
491
|
+
out.write(`${PAD} ${c.dim("Open")} ${c.cyan(url)}\n${PAD} ${c.dim("Code")} ${c.bold(userCode)}\n`);
|
|
492
|
+
drawn += 2;
|
|
493
|
+
busy.show(`${opened ? "browser opened, " : ""}waiting for you to approve · esc skips`);
|
|
494
|
+
},
|
|
495
|
+
approved: () => busy.stop(),
|
|
496
|
+
// Routing's line is said short; runtime data's is kept as sign-in words
|
|
497
|
+
// it, when anything is sent.
|
|
498
|
+
lines: (lines) => { extra = lines.slice(1).filter((line) => !line.includes("nothing sent")); },
|
|
499
|
+
});
|
|
500
|
+
settle();
|
|
501
|
+
row(c.green("✓"), `${c.dim("on · signed in")}${email ? c.dim(` as ${email}`) : ""}`);
|
|
502
|
+
said();
|
|
503
|
+
for (const line of extra)
|
|
504
|
+
out.write(`${PAD}${" ".repeat(12)}${c.dim(line)}\n`);
|
|
505
|
+
return true;
|
|
506
|
+
}
|
|
507
|
+
catch (error) {
|
|
508
|
+
settle();
|
|
509
|
+
// Esc during the receipt step, after the credentials were saved.
|
|
510
|
+
if (skip.signal.aborted && await deps.signedIn()) {
|
|
511
|
+
row(c.green("✓"), c.dim("on · signed in"));
|
|
512
|
+
said();
|
|
513
|
+
return true;
|
|
514
|
+
}
|
|
515
|
+
if (skip.signal.aborted)
|
|
516
|
+
return later("skipped");
|
|
517
|
+
const message = (error instanceof Error ? error.message : String(error)).replace(/\.$/, "");
|
|
518
|
+
const code = error.code;
|
|
519
|
+
if (code === "sign_in_closed" || code === "cloud_unreachable")
|
|
520
|
+
return later(message);
|
|
521
|
+
row(c.red("✗"), `sign-in failed: ${message} · ${c.cyan(`${deps.cmd} login`)}`);
|
|
522
|
+
return false;
|
|
523
|
+
}
|
|
524
|
+
finally {
|
|
525
|
+
busy.stop();
|
|
526
|
+
stop();
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
// The agents line, then one line per kind of login found beside them.
|
|
530
|
+
function foundBlock(agents, found, c) {
|
|
531
|
+
const lines = [foundLine(agents)];
|
|
532
|
+
const row = (label, value) => lines.push(` ${c.dim(label.padEnd(15))}${value}`);
|
|
533
|
+
if ((found.claudeLogins?.length ?? 0) > 1)
|
|
534
|
+
row("Claude logins", found.claudeLogins.map(tilde).join(" · "));
|
|
535
|
+
if (found.codexLogin)
|
|
536
|
+
row("Codex login", found.codexLogin);
|
|
537
|
+
if (found.keys?.length)
|
|
538
|
+
row("API keys", found.keys.map((key) => key.added ? `${key.env} ${c.dim("(in Auto's pool)")}` : key.env).join(" · "));
|
|
539
|
+
return lines.join("\n");
|
|
540
|
+
}
|
|
541
|
+
// What the confirming key does, in a few rows: the full file list is under Details.
|
|
542
|
+
function summaryRows(plan, selection, agentNames, found) {
|
|
543
|
+
const logins = found.claudeLogins?.length ?? 0;
|
|
544
|
+
const names = agentNames.map((name) => name === "Claude Code" && logins > 1 ? `${name} (${logins} logins)` : name);
|
|
545
|
+
const downloads = plan.lines.filter((line) => line.action === "DOWNLOAD").flatMap((line) => line.target.split(", ")).length;
|
|
546
|
+
const files = plan.lines.filter((line) => line.action === "CREATE" || line.action === "UPDATE").length;
|
|
547
|
+
const changes = [
|
|
548
|
+
...(files ? [`${files} config ${files === 1 ? "file" : "files"}`] : []),
|
|
549
|
+
...(downloads ? [`${downloads} signed ${downloads === 1 ? "download" : "downloads"}`] : []),
|
|
550
|
+
...(files ? ["undo: caveman off --all"] : []),
|
|
551
|
+
];
|
|
552
|
+
return [
|
|
553
|
+
["Agents", names.join(" · ") || "none"],
|
|
554
|
+
["Modules", MODULES.filter((m) => selection[m.id]).map((m) => m.title).join(" · ") || "none"],
|
|
555
|
+
// What leaves the machine is said before the key that agrees to it.
|
|
556
|
+
...MODULES.filter((m) => m.needsSignIn && selection[m.id]).map((m) => [`${m.title[0].toUpperCase()}${m.title.slice(1)}`, `${m.summary} · free account`]),
|
|
557
|
+
["Changes", plan.lines.length === 0 ? "nothing: this is already set up" : changes.join(" · ") || "runs only"],
|
|
558
|
+
];
|
|
559
|
+
}
|
|
560
|
+
function cancelled(out, c) {
|
|
561
|
+
out.write(`${PAD}${c.dim("Cancelled. Nothing changed.")}\n`);
|
|
562
|
+
return { confirmed: false, cancelled: true, ok: true };
|
|
563
|
+
}
|
|
564
|
+
// A legacy Windows console (conhost on a raster font) has none of these
|
|
565
|
+
// glyphs; Windows Terminal and the VS Code terminal do.
|
|
566
|
+
function glyphs() {
|
|
567
|
+
const plain = process.platform === "win32" && !process.env.WT_SESSION && process.env.TERM_PROGRAM !== "vscode";
|
|
568
|
+
return plain
|
|
569
|
+
? { on: "[x]", off: "[ ]", pointer: ">", dot: "*", spin: ["|", "/", "-", "\\"] }
|
|
570
|
+
: { on: "◼", off: "◻", pointer: "›", dot: "●", spin: [..."⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"] };
|
|
571
|
+
}
|
|
572
|
+
function clip(text, width) {
|
|
573
|
+
return text.length > width ? `${text.slice(0, Math.max(0, width - 1))}…` : text;
|
|
574
|
+
}
|
|
575
|
+
// One line that work in progress rewrites. `say` prints a finished line above
|
|
576
|
+
// it. Without a terminal to redraw in, each update is its own line.
|
|
577
|
+
function spinner(out, c, animate, pad = "") {
|
|
578
|
+
const frames = glyphs().spin;
|
|
579
|
+
let frame = 0;
|
|
580
|
+
let text = "";
|
|
581
|
+
let timer;
|
|
582
|
+
const erase = () => { if (animate && text)
|
|
583
|
+
out.write("\r\x1b[2K"); };
|
|
584
|
+
const draw = () => out.write(`\r\x1b[2K${pad}${c.accent(frames[frame++ % frames.length])} ${c.dim(clip(text, Math.max(20, (out.columns || 80) - 3 - pad.length)))}`);
|
|
585
|
+
return {
|
|
586
|
+
show(next) {
|
|
587
|
+
if (!animate)
|
|
588
|
+
return void out.write(`${next}\n`);
|
|
589
|
+
text = next;
|
|
590
|
+
draw();
|
|
591
|
+
timer ??= setInterval(draw, 80);
|
|
592
|
+
timer.unref?.();
|
|
593
|
+
},
|
|
594
|
+
say(line) {
|
|
595
|
+
erase();
|
|
596
|
+
out.write(`${line}\n`);
|
|
597
|
+
if (animate && text)
|
|
598
|
+
draw();
|
|
599
|
+
},
|
|
600
|
+
stop() {
|
|
601
|
+
if (timer)
|
|
602
|
+
clearInterval(timer);
|
|
603
|
+
timer = undefined;
|
|
604
|
+
erase();
|
|
605
|
+
text = "";
|
|
606
|
+
},
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
function colors(out) {
|
|
610
|
+
const on = Boolean(out.isTTY) && !process.env.NO_COLOR;
|
|
611
|
+
const paint = (code) => (s) => on ? `\x1b[${code}m${s}\x1b[0m` : s;
|
|
612
|
+
// accent: the statusline badge's orange.
|
|
613
|
+
return { bold: paint("1"), dim: paint("2"), under: paint("4"), cyan: paint("36"), green: paint("32"), yellow: paint("33"), red: paint("31"), accent: paint("38;5;172") };
|
|
614
|
+
}
|
|
615
|
+
// Keys typed before a prompt is on screen (an Enter hit twice while the plan
|
|
616
|
+
// was computed) are dropped, so nothing is ever answered unseen.
|
|
617
|
+
function keys(input, onKey) {
|
|
618
|
+
emitKeypressEvents(input);
|
|
619
|
+
while (input.read() !== null)
|
|
620
|
+
;
|
|
621
|
+
input.setRawMode?.(true);
|
|
622
|
+
input.resume();
|
|
623
|
+
const handler = (_, key) => onKey(key ?? {});
|
|
624
|
+
input.on("keypress", handler);
|
|
625
|
+
return () => {
|
|
626
|
+
input.off("keypress", handler);
|
|
627
|
+
input.setRawMode?.(false);
|
|
628
|
+
input.pause();
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
function live(out, render, onKey, input, onCancel) {
|
|
632
|
+
return new Promise((resolve) => {
|
|
633
|
+
let rows = 0;
|
|
634
|
+
const draw = (active) => {
|
|
635
|
+
// No lines: the frame is taken off the screen (a view that gives way to the next).
|
|
636
|
+
const lines = render(active).map((line) => line ? `${PAD}${line}` : line);
|
|
637
|
+
out.write(`${rows > 1 ? `\r\x1b[${rows - 1}A` : "\r"}\x1b[J${lines.join("\n")}`);
|
|
638
|
+
rows = lines.length;
|
|
639
|
+
};
|
|
640
|
+
let finished = false;
|
|
641
|
+
// The cursor comes back however the process ends, a kill included.
|
|
642
|
+
const restore = () => out.write("\x1b[?25h");
|
|
643
|
+
const onSignal = (signal) => {
|
|
644
|
+
restore();
|
|
645
|
+
input.setRawMode?.(false);
|
|
646
|
+
process.kill(process.pid, signal);
|
|
647
|
+
};
|
|
648
|
+
process.once("exit", restore);
|
|
649
|
+
process.once("SIGTERM", onSignal);
|
|
650
|
+
process.once("SIGHUP", onSignal);
|
|
651
|
+
out.write("\x1b[?25l");
|
|
652
|
+
draw(true);
|
|
653
|
+
const finish = (ok) => {
|
|
654
|
+
finished = true;
|
|
655
|
+
process.off("exit", restore);
|
|
656
|
+
process.off("SIGTERM", onSignal);
|
|
657
|
+
process.off("SIGHUP", onSignal);
|
|
658
|
+
stop();
|
|
659
|
+
draw(false);
|
|
660
|
+
out.write(`${rows ? "\n" : ""}\x1b[?25h`);
|
|
661
|
+
resolve(ok);
|
|
662
|
+
};
|
|
663
|
+
const stop = keys(input, (key) => {
|
|
664
|
+
if (finished)
|
|
665
|
+
return;
|
|
666
|
+
if (key.name === "escape" || (key.ctrl && key.name === "c")) {
|
|
667
|
+
onCancel?.();
|
|
668
|
+
return finish(false);
|
|
669
|
+
}
|
|
670
|
+
onKey(key, () => finish(true));
|
|
671
|
+
if (!finished)
|
|
672
|
+
draw(true);
|
|
673
|
+
});
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
// `gone`: once answered, the picker leaves the screen (a cancelled one stays).
|
|
677
|
+
function toggle(input, out, c, title, layout, items, gone = false) {
|
|
678
|
+
let left = false;
|
|
679
|
+
const enabled = items.map((item, i) => item.disabled ? -1 : i).filter((i) => i >= 0);
|
|
680
|
+
let at = 0;
|
|
681
|
+
const width = () => Math.max(20, (out.columns || 80) - 1 - PAD.length);
|
|
682
|
+
const labelWidth = Math.max(0, ...items.map((item) => item.label.length)) + 3;
|
|
683
|
+
const g = glyphs();
|
|
684
|
+
const box = (item) => item.on ? g.on : g.off;
|
|
685
|
+
const render = (active) => {
|
|
686
|
+
if (!active && gone && !left)
|
|
687
|
+
return [];
|
|
688
|
+
const current = active ? enabled[at] : -1;
|
|
689
|
+
if (layout === "column") {
|
|
690
|
+
return [title, ...items.map((item, i) => {
|
|
691
|
+
const label = item.label.padEnd(labelWidth);
|
|
692
|
+
const hint = (item.hint ?? "").slice(0, Math.max(0, width() - 3 - labelWidth));
|
|
693
|
+
return `${i === current ? c.accent(g.pointer) : " "}${box(item)} ${i === current ? c.accent(label) : label}${c.dim(hint)}`;
|
|
694
|
+
})];
|
|
695
|
+
}
|
|
696
|
+
// Agents that are not installed share one dimmed entry at the end.
|
|
697
|
+
const missing = items.filter((item) => item.disabled).map((item) => item.label);
|
|
698
|
+
const cells = items.flatMap((item, i) => item.disabled ? [] : [{ text: `${box(item)} ${item.label}`, hot: i === current }]);
|
|
699
|
+
if (missing.length)
|
|
700
|
+
cells.push({ text: `${g.off} ${missing.join(", ")} (not installed)`, hot: false });
|
|
701
|
+
const lines = [title];
|
|
702
|
+
let line = "";
|
|
703
|
+
let length = 0;
|
|
704
|
+
for (const cell of cells) {
|
|
705
|
+
if (length > 0 && length + 3 + cell.text.length > width()) {
|
|
706
|
+
lines.push(line);
|
|
707
|
+
line = "";
|
|
708
|
+
length = 0;
|
|
709
|
+
}
|
|
710
|
+
const styled = cell.hot ? c.accent(cell.text) : cell.text.endsWith("(not installed)") ? c.dim(cell.text) : cell.text;
|
|
711
|
+
line += `${length === 0 ? " " : " "}${styled}`;
|
|
712
|
+
length += (length === 0 ? 1 : 3) + cell.text.length;
|
|
713
|
+
}
|
|
714
|
+
lines.push(line);
|
|
715
|
+
return lines;
|
|
716
|
+
};
|
|
717
|
+
if (enabled.length === 0) {
|
|
718
|
+
if (!gone)
|
|
719
|
+
out.write(`${indent(render(false).join("\n"))}\n`);
|
|
720
|
+
return Promise.resolve(items.map((item) => item.on));
|
|
721
|
+
}
|
|
722
|
+
return live(out, render, (key, done) => {
|
|
723
|
+
if (key.name === "return" || key.name === "enter")
|
|
724
|
+
return done();
|
|
725
|
+
if (key.name === "space") {
|
|
726
|
+
const item = items[enabled[at]];
|
|
727
|
+
item.on = !item.on;
|
|
728
|
+
}
|
|
729
|
+
else if (["up", "left", "k", "h"].includes(key.name ?? "") || (key.name === "tab" && key.shift)) {
|
|
730
|
+
at = (at - 1 + enabled.length) % enabled.length;
|
|
731
|
+
}
|
|
732
|
+
else if (["down", "right", "j", "l", "tab"].includes(key.name ?? "")) {
|
|
733
|
+
at = (at + 1) % enabled.length;
|
|
734
|
+
}
|
|
735
|
+
}, input, () => { left = true; }).then((ok) => ok ? items.map((item) => item.on) : null);
|
|
736
|
+
}
|
|
737
|
+
// A Yes within the first moments after the question draws is the tail of a
|
|
738
|
+
// double-tapped Enter, not an answer to a plan nobody has read yet.
|
|
739
|
+
const CONFIRM_GRACE_MS = 400;
|
|
740
|
+
function confirm(input, out, c, question) {
|
|
741
|
+
let yes = true;
|
|
742
|
+
const shownAt = Date.now();
|
|
743
|
+
const pointer = c.dim(glyphs().pointer);
|
|
744
|
+
const render = (active) => [active
|
|
745
|
+
? `${question} ${pointer} ${yes ? c.accent(c.bold("Yes")) : c.dim("Yes")} ${c.dim("/")} ${yes ? c.dim("No") : c.accent(c.bold("No"))}`
|
|
746
|
+
: `${question} ${pointer} ${yes ? "Yes" : "No"}`];
|
|
747
|
+
return live(out, render, (key, done) => {
|
|
748
|
+
const early = Date.now() - shownAt < CONFIRM_GRACE_MS;
|
|
749
|
+
if (early && (key.name === "y" || key.name === "return" || key.name === "enter"))
|
|
750
|
+
return;
|
|
751
|
+
if (key.name === "y") {
|
|
752
|
+
yes = true;
|
|
753
|
+
return done();
|
|
754
|
+
}
|
|
755
|
+
if (key.name === "n") {
|
|
756
|
+
yes = false;
|
|
757
|
+
return done();
|
|
758
|
+
}
|
|
759
|
+
if (key.name === "return" || key.name === "enter")
|
|
760
|
+
return done();
|
|
761
|
+
if (["left", "right", "tab", "h", "l", "up", "down"].includes(key.name ?? ""))
|
|
762
|
+
yes = !yes;
|
|
763
|
+
// Esc leaves the question showing No, never a Yes that did not happen.
|
|
764
|
+
}, input, () => { yes = false; }).then((ok) => ok ? yes : null);
|
|
765
|
+
}
|
|
766
|
+
// The whole first screen: what setup will do, and the one key that does it.
|
|
767
|
+
// `k` ticks the found API keys (off until then); Customize and Details return
|
|
768
|
+
// here.
|
|
769
|
+
function choose(input, out, c, rows, found, primary) {
|
|
770
|
+
const options = [
|
|
771
|
+
{ id: "go", label: primary },
|
|
772
|
+
{ id: "customize", label: "Customize" },
|
|
773
|
+
{ id: "details", label: "Details" },
|
|
774
|
+
{ id: "no", label: "Not now" },
|
|
775
|
+
];
|
|
776
|
+
const g = glyphs();
|
|
777
|
+
let at = 0;
|
|
778
|
+
let left = false;
|
|
779
|
+
const gaveWay = () => !left && (options[at].id === "customize" || options[at].id === "details");
|
|
780
|
+
const shownAt = Date.now();
|
|
781
|
+
const width = () => Math.max(20, (out.columns || 80) - 1 - PAD.length);
|
|
782
|
+
const render = (active) => {
|
|
783
|
+
const lines = [c.bold("Setup"), ...rows.map(([label, value]) => ` ${c.dim(label.padEnd(10))}${clip(value, width() - 12)}`)];
|
|
784
|
+
if (found.length) {
|
|
785
|
+
// The count and what it costs come first: a long list is clipped at its end.
|
|
786
|
+
const text = found.length === 1
|
|
787
|
+
? `let Auto spend on ${found[0].env}`
|
|
788
|
+
: `let Auto spend on ${found.length} keys · ${found.map((key) => key.env).join(", ")}`;
|
|
789
|
+
const on = found.filter((key) => key.on);
|
|
790
|
+
// `off --all` (the Changes row's undo) leaves a stored key in place.
|
|
791
|
+
const undo = on.length ? ` · undo: ${on.map((key) => `caveman providers remove ${key.id}`).join(" · ")}` : "";
|
|
792
|
+
lines.push(` ${c.dim("Keys".padEnd(10))}${on.length ? c.accent(g.on) : g.off} ${clip(text + undo, width() - 14 - g.on.length)}`);
|
|
793
|
+
}
|
|
794
|
+
// Customize and Details take this screen's place and bring it back after.
|
|
795
|
+
if (!active)
|
|
796
|
+
return gaveWay() ? [] : [...lines, "", `${c.dim(g.pointer)} ${options[at].label}`];
|
|
797
|
+
// The letter that picks an option is underlined in it.
|
|
798
|
+
const label = (option, i) => i === 0 ? option.label : `${c.under(option.label[0])}${option.label.slice(1)}`;
|
|
799
|
+
return [
|
|
800
|
+
...lines,
|
|
801
|
+
"",
|
|
802
|
+
// A row that wraps breaks the redraw: a narrow terminal shows the current
|
|
803
|
+
// choice alone, and the arrows still move through all four.
|
|
804
|
+
width() < 48
|
|
805
|
+
? c.accent(c.bold(`${g.pointer} ${options[at].label}`))
|
|
806
|
+
: options.map((option, i) => i === at ? c.accent(c.bold(`${g.pointer} ${option.label}`)) : ` ${label(option, i)}`).join(" "),
|
|
807
|
+
c.dim(clip(`enter selects${found.length ? " · k keys" : ""} · esc cancels`, width())),
|
|
808
|
+
];
|
|
809
|
+
};
|
|
810
|
+
return live(out, render, (key, done) => {
|
|
811
|
+
const name = key.name ?? "";
|
|
812
|
+
// The tail of a double-tapped Enter is not a Yes to a plan nobody has read.
|
|
813
|
+
const early = Date.now() - shownAt < CONFIRM_GRACE_MS;
|
|
814
|
+
if (name === "return" || name === "enter")
|
|
815
|
+
return early && at === 0 ? undefined : done();
|
|
816
|
+
if (name === "y") {
|
|
817
|
+
if (early)
|
|
818
|
+
return;
|
|
819
|
+
at = 0;
|
|
820
|
+
return done();
|
|
821
|
+
}
|
|
822
|
+
const hot = { c: 1, d: 2, n: 3 }[name];
|
|
823
|
+
if (hot !== undefined) {
|
|
824
|
+
at = hot;
|
|
825
|
+
return done();
|
|
826
|
+
}
|
|
827
|
+
if (name === "k" && found.length) {
|
|
828
|
+
const on = !found.some((item) => item.on);
|
|
829
|
+
for (const item of found)
|
|
830
|
+
item.on = on;
|
|
831
|
+
}
|
|
832
|
+
else if (["left", "up", "h"].includes(name) || (name === "tab" && key.shift)) {
|
|
833
|
+
at = (at - 1 + options.length) % options.length;
|
|
834
|
+
}
|
|
835
|
+
else if (["right", "down", "l", "tab"].includes(name)) {
|
|
836
|
+
at = (at + 1) % options.length;
|
|
837
|
+
}
|
|
838
|
+
}, input, () => { left = true; }).then((ok) => ok ? options[at].id : null);
|
|
839
|
+
}
|
|
840
|
+
// Customize: the module, agent and key pickers in turn; null when cancelled.
|
|
841
|
+
async function customize(input, out, c, selection, agents, found, usable, missing) {
|
|
842
|
+
const modules = await toggle(input, out, c, `Modules ${c.dim("· space toggles, enter continues")}`, "column", MODULES.map((m) => ({ label: m.title, hint: m.needsSignIn ? `${m.summary} · free account` : m.summary, on: selection[m.id] })), true);
|
|
843
|
+
if (!modules)
|
|
844
|
+
return null;
|
|
845
|
+
const picked = Object.fromEntries(MODULES.map((m, i) => [m.id, modules[i]]));
|
|
846
|
+
const shown = [...usable, ...missing];
|
|
847
|
+
if (shown.length > 0) {
|
|
848
|
+
const ticked = await toggle(input, out, c, `Agents ${c.dim("· space toggles, enter continues")}`, "row", shown.map((a) => ({ label: a.name, on: agents.includes(a.id), disabled: missing.includes(a) })), true);
|
|
849
|
+
if (!ticked)
|
|
850
|
+
return null;
|
|
851
|
+
agents = shown.filter((_, i) => ticked[i]).map((a) => a.id);
|
|
852
|
+
}
|
|
853
|
+
if (found.length > 0) {
|
|
854
|
+
const ticked = await toggle(input, out, c, `Keys for Auto ${c.dim("· Auto can spend on a key it is given")}`, "column", found.map((key) => ({ label: key.env, hint: key.name, on: key.on })), true);
|
|
855
|
+
if (!ticked)
|
|
856
|
+
return null;
|
|
857
|
+
found.forEach((key, i) => { key.on = ticked[i]; });
|
|
858
|
+
}
|
|
859
|
+
return { selection: picked, agents };
|
|
860
|
+
}
|