@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 219 lines 6.85 KB
Raw
1 import * as discoveryengine from "@distilled.cloud/gcp/discoveryengine_v1";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import { GcpEnvironment } from "../Environment.ts";
8 import type { Providers } from "../Providers.ts";
9 import { parentBefore, parseResourceName, sameJson } from "./internal.ts";
10
11 export type CollectionsEnginesConversationProps = {
12 /**
13 * Parent Engine resource name
14 * `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`.
15 * Immutable — changing it replaces the conversation.
16 */
17 engine: string;
18 /**
19 * User tracking id.
20 */
21 userPseudoId?: string;
22 /**
23 * Conversation state.
24 */
25 state?: discoveryengine.GoogleCloudDiscoveryengineV1ConversationStateEnum;
26 /**
27 * Conversation messages.
28 */
29 messages?: discoveryengine.GoogleCloudDiscoveryengineV1ConversationMessageList;
30 };
31
32 export type CollectionsEnginesConversation = Resource<
33 "GCP.DiscoveryEngine.CollectionsEnginesConversation",
34 CollectionsEnginesConversationProps,
35 {
36 /** Full resource name. */
37 name: string;
38 /** Conversation id (last path segment). */
39 conversationId: string;
40 /** Parent engine resource name. */
41 engine: string;
42 /** Project id. */
43 project: string;
44 /** Location id. */
45 location: string;
46 /** Collection id. */
47 collectionId: string;
48 /** Tracking id. */
49 userPseudoId: string | undefined;
50 /** Conversation state. */
51 state: string | undefined;
52 /** RFC3339 start timestamp. */
53 startTime: string | undefined;
54 /** RFC3339 end timestamp. */
55 endTime: string | undefined;
56 },
57 never,
58 Providers
59 >;
60
61 /**
62 * A Discovery Engine Conversation on a collection Engine.
63 *
64 * Its id is assigned by the API, so only a recorded resource can be read
65 * back. The API assigns the conversation id. Parent engine is immutable;
66 * state and messages update in place.
67 *
68 * ### Creating a Conversation
69 * **Example:** Empty conversation
70 * ```typescript
71 * const conversation =
72 * yield* GCP.DiscoveryEngine.CollectionsEnginesConversation("Chat", {
73 * engine: engine.name,
74 * });
75 * ```
76 *
77 * ### Updating a Conversation
78 * **Example:** Complete the conversation
79 * ```typescript
80 * // Same logical id as before; only the changed props differ.
81 * const conversation =
82 * yield* GCP.DiscoveryEngine.CollectionsEnginesConversation("Chat", {
83 * engine: engine.name,
84 * state: "COMPLETED",
85 * });
86 * ```
87 *
88 * @resource
89 * @category DiscoveryEngine
90 */
91 export const CollectionsEnginesConversation = Resource<CollectionsEnginesConversation>(
92 "GCP.DiscoveryEngine.CollectionsEnginesConversation",
93 );
94
95 export class CollectionsEnginesConversationNotResolved extends Data.TaggedError(
96 "GCP.DiscoveryEngine.CollectionsEnginesConversationNotResolved",
97 )<{
98 resourceName: string;
99 }> {}
100
101 const getByName = (name: string) =>
102 discoveryengine
103 .getProjectsLocationsCollectionsEnginesConversations({ name })
104 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
105
106 const toAttrs = (
107 conversation: discoveryengine.GoogleCloudDiscoveryengineV1Conversation,
108 project: string,
109 ) => {
110 const name = conversation.name ?? "";
111 const parsed = parseResourceName(name, "conversations");
112 return {
113 name,
114 conversationId: parsed.id,
115 engine: parentBefore(name, "conversations"),
116 project: parsed.project || project,
117 location: parsed.location,
118 collectionId: parsed.collectionId,
119 userPseudoId: conversation.userPseudoId,
120 state: conversation.state,
121 startTime: conversation.startTime,
122 endTime: conversation.endTime,
123 };
124 };
125
126 export const CollectionsEnginesConversationProvider = () =>
127 Provider.succeed(CollectionsEnginesConversation, {
128 stables: [
129 "name",
130 "conversationId",
131 "engine",
132 "project",
133 "location",
134 "collectionId",
135 "startTime",
136 ],
137
138 diff: Effect.fn(function* ({ news, olds, output }) {
139 if (!isResolved(news)) return undefined;
140 const previousEngine = olds?.engine ?? output?.engine;
141 if (previousEngine !== undefined && news.engine !== previousEngine) {
142 return { action: "replace" as const, deleteFirst: false };
143 }
144 return undefined;
145 }),
146
147 read: Effect.fn(function* ({ output }) {
148 const env = yield* GcpEnvironment.current;
149 // Server-assigned id: only a recorded name can be observed.
150 if (output?.name === undefined) return undefined;
151 const existing = yield* getByName(output.name);
152 if (existing === undefined) return undefined;
153 return toAttrs(existing, env.project);
154 }),
155
156 reconcile: Effect.fn(function* ({ news, output }) {
157 const env = yield* GcpEnvironment.current;
158 const userPseudoId = news.userPseudoId;
159 const fallbackName = output?.name ?? `${news.engine}/conversations/-`;
160
161 let current = output?.name !== undefined ? yield* getByName(output.name) : undefined;
162
163 if (current === undefined) {
164 const created = yield* discoveryengine
165 .createProjectsLocationsCollectionsEnginesConversations({
166 parent: news.engine,
167 body: {
168 userPseudoId,
169 state: news.state,
170 messages: news.messages,
171 },
172 })
173 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
174 current = created ?? undefined;
175 }
176
177 if (current === undefined) {
178 return yield* new CollectionsEnginesConversationNotResolved({
179 resourceName: fallbackName,
180 });
181 }
182
183 const name = current.name ?? fallbackName;
184 const userChanged = userPseudoId !== undefined && current.userPseudoId !== userPseudoId;
185 const stateChanged = (current.state ?? "") !== (news.state ?? "");
186 const messagesChanged = !sameJson(current.messages, news.messages);
187
188 if (userChanged || stateChanged || messagesChanged) {
189 current = yield* discoveryengine.patchProjectsLocationsCollectionsEnginesConversations({
190 name,
191 updateMask: [
192 userChanged ? "user_pseudo_id" : undefined,
193 stateChanged ? "state" : undefined,
194 messagesChanged ? "messages" : undefined,
195 ]
196 .filter((field): field is string => field !== undefined)
197 .join(","),
198 body: {
199 name,
200 userPseudoId,
201 state: news.state,
202 messages: news.messages,
203 },
204 });
205 }
206
207 return toAttrs(current, env.project);
208 }),
209
210 delete: Effect.fn(function* ({ output }) {
211 const existing = yield* getByName(output.name);
212 if (existing === undefined) return;
213 yield* discoveryengine
214 .deleteProjectsLocationsCollectionsEnginesConversations({
215 name: output.name,
216 })
217 .pipe(Effect.catchTag("NotFound", () => Effect.void));
218 }),
219 });