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

main
ts 260 lines 9.6 KB
Raw
1 import * as control from "@distilled.cloud/aws/bedrock-agentcore-control";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import {
11 AgentCoreProvisioningFailed,
12 createAgentCoreName,
13 readAgentCoreTags,
14 retryWhileConflict,
15 retryWhileValidation,
16 syncAgentCoreTags,
17 } from "./internal.ts";
18
19 export interface BrowserCustomProps {
20 /**
21 * Name of the browser. Must match `[a-zA-Z][a-zA-Z0-9_]{0,47}`
22 * (underscores, no hyphens). If omitted, a deterministic physical name is
23 * generated from the app, stage, and logical ID. Changing the name triggers
24 * a replacement.
25 */
26 name?: string;
27 /**
28 * A description of the browser. Changing it triggers a replacement (the
29 * API has no update operation).
30 */
31 description?: string;
32 /**
33 * The ARN of an IAM role browser sessions assume (required for session
34 * recording to S3). Changing it triggers a replacement.
35 */
36 executionRoleArn?: string;
37 /**
38 * Network access for browser sessions: `PUBLIC` (internet egress) or
39 * `VPC`. Changing it triggers a replacement.
40 * @default { networkMode: "PUBLIC" }
41 */
42 networkConfiguration?: control.BrowserNetworkConfiguration;
43 /**
44 * Session recording configuration (S3 destination). Changing it triggers a
45 * replacement.
46 */
47 recording?: control.RecordingConfig;
48 /**
49 * Tags to apply to the browser. Merged with internal Alchemy tags.
50 */
51 tags?: Record<string, string>;
52 }
53
54 export interface BrowserCustom extends Resource<
55 "AWS.BedrockAgentCore.BrowserCustom",
56 BrowserCustomProps,
57 {
58 /**
59 * The unique identifier of the browser.
60 */
61 browserId: string;
62 /**
63 * The ARN of the browser.
64 */
65 browserArn: string;
66 /**
67 * Name of the browser.
68 */
69 name: string;
70 /**
71 * Current status of the browser (e.g. `READY`).
72 */
73 status: string;
74 }
75 > {}
76
77 /**
78 * A custom Amazon Bedrock AgentCore Browser — a managed, isolated cloud
79 * browser that agents drive to interact with websites.
80 *
81 * A custom browser controls the sandbox's network mode, execution role, and
82 * session recording. All configuration is create-only (the API has no update
83 * operation); property changes trigger a replacement.
84 *
85 * ### Creating Browsers
86 * **Example:** Public-Egress Browser
87 * ```typescript
88 * import * as AgentCore from "@alchemy.run/aws/BedrockAgentCore";
89 *
90 * const browser = yield* AgentCore.BrowserCustom("AgentBrowser", {});
91 * ```
92 *
93 * **Example:** Browser with Session Recording
94 * ```typescript
95 * const browser = yield* AgentCore.BrowserCustom("RecordedBrowser", {
96 * executionRoleArn: role.roleArn,
97 * recording: {
98 * enabled: true,
99 * s3Location: { bucket: bucket.bucketName, prefix: "sessions/" },
100 * },
101 * });
102 * ```
103 *
104 * @resource
105 */
106 export const BrowserCustom = Resource<BrowserCustom>("AWS.BedrockAgentCore.BrowserCustom");
107
108 export const BrowserCustomProvider = () =>
109 Provider.effect(
110 BrowserCustom,
111 Effect.gen(function* () {
112 const createName = Effect.fn(function* (id: string, props: Pick<BrowserCustomProps, "name">) {
113 return props.name ?? (yield* createAgentCoreName(id));
114 });
115
116 // getBrowser still resolves soft-deleted browsers — DELETED/DELETING
117 // count as gone.
118 const getLiveOrUndefined = Effect.fn(function* (browserId: string) {
119 const found = yield* control
120 .getBrowser({ browserId })
121 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
122 return found === undefined || found.status === "DELETED" || found.status === "DELETING"
123 ? undefined
124 : found;
125 });
126
127 const findByName = Effect.fn(function* (name: string) {
128 const pages = yield* control.listBrowsers.pages({}).pipe(Stream.runCollect);
129 const summary = Array.from(pages)
130 .flatMap((page) => page.browserSummaries ?? [])
131 .find((s) => s.name === name && s.status !== "DELETED" && s.status !== "DELETING");
132 return summary === undefined ? undefined : yield* getLiveOrUndefined(summary.browserId);
133 });
134
135 const toAttributes = (browser: control.GetBrowserResponse) => ({
136 browserId: browser.browserId,
137 browserArn: browser.browserArn,
138 name: browser.name,
139 status: browser.status,
140 });
141
142 return BrowserCustom.Provider.of({
143 stables: ["browserId", "browserArn", "name"],
144
145 list: () =>
146 Effect.gen(function* () {
147 const pages = yield* control.listBrowsers.pages({}).pipe(Stream.runCollect);
148 const summaries = Array.from(pages)
149 .flatMap((page) => page.browserSummaries ?? [])
150 .filter((s) => s.status !== "DELETED" && s.status !== "DELETING");
151 const hydrated = yield* Effect.forEach(
152 summaries,
153 (s) => getLiveOrUndefined(s.browserId),
154 { concurrency: 5 },
155 );
156 return hydrated.filter((b) => b !== undefined).map(toAttributes);
157 }),
158
159 read: Effect.fn(function* ({ id, olds, output }) {
160 const browser = output?.browserId
161 ? yield* getLiveOrUndefined(output.browserId)
162 : yield* findByName(yield* createName(id, olds ?? ({} as BrowserCustomProps)));
163 if (browser === undefined) return undefined;
164 const attrs = toAttributes(browser);
165 const tags = yield* readAgentCoreTags(browser.browserArn);
166 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
167 }),
168
169 // Everything except tags is create-only — any change replaces.
170 diff: Effect.fn(function* ({ id, news, olds }) {
171 if (!isResolved(news)) return undefined;
172 const oldProps = olds ?? ({} as BrowserCustomProps);
173 const newProps = news ?? ({} as BrowserCustomProps);
174 const oldName = yield* createName(id, oldProps);
175 const newName = yield* createName(id, newProps);
176 if (
177 oldName !== newName ||
178 (oldProps.description ?? undefined) !== (newProps.description ?? undefined) ||
179 (oldProps.executionRoleArn ?? undefined) !== (newProps.executionRoleArn ?? undefined) ||
180 JSON.stringify(oldProps.networkConfiguration ?? { networkMode: "PUBLIC" }) !==
181 JSON.stringify(newProps.networkConfiguration ?? { networkMode: "PUBLIC" }) ||
182 JSON.stringify(oldProps.recording ?? null) !==
183 JSON.stringify(newProps.recording ?? null)
184 ) {
185 return { action: "replace" } as const;
186 }
187 }),
188
189 reconcile: Effect.fn(function* ({ id, news, output, session }) {
190 const props = news ?? ({} as BrowserCustomProps);
191 const name = output?.name ?? (yield* createName(id, props));
192 const internalTags = yield* createInternalTags(id);
193 const desiredTags = { ...props.tags, ...internalTags };
194
195 // 1. OBSERVE
196 let browser = output?.browserId ? yield* getLiveOrUndefined(output.browserId) : undefined;
197 if (browser === undefined) {
198 browser = yield* findByName(name);
199 }
200
201 // 2. ENSURE — creation is synchronous (READY on return); tolerate
202 // the name-exists race and transient IAM propagation.
203 if (browser === undefined) {
204 const created = yield* control
205 .createBrowser({
206 name,
207 description: props.description,
208 executionRoleArn: props.executionRoleArn,
209 networkConfiguration: props.networkConfiguration ?? {
210 networkMode: "PUBLIC",
211 },
212 recording: props.recording,
213 tags: desiredTags,
214 })
215 .pipe(
216 retryWhileValidation,
217 Effect.catchTag("ConflictException", () => Effect.undefined),
218 );
219 browser =
220 created === undefined
221 ? yield* findByName(name)
222 : yield* getLiveOrUndefined(created.browserId);
223 }
224 if (browser === undefined) {
225 return yield* new AgentCoreProvisioningFailed({
226 message: `browser '${name}' was neither created nor found`,
227 });
228 }
229 if (browser.status === "CREATE_FAILED") {
230 return yield* new AgentCoreProvisioningFailed({
231 message: `browser '${name}' failed: ${browser.failureReason ?? "unknown"}`,
232 });
233 }
234
235 // 3. SYNC — only tags are mutable.
236 yield* syncAgentCoreTags(browser.browserArn, desiredTags);
237
238 // 4. RETURN fresh attributes.
239 yield* session.note(browser.browserId);
240 return toAttributes(browser);
241 }),
242
243 delete: Effect.fn(function* ({ output }) {
244 yield* control.deleteBrowser({ browserId: output.browserId }).pipe(
245 retryWhileConflict,
246 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
247 );
248 yield* control.getBrowser({ browserId: output.browserId }).pipe(
249 Effect.map((b) => b.status as string),
250 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed("DELETED" as string)),
251 Effect.repeat({
252 schedule: Schedule.fixed("3 seconds"),
253 until: (status) => status === "DELETED" || status === "DELETE_FAILED",
254 times: 20,
255 }),
256 );
257 }),
258 });
259 }),
260 );