@godspeedai/cognate-capabilities 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +11 -2
- package/package.json +31 -4
- package/src/index.ts +3 -0
- package/src/model.ts +90 -0
- package/src/selector.ts +235 -0
- package/src/types.ts +48 -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/README.md
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @godspeedai/cognate-capabilities
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Two-phase capability selection (spec §3.6, §8.2, §17, §30): every `EligibilityRule` filters
|
|
4
|
+
every candidate first, and every (provider, rule) result is recorded. Only the eligible set is
|
|
5
|
+
exposed to an adaptive `Ranker`, which can narrow but never widen it — an unknown, ineligible,
|
|
6
|
+
duplicated, or non-finite ranker entry is dropped, and a missing or throwing ranker falls back to
|
|
7
|
+
deterministic `providerId` order.
|
|
8
|
+
|
|
9
|
+
`recordSelection` / `recordOutcome` make selections and their outcomes durable facts on stream
|
|
10
|
+
`selection-<id>`. `outcomeProjection()` derives a Laplace-smoothed success rate per
|
|
11
|
+
`(capability, provider)`, and `createOutcomeRanker(store)` turns that into a `Ranker` so feedback
|
|
12
|
+
only changes ranking after it is committed and projected (spec §15).
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@godspeedai/cognate-capabilities",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Two-phase capability selection: deterministic eligibility, then contained adaptive ranking with durable explanations (spec §8.2, §17, §30).",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/GodSpeedAI/Cognate.git",
|
|
10
|
+
"directory": "packages/capabilities"
|
|
11
|
+
},
|
|
12
|
+
"engines": {
|
|
13
|
+
"bun": ">=1.4.0"
|
|
14
|
+
},
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"src"
|
|
20
|
+
],
|
|
21
|
+
"exports": {
|
|
22
|
+
".": "./src/index.ts"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@godspeedai/cognate-events": "^0.1.0",
|
|
26
|
+
"@godspeedai/cognate-kernel-api": "^0.1.0",
|
|
27
|
+
"@godspeedai/cognate-projections": "^0.1.0"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@godspeedai/cognate-store-memory": "workspace:*",
|
|
31
|
+
"@godspeedai/cognate-store-sqlite": "workspace:*"
|
|
32
|
+
}
|
|
33
|
+
}
|
package/src/index.ts
ADDED
package/src/model.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Model provider contract (spec §26). Plain types: no LLM SDK is required by the kernel or this package.
|
|
2
|
+
import type { Json } from "@godspeedai/cognate-events";
|
|
3
|
+
import type { CapabilityContract } from "@godspeedai/cognate-kernel-api";
|
|
4
|
+
|
|
5
|
+
export type ModelRole = "system" | "user" | "assistant" | "tool";
|
|
6
|
+
|
|
7
|
+
export interface ModelMessage {
|
|
8
|
+
readonly role: ModelRole;
|
|
9
|
+
readonly content: string;
|
|
10
|
+
/** For role `tool`: the call this message answers. */
|
|
11
|
+
readonly toolCallId?: string;
|
|
12
|
+
/** For role `assistant`: tool calls it made. */
|
|
13
|
+
readonly toolCalls?: readonly ToolCall[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface ToolDefinition {
|
|
17
|
+
readonly name: string;
|
|
18
|
+
readonly description: string;
|
|
19
|
+
/** JSON Schema of the tool input. */
|
|
20
|
+
readonly inputSchema: { readonly [key: string]: Json };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ToolCall {
|
|
24
|
+
readonly id: string;
|
|
25
|
+
readonly name: string;
|
|
26
|
+
readonly arguments: Json;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface ModelRequest {
|
|
30
|
+
readonly messages: readonly ModelMessage[];
|
|
31
|
+
readonly tools?: readonly ToolDefinition[];
|
|
32
|
+
/** Stream ordered progress through the invoking capability context when supported. */
|
|
33
|
+
readonly stream?: boolean;
|
|
34
|
+
/** Request structured JSON output, optionally constrained by a JSON Schema. */
|
|
35
|
+
readonly responseFormat?: { readonly type: "json"; readonly schema?: { readonly [key: string]: Json } };
|
|
36
|
+
readonly maxTokens?: number;
|
|
37
|
+
readonly temperature?: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface ModelResponse {
|
|
41
|
+
readonly message: { readonly role: "assistant"; readonly content: string };
|
|
42
|
+
readonly toolCalls: readonly ToolCall[];
|
|
43
|
+
readonly finishReason: "stop" | "length" | "tool_calls" | "content_filter" | "error";
|
|
44
|
+
readonly usage?: { readonly inputTokens: number; readonly outputTokens: number };
|
|
45
|
+
readonly model: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type ModelDelta =
|
|
49
|
+
| { readonly type: "text"; readonly text: string }
|
|
50
|
+
| { readonly type: "tool_call_start"; readonly callId: string; readonly name: string }
|
|
51
|
+
| { readonly type: "tool_call_args"; readonly callId: string; readonly delta: string }
|
|
52
|
+
| { readonly type: "tool_call_end"; readonly callId: string }
|
|
53
|
+
| { readonly type: "tool_call"; readonly call: ToolCall }
|
|
54
|
+
| { readonly type: "done"; readonly response: ModelResponse };
|
|
55
|
+
|
|
56
|
+
/** Capability flags a provider declares; eligibility filters on them (spec §26, §8.2). */
|
|
57
|
+
export interface ModelFeatures {
|
|
58
|
+
readonly generate: true;
|
|
59
|
+
readonly stream: boolean;
|
|
60
|
+
readonly tool_use: boolean;
|
|
61
|
+
readonly structured_output: boolean;
|
|
62
|
+
readonly multimodal_input: boolean;
|
|
63
|
+
readonly context_limit: number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export class ModelProviderError extends Error {
|
|
67
|
+
override readonly name = "ModelProviderError";
|
|
68
|
+
constructor(
|
|
69
|
+
readonly kind: "unauthorized" | "rate_limited" | "invalid_request" | "unavailable" | "cancelled" | "malformed_response",
|
|
70
|
+
message: string,
|
|
71
|
+
readonly status?: number,
|
|
72
|
+
) {
|
|
73
|
+
super(message);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface ModelProvider {
|
|
78
|
+
/** Provider instance id, e.g. `local` or `openai-compatible:gpt-4o-mini`. */
|
|
79
|
+
readonly id: string;
|
|
80
|
+
readonly model: string;
|
|
81
|
+
readonly features: ModelFeatures;
|
|
82
|
+
generate(request: ModelRequest, signal?: AbortSignal): Promise<ModelResponse>;
|
|
83
|
+
stream(request: ModelRequest, signal?: AbortSignal): AsyncIterable<ModelDelta>;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The capability contract a provider publishes: id `model.generate`, features as attributes. Never includes credentials. */
|
|
87
|
+
export function modelContract(provider: ModelProvider): CapabilityContract {
|
|
88
|
+
const { generate: _generate, ...features } = provider.features;
|
|
89
|
+
return { id: "model.generate", version: "1.0.0", attributes: { ...features, provider: provider.id, model: provider.model } };
|
|
90
|
+
}
|
package/src/selector.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { isCompatible } from "@godspeedai/cognate-kernel-api";
|
|
3
|
+
import type { DurableStore, Json } from "@godspeedai/cognate-events";
|
|
4
|
+
import type { Projection, ProjectionState } from "@godspeedai/cognate-projections";
|
|
5
|
+
import type { Candidate, EligibilityRule, Outcome, Ranker, SelectionDecision, SelectionRequest } from "./types.ts";
|
|
6
|
+
|
|
7
|
+
export interface SelectorOptions {
|
|
8
|
+
readonly rules: readonly EligibilityRule[];
|
|
9
|
+
readonly ranker?: Ranker;
|
|
10
|
+
readonly ids?: () => string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function byProviderIdAsc(a: string, b: string): number {
|
|
14
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Two-phase selection (spec §3.6, §8.2): every rule filters first; the ranker orders only the eligible set.
|
|
19
|
+
* Unknown, duplicate, or non-finite ranker output is ignored; ranker failure falls back to deterministic order
|
|
20
|
+
* (lexicographic providerId). The selected provider is always eligible.
|
|
21
|
+
*/
|
|
22
|
+
export function createSelector(options: SelectorOptions): { select(request: SelectionRequest): Promise<SelectionDecision> } {
|
|
23
|
+
return {
|
|
24
|
+
async select(request: SelectionRequest): Promise<SelectionDecision> {
|
|
25
|
+
const candidates = request.candidates;
|
|
26
|
+
const filters: { providerId: string; ruleId: string; eligible: boolean; reason: string }[] = [];
|
|
27
|
+
const eligibleFlags = new Map<string, boolean>();
|
|
28
|
+
for (const candidate of candidates) eligibleFlags.set(candidate.providerId, true);
|
|
29
|
+
|
|
30
|
+
for (const rule of options.rules) {
|
|
31
|
+
for (const candidate of candidates) {
|
|
32
|
+
const result = rule.evaluate(candidate, request);
|
|
33
|
+
filters.push({ providerId: candidate.providerId, ruleId: rule.id, eligible: result.eligible, reason: result.reason });
|
|
34
|
+
if (!result.eligible) eligibleFlags.set(candidate.providerId, false);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const eligibleCandidates = candidates.filter((c) => eligibleFlags.get(c.providerId) === true);
|
|
39
|
+
const eligible = eligibleCandidates.map((c) => c.providerId);
|
|
40
|
+
|
|
41
|
+
let scores: readonly { readonly providerId: string; readonly score: number }[] = [];
|
|
42
|
+
let selected: string | null = null;
|
|
43
|
+
let rankerId: string | null = options.ranker?.id ?? null;
|
|
44
|
+
let fallback: string | null = null;
|
|
45
|
+
|
|
46
|
+
if (eligible.length === 0) {
|
|
47
|
+
// no eligible candidate: selected stays null, ranker is never called.
|
|
48
|
+
} else if (!options.ranker) {
|
|
49
|
+
fallback = "no ranker";
|
|
50
|
+
selected = [...eligible].sort(byProviderIdAsc)[0]!;
|
|
51
|
+
} else {
|
|
52
|
+
try {
|
|
53
|
+
const raw = await options.ranker.rank(eligibleCandidates, request);
|
|
54
|
+
const seen = new Set<string>();
|
|
55
|
+
const validated: { providerId: string; score: number }[] = [];
|
|
56
|
+
for (const entry of raw) {
|
|
57
|
+
if (!eligibleFlags.get(entry.providerId)) continue; // unknown or not eligible
|
|
58
|
+
if (seen.has(entry.providerId)) continue; // duplicate
|
|
59
|
+
if (!Number.isFinite(entry.score)) continue; // non-finite
|
|
60
|
+
seen.add(entry.providerId);
|
|
61
|
+
validated.push({ providerId: entry.providerId, score: entry.score });
|
|
62
|
+
}
|
|
63
|
+
scores = validated;
|
|
64
|
+
|
|
65
|
+
const ranked = [...validated].sort((a, b) => b.score - a.score || byProviderIdAsc(a.providerId, b.providerId));
|
|
66
|
+
const omitted = eligible.filter((id) => !seen.has(id)).sort(byProviderIdAsc);
|
|
67
|
+
const order = [...ranked.map((s) => s.providerId), ...omitted];
|
|
68
|
+
selected = order[0] ?? null;
|
|
69
|
+
} catch (error) {
|
|
70
|
+
fallback = `ranker failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
71
|
+
scores = [];
|
|
72
|
+
selected = [...eligible].sort(byProviderIdAsc)[0]!;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
selectionId: options.ids ? options.ids() : randomUUID(),
|
|
78
|
+
requirement: request.requirement,
|
|
79
|
+
candidates: candidates.map((c) => c.providerId),
|
|
80
|
+
filters,
|
|
81
|
+
eligible,
|
|
82
|
+
scores,
|
|
83
|
+
selected,
|
|
84
|
+
ranker: rankerId,
|
|
85
|
+
fallback,
|
|
86
|
+
};
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Built-in rule: contract compatibility with the requirement (identity, major version, attributes). */
|
|
92
|
+
export const compatibilityRule: EligibilityRule = {
|
|
93
|
+
id: "compatibility",
|
|
94
|
+
evaluate(candidate, request) {
|
|
95
|
+
const ok = isCompatible(request.requirement, candidate.contract);
|
|
96
|
+
return { eligible: ok, reason: ok ? "compatible with requirement" : "incompatible with requirement" };
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
export interface RecordContext {
|
|
101
|
+
readonly tenant: string;
|
|
102
|
+
readonly scopeId: string;
|
|
103
|
+
readonly correlationId: string;
|
|
104
|
+
readonly runId: string | null;
|
|
105
|
+
readonly causationId?: string;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Append `capability.selected` with the full explanation (stream `selection-<selectionId>`). */
|
|
109
|
+
export async function recordSelection(store: DurableStore, decision: SelectionDecision, context: RecordContext): Promise<void> {
|
|
110
|
+
const streamId = `selection-${decision.selectionId}`;
|
|
111
|
+
const expectedVersion = await store.streamVersion(streamId);
|
|
112
|
+
await store.commit({
|
|
113
|
+
appends: [
|
|
114
|
+
{
|
|
115
|
+
streamId,
|
|
116
|
+
expectedVersion,
|
|
117
|
+
events: [
|
|
118
|
+
{
|
|
119
|
+
eventType: "capability.selected",
|
|
120
|
+
schemaVersion: 1,
|
|
121
|
+
occurredAt: new Date().toISOString(),
|
|
122
|
+
tenant: context.tenant,
|
|
123
|
+
correlationId: context.correlationId,
|
|
124
|
+
causationId: context.causationId ?? null,
|
|
125
|
+
runId: context.runId,
|
|
126
|
+
scopeId: context.scopeId,
|
|
127
|
+
payload: decision as unknown as Json,
|
|
128
|
+
},
|
|
129
|
+
],
|
|
130
|
+
},
|
|
131
|
+
],
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Append `capability.outcome` for a recorded selection. Must be durable before it can influence ranking (spec §15). */
|
|
136
|
+
export async function recordOutcome(store: DurableStore, selectionId: string, outcome: Outcome, context: RecordContext): Promise<void> {
|
|
137
|
+
const streamId = `selection-${selectionId}`;
|
|
138
|
+
const expectedVersion = await store.streamVersion(streamId);
|
|
139
|
+
const payload: Json = {
|
|
140
|
+
selectionId,
|
|
141
|
+
success: outcome.success,
|
|
142
|
+
...(outcome.latencyMs !== undefined ? { latencyMs: outcome.latencyMs } : {}),
|
|
143
|
+
...(outcome.cost !== undefined ? { cost: outcome.cost } : {}),
|
|
144
|
+
};
|
|
145
|
+
await store.commit({
|
|
146
|
+
appends: [
|
|
147
|
+
{
|
|
148
|
+
streamId,
|
|
149
|
+
expectedVersion,
|
|
150
|
+
events: [
|
|
151
|
+
{
|
|
152
|
+
eventType: "capability.outcome",
|
|
153
|
+
schemaVersion: 1,
|
|
154
|
+
occurredAt: new Date().toISOString(),
|
|
155
|
+
tenant: context.tenant,
|
|
156
|
+
correlationId: context.correlationId,
|
|
157
|
+
causationId: context.causationId ?? null,
|
|
158
|
+
runId: context.runId,
|
|
159
|
+
scopeId: context.scopeId,
|
|
160
|
+
payload,
|
|
161
|
+
},
|
|
162
|
+
],
|
|
163
|
+
},
|
|
164
|
+
],
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const OUTCOME_PROJECTION_NAME = "capability-outcomes";
|
|
169
|
+
const OUTCOME_PROJECTION_VERSION = "1";
|
|
170
|
+
|
|
171
|
+
interface SelectionStats {
|
|
172
|
+
readonly providerId: string;
|
|
173
|
+
readonly capability: string;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
interface OutcomeStats {
|
|
177
|
+
readonly successes: number;
|
|
178
|
+
readonly total: number;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Cognate-owned outcome ranker (SONA was rejected, ADR-0005): a rebuildable projection over `capability.outcome`
|
|
183
|
+
* events counting each provider's successes and outcomes for a capability id.
|
|
184
|
+
*/
|
|
185
|
+
export function outcomeProjection(): Projection {
|
|
186
|
+
return {
|
|
187
|
+
name: OUTCOME_PROJECTION_NAME,
|
|
188
|
+
version: OUTCOME_PROJECTION_VERSION,
|
|
189
|
+
apply(event, state: ProjectionState) {
|
|
190
|
+
if (event.eventType === "capability.selected") {
|
|
191
|
+
const payload = event.payload as { selectionId: string; selected: string | null; requirement: { capability: string } } | null;
|
|
192
|
+
if (!payload || payload.selected === null) return [];
|
|
193
|
+
const value: SelectionStats = { providerId: payload.selected, capability: payload.requirement.capability };
|
|
194
|
+
return [{ key: `selection:${payload.selectionId}`, value: value as unknown as Json }];
|
|
195
|
+
}
|
|
196
|
+
if (event.eventType === "capability.outcome") {
|
|
197
|
+
const payload = event.payload as { selectionId: string; success: boolean } | null;
|
|
198
|
+
if (!payload) return [];
|
|
199
|
+
const selection = state.get(`selection:${payload.selectionId}`) as unknown as SelectionStats | undefined;
|
|
200
|
+
if (!selection) return [];
|
|
201
|
+
const statsKey = `stats:${selection.capability}:${selection.providerId}`;
|
|
202
|
+
const existing = (state.get(statsKey) as unknown as OutcomeStats | undefined) ?? { successes: 0, total: 0 };
|
|
203
|
+
const updated: OutcomeStats = { successes: existing.successes + (payload.success ? 1 : 0), total: existing.total + 1 };
|
|
204
|
+
return [{ key: statsKey, value: updated as unknown as Json }];
|
|
205
|
+
}
|
|
206
|
+
return [];
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* UCB1 over the eligible set (Auer et al., 2002): `successRate + sqrt(2 ln N / n)`, where `n` is a provider's recorded
|
|
213
|
+
* outcomes and `N` the total across the eligible providers. Untried providers score `Number.MAX_VALUE` (finite, so the
|
|
214
|
+
* selector accepts it) and are tried first; ties fall to provider-id order. Deterministic: a pure function of the
|
|
215
|
+
* projection, so replaying the same outcomes yields the same ranking.
|
|
216
|
+
*/
|
|
217
|
+
export function createOutcomeRanker(store: DurableStore): Ranker {
|
|
218
|
+
return {
|
|
219
|
+
id: "outcome-ranker",
|
|
220
|
+
async rank(eligible: readonly Candidate[], request: SelectionRequest) {
|
|
221
|
+
const capability = request.requirement.capability;
|
|
222
|
+
const stats = await Promise.all(
|
|
223
|
+
eligible.map(async (candidate) => {
|
|
224
|
+
const read = (await store.readProjection(OUTCOME_PROJECTION_NAME, `stats:${capability}:${candidate.providerId}`)) as unknown as OutcomeStats | undefined;
|
|
225
|
+
return { providerId: candidate.providerId, successes: read?.successes ?? 0, total: read?.total ?? 0 };
|
|
226
|
+
}),
|
|
227
|
+
);
|
|
228
|
+
const plays = stats.reduce((sum, s) => sum + s.total, 0);
|
|
229
|
+
return stats.map(({ providerId, successes, total }) => ({
|
|
230
|
+
providerId,
|
|
231
|
+
score: total === 0 ? Number.MAX_VALUE : successes / total + Math.sqrt((2 * Math.log(plays)) / total),
|
|
232
|
+
}));
|
|
233
|
+
},
|
|
234
|
+
};
|
|
235
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Json } from "@godspeedai/cognate-events";
|
|
2
|
+
import type { CapabilityContract, Principal, Requirement } from "@godspeedai/cognate-kernel-api";
|
|
3
|
+
|
|
4
|
+
export interface Candidate {
|
|
5
|
+
readonly providerId: string;
|
|
6
|
+
readonly contract: CapabilityContract;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface SelectionRequest {
|
|
10
|
+
readonly requirement: Requirement;
|
|
11
|
+
readonly candidates: readonly Candidate[];
|
|
12
|
+
readonly principal: Principal;
|
|
13
|
+
readonly tenant: string;
|
|
14
|
+
/** Opaque task context for rankers (e.g. task kind); never used for eligibility. */
|
|
15
|
+
readonly context?: { readonly [key: string]: Json };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** A deterministic eligibility rule (semantic, security, policy, compatibility). Must be pure. */
|
|
19
|
+
export interface EligibilityRule {
|
|
20
|
+
readonly id: string;
|
|
21
|
+
evaluate(candidate: Candidate, request: SelectionRequest): { readonly eligible: boolean; readonly reason: string };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Adaptive ranking; sees only eligible candidates. May be unavailable or misbehave; it can never widen the set. */
|
|
25
|
+
export interface Ranker {
|
|
26
|
+
readonly id: string;
|
|
27
|
+
rank(eligible: readonly Candidate[], request: SelectionRequest): Promise<readonly { readonly providerId: string; readonly score: number }[]>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface SelectionDecision {
|
|
31
|
+
readonly selectionId: string;
|
|
32
|
+
readonly requirement: Requirement;
|
|
33
|
+
readonly candidates: readonly string[];
|
|
34
|
+
readonly filters: readonly { readonly providerId: string; readonly ruleId: string; readonly eligible: boolean; readonly reason: string }[];
|
|
35
|
+
readonly eligible: readonly string[];
|
|
36
|
+
readonly scores: readonly { readonly providerId: string; readonly score: number }[];
|
|
37
|
+
/** `null` when no candidate is eligible. */
|
|
38
|
+
readonly selected: string | null;
|
|
39
|
+
readonly ranker: string | null;
|
|
40
|
+
/** Why deterministic ordering was used instead of the ranker, if it was. */
|
|
41
|
+
readonly fallback: string | null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface Outcome {
|
|
45
|
+
readonly success: boolean;
|
|
46
|
+
readonly latencyMs?: number;
|
|
47
|
+
readonly cost?: number;
|
|
48
|
+
}
|