loopengine 0.3.100 → 0.4.1
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/dist/core/audit-store.d.ts +70 -0
- package/dist/core/audit-store.js +191 -0
- package/dist/core/workflow-runs.d.ts +76 -10
- package/dist/core/workflow-runs.js +175 -13
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -2
- package/dist/models.yaml +9 -2
- package/dist/web/agents-config-page.js +280 -59
- package/dist/web/goals-page.js +2 -1
- package/dist/web/inbox-page.js +25 -4
- package/dist/web/workflow-evidence.d.ts +90 -12
- package/dist/web/workflow-evidence.js +181 -42
- package/package.json +3 -1
package/dist/web/inbox-page.js
CHANGED
|
@@ -62,6 +62,10 @@ export const inboxPageHtml = `<!doctype html>
|
|
|
62
62
|
.ib-step-k { font-size: 12px; font-weight: 700; color: var(--ink-muted); }
|
|
63
63
|
.ib-step details summary { cursor: pointer; font-size: 12.5px; color: var(--ink-muted); }
|
|
64
64
|
.ib-who { font-size: 13px; display: grid; gap: 4px; }
|
|
65
|
+
.ib-reason { color: var(--ink-muted); margin: 2px 0 0 12px; }
|
|
66
|
+
.ib-change { display: grid; gap: 2px; margin: 2px 0 0 12px; font-size: 12.5px; }
|
|
67
|
+
.ib-change del { color: var(--bad); }
|
|
68
|
+
.ib-change ins { color: var(--good); text-decoration: none; }
|
|
65
69
|
.hint { font-size: 12.5px; color: var(--ink-muted); }
|
|
66
70
|
.ib-md { font-size: 14px; line-height: 1.55; overflow-wrap: anywhere; }
|
|
67
71
|
.ib-md > :first-child { margin-top: 0; }
|
|
@@ -218,6 +222,7 @@ ${renderMarkdownScript}
|
|
|
218
222
|
'<p class="ib-question">The agent wants to run <code>' + esc(p.tool) + '</code> with:</p>' + kvHtml(p.args) +
|
|
219
223
|
(canDecide()
|
|
220
224
|
? '<textarea class="ib-args mono" hidden>' + esc(JSON.stringify(p.args, null, 2)) + '</textarea>' +
|
|
225
|
+
'<textarea class="ib-deny-reason" hidden placeholder="Why not? (optional) The agent reads this, and it' + String.fromCharCode(8217) + 's kept with the case."></textarea>' +
|
|
221
226
|
'<div class="ib-actions"><button type="button" class="ib-btn" data-act="approve">Approve</button>' +
|
|
222
227
|
'<button type="button" class="ib-btn plain" data-act="change">Change</button>' +
|
|
223
228
|
'<button type="button" class="ib-btn bad" data-act="deny">Deny</button><span class="hint ib-result" role="status"></span></div>'
|
|
@@ -234,14 +239,27 @@ ${renderMarkdownScript}
|
|
|
234
239
|
(s.result != null ? '<pre class="ib-pre" style="margin-top:6px">' + esc(s.result) + '</pre>' : '') + '</details></li>';
|
|
235
240
|
}
|
|
236
241
|
|
|
242
|
+
// What a person changed before approving: each field whose value
|
|
243
|
+
// differs, from what the agent asked for to what ran.
|
|
244
|
+
function changeOf(before, after) {
|
|
245
|
+
if (!before || !after || typeof before !== 'object' || typeof after !== 'object') return '';
|
|
246
|
+
var keys = Object.keys(before).concat(Object.keys(after).filter(function (k) { return !(k in before); }));
|
|
247
|
+
var show = function (v) { var t = v === undefined ? '(none)' : typeof v === 'string' ? v : JSON.stringify(v); return esc(t.length > 160 ? t.slice(0, 160) + String.fromCharCode(8230) : t); };
|
|
248
|
+
return keys.filter(function (k) { return JSON.stringify(before[k]) !== JSON.stringify(after[k]); }).map(function (k) {
|
|
249
|
+
return '<div><code>' + esc(k) + '</code>: <del>' + show(before[k]) + '</del> ' + String.fromCharCode(8594) + ' <ins>' + show(after[k]) + '</ins></div>';
|
|
250
|
+
}).join('');
|
|
251
|
+
}
|
|
252
|
+
|
|
237
253
|
function decidedHtml(run) {
|
|
238
254
|
var rows = [];
|
|
239
|
-
(run.decisions || []).forEach(function (d) { rows.push({ at: d.at, text: (d.approved ? (d.edited ? 'Approved as changed' : 'Approved') : 'Denied') + ' ' + d.tool, by: d.by }); });
|
|
255
|
+
(run.decisions || []).forEach(function (d) { rows.push({ at: d.at, text: (d.approved ? (d.edited ? 'Approved as changed' : 'Approved') : 'Denied') + ' ' + d.tool, by: d.by, reason: d.reason, change: d.edited ? changeOf(d.before, d.after) : '' }); });
|
|
240
256
|
(run.answers || []).forEach(function (a) { rows.push({ at: a.at, text: 'Answered: ' + a.answer, by: a.by }); });
|
|
241
257
|
rows.sort(function (a, b) { return String(a.at).localeCompare(String(b.at)); });
|
|
242
258
|
if (!rows.length) return '';
|
|
243
259
|
return '<div class="ib-card"><h3>Decisions</h3><div class="ib-who">' + rows.map(function (r) {
|
|
244
|
-
return '<div>' + esc(r.text) + ' <span class="hint">' + (r.by ? 'by ' + esc(r.by) + DOT : '') + esc(when(r.at)) + '</span
|
|
260
|
+
return '<div>' + esc(r.text) + ' <span class="hint">' + (r.by ? 'by ' + esc(r.by) + DOT : '') + esc(when(r.at)) + '</span>' +
|
|
261
|
+
(r.reason ? '<div class="ib-reason">' + String.fromCharCode(8220) + esc(r.reason) + String.fromCharCode(8221) + '</div>' : '') +
|
|
262
|
+
(r.change ? '<div class="ib-change">' + r.change + '</div>' : '') + '</div>';
|
|
245
263
|
}).join('') + '</div></div>';
|
|
246
264
|
}
|
|
247
265
|
|
|
@@ -324,8 +342,11 @@ ${renderMarkdownScript}
|
|
|
324
342
|
});
|
|
325
343
|
if (deny) deny.addEventListener('click', function (ev) {
|
|
326
344
|
var b = ev.currentTarget;
|
|
327
|
-
|
|
328
|
-
|
|
345
|
+
var reason = card.querySelector('.ib-deny-reason');
|
|
346
|
+
if (b.getAttribute('data-confirming') !== '1') { b.setAttribute('data-confirming', '1'); b.textContent = 'Deny'; reason.hidden = false; reason.focus(); return; }
|
|
347
|
+
var body = { decision: 'deny' };
|
|
348
|
+
if (reason.value.trim()) body.reason = reason.value.trim();
|
|
349
|
+
send(card, '/pending-approvals/' + encodeURIComponent(id) + '/resolve', body);
|
|
329
350
|
});
|
|
330
351
|
})(cards[i]);
|
|
331
352
|
}
|
|
@@ -30,30 +30,67 @@ export declare function runFeedbackFrom(run: WorkflowRun, body: Record<string, u
|
|
|
30
30
|
export interface EvalCase {
|
|
31
31
|
id: string;
|
|
32
32
|
params: Record<string, string>;
|
|
33
|
-
/** The good result to compare against
|
|
33
|
+
/** The good result to compare against; empty for a case checked only
|
|
34
|
+
* on criteria that need none. */
|
|
34
35
|
reference: string;
|
|
35
36
|
/** The run it was saved from. */
|
|
36
37
|
fromRun?: string;
|
|
37
38
|
createdAt: string;
|
|
38
39
|
}
|
|
40
|
+
/** A yes or no check on every result. `judge`: a statement the judge
|
|
41
|
+
* says is true or false of the result. `reference`: the result matches
|
|
42
|
+
* the case's good result (cases without one skip it). `contains` /
|
|
43
|
+
* `not_contains`: `value` is or isn't in the result, ignoring case.
|
|
44
|
+
* `tool_called` / `tool_not_called`: the run did or didn't call tool
|
|
45
|
+
* `value` (in a test run, a call it would have made counts). */
|
|
46
|
+
export type CriterionKind = 'judge' | 'reference' | 'contains' | 'not_contains' | 'tool_called' | 'tool_not_called';
|
|
47
|
+
export interface EvalCriterion {
|
|
48
|
+
id: string;
|
|
49
|
+
text: string;
|
|
50
|
+
kind: CriterionKind;
|
|
51
|
+
value?: string;
|
|
52
|
+
}
|
|
53
|
+
export interface EvalCheck {
|
|
54
|
+
criterionId: string;
|
|
55
|
+
pass: boolean;
|
|
56
|
+
reason?: string;
|
|
57
|
+
}
|
|
39
58
|
export interface EvalCaseResult {
|
|
40
59
|
caseId: string;
|
|
41
60
|
result?: string;
|
|
42
61
|
error?: string;
|
|
62
|
+
/** The tools the test run called. */
|
|
63
|
+
tools?: string[];
|
|
64
|
+
checks?: EvalCheck[];
|
|
65
|
+
/** Rounds from before criteria: a 1-5 score. */
|
|
43
66
|
score?: number;
|
|
44
67
|
reason?: string;
|
|
45
68
|
}
|
|
46
69
|
export interface EvalRound {
|
|
47
70
|
at: string;
|
|
71
|
+
/** The brief version it tested (core/audit-store.ts), when kept. */
|
|
72
|
+
briefVersion?: number;
|
|
48
73
|
/** The workflow's model and the judge's, as "provider model". */
|
|
49
74
|
model: string;
|
|
50
75
|
judge: string;
|
|
51
76
|
cases: EvalCaseResult[];
|
|
52
|
-
/**
|
|
77
|
+
/** The criteria the round checked, as they were. */
|
|
78
|
+
criteria?: EvalCriterion[];
|
|
79
|
+
/** Each criterion's pass rate: cases that passed it, of those it
|
|
80
|
+
* applied to. */
|
|
81
|
+
passRates?: {
|
|
82
|
+
criterionId: string;
|
|
83
|
+
passed: number;
|
|
84
|
+
total: number;
|
|
85
|
+
}[];
|
|
86
|
+
/** Cases that passed every check that applied to them. */
|
|
87
|
+
allPassed?: number;
|
|
88
|
+
/** Rounds from before criteria: the mean 1-5 score. */
|
|
53
89
|
average?: number;
|
|
54
90
|
}
|
|
55
91
|
export interface WorkflowEvals {
|
|
56
92
|
cases: EvalCase[];
|
|
93
|
+
criteria: EvalCriterion[];
|
|
57
94
|
rounds: EvalRound[];
|
|
58
95
|
/** Set while a round is running. */
|
|
59
96
|
running?: {
|
|
@@ -62,6 +99,8 @@ export interface WorkflowEvals {
|
|
|
62
99
|
total: number;
|
|
63
100
|
};
|
|
64
101
|
}
|
|
102
|
+
/** The check a workflow has before anyone sets criteria. */
|
|
103
|
+
export declare const REFERENCE_CRITERION: EvalCriterion;
|
|
65
104
|
export declare function readEvals(agentDir: string, workflowId: string): WorkflowEvals;
|
|
66
105
|
/** Adds a case: from a past run (its inputs, and its result unless a
|
|
67
106
|
* `reference` is given), or from `params` and a `reference`. */
|
|
@@ -72,26 +111,65 @@ export declare function addEvalCase(agentDir: string, workflowId: string, input:
|
|
|
72
111
|
}): EvalCase;
|
|
73
112
|
export declare function updateEvalCase(agentDir: string, workflowId: string, caseId: string, reference: unknown): void;
|
|
74
113
|
export declare function removeEvalCase(agentDir: string, workflowId: string, caseId: string): void;
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
export declare function
|
|
114
|
+
/** Replaces the workflow's criteria. Each needs its words; a code check
|
|
115
|
+
* needs its value. */
|
|
116
|
+
export declare function setEvalCriteria(agentDir: string, workflowId: string, input: unknown): EvalCriterion[];
|
|
117
|
+
/** The criteria a round checks: the workflow's, or with none set,
|
|
118
|
+
* whether the result matches the good result. */
|
|
119
|
+
export declare function effectiveCriteria(evals: Pick<WorkflowEvals, 'criteria'>): EvalCriterion[];
|
|
120
|
+
/** The checks a program answers, on one result. */
|
|
121
|
+
export declare function codeCheck(criterion: EvalCriterion, run: {
|
|
122
|
+
result: string;
|
|
123
|
+
tools: string[];
|
|
124
|
+
}): EvalCheck | undefined;
|
|
125
|
+
export declare const EVAL_CRITERIA_PROMPT = "You check one result of an AI agent's workflow against a list of statements. For each statement, say whether it is true of the result.\n\nJudge substance, not style: the same facts and decisions in other words count. A test run doesn't make calls that need approval; a result saying it would have made one, or a call listed as attempted, counts as making it. When a statement can't be checked from what you're given, it is false, and say why.\n\nReply with JSON only: {\"checks\": [{\"id\": \"<the statement's id>\", \"pass\": true or false, \"reason\": \"<one sentence; required when false>\"}]}, one entry per statement.";
|
|
126
|
+
/** The judge's answers for one result, one call for all its statements. */
|
|
127
|
+
export declare function judgeCriteria(judge: ModelCall, input: {
|
|
78
128
|
instructions: string;
|
|
79
|
-
reference
|
|
129
|
+
reference?: string;
|
|
80
130
|
result: string;
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
131
|
+
tools: string[];
|
|
132
|
+
criteria: EvalCriterion[];
|
|
133
|
+
}): Promise<EvalCheck[]>;
|
|
134
|
+
/** Every check on one case's result: the program's, then the judge's in
|
|
135
|
+
* one call. A case with no good result skips the reference check; a
|
|
136
|
+
* failed run fails every check that applies. */
|
|
137
|
+
export declare function checkCase(judge: ModelCall, input: {
|
|
138
|
+
instructions: string;
|
|
139
|
+
criteria: EvalCriterion[];
|
|
140
|
+
reference: string;
|
|
141
|
+
run: {
|
|
142
|
+
result: string;
|
|
143
|
+
tools: string[];
|
|
144
|
+
} | {
|
|
145
|
+
error: string;
|
|
146
|
+
};
|
|
147
|
+
}): Promise<EvalCheck[]>;
|
|
148
|
+
/** A round's pass rate per criterion, and the cases that passed all. */
|
|
149
|
+
export declare function roundSummary(criteria: EvalCriterion[], cases: EvalCaseResult[]): Pick<EvalRound, 'passRates' | 'allPassed'>;
|
|
150
|
+
export declare const DRAFT_CRITERIA_PROMPT = "You write the checks a workflow's results are tested against, from its brief: what the agent is told to do, its rules and policies.\n\nWrite three to six yes or no checks, the ones that matter most: a result failing one is a result a person would have to fix. Each is a short statement true of a good result (\"The reply gives the order's tracking number\", \"It doesn't promise a refund\"). Take them from the brief's rules and its job; never invent requirements it doesn't state.\n\nEach check has a kind:\n- \"judge\": a statement a reviewer decides by reading the result (most checks).\n- \"contains\" / \"not_contains\" with \"value\": an exact phrase that must or mustn't appear, only when the brief names the exact words (a sign-off, a banned phrase).\n- \"tool_called\" / \"tool_not_called\" with \"value\": a tool the run must or mustn't call, only when the brief says so and the tool's exact name is in the list given.\n\nReply with JSON only: {\"criteria\": [{\"text\": \"...\", \"kind\": \"judge\"}, {\"text\": \"...\", \"kind\": \"tool_called\", \"value\": \"<tool name>\"}]}";
|
|
151
|
+
/** Criteria drafted from a workflow's brief, for a person to edit before
|
|
152
|
+
* saving. */
|
|
153
|
+
export declare function draftCriteria(model: ModelCall, input: {
|
|
154
|
+
instructions: string;
|
|
155
|
+
tools: string[];
|
|
156
|
+
}): Promise<EvalCriterion[]>;
|
|
85
157
|
export interface EvalRunDeps {
|
|
86
158
|
agentDir: string;
|
|
87
159
|
workflowId: string;
|
|
160
|
+
/** The brief version being tested, recorded on the round. */
|
|
161
|
+
briefVersion?: number;
|
|
88
162
|
instructions: string;
|
|
89
163
|
/** The workflow's model and the judge's, as "provider model". */
|
|
90
164
|
model: string;
|
|
91
165
|
judgeLabel: string;
|
|
92
166
|
judge: ModelCall;
|
|
93
|
-
/** One test run of the workflow with these inputs
|
|
94
|
-
|
|
167
|
+
/** One test run of the workflow with these inputs: its result, and
|
|
168
|
+
* the tools it called. */
|
|
169
|
+
runCase(params: Record<string, string>): Promise<{
|
|
170
|
+
result: string;
|
|
171
|
+
tools: string[];
|
|
172
|
+
}>;
|
|
95
173
|
}
|
|
96
174
|
/** Runs every case once and scores it, recording progress as it goes.
|
|
97
175
|
* Throws when a round is already running or there are no cases. */
|
|
@@ -6,14 +6,21 @@
|
|
|
6
6
|
// the feedback an app or person reported afterwards
|
|
7
7
|
// (POST /agents/:name/runs/:id/feedback): the text actually used,
|
|
8
8
|
// compared with the result (none, light or heavy edits), and a verdict.
|
|
9
|
-
// - Eval cases: real inputs
|
|
10
|
-
// beside its skill
|
|
11
|
-
//
|
|
9
|
+
// - Eval cases: real inputs, and when there is one a good result to
|
|
10
|
+
// compare against, kept beside its skill
|
|
11
|
+
// (agents/<name>/skills/<id>/evals.json). A case is usually saved from
|
|
12
|
+
// a past run, its result edited into the good one.
|
|
13
|
+
// - Criteria: the workflow's yes or no checks, in the same file. Some a
|
|
14
|
+
// program answers (a phrase is or isn't in the result, a tool was or
|
|
15
|
+
// wasn't called); the rest a judge model answers, one call per case
|
|
16
|
+
// for all of them, a model other than the workflow's own (models
|
|
17
|
+
// favour their own writing). With none set, the one check is whether
|
|
18
|
+
// the result matches the case's good result.
|
|
12
19
|
// - Eval results: each time the cases are run, as a test run (tools its
|
|
13
20
|
// rules don't allow aren't run, nobody is asked anything), every
|
|
14
|
-
// result is
|
|
15
|
-
//
|
|
16
|
-
// The latest 10 rounds are kept.
|
|
21
|
+
// result is checked against every criterion; a round reports each
|
|
22
|
+
// criterion's pass rate and how many cases passed them all. A crash
|
|
23
|
+
// fails every check. The latest 10 rounds are kept.
|
|
17
24
|
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
18
25
|
import { dirname, join } from 'node:path';
|
|
19
26
|
import { randomUUID } from 'node:crypto';
|
|
@@ -75,16 +82,20 @@ export function runFeedbackFrom(run, body) {
|
|
|
75
82
|
}
|
|
76
83
|
const MAX_CASES = 30;
|
|
77
84
|
const MAX_ROUNDS = 10;
|
|
85
|
+
const MAX_CRITERIA = 8;
|
|
86
|
+
const CRITERION_KINDS = ['judge', 'reference', 'contains', 'not_contains', 'tool_called', 'tool_not_called'];
|
|
87
|
+
/** The check a workflow has before anyone sets criteria. */
|
|
88
|
+
export const REFERENCE_CRITERION = { id: 'reference', text: 'Matches the good result: the same facts and decisions', kind: 'reference' };
|
|
78
89
|
function evalsFile(agentDir, workflowId) {
|
|
79
90
|
return join(agentDir, 'skills', workflowId, 'evals.json');
|
|
80
91
|
}
|
|
81
92
|
export function readEvals(agentDir, workflowId) {
|
|
82
93
|
try {
|
|
83
94
|
const raw = JSON.parse(readFileSync(evalsFile(agentDir, workflowId), 'utf8'));
|
|
84
|
-
return { cases: Array.isArray(raw.cases) ? raw.cases : [], rounds: Array.isArray(raw.rounds) ? raw.rounds : [], ...(raw.running ? { running: raw.running } : {}) };
|
|
95
|
+
return { cases: Array.isArray(raw.cases) ? raw.cases : [], criteria: Array.isArray(raw.criteria) ? raw.criteria : [], rounds: Array.isArray(raw.rounds) ? raw.rounds : [], ...(raw.running ? { running: raw.running } : {}) };
|
|
85
96
|
}
|
|
86
97
|
catch {
|
|
87
|
-
return { cases: [], rounds: [] };
|
|
98
|
+
return { cases: [], criteria: [], rounds: [] };
|
|
88
99
|
}
|
|
89
100
|
}
|
|
90
101
|
function writeEvals(agentDir, workflowId, evals) {
|
|
@@ -102,10 +113,10 @@ export function addEvalCase(agentDir, workflowId, input) {
|
|
|
102
113
|
const evals = readEvals(agentDir, workflowId);
|
|
103
114
|
if (evals.cases.length >= MAX_CASES)
|
|
104
115
|
throw new EvidenceError(`A workflow keeps up to ${MAX_CASES} eval cases; remove one first.`);
|
|
105
|
-
const reference = typeof input.reference === 'string' && input.reference.trim() ? input.reference.trim() : input.run?.result?.trim();
|
|
106
|
-
if (!reference)
|
|
107
|
-
throw new EvidenceError('A case needs a good result to compare against.');
|
|
116
|
+
const reference = (typeof input.reference === 'string' && input.reference.trim() ? input.reference.trim() : input.run?.result?.trim()) ?? '';
|
|
108
117
|
const params = input.run?.params ?? input.params ?? {};
|
|
118
|
+
if (!reference && !Object.keys(params).length)
|
|
119
|
+
throw new EvidenceError('A case needs its inputs, a good result, or both.');
|
|
109
120
|
if (input.run && evals.cases.some((c) => c.fromRun === input.run.run_id))
|
|
110
121
|
throw new EvidenceError('That run is already a case.');
|
|
111
122
|
const c = { id: randomUUID().slice(0, 8), params, reference: reference.slice(0, 50000), ...(input.run ? { fromRun: input.run.run_id } : {}), createdAt: new Date().toISOString() };
|
|
@@ -114,8 +125,8 @@ export function addEvalCase(agentDir, workflowId, input) {
|
|
|
114
125
|
}
|
|
115
126
|
export function updateEvalCase(agentDir, workflowId, caseId, reference) {
|
|
116
127
|
const evals = readEvals(agentDir, workflowId);
|
|
117
|
-
if (typeof reference !== 'string'
|
|
118
|
-
throw new EvidenceError('
|
|
128
|
+
if (typeof reference !== 'string')
|
|
129
|
+
throw new EvidenceError('reference must be text; send "" for none.');
|
|
119
130
|
if (!evals.cases.some((c) => c.id === caseId))
|
|
120
131
|
throw new EvidenceError('No such case.');
|
|
121
132
|
writeEvals(agentDir, workflowId, { ...evals, cases: evals.cases.map((c) => (c.id === caseId ? { ...c, reference: reference.trim().slice(0, 50000) } : c)) });
|
|
@@ -124,32 +135,158 @@ export function removeEvalCase(agentDir, workflowId, caseId) {
|
|
|
124
135
|
const evals = readEvals(agentDir, workflowId);
|
|
125
136
|
writeEvals(agentDir, workflowId, { ...evals, cases: evals.cases.filter((c) => c.id !== caseId) });
|
|
126
137
|
}
|
|
127
|
-
|
|
138
|
+
/** Replaces the workflow's criteria. Each needs its words; a code check
|
|
139
|
+
* needs its value. */
|
|
140
|
+
export function setEvalCriteria(agentDir, workflowId, input) {
|
|
141
|
+
if (!Array.isArray(input))
|
|
142
|
+
throw new EvidenceError('criteria must be a list.');
|
|
143
|
+
if (input.length > MAX_CRITERIA)
|
|
144
|
+
throw new EvidenceError(`Keep it to ${MAX_CRITERIA} criteria: the ones that matter most.`);
|
|
145
|
+
const used = new Set();
|
|
146
|
+
const criteria = input.map((raw, i) => {
|
|
147
|
+
const c = (raw ?? {});
|
|
148
|
+
const kind = CRITERION_KINDS.includes(c.kind) ? c.kind : 'judge';
|
|
149
|
+
const text = typeof c.text === 'string' ? c.text.trim().slice(0, 300) : '';
|
|
150
|
+
const value = typeof c.value === 'string' ? c.value.trim().slice(0, 300) : '';
|
|
151
|
+
if (!text)
|
|
152
|
+
throw new EvidenceError(`Criterion ${i + 1} needs its words.`);
|
|
153
|
+
if (kind !== 'judge' && kind !== 'reference' && !value)
|
|
154
|
+
throw new EvidenceError(`Criterion ${i + 1} needs ${kind.startsWith('tool') ? 'the tool' : 'the text to look for'}.`);
|
|
155
|
+
let id = typeof c.id === 'string' && /^[a-z0-9-]{1,40}$/.test(c.id) ? c.id : randomUUID().slice(0, 8);
|
|
156
|
+
if (used.has(id))
|
|
157
|
+
id = randomUUID().slice(0, 8);
|
|
158
|
+
used.add(id);
|
|
159
|
+
return { id, text, kind, ...(value && kind !== 'judge' && kind !== 'reference' ? { value } : {}) };
|
|
160
|
+
});
|
|
161
|
+
const evals = readEvals(agentDir, workflowId);
|
|
162
|
+
writeEvals(agentDir, workflowId, { ...evals, criteria });
|
|
163
|
+
return criteria;
|
|
164
|
+
}
|
|
165
|
+
/** The criteria a round checks: the workflow's, or with none set,
|
|
166
|
+
* whether the result matches the good result. */
|
|
167
|
+
export function effectiveCriteria(evals) {
|
|
168
|
+
return evals.criteria.length ? evals.criteria : [REFERENCE_CRITERION];
|
|
169
|
+
}
|
|
170
|
+
/** The checks a program answers, on one result. */
|
|
171
|
+
export function codeCheck(criterion, run) {
|
|
172
|
+
const value = (criterion.value ?? '').toLowerCase();
|
|
173
|
+
const text = run.result.toLowerCase();
|
|
174
|
+
switch (criterion.kind) {
|
|
175
|
+
case 'contains': return { criterionId: criterion.id, pass: text.includes(value), ...(text.includes(value) ? {} : { reason: `"${criterion.value}" isn't in the result.` }) };
|
|
176
|
+
case 'not_contains': return { criterionId: criterion.id, pass: !text.includes(value), ...(text.includes(value) ? { reason: `"${criterion.value}" is in the result.` } : {}) };
|
|
177
|
+
case 'tool_called': {
|
|
178
|
+
const called = run.tools.some((t) => t.toLowerCase() === value);
|
|
179
|
+
return { criterionId: criterion.id, pass: called, ...(called ? {} : { reason: `It didn't call ${criterion.value}.` }) };
|
|
180
|
+
}
|
|
181
|
+
case 'tool_not_called': {
|
|
182
|
+
const called = run.tools.some((t) => t.toLowerCase() === value);
|
|
183
|
+
return { criterionId: criterion.id, pass: !called, ...(called ? { reason: `It called ${criterion.value}.` } : {}) };
|
|
184
|
+
}
|
|
185
|
+
default: return undefined;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
export const EVAL_CRITERIA_PROMPT = `You check one result of an AI agent's workflow against a list of statements. For each statement, say whether it is true of the result.
|
|
189
|
+
|
|
190
|
+
Judge substance, not style: the same facts and decisions in other words count. A test run doesn't make calls that need approval; a result saying it would have made one, or a call listed as attempted, counts as making it. When a statement can't be checked from what you're given, it is false, and say why.
|
|
191
|
+
|
|
192
|
+
Reply with JSON only: {"checks": [{"id": "<the statement's id>", "pass": true or false, "reason": "<one sentence; required when false>"}]}, one entry per statement.`;
|
|
193
|
+
/** The judge's answers for one result, one call for all its statements. */
|
|
194
|
+
export async function judgeCriteria(judge, input) {
|
|
195
|
+
const statements = input.criteria.map((c) => `- ${c.id}: ${c.kind === 'reference' ? 'The result has the same facts and decisions as the good result (wording may differ).' : c.text}`).join('\n');
|
|
196
|
+
const content = `The workflow's instructions:\n<instructions>\n${input.instructions.slice(0, 12000)}\n</instructions>\n\n` +
|
|
197
|
+
(input.reference ? `The good result for these inputs:\n<good_result>\n${input.reference.slice(0, 12000)}\n</good_result>\n\n` : '') +
|
|
198
|
+
`Tools the run called: ${input.tools.length ? input.tools.join(', ') : 'none'}\n\nThe result to check:\n<result>\n${input.result.slice(0, 12000)}\n</result>\n\nThe statements:\n${statements}`;
|
|
199
|
+
const response = await judge([{ role: 'user', content }], EVAL_CRITERIA_PROMPT, []);
|
|
200
|
+
const text = response.content.filter((b) => b.type === 'text').map((b) => b.text ?? '').join('');
|
|
201
|
+
const match = /\{[\s\S]*\}/.exec(text);
|
|
202
|
+
let parsed = {};
|
|
203
|
+
try {
|
|
204
|
+
parsed = JSON.parse(match?.[0] ?? '');
|
|
205
|
+
}
|
|
206
|
+
catch { }
|
|
207
|
+
const answers = new Map();
|
|
208
|
+
for (const a of Array.isArray(parsed.checks) ? parsed.checks : []) {
|
|
209
|
+
const x = (a ?? {});
|
|
210
|
+
if (typeof x.id === 'string' && typeof x.pass === 'boolean')
|
|
211
|
+
answers.set(x.id, { pass: x.pass, reason: typeof x.reason === 'string' ? x.reason.slice(0, 400) : '' });
|
|
212
|
+
}
|
|
213
|
+
if (!answers.size)
|
|
214
|
+
throw new Error('The judge did not answer the checks.');
|
|
215
|
+
return input.criteria.map((c) => {
|
|
216
|
+
const a = answers.get(c.id);
|
|
217
|
+
return a ? { criterionId: c.id, pass: a.pass, ...(a.reason && !a.pass ? { reason: a.reason } : {}) } : { criterionId: c.id, pass: false, reason: 'The judge gave no answer for this check.' };
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
/** Every check on one case's result: the program's, then the judge's in
|
|
221
|
+
* one call. A case with no good result skips the reference check; a
|
|
222
|
+
* failed run fails every check that applies. */
|
|
223
|
+
export async function checkCase(judge, input) {
|
|
224
|
+
const applies = input.criteria.filter((c) => c.kind !== 'reference' || input.reference.trim());
|
|
225
|
+
if ('error' in input.run) {
|
|
226
|
+
const error = input.run.error;
|
|
227
|
+
return applies.map((c) => ({ criterionId: c.id, pass: false, reason: `The run failed: ${error.slice(0, 200)}` }));
|
|
228
|
+
}
|
|
229
|
+
const run = input.run;
|
|
230
|
+
const coded = new Map(applies.flatMap((c) => { const r = codeCheck(c, run); return r ? [[c.id, r]] : []; }));
|
|
231
|
+
const forJudge = applies.filter((c) => !coded.has(c.id));
|
|
232
|
+
let judged = new Map();
|
|
233
|
+
if (forJudge.length) {
|
|
234
|
+
try {
|
|
235
|
+
judged = new Map((await judgeCriteria(judge, { instructions: input.instructions, reference: input.reference || undefined, result: run.result, tools: run.tools, criteria: forJudge })).map((c) => [c.criterionId, c]));
|
|
236
|
+
}
|
|
237
|
+
catch (err) {
|
|
238
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
239
|
+
judged = new Map(forJudge.map((c) => [c.id, { criterionId: c.id, pass: false, reason }]));
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return applies.map((c) => coded.get(c.id) ?? judged.get(c.id));
|
|
243
|
+
}
|
|
244
|
+
/** A round's pass rate per criterion, and the cases that passed all. */
|
|
245
|
+
export function roundSummary(criteria, cases) {
|
|
246
|
+
const passRates = criteria.map((c) => {
|
|
247
|
+
const checks = cases.flatMap((r) => (r.checks ?? []).filter((x) => x.criterionId === c.id));
|
|
248
|
+
return { criterionId: c.id, passed: checks.filter((x) => x.pass).length, total: checks.length };
|
|
249
|
+
});
|
|
250
|
+
return { passRates, allPassed: cases.filter((r) => (r.checks ?? []).length && r.checks.every((x) => x.pass)).length };
|
|
251
|
+
}
|
|
252
|
+
export const DRAFT_CRITERIA_PROMPT = `You write the checks a workflow's results are tested against, from its brief: what the agent is told to do, its rules and policies.
|
|
128
253
|
|
|
129
|
-
|
|
130
|
-
5 = as good as the good result or better: same facts and decisions, nothing wrong or missing that matters.
|
|
131
|
-
4 = right in substance, small gaps or wording differences that wouldn't matter to the person using it.
|
|
132
|
-
3 = usable after edits: a fact, step or decision missing or off, but nothing harmful.
|
|
133
|
-
2 = needs a rewrite: wrong in a way that matters (a wrong fact, a wrong decision, a promise it shouldn't make).
|
|
134
|
-
1 = wrong or harmful, or no real result.
|
|
254
|
+
Write three to six yes or no checks, the ones that matter most: a result failing one is a result a person would have to fix. Each is a short statement true of a good result ("The reply gives the order's tracking number", "It doesn't promise a refund"). Take them from the brief's rules and its job; never invent requirements it doesn't state.
|
|
135
255
|
|
|
136
|
-
|
|
256
|
+
Each check has a kind:
|
|
257
|
+
- "judge": a statement a reviewer decides by reading the result (most checks).
|
|
258
|
+
- "contains" / "not_contains" with "value": an exact phrase that must or mustn't appear, only when the brief names the exact words (a sign-off, a banned phrase).
|
|
259
|
+
- "tool_called" / "tool_not_called" with "value": a tool the run must or mustn't call, only when the brief says so and the tool's exact name is in the list given.
|
|
137
260
|
|
|
138
|
-
Reply with JSON only: {"
|
|
139
|
-
/**
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
const
|
|
261
|
+
Reply with JSON only: {"criteria": [{"text": "...", "kind": "judge"}, {"text": "...", "kind": "tool_called", "value": "<tool name>"}]}`;
|
|
262
|
+
/** Criteria drafted from a workflow's brief, for a person to edit before
|
|
263
|
+
* saving. */
|
|
264
|
+
export async function draftCriteria(model, input) {
|
|
265
|
+
const content = `The workflow's brief:\n<brief>\n${input.instructions.slice(0, 16000)}\n</brief>\n\nIts tools: ${input.tools.length ? input.tools.join(', ') : 'none'}`;
|
|
266
|
+
const response = await model([{ role: 'user', content }], DRAFT_CRITERIA_PROMPT, []);
|
|
143
267
|
const text = response.content.filter((b) => b.type === 'text').map((b) => b.text ?? '').join('');
|
|
144
268
|
const match = /\{[\s\S]*\}/.exec(text);
|
|
269
|
+
let parsed = {};
|
|
145
270
|
try {
|
|
146
|
-
|
|
147
|
-
const score = Math.round(Number(parsed.score));
|
|
148
|
-
if (score >= 1 && score <= 5)
|
|
149
|
-
return { score, reason: typeof parsed.reason === 'string' ? parsed.reason.slice(0, 600) : '' };
|
|
271
|
+
parsed = JSON.parse(match?.[0] ?? '');
|
|
150
272
|
}
|
|
151
273
|
catch { }
|
|
152
|
-
|
|
274
|
+
const tools = new Set(input.tools.map((t) => t.toLowerCase()));
|
|
275
|
+
const drafted = (Array.isArray(parsed.criteria) ? parsed.criteria : []).flatMap((raw) => {
|
|
276
|
+
const c = (raw ?? {});
|
|
277
|
+
const text = typeof c.text === 'string' ? c.text.trim().slice(0, 300) : '';
|
|
278
|
+
let kind = CRITERION_KINDS.includes(c.kind) && c.kind !== 'reference' ? c.kind : 'judge';
|
|
279
|
+
const value = typeof c.value === 'string' ? c.value.trim().slice(0, 300) : '';
|
|
280
|
+
// A tool it can't call, or a phrase with no words, is judged instead.
|
|
281
|
+
if ((kind === 'tool_called' || kind === 'tool_not_called') && !tools.has(value.toLowerCase()))
|
|
282
|
+
kind = 'judge';
|
|
283
|
+
if ((kind === 'contains' || kind === 'not_contains') && !value)
|
|
284
|
+
kind = 'judge';
|
|
285
|
+
return text ? [{ id: randomUUID().slice(0, 8), text, kind, ...(kind !== 'judge' ? { value } : {}) }] : [];
|
|
286
|
+
});
|
|
287
|
+
if (!drafted.length)
|
|
288
|
+
throw new EvidenceError('No checks could be drafted from this brief: add them by hand.');
|
|
289
|
+
return drafted.slice(0, MAX_CRITERIA);
|
|
153
290
|
}
|
|
154
291
|
/** Runs every case once and scores it, recording progress as it goes.
|
|
155
292
|
* Throws when a round is already running or there are no cases. */
|
|
@@ -163,32 +300,34 @@ export function startEvalRound(deps) {
|
|
|
163
300
|
const cases = evals.cases;
|
|
164
301
|
const startedAt = new Date().toISOString();
|
|
165
302
|
writeEvals(deps.agentDir, deps.workflowId, { ...evals, running: { startedAt, done: 0, total: cases.length } });
|
|
303
|
+
const criteria = effectiveCriteria(evals);
|
|
166
304
|
return (async () => {
|
|
167
305
|
const results = [];
|
|
168
306
|
for (const c of cases) {
|
|
307
|
+
let run;
|
|
169
308
|
try {
|
|
170
|
-
|
|
171
|
-
try {
|
|
172
|
-
const verdict = await judgeEvalResult(deps.judge, { instructions: deps.instructions, reference: c.reference, result });
|
|
173
|
-
results.push({ caseId: c.id, result: result.slice(0, 20000), ...verdict });
|
|
174
|
-
}
|
|
175
|
-
catch (err) {
|
|
176
|
-
results.push({ caseId: c.id, result: result.slice(0, 20000), error: err instanceof Error ? err.message : String(err) });
|
|
177
|
-
}
|
|
309
|
+
run = await deps.runCase(c.params);
|
|
178
310
|
}
|
|
179
311
|
catch (err) {
|
|
180
|
-
|
|
312
|
+
run = { error: err instanceof Error ? err.message : String(err) };
|
|
181
313
|
}
|
|
314
|
+
const checks = await checkCase(deps.judge, { instructions: deps.instructions, criteria, reference: c.reference ?? '', run });
|
|
315
|
+
results.push({
|
|
316
|
+
caseId: c.id,
|
|
317
|
+
...('error' in run ? { error: run.error } : { result: run.result.slice(0, 20000), tools: [...new Set(run.tools)] }),
|
|
318
|
+
checks,
|
|
319
|
+
});
|
|
182
320
|
const now = readEvals(deps.agentDir, deps.workflowId);
|
|
183
321
|
writeEvals(deps.agentDir, deps.workflowId, { ...now, running: { startedAt, done: results.length, total: cases.length } });
|
|
184
322
|
}
|
|
185
|
-
const scored = results.filter((r) => typeof r.score === 'number');
|
|
186
323
|
const round = {
|
|
187
324
|
at: startedAt,
|
|
325
|
+
...(deps.briefVersion ? { briefVersion: deps.briefVersion } : {}),
|
|
188
326
|
model: deps.model,
|
|
189
327
|
judge: deps.judgeLabel,
|
|
190
328
|
cases: results,
|
|
191
|
-
|
|
329
|
+
criteria,
|
|
330
|
+
...roundSummary(criteria, results),
|
|
192
331
|
};
|
|
193
332
|
const now = readEvals(deps.agentDir, deps.workflowId);
|
|
194
333
|
const { running: _done, ...rest } = now;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "loopengine",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Runtime for tool-using AI agents with a transparent ReAct loop.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -45,6 +45,8 @@
|
|
|
45
45
|
"dist/core/secret-store.d.ts",
|
|
46
46
|
"dist/core/trusted-proxy.js",
|
|
47
47
|
"dist/core/trusted-proxy.d.ts",
|
|
48
|
+
"dist/core/audit-store.js",
|
|
49
|
+
"dist/core/audit-store.d.ts",
|
|
48
50
|
"dist/core/workspace-roles.js",
|
|
49
51
|
"dist/core/workspace-roles.d.ts",
|
|
50
52
|
"dist/core/unattended.js",
|