@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,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ch07 `:8081` extension invoke server — the SDK counterpart to k9o-init's
|
|
3
|
+
* reverse proxy.
|
|
4
|
+
*
|
|
5
|
+
* k9o-init reverse-proxies `POST /invoke` from its vsock:8000 listener to
|
|
6
|
+
* `K9O_INVOKE_LISTEN` (default `127.0.0.1:8081`) inside the guest — nothing
|
|
7
|
+
* served that port until now, so a booted Path-A (`runtime_tier: "container"`)
|
|
8
|
+
* guest returned a clean 503 on every invoke. This module is that server.
|
|
9
|
+
*
|
|
10
|
+
* Wire contract matches `runPlatformInvocation()` in
|
|
11
|
+
* `k9o-core/services/gateway/src/routes/invoke.ts` verbatim (read directly
|
|
12
|
+
* from source, not guessed):
|
|
13
|
+
*
|
|
14
|
+
* Request: POST /invoke
|
|
15
|
+
* { functionName, version?, rootfsKey?, invocationId, payload, context? }
|
|
16
|
+
* Response: JSON body — the gateway's `decodeResult()` JSON.parses it
|
|
17
|
+
* (falls back to base64 wrapping if the body isn't valid JSON), so this
|
|
18
|
+
* server always emits `application/json`.
|
|
19
|
+
* - 200–399 → success; body is the function handler's return value
|
|
20
|
+
* - ≥500 → maps to `K9O_FUNCTION_RUNTIME_ERROR` at the gateway
|
|
21
|
+
* - ≥400 → maps to `K9O_FUNCTION_DEPLOYMENT_FAILED` (e.g. an
|
|
22
|
+
* unregistered `functionName` — the rootfs/manifest is
|
|
23
|
+
* inconsistent with what's actually registered at runtime)
|
|
24
|
+
*
|
|
25
|
+
* Extension authors don't call this directly in most cases — the container
|
|
26
|
+
* entrypoint calls `startInvokeServer(k9o.functions)` once at boot, having
|
|
27
|
+
* already registered handlers via `k9o.functions.handle(name, fn)`.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import type { FunctionsNamespace, FunctionInvocationRequest } from "./namespaces/functions.ts";
|
|
31
|
+
import type { BffNamespace, BffRequest } from "./namespaces/bff.ts";
|
|
32
|
+
import type { HooksNamespace } from "./namespaces/hooks.ts";
|
|
33
|
+
import type { WebhookIngressNamespace } from "./namespaces/webhook-ingress.ts";
|
|
34
|
+
import { routeExtensionInvocation } from "./bff-hook-discriminator.ts";
|
|
35
|
+
import { dispatchContextFromFrame } from "./dispatch-context.ts";
|
|
36
|
+
|
|
37
|
+
/** Fields a handler may rely on even if the gateway omits an empty one. */
|
|
38
|
+
const BFF_REQUEST_DEFAULTS = { headers: {}, query: {}, params: {}, body: null } as const;
|
|
39
|
+
|
|
40
|
+
const DEFAULT_HOSTNAME = "127.0.0.1";
|
|
41
|
+
const DEFAULT_PORT = 8081;
|
|
42
|
+
|
|
43
|
+
function invokeListenAddr(): { hostname: string; port: number } {
|
|
44
|
+
const raw = process.env["K9O_INVOKE_LISTEN"];
|
|
45
|
+
if (!raw) return { hostname: DEFAULT_HOSTNAME, port: DEFAULT_PORT };
|
|
46
|
+
const idx = raw.lastIndexOf(":");
|
|
47
|
+
if (idx <= 0) return { hostname: DEFAULT_HOSTNAME, port: DEFAULT_PORT };
|
|
48
|
+
const hostname = raw.slice(0, idx) || DEFAULT_HOSTNAME;
|
|
49
|
+
const port = parseInt(raw.slice(idx + 1), 10);
|
|
50
|
+
return { hostname, port: Number.isFinite(port) && port > 0 ? port : DEFAULT_PORT };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function isFunctionInvocationRequest(body: unknown): body is FunctionInvocationRequest {
|
|
54
|
+
return (
|
|
55
|
+
body !== null &&
|
|
56
|
+
typeof body === "object" &&
|
|
57
|
+
typeof (body as Record<string, unknown>)["functionName"] === "string" &&
|
|
58
|
+
typeof (body as Record<string, unknown>)["invocationId"] === "string" &&
|
|
59
|
+
"payload" in (body as Record<string, unknown>)
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function jsonResponse(status: number, body: unknown): Response {
|
|
64
|
+
return new Response(JSON.stringify(body), {
|
|
65
|
+
status,
|
|
66
|
+
headers: { "content-type": "application/json" },
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export type InvokeServerOptions = {
|
|
71
|
+
/** The `k9o.bff` namespace serving `context.kind === "bff"` frames. Without it BFF frames fail (500). */
|
|
72
|
+
bff?: BffNamespace;
|
|
73
|
+
/** The `k9o.hooks` namespace serving `context.kind === "hook"` frames. Without it hook frames fail (500). */
|
|
74
|
+
hooks?: HooksNamespace;
|
|
75
|
+
/** The `k9o.webhookIngress` namespace serving `context.kind === "webhook"` frames. Without it they fail (500). */
|
|
76
|
+
webhookIngress?: WebhookIngressNamespace;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export type InvokeServerHandle = {
|
|
80
|
+
stop(): void;
|
|
81
|
+
readonly hostname: string;
|
|
82
|
+
readonly port: number;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Start the `:8081` invoke server, dispatching every `POST /invoke` through
|
|
87
|
+
* `routeExtensionInvocation()`: only the gateway-set `context.kind` selects the route (`bff`, `hook`,
|
|
88
|
+
* `invoke`, `trigger`), and a frame with no or unknown context is refused. Binds to `K9O_INVOKE_LISTEN` (default
|
|
89
|
+
* `127.0.0.1:8081`, matching k9o-init's proxy target).
|
|
90
|
+
*/
|
|
91
|
+
export function startInvokeServer(
|
|
92
|
+
functions: FunctionsNamespace,
|
|
93
|
+
options: InvokeServerOptions = {},
|
|
94
|
+
): InvokeServerHandle {
|
|
95
|
+
const { hostname, port } = invokeListenAddr();
|
|
96
|
+
|
|
97
|
+
const server = Bun.serve({
|
|
98
|
+
hostname,
|
|
99
|
+
port,
|
|
100
|
+
async fetch(req) {
|
|
101
|
+
const url = new URL(req.url);
|
|
102
|
+
if (req.method !== "POST" || url.pathname !== "/invoke") {
|
|
103
|
+
return jsonResponse(404, { error: "not found" });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
let body: unknown;
|
|
107
|
+
try {
|
|
108
|
+
body = await req.json();
|
|
109
|
+
} catch {
|
|
110
|
+
return jsonResponse(400, { error: "invalid JSON body" });
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (!isFunctionInvocationRequest(body)) {
|
|
114
|
+
return jsonResponse(400, { error: "malformed invocation request" });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
try {
|
|
118
|
+
const result = await routeExtensionInvocation(body, {
|
|
119
|
+
dispatchBff: async (bffReq, frame) => {
|
|
120
|
+
if (options.bff === undefined) throw new Error("no BFF namespace is bound to this invoke server");
|
|
121
|
+
const normalised = { ...BFF_REQUEST_DEFAULTS, ...bffReq } as BffRequest;
|
|
122
|
+
return options.bff.dispatch(normalised, dispatchContextFromFrame(frame.context));
|
|
123
|
+
},
|
|
124
|
+
dispatchHook: async (hookName, frame) => {
|
|
125
|
+
if (options.hooks === undefined) throw new Error("no hooks namespace is bound to this invoke server");
|
|
126
|
+
return options.hooks.dispatch(hookName, frame.payload, dispatchContextFromFrame(frame.context));
|
|
127
|
+
},
|
|
128
|
+
dispatchWebhook: async (webhookPath, frame) => {
|
|
129
|
+
if (options.webhookIngress === undefined) throw new Error("no webhookIngress namespace is bound to this invoke server");
|
|
130
|
+
const c = frame.context as Record<string, unknown>;
|
|
131
|
+
return options.webhookIngress.dispatch(webhookPath, frame.payload, dispatchContextFromFrame(frame.context), c["deliveryId"] as string);
|
|
132
|
+
},
|
|
133
|
+
dispatchFunction: (frame) => functions.dispatch(frame),
|
|
134
|
+
});
|
|
135
|
+
return jsonResponse(result.status, result.body);
|
|
136
|
+
} catch (e) {
|
|
137
|
+
// A deliberate application-level rejection (HookRejectedError, 4xx) keeps its status so the
|
|
138
|
+
// gateway does not retry it; every other failure is a 5xx.
|
|
139
|
+
const status = e instanceof Error && e.name === "HookRejectedError" ? (e as Error & { status: number }).status : 500;
|
|
140
|
+
return jsonResponse(status, { error: e instanceof Error ? e.message : String(e) });
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
stop: () => server.stop(),
|
|
147
|
+
hostname,
|
|
148
|
+
port,
|
|
149
|
+
};
|
|
150
|
+
}
|
package/src/kerror.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RuntimeKError — thrown by @k9o/extension-runtime on any platform error.
|
|
3
|
+
*
|
|
4
|
+
* Per (throw-on-error for TypeScript/JavaScript), every non-2xx
|
|
5
|
+
* platform response is surfaced as a RuntimeKError. Callers check
|
|
6
|
+
* `e instanceof KError` (the exported alias) and inspect `e.code`.
|
|
7
|
+
*/
|
|
8
|
+
export class RuntimeKError extends Error {
|
|
9
|
+
readonly code: string;
|
|
10
|
+
readonly context: Record<string, unknown>;
|
|
11
|
+
readonly recommendation: Record<string, unknown> | null;
|
|
12
|
+
|
|
13
|
+
constructor(
|
|
14
|
+
code: string,
|
|
15
|
+
message: string,
|
|
16
|
+
context: Record<string, unknown> = {},
|
|
17
|
+
recommendation: Record<string, unknown> | null = null,
|
|
18
|
+
) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = "KError";
|
|
21
|
+
this.code = code;
|
|
22
|
+
this.context = context;
|
|
23
|
+
this.recommendation = recommendation;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Thrown when the gateway answers a direct record write with 202 `pending_approval`: a project approval policy
|
|
29
|
+
* queued the change, so it is NOT applied. `proposalId` is the approval case a checker decides in Approvals.
|
|
30
|
+
*/
|
|
31
|
+
export class QueuedWriteError extends RuntimeKError {
|
|
32
|
+
readonly proposalId: string | null;
|
|
33
|
+
|
|
34
|
+
constructor(operation: string, collection: string, proposalId: string | null) {
|
|
35
|
+
super(
|
|
36
|
+
"EXTENSION_WRITE_QUEUED",
|
|
37
|
+
`documents.${operation} on '${collection}' was queued for approval, not applied`,
|
|
38
|
+
{ collection, operation, proposalId },
|
|
39
|
+
);
|
|
40
|
+
this.proposalId = proposalId;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Exported alias — extension authors catch `KError` examples. */
|
|
45
|
+
export { RuntimeKError as KError };
|
|
@@ -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
|
+
}
|