@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.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +625 -2
  3. package/config/routing/engineering.action-risk.consensus.v1.json +16 -0
  4. package/config/routing/engineering.task-route.cascade.v1.json +21 -0
  5. package/dist/action-policy.d.ts +104 -0
  6. package/dist/action-policy.js +173 -0
  7. package/dist/cache.d.ts +17 -0
  8. package/dist/cache.js +139 -0
  9. package/dist/cli.d.ts +2 -0
  10. package/dist/cli.js +142 -0
  11. package/dist/concurrency.d.ts +12 -0
  12. package/dist/concurrency.js +110 -0
  13. package/dist/config.d.ts +61 -0
  14. package/dist/config.js +247 -0
  15. package/dist/decision.d.ts +75 -0
  16. package/dist/decision.js +278 -0
  17. package/dist/engine.d.ts +63 -0
  18. package/dist/engine.js +79 -0
  19. package/dist/errors.d.ts +6 -0
  20. package/dist/errors.js +19 -0
  21. package/dist/http.d.ts +18 -0
  22. package/dist/http.js +140 -0
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.js +14 -0
  25. package/dist/package-info.d.ts +1 -0
  26. package/dist/package-info.js +5 -0
  27. package/dist/policy/evaluate.d.ts +7 -0
  28. package/dist/policy/evaluate.js +39 -0
  29. package/dist/policy/events.d.ts +32 -0
  30. package/dist/policy/events.js +31 -0
  31. package/dist/policy/payload.d.ts +6 -0
  32. package/dist/policy/payload.js +11 -0
  33. package/dist/policy/registry.d.ts +22 -0
  34. package/dist/policy/registry.js +89 -0
  35. package/dist/policy/schema.d.ts +198 -0
  36. package/dist/policy/schema.js +112 -0
  37. package/dist/policy/scope.d.ts +5 -0
  38. package/dist/policy/scope.js +120 -0
  39. package/dist/probability.d.ts +1 -0
  40. package/dist/probability.js +3 -0
  41. package/dist/providers/discovery.d.ts +10 -0
  42. package/dist/providers/discovery.js +113 -0
  43. package/dist/providers/index.d.ts +56 -0
  44. package/dist/providers/index.js +83 -0
  45. package/dist/providers/ollama.d.ts +12 -0
  46. package/dist/providers/ollama.js +93 -0
  47. package/dist/providers/opencode-go.d.ts +3 -0
  48. package/dist/providers/opencode-go.js +40 -0
  49. package/dist/providers/system-one.d.ts +21 -0
  50. package/dist/providers/system-one.js +44 -0
  51. package/dist/providers/typesafe.d.ts +3 -0
  52. package/dist/providers/typesafe.js +36 -0
  53. package/dist/public.d.ts +5 -0
  54. package/dist/public.js +5 -0
  55. package/dist/response.d.ts +6 -0
  56. package/dist/response.js +104 -0
  57. package/dist/routing/cascade.d.ts +112 -0
  58. package/dist/routing/cascade.js +220 -0
  59. package/dist/routing/consensus.d.ts +148 -0
  60. package/dist/routing/consensus.js +367 -0
  61. package/dist/routing/retry.d.ts +3 -0
  62. package/dist/routing/retry.js +47 -0
  63. package/dist/routing/router.d.ts +12 -0
  64. package/dist/routing/router.js +27 -0
  65. package/dist/schemas.d.ts +339 -0
  66. package/dist/schemas.js +283 -0
  67. package/dist/server.d.ts +42 -0
  68. package/dist/server.js +416 -0
  69. package/dist/telemetry/events.d.ts +15 -0
  70. package/dist/telemetry/events.js +87 -0
  71. package/dist/telemetry/sink.d.ts +7 -0
  72. package/dist/telemetry/sink.js +59 -0
  73. package/dist/templates/registry.d.ts +13 -0
  74. package/dist/templates/registry.js +100 -0
  75. package/dist/templates/schema.d.ts +115 -0
  76. package/dist/templates/schema.js +70 -0
  77. package/dist/types.d.ts +86 -0
  78. package/dist/types.js +2 -0
  79. package/package.json +77 -3
  80. package/policies/engineering-default.v1.json +36 -0
  81. package/policies/engineering-strict.v1.json +36 -0
  82. package/templates/engineering.action-risk.v1.json +32 -0
  83. package/templates/engineering.compatibility.v1.json +25 -0
  84. package/templates/engineering.pr-risk.v1.json +26 -0
  85. package/templates/engineering.security-sensitivity.v1.json +20 -0
  86. package/templates/engineering.task-route.v1.json +27 -0
  87. package/templates/engineering.test-depth.v1.json +26 -0
