The best way to control Claude Code, Codex and more from any computer or phone

main
ts 337 lines 14.7 KB
Raw
1 import { inspect } from "node:util";
2 import * as Prompt from "effect/cli/Prompt";
3 import * as Clock from "effect/Clock";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import type * as LogLevel from "effect/LogLevel";
7 import type { ApplyEvent, ApplyStatus } from "../Events.ts";
8 import { NonInteractiveTerminal } from "../Interaction.ts";
9 import type { ActionApply, ActionDelete, CRUD, Plan } from "../Plan.ts";
10 import { Cli, type PlanDisplayOptions } from "../Report.ts";
11 import { canPromptOnStdin } from "../Util/interactive.ts";
12 import { formatResourceTag } from "../Util/ResourceOutput.ts";
13 import { ansiFg, colorsEnabled } from "../Util/Terminal.ts";
14 import { theme } from "../Util/Theme.ts";
15 import {
16 actionStyle,
17 applyStatusColor,
18 isTerminalStatus as isTerminal,
19 } from "./components/view/statusStyle.ts";
20 import { formatElapsed } from "./Format.ts";
21 import { formatModeNote } from "./ModeTag.ts";
22 import { actionHasPlannedWork, buildPlanSummary } from "./NamespaceTree.ts";
23 import { present } from "./Present.ts";
24 import { formatDeclaredPropertyYaml, matchYamlChange, matchYamlKey } from "./PropertyDiff.ts";
25
26 const ESC = "\x1b[";
27 const RESET = `${ESC}0m`;
28 // Shared with every other non-ink output path — notably it honors
29 // FORCE_COLOR, so lines emitted from the piped dev sidecar keep their color.
30 const useColor = colorsEnabled();
31 const c = (code: string, s: string) => (useColor ? `${ESC}${code}m${s}${RESET}` : s);
32 const hex = (color: string) => (s: string) => (useColor ? `${ansiFg(color)}${s}${RESET}` : s);
33 const dim = (s: string) => c("2", s);
34 const bold = (s: string) => c("1", s);
35 const red = hex(theme.color.danger);
36 const green = hex(theme.color.success);
37 const blue = hex(theme.color.accent);
38 const cyan = hex(theme.color.info);
39
40 // noop stays terminal-dim rather than brand-muted so it recedes in plain logs
41 const actionColor: Record<CRUD["action"], (s: string) => string> = {
42 create: hex(actionStyle.create.color),
43 update: hex(actionStyle.update.color),
44 adopted: hex(actionStyle.adopted.color),
45 replace: hex(actionStyle.replace.color),
46 delete: hex(actionStyle.delete.color),
47 orphaned: hex(actionStyle.orphaned.color),
48 noop: dim,
49 };
50
51 // muted stays terminal-dim rather than brand-muted, matching `actionColor`.
52 const statusColor = (status: ApplyStatus): ((s: string) => string) => {
53 const color = applyStatusColor(status);
54 if (color === undefined || color === theme.color.muted) return dim;
55 return hex(color);
56 };
57
58 const tag = formatResourceTag;
59
60 /** A progress line about one resource. */
61 const logFor = (fqn: string, message: string, level?: LogLevel.Severity) =>
62 present(message, { resource: fqn, level });
63
64 /**
65 * In-progress statuses that represent real cloud work. Plain output has no
66 * spinner, so these lines are the liveness signal in CI logs
67 * (CloudFormation-style IN_PROGRESS rows). Bookkeeping transitions
68 * (`pending`, `attaching`, `post-attach`) stay silent — they resolve in
69 * milliseconds and would double the log for no information.
70 */
71 const isActive = (status: ApplyStatus): boolean =>
72 status === "pre-creating" ||
73 status === "creating" ||
74 status === "creating replacement" ||
75 status === "updating" ||
76 status === "adopting" ||
77 status === "deleting" ||
78 status === "orphaning" ||
79 status === "replacing" ||
80 status === "running";
81
82 /**
83 * Dim `(local)` / `(remote)` / `(local → live)` suffix for a resource row,
84 * or `""` when the row's mode matches the run default (the quiet common
85 * case). See {@link formatModeNote} for the rule.
86 */
87 const modeSuffix = (options: Parameters<typeof formatModeNote>[0]): string => {
88 const note = formatModeNote(options);
89 return note ? ` ${dim(`(${note})`)}` : "";
90 };
91
92 /** Exported for unit tests — pure plan-preview rendering. */
93 export const formatPlanLines = (plan: Plan, options: PlanDisplayOptions = {}): string[] => {
94 const allItems = [...Object.values(plan.resources), ...Object.values(plan.deletions)] as CRUD[];
95 const tasks = [...Object.values(plan.actions ?? {}), ...Object.values(plan.actionDeletions ?? {})]
96 .filter((task): task is ActionApply | ActionDelete => task !== undefined)
97 .filter(actionHasPlannedWork);
98 if (allItems.length === 0 && tasks.length === 0) {
99 return [`${bold("Plan:")} ${dim("no resources")}`];
100 }
101
102 const { counts, bindingChanges } = buildPlanSummary(plan);
103 const summaryParts = (["create", "update", "adopted", "replace", "delete", "orphaned"] as const)
104 .filter((a) => counts[a])
105 .map((a) => actionColor[a](`${counts[a]} to ${a}`));
106 if (bindingChanges > 0) {
107 summaryParts.push(cyan(`${bindingChanges} binding changes`));
108 }
109 if (tasks.length > 0) {
110 summaryParts.push(cyan(`${tasks.length} tasks`));
111 }
112 const summary = summaryParts.length === 0 ? dim("no changes") : summaryParts.join(dim(", "));
113
114 const sorted = [...allItems].sort((a, b) =>
115 a.resource.LogicalId.localeCompare(b.resource.LogicalId),
116 );
117 const lines = [`${bold("Plan:")} ${summary}`];
118 if (options.detailed && sorted.length > 0) lines.push("");
119 for (const [index, item] of sorted.entries()) {
120 if (options.detailed && index > 0) lines.push("");
121 const action = actionColor[item.action](item.action);
122 const mode = modeSuffix({
123 mode: item.mode,
124 priorMode: item.action === "replace" ? item.state.providerMode : undefined,
125 defaultMode: plan.defaultMode,
126 });
127 // Surface FQN migrations: `[Assets] update (renamed from Bucket)` —
128 // the update exists to re-brand the moved row's physical resource, and
129 // without the note the plan gives no hint why an untouched resource
130 // reconciles. (Only apply-side nodes can carry a rename — see
131 // `ApplyNodeBase`.)
132 const renamed =
133 "renamedFrom" in item && item.renamedFrom?.length
134 ? ` ${dim(`(renamed from ${item.renamedFrom.join(", ")})`)}`
135 : "";
136 lines.push(`${tag(item.resource.FQN)} ${action}${mode}${renamed}`);
137 for (const binding of [...item.bindings].sort((a, b) => a.sid.localeCompare(b.sid))) {
138 const bindingAction =
139 binding.action === "delete" ? dim("unbind") : actionColor[binding.action](binding.action);
140 lines.push(`${tag(`${item.resource.FQN}/${binding.sid}`)} ${bindingAction}`);
141 }
142 if (
143 options.detailed &&
144 (item.action === "create" ||
145 item.action === "update" ||
146 item.action === "adopted" ||
147 item.action === "replace")
148 ) {
149 const document = formatDeclaredPropertyYaml(
150 item.action === "create" ? {} : item.state.props,
151 item.props,
152 item.action === "adopted" ? "update" : item.action,
153 );
154 if (document === undefined) {
155 lines.push(` ${dim("no declared property changes")}`);
156 } else {
157 lines.push(...document.lines.map((line) => ` ${colorYamlLine(line, document.kind)}`));
158 }
159 }
160 }
161 for (const task of tasks.sort((a, b) => a.def.LogicalId.localeCompare(b.def.LogicalId))) {
162 lines.push(
163 `${tag(task.def.FQN)} ${cyan(task.action === "delete" ? "drop" : "run")} ${dim("[action]")}`,
164 );
165 }
166 return lines;
167 };
168
169 const colorYamlLine = (line: string, kind: "create" | "change" | "drift"): string => {
170 const change = matchYamlChange(line);
171 if (change !== undefined) {
172 const color = change.marker === "-" ? red : green;
173 return color(`${change.marker} ${change.content}`);
174 }
175 const key = matchYamlKey(line);
176 if (key === undefined) return line;
177 const color = kind === "create" ? green : cyan;
178 return `${key.indent}${color(key.key)}${key.value}`;
179 };
180
181 export const LoggingCli = Layer.effect(
182 Cli,
183 Effect.gen(function* () {
184 // Captured at layer build so `approvePlan` keeps the CLIService signature
185 // (no requirements on the returned Effects).
186 const promptContext = yield* Effect.context<Prompt.Environment>();
187 const confirm = (options: Prompt.ConfirmOptions) =>
188 Prompt.Confirm(options).pipe(
189 Effect.catchTag("QuitError", () => Effect.succeed(false)),
190 Effect.provideContext(promptContext),
191 );
192 return Cli.of({
193 startPlanningSession: (label, _detail, title) =>
194 Effect.gen(function* () {
195 // Same information as the interactive session, one plain line per
196 // change: the title header carries the operation + stage once, each
197 // phase prints as it starts, and the settle line carries the total
198 // planning time (the spinner's implicit "how long did that take").
199 const startedAt = yield* Clock.currentTimeMillis;
200 if (title !== undefined) yield* present(bold(title));
201 yield* present(dim(label));
202 let closed = false;
203 let lastLabel = label;
204 const write = (nextLabel: string, _nextDetail?: string) =>
205 Effect.suspend(() => {
206 // Repeated updates within one phase (spinner detail refreshes)
207 // carry nothing new for a line-per-change log.
208 if (closed || nextLabel === lastLabel) return Effect.void;
209 lastLabel = nextLabel;
210 return present(dim(nextLabel));
211 });
212 const finish = (message: string, paint: (s: string) => string) =>
213 Effect.suspend(() => {
214 if (closed) return Effect.void;
215 closed = true;
216 return Clock.currentTimeMillis.pipe(
217 Effect.flatMap((now) =>
218 present(`${paint(message)} ${dim(`(${formatElapsed(now - startedAt)})`)}`),
219 ),
220 );
221 });
222 return {
223 update: write,
224 succeed: (message = "Plan ready") => finish(message, green),
225 fail: (message = "Planning failed") => finish(message, red),
226 close: Effect.sync(() => {
227 closed = true;
228 }),
229 };
230 }),
231 approvePlan: (plan, options) =>
232 Effect.gen(function* () {
233 for (const line of formatPlanLines(plan, options)) yield* present(line);
234 if (canPromptOnStdin()) {
235 return yield* confirm(
236 plan.destroy === true
237 ? { message: "Destroy these resources?", initial: false }
238 : { message: "Apply this plan?", initial: true },
239 );
240 }
241 return yield* new NonInteractiveTerminal({
242 operation: "approve deployment plan",
243 message:
244 "Cannot approve this operation without terminal input. Pass --yes to continue.",
245 });
246 }),
247 displayPlan: (plan, options) =>
248 Effect.gen(function* () {
249 for (const line of formatPlanLines(plan, options)) yield* present(line);
250 }),
251 startApplySession: (plan, options) =>
252 Effect.gen(function* () {
253 for (const line of formatPlanLines(plan, options)) yield* present(line);
254 yield* present("");
255
256 const startedAt = yield* Clock.currentTimeMillis;
257 const started = new Map<string, number>();
258 const terminal = new Map<string, ApplyStatus>();
259 const notes = new Map<string, string>();
260 const statusNotes = new Map<string, string>();
261 return {
262 setOutput: (value: unknown) => present(inspect(value, { colors: false })),
263 // Presents the apply events (which are already log records) as
264 // lines shaped like log lines, so the plain output reads as one
265 // stream.
266 emit: (event: ApplyEvent) =>
267 Clock.currentTimeMillis.pipe(
268 Effect.flatMap((now) =>
269 Effect.suspend(() => {
270 if (event.type === "apply.resource.note") {
271 // `status` notes only surface as the settle line's suffix;
272 // everything else streams, deduping consecutive repeats.
273 if (event.kind === "status") {
274 statusNotes.set(event.fqn, event.message);
275 return Effect.void;
276 }
277 if (notes.get(event.fqn) === event.message) return Effect.void;
278 notes.set(event.fqn, event.message);
279 return logFor(event.fqn, blue(event.message));
280 }
281 const id = event.fqn;
282 const mode = modeSuffix({
283 mode: event.providerMode,
284 priorMode: event.fromProviderMode,
285 defaultMode: plan.defaultMode,
286 });
287 if (!isTerminal(event.status)) {
288 if (!isActive(event.status)) return Effect.void;
289 if (!started.has(id)) started.set(id, now);
290 return logFor(id, `${dim(event.status)}${mode}`);
291 }
292 terminal.set(id, event.status);
293 const status = statusColor(event.status)(event.status);
294 const from = started.get(id);
295 const took =
296 from === undefined ? "" : ` ${dim(`(${formatElapsed(now - from)})`)}`;
297 const message = event.message ?? statusNotes.get(event.fqn);
298 // Failures carry their error as the message — paint it
299 // red so the line reads as the error line for that
300 // resource, without waiting for the final cause dump.
301 const msg = message
302 ? ` ${dim("—")} ${event.status === "fail" ? red(message) : message}`
303 : "";
304 // At the level `emit` gives the event, so `--log-level error`
305 // still shows a failed resource.
306 return logFor(
307 id,
308 `${status}${mode}${msg}${took}`,
309 event.status === "fail" ? "Error" : undefined,
310 );
311 }),
312 ),
313 ),
314 done: (outcome) =>
315 Clock.currentTimeMillis.pipe(
316 Effect.flatMap((now) => {
317 const statuses = [...terminal.values()];
318 const failed = statuses.filter((s) => s === "fail").length;
319 const skipped = statuses.filter((s) => s === "skipped").length;
320 const succeeded = terminal.size - failed - skipped;
321 const parts = [green(`${succeeded} succeeded`)];
322 if (failed) parts.push(red(`${failed} failed`));
323 if (skipped) parts.push(dim(`${skipped} skipped`));
324 return present("").pipe(
325 Effect.andThen(
326 present(
327 `${bold(outcome === "success" ? "Done:" : "Failed:")} ${parts.join(dim(", "))} ${dim(`(${formatElapsed(now - startedAt)})`)}`,
328 ),
329 ),
330 );
331 }),
332 ),
333 };
334 }),
335 });
336 }),
337 );