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

main
ts 221 lines 6.9 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 { parentOf, parseResourceName, sameJson } from "./internal.ts";
10
11 export type ConversationMessage = {
12 userInput?: {
13 input?: string;
14 context?: {
15 contextDocuments?: string[];
16 activeDocument?: string;
17 };
18 };
19 };
20
21 export type CollectionsDataStoresConversationProps = {
22 /**
23 * Parent data store resource name. Immutable — changing it replaces
24 * the conversation.
25 */
26 dataStore: string;
27 /**
28 * Conversation state.
29 * @default "IN_PROGRESS"
30 */
31 state?: "STATE_UNSPECIFIED" | "IN_PROGRESS" | "COMPLETED" | (string & {});
32 /**
33 * End-user id.
34 */
35 userPseudoId?: string;
36 /**
37 * Conversation messages.
38 */
39 messages?: ConversationMessage[];
40 };
41
42 export type CollectionsDataStoresConversation = Resource<
43 "GCP.DiscoveryEngine.CollectionsDataStoresConversation",
44 CollectionsDataStoresConversationProps,
45 {
46 /** Full resource name. */
47 name: string;
48 /** Conversation id (last path segment). */
49 conversationId: string;
50 /** Parent data store resource name. */
51 dataStore: string;
52 /** Project id. */
53 project: string;
54 /** Location id. */
55 location: string;
56 /** Conversation state. */
57 state: string | undefined;
58 /** User-supplied user pseudo id with the Alchemy token stripped. */
59 userPseudoId: string | undefined;
60 /** Conversation messages. */
61 messages: ConversationMessage[];
62 /** RFC3339 start time. */
63 startTime: string | undefined;
64 /** RFC3339 end time. */
65 endTime: string | undefined;
66 },
67 never,
68 Providers
69 >;
70
71 /**
72 * A Discovery Engine conversation on a collection data store.
73 *
74 * Its id is assigned by the API, so only a recorded resource can be read
75 * back. The parent data store is immutable. State and messages update in
76 * place. The conversation id is assigned by the API.
77 *
78 * ### Creating a Conversation
79 * **Example:** Open a conversation
80 * ```typescript
81 * const store = yield* GCP.DiscoveryEngine.CollectionsDataStore("Docs", {});
82 * const chat = yield* GCP.DiscoveryEngine.CollectionsDataStoresConversation(
83 * "Visitor",
84 * {
85 * dataStore: store.name,
86 * userPseudoId: "user-1",
87 * },
88 * );
89 * ```
90 *
91 * @resource
92 * @category DiscoveryEngine
93 */
94 export const CollectionsDataStoresConversation = Resource<CollectionsDataStoresConversation>(
95 "GCP.DiscoveryEngine.CollectionsDataStoresConversation",
96 );
97
98 export class CollectionsDataStoresConversationNotResolved extends Data.TaggedError(
99 "GCP.DiscoveryEngine.CollectionsDataStoresConversationNotResolved",
100 )<{
101 resourceName: string;
102 }> {}
103
104 const toAttrs = (
105 conversation: discoveryengine.GoogleCloudDiscoveryengineV1Conversation,
106 project: string,
107 ) => {
108 const name = conversation.name ?? "";
109 const parsed = parseResourceName(name, "conversations");
110 return {
111 name,
112 conversationId: parsed.id,
113 dataStore: parentOf(name, "conversations"),
114 project: parsed.project || project,
115 location: parsed.location,
116 state: conversation.state,
117 userPseudoId: conversation.userPseudoId,
118 messages: (conversation.messages ?? []).map((message) => ({
119 userInput: message.userInput
120 ? {
121 input: message.userInput.input,
122 context: message.userInput.context,
123 }
124 : undefined,
125 })),
126 startTime: conversation.startTime,
127 endTime: conversation.endTime,
128 };
129 };
130
131 const getByName = (name: string) =>
132 name.length === 0
133 ? Effect.undefined
134 : discoveryengine
135 .getProjectsLocationsCollectionsDataStoresConversations({ name })
136 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
137
138 export const CollectionsDataStoresConversationProvider = () =>
139 Provider.succeed(CollectionsDataStoresConversation, {
140 stables: ["name", "conversationId", "dataStore", "project", "location", "startTime"],
141
142 diff: Effect.fn(function* ({ news, olds, output }) {
143 if (!isResolved(news)) return undefined;
144 const previousParent = olds?.dataStore ?? output?.dataStore;
145 if (previousParent !== undefined && news.dataStore !== previousParent) {
146 return { action: "replace" as const, deleteFirst: false };
147 }
148 return undefined;
149 }),
150
151 read: Effect.fn(function* ({ output }) {
152 const env = yield* GcpEnvironment.current;
153 // Server-assigned id: only a recorded name can be observed.
154 if (output?.name === undefined) return undefined;
155 const existing = yield* getByName(output.name);
156 if (existing === undefined) return undefined;
157 return toAttrs(existing, env.project);
158 }),
159
160 reconcile: Effect.fn(function* ({ news, output }) {
161 const env = yield* GcpEnvironment.current;
162 const userPseudoId = news.userPseudoId;
163 const state = news.state ?? "IN_PROGRESS";
164
165 let current = yield* getByName(output?.name ?? "");
166
167 if (current === undefined) {
168 const created = yield* discoveryengine
169 .createProjectsLocationsCollectionsDataStoresConversations({
170 parent: news.dataStore,
171 body: {
172 state,
173 userPseudoId,
174 messages: news.messages,
175 },
176 })
177 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
178 current = created ?? undefined;
179 }
180
181 if (current === undefined) {
182 return yield* new CollectionsDataStoresConversationNotResolved({
183 resourceName: output?.name ?? `${news.dataStore}/conversations/-`,
184 });
185 }
186
187 const resource = current.name ?? "";
188 const stateChanged = (current.state ?? "") !== state;
189 const userChanged = userPseudoId !== undefined && current.userPseudoId !== userPseudoId;
190 const messagesChanged = !sameJson(current.messages, news.messages);
191
192 if (stateChanged || userChanged || messagesChanged) {
193 current = yield* discoveryengine.patchProjectsLocationsCollectionsDataStoresConversations({
194 name: resource,
195 updateMask: [
196 stateChanged ? "state" : undefined,
197 userChanged ? "user_pseudo_id" : undefined,
198 messagesChanged ? "messages" : undefined,
199 ]
200 .filter((field): field is string => field !== undefined)
201 .join(","),
202 body: {
203 name: resource,
204 state,
205 userPseudoId,
206 messages: news.messages,
207 },
208 });
209 }
210
211 return toAttrs(current, env.project);
212 }),
213
214 delete: Effect.fn(function* ({ output }) {
215 yield* discoveryengine
216 .deleteProjectsLocationsCollectionsDataStoresConversations({
217 name: output.name,
218 })
219 .pipe(Effect.catchTag("NotFound", () => Effect.void));
220 }),
221 });