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

main
ts 387 lines 12.9 KB
Raw
1 import * as dialogflow from "@distilled.cloud/gcp/dialogflow_v3";
2 import { unownedUnlessPrevious } 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 DEFAULT_LOCATION,
14 encodeOwnership,
15 encodeOwnershipLine,
16 expandAgent,
17 fingerprint,
18 hasOwnershipMarker,
19 internalLabels,
20 lastSegment,
21 locationOf,
22 namedAgents,
23 normalizeLocation,
24 ownedByAlchemy,
25 parentOf,
26 parseOwnership,
27 projectOf,
28 toResourceId,
29 updateMaskOf,
30 retryQuota,
31 } from "./internal.ts";
32
33 export type ToolFunctionSpec = {
34 /** JSON Schema for the tool input. */
35 inputSchema?: Record<string, unknown>;
36 /** JSON Schema for the tool output. */
37 outputSchema?: Record<string, unknown>;
38 };
39
40 export type ToolOpenApiSpec = {
41 /** OpenAPI schema as YAML or JSON text. */
42 textSchema?: string;
43 };
44
45 export type ToolDataStoreSpec = {
46 /** Data store connections. */
47 dataStoreConnections?: Array<{
48 dataStore?: string;
49 dataStoreType?: string;
50 documentProcessingMode?: string;
51 }>;
52 };
53
54 export type AgentsToolProps = {
55 /**
56 * Parent agent resource name
57 * `projects/{project}/locations/{location}/agents/{agent}`.
58 * Immutable — changing it replaces the tool.
59 */
60 agent: string;
61 /**
62 * Tool id (the `{tool}` segment). Server-assigned when omitted.
63 * Immutable — changing it replaces the tool.
64 */
65 toolId?: string;
66 /**
67 * Location used when `agent` is an id rather than a resource name.
68 * Immutable — changing it replaces the tool.
69 * @default "global"
70 */
71 location?: string;
72 /**
73 * Human-readable name. Tools have no labels field, so Alchemy stamps
74 * ownership into `displayName` and `description`.
75 */
76 displayName?: string;
77 /**
78 * Human-readable description. Required by the API; Alchemy stamps
79 * ownership into this field.
80 */
81 description?: string;
82 /**
83 * Client-side function spec. Used when neither `openApiSpec` nor
84 * `dataStoreSpec` is set.
85 */
86 functionSpec?: ToolFunctionSpec;
87 /** OpenAPI tool spec. Mutually exclusive with the other specs. */
88 openApiSpec?: ToolOpenApiSpec;
89 /** Data-store tool spec. Mutually exclusive with the other specs. */
90 dataStoreSpec?: ToolDataStoreSpec;
91 };
92
93 export type AgentsTool = Resource<
94 "GCP.Dialogflow.AgentsTool",
95 AgentsToolProps,
96 {
97 /** Full resource name `.../agents/{agent}/tools/{tool}`. */
98 name: string;
99 /** Tool id (last path segment). */
100 toolId: string;
101 /** Parent agent resource name. */
102 agent: string;
103 /** Location id. */
104 location: string;
105 /** Project id. */
106 project: string;
107 /** User display name with the Alchemy ownership prefix stripped. */
108 displayName: string | undefined;
109 /** User description with the Alchemy ownership prefix stripped. */
110 description: string | undefined;
111 /** Function spec. */
112 functionSpec: ToolFunctionSpec | undefined;
113 /** OpenAPI spec. */
114 openApiSpec: ToolOpenApiSpec | undefined;
115 /** Data-store spec. */
116 dataStoreSpec: ToolDataStoreSpec | undefined;
117 /** Tool type (`CUSTOMIZED_TOOL`, `BUILTIN_TOOL`). */
118 toolType: string | undefined;
119 },
120 never,
121 Providers
122 >;
123
124 /**
125 * A Dialogflow CX tool (function, OpenAPI, or data-store).
126 *
127 * Tools have no labels field — Alchemy stamps ownership into
128 * `displayName` and `description` so `list` / nuke can find them. Parent
129 * agent, id, and spec kind are immutable. Display name, description, and
130 * spec payload update in place.
131 *
132 * ### Creating a Tool
133 * **Example:** Function tool
134 * ```typescript
135 * const tool = yield* GCP.Dialogflow.AgentsTool("Lookup", {
136 * agent: agentName,
137 * displayName: "lookup",
138 * description: "Look up an order.",
139 * functionSpec: {
140 * inputSchema: {
141 * type: "object",
142 * properties: { orderId: { type: "string" } },
143 * },
144 * outputSchema: {
145 * type: "object",
146 * properties: { status: { type: "string" } },
147 * },
148 * },
149 * });
150 * ```
151 *
152 * @resource
153 * @category Dialogflow
154 */
155 export const AgentsTool = Resource<AgentsTool>("GCP.Dialogflow.AgentsTool");
156
157 export class AgentsToolNotResolved extends Data.TaggedError(
158 "GCP.Dialogflow.AgentsToolNotResolved",
159 )<{
160 resourceName: string;
161 }> {}
162
163 const DEFAULT_FUNCTION_SPEC: ToolFunctionSpec = {
164 inputSchema: {
165 type: "object",
166 properties: { query: { type: "string" } },
167 },
168 outputSchema: {
169 type: "object",
170 properties: { result: { type: "string" } },
171 },
172 };
173
174 const resourceName = (agent: string, toolId: string) => `${agent}/tools/${toolId}`;
175
176 const specKind = (props: {
177 openApiSpec?: unknown;
178 dataStoreSpec?: unknown;
179 functionSpec?: unknown;
180 }) => {
181 if (props.openApiSpec) return "openapi";
182 if (props.dataStoreSpec) return "datastore";
183 return "function";
184 };
185
186 const functionSpecOf = (
187 spec: dialogflow.GoogleCloudDialogflowCxV3ToolFunctionTool | undefined,
188 ): ToolFunctionSpec | undefined => {
189 if (spec === undefined) return undefined;
190 return {
191 inputSchema: spec.inputSchema as Record<string, unknown> | undefined,
192 outputSchema: spec.outputSchema as Record<string, unknown> | undefined,
193 };
194 };
195
196 const toAttrs = (
197 tool: dialogflow.GoogleCloudDialogflowCxV3Tool,
198 project: string,
199 agentHint?: string,
200 ) => {
201 const name = tool.name ?? "";
202 return {
203 name,
204 toolId: lastSegment(name),
205 agent: name.includes("/tools/")
206 ? collectionParent(name, "agents")
207 : (agentHint ?? parentOf(name)),
208 location: locationOf(name),
209 project: projectOf(name) || project,
210 displayName: parseOwnership(tool.displayName).text,
211 description: parseOwnership(tool.description).text,
212 functionSpec: functionSpecOf(tool.functionSpec),
213 openApiSpec: tool.openApiSpec ? { textSchema: tool.openApiSpec.textSchema } : undefined,
214 dataStoreSpec: tool.dataStoreSpec
215 ? { dataStoreConnections: tool.dataStoreSpec.dataStoreConnections }
216 : undefined,
217 toolType: tool.toolType,
218 };
219 };
220
221 const getByName = (name: string) =>
222 name.length === 0
223 ? Effect.undefined
224 : dialogflow
225 .getProjectsLocationsAgentsTools({ name })
226 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
227
228 const listAt = (parent: string, project: string) =>
229 dialogflow.listProjectsLocationsAgentsTools.pages({ parent, pageSize: 100 }).pipe(
230 Stream.flatMap((page) => Stream.fromIterable(page.tools ?? [])),
231 Stream.filter(
232 (tool) => hasOwnershipMarker(tool.displayName) || hasOwnershipMarker(tool.description),
233 ),
234 Stream.map((tool) => toAttrs(tool, project, parent)),
235 Stream.runCollect,
236 Effect.map((chunk) => Array.from(chunk)),
237 Effect.catchTag("NotFound", () => Effect.succeed([])),
238 );
239
240 const findByDisplayName = (parent: string, displayName: string) =>
241 dialogflow.listProjectsLocationsAgentsTools.pages({ parent, pageSize: 100 }).pipe(
242 Stream.flatMap((page) => Stream.fromIterable(page.tools ?? [])),
243 Stream.filter((tool) => tool.displayName === displayName),
244 Stream.runHead,
245 Effect.map((option) => (option._tag === "Some" ? option.value : undefined)),
246 Effect.catchTag("NotFound", () => Effect.undefined),
247 );
248
249 const toBody = (
250 news: AgentsToolProps,
251 displayName: string,
252 description: string,
253 ): dialogflow.GoogleCloudDialogflowCxV3Tool => {
254 const kind = specKind(news);
255 return {
256 displayName,
257 description,
258 functionSpec: kind === "function" ? (news.functionSpec ?? DEFAULT_FUNCTION_SPEC) : undefined,
259 openApiSpec: kind === "openapi" ? news.openApiSpec : undefined,
260 dataStoreSpec: kind === "datastore" ? news.dataStoreSpec : undefined,
261 };
262 };
263
264 export const AgentsToolProvider = () =>
265 Provider.succeed(AgentsTool, {
266 stables: ["name", "toolId", "agent", "location", "project"],
267
268 diff: Effect.fn(function* ({ news, olds, output }) {
269 if (!isResolved(news)) return undefined;
270 const previousAgent = olds?.agent ?? output?.agent;
271 if (previousAgent !== undefined && news.agent !== previousAgent) {
272 return { action: "replace" as const, deleteFirst: false };
273 }
274 const previousId = olds?.toolId ?? output?.toolId;
275 if (previousId !== undefined && news.toolId !== undefined && news.toolId !== previousId) {
276 return { action: "replace" as const, deleteFirst: false };
277 }
278 const previousKind = specKind(olds ?? output ?? {});
279 const nextKind = specKind(news);
280 if (previousKind !== nextKind && previousKind !== "function") {
281 return { action: "replace" as const, deleteFirst: true };
282 }
283 return undefined;
284 }),
285
286 read: Effect.fn(function* ({ id, olds, output, previous }) {
287 const env = yield* GcpEnvironment.current;
288 const location = normalizeLocation(olds?.location ?? output?.location);
289 const agent = olds?.agent ? expandAgent(olds.agent, env.project, location) : output?.agent;
290 const toolId = yield* toResourceId(id, olds?.toolId, output?.toolId);
291 const name = output?.name ?? (agent !== undefined ? resourceName(agent, toolId) : "");
292 let existing = yield* getByName(name);
293 if (existing === undefined && agent !== undefined) {
294 const ownership = yield* internalLabels(id);
295 existing = yield* findByDisplayName(
296 agent,
297 encodeOwnershipLine(ownership, olds?.displayName),
298 );
299 }
300 if (existing === undefined) return undefined;
301 const attrs = toAttrs(existing, env.project, agent);
302 const named = yield* ownedByAlchemy(id, existing.displayName);
303 const described = yield* ownedByAlchemy(id, existing.description);
304 return named || described ? attrs : unownedUnlessPrevious(attrs, previous, "name");
305 }),
306
307 list: () =>
308 Effect.gen(function* () {
309 const env = yield* GcpEnvironment.current;
310 const agents = yield* namedAgents(env.project);
311 const pages = yield* Effect.forEach(agents, (agent) => listAt(agent.name, env.project), {
312 concurrency: 4,
313 });
314 return pages.flat();
315 }),
316
317 reconcile: Effect.fn(function* ({ id, news, output }) {
318 const env = yield* GcpEnvironment.current;
319 const location = normalizeLocation(news.location ?? output?.location ?? DEFAULT_LOCATION);
320 const agent = expandAgent(news.agent, env.project, location);
321 const toolId = yield* toResourceId(id, news.toolId, output?.toolId);
322 const name = output?.name ?? resourceName(agent, toolId);
323 const ownership = yield* internalLabels(id);
324 const displayName = encodeOwnershipLine(ownership, news.displayName);
325 const description = encodeOwnership(ownership, news.description);
326 const body = toBody(news, displayName, description);
327
328 let current = yield* getByName(output?.name ?? name);
329 if (current === undefined) {
330 current = yield* findByDisplayName(agent, displayName);
331 }
332
333 if (current === undefined) {
334 const created = yield* dialogflow
335 .createProjectsLocationsAgentsTools({
336 parent: agent,
337 body,
338 })
339 .pipe(Effect.catchTag("Conflict", () => findByDisplayName(agent, displayName)));
340 current = created ?? undefined;
341 }
342
343 if (current === undefined) {
344 return yield* new AgentsToolNotResolved({ resourceName: name });
345 }
346
347 const currentName = current.name ?? name;
348 const displayChanged = (current.displayName ?? "") !== displayName;
349 const descriptionChanged = (current.description ?? "") !== description;
350 const functionChanged =
351 fingerprint(functionSpecOf(current.functionSpec)) !== fingerprint(body.functionSpec);
352 const openApiChanged = fingerprint(current.openApiSpec) !== fingerprint(body.openApiSpec);
353 const dataStoreChanged =
354 fingerprint(current.dataStoreSpec) !== fingerprint(body.dataStoreSpec);
355
356 if (
357 displayChanged ||
358 descriptionChanged ||
359 functionChanged ||
360 openApiChanged ||
361 dataStoreChanged
362 ) {
363 current = yield* dialogflow.patchProjectsLocationsAgentsTools({
364 name: currentName,
365 updateMask: updateMaskOf(
366 displayChanged ? "display_name" : undefined,
367 descriptionChanged ? "description" : undefined,
368 functionChanged && body.functionSpec ? "function_spec" : undefined,
369 openApiChanged && body.openApiSpec ? "open_api_spec" : undefined,
370 dataStoreChanged && body.dataStoreSpec ? "data_store_spec" : undefined,
371 ),
372 body: { ...body, name: currentName },
373 });
374 }
375
376 return toAttrs(current, env.project, agent);
377 }, retryQuota),
378
379 delete: Effect.fn(function* ({ output }) {
380 yield* dialogflow
381 .deleteProjectsLocationsAgentsTools({
382 name: output.name,
383 force: true,
384 })
385 .pipe(Effect.catchTag("NotFound", () => Effect.void));
386 }, retryQuota),
387 });