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

main
ts 296 lines 10.7 KB
Raw
1 import * as bda from "@distilled.cloud/aws/bedrock-data-automation";
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 Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import { readBdaTags, syncBdaTags, toBdaTagList, unredact } from "./internal.ts";
12
13 export interface BlueprintProps {
14 /**
15 * Name of the blueprint. Must match `[a-zA-Z0-9-_]+` and be at most 128
16 * characters. Changing the name replaces the blueprint.
17 * @default ${app}-${stage}-${id}
18 */
19 blueprintName?: string;
20 /**
21 * The modality the blueprint extracts custom output from: `DOCUMENT`,
22 * `IMAGE`, `AUDIO`, or `VIDEO`. Changing the type replaces the blueprint.
23 */
24 type: bda.Type;
25 /**
26 * The JSON schema (as a string) describing the custom output fields the
27 * blueprint extracts. See the Bedrock Data Automation blueprint schema
28 * reference for the expected document shape.
29 */
30 schema: string;
31 /**
32 * The stage of the blueprint: `DEVELOPMENT` or `LIVE`. Stages are distinct
33 * addressable copies, so changing the stage replaces the blueprint.
34 * @default LIVE
35 */
36 blueprintStage?: bda.BlueprintStage;
37 /**
38 * Customer-managed KMS encryption for the blueprint. When omitted, the
39 * service uses an AWS-owned key.
40 */
41 encryptionConfiguration?: bda.EncryptionConfiguration;
42 /**
43 * Tags to apply to the blueprint. Merged with internal Alchemy tags.
44 */
45 tags?: Record<string, string>;
46 }
47
48 export interface Blueprint extends Resource<
49 "AWS.BedrockDataAutomation.Blueprint",
50 BlueprintProps,
51 {
52 /**
53 * The ARN of the blueprint.
54 */
55 blueprintArn: string;
56 /**
57 * Name of the blueprint.
58 */
59 blueprintName: string;
60 /**
61 * The stage (`DEVELOPMENT` or `LIVE`) of the blueprint.
62 */
63 blueprintStage: string;
64 /**
65 * The modality (`DOCUMENT`, `IMAGE`, `AUDIO`, or `VIDEO`) the blueprint
66 * extracts custom output from.
67 */
68 type: string;
69 },
70 never,
71 Providers
72 > {}
73
74 /**
75 * An Amazon Bedrock Data Automation Blueprint — a JSON schema describing the
76 * custom output fields to extract from documents, images, audio, or video.
77 * Attach blueprints to a `DataAutomationProject` via its
78 * `customOutputConfiguration`.
79 *
80 * ### Creating Blueprints
81 * **Example:** Document blueprint with custom fields
82 * ```typescript
83 * import * as BDA from "@alchemy.run/aws/BedrockDataAutomation";
84 *
85 * const blueprint = yield* BDA.Blueprint("InvoiceBlueprint", {
86 * type: "DOCUMENT",
87 * schema: JSON.stringify({
88 * $schema: "http://json-schema.org/draft-07/schema#",
89 * description: "Extract invoice fields",
90 * class: "invoice",
91 * type: "object",
92 * properties: {
93 * invoice_number: {
94 * type: "string",
95 * inferenceType: "explicit",
96 * instruction: "The invoice number",
97 * },
98 * },
99 * }),
100 * });
101 * ```
102 *
103 * **Example:** Attach a blueprint to a project
104 * ```typescript
105 * const project = yield* BDA.DataAutomationProject("Docs", {
106 * standardOutputConfiguration: {},
107 * customOutputConfiguration: {
108 * blueprints: [{ blueprintArn: blueprint.blueprintArn }],
109 * },
110 * });
111 * ```
112 *
113 * @resource
114 */
115 export const Blueprint = Resource<Blueprint>("AWS.BedrockDataAutomation.Blueprint");
116
117 export const BlueprintProvider = () =>
118 Provider.effect(
119 Blueprint,
120 Effect.gen(function* () {
121 const createName = Effect.fn(function* (
122 id: string,
123 props: Pick<BlueprintProps, "blueprintName">,
124 ) {
125 return props.blueprintName ?? (yield* createPhysicalName({ id, maxLength: 128 }));
126 });
127
128 const toAttributes = (blueprint: bda.Blueprint) => ({
129 blueprintArn: blueprint.blueprintArn,
130 blueprintName: unredact(blueprint.blueprintName),
131 blueprintStage: blueprint.blueprintStage ?? "LIVE",
132 type: blueprint.type as string,
133 });
134
135 const observeBlueprint = Effect.fn(function* (
136 blueprintArn: string,
137 blueprintStage?: bda.BlueprintStage,
138 ) {
139 return yield* bda.getBlueprint({ blueprintArn, blueprintStage }).pipe(
140 Effect.map((r) => r.blueprint),
141 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
142 );
143 });
144
145 const findBlueprintArn = Effect.fn(function* (name: string) {
146 const summaries = yield* bda.listBlueprints
147 .items({ resourceOwner: "ACCOUNT" })
148 .pipe(Stream.runCollect);
149 return Array.from(summaries).find(
150 (s) => s.blueprintName !== undefined && unredact(s.blueprintName) === name,
151 )?.blueprintArn;
152 });
153
154 return Blueprint.Provider.of({
155 stables: ["blueprintArn", "blueprintName", "type"],
156
157 list: () =>
158 Effect.gen(function* () {
159 const summaries = yield* bda.listBlueprints
160 .items({ resourceOwner: "ACCOUNT" })
161 .pipe(Stream.runCollect);
162 const attrs = yield* Effect.forEach(
163 Array.from(summaries),
164 (s) =>
165 observeBlueprint(s.blueprintArn, s.blueprintStage).pipe(
166 Effect.map((blueprint) =>
167 blueprint === undefined ? [] : [toAttributes(blueprint)],
168 ),
169 ),
170 { concurrency: 5 },
171 );
172 return attrs.flat();
173 }),
174
175 read: Effect.fn(function* ({ id, olds, output }) {
176 const blueprintArn =
177 output?.blueprintArn ?? (yield* findBlueprintArn(yield* createName(id, olds ?? {})));
178 if (blueprintArn === undefined) return undefined;
179 const found = yield* observeBlueprint(blueprintArn, olds?.blueprintStage);
180 if (found === undefined) return undefined;
181 const attrs = toAttributes(found);
182 const tags = yield* readBdaTags(blueprintArn);
183 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
184 }),
185
186 diff: Effect.fn(function* ({ id, news, olds }) {
187 if (!isResolved(news)) return undefined;
188 const oldName = yield* createName(id, olds ?? {});
189 const newName = yield* createName(id, news ?? {});
190 if (
191 oldName !== newName ||
192 olds?.type !== news.type ||
193 olds?.blueprintStage !== news.blueprintStage
194 ) {
195 return { action: "replace" } as const;
196 }
197 // fall through: engine default update logic for mutable fields
198 }),
199
200 reconcile: Effect.fn(function* ({ id, news, output, session }) {
201 const blueprintName = output?.blueprintName ?? (yield* createName(id, news));
202 const internalTags = yield* createInternalTags(id);
203 const desiredTags = { ...news.tags, ...internalTags };
204
205 // 1. OBSERVE — cloud state is authoritative; output caches the ARN.
206 const cachedArn = output?.blueprintArn ?? (yield* findBlueprintArn(blueprintName));
207 let live =
208 cachedArn === undefined
209 ? undefined
210 : yield* observeBlueprint(cachedArn, news.blueprintStage);
211
212 // 2. ENSURE — create when missing; a concurrent create surfaces as
213 // the typed ConflictException, which we treat as a race and
214 // re-observe by name.
215 if (live === undefined) {
216 live = yield* bda
217 .createBlueprint({
218 blueprintName,
219 type: news.type,
220 schema: news.schema,
221 blueprintStage: news.blueprintStage,
222 encryptionConfiguration: news.encryptionConfiguration,
223 tags: toBdaTagList(desiredTags),
224 })
225 .pipe(
226 Effect.map((r) => r.blueprint),
227 Effect.catchTag("ConflictException", (conflict) =>
228 Effect.gen(function* () {
229 const arn = yield* findBlueprintArn(blueprintName);
230 const observed =
231 arn === undefined
232 ? undefined
233 : yield* observeBlueprint(arn, news.blueprintStage);
234 return observed === undefined ? yield* conflict : observed;
235 }),
236 ),
237 );
238 }
239
240 // 3. SYNC — diff the OBSERVED schema and encryption key against the
241 // desired state; apply the idempotent PUT only on drift.
242 const kmsDrift =
243 news.encryptionConfiguration !== undefined &&
244 live.kmsKeyId !== news.encryptionConfiguration.kmsKeyId;
245 if (unredact(live.schema) !== news.schema || kmsDrift) {
246 live = yield* bda
247 .updateBlueprint({
248 blueprintArn: live.blueprintArn,
249 schema: news.schema,
250 blueprintStage: news.blueprintStage,
251 encryptionConfiguration: news.encryptionConfiguration,
252 })
253 .pipe(Effect.map((r) => r.blueprint));
254 }
255
256 // 3b. SYNC TAGS against observed cloud tags.
257 yield* syncBdaTags(live.blueprintArn, desiredTags);
258
259 yield* session.note(blueprintName);
260 return toAttributes(live);
261 }),
262
263 delete: Effect.fn(function* ({ output }) {
264 // Versions (immutable snapshots, e.g. from CreateBlueprintVersion)
265 // block deletion of the blueprint itself — delete them first.
266 // NOTE: the blueprintArn filter cannot be combined with other
267 // filters ("Invalid List filter combination").
268 const versions = yield* bda.listBlueprints
269 .items({ blueprintArn: output.blueprintArn })
270 .pipe(
271 Stream.runCollect,
272 Effect.map((summaries) =>
273 Array.from(summaries)
274 .map((s) => s.blueprintVersion)
275 .filter((v): v is string => v !== undefined),
276 ),
277 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([] as string[])),
278 );
279 yield* Effect.forEach(
280 versions,
281 (blueprintVersion) =>
282 bda
283 .deleteBlueprint({
284 blueprintArn: output.blueprintArn,
285 blueprintVersion,
286 })
287 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)),
288 { concurrency: 1 },
289 );
290 yield* bda
291 .deleteBlueprint({ blueprintArn: output.blueprintArn })
292 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
293 }),
294 });
295 }),
296 );