@k9o/extension-runtime 0.0.0-stage → 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/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +166 -2
- package/package.json +30 -4
- package/src/base64.ts +11 -0
- package/src/bff-hook-discriminator.ts +72 -0
- package/src/client.ts +148 -0
- package/src/context.ts +70 -0
- package/src/dispatch-context.ts +58 -0
- package/src/guards.ts +35 -0
- package/src/http.ts +233 -0
- package/src/index.ts +163 -0
- package/src/insecure-http.ts +575 -0
- package/src/invoke-server.ts +150 -0
- package/src/kerror.ts +45 -0
- package/src/namespaces/ai-agent-runtime.ts +170 -0
- package/src/namespaces/ai.ts +56 -0
- package/src/namespaces/analytics.ts +122 -0
- package/src/namespaces/attributes.ts +34 -0
- package/src/namespaces/audit.ts +92 -0
- package/src/namespaces/auth-migrations.ts +176 -0
- package/src/namespaces/bff.ts +140 -0
- package/src/namespaces/collections.ts +104 -0
- package/src/namespaces/compliance.ts +48 -0
- package/src/namespaces/credentials.ts +85 -0
- package/src/namespaces/documents.ts +128 -0
- package/src/namespaces/egress.ts +31 -0
- package/src/namespaces/files.ts +96 -0
- package/src/namespaces/functions.ts +91 -0
- package/src/namespaces/hooks.ts +186 -0
- package/src/namespaces/identity.ts +97 -0
- package/src/namespaces/kibo.ts +60 -0
- package/src/namespaces/policy.ts +50 -0
- package/src/namespaces/streaming.ts +80 -0
- package/src/namespaces/tables.ts +166 -0
- package/src/namespaces/vectors.ts +243 -0
- package/src/namespaces/webhook-ingress.ts +98 -0
- package/src/namespaces/workflow.ts +65 -0
- package/src/types.ts +143 -0
- package/src/warden.ts +320 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.kibo — encrypt/decrypt data under the project's own key.
|
|
3
|
+
*
|
|
4
|
+
* The gateway resolves the key from the project alone; the extension never names or
|
|
5
|
+
* receives a key. `keyId` is an OPAQUE CONTEXT LABEL chosen by the caller (for example
|
|
6
|
+
* `"r2-secret-access-key"`): it selects no key, it is bound into the ciphertext together
|
|
7
|
+
* with the project and the calling extension, and `decrypt` succeeds only with the same
|
|
8
|
+
* label from the same extension. Persist the returned `{ ciphertext, keyId }` and pass both
|
|
9
|
+
* back to `decrypt`.
|
|
10
|
+
*
|
|
11
|
+
* Wire: `POST /@<project>/kibo/encrypt` `{ plaintext, label }` → `{ ciphertext, label }`;
|
|
12
|
+
* `POST /@<project>/kibo/decrypt` `{ ciphertext, label }` → `{ plaintext }`. `plaintext` and
|
|
13
|
+
* `ciphertext` are standard base64; this namespace encodes and decodes the plaintext as UTF-8
|
|
14
|
+
* text. The wire field is named `label` (not `keyId`) so it cannot be read as a key selector;
|
|
15
|
+
* this API keeps `keyId` for callers that already persist it.
|
|
16
|
+
*
|
|
17
|
+
* Requires the `kibo` `encrypt` / `decrypt` manifest permission. There is no key-rotation
|
|
18
|
+
* call: a new context label is simply a new context, and key rotation is a platform concern.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { base64ToBytes, bytesToBase64 } from "../base64.ts";
|
|
22
|
+
import type { Transport } from "../http.ts";
|
|
23
|
+
import type { ApiResponse, KiboDecryptResult, KiboEncryptResult } from "../types.ts";
|
|
24
|
+
|
|
25
|
+
export type KiboNamespace = {
|
|
26
|
+
encrypt(data: string, keyId: string): Promise<ApiResponse<KiboEncryptResult>>;
|
|
27
|
+
decrypt(ciphertext: string, keyId: string): Promise<ApiResponse<KiboDecryptResult>>;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** The label grammar the gateway enforces; checked here so a bad label fails before a network call. */
|
|
31
|
+
const LABEL_RE = /^[A-Za-z0-9._:/-]{1,128}$/;
|
|
32
|
+
|
|
33
|
+
function assertLabel(keyId: string): void {
|
|
34
|
+
if (!LABEL_RE.test(keyId)) {
|
|
35
|
+
throw new TypeError("k9o.kibo keyId is a context label: 1-128 characters from A-Z a-z 0-9 . _ : / -");
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function makeKibo(transport: Transport, projectSlug: string): KiboNamespace {
|
|
40
|
+
const base = `/@${projectSlug}/kibo`;
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
async encrypt(data, keyId) {
|
|
44
|
+
assertLabel(keyId);
|
|
45
|
+
const res = await transport.post<{ ciphertext: string; label: string }>(`${base}/encrypt`, {
|
|
46
|
+
plaintext: bytesToBase64(new TextEncoder().encode(data)),
|
|
47
|
+
label: keyId,
|
|
48
|
+
});
|
|
49
|
+
return { ...res, data: { ciphertext: res.data.ciphertext, keyId: res.data.label } };
|
|
50
|
+
},
|
|
51
|
+
|
|
52
|
+
async decrypt(ciphertext, keyId) {
|
|
53
|
+
assertLabel(keyId);
|
|
54
|
+
const res = await transport.post<{ plaintext: string }>(`${base}/decrypt`, { ciphertext, label: keyId });
|
|
55
|
+
// fatal: a plaintext that is not valid UTF-8 throws instead of being silently mangled.
|
|
56
|
+
const plaintext = new TextDecoder("utf-8", { fatal: true }).decode(base64ToBytes(res.data.plaintext));
|
|
57
|
+
return { ...res, data: { plaintext } };
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.policy — Maker-Checker policy evaluation
|
|
3
|
+
*
|
|
4
|
+
* Returns a discriminated PolicyResult:
|
|
5
|
+
* { pending: false, allowed: boolean } — synchronous decision (HTTP 200)
|
|
6
|
+
* { pending: true, pendingId, estimatedResolutionAt } — queued for human
|
|
7
|
+
* approval (HTTP 202); extension should surface the Lookout PendingBadge
|
|
8
|
+
* pattern and retry once approved.
|
|
9
|
+
*
|
|
10
|
+
* EXTENSION_PERMISSION_DENIED (403) is thrown by RuntimeKError if the
|
|
11
|
+
* calling extension's token lacks authority to evaluate the named policy.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { Transport } from "../http.ts";
|
|
15
|
+
import type { PolicyResult } from "../types.ts";
|
|
16
|
+
|
|
17
|
+
type PolicyEvalResponseData = {
|
|
18
|
+
allowed?: boolean;
|
|
19
|
+
pendingId?: string;
|
|
20
|
+
estimatedResolutionAt?: string | null;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export type PolicyNamespace = {
|
|
24
|
+
evaluate(
|
|
25
|
+
policyId: string,
|
|
26
|
+
context: Record<string, unknown>,
|
|
27
|
+
): Promise<PolicyResult>;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export function makePolicy(
|
|
31
|
+
transport: Transport,
|
|
32
|
+
projectSlug: string,
|
|
33
|
+
): PolicyNamespace {
|
|
34
|
+
return {
|
|
35
|
+
async evaluate(policyId, context) {
|
|
36
|
+
const res = await transport.post<PolicyEvalResponseData>(
|
|
37
|
+
`/@${projectSlug}/policies/${policyId}/evaluate`,
|
|
38
|
+
{ context },
|
|
39
|
+
);
|
|
40
|
+
if (res.data.pendingId !== undefined) {
|
|
41
|
+
return {
|
|
42
|
+
pending: true,
|
|
43
|
+
pendingId: res.data.pendingId,
|
|
44
|
+
estimatedResolutionAt: res.data.estimatedResolutionAt ?? null,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
return { pending: false, allowed: res.data.allowed ?? false };
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.streaming — async fanout subscriptions via the canonical StreamingTransport
|
|
3
|
+
* interface.
|
|
4
|
+
*
|
|
5
|
+
* Extensions subscribe to source-collection mutations, webhook events, or
|
|
6
|
+
* AI-agent state changes via `client.streaming.subscribe<T>(channel, opts?)`.
|
|
7
|
+
* Channel naming convention: `<extensionSlug>:<collection>:<event>`
|
|
8
|
+
* (e.g., `cairn:orders:mutated`, `lookout:invoices:created`).
|
|
9
|
+
*
|
|
10
|
+
* **Production transport is the platform gateway territory** — plugin-token-
|
|
11
|
+
* authenticated subscribe over WebSocket/SSE; capability-profile-bounded
|
|
12
|
+
* the platform ships the substrate; the SDK exposes the consumer surface.
|
|
13
|
+
*
|
|
14
|
+
* **Dev/test injection:** authors pass a transport instance via
|
|
15
|
+
* `createExtensionClient({ streamingTransport })`. For local testing, use
|
|
16
|
+
* `createStubStreamingTransport({ channels })` from `@k9o/extension-platform`
|
|
17
|
+
* — it returns deterministic async iterables. When no transport is injected,
|
|
18
|
+
* `client.streaming` returns a placeholder that throws on `subscribe` /
|
|
19
|
+
* `publish` with a descriptive configuration error; `unsubscribe` is
|
|
20
|
+
* no-op-tolerant (matches this package idempotency contract).
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* `StreamingTransport` + `SubscribeOptions` shapes are kept structurally
|
|
25
|
+
* equivalent to the canonical interface in `@k9o/extension-platform`'s
|
|
26
|
+
* `streaming-transport.ts`. We re-author them locally (rather than importing)
|
|
27
|
+
* so `@k9o/extension-runtime` stays runtime-dep-free — partners installing the SDK
|
|
28
|
+
* shouldn't have to pull in the platform package (which has Postgres etc.
|
|
29
|
+
* server-side dependencies). The structural equivalence means a
|
|
30
|
+
* `createStubStreamingTransport()` from this package is fully assignable to
|
|
31
|
+
* `StreamingNamespace` at the SDK boundary.
|
|
32
|
+
*
|
|
33
|
+
* Drift risk: low — 3-method interface; both surfaces are reviewed in lockstep.
|
|
34
|
+
* Discipline: any shape change to this package's StreamingTransport must mirror here.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
export type SubscribeOptions = {
|
|
38
|
+
/** Server-side filter applied at the gateway. JSON-serialisable. */
|
|
39
|
+
filter?: Readonly<Record<string, unknown>>;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export type StreamingTransport = {
|
|
43
|
+
subscribe: <T>(channel: string, opts?: SubscribeOptions) => AsyncIterable<T>;
|
|
44
|
+
publish: <T>(channel: string, message: T) => Promise<void>;
|
|
45
|
+
unsubscribe: (channel: string) => Promise<void>;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export type StreamingNamespace = StreamingTransport;
|
|
49
|
+
|
|
50
|
+
const NOT_CONFIGURED_MESSAGE =
|
|
51
|
+
"k9o.streaming: no transport configured. Inject via createExtensionClient({ streamingTransport }) " +
|
|
52
|
+
"or use createStubStreamingTransport() from @k9o/extension-platform for dev/test.";
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Returns the injected `StreamingTransport` if provided, otherwise a
|
|
56
|
+
* not-configured placeholder. The placeholder lets `client.streaming` stay
|
|
57
|
+
* always-defined (no narrowing required on consumers) while surfacing a
|
|
58
|
+
* clear error message at call-time if the transport is missing.
|
|
59
|
+
*
|
|
60
|
+
* `unsubscribe` on the placeholder is a tolerant no-op — extensions cleaning
|
|
61
|
+
* up subscriptions in finally-blocks shouldn't have to special-case the
|
|
62
|
+
* "never subscribed" path.
|
|
63
|
+
*/
|
|
64
|
+
export function makeStreaming(
|
|
65
|
+
transport?: StreamingTransport,
|
|
66
|
+
): StreamingNamespace {
|
|
67
|
+
if (transport) return transport;
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
subscribe: () => {
|
|
71
|
+
throw new Error(NOT_CONFIGURED_MESSAGE);
|
|
72
|
+
},
|
|
73
|
+
publish: async () => {
|
|
74
|
+
throw new Error(NOT_CONFIGURED_MESSAGE);
|
|
75
|
+
},
|
|
76
|
+
unsubscribe: async () => {
|
|
77
|
+
// Tolerant no-op — see header comment.
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.tables — extension-owned schema row access.
|
|
3
|
+
*
|
|
4
|
+
* Extensions that declare `schema.tables` in their manifest get partner-owned
|
|
5
|
+
* SQL tables with explicit migrations. Runtime access is row-oriented
|
|
6
|
+
* (`insert` / `upsert` / `query` / `update` / `delete`), NOT document-oriented like `k9o.documents`.
|
|
7
|
+
*
|
|
8
|
+
* Gateway route: `POST /@{projectSlug}/extensions/{slug}/tables/{tableName}/{op}`, with
|
|
9
|
+
* `op` one of `query | insert | upsert | update | delete`. The request and response shapes below
|
|
10
|
+
* are the gateway's own: `values`, `set`, `where` conditions, `conflictTarget`, `rows`, `rowCount`, `cursor`.
|
|
11
|
+
*
|
|
12
|
+
* Consumed by Long Tail Pattern B connectors (e.g., `k9o-gitlab` materialising
|
|
13
|
+
* `gitlab_mrs` / `gitlab_pipelines` rows from webhook events; `k9o-asana`,
|
|
14
|
+
* `k9o-vercel`, GDPR SAR, HIPAA Audit Exporter follow the same pattern).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { Transport } from "../http.ts";
|
|
18
|
+
|
|
19
|
+
export type TableRow = Record<string, unknown>;
|
|
20
|
+
|
|
21
|
+
/** Comparison operators the gateway accepts on extension tables. */
|
|
22
|
+
export type TableFilterOp = "eq" | "neq" | "gt" | "gte" | "lt" | "lte" | "in" | "like";
|
|
23
|
+
|
|
24
|
+
export type TableCondition = { field: string; op: TableFilterOp; value: unknown };
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Which rows to match. Either a list of conditions, or a plain object of column values.
|
|
28
|
+
* A plain object matches rows where every column is equal to the given value; an array value
|
|
29
|
+
* means "is one of those values".
|
|
30
|
+
*/
|
|
31
|
+
export type TableFilter = TableCondition[] | Record<string, unknown>;
|
|
32
|
+
|
|
33
|
+
export type TableOrder = { field: string; dir: "asc" | "desc" };
|
|
34
|
+
|
|
35
|
+
export type TablesUpsertOptions = {
|
|
36
|
+
/** Columns of a UNIQUE or PRIMARY KEY constraint; a matching row is updated instead of inserted. */
|
|
37
|
+
conflictTarget: string[];
|
|
38
|
+
/**
|
|
39
|
+
* Columns to update on conflict. Default: every inserted column that is not in `conflictTarget`. `[]` updates
|
|
40
|
+
* nothing: a matching row is left as it is and is not returned, so `rows` holds only the rows inserted.
|
|
41
|
+
*/
|
|
42
|
+
update?: string[];
|
|
43
|
+
/**
|
|
44
|
+
* Column → integer step, added in the same statement (`col = col + n`; NULL counts as 0). On an insert the column
|
|
45
|
+
* starts at n. Integer and numeric columns only, |n| ≤ 2147483647; a column named here may not also be in the values,
|
|
46
|
+
* `update` or `conflictTarget`.
|
|
47
|
+
*/
|
|
48
|
+
increment?: Record<string, number>;
|
|
49
|
+
/** Column → floor for an incremented column. A result below it is refused (409, `floor_reached`) and nothing is written. */
|
|
50
|
+
min?: Record<string, number>;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export type TablesUpdateOptions = {
|
|
54
|
+
/** Column → integer step, as on `upsert`. A column named here may not also be in `set`. */
|
|
55
|
+
increment?: Record<string, number>;
|
|
56
|
+
/** Column → floor for an incremented column, as on `upsert`. */
|
|
57
|
+
min?: Record<string, number>;
|
|
58
|
+
/** The exact number of rows the update must touch; any other count is refused (409, `guard_failed`) and nothing is written. */
|
|
59
|
+
expectRows?: number;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export type TablesQueryOptions = {
|
|
63
|
+
/** Columns to return. Default: all. */
|
|
64
|
+
select?: string[];
|
|
65
|
+
order?: TableOrder[];
|
|
66
|
+
/** Row cap; the gateway applies a default of 100 and a ceiling of 1000. */
|
|
67
|
+
limit?: number;
|
|
68
|
+
/** The `cursor` of the previous page. */
|
|
69
|
+
cursor?: string;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export type TablesWriteResult = { rows: TableRow[]; rowCount: number };
|
|
73
|
+
|
|
74
|
+
export type TablesNamespace = {
|
|
75
|
+
insert(tableName: string, values: TableRow | TableRow[]): Promise<TablesWriteResult>;
|
|
76
|
+
upsert(
|
|
77
|
+
tableName: string,
|
|
78
|
+
values: TableRow | TableRow[],
|
|
79
|
+
opts: TablesUpsertOptions,
|
|
80
|
+
): Promise<TablesWriteResult>;
|
|
81
|
+
query(
|
|
82
|
+
tableName: string,
|
|
83
|
+
filter?: TableFilter,
|
|
84
|
+
opts?: TablesQueryOptions,
|
|
85
|
+
): Promise<{ rows: TableRow[]; cursor: string | null }>;
|
|
86
|
+
/** `set` may be `{}` when `opts.increment` names what changes. */
|
|
87
|
+
update(tableName: string, set: TableRow, filter: TableFilter, opts?: TablesUpdateOptions): Promise<TablesWriteResult>;
|
|
88
|
+
delete(tableName: string, filter: TableFilter): Promise<TablesWriteResult>;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/** Turn a plain object into the gateway's condition list. A condition list passes through unchanged. */
|
|
92
|
+
export function toConditions(filter: TableFilter | undefined): TableCondition[] {
|
|
93
|
+
if (filter === undefined) return [];
|
|
94
|
+
if (Array.isArray(filter)) return filter;
|
|
95
|
+
return Object.entries(filter).map(([field, value]) => ({
|
|
96
|
+
field,
|
|
97
|
+
op: Array.isArray(value) ? "in" : "eq",
|
|
98
|
+
value,
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function requireConditions(op: string, filter: TableFilter): TableCondition[] {
|
|
103
|
+
const where = toConditions(filter);
|
|
104
|
+
if (where.length === 0) {
|
|
105
|
+
throw new Error(`tables.${op} needs at least one condition; the gateway refuses an unscoped ${op}.`);
|
|
106
|
+
}
|
|
107
|
+
return where;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function makeTables(
|
|
111
|
+
transport: Transport,
|
|
112
|
+
projectSlug: string,
|
|
113
|
+
extensionSlug: string,
|
|
114
|
+
): TablesNamespace {
|
|
115
|
+
const url = (tableName: string, op: string) =>
|
|
116
|
+
`/@${projectSlug}/extensions/${extensionSlug}/tables/${tableName}/${op}`;
|
|
117
|
+
|
|
118
|
+
const write = async (tableName: string, op: string, body: object): Promise<TablesWriteResult> => {
|
|
119
|
+
const res = await transport.post<{ rows: TableRow[]; rowCount: number }>(url(tableName, op), body);
|
|
120
|
+
return { rows: res.data.rows, rowCount: res.data.rowCount };
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
insert: (tableName, values) => write(tableName, "insert", { values }),
|
|
125
|
+
|
|
126
|
+
upsert(tableName, values, opts) {
|
|
127
|
+
if (!Array.isArray(opts?.conflictTarget) || opts.conflictTarget.length === 0) {
|
|
128
|
+
throw new Error("tables.upsert needs opts.conflictTarget: the columns of a UNIQUE or PRIMARY KEY constraint.");
|
|
129
|
+
}
|
|
130
|
+
return write(tableName, "upsert", {
|
|
131
|
+
values,
|
|
132
|
+
conflictTarget: opts.conflictTarget,
|
|
133
|
+
...(opts.update !== undefined ? { update: opts.update } : {}),
|
|
134
|
+
...(opts.increment !== undefined ? { increment: opts.increment } : {}),
|
|
135
|
+
...(opts.min !== undefined ? { min: opts.min } : {}),
|
|
136
|
+
});
|
|
137
|
+
},
|
|
138
|
+
|
|
139
|
+
async query(tableName, filter, opts) {
|
|
140
|
+
const res = await transport.post<{ rows: TableRow[]; cursor: string | null }>(url(tableName, "query"), {
|
|
141
|
+
where: toConditions(filter),
|
|
142
|
+
...(opts?.select !== undefined ? { select: opts.select } : {}),
|
|
143
|
+
...(opts?.order !== undefined ? { order: opts.order } : {}),
|
|
144
|
+
...(opts?.limit !== undefined ? { limit: opts.limit } : {}),
|
|
145
|
+
...(opts?.cursor !== undefined ? { cursor: opts.cursor } : {}),
|
|
146
|
+
});
|
|
147
|
+
return { rows: res.data.rows, cursor: res.data.cursor ?? null };
|
|
148
|
+
},
|
|
149
|
+
|
|
150
|
+
update(tableName, set, filter, opts) {
|
|
151
|
+
const hasSet = Object.keys(set).length > 0;
|
|
152
|
+
if (!hasSet && opts?.increment === undefined) {
|
|
153
|
+
throw new Error("tables.update needs columns in `set` or an `increment`; there is nothing to change.");
|
|
154
|
+
}
|
|
155
|
+
return write(tableName, "update", {
|
|
156
|
+
...(hasSet ? { set } : {}),
|
|
157
|
+
where: requireConditions("update", filter),
|
|
158
|
+
...(opts?.increment !== undefined ? { increment: opts.increment } : {}),
|
|
159
|
+
...(opts?.min !== undefined ? { min: opts.min } : {}),
|
|
160
|
+
...(opts?.expectRows !== undefined ? { expectRows: opts.expectRows } : {}),
|
|
161
|
+
});
|
|
162
|
+
},
|
|
163
|
+
|
|
164
|
+
delete: (tableName, filter) => write(tableName, "delete", { where: requireConditions("delete", filter) }),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.vectors — pre-computed vector upsert + KNN search.
|
|
3
|
+
*
|
|
4
|
+
* Batch-upserts pre-computed embedding rows into an extension-owned derived
|
|
5
|
+
* collection, and searches over them by cosine/euclidean/dot similarity. The
|
|
6
|
+
* `collection` argument MUST be the extension's own `_`-prefixed derived
|
|
7
|
+
* collection slug (gateway enforces ownership; opaque substrate access is
|
|
8
|
+
* retired guard). SDK enforces the `_`-prefix rule before
|
|
9
|
+
* making any network call — K9O_VECTORS_COLLECTION_GUARD is thrown
|
|
10
|
+
* synchronously on violation, same message pattern for both verbs.
|
|
11
|
+
*
|
|
12
|
+
* `subjectIds` (write-contract v1) — required
|
|
13
|
+
* IFF the row derives from a subject-bearing source; exempt for a provably
|
|
14
|
+
* `shared` (non-PII) source collection. Cardinality-1, `eu_<base62>` format
|
|
15
|
+
* when present. The gateway itself is schema-optional + handler-enforced
|
|
16
|
+
* (fail-closed: unresolvable/unclassed source = required) so a generic shape
|
|
17
|
+
* error never masks the specific `K9O_VECTOR_SUBJECT_ATTRIBUTION_REQUIRED`
|
|
18
|
+
* code — the SDK type mirrors that conditionality rather than over-requiring.
|
|
19
|
+
*
|
|
20
|
+
* The general `from.vectorSearch` builder is a separate,
|
|
21
|
+
* broader gateway surface and is not part of this namespace — `vectors.search`
|
|
22
|
+
* is the derived-collection retrieval sibling of `vectors.upsert`.
|
|
23
|
+
*
|
|
24
|
+
* `fromRead` (upsert option) — rows derived from one `files.read` carry that read's `readId` instead of `subjectIds`;
|
|
25
|
+
* see `VectorsUpsertOptions`.
|
|
26
|
+
*
|
|
27
|
+
* Gateway routes:
|
|
28
|
+
* POST /@{projectSlug}/vectors/{collection}/upsert
|
|
29
|
+
* POST /@{projectSlug}/vectors/{collection}/search
|
|
30
|
+
* POST /@{projectSlug}/vectors/{collection}/delete
|
|
31
|
+
* POST /@{projectSlug}/vectors/{collection}/hashes
|
|
32
|
+
*
|
|
33
|
+
* Primary consumer: context-retrieval extensions (vector ingestion + retrieval).
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import type { Transport } from "../http.ts";
|
|
37
|
+
import { RuntimeKError } from "../kerror.ts";
|
|
38
|
+
|
|
39
|
+
export type VectorRow = {
|
|
40
|
+
/** Optional caller-assigned stable ID for idempotent upsert. */
|
|
41
|
+
id?: string;
|
|
42
|
+
/** Pre-computed embedding as a float array. Dimension must match the collection schema. */
|
|
43
|
+
vector: number[];
|
|
44
|
+
/** Source provenance — links the vector back to the originating document chunk. */
|
|
45
|
+
_source: {
|
|
46
|
+
/** Document handle (collection-scoped document identifier). */
|
|
47
|
+
handle: string;
|
|
48
|
+
/** Zero-indexed chunk position within the document. */
|
|
49
|
+
chunkIndex: number;
|
|
50
|
+
};
|
|
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;
|
|
56
|
+
/**
|
|
57
|
+
* The row's owning subject — write-contract v1
|
|
58
|
+
* grammar. Cardinality-1: exactly `[ownerColumnValue]`, format
|
|
59
|
+
* `eu_<base62>`. Scopes per-subject seal-and-erase (text DEK, blind-index
|
|
60
|
+
* linkage-delete, vector epoch-drop). Read at embed time from the source
|
|
61
|
+
* row's already-fail-closed `ownerColumn` — zero NLP, zero recall risk.
|
|
62
|
+
*
|
|
63
|
+
* Omit ONLY when the row derives from a provably `shared` (non-PII) source
|
|
64
|
+
* collection — the gateway exempts that case (C1-EXEMPT). Any other
|
|
65
|
+
* omission (including an unresolvable/unclassed source) is rejected with
|
|
66
|
+
* `400 K9O_VECTOR_SUBJECT_ATTRIBUTION_REQUIRED` — the gateway's default is
|
|
67
|
+
* fail-closed, not fail-open.
|
|
68
|
+
*/
|
|
69
|
+
subjectIds?: [string];
|
|
70
|
+
/** Arbitrary extension-defined metadata stored alongside the vector. */
|
|
71
|
+
metadata?: Record<string, unknown>;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export type VectorsUpsertResult = {
|
|
75
|
+
/** Number of rows written (inserted or replaced). */
|
|
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 }[];
|
|
84
|
+
/** Collection slug the rows were written to. */
|
|
85
|
+
collection: string;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
export type VectorSearchQuery = {
|
|
89
|
+
/** Query embedding. Must match the collection's stored vector dimension. */
|
|
90
|
+
queryVector: number[];
|
|
91
|
+
/** Max results, 1..1000. Default 10, server-capped. */
|
|
92
|
+
topK?: number;
|
|
93
|
+
/** Similarity floor — results with `score < minScore` are excluded. */
|
|
94
|
+
minScore?: number;
|
|
95
|
+
/** Similarity metric. Default `"cosine"` (the RAG-standard for embeddings). */
|
|
96
|
+
metric?: "cosine" | "euclidean" | "dot";
|
|
97
|
+
/**
|
|
98
|
+
* Equality filters on non-vector columns, bound-param safe. Keys:
|
|
99
|
+
* `id`, `contentHash`, `source.<key>` (→ `_source->>key`), `metadata.<key>`
|
|
100
|
+
* (→ `metadata->>key`). An unlisted path → 400 `K9O_INVALID_FIELD_VALUE`.
|
|
101
|
+
*/
|
|
102
|
+
filters?: Record<string, string>;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
export type VectorSearchResultRow = {
|
|
106
|
+
id: string;
|
|
107
|
+
/** Monotone similarity — higher is closer, for all three metrics. */
|
|
108
|
+
score: number;
|
|
109
|
+
_source: { handle: string; chunkIndex: number; [k: string]: unknown };
|
|
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;
|
|
112
|
+
/** Convenience field: `= metadata.model ?? null` (no first-class model column). */
|
|
113
|
+
model?: string | null;
|
|
114
|
+
/** Convenience field: `= _source.chunkIndex ?? null` — a chunk *index*, not chunk text. */
|
|
115
|
+
chunk?: number | null;
|
|
116
|
+
metadata?: Record<string, unknown>;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
export type VectorSearchResult = {
|
|
120
|
+
results: VectorSearchResultRow[];
|
|
121
|
+
collection: string;
|
|
122
|
+
};
|
|
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
|
+
|
|
167
|
+
export type VectorsNamespace = {
|
|
168
|
+
upsert(collection: string, rows: VectorRow[], options?: VectorsUpsertOptions): Promise<VectorsUpsertResult>;
|
|
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>;
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
function assertOwnCollection(verb: "upsert" | "search" | "delete" | "hashes", collection: string): void {
|
|
181
|
+
if (!collection.startsWith("_")) {
|
|
182
|
+
throw new Error(
|
|
183
|
+
`K9O_VECTORS_COLLECTION_GUARD: vectors.${verb} may only ${verb === "search" || verb === "hashes" ? "read" : verb === "delete" ? "delete from" : "write to"} ` +
|
|
184
|
+
`extension-owned derived collections (must start with '_'); ` +
|
|
185
|
+
`got '${collection}'.`,
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export function makeVectors(
|
|
191
|
+
transport: Transport,
|
|
192
|
+
projectSlug: string,
|
|
193
|
+
): VectorsNamespace {
|
|
194
|
+
return {
|
|
195
|
+
async upsert(collection, rows, options) {
|
|
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
|
+
}
|
|
212
|
+
const res = await transport.post<VectorsUpsertResult>(
|
|
213
|
+
`/@${projectSlug}/vectors/${collection}/upsert`,
|
|
214
|
+
fromRead === undefined ? { rows } : { rows, fromRead },
|
|
215
|
+
);
|
|
216
|
+
return { upserted: res.data.upserted, rows: res.data.rows, collection: res.data.collection };
|
|
217
|
+
},
|
|
218
|
+
async search(collection, query) {
|
|
219
|
+
assertOwnCollection("search", collection);
|
|
220
|
+
const res = await transport.post<VectorSearchResult>(
|
|
221
|
+
`/@${projectSlug}/vectors/${collection}/search`,
|
|
222
|
+
query,
|
|
223
|
+
);
|
|
224
|
+
return { results: res.data.results, collection: res.data.collection };
|
|
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
|
+
},
|
|
242
|
+
};
|
|
243
|
+
}
|