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

main
ts 122 lines 4.55 KB
Raw
1 import * as Domain from "@alchemy.run/domain";
2 import * as Cause from "effect/Cause";
3 import * as Effect from "effect/Effect";
4 import * as Exit from "effect/Exit";
5 import * as Schema from "effect/Schema";
6 import { Activity, DurableDeferred, Workflow } from "effect/workflow";
7 import { Account } from "../Account/Account.aggregate.ts";
8 import { AccountId } from "../Account/Account.id.ts";
9 import { CreditTransfer } from "../Account/CreditTransfer.command.ts";
10 import { DebitTransfer } from "../Account/DebitTransfer.command.ts";
11 import { Frozen } from "../Account/Frozen.rejection.ts";
12 import { InsufficientFunds } from "../Account/InsufficientFunds.rejection.ts";
13 import { NotOpen } from "../Account/NotOpen.rejection.ts";
14 import { NotOwner } from "../Account/NotOwner.rejection.ts";
15 import { RefundTransfer } from "../Account/RefundTransfer.command.ts";
16 import { Actor } from "../Actor.ts";
17 import { Cents } from "../Money.ts";
18 import { CompleteTransfer } from "./CompleteTransfer.command.ts";
19 import { FailTransfer } from "./FailTransfer.command.ts";
20 import { Transfer } from "./Transfer.aggregate.ts";
21 import { TransferId } from "./Transfer.id.ts";
22
23 /** The destination account isn't open, so the money can't arrive. */
24 export class DestinationClosed extends Domain.Rejection("DestinationClosed") {}
25
26 /**
27 * What the Transfer decided about a large transfer: an agent approved it, or
28 * its approval window closed first.
29 */
30 export const Decision = DurableDeferred.make("decision", {
31 success: Schema.Literals(["approved", "expired"]),
32 });
33
34 /**
35 * Moves money between two accounts on behalf of the requester: waits for the
36 * Transfer to decide a large transfer, debits the source, credits the
37 * destination, and refunds the debit if the credit fails. The outcome is
38 * recorded on the Transfer either way.
39 */
40 export class ExecuteTransfer extends Domain.Saga("ExecuteTransfer", {
41 key: TransferId,
42 input: {
43 from: AccountId,
44 to: AccountId,
45 amount: Cents,
46 requestedBy: Actor,
47 needsApproval: Schema.Boolean,
48 },
49 rejects: [NotOpen, NotOwner, Frozen, InsufficientFunds, DestinationClosed],
50 }) {}
51
52 /** Why a transfer failed, in the words the Transfer records. */
53 const reasonOf = (cause: Cause.Cause<unknown>): string => {
54 const rejection = cause.reasons.find((reason) => reason._tag === "Fail");
55 const error =
56 rejection?._tag === "Fail" ? (rejection.error as { readonly _tag: string }) : undefined;
57 switch (error?._tag) {
58 case "NotOpen":
59 return "source account not open";
60 case "NotOwner":
61 return "not your account";
62 case "Frozen":
63 return `source frozen: ${(error as Frozen).reason}`;
64 case "InsufficientFunds":
65 return "insufficient funds";
66 case "DestinationClosed":
67 return "destination account not open";
68 default:
69 return "interrupted";
70 }
71 };
72
73 export const ExecuteTransferLive = ExecuteTransfer.toLayer(
74 Effect.gen(function* () {
75 const accounts = yield* Account;
76 const transfers = yield* Transfer;
77
78 return Effect.fn(function* ({ key, from, to, amount, requestedBy, needsApproval }) {
79 // Registered first, so it runs last: after any compensations.
80 yield* Workflow.addFinalizer((exit) =>
81 Exit.isSuccess(exit)
82 ? Effect.void
83 : Activity.make({
84 name: "record-failure",
85 execute: transfers.send(key, new FailTransfer({ reason: reasonOf(exit.cause) })),
86 }).pipe(Effect.orDie),
87 );
88
89 if (needsApproval) {
90 // The Transfer decides between approval and expiry; nothing to do if it expired.
91 if ((yield* DurableDeferred.await(Decision)) === "expired") return;
92 }
93
94 // Debit first: if the credit fails, the money is refunded, so it's never created.
95 yield* Activity.make({
96 name: "debit",
97 error: Schema.Union([NotOpen, NotOwner, Frozen, InsufficientFunds]),
98 execute: accounts.send(from, new DebitTransfer({ transferId: key, amount, requestedBy })),
99 }).pipe(
100 ExecuteTransfer.withCompensation(() =>
101 Activity.make({
102 name: "refund",
103 execute: accounts.send(from, new RefundTransfer({ transferId: key, amount })),
104 }),
105 ),
106 );
107
108 yield* Activity.make({
109 name: "credit",
110 error: DestinationClosed,
111 execute: accounts
112 .send(to, new CreditTransfer({ transferId: key, amount }))
113 .pipe(Effect.catchTag("NotOpen", () => Effect.fail(new DestinationClosed()))),
114 });
115
116 yield* Activity.make({
117 name: "complete",
118 execute: transfers.send(key, new CompleteTransfer()),
119 });
120 });
121 }),
122 );