@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 380 lines 13.1 KB
Raw
1 import * as aiplatform from "@distilled.cloud/gcp/aiplatform_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 * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import { listLocations } from "./names.ts";
13 import { resourceNameFromOperation, waitForOperation } from "./operations.ts";
14 import { listAlchemyReasoningEngines } from "./ReasoningEngine.ts";
15 import {
16 AiPlatformNotResolved,
17 AiPlatformStillExists,
18 collectPages,
19 encodeDescription,
20 hasDescriptionOwnership,
21 jsonEqual,
22 lastSegment,
23 locationParent,
24 normalizeLocation,
25 parentBefore,
26 parseDescription,
27 parseResourceName,
28 toPhysicalId,
29 } from "./shared.ts";
30
31 const COLLECTION = "memories";
32
33 export type MemoryMetadataValue = {
34 boolValue?: boolean;
35 doubleValue?: number;
36 stringValue?: string;
37 timestampValue?: string;
38 };
39
40 export type ReasoningEnginesMemoryProps = {
41 /**
42 * Parent Reasoning Engine. Full name
43 * `projects/{project}/locations/{location}/reasoningEngines/{engine}`
44 * or the engine id (combined with `location`). Immutable — changing it
45 * replaces the memory.
46 */
47 reasoningEngine: string;
48 /**
49 * Vertex AI location. Used when `reasoningEngine` is a bare id.
50 * Immutable. @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
51 */
52 location?: string;
53 /**
54 * Memory id. If omitted, a unique RFC1035 name is generated. Immutable
55 * — changing it replaces the memory.
56 */
57 memoryId?: string;
58 /**
59 * Isolation scope. Required and immutable. Values cannot contain `*`.
60 */
61 scope: Record<string, string>;
62 /**
63 * Semantic fact extracted from source content.
64 */
65 fact?: string;
66 /**
67 * Display name.
68 */
69 displayName?: string;
70 /**
71 * Human-readable description. Memory has no labels field, so Alchemy
72 * ownership is stored in a `[alchemy …]` prefix for `list` / nuke.
73 */
74 description?: string;
75 /**
76 * User-provided metadata (not generated by Memory Bank).
77 */
78 metadata?: Record<string, MemoryMetadataValue>;
79 /**
80 * TTL for this memory (e.g. `"86400s"`). Input only.
81 */
82 ttl?: string;
83 /**
84 * Absolute expire time (RFC3339).
85 */
86 expireTime?: string;
87 };
88
89 export type ReasoningEnginesMemory = Resource<
90 "GCP.AIPlatform.ReasoningEnginesMemory",
91 ReasoningEnginesMemoryProps,
92 {
93 /** Full resource name. */
94 name: string;
95 /** Memory id (last path segment). */
96 memoryId: string;
97 /** Parent Reasoning Engine resource name. */
98 reasoningEngine: string;
99 /** Project id. */
100 project: string;
101 /** Location id. */
102 location: string;
103 /** Isolation scope. */
104 scope: aiplatform.StringMap;
105 /** Semantic fact. */
106 fact: string | undefined;
107 /** Display name. */
108 displayName: string | undefined;
109 /** User description with the Alchemy ownership prefix stripped. */
110 description: string | undefined;
111 /** RFC3339 expire time. */
112 expireTime: string | undefined;
113 /** RFC3339 creation timestamp. */
114 createTime: string | undefined;
115 /** RFC3339 last-update timestamp. */
116 updateTime: string | undefined;
117 },
118 never,
119 Providers
120 >;
121
122 /**
123 * A Vertex AI Reasoning Engine memory — scoped semantic knowledge used
124 * by an Agent Engine Memory Bank.
125 *
126 * Memory has no labels, so Alchemy stamps ownership into the
127 * description. Changing `memoryId`, `reasoningEngine`, `location`, or
128 * `scope` replaces the memory. Fact, description, and metadata update in
129 * place.
130 *
131 * ### Creating a Memory
132 * **Example:** User-scoped fact
133 * ```typescript
134 * const memory = yield* GCP.AIPlatform.ReasoningEnginesMemory("Pref", {
135 * reasoningEngine: engine.name,
136 * scope: { user_id: "user-123" },
137 * fact: "the user prefers concise answers",
138 * });
139 * ```
140 *
141 * @resource
142 * @category AIPlatform
143 */
144 export const ReasoningEnginesMemory = Resource<ReasoningEnginesMemory>(
145 "GCP.AIPlatform.ReasoningEnginesMemory",
146 );
147
148 export class ReasoningEnginesMemoryNotResolved extends Data.TaggedError(
149 "GCP.AIPlatform.ReasoningEnginesMemoryNotResolved",
150 )<{
151 resourceName: string;
152 }> {}
153
154 const engineNameOf = (project: string, location: string, reasoningEngine: string) =>
155 reasoningEngine.includes("/")
156 ? reasoningEngine
157 : `${locationParent(project, location)}/reasoningEngines/${reasoningEngine}`;
158
159 const resourceName = (parent: string, memoryId: string) => `${parent}/${COLLECTION}/${memoryId}`;
160
161 const toAttrs = (memory: aiplatform.GoogleCloudAiplatformV1Memory, project: string) => {
162 const name = memory.name ?? "";
163 const parsed = parseResourceName(name, COLLECTION);
164 const description = parseDescription(memory.description);
165 return {
166 name,
167 memoryId: parsed.id,
168 reasoningEngine: parentBefore(name, COLLECTION),
169 project: parsed.project || project,
170 location: parsed.location,
171 scope: memory.scope ?? {},
172 fact: memory.fact,
173 displayName: memory.displayName,
174 description: description.description,
175 expireTime: memory.expireTime,
176 createTime: memory.createTime,
177 updateTime: memory.updateTime,
178 };
179 };
180
181 const getByName = (name: string) =>
182 aiplatform
183 .getProjectsLocationsReasoningEnginesMemories({ name })
184 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
185
186 const waitUntilExists = (name: string) =>
187 getByName(name).pipe(
188 Effect.filterOrFail(
189 (memory): memory is aiplatform.GoogleCloudAiplatformV1Memory => memory !== undefined,
190 () => new AiPlatformNotResolved({ resourceName: name }),
191 ),
192 Effect.retry({
193 while: (error) => error._tag === "GCP.AIPlatform.NotResolved",
194 times: 8,
195 schedule: Schedule.spaced("2 seconds"),
196 }),
197 );
198
199 const waitUntilGone = (name: string) =>
200 getByName(name).pipe(
201 Effect.filterOrFail(
202 (memory) => memory === undefined,
203 () => new AiPlatformStillExists({ resourceName: name }),
204 ),
205 Effect.asVoid,
206 Effect.retry({
207 while: (error) => error._tag === "GCP.AIPlatform.StillExists",
208 times: 10,
209 schedule: Schedule.spaced("2 seconds"),
210 }),
211 );
212
213 const listMemories = (parent: string) =>
214 collectPages(
215 aiplatform.listProjectsLocationsReasoningEnginesMemories.pages({
216 parent,
217 pageSize: 100,
218 }),
219 ).pipe(
220 Effect.map((pages) => pages.flatMap((page) => page.memories ?? [])),
221 Effect.catchTag("NotFound", () =>
222 Effect.succeed<aiplatform.GoogleCloudAiplatformV1Memory[]>([]),
223 ),
224 );
225
226 export const ReasoningEnginesMemoryProvider = () =>
227 Provider.succeed(ReasoningEnginesMemory, {
228 stables: ["name", "memoryId", "reasoningEngine", "project", "location", "createTime"],
229
230 diff: Effect.fn(function* ({ news, olds, output }) {
231 const env = yield* GcpEnvironment.current;
232 if (!isResolved(news)) return undefined;
233 const previousId = olds?.memoryId ?? output?.memoryId;
234 const nextId = news.memoryId ?? previousId;
235 const previousParent = lastSegment(olds?.reasoningEngine ?? output?.reasoningEngine ?? "");
236 const nextParent = lastSegment(news.reasoningEngine);
237 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
238 const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);
239 const scopeChanged = olds !== undefined && !jsonEqual(news.scope, olds.scope);
240 const replace =
241 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
242 (previousParent.length > 0 && previousParent !== nextParent) ||
243 previousLocation !== nextLocation ||
244 scopeChanged;
245 if (!replace) return undefined;
246 return {
247 action: "replace" as const,
248 deleteFirst:
249 previousLocation === nextLocation &&
250 previousParent === nextParent &&
251 previousId !== undefined &&
252 nextId === previousId,
253 };
254 }),
255
256 read: Effect.fn(function* ({ id, olds, output }) {
257 const env = yield* GcpEnvironment.current;
258 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
259 const engine = olds?.reasoningEngine ?? output?.reasoningEngine;
260 // A create interrupted before its engine resolved has nothing to find.
261 if (output?.name === undefined && typeof engine !== "string") {
262 return undefined;
263 }
264 const parent = engineNameOf(env.project, location, engine ?? "");
265 const memoryId = yield* toPhysicalId(id, olds?.memoryId, output?.memoryId);
266 const name = output?.name ?? resourceName(parent, memoryId);
267 const existing = yield* getByName(name);
268 if (existing === undefined) return undefined;
269 const attrs = toAttrs(existing, env.project);
270 const parsed = parseDescription(existing.description);
271 return (yield* hasAlchemyLabels(id, parsed.labels)) ? attrs : Unowned(attrs);
272 }),
273
274 list: () =>
275 Effect.gen(function* () {
276 const env = yield* GcpEnvironment.current;
277 const engines = (yield* Effect.forEach(listLocations(env.region), (location) =>
278 listAlchemyReasoningEngines(env.project, location),
279 )).flat();
280 const memories = yield* Effect.forEach(
281 engines,
282 (engine) =>
283 engine.name
284 ? listMemories(engine.name)
285 : Effect.succeed<aiplatform.GoogleCloudAiplatformV1Memory[]>([]),
286 { concurrency: 4 },
287 );
288 return memories
289 .flat()
290 .filter((memory) => hasDescriptionOwnership(memory.description))
291 .map((memory) => toAttrs(memory, env.project));
292 }),
293
294 reconcile: Effect.fn(function* ({ id, news, output }) {
295 const env = yield* GcpEnvironment.current;
296 const location = normalizeLocation(news.location ?? output?.location, env.region);
297 const parent = engineNameOf(env.project, location, news.reasoningEngine);
298 const memoryId = yield* toPhysicalId(id, news.memoryId, output?.memoryId);
299 const name = resourceName(parent, memoryId);
300 const internal = yield* createInternalLabels(id);
301 const stampedDescription = encodeDescription(internal, news.description);
302
303 let current = yield* getByName(output?.name ?? name);
304
305 if (current === undefined) {
306 const created = yield* aiplatform
307 .createProjectsLocationsReasoningEnginesMemories({
308 parent,
309 memoryId,
310 body: {
311 scope: news.scope,
312 fact: news.fact,
313 displayName: news.displayName,
314 description: stampedDescription,
315 metadata: news.metadata,
316 ttl: news.ttl,
317 expireTime: news.expireTime,
318 },
319 })
320 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
321 if (created !== undefined) {
322 yield* waitForOperation(created, { alreadyExistsOk: true });
323 }
324 const createdName = resourceNameFromOperation(created ?? {}) ?? output?.name ?? name;
325 current = yield* waitUntilExists(createdName);
326 }
327
328 if (current === undefined || current.name === undefined) {
329 return yield* new ReasoningEnginesMemoryNotResolved({ resourceName: name });
330 }
331
332 const observedName = current.name;
333 const observed = parseDescription(current.description);
334 const factChanged = (current.fact ?? "") !== (news.fact ?? "");
335 const displayChanged = (current.displayName ?? "") !== (news.displayName ?? "");
336 const descriptionChanged = (observed.description ?? "") !== (news.description ?? "");
337 const metadataChanged = !jsonEqual(current.metadata, news.metadata);
338
339 if (factChanged || displayChanged || descriptionChanged || metadataChanged) {
340 const updateMask = [
341 factChanged ? "fact" : undefined,
342 displayChanged ? "display_name" : undefined,
343 descriptionChanged ? "description" : undefined,
344 metadataChanged ? "metadata" : undefined,
345 ].filter((field): field is string => field !== undefined);
346 const patched = yield* aiplatform.patchProjectsLocationsReasoningEnginesMemories({
347 name: observedName,
348 updateMask: updateMask.join(","),
349 body: {
350 name: observedName,
351 fact: news.fact,
352 displayName: news.displayName,
353 description: stampedDescription,
354 metadata: news.metadata,
355 },
356 });
357 yield* waitForOperation(patched);
358 current = yield* getByName(observedName);
359 }
360
361 if (current === undefined) {
362 return yield* new ReasoningEnginesMemoryNotResolved({
363 resourceName: observedName,
364 });
365 }
366 return toAttrs(current, env.project);
367 }),
368
369 delete: Effect.fn(function* ({ output }) {
370 const operation = yield* aiplatform
371 .deleteProjectsLocationsReasoningEnginesMemories({
372 name: output.name,
373 })
374 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
375 if (operation !== undefined) {
376 yield* waitForOperation(operation, { notFoundOk: true });
377 }
378 yield* waitUntilGone(output.name);
379 }),
380 });