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

main
ts 331 lines 12.1 KB
Raw
1 import * as mi from "@distilled.cloud/aws/iot-managed-integrations";
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 { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Redacted from "effect/Redacted";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13 import { syncManagedIntegrationsTags, toTagRecord, unwrapSensitive } from "./internal.ts";
14
15 export class ManagedThingUnexpectedResponse extends Data.TaggedError(
16 "ManagedThingUnexpectedResponse",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export interface ManagedThingProps {
23 /**
24 * Role of the device in Managed integrations: a `CONTROLLER` onboards and
25 * controls devices; a `DEVICE` is an endpoint. Changing the role replaces
26 * the managed thing.
27 */
28 role: mi.Role;
29 /**
30 * Authentication material used to onboard the device (e.g. the payload of
31 * a Wi-Fi setup or Zigbee QR bar code). This is a device-onboarding
32 * credential — wrap it with `Redacted.make(...)`. Create-only — changing
33 * it replaces the managed thing.
34 */
35 authenticationMaterial: Redacted.Redacted<string>;
36 /**
37 * Type of the authentication material.
38 * E.g. `WIFI_SETUP_QR_BAR_CODE`, `ZIGBEE_QR_BAR_CODE`, `ZWAVE_QR_BAR_CODE`.
39 * Create-only — changing it replaces the managed thing.
40 */
41 authenticationMaterialType: mi.AuthMaterialType;
42 /**
43 * Display name of the managed thing. If omitted, a unique name is generated
44 * from the app, stage, and logical ID.
45 */
46 name?: string;
47 /**
48 * Identifier of the credential locker used by the managed thing.
49 */
50 credentialLockerId?: string;
51 /**
52 * Owner of the managed thing.
53 */
54 owner?: string;
55 /**
56 * Serial number of the device.
57 */
58 serialNumber?: string;
59 /**
60 * Brand of the device.
61 */
62 brand?: string;
63 /**
64 * Model of the device.
65 */
66 model?: string;
67 /**
68 * Classification of the managed thing.
69 */
70 classification?: string;
71 /**
72 * Capability report of the device.
73 */
74 capabilityReport?: mi.CapabilityReport;
75 /**
76 * Metadata key-value pairs for the managed thing.
77 */
78 metaData?: Record<string, string>;
79 /**
80 * User-defined tags to apply to the managed thing.
81 */
82 tags?: Record<string, string>;
83 }
84
85 export interface ManagedThing extends Resource<
86 "AWS.IoTManagedIntegrations.ManagedThing",
87 ManagedThingProps,
88 {
89 /** Service-generated identifier of the managed thing. */
90 managedThingId: string;
91 /** ARN of the managed thing. */
92 managedThingArn: string;
93 /** Display name of the managed thing. */
94 managedThingName: string;
95 /** Role of the device (CONTROLLER or DEVICE). */
96 role: mi.Role;
97 /** Provisioning status of the managed thing. */
98 provisioningStatus: mi.ProvisioningStatus | undefined;
99 /** Tags applied to the managed thing (user + internal). */
100 tags: Record<string, string>;
101 },
102 never,
103 Providers
104 > {}
105
106 /**
107 * An AWS IoT Managed Integrations managed thing — the cloud representation of
108 * a device (or controller) onboarded through Managed integrations, carrying
109 * its identity, protocol, and capability data model.
110 *
111 * Creating a managed thing requires real device onboarding material (e.g. a
112 * Wi-Fi Simple Setup or Zigbee QR bar code payload). IoT Managed Integrations
113 * is a regional service available in a limited set of regions (e.g.
114 * `eu-west-1`, `ca-central-1`).
115 *
116 * ### Creating Managed Things
117 * **Example:** Controller from a Wi-Fi Setup QR Code
118 * ```typescript
119 * const thing = yield* ManagedThing("Hub", {
120 * role: "CONTROLLER",
121 * authenticationMaterial: Redacted.make(wifiSetupQrCodePayload),
122 * authenticationMaterialType: "WIFI_SETUP_QR_BAR_CODE",
123 * });
124 * ```
125 *
126 * **Example:** Device with a Credential Locker
127 * ```typescript
128 * const locker = yield* CredentialLocker("DeviceCredentials", {});
129 * const thing = yield* ManagedThing("Sensor", {
130 * role: "DEVICE",
131 * authenticationMaterial: Redacted.make(zigbeeQrCodePayload),
132 * authenticationMaterialType: "ZIGBEE_QR_BAR_CODE",
133 * credentialLockerId: locker.credentialLockerId,
134 * serialNumber: "SN-0001",
135 * });
136 * ```
137 *
138 * @resource
139 */
140 export const ManagedThing = Resource<ManagedThing>("AWS.IoTManagedIntegrations.ManagedThing");
141
142 export const ManagedThingProvider = () =>
143 Provider.effect(
144 ManagedThing,
145 Effect.gen(function* () {
146 const toName = (id: string, props: { name?: string } = {}) =>
147 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 64 });
148
149 const observeById = (identifier: string) =>
150 mi
151 .getManagedThing({ Identifier: identifier })
152 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
153
154 // Recover an existing managed thing by display name when no Id is
155 // cached (e.g. after a state persistence failure).
156 const findByName = Effect.fn(function* (name: string) {
157 const summary = yield* mi.listManagedThings.items({}).pipe(
158 Stream.filter((item) => item.Name === name),
159 Stream.take(1),
160 Stream.runCollect,
161 Effect.map((chunk) => Array.from(chunk)[0]),
162 );
163 if (summary?.Id === undefined) return undefined;
164 return yield* observeById(summary.Id);
165 });
166
167 const toAttributes = Effect.fn(function* (thing: mi.GetManagedThingResponse) {
168 if (
169 thing.Id === undefined ||
170 thing.Arn === undefined ||
171 thing.Name === undefined ||
172 thing.Role === undefined
173 ) {
174 return yield* new ManagedThingUnexpectedResponse({
175 message: "managed thing response is missing Id, Arn, Name, or Role",
176 });
177 }
178 return {
179 managedThingId: thing.Id,
180 managedThingArn: thing.Arn,
181 managedThingName: thing.Name,
182 role: thing.Role,
183 provisioningStatus: thing.ProvisioningStatus,
184 tags: toTagRecord(thing.Tags),
185 };
186 });
187
188 return {
189 stables: ["managedThingId", "managedThingArn"],
190 diff: Effect.fn(function* ({ olds, news }) {
191 if (!isResolved(news)) return;
192 if (olds === undefined) return;
193 // Role and authentication material are create-only.
194 if (
195 olds.role !== news.role ||
196 Redacted.value(olds.authenticationMaterial) !==
197 Redacted.value(news.authenticationMaterial) ||
198 olds.authenticationMaterialType !== news.authenticationMaterialType
199 ) {
200 return { action: "replace" } as const;
201 }
202 }),
203 read: Effect.fn(function* ({ id, olds, output }) {
204 const thing =
205 output?.managedThingId !== undefined
206 ? yield* observeById(output.managedThingId)
207 : yield* findByName(yield* toName(id, olds ?? {}));
208 if (thing === undefined) return undefined;
209 const attrs = yield* toAttributes(thing);
210 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
211 }),
212 reconcile: Effect.fn(function* ({ id, news, output, session }) {
213 const name = yield* toName(id, news);
214 const internalTags = yield* createInternalTags(id);
215 const desiredTags = { ...internalTags, ...news.tags };
216
217 // Observe — cloud state is authoritative; output is only an Id cache.
218 let thing =
219 output?.managedThingId !== undefined
220 ? yield* observeById(output.managedThingId)
221 : yield* findByName(name);
222
223 // Ensure — create if missing.
224 if (thing === undefined) {
225 const created = yield* mi.createManagedThing({
226 Role: news.role,
227 AuthenticationMaterial: news.authenticationMaterial,
228 AuthenticationMaterialType: news.authenticationMaterialType,
229 Name: name,
230 CredentialLockerId: news.credentialLockerId,
231 Owner: news.owner,
232 SerialNumber: news.serialNumber,
233 Brand: news.brand,
234 Model: news.model,
235 Classification: news.classification,
236 CapabilityReport: news.capabilityReport,
237 MetaData: news.metaData,
238 Tags: desiredTags,
239 });
240 if (created.Id === undefined) {
241 return yield* new ManagedThingUnexpectedResponse({
242 message: `failed to create managed thing '${name}'`,
243 });
244 }
245 thing = yield* observeById(created.Id);
246 if (thing === undefined) {
247 return yield* new ManagedThingUnexpectedResponse({
248 message: `managed thing '${created.Id}' vanished after create`,
249 });
250 }
251 } else if (thing.Id !== undefined) {
252 // Sync mutable, observable fields — apply only the delta.
253 const observed = {
254 name: thing.Name,
255 credentialLockerId: thing.CredentialLockerId,
256 owner: unwrapSensitive(thing.Owner),
257 serialNumber: unwrapSensitive(thing.SerialNumber),
258 brand: unwrapSensitive(thing.Brand),
259 model: unwrapSensitive(thing.Model),
260 classification: unwrapSensitive(thing.Classification),
261 };
262 const desired = {
263 name,
264 credentialLockerId: news.credentialLockerId,
265 owner: news.owner,
266 serialNumber: news.serialNumber,
267 brand: news.brand,
268 model: news.model,
269 classification: news.classification,
270 };
271 const changed = (Object.keys(desired) as (keyof typeof desired)[]).filter(
272 (key) => desired[key] !== undefined && desired[key] !== observed[key],
273 );
274 if (changed.length > 0) {
275 yield* mi.updateManagedThing({
276 Identifier: thing.Id,
277 Name: name,
278 CredentialLockerId: news.credentialLockerId,
279 Owner: news.owner,
280 SerialNumber: news.serialNumber,
281 Brand: news.brand,
282 Model: news.model,
283 Classification: news.classification,
284 MetaData: news.metaData,
285 });
286 thing = yield* observeById(thing.Id);
287 if (thing === undefined) {
288 return yield* new ManagedThingUnexpectedResponse({
289 message: `managed thing '${name}' vanished during update`,
290 });
291 }
292 }
293 }
294
295 // Sync tags — diff against OBSERVED cloud tags.
296 if (thing.Arn !== undefined) {
297 yield* syncManagedIntegrationsTags(thing.Arn, toTagRecord(thing.Tags), desiredTags);
298 }
299
300 const attrs = yield* toAttributes(thing);
301 yield* session.note(attrs.managedThingArn);
302 return { ...attrs, tags: desiredTags };
303 }),
304 // Enumerate every managed thing in the account/region; fetch each one
305 // to resolve tags (summaries omit them).
306 list: () =>
307 Effect.gen(function* () {
308 const summaries = yield* mi.listManagedThings.items({}).pipe(
309 Stream.runCollect,
310 Effect.map((chunk) => Array.from(chunk)),
311 );
312 const things = yield* Effect.forEach(
313 summaries.filter(
314 (s): s is mi.ManagedThingSummary & { Id: string } => s.Id !== undefined,
315 ),
316 (summary) => observeById(summary.Id),
317 { concurrency: 5 },
318 );
319 return yield* Effect.forEach(
320 things.filter((thing): thing is mi.GetManagedThingResponse => thing !== undefined),
321 toAttributes,
322 );
323 }),
324 delete: Effect.fn(function* ({ output }) {
325 yield* mi
326 .deleteManagedThing({ Identifier: output.managedThingId })
327 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
328 }),
329 };
330 }),
331 );