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

main
ts 234 lines 8.24 KB
Raw
1 import * as contacts from "@distilled.cloud/aws/ssm-contacts";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10
11 /** How Incident Manager engages the contact through this channel. */
12 export type ContactChannelType = "SMS" | "VOICE" | "EMAIL";
13
14 export interface ContactChannelProps {
15 /**
16 * The ARN of the contact this channel belongs to. Changing it replaces the
17 * channel.
18 */
19 contactId: string;
20
21 /**
22 * The name of the contact channel.
23 *
24 * @default ${app}-${id}-${stage}-${suffix}
25 */
26 name?: string;
27
28 /**
29 * The channel type: `SMS`, `VOICE`, or `EMAIL`. Changing it replaces the
30 * channel.
31 */
32 type: ContactChannelType;
33
34 /**
35 * The address of the channel: an E.164 phone number (`+15551234567`) for
36 * `SMS`/`VOICE`, or an email address for `EMAIL`.
37 */
38 deliveryAddress: contacts.ContactChannelAddress;
39
40 /**
41 * When `true`, the channel is created without sending an activation code —
42 * the contact's device does not receive a message. Activate later with
43 * `sendActivationCode` + `activateContactChannel`.
44 *
45 * @default false (AWS sends an activation code on create)
46 */
47 deferActivation?: boolean;
48 }
49
50 /** @resource */
51 export interface ContactChannel extends Resource<
52 "AWS.SSMContacts.ContactChannel",
53 ContactChannelProps,
54 {
55 /** ARN of the contact channel. */
56 contactChannelArn: string;
57 /** ARN of the owning contact. */
58 contactArn: string;
59 /** Name of the channel. */
60 name: string;
61 /** The channel type. */
62 type: string;
63 /** `ACTIVATED` or `NOT_ACTIVATED`. */
64 activationStatus: string | undefined;
65 },
66 never,
67 Providers
68 > {}
69
70 /**
71 * An Incident Manager contact channel — the method (SMS, voice, or email)
72 * that Incident Manager uses to engage a contact during an incident.
73 *
74 * ### Creating Contact Channels
75 * **Example:** Email channel without activation
76 * ```typescript
77 * const email = yield* SSMContacts.ContactChannel("Email", {
78 * contactId: oncall.contactArn,
79 * type: "EMAIL",
80 * deliveryAddress: { SimpleAddress: "oncall@example.com" },
81 * deferActivation: true,
82 * });
83 * ```
84 *
85 * **Example:** SMS channel
86 * ```typescript
87 * const sms = yield* SSMContacts.ContactChannel("Sms", {
88 * contactId: oncall.contactArn,
89 * type: "SMS",
90 * deliveryAddress: { SimpleAddress: "+15551234567" },
91 * });
92 * ```
93 */
94 const ContactChannelResource = Resource<ContactChannel>("AWS.SSMContacts.ContactChannel");
95
96 export { ContactChannelResource as ContactChannel };
97
98 export const ContactChannelProvider = () =>
99 Provider.effect(
100 ContactChannelResource,
101 Effect.gen(function* () {
102 const createName = Effect.fn(function* (id: string, props: { name?: string }) {
103 return props.name ?? (yield* createPhysicalName({ id, maxLength: 200 }));
104 });
105
106 const getChannel = (arn: string) =>
107 contacts
108 .getContactChannel({ ContactChannelId: arn })
109 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
110
111 // A channel's ARN embeds a generated UUID, so without cached output we
112 // fall back to searching the owning contact's channels by name + type.
113 const findChannel = (contactId: string, name: string, type: string) =>
114 contacts.listContactChannels.items({ ContactId: contactId }).pipe(
115 Stream.filter((channel) => channel.Name === name && (channel.Type ?? type) === type),
116 Stream.take(1),
117 Stream.runCollect,
118 Effect.map((chunk) => Array.from(chunk)[0]),
119 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
120 );
121
122 const buildAttrs = (channel: {
123 ContactChannelArn: string;
124 ContactArn: string;
125 Name: string;
126 Type?: string | undefined;
127 ActivationStatus?: string | undefined;
128 }) => ({
129 contactChannelArn: channel.ContactChannelArn,
130 contactArn: channel.ContactArn,
131 name: channel.Name,
132 type: channel.Type ?? "",
133 activationStatus: channel.ActivationStatus,
134 });
135
136 return ContactChannelResource.Provider.of({
137 stables: ["contactChannelArn", "contactArn", "type"],
138
139 // Sub-resource keyed by its parent contact — enumeration across all
140 // contacts is not meaningful here.
141 list: () => Effect.succeed([]),
142
143 read: Effect.fn(function* ({ id, olds, output }) {
144 if (output !== undefined) {
145 const channel = yield* getChannel(output.contactChannelArn);
146 if (channel === undefined) return undefined;
147 return buildAttrs(channel);
148 }
149 // No cached identifier — recover by searching the parent contact
150 // from prior props. Channels are not taggable, so a match found
151 // this way cannot prove ownership.
152 if (olds?.contactId === undefined) return undefined;
153 const name = yield* createName(id, olds);
154 const found = yield* findChannel(olds.contactId, name, olds.type);
155 return found === undefined ? undefined : Unowned(buildAttrs(found));
156 }),
157
158 // The owning contact and channel type are create-only; name and
159 // delivery address update in place.
160 diff: Effect.fn(function* ({ news, olds }) {
161 if (!isResolved(news)) return undefined;
162 if (olds.contactId !== news.contactId) {
163 return { action: "replace" } as const;
164 }
165 if (olds.type !== news.type) return { action: "replace" } as const;
166 }),
167
168 reconcile: Effect.fn(function* ({ id, news, output, session }) {
169 const name = output?.name ?? (yield* createName(id, news));
170
171 // 1. OBSERVE — by cached ARN first, then by (contact, name, type).
172 let channel = output ? yield* getChannel(output.contactChannelArn) : undefined;
173 if (channel === undefined) {
174 const found = yield* findChannel(news.contactId, name, news.type);
175 if (found !== undefined) {
176 channel = yield* getChannel(found.ContactChannelArn);
177 }
178 }
179
180 // 2. ENSURE — create if missing; tolerate the already-exists race
181 // by re-searching.
182 if (channel === undefined) {
183 yield* session.note(`creating contact channel ${name}`);
184 const arn = yield* contacts
185 .createContactChannel({
186 ContactId: news.contactId,
187 Name: name,
188 Type: news.type,
189 DeliveryAddress: news.deliveryAddress,
190 DeferActivation: news.deferActivation,
191 })
192 .pipe(
193 Effect.map((r) => r.ContactChannelArn),
194 Effect.catchTag("ConflictException", () =>
195 findChannel(news.contactId, name, news.type).pipe(
196 Effect.map((found) => found!.ContactChannelArn),
197 ),
198 ),
199 );
200 channel = (yield* getChannel(arn))!;
201 }
202
203 // 3. SYNC name + delivery address — observed vs desired.
204 const nameDelta = channel.Name !== name;
205 const addressDelta =
206 (channel.DeliveryAddress.SimpleAddress ?? "") !==
207 (news.deliveryAddress.SimpleAddress ?? "");
208 if (nameDelta || addressDelta) {
209 yield* contacts.updateContactChannel({
210 ContactChannelId: channel.ContactChannelArn,
211 Name: name,
212 DeliveryAddress: news.deliveryAddress,
213 });
214 }
215
216 // 4. RETURN fresh attributes.
217 const final = (yield* getChannel(channel.ContactChannelArn))!;
218 yield* session.note(final.ContactChannelArn);
219 return buildAttrs(final);
220 }),
221
222 delete: Effect.fn(function* ({ output }) {
223 yield* contacts
224 .deleteContactChannel({
225 ContactChannelId: output.contactChannelArn,
226 })
227 .pipe(
228 Effect.asVoid,
229 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
230 );
231 }),
232 });
233 }),
234 );