@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,110 @@
|
|
|
1
|
+
import { addAbortListener } from "node:events";
|
|
2
|
+
import { DecisionError } from "./errors.js";
|
|
3
|
+
export function decisionStopError(context) {
|
|
4
|
+
if (context.signal?.aborted) {
|
|
5
|
+
return new DecisionError("cancelled", "Decision request was cancelled.");
|
|
6
|
+
}
|
|
7
|
+
if (context.deadlineAt !== undefined && !(performance.now() < context.deadlineAt)) {
|
|
8
|
+
return new DecisionError("timeout", "Decision request timed out.");
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export class ProviderQueue {
|
|
12
|
+
maxActive;
|
|
13
|
+
maxQueued;
|
|
14
|
+
active = 0;
|
|
15
|
+
waiting = [];
|
|
16
|
+
constructor(maxActive, maxQueued) {
|
|
17
|
+
this.maxActive = maxActive;
|
|
18
|
+
this.maxQueued = maxQueued;
|
|
19
|
+
}
|
|
20
|
+
run(context, work, onFailure) {
|
|
21
|
+
if (this.waiting.length === this.maxQueued) {
|
|
22
|
+
for (const job of this.waiting.slice())
|
|
23
|
+
job.discardIfStopped();
|
|
24
|
+
}
|
|
25
|
+
const stopped = decisionStopError(context);
|
|
26
|
+
if (stopped) {
|
|
27
|
+
onFailure?.(stopped);
|
|
28
|
+
return Promise.reject(stopped);
|
|
29
|
+
}
|
|
30
|
+
if (this.active >= this.maxActive && this.waiting.length >= this.maxQueued) {
|
|
31
|
+
const error = new DecisionError("overload", "Provider decision queue is full (overload).");
|
|
32
|
+
onFailure?.(error);
|
|
33
|
+
return Promise.reject(error);
|
|
34
|
+
}
|
|
35
|
+
return new Promise((resolve, reject) => {
|
|
36
|
+
let started = false;
|
|
37
|
+
const controller = new AbortController();
|
|
38
|
+
const cancel = () => stop(new DecisionError("cancelled", "Decision request was cancelled."));
|
|
39
|
+
const timeout = () => stop(new DecisionError("timeout", "Decision request timed out."));
|
|
40
|
+
const listener = context.signal && addAbortListener(context.signal, cancel);
|
|
41
|
+
const timer = context.deadlineAt === undefined
|
|
42
|
+
? undefined
|
|
43
|
+
: setTimeout(timeout, Math.max(1, Math.ceil(context.deadlineAt - performance.now())));
|
|
44
|
+
function cleanup() {
|
|
45
|
+
clearTimeout(timer);
|
|
46
|
+
listener?.[Symbol.dispose]();
|
|
47
|
+
}
|
|
48
|
+
const fail = (error) => {
|
|
49
|
+
reject(error);
|
|
50
|
+
// Stop a failing batch before a freed slot can dispatch one of its queued items.
|
|
51
|
+
onFailure?.(error);
|
|
52
|
+
};
|
|
53
|
+
const stop = (error) => {
|
|
54
|
+
if (controller.signal.aborted)
|
|
55
|
+
return;
|
|
56
|
+
controller.abort(error);
|
|
57
|
+
cleanup();
|
|
58
|
+
if (!started) {
|
|
59
|
+
const index = this.waiting.indexOf(job);
|
|
60
|
+
if (index !== -1)
|
|
61
|
+
this.waiting.splice(index, 1);
|
|
62
|
+
}
|
|
63
|
+
fail(error);
|
|
64
|
+
};
|
|
65
|
+
const discardIfStopped = () => {
|
|
66
|
+
const error = decisionStopError(context);
|
|
67
|
+
if (!error)
|
|
68
|
+
return false;
|
|
69
|
+
stop(error);
|
|
70
|
+
return true;
|
|
71
|
+
};
|
|
72
|
+
const start = () => {
|
|
73
|
+
if (discardIfStopped())
|
|
74
|
+
return;
|
|
75
|
+
started = true;
|
|
76
|
+
this.active++;
|
|
77
|
+
void (async () => {
|
|
78
|
+
try {
|
|
79
|
+
const result = await work(controller.signal);
|
|
80
|
+
const stopped = decisionStopError(context);
|
|
81
|
+
if (stopped)
|
|
82
|
+
stop(stopped);
|
|
83
|
+
else
|
|
84
|
+
resolve(result);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (!controller.signal.aborted)
|
|
88
|
+
fail(decisionStopError(context) ?? error);
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
// A provider keeps its slot until it settles, even after cancellation.
|
|
92
|
+
cleanup();
|
|
93
|
+
this.active--;
|
|
94
|
+
this.drain();
|
|
95
|
+
}
|
|
96
|
+
})();
|
|
97
|
+
};
|
|
98
|
+
const job = { start, discardIfStopped };
|
|
99
|
+
if (this.active < this.maxActive)
|
|
100
|
+
start();
|
|
101
|
+
else
|
|
102
|
+
this.waiting.push(job);
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
drain() {
|
|
106
|
+
while (this.active < this.maxActive && this.waiting.length > 0) {
|
|
107
|
+
this.waiting.shift()?.start();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export declare const providerIds: readonly ["ollama", "typesafe", "opencode-go"];
|
|
2
|
+
export type ActionPolicyFailureMode = "native" | "review" | "block";
|
|
3
|
+
export type ProviderId = (typeof providerIds)[number];
|
|
4
|
+
export type ModelConfig = Readonly<{
|
|
5
|
+
defaultModel: string;
|
|
6
|
+
allowedModels?: readonly string[];
|
|
7
|
+
}>;
|
|
8
|
+
export type OllamaConfig = ModelConfig & Readonly<{
|
|
9
|
+
baseUrl: string;
|
|
10
|
+
loopback: boolean;
|
|
11
|
+
localOnly: boolean;
|
|
12
|
+
timeoutMs: number;
|
|
13
|
+
keepAlive?: string;
|
|
14
|
+
}>;
|
|
15
|
+
export type HostedConfig = Readonly<{
|
|
16
|
+
status: "inactive" | "invalid";
|
|
17
|
+
detail: string;
|
|
18
|
+
}> | (ModelConfig & Readonly<{
|
|
19
|
+
status: "configured";
|
|
20
|
+
apiKey: string;
|
|
21
|
+
timeoutMs: number;
|
|
22
|
+
}>);
|
|
23
|
+
export type CacheConfig = Readonly<{
|
|
24
|
+
ttlMs: number;
|
|
25
|
+
maxEntries: number;
|
|
26
|
+
maxBytes: number;
|
|
27
|
+
}>;
|
|
28
|
+
export type RouteTarget = Readonly<{
|
|
29
|
+
provider: ProviderId;
|
|
30
|
+
model: string;
|
|
31
|
+
}>;
|
|
32
|
+
export type RoutingConfig = Readonly<{
|
|
33
|
+
retryAttempts: number;
|
|
34
|
+
retryBilled: boolean;
|
|
35
|
+
fallback: readonly RouteTarget[];
|
|
36
|
+
}>;
|
|
37
|
+
export type ProviderConfig = Readonly<{
|
|
38
|
+
cache: CacheConfig;
|
|
39
|
+
routing: RoutingConfig;
|
|
40
|
+
actionPolicyTimeoutMs: number;
|
|
41
|
+
actionPolicyFailureMode: ActionPolicyFailureMode;
|
|
42
|
+
actionPolicyScope: "consequential" | "strict";
|
|
43
|
+
defaultProvider: ProviderId;
|
|
44
|
+
allowedProviders: readonly ProviderId[];
|
|
45
|
+
ollama: OllamaConfig;
|
|
46
|
+
typesafe: HostedConfig;
|
|
47
|
+
opencodeGo: HostedConfig;
|
|
48
|
+
}>;
|
|
49
|
+
export declare function allowlistSetting(provider: string): string;
|
|
50
|
+
export declare function readCacheConfig(env: NodeJS.ProcessEnv): CacheConfig;
|
|
51
|
+
export type TelemetryConfig = Readonly<{
|
|
52
|
+
file?: string;
|
|
53
|
+
maxBytes: number;
|
|
54
|
+
maxFiles: number;
|
|
55
|
+
}>;
|
|
56
|
+
export declare function readTelemetryConfig(env: NodeJS.ProcessEnv): TelemetryConfig;
|
|
57
|
+
export declare function readActionPolicyFailureMode(env: NodeJS.ProcessEnv): ActionPolicyFailureMode;
|
|
58
|
+
export declare function readActionPolicyScope(env: NodeJS.ProcessEnv): ProviderConfig["actionPolicyScope"];
|
|
59
|
+
export declare function readProviderConfig(env: NodeJS.ProcessEnv): ProviderConfig;
|
|
60
|
+
export declare function resolveModel(config: ModelConfig, requested: string | undefined, allowlistSetting: string): string;
|
|
61
|
+
export declare function classifyOllamaLocality(config: OllamaConfig, model: string): "local" | "non-local" | "unknown";
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { lstatSync } from "node:fs";
|
|
2
|
+
import { isIP } from "node:net";
|
|
3
|
+
import { isAbsolute } from "node:path";
|
|
4
|
+
import { DecisionError } from "./errors.js";
|
|
5
|
+
export const providerIds = ["ollama", "typesafe", "opencode-go"];
|
|
6
|
+
const MAX_TIMEOUT_MS = 2_147_483_647;
|
|
7
|
+
// Model revisions are unknown until provider discovery reports them, so entries stay short-lived.
|
|
8
|
+
const MAX_CACHE_TTL_MS = 300_000;
|
|
9
|
+
function parseProviderId(value, setting) {
|
|
10
|
+
const provider = providerIds.find((id) => id === value);
|
|
11
|
+
if (!provider)
|
|
12
|
+
throw new DecisionError("configuration", `${setting} must name a supported provider.`);
|
|
13
|
+
return provider;
|
|
14
|
+
}
|
|
15
|
+
function parseList(value) {
|
|
16
|
+
return Object.freeze(value
|
|
17
|
+
.split(",")
|
|
18
|
+
.map((entry) => entry.trim())
|
|
19
|
+
.filter(Boolean));
|
|
20
|
+
}
|
|
21
|
+
function validateModelName(value, setting) {
|
|
22
|
+
if (value.length > 256 || !value.trim() || value !== value.trim() || /\p{Cc}/u.test(value)) {
|
|
23
|
+
throw new DecisionError("configuration", `${setting} must be a nonblank model name of at most 256 characters without surrounding whitespace or control characters.`);
|
|
24
|
+
}
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
function parseBoolean(value, name) {
|
|
28
|
+
if (value === undefined || value === "false")
|
|
29
|
+
return false;
|
|
30
|
+
if (value === "true")
|
|
31
|
+
return true;
|
|
32
|
+
throw new DecisionError("configuration", `${name} must be true or false.`);
|
|
33
|
+
}
|
|
34
|
+
function parseTimeout(value, fallback, name) {
|
|
35
|
+
const timeout = Number(value ?? fallback);
|
|
36
|
+
if (!Number.isInteger(timeout) || timeout < 1 || timeout > MAX_TIMEOUT_MS) {
|
|
37
|
+
throw new DecisionError("configuration", `${name} must be an integer between 1 and ${MAX_TIMEOUT_MS}.`);
|
|
38
|
+
}
|
|
39
|
+
return timeout;
|
|
40
|
+
}
|
|
41
|
+
function readOllama(env, localOnly) {
|
|
42
|
+
let url;
|
|
43
|
+
try {
|
|
44
|
+
url = new URL(env.OLLAMA_BASE_URL ?? "http://127.0.0.1:11434");
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
throw new DecisionError("configuration", "OLLAMA_BASE_URL must be an absolute HTTP or HTTPS URL.");
|
|
48
|
+
}
|
|
49
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
50
|
+
throw new DecisionError("configuration", "OLLAMA_BASE_URL must be an absolute HTTP or HTTPS URL.");
|
|
51
|
+
}
|
|
52
|
+
if (url.username || url.password || /[?#]/.test(url.href)) {
|
|
53
|
+
throw new DecisionError("configuration", "OLLAMA_BASE_URL must omit credentials, queries and fragments.");
|
|
54
|
+
}
|
|
55
|
+
const host = url.hostname;
|
|
56
|
+
const loopback = host === "localhost" || host === "[::1]" || (isIP(host) === 4 && host.startsWith("127."));
|
|
57
|
+
const insecureHttp = parseBoolean(env.OLLAMA_ALLOW_INSECURE_HTTP, "OLLAMA_ALLOW_INSECURE_HTTP");
|
|
58
|
+
if (url.protocol === "http:" && !loopback && !insecureHttp) {
|
|
59
|
+
throw new DecisionError("configuration", "Non-loopback Ollama endpoints require HTTPS or OLLAMA_ALLOW_INSECURE_HTTP=true.");
|
|
60
|
+
}
|
|
61
|
+
return Object.freeze({
|
|
62
|
+
baseUrl: url.href.replace(/\/+$/, ""),
|
|
63
|
+
loopback,
|
|
64
|
+
localOnly,
|
|
65
|
+
defaultModel: validateModelName(env.OLLAMA_DECISION_MODEL ?? "d3:4b", "OLLAMA_DECISION_MODEL"),
|
|
66
|
+
allowedModels: env.OLLAMA_ALLOWED_MODELS === undefined ? undefined : parseList(env.OLLAMA_ALLOWED_MODELS),
|
|
67
|
+
timeoutMs: parseTimeout(env.OLLAMA_TIMEOUT_MS, 120_000, "OLLAMA_TIMEOUT_MS"),
|
|
68
|
+
keepAlive: env.OLLAMA_KEEP_ALIVE,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
const hostedSpecs = [
|
|
72
|
+
{ id: "typesafe", prefix: "TYPESAFE", label: "TypeSafe", defaultModel: "jev-latest" },
|
|
73
|
+
{ id: "opencode-go", prefix: "OPENCODE_GO", label: "OpenCode Go", defaultModel: "jev-1.14" },
|
|
74
|
+
];
|
|
75
|
+
// The allowlist setting that names the approved models of each provider.
|
|
76
|
+
export function allowlistSetting(provider) {
|
|
77
|
+
const spec = hostedSpecs.find(({ id }) => id === provider);
|
|
78
|
+
return spec ? `${spec.prefix}_ALLOWED_MODELS` : "OLLAMA_ALLOWED_MODELS";
|
|
79
|
+
}
|
|
80
|
+
function readHosted(env, spec, allowed) {
|
|
81
|
+
const { prefix, label } = spec;
|
|
82
|
+
const apiKey = env[`${prefix}_API_KEY`]?.trim();
|
|
83
|
+
if (!apiKey) {
|
|
84
|
+
return Object.freeze({ status: "inactive", detail: `${prefix}_API_KEY is not configured.` });
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
if (!/^[!-~]+$/.test(apiKey)) {
|
|
88
|
+
throw new DecisionError("configuration", `${prefix}_API_KEY must be a single ASCII token.`);
|
|
89
|
+
}
|
|
90
|
+
const allowedModels = env[`${prefix}_ALLOWED_MODELS`];
|
|
91
|
+
return Object.freeze({
|
|
92
|
+
status: "configured",
|
|
93
|
+
apiKey,
|
|
94
|
+
timeoutMs: parseTimeout(env[`${prefix}_TIMEOUT_MS`], 30_000, `${prefix}_TIMEOUT_MS`),
|
|
95
|
+
defaultModel: validateModelName(env[`${prefix}_DECISION_MODEL`] ?? spec.defaultModel, `${prefix}_DECISION_MODEL`),
|
|
96
|
+
allowedModels: allowedModels === undefined ? undefined : parseList(allowedModels),
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (allowed)
|
|
101
|
+
throw error;
|
|
102
|
+
return Object.freeze({ status: "invalid", detail: `${label} configuration is invalid.` });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function parseBoundedInteger(value, fallback, minimum, maximum, name) {
|
|
106
|
+
const parsed = Number(value ?? fallback);
|
|
107
|
+
if (!Number.isInteger(parsed) || parsed < minimum || parsed > maximum) {
|
|
108
|
+
throw new DecisionError("configuration", `${name} must be an integer between ${minimum} and ${maximum}.`);
|
|
109
|
+
}
|
|
110
|
+
return parsed;
|
|
111
|
+
}
|
|
112
|
+
export function readCacheConfig(env) {
|
|
113
|
+
return Object.freeze({
|
|
114
|
+
ttlMs: parseBoundedInteger(env.DECISION_CACHE_TTL_MS, 0, 0, MAX_CACHE_TTL_MS, "DECISION_CACHE_TTL_MS"),
|
|
115
|
+
maxEntries: parseBoundedInteger(env.DECISION_CACHE_MAX_ENTRIES, 256, 1, 10_000, "DECISION_CACHE_MAX_ENTRIES"),
|
|
116
|
+
maxBytes: 8 * 1_048_576,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
// Telemetry is off unless an operator names an absolute audit file.
|
|
120
|
+
export function readTelemetryConfig(env) {
|
|
121
|
+
const file = env.DECISION_TELEMETRY_FILE;
|
|
122
|
+
if (file !== undefined && !isAbsolute(file)) {
|
|
123
|
+
throw new DecisionError("configuration", "DECISION_TELEMETRY_FILE must be an absolute path.");
|
|
124
|
+
}
|
|
125
|
+
if (file !== undefined) {
|
|
126
|
+
try {
|
|
127
|
+
if (lstatSync(file, { throwIfNoEntry: false })?.isFile() === false)
|
|
128
|
+
throw new Error();
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
throw new DecisionError("configuration", "DECISION_TELEMETRY_FILE must name a regular file or a new file.");
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return Object.freeze({
|
|
135
|
+
file,
|
|
136
|
+
maxBytes: parseBoundedInteger(env.DECISION_TELEMETRY_MAX_BYTES, 10 * 1_048_576, 65_536, 1_073_741_824, "DECISION_TELEMETRY_MAX_BYTES"),
|
|
137
|
+
maxFiles: parseBoundedInteger(env.DECISION_TELEMETRY_MAX_FILES, 3, 1, 20, "DECISION_TELEMETRY_MAX_FILES"),
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
function readRouting(env, allowedProviders, ollama, hosted) {
|
|
141
|
+
const allowRemote = parseBoolean(env.DECISION_FALLBACK_ALLOW_REMOTE, "DECISION_FALLBACK_ALLOW_REMOTE");
|
|
142
|
+
const fallback = [];
|
|
143
|
+
for (const entry of parseList(env.DECISION_FALLBACK ?? "")) {
|
|
144
|
+
// Provider IDs contain no colon, while Ollama model names usually do.
|
|
145
|
+
const separator = entry.indexOf(":");
|
|
146
|
+
const model = entry.slice(separator + 1);
|
|
147
|
+
if (separator < 1 || !model) {
|
|
148
|
+
throw new DecisionError("configuration", "DECISION_FALLBACK entries must have the form provider:model.");
|
|
149
|
+
}
|
|
150
|
+
const provider = parseProviderId(entry.slice(0, separator), "DECISION_FALLBACK");
|
|
151
|
+
if (!allowedProviders.includes(provider)) {
|
|
152
|
+
throw new DecisionError("configuration", "DECISION_FALLBACK must name providers in DECISION_ALLOWED_PROVIDERS.");
|
|
153
|
+
}
|
|
154
|
+
let locality = "non-local";
|
|
155
|
+
if (provider === "ollama") {
|
|
156
|
+
resolveModel(ollama, model, "OLLAMA_ALLOWED_MODELS");
|
|
157
|
+
locality = classifyOllamaLocality(ollama, model);
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
const settings = hosted[provider];
|
|
161
|
+
if (settings.status !== "configured")
|
|
162
|
+
throw new DecisionError("configuration", settings.detail);
|
|
163
|
+
resolveModel(settings, model, allowlistSetting(provider));
|
|
164
|
+
}
|
|
165
|
+
if (locality !== "local" && (ollama.localOnly || !allowRemote)) {
|
|
166
|
+
throw new DecisionError("configuration", "A DECISION_FALLBACK target that is not an approved local model requires DECISION_FALLBACK_ALLOW_REMOTE=true and is not allowed in local-only mode.");
|
|
167
|
+
}
|
|
168
|
+
if (fallback.some((target) => target.provider === provider && target.model === model)) {
|
|
169
|
+
throw new DecisionError("configuration", "DECISION_FALLBACK contains a duplicate target.");
|
|
170
|
+
}
|
|
171
|
+
fallback.push(Object.freeze({ provider, model }));
|
|
172
|
+
}
|
|
173
|
+
if (fallback.length > 4) {
|
|
174
|
+
throw new DecisionError("configuration", "DECISION_FALLBACK accepts at most 4 targets.");
|
|
175
|
+
}
|
|
176
|
+
return Object.freeze({
|
|
177
|
+
retryAttempts: parseBoundedInteger(env.DECISION_RETRY_ATTEMPTS, 0, 0, 3, "DECISION_RETRY_ATTEMPTS"),
|
|
178
|
+
retryBilled: parseBoolean(env.DECISION_RETRY_BILLED, "DECISION_RETRY_BILLED"),
|
|
179
|
+
fallback: Object.freeze(fallback),
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
export function readActionPolicyFailureMode(env) {
|
|
183
|
+
const mode = env.DECISION_ACTION_POLICY_FAILURE_MODE ?? "native";
|
|
184
|
+
if (mode === "native" || mode === "review" || mode === "block")
|
|
185
|
+
return mode;
|
|
186
|
+
throw new DecisionError("configuration", "DECISION_ACTION_POLICY_FAILURE_MODE must be native, review, or block.");
|
|
187
|
+
}
|
|
188
|
+
export function readActionPolicyScope(env) {
|
|
189
|
+
const scope = env.DECISION_ACTION_POLICY_SCOPE ?? "consequential";
|
|
190
|
+
if (scope === "consequential" || scope === "strict")
|
|
191
|
+
return scope;
|
|
192
|
+
throw new DecisionError("configuration", "DECISION_ACTION_POLICY_SCOPE must be consequential or strict.");
|
|
193
|
+
}
|
|
194
|
+
export function readProviderConfig(env) {
|
|
195
|
+
const defaultProvider = parseProviderId(env.DECISION_PROVIDER ?? "ollama", "DECISION_PROVIDER");
|
|
196
|
+
const configured = env.DECISION_ALLOWED_PROVIDERS;
|
|
197
|
+
const allowedProviders = Object.freeze(configured !== undefined
|
|
198
|
+
? parseList(configured).map((id) => parseProviderId(id, "DECISION_ALLOWED_PROVIDERS"))
|
|
199
|
+
: [defaultProvider]);
|
|
200
|
+
if (!allowedProviders.includes(defaultProvider)) {
|
|
201
|
+
throw new DecisionError("configuration", "DECISION_ALLOWED_PROVIDERS must include DECISION_PROVIDER.");
|
|
202
|
+
}
|
|
203
|
+
const localOnly = parseBoolean(env.DECISION_LOCAL_ONLY, "DECISION_LOCAL_ONLY");
|
|
204
|
+
if (localOnly && defaultProvider !== "ollama") {
|
|
205
|
+
throw new DecisionError("configuration", "Local-only mode requires Ollama as the default provider.");
|
|
206
|
+
}
|
|
207
|
+
const [typesafe, opencodeGo] = hostedSpecs.map((spec) => {
|
|
208
|
+
const settings = localOnly
|
|
209
|
+
? Object.freeze({
|
|
210
|
+
status: "inactive",
|
|
211
|
+
detail: `Local-only mode does not allow the hosted ${spec.label} provider.`,
|
|
212
|
+
})
|
|
213
|
+
: readHosted(env, spec, allowedProviders.includes(spec.id));
|
|
214
|
+
if (defaultProvider === spec.id && settings.status !== "configured") {
|
|
215
|
+
throw new DecisionError("configuration", settings.detail);
|
|
216
|
+
}
|
|
217
|
+
return settings;
|
|
218
|
+
});
|
|
219
|
+
const ollama = readOllama(env, localOnly);
|
|
220
|
+
return Object.freeze({
|
|
221
|
+
cache: readCacheConfig(env),
|
|
222
|
+
routing: readRouting(env, allowedProviders, ollama, { typesafe, "opencode-go": opencodeGo }),
|
|
223
|
+
defaultProvider,
|
|
224
|
+
allowedProviders,
|
|
225
|
+
actionPolicyFailureMode: readActionPolicyFailureMode(env),
|
|
226
|
+
actionPolicyScope: readActionPolicyScope(env),
|
|
227
|
+
actionPolicyTimeoutMs: parseTimeout(env.DECISION_ACTION_POLICY_TIMEOUT_MS, 25_000, "DECISION_ACTION_POLICY_TIMEOUT_MS"),
|
|
228
|
+
ollama,
|
|
229
|
+
typesafe,
|
|
230
|
+
opencodeGo,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
export function resolveModel(config, requested, allowlistSetting) {
|
|
234
|
+
const model = validateModelName(requested ?? config.defaultModel, "The model");
|
|
235
|
+
if (config.allowedModels && !config.allowedModels.includes(model)) {
|
|
236
|
+
throw new DecisionError("configuration", `The model is not allowed. Check ${allowlistSetting}.`);
|
|
237
|
+
}
|
|
238
|
+
return model;
|
|
239
|
+
}
|
|
240
|
+
export function classifyOllamaLocality(config, model) {
|
|
241
|
+
const modelName = model.split("/").at(-1) ?? model;
|
|
242
|
+
if (!config.loopback || /[:-]cloud(?:$|[-:@])/i.test(modelName))
|
|
243
|
+
return "non-local";
|
|
244
|
+
if (config.allowedModels?.includes(model))
|
|
245
|
+
return "local";
|
|
246
|
+
return "unknown";
|
|
247
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { type ProviderRegistry } from "./providers/index.js";
|
|
2
|
+
import { type RouteAttempt } from "./routing/router.js";
|
|
3
|
+
import { type GatePolicy } from "./schemas.js";
|
|
4
|
+
import { type BatchFailureMode, type BatchItem, type DecisionProvider, type DecisionRequest, type DecisionResponse, type JsonValue } from "./types.js";
|
|
5
|
+
export type RouteDependencies = {
|
|
6
|
+
sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
7
|
+
random: () => number;
|
|
8
|
+
};
|
|
9
|
+
export declare function failedRouteAttempts(error: unknown): RouteAttempt[] | undefined;
|
|
10
|
+
export declare function routeDecision(request: DecisionRequest, registry?: {
|
|
11
|
+
cache: Readonly<{
|
|
12
|
+
ttlMs: number;
|
|
13
|
+
maxEntries: number;
|
|
14
|
+
maxBytes: number;
|
|
15
|
+
}>;
|
|
16
|
+
routing: Readonly<{
|
|
17
|
+
retryAttempts: number;
|
|
18
|
+
retryBilled: boolean;
|
|
19
|
+
fallback: readonly import("./config.js").RouteTarget[];
|
|
20
|
+
}>;
|
|
21
|
+
localOnly: boolean;
|
|
22
|
+
locality: (id: string, model: string) => "local" | "non-local" | "unknown";
|
|
23
|
+
actionPolicyTimeoutMs: number;
|
|
24
|
+
actionPolicyFailureMode: import("./config.js").ActionPolicyFailureMode;
|
|
25
|
+
actionPolicyScope: "consequential" | "strict";
|
|
26
|
+
defaultProvider: "ollama" | "opencode-go" | "typesafe";
|
|
27
|
+
getProvider: (id?: string) => DecisionProvider;
|
|
28
|
+
effectiveModel: (id?: string, requestedModel?: string) => string;
|
|
29
|
+
resolveActionPolicyTarget(id?: string, requestedModel?: string): {
|
|
30
|
+
model: string;
|
|
31
|
+
locality: "local" | "non-local" | "unknown";
|
|
32
|
+
modelApproved: boolean;
|
|
33
|
+
};
|
|
34
|
+
listProviders(): DecisionProvider[];
|
|
35
|
+
}, deps?: RouteDependencies): Promise<{
|
|
36
|
+
result: DecisionResponse;
|
|
37
|
+
attempts: RouteAttempt[];
|
|
38
|
+
}>;
|
|
39
|
+
export declare function decide(request: DecisionRequest, registry?: {
|
|
40
|
+
cache: Readonly<{
|
|
41
|
+
ttlMs: number;
|
|
42
|
+
maxEntries: number;
|
|
43
|
+
maxBytes: number;
|
|
44
|
+
}>;
|
|
45
|
+
routing: Readonly<{
|
|
46
|
+
retryAttempts: number;
|
|
47
|
+
retryBilled: boolean;
|
|
48
|
+
fallback: readonly import("./config.js").RouteTarget[];
|
|
49
|
+
}>;
|
|
50
|
+
localOnly: boolean;
|
|
51
|
+
locality: (id: string, model: string) => "local" | "non-local" | "unknown";
|
|
52
|
+
actionPolicyTimeoutMs: number;
|
|
53
|
+
actionPolicyFailureMode: import("./config.js").ActionPolicyFailureMode;
|
|
54
|
+
actionPolicyScope: "consequential" | "strict";
|
|
55
|
+
defaultProvider: "ollama" | "opencode-go" | "typesafe";
|
|
56
|
+
getProvider: (id?: string) => DecisionProvider;
|
|
57
|
+
effectiveModel: (id?: string, requestedModel?: string) => string;
|
|
58
|
+
resolveActionPolicyTarget(id?: string, requestedModel?: string): {
|
|
59
|
+
model: string;
|
|
60
|
+
locality: "local" | "non-local" | "unknown";
|
|
61
|
+
modelApproved: boolean;
|
|
62
|
+
};
|
|
63
|
+
listProviders(): DecisionProvider[];
|
|
64
|
+
}): Promise<DecisionResponse>;
|
|
65
|
+
type BatchRequest = Omit<DecisionRequest, "state">;
|
|
66
|
+
export declare function batchDecide(states: JsonValue[], request: BatchRequest, concurrency?: number, registry?: ProviderRegistry, mode?: "fail_fast"): Promise<DecisionResponse[]>;
|
|
67
|
+
export declare function batchDecide(states: JsonValue[], request: BatchRequest, concurrency: number, registry: ProviderRegistry, mode: "partial"): Promise<BatchItem[]>;
|
|
68
|
+
export declare function batchDecide(states: JsonValue[], request: BatchRequest, concurrency: number, registry: ProviderRegistry, mode: BatchFailureMode): Promise<DecisionResponse[] | BatchItem[]>;
|
|
69
|
+
type Answer = Record<string, JsonValue>;
|
|
70
|
+
type GateAction = "allow" | "review" | "block";
|
|
71
|
+
export declare function gate(answers: Answer, inputPolicy?: GatePolicy): {
|
|
72
|
+
action: GateAction;
|
|
73
|
+
reasons: string[];
|
|
74
|
+
};
|
|
75
|
+
export {};
|