@k9o/extension-runtime 0.0.0-stage → 1.5.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 +71 -0
- package/src/client.ts +130 -0
- package/src/context.ts +70 -0
- package/src/dispatch-context.ts +58 -0
- package/src/guards.ts +35 -0
- package/src/http.ts +164 -0
- package/src/index.ts +142 -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/bff.ts +130 -0
- package/src/namespaces/collections.ts +104 -0
- package/src/namespaces/compliance.ts +48 -0
- package/src/namespaces/credentials.ts +77 -0
- package/src/namespaces/documents.ts +128 -0
- package/src/namespaces/egress.ts +31 -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 +144 -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,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.collections — collection-level read/write + ch04.
|
|
3
|
+
*
|
|
4
|
+
* Extensions read collection metadata (slug, name) and its schema descriptor, and can update
|
|
5
|
+
* mutable collection properties where the manifest grants collections/write.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { Transport } from "../http.ts";
|
|
9
|
+
import type { ApiResponse, Collection } from "../types.ts";
|
|
10
|
+
|
|
11
|
+
/** field-level at-rest protection descriptor; `null` on a column means unprotected. */
|
|
12
|
+
export type ColumnProtection = {
|
|
13
|
+
encrypted: boolean;
|
|
14
|
+
/** `inline` = Mode C (ciphertext in the row); `vault` = Mode D (vault token). */
|
|
15
|
+
store: "inline" | "vault";
|
|
16
|
+
blindIndexed: boolean;
|
|
17
|
+
searchable: boolean;
|
|
18
|
+
/** True when a reveal gate is present (its presence, not its rule). */
|
|
19
|
+
revealGated: boolean;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type CollectionSchemaColumn = {
|
|
23
|
+
name: string;
|
|
24
|
+
type: string;
|
|
25
|
+
nullable: boolean;
|
|
26
|
+
isPrimary: boolean;
|
|
27
|
+
isUnique: boolean;
|
|
28
|
+
default: string | null;
|
|
29
|
+
vectorDimension: number | null;
|
|
30
|
+
/** Platform-reserved column (name begins with `_`). */
|
|
31
|
+
reserved: boolean;
|
|
32
|
+
/** True for the collection's per-subject owner column (RC-6 erasure attribution). */
|
|
33
|
+
isOwnerColumn: boolean;
|
|
34
|
+
protection: ColumnProtection | null;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export type CollectionSchemaIndex = {
|
|
38
|
+
name: string;
|
|
39
|
+
columns: string[];
|
|
40
|
+
type: string;
|
|
41
|
+
unique: boolean;
|
|
42
|
+
status: "active" | "building" | "invalid";
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export type CollectionSchemaRelationship = {
|
|
46
|
+
column: string;
|
|
47
|
+
joinAlias: string;
|
|
48
|
+
joinType: string;
|
|
49
|
+
targetCollection: string;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/** The schema-introspection descriptor for one collection. */
|
|
53
|
+
export type CollectionSchema = {
|
|
54
|
+
name: string;
|
|
55
|
+
rowCount: number;
|
|
56
|
+
rowCountIsExact: boolean;
|
|
57
|
+
lastMigrationSlug: string | null;
|
|
58
|
+
lastMigrationAppliedAt: string | null;
|
|
59
|
+
/** The per-subject owner column, or null for a shared / non-per-subject collection. */
|
|
60
|
+
ownerColumn: string | null;
|
|
61
|
+
columns: CollectionSchemaColumn[];
|
|
62
|
+
relationships: CollectionSchemaRelationship[];
|
|
63
|
+
indexes: CollectionSchemaIndex[];
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* One protected column of the project (`GET /@<project>/schema/protected-columns`): names and protection only,
|
|
68
|
+
* never a value. Needs the `schema read ["protected_columns"]` grant.
|
|
69
|
+
*/
|
|
70
|
+
export type ProtectedColumn = {
|
|
71
|
+
collection: string;
|
|
72
|
+
column: string;
|
|
73
|
+
store: string;
|
|
74
|
+
searchable: boolean;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
export type CollectionsNamespace = {
|
|
78
|
+
read(): Promise<ApiResponse<Collection[]>>;
|
|
79
|
+
/**
|
|
80
|
+
* Schema descriptor for one collection (`GET /@<project>/schema/collections/<name>`).
|
|
81
|
+
* Protection and `ownerColumn` are platform facts: take them from here, never from a caller.
|
|
82
|
+
*/
|
|
83
|
+
schema(name: string): Promise<ApiResponse<CollectionSchema>>;
|
|
84
|
+
/** The project's protected columns, names only (`GET /@<project>/schema/protected-columns`). Needs `schema read ["protected_columns"]`. */
|
|
85
|
+
protectedColumns(): Promise<ApiResponse<ProtectedColumn[]>>;
|
|
86
|
+
write(id: string, updates: Partial<Pick<Collection, "name">>): Promise<ApiResponse<Collection>>;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
export function makeCollections(
|
|
90
|
+
transport: Transport,
|
|
91
|
+
projectSlug: string,
|
|
92
|
+
): CollectionsNamespace {
|
|
93
|
+
const base = `/@${projectSlug}/collections`;
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
read: () => transport.get<Collection[]>(base),
|
|
97
|
+
schema: (name) =>
|
|
98
|
+
transport.get<CollectionSchema>(
|
|
99
|
+
`/@${projectSlug}/schema/collections/${encodeURIComponent(name)}`,
|
|
100
|
+
),
|
|
101
|
+
protectedColumns: () => transport.get<ProtectedColumn[]>(`/@${projectSlug}/schema/protected-columns`),
|
|
102
|
+
write: (id, updates) => transport.patch<Collection>(`${base}/${id}`, updates),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.compliance — compliance-export EXTENSION-CALLER path.
|
|
3
|
+
*
|
|
4
|
+
* The MINT (`POST .../compliance-export-delegate`) is operator-authed, not
|
|
5
|
+
* extension-authed — an operator holding PROJECT_AUDITOR/PROJECT_ADMIN mints a
|
|
6
|
+
* short-lived delegate token and hands it to the extension out of band (e.g. as
|
|
7
|
+
* an input to the extension's own export function). This namespace is only the
|
|
8
|
+
* FETCH half: the extension presents its own plugin-token bearer (standard
|
|
9
|
+
* Authorization, injected by Transport) PLUS the delegate token via the
|
|
10
|
+
* `X-K9O-Compliance-Delegate` header (never the bearer — a separate credential
|
|
11
|
+
* per the gateway's own fail-closed checks in
|
|
12
|
+
* routes/compliance-export-delegate.ts).
|
|
13
|
+
*
|
|
14
|
+
* Manifest requirement: the extension must declare the `compliance_bundle`
|
|
15
|
+
* `export` permission — a transparency-only declaration; the actual
|
|
16
|
+
* authority is the delegate token, never this manifest grant alone.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type { Transport } from "../http.ts";
|
|
20
|
+
import type { ApiResponse, CredentialAttestationBundle } from "../types.ts";
|
|
21
|
+
|
|
22
|
+
export type ComplianceNamespace = {
|
|
23
|
+
/**
|
|
24
|
+
* Fetch the compliance attestation bundle using an operator-minted delegate
|
|
25
|
+
* token. `body` is forwarded byte-identical to kibo's compliance-export
|
|
26
|
+
* endpoint (e.g. a window/date-range selector) — optional, shape owned by
|
|
27
|
+
* the kibo side, not validated here.
|
|
28
|
+
*/
|
|
29
|
+
export(
|
|
30
|
+
delegateToken: string,
|
|
31
|
+
body?: Record<string, unknown>,
|
|
32
|
+
): Promise<ApiResponse<CredentialAttestationBundle>>;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export function makeCompliance(
|
|
36
|
+
transport: Transport,
|
|
37
|
+
projectSlug: string,
|
|
38
|
+
extensionSlug: string,
|
|
39
|
+
): ComplianceNamespace {
|
|
40
|
+
const base = `/@${projectSlug}/extensions-admin/${extensionSlug}`;
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
export: (delegateToken, body) =>
|
|
44
|
+
transport.post<CredentialAttestationBundle>(`${base}/compliance-export`, body, {
|
|
45
|
+
"X-K9O-Compliance-Delegate": delegateToken,
|
|
46
|
+
}),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.credentials.send — authenticated_send, the extension's half.
|
|
3
|
+
*
|
|
4
|
+
* Asks the platform to send ONE request to the destination bound to one of the extension's declared credential roles,
|
|
5
|
+
* signed with that role's credential. The extension never sees the secret; the platform checks the grant, the binding,
|
|
6
|
+
* the destination pins and the credential version, and drops a response that carries the credential back.
|
|
7
|
+
*
|
|
8
|
+
* Manifest requirement: a `(egress, authenticated_send, <role>)` permission for every role named here, and a
|
|
9
|
+
* `requires` entry for the role. Without the grant the route refuses and `send` throws that refusal (a RuntimeKError
|
|
10
|
+
* with the route's own code, message and context). Nothing here retries, falls back to `k9o.fetch`, or answers
|
|
11
|
+
* for the platform: every refusal reaches the caller as the route gave it (K9O_EXTENSION_PERMISSION_DENIED,
|
|
12
|
+
* K9O_INVALID_FIELD_VALUE, K9O_RATE_LIMITED, K9O_ACCESS_DENIED for a reflected credential, K9O_UPSTREAM_UNAVAILABLE ...).
|
|
13
|
+
*
|
|
14
|
+
* Name the destination one of two ways, never both: `url`, the full destination as bound for the role (the route
|
|
15
|
+
* resolves it against the binding's pins and refuses anything outside them); or `path` (with its query), for a role
|
|
16
|
+
* bound by origin, where the platform supplies the host from the binding and refuses a `url`. A `string` body is sent
|
|
17
|
+
* as UTF-8; bytes are sent as base64 (`bodyEncoding: "base64"`). The answer's `body` is decoded from the route's base64.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { base64ToBytes, bytesToBase64 } from "../base64.ts";
|
|
21
|
+
import type { Transport } from "../http.ts";
|
|
22
|
+
import { RuntimeKError } from "../kerror.ts";
|
|
23
|
+
|
|
24
|
+
export type CredentialSendRequest = {
|
|
25
|
+
method: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | (string & {});
|
|
26
|
+
headers?: Record<string, string>;
|
|
27
|
+
body?: string | Uint8Array | ArrayBuffer;
|
|
28
|
+
} & ({ url: string; path?: never } | { path: string; url?: never });
|
|
29
|
+
|
|
30
|
+
export type CredentialSendResult = {
|
|
31
|
+
status: number;
|
|
32
|
+
/** The destination's response headers, after the platform's filter. */
|
|
33
|
+
headers: Record<string, string>;
|
|
34
|
+
/** The response body, decoded from base64. */
|
|
35
|
+
body: Uint8Array;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export type CredentialsNamespace = {
|
|
39
|
+
send(role: string, request: CredentialSendRequest): Promise<CredentialSendResult>;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
type SendData = { status: number; headers: Record<string, string>; body: string; bodyEncoding: "base64" };
|
|
43
|
+
|
|
44
|
+
const malformed = (role: string, why: string): RuntimeKError =>
|
|
45
|
+
new RuntimeKError("K9O_UPSTREAM_UNAVAILABLE", `The authenticated send answer was not usable: ${why}`, { role, reason: "malformed_send_answer" }, null);
|
|
46
|
+
|
|
47
|
+
export function makeCredentials(transport: Transport, projectSlug: string, extensionSlug: string): CredentialsNamespace {
|
|
48
|
+
return {
|
|
49
|
+
async send(role, request) {
|
|
50
|
+
const body: Record<string, unknown> =
|
|
51
|
+
request.path !== undefined ? { method: request.method, path: request.path } : { method: request.method, url: request.url };
|
|
52
|
+
if (request.headers !== undefined) body.headers = request.headers;
|
|
53
|
+
if (request.body !== undefined) {
|
|
54
|
+
if (typeof request.body === "string") body.body = request.body;
|
|
55
|
+
else {
|
|
56
|
+
body.body = bytesToBase64(request.body instanceof ArrayBuffer ? new Uint8Array(request.body) : request.body);
|
|
57
|
+
body.bodyEncoding = "base64";
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const res = await transport.post<SendData>(
|
|
61
|
+
`/@${projectSlug}/extensions/${extensionSlug}/credentials/${encodeURIComponent(role)}/send`,
|
|
62
|
+
body,
|
|
63
|
+
);
|
|
64
|
+
const d = res.data;
|
|
65
|
+
if (d === undefined || d === null || typeof d.status !== "number" || typeof d.body !== "string" || d.bodyEncoding !== "base64") {
|
|
66
|
+
throw malformed(role, "missing status or base64 body");
|
|
67
|
+
}
|
|
68
|
+
let decoded: Uint8Array;
|
|
69
|
+
try {
|
|
70
|
+
decoded = base64ToBytes(d.body);
|
|
71
|
+
} catch {
|
|
72
|
+
throw malformed(role, "body is not base64");
|
|
73
|
+
}
|
|
74
|
+
return { status: d.status, headers: d.headers ?? {}, body: decoded };
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.documents — data access namespace + ch04 data pillar.
|
|
3
|
+
*
|
|
4
|
+
* Composed against manifest-declared permission scope triples
|
|
5
|
+
* EXTENSION_PERMISSION_DENIED (403) is thrown by RuntimeKError if the manifest
|
|
6
|
+
* did not grant the required (documents, action, qualifier) triple.
|
|
7
|
+
*
|
|
8
|
+
* Endpoint paths: the gateway's data-plane record routes, `/@<project>/data/<collection>`.
|
|
9
|
+
* That is the surface the extension grant gate classifies (`classifyForGrant`: `/data/<col>` GET is
|
|
10
|
+
* `(documents, read, <col>)`, POST/PUT/PATCH is write, DELETE is delete) and the one the callback bridge
|
|
11
|
+
* allow-lists. The earlier `/collections/<c>/documents` path has no gateway route.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { Transport } from "../http.ts";
|
|
15
|
+
import { QueuedWriteError } from "../kerror.ts";
|
|
16
|
+
import type { ApiResponse, Document, DocumentFilter } from "../types.ts";
|
|
17
|
+
|
|
18
|
+
export type DocumentsNamespace = {
|
|
19
|
+
read(
|
|
20
|
+
collection: string,
|
|
21
|
+
filter?: DocumentFilter,
|
|
22
|
+
): Promise<ApiResponse<Document[]>>;
|
|
23
|
+
/** Throws `QueuedWriteError` when a project approval policy queued the write instead of applying it. */
|
|
24
|
+
write(collection: string, data: Document): Promise<ApiResponse<Document>>;
|
|
25
|
+
/**
|
|
26
|
+
* Insert-or-ignore create with a caller-supplied row `id`, so a retry after a lost reply stores one row.
|
|
27
|
+
* `created` is true when this call stored the row (201) and false when the id already existed (200): the
|
|
28
|
+
* stored row comes back and `data` is NOT applied. A gateway that does not yet reject a replay whose columns differ
|
|
29
|
+
* from the stored row (409, no row returned) answers 200 there too, so a differing replay keeps the first values
|
|
30
|
+
* silently; on a gateway that does, that call throws `KError` with the 409. Do not rely on retry being safe against
|
|
31
|
+
* a gateway without the 409. An older gateway also answers 200 for a new row, so `created` is meaningful only
|
|
32
|
+
* against a gateway that answers 201 for one.
|
|
33
|
+
* Throws `QueuedWriteError` when a project approval policy queued the write; a retry may queue a second case.
|
|
34
|
+
*/
|
|
35
|
+
insert(collection: string, data: Document & { id: string }): Promise<ApiResponse<Document> & { created: boolean }>;
|
|
36
|
+
/** Throws `QueuedWriteError` when a project approval policy queued the delete instead of applying it. */
|
|
37
|
+
delete(collection: string, id: string): Promise<void>;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** The gateway's reserved list-query keys: a filter column with one of these names would be read as a control. */
|
|
41
|
+
const RESERVED_QUERY_KEYS = new Set([
|
|
42
|
+
"limit", "cursor", "count", "select", "order", "single", "range", "or", "aggregate", "embed",
|
|
43
|
+
"textSearch", "textSearchLanguage", "textSearchType", "vectorSearch", "vectorMetric", "vectorLimit",
|
|
44
|
+
"reveal", "revealPurpose", "deleted",
|
|
45
|
+
]);
|
|
46
|
+
const COLUMN = /^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/;
|
|
47
|
+
/** Compared case-insensitively: whether the gateway matches a reserved key exactly is not something the SDK relies on. */
|
|
48
|
+
const RESERVED_LOWER = new Set([...RESERVED_QUERY_KEYS].map((k) => k.toLowerCase()));
|
|
49
|
+
|
|
50
|
+
/** `eq` map to the gateway's `?<col>=<op>.<value>` filter grammar. Refuses what it cannot say exactly. */
|
|
51
|
+
function filterParams(eq: Record<string, unknown>): [string, string][] {
|
|
52
|
+
const out: [string, string][] = [];
|
|
53
|
+
for (const [col, v] of Object.entries(eq)) {
|
|
54
|
+
if (!COLUMN.test(col)) throw new TypeError(`documents.read: filter column "${col}" is not a valid column name`);
|
|
55
|
+
if (RESERVED_LOWER.has(col.toLowerCase())) throw new TypeError(`documents.read: filter column "${col}" collides with a reserved list parameter`);
|
|
56
|
+
if (v === null) out.push([col, "is.null"]);
|
|
57
|
+
else if (typeof v === "number" && !Number.isFinite(v)) throw new TypeError(`documents.read: filter value for "${col}" must be a finite number`);
|
|
58
|
+
else if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") out.push([col, `eq.${String(v)}`]);
|
|
59
|
+
else throw new TypeError(`documents.read: filter value for "${col}" must be a string, number, boolean or null`);
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A path segment must name something: `.`, `..` and the empty string are path operators or nothing, never a collection or id. */
|
|
65
|
+
export function segment(what: "collection" | "id", v: unknown): string {
|
|
66
|
+
if (typeof v !== "string" || v === "" || v === "." || v === "..") {
|
|
67
|
+
throw new TypeError(`documents: ${what} must be a non-empty name, not "." or ".."`);
|
|
68
|
+
}
|
|
69
|
+
return encodeURIComponent(v);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A direct write the gateway queued answers 202 `{ data: { id, status: "pending_approval" } }` (`gateSingleRecordWrite`). */
|
|
73
|
+
function refuseQueued(operation: string, collection: string, res: unknown): void {
|
|
74
|
+
const data = (res as { data?: { id?: unknown; status?: unknown } } | undefined)?.data;
|
|
75
|
+
if (data?.status === "pending_approval") {
|
|
76
|
+
throw new QueuedWriteError(operation, collection, typeof data.id === "string" ? data.id : null);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function makeDocuments(
|
|
81
|
+
transport: Transport,
|
|
82
|
+
projectSlug: string,
|
|
83
|
+
): DocumentsNamespace {
|
|
84
|
+
const base = (collection: string) => `/@${projectSlug}/data/${segment("collection", collection)}`;
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
async read(collection, filter) {
|
|
88
|
+
const params = new URLSearchParams();
|
|
89
|
+
if (filter?.limit) params.set("limit", String(filter.limit));
|
|
90
|
+
if (filter?.cursor) params.set("cursor", filter.cursor);
|
|
91
|
+
if (filter?.eq) for (const [k, v] of filterParams(filter.eq)) params.append(k, v);
|
|
92
|
+
const qs = params.size > 0 ? `?${params.toString()}` : "";
|
|
93
|
+
return transport.get<Document[]>(`${base(collection)}${qs}`);
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
async write(collection, data) {
|
|
97
|
+
const { id, ...rest } = data as Document & { id?: unknown };
|
|
98
|
+
// A present non-string id must not fall through to a create: an intended update would insert a row.
|
|
99
|
+
if (id !== undefined && typeof id !== "string") {
|
|
100
|
+
throw new TypeError("documents.write: id must be a string when present");
|
|
101
|
+
}
|
|
102
|
+
if (typeof id === "string") {
|
|
103
|
+
// The id is the path; the body carries only the fields to change.
|
|
104
|
+
const res = await transport.patch<Document>(`${base(collection)}/${segment("id", id)}`, rest);
|
|
105
|
+
refuseQueued("write", collection, res);
|
|
106
|
+
return res;
|
|
107
|
+
}
|
|
108
|
+
const res = await transport.post<Document>(base(collection), data);
|
|
109
|
+
refuseQueued("write", collection, res);
|
|
110
|
+
return res;
|
|
111
|
+
},
|
|
112
|
+
|
|
113
|
+
async insert(collection, data) {
|
|
114
|
+
const id = (data as { id?: unknown } | null)?.id;
|
|
115
|
+
if (typeof id !== "string") throw new TypeError("documents.insert: id must be a string");
|
|
116
|
+
segment("id", id);
|
|
117
|
+
const { status, body } = await transport.postWithStatus<Document>(`${base(collection)}?onConflict=ignore`, data);
|
|
118
|
+
refuseQueued("insert", collection, body);
|
|
119
|
+
return { ...body, created: status === 201 };
|
|
120
|
+
},
|
|
121
|
+
|
|
122
|
+
async delete(collection, id) {
|
|
123
|
+
// The transport types a DELETE as void, but the gateway answers a queued delete with a 202 body.
|
|
124
|
+
const res: unknown = await transport.delete_(`${base(collection)}/${segment("id", id)}`);
|
|
125
|
+
refuseQueued("delete", collection, res);
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.fetch — manifest-declared egress dependencies.
|
|
3
|
+
*
|
|
4
|
+
* Extensions CANNOT call arbitrary URLs directly; the sandbox network is
|
|
5
|
+
* restricted. All outbound HTTP goes through the platform's egress proxy
|
|
6
|
+
* which enforces the manifest's per-extension allowlist.
|
|
7
|
+
*
|
|
8
|
+
* Callers use k9o.fetch exactly like globalThis.fetch; the proxy returns
|
|
9
|
+
* the upstream Response, status and headers included (marked `x-k9o-egress: proxied`).
|
|
10
|
+
* A failure produced by the proxy itself (not granted, not bound, blocked target, size
|
|
11
|
+
* cap, timeout) carries no such marker and is thrown as a RuntimeKError.
|
|
12
|
+
*
|
|
13
|
+
* Named `egress` internally to avoid collision with the `fetch` keyword;
|
|
14
|
+
* exported to the k9o client object as `k9o.fetch`.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { Transport } from "../http.ts";
|
|
18
|
+
|
|
19
|
+
export type EgressNamespace = {
|
|
20
|
+
fetch(url: string, options?: RequestInit): Promise<Response>;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function makeEgress(
|
|
24
|
+
transport: Transport,
|
|
25
|
+
projectSlug: string,
|
|
26
|
+
extensionSlug: string,
|
|
27
|
+
): EgressNamespace {
|
|
28
|
+
return {
|
|
29
|
+
fetch: (url, options) => transport.proxyFetch(projectSlug, extensionSlug, url, options),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.functions — Platform-tier function handler registration namespace.
|
|
3
|
+
*
|
|
4
|
+
* Extension authors register function handlers via `k9o.functions.handle(name, handler)`.
|
|
5
|
+
* This is the SDK counterpart to k9o-init's `:8081` reverse-proxy target
|
|
6
|
+
* (`invoke-server.ts` wires this
|
|
7
|
+
* namespace's `dispatch()` to an actual HTTP listener).
|
|
8
|
+
*
|
|
9
|
+
* `name` matches the manifest's `background_logic.functions[].name` (ch09
|
|
10
|
+
* `FunctionDescriptor`) for Path A (`runtime_tier: "container"`)
|
|
11
|
+
* extensions — the extension's own persistent process serves invocations
|
|
12
|
+
* for however many function names it registers.
|
|
13
|
+
*
|
|
14
|
+
* Handler ergonomics are RPC-style (Lambda-like): return the result value on
|
|
15
|
+
* success, throw on failure. `dispatch()` catches thrown errors and maps them
|
|
16
|
+
* to the runtime-error status (500) — extension authors never
|
|
17
|
+
* construct HTTP status codes themselves.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export type FunctionInvocationRequest = {
|
|
21
|
+
/** Matches the manifest-declared function name being invoked. */
|
|
22
|
+
functionName: string;
|
|
23
|
+
/** Caller-supplied payload — the function's argument. */
|
|
24
|
+
payload: unknown;
|
|
25
|
+
/** Unique per-invocation id, minted by the gateway. */
|
|
26
|
+
invocationId: string;
|
|
27
|
+
/** Function version, when the platform tracks per-function versioning. */
|
|
28
|
+
version?: unknown;
|
|
29
|
+
/**
|
|
30
|
+
* inject-locus — the plugin-token context (when the invocation
|
|
31
|
+
* carries an extension-scoped token for gateway callbacks).
|
|
32
|
+
*/
|
|
33
|
+
context?: unknown;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export type FunctionHandler = (
|
|
37
|
+
req: FunctionInvocationRequest,
|
|
38
|
+
) => Promise<unknown> | unknown;
|
|
39
|
+
|
|
40
|
+
export type FunctionDispatchResult = {
|
|
41
|
+
/** 200 on success; 500 when the handler threw; 400 when `functionName` has no registered handler. */
|
|
42
|
+
status: number;
|
|
43
|
+
body: unknown;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export type FunctionsNamespace = {
|
|
47
|
+
/**
|
|
48
|
+
* Register a handler for a function name.
|
|
49
|
+
* Registering the same name twice overwrites the first handler (last-write-wins).
|
|
50
|
+
*/
|
|
51
|
+
handle(name: string, handler: FunctionHandler): void;
|
|
52
|
+
/**
|
|
53
|
+
* Invoke the registered handler for a function invocation request.
|
|
54
|
+
* Used by `startInvokeServer()` to serve k9o-init's `:8081` reverse-proxy target.
|
|
55
|
+
* Returns `{ status: 400, body: { error: "..." } }` when no handler is registered.
|
|
56
|
+
*/
|
|
57
|
+
dispatch(req: FunctionInvocationRequest): Promise<FunctionDispatchResult>;
|
|
58
|
+
/** Inspect the set of names that have a registered handler. Frozen snapshot. */
|
|
59
|
+
registeredNames(): readonly string[];
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export function makeFunctions(): FunctionsNamespace {
|
|
63
|
+
const registry = new Map<string, FunctionHandler>();
|
|
64
|
+
|
|
65
|
+
return {
|
|
66
|
+
handle(name, handler) {
|
|
67
|
+
registry.set(name, handler);
|
|
68
|
+
},
|
|
69
|
+
|
|
70
|
+
async dispatch(req) {
|
|
71
|
+
const handler = registry.get(req.functionName);
|
|
72
|
+
if (!handler) {
|
|
73
|
+
return {
|
|
74
|
+
status: 400,
|
|
75
|
+
body: { error: `No function handler registered for: ${req.functionName}` },
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
const result = await handler(req);
|
|
80
|
+
return { status: 200, body: result ?? null };
|
|
81
|
+
} catch (e) {
|
|
82
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
83
|
+
return { status: 500, body: { error: message } };
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
|
|
87
|
+
registeredNames() {
|
|
88
|
+
return Object.freeze([...registry.keys()]);
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.hooks — lifecycle-hook handler registration ("Hook delivery").
|
|
3
|
+
*
|
|
4
|
+
* An extension declares which hooks it serves in `manifest.hooks` (`{ enable: "POST /hooks/enable" }`)
|
|
5
|
+
* and registers the implementation here: `k9o.hooks.handle("enable", (payload, ctx) => { ... })`.
|
|
6
|
+
*
|
|
7
|
+
* Delivery inside the sandbox: the gateway sends the hook through the same dispatcher as a request,
|
|
8
|
+
* with the platform as actor, and sets the frame `context.kind = "hook"` plus `context.hookName` (the
|
|
9
|
+
* event name, one of `HOOK_EVENTS`). The discriminator routes to this namespace ONLY on that
|
|
10
|
+
* gateway-set field; the declared path is not a route here and the payload cannot select a hook.
|
|
11
|
+
* Delivery inside the sandbox needs no HMAC (`hookSecret` applies only to a delivery that crosses to
|
|
12
|
+
* an external host, none is specified for v2).
|
|
13
|
+
*
|
|
14
|
+
* Delivery is at-least-once: `purge` fires before teardown and a stranded-purge sweep may deliver it
|
|
15
|
+
* again, and critical hooks are retried, so every handler MUST be idempotent.
|
|
16
|
+
*
|
|
17
|
+
* `call_decided` is not a lifecycle event: it carries the outcome of a call the Warden held for approval, sent only to
|
|
18
|
+
* the install that made the call, once the call has ended. Serve it with `onCallDecided`, which validates the payload
|
|
19
|
+
* and hands the handler a typed {@link CallDecided}. A delivery the handler acknowledges collects the result: the
|
|
20
|
+
* platform deletes it. Throw `HookRejectedError` to refuse it without a retry (the result then stays readable at
|
|
21
|
+
* `GET /@<project>/mcp/calls/:callId` until it expires); throw anything else and it is retried.
|
|
22
|
+
*
|
|
23
|
+
* Failure semantics follow: a handler that throws is a 5xx (the gateway retries critical
|
|
24
|
+
* hooks); a handler that wants to refuse throws `HookRejectedError` with a 4xx status (application-level
|
|
25
|
+
* rejection, no retry). A hook the manifest declares but no handler serves fails loudly (5xx), never a
|
|
26
|
+
* silent success.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import type { HookEvent } from "@k9o/extension-manifest";
|
|
30
|
+
import type { DispatchContext } from "../dispatch-context.ts";
|
|
31
|
+
|
|
32
|
+
export type { HookEvent };
|
|
33
|
+
|
|
34
|
+
/** The closed v2 hook-event enum, and `call_decided`. */
|
|
35
|
+
export const HOOK_EVENTS = ["enable", "configure", "activate", "deactivate", "purge", "monitor", "data_export", "call_decided"] as const satisfies readonly HookEvent[];
|
|
36
|
+
|
|
37
|
+
/** How a held call ended. `done` carries the tool's result; the others ran nothing, or nothing that answered. */
|
|
38
|
+
export type CallDecidedOutcome = "done" | "refused" | "rejected" | "expired";
|
|
39
|
+
const CALL_DECIDED_OUTCOMES: readonly CallDecidedOutcome[] = ["done", "refused", "rejected", "expired"];
|
|
40
|
+
|
|
41
|
+
/** The `call_decided` payload, as the gateway builds it. */
|
|
42
|
+
export type CallDecided = {
|
|
43
|
+
event: "call_decided";
|
|
44
|
+
extensionId: string;
|
|
45
|
+
projectId: string;
|
|
46
|
+
/** The id the held answer named (the approval id). */
|
|
47
|
+
callId: string;
|
|
48
|
+
outcome: CallDecidedOutcome;
|
|
49
|
+
/** A fixed reason word (for example `token_revoked`, `approval_window_closed`, `tool_error`), or null. */
|
|
50
|
+
reason: string | null;
|
|
51
|
+
/** ISO 8601. */
|
|
52
|
+
endedAt: string | null;
|
|
53
|
+
/** The tool's answer when `outcome` is `done`, else null. */
|
|
54
|
+
result: unknown;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
export type CallDecidedHandler = (call: CallDecided, ctx: DispatchContext) => Promise<unknown> | unknown;
|
|
58
|
+
|
|
59
|
+
/** A `call_decided` body this SDK can type, or null. */
|
|
60
|
+
function asCallDecided(body: Record<string, unknown>): CallDecided | null {
|
|
61
|
+
const str = (v: unknown): v is string => typeof v === "string" && v.length > 0;
|
|
62
|
+
const nullableStr = (v: unknown): v is string | null => v === null || typeof v === "string";
|
|
63
|
+
const outcome = body["outcome"];
|
|
64
|
+
if (!str(body["callId"]) || !str(body["extensionId"]) || !str(body["projectId"])) return null;
|
|
65
|
+
if (typeof outcome !== "string" || !(CALL_DECIDED_OUTCOMES as readonly string[]).includes(outcome)) return null;
|
|
66
|
+
if (!nullableStr(body["reason"] ?? null) || !nullableStr(body["endedAt"] ?? null)) return null;
|
|
67
|
+
return {
|
|
68
|
+
event: "call_decided",
|
|
69
|
+
extensionId: body["extensionId"],
|
|
70
|
+
projectId: body["projectId"],
|
|
71
|
+
callId: body["callId"],
|
|
72
|
+
outcome: outcome as CallDecidedOutcome,
|
|
73
|
+
reason: (body["reason"] as string | null | undefined) ?? null,
|
|
74
|
+
endedAt: (body["endedAt"] as string | null | undefined) ?? null,
|
|
75
|
+
result: outcome === "done" ? (body["result"] ?? null) : null,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The canonical hook body, as the gateway builds it. Lifecycle hooks carry the delivery
|
|
81
|
+
* fields; `monitor` carries only ids and correlation ids and no customer data. The gateway is
|
|
82
|
+
* authoritative for the field set; unknown extra fields are passed through untouched.
|
|
83
|
+
*/
|
|
84
|
+
export type HookPayload = {
|
|
85
|
+
event: HookEvent;
|
|
86
|
+
extensionId: string;
|
|
87
|
+
projectId: string;
|
|
88
|
+
orgId?: string;
|
|
89
|
+
deliveryId?: string;
|
|
90
|
+
timestamp?: string;
|
|
91
|
+
manifestVersion?: string;
|
|
92
|
+
/** The grants just bound (enable) or in force. */
|
|
93
|
+
permissionGrants?: unknown[];
|
|
94
|
+
/** Current per-project configuration; empty on first enable. */
|
|
95
|
+
config?: Record<string, unknown>;
|
|
96
|
+
/** `monitor` correlation ids. */
|
|
97
|
+
requestId?: string;
|
|
98
|
+
traceId?: string;
|
|
99
|
+
[extra: string]: unknown;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/** `monitor` must return this closed shape. */
|
|
103
|
+
export type MonitorResult = { healthy: boolean; message?: string; details?: Record<string, unknown> };
|
|
104
|
+
|
|
105
|
+
export type HookHandler = (payload: HookPayload, ctx: DispatchContext) => Promise<unknown> | unknown;
|
|
106
|
+
|
|
107
|
+
/** Throw from a handler to reject a delivery at application level: a 4xx is not retried. */
|
|
108
|
+
export class HookRejectedError extends Error {
|
|
109
|
+
readonly status: number;
|
|
110
|
+
constructor(message: string, status = 400) {
|
|
111
|
+
super(message);
|
|
112
|
+
this.name = "HookRejectedError";
|
|
113
|
+
if (!Number.isInteger(status) || status < 400 || status > 499) {
|
|
114
|
+
throw new RangeError("HookRejectedError status must be a 4xx integer");
|
|
115
|
+
}
|
|
116
|
+
this.status = status;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export type HooksNamespace = {
|
|
121
|
+
/** Register the handler for one hook event. Registering the same event twice overwrites (last write wins). */
|
|
122
|
+
handle(event: HookEvent, handler: HookHandler): void;
|
|
123
|
+
/**
|
|
124
|
+
* Serve `call_decided`: the outcome of a call this install made that the Warden held for approval. Declare
|
|
125
|
+
* `hooks.call_decided` (`"POST /hooks/call-decided"`) in the manifest, or nothing is sent. Same as
|
|
126
|
+
* `handle("call_decided", …)` with the payload checked and typed; a malformed one is a 4xx rejection.
|
|
127
|
+
*/
|
|
128
|
+
onCallDecided(handler: CallDecidedHandler): void;
|
|
129
|
+
/**
|
|
130
|
+
* Deliver a hook to its handler. Used by the invoke server for `context.kind === "hook"` frames.
|
|
131
|
+
* Rejects with `HookRejectedError` (4xx) for an unknown event or a payload whose own `event` disagrees
|
|
132
|
+
* with the frame's, and with a plain `Error` (5xx) when no handler is registered or `monitor` returns
|
|
133
|
+
* the wrong shape.
|
|
134
|
+
*/
|
|
135
|
+
dispatch(event: string, payload: unknown, ctx: DispatchContext): Promise<unknown>;
|
|
136
|
+
/** Events that have a handler. Frozen snapshot. */
|
|
137
|
+
registeredEvents(): readonly HookEvent[];
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
function isHookEvent(v: string): v is HookEvent {
|
|
141
|
+
return (HOOK_EVENTS as readonly string[]).includes(v);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function makeHooks(): HooksNamespace {
|
|
145
|
+
const registry = new Map<HookEvent, HookHandler>();
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
handle(event, handler) {
|
|
149
|
+
if (!isHookEvent(event)) throw new RangeError(`unknown hook event: ${String(event)}`);
|
|
150
|
+
registry.set(event, handler);
|
|
151
|
+
},
|
|
152
|
+
|
|
153
|
+
onCallDecided(handler) {
|
|
154
|
+
registry.set("call_decided", (payload, ctx) => {
|
|
155
|
+
const call = asCallDecided(payload as Record<string, unknown>);
|
|
156
|
+
if (call === null) throw new HookRejectedError("call_decided payload is malformed", 400);
|
|
157
|
+
return handler(call, ctx);
|
|
158
|
+
});
|
|
159
|
+
},
|
|
160
|
+
|
|
161
|
+
async dispatch(event, payload, ctx) {
|
|
162
|
+
if (!isHookEvent(event)) throw new HookRejectedError("unknown hook event", 400);
|
|
163
|
+
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
|
|
164
|
+
throw new HookRejectedError("hook payload must be an object", 400);
|
|
165
|
+
}
|
|
166
|
+
const body = payload as Record<string, unknown>;
|
|
167
|
+
if (body["event"] !== undefined && body["event"] !== event) {
|
|
168
|
+
throw new HookRejectedError("hook payload event does not match the delivered hook", 400);
|
|
169
|
+
}
|
|
170
|
+
const handler = registry.get(event);
|
|
171
|
+
if (handler === undefined) throw new Error(`no handler is registered for the "${event}" hook`);
|
|
172
|
+
const result = await handler({ ...body, event } as HookPayload, ctx);
|
|
173
|
+
if (event === "monitor") {
|
|
174
|
+
const r = result as Record<string, unknown> | null | undefined;
|
|
175
|
+
if (r === null || typeof r !== "object" || typeof r["healthy"] !== "boolean") {
|
|
176
|
+
throw new Error('the "monitor" hook must return { healthy: boolean, message?, details? }');
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return result ?? null;
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
registeredEvents() {
|
|
183
|
+
return Object.freeze(HOOK_EVENTS.filter((e) => registry.has(e)));
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
}
|