wachiman 1.14.0 → 1.15.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.
- package/README.md +1 -1
- package/package.json +4 -2
- package/src/accounts/confirm.ts +62 -3
- package/src/cli.ts +107 -122
- package/src/engine.ts +14 -0
- package/src/help.ts +555 -0
- package/src/init/options.ts +1 -1
- package/src/init/run.ts +43 -17
- package/src/ledger-read/command.ts +106 -0
- package/src/ledger-read/credentials.ts +103 -0
- package/src/ledger-read/files.ts +141 -0
- package/src/ledger-read/pull.ts +69 -0
- package/src/ledger-read/rows.ts +60 -0
- package/src/ledger-read/types.ts +127 -0
- package/src/ledger.ts +34 -18
- package/src/setup/run.ts +27 -10
- package/src/spend/report.ts +349 -0
- package/src/status/command.ts +150 -36
- package/src/store/command.ts +20 -3
- package/src/store/html.ts +205 -8
- package/src/store/index.ts +64 -5
- package/src/store/rows.ts +103 -0
- package/src/wizard/interactive.ts +11 -0
- package/src/wizard/launcher.ts +340 -0
- package/src/wizard/load.ts +30 -0
- package/src/wizard/mascot.ts +223 -0
- package/src/wizard/prompt-fancy.ts +127 -0
- package/src/wizard/prompt.ts +95 -61
- package/src/wizard/style.ts +93 -13
- package/src/wizard/tone.ts +11 -0
- package/src/wizard/ui.ts +78 -0
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The interactive launcher: bare `wachiman` on a terminal opens a menu instead of printing the
|
|
3
|
+
* help. It collects what a command needs (the scope, a base, a question), shows the equivalent
|
|
4
|
+
* command line, and hands over to the real command through `dispatch`; it holds no review logic.
|
|
5
|
+
*
|
|
6
|
+
* It opens only when stdin, stdout and stderr are terminals and `CI` is unset. Anything else keeps
|
|
7
|
+
* the old behavior of a bare `wachiman`.
|
|
8
|
+
*
|
|
9
|
+
* Nothing runs before the person confirms. For a command that spends the Claude subscription (a
|
|
10
|
+
* review, an answer, a loop round) the confirmation first shows the repository, the scope, the
|
|
11
|
+
* profile and the command. The prompt session is closed before `dispatch`, so the command owns the
|
|
12
|
+
* terminal. The exception is `init` and `setup`: they are wizards of their own, so the launcher
|
|
13
|
+
* leaves the session frame open and the command's own outro closes it.
|
|
14
|
+
*
|
|
15
|
+
* The menus are Clack's, through the prompt wrapper in `./prompt.ts`; the launcher holds no
|
|
16
|
+
* terminal code of its own.
|
|
17
|
+
*/
|
|
18
|
+
import { UsageError } from "../config";
|
|
19
|
+
import { spawnGit, type GitRunner } from "../evidence";
|
|
20
|
+
import { projectShow } from "../accounts/commands";
|
|
21
|
+
import { repositoryKey } from "../history/store";
|
|
22
|
+
import { quoteArgument } from "./command";
|
|
23
|
+
import { shouldLaunch, type LauncherStreams } from "./interactive";
|
|
24
|
+
import { openPrompter, type Choice, type Outcome, type Prompter, type PromptIO } from "./prompt";
|
|
25
|
+
|
|
26
|
+
export { shouldLaunch, type LauncherStreams } from "./interactive";
|
|
27
|
+
|
|
28
|
+
export type Scope =
|
|
29
|
+
| { kind: "branch"; base: string }
|
|
30
|
+
| { kind: "commit"; commit: string }
|
|
31
|
+
| { kind: "staged" }
|
|
32
|
+
| { kind: "tree" };
|
|
33
|
+
|
|
34
|
+
/** The flags of `local`, `ask` and `loop` that select what is looked at. */
|
|
35
|
+
export function scopeArgs(scope: Scope): string[] {
|
|
36
|
+
switch (scope.kind) {
|
|
37
|
+
case "branch":
|
|
38
|
+
return ["--base", scope.base];
|
|
39
|
+
case "commit":
|
|
40
|
+
return ["--commit", scope.commit];
|
|
41
|
+
case "staged":
|
|
42
|
+
return ["--working-tree", "staged"];
|
|
43
|
+
case "tree":
|
|
44
|
+
return ["--working-tree", "all"];
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function scopeLabel(scope: Scope): string {
|
|
49
|
+
switch (scope.kind) {
|
|
50
|
+
case "branch":
|
|
51
|
+
return `this branch against ${scope.base}`;
|
|
52
|
+
case "commit":
|
|
53
|
+
return `the commit ${scope.commit}`;
|
|
54
|
+
case "staged":
|
|
55
|
+
return "the staged changes";
|
|
56
|
+
case "tree":
|
|
57
|
+
return "all uncommitted changes in the working tree";
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export type Action =
|
|
62
|
+
| "review"
|
|
63
|
+
| "ask"
|
|
64
|
+
| "loop-start"
|
|
65
|
+
| "loop-continue"
|
|
66
|
+
| "history"
|
|
67
|
+
| "status"
|
|
68
|
+
| "dashboard"
|
|
69
|
+
| "setup"
|
|
70
|
+
| "init"
|
|
71
|
+
| "doctor"
|
|
72
|
+
| "profile"
|
|
73
|
+
| "skills";
|
|
74
|
+
|
|
75
|
+
/** What each menu entry runs. The scope, base and question come from the questions asked before. */
|
|
76
|
+
export function commandArgs(action: Action, o: { scope?: Scope; question?: string; base?: string } = {}): string[] {
|
|
77
|
+
switch (action) {
|
|
78
|
+
case "review":
|
|
79
|
+
return ["local", ...(o.scope ? scopeArgs(o.scope) : [])];
|
|
80
|
+
case "ask":
|
|
81
|
+
return ["ask", ...(o.question ? [o.question] : []), ...(o.scope ? scopeArgs(o.scope) : [])];
|
|
82
|
+
case "loop-start":
|
|
83
|
+
return ["loop", "--base", o.base ?? ""];
|
|
84
|
+
case "loop-continue":
|
|
85
|
+
return ["loop"];
|
|
86
|
+
case "profile":
|
|
87
|
+
return ["profile", "list"];
|
|
88
|
+
case "skills":
|
|
89
|
+
return ["skills", "install"];
|
|
90
|
+
default:
|
|
91
|
+
return [action];
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Only these call `claude` on the subscription. */
|
|
96
|
+
export const SPENDING: ReadonlySet<Action> = new Set<Action>(["review", "ask", "loop-start", "loop-continue"]);
|
|
97
|
+
|
|
98
|
+
/** The command as someone would type it. */
|
|
99
|
+
export const commandLine = (argv: string[]) => ["wachiman", ...argv].map((a) => quoteArgument(a, "posix")).join(" ");
|
|
100
|
+
|
|
101
|
+
/** The branch a change is compared against: origin's default branch, else the first of origin/main, main, origin/master, master that exists. */
|
|
102
|
+
export function detectBase(cwd: string, git: GitRunner = spawnGit): string | undefined {
|
|
103
|
+
const run = (args: string[]) => git(args, { cwd, timeoutMs: 10_000 });
|
|
104
|
+
const head = run(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]);
|
|
105
|
+
if (head.status === 0 && head.stdout.trim() !== "") return head.stdout.trim();
|
|
106
|
+
return ["origin/main", "main", "origin/master", "master"].find((ref) => run(["rev-parse", "--verify", "--quiet", ref]).status === 0);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The branches a change can be compared against: local and remote, the detected base first, `HEAD` and the symbolic `origin/HEAD` left out. */
|
|
110
|
+
export function listRefs(cwd: string, base: string | undefined, git: GitRunner = spawnGit): string[] {
|
|
111
|
+
const out = git(["for-each-ref", "--format=%(refname:short)", "--sort=-committerdate", "refs/heads", "refs/remotes"], { cwd, timeoutMs: 10_000 });
|
|
112
|
+
if (out.status !== 0) return base ? [base] : [];
|
|
113
|
+
const refs = out.stdout.split("\n").map((r) => r.trim()).filter((r) => r !== "" && r !== "origin" && !r.endsWith("/HEAD"));
|
|
114
|
+
return [...new Set([...(base ? [base] : []), ...refs])];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface LauncherDeps {
|
|
118
|
+
env: Record<string, string | undefined>;
|
|
119
|
+
version: string;
|
|
120
|
+
/** Runs a command the way `wachiman <argv>` would, and returns its exit code. */
|
|
121
|
+
dispatch: (argv: string[]) => Promise<number>;
|
|
122
|
+
streams?: LauncherStreams;
|
|
123
|
+
promptIO?: PromptIO;
|
|
124
|
+
/** An open prompt session, for a test of the terminal flow; otherwise one is opened over `promptIO` or the terminal. */
|
|
125
|
+
prompter?: Prompter;
|
|
126
|
+
cwd?: string;
|
|
127
|
+
git?: GitRunner;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** `undefined` when the launcher does not apply (the caller keeps its old behavior). */
|
|
131
|
+
export async function maybeLaunch(deps: LauncherDeps): Promise<number | undefined> {
|
|
132
|
+
const streams = deps.streams ?? { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr };
|
|
133
|
+
if (!shouldLaunch(deps.env, streams)) return undefined;
|
|
134
|
+
return runLauncher(deps);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
type Top = "review" | "ask" | "loop" | "findings" | "configure" | "exit";
|
|
138
|
+
type Back = "back";
|
|
139
|
+
|
|
140
|
+
const TOP: Choice<Top>[] = [
|
|
141
|
+
{ label: "Review changes", value: "review" },
|
|
142
|
+
{ label: "Ask about changes", value: "ask" },
|
|
143
|
+
{ label: "Review loop", value: "loop" },
|
|
144
|
+
{ label: "Findings & usage", value: "findings", description: "history, status, dashboard" },
|
|
145
|
+
{ label: "Configure", value: "configure", description: "setup, init, doctor, profile, skills" },
|
|
146
|
+
{ label: "Exit", value: "exit" },
|
|
147
|
+
];
|
|
148
|
+
|
|
149
|
+
const SCOPES: Choice<Scope["kind"]>[] = [
|
|
150
|
+
{ label: "This branch against its base", value: "branch" },
|
|
151
|
+
{ label: "One commit", value: "commit" },
|
|
152
|
+
{ label: "Staged changes", value: "staged" },
|
|
153
|
+
{ label: "All working-tree changes", value: "tree" },
|
|
154
|
+
];
|
|
155
|
+
|
|
156
|
+
const FINDINGS: Choice<Action | Back>[] = [
|
|
157
|
+
{ label: "History of findings", value: "history" },
|
|
158
|
+
{ label: "Status and estimated cost", value: "status" },
|
|
159
|
+
{ label: "Dashboard (an HTML page)", value: "dashboard" },
|
|
160
|
+
{ label: "Back", value: "back" },
|
|
161
|
+
];
|
|
162
|
+
|
|
163
|
+
const CONFIGURE: Choice<Action | Back>[] = [
|
|
164
|
+
{ label: "Set up this repository", value: "setup", description: "bind it to a Claude account profile" },
|
|
165
|
+
{ label: "Write the GitHub workflow", value: "init" },
|
|
166
|
+
{ label: "Doctor", value: "doctor", description: "check what a local run would use" },
|
|
167
|
+
{ label: "Account profiles", value: "profile" },
|
|
168
|
+
{ label: "Agent skills", value: "skills", description: "install the wachiman-review skills" },
|
|
169
|
+
{ label: "Back", value: "back" },
|
|
170
|
+
];
|
|
171
|
+
|
|
172
|
+
/** A ref or a commit: not empty, and not something `git` or the CLI would read as a flag. */
|
|
173
|
+
const refProblem = (what: string) => (v: string) => (v === "" ? `${what} is required.` : v.startsWith("-") ? `${what} cannot start with a dash.` : undefined);
|
|
174
|
+
|
|
175
|
+
interface Plan {
|
|
176
|
+
action: Action;
|
|
177
|
+
argv: string[];
|
|
178
|
+
scope?: Scope;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export async function runLauncher(deps: LauncherDeps): Promise<number> {
|
|
182
|
+
const { env, version } = deps;
|
|
183
|
+
const cwd = deps.cwd ?? process.cwd();
|
|
184
|
+
const prompter = deps.prompter ?? (await openPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr }, env));
|
|
185
|
+
const finish = (code: number, outcome: Outcome = "done", message?: string) => {
|
|
186
|
+
// The prompt session ends before the command starts: it takes the terminal for itself.
|
|
187
|
+
prompter.close(outcome, message);
|
|
188
|
+
return code;
|
|
189
|
+
};
|
|
190
|
+
try {
|
|
191
|
+
await prompter.intro(version);
|
|
192
|
+
const context = repoContext(cwd, env, deps.git);
|
|
193
|
+
prompter.say(context.line, "muted");
|
|
194
|
+
|
|
195
|
+
for (;;) {
|
|
196
|
+
prompter.say("");
|
|
197
|
+
const top = await prompter.select<Top>("What would you like to do?", TOP, 0);
|
|
198
|
+
if (top === null) return finish(cancelled(prompter), "cancelled", NOTHING_RAN);
|
|
199
|
+
if (top === "exit") return finish(0);
|
|
200
|
+
if ((top === "review" || top === "ask" || top === "loop") && !context.name) {
|
|
201
|
+
// Fail before the scope, base and question prompts: none of these can run outside a clone.
|
|
202
|
+
prompter.say("This needs a git repository. Run wachiman from inside a clone.", "error");
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
const plan = await planFor(top, prompter, { cwd, git: deps.git, context });
|
|
206
|
+
if (plan === "back") continue;
|
|
207
|
+
if (plan === null) return finish(cancelled(prompter), "cancelled", NOTHING_RAN);
|
|
208
|
+
|
|
209
|
+
const line = commandLine(plan.argv);
|
|
210
|
+
if (SPENDING.has(plan.action) || plan.action === "skills") {
|
|
211
|
+
const rows: [string, string][] = SPENDING.has(plan.action)
|
|
212
|
+
? [["repository", context.name ?? "-"], ["scope", plan.scope ? scopeLabel(plan.scope) : "the open loop"], ["profile", context.profile], ["command", line]]
|
|
213
|
+
: [["command", line]];
|
|
214
|
+
const cost = SPENDING.has(plan.action) ? "It runs your signed-in Claude and counts against your subscription." : "It copies the skills into ~/.agents/skills and each Claude Code config directory.";
|
|
215
|
+
if (prompter.fancy) prompter.note([...rows.map(([k, v]) => `${k.padEnd(10)} ${v}`), "", cost].join("\n"), SPENDING.has(plan.action) ? "Ready to run" : "Ready to install");
|
|
216
|
+
else {
|
|
217
|
+
prompter.say("");
|
|
218
|
+
for (const [k, v] of rows) prompter.say(` ${k.padEnd(10)} ${v}`);
|
|
219
|
+
prompter.say(` ${cost}`, "muted");
|
|
220
|
+
}
|
|
221
|
+
const go = await prompter.confirm(SPENDING.has(plan.action) ? "Run it?" : "Install them?", true);
|
|
222
|
+
if (go === null) return finish(cancelled(prompter), "cancelled", NOTHING_RAN);
|
|
223
|
+
if (!go) {
|
|
224
|
+
prompter.say("Nothing was run.", "muted");
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
} else if (!prompter.fancy) prompter.say(` ${line}`, "muted");
|
|
228
|
+
if (SESSION_COMMANDS.has(plan.action)) prompter.suspend();
|
|
229
|
+
else prompter.close("done", prompter.fancy ? `Running ${line}` : undefined);
|
|
230
|
+
return await deps.dispatch(plan.argv);
|
|
231
|
+
}
|
|
232
|
+
} catch (error) {
|
|
233
|
+
prompter.close("failed");
|
|
234
|
+
throw error;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** `init` and `setup` run a wizard of their own: the launcher leaves the session frame open for their outro. */
|
|
239
|
+
const SESSION_COMMANDS: ReadonlySet<Action> = new Set<Action>(["init", "setup"]);
|
|
240
|
+
|
|
241
|
+
const NOTHING_RAN = "Cancelled. Nothing was run.";
|
|
242
|
+
|
|
243
|
+
function cancelled(prompter: Prompter): number {
|
|
244
|
+
// The outro of a terminal session says it; a plain one needs the line.
|
|
245
|
+
if (!prompter.fancy) prompter.say("cancelled: nothing was run.", "warning");
|
|
246
|
+
return 130;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** The repository name and the profile a run here would use, for the first line and the confirmation. Never throws. */
|
|
250
|
+
function repoContext(cwd: string, env: Record<string, string | undefined>, git?: GitRunner): { name?: string; profile: string; line: string } {
|
|
251
|
+
let name: string | undefined;
|
|
252
|
+
try {
|
|
253
|
+
name = repositoryKey(cwd, git).name;
|
|
254
|
+
} catch (error) {
|
|
255
|
+
if (!(error instanceof UsageError)) throw error;
|
|
256
|
+
}
|
|
257
|
+
let profile = "unresolved";
|
|
258
|
+
if (name) {
|
|
259
|
+
try {
|
|
260
|
+
const { resolved } = projectShow(cwd, env, { git });
|
|
261
|
+
profile =
|
|
262
|
+
"error" in resolved
|
|
263
|
+
? "unresolved (run wachiman setup)"
|
|
264
|
+
: resolved.rung === "binding"
|
|
265
|
+
? resolved.profile
|
|
266
|
+
: resolved.rung === "builtIn"
|
|
267
|
+
? `${resolved.profile}, not bound to this repository`
|
|
268
|
+
: `${resolved.profile} (from ${resolved.rung})`;
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (!(error instanceof UsageError)) throw error;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return { name, profile, line: name ? `${name} · profile ${profile}` : "not inside a git repository" };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Asks what the chosen entry needs. `"back"` returns to the main menu; `null` is a cancellation. */
|
|
277
|
+
async function planFor(top: Exclude<Top, "exit">, prompter: Prompter, ctx: { cwd: string; git?: GitRunner; context: { name?: string } }): Promise<Plan | Back | null> {
|
|
278
|
+
if (top === "findings" || top === "configure") {
|
|
279
|
+
const picked = await prompter.select<Action | Back>(top === "findings" ? "Findings & usage" : "Configure", top === "findings" ? FINDINGS : CONFIGURE, 0);
|
|
280
|
+
if (picked === null) return null;
|
|
281
|
+
return picked === "back" ? "back" : { action: picked, argv: commandArgs(picked) };
|
|
282
|
+
}
|
|
283
|
+
if (top === "loop") {
|
|
284
|
+
const mode = await prompter.select<"start" | "continue" | Back>(
|
|
285
|
+
"Review loop",
|
|
286
|
+
[
|
|
287
|
+
{ label: "Start a new loop", value: "start", description: "replaces an open loop; round 1 reviews everything since the base" },
|
|
288
|
+
{ label: "Continue the open loop", value: "continue", description: "reviews only the commits since the last round" },
|
|
289
|
+
{ label: "Back", value: "back" },
|
|
290
|
+
],
|
|
291
|
+
1,
|
|
292
|
+
);
|
|
293
|
+
if (mode === null) return null;
|
|
294
|
+
if (mode === "back") return "back";
|
|
295
|
+
if (mode === "continue") return { action: "loop-continue", argv: commandArgs("loop-continue") };
|
|
296
|
+
const base = await askBase(prompter, "Base (the branch or commit the loop starts from)", ctx);
|
|
297
|
+
if (base === null) return null;
|
|
298
|
+
return { action: "loop-start", argv: commandArgs("loop-start", { base }), scope: { kind: "branch", base } };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const kind = await prompter.select<Scope["kind"]>(top === "review" ? "What should be reviewed?" : "What is the question about?", SCOPES, 0);
|
|
302
|
+
if (kind === null) return null;
|
|
303
|
+
let scope: Scope;
|
|
304
|
+
if (kind === "branch") {
|
|
305
|
+
const base = await askBase(prompter, "Base (the branch or commit this one is compared against)", ctx);
|
|
306
|
+
if (base === null) return null;
|
|
307
|
+
scope = { kind, base };
|
|
308
|
+
} else if (kind === "commit") {
|
|
309
|
+
const commit = await prompter.text("Commit", "HEAD", refProblem("The commit"));
|
|
310
|
+
if (commit === null) return null;
|
|
311
|
+
scope = { kind, commit };
|
|
312
|
+
} else scope = { kind };
|
|
313
|
+
|
|
314
|
+
if (top === "review") return { action: "review", argv: commandArgs("review", { scope }), scope };
|
|
315
|
+
const question = await prompter.text("Question (leave empty for a walkthrough of the change)", "", (v) => (v.startsWith("-") ? "Start the question with a word, not a dash." : undefined));
|
|
316
|
+
if (question === null) return null;
|
|
317
|
+
return { action: "ask", argv: commandArgs("ask", { scope, question }), scope };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
const OTHER_REF = Symbol("other-ref");
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* The base of a comparison. On a terminal with more than one branch it is a list the person filters
|
|
324
|
+
* by typing, with a last entry to type any other commit; otherwise (and always without a terminal)
|
|
325
|
+
* it is the question with the detected base as its default.
|
|
326
|
+
*/
|
|
327
|
+
async function askBase(prompter: Prompter, label: string, ctx: { cwd: string; git?: GitRunner }): Promise<string | null> {
|
|
328
|
+
const detected = detectBase(ctx.cwd, ctx.git);
|
|
329
|
+
const refs = prompter.fancy ? listRefs(ctx.cwd, detected, ctx.git) : [];
|
|
330
|
+
if (refs.length > 1) {
|
|
331
|
+
const choices: Choice<string | typeof OTHER_REF>[] = [
|
|
332
|
+
...refs.map((ref) => ({ label: ref, value: ref, ...(ref === detected ? { description: "the default base" } : {}) })),
|
|
333
|
+
{ label: "Another branch or commit…", value: OTHER_REF },
|
|
334
|
+
];
|
|
335
|
+
const picked = await prompter.autocomplete(label, choices, 0);
|
|
336
|
+
if (picked === null) return null;
|
|
337
|
+
if (picked !== OTHER_REF) return picked;
|
|
338
|
+
}
|
|
339
|
+
return prompter.text(label, detected, refProblem("The base"));
|
|
340
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loads the terminal UI of a wizard on demand. `init` and `setup` import this file, which has no
|
|
3
|
+
* import of chalk or Clack: the packages are only reached by the dynamic `import()` below, in the
|
|
4
|
+
* branch that asks questions on a terminal. A run with `--yes`, `--json`, `--dry-run`, a pipe or CI
|
|
5
|
+
* never loads them, and neither does a clone that never ran `bun install`, which gets one clear
|
|
6
|
+
* message instead of a stack trace when it asks for the terminal screens.
|
|
7
|
+
*/
|
|
8
|
+
import { UsageError } from "../config";
|
|
9
|
+
|
|
10
|
+
export type TerminalUi = Pick<typeof import("./prompt"), "openPrompter"> & Pick<typeof import("./style"), "wizardIo">;
|
|
11
|
+
|
|
12
|
+
export async function loadTerminalUi(): Promise<TerminalUi> {
|
|
13
|
+
try {
|
|
14
|
+
const [prompt, style] = await Promise.all([import("./prompt"), import("./style")]);
|
|
15
|
+
return { openPrompter: prompt.openPrompter, wizardIo: style.wizardIo };
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (isMissingPackage(error)) {
|
|
18
|
+
throw new UsageError(
|
|
19
|
+
"The terminal screens need the packages in package.json (chalk and @clack/prompts). Run `bun install` in this clone, install wachiman from npm, or pass the answers as flags with --yes.",
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Bun and Node say it with a code or with the text; either is a package that is not installed. */
|
|
27
|
+
export function isMissingPackage(error: unknown): boolean {
|
|
28
|
+
const e = error as { code?: string; message?: string } | undefined;
|
|
29
|
+
return e?.code === "ERR_MODULE_NOT_FOUND" || /Cannot find (package|module) '(chalk|@clack\/[a-z-]+|sisteransi|fast-[a-z-]+)/.test(e?.message ?? "");
|
|
30
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The intro of the interactive commands: a colored `wachiman` chip with "On watch." and the
|
|
3
|
+
* version, then Wachi, the guard: a wide rounded face with a W badge, round ◉ eyes and a small ‿ smile,
|
|
4
|
+
* with a short line typed out next to the eyes. While it types, Wachi blinks once, and it winks
|
|
5
|
+
* (one eye) when the line is done.
|
|
6
|
+
*
|
|
7
|
+
* ┌ wachiman On watch. v1.14.0
|
|
8
|
+
* │
|
|
9
|
+
* │ ╭─────────────╮
|
|
10
|
+
* │ │ W │
|
|
11
|
+
* │ │ │
|
|
12
|
+
* │ │ ◉ ◉ │ Wachi: Shift started. Let's watch this repo.
|
|
13
|
+
* │ │ ‿ │
|
|
14
|
+
* │ │ │
|
|
15
|
+
* │ ╰─────────────╯
|
|
16
|
+
*
|
|
17
|
+
* Every row of the face is 15 columns wide (13 inside: the eyes row is 3 + 1 + 5 + 1 + 3): a new row or variant must keep that sum,
|
|
18
|
+
* or the right border shifts. The art is original and lives here as data. `mascotScene` and
|
|
19
|
+
* `chipTitle` are pure, so tests read them; `playIntro` does the typing.
|
|
20
|
+
*
|
|
21
|
+
* Rules the player keeps:
|
|
22
|
+
* - The typing runs only on a real terminal with color, outside CI, and without
|
|
23
|
+
* WACHIMAN_NO_ANIMATION. Anywhere else (and with NO_COLOR or TERM=dumb) the same scene is printed
|
|
24
|
+
* at once, with no escape code but color.
|
|
25
|
+
* - Any key skips the typing; Ctrl-C ends it (the caller then cancels).
|
|
26
|
+
* - The cursor is always restored, also on an exception and on process exit.
|
|
27
|
+
*/
|
|
28
|
+
import { BRAND_HEX, colorLevel, makeChalk, terminalStyle, type Paint } from "./style";
|
|
29
|
+
import type { Ui } from "./ui";
|
|
30
|
+
|
|
31
|
+
export const NAME = "Wachi";
|
|
32
|
+
export const DEFAULT_LINE = "Shift started. Let's watch this repo.";
|
|
33
|
+
|
|
34
|
+
/** Inside width of the face; every row pads to it. */
|
|
35
|
+
export const FACE_INSIDE = 13;
|
|
36
|
+
|
|
37
|
+
export interface MascotOptions {
|
|
38
|
+
paint: Paint;
|
|
39
|
+
/** `TERM=dumb`: ASCII only. */
|
|
40
|
+
ascii: boolean;
|
|
41
|
+
columns: number;
|
|
42
|
+
/** What Wachi says. */
|
|
43
|
+
message: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Which eyes are open: both, neither (a blink) or only the left one (a wink). */
|
|
47
|
+
export type Eyes = "open" | "blink" | "wink";
|
|
48
|
+
|
|
49
|
+
export interface MascotScene {
|
|
50
|
+
/** Rows printed whole before the line that is typed. */
|
|
51
|
+
top: string[];
|
|
52
|
+
/** The start of the typed line: the eyes row with Wachi's name. Printed without a newline. */
|
|
53
|
+
lead: string;
|
|
54
|
+
/**
|
|
55
|
+
* `lead` with the eyes closed or winking, for redrawing the typed line in place. Absent on a
|
|
56
|
+
* narrow terminal, where the eyes are not on the typed line and so cannot be redrawn.
|
|
57
|
+
*/
|
|
58
|
+
leads?: Record<Eyes, string>;
|
|
59
|
+
/** The text typed after `lead`. */
|
|
60
|
+
message: string;
|
|
61
|
+
/** Rows printed whole after the typed line. */
|
|
62
|
+
bottom: string[];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Narrower than this, the line goes under the face instead of beside it. */
|
|
66
|
+
export const SIDE_BY_SIDE_COLUMNS = 66;
|
|
67
|
+
|
|
68
|
+
export function mascotScene({ paint, ascii, columns, message }: MascotOptions): MascotScene {
|
|
69
|
+
const edge = (text: string) => paint(text, "muted");
|
|
70
|
+
const g = ascii
|
|
71
|
+
? { tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|", eye: "o", shut: "-", mark: "u" }
|
|
72
|
+
: { tl: "╭", tr: "╮", bl: "╰", br: "╯", h: "─", v: "│", eye: "◉", shut: "─", mark: "‿" };
|
|
73
|
+
const border = (l: string, r: string) => edge(`${l}${g.h.repeat(FACE_INSIDE)}${r}`);
|
|
74
|
+
const center = (text: string) => {
|
|
75
|
+
const pad = (FACE_INSIDE - text.length) / 2;
|
|
76
|
+
return [" ".repeat(Math.floor(pad)), " ".repeat(Math.ceil(pad))] as const;
|
|
77
|
+
};
|
|
78
|
+
const centered = (text: string, tone: Parameters<Paint>[1]) => {
|
|
79
|
+
const [l, r] = center(text);
|
|
80
|
+
return `${edge(g.v)}${l}${paint(text, tone)}${r}${edge(g.v)}`;
|
|
81
|
+
};
|
|
82
|
+
const badge = centered("W", "warning");
|
|
83
|
+
const open = paint(g.eye, "strong");
|
|
84
|
+
const shut = paint(g.shut, "strong");
|
|
85
|
+
const eyesRow = (left: string, right: string) => `${edge(g.v)} ${left} ${right} ${edge(g.v)}`;
|
|
86
|
+
const eyes = eyesRow(open, open);
|
|
87
|
+
const blank = `${edge(g.v)}${" ".repeat(FACE_INSIDE)}${edge(g.v)}`;
|
|
88
|
+
const mark = centered(g.mark, "brand");
|
|
89
|
+
const name = `${paint(`${NAME}:`, "brand")} `;
|
|
90
|
+
const top = [border(g.tl, g.tr), badge, blank];
|
|
91
|
+
const bottom = [mark, blank, border(g.bl, g.br)];
|
|
92
|
+
if (columns >= SIDE_BY_SIDE_COLUMNS) {
|
|
93
|
+
// The blink and wink redraw the line from its start with a carriage return, which only works
|
|
94
|
+
// when the line did not wrap: the 3-column row prefix, the face, the gap, the name, the text.
|
|
95
|
+
const width = ROW_PREFIX + FACE_INSIDE + 2 + 3 + NAME.length + 2 + [...message].length;
|
|
96
|
+
if (width > columns) return { top, lead: `${eyes} ${name}`, message, bottom };
|
|
97
|
+
const leads: Record<Eyes, string> = {
|
|
98
|
+
open: `${eyes} ${name}`,
|
|
99
|
+
blink: `${eyesRow(shut, shut)} ${name}`,
|
|
100
|
+
wink: `${eyesRow(open, shut)} ${name}`,
|
|
101
|
+
};
|
|
102
|
+
return { top, lead: leads.open, leads, message, bottom };
|
|
103
|
+
}
|
|
104
|
+
// A narrow terminal: the whole face first, then the line on its own row.
|
|
105
|
+
return { top: [...top, eyes, ...bottom], lead: name, message, bottom: [] };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The first line of the session: the chip, "On watch." and the version. */
|
|
109
|
+
export function chipTitle(version: string, output: { isTTY?: boolean }, env: Record<string, string | undefined>): string {
|
|
110
|
+
const c = makeChalk(output, env);
|
|
111
|
+
const chip = colorLevel(output, env) === 0 ? "wachiman" : c.bgHex(BRAND_HEX).hex("#0b1020").bold(" wachiman ");
|
|
112
|
+
return `${chip} On watch. ${terminalStyle(output, env)(`v${version}`, "muted")}`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface IntroTerminal {
|
|
116
|
+
/** stderr, the stream the prompts use. */
|
|
117
|
+
output: NodeJS.WritableStream & { isTTY?: boolean; columns?: number };
|
|
118
|
+
input: NodeJS.ReadableStream & { isTTY?: boolean; isRaw?: boolean; setRawMode?: (mode: boolean) => unknown };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Whether the typing may play; anywhere else the scene is printed at once. */
|
|
122
|
+
export function canAnimate(term: IntroTerminal, env: Record<string, string | undefined>) {
|
|
123
|
+
return (
|
|
124
|
+
term.output.isTTY === true &&
|
|
125
|
+
term.input.isTTY === true &&
|
|
126
|
+
typeof term.input.setRawMode === "function" &&
|
|
127
|
+
colorLevel(term.output, env) > 0 &&
|
|
128
|
+
!env.CI &&
|
|
129
|
+
!env.WACHIMAN_NO_ANIMATION &&
|
|
130
|
+
(term.output.columns ?? 80) >= 40
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export type IntroResult = "static" | "played" | "skipped" | "interrupted";
|
|
135
|
+
|
|
136
|
+
const HIDE = "\x1b[?25l";
|
|
137
|
+
const SHOW = "\x1b[?25h";
|
|
138
|
+
/** One character every 18 ms: the 37-character default line takes about 0.7 s. */
|
|
139
|
+
export const TYPE_MS = 18;
|
|
140
|
+
/** playIntro prints each row after the muted bar and two spaces. */
|
|
141
|
+
const ROW_PREFIX = 3;
|
|
142
|
+
/** A blink keeps both eyes shut this long. */
|
|
143
|
+
export const BLINK_MS = 140;
|
|
144
|
+
/** After the line is typed, Wachi waits this long, then winks for `WINK_MS`. */
|
|
145
|
+
export const WINK_DELAY_MS = 250;
|
|
146
|
+
export const WINK_MS = 420;
|
|
147
|
+
|
|
148
|
+
export interface IntroOptions {
|
|
149
|
+
ui: Ui;
|
|
150
|
+
term: IntroTerminal;
|
|
151
|
+
env: Record<string, string | undefined>;
|
|
152
|
+
version: string;
|
|
153
|
+
/** What Wachi says; the default is `DEFAULT_LINE`. */
|
|
154
|
+
line?: string;
|
|
155
|
+
/** Replaced in tests; the default is a timer. */
|
|
156
|
+
sleep?: (ms: number) => Promise<void>;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export async function playIntro({ ui, term, env, version, line = DEFAULT_LINE, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }: IntroOptions): Promise<IntroResult> {
|
|
160
|
+
const { output, input } = term;
|
|
161
|
+
const paint = terminalStyle(output, env);
|
|
162
|
+
const scene = mascotScene({ paint, ascii: env.TERM === "dumb", columns: output.columns ?? 80, message: line });
|
|
163
|
+
const bar = paint(env.TERM === "dumb" ? "|" : "│", "muted");
|
|
164
|
+
const row = (text: string) => `${bar} ${text}`;
|
|
165
|
+
ui.intro(chipTitle(version, output, env));
|
|
166
|
+
output.write(`${bar}\n${scene.top.map((r) => `${row(r)}\n`).join("")}`);
|
|
167
|
+
if (!canAnimate(term, env)) {
|
|
168
|
+
output.write(`${row(scene.lead)}${scene.message}\n${scene.bottom.map((r) => `${row(r)}\n`).join("")}`);
|
|
169
|
+
return "static";
|
|
170
|
+
}
|
|
171
|
+
const wasRaw = input.isRaw === true;
|
|
172
|
+
let stop: "skipped" | "interrupted" | undefined;
|
|
173
|
+
let wake: (() => void) | undefined;
|
|
174
|
+
const onData = (chunk: Buffer | string) => {
|
|
175
|
+
stop = String(chunk).includes("\u0003") ? "interrupted" : (stop ?? "skipped");
|
|
176
|
+
wake?.();
|
|
177
|
+
};
|
|
178
|
+
const restoreCursor = () => void output.write(SHOW);
|
|
179
|
+
process.once("exit", restoreCursor);
|
|
180
|
+
try {
|
|
181
|
+
input.setRawMode!(true);
|
|
182
|
+
input.on("data", onData);
|
|
183
|
+
input.resume();
|
|
184
|
+
output.write(`${HIDE}${row(scene.lead)}`);
|
|
185
|
+
await Promise.race([sleep(120), new Promise<void>((resolve) => (wake = resolve))]);
|
|
186
|
+
const chars = [...scene.message];
|
|
187
|
+
const pause = (ms: number) => Promise.race([sleep(ms), new Promise<void>((resolve) => (wake = resolve))]);
|
|
188
|
+
// Redraw the typed line in place with other eyes: carriage return, then lead and text again.
|
|
189
|
+
const face = (eyes: Eyes, text: string) => void output.write(`\r${row(scene.leads![eyes])}${text}`);
|
|
190
|
+
const blinkAt = scene.leads ? Math.floor(chars.length / 3) : -1;
|
|
191
|
+
let typed = 0;
|
|
192
|
+
for (const ch of chars) {
|
|
193
|
+
if (stop) break;
|
|
194
|
+
if (typed === blinkAt) {
|
|
195
|
+
const sofar = chars.slice(0, typed).join("");
|
|
196
|
+
face("blink", sofar);
|
|
197
|
+
await pause(BLINK_MS);
|
|
198
|
+
face("open", sofar);
|
|
199
|
+
}
|
|
200
|
+
output.write(ch);
|
|
201
|
+
typed += 1;
|
|
202
|
+
await pause(TYPE_MS);
|
|
203
|
+
}
|
|
204
|
+
// A key skipped the typing: the rest of the line appears at once.
|
|
205
|
+
output.write(chars.slice(typed).join(""));
|
|
206
|
+
if (!stop && scene.leads) {
|
|
207
|
+
await pause(WINK_DELAY_MS);
|
|
208
|
+
if (!stop) {
|
|
209
|
+
face("wink", scene.message);
|
|
210
|
+
await pause(WINK_MS);
|
|
211
|
+
face("open", scene.message);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
} finally {
|
|
215
|
+
input.off("data", onData);
|
|
216
|
+
input.setRawMode!(wasRaw);
|
|
217
|
+
input.pause();
|
|
218
|
+
output.write(`\n${SHOW}`);
|
|
219
|
+
process.off("exit", restoreCursor);
|
|
220
|
+
}
|
|
221
|
+
output.write(scene.bottom.map((r) => `${row(r)}\n`).join(""));
|
|
222
|
+
return stop ?? "played";
|
|
223
|
+
}
|