@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
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import * as z from "zod/v4";
|
|
3
|
+
import { providerIds } from "../config.js";
|
|
4
|
+
import { effectiveScope } from "../action-policy.js";
|
|
5
|
+
import { decisionStopError } from "../concurrency.js";
|
|
6
|
+
import { routeDecision } from "../decision.js";
|
|
7
|
+
import { DecisionError } from "../errors.js";
|
|
8
|
+
import { evaluatePolicyAnswers } from "../policy/evaluate.js";
|
|
9
|
+
import { projectNonLocalAction } from "../policy/payload.js";
|
|
10
|
+
import { isDecisionModelTool, shouldEvaluateAction } from "../policy/scope.js";
|
|
11
|
+
import { isProbability } from "../probability.js";
|
|
12
|
+
import { decisionOutputSchema, jsonValueSchema, withinPayloadLimit } from "../schemas.js";
|
|
13
|
+
import { templateIdentitySchema } from "../templates/schema.js";
|
|
14
|
+
const memberSchema = z.strictObject({
|
|
15
|
+
provider: z.enum(providerIds),
|
|
16
|
+
model: z.string().min(1).max(256),
|
|
17
|
+
revision: z
|
|
18
|
+
.string()
|
|
19
|
+
.regex(/^[0-9a-f]{12,64}$/)
|
|
20
|
+
.optional(),
|
|
21
|
+
});
|
|
22
|
+
export const consensusProfileSchema = templateIdentitySchema
|
|
23
|
+
.extend({
|
|
24
|
+
template: templateIdentitySchema,
|
|
25
|
+
policy_profile: templateIdentitySchema.optional(),
|
|
26
|
+
members: z.array(memberSchema).min(2).max(4),
|
|
27
|
+
quorum: z.number().int().min(2),
|
|
28
|
+
max_calls: z.number().int().min(2),
|
|
29
|
+
// Every member that answers must agree. Majority voting is not supported.
|
|
30
|
+
agreement: z.literal("unanimous"),
|
|
31
|
+
// A noul answer counts as true at or above this probability.
|
|
32
|
+
noul_threshold: z.number().min(0).max(1),
|
|
33
|
+
// Score answers agree when the highest and lowest differ by at most this amount.
|
|
34
|
+
score_tolerance: z.number().min(0),
|
|
35
|
+
allow_non_local: z.boolean(),
|
|
36
|
+
})
|
|
37
|
+
.refine(({ members, quorum, max_calls }) => quorum <= max_calls &&
|
|
38
|
+
max_calls <= members.length &&
|
|
39
|
+
new Set(members.map(({ provider, model }) => `${provider}:${model}`)).size === members.length);
|
|
40
|
+
export const consensusInputSchema = z
|
|
41
|
+
.strictObject({
|
|
42
|
+
consensus: templateIdentitySchema.describe("Exact ID and version of a trusted consensus profile."),
|
|
43
|
+
state: jsonValueSchema.describe("State for the consensus profile's template."),
|
|
44
|
+
})
|
|
45
|
+
.refine(withinPayloadLimit, { message: "Request payload is too large." });
|
|
46
|
+
export const consensusOutputSchema = z.object({
|
|
47
|
+
consensus: templateIdentitySchema,
|
|
48
|
+
template: templateIdentitySchema,
|
|
49
|
+
status: z.enum(["agreed", "disagreed", "no_quorum"]),
|
|
50
|
+
result: decisionOutputSchema.optional(),
|
|
51
|
+
members: z.array(z.object({
|
|
52
|
+
provider: z.string(),
|
|
53
|
+
model: z.string(),
|
|
54
|
+
outcome: z.string(),
|
|
55
|
+
answers: z.record(z.string(), z.union([z.string(), z.boolean(), z.number()])).optional(),
|
|
56
|
+
})),
|
|
57
|
+
});
|
|
58
|
+
const bundledFiles = [
|
|
59
|
+
new URL("../../config/routing/engineering.action-risk.consensus.v1.json", import.meta.url),
|
|
60
|
+
];
|
|
61
|
+
export function createConsensusRegistry(definitions, templates) {
|
|
62
|
+
const entries = new Map();
|
|
63
|
+
for (const raw of definitions) {
|
|
64
|
+
const parsed = consensusProfileSchema.safeParse(raw);
|
|
65
|
+
if (!parsed.success)
|
|
66
|
+
throw new DecisionError("configuration", "Invalid consensus profile.");
|
|
67
|
+
const definition = parsed.data;
|
|
68
|
+
const key = `${definition.id}@${definition.version}`;
|
|
69
|
+
if (entries.has(key)) {
|
|
70
|
+
throw new DecisionError("configuration", `Duplicate consensus profile ${key}.`);
|
|
71
|
+
}
|
|
72
|
+
let questions;
|
|
73
|
+
try {
|
|
74
|
+
({ questions } = templates.get(definition.template));
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
throw new DecisionError("configuration", `Consensus profile ${key} names an unknown template.`);
|
|
78
|
+
}
|
|
79
|
+
entries.set(key, { definition, questions });
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
get({ id, version }) {
|
|
83
|
+
const entry = entries.get(`${id}@${version}`);
|
|
84
|
+
if (!entry) {
|
|
85
|
+
throw new DecisionError("invalid_request", "Unknown consensus profile ID and version.");
|
|
86
|
+
}
|
|
87
|
+
return structuredClone(entry);
|
|
88
|
+
},
|
|
89
|
+
list() {
|
|
90
|
+
return Array.from(entries.values(), ({ definition: { id, version, template } }) => ({
|
|
91
|
+
id,
|
|
92
|
+
version,
|
|
93
|
+
template,
|
|
94
|
+
})).sort((left, right) => left.id.localeCompare(right.id) || left.version - right.version);
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
export function loadConsensusRegistry(templates) {
|
|
99
|
+
const definitions = bundledFiles.map((file) => {
|
|
100
|
+
try {
|
|
101
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
throw new DecisionError("configuration", "Could not read a bundled consensus profile.");
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
return createConsensusRegistry(definitions, templates);
|
|
108
|
+
}
|
|
109
|
+
// Every member must pass the provider, model and locality rules before any inference starts.
|
|
110
|
+
function checkMembers(definition, registry) {
|
|
111
|
+
for (const { provider, model } of definition.members) {
|
|
112
|
+
registry.getProvider(provider);
|
|
113
|
+
registry.effectiveModel(provider, model);
|
|
114
|
+
const local = registry.locality(provider, model) === "local";
|
|
115
|
+
if (!local && (!definition.allow_non_local || registry.localOnly)) {
|
|
116
|
+
throw new DecisionError("configuration", "The consensus profile names a member that is not an approved local model.");
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function isFatal(error) {
|
|
121
|
+
return (error instanceof DecisionError &&
|
|
122
|
+
(error.code === "cancelled" ||
|
|
123
|
+
error.code === "configuration" ||
|
|
124
|
+
error.code === "invalid_request"));
|
|
125
|
+
}
|
|
126
|
+
// Members run concurrently through the shared provider queues. Members after max_calls
|
|
127
|
+
// are not called.
|
|
128
|
+
async function callMembers(definition, run, propagateFatal = true) {
|
|
129
|
+
const active = definition.members.slice(0, definition.max_calls);
|
|
130
|
+
const settled = await Promise.allSettled(active.map((member) => run(member)));
|
|
131
|
+
if (propagateFatal) {
|
|
132
|
+
for (const entry of settled) {
|
|
133
|
+
if (entry.status === "rejected" && isFatal(entry.reason))
|
|
134
|
+
throw entry.reason;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return definition.members.map(({ provider, model }, index) => {
|
|
138
|
+
const target = { provider, model };
|
|
139
|
+
const entry = settled[index];
|
|
140
|
+
if (!entry)
|
|
141
|
+
return { target, outcome: "budget" };
|
|
142
|
+
if (entry.status === "fulfilled")
|
|
143
|
+
return { target, value: entry.value };
|
|
144
|
+
const outcome = entry.reason instanceof DecisionError ? entry.reason.code : "internal";
|
|
145
|
+
return { target, outcome };
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
// Reduces each answer to the value that members must agree on. Probabilities are not
|
|
149
|
+
// averaged, because the members' confidence is not calibrated against each other.
|
|
150
|
+
function summarize(questions, response, noulThreshold) {
|
|
151
|
+
const summary = {};
|
|
152
|
+
for (const [name, question] of Object.entries(questions)) {
|
|
153
|
+
const answer = Object.hasOwn(response.answers, name) ? response.answers[name] : undefined;
|
|
154
|
+
if (!answer)
|
|
155
|
+
return undefined;
|
|
156
|
+
if (answer.type === "choice" && question.type === "choice") {
|
|
157
|
+
if (!Object.hasOwn(question.criteria, answer.choice))
|
|
158
|
+
return undefined;
|
|
159
|
+
summary[name] = answer.choice;
|
|
160
|
+
}
|
|
161
|
+
else if (answer.type === "noul" && question.type === "noul") {
|
|
162
|
+
if (!isProbability(answer.noul))
|
|
163
|
+
return undefined;
|
|
164
|
+
summary[name] = answer.noul >= noulThreshold;
|
|
165
|
+
}
|
|
166
|
+
else if (answer.type === "score" && question.type === "score") {
|
|
167
|
+
const highest = question.criteria.length - 1;
|
|
168
|
+
if (!Number.isFinite(answer.score) || answer.score < 0 || answer.score > highest) {
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
summary[name] = answer.score;
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return summary;
|
|
178
|
+
}
|
|
179
|
+
function agree(questions, summaries, tolerance) {
|
|
180
|
+
return Object.entries(questions).every(([name, question]) => {
|
|
181
|
+
const values = summaries.map((summary) => summary[name]);
|
|
182
|
+
if (question.type === "score") {
|
|
183
|
+
const scores = values;
|
|
184
|
+
// The small epsilon absorbs floating-point error at the tolerance boundary.
|
|
185
|
+
return Math.max(...scores) - Math.min(...scores) <= tolerance + 1e-9;
|
|
186
|
+
}
|
|
187
|
+
return values.every((value) => value === values[0]);
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
export async function runConsensus(consensus, state, registry, context = {}) {
|
|
191
|
+
const { definition, questions } = consensus;
|
|
192
|
+
checkMembers(definition, registry);
|
|
193
|
+
const stopped = decisionStopError(context);
|
|
194
|
+
if (stopped)
|
|
195
|
+
throw stopped;
|
|
196
|
+
const first = registry.getProvider(definition.members[0].provider);
|
|
197
|
+
const deadlineAt = Math.min(context.deadlineAt ?? Infinity, performance.now() + (first.timeoutMs ?? 30_000));
|
|
198
|
+
const calls = await callMembers(definition, async (target) => {
|
|
199
|
+
const routed = await routeDecision({ ...target, state, questions, context: { signal: context.signal, deadlineAt } }, registry);
|
|
200
|
+
return routed.result;
|
|
201
|
+
});
|
|
202
|
+
const members = [];
|
|
203
|
+
const summaries = [];
|
|
204
|
+
let result;
|
|
205
|
+
for (const call of calls) {
|
|
206
|
+
if (!("value" in call)) {
|
|
207
|
+
members.push({ ...call.target, outcome: call.outcome });
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const answers = summarize(questions, call.value, definition.noul_threshold);
|
|
211
|
+
if (!answers) {
|
|
212
|
+
members.push({ ...call.target, outcome: "invalid_response" });
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
members.push({ ...call.target, outcome: "ok", answers });
|
|
216
|
+
summaries.push(answers);
|
|
217
|
+
result ??= call.value;
|
|
218
|
+
}
|
|
219
|
+
if (summaries.length > 1 && !agree(questions, summaries, definition.score_tolerance)) {
|
|
220
|
+
return { status: "disagreed", members };
|
|
221
|
+
}
|
|
222
|
+
if (summaries.length < definition.quorum)
|
|
223
|
+
return { status: "no_quorum", members };
|
|
224
|
+
return { status: "agreed", result, members };
|
|
225
|
+
}
|
|
226
|
+
export function checkPolicyConsensusProfile(profile, consensus) {
|
|
227
|
+
const policy = profile.definition;
|
|
228
|
+
const definition = consensus.definition;
|
|
229
|
+
const evaluatedPolicy = definition.policy_profile;
|
|
230
|
+
if (evaluatedPolicy &&
|
|
231
|
+
(evaluatedPolicy.id !== policy.id || evaluatedPolicy.version !== policy.version)) {
|
|
232
|
+
throw new DecisionError("configuration", "Consensus requires its evaluated policy profile.");
|
|
233
|
+
}
|
|
234
|
+
if (definition.template.id !== policy.template.id ||
|
|
235
|
+
definition.template.version !== policy.template.version) {
|
|
236
|
+
throw new DecisionError("configuration", "The consensus profile must use the policy profile's template.");
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
function checkPolicyConsensus(profile, consensus, registry) {
|
|
240
|
+
checkPolicyConsensusProfile(profile, consensus);
|
|
241
|
+
const policy = profile.definition;
|
|
242
|
+
const definition = consensus.definition;
|
|
243
|
+
checkMembers(definition, registry);
|
|
244
|
+
if (definition.members.some(({ provider }) => !policy.providers.some((id) => id === provider))) {
|
|
245
|
+
throw new DecisionError("configuration", "The policy profile restricts a consensus member's provider.");
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
// Reads DECISION_ACTION_POLICY_CONSENSUS. Live action policy uses consensus only when an
|
|
249
|
+
// operator opts in, because the held-out evidence is small: 1 false allow in 10 risky
|
|
250
|
+
// actions, exactly at the 0.1 limit. Re-run with more held-out records before considering
|
|
251
|
+
// consensus as a default.
|
|
252
|
+
export function loadActionPolicyConsensus(selection, consensuses, profile, registry) {
|
|
253
|
+
if (selection === undefined)
|
|
254
|
+
return undefined;
|
|
255
|
+
const match = /^(.+)@(\d+)$/.exec(selection);
|
|
256
|
+
let consensus;
|
|
257
|
+
try {
|
|
258
|
+
if (!match)
|
|
259
|
+
throw new Error();
|
|
260
|
+
consensus = consensuses.get({ id: match[1], version: Number(match[2]) });
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
throw new DecisionError("configuration", "DECISION_ACTION_POLICY_CONSENSUS must name an installed consensus profile and version.");
|
|
264
|
+
}
|
|
265
|
+
checkPolicyConsensus(profile, consensus, registry);
|
|
266
|
+
if (!consensus.definition.policy_profile ||
|
|
267
|
+
consensus.definition.members.some(({ revision }) => !revision)) {
|
|
268
|
+
throw new DecisionError("configuration", "Live consensus requires an evaluated policy profile and member revisions.");
|
|
269
|
+
}
|
|
270
|
+
return consensus;
|
|
271
|
+
}
|
|
272
|
+
// Any valid block wins. Otherwise only a quorum of members that all reach the same
|
|
273
|
+
// action decides; disagreement or a missing quorum requires review.
|
|
274
|
+
export async function evaluateConsensusActionPolicy(request, registry, profile, consensus) {
|
|
275
|
+
const policy = profile.definition;
|
|
276
|
+
const definition = consensus.definition;
|
|
277
|
+
checkPolicyConsensus(profile, consensus, registry);
|
|
278
|
+
const identity = {
|
|
279
|
+
profile: { id: policy.id, version: policy.version },
|
|
280
|
+
consensus: { id: definition.id, version: definition.version },
|
|
281
|
+
};
|
|
282
|
+
const scope = effectiveScope(policy.scope, request.scope);
|
|
283
|
+
if (!shouldEvaluateAction(request.toolName, request.toolInput, scope)) {
|
|
284
|
+
return {
|
|
285
|
+
...identity,
|
|
286
|
+
status: "skipped",
|
|
287
|
+
action: "allow",
|
|
288
|
+
reasonCode: isDecisionModelTool(request.toolName) ? "recursive_tool" : "out_of_scope",
|
|
289
|
+
reasons: ["Action did not match the configured decision-review scope."],
|
|
290
|
+
members: [],
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
const deadlineAt = Math.min(performance.now() + registry.actionPolicyTimeoutMs, request.context?.deadlineAt ?? Infinity);
|
|
294
|
+
const calls = await callMembers(definition, async ({ provider, model, revision }) => {
|
|
295
|
+
const target = registry.resolveActionPolicyTarget(provider, model);
|
|
296
|
+
if (revision) {
|
|
297
|
+
const status = await registry
|
|
298
|
+
.getProvider(provider)
|
|
299
|
+
.available(request.context?.signal, deadlineAt);
|
|
300
|
+
const entry = status.models?.find((candidate) => candidate.name === model);
|
|
301
|
+
if (entry?.status !== "ready" || !entry.revision?.toLowerCase().startsWith(revision)) {
|
|
302
|
+
return { provider, model, status: "failed", reasonCode: "configuration" };
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
const nonLocal = target.locality !== "local";
|
|
306
|
+
// Each member gets the same S07 data rules as a single-model policy decision.
|
|
307
|
+
const state = nonLocal
|
|
308
|
+
? policy.data === "reduced_non_local" &&
|
|
309
|
+
target.modelApproved &&
|
|
310
|
+
projectNonLocalAction(request.toolName, request.toolInput)
|
|
311
|
+
: { tool_name: request.toolName, tool_input: request.toolInput };
|
|
312
|
+
if (!state)
|
|
313
|
+
return { provider, model, status: "skipped", reasonCode: "local_context_required" };
|
|
314
|
+
if (!(await profile.validateState(state))) {
|
|
315
|
+
return { provider, model, status: "skipped", reasonCode: "policy_state_invalid" };
|
|
316
|
+
}
|
|
317
|
+
const { result } = await routeDecision({
|
|
318
|
+
provider,
|
|
319
|
+
model: target.model,
|
|
320
|
+
state,
|
|
321
|
+
questions: profile.questions,
|
|
322
|
+
context: { ...request.context, deadlineAt },
|
|
323
|
+
}, registry);
|
|
324
|
+
const evaluated = evaluatePolicyAnswers(result.answers, profile, nonLocal);
|
|
325
|
+
return {
|
|
326
|
+
provider,
|
|
327
|
+
model,
|
|
328
|
+
status: "evaluated",
|
|
329
|
+
action: evaluated.action,
|
|
330
|
+
reasonCode: evaluated.reasonCode,
|
|
331
|
+
};
|
|
332
|
+
}, false);
|
|
333
|
+
const cancelled = decisionStopError({ signal: request.context?.signal });
|
|
334
|
+
if (cancelled)
|
|
335
|
+
throw cancelled;
|
|
336
|
+
const members = calls.map((call) => {
|
|
337
|
+
if ("value" in call)
|
|
338
|
+
return call.value;
|
|
339
|
+
if (call.outcome === "budget")
|
|
340
|
+
return { ...call.target, status: "budget" };
|
|
341
|
+
return { ...call.target, status: "failed", reasonCode: call.outcome };
|
|
342
|
+
});
|
|
343
|
+
const actions = members.flatMap((member) => member.status === "evaluated" ? [member.action] : []);
|
|
344
|
+
const decide = (action, reasonCode, reason) => ({
|
|
345
|
+
...identity,
|
|
346
|
+
status: "evaluated",
|
|
347
|
+
action,
|
|
348
|
+
reasonCode,
|
|
349
|
+
reasons: [reason],
|
|
350
|
+
members,
|
|
351
|
+
});
|
|
352
|
+
if (actions.includes("block")) {
|
|
353
|
+
return decide("block", "consensus_block", "A consensus member blocked the action");
|
|
354
|
+
}
|
|
355
|
+
if (actions.length < definition.quorum) {
|
|
356
|
+
return decide("review", "consensus_no_quorum", `Fewer than ${definition.quorum} consensus members returned a valid policy result`);
|
|
357
|
+
}
|
|
358
|
+
if (new Set(actions).size > 1) {
|
|
359
|
+
return decide("review", "consensus_disagreement", "Consensus members disagreed");
|
|
360
|
+
}
|
|
361
|
+
if (members.some((member) => member.status !== "evaluated" && member.status !== "budget")) {
|
|
362
|
+
return decide("review", "consensus_review", "An attempted member did not return a policy result");
|
|
363
|
+
}
|
|
364
|
+
return actions[0] === "allow"
|
|
365
|
+
? decide("allow", "consensus_allow", "All consensus members allowed the action")
|
|
366
|
+
: decide("review", "consensus_review", "All consensus members required review");
|
|
367
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { addAbortListener } from "node:events";
|
|
2
|
+
import { DecisionError } from "../errors.js";
|
|
3
|
+
import { DecisionProviderError } from "../http.js";
|
|
4
|
+
const TRANSIENT_HTTP_STATUS = new Set([429, 502, 503, 504]);
|
|
5
|
+
const BASE_DELAY_MS = 200;
|
|
6
|
+
const MAX_DELAY_MS = 2_000;
|
|
7
|
+
const MAX_RETRY_AFTER_MS = 30_000;
|
|
8
|
+
// Only failures that a later attempt can plausibly avoid are retried or sent to a fallback.
|
|
9
|
+
export function isTransient(error) {
|
|
10
|
+
if (!(error instanceof DecisionError))
|
|
11
|
+
return false;
|
|
12
|
+
if (error.code === "transport" || error.code === "overload")
|
|
13
|
+
return true;
|
|
14
|
+
return (error.code === "http" &&
|
|
15
|
+
error instanceof DecisionProviderError &&
|
|
16
|
+
error.status !== undefined &&
|
|
17
|
+
TRANSIENT_HTTP_STATUS.has(error.status));
|
|
18
|
+
}
|
|
19
|
+
// Returns undefined when the provider asks for a longer wait than the router accepts.
|
|
20
|
+
export function retryDelayMs(retry, error, random) {
|
|
21
|
+
const backoff = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** retry);
|
|
22
|
+
const jittered = backoff * (0.5 + random() / 2);
|
|
23
|
+
const retryAfter = error instanceof DecisionProviderError ? error.retryAfterMs : undefined;
|
|
24
|
+
if (retryAfter === undefined)
|
|
25
|
+
return jittered;
|
|
26
|
+
if (retryAfter > MAX_RETRY_AFTER_MS)
|
|
27
|
+
return undefined;
|
|
28
|
+
return Math.max(jittered, retryAfter);
|
|
29
|
+
}
|
|
30
|
+
export function sleep(ms, signal) {
|
|
31
|
+
const cancelled = () => new DecisionError("cancelled", "Decision request was cancelled.");
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
if (signal?.aborted) {
|
|
34
|
+
reject(cancelled());
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const listener = signal &&
|
|
38
|
+
addAbortListener(signal, () => {
|
|
39
|
+
clearTimeout(timer);
|
|
40
|
+
reject(cancelled());
|
|
41
|
+
});
|
|
42
|
+
const timer = setTimeout(() => {
|
|
43
|
+
listener?.[Symbol.dispose]();
|
|
44
|
+
resolve();
|
|
45
|
+
}, ms);
|
|
46
|
+
});
|
|
47
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { DecisionErrorCode } from "../errors.js";
|
|
2
|
+
import type { ProviderRegistry } from "../providers/index.js";
|
|
3
|
+
import type { DecisionProvider } from "../types.js";
|
|
4
|
+
export type RouteTarget = {
|
|
5
|
+
provider: string;
|
|
6
|
+
model: string;
|
|
7
|
+
};
|
|
8
|
+
export type RouteAttempt = RouteTarget & {
|
|
9
|
+
outcome: "ok" | DecisionErrorCode | "internal";
|
|
10
|
+
};
|
|
11
|
+
export declare function planTargets(registry: ProviderRegistry, provider?: string, model?: string): RouteTarget[];
|
|
12
|
+
export declare function canServe(provider: DecisionProvider, model: string, signal?: AbortSignal, deadlineAt?: number): Promise<boolean>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// The primary target passes the provider and model allowlists before any inference starts.
|
|
2
|
+
// An explicit provider or model keeps the request fixed to that target.
|
|
3
|
+
export function planTargets(registry, provider, model) {
|
|
4
|
+
const id = registry.getProvider(provider).id;
|
|
5
|
+
const targets = [{ provider: id, model: registry.effectiveModel(id, model) }];
|
|
6
|
+
if (provider !== undefined || model !== undefined)
|
|
7
|
+
return targets;
|
|
8
|
+
for (const target of registry.routing.fallback) {
|
|
9
|
+
const known = targets.some((planned) => planned.provider === target.provider && planned.model === target.model);
|
|
10
|
+
if (!known)
|
|
11
|
+
targets.push({ provider: target.provider, model: target.model });
|
|
12
|
+
}
|
|
13
|
+
return targets;
|
|
14
|
+
}
|
|
15
|
+
// A fallback target is skipped when discovery shows that it cannot answer.
|
|
16
|
+
export async function canServe(provider, model, signal, deadlineAt) {
|
|
17
|
+
try {
|
|
18
|
+
const status = await provider.available(signal, deadlineAt);
|
|
19
|
+
if (!status.ok)
|
|
20
|
+
return false;
|
|
21
|
+
const entry = status.models?.find((candidate) => candidate.name === model);
|
|
22
|
+
return entry === undefined || entry.status === "ready" || entry.status === "unknown";
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|