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.
@@ -0,0 +1,127 @@
1
+ /**
2
+ * What the laptop reads from the ledger (`GET /v1/entries`, ledger API contract v1). Parsed leniently
3
+ * on the fields the report uses; a response that is not the documented shape is an error, never zero.
4
+ */
5
+ export const ENTRY_STATES = ["reserved", "settled", "unsettled", "unreserved"] as const;
6
+ export type EntryState = (typeof ENTRY_STATES)[number];
7
+
8
+ export interface LedgerCall {
9
+ operation: string;
10
+ label: string;
11
+ model: string;
12
+ turns: number;
13
+ duration_ms: number;
14
+ input_tokens: number;
15
+ output_tokens: number;
16
+ cache_read_tokens: number;
17
+ cache_write_tokens: number;
18
+ /** Null when the call died without a result and its real cost is unknown. */
19
+ cost_usd: number | null;
20
+ costKnown: boolean;
21
+ terminal_reason: string | null;
22
+ auth: string;
23
+ }
24
+
25
+ export interface LedgerEntry {
26
+ id: string;
27
+ day: string;
28
+ week: string;
29
+ repository: string;
30
+ repository_id: number | string;
31
+ pr: number | null;
32
+ run_id: number | string | null;
33
+ run_attempt: number | null;
34
+ trigger: string;
35
+ forced: boolean;
36
+ state: EntryState;
37
+ reservedUsd: number;
38
+ settledUsd: number | null;
39
+ created_at: string;
40
+ settled_at: string | null;
41
+ calls: LedgerCall[];
42
+ }
43
+
44
+ export interface LedgerLimits {
45
+ dailyUsd: number | null;
46
+ weeklyUsd: number | null;
47
+ }
48
+
49
+ export interface EntriesResponse {
50
+ account: string;
51
+ limits: LedgerLimits;
52
+ entries: LedgerEntry[];
53
+ }
54
+
55
+ export const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
56
+ /** An account name becomes a directory name; anything else is refused. */
57
+ export const ACCOUNT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
58
+
59
+ const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
60
+ const num = (v: unknown, fallback = 0) => (typeof v === "number" && Number.isFinite(v) ? v : fallback);
61
+ const str = (v: unknown, fallback = "") => (typeof v === "string" ? v : fallback);
62
+ /** A number, or a string that is one (the service sends `run_attempt` as a string). */
63
+ const numOrNumericString = (v: unknown) => {
64
+ if (typeof v === "number" && Number.isFinite(v)) return v;
65
+ if (typeof v === "string" && /^\d+$/.test(v.trim())) return Number.parseInt(v, 10);
66
+ return null;
67
+ };
68
+ const nullableNum = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null);
69
+
70
+ function parseCall(raw: unknown): LedgerCall {
71
+ const c = isObject(raw) ? raw : {};
72
+ const cost = nullableNum(c.cost_usd);
73
+ return {
74
+ operation: str(c.operation),
75
+ label: str(c.label),
76
+ model: str(c.model),
77
+ turns: num(c.turns),
78
+ duration_ms: num(c.duration_ms),
79
+ input_tokens: num(c.input_tokens),
80
+ output_tokens: num(c.output_tokens),
81
+ cache_read_tokens: num(c.cache_read_tokens),
82
+ cache_write_tokens: num(c.cache_write_tokens),
83
+ cost_usd: cost,
84
+ costKnown: c.costKnown !== false && cost !== null,
85
+ terminal_reason: typeof c.terminal_reason === "string" ? c.terminal_reason : null,
86
+ auth: str(c.auth, "api-key"),
87
+ };
88
+ }
89
+
90
+ function parseEntry(raw: unknown): LedgerEntry {
91
+ if (!isObject(raw)) throw new Error("an entry is not an object");
92
+ const state = raw.state;
93
+ if (!(ENTRY_STATES as readonly unknown[]).includes(state)) throw new Error(`an entry has the unknown state ${JSON.stringify(state)}`);
94
+ if (typeof raw.id !== "string" || raw.id === "") throw new Error("an entry has no id");
95
+ if (typeof raw.day !== "string" || !DAY_PATTERN.test(raw.day)) throw new Error("an entry has no valid day");
96
+ if (typeof raw.week !== "string" || !DAY_PATTERN.test(raw.week)) throw new Error("an entry has no valid week");
97
+ return {
98
+ id: raw.id,
99
+ day: raw.day,
100
+ week: raw.week,
101
+ repository: str(raw.repository),
102
+ repository_id: typeof raw.repository_id === "number" || typeof raw.repository_id === "string" ? raw.repository_id : "",
103
+ pr: typeof raw.pr === "number" && Number.isInteger(raw.pr) ? raw.pr : null,
104
+ run_id: typeof raw.run_id === "number" || typeof raw.run_id === "string" ? raw.run_id : null,
105
+ run_attempt: numOrNumericString(raw.run_attempt),
106
+ trigger: str(raw.trigger),
107
+ forced: raw.forced === true,
108
+ state: state as EntryState,
109
+ reservedUsd: num(raw.reservedUsd),
110
+ settledUsd: nullableNum(raw.settledUsd),
111
+ created_at: str(raw.created_at),
112
+ settled_at: typeof raw.settled_at === "string" ? raw.settled_at : null,
113
+ calls: Array.isArray(raw.calls) ? raw.calls.map(parseCall) : [],
114
+ };
115
+ }
116
+
117
+ export function parseEntriesResponse(body: unknown): EntriesResponse {
118
+ if (!isObject(body)) throw new Error("the ledger answered with something that is not a JSON object");
119
+ if (typeof body.account !== "string" || !ACCOUNT_PATTERN.test(body.account)) throw new Error("the ledger answer has no usable account name");
120
+ if (!Array.isArray(body.entries)) throw new Error("the ledger answer has no entries list");
121
+ const limits = isObject(body.limits) ? body.limits : {};
122
+ return {
123
+ account: body.account,
124
+ limits: { dailyUsd: nullableNum(limits.dailyUsd), weeklyUsd: nullableNum(limits.weeklyUsd) },
125
+ entries: body.entries.map(parseEntry),
126
+ };
127
+ }
package/src/ledger.ts CHANGED
@@ -11,15 +11,34 @@
11
11
  import { spawnSync } from "node:child_process";
