@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/src/context.ts ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Sandbox context resolution for @k9o/extension-runtime.
3
+ *
4
+ * The K9O runtime injects context via environment variables for both
5
+ * runtime_tier: "wasm" (Bun WASM sandbox) and runtime_tier: "container"
6
+ * (Firecracker microVM). Extensions call createExtensionClient() with no
7
+ * args and the context is resolved automatically.
8
+ *
9
+ * Env vars injected by the sandbox:
10
+ * K9O_PLUGIN_TOKEN — scoped plugin token
11
+ * K9O_BASE_URL — platform API base, e.g. https://<orgSlug>.api.k9o.io (no path, no version — version in K9o-API-Version header)
12
+ * K9O_PROJECT_ID — bound project ID (e.g. proj_abc123) — data-model identity
13
+ * K9O_PROJECT_SLUG — bound project slug (e.g. my-project) — `@<slug>` URL path position
14
+ * K9O_EXTENSION_SLUG — extension's slug
15
+ * K9O_DEV_MODE — "true" when running inside k9o partner dev
16
+ * K9O_DEV_MODE_KEY_FINGERPRINT — SHA256 fingerprint of the synthetic dev key
17
+ */
18
+
19
+ import type { SandboxContext } from "./types.ts";
20
+
21
+ export function resolveContext(override?: Partial<SandboxContext>): SandboxContext {
22
+ const pluginToken =
23
+ override?.pluginToken ?? process.env["K9O_PLUGIN_TOKEN"] ?? "";
24
+ const baseUrl =
25
+ override?.baseUrl ??
26
+ process.env["K9O_BASE_URL"] ??
27
+ "";
28
+ const projectId =
29
+ override?.projectId ?? process.env["K9O_PROJECT_ID"] ?? "";
30
+ const projectSlug =
31
+ override?.projectSlug ?? process.env["K9O_PROJECT_SLUG"] ?? "";
32
+ const extensionSlug =
33
+ override?.extensionSlug ?? process.env["K9O_EXTENSION_SLUG"] ?? "";
34
+ const devMode =
35
+ override?.devMode ?? (process.env["K9O_DEV_MODE"] === "true" ? true : undefined);
36
+ const devModeKeyFingerprint =
37
+ override?.devModeKeyFingerprint ?? process.env["K9O_DEV_MODE_KEY_FINGERPRINT"];
38
+
39
+ if (!pluginToken) {
40
+ throw new Error(
41
+ "K9O_PLUGIN_TOKEN is not set. The K9O runtime must inject this before extension code runs.",
42
+ );
43
+ }
44
+ if (!baseUrl) {
45
+ throw new Error(
46
+ "K9O_BASE_URL is not set. The K9O runtime must inject this before extension code runs. " +
47
+ "Canonical form: https://<orgSlug>.api.k9o.io (no path segment; version in K9o-API-Version header).",
48
+ );
49
+ }
50
+ if (!projectId) {
51
+ throw new Error(
52
+ "K9O_PROJECT_ID is not set. The K9O runtime must inject this before extension code runs.",
53
+ );
54
+ }
55
+ if (!projectSlug) {
56
+ throw new Error(
57
+ "K9O_PROJECT_SLUG is not set. The K9O runtime must inject this before extension code runs.",
58
+ );
59
+ }
60
+
61
+ return {
62
+ pluginToken,
63
+ baseUrl,
64
+ projectId,
65
+ projectSlug,
66
+ extensionSlug,
67
+ ...(devMode !== undefined ? { devMode } : {}),
68
+ ...(devModeKeyFingerprint !== undefined ? { devModeKeyFingerprint } : {}),
69
+ };
70
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Per-dispatch client context.
3
+ *
4
+ * The plugin token and base URL are minted per invocation and ride the frame `context`, NOT the
5
+ * environment: a client built once at module load from `K9O_PLUGIN_TOKEN` holds a stale token on the
6
+ * second request in a warm sandbox. Handlers build their callback client per request:
7
+ *
8
+ * bff.handle("/x", (req, ctx) => {
9
+ * const k9o = createExtensionClient({ context: ctx.client });
10
+ * ...
11
+ * });
12
+ */
13
+
14
+ import type { SandboxContext } from "./types.ts";
15
+
16
+ /** What a handler receives alongside the request for the current dispatch. */
17
+ export type DispatchContext = {
18
+ /** Gateway-set discriminator for this frame. */
19
+ kind: string;
20
+ /** Override map for `createExtensionClient({ context })`, built from this dispatch's frame context. */
21
+ client: Partial<SandboxContext>;
22
+ /** Plugin-token expiry (ISO 8601) when the gateway supplies it. */
23
+ expiresAt?: string;
24
+ };
25
+
26
+ function str(v: unknown): string | undefined {
27
+ return typeof v === "string" && v.length > 0 ? v : undefined;
28
+ }
29
+
30
+ /**
31
+ * Build the per-dispatch context from the frame's `context`. The plugin token MUST come from the
32
+ * frame; there is no env fallback here, so a missing token is an error rather than a stale one.
33
+ * `baseUrl`, `projectId` and `projectSlug` are taken from the frame when the gateway supplies them
34
+ * and otherwise fall back to the sandbox env in `createExtensionClient`.
35
+ */
36
+ export function dispatchContextFromFrame(frameContext: unknown): DispatchContext {
37
+ if (frameContext === null || typeof frameContext !== "object" || Array.isArray(frameContext)) {
38
+ throw new Error("dispatch context missing: the frame carries no context object");
39
+ }
40
+ const c = frameContext as Record<string, unknown>;
41
+ const pluginToken = str(c["pluginToken"]);
42
+ if (pluginToken === undefined) throw new Error("dispatch context has no pluginToken");
43
+ const client: Partial<SandboxContext> = { pluginToken };
44
+ const baseUrl = str(c["baseUrl"]);
45
+ const projectId = str(c["projectId"]);
46
+ const projectSlug = str(c["projectSlug"]);
47
+ const extensionSlug = str(c["extensionSlug"]);
48
+ if (baseUrl !== undefined) client.baseUrl = baseUrl;
49
+ if (projectId !== undefined) client.projectId = projectId;
50
+ if (projectSlug !== undefined) client.projectSlug = projectSlug;
51
+ if (extensionSlug !== undefined) client.extensionSlug = extensionSlug;
52
+ const expiresAt = str(c["expiresAt"]);
53
+ return {
54
+ kind: String(c["kind"] ?? ""),
55
+ client,
56
+ ...(expiresAt !== undefined ? { expiresAt } : {}),
57
+ };
58
+ }
package/src/guards.ts ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Type narrowing helpers for RuntimeKError ergonomics.
3
+ *
4
+ * Extension authors catch errors from k9o.* calls and use these helpers
5
+ * to narrow the error type before inspecting `e.code`:
6
+ *
7
+ * try {
8
+ * const docs = await k9o.documents.read("orders");
9
+ * } catch (e) {
10
+ * if (isKError(e) && e.code === "EXTENSION_PERMISSION_DENIED") {
11
+ * // handle gracefully
12
+ * }
13
+ * throw e;
14
+ * }
15
+ */
16
+
17
+ import { RuntimeKError } from "./kerror.ts";
18
+
19
+ /** Returns true when `e` is a RuntimeKError instance. */
20
+ export function isKError(e: unknown): e is RuntimeKError {
21
+ return e instanceof RuntimeKError;
22
+ }
23
+
24
+ /**
25
+ * Asserts that `e` is a RuntimeKError.
26
+ * Throws `TypeError` if not — use in contexts where a KError is
27
+ * structurally guaranteed and a non-KError indicates a programming error.
28
+ */
29
+ export function assertKError(e: unknown): asserts e is RuntimeKError {
30
+ if (!(e instanceof RuntimeKError)) {
31
+ throw new TypeError(
32
+ `Expected KError but received: ${e instanceof Error ? e.message : String(e)}`,
33
+ );
34
+ }
35
+ }
package/src/http.ts ADDED
@@ -0,0 +1,164 @@
1
+ /**
2
+ * HTTP transport for the @k9o/extension-runtime runtime SDK.
3
+ *
4
+ * Wraps fetch with:
5
+ * - Bearer token injection (scoped plugin token)
6
+ * - JSON request serialisation + response deserialisation
7
+ * - RuntimeKError throw on any non-2xx response
8
+ *
9
+ * `fetchFn` is dependency-injected so tests supply a mock without monkey-
10
+ * patching globalThis.fetch.
11
+ */
12
+
13
+ import { bytesToBase64 } from "./base64.ts";
14
+ import { RuntimeKError } from "./kerror.ts";
15
+ import type { ApiResponse, KErrorPayload } from "./types.ts";
16
+
17
+ export type FetchFn = typeof globalThis.fetch;
18
+
19
+ export type Transport = {
20
+ get<T>(path: string): Promise<ApiResponse<T>>;
21
+ /**
22
+ * `extraHeaders` — for the rare route that requires a caller-supplied credential
23
+ * OUTSIDE the standard Authorization bearer (e.g.'s
24
+ * `X-K9O-Compliance-Delegate`). Never used to override Authorization/Content-Type/
25
+ * Accept — those stay platform-controlled; extraHeaders is additive only.
26
+ */
27
+ post<T>(path: string, body?: unknown, extraHeaders?: Record<string, string>): Promise<ApiResponse<T>>;
28
+ /** A POST that also reports the HTTP status, for the route whose 201 and 200 mean different things. */
29
+ postWithStatus<T>(path: string, body?: unknown): Promise<{ status: number; body: ApiResponse<T> }>;
30
+ patch<T>(path: string, body?: unknown): Promise<ApiResponse<T>>;
31
+ delete_(path: string): Promise<void>;
32
+ /** Raw fetch through the platform egress proxy — returns the platform-proxied Response. */
33
+ proxyFetch(
34
+ projectSlug: string,
35
+ extensionSlug: string,
36
+ url: string,
37
+ options?: RequestInit,
38
+ ): Promise<Response>;
39
+ };
40
+
41
+ /**
42
+ * Encode a `fetch` request body for the JSON envelope the egress proxy receives.
43
+ * Strings pass through unchanged. Binary bodies are base64-encoded and flagged with
44
+ * `bodyEncoding: "base64"` so the proxy can restore the exact bytes; a plain `JSON.stringify`
45
+ * of a `Uint8Array` silently produces `{"0":1,...}`. Body types that cannot be carried
46
+ * faithfully (streams, Blob, FormData) throw instead of being corrupted.
47
+ */
48
+ export function encodeProxyBody(
49
+ body: RequestInit["body"],
50
+ ): { body?: string; bodyEncoding?: "base64" } {
51
+ if (body === undefined || body === null) return {};
52
+ if (typeof body === "string") return { body };
53
+ if (body instanceof URLSearchParams) return { body: body.toString() };
54
+ if (body instanceof ArrayBuffer) return { body: bytesToBase64(new Uint8Array(body)), bodyEncoding: "base64" };
55
+ if (ArrayBuffer.isView(body)) {
56
+ return { body: bytesToBase64(new Uint8Array(body.buffer, body.byteOffset, body.byteLength)), bodyEncoding: "base64" };
57
+ }
58
+ throw new TypeError(
59
+ "k9o.fetch supports string, URLSearchParams, ArrayBuffer and typed-array request bodies; convert Blob, FormData and streams to bytes first",
60
+ );
61
+ }
62
+
63
+ /** Response header the egress proxy sets on every pass-through of an upstream response. */
64
+ export const EGRESS_PROXIED_HEADER = "x-k9o-egress";
65
+
66
+ export function createTransport(
67
+ baseUrl: string,
68
+ pluginToken: string,
69
+ fetchFn: FetchFn = globalThis.fetch,
70
+ ): Transport {
71
+ const headers = (): Record<string, string> => ({
72
+ Authorization: `Bearer ${pluginToken}`,
73
+ "Content-Type": "application/json",
74
+ Accept: "application/json",
75
+ });
76
+
77
+ async function requestWithStatus<T>(
78
+ method: string,
79
+ path: string,
80
+ body?: unknown,
81
+ extraHeaders?: Record<string, string>,
82
+ ): Promise<{ status: number; body: T }> {
83
+ const url = `${baseUrl}${path}`;
84
+ const init: RequestInit = {
85
+ method,
86
+ headers: extraHeaders === undefined ? headers() : { ...headers(), ...extraHeaders },
87
+ };
88
+ if (body !== undefined) {
89
+ init.body = JSON.stringify(body);
90
+ }
91
+ const res = await fetchFn(url, init);
92
+ if (!res.ok) {
93
+ const err = (await res.json().catch(() => ({
94
+ code: "UNKNOWN_ERROR",
95
+ message: `HTTP ${res.status}`,
96
+ context: {},
97
+ recommendation: null,
98
+ }))) as KErrorPayload;
99
+ throw new RuntimeKError(err.code, err.message, err.context, err.recommendation);
100
+ }
101
+ if (res.status === 204) {
102
+ return { status: 204, body: undefined as T };
103
+ }
104
+ return { status: res.status, body: (await res.json()) as T };
105
+ }
106
+
107
+ async function request<T>(
108
+ method: string,
109
+ path: string,
110
+ body?: unknown,
111
+ extraHeaders?: Record<string, string>,
112
+ ): Promise<T> {
113
+ return (await requestWithStatus<T>(method, path, body, extraHeaders)).body;
114
+ }
115
+
116
+ return {
117
+ get: <T>(path: string) => request<ApiResponse<T>>("GET", path),
118
+ post: <T>(path: string, body?: unknown, extraHeaders?: Record<string, string>) =>
119
+ request<ApiResponse<T>>("POST", path, body, extraHeaders),
120
+ postWithStatus: <T>(path: string, body?: unknown) =>
121
+ requestWithStatus<ApiResponse<T>>("POST", path, body),
122
+ patch: <T>(path: string, body?: unknown) =>
123
+ request<ApiResponse<T>>("PATCH", path, body),
124
+ delete_: (path: string) => request<void>("DELETE", path),
125
+
126
+ async proxyFetch(projectSlug, extensionSlug, url, options) {
127
+ const proxyPath = `/@${projectSlug}/extensions/${extensionSlug}/egress`;
128
+ // Headers may be a `Headers` instance or tuple array; JSON.stringify would drop both.
129
+ // `forEach`, not `Object.fromEntries(headers)`: a consumer compiling with lib DOM but not DOM.Iterable
130
+ // (k9o-salesforce) cannot iterate a `Headers`, and the SDK source is typechecked in the consumer.
131
+ let headerRecord: Record<string, string> | undefined;
132
+ if (options?.headers !== undefined) {
133
+ headerRecord = {};
134
+ const target = headerRecord;
135
+ new Headers(options.headers).forEach((value, key) => {
136
+ target[key] = value;
137
+ });
138
+ }
139
+ const proxyBody = {
140
+ url,
141
+ method: options?.method ?? "GET",
142
+ headers: headerRecord,
143
+ ...encodeProxyBody(options?.body),
144
+ };
145
+ const res = await fetchFn(`${baseUrl}${proxyPath}`, {
146
+ method: "POST",
147
+ headers: headers(),
148
+ body: JSON.stringify(proxyBody),
149
+ });
150
+ // The proxy marks every pass-through of an UPSTREAM response with `x-k9o-egress: proxied`, so an
151
+ // upstream 4xx/5xx (an S3 SlowDown, a vendor 500) reaches the caller with its own status, body and
152
+ // headers. An unmarked non-2xx/3xx response was produced by the proxy itself (grant or binding
153
+ // denied, SSRF-blocked, timeout, size cap) and is thrown as a KError.
154
+ if (res.headers.get(EGRESS_PROXIED_HEADER) === "proxied" || res.ok) return res;
155
+ const err = (await res.json().catch(() => ({
156
+ code: "EGRESS_PROXY_ERROR",
157
+ message: `Egress proxy returned HTTP ${res.status}`,
158
+ context: {},
159
+ recommendation: null,
160
+ }))) as KErrorPayload;
161
+ throw new RuntimeKError(err.code, err.message, err.context, err.recommendation);
162
+ },
163
+ };
164
+ }
package/src/index.ts ADDED
@@ -0,0 +1,142 @@
1
+ /**
2
+ * @k9o/extension-runtime — runtime SDK for extensions running inside the K9O sandbox.
3
+ *
4
+ * Primary export: `createExtensionClient()` — factory for dependency injection.
5
+ * Convenience export: `k9o` — singleton that reads context from env vars.
6
+ *
7
+ * KError: thrown on any platform error; catch with `instanceof KError`.
8
+ */
9
+
10
+ export { createExtensionClient, type ExtensionClient, type CreateExtensionClientOptions } from "./client.ts";
11
+ export type { BffNamespace, BffHandler, BffRequest, BffResponse, BffOperator } from "./namespaces/bff.ts";
12
+ export type {
13
+ FunctionsNamespace,
14
+ FunctionHandler,
15
+ FunctionInvocationRequest,
16
+ FunctionDispatchResult,
17
+ } from "./namespaces/functions.ts";
18
+ export { routeExtensionInvocation, DISPATCH_KINDS, type DispatchKind, type DiscriminatorDeps, type RefuseReason } from "./bff-hook-discriminator.ts";
19
+ export {
20
+ makeHooks,
21
+ HOOK_EVENTS,
22
+ HookRejectedError,
23
+ type HooksNamespace,
24
+ type HookHandler,
25
+ type HookPayload,
26
+ type MonitorResult,
27
+ type CallDecided,
28
+ type CallDecidedHandler,
29
+ type CallDecidedOutcome,
30
+ } from "./namespaces/hooks.ts";
31
+ export { makeWebhookIngress, type WebhookIngressNamespace, type WebhookHandler, type WebhookDelivery } from "./namespaces/webhook-ingress.ts";
32
+ export { dispatchContextFromFrame, type DispatchContext } from "./dispatch-context.ts";
33
+ export { startInvokeServer, type InvokeServerHandle, type InvokeServerOptions } from "./invoke-server.ts";
34
+ export { toConditions } from "./namespaces/tables.ts";
35
+ export type {
36
+ TablesNamespace,
37
+ TablesUpsertOptions,
38
+ TablesUpdateOptions,
39
+ TablesQueryOptions,
40
+ TablesWriteResult,
41
+ TableRow,
42
+ TableFilter,
43
+ TableFilterOp,
44
+ TableCondition,
45
+ TableOrder,
46
+ } from "./namespaces/tables.ts";
47
+ export type {
48
+ StreamingNamespace,
49
+ StreamingTransport,
50
+ SubscribeOptions,
51
+ } from "./namespaces/streaming.ts";
52
+ export type {
53
+ AgentRuntime,
54
+ AuditEvent,
55
+ AuditReadOptions,
56
+ WriteProposal,
57
+ WriteProposalResult,
58
+ // `GenerateOptions` / `GenerateResult` from agent-runtime aliased to avoid
59
+ // collision with the `k9o.ai.generate()` types in ./types.ts.
60
+ // The binding shape is preserved verbatim on the AgentRuntime interface
61
+ // itself.
62
+ GenerateOptions as AgentGenerateOptions,
63
+ GenerateResult as AgentGenerateResult,
64
+ } from "./namespaces/ai-agent-runtime.ts";
65
+ export { warden_gate, type WardenDecision } from "./warden.ts";
66
+ export type {
67
+ VectorsNamespace,
68
+ VectorRow,
69
+ VectorsUpsertResult,
70
+ VectorSearchQuery,
71
+ VectorSearchResult,
72
+ VectorSearchResultRow,
73
+ } from "./namespaces/vectors.ts";
74
+ export { RuntimeKError as KError, RuntimeKError, QueuedWriteError } from "./kerror.ts";
75
+ export { isKError, assertKError } from "./guards.ts";
76
+ export type { SandboxContext } from "./types.ts";
77
+
78
+ /**
79
+ * Host-theme helpers live in `@k9o/extension-manifest`
80
+ * alongside `iframe-bridge` — the architecturally-correct package for
81
+ * iframe-side helpers. Spec's `@k9o/extension-runtime` import-path mention is
82
+ * a wording slip; the substance is unchanged (canonical authoring import
83
+ * remains `import { createHostTheme } from "@k9o/extension-manifest"`). Mirrored here
84
+ * for spec-import-path compliance now that the workspace dependency is
85
+ * configured — both import paths resolve to the same
86
+ * implementation, not a duplicate.
87
+ */
88
+ export {
89
+ createHostTheme,
90
+ HOST_THEME_PROPOSE_TIMEOUT_MS,
91
+ HOST_THEME_REJECT_REASONS,
92
+ type DocumentSink,
93
+ type HostTheme,
94
+ type HostThemeOptions,
95
+ type ProposeResult,
96
+ type ThemeIntent,
97
+ type ThemeIntentMessage,
98
+ type ThemeRejectReason,
99
+ type ThemeUpdatePayload,
100
+ } from "@k9o/extension-manifest";
101
+ export type { IdentityProviderConfig, IdentityProvidersNamespace, ListIdentityProvidersOptions } from "./namespaces/identity.ts";
102
+ export type {
103
+ Document,
104
+ DocumentFilter,
105
+ Collection,
106
+ AttributeMap,
107
+ IdentityClaims,
108
+ PolicyResult,
109
+ KiboEncryptResult,
110
+ KiboDecryptResult,
111
+ GenerateOptions,
112
+ GenerateResult,
113
+ EmbedOptions,
114
+ EmbedResult,
115
+ WorkflowTriggerResult,
116
+ WorkflowRunStatus,
117
+ Meta,
118
+ ApiResponse,
119
+ CredentialAttestationBundle,
120
+ } from "./types.ts";
121
+ export type {
122
+ CollectionSchema,
123
+ ProtectedColumn,
124
+ CollectionSchemaColumn,
125
+ CollectionSchemaIndex,
126
+ CollectionSchemaRelationship,
127
+ ColumnProtection,
128
+ } from "./namespaces/collections.ts";
129
+ export type { CredentialsNamespace, CredentialSendRequest, CredentialSendResult } from "./namespaces/credentials.ts";
130
+ export type { ComplianceNamespace } from "./namespaces/compliance.ts";
131
+ export type {
132
+ AnalyticsNamespace,
133
+ AnalyticsPartitionConstraint,
134
+ AnalyticsPartitionFilter,
135
+ AnalyticsPartitionScalar,
136
+ AnalyticsReadOptions,
137
+ AnalyticsReadPage,
138
+ AnalyticsReadSchemaColumn,
139
+ AnalyticsWriteOnError,
140
+ AnalyticsWriteOptions,
141
+ AnalyticsWriteResult,
142
+ } from "./namespaces/analytics.ts";
@@ -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 };