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

main
ts 325 lines 12 KB
Raw
1 import * as cloudcontrol from "@distilled.cloud/aws/cloudcontrol";
2 import { deepEqual, isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource as makeResource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Redacted from "effect/Redacted";
8 import * as Schedule from "effect/Schedule";
9 import type { Providers } from "../Providers.ts";
10
11 export interface CloudControlResourceProps {
12 /**
13 * The CloudFormation resource type name, e.g. `"AWS::SNS::Topic"` or
14 * `"AWS::SSM::Parameter"`. Changing the type replaces the resource. See the
15 * Cloud Control API's supported resource types in the AWS documentation.
16 */
17 typeName: string;
18 /**
19 * A specific version of the resource type to use. Defaults to the account's
20 * default version.
21 */
22 typeVersionId?: string;
23 /**
24 * The desired state of the resource as a plain object matching the CFN
25 * resource type's property schema (e.g. `{ Name, Type, Value }` for
26 * `AWS::SSM::Parameter`). Only the keys you specify are managed — on update,
27 * a JSON Patch is computed over exactly these keys, so create-only
28 * properties you never change are left untouched.
29 */
30 desiredState: Record<string, unknown>;
31 /**
32 * ARN of an IAM role Cloud Control assumes to perform the operation.
33 * Defaults to the deploying principal's credentials.
34 */
35 roleArn?: string;
36 }
37
38 export interface CloudControlResource extends makeResource<
39 "AWS.CloudControl.Resource",
40 CloudControlResourceProps,
41 {
42 /** The CloudFormation resource type name (e.g. `AWS::SSM::Parameter`). */
43 typeName: string;
44 /** The resource's primary identifier assigned by Cloud Control. */
45 identifier: string;
46 /** The observed properties of the resource as a plain object. */
47 properties: Record<string, unknown>;
48 },
49 never,
50 Providers
51 > {}
52
53 /**
54 * A generic AWS resource managed through the Cloud Control API — the escape
55 * hatch that covers hundreds of CloudFormation resource types with a single
56 * Alchemy resource.
57 *
58 * Provide a CloudFormation `typeName` and a `desiredState` object; the provider
59 * drives Cloud Control's asynchronous create/update/delete and polls the
60 * request token (bounded) until it reaches `SUCCESS`, surfacing a `FAILED`
61 * operation as a typed error rather than hanging. Updates are expressed as an
62 * RFC 6902 JSON Patch computed over the keys you specify.
63 * ### Managing a Resource
64 * **Example:** SSM Parameter
65 * ```typescript
66 * const param = yield* CloudControl.Resource("Greeting", {
67 * typeName: "AWS::SSM::Parameter",
68 * desiredState: {
69 * Name: "/app/greeting",
70 * Type: "String",
71 * Value: "hello",
72 * },
73 * });
74 * // param.identifier -> "/app/greeting"
75 * // param.properties.Value -> "hello"
76 * ```
77 *
78 * **Example:** SNS Topic
79 * ```typescript
80 * const topic = yield* CloudControl.Resource("Alerts", {
81 * typeName: "AWS::SNS::Topic",
82 * desiredState: { TopicName: "alerts", DisplayName: "Alerts" },
83 * });
84 * // topic.identifier -> "arn:aws:sns:us-west-2:...:alerts"
85 * ```
86 *
87 * @resource
88 */
89 export const Resource = makeResource<CloudControlResource>("AWS.CloudControl.Resource");
90
91 class ResourceRequestNotSettled extends Data.TaggedError("ResourceRequestNotSettled")<{
92 readonly requestToken: string;
93 readonly status: string;
94 }> {}
95
96 class ResourceRequestFailed extends Data.TaggedError("ResourceRequestFailed")<{
97 readonly typeName: string;
98 readonly operation: string;
99 readonly errorCode: string | undefined;
100 readonly statusMessage: string | undefined;
101 }> {}
102
103 /** Unwrap distilled's sensitive-string decoding to a plain string. */
104 const plain = (value: string | Redacted.Redacted<string> | undefined): string | undefined =>
105 value === undefined || typeof value === "string" ? value : Redacted.value(value);
106
107 const parseProperties = (
108 properties: string | Redacted.Redacted<string> | undefined,
109 ): Record<string, unknown> => {
110 const raw = plain(properties);
111 if (raw === undefined) return {};
112 try {
113 const parsed = JSON.parse(raw);
114 return parsed !== null && typeof parsed === "object" ? parsed : {};
115 } catch {
116 return {};
117 }
118 };
119
120 /** RFC 6901 escape for a JSON Pointer path segment. */
121 const escapePointer = (key: string): string => key.replace(/~/g, "~0").replace(/\//g, "~1");
122
123 /**
124 * Build an RFC 6902 JSON Patch that converges the observed properties to the
125 * user-specified desired state. Only keys present in `desired` are touched —
126 * create-only properties the user never changes are left alone (patching them
127 * would trigger `NotUpdatableException`).
128 */
129 const buildPatch = (
130 observed: Record<string, unknown>,
131 desired: Record<string, unknown>,
132 ): Array<{ op: "add" | "replace"; path: string; value: unknown }> =>
133 Object.entries(desired).flatMap(([key, value]) => {
134 const hasKey = Object.prototype.hasOwnProperty.call(observed, key);
135 if (hasKey && deepEqual(observed[key], value)) {
136 return [];
137 }
138 return [
139 {
140 op: hasKey ? ("replace" as const) : ("add" as const),
141 path: `/${escapePointer(key)}`,
142 value,
143 },
144 ];
145 });
146
147 /**
148 * Normalize `AWS::SSM::Document` state before diffing. SSM returns JSON
149 * `Content` as a formatted string, so compare it structurally, and omits
150 * the write-only `UpdateMethod`, which selects how a real change is applied
151 * rather than describing persistent document state — resend it only
152 * alongside an actual change.
153 *
154 * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ssm-document.html
155 */
156 const resourcePatch = (
157 typeName: string,
158 observed: Record<string, unknown>,
159 desired: Record<string, unknown>,
160 ) => {
161 if (typeName !== "AWS::SSM::Document") return buildPatch(observed, desired);
162 const { UpdateMethod, ...document } = desired;
163 const normalizeDocument = (value: Record<string, unknown>) =>
164 value.DocumentFormat === "JSON" && typeof value.Content === "string"
165 ? { ...value, Content: JSON.parse(value.Content) }
166 : value;
167 const patch = buildPatch(normalizeDocument(observed), normalizeDocument(document));
168 return patch.length > 0 && UpdateMethod !== undefined
169 ? [...patch, ...buildPatch(observed, { UpdateMethod })]
170 : patch;
171 };
172
173 export const CloudControlResourceProvider = () =>
174 Provider.effect(
175 Resource,
176 Effect.gen(function* () {
177 /**
178 * Poll a Cloud Control request token until the operation settles.
179 * Operations are typically fast (seconds); budget ~5 min (60 * 5s).
180 * Returns the terminal ProgressEvent, failing on FAILED.
181 */
182 const waitForRequest = Effect.fn(function* (requestToken: string, typeName: string) {
183 const event = yield* cloudcontrol
184 .getResourceRequestStatus({ RequestToken: requestToken })
185 .pipe(
186 Effect.map((r) => r.ProgressEvent),
187 Effect.flatMap((e) => {
188 const status = e?.OperationStatus;
189 if (
190 status === "PENDING" ||
191 status === "IN_PROGRESS" ||
192 status === "CANCEL_IN_PROGRESS"
193 ) {
194 return Effect.fail(
195 new ResourceRequestNotSettled({
196 requestToken,
197 status: status ?? "UNKNOWN",
198 }),
199 );
200 }
201 return Effect.succeed(e);
202 }),
203 Effect.retry({
204 while: (e) => e._tag === "ResourceRequestNotSettled",
205 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(60)]),
206 }),
207 );
208 if (event?.OperationStatus !== "SUCCESS") {
209 return yield* new ResourceRequestFailed({
210 typeName,
211 operation: event?.Operation ?? "UNKNOWN",
212 errorCode: event?.ErrorCode,
213 statusMessage: event?.StatusMessage,
214 });
215 }
216 return event;
217 });
218
219 /** Read live resource properties; a missing resource reads as absent. */
220 const getResource = Effect.fn(function* (typeName: string, identifier: string) {
221 return yield* cloudcontrol.getResource({ TypeName: typeName, Identifier: identifier }).pipe(
222 Effect.map((r) => r.ResourceDescription),
223 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
224 );
225 });
226
227 return {
228 stables: ["typeName", "identifier"],
229
230 diff: Effect.fn(function* ({ olds, news }) {
231 if (!isResolved(news)) return undefined;
232 if ((olds?.typeName ?? undefined) !== (news?.typeName ?? undefined)) {
233 return { action: "replace" } as const;
234 }
235 }),
236
237 read: Effect.fn(function* ({ output }) {
238 if (output?.identifier === undefined) return undefined;
239 const description = yield* getResource(output.typeName, output.identifier);
240 if (description?.Identifier === undefined) return undefined;
241 return {
242 typeName: output.typeName,
243 identifier: description.Identifier,
244 properties: parseProperties(description.Properties),
245 };
246 }),
247
248 reconcile: Effect.fn(function* ({ news, output, session }) {
249 const typeName = news.typeName;
250
251 // 1. Observe — cloud state is authoritative; output is only an id
252 // cache.
253 let identifier = output?.identifier;
254 let description =
255 identifier !== undefined ? yield* getResource(typeName, identifier) : undefined;
256
257 // 2. Ensure — create if missing, then poll to SUCCESS.
258 if (description === undefined) {
259 const created = yield* cloudcontrol.createResource({
260 TypeName: typeName,
261 TypeVersionId: news.typeVersionId,
262 RoleArn: news.roleArn,
263 DesiredState: JSON.stringify(news.desiredState),
264 });
265 const settled = yield* waitForRequest(created.ProgressEvent!.RequestToken!, typeName);
266 identifier = settled.Identifier!;
267 description = yield* getResource(typeName, identifier);
268 } else {
269 // 3. Sync — patch only the drifted user-specified keys.
270 identifier = description.Identifier!;
271 const patch = resourcePatch(
272 typeName,
273 parseProperties(description.Properties),
274 news.desiredState,
275 );
276 if (patch.length > 0) {
277 const updated = yield* cloudcontrol.updateResource({
278 TypeName: typeName,
279 TypeVersionId: news.typeVersionId,
280 RoleArn: news.roleArn,
281 Identifier: identifier,
282 PatchDocument: JSON.stringify(patch),
283 });
284 yield* waitForRequest(updated.ProgressEvent!.RequestToken!, typeName);
285 description = yield* getResource(typeName, identifier);
286 }
287 }
288
289 // 4. Return fresh attributes.
290 yield* session.note(identifier);
291 return {
292 typeName,
293 identifier,
294 properties: parseProperties(description?.Properties),
295 };
296 }),
297
298 delete: Effect.fn(function* ({ output }) {
299 const deleted = yield* cloudcontrol
300 .deleteResource({
301 TypeName: output.typeName,
302 Identifier: output.identifier,
303 })
304 .pipe(
305 Effect.map((r) => r.ProgressEvent),
306 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
307 );
308 if (deleted?.RequestToken !== undefined) {
309 yield* waitForRequest(deleted.RequestToken, output.typeName).pipe(
310 // A resource already gone by the time deletion settles is not an
311 // error.
312 Effect.catchTag("ResourceRequestFailed", (e) =>
313 e.errorCode === "NotFound" ? Effect.void : Effect.fail(e),
314 ),
315 );
316 }
317 }),
318
319 // Cloud Control's ListResources requires a TypeName; there is no
320 // global enumeration across every managed type, so the generic
321 // escape-hatch resource is not listable.
322 list: () => Effect.succeed([]),
323 };
324 }),
325 );