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

main
ts 145 lines 5.38 KB
Raw
1 import * as Cause from "effect/Cause";
2 import * as Context from "effect/Context";
3 import * as Effect from "effect/Effect";
4 import * as Exit from "effect/Exit";
5 import * as Option from "effect/Option";
6 import * as Scope from "effect/Scope";
7 import { onEvent, type ApplyEvent, type NoteKind } from "./Events.ts";
8 import type { NonInteractiveTerminal } from "./Interaction.ts";
9 import type { Plan } from "./Plan.ts";
10
11 // The presentation contract: the renderer interfaces a presentation layer
12 // (the bundled CLI, a custom renderer, tests) implements, and `renderApply`,
13 // which feeds a plan's apply events to the ambient one. The engine only
14 // emits events (Events.ts); nothing in here knows about terminals.
15
16 /** A renderer drawing one plan's apply, fed by {@link renderApply}. */
17 export interface PlanStatusSession {
18 emit: (event: ApplyEvent) => Effect.Effect<void>;
19 done: (outcome: "success" | "failure") => Effect.Effect<void>;
20 /** Replace the dev widget's stack output view without writing scrollback. */
21 setOutput?: (value: unknown) => Effect.Effect<void>;
22 /**
23 * Tear down the session's live presentation without settling it. Dev keeps
24 * its widget mounted after `done`; an interrupted generation (reload,
25 * Ctrl+C) must remove it so the next generation does not stack another.
26 */
27 close?: Effect.Effect<void>;
28 }
29
30 export interface PlanningStatusSession {
31 update: (
32 label: string,
33 detail?: string,
34 options?: {
35 /**
36 * Animate the status glyph. Pass `false` for phases whose work runs
37 * synchronously on the main thread (e.g. module import) — a spinner
38 * cannot animate while the event loop is blocked, so it freezes
39 * mid-frame and reads as hung; a static row doesn't promise motion.
40 */
41 readonly spinning?: boolean;
42 },
43 ) => Effect.Effect<void>;
44 succeed: (message?: string) => Effect.Effect<void>;
45 fail: (message?: string) => Effect.Effect<void>;
46 close: Effect.Effect<void>;
47 }
48
49 /**
50 * What a provider's lifecycle operation gets to report progress on its
51 * resource: each note is an `apply.resource.note` event.
52 */
53 export interface ScopedPlanStatusSession {
54 note: (note: string, options?: { readonly kind?: NoteKind }) => Effect.Effect<void>;
55 }
56
57 /** The session for one resource: its notes go to `report` as events. */
58 export const resourceSession = (
59 report: (event: ApplyEvent) => Effect.Effect<void>,
60 fqn: string,
61 id: string,
62 ): ScopedPlanStatusSession => ({
63 note: (message, options) =>
64 report({ type: "apply.resource.note", fqn, id, message, kind: options?.kind }),
65 });
66
67 /** A session that drops its notes, for calling a provider outside apply. */
68 export const noopSession: ScopedPlanStatusSession = {
69 note: () => Effect.void,
70 };
71
72 export interface PlanDisplayOptions {
73 /** Show declared resource inputs as structured YAML. */
74 detailed?: boolean;
75 /** Stage displayed in terminal lifecycle updates. */
76 stage?: string;
77 /** Keep the dev plan mounted as a collapsible widget below static logs. */
78 dev?: boolean;
79 }
80
81 export interface CLIService {
82 startPlanningSession: (
83 label: string,
84 detail?: string,
85 title?: string,
86 ) => Effect.Effect<PlanningStatusSession>;
87 approvePlan: <P extends Plan>(
88 plan: P,
89 options?: PlanDisplayOptions,
90 ) => Effect.Effect<boolean, NonInteractiveTerminal>;
91 displayPlan: <P extends Plan>(plan: P, options?: PlanDisplayOptions) => Effect.Effect<void>;
92 startApplySession: <P extends Plan>(
93 plan: P,
94 options?: PlanDisplayOptions,
95 ) => Effect.Effect<PlanStatusSession>;
96 }
97
98 export class Cli extends Context.Service<Cli, CLIService>()("CLI") {}
99
100 /**
101 * Draw `effect`'s apply events through the ambient {@link Cli} renderer:
102 * plan rows, per-resource status and notes, then the outcome. Without a
103 * renderer the effect runs as-is; its events are still log records.
104 */
105 export const renderApply =
106 (plan: Plan, options?: PlanDisplayOptions) =>
107 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
108 Effect.flatMap(
109 Effect.serviceOption(Cli),
110 Option.match({
111 onNone: () => effect,
112 onSome: (cli) =>
113 Effect.gen(function* () {
114 const session = yield* cli.startApplySession(plan, options);
115 // Dev keeps the widget mounted after apply settles and parks in the
116 // ambient scope; bind the widget's teardown to that scope so a reload
117 // or Ctrl+C removes it instead of stacking it under the next one.
118 if (options?.dev && session.close !== undefined) {
119 const scope = yield* Effect.serviceOption(Scope.Scope);
120 if (Option.isSome(scope)) {
121 yield* Scope.addFinalizer(scope.value, session.close);
122 }
123 }
124 return yield* effect.pipe(
125 onEvent((event) =>
126 event.type === "apply.resource.status" || event.type === "apply.resource.note"
127 ? session.emit(event)
128 : Effect.void,
129 ),
130 Effect.tap((value) =>
131 options?.dev && session.setOutput !== undefined
132 ? session.setOutput(value)
133 : Effect.void,
134 ),
135 Effect.onExit((exit) =>
136 Exit.isSuccess(exit)
137 ? session.done("success")
138 : Cause.hasInterruptsOnly(exit.cause)
139 ? Effect.void
140 : session.done("failure"),
141 ),
142 );
143 }),
144 }),
145 );