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

main
ts 166 lines 6.16 KB
Raw
1 import type * as runtime from "@cloudflare/workers-types";
2 import * as vectorize from "@distilled.cloud/cloudflare/vectorize";
3 import * as Effect from "effect/Effect";
4 import type * as HttpClient from "effect/http/HttpClient";
5 import type { Credentials } from "../Credentials.ts";
6 import type { SearchIndexClient } from "./SearchIndex.ts";
7
8 // Shared HTTP scaffolding for the Vectorize `SearchIndex` binding. NOT
9 // re-exported from `index.ts` — only the contract and the impl layers are
10 // public. A future token-scoped `SearchIndexHttp` layer reuses this builder
11 // with an auth minted from an `AccountApiToken`; `SearchIndexLocal` builds the
12 // auth from the ambient current-credentials context.
13
14 /**
15 * Injectable auth shared by the Local (current-credentials) impl and a future
16 * Http (scoped-token) impl. `authorize` discharges the
17 * `Credentials | HttpClient` requirement of a distilled op; `accountId` is the
18 * Cloudflare account the ops run against.
19 */
20 export interface SearchIndexAuth {
21 authorize: <A, E>(
22 eff: Effect.Effect<A, E, Credentials | HttpClient.HttpClient>,
23 ) => Effect.Effect<A, E>;
24 accountId: string;
25 }
26
27 /**
28 * Build a {@link SearchIndexClient} over the Vectorize HTTP API.
29 *
30 * `indexName` is an Effect so the resolution stays deferred to each call —
31 * inside an Action it resolves through the apply-time RuntimeContext. The
32 * credentials are provided ONLY around the distilled op (via `auth.authorize`),
33 * never around the name accessor, matching the D1 / KV Local variants. `orDie`
34 * mirrors the native binding, whose client methods surface transport failures
35 * as defects.
36 *
37 * Two methods have no Cloudflare HTTP equivalent and `Effect.die`:
38 * - `raw` — there is no HTTP-backed `runtime.Vectorize` object to hand back.
39 * - `queryById` — the HTTP query endpoint only accepts a raw vector, not an id.
40 */
41 export const makeHttpSearchIndexClient = (
42 auth: SearchIndexAuth,
43 indexName: Effect.Effect<string>,
44 ): SearchIndexClient => {
45 const { accountId } = auth;
46 const local = <A, E>(
47 fn: (name: string) => Effect.Effect<A, E, Credentials | HttpClient.HttpClient>,
48 ): Effect.Effect<A> =>
49 Effect.flatMap(indexName, (name) => auth.authorize(fn(name))).pipe(Effect.orDie);
50
51 return {
52 raw: Effect.die(
53 new Error(
54 "SearchIndex over HTTP: `raw` is not available — use a native Worker binding (SearchIndexBinding) for direct access.",
55 ),
56 ),
57 describe: () =>
58 local((name) =>
59 vectorize.getIndexInfo({ accountId, indexName: name }).pipe(Effect.map(toIndexInfo)),
60 ),
61 query: (vector, options) =>
62 local((name) =>
63 vectorize
64 .queryIndex({
65 accountId,
66 indexName: name,
67 vector: Array.from(vector),
68 topK: options?.topK,
69 returnValues: options?.returnValues,
70 returnMetadata: toReturnMetadata(options?.returnMetadata),
71 filter: options?.filter,
72 })
73 .pipe(Effect.map(toMatches)),
74 ),
75 queryById: () =>
76 Effect.die(
77 new Error(
78 "SearchIndex over HTTP: `queryById` is not supported — the HTTP query endpoint only accepts a raw query vector. Fetch the vector with `getByIds` and pass its values to `query`.",
79 ),
80 ),
81 insert: (vectors) =>
82 local((name) =>
83 vectorize
84 .insertIndex({
85 accountId,
86 indexName: name,
87 body: toNdjsonBlob(vectors),
88 })
89 .pipe(Effect.map(toMutation)),
90 ),
91 upsert: (vectors) =>
92 local((name) =>
93 vectorize
94 .upsertIndex({
95 accountId,
96 indexName: name,
97 body: toNdjsonBlob(vectors),
98 })
99 .pipe(Effect.map(toMutation)),
100 ),
101 deleteByIds: (ids) =>
102 local((name) =>
103 vectorize
104 .deleteByIdsIndex({ accountId, indexName: name, ids })
105 .pipe(Effect.map(toMutation)),
106 ),
107 getByIds: (ids) =>
108 local((name) =>
109 vectorize
110 .getByIdsIndex({ accountId, indexName: name, ids })
111 .pipe(Effect.map((result) => (result ?? []) as runtime.VectorizeVector[])),
112 ),
113 } satisfies SearchIndexClient;
114 };
115
116 // ── shape adapters (runtime types <-> distilled HTTP types) ─────────────────
117
118 /**
119 * Serialize vectors to an ndjson Blob — the raw `application/x-ndjson` request
120 * body of the Vectorize v2 insert/upsert endpoints.
121 */
122 const toNdjsonBlob = (vectors: runtime.VectorizeVector[]): Blob => new Blob([toNdjson(vectors)]);
123
124 /** Serialize vectors to ndjson — one JSON vector per line. */
125 const toNdjson = (vectors: runtime.VectorizeVector[]): string =>
126 vectors
127 .map((v) =>
128 JSON.stringify({
129 id: v.id,
130 // A `VectorFloatArray` (Float32Array) would `JSON.stringify` to an
131 // object, not an array — normalize to a plain number array.
132 values: Array.from(v.values),
133 ...(v.namespace !== undefined ? { namespace: v.namespace } : {}),
134 ...(v.metadata !== undefined ? { metadata: v.metadata } : {}),
135 }),
136 )
137 .join("\n");
138
139 const toReturnMetadata = (
140 value: runtime.VectorizeQueryOptions["returnMetadata"],
141 ): "none" | "indexed" | "all" | undefined =>
142 value === undefined ? undefined : typeof value === "boolean" ? (value ? "all" : "none") : value;
143
144 const toMutation = (r: { mutationId?: string | null }): runtime.VectorizeAsyncMutation => ({
145 mutationId: r.mutationId ?? "",
146 });
147
148 const toIndexInfo = (r: vectorize.GetIndexInfoResponse): runtime.VectorizeIndexInfo =>
149 ({
150 vectorCount: r.vectorCount ?? 0,
151 dimensions: r.dimensions ?? 0,
152 processedUpToDatetime: r.processedUpToDatetime ?? undefined,
153 processedUpToMutation: r.processedUpToMutation ?? undefined,
154 }) as unknown as runtime.VectorizeIndexInfo;
155
156 const toMatches = (r: vectorize.QueryIndexResponse): runtime.VectorizeMatches =>
157 ({
158 count: r.count ?? r.matches?.length ?? 0,
159 matches: (r.matches ?? []).map((m) => ({
160 id: m.id ?? "",
161 score: m.score ?? 0,
162 ...(m.values != null ? { values: m.values } : {}),
163 ...(m.namespace != null ? { namespace: m.namespace } : {}),
164 ...(m.metadata != null ? { metadata: m.metadata } : {}),
165 })),
166 }) as unknown as runtime.VectorizeMatches;