@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,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "engineering.action-risk.consensus",
|
|
3
|
+
"version": 1,
|
|
4
|
+
"template": { "id": "engineering.action-risk", "version": 1 },
|
|
5
|
+
"policy_profile": { "id": "engineering-default", "version": 1 },
|
|
6
|
+
"members": [
|
|
7
|
+
{ "provider": "ollama", "model": "d1-omni:600m", "revision": "1ba59f63e836" },
|
|
8
|
+
{ "provider": "ollama", "model": "d3:4b", "revision": "510b1771140e" }
|
|
9
|
+
],
|
|
10
|
+
"quorum": 2,
|
|
11
|
+
"max_calls": 2,
|
|
12
|
+
"agreement": "unanimous",
|
|
13
|
+
"noul_threshold": 0.5,
|
|
14
|
+
"score_tolerance": 0,
|
|
15
|
+
"allow_non_local": false
|
|
16
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "engineering.task-route.cascade",
|
|
3
|
+
"version": 1,
|
|
4
|
+
"template": { "id": "engineering.task-route", "version": 1 },
|
|
5
|
+
"max_attempts": 2,
|
|
6
|
+
"max_non_local_attempts": 0,
|
|
7
|
+
"stages": [
|
|
8
|
+
{
|
|
9
|
+
"provider": "ollama",
|
|
10
|
+
"model": "strands-decider:2b",
|
|
11
|
+
"revision": "fd88a2b3ab3f",
|
|
12
|
+
"min_margin": 0.3
|
|
13
|
+
},
|
|
14
|
+
{ "provider": "ollama", "model": "d3:4b", "revision": "510b1771140e", "min_margin": 0.3 }
|
|
15
|
+
],
|
|
16
|
+
"calibration": {
|
|
17
|
+
"dataset": "task-route.dev@1",
|
|
18
|
+
"sha256": "82bd1937fa7440ba0f8410c25c62778cef18b1cc98de9e3210c95d160891bcd0",
|
|
19
|
+
"recorded": "2026-11-30"
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { ActionPolicyFailureMode } from "./config.js";
|
|
2
|
+
import { type DecisionErrorCode } from "./errors.js";
|
|
3
|
+
import { type PolicyAdapter, type PolicyTargetIdentity } from "./policy/events.js";
|
|
4
|
+
import { type EvaluatedPolicyReason } from "./policy/evaluate.js";
|
|
5
|
+
import { type ActionPolicyScope } from "./policy/scope.js";
|
|
6
|
+
import { type ProviderRegistry } from "./providers/index.js";
|
|
7
|
+
import type { TemplateIdentity } from "./templates/schema.js";
|
|
8
|
+
import type { DecisionContext, DecisionResponse, JsonValue } from "./types.js";
|
|
9
|
+
export { isDecisionModelTool, shouldEvaluateAction, type ActionPolicyScope, } from "./policy/scope.js";
|
|
10
|
+
export type ActionPolicyRequest = {
|
|
11
|
+
toolName: string;
|
|
12
|
+
toolInput: JsonValue;
|
|
13
|
+
provider?: string;
|
|
14
|
+
model?: string;
|
|
15
|
+
scope?: ActionPolicyScope;
|
|
16
|
+
failureMode?: ActionPolicyFailureMode;
|
|
17
|
+
context?: DecisionContext;
|
|
18
|
+
};
|
|
19
|
+
export type ActionPolicyResult = {
|
|
20
|
+
reasons: string[];
|
|
21
|
+
profile: TemplateIdentity;
|
|
22
|
+
} & ({
|
|
23
|
+
status: "evaluated";
|
|
24
|
+
reasonCode: EvaluatedPolicyReason;
|
|
25
|
+
action: "allow" | "review" | "block";
|
|
26
|
+
evaluated: true;
|
|
27
|
+
provider: string;
|
|
28
|
+
model?: string;
|
|
29
|
+
answers: DecisionResponse["answers"];
|
|
30
|
+
} | {
|
|
31
|
+
status: "skipped";
|
|
32
|
+
action: "allow";
|
|
33
|
+
evaluated: false;
|
|
34
|
+
reasonCode: "out_of_scope" | "recursive_tool";
|
|
35
|
+
} | {
|
|
36
|
+
status: "skipped";
|
|
37
|
+
action: "review";
|
|
38
|
+
evaluated: false;
|
|
39
|
+
reasonCode: "local_context_required" | "provider_restricted" | "policy_state_invalid";
|
|
40
|
+
} | {
|
|
41
|
+
status: "failed";
|
|
42
|
+
action: "allow" | "review" | "block";
|
|
43
|
+
evaluated: false;
|
|
44
|
+
reasonCode: DecisionErrorCode | "internal";
|
|
45
|
+
});
|
|
46
|
+
export declare function effectiveScope(minimum: ActionPolicyScope, requested?: ActionPolicyScope): ActionPolicyScope;
|
|
47
|
+
export declare function effectiveFailureMode(minimum: ActionPolicyFailureMode, requested?: ActionPolicyFailureMode): ActionPolicyFailureMode;
|
|
48
|
+
export declare function evaluateActionPolicy(request: ActionPolicyRequest, registry?: ProviderRegistry, profile?: {
|
|
49
|
+
definition: import("./policy/schema.js").PolicyProfile;
|
|
50
|
+
questions: import("./types.js").DecisionQuestions;
|
|
51
|
+
validateState: (state: unknown) => Promise<boolean>;
|
|
52
|
+
}, onTarget?: (target: PolicyTargetIdentity) => void): Promise<ActionPolicyResult>;
|
|
53
|
+
export declare function observeActionPolicy(request: ActionPolicyRequest, adapter: PolicyAdapter, registry?: {
|
|
54
|
+
cache: Readonly<{
|
|
55
|
+
ttlMs: number;
|
|
56
|
+
maxEntries: number;
|
|
57
|
+
maxBytes: number;
|
|
58
|
+
}>;
|
|
59
|
+
routing: Readonly<{
|
|
60
|
+
retryAttempts: number;
|
|
61
|
+
retryBilled: boolean;
|
|
62
|
+
fallback: readonly import("./config.js").RouteTarget[];
|
|
63
|
+
}>;
|
|
64
|
+
localOnly: boolean;
|
|
65
|
+
locality: (id: string, model: string) => "local" | "non-local" | "unknown";
|
|
66
|
+
actionPolicyTimeoutMs: number;
|
|
67
|
+
actionPolicyFailureMode: ActionPolicyFailureMode;
|
|
68
|
+
actionPolicyScope: "consequential" | "strict";
|
|
69
|
+
defaultProvider: "ollama" | "opencode-go" | "typesafe";
|
|
70
|
+
getProvider: (id?: string) => import("./types.js").DecisionProvider;
|
|
71
|
+
effectiveModel: (id?: string, requestedModel?: string) => string;
|
|
72
|
+
resolveActionPolicyTarget(id?: string, requestedModel?: string): {
|
|
73
|
+
model: string;
|
|
74
|
+
locality: "local" | "non-local" | "unknown";
|
|
75
|
+
modelApproved: boolean;
|
|
76
|
+
};
|
|
77
|
+
listProviders(): import("./types.js").DecisionProvider[];
|
|
78
|
+
}, profile?: {
|
|
79
|
+
definition: import("./policy/schema.js").PolicyProfile;
|
|
80
|
+
questions: import("./types.js").DecisionQuestions;
|
|
81
|
+
validateState: (state: unknown) => Promise<boolean>;
|
|
82
|
+
}): Promise<{
|
|
83
|
+
event: string;
|
|
84
|
+
adapter: PolicyAdapter;
|
|
85
|
+
status: "evaluated" | "failed" | "skipped";
|
|
86
|
+
profile: {
|
|
87
|
+
id: string;
|
|
88
|
+
version: number;
|
|
89
|
+
};
|
|
90
|
+
provider?: string | undefined;
|
|
91
|
+
model?: string | undefined;
|
|
92
|
+
consensus?: {
|
|
93
|
+
id: string;
|
|
94
|
+
version: number;
|
|
95
|
+
} | undefined;
|
|
96
|
+
members?: {
|
|
97
|
+
provider: string;
|
|
98
|
+
model: string;
|
|
99
|
+
}[] | undefined;
|
|
100
|
+
reasonCode: string;
|
|
101
|
+
outcome: "would_allow" | "would_block" | "would_review";
|
|
102
|
+
}>;
|
|
103
|
+
export declare function codexPreToolUseOutput(result: Pick<ActionPolicyResult, "action" | "reasons">): Record<string, JsonValue>;
|
|
104
|
+
export declare function claudeCodePreToolUseOutput(result: Pick<ActionPolicyResult, "action" | "reasons">): Record<string, JsonValue>;
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { decide } from "./decision.js";
|
|
2
|
+
import { DecisionError } from "./errors.js";
|
|
3
|
+
import { recordPolicyObservation, } from "./policy/events.js";
|
|
4
|
+
import { evaluatePolicyAnswers } from "./policy/evaluate.js";
|
|
5
|
+
import { getPolicyProfile } from "./policy/registry.js";
|
|
6
|
+
import { projectNonLocalAction } from "./policy/payload.js";
|
|
7
|
+
import { isDecisionModelTool, shouldEvaluateAction, } from "./policy/scope.js";
|
|
8
|
+
import { getProviderRegistry } from "./providers/index.js";
|
|
9
|
+
export { isDecisionModelTool, shouldEvaluateAction, } from "./policy/scope.js";
|
|
10
|
+
export function effectiveScope(minimum, requested) {
|
|
11
|
+
if (minimum === "all" || requested === "all")
|
|
12
|
+
return "all";
|
|
13
|
+
if (minimum === "strict" || requested === "strict")
|
|
14
|
+
return "strict";
|
|
15
|
+
return "consequential";
|
|
16
|
+
}
|
|
17
|
+
export function effectiveFailureMode(minimum, requested) {
|
|
18
|
+
if (minimum === "block" || requested === "block")
|
|
19
|
+
return "block";
|
|
20
|
+
if (minimum === "review" || requested === "review")
|
|
21
|
+
return "review";
|
|
22
|
+
return "native";
|
|
23
|
+
}
|
|
24
|
+
export async function evaluateActionPolicy(request, registry, profile = getPolicyProfile(), onTarget) {
|
|
25
|
+
const { definition, questions } = profile;
|
|
26
|
+
const identity = { id: definition.id, version: definition.version };
|
|
27
|
+
const scope = effectiveScope(definition.scope, request.scope);
|
|
28
|
+
if (!shouldEvaluateAction(request.toolName, request.toolInput, scope)) {
|
|
29
|
+
return {
|
|
30
|
+
profile: identity,
|
|
31
|
+
status: "skipped",
|
|
32
|
+
reasonCode: isDecisionModelTool(request.toolName) ? "recursive_tool" : "out_of_scope",
|
|
33
|
+
action: "allow",
|
|
34
|
+
reasons: ["Action did not match the configured decision-review scope."],
|
|
35
|
+
evaluated: false,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
let requireReview = true;
|
|
39
|
+
try {
|
|
40
|
+
const activeRegistry = registry ?? getProviderRegistry();
|
|
41
|
+
const provider = request.provider ?? activeRegistry.defaultProvider;
|
|
42
|
+
if (!definition.providers.some((allowed) => allowed === provider)) {
|
|
43
|
+
return {
|
|
44
|
+
profile: identity,
|
|
45
|
+
status: "skipped",
|
|
46
|
+
action: "review",
|
|
47
|
+
evaluated: false,
|
|
48
|
+
reasonCode: "provider_restricted",
|
|
49
|
+
reasons: ["The action policy profile restricts this decision provider"],
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
const target = activeRegistry.resolveActionPolicyTarget(provider, request.model);
|
|
53
|
+
const nonLocal = target.locality !== "local";
|
|
54
|
+
requireReview = nonLocal;
|
|
55
|
+
const state = nonLocal
|
|
56
|
+
? definition.data === "reduced_non_local" &&
|
|
57
|
+
target.modelApproved &&
|
|
58
|
+
projectNonLocalAction(request.toolName, request.toolInput)
|
|
59
|
+
: { tool_name: request.toolName, tool_input: request.toolInput };
|
|
60
|
+
if (!state) {
|
|
61
|
+
return {
|
|
62
|
+
profile: identity,
|
|
63
|
+
status: "skipped",
|
|
64
|
+
action: "review",
|
|
65
|
+
evaluated: false,
|
|
66
|
+
reasonCode: "local_context_required",
|
|
67
|
+
reasons: ["The decision policy requires an approved local model for this action"],
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
if (!(await profile.validateState(state))) {
|
|
71
|
+
return {
|
|
72
|
+
profile: identity,
|
|
73
|
+
status: "skipped",
|
|
74
|
+
action: "review",
|
|
75
|
+
evaluated: false,
|
|
76
|
+
reasonCode: "policy_state_invalid",
|
|
77
|
+
reasons: ["Action state does not match the policy template"],
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
onTarget?.({ provider, model: target.modelApproved ? target.model : undefined });
|
|
81
|
+
const deadlineAt = performance.now() + activeRegistry.actionPolicyTimeoutMs;
|
|
82
|
+
const response = await decide({
|
|
83
|
+
provider: request.provider,
|
|
84
|
+
model: target.model,
|
|
85
|
+
context: {
|
|
86
|
+
...request.context,
|
|
87
|
+
deadlineAt: Math.min(deadlineAt, request.context?.deadlineAt ?? Infinity),
|
|
88
|
+
},
|
|
89
|
+
state,
|
|
90
|
+
questions,
|
|
91
|
+
}, activeRegistry);
|
|
92
|
+
return {
|
|
93
|
+
...evaluatePolicyAnswers(response.answers, profile, requireReview),
|
|
94
|
+
profile: identity,
|
|
95
|
+
status: "evaluated",
|
|
96
|
+
evaluated: true,
|
|
97
|
+
provider: response.provider,
|
|
98
|
+
model: response.model,
|
|
99
|
+
answers: response.answers,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
const reasonCode = error instanceof DecisionError ? error.code : "internal";
|
|
104
|
+
const failureMode = effectiveFailureMode(definition.failure_mode, request.failureMode);
|
|
105
|
+
return {
|
|
106
|
+
profile: identity,
|
|
107
|
+
status: "failed",
|
|
108
|
+
action: failureMode === "native"
|
|
109
|
+
? requireReview || reasonCode === "configuration" || reasonCode === "invalid_response"
|
|
110
|
+
? "review"
|
|
111
|
+
: "allow"
|
|
112
|
+
: failureMode,
|
|
113
|
+
reasons: [`Decision policy failed (${reasonCode})`],
|
|
114
|
+
evaluated: false,
|
|
115
|
+
reasonCode,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
export async function observeActionPolicy(request, adapter, registry = getProviderRegistry(), profile = getPolicyProfile()) {
|
|
120
|
+
let target;
|
|
121
|
+
try {
|
|
122
|
+
const result = await evaluateActionPolicy(request, registry, profile, (identity) => {
|
|
123
|
+
target = identity;
|
|
124
|
+
});
|
|
125
|
+
return recordPolicyObservation(adapter, result, target);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
const { id, version, failure_mode } = profile.definition;
|
|
129
|
+
const failureMode = effectiveFailureMode(failure_mode, request.failureMode);
|
|
130
|
+
return recordPolicyObservation(adapter, {
|
|
131
|
+
profile: { id, version },
|
|
132
|
+
status: "failed",
|
|
133
|
+
reasonCode: "internal",
|
|
134
|
+
action: failureMode === "native" ? "allow" : failureMode,
|
|
135
|
+
}, target);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
export function codexPreToolUseOutput(result) {
|
|
139
|
+
if (result.action === "allow")
|
|
140
|
+
return {};
|
|
141
|
+
const reason = result.reasons.join("; ") || "Decision policy requires review.";
|
|
142
|
+
if (result.action === "block") {
|
|
143
|
+
return {
|
|
144
|
+
hookSpecificOutput: {
|
|
145
|
+
hookEventName: "PreToolUse",
|
|
146
|
+
permissionDecision: "deny",
|
|
147
|
+
permissionDecisionReason: `Decision model policy blocked this action: ${reason}`,
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
hookSpecificOutput: {
|
|
153
|
+
hookEventName: "PreToolUse",
|
|
154
|
+
additionalContext: `Decision model policy marked this action for review: ${reason}. ` +
|
|
155
|
+
"Do not bypass normal Codex permission checks. If the action is consequential and Codex does not request approval, ask the user before performing it.",
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
// Allow returns no decision, because a Claude Code "allow" would skip its own permission prompt.
|
|
160
|
+
export function claudeCodePreToolUseOutput(result) {
|
|
161
|
+
if (result.action === "allow")
|
|
162
|
+
return {};
|
|
163
|
+
const reason = result.reasons.join("; ") || "Decision policy requires review.";
|
|
164
|
+
return {
|
|
165
|
+
hookSpecificOutput: {
|
|
166
|
+
hookEventName: "PreToolUse",
|
|
167
|
+
permissionDecision: result.action === "block" ? "deny" : "ask",
|
|
168
|
+
permissionDecisionReason: result.action === "block"
|
|
169
|
+
? `Decision model policy blocked this action: ${reason}`
|
|
170
|
+
: `Decision model policy requires review: ${reason}`,
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
}
|
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { CacheConfig } from "./config.js";
|
|
2
|
+
import type { ProviderRegistry } from "./providers/index.js";
|
|
3
|
+
import { type RouteAttempt } from "./routing/router.js";
|
|
4
|
+
import type { DecisionRequest, DecisionResponse } from "./types.js";
|
|
5
|
+
export type CacheStatus = "hit" | "miss" | "shared" | "bypass";
|
|
6
|
+
type Routed = {
|
|
7
|
+
result: DecisionResponse;
|
|
8
|
+
attempts: RouteAttempt[];
|
|
9
|
+
};
|
|
10
|
+
export type CachedDecision = Routed & {
|
|
11
|
+
cache: CacheStatus;
|
|
12
|
+
};
|
|
13
|
+
export declare function createDecisionCache(config: CacheConfig, now?: () => number): {
|
|
14
|
+
decide(request: DecisionRequest, registry: ProviderRegistry, scope?: string): Promise<CachedDecision>;
|
|
15
|
+
};
|
|
16
|
+
export type DecisionCache = ReturnType<typeof createDecisionCache>;
|
|
17
|
+
export {};
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { addAbortListener } from "node:events";
|
|
3
|
+
import { decisionStopError } from "./concurrency.js";
|
|
4
|
+
import { routeDecision } from "./decision.js";
|
|
5
|
+
import { DecisionError } from "./errors.js";
|
|
6
|
+
import { containsRecognizedSecret } from "./policy/payload.js";
|
|
7
|
+
import { planTargets } from "./routing/router.js";
|
|
8
|
+
// Object key order in state carries no meaning; question order and array order can.
|
|
9
|
+
function canonicalState(value) {
|
|
10
|
+
if (Array.isArray(value))
|
|
11
|
+
return value.map(canonicalState);
|
|
12
|
+
if (typeof value !== "object" || value === null)
|
|
13
|
+
return value;
|
|
14
|
+
return Object.fromEntries(Object.keys(value)
|
|
15
|
+
.sort()
|
|
16
|
+
.map((key) => [key, canonicalState(value[key])]));
|
|
17
|
+
}
|
|
18
|
+
function waitFor(flight, context, release) {
|
|
19
|
+
flight.waiters++;
|
|
20
|
+
return new Promise((resolve, reject) => {
|
|
21
|
+
let done = false;
|
|
22
|
+
const finish = (settle) => {
|
|
23
|
+
if (done)
|
|
24
|
+
return;
|
|
25
|
+
done = true;
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
listener?.[Symbol.dispose]();
|
|
28
|
+
if (--flight.waiters === 0)
|
|
29
|
+
release();
|
|
30
|
+
settle();
|
|
31
|
+
};
|
|
32
|
+
const leave = (error) => finish(() => reject(error));
|
|
33
|
+
const listener = context?.signal &&
|
|
34
|
+
addAbortListener(context.signal, () => leave(new DecisionError("cancelled", "Decision request was cancelled.")));
|
|
35
|
+
const timer = context?.deadlineAt === undefined
|
|
36
|
+
? undefined
|
|
37
|
+
: setTimeout(() => leave(new DecisionError("timeout", "Decision request timed out.")), Math.max(1, Math.ceil(context.deadlineAt - performance.now())));
|
|
38
|
+
if (context?.signal?.aborted) {
|
|
39
|
+
leave(new DecisionError("cancelled", "Decision request was cancelled."));
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
flight.promise.then((routed) => finish(() => resolve(structuredClone(routed))), (error) => finish(() => reject(error)));
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
export function createDecisionCache(config, now = Date.now) {
|
|
46
|
+
const entries = new Map();
|
|
47
|
+
const flights = new Map();
|
|
48
|
+
let bytesUsed = 0;
|
|
49
|
+
function remove(key) {
|
|
50
|
+
const entry = entries.get(key);
|
|
51
|
+
if (!entry)
|
|
52
|
+
return;
|
|
53
|
+
entries.delete(key);
|
|
54
|
+
bytesUsed -= entry.bytes;
|
|
55
|
+
}
|
|
56
|
+
function store(key, result) {
|
|
57
|
+
if (containsRecognizedSecret(result))
|
|
58
|
+
return;
|
|
59
|
+
const bytes = Buffer.byteLength(JSON.stringify(result));
|
|
60
|
+
if (bytes > config.maxBytes)
|
|
61
|
+
return;
|
|
62
|
+
remove(key);
|
|
63
|
+
entries.set(key, { result, bytes, expiresAt: now() + config.ttlMs });
|
|
64
|
+
bytesUsed += bytes;
|
|
65
|
+
for (const oldest of entries.keys()) {
|
|
66
|
+
if (entries.size <= config.maxEntries && bytesUsed <= config.maxBytes)
|
|
67
|
+
break;
|
|
68
|
+
remove(oldest);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function cacheKey(request, registry, scope) {
|
|
72
|
+
if (config.ttlMs === 0 ||
|
|
73
|
+
containsRecognizedSecret(request.state) ||
|
|
74
|
+
containsRecognizedSecret(request.questions))
|
|
75
|
+
return undefined;
|
|
76
|
+
try {
|
|
77
|
+
const targets = planTargets(registry, request.provider, request.model);
|
|
78
|
+
const { provider, model } = targets[0];
|
|
79
|
+
const material = [targets, scope ?? null, canonicalState(request.state)];
|
|
80
|
+
const key = createHash("sha256")
|
|
81
|
+
.update(JSON.stringify([...material, request.questions]))
|
|
82
|
+
.digest("hex");
|
|
83
|
+
return { key, provider, model };
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
// Let the normal decision path report configuration errors.
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
async decide(request, registry, scope) {
|
|
92
|
+
const stopped = decisionStopError(request.context ?? {});
|
|
93
|
+
if (stopped)
|
|
94
|
+
throw stopped;
|
|
95
|
+
const target = cacheKey(request, registry, scope);
|
|
96
|
+
if (target === undefined) {
|
|
97
|
+
return { ...(await routeDecision(request, registry)), cache: "bypass" };
|
|
98
|
+
}
|
|
99
|
+
const { key } = target;
|
|
100
|
+
const entry = entries.get(key);
|
|
101
|
+
if (entry && now() < entry.expiresAt) {
|
|
102
|
+
entries.delete(key);
|
|
103
|
+
entries.set(key, entry);
|
|
104
|
+
return { result: structuredClone(entry.result), attempts: [], cache: "hit" };
|
|
105
|
+
}
|
|
106
|
+
remove(key);
|
|
107
|
+
let flight = flights.get(key);
|
|
108
|
+
const cache = flight ? "shared" : "miss";
|
|
109
|
+
if (!flight) {
|
|
110
|
+
const controller = new AbortController();
|
|
111
|
+
const promise = routeDecision({ ...request, context: { signal: controller.signal } }, registry).then((routed) => {
|
|
112
|
+
// A fallback answer belongs to another model, so it is not stored under this key.
|
|
113
|
+
const last = routed.attempts.at(-1);
|
|
114
|
+
if (last?.provider === target.provider && last.model === target.model) {
|
|
115
|
+
store(key, routed.result);
|
|
116
|
+
}
|
|
117
|
+
return routed;
|
|
118
|
+
});
|
|
119
|
+
const created = { promise, controller, waiters: 0 };
|
|
120
|
+
// A cancelled flight may reject after every waiter has left.
|
|
121
|
+
promise
|
|
122
|
+
.catch(() => undefined)
|
|
123
|
+
.finally(() => {
|
|
124
|
+
if (flights.get(key) === created)
|
|
125
|
+
flights.delete(key);
|
|
126
|
+
});
|
|
127
|
+
flights.set(key, created);
|
|
128
|
+
flight = created;
|
|
129
|
+
}
|
|
130
|
+
const current = flight;
|
|
131
|
+
const release = () => {
|
|
132
|
+
if (flights.get(key) === current)
|
|
133
|
+
flights.delete(key);
|
|
134
|
+
current.controller.abort();
|
|
135
|
+
};
|
|
136
|
+
return { ...(await waitFor(current, request.context, release)), cache };
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
5
|
+
import { createDecisionEngine } from "./engine.js";
|
|
6
|
+
import { DecisionError } from "./errors.js";
|
|
7
|
+
const usage = `Usage: verdict <command> [--input <file>]
|
|
8
|
+
|
|
9
|
+
Commands:
|
|
10
|
+
serve Start the MCP server on stdio.
|
|
11
|
+
decide Run decision_decide with a JSON request.
|
|
12
|
+
run Run decision_run with a JSON request.
|
|
13
|
+
validate Run decision_validate with a JSON request.
|
|
14
|
+
providers Report provider readiness.
|
|
15
|
+
templates List installed templates.
|
|
16
|
+
|
|
17
|
+
decide, run and validate read JSON from --input or from stdin. Results go to stdout as
|
|
18
|
+
JSON, and diagnostics go to stderr.
|
|
19
|
+
|
|
20
|
+
Exit codes: 0 success, 1 internal error, 2 usage or invalid input, 3 configuration error,
|
|
21
|
+
4 provider or decision failure, 5 validate found invalid state, 130 cancelled.`;
|
|
22
|
+
const exitCodes = {
|
|
23
|
+
ok: 0,
|
|
24
|
+
internal: 1,
|
|
25
|
+
usage: 2,
|
|
26
|
+
configuration: 3,
|
|
27
|
+
provider: 4,
|
|
28
|
+
invalid: 5,
|
|
29
|
+
cancelled: 130,
|
|
30
|
+
};
|
|
31
|
+
const errorExitCodes = {
|
|
32
|
+
invalid_request: exitCodes.usage,
|
|
33
|
+
configuration: exitCodes.configuration,
|
|
34
|
+
cancelled: exitCodes.cancelled,
|
|
35
|
+
timeout: exitCodes.provider,
|
|
36
|
+
transport: exitCodes.provider,
|
|
37
|
+
http: exitCodes.provider,
|
|
38
|
+
invalid_response: exitCodes.provider,
|
|
39
|
+
overload: exitCodes.provider,
|
|
40
|
+
output_limit: exitCodes.provider,
|
|
41
|
+
};
|
|
42
|
+
class UsageError extends Error {
|
|
43
|
+
}
|
|
44
|
+
async function readInput(path) {
|
|
45
|
+
let text;
|
|
46
|
+
try {
|
|
47
|
+
if (path === undefined) {
|
|
48
|
+
const chunks = [];
|
|
49
|
+
for await (const chunk of process.stdin)
|
|
50
|
+
chunks.push(chunk);
|
|
51
|
+
text = Buffer.concat(chunks).toString("utf8");
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
text = await readFile(path, "utf8");
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
throw new UsageError("Could not read the input.");
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
return JSON.parse(text);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
throw new UsageError("The input is not valid JSON.");
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function execute(command, engine, input, signal) {
|
|
68
|
+
const write = (value) => process.stdout.write(JSON.stringify(value, null, 2) + "\n");
|
|
69
|
+
switch (command) {
|
|
70
|
+
case "decide":
|
|
71
|
+
write(await engine.decide((await readInput(input)), { signal }));
|
|
72
|
+
return exitCodes.ok;
|
|
73
|
+
case "run":
|
|
74
|
+
write(await engine.run((await readInput(input)), { signal }));
|
|
75
|
+
return exitCodes.ok;
|
|
76
|
+
case "validate": {
|
|
77
|
+
const result = await engine.validate((await readInput(input)));
|
|
78
|
+
write(result);
|
|
79
|
+
return result.valid ? exitCodes.ok : exitCodes.invalid;
|
|
80
|
+
}
|
|
81
|
+
case "providers":
|
|
82
|
+
write(await engine.providers({ signal }));
|
|
83
|
+
return exitCodes.ok;
|
|
84
|
+
case "templates":
|
|
85
|
+
write(engine.templates());
|
|
86
|
+
return exitCodes.ok;
|
|
87
|
+
default:
|
|
88
|
+
throw new UsageError(usage);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
async function main() {
|
|
92
|
+
let command;
|
|
93
|
+
let input;
|
|
94
|
+
try {
|
|
95
|
+
const { values, positionals } = parseArgs({
|
|
96
|
+
allowPositionals: true,
|
|
97
|
+
options: { input: { type: "string" }, help: { type: "boolean" } },
|
|
98
|
+
});
|
|
99
|
+
if (values.help) {
|
|
100
|
+
process.stdout.write(usage + "\n");
|
|
101
|
+
return exitCodes.ok;
|
|
102
|
+
}
|
|
103
|
+
if (positionals.length !== 1)
|
|
104
|
+
throw new UsageError(usage);
|
|
105
|
+
[command] = positionals;
|
|
106
|
+
input = values.input;
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
console.error(error instanceof UsageError ? error.message : usage);
|
|
110
|
+
return exitCodes.usage;
|
|
111
|
+
}
|
|
112
|
+
const controller = new AbortController();
|
|
113
|
+
try {
|
|
114
|
+
const engine = createDecisionEngine();
|
|
115
|
+
if (command === "serve") {
|
|
116
|
+
if (input !== undefined)
|
|
117
|
+
throw new UsageError(usage);
|
|
118
|
+
void serveStdio(() => engine.createMcpServer());
|
|
119
|
+
console.error("Decision Models MCP server running on stdio");
|
|
120
|
+
return exitCodes.ok;
|
|
121
|
+
}
|
|
122
|
+
process.once("SIGINT", () => controller.abort());
|
|
123
|
+
return await execute(command, engine, input, controller.signal);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
if (error instanceof UsageError) {
|
|
127
|
+
console.error(error.message);
|
|
128
|
+
return exitCodes.usage;
|
|
129
|
+
}
|
|
130
|
+
if (error instanceof DecisionError) {
|
|
131
|
+
console.error(error.message);
|
|
132
|
+
return errorExitCodes[error.code];
|
|
133
|
+
}
|
|
134
|
+
if (controller.signal.aborted) {
|
|
135
|
+
console.error("Decision cancelled.");
|
|
136
|
+
return exitCodes.cancelled;
|
|
137
|
+
}
|
|
138
|
+
console.error("Decision failed.");
|
|
139
|
+
return exitCodes.internal;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
process.exitCode = await main();
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { DecisionError } from "./errors.js";
|
|
2
|
+
import type { DecisionContext } from "./types.js";
|
|
3
|
+
export declare function decisionStopError(context: DecisionContext): DecisionError | undefined;
|
|
4
|
+
export declare class ProviderQueue {
|
|
5
|
+
private readonly maxActive;
|
|
6
|
+
private readonly maxQueued;
|
|
7
|
+
private active;
|
|
8
|
+
private readonly waiting;
|
|
9
|
+
constructor(maxActive: number, maxQueued: number);
|
|
10
|
+
run<T>(context: DecisionContext, work: (signal: AbortSignal) => Promise<T>, onFailure?: (error: unknown) => void): Promise<T>;
|
|
11
|
+
private drain;
|
|
12
|
+
}
|