@k9o/extension-runtime 1.5.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +2 -2
- package/src/bff-hook-discriminator.ts +3 -2
- package/src/client.ts +19 -1
- package/src/http.ts +75 -6
- package/src/index.ts +21 -0
- package/src/insecure-http.ts +575 -0
- package/src/namespaces/auth-migrations.ts +176 -0
- package/src/namespaces/bff.ts +12 -2
- package/src/namespaces/credentials.ts +8 -0
- package/src/namespaces/files.ts +96 -0
- package/src/namespaces/vectors.ts +108 -9
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.authMigrations — the sign-in migration extension's three calls: register a run, read it, and have the platform
|
|
3
|
+
* create the run's users.
|
|
4
|
+
*
|
|
5
|
+
* Only an installed sign-in migration extension calls these, with its plugin token; the platform refuses any other
|
|
6
|
+
* extension with `K9O_EXTENSION_PERMISSION_DENIED`. The source vendor comes from the extension, never from the caller, and
|
|
7
|
+
* the source account is read from the credential bound to `credentialRole` and pinned to the run. The platform sends back
|
|
8
|
+
* a run without any hash, seed or credential. The extension sends user ids and addresses only; the vendor's password
|
|
9
|
+
* export, the hash parameters, rollback, finalize and end are a project admin's, not an extension's.
|
|
10
|
+
*
|
|
11
|
+
* Refusals reach the caller as the route gave them (`K9O_NOT_FOUND` for a run id that does not exist or belongs to another
|
|
12
|
+
* extension, `K9O_EXTENSION_PERMISSION_DENIED`,
|
|
13
|
+
* `K9O_INVALID_FIELD_VALUE`). A value the route documents a hard limit for is checked here first and refused with
|
|
14
|
+
* `K9O_INVALID_FIELD_VALUE`, with no network call.
|
|
15
|
+
*
|
|
16
|
+
* Gateway routes:
|
|
17
|
+
* POST /@{projectSlug}/auth-migrations body CreateRunBody, 201 with the run
|
|
18
|
+
* GET /@{projectSlug}/auth-migrations/{runId} the run
|
|
19
|
+
* POST /@{projectSlug}/auth-migrations/{runId}/users body { users }, 200 with { users } (one result per user)
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import type { Transport } from "../http.ts";
|
|
23
|
+
import { RuntimeKError } from "../kerror.ts";
|
|
24
|
+
|
|
25
|
+
/** The most users one `createUsers` call takes. */
|
|
26
|
+
export const AUTH_MIGRATIONS_MAX_USERS_PER_CALL = 1000;
|
|
27
|
+
/** The most days unused imported hashes can be kept. */
|
|
28
|
+
export const AUTH_MIGRATIONS_HASH_EXPIRY_MAX_DAYS = 365;
|
|
29
|
+
/** The most days the rollback snapshot can be kept after cutover. */
|
|
30
|
+
export const AUTH_MIGRATIONS_ROLLBACK_RETENTION_MAX_DAYS = 365;
|
|
31
|
+
|
|
32
|
+
export type AuthMigrationSource = "auth0" | "clerk" | "firebase" | "supabase" | "stytch";
|
|
33
|
+
export type AuthMigrationPasswordHandling = "hash_import" | "reset";
|
|
34
|
+
|
|
35
|
+
export type AuthMigrationsCreateRunBody = {
|
|
36
|
+
/** `hash_import` keeps users' passwords (the platform refuses it for Auth0 and Stytch for now); `reset` has them set a new one. */
|
|
37
|
+
passwordHandling: AuthMigrationPasswordHandling;
|
|
38
|
+
/** The manifest credential role bound to the source vendor's API credential: 1 to 64 characters of a-z, 0-9 and `-`. */
|
|
39
|
+
credentialRole: string;
|
|
40
|
+
/** Days until unused imported hashes are deleted, 1 to 365 (default 90). */
|
|
41
|
+
hashExpiresInDays?: number;
|
|
42
|
+
/** Days the rollback snapshot is kept after cutover, 1 to 365 (default 90). */
|
|
43
|
+
rollbackRetentionDays?: number;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** A sign-in migration run. It never carries a hash, a seed or a credential. */
|
|
47
|
+
export type AuthMigrationRun = {
|
|
48
|
+
/** The run's id (`amr_...`). */
|
|
49
|
+
id: string;
|
|
50
|
+
/** The vendor the users come from, set by the installed extension. */
|
|
51
|
+
source: AuthMigrationSource;
|
|
52
|
+
/** The migration extension that registered the run. */
|
|
53
|
+
extensionSlug: string;
|
|
54
|
+
/** The extension's credential role whose bound credential identifies the source account. */
|
|
55
|
+
credentialRole: string;
|
|
56
|
+
passwordHandling: AuthMigrationPasswordHandling;
|
|
57
|
+
/** The source account the run is pinned to, read from the credential when the run was created. */
|
|
58
|
+
sourceAccount: string;
|
|
59
|
+
/** `per_row`: each row's hash is accepted when its format is one the platform verifies. `awaiting_format_ruling`: this source's hashes are not imported yet. */
|
|
60
|
+
hashImport: "per_row" | "awaiting_format_ruling";
|
|
61
|
+
/** Whether authenticator-app seeds carry over from this source. `none`: those users enrol again. */
|
|
62
|
+
totpCarryOver: "none" | "awaiting_format_ruling";
|
|
63
|
+
/** Whether a rollback can restore authenticator-app factors at the source. */
|
|
64
|
+
rollbackRestoresTotp: boolean;
|
|
65
|
+
/** Firebase only: whether the project's hash parameters are entered. */
|
|
66
|
+
hashParametersSet: boolean;
|
|
67
|
+
/** ISO 8601 date-time when unused imported hashes are deleted; those users then reset their passwords. */
|
|
68
|
+
hashExpiresAt: string;
|
|
69
|
+
/** How long the rollback snapshot is kept, counted from cutover, 1 to 365 days. */
|
|
70
|
+
rollbackRetentionDays: number;
|
|
71
|
+
/** When the first secrets upload ran, or null before it. */
|
|
72
|
+
cutoverAt: string | null;
|
|
73
|
+
/** When the rollback snapshot is deleted, or null when there is none. */
|
|
74
|
+
snapshotExpiresAt: string | null;
|
|
75
|
+
/** `held`: a rollback can run. `pin_changed`: the source credential changed, so the snapshot can only be deleted. */
|
|
76
|
+
snapshotState: "none" | "held" | "pin_changed" | "pushed" | "deleted";
|
|
77
|
+
status: "open" | "finalized" | "rolled_back" | "ended";
|
|
78
|
+
createdAt: string;
|
|
79
|
+
updatedAt: string;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
export type AuthMigrationUser = {
|
|
83
|
+
/** The user's id at the source, 1 to 256 characters. */
|
|
84
|
+
sourceId: string;
|
|
85
|
+
/** The user's address, 3 to 254 characters. */
|
|
86
|
+
email: string;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
export type AuthMigrationsCreateUsersOptions = {
|
|
90
|
+
/** 1 to 1000 users. */
|
|
91
|
+
users: AuthMigrationUser[];
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
export type AuthMigrationUserResult = {
|
|
95
|
+
/** The user's id at the source. */
|
|
96
|
+
sourceId: string;
|
|
97
|
+
/** The end user created for it (`eu_...`), or null when refused. */
|
|
98
|
+
endUserId: string | null;
|
|
99
|
+
/** `email_exists`: an end user already has this address; it is never mapped and gets no imported credential. */
|
|
100
|
+
status: "created" | "already_created" | "email_exists";
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
export type AuthMigrationsCreateUsersResult = {
|
|
104
|
+
users: AuthMigrationUserResult[];
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
export type AuthMigrationsNamespace = {
|
|
108
|
+
createRun(body: AuthMigrationsCreateRunBody): Promise<AuthMigrationRun>;
|
|
109
|
+
getRun(runId: string): Promise<AuthMigrationRun>;
|
|
110
|
+
createUsers(runId: string, options: AuthMigrationsCreateUsersOptions): Promise<AuthMigrationsCreateUsersResult>;
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const invalidField = (field: string, message: string, extra: Record<string, unknown> = {}): RuntimeKError =>
|
|
114
|
+
new RuntimeKError("K9O_INVALID_FIELD_VALUE", message, { field, ...extra });
|
|
115
|
+
|
|
116
|
+
function checkDays(field: string, value: unknown, max: number): void {
|
|
117
|
+
if (value === undefined) return;
|
|
118
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > max) {
|
|
119
|
+
throw invalidField(field, `${field} must be a whole number of days from 1 to ${max}`, { max });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function checkRunId(runId: unknown): asserts runId is string {
|
|
124
|
+
if (typeof runId !== "string" || runId.length === 0) throw invalidField("runId", "runId must be a non-empty string");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function makeAuthMigrations(transport: Transport, projectSlug: string): AuthMigrationsNamespace {
|
|
128
|
+
const base = `/@${projectSlug}/auth-migrations`;
|
|
129
|
+
return {
|
|
130
|
+
async createRun(body) {
|
|
131
|
+
const { passwordHandling, credentialRole, hashExpiresInDays, rollbackRetentionDays } = body;
|
|
132
|
+
if (passwordHandling !== "hash_import" && passwordHandling !== "reset") {
|
|
133
|
+
throw invalidField("passwordHandling", 'passwordHandling must be "hash_import" or "reset"');
|
|
134
|
+
}
|
|
135
|
+
if (typeof credentialRole !== "string" || !/^[a-z0-9-]{1,64}$/.test(credentialRole)) {
|
|
136
|
+
throw invalidField("credentialRole", "credentialRole must be 1 to 64 characters of a-z, 0-9 and -");
|
|
137
|
+
}
|
|
138
|
+
checkDays("hashExpiresInDays", hashExpiresInDays, AUTH_MIGRATIONS_HASH_EXPIRY_MAX_DAYS);
|
|
139
|
+
checkDays("rollbackRetentionDays", rollbackRetentionDays, AUTH_MIGRATIONS_ROLLBACK_RETENTION_MAX_DAYS);
|
|
140
|
+
const payload: AuthMigrationsCreateRunBody = { passwordHandling, credentialRole };
|
|
141
|
+
if (hashExpiresInDays !== undefined) payload.hashExpiresInDays = hashExpiresInDays;
|
|
142
|
+
if (rollbackRetentionDays !== undefined) payload.rollbackRetentionDays = rollbackRetentionDays;
|
|
143
|
+
const res = await transport.post<AuthMigrationRun>(base, payload);
|
|
144
|
+
return res.data;
|
|
145
|
+
},
|
|
146
|
+
|
|
147
|
+
async getRun(runId) {
|
|
148
|
+
checkRunId(runId);
|
|
149
|
+
const res = await transport.get<AuthMigrationRun>(`${base}/${encodeURIComponent(runId)}`);
|
|
150
|
+
return res.data;
|
|
151
|
+
},
|
|
152
|
+
|
|
153
|
+
async createUsers(runId, options) {
|
|
154
|
+
checkRunId(runId);
|
|
155
|
+
const users = options.users;
|
|
156
|
+
if (!Array.isArray(users) || users.length < 1) throw invalidField("users", "users must hold at least 1 user");
|
|
157
|
+
if (users.length > AUTH_MIGRATIONS_MAX_USERS_PER_CALL) {
|
|
158
|
+
throw invalidField("users", `users takes at most ${AUTH_MIGRATIONS_MAX_USERS_PER_CALL} users per call; send more in further calls`, {
|
|
159
|
+
max: AUTH_MIGRATIONS_MAX_USERS_PER_CALL,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
users.forEach((u, i) => {
|
|
163
|
+
if (typeof u?.sourceId !== "string" || u.sourceId.length < 1 || u.sourceId.length > 256) {
|
|
164
|
+
throw invalidField(`users[${i}].sourceId`, "sourceId must be 1 to 256 characters");
|
|
165
|
+
}
|
|
166
|
+
if (typeof u.email !== "string" || u.email.length < 3 || u.email.length > 254) {
|
|
167
|
+
throw invalidField(`users[${i}].email`, "email must be 3 to 254 characters");
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
const res = await transport.post<AuthMigrationsCreateUsersResult>(`${base}/${encodeURIComponent(runId)}/users`, {
|
|
171
|
+
users: users.map((u) => ({ sourceId: u.sourceId, email: u.email })),
|
|
172
|
+
});
|
|
173
|
+
return res.data;
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
}
|
package/src/namespaces/bff.ts
CHANGED
|
@@ -57,9 +57,19 @@ export type BffRequest = {
|
|
|
57
57
|
operator?: BffOperator;
|
|
58
58
|
/**
|
|
59
59
|
* Who called when no operator did, set by the gateway: another extension on an `extension` endpoint, or the
|
|
60
|
-
* platform's scheduler on a `schedule` endpoint (`name` is the schedule's, from the manifest)
|
|
60
|
+
* platform's scheduler on a `schedule` endpoint (`name` is the schedule's, from the manifest), the platform's event
|
|
61
|
+
* delivery on an `event` endpoint (`name` is the declared event subscription's), or the subject-erasure process calling
|
|
62
|
+
* the extension's declared erasure hook (`erasure`), the platform on a route declared `auth: "platform"` (`purpose` is `password_range` for a breached-password lookup, `setting_verify` when an admin presses Verify on an install setting that declares `verify`), a project service token, or an end user.
|
|
61
63
|
*/
|
|
62
|
-
caller?:
|
|
64
|
+
caller?:
|
|
65
|
+
| { kind: "extension"; extensionId: string; slug: string }
|
|
66
|
+
| { kind: "schedule"; name: string }
|
|
67
|
+
| { kind: "event"; name: string }
|
|
68
|
+
| { kind: "erasure" }
|
|
69
|
+
| { kind: "platform"; purpose: "password_range" }
|
|
70
|
+
| { kind: "platform"; purpose: "setting_verify" }
|
|
71
|
+
| { kind: "service_token"; tokenId: string; role: string }
|
|
72
|
+
| { kind: "end_user"; endUserId: string; appId: string | null; amr: string[] | null; authTime: number | null };
|
|
63
73
|
/** Where the call chain started, set by the gateway: an operator, or `system` for a scheduled run. */
|
|
64
74
|
origin?: { kind: "operator"; userId: string; role: string; run?: { id: string; step: number } } | { kind: "system" };
|
|
65
75
|
};
|
|
@@ -25,6 +25,13 @@ export type CredentialSendRequest = {
|
|
|
25
25
|
method: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | (string & {});
|
|
26
26
|
headers?: Record<string, string>;
|
|
27
27
|
body?: string | Uint8Array | ArrayBuffer;
|
|
28
|
+
/**
|
|
29
|
+
* A push send only: the `deviceLease` carried by the push frame. The platform inserts the device's token into the
|
|
30
|
+
* request and chooses the host from the device's environment, so the extension never holds either. A role that sends
|
|
31
|
+
* push notifications is refused without it (`K9O_ACCESS_DENIED`, reason `push_lease_required`). The lease is passed
|
|
32
|
+
* on exactly as received.
|
|
33
|
+
*/
|
|
34
|
+
deviceLease?: string;
|
|
28
35
|
} & ({ url: string; path?: never } | { path: string; url?: never });
|
|
29
36
|
|
|
30
37
|
export type CredentialSendResult = {
|
|
@@ -50,6 +57,7 @@ export function makeCredentials(transport: Transport, projectSlug: string, exten
|
|
|
50
57
|
const body: Record<string, unknown> =
|
|
51
58
|
request.path !== undefined ? { method: request.method, path: request.path } : { method: request.method, url: request.url };
|
|
52
59
|
if (request.headers !== undefined) body.headers = request.headers;
|
|
60
|
+
if (request.deviceLease !== undefined) body.deviceLease = request.deviceLease;
|
|
53
61
|
if (request.body !== undefined) {
|
|
54
62
|
if (typeof request.body === "string") body.body = request.body;
|
|
55
63
|
else {
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.files — read the bytes of an object in a project storage bucket.
|
|
3
|
+
*
|
|
4
|
+
* Needs the manifest's `files read` grant on the bucket; nothing else in the manifest changes. The gateway returns at most
|
|
5
|
+
* 8 MiB per read: read a larger object in ranges with `offset` and `length`. Every read is recorded in the project's audit
|
|
6
|
+
* log before any byte is sent, and the read's id (`readId`) is what `vectors.upsert(..., { fromRead })` takes when the
|
|
7
|
+
* rows were derived from these bytes.
|
|
8
|
+
*
|
|
9
|
+
* An extension reads only an object whose data subject the platform recorded at upload; any other object is refused with
|
|
10
|
+
* `K9O_OBJECT_SUBJECT_UNRESOLVED`. Other refusals reach the caller as the route gave them (`K9O_RATE_LIMITED` with
|
|
11
|
+
* `context.retryAfter` when reads come too fast, `K9O_INVALID_FIELD_VALUE` for an offset past the end of the object,
|
|
12
|
+
* `K9O_EXTENSION_PERMISSION_DENIED` without the grant or for a system bucket, a not-found error for a missing object).
|
|
13
|
+
*
|
|
14
|
+
* Gateway route:
|
|
15
|
+
* POST /@{projectSlug}/storage/buckets/{bucket}/objects/content body { path, offset?, length? }, raw bytes back
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { Transport } from "../http.ts";
|
|
19
|
+
import { RuntimeKError } from "../kerror.ts";
|
|
20
|
+
|
|
21
|
+
/** The most bytes one read returns: 8 MiB. */
|
|
22
|
+
export const FILES_READ_MAX_LENGTH = 8 * 1024 * 1024;
|
|
23
|
+
|
|
24
|
+
export type FilesReadOptions = {
|
|
25
|
+
/** The object's path in the bucket, 1 to 1024 characters. */
|
|
26
|
+
path: string;
|
|
27
|
+
/** The first byte to return, from 0 (default 0). */
|
|
28
|
+
offset?: number;
|
|
29
|
+
/** How many bytes to return, 1 to 8388608 (default: to the end of the object, at most 8 MiB). */
|
|
30
|
+
length?: number;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export type FilesReadResult = {
|
|
34
|
+
/** The bytes from `offset`, at most `length` of them. */
|
|
35
|
+
bytes: Uint8Array;
|
|
36
|
+
/** The id of this read's audit event (`evt_...`); pass it as `fromRead` when writing vectors derived from these bytes. */
|
|
37
|
+
readId: string;
|
|
38
|
+
/** The object's whole size in bytes, not the size of this range; `null` when the platform could not tell. */
|
|
39
|
+
size: number | null;
|
|
40
|
+
/** The object's content type as uploaded, or an empty string when none was recorded. */
|
|
41
|
+
contentType: string;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export type FilesNamespace = {
|
|
45
|
+
read(bucket: string, options: FilesReadOptions): Promise<FilesReadResult>;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const invalidField = (field: string, message: string, extra: Record<string, unknown> = {}): RuntimeKError =>
|
|
49
|
+
new RuntimeKError("K9O_INVALID_FIELD_VALUE", message, { field, ...extra });
|
|
50
|
+
|
|
51
|
+
const invalidResponse = (header: string, message: string): RuntimeKError =>
|
|
52
|
+
new RuntimeKError("K9O_INVALID_RESPONSE", message, { header });
|
|
53
|
+
|
|
54
|
+
export function makeFiles(transport: Transport, projectSlug: string): FilesNamespace {
|
|
55
|
+
return {
|
|
56
|
+
async read(bucket, options) {
|
|
57
|
+
if (typeof bucket !== "string" || bucket.length === 0) throw invalidField("bucket", "bucket must be a non-empty string");
|
|
58
|
+
const { path, offset, length } = options;
|
|
59
|
+
if (typeof path !== "string" || path.length === 0) throw invalidField("path", "path must be a non-empty string");
|
|
60
|
+
if (offset !== undefined && (!Number.isInteger(offset) || offset < 0)) {
|
|
61
|
+
throw invalidField("offset", "offset must be a whole number of bytes, 0 or more");
|
|
62
|
+
}
|
|
63
|
+
if (length !== undefined) {
|
|
64
|
+
if (!Number.isInteger(length) || length < 1) {
|
|
65
|
+
throw invalidField("length", "length must be a whole number of bytes, 1 or more");
|
|
66
|
+
}
|
|
67
|
+
if (length > FILES_READ_MAX_LENGTH) {
|
|
68
|
+
throw invalidField("length", `length is at most ${FILES_READ_MAX_LENGTH} bytes; read a larger object in ranges`, {
|
|
69
|
+
max: FILES_READ_MAX_LENGTH,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const body: { path: string; offset?: number; length?: number } = { path };
|
|
74
|
+
if (offset !== undefined) body.offset = offset;
|
|
75
|
+
if (length !== undefined) body.length = length;
|
|
76
|
+
const res = await transport.postBytes(
|
|
77
|
+
`/@${projectSlug}/storage/buckets/${encodeURIComponent(bucket)}/objects/content`,
|
|
78
|
+
body,
|
|
79
|
+
);
|
|
80
|
+
const readId = res.headers.get("K9O-Read-Id");
|
|
81
|
+
if (readId === null || readId.length === 0) {
|
|
82
|
+
throw invalidResponse("K9O-Read-Id", "The object read came back without a K9O-Read-Id header");
|
|
83
|
+
}
|
|
84
|
+
const sizeHeader = res.headers.get("K9O-Object-Size");
|
|
85
|
+
if (sizeHeader === null || (sizeHeader !== "" && !/^\d+$/.test(sizeHeader))) {
|
|
86
|
+
throw invalidResponse("K9O-Object-Size", "The object read came back without a usable K9O-Object-Size header");
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
bytes: res.bytes,
|
|
90
|
+
readId,
|
|
91
|
+
size: sizeHeader === "" ? null : Number(sizeHeader),
|
|
92
|
+
contentType: res.headers.get("K9O-Object-Content-Type") ?? "",
|
|
93
|
+
};
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
@@ -21,14 +21,20 @@
|
|
|
21
21
|
* broader gateway surface and is not part of this namespace — `vectors.search`
|
|
22
22
|
* is the derived-collection retrieval sibling of `vectors.upsert`.
|
|
23
23
|
*
|
|
24
|
+
* `fromRead` (upsert option) — rows derived from one `files.read` carry that read's `readId` instead of `subjectIds`;
|
|
25
|
+
* see `VectorsUpsertOptions`.
|
|
26
|
+
*
|
|
24
27
|
* Gateway routes:
|
|
25
28
|
* POST /@{projectSlug}/vectors/{collection}/upsert
|
|
26
29
|
* POST /@{projectSlug}/vectors/{collection}/search
|
|
30
|
+
* POST /@{projectSlug}/vectors/{collection}/delete
|
|
31
|
+
* POST /@{projectSlug}/vectors/{collection}/hashes
|
|
27
32
|
*
|
|
28
33
|
* Primary consumer: context-retrieval extensions (vector ingestion + retrieval).
|
|
29
34
|
*/
|
|
30
35
|
|
|
31
36
|
import type { Transport } from "../http.ts";
|
|
37
|
+
import { RuntimeKError } from "../kerror.ts";
|
|
32
38
|
|
|
33
39
|
export type VectorRow = {
|
|
34
40
|
/** Optional caller-assigned stable ID for idempotent upsert. */
|
|
@@ -42,8 +48,11 @@ export type VectorRow = {
|
|
|
42
48
|
/** Zero-indexed chunk position within the document. */
|
|
43
49
|
chunkIndex: number;
|
|
44
50
|
};
|
|
45
|
-
/**
|
|
46
|
-
|
|
51
|
+
/**
|
|
52
|
+
* The chunk's source text. The platform computes a keyed hash of it (`rows[].contentHash` on the upsert result), so send it
|
|
53
|
+
* when you want to skip re-embedding unchanged chunks. There is no `contentHash` to send: the gateway no longer takes one.
|
|
54
|
+
*/
|
|
55
|
+
text?: string;
|
|
47
56
|
/**
|
|
48
57
|
* The row's owning subject — write-contract v1
|
|
49
58
|
* grammar. Cardinality-1: exactly `[ownerColumnValue]`, format
|
|
@@ -65,6 +74,13 @@ export type VectorRow = {
|
|
|
65
74
|
export type VectorsUpsertResult = {
|
|
66
75
|
/** Number of rows written (inserted or replaced). */
|
|
67
76
|
upserted: number;
|
|
77
|
+
/**
|
|
78
|
+
* One entry per row sent, in the order sent: the chunk's id (the one sent, or the `rec_...` id the platform minted) and its
|
|
79
|
+
* keyed content hash. The hash is 64 lowercase hex, the same for the same `text` in the same collection, and not comparable
|
|
80
|
+
* across collections or projects. It is `null` for a row sent without `text`. Compare it with the hash you stored to skip
|
|
81
|
+
* re-embedding an unchanged chunk.
|
|
82
|
+
*/
|
|
83
|
+
rows: { id: string; contentHash: string | null }[];
|
|
68
84
|
/** Collection slug the rows were written to. */
|
|
69
85
|
collection: string;
|
|
70
86
|
};
|
|
@@ -91,7 +107,8 @@ export type VectorSearchResultRow = {
|
|
|
91
107
|
/** Monotone similarity — higher is closer, for all three metrics. */
|
|
92
108
|
score: number;
|
|
93
109
|
_source: { handle: string; chunkIndex: number; [k: string]: unknown };
|
|
94
|
-
|
|
110
|
+
/** The keyed content hash the platform computed from the row's `text` at upsert: 64 lowercase hex, or `null` when no `text` was sent. */
|
|
111
|
+
contentHash?: string | null;
|
|
95
112
|
/** Convenience field: `= metadata.model ?? null` (no first-class model column). */
|
|
96
113
|
model?: string | null;
|
|
97
114
|
/** Convenience field: `= _source.chunkIndex ?? null` — a chunk *index*, not chunk text. */
|
|
@@ -104,15 +121,66 @@ export type VectorSearchResult = {
|
|
|
104
121
|
collection: string;
|
|
105
122
|
};
|
|
106
123
|
|
|
124
|
+
export type VectorsDeleteQuery = {
|
|
125
|
+
/**
|
|
126
|
+
* Equality filters. At least one `metadata.<key>` equality is required
|
|
127
|
+
* (a call without one is refused with 400 `K9O_INVALID_FIELD_VALUE`,
|
|
128
|
+
* `filter_required` or `metadata_equality_required`). You can narrow
|
|
129
|
+
* further with `source.handle`, `id` or `contentHash`.
|
|
130
|
+
*/
|
|
131
|
+
filters: Record<string, string | number | boolean>;
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
export type VectorsDeleteResult = {
|
|
135
|
+
/** Number of rows removed. */
|
|
136
|
+
deleted: number;
|
|
137
|
+
/** Collection slug the rows were removed from. */
|
|
138
|
+
collection: string;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
export type VectorsHashesQuery = {
|
|
142
|
+
/** The `_source.handle` the rows were upserted with, matched exactly (no prefix or pattern). */
|
|
143
|
+
sourceHandle: string;
|
|
144
|
+
/** The `nextCursor` of the previous page, for the same collection and `sourceHandle`. Opaque: a cursor from another collection or handle is refused. */
|
|
145
|
+
cursor?: string;
|
|
146
|
+
/** The most chunks one page returns, 1..1000. Default 1000. */
|
|
147
|
+
limit?: number;
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
export type VectorsHashesResult = {
|
|
151
|
+
/** The source's chunks the caller can read: id and keyed content hash only, no text, metadata or vectors. `contentHash` is `null` for a row stored without `text`. */
|
|
152
|
+
rows: { id: string; contentHash: string | null }[];
|
|
153
|
+
/** Send as `cursor` for the next page; `null` on the last page. */
|
|
154
|
+
nextCursor: string | null;
|
|
155
|
+
collection: string;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
export type VectorsUpsertOptions = {
|
|
159
|
+
/**
|
|
160
|
+
* The `readId` of the `files.read` these rows were derived from (`evt_...`). The platform then sets every row's subject
|
|
161
|
+
* from that read, so no row may carry `subjectIds`: the call is refused before any request when one does. The read must be
|
|
162
|
+
* at most one hour old and made by this extension install; one read id may serve several upserts about the same object.
|
|
163
|
+
*/
|
|
164
|
+
fromRead?: string;
|
|
165
|
+
};
|
|
166
|
+
|
|
107
167
|
export type VectorsNamespace = {
|
|
108
|
-
upsert(collection: string, rows: VectorRow[]): Promise<VectorsUpsertResult>;
|
|
168
|
+
upsert(collection: string, rows: VectorRow[], options?: VectorsUpsertOptions): Promise<VectorsUpsertResult>;
|
|
109
169
|
search(collection: string, query: VectorSearchQuery): Promise<VectorSearchResult>;
|
|
170
|
+
/** Deletes the rows matching `filters`. Needs the manifest's `vectors write` grant on the collection. */
|
|
171
|
+
delete(collection: string, query: VectorsDeleteQuery): Promise<VectorsDeleteResult>;
|
|
172
|
+
/**
|
|
173
|
+
* The content hashes of one source's chunks, so a re-ingest can skip chunks whose text is unchanged (compare each `contentHash` with the
|
|
174
|
+
* one `upsert` returned). The same grant and caller rules as `search`. A handle with no chunks the caller can see, and an unknown handle,
|
|
175
|
+
* answer the same empty page. Page with `nextCursor` until it is `null`.
|
|
176
|
+
*/
|
|
177
|
+
hashes(collection: string, query: VectorsHashesQuery): Promise<VectorsHashesResult>;
|
|
110
178
|
};
|
|
111
179
|
|
|
112
|
-
function assertOwnCollection(verb: "upsert" | "search", collection: string): void {
|
|
180
|
+
function assertOwnCollection(verb: "upsert" | "search" | "delete" | "hashes", collection: string): void {
|
|
113
181
|
if (!collection.startsWith("_")) {
|
|
114
182
|
throw new Error(
|
|
115
|
-
`K9O_VECTORS_COLLECTION_GUARD: vectors.${verb} may only ${verb === "
|
|
183
|
+
`K9O_VECTORS_COLLECTION_GUARD: vectors.${verb} may only ${verb === "search" || verb === "hashes" ? "read" : verb === "delete" ? "delete from" : "write to"} ` +
|
|
116
184
|
`extension-owned derived collections (must start with '_'); ` +
|
|
117
185
|
`got '${collection}'.`,
|
|
118
186
|
);
|
|
@@ -124,13 +192,28 @@ export function makeVectors(
|
|
|
124
192
|
projectSlug: string,
|
|
125
193
|
): VectorsNamespace {
|
|
126
194
|
return {
|
|
127
|
-
async upsert(collection, rows) {
|
|
195
|
+
async upsert(collection, rows, options) {
|
|
128
196
|
assertOwnCollection("upsert", collection);
|
|
197
|
+
const fromRead = options?.fromRead;
|
|
198
|
+
if (fromRead !== undefined) {
|
|
199
|
+
if (typeof fromRead !== "string" || !fromRead.startsWith("evt_") || fromRead.length <= 4) {
|
|
200
|
+
throw new RuntimeKError("K9O_INVALID_FIELD_VALUE", "fromRead must be the readId of a files.read (it starts with 'evt_')", {
|
|
201
|
+
field: "fromRead",
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
if (rows.some((row) => row.subjectIds !== undefined)) {
|
|
205
|
+
throw new RuntimeKError(
|
|
206
|
+
"K9O_INVALID_FIELD_VALUE",
|
|
207
|
+
"Send fromRead or subjectIds, not both: fromRead sets the subject from the read",
|
|
208
|
+
{ field: "subjectIds", reason: "from_read_with_subject_ids" },
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
129
212
|
const res = await transport.post<VectorsUpsertResult>(
|
|
130
213
|
`/@${projectSlug}/vectors/${collection}/upsert`,
|
|
131
|
-
{ rows },
|
|
214
|
+
fromRead === undefined ? { rows } : { rows, fromRead },
|
|
132
215
|
);
|
|
133
|
-
return { upserted: res.data.upserted, collection: res.data.collection };
|
|
216
|
+
return { upserted: res.data.upserted, rows: res.data.rows, collection: res.data.collection };
|
|
134
217
|
},
|
|
135
218
|
async search(collection, query) {
|
|
136
219
|
assertOwnCollection("search", collection);
|
|
@@ -140,5 +223,21 @@ export function makeVectors(
|
|
|
140
223
|
);
|
|
141
224
|
return { results: res.data.results, collection: res.data.collection };
|
|
142
225
|
},
|
|
226
|
+
async delete(collection, query) {
|
|
227
|
+
assertOwnCollection("delete", collection);
|
|
228
|
+
const res = await transport.post<VectorsDeleteResult>(
|
|
229
|
+
`/@${projectSlug}/vectors/${collection}/delete`,
|
|
230
|
+
query,
|
|
231
|
+
);
|
|
232
|
+
return { deleted: res.data.deleted, collection: res.data.collection };
|
|
233
|
+
},
|
|
234
|
+
async hashes(collection, query) {
|
|
235
|
+
assertOwnCollection("hashes", collection);
|
|
236
|
+
if (typeof query.sourceHandle !== "string" || query.sourceHandle.length === 0) {
|
|
237
|
+
throw new RuntimeKError("K9O_INVALID_FIELD_VALUE", "sourceHandle is the _source.handle the rows were upserted with", { field: "sourceHandle" });
|
|
238
|
+
}
|
|
239
|
+
const res = await transport.post<VectorsHashesResult>(`/@${projectSlug}/vectors/${collection}/hashes`, query);
|
|
240
|
+
return { rows: res.data.rows, nextCursor: res.data.nextCursor, collection: res.data.collection };
|
|
241
|
+
},
|
|
143
242
|
};
|
|
144
243
|
}
|