@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, 04:45 UTC

main
ts 363 lines 13.6 KB
Raw
1 import * as aisearch from "@distilled.cloud/cloudflare/aisearch";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { isResourceOfType, Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10
11 const TypeId = "Cloudflare.AI.SearchNamespace" as const;
12 type TypeId = typeof TypeId;
13
14 export type SearchNamespaceProps = {
15 /**
16 * Namespace name. Lowercase letters, digits, and hyphens; must start and
17 * end with an alphanumeric character; 1-28 characters. The name is the
18 * namespace's identity (it appears in the API path) and cannot be
19 * renamed — changing it triggers a replacement. If omitted, a unique
20 * name is generated from the app, stage, and logical ID.
21 * @default ${app}-${id}-${stage}-${suffix}
22 */
23 name?: string;
24 /**
25 * Optional human-readable description for the namespace.
26 * Max 256 characters.
27 */
28 description?: string;
29 };
30
31 export type SearchNamespaceAttributes = {
32 /**
33 * Namespace name (its identity within the account).
34 */
35 name: string;
36 /**
37 * The Cloudflare account the namespace belongs to.
38 */
39 accountId: string;
40 /**
41 * Human-readable description, when set.
42 */
43 description: string | undefined;
44 /**
45 * When the namespace was created.
46 */
47 createdAt: string | undefined;
48 };
49
50 export type SearchNamespace = Resource<
51 TypeId,
52 SearchNamespaceProps,
53 SearchNamespaceAttributes,
54 never,
55 Providers
56 >;
57
58 /**
59 * A Cloudflare.AI. Search namespace — a logical grouping for AI Search
60 * instances within an account.
61 *
62 * Namespaces partition AI Search (formerly AutoRAG) instances: each
63 * namespace owns its own set of namespace-scoped instances and can be
64 * searched or queried as a unit. The namespace `name` is its identity —
65 * changing it triggers a replacement; only the `description` is mutable
66 * in place.
67 *
68 * The account-provided `default` namespace is reserved: it always exists
69 * and Cloudflare disallows modifying or deleting it. Alchemy adopts it so
70 * it can be referenced and bound, but never updates or tears it down.
71 *
72 * ### Creating a Namespace
73 * **Example:** Generated name
74 * ```typescript
75 * const ns = yield* Cloudflare.AI.SearchNamespace("docs", {});
76 * ```
77 *
78 * **Example:** Explicit name and description
79 * ```typescript
80 * const ns = yield* Cloudflare.AI.SearchNamespace("docs", {
81 * name: "docs-search",
82 * description: "Search over the product documentation",
83 * });
84 * ```
85 *
86 * ### Updating a Namespace
87 * **Example:** Change the description in place
88 * Only the `description` is mutable; changing `name` replaces the namespace.
89 * ```typescript
90 * const ns = yield* Cloudflare.AI.SearchNamespace("docs", {
91 * name: "docs-search",
92 * description: "Search over docs and changelogs",
93 * });
94 * ```
95 *
96 * ### Grouping pipelines
97 * Group {@link Search} pipelines under the namespace by passing the
98 * namespace resource itself to each pipeline's `namespace` prop. The engine
99 * orders each pipeline after the namespace on deploy and tears them down
100 * before it on destroy.
101 * **Example:** Two pipelines in one namespace
102 * ```typescript
103 * const ns = yield* Cloudflare.AI.SearchNamespace("docs", {});
104 * const guides = yield* Cloudflare.AI.Search("guides", {
105 * source: guidesBucket,
106 * namespace: ns,
107 * });
108 * const api = yield* Cloudflare.AI.Search("api", {
109 * source: apiBucket,
110 * namespace: ns,
111 * });
112 * ```
113 *
114 * ### Binding to an Effect Worker
115 * Bind the namespace with `Cloudflare.AI.QuerySearchNamespace(namespace)`,
116 * which attaches the `ai_search_namespace` binding and returns a client
117 * whose `.get(name)` selects an instance within the namespace at runtime.
118 * Provide {@link QuerySearchNamespaceBinding} in the Worker's runtime
119 * layer.
120 * **Example:** Select an instance per request
121 * ```typescript
122 * import * as Cloudflare from "@alchemy.run/cloudflare";
123 * import * as Effect from "effect/Effect";
124 * import { HttpServerRequest } from "effect/http/HttpServerRequest";
125 * import * as HttpServerResponse from "effect/http/HttpServerResponse";
126 *
127 * export default class Api extends Cloudflare.Worker<Api>()(
128 * "api",
129 * { main: import.meta.url },
130 * Effect.gen(function* () {
131 * const ns = yield* Cloudflare.AI.QuerySearchNamespace(Docs);
132 *
133 * return {
134 * fetch: Effect.gen(function* () {
135 * const url = new URL((yield* HttpServerRequest).url);
136 * const instance = url.searchParams.get("instance") ?? "guides";
137 * const query = url.searchParams.get("q") ?? "";
138 * const answer = yield* ns.get(instance).chatCompletions({
139 * messages: [{ role: "user", content: query }],
140 * });
141 * return yield* HttpServerResponse.json(answer);
142 * }),
143 * };
144 * }).pipe(Effect.provide(Cloudflare.AI.QuerySearchNamespaceBinding)),
145 * ) {}
146 * ```
147 *
148 * ### Binding to an Async Worker
149 * For a vanilla `async fetch` Worker, pass the namespace under `Worker.env`.
150 * `InferEnv` types `env.SEARCH` as the runtime `SearchNamespace` handle.
151 * **Example:** Async Worker via `env`
152 * ```typescript
153 * export const Api = Cloudflare.Worker("api", {
154 * main: "./worker.ts",
155 * env: { SEARCH: namespace },
156 * });
157 * export type ApiEnv = Cloudflare.InferEnv<typeof Api>;
158 *
159 * // worker.ts
160 * export default {
161 * async fetch(request: Request, env: ApiEnv): Promise<Response> {
162 * const query = new URL(request.url).searchParams.get("q") ?? "";
163 * return Response.json(
164 * await env.SEARCH.get("guides").chatCompletions({
165 * messages: [{ role: "user", content: query }],
166 * }),
167 * );
168 * },
169 * };
170 * ```
171 *
172 * @see https://developers.cloudflare.com/ai-search/
173 *
174 * @resource
175 * @product AI Search
176 * @category AI
177 */
178 export const SearchNamespace = Resource<SearchNamespace>(TypeId, {
179 aliases: ["Cloudflare.AiSearch.Namespace"],
180 });
181
182 /**
183 * Returns true if the given value is a SearchNamespace resource.
184 */
185 export const isSearchNamespace = (value: unknown): value is SearchNamespace =>
186 isResourceOfType(value, TypeId);
187
188 export const SearchNamespaceProvider = () =>
189 Provider.succeed(SearchNamespace, {
190 stables: ["name", "accountId", "createdAt"],
191 diff: Effect.fn(function* ({ id, olds, news, output }) {
192 const { accountId } = yield* yield* CloudflareEnvironment;
193 if (!isResolved(news)) return undefined;
194 if ((output?.accountId ?? accountId) !== accountId) {
195 return { action: "replace" } as const;
196 }
197 // The name is the namespace's identity (it is the API path
198 // parameter) — renaming is a replacement. Props are all optional, so a
199 // no-props resource resolves `news`/`olds` to `undefined` at runtime.
200 const oldName = output?.name ?? (yield* createNamespaceName(id, olds?.name));
201 // Auto-generated names are engine-owned: the deployed name stays
202 // authoritative even if the generator would name this id differently
203 // today. Only an explicit user-provided name can force a replace.
204 const newName = news?.name ?? oldName;
205 if (newName !== oldName) {
206 // A user-pinned name collides with the still-existing old
207 // namespace only when both resolve to the same string — they
208 // don't here, so create-before-delete is safe.
209 return { action: "replace" } as const;
210 }
211 return undefined;
212 }),
213 read: Effect.fn(function* ({ id, output, olds }) {
214 const { accountId } = yield* yield* CloudflareEnvironment;
215 const acct = output?.accountId ?? accountId;
216 // The name is deterministic (explicit prop or generated from the
217 // logical id), so a cold read (lost state) resolves the same
218 // identifier as the original create did.
219 const name = output?.name ?? (yield* createNamespaceName(id, olds?.name));
220 const observed = yield* getNamespace(acct, name);
221 return observed ? toAttributes(observed, acct) : undefined;
222 }),
223 reconcile: Effect.fn(function* ({ id, news, output }) {
224 const { accountId } = yield* yield* CloudflareEnvironment;
225 const acct = output?.accountId ?? accountId;
226 // Props are all optional, so a no-props resource resolves `news` to
227 // `undefined` at runtime — fall back to the empty desired shape.
228 const props = news ?? {};
229 const name = output?.name ?? (yield* createNamespaceName(id, props.name));
230
231 // Observe — `output.name` is a cache, not a guarantee: a missing
232 // namespace falls through to create.
233 let observed = yield* getNamespace(acct, name);
234
235 if (!observed) {
236 // Ensure — greenfield (or out-of-band delete). A concurrent
237 // create surfaces as `NamespaceAlreadyExists` — treat it as a
238 // race and fall through to the sync path against the observed
239 // namespace.
240 const ensured = yield* aisearch
241 .createNamespace({
242 accountId: acct,
243 name,
244 description: props.description,
245 })
246 .pipe(
247 Effect.map((created) => ({ created: true as const, ns: created })),
248 Effect.catchTag("NamespaceAlreadyExists", (originalError) =>
249 Effect.gen(function* () {
250 const existing = yield* getNamespace(acct, name);
251 if (!existing) return yield* originalError;
252 return { created: false as const, ns: existing };
253 }),
254 ),
255 );
256 if (ensured.created) {
257 return toAttributes(ensured.ns, acct);
258 }
259 observed = ensured.ns;
260 }
261
262 // The account-provided `default` namespace is reserved: it always
263 // exists and its metadata cannot be modified
264 // (`cannot_modify_default_namespace`). Adopt it as-is so it can be
265 // referenced/bound, but never attempt to mutate it.
266 if (name === "default") {
267 return toAttributes(observed, acct);
268 }
269
270 // Sync — the description is the only mutable aspect. Diff observed
271 // cloud state against desired; skip the PUT entirely on a no-op.
272 const observedDescription = normalize(observed.description);
273 if (observedDescription === props.description) {
274 return toAttributes(observed, acct);
275 }
276 const updated = yield* aisearch
277 .updateNamespace({
278 accountId: acct,
279 name,
280 // `null` clears a previously-set description.
281 description: props.description ?? null,
282 })
283 .pipe(
284 // The observe read can be eventually consistent: a namespace
285 // deleted out-of-band may still appear in `readNamespace` and
286 // then 404 here. Treat that as "missing" and recreate with the
287 // desired shape.
288 Effect.catchTag("NamespaceNotFound", () =>
289 aisearch.createNamespace({
290 accountId: acct,
291 name,
292 description: props.description,
293 }),
294 ),
295 );
296 return toAttributes(updated, acct);
297 }),
298 delete: Effect.fn(function* ({ output }) {
299 // The account-provided `default` namespace cannot be deleted
300 // (`cannot_modify_default_namespace`); binding/adopting it must never
301 // tear it down, so its delete is a no-op.
302 if (output.name === "default") return;
303 // A missing namespace (already deleted) is success. Instances inside
304 // the namespace must be deleted first — the engine orders that via
305 // the `namespace` reference on dependent resources.
306 yield* aisearch
307 .deleteNamespace({ accountId: output.accountId, name: output.name })
308 .pipe(Effect.catchTag("NamespaceNotFound", () => Effect.void));
309 }),
310 // Account-scoped collection: namespaces are enumerated directly under
311 // the account (no parent fan-out). Exhaustively paginate `listNamespaces`
312 // and hydrate each item into the exact `read` Attributes shape.
313 list: Effect.fn(function* () {
314 const { accountId } = yield* yield* CloudflareEnvironment;
315 return yield* aisearch.listNamespaces.pages({ accountId }).pipe(
316 Stream.runCollect,
317 Effect.map((chunk) =>
318 Array.from(chunk).flatMap((page) =>
319 (page.result ?? [])
320 // The account-provided `default` namespace can't be deleted
321 // (`cannot_modify_default_namespace`); never enumerate it for
322 // account-wide teardown.
323 .filter((ns) => ns.name !== "default")
324 .map((ns) => toAttributes(ns, accountId)),
325 ),
326 ),
327 );
328 }),
329 });
330
331 type ObservedNamespace = aisearch.ReadNamespaceResponse;
332
333 /**
334 * Read a namespace by name, mapping "gone" (`NamespaceNotFound`,
335 * Cloudflare error code 7063) to `undefined`.
336 */
337 const getNamespace = (accountId: string, name: string) =>
338 aisearch
339 .readNamespace({ accountId, name })
340 .pipe(Effect.catchTag("NamespaceNotFound", () => Effect.undefined));
341
342 const createNamespaceName = (id: string, name: string | undefined) =>
343 Effect.gen(function* () {
344 // Cloudflare restricts namespace names to lowercase alphanumerics and
345 // hyphens, 1-28 characters.
346 return name ?? (yield* createPhysicalName({ id, lowercase: true, maxLength: 28 }));
347 });
348
349 /**
350 * Cloudflare returns `null` for an unset description; desired-state
351 * shapes leave it `undefined`. Collapse both to `undefined` for diffing.
352 */
353 const normalize = <T>(value: T | null | undefined): T | undefined => value ?? undefined;
354
355 const toAttributes = (
356 ns: ObservedNamespace | aisearch.CreateNamespaceResponse | aisearch.UpdateNamespaceResponse,
357 accountId: string,
358 ): SearchNamespaceAttributes => ({
359 name: ns.name,
360 accountId,
361 description: normalize(ns.description),
362 createdAt: ns.createdAt,
363 });