@theoklitosbam7/verdict-kit 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 +21 -0
- package/README.md +625 -2
- package/config/routing/engineering.action-risk.consensus.v1.json +16 -0
- package/config/routing/engineering.task-route.cascade.v1.json +21 -0
- package/dist/action-policy.d.ts +104 -0
- package/dist/action-policy.js +173 -0
- package/dist/cache.d.ts +17 -0
- package/dist/cache.js +139 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +142 -0
- package/dist/concurrency.d.ts +12 -0
- package/dist/concurrency.js +110 -0
- package/dist/config.d.ts +61 -0
- package/dist/config.js +247 -0
- package/dist/decision.d.ts +75 -0
- package/dist/decision.js +278 -0
- package/dist/engine.d.ts +63 -0
- package/dist/engine.js +79 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +19 -0
- package/dist/http.d.ts +18 -0
- package/dist/http.js +140 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +14 -0
- package/dist/package-info.d.ts +1 -0
- package/dist/package-info.js +5 -0
- package/dist/policy/evaluate.d.ts +7 -0
- package/dist/policy/evaluate.js +39 -0
- package/dist/policy/events.d.ts +32 -0
- package/dist/policy/events.js +31 -0
- package/dist/policy/payload.d.ts +6 -0
- package/dist/policy/payload.js +11 -0
- package/dist/policy/registry.d.ts +22 -0
- package/dist/policy/registry.js +89 -0
- package/dist/policy/schema.d.ts +198 -0
- package/dist/policy/schema.js +112 -0
- package/dist/policy/scope.d.ts +5 -0
- package/dist/policy/scope.js +120 -0
- package/dist/probability.d.ts +1 -0
- package/dist/probability.js +3 -0
- package/dist/providers/discovery.d.ts +10 -0
- package/dist/providers/discovery.js +113 -0
- package/dist/providers/index.d.ts +56 -0
- package/dist/providers/index.js +83 -0
- package/dist/providers/ollama.d.ts +12 -0
- package/dist/providers/ollama.js +93 -0
- package/dist/providers/opencode-go.d.ts +3 -0
- package/dist/providers/opencode-go.js +40 -0
- package/dist/providers/system-one.d.ts +21 -0
- package/dist/providers/system-one.js +44 -0
- package/dist/providers/typesafe.d.ts +3 -0
- package/dist/providers/typesafe.js +36 -0
- package/dist/public.d.ts +5 -0
- package/dist/public.js +5 -0
- package/dist/response.d.ts +6 -0
- package/dist/response.js +104 -0
- package/dist/routing/cascade.d.ts +112 -0
- package/dist/routing/cascade.js +220 -0
- package/dist/routing/consensus.d.ts +148 -0
- package/dist/routing/consensus.js +367 -0
- package/dist/routing/retry.d.ts +3 -0
- package/dist/routing/retry.js +47 -0
- package/dist/routing/router.d.ts +12 -0
- package/dist/routing/router.js +27 -0
- package/dist/schemas.d.ts +339 -0
- package/dist/schemas.js +283 -0
- package/dist/server.d.ts +42 -0
- package/dist/server.js +416 -0
- package/dist/telemetry/events.d.ts +15 -0
- package/dist/telemetry/events.js +87 -0
- package/dist/telemetry/sink.d.ts +7 -0
- package/dist/telemetry/sink.js +59 -0
- package/dist/templates/registry.d.ts +13 -0
- package/dist/templates/registry.js +100 -0
- package/dist/templates/schema.d.ts +115 -0
- package/dist/templates/schema.js +70 -0
- package/dist/types.d.ts +86 -0
- package/dist/types.js +2 -0
- package/package.json +77 -3
- package/policies/engineering-default.v1.json +36 -0
- package/policies/engineering-strict.v1.json +36 -0
- package/templates/engineering.action-risk.v1.json +32 -0
- package/templates/engineering.compatibility.v1.json +25 -0
- package/templates/engineering.pr-risk.v1.json +26 -0
- package/templates/engineering.security-sensitivity.v1.json +20 -0
- package/templates/engineering.task-route.v1.json +27 -0
- package/templates/engineering.test-depth.v1.json +26 -0
package/dist/decision.js
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { decisionStopError, ProviderQueue } from "./concurrency.js";
|
|
2
|
+
import { DecisionError } from "./errors.js";
|
|
3
|
+
import { isProbability } from "./probability.js";
|
|
4
|
+
import { getProvider, getProviderRegistry } from "./providers/index.js";
|
|
5
|
+
import { isTransient, retryDelayMs, sleep } from "./routing/retry.js";
|
|
6
|
+
import { canServe, planTargets } from "./routing/router.js";
|
|
7
|
+
import { gatePolicySchema } from "./schemas.js";
|
|
8
|
+
import { MAX_BATCH_CONCURRENCY, MAX_BATCH_STATES, } from "./types.js";
|
|
9
|
+
const providerQueues = new WeakMap();
|
|
10
|
+
function withProviderDeadline(provider, context) {
|
|
11
|
+
return {
|
|
12
|
+
signal: context?.signal,
|
|
13
|
+
deadlineAt: Math.min(context?.deadlineAt ?? Infinity, performance.now() + (provider.timeoutMs ?? 30_000)),
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
function runProvider(provider, request, context, finish, onFailure) {
|
|
17
|
+
let queue = providerQueues.get(provider);
|
|
18
|
+
if (!queue) {
|
|
19
|
+
queue = new ProviderQueue(8, 32);
|
|
20
|
+
providerQueues.set(provider, queue);
|
|
21
|
+
}
|
|
22
|
+
return queue.run(context, async (signal) => {
|
|
23
|
+
const result = await provider.decide({ ...request, context: { ...context, signal } });
|
|
24
|
+
signal.throwIfAborted();
|
|
25
|
+
return finish(result);
|
|
26
|
+
}, onFailure);
|
|
27
|
+
}
|
|
28
|
+
const routeDependencies = { sleep, random: Math.random };
|
|
29
|
+
const failedRoutes = new WeakMap();
|
|
30
|
+
export function failedRouteAttempts(error) {
|
|
31
|
+
return error instanceof Error ? failedRoutes.get(error) : undefined;
|
|
32
|
+
}
|
|
33
|
+
export async function routeDecision(request, registry = getProviderRegistry(), deps = routeDependencies) {
|
|
34
|
+
const targets = planTargets(registry, request.provider, request.model);
|
|
35
|
+
const signal = request.context?.signal;
|
|
36
|
+
// Every attempt, backoff and fallback shares the primary provider's request deadline.
|
|
37
|
+
const { deadlineAt = Infinity } = withProviderDeadline(getProvider(targets[0].provider, registry), request.context);
|
|
38
|
+
const { retryAttempts, retryBilled } = registry.routing;
|
|
39
|
+
const attempts = [];
|
|
40
|
+
const record = (attempt) => {
|
|
41
|
+
attempts.push(attempt);
|
|
42
|
+
request.context?.onRouteAttempt?.(attempt);
|
|
43
|
+
};
|
|
44
|
+
let lastError;
|
|
45
|
+
try {
|
|
46
|
+
for (const [index, target] of targets.entries()) {
|
|
47
|
+
const provider = getProvider(target.provider, registry);
|
|
48
|
+
if (index > 0) {
|
|
49
|
+
const stopped = decisionStopError({ signal, deadlineAt });
|
|
50
|
+
if (stopped)
|
|
51
|
+
throw stopped;
|
|
52
|
+
const available = await canServe(provider, target.model, signal, deadlineAt);
|
|
53
|
+
const stoppedAfterProbe = decisionStopError({ signal, deadlineAt });
|
|
54
|
+
if (stoppedAfterProbe)
|
|
55
|
+
throw stoppedAfterProbe;
|
|
56
|
+
if (!available)
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
// A retry to a hosted or unverified target can be billed again, so it needs an opt-in.
|
|
60
|
+
const retries = retryBilled || registry.locality(target.provider, target.model) === "local"
|
|
61
|
+
? retryAttempts
|
|
62
|
+
: 0;
|
|
63
|
+
for (let retry = 0;; retry++) {
|
|
64
|
+
const context = {
|
|
65
|
+
signal,
|
|
66
|
+
deadlineAt: Math.min(deadlineAt, performance.now() + (provider.timeoutMs ?? 30_000)),
|
|
67
|
+
};
|
|
68
|
+
try {
|
|
69
|
+
const result = await runProvider(provider, { ...request, provider: target.provider, model: target.model }, context, (response) => response);
|
|
70
|
+
record({ ...target, outcome: "ok" });
|
|
71
|
+
return { result, attempts };
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
record({
|
|
75
|
+
...target,
|
|
76
|
+
outcome: error instanceof DecisionError ? error.code : "internal",
|
|
77
|
+
});
|
|
78
|
+
lastError = error;
|
|
79
|
+
if (!isTransient(error))
|
|
80
|
+
throw error;
|
|
81
|
+
if (retry >= retries)
|
|
82
|
+
break;
|
|
83
|
+
const delay = retryDelayMs(retry, error, deps.random);
|
|
84
|
+
if (delay === undefined || performance.now() + delay >= deadlineAt)
|
|
85
|
+
break;
|
|
86
|
+
await deps.sleep(delay, signal);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
throw lastError;
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (error instanceof Error && attempts.length > 0)
|
|
94
|
+
failedRoutes.set(error, attempts);
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
export async function decide(request, registry = getProviderRegistry()) {
|
|
99
|
+
return (await routeDecision(request, registry)).result;
|
|
100
|
+
}
|
|
101
|
+
const MAX_BATCH_ITEM_BYTES = 1_048_576;
|
|
102
|
+
const MAX_BATCH_RESULT_BYTES = 4 * MAX_BATCH_ITEM_BYTES;
|
|
103
|
+
function batchErrorCode(error) {
|
|
104
|
+
return error instanceof DecisionError ? error.code : "internal";
|
|
105
|
+
}
|
|
106
|
+
function batchResultBytes(result) {
|
|
107
|
+
try {
|
|
108
|
+
return Buffer.byteLength(JSON.stringify(result));
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
throw new DecisionError("invalid_response", "Decision result could not be serialized.");
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
export async function batchDecide(states, request, concurrency = 4, registry, mode = "fail_fast") {
|
|
115
|
+
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_BATCH_CONCURRENCY) {
|
|
116
|
+
throw new DecisionError("invalid_request", "Batch concurrency must be an integer between 1 and 8.");
|
|
117
|
+
}
|
|
118
|
+
if (states.length > MAX_BATCH_STATES) {
|
|
119
|
+
throw new DecisionError("invalid_request", "A batch can contain at most 20 states.");
|
|
120
|
+
}
|
|
121
|
+
if (!states.length)
|
|
122
|
+
return [];
|
|
123
|
+
const partial = mode === "partial";
|
|
124
|
+
let provider;
|
|
125
|
+
try {
|
|
126
|
+
provider = getProvider(request.provider, registry);
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
if (!partial)
|
|
130
|
+
throw error;
|
|
131
|
+
return states.map((_, index) => ({
|
|
132
|
+
index,
|
|
133
|
+
status: "error",
|
|
134
|
+
code: batchErrorCode(error),
|
|
135
|
+
}));
|
|
136
|
+
}
|
|
137
|
+
const cancelBatch = new AbortController();
|
|
138
|
+
const signal = request.context?.signal
|
|
139
|
+
? AbortSignal.any([request.context.signal, cancelBatch.signal])
|
|
140
|
+
: cancelBatch.signal;
|
|
141
|
+
const context = withProviderDeadline(provider, { ...request.context, signal });
|
|
142
|
+
const completions = Array.from({ length: states.length });
|
|
143
|
+
let next = 0;
|
|
144
|
+
let bytesUsed = 0;
|
|
145
|
+
let firstFailure;
|
|
146
|
+
function stopBatch(error) {
|
|
147
|
+
if (!firstFailure) {
|
|
148
|
+
firstFailure = { error };
|
|
149
|
+
cancelBatch.abort();
|
|
150
|
+
}
|
|
151
|
+
return firstFailure.error;
|
|
152
|
+
}
|
|
153
|
+
function accept(result) {
|
|
154
|
+
const bytes = batchResultBytes(result);
|
|
155
|
+
if (bytes > MAX_BATCH_ITEM_BYTES || (!partial && bytesUsed + bytes > MAX_BATCH_RESULT_BYTES)) {
|
|
156
|
+
throw new DecisionError("output_limit", "Decision batch output limit exceeded (output_limit).");
|
|
157
|
+
}
|
|
158
|
+
if (!partial)
|
|
159
|
+
bytesUsed += bytes;
|
|
160
|
+
return { status: "ok", result, bytes };
|
|
161
|
+
}
|
|
162
|
+
async function worker() {
|
|
163
|
+
while (next < states.length && !decisionStopError(context)) {
|
|
164
|
+
const index = next++;
|
|
165
|
+
try {
|
|
166
|
+
completions[index] = await runProvider(provider, { ...request, state: states[index] }, context, accept, partial ? undefined : stopBatch);
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
if (!partial)
|
|
170
|
+
throw stopBatch(error);
|
|
171
|
+
completions[index] = { status: "error", code: batchErrorCode(error) };
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, states.length) }, worker));
|
|
176
|
+
const stopped = decisionStopError(context);
|
|
177
|
+
if (!partial) {
|
|
178
|
+
if (stopped)
|
|
179
|
+
throw stopped;
|
|
180
|
+
return Array.from(completions, (item) => {
|
|
181
|
+
if (item?.status !== "ok")
|
|
182
|
+
throw new Error("Batch item is missing its result.");
|
|
183
|
+
return item.result;
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
return Array.from(completions, (item, index) => {
|
|
187
|
+
if (!item)
|
|
188
|
+
return { index, status: "error", code: stopped?.code ?? "internal" };
|
|
189
|
+
if (item.status === "error")
|
|
190
|
+
return { index, ...item };
|
|
191
|
+
if (bytesUsed + item.bytes > MAX_BATCH_RESULT_BYTES) {
|
|
192
|
+
return { index, status: "error", code: "output_limit" };
|
|
193
|
+
}
|
|
194
|
+
bytesUsed += item.bytes;
|
|
195
|
+
return { index, status: "ok", result: item.result };
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
export function gate(answers, inputPolicy = {}) {
|
|
199
|
+
const parsedPolicy = gatePolicySchema.safeParse(inputPolicy);
|
|
200
|
+
if (!parsedPolicy.success) {
|
|
201
|
+
return { action: "review", reasons: ["Policy is invalid"] };
|
|
202
|
+
}
|
|
203
|
+
const policy = parsedPolicy.data;
|
|
204
|
+
const hasNoulRule = Object.values(policy.noul ?? {}).some((rule) => rule.block_above !== undefined || rule.review_above !== undefined);
|
|
205
|
+
const hasChoiceRule = Object.values(policy.choice ?? {}).some((rule) => rule.allow !== undefined || rule.review?.length || rule.block?.length);
|
|
206
|
+
if (policy.min_confidence === undefined && !hasNoulRule && !hasChoiceRule) {
|
|
207
|
+
return { action: "review", reasons: ["Policy has no effective rules"] };
|
|
208
|
+
}
|
|
209
|
+
const reasons = [];
|
|
210
|
+
let action = "allow";
|
|
211
|
+
const promote = (target, reason) => {
|
|
212
|
+
if (target === "block" || action === "allow")
|
|
213
|
+
action = target;
|
|
214
|
+
reasons.push(reason);
|
|
215
|
+
};
|
|
216
|
+
if (policy.min_confidence !== undefined && Object.keys(answers).length === 0) {
|
|
217
|
+
promote("review", "Policy requires confidence but no answers were supplied");
|
|
218
|
+
}
|
|
219
|
+
const policyNames = new Set([
|
|
220
|
+
...Object.keys(policy.noul ?? {}),
|
|
221
|
+
...Object.keys(policy.choice ?? {}),
|
|
222
|
+
]);
|
|
223
|
+
for (const name of policyNames) {
|
|
224
|
+
const answer = answers[name];
|
|
225
|
+
if (typeof answer !== "object" || answer === null || Array.isArray(answer)) {
|
|
226
|
+
if (policy.noul?.[name]) {
|
|
227
|
+
promote("review", `${name}: required noul answer is missing or invalid`);
|
|
228
|
+
}
|
|
229
|
+
else {
|
|
230
|
+
promote("review", `${name}: required choice answer is missing`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
for (const [name, answer] of Object.entries(answers)) {
|
|
235
|
+
if (typeof answer !== "object" || answer === null || Array.isArray(answer)) {
|
|
236
|
+
if (policy.min_confidence !== undefined) {
|
|
237
|
+
promote("review", `${name}: confidence is missing or invalid`);
|
|
238
|
+
}
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
if (policy.min_confidence !== undefined) {
|
|
242
|
+
if (!isProbability(answer.confidence)) {
|
|
243
|
+
promote("review", `${name}: confidence is missing or invalid`);
|
|
244
|
+
}
|
|
245
|
+
else if (answer.confidence < policy.min_confidence) {
|
|
246
|
+
promote("review", `${name}: confidence ${answer.confidence} is below ${policy.min_confidence}`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const noulPolicy = policy.noul?.[name];
|
|
250
|
+
if (noulPolicy) {
|
|
251
|
+
if ((answer.type !== undefined && answer.type !== "noul") || !isProbability(answer.noul)) {
|
|
252
|
+
promote("review", `${name}: required noul answer is missing or invalid`);
|
|
253
|
+
}
|
|
254
|
+
else if (noulPolicy.block_above !== undefined && answer.noul >= noulPolicy.block_above) {
|
|
255
|
+
promote("block", `${name}: noul ${answer.noul} >= block threshold ${noulPolicy.block_above}`);
|
|
256
|
+
}
|
|
257
|
+
else if (noulPolicy.review_above !== undefined && answer.noul >= noulPolicy.review_above) {
|
|
258
|
+
promote("review", `${name}: noul ${answer.noul} >= review threshold ${noulPolicy.review_above}`);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const choicePolicy = policy.choice?.[name];
|
|
262
|
+
if (choicePolicy) {
|
|
263
|
+
if ((answer.type !== undefined && answer.type !== "choice") ||
|
|
264
|
+
typeof answer.choice !== "string") {
|
|
265
|
+
promote("review", `${name}: required choice answer is missing or invalid`);
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
const choice = answer.choice;
|
|
269
|
+
if (choicePolicy.block?.includes(choice))
|
|
270
|
+
promote("block", `${name}: choice '${choice}' is blocked`);
|
|
271
|
+
else if (choicePolicy.review?.includes(choice))
|
|
272
|
+
promote("review", `${name}: choice '${choice}' requires review`);
|
|
273
|
+
else if (!choicePolicy.allow?.includes(choice))
|
|
274
|
+
promote("review", `${name}: choice '${choice}' is unknown to the policy`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return { action, reasons };
|
|
278
|
+
}
|
package/dist/engine.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type * as z from "zod/v4";
|
|
2
|
+
import { type ProviderRegistry } from "./providers/index.js";
|
|
3
|
+
import { actionPolicyInputSchema, decideInputSchema } from "./schemas.js";
|
|
4
|
+
import { type TelemetrySink } from "./telemetry/sink.js";
|
|
5
|
+
import { type TemplateRegistry } from "./templates/registry.js";
|
|
6
|
+
import { templateRunInputSchema, templateValidateInputSchema } from "./templates/schema.js";
|
|
7
|
+
export type DecisionEngineOptions = {
|
|
8
|
+
env?: NodeJS.ProcessEnv;
|
|
9
|
+
registry?: ProviderRegistry;
|
|
10
|
+
templates?: TemplateRegistry;
|
|
11
|
+
telemetry?: TelemetrySink;
|
|
12
|
+
};
|
|
13
|
+
export type CallOptions = {
|
|
14
|
+
signal?: AbortSignal;
|
|
15
|
+
};
|
|
16
|
+
export declare function createDecisionEngine(options?: DecisionEngineOptions): {
|
|
17
|
+
decide(input: z.input<typeof decideInputSchema>, call?: CallOptions): Promise<import("./types.js").DecisionResponse>;
|
|
18
|
+
run(input: z.input<typeof templateRunInputSchema>, call?: CallOptions): Promise<{
|
|
19
|
+
template: {
|
|
20
|
+
id: string;
|
|
21
|
+
version: number;
|
|
22
|
+
};
|
|
23
|
+
result: import("./types.js").DecisionResponse;
|
|
24
|
+
}>;
|
|
25
|
+
validate(input: z.input<typeof templateValidateInputSchema>): Promise<{
|
|
26
|
+
template: {
|
|
27
|
+
id: string;
|
|
28
|
+
version: number;
|
|
29
|
+
};
|
|
30
|
+
valid: true;
|
|
31
|
+
message?: undefined;
|
|
32
|
+
} | {
|
|
33
|
+
template: {
|
|
34
|
+
id: string;
|
|
35
|
+
version: number;
|
|
36
|
+
};
|
|
37
|
+
valid: false;
|
|
38
|
+
message: string;
|
|
39
|
+
}>;
|
|
40
|
+
templates(): {
|
|
41
|
+
templates: {
|
|
42
|
+
id: string;
|
|
43
|
+
version: number;
|
|
44
|
+
description: string;
|
|
45
|
+
uri: string;
|
|
46
|
+
}[];
|
|
47
|
+
};
|
|
48
|
+
providers(call?: CallOptions): Promise<{
|
|
49
|
+
default: "ollama" | "opencode-go" | "typesafe";
|
|
50
|
+
providers: {
|
|
51
|
+
ok: boolean;
|
|
52
|
+
detail?: string;
|
|
53
|
+
questionTypes?: Array<import("./types.js").DecisionQuestion["type"]>;
|
|
54
|
+
models?: import("./types.js").ModelReadiness[];
|
|
55
|
+
id: string;
|
|
56
|
+
description: string;
|
|
57
|
+
readiness: import("./types.js").ProviderReadiness;
|
|
58
|
+
}[];
|
|
59
|
+
}>;
|
|
60
|
+
actionPolicy(input: z.input<typeof actionPolicyInputSchema>, call?: CallOptions): Promise<import("./routing/consensus.js").ConsensusPolicyResult | import("./action-policy.js").ActionPolicyResult>;
|
|
61
|
+
createMcpServer(): import("@modelcontextprotocol/server").McpServer;
|
|
62
|
+
};
|
|
63
|
+
export type DecisionEngine = ReturnType<typeof createDecisionEngine>;
|
package/dist/engine.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { evaluateActionPolicy } from "./action-policy.js";
|
|
2
|
+
import { createDecisionCache } from "./cache.js";
|
|
3
|
+
import { readTelemetryConfig } from "./config.js";
|
|
4
|
+
import { DecisionError } from "./errors.js";
|
|
5
|
+
import { readPolicyAdapterMode } from "./policy/events.js";
|
|
6
|
+
import { loadPolicyProfile } from "./policy/registry.js";
|
|
7
|
+
import { createProviderRegistry } from "./providers/index.js";
|
|
8
|
+
import { loadCascadeRegistry } from "./routing/cascade.js";
|
|
9
|
+
import { evaluateConsensusActionPolicy, loadActionPolicyConsensus, loadConsensusRegistry, } from "./routing/consensus.js";
|
|
10
|
+
import { actionPolicyInputSchema, decideInputSchema, jsonValueSchema } from "./schemas.js";
|
|
11
|
+
import { createServer, expandTemplateRun, listProviderStatus, validateTemplateState, } from "./server.js";
|
|
12
|
+
import { createTelemetrySink } from "./telemetry/sink.js";
|
|
13
|
+
import { loadTemplateRegistry } from "./templates/registry.js";
|
|
14
|
+
import { templateRunInputSchema, templateValidateInputSchema } from "./templates/schema.js";
|
|
15
|
+
function parse(schema, input) {
|
|
16
|
+
const parsed = schema.safeParse(input);
|
|
17
|
+
if (!parsed.success) {
|
|
18
|
+
const issue = parsed.error.issues[0];
|
|
19
|
+
const path = issue?.path.length ? `${issue.path.join(".")}: ` : "";
|
|
20
|
+
throw new DecisionError("invalid_request", `Invalid input. ${path}${issue?.message ?? ""}`);
|
|
21
|
+
}
|
|
22
|
+
return parsed.data;
|
|
23
|
+
}
|
|
24
|
+
// Loads every startup setting once, as the MCP server does, and fails with a
|
|
25
|
+
// configuration error before any call when a setting is invalid.
|
|
26
|
+
export function createDecisionEngine(options = {}) {
|
|
27
|
+
const env = options.env ?? process.env;
|
|
28
|
+
const registry = options.registry ?? createProviderRegistry(env);
|
|
29
|
+
const templates = options.templates ?? loadTemplateRegistry(env.DECISION_TEMPLATE_DIR);
|
|
30
|
+
const profile = loadPolicyProfile(env.DECISION_POLICY_PROFILE, templates);
|
|
31
|
+
const mode = readPolicyAdapterMode(env.DECISION_ACTION_POLICY_MODE);
|
|
32
|
+
const cascades = loadCascadeRegistry(templates);
|
|
33
|
+
const consensuses = loadConsensusRegistry(templates);
|
|
34
|
+
const actionConsensus = loadActionPolicyConsensus(env.DECISION_ACTION_POLICY_CONSENSUS, consensuses, profile, registry);
|
|
35
|
+
const telemetry = options.telemetry ?? createTelemetrySink(readTelemetryConfig(env));
|
|
36
|
+
const cache = createDecisionCache(registry.cache);
|
|
37
|
+
return {
|
|
38
|
+
async decide(input, call = {}) {
|
|
39
|
+
const { state, questions, provider, model } = parse(decideInputSchema, input);
|
|
40
|
+
const { result } = await cache.decide({ state: state, questions, provider, model, context: call }, registry);
|
|
41
|
+
return result;
|
|
42
|
+
},
|
|
43
|
+
async run(input, call = {}) {
|
|
44
|
+
const request = parse(templateRunInputSchema, input);
|
|
45
|
+
const { template } = request;
|
|
46
|
+
const { result } = await cache.decide({ ...(await expandTemplateRun(templates, request)), context: call }, registry, `${template.id}@${template.version}`);
|
|
47
|
+
return { template, result };
|
|
48
|
+
},
|
|
49
|
+
validate(input) {
|
|
50
|
+
return validateTemplateState(templates, parse(templateValidateInputSchema, input));
|
|
51
|
+
},
|
|
52
|
+
templates() {
|
|
53
|
+
return { templates: templates.list() };
|
|
54
|
+
},
|
|
55
|
+
providers(call = {}) {
|
|
56
|
+
return listProviderStatus(registry, call.signal);
|
|
57
|
+
},
|
|
58
|
+
async actionPolicy(input, call = {}) {
|
|
59
|
+
const { tool_name, tool_input, scope, provider, model } = parse(actionPolicyInputSchema, input);
|
|
60
|
+
const request = {
|
|
61
|
+
toolName: tool_name,
|
|
62
|
+
toolInput: parse(jsonValueSchema, tool_input),
|
|
63
|
+
scope,
|
|
64
|
+
failureMode: registry.actionPolicyFailureMode,
|
|
65
|
+
provider,
|
|
66
|
+
model,
|
|
67
|
+
context: call,
|
|
68
|
+
};
|
|
69
|
+
if (actionConsensus && provider === undefined && model === undefined) {
|
|
70
|
+
return evaluateConsensusActionPolicy(request, registry, profile, actionConsensus);
|
|
71
|
+
}
|
|
72
|
+
return evaluateActionPolicy(request, registry, profile);
|
|
73
|
+
},
|
|
74
|
+
// Each call returns a new MCP server, with its own cache, for one client connection.
|
|
75
|
+
createMcpServer() {
|
|
76
|
+
return createServer(registry, templates, profile, mode, cascades, consensuses, actionConsensus, telemetry);
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare const decisionErrorCodes: readonly ["cancelled", "timeout", "transport", "http", "invalid_request", "invalid_response", "configuration", "overload", "output_limit"];
|
|
2
|
+
export type DecisionErrorCode = (typeof decisionErrorCodes)[number];
|
|
3
|
+
export declare class DecisionError extends Error {
|
|
4
|
+
readonly code: DecisionErrorCode;
|
|
5
|
+
constructor(code: DecisionErrorCode, message: string);
|
|
6
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export const decisionErrorCodes = [
|
|
2
|
+
"cancelled",
|
|
3
|
+
"timeout",
|
|
4
|
+
"transport",
|
|
5
|
+
"http",
|
|
6
|
+
"invalid_request",
|
|
7
|
+
"invalid_response",
|
|
8
|
+
"configuration",
|
|
9
|
+
"overload",
|
|
10
|
+
"output_limit",
|
|
11
|
+
];
|
|
12
|
+
export class DecisionError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
constructor(code, message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.name = "DecisionError";
|
|
18
|
+
}
|
|
19
|
+
}
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { DecisionError, type DecisionErrorCode } from "./errors.js";
|
|
2
|
+
import type { DecisionContext, JsonValue } from "./types.js";
|
|
3
|
+
export declare class DecisionProviderError extends DecisionError {
|
|
4
|
+
readonly provider: string;
|
|
5
|
+
readonly status?: number | undefined;
|
|
6
|
+
readonly retryAfterMs?: number | undefined;
|
|
7
|
+
constructor(code: DecisionErrorCode, message: string, provider: string, status?: number | undefined, retryAfterMs?: number | undefined);
|
|
8
|
+
}
|
|
9
|
+
type RequestOptions = {
|
|
10
|
+
context?: DecisionContext;
|
|
11
|
+
headers?: Record<string, string>;
|
|
12
|
+
timeoutMs?: number;
|
|
13
|
+
maxRequestBytes?: number;
|
|
14
|
+
maxResponseBytes?: number;
|
|
15
|
+
};
|
|
16
|
+
export declare function postJson(provider: string, url: string, payload: unknown, options?: RequestOptions): Promise<JsonValue>;
|
|
17
|
+
export declare function getJson(provider: string, url: string, options?: Omit<RequestOptions, "maxRequestBytes">): Promise<JsonValue>;
|
|
18
|
+
export {};
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { addAbortListener } from "node:events";
|
|
2
|
+
import { DecisionError } from "./errors.js";
|
|
3
|
+
const DEFAULT_MAX_BODY_BYTES = 1_048_576;
|
|
4
|
+
export class DecisionProviderError extends DecisionError {
|
|
5
|
+
provider;
|
|
6
|
+
status;
|
|
7
|
+
retryAfterMs;
|
|
8
|
+
constructor(code, message, provider, status, retryAfterMs) {
|
|
9
|
+
super(code, message);
|
|
10
|
+
this.provider = provider;
|
|
11
|
+
this.status = status;
|
|
12
|
+
this.retryAfterMs = retryAfterMs;
|
|
13
|
+
this.name = "DecisionProviderError";
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
// Retry-After is either delay seconds or an HTTP date.
|
|
17
|
+
function parseRetryAfter(value) {
|
|
18
|
+
if (value === null)
|
|
19
|
+
return undefined;
|
|
20
|
+
if (/^\d+$/.test(value.trim()))
|
|
21
|
+
return Number(value.trim()) * 1_000;
|
|
22
|
+
const date = Date.parse(value);
|
|
23
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
|
|
24
|
+
}
|
|
25
|
+
async function readLimitedText(provider, response, maxBytes, signal) {
|
|
26
|
+
if (!response.body)
|
|
27
|
+
return "";
|
|
28
|
+
const reader = response.body.getReader();
|
|
29
|
+
const decoder = new TextDecoder();
|
|
30
|
+
const cancel = () => void reader.cancel().catch(() => undefined);
|
|
31
|
+
const abortListener = addAbortListener(signal, cancel);
|
|
32
|
+
let completed = false;
|
|
33
|
+
let total = 0;
|
|
34
|
+
let text = "";
|
|
35
|
+
try {
|
|
36
|
+
for (;;) {
|
|
37
|
+
signal.throwIfAborted();
|
|
38
|
+
const { done, value } = await reader.read();
|
|
39
|
+
signal.throwIfAborted();
|
|
40
|
+
if (done) {
|
|
41
|
+
completed = true;
|
|
42
|
+
return text + decoder.decode();
|
|
43
|
+
}
|
|
44
|
+
total += value.byteLength;
|
|
45
|
+
if (total > maxBytes) {
|
|
46
|
+
throw new DecisionProviderError("invalid_response", `${provider} response exceeded ${maxBytes} bytes.`, provider, response.status);
|
|
47
|
+
}
|
|
48
|
+
text += decoder.decode(value, { stream: true });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
abortListener[Symbol.dispose]();
|
|
53
|
+
if (!completed)
|
|
54
|
+
cancel();
|
|
55
|
+
reader.releaseLock();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
export function postJson(provider, url, payload, options = {}) {
|
|
59
|
+
return requestJson(provider, url, { method: "POST", payload }, options);
|
|
60
|
+
}
|
|
61
|
+
export function getJson(provider, url, options = {}) {
|
|
62
|
+
return requestJson(provider, url, { method: "GET" }, options);
|
|
63
|
+
}
|
|
64
|
+
async function requestJson(provider, url, request, options) {
|
|
65
|
+
const controller = new AbortController();
|
|
66
|
+
const { signal } = controller;
|
|
67
|
+
const callerSignal = options.context?.signal;
|
|
68
|
+
const deadlineAt = Math.min(performance.now() + (options.timeoutMs ?? 30_000), options.context?.deadlineAt ?? Infinity);
|
|
69
|
+
const maxRequestBytes = options.maxRequestBytes ?? DEFAULT_MAX_BODY_BYTES;
|
|
70
|
+
const maxResponseBytes = options.maxResponseBytes ?? DEFAULT_MAX_BODY_BYTES;
|
|
71
|
+
const onCancel = () => controller.abort(new DecisionProviderError("cancelled", `${provider} request was cancelled.`, provider));
|
|
72
|
+
const onTimeout = () => controller.abort(new DecisionProviderError("timeout", `${provider} request timed out.`, provider));
|
|
73
|
+
if (callerSignal?.aborted)
|
|
74
|
+
onCancel();
|
|
75
|
+
signal.throwIfAborted();
|
|
76
|
+
const remainingMs = deadlineAt - performance.now();
|
|
77
|
+
if (!(remainingMs > 0))
|
|
78
|
+
onTimeout();
|
|
79
|
+
signal.throwIfAborted();
|
|
80
|
+
const abortListener = callerSignal && addAbortListener(callerSignal, onCancel);
|
|
81
|
+
const timer = setTimeout(onTimeout, Math.ceil(remainingMs));
|
|
82
|
+
const checkDeadline = () => {
|
|
83
|
+
if (!signal.aborted && performance.now() >= deadlineAt)
|
|
84
|
+
onTimeout();
|
|
85
|
+
signal.throwIfAborted();
|
|
86
|
+
};
|
|
87
|
+
try {
|
|
88
|
+
let body;
|
|
89
|
+
try {
|
|
90
|
+
body = request.method === "POST" ? JSON.stringify(request.payload) : undefined;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// The diagnostic below stays independent of the payload.
|
|
94
|
+
}
|
|
95
|
+
if (request.method === "POST" && body === undefined) {
|
|
96
|
+
throw new DecisionProviderError("invalid_request", `${provider} request could not be serialized as JSON.`, provider);
|
|
97
|
+
}
|
|
98
|
+
if (body !== undefined && Buffer.byteLength(body) > maxRequestBytes) {
|
|
99
|
+
throw new DecisionProviderError("invalid_request", `${provider} request exceeded ${maxRequestBytes} bytes.`, provider);
|
|
100
|
+
}
|
|
101
|
+
checkDeadline();
|
|
102
|
+
const response = await fetch(url, {
|
|
103
|
+
method: request.method,
|
|
104
|
+
headers: {
|
|
105
|
+
...(body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
106
|
+
Accept: "application/json",
|
|
107
|
+
...options.headers,
|
|
108
|
+
},
|
|
109
|
+
body,
|
|
110
|
+
signal,
|
|
111
|
+
redirect: "error",
|
|
112
|
+
});
|
|
113
|
+
if (signal.aborted || performance.now() >= deadlineAt || !response.ok) {
|
|
114
|
+
void response.body?.cancel().catch(() => undefined);
|
|
115
|
+
checkDeadline();
|
|
116
|
+
throw new DecisionProviderError("http", `${provider} request failed with HTTP ${response.status}.`, provider, response.status, parseRetryAfter(response.headers.get("retry-after")));
|
|
117
|
+
}
|
|
118
|
+
const raw = await readLimitedText(provider, response, maxResponseBytes, signal);
|
|
119
|
+
checkDeadline();
|
|
120
|
+
let result;
|
|
121
|
+
try {
|
|
122
|
+
result = JSON.parse(raw);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
throw new DecisionProviderError("invalid_response", `${provider} returned a non-JSON response.`, provider, response.status);
|
|
126
|
+
}
|
|
127
|
+
checkDeadline();
|
|
128
|
+
return result;
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
checkDeadline();
|
|
132
|
+
if (error instanceof DecisionError)
|
|
133
|
+
throw error;
|
|
134
|
+
throw new DecisionProviderError("transport", `${provider} request failed before a valid response was received.`, provider);
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
clearTimeout(timer);
|
|
138
|
+
abortListener?.[Symbol.dispose]();
|
|
139
|
+
}
|
|
140
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
2
|
+
import { createDecisionEngine } from "./engine.js";
|
|
3
|
+
import { DecisionError } from "./errors.js";
|
|
4
|
+
try {
|
|
5
|
+
const engine = createDecisionEngine();
|
|
6
|
+
void serveStdio(() => engine.createMcpServer());
|
|
7
|
+
console.error("Decision Models MCP server running on stdio");
|
|
8
|
+
}
|
|
9
|
+
catch (error) {
|
|
10
|
+
console.error(error instanceof DecisionError
|
|
11
|
+
? error.message
|
|
12
|
+
: "Could not initialize the Decision Models MCP server.");
|
|
13
|
+
process.exitCode = 1;
|
|
14
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const packageVersion: string;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
// src/ and dist/ both sit one level below the package root, and the published package
|
|
3
|
+
// always contains package.json, so the same relative path works from source and build.
|
|
4
|
+
const { version } = createRequire(import.meta.url)("../package.json");
|
|
5
|
+
export const packageVersion = version;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { gate } from "../decision.js";
|
|
2
|
+
import type { DecisionResponse } from "../types.js";
|
|
3
|
+
import type { ResolvedPolicyProfile } from "./registry.js";
|
|
4
|
+
export type EvaluatedPolicyReason = "policy_allow" | "policy_review" | "policy_block" | "required_answer_invalid" | "reduced_context";
|
|
5
|
+
export declare function evaluatePolicyAnswers(answers: DecisionResponse["answers"], { definition, questions }: ResolvedPolicyProfile, reducedContext: boolean): ReturnType<typeof gate> & {
|
|
6
|
+
reasonCode: EvaluatedPolicyReason;
|
|
7
|
+
};
|