@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, 06:00 UTC

main
ts 279 lines 11 KB
Raw
1 import * as Context from "effect/Context";
2 import * as Effect from "effect/Effect";
3 import * as Layer from "effect/Layer";
4 import type { Pipeable } from "effect/Pipeable";
5 import { makeCaptureContext } from "./ActionRuntimeContext.ts";
6 import { toFqn } from "./FQN.ts";
7 import type { Input } from "./Input.ts";
8 import { CurrentNamespace, type NamespaceNode } from "./Namespace.ts";
9 import * as Output from "./Output.ts";
10 import { RuntimeContext } from "./RuntimeContext.ts";
11 import { Stack } from "./Stack.ts";
12
13 /**
14 * An Action is a node in the dependency graph that runs an Effect with its
15 * resolved input during {@link plan}/{@link apply}. It is similar to a
16 * Resource but without a Provider lifecycle:
17 *
18 * - It has a LogicalId and typed Input.
19 * - The body Effect is called when input changes (diff) or `--force` is set.
20 * - There is no replace/precreate/read/delete: removing an Action from the
21 * stack simply drops its persisted state without invoking the body.
22 * - Dependencies pulled in by the init Effect surface as `Req` on the
23 * call site, exactly like a Resource's provider services.
24 *
25 * Actions are recorded on {@link Stack.actions} and produce a single output
26 * value; `yield*` on the constructor returns `Output<Out>` for use as
27 * input to downstream Resources / Actions.
28 */
29 export interface ActionLike<
30 Type extends string = string,
31 In extends object | undefined = any,
32 Out = any,
33 > {
34 readonly Kind: "action";
35 readonly Namespace: NamespaceNode | undefined;
36 readonly FQN: string;
37 readonly Type: Type;
38 readonly LogicalId: string;
39 readonly Input: In;
40 /**
41 * Resource Outputs referenced via `yield* output` inside the init Effect,
42 * keyed by the Output's sanitized key. They become dependency edges (the
43 * Action waits for these upstreams) and are resolved against the tracker at
44 * apply time, then exposed to the body through the resolve
45 * {@link RuntimeContext}. Empty when the Action captures nothing.
46 */
47 readonly Captures: Record<string, Output.Output>;
48 /** Resolved runner — populated by the init effect (if any). */
49 readonly Run: (input: In) => Effect.Effect<Out, any, any>;
50 /** @internal phantom */
51 Output: Out;
52 }
53
54 export const isAction = (value: any): value is ActionLike =>
55 typeof value === "object" && value !== null && value?.Kind === "action";
56
57 /** Body function — runs each time the resolved input changes. */
58 export type ActionRunner<In extends object | undefined, Out, Req = any> = (
59 input: In,
60 ) => Effect.Effect<Out, any, Req>;
61
62 /**
63 * Init Effect — declares dependencies via `yield*` and returns the runner.
64 * Lets multiple Action definitions share resolved services.
65 */
66 export type ActionInit<In extends object | undefined, Out, Req> = Effect.Effect<
67 ActionRunner<In, Out, any>,
68 any,
69 Req
70 >;
71
72 // ── Public API ─────────────────────────────────────────────────────────────
73 //
74 // Direct runner:
75 //
76 // const Sync = Action("Sync", Effect.fn(function* (input: { table: string }) {
77 // return { rows: 42 };
78 // }));
79 //
80 // Init constructor — pulls in dependencies, returns the runner. The init
81 // Effect's `Req` channel bubbles up to the call site:
82 //
83 // const Sync = Action("Sync", Effect.gen(function* () {
84 // const db = yield* Database;
85 // return Effect.fn(function* (input: { table: string }) {
86 // return { rows: yield* db.count(input.table) };
87 // });
88 // }));
89 //
90 // Either way, call it inside a stack to register an instance — `yield*`
91 // returns `Output<Out>` ready to feed into downstream nodes:
92 //
93 // const rows = yield* Sync({ table: bucket.name });
94 // // rows: Output<{ rows: number }, never>
95 //
96 // Tagged form for split contract/implementation — declare the type with an
97 // interface, build the value with the no-arg overload, then supply the runner
98 // via `.make` (add the returned Layer to the stack's `providers`, or provide it
99 // locally with `Effect.provide`). The init passed to `.make` runs under the
100 // same capture context as the inline form, so `yield* output` accessors work:
101 //
102 // interface Sync extends Action<"Sync", { table: string }, { rows: number }> {}
103 // const Sync = Action<Sync, { table: string }, { rows: number }>()("Sync");
104 // const SyncLive = Sync.make(Effect.gen(function* () { /* ... */ }));
105
106 export function Action<Type extends string, In extends object | undefined, Out, Req = never>(
107 type: Type,
108 initOrRun: ActionRunner<In, Out, Req> | ActionInit<In, Out, Req>,
109 ): ActionClass<never, Type, In, Out, Req>;
110
111 export function Action<Self, In extends object | undefined, Out>(): <Type extends string>(
112 type: Type,
113 ) => ActionClass<Self, Type, In, Out, Self>;
114
115 export function Action(...args: any[]): any {
116 if (args.length === 0) {
117 // Tagged form: Action<Self, In, Out>()(type)
118 return (type: string) => makeActionClass(type, undefined);
119 }
120 // Inline form: Action(type, runnerOrInit)
121 const [type, initOrRun] = args as [
122 string,
123 ActionRunner<any, any, any> | ActionInit<any, any, any>,
124 ];
125 return makeActionClass(type, initOrRun);
126 }
127
128 export interface ActionClass<Self, Type extends string, In extends object | undefined, Out, Req> {
129 readonly Type: Type;
130 /**
131 * Default form — uses `Type` as the LogicalId. One instance per Action
132 * definition (the common case for deploy-time work). Returns the Action's
133 * output as `Output<Out>`.
134 */
135 (input: { [k in keyof In]: Input<In[k]> }): Effect.Effect<
136 Output.ToOutput<Out, never>,
137 never,
138 Req | Stack
139 >;
140 /**
141 * Explicit-id form — register multiple instances of the same Action
142 * definition under distinct logical ids.
143 */
144 (
145 id: string,
146 input: { [k in keyof In]: Input<In[k]> },
147 ): Effect.Effect<Output.ToOutput<Out, never>, never, Req | Stack>;
148 /**
149 * Tagged-only: bind an init Effect to this Action's Self tag. Add the
150 * returned Layer to the stack's `providers`.
151 */
152 make: [Self] extends [never]
153 ? never
154 : <R = never>(
155 init: ActionRunner<In, Out, R> | ActionInit<In, Out, R>,
156 ) => Layer.Layer<Self, never, R>;
157 /** Tagged-only: the Context tag holding the resolved runner. */
158 readonly Self: [Self] extends [never] ? never : Context.Service<Self, ActionRunner<In, Out, any>>;
159 }
160
161 const isRunnerEffect = (
162 v: ActionRunner<any, any, any> | ActionInit<any, any, any>,
163 ): v is ActionInit<any, any, any> => Effect.isEffect(v as any);
164
165 const makeActionClass = (
166 type: string,
167 baked: ActionRunner<any, any, any> | ActionInit<any, any, any> | undefined,
168 ): any => {
169 // Pre-resolve baked init/runner into a single Effect<Runner, _, Req>. Use
170 // Effect.cached so the init's body runs at most once per process — every
171 // action instance after the first reuses the resolved runner without paying
172 // the init cost (or re-yielding its dependencies).
173 let resolveRunner: Effect.Effect<ActionRunner<any, any, any>, any, any> | undefined;
174 if (baked !== undefined) {
175 resolveRunner = isRunnerEffect(baked)
176 ? baked.pipe(Effect.cached, Effect.runSync)
177 : Effect.succeed(baked);
178 }
179
180 // Tagged form needs a Context tag so the user can supply the runner
181 // through a Layer. Inline form bakes the runner in and skips the tag.
182 const SelfTag = baked
183 ? undefined
184 : Context.Service<any, ActionRunner<any, any, any>>(`alchemy/Action<${type}>`);
185
186 // Outputs referenced via `yield* output` inside the init Effect land here,
187 // recorded by the capture RuntimeContext. Shared per definition — the init
188 // runs at most once (Effect.cached), so captures are inherently
189 // per-definition, matching how the init's `Req` bubbles per definition.
190 const captures: Record<string, Output.Output> = {};
191 const captureContext = makeCaptureContext(captures);
192
193 const constructor = (...args: [any] | [string, any]) => {
194 const [id, input] = args.length === 1 ? [type, args[0]] : (args as [string, any]);
195 return Effect.gen(function* () {
196 const run = resolveRunner
197 ? yield* resolveRunner.pipe(Effect.provideService(RuntimeContext, captureContext))
198 : ((yield* SelfTag!) as ActionRunner<any, any, any>);
199 return yield* registerAction(type, id, input, run, captures);
200 });
201 };
202
203 const extra: Record<string, any> = { Type: type };
204 if (SelfTag) {
205 extra.Self = SelfTag;
206 // `.make(initOrRun)` — accepts either a direct runner or an init Effect.
207 // For init form we use `Layer.effect` so the init's Req surfaces on the
208 // Layer, and run it under the capture RuntimeContext so `yield* output`
209 // accessors are recorded just like the inline form; for runners we use
210 // `Layer.succeed` (nothing to capture).
211 extra.make = <R>(initOrRun: ActionRunner<any, any, R> | ActionInit<any, any, R>) =>
212 isRunnerEffect(initOrRun)
213 ? Layer.effect(
214 SelfTag,
215 (initOrRun as ActionInit<any, any, R>).pipe(
216 Effect.provideService(RuntimeContext, captureContext),
217 ),
218 )
219 : Layer.succeed(SelfTag, initOrRun as ActionRunner<any, any, any>);
220 }
221 return Object.assign(constructor, extra);
222 };
223
224 const registerAction = <Type extends string, In extends object | undefined, Out>(
225 type: Type,
226 id: string,
227 input: any,
228 run: ActionRunner<In, Out, any>,
229 captures: Record<string, Output.Output>,
230 ): Effect.Effect<Output.ToOutput<Out, never>, never, Stack> =>
231 Effect.gen(function* () {
232 const stack = yield* Stack;
233 const namespace = yield* CurrentNamespace;
234 const fqn = toFqn(namespace, id);
235
236 const actions = (stack.actions ??= {});
237 const existing = actions[fqn];
238 if (existing) return Output.of(existing as any) as unknown as Output.ToOutput<Out, never>;
239
240 // FQN collision check: actions share the same FQN namespace as resources
241 // so the dependency graph stays unified. Rejecting overlaps here makes
242 // the constraint obvious at registration time.
243 if (stack.resources[fqn]) {
244 return yield* Effect.die(
245 new Error(`Action '${fqn}' collides with a Resource of the same logical id`),
246 );
247 }
248
249 const target: ActionLike<Type, In, Out> = {
250 Kind: "action" as const,
251 Type: type,
252 Namespace: namespace,
253 FQN: fqn,
254 LogicalId: id,
255 Input: input,
256 Captures: captures,
257 Run: run,
258 Output: undefined as any,
259 };
260 (target as any).toString = () => `Action<${type}>(${id})`;
261
262 actions[fqn] = target as any;
263 // `yield* Sync({...})` returns `Output<Out>`. The engine writes the
264 // materialized value into `tracker[fqn]` during apply; `Output.of(action)`
265 // resolves a ResourceExpr by looking up `outputs[fqn]` — which is
266 // precisely that materialized value. Property access into the returned
267 // Output chains through the standard PropExpr proxy.
268 return Output.of(target as any) as unknown as Output.ToOutput<Out, never>;
269 });
270
271 /**
272 * Pipeable Action instance used internally by Plan/Apply. Users get an
273 * `Output<Out>` from `yield*` and don't normally see this.
274 */
275 export type Action<
276 Type extends string = string,
277 In extends object | undefined = any,
278 Out = any,
279 > = Pipeable & ActionLike<Type, In, Out>;