@kindgi/capabilities 0.0.0-bootstrap.0 → 0.1.1
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/README.md +112 -2
- package/dist/adapter-factory.d.ts +121 -0
- package/dist/adapter-factory.d.ts.map +1 -0
- package/dist/adapter-factory.js +36 -0
- package/dist/adapter-factory.js.map +1 -0
- package/dist/capability.schema.json +250 -0
- package/dist/define.d.ts +13 -0
- package/dist/define.d.ts.map +1 -0
- package/dist/define.js +45 -0
- package/dist/define.js.map +1 -0
- package/dist/errors.d.ts +67 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +4 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/registry.d.ts +26 -0
- package/dist/registry.d.ts.map +1 -0
- package/dist/registry.js +156 -0
- package/dist/registry.js.map +1 -0
- package/dist/router.d.ts +73 -0
- package/dist/router.d.ts.map +1 -0
- package/dist/router.js +484 -0
- package/dist/router.js.map +1 -0
- package/dist/types.d.ts +498 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +33 -0
- package/dist/types.js.map +1 -0
- package/package.json +52 -4
- package/src/adapter-factory.ts +155 -0
- package/src/capability.schema.json +250 -0
- package/src/define.ts +54 -0
- package/src/errors.ts +74 -0
- package/src/index.ts +51 -0
- package/src/registry.ts +179 -0
- package/src/router.ts +560 -0
- package/src/types.ts +533 -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 describing the origin of the Work and
|
|
141
|
+
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 2026 Kindgi Inc.
|
|
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/README.md
CHANGED
|
@@ -1,3 +1,113 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@kindgi/capabilities`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Capability declarations, a tenant-scoped model-provider registry, and a deterministic router for Kindgi. An agent declares what it needs from a model (features, context window, cost, region, latency, provider or model allow and deny lists) and what it prefers; the router picks a `(provider, model)` pair from the tenant's registered providers that meets every hard requirement and the tenant's policy, ranked by the preferences. The package also defines `ModelProvider`, the provider-neutral contract that model adapters implement.
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
Keep agent definitions independent of any one model vendor. Agents state requirements instead of naming a model; the binding to a concrete model happens at run time, and when nothing qualifies the router returns a structured explanation of which candidate failed which requirement. Providers are registered per tenant, so routing for one tenant never sees another tenant's providers.
|
|
8
|
+
|
|
9
|
+
## Exports
|
|
10
|
+
|
|
11
|
+
- **Declaring requirements**
|
|
12
|
+
- **`Capability`** — `{ kind?, needs, prefer?, budget? }`. `kind` defaults to `DEFAULT_CAPABILITY_KIND` (`'llm-inference'`); `BUILT_IN_CAPABILITY_KINDS` / `BuiltInCapabilityKind` list the well-known kinds, and `CapabilityKind` is an open string.
|
|
13
|
+
- **`Requirement`** — hard constraints: `{ feature }`, `{ contextWindow: { op, value } }`, `{ costPerCall: { op, usd } }` (compared against the model's prompt price per 1K tokens), `{ region }`, `{ p95LatencyMs: { op, value } }`, `{ providers: { allow?, deny? } }`, `{ models: { allow?, deny? } }`. Operators are `ComparisonOp` (`>=`, `>`, `=`, `<=`, `<`) and `UpperBoundOp` (`<=`, `<`) for latency.
|
|
14
|
+
- **`Preference`** — `{ feature, weight }`; `feature` is a `Feature` or a provider attribute such as `'lower-cost'`. Weights add up per candidate and may be negative.
|
|
15
|
+
- **`FEATURES`** / **`Feature`** — the closed feature set: `structured-output`, `vision`, `audio-input`, `audio-output`, `tool-use`, `parallel-tool-use`, `thinking`, `long-context`, `code-execution`, `web-search`, `file-search`, `streaming`, `batch`.
|
|
16
|
+
- **`Budget`** — `maxCostUsd`, `maxTokens`, `maxDurationMs`.
|
|
17
|
+
- **`defineCapability(spec)`** — validates a declaration against the bundled `capability.schema.json` (the same file as in [`@kindgi/specs`](../specs/); its `$id` is exported as `CAPABILITY_SCHEMA_URI`) and returns `Result<Capability, InvalidCapabilityError>`. The schema accepts `needs`, `prefer` and `budget` with every requirement except `models`, so a declaration that sets `kind` or uses a `models` requirement is rejected here even though the type and the router accept it.
|
|
18
|
+
- **Providers**
|
|
19
|
+
- **`ModelProvider`** — `metadata` plus `invoke(input: ModelCallInput): Promise<ModelCallResult>`.
|
|
20
|
+
- **`ProviderMetadata`** — `id`, `region` (`'unspecified'` if not region-scoped), `models`, and optional `attributes`, `description`, `capabilityKind`. One provider is one connection that can expose several models.
|
|
21
|
+
- **`ModelInfo`** — `name`, `contextWindow`, `features`, `cost` (`promptUsdPer1kTokens`, `completionUsdPer1kTokens`), and optional `p95LatencyMs`, `maxOutputTokens`, `description`.
|
|
22
|
+
- **Model call shape** — **`ModelCallInput`** (`model`, `messages`, optional `tools`, `structuredOutput`, `temperature`, `maxOutputTokens`, `abortSignal`), **`ModelMessage`** (roles `system`, `user`, `assistant`, `tool`), **`ModelToolCall`**, **`ModelToolDefinition`**, **`StructuredOutputRequest`**, **`ModelCallResult`** (`message`, `finishReason`, `usage`, `costUsd`, `durationMs`, `provider`), **`UsageCounters`**. Adapters translate these to and from their vendor SDKs.
|
|
23
|
+
- **Registry**
|
|
24
|
+
- **`createProviderRegistry(seed?)`** — in-memory registry. Returns `{ registry, register }`: `register(tenantId, provider)` validates the metadata and returns a `Result` (`invalid-provider`, `duplicate-provider`); `registry` is the `ProviderRegistry` view, whose own `register` throws on the same errors.
|
|
25
|
+
- **`ProviderRegistry`** — `register`, `get`, `list`, `has`, all keyed by `tenantId`, plus optional `hydrate(tenantId)` and `invalidate(tenantId)` for implementations backed by persistent storage.
|
|
26
|
+
- **Routing**
|
|
27
|
+
- **`route(input: RouteInput)`** — returns `Result<RoutingDecision, CapabilityError>`. It expands each provider into one candidate per model, filters by `kind`, `needs` and the tenant policy, ranks by summed preference weight, moves candidates matching `preferredProvider` / `preferredModel` to the front, and breaks ties on `(providerId, modelName)`. The same inputs always produce the same decision.
|
|
28
|
+
- **`RouteInput`** — `capability`, `providers` (already scoped to one tenant, e.g. `registry.list(tenantId)`), and optional `tenantPolicy`, `preferredProvider`, `preferredModel`.
|
|
29
|
+
- **`RoutingDecision`** — the chosen `provider` and `model`, a human-readable `reason`, and `alternates` (`ProviderModelPick[]`) in rank order.
|
|
30
|
+
- **`matchTuples(input)`** — the filtering step on its own: the passing candidates, unranked, or `capability-unsatisfiable` when none pass.
|
|
31
|
+
- **`TenantPolicy`** — `tenantId`, provider and model `allow` / `deny` lists, `regionAllow`, `maxCostPerCallUsd`, `maxTokensPerCall`. An allow list (or `regionAllow`) that is present restricts even when empty: `[]` allows nothing.
|
|
32
|
+
- **Adapter factories** — **`createAdapterFactoryRegistry(seed?)`** returns an **`AdapterFactoryRegistry`** (`register`, `get`, `has`, `list`): a deployment-wide map from adapter id to the code that builds providers. An **`AdapterFactoryEntry`** holds `adapterId`, `capabilityKind`, a `factory` (**`AdapterFactory`**: `(input: AdapterFactoryInput) => ModelProvider`, where `AdapterFactoryInput` is `metadata` plus an optional `resolveApiKey`), and an optional `prepare(params)` that streams **`PrepareEvent`**s (`progress`, `ready`, `error`) for downloads or warm-up. Registering the same id twice throws.
|
|
33
|
+
- **Errors** — **`CapabilityError`**, a union of `InvalidCapabilityError`, `InvalidProviderError`, `DuplicateProviderError`, `CapabilityUnsatisfiableError` and `BudgetExceededError`. `CapabilityUnsatisfiableError.reasons` lists, for each requirement that rejected at least one candidate, the candidates that satisfied it and a structured **`RejectionReason`** for each that did not (`missing-feature`, `context-window-mismatch`, `region-mismatch`, `tenant-denied`, `capability-kind-mismatch`, …).
|
|
34
|
+
|
|
35
|
+
## Example
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { createProviderRegistry, defineCapability, route } from '@kindgi/capabilities';
|
|
39
|
+
import type { ModelProvider } from '@kindgi/capabilities';
|
|
40
|
+
import type { TenantId } from '@kindgi/types';
|
|
41
|
+
|
|
42
|
+
// One connection to a model vendor, exposing two models.
|
|
43
|
+
const acmeLlm: ModelProvider = {
|
|
44
|
+
metadata: {
|
|
45
|
+
id: 'acme-llm',
|
|
46
|
+
region: 'eu-west-1',
|
|
47
|
+
attributes: ['lower-cost'],
|
|
48
|
+
models: [
|
|
49
|
+
{
|
|
50
|
+
name: 'acme-large',
|
|
51
|
+
contextWindow: 200_000,
|
|
52
|
+
features: ['tool-use', 'structured-output', 'streaming'],
|
|
53
|
+
cost: { promptUsdPer1kTokens: 0.003, completionUsdPer1kTokens: 0.015 },
|
|
54
|
+
p95LatencyMs: 4_000,
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
name: 'acme-small',
|
|
58
|
+
contextWindow: 32_000,
|
|
59
|
+
features: ['tool-use'],
|
|
60
|
+
cost: { promptUsdPer1kTokens: 0.0002, completionUsdPer1kTokens: 0.0008 },
|
|
61
|
+
},
|
|
62
|
+
],
|
|
63
|
+
},
|
|
64
|
+
invoke: (input) => callAcmeApi(input), // your vendor SDK call
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const tenantId = process.env.TENANT_ID as TenantId;
|
|
68
|
+
const { registry, register } = createProviderRegistry();
|
|
69
|
+
const registered = register(tenantId, acmeLlm);
|
|
70
|
+
if (registered.kind === 'err') throw new Error(registered.error.message);
|
|
71
|
+
|
|
72
|
+
const capability = defineCapability({
|
|
73
|
+
needs: [{ feature: 'tool-use' }, { contextWindow: { op: '>=', value: 100_000 } }],
|
|
74
|
+
prefer: [{ feature: 'lower-cost', weight: 1 }],
|
|
75
|
+
});
|
|
76
|
+
if (capability.kind === 'err') throw new Error(capability.error.message);
|
|
77
|
+
|
|
78
|
+
const decision = route({
|
|
79
|
+
capability: capability.value,
|
|
80
|
+
providers: registry.list(tenantId),
|
|
81
|
+
tenantPolicy: { tenantId, regionAllow: ['eu-west-1'] },
|
|
82
|
+
});
|
|
83
|
+
if (decision.kind === 'err') {
|
|
84
|
+
if (decision.error.code === 'capability-unsatisfiable') {
|
|
85
|
+
for (const r of decision.error.reasons) {
|
|
86
|
+
console.error(r.requirement, r.rejectingProviders.map((p) => `${p.id}: ${p.reason.code}`));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
process.exit(1);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// acme-small fails the context-window requirement, so this is acme-llm / acme-large.
|
|
93
|
+
const { provider, model } = decision.value;
|
|
94
|
+
const reply = await provider.invoke({
|
|
95
|
+
model: model.name,
|
|
96
|
+
messages: [{ role: 'user', content: 'Summarize clause 4.2 in one sentence.' }],
|
|
97
|
+
});
|
|
98
|
+
console.log(reply.message.content, reply.costUsd);
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Non-goals
|
|
102
|
+
|
|
103
|
+
- **No vendor adapters.** Concrete `ModelProvider` implementations live in adapter packages such as those under [`packages/adapters`](../adapters/).
|
|
104
|
+
- **No cost metering.** `Budget` and `BudgetExceededError` describe limits; nothing in this package tracks spend or enforces them.
|
|
105
|
+
- **No retries or failover.** `route` returns ranked `alternates`; retrying with the next candidate is up to the caller.
|
|
106
|
+
- **No persistence.** Both registries are in-memory. Implementations backed by storage plug in through `ProviderRegistry.hydrate` and `invalidate`.
|
|
107
|
+
|
|
108
|
+
## Related
|
|
109
|
+
|
|
110
|
+
- [`@kindgi/agents`](../agents/) — routes an agent's capability declaration with `route` at the start of every turn.
|
|
111
|
+
- [`@kindgi/specs`](../specs/) — `capability.schema.json`, the wire schema `defineCapability` validates against.
|
|
112
|
+
- [`@kindgi/dev-echo-provider`](../dev-echo-provider/) — a `ModelProvider` for local development.
|
|
113
|
+
- [`@kindgi/types`](../types/) — `TenantId` and `Result`.
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import type { ModelProvider, ProviderMetadata } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* In-process factory-function registry — the code-side counterpart of a
|
|
4
|
+
* persistent adapter registry (`AdapterRegistryBinding` in
|
|
5
|
+
* `@kindgi/api`). A store can hold adapter records but not JavaScript
|
|
6
|
+
* functions, so the runtime keeps a Map keyed by the same adapter id
|
|
7
|
+
* the stored record uses.
|
|
8
|
+
*
|
|
9
|
+
* Populated at boot by deployment code, in lockstep with the adapters
|
|
10
|
+
* it registers in storage. A storage-backed provider registry reads a
|
|
11
|
+
* tenant's stored providers, looks up each one's adapter id here, calls
|
|
12
|
+
* the factory to instantiate a `ModelProvider`, and caches the result.
|
|
13
|
+
*
|
|
14
|
+
* Failure surfaces:
|
|
15
|
+
* - A stored provider references an adapter id with no in-process
|
|
16
|
+
* factory (deployment forgot to register it, or a boot ordering
|
|
17
|
+
* bug) → `get(adapterId)` returns `undefined`, and the provider
|
|
18
|
+
* registry fails the invocation with a clear error.
|
|
19
|
+
* - Factory throws at construction time → propagates through the
|
|
20
|
+
* provider registry to the caller.
|
|
21
|
+
*/
|
|
22
|
+
export interface AdapterFactoryEntry {
|
|
23
|
+
/** Adapter identifier — MUST equal the id of the stored adapter record. */
|
|
24
|
+
readonly adapterId: string;
|
|
25
|
+
/** Capability kind this adapter fulfils (`'llm-inference'`, `'embedding'`, ...). */
|
|
26
|
+
readonly capabilityKind: string;
|
|
27
|
+
readonly factory: AdapterFactory;
|
|
28
|
+
/**
|
|
29
|
+
* Optional download / warmup step. Adapters that need
|
|
30
|
+
* expensive one-time setup (in-process model downloads, ONNX
|
|
31
|
+
* runtime warmup, cache preheating) implement this; adapters that
|
|
32
|
+
* only need config-time construction leave it undefined.
|
|
33
|
+
*
|
|
34
|
+
* Streams `PrepareEvent`s so the caller (HTTP SSE endpoint,
|
|
35
|
+
* console progress bar) can render progress. Framework doesn't
|
|
36
|
+
* cache — implementations decide whether re-invoking `prepare` on
|
|
37
|
+
* an already-prepared adapter is a no-op or a re-check.
|
|
38
|
+
*
|
|
39
|
+
* `params` shape is adapter-specific — the framework passes it
|
|
40
|
+
* through unchanged (e.g. `{model: 'smollm2-360m'}` for
|
|
41
|
+
* in-process).
|
|
42
|
+
*/
|
|
43
|
+
readonly prepare?: (params?: Readonly<Record<string, unknown>>) => AsyncIterable<PrepareEvent>;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Event stream emitted by `AdapterFactoryEntry.prepare()`. Shape kept
|
|
47
|
+
* deliberately open (`message` + optional numeric progress fields)
|
|
48
|
+
* so adapters with different progress models (byte-count download,
|
|
49
|
+
* step-count warmup, cache hit ratio) can populate what they know.
|
|
50
|
+
* Consumers render whichever fields are present.
|
|
51
|
+
*/
|
|
52
|
+
export type PrepareEvent = {
|
|
53
|
+
readonly kind: 'progress';
|
|
54
|
+
readonly message?: string;
|
|
55
|
+
/** Ratio in [0, 1] when known; absent for indeterminate progress. */
|
|
56
|
+
readonly ratio?: number;
|
|
57
|
+
readonly loadedBytes?: number;
|
|
58
|
+
readonly totalBytes?: number;
|
|
59
|
+
readonly file?: string;
|
|
60
|
+
} | {
|
|
61
|
+
readonly kind: 'ready';
|
|
62
|
+
readonly message?: string;
|
|
63
|
+
} | {
|
|
64
|
+
readonly kind: 'error';
|
|
65
|
+
readonly message: string;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Input passed to an adapter factory at instantiation time. The
|
|
69
|
+
* provider registry composes the arguments from persisted state (the
|
|
70
|
+
* stored provider `metadata`) plus a pre-bound `resolveApiKey` closure
|
|
71
|
+
* that reads the tenant-scoped secret store.
|
|
72
|
+
*
|
|
73
|
+
* Adapters that don't need credentials (dev-echo, in-process
|
|
74
|
+
* models) receive no `resolveApiKey` — they ignore the field
|
|
75
|
+
* entirely.
|
|
76
|
+
*/
|
|
77
|
+
export interface AdapterFactoryInput {
|
|
78
|
+
readonly metadata: ProviderMetadata;
|
|
79
|
+
/**
|
|
80
|
+
* How the adapter connects — the provider's adapter-specific,
|
|
81
|
+
* non-secret settings (a cloud project, a base URL), as registered
|
|
82
|
+
* with the provider. Credentials never go here; they come from
|
|
83
|
+
* `resolveApiKey`. Each adapter documents and validates its own keys.
|
|
84
|
+
*/
|
|
85
|
+
readonly config?: AdapterConfig;
|
|
86
|
+
/**
|
|
87
|
+
* Lazy API-key resolver. Adapters that need external
|
|
88
|
+
* credentials pass this into their SDK client construction (or
|
|
89
|
+
* refresh on every invoke, as
|
|
90
|
+
* `@kindgi/adapter-model-anthropic` does).
|
|
91
|
+
*/
|
|
92
|
+
readonly resolveApiKey?: () => Promise<string>;
|
|
93
|
+
/**
|
|
94
|
+
* The fetch for a provider endpoint the registration chose (a base URL).
|
|
95
|
+
* The runtime passes one that refuses the hosts its deployment forbids
|
|
96
|
+
* (`KINDGI_TENANT_HOST_ACCESS`: the cloud metadata endpoints and the
|
|
97
|
+
* server's own host). Absent: the global `fetch`.
|
|
98
|
+
*/
|
|
99
|
+
readonly fetch?: typeof fetch;
|
|
100
|
+
}
|
|
101
|
+
/** An adapter's connection settings: flat, non-secret values. */
|
|
102
|
+
export type AdapterConfig = Readonly<Record<string, string | number | boolean>>;
|
|
103
|
+
export type AdapterFactory = (input: AdapterFactoryInput) => ModelProvider;
|
|
104
|
+
export interface AdapterFactoryRegistry {
|
|
105
|
+
register(entry: AdapterFactoryEntry): void;
|
|
106
|
+
get(adapterId: string): AdapterFactoryEntry | undefined;
|
|
107
|
+
has(adapterId: string): boolean;
|
|
108
|
+
list(): readonly AdapterFactoryEntry[];
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Create an in-memory `AdapterFactoryRegistry`. Global
|
|
112
|
+
* (deployment-scoped) — every tenant reads from the same map because
|
|
113
|
+
* adapter code is code, not user data.
|
|
114
|
+
*
|
|
115
|
+
* Duplicate registrations under the same `adapterId` throw at
|
|
116
|
+
* `register` time; accidental clobber of a running factory would be
|
|
117
|
+
* catastrophic. Deployments call `register` once per shipped adapter
|
|
118
|
+
* at boot.
|
|
119
|
+
*/
|
|
120
|
+
export declare function createAdapterFactoryRegistry(seed?: readonly AdapterFactoryEntry[]): AdapterFactoryRegistry;
|
|
121
|
+
//# sourceMappingURL=adapter-factory.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter-factory.d.ts","sourceRoot":"","sources":["../src/adapter-factory.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAElE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,WAAW,mBAAmB;IAClC,2EAA2E;IAC3E,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,oFAAoF;IACpF,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAC;IACjC;;;;;;;;;;;;;;OAcG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,MAAM,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,KAAK,aAAa,CAAC,YAAY,CAAC,CAAC;CAChG;AAED;;;;;;GAMG;AACH,MAAM,MAAM,YAAY,GACpB;IACE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAC1B,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,qEAAqE;IACrE,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;CACxB,GACD;IAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,GACrD;IAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAEzD;;;;;;;;;GASG;AACH,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,QAAQ,EAAE,gBAAgB,CAAC;IACpC;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,aAAa,CAAC;IAChC;;;;;OAKG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAC/C;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CAC/B;AAED,iEAAiE;AACjE,MAAM,MAAM,aAAa,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC;AAEhF,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,mBAAmB,KAAK,aAAa,CAAC;AAE3E,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,KAAK,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAC3C,GAAG,CAAC,SAAS,EAAE,MAAM,GAAG,mBAAmB,GAAG,SAAS,CAAC;IACxD,GAAG,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC;IAChC,IAAI,IAAI,SAAS,mBAAmB,EAAE,CAAC;CACxC;AAED;;;;;;;;;GASG;AACH,wBAAgB,4BAA4B,CAC1C,IAAI,GAAE,SAAS,mBAAmB,EAAO,GACxC,sBAAsB,CA0BxB"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Copyright (C) 2026 Kindgi Inc.
|
|
3
|
+
/**
|
|
4
|
+
* Create an in-memory `AdapterFactoryRegistry`. Global
|
|
5
|
+
* (deployment-scoped) — every tenant reads from the same map because
|
|
6
|
+
* adapter code is code, not user data.
|
|
7
|
+
*
|
|
8
|
+
* Duplicate registrations under the same `adapterId` throw at
|
|
9
|
+
* `register` time; accidental clobber of a running factory would be
|
|
10
|
+
* catastrophic. Deployments call `register` once per shipped adapter
|
|
11
|
+
* at boot.
|
|
12
|
+
*/
|
|
13
|
+
export function createAdapterFactoryRegistry(seed = []) {
|
|
14
|
+
const entries = new Map();
|
|
15
|
+
function register(entry) {
|
|
16
|
+
if (entries.has(entry.adapterId)) {
|
|
17
|
+
throw new Error(`AdapterFactoryRegistry: "${entry.adapterId}" is already registered. Duplicate adapter registration at boot indicates a wiring bug.`);
|
|
18
|
+
}
|
|
19
|
+
entries.set(entry.adapterId, entry);
|
|
20
|
+
}
|
|
21
|
+
for (const entry of seed)
|
|
22
|
+
register(entry);
|
|
23
|
+
return {
|
|
24
|
+
register,
|
|
25
|
+
get(adapterId) {
|
|
26
|
+
return entries.get(adapterId);
|
|
27
|
+
},
|
|
28
|
+
has(adapterId) {
|
|
29
|
+
return entries.has(adapterId);
|
|
30
|
+
},
|
|
31
|
+
list() {
|
|
32
|
+
return [...entries.values()];
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=adapter-factory.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter-factory.js","sourceRoot":"","sources":["../src/adapter-factory.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAmHjC;;;;;;;;;GASG;AACH,MAAM,UAAU,4BAA4B,CAC1C,OAAuC,EAAE;IAEzC,MAAM,OAAO,GAAG,IAAI,GAAG,EAA+B,CAAC;IAEvD,SAAS,QAAQ,CAAC,KAA0B;QAC1C,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC;YACjC,MAAM,IAAI,KAAK,CACb,4BAA4B,KAAK,CAAC,SAAS,yFAAyF,CACrI,CAAC;QACJ,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC;IAED,KAAK,MAAM,KAAK,IAAI,IAAI;QAAE,QAAQ,CAAC,KAAK,CAAC,CAAC;IAE1C,OAAO;QACL,QAAQ;QACR,GAAG,CAAC,SAAS;YACX,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QAChC,CAAC;QACD,GAAG,CAAC,SAAS;YACX,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QAChC,CAAC;QACD,IAAI;YACF,OAAO,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QAC/B,CAAC;KACF,CAAC;AACJ,CAAC"}
|