@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 407 lines 13.8 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 encodeOwnershipLine,
15 fingerprint,
16 hasOwnershipMarker,
17 internalLabels,
18 lastSegment,
19 locationOf,
20 namedAgents,
21 ownedByAlchemy,
22 parentOf,
23 parseOwnership,
24 projectOf,
25 sameText,
26 toResourceId,
27 retryQuota,
28 } from "./internal.ts";
29
30 export type ExampleConversationState =
31 | "OUTPUT_STATE_UNSPECIFIED"
32 | "OUTPUT_STATE_OK"
33 | "OUTPUT_STATE_CANCELLED"
34 | "OUTPUT_STATE_FAILED"
35 | "OUTPUT_STATE_ESCALATED"
36 | "OUTPUT_STATE_PENDING";
37
38 export type ExampleAction = {
39 /** User utterance. */
40 userUtterance?: { text?: string };
41 /** Agent utterance. */
42 agentUtterance?: { text?: string };
43 /** Tool use. */
44 toolUse?: {
45 tool?: string;
46 action?: string;
47 displayName?: string;
48 };
49 /** Playbook invocation. */
50 playbookInvocation?: {
51 playbook?: string;
52 displayName?: string;
53 };
54 /** Flow invocation. */
55 flowInvocation?: {
56 flow?: string;
57 displayName?: string;
58 };
59 };
60
61 export type AgentsPlaybooksExampleProps = {
62 /**
63 * Parent playbook resource name
64 * `projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}`.
65 * Immutable — changing it replaces the example.
66 */
67 playbook: string;
68 /**
69 * Example id (the `{example}` segment). Server-assigned when omitted.
70 * Immutable — changing it replaces the example.
71 */
72 exampleId?: string;
73 /**
74 * Human-readable name. Examples have no labels field, so Alchemy
75 * stamps ownership into `displayName` and `description`.
76 */
77 displayName?: string;
78 /**
79 * End state of the example conversation.
80 * @default "OUTPUT_STATE_OK"
81 */
82 conversationState?: ExampleConversationState | (string & {});
83 /**
84 * Ordered conversation actions. Defaults to a single user utterance
85 * followed by an agent utterance.
86 */
87 actions?: ExampleAction[];
88 /** Human-readable description. */
89 description?: string;
90 /** Language code (`en`, `en-US`, …). */
91 languageCode?: string;
92 /** Preceding conversation summary used as playbook input. */
93 playbookInput?: { precedingConversationSummary?: string };
94 /** Playbook output summary. */
95 playbookOutput?: { executionSummary?: string };
96 };
97
98 export type AgentsPlaybooksExample = Resource<
99 "GCP.Dialogflow.AgentsPlaybooksExample",
100 AgentsPlaybooksExampleProps,
101 {
102 /** Full resource name `.../playbooks/{playbook}/examples/{example}`. */
103 name: string;
104 /** Example id (last path segment). */
105 exampleId: string;
106 /** Parent playbook resource name. */
107 playbook: string;
108 /** Location id. */
109 location: string;
110 /** Project id. */
111 project: string;
112 /** User display name with the Alchemy ownership prefix stripped. */
113 displayName: string | undefined;
114 /** Conversation end state. */
115 conversationState: string | undefined;
116 /** Conversation actions. */
117 actions: ExampleAction[] | undefined;
118 /** User description with the Alchemy ownership prefix stripped. */
119 description: string | undefined;
120 /** Language code. */
121 languageCode: string | undefined;
122 /** Token count. */
123 tokenCount: string | undefined;
124 /** RFC3339 create timestamp. */
125 createTime: string | undefined;
126 /** RFC3339 update timestamp. */
127 updateTime: string | undefined;
128 },
129 never,
130 Providers
131 >;
132
133 /**
134 * A Dialogflow CX playbook example (few-shot conversation).
135 *
136 * Examples have no labels field — Alchemy stamps ownership into
137 * `displayName` and `description` so `list` / nuke can find them. Parent
138 * playbook and id are immutable. Display name, conversation state,
139 * actions, and description update in place.
140 *
141 * ### Creating an Example
142 * **Example:** Greeting conversation
143 * ```typescript
144 * const example = yield* GCP.Dialogflow.AgentsPlaybooksExample("Hello", {
145 * playbook: playbook.name,
146 * displayName: "hello",
147 * conversationState: "OUTPUT_STATE_OK",
148 * actions: [
149 * { userUtterance: { text: "hello" } },
150 * { agentUtterance: { text: "Hi, how can I help?" } },
151 * ],
152 * });
153 * ```
154 *
155 * @resource
156 * @category Dialogflow
157 */
158 export const AgentsPlaybooksExample = Resource<AgentsPlaybooksExample>(
159 "GCP.Dialogflow.AgentsPlaybooksExample",
160 );
161
162 export class AgentsPlaybooksExampleNotResolved extends Data.TaggedError(
163 "GCP.Dialogflow.AgentsPlaybooksExampleNotResolved",
164 )<{
165 resourceName: string;
166 }> {}
167
168 const DEFAULT_STATE: ExampleConversationState = "OUTPUT_STATE_OK";
169 const DEFAULT_ACTIONS: ExampleAction[] = [
170 { userUtterance: { text: "hello" } },
171 { agentUtterance: { text: "Hi, how can I help?" } },
172 ];
173
174 const resourceName = (playbook: string, exampleId: string) => `${playbook}/examples/${exampleId}`;
175
176 const actionsOf = (
177 actions: dialogflow.GoogleCloudDialogflowCxV3ActionList | undefined,
178 ): ExampleAction[] | undefined => {
179 if (actions === undefined) return undefined;
180 return actions.map((action) => ({
181 userUtterance: action.userUtterance ? { text: action.userUtterance.text } : undefined,
182 agentUtterance: action.agentUtterance ? { text: action.agentUtterance.text } : undefined,
183 toolUse: action.toolUse
184 ? {
185 tool: action.toolUse.tool,
186 action: action.toolUse.action,
187 displayName: action.toolUse.displayName,
188 }
189 : undefined,
190 playbookInvocation: action.playbookInvocation
191 ? {
192 playbook: action.playbookInvocation.playbook,
193 displayName: action.playbookInvocation.displayName,
194 }
195 : undefined,
196 flowInvocation: action.flowInvocation
197 ? {
198 flow: action.flowInvocation.flow,
199 displayName: action.flowInvocation.displayName,
200 }
201 : undefined,
202 }));
203 };
204
205 const toAttrs = (
206 example: dialogflow.GoogleCloudDialogflowCxV3Example,
207 project: string,
208 playbookHint?: string,
209 ) => {
210 const name = example.name ?? "";
211 return {
212 name,
213 exampleId: lastSegment(name),
214 playbook: name.includes("/examples/")
215 ? collectionParent(name, "playbooks")
216 : (playbookHint ?? parentOf(name)),
217 location: locationOf(name),
218 project: projectOf(name) || project,
219 displayName: parseOwnership(example.displayName).text,
220 conversationState: example.conversationState,
221 actions: actionsOf(example.actions),
222 description: parseOwnership(example.description).text,
223 languageCode: example.languageCode,
224 tokenCount: example.tokenCount,
225 createTime: example.createTime,
226 updateTime: example.updateTime,
227 };
228 };
229
230 const getByName = (name: string) =>
231 name.length === 0
232 ? Effect.undefined
233 : dialogflow
234 .getProjectsLocationsAgentsPlaybooksExamples({ name })
235 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
236
237 const listAt = (parent: string, project: string) =>
238 dialogflow.listProjectsLocationsAgentsPlaybooksExamples.pages({ parent, pageSize: 100 }).pipe(
239 Stream.flatMap((page) => Stream.fromIterable(page.examples ?? [])),
240 Stream.filter(
241 (example) =>
242 hasOwnershipMarker(example.displayName) || hasOwnershipMarker(example.description),
243 ),
244 Stream.map((example) => toAttrs(example, project, parent)),
245 Stream.runCollect,
246 Effect.map((chunk) => Array.from(chunk)),
247 Effect.catchTag("NotFound", () => Effect.succeed([])),
248 );
249
250 const listPlaybooks = (agent: string) =>
251 dialogflow.listProjectsLocationsAgentsPlaybooks.pages({ parent: agent, pageSize: 100 }).pipe(
252 Stream.flatMap((page) => Stream.fromIterable(page.playbooks ?? [])),
253 Stream.runCollect,
254 Effect.map((chunk) => Array.from(chunk)),
255 Effect.catchTag("NotFound", () => Effect.succeed([])),
256 );
257
258 const findByDisplayName = (parent: string, displayName: string) =>
259 dialogflow.listProjectsLocationsAgentsPlaybooksExamples.pages({ parent, pageSize: 100 }).pipe(
260 Stream.flatMap((page) => Stream.fromIterable(page.examples ?? [])),
261 Stream.filter((example) => example.displayName === displayName),
262 Stream.runHead,
263 Effect.map((option) => (option._tag === "Some" ? option.value : undefined)),
264 Effect.catchTag("NotFound", () => Effect.undefined),
265 );
266
267 export const AgentsPlaybooksExampleProvider = () =>
268 Provider.succeed(AgentsPlaybooksExample, {
269 stables: ["name", "exampleId", "playbook", "location", "project", "createTime"],
270
271 diff: Effect.fn(function* ({ news, olds, output }) {
272 if (!isResolved(news)) return undefined;
273 const previousParent = olds?.playbook ?? output?.playbook;
274 if (previousParent !== undefined && news.playbook !== previousParent) {
275 return { action: "replace" as const, deleteFirst: false };
276 }
277 const previousId = olds?.exampleId ?? output?.exampleId;
278 if (
279 previousId !== undefined &&
280 news.exampleId !== undefined &&
281 news.exampleId !== previousId
282 ) {
283 return { action: "replace" as const, deleteFirst: false };
284 }
285 return undefined;
286 }),
287
288 read: Effect.fn(function* ({ id, olds, output }) {
289 const env = yield* GcpEnvironment.current;
290 const playbook = olds?.playbook ?? output?.playbook;
291 const exampleId = yield* toResourceId(id, olds?.exampleId, output?.exampleId);
292 const name =
293 output?.name ?? (playbook !== undefined ? resourceName(playbook, exampleId) : "");
294 let existing = yield* getByName(name);
295 if (existing === undefined && playbook !== undefined) {
296 const ownership = yield* internalLabels(id);
297 existing = yield* findByDisplayName(
298 playbook,
299 encodeOwnershipLine(ownership, olds?.displayName),
300 );
301 }
302 if (existing === undefined) return undefined;
303 const attrs = toAttrs(existing, env.project, playbook);
304 const named = yield* ownedByAlchemy(id, existing.displayName);
305 const described = yield* ownedByAlchemy(id, existing.description);
306 return named || described ? attrs : Unowned(attrs);
307 }),
308
309 list: () =>
310 Effect.gen(function* () {
311 const env = yield* GcpEnvironment.current;
312 const agents = yield* namedAgents(env.project);
313 const pages = yield* Effect.forEach(
314 agents,
315 (agent) =>
316 Effect.gen(function* () {
317 const playbooks = yield* listPlaybooks(agent.name);
318 const examples = yield* Effect.forEach(
319 playbooks,
320 (playbook) =>
321 playbook.name ? listAt(playbook.name, env.project) : Effect.succeed([]),
322 { concurrency: 4 },
323 );
324 return examples.flat();
325 }),
326 { concurrency: 2 },
327 );
328 return pages.flat();
329 }),
330
331 reconcile: Effect.fn(function* ({ id, news, output }) {
332 const env = yield* GcpEnvironment.current;
333 const playbook = news.playbook;
334 const exampleId = yield* toResourceId(id, news.exampleId, output?.exampleId);
335 const name = output?.name ?? resourceName(playbook, exampleId);
336 const ownership = yield* internalLabels(id);
337 const displayName = encodeOwnershipLine(ownership, news.displayName);
338 const description = encodeOwnership(ownership, news.description);
339 const conversationState = news.conversationState ?? DEFAULT_STATE;
340 const actions = news.actions ?? DEFAULT_ACTIONS;
341 const body: dialogflow.GoogleCloudDialogflowCxV3Example = {
342 displayName,
343 description,
344 conversationState,
345 actions,
346 languageCode: news.languageCode,
347 playbookInput: news.playbookInput,
348 playbookOutput: news.playbookOutput,
349 };
350
351 let current = yield* getByName(output?.name ?? name);
352 if (current === undefined) {
353 current = yield* findByDisplayName(playbook, displayName);
354 }
355
356 if (current === undefined) {
357 const created = yield* dialogflow
358 .createProjectsLocationsAgentsPlaybooksExamples({
359 parent: playbook,
360 body,
361 })
362 .pipe(Effect.catchTag("Conflict", () => findByDisplayName(playbook, displayName)));
363 current = created ?? undefined;
364 }
365
366 if (current === undefined) {
367 return yield* new AgentsPlaybooksExampleNotResolved({ resourceName: name });
368 }
369
370 const currentName = current.name ?? name;
371 const displayChanged = (current.displayName ?? "") !== displayName;
372 const descriptionChanged = (current.description ?? "") !== description;
373 const stateChanged = (current.conversationState ?? DEFAULT_STATE) !== conversationState;
374 const actionsChanged = fingerprint(actionsOf(current.actions)) !== fingerprint(actions);
375 const languageChanged = !sameText(current.languageCode, news.languageCode);
376 const inputChanged = fingerprint(current.playbookInput) !== fingerprint(news.playbookInput);
377 const outputChanged =
378 fingerprint(current.playbookOutput) !== fingerprint(news.playbookOutput);
379
380 if (
381 displayChanged ||
382 descriptionChanged ||
383 stateChanged ||
384 actionsChanged ||
385 languageChanged ||
386 inputChanged ||
387 outputChanged
388 ) {
389 current = yield* dialogflow.patchProjectsLocationsAgentsPlaybooksExamples({
390 // Repeated fields named in an update mask (`actions`) are
391 // silently ignored; the body is complete, so replace it whole.
392 name: currentName,
393 body: { ...body, name: currentName },
394 });
395 }
396
397 return toAttrs(current, env.project, playbook);
398 }, retryQuota),
399
400 delete: Effect.fn(function* ({ output }) {
401 yield* dialogflow
402 .deleteProjectsLocationsAgentsPlaybooksExamples({
403 name: output.name,
404 })
405 .pipe(Effect.catchTag("NotFound", () => Effect.void));
406 }, retryQuota),
407 });