12
12
  import { createPublicKey, verify } from "node:crypto";
13
13
 
14
- /** `curl`'s exit status and output; the HTTP status is read from the output (see `call`). */
15
- export type CurlFn = (args: string[]) => { status: number; stdout: string; stderr: string };
14
+ /**
15
+ * `curl`'s exit status and output; the HTTP status is read from the output (see `call`). `stdin` is the
16
+ * text curl reads as its configuration (`--config -`): every secret and every payload travels there,
17
+ * never in `args`, because the argument list of a process is readable by every other process on the
18
+ * machine and capped at 128 KB per argument. Copy this split for any new route.
19
+ */
20
+ export type CurlFn = (args: string[], stdin?: string) => { status: number; stdout: string; stderr: string };
16
21
 
17
- export const defaultCurl: CurlFn = (args) => {
18
- const run = spawnSync("curl", ["--silent", "--show-error", "--max-time", "20", ...args], { encoding: "utf8" });
22
+ /**
23
+ * Twenty seconds at most, and no redirect is followed (curl's default: no `--location`). `-q` must
24
+ * come first: it keeps the machine's `~/.curlrc` from changing either (a `location`, a `proxy`).
25
+ */
26
+ export const defaultCurl: CurlFn = (args, stdin) => {
27
+ const run = spawnSync("curl", ["-q", "--silent", "--show-error", "--max-time", "20", ...args], { encoding: "utf8", input: stdin });
19
28
  return { status: run.status ?? 1, stdout: run.stdout ?? "", stderr: run.stderr ?? run.error?.message ?? "" };
20
29
  };
21
30
 
31
+ const ESCAPES: Record<string, string> = { "\\": "\\\\", '"': '\\"', "\t": "\\t", "\n": "\\n", "\r": "\\r", "\v": "\\v" };
32
+
33
+ /**
34
+ * One curl configuration file (`curl --config -`): `option = "value"` lines. Inside the double quotes
35
+ * curl reads `\\`, `\"`, `\t`, `\n`, `\r` and `\v` as escapes, so these are the only characters changed.
36
+ */
37
+ export const curlConfig = (entries: [option: string, value: string][]): string =>
38
+ entries.map(([option, value]) => `${option} = "${value.replace(/[\\"\t\n\r\v]/g, (c) => ESCAPES[c]!)}"\n`).join("");
39
+
22
40
  export interface LedgerEnv {
41
+ GITHUB_ACTIONS?: string;
23
42
  ACTIONS_ID_TOKEN_REQUEST_URL?: string;
24
43
  ACTIONS_ID_TOKEN_REQUEST_TOKEN?: string;
25
44
  }
@@ -121,9 +140,12 @@ function unusable(route: string, status: number, what: string): Error {
121
140
  );
122
141
  }