@@ -0,0 +1 @@
1
+ export declare function isProbability(value: unknown): value is number;
@@ -0,0 +1,3 @@
1
+ export function isProbability(value) {
2
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
3
+ }
@@ -0,0 +1,10 @@
1
+ import type { ModelConfig } from "../config.js";
2
+ import type { ModelReadiness, ProviderStatus } from "../types.js";
3
+ export declare const PROBE_TIMEOUT_MS = 2000;
4
+ export declare const QUESTION_TYPES: NonNullable<ProviderStatus["questionTypes"]>;
5
+ export declare function cachedProbe(probe: () => Promise<ProviderStatus>): (signal?: AbortSignal, deadlineAt?: number) => Promise<ProviderStatus>;
6
+ export declare function approvedModels(config: ModelConfig): string[] | undefined;
7
+ export declare function notConfigured(detail: string): ProviderStatus;
8
+ export declare function discovered(models: ModelReadiness[]): ProviderStatus;
9
+ export declare function unexpectedModelList(label: string): ProviderStatus;
10
+ export declare function discoveryFailure(label: string, error: unknown): ProviderStatus;
@@ -0,0 +1,113 @@
1
+ import { addAbortListener } from "node:events";
2
+ import { decisionStopError } from "../concurrency.js";
3
+ import { DecisionError } from "../errors.js";
4
+ import { DecisionProviderError } from "../http.js";
5
+ export const PROBE_TIMEOUT_MS = 2_000;
6
+ const PROBE_TTL_MS = 10_000;
7
+ export const QUESTION_TYPES = [
8
+ "choice",
9
+ "noul",
10
+ "score",
11
+ ];
12
+ // Concurrent callers share one probe, and a result is reused briefly to bound provider load.
13
+ export function cachedProbe(probe) {
14
+ let cached;
15
+ let inflight;
16
+ return async (signal, deadlineAt) => {
17
+ const context = { signal, deadlineAt };
18
+ const stopped = decisionStopError(context);
19
+ if (stopped)
20
+ throw stopped;
21
+ if (cached && Date.now() < cached.expiresAt)
22
+ return Promise.resolve(cached.status);
23
+ inflight ??= probe()
24
+ .then((status) => {
25
+ cached = { status, expiresAt: Date.now() + PROBE_TTL_MS };
26
+ return status;
27
+ })
28
+ .finally(() => {
29
+ inflight = undefined;
30
+ });
31
+ if (!signal && deadlineAt === undefined)
32
+ return inflight;
33
+ let listener;
34
+ let timer;
35
+ const stop = new Promise((_resolve, reject) => {
36
+ listener =
37
+ signal &&
38
+ addAbortListener(signal, () => reject(new DecisionError("cancelled", "Decision request was cancelled.")));
39
+ if (deadlineAt !== undefined && Number.isFinite(deadlineAt)) {
40
+ timer = setTimeout(() => reject(new DecisionError("timeout", "Decision request timed out.")), Math.max(1, Math.ceil(deadlineAt - performance.now())));
41
+ }
42
+ });
43
+ try {
44
+ const status = await Promise.race([inflight, stop]);
45
+ const stopped = decisionStopError(context);
46
+ if (stopped)
47
+ throw stopped;
48
+ return status;
49
+ }
50
+ finally {
51
+ clearTimeout(timer);
52
+ listener?.[Symbol.dispose]();
53
+ }
54
+ };
55
+ }
56
+ // Report only models the server accepts, so discovery never names a denied model.
57
+ export function approvedModels(config) {
58
+ if (!config.allowedModels)
59
+ return [config.defaultModel];
60
+ if (!config.allowedModels.includes(config.defaultModel))
61
+ return undefined;
62
+ return [...config.allowedModels];
63
+ }
64
+ export function notConfigured(detail) {
65
+ return { ok: false, readiness: "not_configured", detail };
66
+ }
67
+ const defaultModelReadiness = {
68
+ ready: "ready",
69
+ missing: "model_missing",
70
+ unsupported: "model_unsupported",
71
+ unknown: "unknown",
72
+ };
73
+ const readinessDetail = {
74
+ model_missing: "The default model is not available.",
75
+ model_unsupported: "The default model does not report decision support.",
76
+ unknown: "The provider could not confirm that the default model supports decisions.",
77
+ };
78
+ export function discovered(models) {
79
+ const readiness = defaultModelReadiness[models.find((model) => model.default)?.status ?? "unknown"];
80
+ const detail = readinessDetail[readiness];
81
+ return {
82
+ ok: true,
83
+ readiness,
84
+ ...(detail ? { detail } : {}),
85
+ questionTypes: QUESTION_TYPES,
86
+ models,
87
+ };
88
+ }
89
+ export function unexpectedModelList(label) {
90
+ return {
91
+ ok: true,
92
+ readiness: "unknown",
93
+ detail: `${label} returned an unexpected model list.`,
94
+ questionTypes: QUESTION_TYPES,
95
+ };
96
+ }
97
+ export function discoveryFailure(label, error) {
98
+ if (error instanceof DecisionProviderError) {
99
+ if (error.code === "invalid_response")
100
+ return unexpectedModelList(label);
101
+ if (error.status === 401 || error.status === 403) {
102
+ return {
103
+ ok: false,
104
+ readiness: "unauthenticated",
105
+ detail: `${label} rejected the credentials.`,
106
+ };
107
+ }
108
+ if (error.code === "http" && error.status !== 429 && (error.status ?? 500) < 500) {
109
+ return { ok: false, readiness: "unknown", detail: `${label} returned HTTP ${error.status}.` };
110
+ }
111
+ }
112
+ return { ok: false, readiness: "unreachable", detail: `${label} discovery request failed.` };
113
+ }
@@ -0,0 +1,56 @@
1
+ import type { DecisionProvider } from "../types.js";
2
+ export declare function createProviderRegistry(env: NodeJS.ProcessEnv): {
3
+ cache: Readonly<{
4
+ ttlMs: number;
5
+ maxEntries: number;
6
+ maxBytes: number;
7
+ }>;
8
+ routing: Readonly<{
9
+ retryAttempts: number;
10
+ retryBilled: boolean;
11
+ fallback: readonly import("../config.js").RouteTarget[];
12
+ }>;
13
+ localOnly: boolean;
14
+ locality: (id: string, model: string) => "local" | "non-local" | "unknown";
15
+ actionPolicyTimeoutMs: number;
16
+ actionPolicyFailureMode: import("../config.js").ActionPolicyFailureMode;
17
+ actionPolicyScope: "consequential" | "strict";
18
+ defaultProvider: "ollama" | "opencode-go" | "typesafe";
19
+ getProvider: (id?: string) => DecisionProvider;
20
+ effectiveModel: (id?: string, requestedModel?: string) => string;
21
+ resolveActionPolicyTarget(id?: string, requestedModel?: string): {
22
+ model: string;
23
+ locality: "local" | "non-local" | "unknown";
24
+ modelApproved: boolean;
25
+ };
26
+ listProviders(): DecisionProvider[];
27
+ };
28
+ export type ProviderRegistry = ReturnType<typeof createProviderRegistry>;
29
+ export declare function getProviderRegistry(): ProviderRegistry;
30
+ export declare function getProvider(id?: string, registry?: {
31
+ cache: Readonly<{
32
+ ttlMs: number;
33
+ maxEntries: number;
34
+ maxBytes: number;
35
+ }>;
36
+ routing: Readonly<{
37
+ retryAttempts: number;
38
+ retryBilled: boolean;
39
+ fallback: readonly import("../config.js").RouteTarget[];
40
+ }>;
41
+ localOnly: boolean;
42
+ locality: (id: string, model: string) => "local" | "non-local" | "unknown";
43
+ actionPolicyTimeoutMs: number;
44
+ actionPolicyFailureMode: import("../config.js").ActionPolicyFailureMode;
45
+ actionPolicyScope: "consequential" | "strict";
46
+ defaultProvider: "ollama" | "opencode-go" | "typesafe";
47
+ getProvider: (id?: string) => DecisionProvider;
48
+ effectiveModel: (id?: string, requestedModel?: string) => string;
49
+ resolveActionPolicyTarget(id?: string, requestedModel?: string): {
50
+ model: string;
51
+ locality: "local" | "non-local" | "unknown";
52
+ modelApproved: boolean;
53
+ };
54
+ listProviders(): DecisionProvider[];
55
+ }): DecisionProvider;
56
+ export declare function listProviders(): DecisionProvider[];
@@ -0,0 +1,83 @@
1
+ import { allowlistSetting, classifyOllamaLocality, readProviderConfig, resolveModel, } from "../config.js";
2
+ import { DecisionError } from "../errors.js";
3
+ import { notConfigured } from "./discovery.js";
4
+ import { OllamaProvider } from "./ollama.js";
5
+ import { createOpenCodeGoProvider } from "./opencode-go.js";
6
+ import { createTypeSafeProvider } from "./typesafe.js";
7
+ export function createProviderRegistry(env) {
8
+ const config = readProviderConfig(env);
9
+ const providers = new Map([
10
+ ["ollama", new OllamaProvider(config.ollama)],
11
+ ["typesafe", createTypeSafeProvider(config.typesafe)],
12
+ ["opencode-go", createOpenCodeGoProvider(config.opencodeGo)],
13
+ ]);
14
+ const allowedProviders = new Set(config.allowedProviders);
15
+ function getProvider(id = config.defaultProvider) {
16
+ const provider = providers.get(id);
17
+ if (!provider) {
18
+ throw new DecisionError("configuration", `Unknown decision provider '${id}'. Available providers: ${[...providers.keys()].join(", ")}.`);
19
+ }
20
+ if (!allowedProviders.has(id)) {
21
+ throw new DecisionError("configuration", `Decision provider '${id}' is not allowed. Set DECISION_ALLOWED_PROVIDERS to permit it.`);
22
+ }
23
+ return provider;
24
+ }
25
+ function configuredSettings(id) {
26
+ getProvider(id);
27
+ const settings = id === "ollama" ? config.ollama : id === "typesafe" ? config.typesafe : config.opencodeGo;
28
+ if ("status" in settings && settings.status !== "configured") {
29
+ throw new DecisionError("configuration", settings.detail);
30
+ }
31
+ return settings;
32
+ }
33
+ function effectiveModel(id = config.defaultProvider, requestedModel) {
34
+ return resolveModel(configuredSettings(id), requestedModel, allowlistSetting(id));
35
+ }
36
+ function locality(id, model) {
37
+ return id === "ollama" ? classifyOllamaLocality(config.ollama, model) : "non-local";
38
+ }
39
+ return {
40
+ cache: config.cache,
41
+ routing: config.routing,
42
+ localOnly: config.ollama.localOnly,
43
+ locality,
44
+ actionPolicyTimeoutMs: config.actionPolicyTimeoutMs,
45
+ actionPolicyFailureMode: config.actionPolicyFailureMode,
46
+ actionPolicyScope: config.actionPolicyScope,
47
+ defaultProvider: config.defaultProvider,
48
+ getProvider,
49
+ effectiveModel,
50
+ resolveActionPolicyTarget(id = config.defaultProvider, requestedModel) {
51
+ const settings = configuredSettings(id);
52
+ const model = effectiveModel(id, requestedModel);
53
+ const targetLocality = locality(id, model);
54
+ const modelApproved = model === settings.defaultModel || settings.allowedModels?.includes(model) === true;
55
+ return {
56
+ model,
57
+ locality: targetLocality,
58
+ modelApproved: modelApproved && (!config.ollama.localOnly || targetLocality === "local"),
59
+ };
60
+ },
61
+ listProviders() {
62
+ return [...providers.values()].map((provider) => allowedProviders.has(provider.id)
63
+ ? provider
64
+ : {
65
+ id: provider.id,
66
+ description: provider.description,
67
+ available: async () => notConfigured("Provider is not in DECISION_ALLOWED_PROVIDERS."),
68
+ decide: async (request) => getProvider(provider.id).decide(request),
69
+ });
70
+ },
71
+ };
72
+ }
73
+ let processRegistry;
74
+ export function getProviderRegistry() {
75
+ processRegistry ??= createProviderRegistry(process.env);
76
+ return processRegistry;
77
+ }
78
+ export function getProvider(id, registry = getProviderRegistry()) {
79
+ return registry.getProvider(id);
80
+ }
81
+ export function listProviders() {
82
+ return getProviderRegistry().listProviders();
83
+ }
@@ -0,0 +1,12 @@
1
+ import { type OllamaConfig } from "../config.js";
2
+ import type { DecisionProvider, DecisionRequest, DecisionResponse, ProviderStatus } from "../types.js";
3
+ export declare class OllamaProvider implements DecisionProvider {
4
+ private readonly config;
5
+ readonly id = "ollama";
6
+ readonly description = "Ollama /v1/systemone decision models";
7
+ constructor(config: OllamaConfig);
8
+ get timeoutMs(): number;
9
+ readonly available: (signal?: AbortSignal, deadlineAt?: number) => Promise<ProviderStatus>;
10
+ private discover;
11
+ decide(request: DecisionRequest): Promise<DecisionResponse>;
12
+ }
@@ -0,0 +1,93 @@
1
+ import * as z from "zod/v4";
2
+ import { classifyOllamaLocality, resolveModel } from "../config.js";
3
+ import { DecisionError } from "../errors.js";
4
+ import { getJson, postJson } from "../http.js";
5
+ import { validateDecisionResponse } from "../response.js";
6
+ import { approvedModels, cachedProbe, discovered, discoveryFailure, notConfigured, PROBE_TIMEOUT_MS, unexpectedModelList, } from "./discovery.js";
7
+ // Ollama's GET /api/tags lists installed models. Ollama 0.40.19 also returns each model's capabilities.
8
+ const tagsSchema = z.object({
9
+ models: z.array(z.looseObject({
10
+ name: z.string(),
11
+ model: z.string().optional(),
12
+ digest: z.string().optional(),
13
+ capabilities: z.array(z.string()).optional(),
14
+ })),
15
+ });
16
+ // Ollama treats a model name without a tag as the latest tag.
17
+ function withTag(name) {
18
+ return /:[^/]*$/.test(name) ? name : `${name}:latest`;
19
+ }
20
+ export class OllamaProvider {
21
+ config;
22
+ id = "ollama";
23
+ description = "Ollama /v1/systemone decision models";
24
+ constructor(config) {
25
+ this.config = config;
26
+ }
27
+ get timeoutMs() {
28
+ return this.config.timeoutMs;
29
+ }
30
+ available = cachedProbe(() => this.discover());
31
+ async discover() {
32
+ const { baseUrl, defaultModel, loopback, localOnly } = this.config;
33
+ if (localOnly && !loopback) {
34
+ return notConfigured("Local-only mode requires a loopback Ollama endpoint.");
35
+ }
36
+ const names = approvedModels(this.config);
37
+ if (!names)
38
+ return notConfigured("The default model is not in OLLAMA_ALLOWED_MODELS.");
39
+ if (localOnly && classifyOllamaLocality(this.config, defaultModel) !== "local") {
40
+ return notConfigured("Local-only mode requires an approved local default model.");
41
+ }
42
+ let raw;
43
+ try {
44
+ raw = await getJson(this.id, `${baseUrl}/api/tags`, { timeoutMs: PROBE_TIMEOUT_MS });
45
+ }
46
+ catch (error) {
47
+ return discoveryFailure("Ollama", error);
48
+ }
49
+ const parsed = tagsSchema.safeParse(raw);
50
+ if (!parsed.success)
51
+ return unexpectedModelList("Ollama");
52
+ return discovered(names
53
+ .filter((name) => !localOnly || classifyOllamaLocality(this.config, name) === "local")
54
+ .map((name) => {
55
+ const locality = classifyOllamaLocality(this.config, name);
56
+ const installed = parsed.data.models.find((model) => [model.name, model.model].some((installedName) => installedName && withTag(installedName) === withTag(name)));
57
+ const identity = { name, default: name === defaultModel, locality };
58
+ if (!installed)
59
+ return { ...identity, status: "missing" };
60
+ const status = !installed.capabilities
61
+ ? "unknown"
62
+ : installed.capabilities.includes("decision")
63
+ ? "ready"
64
+ : "unsupported";
65
+ return {
66
+ ...identity,
67
+ status,
68
+ ...(installed.digest && /^[0-9a-f]{12,64}$/i.test(installed.digest)
69
+ ? { revision: installed.digest }
70
+ : {}),
71
+ };
72
+ }));
73
+ }
74
+ async decide(request) {
75
+ const { baseUrl, keepAlive, localOnly, timeoutMs } = this.config;
76
+ const model = resolveModel(this.config, request.model, "OLLAMA_ALLOWED_MODELS");
77
+ if (localOnly && classifyOllamaLocality(this.config, model) !== "local") {
78
+ throw new DecisionError("configuration", "Local-only mode requires a loopback endpoint and an approved local Ollama model.");
79
+ }
80
+ const payload = {
81
+ model,
82
+ state: request.state,
83
+ questions: request.questions,
84
+ };
85
+ if (keepAlive)
86
+ payload.keep_alive = keepAlive;
87
+ const raw = await postJson(this.id, `${baseUrl}/v1/systemone`, payload, {
88
+ context: request.context,
89
+ timeoutMs,
90
+ });
91
+ return validateDecisionResponse(this.id, request, raw, model);
92
+ }
93
+ }
@@ -0,0 +1,3 @@
1
+ import type { HostedConfig } from "../config.js";
2
+ import { SystemOneProvider } from "./system-one.js";
3
+ export declare function createOpenCodeGoProvider(config: HostedConfig): SystemOneProvider;
@@ -0,0 +1,40 @@
1
+ import * as z from "zod/v4";
2
+ import { getJson } from "../http.js";
3
+ import { packageVersion } from "../package-info.js";
4
+ import { discovered, discoveryFailure, PROBE_TIMEOUT_MS, unexpectedModelList, } from "./discovery.js";
5
+ import { SystemOneProvider } from "./system-one.js";
6
+ // The model list is public, so discovery never sends the API key.
7
+ const MODELS_URL = "https://opencode.ai/inference/go/v1/models";
8
+ const modelListSchema = z.object({
9
+ data: z.array(z.looseObject({ id: z.string(), type: z.string().optional() })),
10
+ });
11
+ export function createOpenCodeGoProvider(config) {
12
+ return new SystemOneProvider(config, {
13
+ id: "opencode-go",
14
+ description: "OpenCode Go System One API for hosted decision models such as Jev",
15
+ url: "https://opencode.ai/inference/go/systemone/v1/systemone",
16
+ // OpenCode Go asks clients to identify themselves instead of sending a library name.
17
+ headers: {
18
+ "User-Agent": `verdict-kit/${packageVersion} (+https://github.com/theoklitosBam7/tb-verdict-kit)`,
19
+ },
20
+ async discover({ defaultModel }, names) {
21
+ let raw;
22
+ try {
23
+ raw = await getJson("opencode-go", MODELS_URL, { timeoutMs: PROBE_TIMEOUT_MS });
24
+ }
25
+ catch (error) {
26
+ return discoveryFailure("OpenCode Go", error);
27
+ }
28
+ const parsed = modelListSchema.safeParse(raw);
29
+ if (!parsed.success)
30
+ return unexpectedModelList("OpenCode Go");
31
+ const decisionModels = new Set(parsed.data.data.filter((model) => model.type === "decision").map((model) => model.id));
32
+ return discovered(names.map((name) => ({
33
+ name,
34
+ default: name === defaultModel,
35
+ status: decisionModels.has(name) ? "ready" : "missing",
36
+ locality: "non-local",
37
+ })));
38
+ },
39
+ });
40
+ }
@@ -0,0 +1,21 @@
1
+ import { type HostedConfig } from "../config.js";
2
+ import type { DecisionProvider, DecisionRequest, DecisionResponse, ProviderStatus } from "../types.js";
3
+ export type SystemOneEndpoint = Readonly<{
4
+ id: string;
5
+ description: string;
6
+ url: string;
7
+ headers?: Readonly<Record<string, string>>;
8
+ discover(config: Extract<HostedConfig, {
9
+ status: "configured";
10
+ }>, names: string[]): Promise<ProviderStatus>;
11
+ }>;
12
+ export declare class SystemOneProvider implements DecisionProvider {
13
+ private readonly config;
14
+ private readonly endpoint;
15
+ readonly id: string;
16
+ readonly description: string;
17
+ constructor(config: HostedConfig, endpoint: SystemOneEndpoint);
18
+ get timeoutMs(): number | undefined;
19
+ readonly available: (signal?: AbortSignal, deadlineAt?: number) => Promise<ProviderStatus>;
20
+ decide(request: DecisionRequest): Promise<DecisionResponse>;
21
+ }
@@ -0,0 +1,44 @@
1
+ import { allowlistSetting, resolveModel } from "../config.js";
2
+ import { DecisionError } from "../errors.js";
3
+ import { postJson } from "../http.js";
4
+ import { validateDecisionResponse } from "../response.js";
5
+ import { approvedModels, cachedProbe, notConfigured } from "./discovery.js";
6
+ // A hosted provider that speaks the System One request format, such as TypeSafe or
7
+ // OpenCode Go. Both send the same request and return the same answer contract.
8
+ export class SystemOneProvider {
9
+ config;
10
+ endpoint;
11
+ id;
12
+ description;
13
+ constructor(config, endpoint) {
14
+ this.config = config;
15
+ this.endpoint = endpoint;
16
+ this.id = endpoint.id;
17
+ this.description = endpoint.description;
18
+ }
19
+ get timeoutMs() {
20
+ return this.config.status === "configured" ? this.config.timeoutMs : undefined;
21
+ }
22
+ available = cachedProbe(async () => {
23
+ if (this.config.status !== "configured")
24
+ return notConfigured(this.config.detail);
25
+ const names = approvedModels(this.config);
26
+ if (!names) {
27
+ return notConfigured(`The default model is not in ${allowlistSetting(this.id)}.`);
28
+ }
29
+ return this.endpoint.discover(this.config, names);
30
+ });
31
+ async decide(request) {
32
+ if (this.config.status !== "configured")
33
+ throw new DecisionError("configuration", this.config.detail);
34
+ const { apiKey, timeoutMs } = this.config;
35
+ const model = resolveModel(this.config, request.model, allowlistSetting(this.id));
36
+ const payload = { model, state: request.state, questions: request.questions };
37
+ const raw = await postJson(this.id, this.endpoint.url, payload, {
38
+ context: request.context,
39
+ headers: { ...this.endpoint.headers, Authorization: `Bearer ${apiKey}` },
40
+ timeoutMs,
41
+ });
42
+ return validateDecisionResponse(this.id, request, raw, model);
43
+ }
44
+ }
@@ -0,0 +1,3 @@
1
+ import type { HostedConfig } from "../config.js";
2
+ import { SystemOneProvider } from "./system-one.js";
3
+ export declare function createTypeSafeProvider(config: HostedConfig): SystemOneProvider;
@@ -0,0 +1,36 @@
1
+ import * as z from "zod/v4";
2
+ import { getJson } from "../http.js";
3
+ import { discovered, discoveryFailure, PROBE_TIMEOUT_MS, unexpectedModelList, } from "./discovery.js";
4
+ import { SystemOneProvider } from "./system-one.js";
5
+ // Lists the models available to the authenticated account without running inference.
6
+ const MODELS_URL = "https://api.typesafe.ai/v1/models";
7
+ const modelListSchema = z.object({ models: z.array(z.looseObject({ name: z.string() })) });
8
+ export function createTypeSafeProvider(config) {
9
+ return new SystemOneProvider(config, {
10
+ id: "typesafe",
11
+ description: "Official TypeSafe AI System One API",
12
+ url: "https://api.typesafe.ai/v1/systemone",
13
+ async discover({ apiKey, defaultModel }, names) {
14
+ let raw;
15
+ try {
16
+ raw = await getJson("typesafe", MODELS_URL, {
17
+ headers: { Authorization: `Bearer ${apiKey}` },
18
+ timeoutMs: PROBE_TIMEOUT_MS,
19
+ });
20
+ }
21
+ catch (error) {
22
+ return discoveryFailure("TypeSafe", error);
23
+ }
24
+ const parsed = modelListSchema.safeParse(raw);
25
+ if (!parsed.success)
26
+ return unexpectedModelList("TypeSafe");
27
+ const listed = new Set(parsed.data.models.map((model) => model.name));
28
+ return discovered(names.map((name) => ({
29
+ name,
30
+ default: name === defaultModel,
31
+ status: listed.has(name) ? "ready" : "missing",
32
+ locality: "non-local",
33
+ })));
34
+ },
35
+ });
36
+ }
@@ -0,0 +1,5 @@
1
+ export { createDecisionEngine, type CallOptions, type DecisionEngine, type DecisionEngineOptions, } from "./engine.js";
2
+ export { DecisionError, decisionErrorCodes, type DecisionErrorCode } from "./errors.js";
3
+ export { evaluateActionPolicy, isDecisionModelTool, observeActionPolicy, type ActionPolicyRequest, type ActionPolicyResult, } from "./action-policy.js";
4
+ export { createProviderRegistry, type ProviderRegistry } from "./providers/index.js";
5
+ export type { DecisionProvider, DecisionQuestions, DecisionRequest, DecisionResponse, JsonValue, ProviderStatus, } from "./types.js";
package/dist/public.js ADDED
@@ -0,0 +1,5 @@
1
+ // Public SDK entry point. Importing this module has no side effects.
2
+ export { createDecisionEngine, } from "./engine.js";
3
+ export { DecisionError, decisionErrorCodes } from "./errors.js";
4
+ export { evaluateActionPolicy, isDecisionModelTool, observeActionPolicy, } from "./action-policy.js";
5
+ export { createProviderRegistry } from "./providers/index.js";
@@ -0,0 +1,6 @@
1
+ import { DecisionError } from "./errors.js";
2
+ import type { DecisionRequest, DecisionResponse, JsonValue } from "./types.js";
3
+ export declare class InvalidDecisionResponseError extends DecisionError {
4
+ constructor(message: string);
5
+ }
6
+ export declare function validateDecisionResponse(provider: string, request: DecisionRequest, raw: JsonValue, resolvedModel?: string | undefined): DecisionResponse;
@@ -0,0 +1,104 @@
1
+ import { DecisionError } from "./errors.js";
2
+ import { isProbability } from "./probability.js";
3
+ import { answerLegendSchema, finiteJsonSchema } from "./schemas.js";
4
+ export class InvalidDecisionResponseError extends DecisionError {
5
+ constructor(message) {
6
+ super("invalid_response", message);
7
+ this.name = "InvalidDecisionResponseError";
8
+ }
9
+ }
10
+ function asObject(value, message) {
11
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
12
+ throw new InvalidDecisionResponseError(message);
13
+ }
14
+ return value;
15
+ }
16
+ function assertProbability(value, label) {
17
+ if (!isProbability(value)) {
18
+ throw new InvalidDecisionResponseError(`${label} must be a number between 0 and 1.`);
19
+ }
20
+ }
21
+ function validateProbabilities(name, question, value) {
22
+ const label = `${name}.probabilities`;
23
+ const probabilities = asObject(value, `${label} must be an object.`);
24
+ let expectedKeys;
25
+ if (question.type === "choice") {
26
+ expectedKeys = Object.keys(question.criteria);
27
+ }
28
+ else if (question.type === "score") {
29
+ expectedKeys = question.criteria.map((_, index) => String(index));
30
+ }
31
+ const values = Object.values(probabilities);
32
+ if (expectedKeys &&
33
+ (values.length !== expectedKeys.length ||
34
+ expectedKeys.some((key) => !Object.hasOwn(probabilities, key)))) {
35
+ throw new InvalidDecisionResponseError(`${label} must match the requested criteria.`);
36
+ }
37
+ let total = 0;
38
+ for (const probability of values) {
39
+ assertProbability(probability, label);
40
+ total += probability;
41
+ }
42
+ // Four decimal places can introduce half a unit of rounding per criterion.
43
+ const tolerance = values.length * 0.00005 + 1e-9;
44
+ if (expectedKeys && Math.abs(total - 1) > tolerance) {
45
+ throw new InvalidDecisionResponseError(`${label} must sum to 1 within rounding tolerance.`);
46
+ }
47
+ }
48
+ function validateAnswer(name, question, value) {
49
+ const answer = asObject(value, `Provider answer '${name}' must be an object.`);
50
+ if (answer.type !== question.type) {
51
+ throw new InvalidDecisionResponseError(`Provider answer '${name}' must have type '${question.type}'.`);
52
+ }
53
+ if (answer.confidence !== undefined) {
54
+ assertProbability(answer.confidence, `${name}.confidence`);
55
+ }
56
+ if (answer.probabilities !== undefined) {
57
+ validateProbabilities(name, question, answer.probabilities);
58
+ }
59
+ if (!finiteJsonSchema.safeParse(answer).success ||
60
+ (answer.legend !== undefined && !answerLegendSchema.safeParse(answer.legend).success)) {
61
+ throw new InvalidDecisionResponseError(`Provider answer '${name}' contains invalid metadata.`);
62
+ }
63
+ switch (question.type) {
64
+ case "choice":
65
+ if (typeof answer.choice !== "string") {
66
+ throw new InvalidDecisionResponseError(`${name}.choice must be a string.`);
67
+ }
68
+ if (!Object.hasOwn(question.criteria, answer.choice)) {
69
+ throw new InvalidDecisionResponseError(`${name}.choice is not one of the requested criteria.`);
70
+ }
71
+ return { ...answer, type: question.type, choice: answer.choice };
72
+ case "noul":
73
+ assertProbability(answer.noul, `${name}.noul`);
74
+ return { ...answer, type: question.type, noul: answer.noul };
75
+ case "score": {
76
+ const score = answer.score;
77
+ const highest = question.criteria.length - 1;
78
+ if (typeof score !== "number" || !Number.isFinite(score) || score < 0 || score > highest) {
79
+ throw new InvalidDecisionResponseError(`${name}.score must be a number between 0 and ${highest}.`);
80
+ }
81
+ return { ...answer, type: question.type, score };
82
+ }
83
+ }
84
+ }
85
+ export function validateDecisionResponse(provider, request, raw, resolvedModel = request.model) {
86
+ const object = asObject(raw, `${provider} returned an unexpected response shape.`);
87
+ const answers = asObject(object.answers, `${provider} response is missing a valid answers object.`);
88
+ const expectedKeys = Object.keys(request.questions).sort();
89
+ const actualKeys = Object.keys(answers).sort();
90
+ if (expectedKeys.length !== actualKeys.length ||
91
+ expectedKeys.some((key, index) => key !== actualKeys[index])) {
92
+ throw new InvalidDecisionResponseError(`${provider} response answer keys do not match the requested questions.`);
93
+ }
94
+ const validated = Object.fromEntries(Object.entries(request.questions).map(([name, question]) => [
95
+ name,
96
+ validateAnswer(name, question, answers[name]),
97
+ ]));
98
+ return {
99
+ provider,
100
+ model: resolvedModel,
101
+ answers: validated,
102
+ usage: finiteJsonSchema.safeParse(object.usage).data,
103
+ };
104
+ }