@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,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.ai.agentRuntime — singleton runtime contract for type-(b) AI agents.
|
|
3
|
+
*
|
|
4
|
+
* Binding shape (sourced verbatim from the compliance-audit and hr-onboarding
|
|
5
|
+
* agent extensions). Three load-bearing facts:
|
|
6
|
+
*
|
|
7
|
+
* 1. `audit.read({ limit, orderBy })` is the Compliance Audit Agent primary
|
|
8
|
+
* read path. Gov Records + Insurance Underwriting also consume.
|
|
9
|
+
* 2. `ai.generate({ model?, prompt, maxTokens })` returns `{ text }` envelope
|
|
10
|
+
* (NOT bare-string text). `maxTokens` is binding for gateway
|
|
11
|
+
* tier-gated metering The gateway's `content`, `usage.totalTokens`,
|
|
12
|
+
* `finishReason` and `modelId` are mapped to `text`, `tokensUsed`, `finishReason` and `modelUsed`.
|
|
13
|
+
* 3. `data.write.propose()` returns `{ pending_change_id, status }`. The
|
|
14
|
+
* gateway queues every proposal for a person (, `forceQueue`), so
|
|
15
|
+
* `status` is always `"pending"`; nothing is written until it is approved.
|
|
16
|
+
*
|
|
17
|
+
* Production gateway routes (canonical `@<projectSlug>` path form):
|
|
18
|
+
* - `GET /@{projectSlug}/extensions/{slug}/audit/events?limit=&orderBy=`
|
|
19
|
+
* - `POST /@{projectSlug}/ai/generate` (same route as k9o.ai.generate)
|
|
20
|
+
* - `POST /@{projectSlug}/data/{collection}/propose` (insert; the record is the body)
|
|
21
|
+
* - `PATCH /@{projectSlug}/data/{collection}/{id}/propose` (update; the fields are the body)
|
|
22
|
+
* - `DELETE /@{projectSlug}/data/{collection}/{id}/propose` (delete; no body)
|
|
23
|
+
* Each needs `documents propose <collection>`, or the write (delete) grant it proposes.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import type { Transport } from "../http.ts";
|
|
27
|
+
import { segment } from "./documents.ts";
|
|
28
|
+
|
|
29
|
+
export type AuditEvent = {
|
|
30
|
+
/** ISO-8601 timestamp. */
|
|
31
|
+
occurredAt: string;
|
|
32
|
+
/** Dotted action vocab (e.g., `"data.write.documents.create"`). */
|
|
33
|
+
action: string;
|
|
34
|
+
/** Subject identity (`user_id` / `extension_id`). */
|
|
35
|
+
actor: string;
|
|
36
|
+
/** Collection / document ID or file path. */
|
|
37
|
+
resource: string;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export type AuditReadOptions = {
|
|
41
|
+
/** Default 500 in agent code; callers can override. */
|
|
42
|
+
limit: number;
|
|
43
|
+
orderBy: "occurredAt_desc" | "occurredAt_asc";
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export type GenerateOptions = {
|
|
47
|
+
/** Optional; defaults to the organisation's default language model. */
|
|
48
|
+
model?: string;
|
|
49
|
+
prompt: string;
|
|
50
|
+
/** Binding for gateway tier-gated metering */
|
|
51
|
+
maxTokens: number;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* `GenerateResult` envelope (binding source: agent
|
|
56
|
+
* authoring). The `text` field is the load-bearing payload; `tokensUsed` /
|
|
57
|
+
* `finishReason` / `modelUsed` are forward-compat metadata fields that the
|
|
58
|
+
* gateway may populate when available (metering envelope).
|
|
59
|
+
*
|
|
60
|
+
* Consumers should branch on field presence (`result.tokensUsed != null`)
|
|
61
|
+
* rather than asserting presence — the gateway populates these incrementally
|
|
62
|
+
* as the metering substrate matures.
|
|
63
|
+
*/
|
|
64
|
+
export type GenerateResult = {
|
|
65
|
+
/** Raw LLM output; agents parse into structured shape per their narrative schema. */
|
|
66
|
+
text: string;
|
|
67
|
+
/** Total token count consumed (input + output). Forward-compat */
|
|
68
|
+
tokensUsed?: number;
|
|
69
|
+
/**
|
|
70
|
+
* Reason the call terminated, as the gateway reports it (for example `"stop"` for natural completion or
|
|
71
|
+
* `"length"` when `maxTokens` was hit).
|
|
72
|
+
*/
|
|
73
|
+
finishReason?: string;
|
|
74
|
+
/**
|
|
75
|
+
* Actual model that served the call. May differ from `GenerateOptions.model`
|
|
76
|
+
* when the organisation's default resolved server-side.
|
|
77
|
+
*/
|
|
78
|
+
modelUsed?: string;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/** A proposed write. `operation` defaults to `"insert"`. */
|
|
82
|
+
export type WriteProposal =
|
|
83
|
+
| { collection: string; operation?: "insert"; document: Record<string, unknown> }
|
|
84
|
+
| { collection: string; operation: "update"; id: string; document: Record<string, unknown> }
|
|
85
|
+
| { collection: string; operation: "delete"; id: string };
|
|
86
|
+
|
|
87
|
+
export type WriteProposalResult = {
|
|
88
|
+
/** The approval case's id. snake_case wire shape. */
|
|
89
|
+
pending_change_id: string;
|
|
90
|
+
/** Always `"pending"`: the gateway queues every proposal, and a person decides it in Approvals. */
|
|
91
|
+
status: "pending";
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** The gateway's 202 body for a proposal (`collection-records.ts` `gateSingleRecordWrite`). */
|
|
95
|
+
type QueuedProposal = { id: string; status: string; operation: string; makerId: string; targetRecordId: string | null };
|
|
96
|
+
|
|
97
|
+
export type AgentRuntime = {
|
|
98
|
+
audit: {
|
|
99
|
+
read(options: AuditReadOptions): Promise<readonly AuditEvent[]>;
|
|
100
|
+
};
|
|
101
|
+
ai: {
|
|
102
|
+
generate(options: GenerateOptions): Promise<GenerateResult>;
|
|
103
|
+
};
|
|
104
|
+
data: {
|
|
105
|
+
write: {
|
|
106
|
+
propose(proposal: WriteProposal): Promise<WriteProposalResult>;
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
export function makeAgentRuntime(
|
|
112
|
+
transport: Transport,
|
|
113
|
+
projectSlug: string,
|
|
114
|
+
extensionSlug: string,
|
|
115
|
+
): AgentRuntime {
|
|
116
|
+
return {
|
|
117
|
+
audit: {
|
|
118
|
+
async read(options) {
|
|
119
|
+
const params = new URLSearchParams({
|
|
120
|
+
limit: String(options.limit),
|
|
121
|
+
orderBy: options.orderBy,
|
|
122
|
+
});
|
|
123
|
+
const res = await transport.get<readonly AuditEvent[]>(
|
|
124
|
+
`/@${projectSlug}/extensions/${extensionSlug}/audit/events?${params.toString()}`,
|
|
125
|
+
);
|
|
126
|
+
return res.data;
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
ai: {
|
|
130
|
+
async generate(options) {
|
|
131
|
+
const res = await transport.post<{
|
|
132
|
+
modelId: string;
|
|
133
|
+
content: string;
|
|
134
|
+
finishReason?: string;
|
|
135
|
+
usage?: { totalTokens?: number };
|
|
136
|
+
}>(`/@${projectSlug}/ai/generate`, {
|
|
137
|
+
prompt: options.prompt,
|
|
138
|
+
...(options.model !== undefined ? { model: options.model } : {}),
|
|
139
|
+
maxTokens: options.maxTokens,
|
|
140
|
+
});
|
|
141
|
+
// exactOptionalPropertyTypes: only attach optional fields when present.
|
|
142
|
+
const result: GenerateResult = { text: res.data.content };
|
|
143
|
+
if (res.data.usage?.totalTokens !== undefined) result.tokensUsed = res.data.usage.totalTokens;
|
|
144
|
+
if (res.data.finishReason !== undefined) result.finishReason = res.data.finishReason;
|
|
145
|
+
if (res.data.modelId !== undefined) result.modelUsed = res.data.modelId;
|
|
146
|
+
return result;
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
data: {
|
|
150
|
+
write: {
|
|
151
|
+
async propose(proposal) {
|
|
152
|
+
const base = `/@${projectSlug}/data/${segment("collection", proposal.collection)}`;
|
|
153
|
+
let res: { data: QueuedProposal };
|
|
154
|
+
if (proposal.operation === "update") {
|
|
155
|
+
res = await transport.patch<QueuedProposal>(`${base}/${segment("id", proposal.id)}/propose`, proposal.document);
|
|
156
|
+
} else if (proposal.operation === "delete") {
|
|
157
|
+
// The gateway answers a proposed delete with a body (202), which the transport returns as is.
|
|
158
|
+
res = (await transport.delete_(`${base}/${segment("id", proposal.id)}/propose`)) as unknown as { data: QueuedProposal };
|
|
159
|
+
} else {
|
|
160
|
+
res = await transport.post<QueuedProposal>(`${base}/propose`, proposal.document);
|
|
161
|
+
}
|
|
162
|
+
if (res?.data?.status !== "pending_approval" || typeof res.data.id !== "string") {
|
|
163
|
+
throw new TypeError("data.write.propose: the gateway did not queue the proposal");
|
|
164
|
+
}
|
|
165
|
+
return { pending_change_id: res.data.id, status: "pending" };
|
|
166
|
+
},
|
|
167
|
+
},
|
|
168
|
+
},
|
|
169
|
+
};
|
|
170
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.ai — AI gateway: `generate` (text from a prompt) and `embed`.
|
|
3
|
+
*
|
|
4
|
+
* Gateway-mediated: the platform routes to the curated open-source LLM
|
|
5
|
+
* library (phi-3-mini / mistral-7b at v2 launch llm.compatibility).
|
|
6
|
+
* Tier-gated: Base Camp → phi-3-mini only; Ascent+ → phi-3-mini + mistral-7b.
|
|
7
|
+
*
|
|
8
|
+
* MODEL_NOT_DECLARED enforcement: if the extension's manifest does not list
|
|
9
|
+
* the requested model in `llm.compatibility[]`, the platform returns
|
|
10
|
+
* MODEL_NOT_DECLARED (403) and RuntimeKError is thrown.
|
|
11
|
+
*
|
|
12
|
+
* `generate`: `POST /@<project>/ai/generate`. Needs the manifest grant `p.ai.generate()`. The optional `model` defaults
|
|
13
|
+
* to the organisation's default language model when omitted (the gateway answers 400 when there is none).
|
|
14
|
+
*
|
|
15
|
+
* `embed`: `POST /@<project>/ai/embeddings` with the platform's embedding model, run in the
|
|
16
|
+
* project's region. Needs the manifest grant `p.ai.embed()`; without it the gateway answers 403. At most 64 inputs and
|
|
17
|
+
* 256 KiB of input per call; the platform adds nothing to the text (callers add nomic's task prefixes, e.g.
|
|
18
|
+
* "search_document: " / "search_query: ", themselves).
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { Transport } from "../http.ts";
|
|
22
|
+
import type { ApiResponse, EmbedOptions, EmbedResult, GenerateOptions, GenerateResult } from "../types.ts";
|
|
23
|
+
import { makeAgentRuntime, type AgentRuntime } from "./ai-agent-runtime.ts";
|
|
24
|
+
|
|
25
|
+
export type AiNamespace = {
|
|
26
|
+
generate(
|
|
27
|
+
prompt: string,
|
|
28
|
+
options?: GenerateOptions,
|
|
29
|
+
): Promise<ApiResponse<GenerateResult>>;
|
|
30
|
+
embed(input: string | readonly string[], options?: EmbedOptions): Promise<ApiResponse<EmbedResult>>;
|
|
31
|
+
/** Singleton AgentRuntime for type-(b) AI agents. */
|
|
32
|
+
agentRuntime: AgentRuntime;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export function makeAi(
|
|
36
|
+
transport: Transport,
|
|
37
|
+
projectSlug: string,
|
|
38
|
+
extensionSlug: string,
|
|
39
|
+
): AiNamespace {
|
|
40
|
+
return {
|
|
41
|
+
generate: (prompt, options) =>
|
|
42
|
+
transport.post<GenerateResult>(`/@${projectSlug}/ai/generate`, {
|
|
43
|
+
prompt,
|
|
44
|
+
...(options?.model !== undefined ? { model: options.model } : {}),
|
|
45
|
+
...(options?.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),
|
|
46
|
+
...(options?.temperature !== undefined ? { temperature: options.temperature } : {}),
|
|
47
|
+
...(options?.usageType !== undefined ? { usageType: options.usageType } : {}),
|
|
48
|
+
}),
|
|
49
|
+
embed: (input, options) =>
|
|
50
|
+
transport.post<EmbedResult>(`/@${projectSlug}/ai/embeddings`, {
|
|
51
|
+
input: typeof input === "string" ? input : [...input],
|
|
52
|
+
...(options?.model !== undefined ? { model: options.model } : {}),
|
|
53
|
+
}),
|
|
54
|
+
agentRuntime: makeAgentRuntime(transport, projectSlug, extensionSlug),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.analytics — a Data Bridge's inbound write into, and paged read out of, Pulse Analytics
|
|
3
|
+
* (`databridge` resource, `write_analytics` / `read_analytics` actions, `p.databridge.writeAnalytics()` /
|
|
4
|
+
* `readAnalytics()` in `@k9o/extension-manifest`).
|
|
5
|
+
*
|
|
6
|
+
* Rides the governed ingestion write route (`POST /@<proj>/analytics/<slug>/write`) — every source
|
|
7
|
+
* adapter funnels through it, so schema conformance, region derivation, classification, metering,
|
|
8
|
+
* and audit are enforced once, there. `rows` is sent as a JSON array body (the route also accepts NDJSON; this client always
|
|
9
|
+
* sends the array form — simplest for the batch sizes a connector's own polling/webhook cadence
|
|
10
|
+
* produces).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { Transport } from "../http.ts";
|
|
14
|
+
import type { Meta } from "../types.ts";
|
|
15
|
+
|
|
16
|
+
export type AnalyticsWriteOnError = "skip" | "reject";
|
|
17
|
+
|
|
18
|
+
export type AnalyticsWriteOptions = {
|
|
19
|
+
/** Non-conforming rows: "skip" (default; skipped-and-reported) or "reject" (any bad row → 400, nothing ingested). */
|
|
20
|
+
onError?: AnalyticsWriteOnError;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export type AnalyticsWriteResult = {
|
|
24
|
+
ingested: number;
|
|
25
|
+
skipped: number;
|
|
26
|
+
skippedDetails: ReadonlyArray<{ index: number; reason: string }>;
|
|
27
|
+
partitionsTouched: ReadonlyArray<string>;
|
|
28
|
+
bytes: number;
|
|
29
|
+
bytesWritten?: number;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** One partition-column constraint: a scalar, an `in` list, or a `gte`/`lte` range. */
|
|
33
|
+
export type AnalyticsPartitionScalar = string | number | boolean;
|
|
34
|
+
export type AnalyticsPartitionConstraint =
|
|
35
|
+
| AnalyticsPartitionScalar
|
|
36
|
+
| { in: ReadonlyArray<AnalyticsPartitionScalar> }
|
|
37
|
+
| { gte?: AnalyticsPartitionScalar; lte?: AnalyticsPartitionScalar };
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Structured, SQL-free part pruning over the dataset's declared partition columns and `region` only. It selects
|
|
41
|
+
* which stored parts are scanned; it is NOT a row-level predicate.
|
|
42
|
+
*/
|
|
43
|
+
export type AnalyticsPartitionFilter = Readonly<Record<string, AnalyticsPartitionConstraint>>;
|
|
44
|
+
|
|
45
|
+
export type AnalyticsReadOptions = {
|
|
46
|
+
partitionFilter?: AnalyticsPartitionFilter;
|
|
47
|
+
/** Opaque, server-issued. Pass the previous page's `nextCursor` to continue, or a stored one to read only what was written since. */
|
|
48
|
+
cursor?: string;
|
|
49
|
+
/** Default 1000, hard max 10000 (a larger value is clamped by the server, not rejected). */
|
|
50
|
+
limit?: number;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export type AnalyticsReadSchemaColumn = { name: string; type: string };
|
|
54
|
+
|
|
55
|
+
export type AnalyticsReadPage = {
|
|
56
|
+
/**
|
|
57
|
+
* Rows rendered per the dataset's declared column types: int64/decimal and any integer outside the JS safe range
|
|
58
|
+
* arrive as strings, timestamps/dates as ISO-8601 UTC strings, bytes as base64 strings. Each row carries
|
|
59
|
+
* `_k9o_row_id`, stable across re-reads and unique within the dataset: dedup and join on it.
|
|
60
|
+
*/
|
|
61
|
+
rows: ReadonlyArray<Record<string, unknown>>;
|
|
62
|
+
/** `null` once exhausted. Drive paging off this, never off `rows.length === limit`: a page can be short and still have more. */
|
|
63
|
+
nextCursor: string | null;
|
|
64
|
+
/** The dataset's declared columns; present on the first page only (no `cursor` sent). */
|
|
65
|
+
schema?: ReadonlyArray<AnalyticsReadSchemaColumn>;
|
|
66
|
+
/** Server warnings, e.g. `query_limit_clamped` when `limit` exceeded the maximum and was reduced. */
|
|
67
|
+
warnings?: ReadonlyArray<string>;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** The platform list envelope the transport already unwraps: rows are `data`, the next cursor is `meta.cursor.next`, and `meta.schema` rides the first page only. */
|
|
71
|
+
type AnalyticsReadMeta = Meta & { schema?: ReadonlyArray<AnalyticsReadSchemaColumn> };
|
|
72
|
+
|
|
73
|
+
export type AnalyticsNamespace = {
|
|
74
|
+
/** Write rows into the named dataset. `datasetSlug` must match a `databridge`/`write_analytics`
|
|
75
|
+
* manifest grant (exact slug, or a wildcard qualifier). */
|
|
76
|
+
write(
|
|
77
|
+
datasetSlug: string,
|
|
78
|
+
rows: ReadonlyArray<Record<string, unknown>>,
|
|
79
|
+
opts?: AnalyticsWriteOptions,
|
|
80
|
+
): Promise<AnalyticsWriteResult>;
|
|
81
|
+
/**
|
|
82
|
+
* Read one page of the named dataset. `datasetSlug` must match a `databridge`/`read_analytics` manifest grant.
|
|
83
|
+
* Cursor-paginated and non-SQL; persist `nextCursor` to resume incrementally (parts are append-only, so only
|
|
84
|
+
* rows written since are returned). Authorisation is re-derived server-side on every page; the cursor is not a credential.
|
|
85
|
+
*/
|
|
86
|
+
read(datasetSlug: string, opts?: AnalyticsReadOptions): Promise<AnalyticsReadPage>;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
export function makeAnalytics(transport: Transport, projectSlug: string): AnalyticsNamespace {
|
|
90
|
+
return {
|
|
91
|
+
async write(datasetSlug, rows, opts) {
|
|
92
|
+
const onError = opts?.onError ?? "skip";
|
|
93
|
+
const res = await transport.post<AnalyticsWriteResult>(
|
|
94
|
+
`/@${projectSlug}/analytics/${datasetSlug}/write?onError=${onError}`,
|
|
95
|
+
rows,
|
|
96
|
+
);
|
|
97
|
+
return res.data;
|
|
98
|
+
},
|
|
99
|
+
async read(datasetSlug, opts) {
|
|
100
|
+
if (opts?.limit !== undefined && (!Number.isInteger(opts.limit) || opts.limit < 1)) {
|
|
101
|
+
throw new TypeError(`analytics.read: limit must be a positive integer (got ${String(opts.limit)})`);
|
|
102
|
+
}
|
|
103
|
+
const body: { partitionFilter?: AnalyticsPartitionFilter; cursor?: string; limit?: number } = {};
|
|
104
|
+
if (opts?.partitionFilter !== undefined) body.partitionFilter = opts.partitionFilter;
|
|
105
|
+
if (opts?.cursor !== undefined) body.cursor = opts.cursor;
|
|
106
|
+
if (opts?.limit !== undefined) body.limit = opts.limit;
|
|
107
|
+
const res = await transport.post<ReadonlyArray<Record<string, unknown>>>(
|
|
108
|
+
`/@${projectSlug}/analytics/${encodeURIComponent(datasetSlug)}/read`,
|
|
109
|
+
body,
|
|
110
|
+
);
|
|
111
|
+
const meta = res.meta as AnalyticsReadMeta;
|
|
112
|
+
return {
|
|
113
|
+
rows: res.data,
|
|
114
|
+
nextCursor: meta.cursor?.next ?? null,
|
|
115
|
+
...(meta.schema !== undefined ? { schema: meta.schema } : {}),
|
|
116
|
+
...(meta.warnings !== null && meta.warnings !== undefined && meta.warnings.length > 0
|
|
117
|
+
? { warnings: meta.warnings }
|
|
118
|
+
: {}),
|
|
119
|
+
};
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.attributes — project-level attribute key/value store + ch04.
|
|
3
|
+
*
|
|
4
|
+
* Attributes are a per-project, per-collection key/value store scoped to the
|
|
5
|
+
* extension's permission grants. Used for extension-level config and per-
|
|
6
|
+
* collection metadata the extension manages.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { Transport } from "../http.ts";
|
|
10
|
+
import type { ApiResponse, AttributeMap } from "../types.ts";
|
|
11
|
+
|
|
12
|
+
export type AttributesNamespace = {
|
|
13
|
+
read(collection: string, key?: string): Promise<ApiResponse<AttributeMap>>;
|
|
14
|
+
write(collection: string, key: string, value: unknown): Promise<void>;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export function makeAttributes(
|
|
18
|
+
transport: Transport,
|
|
19
|
+
projectSlug: string,
|
|
20
|
+
): AttributesNamespace {
|
|
21
|
+
const base = (slug: string) =>
|
|
22
|
+
`/@${projectSlug}/attributes/${slug}`;
|
|
23
|
+
|
|
24
|
+
return {
|
|
25
|
+
async read(collection, key) {
|
|
26
|
+
const path = key ? `${base(collection)}/${key}` : base(collection);
|
|
27
|
+
return transport.get<AttributeMap>(path);
|
|
28
|
+
},
|
|
29
|
+
|
|
30
|
+
async write(collection, key, value) {
|
|
31
|
+
await transport.patch(`${base(collection)}`, { [key]: value });
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.audit — audit-trail emit audit-attribution path.
|
|
3
|
+
*
|
|
4
|
+
* Extensions emit structured audit events attributed to the extension's
|
|
5
|
+
* identity (extensionId + extensionSlug) alongside the calling user's
|
|
6
|
+
* propagated claims. All emissions are audit-trail logged platform-side;
|
|
7
|
+
* the extension's plugin token gates what event types are permitted.
|
|
8
|
+
*
|
|
9
|
+
* eventType: reverse-DNS namespaced event identifier, e.g.
|
|
10
|
+
* "extensions.forms.submission_created"
|
|
11
|
+
* "extensions.lookout.view_rendered"
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { Transport } from "../http.ts";
|
|
15
|
+
import type { ApiResponse } from "../types.ts";
|
|
16
|
+
|
|
17
|
+
/** One of the extension's own events (`scope: "self"`, the `audit.read` `"_self"` grant). */
|
|
18
|
+
export type AuditOwnEvent = {
|
|
19
|
+
id: string;
|
|
20
|
+
type: string;
|
|
21
|
+
targetKind: string | null;
|
|
22
|
+
targetId: string | null;
|
|
23
|
+
payload: Record<string, unknown>;
|
|
24
|
+
occurredAt: string;
|
|
25
|
+
requestId: string | null;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* One of the project's events (`scope: "project"`, the `audit.read` `"project"` grant, first-party compliance
|
|
30
|
+
* extensions only). A closed projection: never a payload body. `ip` is truncated (/24, /48) for an extension reader.
|
|
31
|
+
*/
|
|
32
|
+
export type AuditProjectEvent = {
|
|
33
|
+
id: string;
|
|
34
|
+
actorId: string | null;
|
|
35
|
+
actorType: string;
|
|
36
|
+
action: string;
|
|
37
|
+
resourceType: string | null;
|
|
38
|
+
resourceId: string | null;
|
|
39
|
+
occurredAt: string;
|
|
40
|
+
outcome: "success" | "failure" | "denied" | null;
|
|
41
|
+
ip: string | null;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export type AuditEventsQuery = {
|
|
45
|
+
/** ISO 8601 bounds on `occurredAt`; the window is at most 400 days (default: the last 400 days). */
|
|
46
|
+
after?: string;
|
|
47
|
+
before?: string;
|
|
48
|
+
/** A literal prefix of the event type. */
|
|
49
|
+
eventType?: string;
|
|
50
|
+
/** 1-200 (default 50). */
|
|
51
|
+
limit?: number;
|
|
52
|
+
/** The previous page's `meta.cursor.next`. */
|
|
53
|
+
cursor?: string;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export type AuditNamespace = {
|
|
57
|
+
emit(eventType: string, payload: Record<string, unknown>): Promise<void>;
|
|
58
|
+
/**
|
|
59
|
+
* Read audit events, newest first, one page at a time. `scope: "self"` (the default) reads the extension's own
|
|
60
|
+
* events (`GET …/audit/events`); `scope: "project"` reads the project's events (`GET …/audit/project-events`).
|
|
61
|
+
*/
|
|
62
|
+
events(query?: AuditEventsQuery & { scope?: "self" }): Promise<ApiResponse<AuditOwnEvent[]>>;
|
|
63
|
+
events(query: AuditEventsQuery & { scope: "project" }): Promise<ApiResponse<AuditProjectEvent[]>>;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
export function makeAudit(
|
|
67
|
+
transport: Transport,
|
|
68
|
+
projectSlug: string,
|
|
69
|
+
extensionSlug = "",
|
|
70
|
+
): AuditNamespace {
|
|
71
|
+
return {
|
|
72
|
+
events: ((query: AuditEventsQuery & { scope?: "self" | "project" } = {}) => {
|
|
73
|
+
const params = new URLSearchParams();
|
|
74
|
+
for (const k of ["after", "before", "eventType", "cursor"] as const) {
|
|
75
|
+
const v = query[k];
|
|
76
|
+
if (v !== undefined) params.set(k, v);
|
|
77
|
+
}
|
|
78
|
+
if (query.limit !== undefined) params.set("limit", String(query.limit));
|
|
79
|
+
const path = query.scope === "project" ? "project-events" : "events";
|
|
80
|
+
const qs = params.toString();
|
|
81
|
+
return transport.get(
|
|
82
|
+
`/@${projectSlug}/extensions/${encodeURIComponent(extensionSlug)}/audit/${path}${qs === "" ? "" : `?${qs}`}`,
|
|
83
|
+
);
|
|
84
|
+
}) as AuditNamespace["events"],
|
|
85
|
+
async emit(eventType, payload) {
|
|
86
|
+
await transport.post(`/@${projectSlug}/audit/events`, {
|
|
87
|
+
eventType,
|
|
88
|
+
payload,
|
|
89
|
+
});
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* k9o.bff — BFF (Backend-for-Frontend) handler registration namespace.
|
|
3
|
+
*
|
|
4
|
+
* Extension authors register BFF endpoint handlers via `k9o.bff.handle(path, handler)`.
|
|
5
|
+
* The gateway forwarder sends a `BffRequest` and wraps nothing around the
|
|
6
|
+
* response: when the endpoint declares `version_attribute`, the gateway spreads `version` at the
|
|
7
|
+
* top of the JSON body next to the handler's own keys; there is no
|
|
8
|
+
* `data` wrapper. A handler returning its own top-level `version` is
|
|
9
|
+
* `K9O_EXTENSION_BFF_VERSION_COLLISION`.
|
|
10
|
+
*
|
|
11
|
+
* Extensions declare BFF endpoints in `manifest.externalEndpoints[]`;
|
|
12
|
+
* `k9o.bff.handle` registers the runtime implementation. Handler path collisions (two
|
|
13
|
+
* `handle()` calls for the same path) overwrite the first registration — last-write-wins.
|
|
14
|
+
*
|
|
15
|
+
* The operator JWT is never sent to the extension; the gateway verifies it and passes the
|
|
16
|
+
* verified claims as `req.operator`.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type { DispatchContext } from "../dispatch-context.ts";
|
|
20
|
+
|
|
21
|
+
/** Verified-claims caller, minimal: no email or name unless the endpoint declares it. */
|
|
22
|
+
export type BffOperator = {
|
|
23
|
+
/** Subject identity — typically `user_id`. */
|
|
24
|
+
sub: string;
|
|
25
|
+
roles: string[];
|
|
26
|
+
org_id: string;
|
|
27
|
+
project_id: string;
|
|
28
|
+
request_id: string;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export type BffHandler = (
|
|
32
|
+
req: BffRequest,
|
|
33
|
+
/** Per-dispatch context: build the callback client from `ctx.client`, never from load-time env. */
|
|
34
|
+
ctx: DispatchContext,
|
|
35
|
+
) => Promise<BffResponse> | BffResponse;
|
|
36
|
+
|
|
37
|
+
export type BffRequest = {
|
|
38
|
+
/** The matched declared path template (e.g. `/forms/:formId`), never the raw request path. */
|
|
39
|
+
path: string;
|
|
40
|
+
/** Values bound to the template's `:name` segments (one segment each; gateway-validated). */
|
|
41
|
+
params: Record<string, string>;
|
|
42
|
+
/** HTTP method from the inbound request (uppercase; e.g., `"GET"`, `"POST"`). */
|
|
43
|
+
method: string;
|
|
44
|
+
/** Explicit parsed query string. */
|
|
45
|
+
query: Record<string, string | string[]>;
|
|
46
|
+
/**
|
|
47
|
+
* Inbound headers forwarded by the gateway through an allowlist: `content-type`, `accept`,
|
|
48
|
+
* `accept-language`, `if-match`, `if-none-match`, `x-request-id`. Never cookies or authorization.
|
|
49
|
+
*/
|
|
50
|
+
headers: Record<string, string>;
|
|
51
|
+
/** Request body parsed as JSON (JSON only at launch), or `null` when no body is present. */
|
|
52
|
+
body: unknown;
|
|
53
|
+
/**
|
|
54
|
+
* Verified-claims caller. Present on `operator-jwt` endpoints; absent on `anonymous` ones.
|
|
55
|
+
* Branch on `req.operator?.sub`.
|
|
56
|
+
*/
|
|
57
|
+
operator?: BffOperator;
|
|
58
|
+
/**
|
|
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).
|
|
61
|
+
*/
|
|
62
|
+
caller?: { kind: "extension"; extensionId: string; slug: string } | { kind: "schedule"; name: string };
|
|
63
|
+
/** Where the call chain started, set by the gateway: an operator, or `system` for a scheduled run. */
|
|
64
|
+
origin?: { kind: "operator"; userId: string; role: string; run?: { id: string; step: number } } | { kind: "system" };
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export type BffResponse = {
|
|
68
|
+
/** HTTP status code for the response (default: 200). */
|
|
69
|
+
status?: number;
|
|
70
|
+
/** Response body — serialised to JSON by the gateway; passes through unwrapped. */
|
|
71
|
+
body: unknown;
|
|
72
|
+
/**
|
|
73
|
+
* Optional response headers, allowlisted by the gateway: `content-type`, `content-length`,
|
|
74
|
+
* `cache-control`, `etag`, `last-modified`, `content-disposition`, and `location` only as a
|
|
75
|
+
* relative path under the mount. `set-cookie` is always dropped.
|
|
76
|
+
*/
|
|
77
|
+
headers?: Record<string, string>;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
export type BffNamespace = {
|
|
81
|
+
/**
|
|
82
|
+
* Register a handler for a BFF endpoint path.
|
|
83
|
+
* Registering the same path twice overwrites the first handler (last-write-wins).
|
|
84
|
+
*
|
|
85
|
+
* @param path Must match a path declared in `manifest.externalEndpoints[]`.
|
|
86
|
+
* @param handler Sync or async function receiving a `BffRequest` + returning `BffResponse`.
|
|
87
|
+
*/
|
|
88
|
+
handle(path: string, handler: BffHandler): void;
|
|
89
|
+
/**
|
|
90
|
+
* Invoke the registered handler for a BFF request.
|
|
91
|
+
* Used by the K9O gateway runtime to route incoming BFF requests.
|
|
92
|
+
* Returns `{ status: 404, body: { error: "..." } }` when no handler is registered.
|
|
93
|
+
*/
|
|
94
|
+
dispatch(req: BffRequest, ctx: DispatchContext): Promise<BffResponse>;
|
|
95
|
+
/**
|
|
96
|
+
* Inspect the set of paths that have a registered handler. Returns a
|
|
97
|
+
* frozen snapshot — does not reflect subsequent `handle()` calls.
|
|
98
|
+
*
|
|
99
|
+
* Use cases: partner-CLI simulate-time cross-check against
|
|
100
|
+
* `manifest.externalEndpoints[]` (warn on declared-but-unregistered or
|
|
101
|
+
* registered-but-undeclared paths); test assertions for side-effect
|
|
102
|
+
* registration in bundle entry points; debugging.
|
|
103
|
+
*/
|
|
104
|
+
registeredPaths(): readonly string[];
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
export function makeBff(): BffNamespace {
|
|
108
|
+
const registry = new Map<string, BffHandler>();
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
handle(path, handler) {
|
|
112
|
+
registry.set(path, handler);
|
|
113
|
+
},
|
|
114
|
+
|
|
115
|
+
async dispatch(req, ctx) {
|
|
116
|
+
const handler = registry.get(req.path);
|
|
117
|
+
if (!handler) {
|
|
118
|
+
return {
|
|
119
|
+
status: 404,
|
|
120
|
+
body: { error: `No BFF handler registered for path: ${req.path}` },
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
return await handler(req, ctx);
|
|
124
|
+
},
|
|
125
|
+
|
|
126
|
+
registeredPaths() {
|
|
127
|
+
return Object.freeze([...registry.keys()]);
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|