123
142
 
124
- /** One request. The HTTP status is the last line of the output (`-w "\n%{http_code}"`). */
125
- function call(curl: CurlFn, args: string[]): { status: number; body: string } {
126
- const run = curl(["-o", "-", "-w", "\n%{http_code}", ...args]);
143
+ /**
144
+ * One request. `args` ends with the url; `secret` is what must not appear in argv (headers, data) and
145
+ * goes to curl on stdin. The HTTP status is the last line of the output (`-w "\n%{http_code}"`).
146
+ */
147
+ function call(curl: CurlFn, args: string[], secret: [option: string, value: string][]): { status: number; body: string } {
148
+ const run = curl(["--config", "-", "-o", "-", "-w", "\n%{http_code}", ...args], curlConfig(secret));
127
149
  if (run.status !== 0) throw new LedgerUnavailable(`curl failed (exit ${run.status}): ${run.stderr.trim()}`);
128
150
  const cut = run.stdout.lastIndexOf("\n");
129
151
  const status = Number(run.stdout.slice(cut + 1).trim());
@@ -141,16 +163,10 @@ const parseObject = (body: string): Record<string, unknown> | undefined => {
141
163
  };
142
164
 
143
165
  const post = (ledgerUrl: string, route: string, token: string, payload: unknown, curl: CurlFn) =>
144
- call(curl, [
145
- "-X",
146
- "POST",
147
- "-H",
148
- `Authorization: Bearer ${token}`,
149
- "-H",
150
- "Content-Type: application/json",
151
- "--data",
152
- JSON.stringify(payload),
153
- `${base(ledgerUrl)}${route}`,
166
+ call(curl, ["-X", "POST", `${base(ledgerUrl)}${route}`], [
167
+ ["header", `Authorization: Bearer ${token}`],
168
+ ["header", "Content-Type: application/json"],
169
+ ["data", JSON.stringify(payload)],
154
170
  ]);
155
171
 
156
172
  /**
@@ -161,7 +177,7 @@ export function requestIdToken(env: LedgerEnv, audience: string, curl: CurlFn):
161
177
  const url = env.ACTIONS_ID_TOKEN_REQUEST_URL;
162
178
  const bearer = env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
163
179
  if (!url || !bearer) throw new LedgerNotPermitted("this job has no OIDC token: id-token: write is not granted");
164
- const { status, body } = call(curl, ["-H", `Authorization: Bearer ${bearer}`, `${url}&audience=${encodeURIComponent(audience)}`]);
180
+ const { status, body } = call(curl, [`${url}&audience=${encodeURIComponent(audience)}`], [["header", `Authorization: Bearer ${bearer}`]]);
165
181
  const value = parseObject(body)?.value;
166
182
  if (status !== 200 || typeof value !== "string" || value === "") {
167
183
  if (isOutage(status)) throw new LedgerUnavailable(`GitHub did not issue an id token (HTTP ${status}).`);
package/src/setup/run.ts CHANGED
@@ -22,15 +22,15 @@ import {
22
22
  type InteractiveSpawn,
23
23
  } from "../accounts/commands";
24
24
  import { updateConfig, wachimanHome, type ProfileEntry, type ProjectBinding, type WachimanConfigV1 } from "../accounts/config";
25
- import { confirmProfile } from "../accounts/confirm";
25
+ import { confirmProfile, confirmProfileAsync, type AsyncSpawnFn } from "../accounts/confirm";
26
26
  import { managedDir } from "../accounts/profile-list";
27
27
  import { lookupProfileRef, profileLine } from "../accounts/resolve";
28
28
  import { UsageError } from "../config";
29
29
  import { repositoryKey } from "../history/store";
30
30
  import { claimManagedProfile, setupProfile } from "../profiles";
31
31
  import { isInteractive, type TerminalStreams } from "../wizard/interactive";
32
- import { createPrompter, type Prompter, type PromptIO } from "../wizard/prompt";
33
- import { wizardIo } from "../wizard/style";
32
+ import { loadTerminalUi } from "../wizard/load";
33
+ import type { Outcome, Prompter, PromptIO } from "../wizard/prompt";
34
34
  import { resolveSetupOptions, type RawSetupFlags } from "./options";
35
35
  import { promptForSetup, type PendingProfile } from "./prompt";
36
36
 
@@ -43,6 +43,8 @@ export interface SetupDeps extends AccountDeps {
43
43
  unboundHints?: readonly string[];
44
44
  streams?: TerminalStreams;
45
45
  promptIO?: PromptIO;
46
+ /** The asynchronous probe of the account, for a test; the default runs `claude` without blocking the terminal. */
47
+ spawnAsync?: AsyncSpawnFn;
46
48
  /** An open prompt session (shared with `init`); the caller closes it. */
47
49
  prompter?: Prompter;
48
50
  }
@@ -59,7 +61,6 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
59
61
  }
60
62
 
61
63
  const repoDir = flags.repoDir ?? ".";
62
- io = wizardIo(io, (deps.promptIO?.output ?? process.stderr) as { isTTY?: boolean }, env);
63
64
  const home = wachimanHome(env);
64
65
  const userHome = deps.userHome ?? homedir();
65
66
  const now = deps.now ?? (() => new Date().toISOString());
@@ -73,8 +74,11 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
73
74
  if (!found.ok) throw new UsageError(found.problem);
74
75
  }
75
76
 
76
- const prompter = deps.prompter ?? createPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr }, env);
77
+ // The terminal UI (chalk and Clack) is loaded only when questions are asked.
78
+ const ui = await loadTerminalUi();
79
+ const prompter = deps.prompter ?? (await ui.openPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr }, env));
77
80
  const ownsPrompter = deps.prompter === undefined;
