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

main
ts 371 lines 14.1 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 unredact,
18 } from "./internal.ts";
19
20 /**
21 * The deployable artifact of an agent runtime — a container image in ECR or
22 * a managed-runtime code bundle in S3. Passed through to the AgentCore API
23 * unchanged — see the AWS SDK `AgentRuntimeArtifact` shape.
24 */
25 export type RuntimeArtifact = control.AgentRuntimeArtifact;
26
27 export interface RuntimeProps {
28 /**
29 * Name of the agent runtime. Must match `[a-zA-Z][a-zA-Z0-9_]{0,47}`
30 * (underscores, no hyphens). If omitted, a deterministic physical name is
31 * generated from the app, stage, and logical ID. Changing the name triggers
32 * a replacement.
33 */
34 agentRuntimeName?: string;
35 /**
36 * A description of the agent runtime.
37 */
38 description?: string;
39 /**
40 * The deployable artifact: `{ containerConfiguration: { containerUri } }`
41 * for an ECR image, or `{ codeConfiguration: ... }` for a managed-runtime
42 * code bundle.
43 */
44 agentRuntimeArtifact: RuntimeArtifact;
45 /**
46 * The ARN of an IAM role the runtime assumes. Must trust
47 * `bedrock-agentcore.amazonaws.com`.
48 */
49 roleArn: string;
50 /**
51 * Network access for the runtime.
52 * @default { networkMode: "PUBLIC" }
53 */
54 networkConfiguration?: control.NetworkConfiguration;
55 /**
56 * The protocol the hosted agent serves (`HTTP`, `MCP`, or `A2A`).
57 */
58 protocolConfiguration?: control.ProtocolConfiguration;
59 /**
60 * Inbound authorization for `InvokeAgentRuntime` (JWT bearer tokens).
61 * Omit for SigV4 (IAM).
62 */
63 authorizerConfiguration?: control.AuthorizerConfiguration;
64 /**
65 * Request headers forwarded to the agent container.
66 */
67 requestHeaderConfiguration?: control.RequestHeaderConfiguration;
68 /**
69 * Idle-session and max-lifetime configuration.
70 */
71 lifecycleConfiguration?: control.LifecycleConfiguration;
72 /**
73 * Environment variables injected into the agent container.
74 */
75 environmentVariables?: Record<string, string>;
76 /**
77 * Runtime platform version, e.g. `"V2"` for snapshot-restored microVMs.
78 * When omitted, AgentCore's default (`"V1"`) applies on create and an
79 * existing runtime keeps its current platform version.
80 */
81 platformVersion?: string;
82 /**
83 * Tags to apply to the runtime. Merged with internal Alchemy tags.
84 */
85 tags?: Record<string, string>;
86 }
87
88 export interface Runtime extends Resource<
89 "AWS.BedrockAgentCore.Runtime",
90 RuntimeProps,
91 {
92 /**
93 * The unique identifier of the agent runtime.
94 */
95 agentRuntimeId: string;
96 /**
97 * The ARN of the agent runtime.
98 */
99 agentRuntimeArn: string;
100 /**
101 * The current version of the agent runtime (bumped on every update).
102 */
103 agentRuntimeVersion: string;
104 /**
105 * Name of the agent runtime.
106 */
107 agentRuntimeName: string;
108 /**
109 * Current status of the agent runtime (e.g. `READY`).
110 */
111 status: string;
112 }
113 > {}
114
115 /**
116 * An Amazon Bedrock AgentCore Runtime — serverless hosting for containerized
117 * AI agents.
118 *
119 * A runtime deploys an agent (an ECR container image or managed-runtime code
120 * bundle) behind the `InvokeAgentRuntime` data-plane API with session
121 * isolation, scaling, and identity built in. Each configuration change
122 * publishes a new immutable runtime version.
123 *
124 * ### Creating Runtimes
125 * **Example:** Container-Backed Agent Runtime
126 * ```typescript
127 * import * as AgentCore from "@alchemy.run/aws/BedrockAgentCore";
128 *
129 * const runtime = yield* AgentCore.Runtime("MyAgent", {
130 * agentRuntimeArtifact: {
131 * containerConfiguration: {
132 * containerUri: `${account}.dkr.ecr.us-west-2.amazonaws.com/my-agent:latest`,
133 * },
134 * },
135 * roleArn: role.roleArn,
136 * });
137 * ```
138 *
139 * ### Invoking from a Function
140 * **Example:** Invoke the Agent
141 * ```typescript
142 * // init
143 * const invoke = yield* AgentCore.InvokeAgentRuntime(runtime);
144 *
145 * return {
146 * fetch: Effect.gen(function* () {
147 * // runtime
148 * const response = yield* invoke({
149 * runtimeSessionId: "session-0000000000000000000000000000000001",
150 * payload: JSON.stringify({ prompt: "hello" }),
151 * });
152 * return HttpServerResponse.json({ contentType: response.contentType });
153 * }),
154 * };
155 * ```
156 *
157 * @resource
158 */
159 export const Runtime = Resource<Runtime>("AWS.BedrockAgentCore.Runtime");
160
161 /** Statuses indicating an in-flight transition to wait out. */
162 const RUNTIME_TRANSIENT = new Set(["CREATING", "UPDATING"]);
163
164 export const RuntimeProvider = () =>
165 Provider.effect(
166 Runtime,
167 Effect.gen(function* () {
168 const createName = Effect.fn(function* (
169 id: string,
170 props: Pick<RuntimeProps, "agentRuntimeName">,
171 ) {
172 return props.agentRuntimeName ?? (yield* createAgentCoreName(id));
173 });
174
175 const getRuntimeOrUndefined = Effect.fn(function* (agentRuntimeId: string) {
176 return yield* control
177 .getAgentRuntime({ agentRuntimeId })
178 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
179 });
180
181 const findByName = Effect.fn(function* (name: string) {
182 const pages = yield* control.listAgentRuntimes.pages({}).pipe(Stream.runCollect);
183 const summary = Array.from(pages)
184 .flatMap((page) => page.agentRuntimes ?? [])
185 .find((s) => s.agentRuntimeName === name);
186 return summary === undefined
187 ? undefined
188 : yield* getRuntimeOrUndefined(summary.agentRuntimeId);
189 });
190
191 const waitForSettled = Effect.fn(function* (agentRuntimeId: string) {
192 return yield* getRuntimeOrUndefined(agentRuntimeId).pipe(
193 Effect.repeat({
194 schedule: Schedule.fixed("5 seconds"),
195 until: (r) => r === undefined || !RUNTIME_TRANSIENT.has(r.status),
196 times: 60,
197 }),
198 );
199 });
200
201 const toAttributes = (runtime: control.GetAgentRuntimeResponse) => ({
202 agentRuntimeId: runtime.agentRuntimeId,
203 agentRuntimeArn: runtime.agentRuntimeArn,
204 agentRuntimeVersion: runtime.agentRuntimeVersion,
205 agentRuntimeName: runtime.agentRuntimeName,
206 status: runtime.status,
207 });
208
209 return Runtime.Provider.of({
210 stables: ["agentRuntimeId", "agentRuntimeArn", "agentRuntimeName"],
211
212 list: () =>
213 Effect.gen(function* () {
214 const pages = yield* control.listAgentRuntimes.pages({}).pipe(Stream.runCollect);
215 const summaries = Array.from(pages).flatMap((page) => page.agentRuntimes ?? []);
216 const hydrated = yield* Effect.forEach(
217 summaries,
218 (s) => getRuntimeOrUndefined(s.agentRuntimeId),
219 { concurrency: 5 },
220 );
221 return hydrated.filter((r) => r !== undefined).map(toAttributes);
222 }),
223
224 read: Effect.fn(function* ({ id, olds, output }) {
225 const runtime = output?.agentRuntimeId
226 ? yield* getRuntimeOrUndefined(output.agentRuntimeId)
227 : yield* findByName(yield* createName(id, olds ?? ({} as RuntimeProps)));
228 if (runtime === undefined || runtime.status === "DELETING") {
229 return undefined;
230 }
231 const attrs = toAttributes(runtime);
232 const tags = yield* readAgentCoreTags(runtime.agentRuntimeArn);
233 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
234 }),
235
236 diff: Effect.fn(function* ({ id, news, olds }) {
237 if (!isResolved(news)) return undefined;
238 const oldName = yield* createName(id, olds ?? ({} as RuntimeProps));
239 const newName = yield* createName(id, news ?? ({} as RuntimeProps));
240 if (oldName !== newName) {
241 return { action: "replace" } as const;
242 }
243 // artifact, role, network, protocol, env vars, and tags converge
244 // via update (each update publishes a new runtime version).
245 }),
246
247 reconcile: Effect.fn(function* ({ id, news, output, session }) {
248 const props = news ?? ({} as RuntimeProps);
249 const name = output?.agentRuntimeName ?? (yield* createName(id, props));
250 const internalTags = yield* createInternalTags(id);
251 const desiredTags = { ...props.tags, ...internalTags };
252 const networkConfiguration = props.networkConfiguration ?? {
253 networkMode: "PUBLIC",
254 };
255
256 // 1. OBSERVE
257 let runtime = output?.agentRuntimeId
258 ? yield* getRuntimeOrUndefined(output.agentRuntimeId)
259 : undefined;
260 if (runtime === undefined) {
261 runtime = yield* findByName(name);
262 }
263
264 // 2. ENSURE — a freshly created IAM role is not instantly
265 // assumable; ride out the transient ValidationException and the
266 // name-exists conflict race.
267 if (runtime === undefined) {
268 const created = yield* control
269 .createAgentRuntime({
270 agentRuntimeName: name,
271 description: props.description,
272 agentRuntimeArtifact: props.agentRuntimeArtifact,
273 roleArn: props.roleArn,
274 networkConfiguration,
275 protocolConfiguration: props.protocolConfiguration,
276 authorizerConfiguration: props.authorizerConfiguration,
277 requestHeaderConfiguration: props.requestHeaderConfiguration,
278 lifecycleConfiguration: props.lifecycleConfiguration,
279 environmentVariables: props.environmentVariables,
280 platformVersion: props.platformVersion,
281 tags: desiredTags,
282 })
283 .pipe(
284 retryWhileValidation,
285 Effect.catchTag("ConflictException", () => Effect.undefined),
286 );
287 runtime =
288 created === undefined
289 ? yield* findByName(name)
290 : yield* getRuntimeOrUndefined(created.agentRuntimeId);
291 }
292 if (runtime === undefined) {
293 return yield* new AgentCoreProvisioningFailed({
294 message: `agent runtime '${name}' was neither created nor found`,
295 });
296 }
297
298 runtime = (yield* waitForSettled(runtime.agentRuntimeId)) ?? runtime;
299 if (runtime.status === "CREATE_FAILED" || runtime.status === "UPDATE_FAILED") {
300 return yield* new AgentCoreProvisioningFailed({
301 message: `agent runtime '${name}' failed: ${runtime.failureReason ?? "unknown"}`,
302 });
303 }
304
305 // 3. SYNC — converge mutable settings from OBSERVED state. Each
306 // update publishes a new immutable runtime version.
307 const drifted =
308 (unredact(runtime.description) ?? undefined) !==
309 (props.description ?? unredact(runtime.description)) ||
310 runtime.roleArn !== props.roleArn ||
311 JSON.stringify(runtime.agentRuntimeArtifact ?? null) !==
312 JSON.stringify(props.agentRuntimeArtifact) ||
313 JSON.stringify(runtime.networkConfiguration) !== JSON.stringify(networkConfiguration) ||
314 JSON.stringify(runtime.environmentVariables ?? {}) !==
315 JSON.stringify(props.environmentVariables ?? {}) ||
316 (props.protocolConfiguration !== undefined &&
317 JSON.stringify(runtime.protocolConfiguration ?? null) !==
318 JSON.stringify(props.protocolConfiguration)) ||
319 (props.lifecycleConfiguration !== undefined &&
320 JSON.stringify(runtime.lifecycleConfiguration ?? null) !==
321 JSON.stringify(props.lifecycleConfiguration)) ||
322 (props.platformVersion !== undefined &&
323 runtime.platformVersion !== props.platformVersion);
324 if (drifted) {
325 yield* control
326 .updateAgentRuntime({
327 agentRuntimeId: runtime.agentRuntimeId,
328 description: props.description,
329 agentRuntimeArtifact: props.agentRuntimeArtifact,
330 roleArn: props.roleArn,
331 networkConfiguration,
332 protocolConfiguration: props.protocolConfiguration,
333 authorizerConfiguration: props.authorizerConfiguration,
334 requestHeaderConfiguration: props.requestHeaderConfiguration,
335 lifecycleConfiguration: props.lifecycleConfiguration,
336 environmentVariables: props.environmentVariables,
337 // Unset keeps the observed version, so unrelated updates never move the platform.
338 platformVersion: props.platformVersion ?? runtime.platformVersion,
339 })
340 .pipe(retryWhileConflict);
341 runtime = (yield* waitForSettled(runtime.agentRuntimeId)) ?? runtime;
342 }
343
344 // 3b. SYNC TAGS against observed cloud tags.
345 yield* syncAgentCoreTags(runtime.agentRuntimeArn, desiredTags);
346
347 // 4. RETURN fresh attributes.
348 yield* session.note(runtime.agentRuntimeId);
349 return toAttributes(runtime);
350 }),
351
352 // A runtime with live endpoints rejects deletion with a
353 // ConflictException until they are gone.
354 delete: Effect.fn(function* ({ output }) {
355 yield* control.deleteAgentRuntime({ agentRuntimeId: output.agentRuntimeId }).pipe(
356 retryWhileConflict,
357 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
358 );
359 yield* control.getAgentRuntime({ agentRuntimeId: output.agentRuntimeId }).pipe(
360 Effect.map((r) => r.status as string),
361 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed("GONE" as string)),
362 Effect.repeat({
363 schedule: Schedule.fixed("5 seconds"),
364 until: (status) => status === "GONE",
365 times: 36,
366 }),
367 );
368 }),
369 });
370 }),
371 );