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

main
ts 388 lines 12.9 KB
Raw
1 import * as ces from "@distilled.cloud/gcp/ces_v1";
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 { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 collectPages,
12 expandApp,
13 forEachApp,
14 normalizeLocation,
15 parseResourceName,
16 replaceOnIdentity,
17 retryTransient,
18 sameJson,
19 sameText,
20 toPhysicalId,
21 toolKind,
22 unstampToolDescription,
23 updateMaskOf,
24 waitUntilGone,
25 } from "./internal.ts";
26
27 export type AppsToolProps = {
28 /**
29 * Parent CES app. Full name
30 * `projects/{project}/locations/{location}/apps/{app}` or the app id
31 * (combined with `location`). Immutable — changing it replaces the
32 * tool.
33 */
34 app: string;
35 /**
36 * Region used when `app` is a bare id.
37 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
38 */
39 location?: string;
40 /**
41 * Tool id. If omitted, a unique name is generated. Immutable —
42 * changing it replaces the tool.
43 */
44 toolId?: string;
45 /**
46 * Execution type (`SYNCHRONOUS`, `ASYNCHRONOUS`).
47 */
48 executionType?: string;
49 /**
50 * Tool timeout (e.g. `"30s"`).
51 */
52 timeout?: string;
53 /**
54 * Fake-mode configuration.
55 */
56 toolFakeConfig?: ces.ToolFakeConfig;
57 /**
58 * Client-side function. Used when no other tool variant is set.
59 */
60 clientFunction?: ces.ClientFunction;
61 /** Python function tool. */
62 pythonFunction?: ces.PythonFunction;
63 /** Google Search grounding tool. */
64 googleSearchTool?: ces.GoogleSearchTool;
65 /** OpenAPI tool. */
66 openApiTool?: ces.OpenApiTool;
67 /** Widget tool. */
68 widgetTool?: ces.WidgetTool;
69 /** File-search tool. */
70 fileSearchTool?: ces.FileSearchTool;
71 /** Vertex AI Search data-store tool. */
72 dataStoreTool?: ces.DataStoreTool;
73 /** Nested-agent tool. */
74 agentTool?: ces.AgentTool;
75 /** Remote A2A agent tool. */
76 remoteAgentTool?: ces.RemoteAgentTool;
77 /** Integration Connectors tool. */
78 connectorTool?: ces.ConnectorTool;
79 /** Built-in system tool. */
80 systemTool?: ces.SystemTool;
81 };
82
83 export type AppsTool = Resource<
84 "GCP.CES.AppsTool",
85 AppsToolProps,
86 {
87 /** Full resource name `.../apps/{app}/tools/{tool}`. */
88 name: string;
89 /** Tool id (last path segment). */
90 toolId: string;
91 /** Parent app resource name. */
92 app: string;
93 /** Location id. */
94 location: string;
95 /** Project id. */
96 project: string;
97 /** Server-derived display name. */
98 displayName: string | undefined;
99 /** Execution type. */
100 executionType: string | undefined;
101 /** Timeout. */
102 timeout: string | undefined;
103 /** Fake-mode configuration. */
104 toolFakeConfig: ces.ToolFakeConfig | undefined;
105 /** Client function (ownership prefix stripped from description). */
106 clientFunction: ces.ClientFunction | undefined;
107 /** Python function. */
108 pythonFunction: ces.PythonFunction | undefined;
109 /** Google Search tool. */
110 googleSearchTool: ces.GoogleSearchTool | undefined;
111 /** OpenAPI tool. */
112 openApiTool: ces.OpenApiTool | undefined;
113 /** Widget tool. */
114 widgetTool: ces.WidgetTool | undefined;
115 /** File-search tool. */
116 fileSearchTool: ces.FileSearchTool | undefined;
117 /** Data-store tool. */
118 dataStoreTool: ces.DataStoreTool | undefined;
119 /** Nested-agent tool. */
120 agentTool: ces.AgentTool | undefined;
121 /** Remote agent tool. */
122 remoteAgentTool: ces.RemoteAgentTool | undefined;
123 /** Connector tool. */
124 connectorTool: ces.ConnectorTool | undefined;
125 /** System tool. */
126 systemTool: ces.SystemTool | undefined;
127 /** RFC3339 creation timestamp. */
128 createTime: string | undefined;
129 /** RFC3339 last-update timestamp. */
130 updateTime: string | undefined;
131 /** Server-assigned etag. */
132 etag: string | undefined;
133 },
134 never,
135 Providers
136 >;
137
138 /**
139 * A Customer Engagement Suite tool inside an app (client function,
140 * Python, OpenAPI, Google Search, widget, and related variants).
141 *
142 * Tools have no labels field, and a tool's description tells the model
143 * when to call it, so Alchemy writes no ownership marker: a generated
144 * tool id identifies the tool, and `read` reports an explicit id it has no
145 * state for as unowned. Parent app, location, tool id, and tool kind are
146 * immutable.
147 *
148 * ### Creating a Tool
149 * **Example:** Client function
150 * ```typescript
151 * const tool = yield* GCP.CES.AppsTool("Lookup", {
152 * app: app.name,
153 * clientFunction: {
154 * name: "lookup_order",
155 * description: "Look up an order by id.",
156 * parameters: {
157 * type: "OBJECT",
158 * properties: { orderId: { type: "STRING" } },
159 * },
160 * },
161 * });
162 * ```
163 *
164 * @resource
165 * @category CES
166 */
167 export const AppsTool = Resource<AppsTool>("GCP.CES.AppsTool");
168
169 export class AppsToolNotResolved extends Data.TaggedError("GCP.CES.AppsToolNotResolved")<{
170 resourceName: string;
171 }> {}
172
173 const resourceName = (app: string, toolId: string) => `${app}/tools/${toolId}`;
174
175 const variantOf = (tool: ces.Tool, kind: ReturnType<typeof toolKind>) => {
176 switch (kind) {
177 case "fileSearchTool":
178 return tool.fileSearchTool;
179 case "pythonFunction":
180 return tool.pythonFunction;
181 case "googleSearchTool":
182 return tool.googleSearchTool;
183 case "mcpTool":
184 return tool.mcpTool;
185 case "remoteAgentTool":
186 return tool.remoteAgentTool;
187 case "widgetTool":
188 return tool.widgetTool;
189 case "systemTool":
190 return tool.systemTool;
191 case "openApiTool":
192 return tool.openApiTool;
193 case "connectorTool":
194 return tool.connectorTool;
195 case "dataStoreTool":
196 return tool.dataStoreTool;
197 case "agentTool":
198 return tool.agentTool;
199 default:
200 return tool.clientFunction;
201 }
202 };
203
204 const toBody = (news: AppsToolProps): ces.Tool => ({
205 executionType: news.executionType,
206 timeout: news.timeout,
207 toolFakeConfig: news.toolFakeConfig,
208 clientFunction: news.clientFunction,
209 pythonFunction: news.pythonFunction,
210 googleSearchTool: news.googleSearchTool,
211 openApiTool: news.openApiTool,
212 widgetTool: news.widgetTool,
213 fileSearchTool: news.fileSearchTool,
214 dataStoreTool: news.dataStoreTool,
215 agentTool: news.agentTool,
216 remoteAgentTool: news.remoteAgentTool,
217 connectorTool: news.connectorTool,
218 systemTool: news.systemTool,
219 });
220
221 const toAttrs = (tool: ces.Tool, project: string, region: string, appHint?: string) => {
222 const name = tool.name ?? "";
223 const parsed = parseResourceName(name, "tools", region);
224 const unstamped = unstampToolDescription(tool);
225 return {
226 name,
227 toolId: parsed.id,
228 app: name.includes("/tools/") ? parsed.app : (appHint ?? parsed.parent),
229 location: parsed.location,
230 project: parsed.project || project,
231 displayName: tool.displayName,
232 executionType: tool.executionType,
233 timeout: tool.timeout,
234 toolFakeConfig: tool.toolFakeConfig,
235 clientFunction: unstamped.clientFunction,
236 pythonFunction: unstamped.pythonFunction,
237 googleSearchTool: unstamped.googleSearchTool,
238 openApiTool: unstamped.openApiTool,
239 widgetTool: unstamped.widgetTool,
240 fileSearchTool: unstamped.fileSearchTool,
241 dataStoreTool: unstamped.dataStoreTool,
242 agentTool: unstamped.agentTool,
243 remoteAgentTool: unstamped.remoteAgentTool,
244 connectorTool: unstamped.connectorTool,
245 systemTool: unstamped.systemTool,
246 createTime: tool.createTime,
247 updateTime: tool.updateTime,
248 etag: tool.etag,
249 };
250 };
251
252 const getByName = (name: string) =>
253 name.length === 0
254 ? Effect.undefined
255 : ces
256 .getProjectsLocationsAppsTools({ name })
257 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
258
259 const listAt = (parent: string, project: string, region: string) =>
260 collectPages(
261 ces.listProjectsLocationsAppsTools.pages({ parent, pageSize: 100 }),
262 (page) => page.tools,
263 ).pipe(Effect.map((tools) => tools.map((tool) => toAttrs(tool, project, region, parent))));
264
265 export const AppsToolProvider = () =>
266 Provider.succeed(AppsTool, {
267 stables: ["name", "toolId", "app", "location", "project", "createTime"],
268
269 diff: Effect.fn(function* ({ news, olds, output }) {
270 if (!isResolved(news)) return undefined;
271 const previousKind = toolKind(olds ?? output ?? {});
272 const nextKind = toolKind(news);
273 return replaceOnIdentity({
274 previousId: olds?.toolId ?? output?.toolId,
275 nextId: news.toolId,
276 previousParent: olds?.app ?? output?.app,
277 nextParent: news.app,
278 extra: previousKind !== nextKind && previousKind !== "clientFunction",
279 });
280 }),
281
282 read: Effect.fn(function* ({ id, olds, output }) {
283 const env = yield* GcpEnvironment.current;
284 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
285 const app = olds?.app ? expandApp(olds.app, env.project, location) : output?.app;
286 const toolId = yield* toPhysicalId(id, olds?.toolId, output?.toolId);
287 const name = output?.name ?? (app !== undefined ? resourceName(app, toolId) : "");
288 const existing = yield* getByName(name);
289 if (existing === undefined) return undefined;
290 const attrs = toAttrs(existing, env.project, env.region, app);
291 return output !== undefined || olds?.toolId === undefined ? attrs : Unowned(attrs);
292 }),
293
294 list: () =>
295 Effect.gen(function* () {
296 const env = yield* GcpEnvironment.current;
297 return yield* forEachApp(
298 env.project,
299 (parent) => listAt(parent, env.project, env.region),
300 env.region,
301 );
302 }),
303
304 reconcile: Effect.fn(function* ({ id, news, output }) {
305 const env = yield* GcpEnvironment.current;
306 const location = normalizeLocation(news.location ?? output?.location, env.region);
307 const app = expandApp(news.app, env.project, location);
308 const toolId = yield* toPhysicalId(id, news.toolId, output?.toolId);
309 const name = output?.name ?? resourceName(app, toolId);
310 const body = toBody(news);
311 const kind = toolKind(body);
312
313 let current = yield* getByName(name);
314
315 if (current === undefined) {
316 const created = yield* retryTransient(
317 ces.createProjectsLocationsAppsTools({
318 parent: app,
319 toolId,
320 body,
321 }),
322 ).pipe(Effect.catchTag("Conflict", () => getByName(name)));
323 current = created ?? undefined;
324 }
325
326 if (current === undefined) {
327 return yield* new AppsToolNotResolved({ resourceName: name });
328 }
329
330 const currentName = current.name ?? name;
331 const executionChanged = !sameText(current.executionType, body.executionType);
332 const timeoutChanged = !sameText(current.timeout, body.timeout);
333 const fakeChanged = !sameJson(current.toolFakeConfig, body.toolFakeConfig);
334 const variantChanged = !sameJson(variantOf(current, kind), variantOf(body, kind));
335
336 if (executionChanged || timeoutChanged || fakeChanged || variantChanged) {
337 current = yield* retryTransient(
338 ces.patchProjectsLocationsAppsTools({
339 name: currentName,
340 updateMask: updateMaskOf(
341 executionChanged ? "execution_type" : undefined,
342 timeoutChanged ? "timeout" : undefined,
343 fakeChanged ? "tool_fake_config" : undefined,
344 variantChanged
345 ? kind === "clientFunction"
346 ? "client_function"
347 : kind === "pythonFunction"
348 ? "python_function"
349 : kind === "googleSearchTool"
350 ? "google_search_tool"
351 : kind === "openApiTool"
352 ? "open_api_tool"
353 : kind === "widgetTool"
354 ? "widget_tool"
355 : kind === "fileSearchTool"
356 ? "file_search_tool"
357 : kind === "dataStoreTool"
358 ? "data_store_tool"
359 : kind === "agentTool"
360 ? "agent_tool"
361 : kind === "remoteAgentTool"
362 ? "remote_agent_tool"
363 : kind === "connectorTool"
364 ? "connector_tool"
365 : kind === "systemTool"
366 ? "system_tool"
367 : "mcp_tool"
368 : undefined,
369 ),
370 body,
371 }),
372 );
373 }
374
375 return toAttrs(current, env.project, env.region, app);
376 }),
377
378 delete: Effect.fn(function* ({ output }) {
379 if (!output.name) return;
380 yield* retryTransient(
381 ces.deleteProjectsLocationsAppsTools({
382 name: output.name,
383 force: true,
384 }),
385 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
386 yield* waitUntilGone(getByName(output.name));
387 }),
388 });