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

main
ts 256 lines 8.74 KB
Raw
1 import * as dialogflow from "@distilled.cloud/gcp/dialogflow_v3";
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 * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 collectionParent,
13 encodeOwnership,
14 hasOwnershipMarker,
15 internalLabels,
16 lastSegment,
17 locationOf,
18 namedAgents,
19 ownedByAlchemy,
20 parentOf,
21 parseOwnership,
22 projectOf,
23 toResourceId,
24 retryQuota,
25 } from "./internal.ts";
26
27 export type AgentsPlaybooksVersionProps = {
28 /**
29 * Parent playbook resource name
30 * `projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}`.
31 * Immutable — changing it replaces the version.
32 */
33 playbook: string;
34 /**
35 * Version id (the `{version}` segment). Server-assigned when omitted.
36 * Immutable — changing it replaces the version.
37 */
38 versionId?: string;
39 /**
40 * Snapshot description. Playbook versions have no labels field, so
41 * Alchemy stamps ownership into this field and strips it from
42 * attributes. Versions are immutable snapshots — changing the
43 * description after create is a no-op.
44 */
45 description?: string;
46 };
47
48 export type AgentsPlaybooksVersion = Resource<
49 "GCP.Dialogflow.AgentsPlaybooksVersion",
50 AgentsPlaybooksVersionProps,
51 {
52 /** Full resource name `.../playbooks/{playbook}/versions/{version}`. */
53 name: string;
54 /** Version id (last path segment). */
55 versionId: string;
56 /** Parent playbook resource name. */
57 playbook: string;
58 /** Location id. */
59 location: string;
60 /** Project id. */
61 project: string;
62 /** User description with the Alchemy ownership prefix stripped. */
63 description: string | undefined;
64 /** RFC3339 snapshot timestamp. */
65 updateTime: string | undefined;
66 },
67 never,
68 Providers
69 >;
70
71 /**
72 * A Dialogflow CX playbook version (immutable snapshot of a playbook).
73 *
74 * Versions have no labels field and no update RPC — Alchemy stamps
75 * ownership into `description` so `list` / nuke can find them. Reconcile
76 * is observe-ensure: if the snapshot is missing it is created; later
77 * description edits are ignored.
78 *
79 * ### Creating a Playbook Version
80 * **Example:** Snapshot
81 * ```typescript
82 * const version = yield* GCP.Dialogflow.AgentsPlaybooksVersion("v1", {
83 * playbook: playbook.name,
84 * description: "initial",
85 * });
86 * ```
87 *
88 * @resource
89 * @category Dialogflow
90 */
91 export const AgentsPlaybooksVersion = Resource<AgentsPlaybooksVersion>(
92 "GCP.Dialogflow.AgentsPlaybooksVersion",
93 );
94
95 export class AgentsPlaybooksVersionNotResolved extends Data.TaggedError(
96 "GCP.Dialogflow.AgentsPlaybooksVersionNotResolved",
97 )<{
98 resourceName: string;
99 }> {}
100
101 const resourceName = (playbook: string, versionId: string) => `${playbook}/versions/${versionId}`;
102
103 const toAttrs = (
104 version: dialogflow.GoogleCloudDialogflowCxV3PlaybookVersion,
105 project: string,
106 playbookHint?: string,
107 ) => {
108 const name = version.name ?? "";
109 return {
110 name,
111 versionId: lastSegment(name),
112 playbook: name.includes("/versions/")
113 ? collectionParent(name, "playbooks")
114 : (playbookHint ?? parentOf(name)),
115 location: locationOf(name),
116 project: projectOf(name) || project,
117 description: parseOwnership(version.description).text,
118 updateTime: version.updateTime,
119 };
120 };
121
122 const getByName = (name: string) =>
123 name.length === 0
124 ? Effect.undefined
125 : dialogflow
126 .getProjectsLocationsAgentsPlaybooksVersions({ name })
127 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
128
129 const listAt = (parent: string, project: string) =>
130 dialogflow.listProjectsLocationsAgentsPlaybooksVersions.pages({ parent, pageSize: 100 }).pipe(
131 Stream.flatMap((page) => Stream.fromIterable(page.playbookVersions ?? [])),
132 Stream.filter((version) => hasOwnershipMarker(version.description)),
133 Stream.map((version) => toAttrs(version, project, parent)),
134 Stream.runCollect,
135 Effect.map((chunk) => Array.from(chunk)),
136 Effect.catchTag("NotFound", () => Effect.succeed([])),
137 );
138
139 const listPlaybooks = (agent: string) =>
140 dialogflow.listProjectsLocationsAgentsPlaybooks.pages({ parent: agent, pageSize: 100 }).pipe(
141 Stream.flatMap((page) => Stream.fromIterable(page.playbooks ?? [])),
142 Stream.runCollect,
143 Effect.map((chunk) => Array.from(chunk)),
144 Effect.catchTag("NotFound", () => Effect.succeed([])),
145 );
146
147 const findByDescription = (parent: string, description: string) =>
148 dialogflow.listProjectsLocationsAgentsPlaybooksVersions.pages({ parent, pageSize: 100 }).pipe(
149 Stream.flatMap((page) => Stream.fromIterable(page.playbookVersions ?? [])),
150 Stream.filter((version) => version.description === description),
151 Stream.runHead,
152 Effect.map((option) => (option._tag === "Some" ? option.value : undefined)),
153 Effect.catchTag("NotFound", () => Effect.undefined),
154 );
155
156 export const AgentsPlaybooksVersionProvider = () =>
157 Provider.succeed(AgentsPlaybooksVersion, {
158 stables: ["name", "versionId", "playbook", "location", "project", "updateTime"],
159
160 diff: Effect.fn(function* ({ news, olds, output }) {
161 if (!isResolved(news)) return undefined;
162 const previousParent = olds?.playbook ?? output?.playbook;
163 if (previousParent !== undefined && news.playbook !== previousParent) {
164 return { action: "replace" as const, deleteFirst: false };
165 }
166 const previousId = olds?.versionId ?? output?.versionId;
167 if (
168 previousId !== undefined &&
169 news.versionId !== undefined &&
170 news.versionId !== previousId
171 ) {
172 return { action: "replace" as const, deleteFirst: false };
173 }
174 return undefined;
175 }),
176
177 read: Effect.fn(function* ({ id, olds, output }) {
178 const env = yield* GcpEnvironment.current;
179 const playbook = olds?.playbook ?? output?.playbook;
180 const name =
181 // Version ids are assigned by the server, so only a recorded name can
182 // be fetched directly (a guessed id is rejected as malformed).
183 output?.name ?? "";
184 let existing = yield* getByName(name);
185 if (existing === undefined && playbook !== undefined) {
186 const ownership = yield* internalLabels(id);
187 existing = yield* findByDescription(
188 playbook,
189 encodeOwnership(ownership, olds?.description),
190 );
191 }
192 if (existing === undefined) return undefined;
193 const attrs = toAttrs(existing, env.project, playbook);
194 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
195 }),
196
197 list: () =>
198 Effect.gen(function* () {
199 const env = yield* GcpEnvironment.current;
200 const agents = yield* namedAgents(env.project);
201 const pages = yield* Effect.forEach(
202 agents,
203 (agent) =>
204 Effect.gen(function* () {
205 const playbooks = yield* listPlaybooks(agent.name);
206 const versions = yield* Effect.forEach(
207 playbooks,
208 (playbook) =>
209 playbook.name ? listAt(playbook.name, env.project) : Effect.succeed([]),
210 { concurrency: 4 },
211 );
212 return versions.flat();
213 }),
214 { concurrency: 2 },
215 );
216 return pages.flat();
217 }),
218
219 reconcile: Effect.fn(function* ({ id, news, output }) {
220 const env = yield* GcpEnvironment.current;
221 const playbook = news.playbook;
222 const versionId = yield* toResourceId(id, news.versionId, output?.versionId);
223 const name = output?.name ?? resourceName(playbook, versionId);
224 const ownership = yield* internalLabels(id);
225 const description = encodeOwnership(ownership, news.description);
226
227 let current = yield* getByName(output?.name ?? "");
228 if (current === undefined) {
229 current = yield* findByDescription(playbook, description);
230 }
231
232 if (current === undefined) {
233 const created = yield* dialogflow
234 .createProjectsLocationsAgentsPlaybooksVersions({
235 parent: playbook,
236 body: { description },
237 })
238 .pipe(Effect.catchTag("Conflict", () => findByDescription(playbook, description)));
239 current = created ?? undefined;
240 }
241
242 if (current === undefined) {
243 return yield* new AgentsPlaybooksVersionNotResolved({ resourceName: name });
244 }
245
246 return toAttrs(current, env.project, playbook);
247 }, retryQuota),
248
249 delete: Effect.fn(function* ({ output }) {
250 yield* dialogflow
251 .deleteProjectsLocationsAgentsPlaybooksVersions({
252 name: output.name,
253 })
254 .pipe(Effect.catchTag("NotFound", () => Effect.void));
255 }, retryQuota),
256 });