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

main
ts 110 lines 3.93 KB
Raw
1 import * as control from "@distilled.cloud/aws/bedrock-agentcore-control";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import { diffTags } from "alchemy/Tags";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as Redacted from "effect/Redacted";
7 import * as Schedule from "effect/Schedule";
8
9 /**
10 * Raised when an AgentCore resource lands in a terminal failure state
11 * (`FAILED`, `CREATE_FAILED`, `UPDATE_FAILED`) during reconciliation.
12 */
13 export class AgentCoreProvisioningFailed extends Data.TaggedError("AgentCoreProvisioningFailed")<{
14 message: string;
15 }> {}
16
17 /**
18 * Unwrap an AgentCore `SensitiveString` (decoded as `Redacted`) to its plain
19 * string value. `String(redacted)` would yield `"<redacted>"`, not the value.
20 */
21 export const unredact = (
22 value: string | Redacted.Redacted<string> | undefined,
23 ): string | undefined =>
24 value === undefined ? undefined : Redacted.isRedacted(value) ? Redacted.value(value) : value;
25
26 /**
27 * AgentCore Memory / Runtime / CodeInterpreter / Browser names must match
28 * `[a-zA-Z][a-zA-Z0-9_]{0,47}` — underscores, no hyphens. Derive a
29 * deterministic physical name and swap hyphens for underscores.
30 */
31 export const createAgentCoreName = Effect.fn(function* (id: string) {
32 const name = yield* createPhysicalName({
33 id,
34 maxLength: 48,
35 delimiter: "_",
36 });
37 return name.replaceAll("-", "_");
38 });
39
40 /**
41 * Gateway names must match `([0-9a-zA-Z][-]?){1,48}` — hyphens allowed but
42 * never consecutive, no underscores. Collapse runs of hyphens.
43 */
44 export const createGatewayName = Effect.fn(function* (id: string) {
45 const name = yield* createPhysicalName({ id, maxLength: 48 });
46 return name.replaceAll(/-+/g, "-");
47 });
48
49 /**
50 * Read the observed tags of an AgentCore resource by ARN. Best-effort — a
51 * failure (e.g. a race with deletion) reports no tags.
52 */
53 export const readAgentCoreTags = Effect.fn(function* (resourceArn: string) {
54 const response = yield* control
55 .listTagsForResource({ resourceArn })
56 .pipe(Effect.orElseSucceed(() => undefined));
57 const tags: Record<string, string> = {};
58 for (const [key, value] of Object.entries(response?.tags ?? {})) {
59 if (value !== undefined) tags[key] = value;
60 }
61 return tags;
62 });
63
64 /**
65 * Sync tags on an AgentCore resource: diff the OBSERVED cloud tags against
66 * the desired set and apply only the delta.
67 */
68 export const syncAgentCoreTags = Effect.fn(function* (
69 resourceArn: string,
70 desired: Record<string, string>,
71 ) {
72 const observed = yield* readAgentCoreTags(resourceArn);
73 const { upsert, removed } = diffTags(observed, desired);
74 if (upsert.length > 0) {
75 yield* control.tagResource({
76 resourceArn,
77 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
78 });
79 }
80 if (removed.length > 0) {
81 yield* control.untagResource({ resourceArn, tagKeys: removed });
82 }
83 });
84
85 /**
86 * Bounded retry through transient `ConflictException`s (e.g. deleting a
87 * gateway whose targets are still tearing down, or mutating a resource that
88 * is mid-transition). Explicitly typed so the conditional `Retry.Return`
89 * type never widens the provider layer's requirements in declaration emit.
90 */
91 export const retryWhileConflict = <A, E extends { readonly _tag: string }, R>(
92 self: Effect.Effect<A, E, R>,
93 ): Effect.Effect<A, E, R> =>
94 Effect.retry(self, {
95 while: (e) => e._tag === "ConflictException",
96 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(15)]),
97 });
98
99 /**
100 * Bounded retry through `ValidationException` during create — a freshly
101 * created IAM role referenced by `roleArn` is not instantly assumable by the
102 * AgentCore service principal (IAM eventual consistency).
103 */
104 export const retryWhileValidation = <A, E extends { readonly _tag: string }, R>(
105 self: Effect.Effect<A, E, R>,
106 ): Effect.Effect<A, E, R> =>
107 Effect.retry(self, {
108 while: (e) => e._tag === "ValidationException",
109 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(8)]),
110 });