@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 398 lines 12.8 KB
Raw
1 import * as Cause from "effect/Cause";
2 import * as Context from "effect/Context";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Exit from "effect/Exit";
6 import * as Layer from "effect/Layer";
7 import * as Schema from "effect/Schema";
8 import { DefinitionError, ReservedOperation } from "./DefinitionError.ts";
9 import type { Fields } from "./Event.ts";
10 import * as Telemetry from "./Telemetry.ts";
11
12 type OpImpl = (args: unknown) => Effect.Effect<unknown, unknown, unknown>;
13
14 /**
15 * Trace every call to an external system: one client span per call, named
16 * after the system and operation, plus a call count by outcome.
17 *
18 * @internal
19 */
20 export const observeOps = (
21 system: string,
22 impl: Readonly<Record<string, OpImpl>>,
23 ): Record<string, OpImpl> =>
24 Object.fromEntries(
25 Object.entries(impl).map(([op, call]) => [
26 op,
27 (args: unknown) =>
28 call(args).pipe(
29 Effect.onExit((exit) =>
30 Telemetry.record(Telemetry.externalCalls, {
31 "domain.system": system,
32 "domain.operation": op,
33 "domain.outcome": Exit.isSuccess(exit) ? "ok" : "failed",
34 }),
35 ),
36 Effect.withSpan(`Domain.external ${system}.${op}`, {
37 kind: "client",
38 attributes: { "domain.system": system, "domain.operation": op },
39 }),
40 ),
41 ]),
42 );
43
44 /**
45 * Sees every call to an implemented external system. A story provides one, so
46 * it can assert what each real call was sent and what it returned.
47 *
48 * @internal
49 */
50 export interface CallRecorder {
51 readonly record: (
52 system: string,
53 op: string,
54 args: unknown,
55 call: Effect.Effect<unknown, unknown, unknown>,
56 ) => Effect.Effect<unknown, unknown, unknown>;
57 }
58
59 /** @internal */
60 export const CallRecorder = Context.Reference<CallRecorder | undefined>(
61 "alchemy/Domain/ExternalSystem/CallRecorder",
62 { defaultValue: () => undefined },
63 );
64
65 const recordOps = (
66 system: string,
67 impl: Readonly<Record<string, OpImpl>>,
68 ): Record<string, OpImpl> =>
69 Object.fromEntries(
70 Object.entries(impl).map(([op, call]) => [
71 op,
72 Effect.fn(function* (args: unknown) {
73 const recorder = yield* CallRecorder;
74 return yield* recorder ? recorder.record(system, op, args, call(args)) : call(args);
75 }),
76 ]),
77 );
78
79 /**
80 * A call to an external system broke its declared schema: the model sent
81 * arguments the operation's `args` reject, or the adapter answered with a
82 * value or error the operation's `success` or `error` reject. It is a defect,
83 * not a business error, because the declaration and the implementation
84 * disagree.
85 */
86 export class ExternalSystemSchemaError extends Data.TaggedError("ExternalSystemSchemaError")<{
87 readonly system: string;
88 readonly op: string;
89 /** The side of the call the schema rejected. */
90 readonly part: "args" | "success" | "error";
91 readonly message: string;
92 }> {}
93
94 const describePart = {
95 args: "was called with arguments its schema rejects",
96 success: "returned a value its success schema rejects",
97 error: "failed with an error its error schema rejects",
98 } as const;
99
100 /** A built check: the value its schema accepts, or an {@link ExternalSystemSchemaError} defect. */
101 type Check = (value: unknown) => Exit.Exit<unknown>;
102
103 /** One operation's built checks. `args` and `success` are absent when it declares none. */
104 interface OpChecks {
105 readonly args: Check | undefined;
106 readonly success: Check | undefined;
107 readonly error: Check;
108 }
109
110 const makeCheck = (
111 system: string,
112 op: string,
113 part: keyof typeof describePart,
114 schema: Schema.Top,
115 ): Check => {
116 // Only the type side: it validates values and never re-runs a transformation.
117 const decode = Schema.decodeUnknownExit(Schema.toType(schema) as Schema.Decoder<unknown>) as (
118 value: unknown,
119 ) => Exit.Exit<unknown, Schema.SchemaError>;
120 return (value) => {
121 const exit = decode(value);
122 if (Exit.isSuccess(exit)) return Exit.succeed(exit.value);
123 const found = Cause.findError(exit.cause);
124 return Exit.die(
125 found._tag === "Success"
126 ? new ExternalSystemSchemaError({
127 system,
128 op,
129 part,
130 message: `${system}.${op} ${describePart[part]}\n${found.success.message}`,
131 })
132 : // A defect inside the schema passes through.
133 Cause.squash(exit.cause),
134 );
135 };
136 };
137
138 /**
139 * Build the checks for every operation of a system, once: its arguments, its
140 * success value and its typed error.
141 *
142 * @internal
143 */
144 export const compileChecks = (
145 system: string,
146 ops: Readonly<Record<string, OpSpec>>,
147 ): Effect.Effect<Readonly<Record<string, OpChecks>>> =>
148 Effect.sync(() =>
149 Object.fromEntries(
150 Object.entries(ops).map(([op, spec]) => [
151 op,
152 {
153 args:
154 spec.args === undefined
155 ? undefined
156 : makeCheck(system, op, "args", Schema.Struct(spec.args)),
157 success:
158 spec.success === undefined
159 ? undefined
160 : makeCheck(system, op, "success", successSchema(spec)),
161 error: makeCheck(system, op, "error", errorSchema(spec)),
162 } satisfies OpChecks,
163 ]),
164 ),
165 );
166
167 /**
168 * Check every call against its operation's built checks: the arguments before
169 * the implementation runs, and its success value or typed error after. A value
170 * a schema rejects becomes an {@link ExternalSystemSchemaError} defect. Defects
171 * pass through.
172 *
173 * @internal
174 */
175 export const validateOps = (
176 checks: Readonly<Record<string, OpChecks>>,
177 impl: Readonly<Record<string, OpImpl>>,
178 ): Record<string, OpImpl> =>
179 Object.fromEntries(
180 Object.entries(impl).map(([op, call]): [string, OpImpl] => {
181 const check = checks[op];
182 if (check === undefined) return [op, call];
183 const { args, success, error } = check;
184 const checked: OpImpl = (input) =>
185 Effect.matchEffect(args ? Effect.flatMap(args(input), call) : call(input), {
186 onSuccess: success ?? Effect.succeed,
187 onFailure: (failure) => Effect.flatMap(error(failure), Effect.fail),
188 });
189 return [op, checked];
190 }),
191 );
192
193 /**
194 * Options for {@link ExternalSystemClass.toLayer}.
195 */
196 export interface ToLayerOptions {
197 /**
198 * Check every call against the operation's schemas. Defaults to `true`.
199 * Turn it off only when the check costs too much, for example on a large
200 * payload an adapter already validates.
201 */
202 readonly validate?: boolean;
203 }
204
205 /**
206 * One operation of an external system: its arguments, success value and business errors.
207 * `error` is one schema, or a list of them when the vendor can refuse in several ways.
208 */
209 export interface OpSpec {
210 readonly args?: Fields;
211 readonly success?: Fields | Schema.Top;
212 readonly error?: Schema.Top | ReadonlyArray<Schema.Top>;
213 }
214
215 type ArgsOf<S extends OpSpec> = S["args"] extends Fields ? Schema.Struct<S["args"]>["Type"] : void;
216 type SuccessOf<S extends OpSpec> = S["success"] extends Schema.Top
217 ? S["success"]["Type"]
218 : S["success"] extends Fields
219 ? Schema.Struct<S["success"]>["Type"]
220 : void;
221 type ErrorOf<S extends OpSpec> =
222 S["error"] extends ReadonlyArray<Schema.Top>
223 ? S["error"][number]["Type"]
224 : S["error"] extends Schema.Top
225 ? S["error"]["Type"]
226 : never;
227
228 /**
229 * The service shape of an external system: one Effect-returning function per operation.
230 */
231 export type Shape<Ops extends Record<string, OpSpec>> = {
232 readonly [K in keyof Ops]: (
233 args: ArgsOf<Ops[K]>,
234 ) => Effect.Effect<SuccessOf<Ops[K]>, ErrorOf<Ops[K]>>;
235 };
236
237 /**
238 * A reference to one external system operation, used by stories (`call`, `succeed`, `fail`).
239 */
240 export interface Op<Args = unknown, Success = unknown, Error = unknown> {
241 readonly kind: "ExternalSystemOp";
242 readonly system: string;
243 readonly op: string;
244 readonly "~args"?: Args;
245 readonly "~success"?: Success;
246 readonly "~error"?: Error;
247 }
248
249 /**
250 * Structural constraint satisfied by every external system class.
251 */
252 export interface Any extends Context.Key<unknown, unknown> {
253 readonly kind: "ExternalSystem";
254 readonly systemName: string;
255 readonly ops: Record<string, OpSpec>;
256 }
257
258 /** The requirement identifier of an external system class. */
259 export type Identifier<P extends Any> = P extends Context.Key<infer I, unknown> ? I : never;
260
261 /**
262 * Type-level identity of an external system in an Effect's requirements.
263 */
264 export interface ExternalSystemKey<Name extends string> {
265 readonly "~alchemy/Domain/ExternalSystem": Name;
266 }
267
268 const RESERVED = [
269 "name",
270 "length",
271 "prototype",
272 "kind",
273 "systemName",
274 "ops",
275 "toLayer",
276 "key",
277 ] as const;
278 type Reserved = (typeof RESERVED)[number];
279 const reserved = new Set<string>(RESERVED);
280
281 /**
282 * An outside system your model calls, such as a payment provider or a fraud
283 * scorer, declared as the operations the model uses. It's an Effect service:
284 * policies `yield*` it, an adapter implements it with `toLayer`, and stories
285 * answer its calls themselves, so the model depends on what it asks for and
286 * never on a vendor.
287 *
288 * ### Declaring an external system and an adapter
289 * **Example:** A fraud scorer
290 * ```typescript
291 * import * as Domain from "@alchemy.run/domain";
292 * import * as Effect from "effect/Effect";
293 * import * as Schema from "effect/Schema";
294 *
295 * export class FraudCheck extends Domain.ExternalSystem("FraudCheck", {
296 * score: { args: { accountId: Schema.String, amount: Schema.Int }, success: { risk: Schema.Number } },
297 * }) {}
298 *
299 * export const SiftFraudCheck = FraudCheck.toLayer(
300 * Effect.succeed({
301 * score: ({ amount }) => Effect.succeed({ risk: amount >= 80_000 ? 0.95 : 0.05 }),
302 * }),
303 * );
304 * ```
305 *
306 * @primitive
307 */
308 export const make = <const Name extends string, const Ops extends Record<string, OpSpec>>(
309 name: Name,
310 // An operation named after a static of the class would replace it.
311 ops: Ops & { readonly [K in Extract<keyof Ops, Reserved>]: never },
312 ): ExternalSystemClass<Name, Ops> => {
313 const Tag = Context.Service<ExternalSystemKey<Name>, Shape<Ops>>()(
314 `alchemy/Domain/ExternalSystem/${name}`,
315 );
316 const cls = class extends Tag {
317 static readonly kind = "ExternalSystem" as const;
318 static readonly systemName: Name = name;
319 static readonly ops: Ops = ops;
320 /** Implement the external system with an Effect that builds its service. */
321 static toLayer<E, R>(
322 build: Effect.Effect<Shape<Ops>, E, R>,
323 options?: ToLayerOptions,
324 ): Layer.Layer<ExternalSystemKey<Name>, E, R> {
325 return Layer.effect(
326 Tag,
327 Effect.gen(function* () {
328 const clash = Object.keys(ops).find((op) => reserved.has(op));
329 if (clash !== undefined) {
330 return yield* Effect.die(
331 new DefinitionError({
332 reason: new ReservedOperation({ system: name, operation: clash }),
333 }),
334 );
335 }
336 const checks = options?.validate === false ? undefined : yield* compileChecks(name, ops);
337 const impl = (yield* build) as Record<string, OpImpl>;
338 const checked = checks === undefined ? impl : validateOps(checks, impl);
339 return observeOps(name, recordOps(name, checked)) as never;
340 }),
341 );
342 }
343 };
344 for (const op of Object.keys(ops)) {
345 // The signature rejects a reserved name; toLayer dies if one gets through.
346 if (reserved.has(op)) continue;
347 // oxlint-disable-next-line effecttsgo/floating-effect -- returns `cls`, which is Effect-able; nothing to run
348 Object.defineProperty(cls, op, {
349 value: { kind: "ExternalSystemOp", system: name, op } satisfies Op,
350 enumerable: true,
351 });
352 }
353 return cls as unknown as ExternalSystemClass<Name, Ops>;
354 };
355
356 /**
357 * The class type returned by {@link make}.
358 */
359 export type ExternalSystemClass<
360 Name extends string,
361 Ops extends Record<string, OpSpec>,
362 > = Context.ServiceClass<ExternalSystemKey<Name>, string, Shape<Ops>> & {
363 readonly kind: "ExternalSystem";
364 readonly systemName: Name;
365 readonly ops: Ops;
366 /**
367 * Implement the external system with an Effect that builds its service.
368 * Every call is checked against the operation's schemas unless
369 * `validate: false`.
370 */
371 toLayer<E, R>(
372 build: Effect.Effect<Shape<Ops>, E, R>,
373 options?: ToLayerOptions,
374 ): Layer.Layer<ExternalSystemKey<Name>, E, R>;
375 } & {
376 readonly [K in keyof Ops]: Op<ArgsOf<Ops[K]>, SuccessOf<Ops[K]>, ErrorOf<Ops[K]>>;
377 };
378
379 /** @internal */
380 export const successSchema = (spec: OpSpec): Schema.Top =>
381 spec.success === undefined
382 ? Schema.Void
383 : "ast" in (spec.success as object)
384 ? (spec.success as Schema.Top)
385 : Schema.Struct(spec.success as Fields);
386
387 /**
388 * The schema of an operation's declared `error`: the schema itself, a
389 * `Schema.Union` of a list, or `Schema.Never` when it declares none.
390 *
391 * @internal
392 */
393 export const errorSchema = (spec: OpSpec): Schema.Top =>
394 spec.error === undefined
395 ? Schema.Never
396 : Array.isArray(spec.error)
397 ? Schema.Union(spec.error as ReadonlyArray<Schema.Top>)
398 : (spec.error as Schema.Top);