@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 379 lines 12.9 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 DEFAULT_LOCATION,
14 encodeOwnershipLine,
15 expandAgent,
16 fingerprint,
17 hasOwnershipMarker,
18 internalLabels,
19 lastSegment,
20 locationOf,
21 namedAgents,
22 normalizeLocation,
23 ownedByAlchemy,
24 parentOf,
25 parseOwnership,
26 projectOf,
27 sameText,
28 toResourceId,
29 updateMaskOf,
30 retryQuota,
31 } from "./internal.ts";
32
33 export type GeneratorModelParameter = {
34 /** Sampling temperature. */
35 temperature?: number;
36 /** Maximum decode steps. */
37 maxDecodeSteps?: number;
38 /** Top-K sampling. */
39 topK?: number;
40 /** Top-P (nucleus) sampling. */
41 topP?: number;
42 };
43
44 export type GeneratorPlaceholder = {
45 /** Placeholder id referenced from the prompt. */
46 id?: string;
47 /** Human-readable placeholder name. */
48 name?: string;
49 };
50
51 export type GeneratorLlmModelSettings = {
52 /** LLM model id. */
53 model?: string;
54 /** Model prompt text. */
55 promptText?: string;
56 };
57
58 export type AgentsGeneratorProps = {
59 /**
60 * Parent agent resource name
61 * `projects/{project}/locations/{location}/agents/{agent}`.
62 * Immutable — changing it replaces the generator.
63 */
64 agent: string;
65 /**
66 * Generator id (the `{generator}` segment). Server-assigned when
67 * omitted. Immutable — changing it replaces the generator.
68 */
69 generatorId?: string;
70 /**
71 * Location used when `agent` is an id rather than a resource name.
72 * Immutable — changing it replaces the generator.
73 * @default "global"
74 */
75 location?: string;
76 /**
77 * Human-readable name. Generators have no labels field, so Alchemy
78 * stamps ownership into this field and strips it from attributes.
79 */
80 displayName?: string;
81 /**
82 * Prompt phrase the generator fills in.
83 * @default "Say hello."
84 */
85 promptText?: string;
86 /** Language code for the prompt (`en`, `en-US`, …). */
87 languageCode?: string;
88 /** Decoding parameters. */
89 modelParameter?: GeneratorModelParameter;
90 /** Placeholders referenced from `promptText`. */
91 placeholders?: GeneratorPlaceholder[];
92 /** LLM model settings. */
93 llmModelSettings?: GeneratorLlmModelSettings;
94 };
95
96 export type AgentsGenerator = Resource<
97 "GCP.Dialogflow.AgentsGenerator",
98 AgentsGeneratorProps,
99 {
100 /** Full resource name `.../agents/{agent}/generators/{generator}`. */
101 name: string;
102 /** Generator id (last path segment). */
103 generatorId: string;
104 /** Parent agent resource name. */
105 agent: string;
106 /** Location id. */
107 location: string;
108 /** Project id. */
109 project: string;
110 /** User display name with the Alchemy ownership prefix stripped. */
111 displayName: string | undefined;
112 /** Prompt text. */
113 promptText: string | undefined;
114 /** Decoding parameters. */
115 modelParameter: GeneratorModelParameter | undefined;
116 /** Placeholders. */
117 placeholders: GeneratorPlaceholder[] | undefined;
118 /** LLM model settings. */
119 llmModelSettings: GeneratorLlmModelSettings | undefined;
120 },
121 never,
122 Providers
123 >;
124
125 /**
126 * A Dialogflow CX generator that produces LLM-backed response text.
127 *
128 * Generators have no labels field — Alchemy stamps ownership into
129 * `displayName` so `list` / nuke can find them. Parent agent and id are
130 * immutable. Display name, prompt, model parameters, placeholders, and
131 * LLM settings update in place.
132 *
133 * ### Creating a Generator
134 * **Example:** Prompt generator
135 * ```typescript
136 * const generator = yield* GCP.Dialogflow.AgentsGenerator("Greeting", {
137 * agent: agentName,
138 * displayName: "greeting",
139 * promptText: "Greet the user by name.",
140 * });
141 * ```
142 *
143 * ### Updating a Generator
144 * Change props on the same logical id; the engine keeps the physical id.
145 *
146 * **Example:** Change the prompt
147 * ```typescript
148 * const generator = yield* GCP.Dialogflow.AgentsGenerator("Greeting", {
149 * agent: agentName,
150 * displayName: "greeting",
151 * promptText: "Greet the user warmly.",
152 * });
153 * ```
154 *
155 * @resource
156 * @category Dialogflow
157 */
158 export const AgentsGenerator = Resource<AgentsGenerator>("GCP.Dialogflow.AgentsGenerator");
159
160 export class AgentsGeneratorNotResolved extends Data.TaggedError(
161 "GCP.Dialogflow.AgentsGeneratorNotResolved",
162 )<{
163 resourceName: string;
164 }> {}
165
166 const DEFAULT_PROMPT = "Say hello.";
167
168 const resourceName = (agent: string, generatorId: string) => `${agent}/generators/${generatorId}`;
169
170 const modelParameterOf = (
171 parameter: dialogflow.GoogleCloudDialogflowCxV3GeneratorModelParameter | undefined,
172 ): GeneratorModelParameter | undefined => {
173 if (parameter === undefined) return undefined;
174 return {
175 temperature: parameter.temperature,
176 maxDecodeSteps: parameter.maxDecodeSteps,
177 topK: parameter.topK,
178 topP: parameter.topP,
179 };
180 };
181
182 const placeholdersOf = (
183 placeholders: dialogflow.GoogleCloudDialogflowCxV3GeneratorPlaceholderList | undefined,
184 ): GeneratorPlaceholder[] | undefined => {
185 if (placeholders === undefined) return undefined;
186 return placeholders.map((placeholder) => ({
187 id: placeholder.id,
188 name: placeholder.name,
189 }));
190 };
191
192 const llmSettingsOf = (
193 settings: dialogflow.GoogleCloudDialogflowCxV3LlmModelSettings | undefined,
194 ): GeneratorLlmModelSettings | undefined => {
195 if (settings === undefined) return undefined;
196 return { model: settings.model, promptText: settings.promptText };
197 };
198
199 const toAttrs = (
200 generator: dialogflow.GoogleCloudDialogflowCxV3Generator,
201 project: string,
202 agentHint?: string,
203 ) => {
204 const name = generator.name ?? "";
205 const parsed = parseOwnership(generator.displayName);
206 return {
207 name,
208 generatorId: lastSegment(name),
209 agent: name.includes("/generators/")
210 ? collectionParent(name, "agents")
211 : (agentHint ?? parentOf(name)),
212 location: locationOf(name),
213 project: projectOf(name) || project,
214 displayName: parsed.text,
215 promptText: generator.promptText?.text,
216 modelParameter: modelParameterOf(generator.modelParameter),
217 placeholders: placeholdersOf(generator.placeholders),
218 llmModelSettings: llmSettingsOf(generator.llmModelSettings),
219 };
220 };
221
222 const getByName = (name: string) =>
223 name.length === 0
224 ? Effect.undefined
225 : dialogflow
226 .getProjectsLocationsAgentsGenerators({ name })
227 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
228
229 const listAt = (parent: string, project: string) =>
230 dialogflow.listProjectsLocationsAgentsGenerators.pages({ parent, pageSize: 100 }).pipe(
231 Stream.flatMap((page) => Stream.fromIterable(page.generators ?? [])),
232 Stream.filter((generator) => hasOwnershipMarker(generator.displayName)),
233 Stream.map((generator) => toAttrs(generator, project, parent)),
234 Stream.runCollect,
235 Effect.map((chunk) => Array.from(chunk)),
236 Effect.catchTag("NotFound", () => Effect.succeed([])),
237 );
238
239 const findByDisplayName = (parent: string, displayName: string) =>
240 dialogflow.listProjectsLocationsAgentsGenerators.pages({ parent, pageSize: 100 }).pipe(
241 Stream.flatMap((page) => Stream.fromIterable(page.generators ?? [])),
242 Stream.filter((generator) => generator.displayName === displayName),
243 Stream.runHead,
244 Effect.map((option) => (option._tag === "Some" ? option.value : undefined)),
245 Effect.catchTag("NotFound", () => Effect.undefined),
246 );
247
248 export const AgentsGeneratorProvider = () =>
249 Provider.succeed(AgentsGenerator, {
250 stables: ["name", "generatorId", "agent", "location", "project"],
251
252 diff: Effect.fn(function* ({ news, olds, output }) {
253 if (!isResolved(news)) return undefined;
254 const previousAgent = olds?.agent ?? output?.agent;
255 if (previousAgent !== undefined && news.agent !== previousAgent) {
256 return { action: "replace" as const, deleteFirst: false };
257 }
258 const previousId = olds?.generatorId ?? output?.generatorId;
259 if (
260 previousId !== undefined &&
261 news.generatorId !== undefined &&
262 news.generatorId !== previousId
263 ) {
264 return { action: "replace" as const, deleteFirst: false };
265 }
266 const previousLocation = olds?.location ?? output?.location;
267 if (
268 previousLocation !== undefined &&
269 news.location !== undefined &&
270 normalizeLocation(previousLocation) !== normalizeLocation(news.location)
271 ) {
272 return { action: "replace" as const, deleteFirst: false };
273 }
274 return undefined;
275 }),
276
277 read: Effect.fn(function* ({ id, olds, output }) {
278 const env = yield* GcpEnvironment.current;
279 const location = normalizeLocation(olds?.location ?? output?.location);
280 const agent = olds?.agent ? expandAgent(olds.agent, env.project, location) : output?.agent;
281 const generatorId = yield* toResourceId(id, olds?.generatorId, output?.generatorId);
282 const name = output?.name ?? (agent !== undefined ? resourceName(agent, generatorId) : "");
283 let existing = yield* getByName(name);
284 if (existing === undefined && agent !== undefined) {
285 const ownership = yield* internalLabels(id);
286 existing = yield* findByDisplayName(
287 agent,
288 encodeOwnershipLine(ownership, olds?.displayName),
289 );
290 }
291 if (existing === undefined) return undefined;
292 const attrs = toAttrs(existing, env.project, agent);
293 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
294 }),
295
296 list: () =>
297 Effect.gen(function* () {
298 const env = yield* GcpEnvironment.current;
299 const agents = yield* namedAgents(env.project);
300 const pages = yield* Effect.forEach(agents, (agent) => listAt(agent.name, env.project), {
301 concurrency: 4,
302 });
303 return pages.flat();
304 }),
305
306 reconcile: Effect.fn(function* ({ id, news, output }) {
307 const env = yield* GcpEnvironment.current;
308 const location = normalizeLocation(news.location ?? output?.location ?? DEFAULT_LOCATION);
309 const agent = expandAgent(news.agent, env.project, location);
310 const generatorId = yield* toResourceId(id, news.generatorId, output?.generatorId);
311 const name = output?.name ?? resourceName(agent, generatorId);
312 const ownership = yield* internalLabels(id);
313 const displayName = encodeOwnershipLine(ownership, news.displayName);
314 const promptText = news.promptText ?? DEFAULT_PROMPT;
315 const body: dialogflow.GoogleCloudDialogflowCxV3Generator = {
316 displayName,
317 promptText: { text: promptText },
318 modelParameter: news.modelParameter,
319 placeholders: news.placeholders,
320 llmModelSettings: news.llmModelSettings,
321 };
322
323 let current = yield* getByName(output?.name ?? name);
324 if (current === undefined) {
325 current = yield* findByDisplayName(agent, displayName);
326 }
327
328 if (current === undefined) {
329 const created = yield* dialogflow
330 .createProjectsLocationsAgentsGenerators({
331 parent: agent,
332 languageCode: news.languageCode,
333 body,
334 })
335 .pipe(Effect.catchTag("Conflict", () => findByDisplayName(agent, displayName)));
336 current = created ?? undefined;
337 }
338
339 if (current === undefined) {
340 return yield* new AgentsGeneratorNotResolved({ resourceName: name });
341 }
342
343 const currentName = current.name ?? name;
344 const displayChanged = (current.displayName ?? "") !== displayName;
345 const promptChanged = !sameText(current.promptText?.text, promptText);
346 const modelChanged =
347 fingerprint(modelParameterOf(current.modelParameter)) !== fingerprint(news.modelParameter);
348 const placeholdersChanged =
349 fingerprint(placeholdersOf(current.placeholders)) !== fingerprint(news.placeholders);
350 const llmChanged =
351 fingerprint(llmSettingsOf(current.llmModelSettings)) !== fingerprint(news.llmModelSettings);
352
353 if (displayChanged || promptChanged || modelChanged || placeholdersChanged || llmChanged) {
354 current = yield* dialogflow.patchProjectsLocationsAgentsGenerators({
355 name: currentName,
356 languageCode: news.languageCode,
357 updateMask: updateMaskOf(
358 displayChanged ? "display_name" : undefined,
359 promptChanged ? "prompt_text" : undefined,
360 modelChanged ? "model_parameter" : undefined,
361 placeholdersChanged ? "placeholders" : undefined,
362 llmChanged ? "llm_model_settings" : undefined,
363 ),
364 body: { ...body, name: currentName },
365 });
366 }
367
368 return toAttrs(current, env.project, agent);
369 }, retryQuota),
370
371 delete: Effect.fn(function* ({ output }) {
372 yield* dialogflow
373 .deleteProjectsLocationsAgentsGenerators({
374 name: output.name,
375 force: true,
376 })
377 .pipe(Effect.catchTag("NotFound", () => Effect.void));
378 }, retryQuota),
379 });