@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.
Files changed (40) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +166 -2
  4. package/package.json +30 -4
  5. package/src/base64.ts +11 -0
  6. package/src/bff-hook-discriminator.ts +72 -0
  7. package/src/client.ts +148 -0
  8. package/src/context.ts +70 -0
  9. package/src/dispatch-context.ts +58 -0
  10. package/src/guards.ts +35 -0
  11. package/src/http.ts +233 -0
  12. package/src/index.ts +163 -0
  13. package/src/insecure-http.ts +575 -0
  14. package/src/invoke-server.ts +150 -0
  15. package/src/kerror.ts +45 -0
  16. package/src/namespaces/ai-agent-runtime.ts +170 -0
  17. package/src/namespaces/ai.ts +56 -0
  18. package/src/namespaces/analytics.ts +122 -0
  19. package/src/namespaces/attributes.ts +34 -0
  20. package/src/namespaces/audit.ts +92 -0
  21. package/src/namespaces/auth-migrations.ts +176 -0
  22. package/src/namespaces/bff.ts +140 -0
  23. package/src/namespaces/collections.ts +104 -0
  24. package/src/namespaces/compliance.ts +48 -0
  25. package/src/namespaces/credentials.ts +85 -0
  26. package/src/namespaces/documents.ts +128 -0
  27. package/src/namespaces/egress.ts +31 -0
  28. package/src/namespaces/files.ts +96 -0
  29. package/src/namespaces/functions.ts +91 -0
  30. package/src/namespaces/hooks.ts +186 -0
  31. package/src/namespaces/identity.ts +97 -0
  32. package/src/namespaces/kibo.ts +60 -0
  33. package/src/namespaces/policy.ts +50 -0
  34. package/src/namespaces/streaming.ts +80 -0
  35. package/src/namespaces/tables.ts +166 -0
  36. package/src/namespaces/vectors.ts +243 -0
  37. package/src/namespaces/webhook-ingress.ts +98 -0
  38. package/src/namespaces/workflow.ts +65 -0
  39. package/src/types.ts +143 -0
  40. package/src/warden.ts +320 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Kilimanjaro SDK
