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

main
ts 571 lines 19.4 KB
Raw
1 import * as dialogflow from "@distilled.cloud/gcp/dialogflow_v3";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Schedule from "effect/Schedule";
6 import * as Stream from "effect/Stream";
7 import { GcpEnvironment } from "../Environment.ts";
8 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
9 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
10
11 /**
12 * Dialogflow's "All other requests per minute" quota is shared by the whole
13 * project and distilled's default backoff gives up within ~30s, before the
14 * minute window resets. Lifecycles are idempotent, so re-run them once the
15 * window has rolled over.
16 */
17 export const retryQuota = <A, E extends { readonly _tag: string }, R>(
18 effect: Effect.Effect<A, E, R>,
19 ) =>
20 effect.pipe(
21 Effect.retry({
22 while: (error) => error._tag === "TooManyRequests",
23 times: 6,
24 schedule: Schedule.spaced("20 seconds"),
25 }),
26 );
27
28 export const DEFAULT_LOCATION = "global";
29 export const DEFAULT_SESSION = "alchemy";
30 export const LIST_LOCATIONS = ["global", "us-central1"] as const;
31
32 /** Locations scanned by `list`: the fixed set plus the stack region. */
33 export const listLocations = (region: string): string[] => [
34 ...new Set<string>([...LIST_LOCATIONS, region]),
35 ];
36 export const MAX_ID_LENGTH = 63;
37 export const MAX_DISPLAY_NAME_LENGTH = 64;
38 export const MAX_ROUTE_GROUP_DISPLAY_NAME_LENGTH = 30;
39 export const MAX_DESCRIPTION_LENGTH = 8000;
40 export const MAX_SESSION_ID_LENGTH = 36;
41
42 export class DialogflowOperationFailed extends Data.TaggedError("GCP.Dialogflow.OperationFailed")<{
43 operation: string;
44 message: string;
45 }> {}
46
47 export class DialogflowOperationPending extends Data.TaggedError(
48 "GCP.Dialogflow.OperationPending",
49 )<{
50 operation: string;
51 }> {}
52
53 export class DialogflowStillExists extends Data.TaggedError("GCP.Dialogflow.ResourceStillExists")<{
54 resourceName: string;
55 }> {}
56
57 export const lastSegment = (value: string) => {
58 const trimmed = value.replace(/\/+$/, "");
59 const parts = trimmed.split("/");
60 return parts[parts.length - 1] || trimmed;
61 };
62
63 export const locationOf = (name: string, fallback = DEFAULT_LOCATION) => {
64 const parts = name.split("/");
65 const index = parts.indexOf("locations");
66 return index >= 0 ? (parts[index + 1] ?? fallback) : fallback;
67 };
68
69 export const projectOf = (name: string) => {
70 const parts = name.split("/");
71 const index = parts.indexOf("projects");
72 return index >= 0 ? (parts[index + 1] ?? "") : "";
73 };
74
75 export const parentOf = (name: string) => {
76 const parts = name.split("/").filter((part) => part.length > 0);
77 return parts.slice(0, -2).join("/");
78 };
79
80 export const collectionParent = (
81 name: string,
82 collection:
83 | "agents"
84 | "playbooks"
85 | "tools"
86 | "sessions"
87 | "entityTypes"
88 | "flows"
89 | "environments"
90 | "webhooks"
91 | "transitionRouteGroups",
92 ) => {
93 const parts = name.split("/").filter((part) => part.length > 0);
94 const index = parts.lastIndexOf(collection);
95 if (index < 0 || parts[index + 1] === undefined) return parentOf(name);
96 return parts.slice(0, index + 2).join("/");
97 };
98
99 export const locationParent = (project: string, location: string) =>
100 `projects/${project}/locations/${location}`;
101
102 export const normalizeLocation = (location: string | undefined) =>
103 lastSegment(location ?? DEFAULT_LOCATION).toLowerCase();
104
105 export const expandAgent = (value: string, project: string, location: string) =>
106 value.includes("/agents/") ? value : `${locationParent(project, location)}/agents/${value}`;
107
108 export const expandName = (
109 value: string,
110 project: string,
111 location: string,
112 collection: "agents" | "flows" | "environments" | "entityTypes",
113 parent?: string,
114 ) => {
115 if (value.includes("/")) return value;
116 if (parent !== undefined) return `${parent}/${collection}/${value}`;
117 return `${locationParent(project, location)}/${collection}/${value}`;
118 };
119
120 export const parseResourceName = (name: string, collection: string) => {
121 const parts = name.split("/").filter((part) => part.length > 0);
122 const collectionAt = parts.lastIndexOf(collection);
123 const locationsAt = parts.lastIndexOf("locations");
124 const projectsAt = parts.lastIndexOf("projects");
125 const agentsAt = parts.lastIndexOf("agents");
126 const flowsAt = parts.lastIndexOf("flows");
127 const environmentsAt = parts.lastIndexOf("environments");
128 const sessionsAt = parts.lastIndexOf("sessions");
129 return {
130 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
131 location:
132 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION,
133 agentId: agentsAt >= 0 && parts[agentsAt + 1] ? parts[agentsAt + 1]! : "",
134 agent: agentsAt >= 0 ? parts.slice(0, agentsAt + 2).join("/") : parentOf(name),
135 flowId: flowsAt >= 0 && parts[flowsAt + 1] ? parts[flowsAt + 1]! : "",
136 flow: flowsAt >= 0 ? parts.slice(0, flowsAt + 2).join("/") : "",
137 environmentId:
138 environmentsAt >= 0 && parts[environmentsAt + 1] ? parts[environmentsAt + 1]! : "",
139 environment: environmentsAt >= 0 ? parts.slice(0, environmentsAt + 2).join("/") : "",
140 sessionId: sessionsAt >= 0 && parts[sessionsAt + 1] ? parts[sessionsAt + 1]! : "",
141 session: sessionsAt >= 0 ? parts.slice(0, sessionsAt + 2).join("/") : "",
142 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
143 parent:
144 collectionAt > 0
145 ? parts.slice(0, collectionAt).join("/")
146 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
147 };
148 };
149
150 export const sameText = (left: string | undefined, right: string | undefined) =>
151 (left ?? "") === (right ?? "");
152
153 export const canonical = (value: unknown): unknown => {
154 if (value === undefined || value === null) return undefined;
155 if (typeof value === "boolean" || typeof value === "number") return value;
156 if (typeof value === "string") {
157 return value.length === 0 ? undefined : value;
158 }
159 if (Array.isArray(value)) {
160 const items = value.map(canonical).filter((item) => item !== undefined);
161 return items.length === 0 ? undefined : items;
162 }
163 if (typeof value === "object") {
164 const entries = Object.entries(value as Record<string, unknown>)
165 .map(([key, item]) => [key, canonical(item)] as const)
166 .filter(([, item]) => item !== undefined)
167 .sort(([left], [right]) => left.localeCompare(right));
168 if (entries.length === 0) return undefined;
169 return Object.fromEntries(entries);
170 }
171 return undefined;
172 };
173
174 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
175
176 export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right);
177
178 export const updateMaskOf = (...fields: Array<string | undefined>) =>
179 fields.filter((field): field is string => field !== undefined).join(",");
180
181 export const toResourceId = (
182 id: string,
183 requested: string | undefined,
184 existing: string | undefined,
185 maxLength = MAX_ID_LENGTH,
186 ) =>
187 Effect.gen(function* () {
188 if (requested !== undefined) return requested;
189 if (existing !== undefined) return existing;
190 const generated = yield* createPhysicalName({
191 id,
192 maxLength,
193 lowercase: true,
194 });
195 const next = /^[a-z]/.test(generated) ? generated : `d${generated}`.slice(0, maxLength);
196 return next.length >= 4 ? next : `${next}xxxx`.slice(0, maxLength);
197 });
198
199 const markerOf = (labels: Record<string, string>, stack: string, stage: string, id: string) =>
200 `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`;
201
202 const compactMarkerOf = (stack: string, stage: string, id: string) =>
203 `[alc ${stack} ${stage} ${id}]`;
204
205 const shrinkMarker = (
206 labels: Record<string, string>,
207 maxLength: number,
208 build: (stack: string, stage: string, id: string) => string,
209 ) => {
210 let stack = labels[alchemyLabelKeys.stack] ?? "x";
211 let stage = labels[alchemyLabelKeys.stage] ?? "x";
212 let id = labels[alchemyLabelKeys.id] ?? "x";
213 let marker = build(stack, stage, id);
214 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
215 if (stack.length >= stage.length && stack.length >= id.length) {
216 stack = stack.slice(0, -1);
217 } else if (stage.length >= id.length) {
218 stage = stage.slice(0, -1);
219 } else {
220 id = id.slice(0, -1);
221 }
222 marker = build(stack, stage, id);
223 }
224 return marker.slice(0, maxLength);
225 };
226
227 const fitMarker = (labels: Record<string, string>, maxLength: number) =>
228 shrinkMarker(labels, maxLength, (stack, stage, id) => markerOf(labels, stack, stage, id));
229
230 const fitCompactMarker = (labels: Record<string, string>, maxLength: number) =>
231 shrinkMarker(labels, maxLength, compactMarkerOf);
232
233 export const encodeOwnership = (
234 labels: Record<string, string>,
235 text: string | undefined,
236 ): string => {
237 const marker = fitMarker(labels, MAX_DESCRIPTION_LENGTH);
238 const trimmed = text?.trim();
239 return trimmed && trimmed.length > 0 ? `${marker}\n${trimmed}` : marker;
240 };
241
242 export const encodeOwnershipLine = (
243 labels: Record<string, string>,
244 text: string | undefined,
245 maxLength = MAX_DISPLAY_NAME_LENGTH,
246 ): string => {
247 const trimmed = text?.replace(/[\r\n]+/g, " ").trim();
248 // Reserve room for the user's text so the marker shrinks instead of the
249 // text being cut off (a compact marker keeps all three ownership fields).
250 const reserved = trimmed ? Math.min(trimmed.length + 1, Math.max(0, maxLength - 16)) : 0;
251 const room = maxLength - reserved;
252 const marker = room < 54 ? fitCompactMarker(labels, room) : fitMarker(labels, room);
253 if (!trimmed) return marker;
254 return `${marker} ${trimmed}`.slice(0, maxLength);
255 };
256
257 export const parseOwnership = (
258 text: string | undefined,
259 ): {
260 labels: Record<string, string>;
261 text: string | undefined;
262 } => {
263 if (text?.startsWith("[alc ")) {
264 const end = text.indexOf("]");
265 if (end < 0) return { labels: {}, text };
266 const parts = text.slice("[alc ".length, end).trim().split(/\s+/);
267 const labels: Record<string, string> = {};
268 if (parts[0]) labels[alchemyLabelKeys.stack] = parts[0]!;
269 if (parts[1]) labels[alchemyLabelKeys.stage] = parts[1]!;
270 if (parts[2]) labels[alchemyLabelKeys.id] = parts[2]!;
271 const rest = text.slice(end + 1).replace(/^[\s\n]+/, "");
272 return { labels, text: rest.length > 0 ? rest : undefined };
273 }
274 if (!text?.startsWith("[alchemy ")) {
275 return { labels: {}, text };
276 }
277 const end = text.indexOf("]");
278 if (end < 0) return { labels: {}, text };
279 const labels: Record<string, string> = {};
280 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
281 const eq = part.indexOf("=");
282 if (eq > 0) {
283 labels[part.slice(0, eq)] = part.slice(eq + 1);
284 }
285 }
286 const rest = text.slice(end + 1).replace(/^[\s\n]+/, "");
287 return { labels, text: rest.length > 0 ? rest : undefined };
288 };
289
290 export const hasOwnershipMarker = (text: string | undefined) =>
291 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
292
293 const prefixMatch = (expected: string, observed: string) =>
294 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
295
296 export const ownedByAlchemy = (id: string, text: string | undefined) =>
297 Effect.gen(function* () {
298 const expected = yield* createInternalLabels(id);
299 const { labels } = parseOwnership(text);
300 if (!hasOwnershipMarker(text)) return false;
301 const exact = yield* hasAlchemyLabels(id, labels);
302 if (exact) return true;
303 return (
304 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
305 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
306 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
307 );
308 });
309
310 export const internalLabels = (id: string) => createInternalLabels(id);
311
312 export const ownershipLabels = (id: string) => createInternalLabels(id);
313
314 export const ownershipText = (resource: { displayName?: string; description?: string }) =>
315 hasOwnershipMarker(resource.description) ? resource.description : resource.displayName;
316
317 export const getByName = <A, E>(name: string, get: (name: string) => Effect.Effect<A, E, never>) =>
318 name.length === 0
319 ? Effect.undefined
320 : get(name).pipe(Effect.catchTag("NotFound" as never, () => Effect.undefined));
321
322 export const listPages = <A, E, R>(pages: Stream.Stream<{ items: readonly A[] }, E, R>) =>
323 pages.pipe(
324 Stream.flatMap((page) => Stream.fromIterable(page.items)),
325 Stream.runCollect,
326 Effect.map((chunk) => Array.from(chunk)),
327 Effect.catchTag("NotFound" as never, () => Effect.succeed([] as A[])),
328 );
329
330 const collect = <Page, Item, E extends { _tag: string }, R>(
331 pages: Stream.Stream<Page, E, R>,
332 items: (page: Page) => readonly Item[] | undefined,
333 ) =>
334 pages.pipe(
335 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
336 Stream.runCollect,
337 Effect.map((chunk) => Array.from(chunk)),
338 Effect.catchIf(
339 (error): error is E => error._tag === "NotFound",
340 () => Effect.succeed([] as Item[]),
341 ),
342 );
343
344 export const listAgents = (project: string, location?: string) =>
345 Effect.gen(function* () {
346 const locations = location
347 ? [normalizeLocation(location)]
348 : listLocations((yield* GcpEnvironment.current).region);
349 return yield* Effect.forEach(
350 locations,
351 (loc) =>
352 collect(
353 dialogflow.listProjectsLocationsAgents.pages({
354 parent: locationParent(project, loc),
355 pageSize: 100,
356 }),
357 (page) => page.agents,
358 ),
359 { concurrency: 2 },
360 ).pipe(Effect.map((groups) => groups.flat()));
361 });
362
363 export const namedAgents = (project: string) =>
364 listAgents(project).pipe(
365 Effect.map((agents) =>
366 agents.filter(
367 (
368 agent,
369 ): agent is dialogflow.GoogleCloudDialogflowCxV3Agent & {
370 name: string;
371 } => typeof agent.name === "string" && agent.name.length > 0,
372 ),
373 ),
374 );
375
376 export const listEntityTypes = (agent: string) =>
377 collect(
378 dialogflow.listProjectsLocationsAgentsEntityTypes.pages({
379 parent: agent,
380 pageSize: 100,
381 }),
382 (page) => page.entityTypes,
383 );
384
385 export const listEnvironments = (agent: string) =>
386 collect(
387 dialogflow.listProjectsLocationsAgentsEnvironments.pages({
388 parent: agent,
389 pageSize: 100,
390 }),
391 (page) => page.environments,
392 );
393
394 export const listExperiments = (environment: string) =>
395 collect(
396 dialogflow.listProjectsLocationsAgentsEnvironmentsExperiments.pages({
397 parent: environment,
398 pageSize: 100,
399 }),
400 (page) => page.experiments,
401 );
402
403 export const listSessionEntityTypes = (session: string) =>
404 collect(
405 dialogflow.listProjectsLocationsAgentsEnvironmentsSessionsEntityTypes.pages({
406 parent: session,
407 pageSize: 100,
408 }),
409 (page) => page.sessionEntityTypes,
410 );
411
412 export const listFlows = (agent: string) =>
413 collect(
414 dialogflow.listProjectsLocationsAgentsFlows.pages({
415 parent: agent,
416 pageSize: 100,
417 }),
418 (page) => page.flows,
419 );
420
421 export const listPagesAt = (flow: string) =>
422 collect(
423 dialogflow.listProjectsLocationsAgentsFlowsPages.pages({
424 parent: flow,
425 pageSize: 100,
426 }),
427 (page) => page.pages,
428 );
429
430 export const listTransitionRouteGroups = (flow: string) =>
431 collect(
432 dialogflow.listProjectsLocationsAgentsFlowsTransitionRouteGroups.pages({
433 parent: flow,
434 pageSize: 100,
435 }),
436 (page) => page.transitionRouteGroups,
437 );
438
439 export const listAgentTransitionRouteGroups = (agent: string) =>
440 collect(
441 dialogflow.listProjectsLocationsAgentsTransitionRouteGroups.pages({
442 parent: agent,
443 pageSize: 100,
444 }),
445 (page) => page.transitionRouteGroups,
446 );
447
448 export const listWebhooks = (agent: string) =>
449 collect(
450 dialogflow.listProjectsLocationsAgentsWebhooks.pages({
451 parent: agent,
452 pageSize: 100,
453 }),
454 (page) => page.webhooks,
455 );
456
457 export const listVersions = (flow: string) =>
458 collect(
459 dialogflow.listProjectsLocationsAgentsFlowsVersions.pages({
460 parent: flow,
461 pageSize: 100,
462 }),
463 (page) => page.versions,
464 );
465
466 export const listSecuritySettings = (parent: string) =>
467 collect(
468 dialogflow.listProjectsLocationsSecuritySettings.pages({
469 parent,
470 pageSize: 100,
471 }),
472 (page) => page.securitySettings,
473 );
474
475 export const resourceNameFromOperation = (
476 operation: dialogflow.GoogleLongrunningOperation,
477 ): string | undefined => {
478 const response = operation.response;
479 const responseName = response?.name;
480 if (typeof responseName === "string" && responseName.length > 0) {
481 return responseName;
482 }
483 const metadata = operation.metadata;
484 const target = metadata?.target;
485 if (typeof target === "string" && target.length > 0) {
486 return target;
487 }
488 const metadataName = metadata?.name;
489 if (typeof metadataName === "string" && metadataName.length > 0) {
490 return metadataName;
491 }
492 return undefined;
493 };
494
495 /** Wait for an operation through the shared GCP waiter. */
496 export const waitForOperation = (
497 operation: dialogflow.GoogleLongrunningOperation,
498 options?: { notFoundOk?: boolean; alreadyExistsOk?: boolean },
499 ) =>
500 waitForGcpOperation(
501 operation,
502 (name) =>
503 dialogflow.getProjectsLocationsOperations({ name }).pipe(
504 Effect.catchTag("NotFound", (error) =>
505 options?.notFoundOk === true
506 ? Effect.succeed<dialogflow.GoogleLongrunningOperation>({
507 name,
508 done: true,
509 })
510 : Effect.fail(error),
511 ),
512 ),
513 { budget: "10 minutes" },
514 ).pipe(
515 // ALREADY_EXISTS (6): a concurrent create won the race. NOT_FOUND (5)
516 // is success for a delete.
517 Effect.catchIf(
518 (error) =>
519 error._tag === "GCP.OperationFailed" &&
520 ((options?.alreadyExistsOk !== false && error.code === 6) ||
521 (options?.notFoundOk === true && error.code === 5)),
522 () => Effect.void,
523 ),
524 // Re-read the finished operation for its typed response and metadata.
525 Effect.flatMap(() =>
526 operation.name === undefined || operation.name.length === 0
527 ? Effect.succeed(operation)
528 : dialogflow
529 .getProjectsLocationsOperations({ name: operation.name })
530 .pipe(Effect.catchTag("NotFound", () => Effect.succeed(operation))),
531 ),
532 );
533
534 export class DialogflowNotYetReadable extends Data.TaggedError("GCP.Dialogflow.NotYetReadable")<{
535 resourceName: string;
536 }> {}
537
538 /** Some Dialogflow creates are not readable for a few seconds afterwards. */
539 export const waitUntilReadable = <A, E extends { readonly _tag: string }, R>(
540 name: string,
541 get: (name: string) => Effect.Effect<A | undefined, E, R>,
542 ) =>
543 get(name).pipe(
544 Effect.flatMap((value) =>
545 value === undefined
546 ? Effect.fail(new DialogflowNotYetReadable({ resourceName: name }))
547 : Effect.succeed(value),
548 ),
549 Effect.retry({
550 while: (error) => error._tag === "GCP.Dialogflow.NotYetReadable",
551 times: 10,
552 schedule: Schedule.spaced("2 seconds"),
553 }),
554 );
555
556 export const waitUntilGone = <A, E extends { readonly _tag: string }, R>(
557 name: string,
558 get: (name: string) => Effect.Effect<A | undefined, E, R>,
559 ) =>
560 get(name).pipe(
561 Effect.flatMap((value) =>
562 value === undefined
563 ? Effect.void
564 : Effect.fail(new DialogflowStillExists({ resourceName: name })),
565 ),
566 Effect.retry({
567 while: (error) => error._tag === "GCP.Dialogflow.ResourceStillExists",
568 times: 10,
569 schedule: Schedule.spaced("1 second"),
570 }),
571 );