@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
package/dist/server.js ADDED
@@ -0,0 +1,416 @@
1
+ import { McpServer } from "@modelcontextprotocol/server";
2
+ import { claudeCodePreToolUseOutput, codexPreToolUseOutput, effectiveFailureMode, evaluateActionPolicy, observeActionPolicy, } from "./action-policy.js";
3
+ import { createDecisionCache } from "./cache.js";
4
+ import { cascadeInputSchema, cascadeOutputSchema, loadCascadeRegistry, runCascade, } from "./routing/cascade.js";
5
+ import { consensusInputSchema, consensusOutputSchema, evaluateConsensusActionPolicy, loadActionPolicyConsensus, loadConsensusRegistry, runConsensus, } from "./routing/consensus.js";
6
+ import { batchDecide, failedRouteAttempts, gate } from "./decision.js";
7
+ import { packageVersion } from "./package-info.js";
8
+ import { readPolicyAdapterMode, recordPolicyObservation } from "./policy/events.js";
9
+ import { loadPolicyProfile } from "./policy/registry.js";
10
+ import { actionPolicyOutputSchema } from "./policy/schema.js";
11
+ import { readTelemetryConfig } from "./config.js";
12
+ import { DecisionError } from "./errors.js";
13
+ import { toolEvent } from "./telemetry/events.js";
14
+ import { createTelemetrySink } from "./telemetry/sink.js";
15
+ import { actionPolicyInputSchema, batchInputSchema, batchOutputSchema, booleanInputSchema, classifyInputSchema, decideInputSchema, decisionOutputSchema, gateInputSchema, gateOutputSchema, jsonValueSchema, providersOutputSchema, scoreInputSchema, } from "./schemas.js";
16
+ import { loadTemplateRegistry } from "./templates/registry.js";
17
+ import { templateListOutputSchema, templateRunInputSchema, templateRunOutputSchema, templateValidateInputSchema, templateValidateOutputSchema, } from "./templates/schema.js";
18
+ const inferenceAnnotations = { readOnlyHint: false, openWorldHint: true };
19
+ const ok = (structuredContent, legacyValue = structuredContent, indent = 2) => ({
20
+ structuredContent,
21
+ content: [{ type: "text", text: JSON.stringify(legacyValue, null, indent) }],
22
+ });
23
+ // Claude Code substitutes "${tool_input}" into mcp_tool hook arguments as JSON text.
24
+ // Its tool inputs are objects, so any other value is invalid input.
25
+ function claudeCodeToolInput(value) {
26
+ let parsed = value;
27
+ if (typeof value === "string") {
28
+ try {
29
+ parsed = JSON.parse(value);
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }
35
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
36
+ ? parsed
37
+ : undefined;
38
+ }
39
+ // Keep audit fields out of MCP error results and hook bodies.
40
+ const telemetryDetails = new WeakMap();
41
+ const fail = (error, attempts = failedRouteAttempts(error)) => {
42
+ const message = error instanceof DecisionError ? error.message : "Decision failed.";
43
+ const result = { content: [{ type: "text", text: message }], isError: true };
44
+ telemetryDetails.set(result, {
45
+ errorCode: error instanceof DecisionError ? error.code : "internal",
46
+ attempts,
47
+ });
48
+ return result;
49
+ };
50
+ const invalidState = "State does not match the template schema.";
51
+ // The MCP tools and the public engine share these helpers, so both return the same results.
52
+ export async function expandTemplateRun(templates, { template, state, provider, model }) {
53
+ if (!(await templates.validateState(template, state))) {
54
+ throw new DecisionError("invalid_request", invalidState);
55
+ }
56
+ const { questions } = templates.get(template);
57
+ const expanded = decideInputSchema.safeParse({ state, questions, provider, model });
58
+ if (!expanded.success) {
59
+ throw new DecisionError("invalid_request", "Expanded decision request is too large or invalid.");
60
+ }
61
+ return { ...expanded.data, state: expanded.data.state };
62
+ }
63
+ export async function validateTemplateState(templates, { template, state }) {
64
+ const valid = await templates.validateState(template, state);
65
+ return valid ? { template, valid } : { template, valid, message: invalidState };
66
+ }
67
+ export async function listProviderStatus(registry, signal) {
68
+ const providers = await Promise.all(registry.listProviders().map(async (provider) => ({
69
+ id: provider.id,
70
+ description: provider.description,
71
+ // Providers that cannot prove model readiness report it as unknown.
72
+ readiness: "unknown",
73
+ ...(await provider.available(signal)),
74
+ })));
75
+ return { default: registry.defaultProvider, providers };
76
+ }
77
+ export function createServer(registry, templates = loadTemplateRegistry(), profile = loadPolicyProfile(process.env.DECISION_POLICY_PROFILE, templates), mode = readPolicyAdapterMode(process.env.DECISION_ACTION_POLICY_MODE), cascades = loadCascadeRegistry(templates), consensuses = loadConsensusRegistry(templates), actionConsensus = loadActionPolicyConsensus(process.env.DECISION_ACTION_POLICY_CONSENSUS, consensuses, profile, registry), telemetry = createTelemetrySink(readTelemetryConfig(process.env))) {
78
+ // One cache per server instance keeps cached results inside one client connection.
79
+ const cache = createDecisionCache(registry.cache);
80
+ const routing = registry.routing.retryAttempts > 0 || registry.routing.fallback.length > 0;
81
+ const runDecision = async (request, scope) => {
82
+ const { result, cache: status, attempts } = await cache.decide(request, registry, scope);
83
+ const meta = {};
84
+ if (registry.cache.ttlMs > 0)
85
+ meta["decision-models/cache"] = { status };
86
+ if (routing && attempts.length > 0)
87
+ meta["decision-models/routing"] = { attempts };
88
+ return { result, meta: Object.keys(meta).length > 0 ? { _meta: meta } : {} };
89
+ };
90
+ const server = new McpServer({ name: "decision-models", version: packageVersion });
91
+ if (telemetry.enabled) {
92
+ // Inference tools record one event per call. Local tools such as templates and gate
93
+ // make no model call and record nothing.
94
+ const register = server.registerTool.bind(server);
95
+ server.registerTool = ((name, config, handler) => register(name, config, (config.annotations === inferenceAnnotations
96
+ ? async (...args) => {
97
+ const start = performance.now();
98
+ const result = await handler(...args);
99
+ telemetry.emit(toolEvent(name, result, performance.now() - start, telemetryDetails.get(result)));
100
+ return result;
101
+ }
102
+ : handler)));
103
+ }
104
+ server.registerTool("decision_decide", {
105
+ description: "Run typed choice, noul, and score decisions. Hosted providers may receive input data and charge for inference.",
106
+ inputSchema: decideInputSchema,
107
+ outputSchema: decisionOutputSchema,
108
+ annotations: inferenceAnnotations,
109
+ }, async ({ state, questions, provider, model }, ctx) => {
110
+ try {
111
+ const { result, meta } = await runDecision({
112
+ state: state,
113
+ questions,
114
+ provider,
115
+ model,
116
+ context: { signal: ctx.mcpReq.signal },
117
+ });
118
+ return { ...ok(result), ...meta };
119
+ }
120
+ catch (error) {
121
+ return fail(error);
122
+ }
123
+ });
124
+ server.registerTool("decision_classify", {
125
+ description: "Classify state into one label using the selected decision provider/model. Useful for routing, intent, workflow, and tool-family selection.",
126
+ inputSchema: classifyInputSchema,
127
+ outputSchema: decisionOutputSchema,
128
+ annotations: inferenceAnnotations,
129
+ }, async ({ state, labels, instructions, provider, model }, ctx) => {
130
+ try {
131
+ const { result, meta } = await runDecision({
132
+ state: state,
133
+ provider,
134
+ model,
135
+ context: { signal: ctx.mcpReq.signal },
136
+ questions: { classification: { type: "choice", instructions, criteria: labels } },
137
+ });
138
+ return { ...ok(result), ...meta };
139
+ }
140
+ catch (error) {
141
+ return fail(error);
142
+ }
143
+ });
144
+ server.registerTool("decision_boolean", {
145
+ description: "Return the provider's estimate of the probability that a yes/no judgement is true.",
146
+ inputSchema: booleanInputSchema,
147
+ outputSchema: decisionOutputSchema,
148
+ annotations: inferenceAnnotations,
149
+ }, async ({ state, question, true_description, false_description, provider, model }, ctx) => {
150
+ try {
151
+ const criteria = true_description || false_description
152
+ ? { true: true_description, false: false_description }
153
+ : undefined;
154
+ const { result, meta } = await runDecision({
155
+ state: state,
156
+ provider,
157
+ model,
158
+ context: { signal: ctx.mcpReq.signal },
159
+ questions: { judgement: { type: "noul", instructions: question, criteria } },
160
+ });
161
+ return { ...ok(result), ...meta };
162
+ }
163
+ catch (error) {
164
+ return fail(error);
165
+ }
166
+ });
167
+ server.registerTool("decision_score", {
168
+ description: "Place state on an ordered rubric using the selected decision provider/model.",
169
+ inputSchema: scoreInputSchema,
170
+ outputSchema: decisionOutputSchema,
171
+ annotations: inferenceAnnotations,
172
+ }, async ({ state, instructions, criteria, provider, model }, ctx) => {
173
+ try {
174
+ const { result, meta } = await runDecision({
175
+ state: state,
176
+ provider,
177
+ model,
178
+ context: { signal: ctx.mcpReq.signal },
179
+ questions: { score: { type: "score", instructions, criteria } },
180
+ });
181
+ return { ...ok(result), ...meta };
182
+ }
183
+ catch (error) {
184
+ return fail(error);
185
+ }
186
+ });
187
+ server.registerTool("decision_batch", {
188
+ description: "Run the same typed questions over several states. Use partial mode to receive an indexed outcome for each input.",
189
+ inputSchema: batchInputSchema,
190
+ outputSchema: batchOutputSchema,
191
+ annotations: inferenceAnnotations,
192
+ }, async ({ states, questions, provider, model, concurrency, failure_mode }, ctx) => {
193
+ try {
194
+ const results = await batchDecide(states, { questions, provider, model, context: { signal: ctx.mcpReq.signal } }, concurrency, registry, failure_mode);
195
+ return ok({ results }, results, 0);
196
+ }
197
+ catch (error) {
198
+ return fail(error);
199
+ }
200
+ });
201
+ server.registerTool("decision_gate", {
202
+ description: "Apply a local advisory allow/review/block policy to caller-supplied answers. Missing or invalid answers require review, and invalid policy rules return an input error. Keep native host permissions enabled.",
203
+ inputSchema: gateInputSchema,
204
+ outputSchema: gateOutputSchema,
205
+ annotations: { readOnlyHint: true, openWorldHint: false },
206
+ }, async ({ answers, policy }) => {
207
+ try {
208
+ return ok(gate(answers, policy));
209
+ }
210
+ catch (error) {
211
+ return fail(error);
212
+ }
213
+ });
214
+ server.registerTool("decision_action_policy", {
215
+ description: "Evaluate a proposed engineering tool call with the decision model, apply the launch-selected advisory policy profile, and return allow, review, or block. Use output=codex_pre_tool_use when called from a Codex PreToolUse MCP hook, or output=claude_code_pre_tool_use when called from a Claude Code PreToolUse mcp_tool hook.",
216
+ inputSchema: actionPolicyInputSchema,
217
+ outputSchema: actionPolicyOutputSchema,
218
+ annotations: inferenceAnnotations,
219
+ }, async ({ tool_name, tool_input, scope, output, provider, model }, ctx) => {
220
+ const hook = output !== "result";
221
+ const claudeCode = output === "claude_code_pre_tool_use";
222
+ const adapter = claudeCode ? "claude-code" : "codex";
223
+ const hookOutput = claudeCode ? claudeCodePreToolUseOutput : codexPreToolUseOutput;
224
+ if (hook && mode === "disabled")
225
+ return ok({});
226
+ const attempts = [];
227
+ const audited = (response, { status, action, reasonCode }) => {
228
+ telemetryDetails.set(response, { policy: { status, action, reasonCode }, attempts });
229
+ return response;
230
+ };
231
+ const input = jsonValueSchema.safeParse(claudeCode ? claudeCodeToolInput(tool_input) : tool_input);
232
+ if (!input.success) {
233
+ if (!hook) {
234
+ return fail(new DecisionError("invalid_request", "Invalid action policy tool input."));
235
+ }
236
+ const failureMode = effectiveFailureMode(profile.definition.failure_mode, registry.actionPolicyFailureMode);
237
+ const result = {
238
+ status: "failed",
239
+ action: failureMode === "native" ? "review" : failureMode,
240
+ reasonCode: "invalid_request",
241
+ reasons: ["Invalid action policy tool input"],
242
+ };
243
+ if (mode === "observe") {
244
+ const event = recordPolicyObservation(adapter, {
245
+ ...result,
246
+ profile: profile.definition,
247
+ });
248
+ return audited({ ...ok({}), _meta: { "decision-models/policy": event } }, result);
249
+ }
250
+ return audited(ok(hookOutput(result)), result);
251
+ }
252
+ const request = {
253
+ toolName: tool_name,
254
+ toolInput: input.data,
255
+ scope: hook && scope === "consequential" ? registry.actionPolicyScope : scope,
256
+ failureMode: registry.actionPolicyFailureMode,
257
+ provider,
258
+ model,
259
+ context: {
260
+ signal: ctx.mcpReq.signal,
261
+ onRouteAttempt: telemetry.enabled
262
+ ? (attempt) => {
263
+ attempts.push(attempt);
264
+ }
265
+ : undefined,
266
+ },
267
+ };
268
+ try {
269
+ // An opted-in consensus profile replaces the default model, but an explicit
270
+ // provider or model from the caller keeps the single-model path.
271
+ if (actionConsensus && provider === undefined && model === undefined) {
272
+ const result = await evaluateConsensusActionPolicy(request, registry, profile, actionConsensus);
273
+ const policyMeta = {
274
+ profile: result.profile,
275
+ consensus: result.consensus,
276
+ reasonCode: result.reasonCode,
277
+ };
278
+ if (hook && mode === "observe") {
279
+ const event = recordPolicyObservation(adapter, result);
280
+ return audited({ ...ok({}), _meta: { "decision-models/policy": event } }, result);
281
+ }
282
+ if (hook) {
283
+ return audited({
284
+ ...ok(hookOutput(result)),
285
+ _meta: { "decision-models/policy": policyMeta },
286
+ }, result);
287
+ }
288
+ return audited(ok(result), result);
289
+ }
290
+ if (hook && mode === "observe") {
291
+ const event = await observeActionPolicy(request, adapter, registry, profile);
292
+ return audited({ ...ok({}), _meta: { "decision-models/policy": event } }, { ...event, action: event.outcome.slice("would_".length) });
293
+ }
294
+ const result = await evaluateActionPolicy(request, registry, profile);
295
+ if (hook) {
296
+ return audited({
297
+ ...ok(hookOutput(result)),
298
+ _meta: {
299
+ "decision-models/policy": {
300
+ profile: result.profile,
301
+ reasonCode: result.reasonCode,
302
+ },
303
+ },
304
+ }, result);
305
+ }
306
+ return audited(ok(result), result);
307
+ }
308
+ catch (error) {
309
+ return hook && mode === "observe" ? ok({}) : fail(error, attempts);
310
+ }
311
+ });
312
+ server.registerTool("decision_providers", {
313
+ description: "List decision-model providers and report each provider's configuration or availability status.",
314
+ outputSchema: providersOutputSchema,
315
+ annotations: { readOnlyHint: true, openWorldHint: true },
316
+ }, async (ctx) => {
317
+ try {
318
+ return ok(await listProviderStatus(registry, ctx.mcpReq.signal));
319
+ }
320
+ catch (error) {
321
+ return fail(error);
322
+ }
323
+ });
324
+ const templateResources = templates.list();
325
+ const localAnnotations = { readOnlyHint: true, openWorldHint: false };
326
+ for (const { id, version, description, uri } of templateResources) {
327
+ server.registerResource(`${id}@${version}`, uri, { description, mimeType: "application/json" }, (resourceUri) => ({
328
+ contents: [
329
+ {
330
+ uri: resourceUri.href,
331
+ mimeType: "application/json",
332
+ text: JSON.stringify(templates.get({ id, version }), null, 2),
333
+ },
334
+ ],
335
+ }));
336
+ }
337
+ server.registerTool("decision_templates", {
338
+ description: "List installed decision templates, their exact versions, and resource URIs.",
339
+ outputSchema: templateListOutputSchema,
340
+ annotations: localAnnotations,
341
+ }, () => ok({ templates: templateResources }));
342
+ server.registerTool("decision_validate", {
343
+ description: "Check whether state matches a specific installed decision template version without running inference.",
344
+ inputSchema: templateValidateInputSchema,
345
+ outputSchema: templateValidateOutputSchema,
346
+ annotations: localAnnotations,
347
+ }, async (input) => {
348
+ try {
349
+ return ok(await validateTemplateState(templates, input));
350
+ }
351
+ catch (error) {
352
+ return fail(error);
353
+ }
354
+ });
355
+ server.registerTool("decision_run", {
356
+ description: "Run an installed decision template at its specified version. Hosted inference may receive state and charge for the request.",
357
+ inputSchema: templateRunInputSchema,
358
+ outputSchema: templateRunOutputSchema,
359
+ annotations: inferenceAnnotations,
360
+ }, async (input, ctx) => {
361
+ try {
362
+ const { template } = input;
363
+ const { result, meta } = await runDecision({
364
+ ...(await expandTemplateRun(templates, input)),
365
+ context: { signal: ctx.mcpReq.signal },
366
+ }, `${template.id}@${template.version}`);
367
+ return { ...ok({ template, result }), ...meta };
368
+ }
369
+ catch (error) {
370
+ return fail(error);
371
+ }
372
+ });
373
+ server.registerTool("decision_cascade", {
374
+ description: "Run a trusted cascade profile: a small model answers first, and less certain answers go to a larger model. Returns accepted with a result, or abstained when no stage met its measured confidence threshold.",
375
+ inputSchema: cascadeInputSchema,
376
+ outputSchema: cascadeOutputSchema,
377
+ annotations: inferenceAnnotations,
378
+ }, async ({ cascade, state }, ctx) => {
379
+ try {
380
+ const resolved = cascades.get(cascade);
381
+ const { template } = resolved.definition;
382
+ if (!(await templates.validateState(template, state))) {
383
+ throw new DecisionError("invalid_request", invalidState);
384
+ }
385
+ const outcome = await runCascade(resolved, state, registry, {
386
+ signal: ctx.mcpReq.signal,
387
+ });
388
+ return ok({ cascade, template, ...outcome });
389
+ }
390
+ catch (error) {
391
+ return fail(error);
392
+ }
393
+ });
394
+ server.registerTool("decision_consensus", {
395
+ description: "Run a trusted consensus profile: several approved models answer the same template, and the result is returned only when every answering member agrees. Returns agreed with a result, disagreed, or no_quorum, with each member's outcome. Treat disagreement as a signal for review.",
396
+ inputSchema: consensusInputSchema,
397
+ outputSchema: consensusOutputSchema,
398
+ annotations: inferenceAnnotations,
399
+ }, async ({ consensus, state }, ctx) => {
400
+ try {
401
+ const resolved = consensuses.get(consensus);
402
+ const { template } = resolved.definition;
403
+ if (!(await templates.validateState(template, state))) {
404
+ throw new DecisionError("invalid_request", invalidState);
405
+ }
406
+ const outcome = await runConsensus(resolved, state, registry, {
407
+ signal: ctx.mcpReq.signal,
408
+ });
409
+ return ok({ consensus, template, ...outcome });
410
+ }
411
+ catch (error) {
412
+ return fail(error);
413
+ }
414
+ });
415
+ return server;
416
+ }
@@ -0,0 +1,15 @@
1
+ import type { RouteAttempt } from "../routing/router.js";
2
+ export type TelemetryEvent = Record<string, unknown>;
3
+ export type TelemetryDetails = {
4
+ errorCode?: string;
5
+ policy?: {
6
+ status: string;
7
+ action: string;
8
+ reasonCode: string;
9
+ };
10
+ attempts?: RouteAttempt[];
11
+ };
12
+ export declare function toolEvent(tool: string, result: {
13
+ structuredContent?: unknown;
14
+ _meta?: unknown;
15
+ }, latencyMs: number, details?: TelemetryDetails): TelemetryEvent;
@@ -0,0 +1,87 @@
1
+ import { providerIds } from "../config.js";
2
+ import { randomUUID } from "node:crypto";
3
+ // Every field comes from a fixed vocabulary or a bounded identifier. Request state,
4
+ // tool input, answers, reasons and error messages are never copied into an event.
5
+ // Model names have passed the model allowlist, and template, policy, cascade and
6
+ // consensus IDs come from trusted registries, so they carry no caller data.
7
+ const CODE = /^[a-z][a-z_]{0,39}$/;
8
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;
9
+ const PROVIDERS = new Set(providerIds);
10
+ const ACTIONS = new Set(["allow", "review", "block"]);
11
+ const OUTCOMES = new Set([
12
+ "evaluated",
13
+ "skipped",
14
+ "failed",
15
+ "accepted",
16
+ "abstained",
17
+ "agreed",
18
+ "disagreed",
19
+ "no_quorum",
20
+ ]);
21
+ const CACHE = new Set(["hit", "miss", "shared", "bypass"]);
22
+ const MAX_ATTEMPTS = 8;
23
+ function record(value) {
24
+ return typeof value === "object" && value !== null && !Array.isArray(value)
25
+ ? value
26
+ : undefined;
27
+ }
28
+ function pick(value, pattern) {
29
+ return typeof value === "string" && pattern.test(value) ? value : undefined;
30
+ }
31
+ function member(value, allowed) {
32
+ return typeof value === "string" && allowed.has(value) ? value : undefined;
33
+ }
34
+ function identity(value) {
35
+ const entry = record(value);
36
+ const id = pick(entry?.id, NAME);
37
+ const version = entry?.version;
38
+ return id && Number.isSafeInteger(version) && version > 0
39
+ ? { id, version }
40
+ : undefined;
41
+ }
42
+ function attempts(list) {
43
+ if (!Array.isArray(list))
44
+ return undefined;
45
+ return list.slice(0, MAX_ATTEMPTS).flatMap((attempt) => {
46
+ const entry = record(attempt);
47
+ const provider = member(entry?.provider, PROVIDERS);
48
+ const model = pick(entry?.model, NAME);
49
+ const outcome = pick(entry?.outcome, CODE);
50
+ return provider && model && outcome ? [{ provider, model, outcome }] : [];
51
+ });
52
+ }
53
+ // Builds one event from an MCP tool result. Fields that do not match their bounded
54
+ // form are left out instead of being escaped.
55
+ export function toolEvent(tool, result, latencyMs, details) {
56
+ const content = record(result.structuredContent);
57
+ const meta = record(result._meta);
58
+ const policy = record(meta?.["decision-models/policy"]);
59
+ const outcome = details?.policy?.status ?? content?.status ?? policy?.status;
60
+ const reasonCode = details?.policy?.reasonCode ?? content?.reasonCode ?? policy?.reasonCode;
61
+ const errorCode = details?.errorCode ?? (outcome === "failed" ? (reasonCode ?? "internal") : undefined);
62
+ const fields = {
63
+ event: "decision_telemetry",
64
+ version: 1,
65
+ id: randomUUID(),
66
+ time: new Date().toISOString(),
67
+ tool,
68
+ status: errorCode === undefined ? "ok" : "error",
69
+ latencyMs: Math.max(0, Math.round(latencyMs)),
70
+ errorCode: errorCode === undefined ? undefined : (pick(errorCode, CODE) ?? "internal"),
71
+ provider: member(content?.provider, PROVIDERS),
72
+ model: pick(content?.model, NAME),
73
+ template: identity(content?.template),
74
+ profile: identity(content?.profile ?? policy?.profile),
75
+ cascade: identity(content?.cascade),
76
+ consensus: identity(content?.consensus ?? policy?.consensus),
77
+ outcome: member(outcome, OUTCOMES),
78
+ action: member(details?.policy?.action ?? content?.action, ACTIONS),
79
+ reasonCode: pick(reasonCode, CODE),
80
+ items: Array.isArray(content?.results) ? content.results.length : undefined,
81
+ cache: member(record(meta?.["decision-models/cache"])?.status, CACHE),
82
+ attempts: attempts(details?.attempts?.length
83
+ ? details.attempts
84
+ : record(meta?.["decision-models/routing"])?.attempts),
85
+ };
86
+ return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
87
+ }
@@ -0,0 +1,7 @@
1
+ import type { TelemetryConfig } from "../config.js";
2
+ import type { TelemetryEvent } from "./events.js";
3
+ export type TelemetrySink = {
4
+ enabled: boolean;
5
+ emit(event: TelemetryEvent): void;
6
+ };
7
+ export declare function createTelemetrySink(config: TelemetryConfig): TelemetrySink;
@@ -0,0 +1,59 @@
1
+ import { appendFileSync, closeSync, constants, fstatSync, lstatSync, openSync, renameSync, rmSync, } from "node:fs";
2
+ // Appends one JSON line per event to a local audit file that only its owner can read.
3
+ // Writes are synchronous so lines from concurrent decisions never interleave. A write
4
+ // failure is reported once on stderr and never changes a decision result.
5
+ export function createTelemetrySink(config) {
6
+ const { file, maxBytes, maxFiles } = config;
7
+ if (file === undefined)
8
+ return { enabled: false, emit() { } };
9
+ let reported = false;
10
+ function rotate(incoming) {
11
+ const stat = lstatSync(file, { throwIfNoEntry: false });
12
+ if (!stat)
13
+ return;
14
+ if (!stat.isFile())
15
+ throw new Error("Not a regular file.");
16
+ if (stat.size + incoming <= maxBytes)
17
+ return;
18
+ rmSync(`${file}.${maxFiles}`, { force: true });
19
+ for (let index = maxFiles - 1; index >= 1; index--) {
20
+ try {
21
+ renameSync(`${file}.${index}`, `${file}.${index + 1}`);
22
+ }
23
+ catch {
24
+ // A missing older file leaves a gap, which the next rotation fills.
25
+ }
26
+ }
27
+ renameSync(file, `${file}.1`);
28
+ }
29
+ return {
30
+ enabled: true,
31
+ emit(event) {
32
+ try {
33
+ const line = JSON.stringify(event) + "\n";
34
+ rotate(Buffer.byteLength(line));
35
+ const { O_APPEND, O_CREAT, O_WRONLY, O_NOFOLLOW, O_NONBLOCK } = constants;
36
+ const fd = openSync(file, O_APPEND | O_CREAT | O_WRONLY | O_NOFOLLOW | O_NONBLOCK, 0o600);
37
+ try {
38
+ if (!fstatSync(fd).isFile())
39
+ throw new Error("Not a regular file.");
40
+ appendFileSync(fd, line);
41
+ }
42
+ finally {
43
+ closeSync(fd);
44
+ }
45
+ }
46
+ catch {
47
+ if (reported)
48
+ return;
49
+ reported = true;
50
+ try {
51
+ console.error("Decision telemetry could not write to DECISION_TELEMETRY_FILE.");
52
+ }
53
+ catch {
54
+ // A diagnostic sink must not change the decision.
55
+ }
56
+ }
57
+ },
58
+ };
59
+ }
@@ -0,0 +1,13 @@
1
+ import { type TemplateDefinition, type TemplateIdentity } from "./schema.js";
2
+ export declare function createTemplateRegistry(definitions: readonly unknown[]): {
3
+ get(identity: TemplateIdentity): TemplateDefinition;
4
+ list(): {
5
+ id: string;
6
+ version: number;
7
+ description: string;
8
+ uri: string;
9
+ }[];
10
+ validateState(identity: TemplateIdentity, state: unknown): Promise<boolean>;
11
+ };
12
+ export type TemplateRegistry = ReturnType<typeof createTemplateRegistry>;
13
+ export declare function loadTemplateRegistry(directory?: string): TemplateRegistry;