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

main
ts 291 lines 10.8 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 CodeInterpreterProps {
20 /**
21 * Name of the code interpreter. 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 code interpreter. Changing it triggers a
29 * replacement (the API has no update operation).
30 */
31 description?: string;
32 /**
33 * The ARN of an IAM role sessions assume to access AWS resources (e.g. S3
34 * buckets) from executed code. Changing it triggers a replacement.
35 */
36 executionRoleArn?: string;
37 /**
38 * Network access for executed code: `SANDBOX` (no egress), `PUBLIC`
39 * (internet egress), or `VPC`. Changing it triggers a replacement.
40 * @default { networkMode: "SANDBOX" }
41 */
42 networkConfiguration?: control.CodeInterpreterNetworkConfiguration;
43 /**
44 * Tags to apply to the code interpreter. Merged with internal Alchemy tags.
45 */
46 tags?: Record<string, string>;
47 }
48
49 export interface CodeInterpreter extends Resource<
50 "AWS.BedrockAgentCore.CodeInterpreter",
51 CodeInterpreterProps,
52 {
53 /**
54 * The unique identifier of the code interpreter.
55 */
56 codeInterpreterId: string;
57 /**
58 * The ARN of the code interpreter.
59 */
60 codeInterpreterArn: string;
61 /**
62 * Name of the code interpreter.
63 */
64 name: string;
65 /**
66 * Current status of the code interpreter (e.g. `READY`).
67 */
68 status: string;
69 }
70 > {}
71
72 /**
73 * A custom Amazon Bedrock AgentCore Code Interpreter — an isolated sandbox
74 * where agents execute Python/JavaScript/TypeScript code.
75 *
76 * A custom interpreter controls the sandbox's network mode and execution
77 * role. All configuration is create-only (the API has no update operation);
78 * property changes trigger a replacement.
79 *
80 * ### Creating Code Interpreters
81 * **Example:** Sandboxed Interpreter (no network egress)
82 * ```typescript
83 * import * as AgentCore from "@alchemy.run/aws/BedrockAgentCore";
84 *
85 * const interpreter = yield* AgentCore.CodeInterpreter("Sandbox", {});
86 * ```
87 *
88 * **Example:** Interpreter with Public Egress
89 * ```typescript
90 * const interpreter = yield* AgentCore.CodeInterpreter("PublicSandbox", {
91 * networkConfiguration: { networkMode: "PUBLIC" },
92 * });
93 * ```
94 *
95 * ### Executing Code from a Function
96 * **Example:** Start a Session and Run Code
97 * ```typescript
98 * // init
99 * const startSession = yield* AgentCore.StartCodeInterpreterSession(interpreter);
100 * const invoke = yield* AgentCore.InvokeCodeInterpreter(interpreter);
101 * const stopSession = yield* AgentCore.StopCodeInterpreterSession(interpreter);
102 *
103 * return {
104 * fetch: Effect.gen(function* () {
105 * // runtime
106 * const session = yield* startSession({ sessionTimeout: "5 minutes" });
107 * const result = yield* invoke({
108 * sessionId: session.sessionId,
109 * name: "executeCode",
110 * arguments: { language: "python", code: "print(1 + 1)" },
111 * });
112 * const output = yield* Stream.runCollect(result.stream);
113 * yield* stopSession({ sessionId: session.sessionId });
114 * return HttpServerResponse.json({ output: Array.from(output) });
115 * }),
116 * };
117 * ```
118 *
119 * @resource
120 */
121 export const CodeInterpreter = Resource<CodeInterpreter>("AWS.BedrockAgentCore.CodeInterpreter");
122
123 export const CodeInterpreterProvider = () =>
124 Provider.effect(
125 CodeInterpreter,
126 Effect.gen(function* () {
127 const createName = Effect.fn(function* (
128 id: string,
129 props: Pick<CodeInterpreterProps, "name">,
130 ) {
131 return props.name ?? (yield* createAgentCoreName(id));
132 });
133
134 // getCodeInterpreter still resolves soft-deleted interpreters —
135 // DELETED/DELETING count as gone.
136 const getLiveOrUndefined = Effect.fn(function* (codeInterpreterId: string) {
137 const found = yield* control
138 .getCodeInterpreter({ codeInterpreterId })
139 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
140 return found === undefined || found.status === "DELETED" || found.status === "DELETING"
141 ? undefined
142 : found;
143 });
144
145 const findByName = Effect.fn(function* (name: string) {
146 const pages = yield* control.listCodeInterpreters.pages({}).pipe(Stream.runCollect);
147 const summary = Array.from(pages)
148 .flatMap((page) => page.codeInterpreterSummaries ?? [])
149 .find((s) => s.name === name && s.status !== "DELETED" && s.status !== "DELETING");
150 return summary === undefined
151 ? undefined
152 : yield* getLiveOrUndefined(summary.codeInterpreterId);
153 });
154
155 const toAttributes = (ci: control.GetCodeInterpreterResponse) => ({
156 codeInterpreterId: ci.codeInterpreterId,
157 codeInterpreterArn: ci.codeInterpreterArn,
158 name: ci.name,
159 status: ci.status,
160 });
161
162 return CodeInterpreter.Provider.of({
163 stables: ["codeInterpreterId", "codeInterpreterArn", "name"],
164
165 list: () =>
166 Effect.gen(function* () {
167 const pages = yield* control.listCodeInterpreters.pages({}).pipe(Stream.runCollect);
168 const summaries = Array.from(pages)
169 .flatMap((page) => page.codeInterpreterSummaries ?? [])
170 .filter((s) => s.status !== "DELETED" && s.status !== "DELETING");
171 const hydrated = yield* Effect.forEach(
172 summaries,
173 (s) => getLiveOrUndefined(s.codeInterpreterId),
174 { concurrency: 5 },
175 );
176 return hydrated.filter((c) => c !== undefined).map(toAttributes);
177 }),
178
179 read: Effect.fn(function* ({ id, olds, output }) {
180 const ci = output?.codeInterpreterId
181 ? yield* getLiveOrUndefined(output.codeInterpreterId)
182 : yield* findByName(yield* createName(id, olds ?? ({} as CodeInterpreterProps)));
183 if (ci === undefined) return undefined;
184 const attrs = toAttributes(ci);
185 const tags = yield* readAgentCoreTags(ci.codeInterpreterArn);
186 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
187 }),
188
189 // Everything except tags is create-only — any change replaces.
190 diff: Effect.fn(function* ({ id, news, olds }) {
191 if (!isResolved(news)) return undefined;
192 const oldProps = olds ?? ({} as CodeInterpreterProps);
193 const newProps = news ?? ({} as CodeInterpreterProps);
194 const oldName = yield* createName(id, oldProps);
195 const newName = yield* createName(id, newProps);
196 if (
197 oldName !== newName ||
198 (oldProps.description ?? undefined) !== (newProps.description ?? undefined) ||
199 (oldProps.executionRoleArn ?? undefined) !== (newProps.executionRoleArn ?? undefined) ||
200 JSON.stringify(oldProps.networkConfiguration ?? { networkMode: "SANDBOX" }) !==
201 JSON.stringify(newProps.networkConfiguration ?? { networkMode: "SANDBOX" })
202 ) {
203 return { action: "replace" } as const;
204 }
205 }),
206
207 reconcile: Effect.fn(function* ({ id, news, output, session }) {
208 const props = news ?? ({} as CodeInterpreterProps);
209 const name = output?.name ?? (yield* createName(id, props));
210 const internalTags = yield* createInternalTags(id);
211 const desiredTags = { ...props.tags, ...internalTags };
212
213 // 1. OBSERVE
214 let ci = output?.codeInterpreterId
215 ? yield* getLiveOrUndefined(output.codeInterpreterId)
216 : undefined;
217 if (ci === undefined) {
218 ci = yield* findByName(name);
219 }
220
221 // 2. ENSURE — creation is synchronous (READY on return); tolerate
222 // the name-exists race and transient IAM propagation.
223 if (ci === undefined) {
224 const created = yield* control
225 .createCodeInterpreter({
226 name,
227 description: props.description,
228 executionRoleArn: props.executionRoleArn,
229 networkConfiguration: props.networkConfiguration ?? {
230 networkMode: "SANDBOX",
231 },
232 tags: desiredTags,
233 })
234 .pipe(
235 retryWhileValidation,
236 Effect.catchTag("ConflictException", () => Effect.undefined),
237 );
238 ci =
239 created === undefined
240 ? yield* findByName(name)
241 : yield* getLiveOrUndefined(created.codeInterpreterId);
242 }
243 if (ci === undefined) {
244 return yield* new AgentCoreProvisioningFailed({
245 message: `code interpreter '${name}' was neither created nor found`,
246 });
247 }
248 if (ci.status === "CREATE_FAILED") {
249 return yield* new AgentCoreProvisioningFailed({
250 message: `code interpreter '${name}' failed: ${ci.failureReason ?? "unknown"}`,
251 });
252 }
253
254 // 3. SYNC — only tags are mutable.
255 yield* syncAgentCoreTags(ci.codeInterpreterArn, desiredTags);
256
257 // 4. RETURN fresh attributes.
258 yield* session.note(ci.codeInterpreterId);
259 return toAttributes(ci);
260 }),
261
262 delete: Effect.fn(function* ({ output }) {
263 yield* control
264 .deleteCodeInterpreter({
265 codeInterpreterId: output.codeInterpreterId,
266 })
267 .pipe(
268 retryWhileConflict,
269 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
270 );
271 // Deletion completes quickly (soft-delete to DELETED); wait until
272 // it is out of the live set so a re-create of the same name works.
273 yield* control
274 .getCodeInterpreter({
275 codeInterpreterId: output.codeInterpreterId,
276 })
277 .pipe(
278 Effect.map((ci) => ci.status as string),
279 Effect.catchTag("ResourceNotFoundException", () =>
280 Effect.succeed("DELETED" as string),
281 ),
282 Effect.repeat({
283 schedule: Schedule.fixed("3 seconds"),
284 until: (status) => status === "DELETED" || status === "DELETE_FAILED",
285 times: 20,
286 }),
287 );
288 }),
289 });
290 }),
291 );