2
+ Copyright 2026 Formelo Inc.
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md CHANGED
@@ -1,3 +1,167 @@
1
- # Temporary Holding Version
1
+ # @k9o/extension-runtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official runtime client for code running inside a [Kilimanjaro](#73-about-kilimanjaro) extension.
4
+
5
+ Use it from your extension's own code to read and write data, generate text and embeddings, and call the other platform services your manifest has been granted. Every call goes through the platform gateway with your extension's token, so it can do only what the manifest declares.
6
+
7
+ ## Contents
8
+
9
+ **A. Get started**
10
+
11
+ 1. [Links](#1-links)
12
+ 2. [Install](#2-install)
13
+ 3. [Choose the right package](#3-choose-the-right-package)
14
+ 4. [Quick start](#4-quick-start)
15
+
16
+ **B. Use the runtime client**
17
+
18
+ 5. [Calling a service with a credential](#5-calling-a-service-with-a-credential)
19
+
20
+ **C. Troubleshoot**
21
+
22
+ 6. [Errors](#6-errors)
23
+
24
+ **D. Reference**
25
+
26
+ 7. [Appendix](#7-appendix)
27
+ - 7.1 [Requirements](#71-requirements)
28
+ - 7.2 [Namespaces](#72-namespaces)
29
+ - 7.3 [About Kilimanjaro](#73-about-kilimanjaro)
30
+ 8. [License](#8-license)
31
+
32
+ ## A. Get started
33
+
34
+ ### 1. Links
35
+
36
+ - Website: <https://kilimanjaro.dev>
37
+ - Documentation / Developer Hub: <https://docs.kilimanjaro.dev>
38
+ - API: <https://api.k9o.io>
39
+ - Console: <https://console.k9o.io>
40
+ - Open source
41
+ - Platform: <https://github.com/k9o-platform>
42
+ - Community: <https://github.com/k9o-community>
43
+
44
+ ### 2. Install
45
+
46
+ ```bash
47
+ npm install @k9o/extension-runtime
48
+ ```
49
+
50
+ ```bash
51
+ bun add @k9o/extension-runtime
52
+ ```
53
+
54
+ ```bash
55
+ pnpm add @k9o/extension-runtime
56
+ ```
57
+
58
+ The package ships TypeScript source and needs Bun 1.1 or later to run. Declare the grants you need in your manifest with [`@k9o/extension-manifest`](https://www.npmjs.com/package/@k9o/extension-manifest) as a development dependency. `k9o-ext init` creates a project with both already wired.
59
+
60
+ ### 3. Choose the right package
61
+
62
+ | Package | Use it when you are… | Registry | Source |
63
+ | --- | --- | --- | --- |
64
+ | `@k9o/core` | Building a backend service that uses the platform's data, compute, governance and control features. | [npm](https://www.npmjs.com/package/@k9o/core) | [sdk-typescript](https://github.com/k9o-platform/sdk-typescript) |
65
+ | `@k9o/gate` | Implementing sign-up, sign-in, sessions, federation and end-user identity, or verifying a Gate token. | [npm](https://www.npmjs.com/package/@k9o/gate) | [sdk-gate-typescript](https://github.com/k9o-platform/sdk-gate-typescript) |
66
+ | `@k9o/extension-client` | Calling an extension installed in your project, by its slug, through typed bindings. To write an extension, use the extension runtime package instead. | [npm](https://www.npmjs.com/package/@k9o/extension-client) | [sdk-extension-client-typescript](https://github.com/k9o-platform/sdk-extension-client-typescript) |
67
+ | `@k9o/extension-runtime` | Writing an extension: reading and writing data, generating text and embeddings, and calling the platform services the extension's manifest grants. | [npm](https://www.npmjs.com/package/@k9o/extension-runtime) | [sdk-extension-runtime-typescript](https://github.com/k9o-platform/sdk-extension-runtime-typescript) |
68
+ | `@k9o/extension-manifest` | Declaring an extension's manifest: its permissions, surfaces and endpoints, checked the way the platform checks them at registration. | [npm](https://www.npmjs.com/package/@k9o/extension-manifest) | [sdk-extension-manifest-typescript](https://github.com/k9o-platform/sdk-extension-manifest-typescript) |
69
+ | `@k9o/kibo` | Keeping secrets in the vault, or encrypting and decrypting with a key you hold. | [npm](https://www.npmjs.com/package/@k9o/kibo) | [sdk-kibo-typescript](https://github.com/k9o-platform/sdk-kibo-typescript) |
70
+ | `@k9o/barbican` | Checking model input and redacting model output on your own machine, with no account. | [npm](https://www.npmjs.com/package/@k9o/barbican) | [sdk-barbican-typescript](https://github.com/k9o-platform/sdk-barbican-typescript) |
71
+ | `@k9o/cli` | Operating projects from a terminal or CI: migrations, functions, sign-in providers and secrets. | [npm](https://www.npmjs.com/package/@k9o/cli) | [k9o-cli](https://github.com/k9o-platform/k9o-cli) |
72
+
73
+ ### 4. Quick start
74
+
75
+ The manifest needs `p.ai.generate()` for this call.
76
+
77
+ ```ts
78
+ import { createExtensionClient } from "@k9o/extension-runtime";
79
+
80
+ const k9o = createExtensionClient();
81
+
82
+ const result = await k9o.ai.generate("Say hi in three words", { maxTokens: 20 });
83
+ console.log(`Output: ${result.data.content}`);
84
+ ```
85
+
86
+ Illustrative output (a model's reply varies):
87
+
88
+ ```text
89
+ Output: Hi there, friend!
90
+ ```
91
+
92
+ The client reads its project, token and gateway address from the sandbox the platform runs your extension in. In tests, pass them yourself:
93
+
94
+ ```ts
95
+ const k9o = createExtensionClient({ context, fetchFn });
96
+ ```
97
+
98
+ ## B. Use the runtime client
99
+
100
+ ### 5. Calling a service with a credential
101
+
102
+ Declare `p.egress.authenticatedSend("openai-api")` and a `requires` entry for the role. The platform signs the request with the bound credential; your code never sees it.
103
+
104
+ ```ts
105
+ const res = await k9o.credentials.send("openai-api", { method: "GET", url: "https://api.openai.com/v1/models" });
106
+ console.log(`Output: ${res.status} ${new TextDecoder().decode(res.body).length > 0}`);
107
+ ```
108
+
109
+ Illustrative output:
110
+
111
+ ```text
112
+ Output: 200 true
113
+ ```
114
+
115
+ `body` is bytes (decoded from the route's base64). Without the grant, `send` throws the gateway's refusal as a `KError`.
116
+
117
+ ## C. Troubleshoot
118
+
119
+ ### 6. Errors
120
+
121
+ A refusal from the gateway, such as a missing grant, is thrown as a `KError` with a stable `code`.
122
+
123
+ ```ts
124
+ try {
125
+ await k9o.ai.embed("hello");
126
+ } catch (error) {
127
+ console.log(`Output: ${(error as { code: string }).code}`);
128
+ }
129
+ ```
130
+
131
+ Illustrative output, for a manifest without `p.ai.embed()`:
132
+
133
+ ```text
134
+ Output: K9O_ACCESS_DENIED
135
+ ```
136
+
137
+ ## D. Reference
138
+
139
+ ### 7. Appendix
140
+
141
+ #### 7.1 Requirements
142
+
143
+ | Requirement | Version |
144
+ | --- | --- |
145
+ | Bun | 1.1 or newer |
146
+ | `@k9o/extension-manifest` | The same version, as a development dependency |
147
+
148
+ #### 7.2 Namespaces
149
+
150
+ The client exposes these on the object `createExtensionClient()` returns: `documents`, `collections`, `attributes`, `identity`, `policy`, `kibo`, `audit`, `ai`, `workflow`, `fetch`, `credentials`, `bff`, `tables`, `streaming`, `vectors`, `functions`, `hooks`, `webhookIngress`, `compliance`, `analytics`, `files` and `authMigrations`. Each call is allowed only if the manifest holds the matching grant.
151
+
152
+ #### 7.3 About Kilimanjaro
153
+
154
+ Kilimanjaro is a modular developer platform for building secure enterprise applications. You define AI agents, functions and data pipelines
155
+ on the platform. The SDKs let you deploy and invoke them, read and write your data, publish to and subscribe to streams, sign users in, and
156
+ encrypt with keys you hold.
157
+
158
+ It provides four building blocks:
159
+
160
+ - **Keep**: AI security and governance. Guardrails and policy for the agents you run.
161
+ - **Pulse**: data intelligence and real-time stream processing. Streams, analytics and live feeds.
162
+ - **Gate**: customer identity and access management. Sign-in and sessions, and automatic data scoping so a signed-in user reaches only their own data.
163
+ - **Kibo**: cryptographic keys and secrets management. Client-side encryption with keys you hold, and a secrets vault.
164
+
165
+ ### 8. License
166
+
167
+ Apache-2.0 © Formelo Inc. See `LICENSE` and `NOTICE`.
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@k9o/extension-runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.6.0",
4
+ "description": "Runtime client for code running inside a Kilimanjaro extension.",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts"
10
+ },
11
+ "engines": {
12
+ "bun": ">=1.1.0"
13
+ },
14
+ "dependencies": {
15
+ "@k9o/extension-manifest": "1.6.0"
16
+ },
17
+ "license": "Apache-2.0",
18
+ "homepage": "https://kilimanjaro.dev",
19
+ "files": [
20
+ "src",
21
+ "LICENSE",
22
+ "NOTICE",
23
+ "README.md"
24
+ ],
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/k9o-platform/sdk-extension-runtime-typescript.git"
31
+ }
32
+ }
package/src/base64.ts ADDED
@@ -0,0 +1,11 @@
1
+ /** Standard base64 helpers shared by the SDK's wire encodings (egress bodies, kibo plaintext). */
2
+
3
+ export function bytesToBase64(bytes: Uint8Array): string {
4
+ let bin = "";
5
+ for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
6
+ return btoa(bin);
7
+ }
8
+
9
+ export function base64ToBytes(b64: string): Uint8Array {
10
+ return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
11
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Extension invocation discriminator (; hosted here). ONLY the gateway-set `context.kind` selects a route; nothing in `payload` (path,
3
+ * operator, a `kind` field) can. A frame with no context, a non-object context or an unknown kind is
4
+ * refused and never dispatched: the fail-closed backstop that does not depend on the gateway
5
+ * invariant landing perfectly.
6
+ *
7
+ * "bff" -> `payload` is a BffRequest -> k9o.bff.dispatch
8
+ * "hook" -> hook handler named by `context.hookName`
9
+ * "webhook" -> webhook handler registered for `context.webhookPath` (verified HTTP webhook or CometD)
10
+ * "invoke"/"trigger"/"messaging.send" -> the ordinary function path (messaging.send is the platform's provider send)
11
+ */
12
+
13
+ import type { BffRequest, BffResponse } from "./namespaces/bff.ts";
14
+ import type { FunctionDispatchResult, FunctionInvocationRequest } from "./namespaces/functions.ts";
15
+
16
+ export type DispatchResult = FunctionDispatchResult;
17
+
18
+ export const DISPATCH_KINDS = ["bff", "hook", "invoke", "messaging.send", "trigger", "webhook"] as const;
19
+ export type DispatchKind = (typeof DISPATCH_KINDS)[number];
20
+
21
+ export type DiscriminatorDeps = {
22
+ dispatchBff: (req: BffRequest, frame: FunctionInvocationRequest) => Promise<BffResponse>;
23
+ dispatchHook: (hookName: string, frame: FunctionInvocationRequest) => Promise<unknown>;
24
+ dispatchWebhook: (webhookPath: string, frame: FunctionInvocationRequest) => Promise<unknown>;
25
+ dispatchFunction: (frame: FunctionInvocationRequest) => Promise<DispatchResult>;
26
+ };
27
+
28
+ export type RefuseReason = "no_context" | "unknown_kind" | "malformed_bff_payload" | "missing_hook_name" | "missing_webhook_path";
29
+
30
+ function refuse(reason: RefuseReason): DispatchResult {
31
+ return { status: 400, body: { error: "extension invocation refused", reason } };
32
+ }
33
+
34
+ function isObject(v: unknown): v is Record<string, unknown> {
35
+ return v !== null && typeof v === "object" && !Array.isArray(v);
36
+ }
37
+
38
+ export async function routeExtensionInvocation(
39
+ frame: FunctionInvocationRequest,
40
+ deps: DiscriminatorDeps,
41
+ ): Promise<DispatchResult> {
42
+ const ctx = frame.context;
43
+ if (!isObject(ctx)) return refuse("no_context");
44
+ const kind = ctx["kind"];
45
+ if (typeof kind !== "string" || !(DISPATCH_KINDS as readonly string[]).includes(kind)) {
46
+ return refuse("unknown_kind");
47
+ }
48
+ switch (kind as DispatchKind) {
49
+ case "bff": {
50
+ if (!isObject(frame.payload)) return refuse("malformed_bff_payload");
51
+ const resp = await deps.dispatchBff(frame.payload as unknown as BffRequest, frame);
52
+ return { status: 200, body: resp };
53
+ }
54
+ case "hook": {
55
+ const hookName = ctx["hookName"];
56
+ if (typeof hookName !== "string" || hookName.length === 0) return refuse("missing_hook_name");
57
+ const result = await deps.dispatchHook(hookName, frame);
58
+ return { status: 200, body: result ?? null };
59
+ }
60
+ case "webhook": {
61
+ // Routed like "hook": by the gateway-set context only, to a dedicated table, never to bff or hook.
62
+ const webhookPath = ctx["webhookPath"];
63
+ if (typeof webhookPath !== "string" || webhookPath.length === 0) return refuse("missing_webhook_path");
64
+ const result = await deps.dispatchWebhook(webhookPath, frame);
65
+ return { status: 200, body: result ?? null };
66
+ }
67
+ case "invoke":
68
+ case "messaging.send":
69
+ case "trigger":
70
+ return deps.dispatchFunction(frame);
71
+ }
72
+ }
package/src/client.ts ADDED
@@ -0,0 +1,148 @@
1
+ /**
2
+ * createExtensionClient — the @k9o/extension-runtime runtime client factory.
3
+ *
4
+ * Returns the `k9o` object extensions call from inside the WASM/Bun or
5
+ * Firecracker sandbox. Reads sandbox context from env vars by default;
6
+ * accepts an override map for tests and local-dev harness.
7
+ *
8
+ * Usage (in extension runtime code):
9
+ *
10
+ * import { createExtensionClient } from "@k9o/extension-runtime";
11
+ * const k9o = createExtensionClient();
12
+ *
13
+ * const docs = await k9o.documents.read("orders");
14
+ * const user = await k9o.identity.current();
15
+ *
16
+ * The singleton `k9o` export is a pre-configured instance that reads from
17
+ * env on first access — useful for simple extensions that don't need
18
+ * dependency injection.
19
+ */
20
+
21
+ import { resolveContext } from "./context.ts";
22
+ import { createTransport, type FetchFn } from "./http.ts";
23
+ import type { SandboxContext } from "./types.ts";
24
+ import { makeDocuments, type DocumentsNamespace } from "./namespaces/documents.ts";
25
+ import { makeCollections, type CollectionsNamespace } from "./namespaces/collections.ts";
26
+ import { makeAttributes, type AttributesNamespace } from "./namespaces/attributes.ts";
27
+ import { makeIdentity, type IdentityNamespace } from "./namespaces/identity.ts";
28
+ import { makePolicy, type PolicyNamespace } from "./namespaces/policy.ts";
29
+ import { makeKibo, type KiboNamespace } from "./namespaces/kibo.ts";
30
+ import { makeAudit, type AuditNamespace } from "./namespaces/audit.ts";
31
+ import { makeAi, type AiNamespace } from "./namespaces/ai.ts";
32
+ import { makeWorkflow, type WorkflowNamespace } from "./namespaces/workflow.ts";
33
+ import { makeEgress, type EgressNamespace } from "./namespaces/egress.ts";
34
+ import { makeCredentials, type CredentialsNamespace } from "./namespaces/credentials.ts";
35
+ import { makeBff, type BffNamespace } from "./namespaces/bff.ts";
36
+ import { makeTables, type TablesNamespace } from "./namespaces/tables.ts";
37
+ import { makeStreaming, type StreamingNamespace, type StreamingTransport } from "./namespaces/streaming.ts";
38
+ import { makeVectors, type VectorsNamespace } from "./namespaces/vectors.ts";
39
+ import { makeFunctions, type FunctionsNamespace } from "./namespaces/functions.ts";
40
+ import { makeHooks, type HooksNamespace } from "./namespaces/hooks.ts";
41
+ import { makeWebhookIngress, type WebhookIngressNamespace } from "./namespaces/webhook-ingress.ts";
42
+ import { makeCompliance, type ComplianceNamespace } from "./namespaces/compliance.ts";
43
+ import { makeFiles, type FilesNamespace } from "./namespaces/files.ts";
44
+ import { makeAuthMigrations, type AuthMigrationsNamespace } from "./namespaces/auth-migrations.ts";
45
+ import { makeAnalytics, type AnalyticsNamespace } from "./namespaces/analytics.ts";
46
+
47
+ export type ExtensionClient = {
48
+ /** Read, write, and delete documents in project collections. */
49
+ documents: DocumentsNamespace;
50
+ /** Read collection metadata; update mutable collection properties. */
51
+ collections: CollectionsNamespace;
52
+ /** Read and write the per-collection attribute key/value store. */
53
+ attributes: AttributesNamespace;
54
+ /** Propagated calling-user JWT claims. */
55
+ identity: IdentityNamespace;
56
+ /** Maker-Checker policy evaluation */
57
+ policy: PolicyNamespace;
58
+ /** Kibo Vault encrypt / decrypt / rotate per ch08. */
59
+ kibo: KiboNamespace;
60
+ /** Audit-trail event emission */
61
+ audit: AuditNamespace;
62
+ /** Gateway-mediated AI inference */
63
+ ai: AiNamespace;
64
+ /** Workflow trigger and polling per ch07. */
65
+ workflow: WorkflowNamespace;
66
+ /** Manifest-allowlisted egress fetch proxy */
67
+ fetch: EgressNamespace["fetch"];
68
+ /** Send one request signed with a declared credential role; the extension never sees the secret (authenticated_send). */
69
+ credentials: CredentialsNamespace;
70
+ /** BFF endpoint handler registration. */
71
+ bff: BffNamespace;
72
+ /** Extension-owned schema row writes. */
73
+ tables: TablesNamespace;
74
+ /** Async fanout streaming subscriptions via the canonical StreamingTransport interface. */
75
+ streaming: StreamingNamespace;
76
+ /** Pre-computed vector upsert into extension-owned derived collections. */
77
+ vectors: VectorsNamespace;
78
+ /** Platform-tier function handler registration — the SDK counterpart to k9o-init's `:8081` reverse proxy per ch07. */
79
+ functions: FunctionsNamespace;
80
+ /** Lifecycle-hook handler registration: enable, configure, activate, deactivate, purge, monitor, data_export. */
81
+ hooks: HooksNamespace;
82
+ /** Verified inbound webhook and CometD handler registration by declared path. Not `webhooks.subscribe`. */
83
+ webhookIngress: WebhookIngressNamespace;
84
+ /** compliance-export fetch (delegate-token authed) — see namespaces/compliance.ts for the mint/fetch split. */
85
+ compliance: ComplianceNamespace;
86
+ /** Data Bridge inbound write into Pulse Analytics. */
87
+ analytics: AnalyticsNamespace;
88
+ /** Read the bytes of an object in a project storage bucket, in ranges of at most 8 MiB. */
89
+ files: FilesNamespace;
90
+ /** The sign-in migration extension's calls: register a run, read it, and have the platform create its users. */
91
+ authMigrations: AuthMigrationsNamespace;
92
+ };
93
+
94
+ export type CreateExtensionClientOptions = {
95
+ /** Partial context override — useful for tests + local-dev harness. */
96
+ context?: Partial<SandboxContext>;
97
+ /** Override the fetch implementation — useful for tests. */
98
+ fetchFn?: FetchFn;
99
+ /**
100
+ * Streaming transport injection. Production: the platform gateway-backed
101
+ * WebSocket/SSE transport. Dev/test: `createStubStreamingTransport()`
102
+ * from `@k9o/extension-platform`. If omitted, `client.streaming`
103
+ * returns a placeholder that throws on subscribe/publish.
104
+ */
105
+ streamingTransport?: StreamingTransport;
106
+ /**
107
+ * Allow plain `http:` to a host that is not loopback. `true` or `false` wins over `K9O_ALLOW_INSECURE_HTTP`
108
+ * (`1` or `true`). Off by default: a base URL that is `http:` off loopback throws `K9O_INVALID_BASE_URL`.
109
+ */
110
+ allowInsecureHttp?: boolean;
111
+ };
112
+
113
+ export function createExtensionClient(
114
+ options: CreateExtensionClientOptions = {},
115
+ ): ExtensionClient {
116
+ const ctx = resolveContext(options.context);
117
+ const transport = createTransport(
118
+ ctx.baseUrl,
119
+ ctx.pluginToken,
120
+ options.fetchFn,
121
+ options.allowInsecureHttp === undefined ? {} : { allowInsecureHttp: options.allowInsecureHttp },
122
+ );
123
+
124
+ return {
125
+ documents: makeDocuments(transport, ctx.projectSlug),
126
+ collections: makeCollections(transport, ctx.projectSlug),
127
+ attributes: makeAttributes(transport, ctx.projectSlug),
128
+ identity: makeIdentity(transport, ctx.projectSlug),
129
+ policy: makePolicy(transport, ctx.projectSlug),
130
+ kibo: makeKibo(transport, ctx.projectSlug),
131
+ audit: makeAudit(transport, ctx.projectSlug, ctx.extensionSlug),
132
+ ai: makeAi(transport, ctx.projectSlug, ctx.extensionSlug),
133
+ workflow: makeWorkflow(transport, ctx.projectSlug),
134
+ fetch: makeEgress(transport, ctx.projectSlug, ctx.extensionSlug).fetch,
135
+ credentials: makeCredentials(transport, ctx.projectSlug, ctx.extensionSlug),
136
+ bff: makeBff(),
137
+ tables: makeTables(transport, ctx.projectSlug, ctx.extensionSlug),
138
+ streaming: makeStreaming(options.streamingTransport),
139
+ vectors: makeVectors(transport, ctx.projectSlug),
140
+ functions: makeFunctions(),
141
+ hooks: makeHooks(),
142
+ webhookIngress: makeWebhookIngress(),
143
+ compliance: makeCompliance(transport, ctx.projectSlug, ctx.extensionSlug),
144
+ analytics: makeAnalytics(transport, ctx.projectSlug),
145
+ files: makeFiles(transport, ctx.projectSlug),
146
+ authMigrations: makeAuthMigrations(transport, ctx.projectSlug),
147
+ };
148
+ }