81
+ io = ui.wizardIo(io, (deps.promptIO?.output ?? process.stderr) as { isTTY?: boolean }, env, prompter);
78
82
  /** What already happened on disk or in Claude and cannot be rolled back; reported whenever the run ends early. */
79
83
  const effects: string[] = [];
80
84
  const reportEffects = () => {
@@ -108,7 +112,12 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
108
112
  }
109
113
  };
110
114
 
115
+ let outcome: Outcome = "failed";
116
+ let closing: string | undefined;
111
117
  try {
118
+ // Only the command that opened the session plays the intro; `init` already did when it hands over,
119
+ // and so did the launcher (it marks WACHIMAN_INTRO_DONE, which `prompter.intro` honors).
120
+ if (ownsPrompter) await prompter.intro(deps.doctor?.version ?? "unknown", "Let's choose which Claude account stands guard.");
112
121
  let answers;
113
122
  try {
114
123
  answers = await promptForSetup(flags, { repo, current, config, home, userHome, createManaged, fromInit: deps.fromInit, initMode: deps.initMode }, prompter);
@@ -121,12 +130,15 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
121
130
  io.stderr("cancelled: no configuration changes saved.");
122
131
  reportEffects();
123
132
  for (const hint of deps.unboundHints ?? []) io.stderr(`Next, on this machine: ${hint} (binds this repository to a Claude account)`);
133
+ outcome = "cancelled";
124
134
  return 130;
125
135
  }
126
136
  if (answers.kind === "declined") {
127
137
  io.stderr("nothing saved: the configuration is unchanged.");
128
138
  reportEffects();
129
139
  for (const hint of deps.unboundHints ?? []) io.stderr(`Next, on this machine: ${hint} (binds this repository to a Claude account)`);
140
+ outcome = "done";
141
+ closing = "Nothing was saved.";
130
142
  return 0;
131
143
  }
132
144
  const resolved = resolveSetupOptions(answers.flags, { interactive: true });
@@ -147,10 +159,12 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
147
159
  if (!found.ok) throw new UsageError(found.problem);
148
160
  const resolvedProfile = { profile: found.profile, rung: "binding" as const, overridden: [] };
149
161
  io.stderr(profileLine(resolvedProfile));
150
- const probe = () => confirmProfile(resolvedProfile, env, deps.spawn, deps.doctor?.confirmIo);
151
- // The probes block while claude runs; an Enter typed meanwhile must not reach "Sign in now?" through a live readline.
162
+ // The real probe is asynchronous, so the spinner turns while `claude` runs; a test's fake `spawn` is synchronous and is called as it always was.
163
+ const probe = () =>
164
+ deps.spawn ? confirmProfile(resolvedProfile, env, deps.spawn, deps.doctor?.confirmIo) : confirmProfileAsync(resolvedProfile, env, deps.spawnAsync, deps.doctor?.confirmIo);
165
+ // An Enter typed meanwhile must not reach "Sign in now?" through a live readline.
152
166
  prompter.suspend();
153
- let status = probe();
167
+ let status = await prompter.task("Checking your Claude account", probe, (s) => s.ok);
154
168
  const signedOut = !status.ok && status.stage === "auth" && status.auth !== undefined && status.auth.exitCode !== 0;
155
169
  // True once the user was told the account state in its own words, so the generic warning would repeat it.
156
170
  let explained = false;
@@ -159,6 +173,7 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
159
173
  const answer = await prompter.confirm("Sign in now?", true);
160
174
  if (answer === null) {
161
175
  io.stderr(`cancelled: the binding of ${repo.name} to ${name} was saved and stays; you are not signed in (run \`wachiman profile login ${name}\`).`);
176
+ outcome = "cancelled";
162
177
  return 130;
163
178
  }
164
179
  if (answer) {
@@ -166,9 +181,10 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
166
181
  const code = runProfile({ kind: "login", profile: name }, env, io, { ...deps, interactive: true, interactiveSpawn: deps.interactiveSpawn });
167
182
  if (code === 130) {
168
183
  io.stderr(`cancelled: the binding of ${repo.name} to ${name} was saved and stays.`);
184
+ outcome = "cancelled";
169
185
  return 130;
170
186
  }
171
- status = probe();
187
+ status = await prompter.task("Checking your Claude account", probe, (s) => s.ok);
172
188
  } else {
173
189
  io.stderr(`not signed in: run \`wachiman profile login ${name}\` before \`wachiman local\`.`);
174
190
  explained = true;
@@ -181,9 +197,10 @@ export async function runSetupCommand(flags: RawSetupFlags, env: Record<string,
181
197
  prompter.step("Checks and next actions", total, total);
182
198
  const code = closeSetup(repoDir, env, io, deps);
183
199
  if (flags.json) io.stdout(`${JSON.stringify(projectShow(repoDir, env, deps), null, 2)}\n`);
200
+ outcome = code === 0 ? "done" : code === 130 ? "cancelled" : "failed";
184
201
  return code;
185
202
  } finally {
186
- if (ownsPrompter) prompter.close();
203
+ if (ownsPrompter) prompter.close(outcome, closing);
187
204
  }
188
205
  }
189
206