@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 296 lines 11.4 KB
Raw
1 import * as Cause from "effect/Cause";
2 import * as Effect from "effect/Effect";
3 import * as Fiber from "effect/Fiber";
4 import * as Logger from "effect/Logger";
5 import type * as LogLevel from "effect/LogLevel";
6 import * as Queue from "effect/Queue";
7 import { CurrentLogAnnotations, MinimumLogLevel } from "effect/References";
8 import * as Schema from "effect/Schema";
9 import * as Stream from "effect/Stream";
10 import { LogAnnotation } from "./Util/LogAnnotation.ts";
11
12 // The engine's typed events: one Schema union discriminated by `type`
13 // (`domain.subject.verb`), emitted as log records through Effect's logger.
14 // `onEvent` observes them; every logger (the run log, JSON output) sees them
15 // too. Time, trace and resource live on the log record, not the event.
16
17 const ProviderMode = Schema.Literals(["local", "live"]);
18
19 export const ApplyStatus = Schema.Literals([
20 "attaching",
21 "post-attach",
22 "pending",
23 "pre-creating",
24 "creating",
25 "creating replacement",
26 "created",
27 "updating",
28 "updated",
29 "adopting",
30 "adopted",
31 "deleting",
32 "deleted",
33 "orphaning",
34 "orphaned",
35 "replacing",
36 "replaced",
37 // Action lifecycle (see `Action`)
38 "running",
39 "ran",
40 "skipped",
41 "fail",
42 ]);
43 export type ApplyStatus = typeof ApplyStatus.Type;
44
45 /**
46 * How append-only renderers surface a note (the interactive view treats every
47 * kind the same): `"status"` is transient spinner text that plain mode folds
48 * into the settle line's suffix, `"output"` is verbatim tool output streamed
49 * line by line, and absent is a one-shot informational note.
50 */
51 export const NoteKind = Schema.Literals(["status", "output"]);
52 export type NoteKind = typeof NoteKind.Type;
53
54 /** One binding row on a planned resource. */
55 export const PlannedBinding = Schema.Struct({
56 sid: Schema.String,
57 action: Schema.Literals(["create", "update", "delete", "noop"]),
58 });
59 export type PlannedBinding = typeof PlannedBinding.Type;
60
61 /** Serializable view of one resource row in a plan. */
62 export const PlannedResource = Schema.Struct({
63 fqn: Schema.String,
64 logicalId: Schema.String,
65 resourceType: Schema.String,
66 /** The action the plan decided for this resource. */
67 action: Schema.Literals(["create", "update", "adopted", "replace", "delete", "orphaned", "noop"]),
68 /** Binding rows the node carries; empty when the resource has none. */
69 bindings: Schema.Array(PlannedBinding),
70 /** Mode the node's provider resolved for; absent for mode-agnostic providers. */
71 providerMode: Schema.optionalKey(ProviderMode),
72 /** On mode-switch replacements: the mode the old generation was created with. */
73 fromProviderMode: Schema.optionalKey(ProviderMode),
74 });
75 export type PlannedResource = typeof PlannedResource.Type;
76
77 /** Serializable view of one stack-action row in a plan. */
78 export const PlannedAction = Schema.Struct({
79 fqn: Schema.String,
80 logicalId: Schema.String,
81 actionType: Schema.String,
82 action: Schema.Literals(["run", "delete", "noop"]),
83 });
84 export type PlannedAction = typeof PlannedAction.Type;
85
86 /** Phases a stack plan moves through before it is ready. */
87 export const PlanningPhase = Schema.Literals([
88 "importing-module",
89 "resolving-services",
90 "loading-state",
91 "computing-plan",
92 "plan-ready",
93 ]);
94 export type PlanningPhase = typeof PlanningPhase.Type;
95
96 /** A note a provider attached to a resource while applying it. */
97 export const ResourceAnnotated = Schema.Struct({
98 type: Schema.Literal("apply.resource.note"),
99 /** Fully-qualified resource or action name used to target its plan row. */
100 fqn: Schema.String,
101 id: Schema.String,
102 message: Schema.String,
103 kind: Schema.optionalKey(NoteKind),
104 });
105 export type ResourceAnnotated = typeof ResourceAnnotated.Type;
106
107 /** A resource or action moved to a new apply status. */
108 export const ResourceStatusChanged = Schema.Struct({
109 type: Schema.Literal("apply.resource.status"),
110 /** Fully-qualified resource or action name used to target its plan row. */
111 fqn: Schema.String,
112 /** Logical id, e.g. `"api"`. */
113 id: Schema.String,
114 /** e.g. `"Cloudflare.Worker"`. */
115 resourceType: Schema.String,
116 status: ApplyStatus,
117 message: Schema.optionalKey(Schema.String),
118 /**
119 * The mode this node's provider was resolved for; absent for mode-agnostic
120 * providers and for actions.
121 */
122 providerMode: Schema.optionalKey(ProviderMode),
123 /**
124 * Set only on mode-switch replacements (local ⇄ live): the mode the OLD
125 * generation was created with. Always differs from `providerMode`.
126 */
127 fromProviderMode: Schema.optionalKey(ProviderMode),
128 });
129 export type ResourceStatusChanged = typeof ResourceStatusChanged.Type;
130
131 export type ApplyEvent = ResourceAnnotated | ResourceStatusChanged;
132
133 /** Every event the engine and the Alchemist operations emit. */
134 export const Event = Schema.Union([
135 /**
136 * The planning pipeline crossed a work boundary. Carries no display text —
137 * wording is the renderer's job.
138 */
139 Schema.Struct({ type: Schema.Literal("plan.phase"), phase: PlanningPhase }),
140 /**
141 * A resource's diff began. Diffs run concurrently and may read the cloud,
142 * so pairing starts with completions lets a renderer show what is in flight.
143 */
144 Schema.Struct({
145 type: Schema.Literal("plan.resource.started"),
146 fqn: Schema.String,
147 logicalId: Schema.String,
148 resourceType: Schema.String,
149 total: Schema.Number,
150 }),
151 /** The planner finished diffing one resource; `completed` of `total` so far. */
152 Schema.Struct({
153 type: Schema.Literal("plan.resource.completed"),
154 ...PlannedResource.fields,
155 completed: Schema.Number,
156 total: Schema.Number,
157 }),
158 /** The planner decided one stack action. */
159 Schema.Struct({
160 type: Schema.Literal("plan.action.completed"),
161 ...PlannedAction.fields,
162 completed: Schema.Number,
163 total: Schema.Number,
164 }),
165 ResourceAnnotated,
166 ResourceStatusChanged,
167 /**
168 * Around a state-store bootstrap or upgrade (e.g. deploying the Cloudflare
169 * state-store worker on first use); `store` names it.
170 */
171 Schema.Struct({ type: Schema.Literal("state.bootstrap.started"), store: Schema.String }),
172 Schema.Struct({ type: Schema.Literal("state.bootstrap.completed"), store: Schema.String }),
173 Schema.Struct({ type: Schema.Literal("provider.configure.started"), provider: Schema.String }),
174 Schema.Struct({ type: Schema.Literal("provider.configure.completed"), provider: Schema.String }),
175 Schema.Struct({ type: Schema.Literal("provider.refresh.started"), provider: Schema.String }),
176 Schema.Struct({ type: Schema.Literal("provider.refresh.completed"), provider: Schema.String }),
177 Schema.Struct({ type: Schema.Literal("nuke.scan.started"), total: Schema.Number }),
178 Schema.Struct({ type: Schema.Literal("nuke.scan.provider.started"), provider: Schema.String }),
179 /** One provider's listing settled: 0 resources and an `error` when it failed. */
180 Schema.Struct({
181 type: Schema.Literal("nuke.scan.provider.completed"),
182 provider: Schema.String,
183 resources: Schema.Number,
184 error: Schema.optionalKey(Schema.String),
185 }),
186 Schema.Struct({ type: Schema.Literal("nuke.pass.started"), pass: Schema.Number }),
187 /** `resource` is the deleted object's display name. */
188 Schema.Struct({
189 type: Schema.Literal("nuke.resource.deleted"),
190 provider: Schema.String,
191 resource: Schema.String,
192 }),
193 /** A deletion attempt failed; the run keeps going. */
194 Schema.Struct({
195 type: Schema.Literal("nuke.resource.failed"),
196 provider: Schema.String,
197 resource: Schema.String,
198 message: Schema.String,
199 }),
200 ]);
201 export type Event = typeof Event.Type;
202
203 const knownEventTypes: ReadonlySet<string> = new Set(
204 Event.members.map((member) => member.fields.type.literal),
205 );
206
207 /** Whether `type` names an event this version knows. */
208 export const isKnownEventType = (type: string): boolean => knownEventTypes.has(type);
209
210 /**
211 * The level an event is logged at: failures stand out, so a reader filtering
212 * the run log by level (`select(.level == "error")`) finds them.
213 */
214 const levelOf = (event: Event): LogLevel.Severity =>
215 event.type === "apply.resource.status" && event.status === "fail"
216 ? "Error"
217 : event.type === "nuke.resource.failed" ||
218 (event.type === "nuke.scan.provider.completed" && event.error !== undefined)
219 ? "Warn"
220 : "Info";
221
222 /**
223 * Emit an event. Events are log records (annotated as events, at Info unless
224 * they report a failure), so every logger sees them: the run log and
225 * `--log-format json` carry them and renderers subscribe with
226 * {@link onEvent}. The pretty console sink skips them, and telemetry does not
227 * export them.
228 */
229 export const emit = (event: Event): Effect.Effect<void> =>
230 Effect.logWithLevel(levelOf(event))(event).pipe(
231 Effect.annotateLogs(LogAnnotation.event, true),
232 // Events always reach the loggers; each sink applies its own floor
233 // (the console's `--log-level`), so a quieter minimum never starves a
234 // renderer or the run log of progress.
235 Effect.provideService(MinimumLogLevel, "Trace"),
236 );
237
238 /** The event a log record carries, if it is one. */
239 const eventOf = (options: Logger.Options<unknown>): Event | undefined => {
240 if (options.fiber.getRef(CurrentLogAnnotations)[LogAnnotation.event] !== true) return undefined;
241 const message = Array.isArray(options.message) ? options.message[0] : options.message;
242 // SAFETY: only `emit` sets the event annotation, and it logs an Event.
243 return message as Event;
244 };
245
246 /**
247 * {@link emit} bound to the current loggers, for reporting from contexts
248 * that may no longer carry them (provider callbacks, cached operations), so
249 * the events still reach the caller's sinks and `onEvent` subscribers.
250 */
251 export const captureEmit: Effect.Effect<(event: Event) => Effect.Effect<void>> = Effect.map(
252 Logger.CurrentLoggers,
253 (loggers) => (event) => emit(event).pipe(Effect.provideService(Logger.CurrentLoggers, loggers)),
254 );
255
256 /**
257 * Observe the events `effect` emits. The handler runs (with the caller's
258 * services) for each event in order, alongside the loggers already
259 * installed, and every handler has finished before this returns.
260 */
261 export const onEvent =
262 <R = never>(handler: (event: Event) => Effect.Effect<void, never, R>) =>
263 <A, E, R2>(effect: Effect.Effect<A, E, R2>): Effect.Effect<A, E, R | R2> =>
264 Effect.gen(function* () {
265 const queue = yield* Queue.unbounded<Event, Cause.Done>();
266 const consumer = yield* Stream.fromQueue(queue).pipe(
267 Stream.runForEach(handler),
268 Effect.forkDetach,
269 );
270 // Every event emitted so far is handled before returning.
271 const drain = Queue.end(queue).pipe(Effect.andThen(Fiber.join(consumer)));
272 return yield* effect.pipe(
273 Effect.provide(
274 Logger.layer(
275 [
276 Logger.make<unknown, void>((options) => {
277 const event = eventOf(options);
278 if (event !== undefined) Queue.offerUnsafe(queue, event);
279 }),
280 ],
281 { mergeWithExisting: true },
282 ),
283 ),
284 // `effect` stays on this fiber, so fibers it forks live as long as
285 // the caller's. A handler that died fails the operation here.
286 Effect.tap(() => drain),
287 Effect.tapCause((cause) =>
288 Cause.hasInterruptsOnly(cause) ? Effect.void : Effect.ignore(drain),
289 ),
290 // Cancelled: stop handling instead of waiting on a blocked handler.
291 Effect.onInterrupt(() => Fiber.interrupt(consumer)),
292 // Whatever the exit, later emits are rejected instead of piling up
293 // in a queue nothing reads.
294 Effect.ensuring(Queue.shutdown(queue)),
295 );
296 });