loopengine 0.4.4 → 0.4.6

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.
@@ -0,0 +1,208 @@
1
+ const short = (text, max) => {
2
+ const flat = text.replace(/\s+/g, ' ').trim();
3
+ return flat.length > max ? flat.slice(0, max - 1) + '…' : flat;
4
+ };
5
+ function counts(runs) {
6
+ const ds = runs.flatMap((r) => r.decisions ?? []);
7
+ const fs = runs.flatMap((r) => (r.feedback ? [r.feedback] : []));
8
+ return {
9
+ runs: runs.length,
10
+ done: runs.filter((r) => r.status === 'done').length,
11
+ failed: runs.filter((r) => r.status === 'error').length,
12
+ open: runs.filter((r) => r.status === 'running' || r.status === 'awaiting_approval').length,
13
+ decided: ds.length,
14
+ approved: ds.filter((d) => d.approved).length,
15
+ changed: ds.filter((d) => d.approved && d.edited).length,
16
+ denied: ds.filter((d) => !d.approved).length,
17
+ answered: runs.reduce((n, r) => n + (r.answers?.length ?? 0), 0),
18
+ feedback: fs.length,
19
+ bad: fs.filter((f) => f.verdict === 'bad').length,
20
+ unedited: fs.filter((f) => f.edit === 'none' && f.verdict !== 'bad').length,
21
+ };
22
+ }
23
+ const show = (v) => short(v === undefined ? '(none)' : typeof v === 'string' ? v : JSON.stringify(v), 200);
24
+ function fieldChanges(before, after) {
25
+ if (!before || !after || typeof before !== 'object' || typeof after !== 'object')
26
+ return undefined;
27
+ const b = before;
28
+ const a = after;
29
+ const fields = [...new Set([...Object.keys(b), ...Object.keys(a)])].filter((k) => JSON.stringify(b[k]) !== JSON.stringify(a[k]));
30
+ return fields.map((field) => ({ field, from: show(b[field]), to: show(a[field]) }));
31
+ }
32
+ /** Lines in `after` and not `before`, and the reverse (a line diff by
33
+ * longest common subsequence, for briefs of a few hundred lines). */
34
+ export function lineDiff(before, after) {
35
+ const a = before.split('\n');
36
+ const b = after.split('\n');
37
+ if (a.length * b.length > 4_000_000) {
38
+ const setA = new Set(a);
39
+ const setB = new Set(b);
40
+ return { added: b.filter((l) => !setA.has(l) && l.trim()), removed: a.filter((l) => !setB.has(l) && l.trim()) };
41
+ }
42
+ const table = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
43
+ for (let i = a.length - 1; i >= 0; i--) {
44
+ for (let j = b.length - 1; j >= 0; j--)
45
+ table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
46
+ }
47
+ const added = [];
48
+ const removed = [];
49
+ let i = 0;
50
+ let j = 0;
51
+ while (i < a.length && j < b.length) {
52
+ if (a[i] === b[j]) {
53
+ i++;
54
+ j++;
55
+ }
56
+ else if (table[i + 1][j] >= table[i][j + 1])
57
+ removed.push(a[i++]);
58
+ else
59
+ added.push(b[j++]);
60
+ }
61
+ removed.push(...a.slice(i));
62
+ added.push(...b.slice(j));
63
+ return { added: added.filter((l) => l.trim()), removed: removed.filter((l) => l.trim()) };
64
+ }
65
+ const pct = (part, whole) => `${Math.round((100 * part) / whole)}%`;
66
+ const plural = (n, word, many = `${word}s`) => `${n.toLocaleString('en-US')} ${n === 1 ? word : many}`;
67
+ // Dollars: to the cent, or to a tenth of a cent under ten cents.
68
+ const dollars = (usd) => `$${usd >= 0.1 ? usd.toFixed(2) : usd >= 0.001 ? usd.toFixed(3) : usd > 0 ? '0.001' : '0'}`;
69
+ // Someone's words in quotes, without their own final full stop.
70
+ const quote = (text, max) => `“${short(text, max).replace(/[.!]+$/, '')}”`;
71
+ const day = (iso) => new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
72
+ export function buildWorkflowAudit(input) {
73
+ const runs = [...input.runs].sort((a, b) => a.started_at.localeCompare(b.started_at));
74
+ const total = counts(runs);
75
+ // Who decided what.
76
+ const people = new Map();
77
+ const person = (by) => people.get(by) ?? people.set(by, { by, approved: 0, changed: 0, denied: 0, answered: 0 }).get(by);
78
+ for (const r of runs) {
79
+ for (const d of r.decisions ?? []) {
80
+ if (!d.by)
81
+ continue;
82
+ const p = person(d.by);
83
+ if (!d.approved)
84
+ p.denied++;
85
+ else if (d.edited)
86
+ p.changed++;
87
+ else
88
+ p.approved++;
89
+ }
90
+ for (const a of r.answers ?? [])
91
+ if (a.by)
92
+ person(a.by).answered++;
93
+ }
94
+ const overruled = runs.flatMap((r) => (r.decisions ?? [])
95
+ .filter((d) => !d.approved || d.edited)
96
+ .map((d) => {
97
+ const changes = d.edited ? fieldChanges(d.before, d.after) : undefined;
98
+ return { at: d.at, runId: r.run_id, tool: d.tool, ...(d.by ? { by: d.by } : {}), approved: d.approved, edited: Boolean(d.edited), ...(d.reason ? { reason: d.reason } : {}), ...(changes?.length ? { changes } : {}) };
99
+ }));
100
+ // The brief: the version in use when the period began, and each saved in it.
101
+ const all = [...input.versions].sort((a, b) => a.number - b.number);
102
+ const atStart = all.filter((v) => v.at < input.since).at(-1);
103
+ const shown = all.filter((v) => v === atStart || (v.at >= input.since && v.at <= input.until));
104
+ const versions = shown.map((v) => {
105
+ const previous = all.filter((x) => x.number < v.number).at(-1);
106
+ const changedInPeriod = v.at >= input.since;
107
+ return {
108
+ number: v.number,
109
+ at: v.at,
110
+ ...(v.by ? { by: v.by } : {}),
111
+ ...(v.reason ? { reason: v.reason } : {}),
112
+ changedInPeriod,
113
+ counts: counts(runs.filter((r) => r.versions?.brief === v.number)),
114
+ ...(changedInPeriod && previous ? { diff: lineDiff(previous.content, v.content) } : {}),
115
+ };
116
+ });
117
+ const priced = runs.filter((r) => input.costs.has(r.run_id));
118
+ const totalUsd = priced.reduce((n, r) => n + input.costs.get(r.run_id), 0);
119
+ const cost = priced.length ? { totalUsd, perRunUsd: totalUsd / priced.length, pricedRuns: priced.length } : undefined;
120
+ const cases = [...runs].reverse().map((r) => ({
121
+ runId: r.run_id,
122
+ at: r.started_at,
123
+ inputs: short(Object.entries(r.params ?? {}).map(([k, v]) => `${k}: ${v}`).join(' · '), 160),
124
+ status: r.status,
125
+ ...(r.versions?.brief ? { briefVersion: r.versions.brief } : {}),
126
+ decidedBy: [...new Set([...(r.decisions ?? []), ...(r.answers ?? [])].map((d) => d.by).filter((b) => Boolean(b)))],
127
+ outcome: short(r.status === 'error' ? r.error ?? '' : r.result ?? '', 200),
128
+ }));
129
+ const changes = input.changes.map((e) => ({ at: e.at, ...(e.by ? { by: e.by } : {}), label: typeof e.data.label === 'string' ? e.data.label : 'Changed a setting' }));
130
+ // ---- The summary, in sentences. ----
131
+ const summary = [];
132
+ const v = input.verification;
133
+ summary.push(v.ok
134
+ ? `The audit log checks out: ${plural(v.events, 'event')} verified.`
135
+ : `The audit log does not check out: it's broken at event #${v.broken?.id}. Treat this report's record as unreliable from there on.`);
136
+ if (!total.runs)
137
+ summary.push('It didn’t run in this period.');
138
+ else {
139
+ summary.push(`${plural(total.runs, 'run')}: ${total.done} done, ${total.failed} failed${total.open ? `, ${total.open} still open` : ''}${total.runs && total.failed ? ` (${pct(total.failed, total.runs)} failed)` : ''}.`);
140
+ if (total.decided) {
141
+ const asAsked = total.approved - total.changed;
142
+ summary.push(`People decided ${plural(total.decided, 'request')}: ${asAsked} approved as asked, ${total.changed} changed before approving, ${total.denied} denied.`);
143
+ }
144
+ else
145
+ summary.push('Nothing needed a person’s approval.');
146
+ const reasons = [...new Set(overruled.filter((d) => !d.approved && d.reason).map((d) => quote(d.reason, 80)))].slice(0, 3);
147
+ if (reasons.length)
148
+ summary.push(`Reasons given for denials include ${reasons.join(', ')}.`);
149
+ if (total.answered)
150
+ summary.push(`It asked, and people answered, ${plural(total.answered, 'question')}.`);
151
+ if (total.feedback)
152
+ summary.push(`Feedback on ${plural(total.feedback, 'result')}: ${total.unedited} used unedited, ${total.bad} marked bad.`);
153
+ }
154
+ // The brief: each change in a sentence when there are one or two, else
155
+ // one sentence for them all; and what changed in how people judged its
156
+ // work, from the version before to the one after.
157
+ const saved = versions.filter((x) => x.changedInPeriod);
158
+ const effect = (from, to) => {
159
+ const rate = (c) => (c.decided >= 3 ? (c.changed + c.denied) / c.decided : undefined);
160
+ const before = from && rate(from.counts);
161
+ const after = rate(to.counts);
162
+ if (before !== undefined && after !== undefined)
163
+ return `; requests changed or denied went from ${Math.round(before * 100)}% to ${Math.round(after * 100)}%`;
164
+ if (from && from.counts.runs >= 3 && to.counts.runs >= 3)
165
+ return `; failures went from ${pct(from.counts.failed, from.counts.runs)} to ${pct(to.counts.failed, to.counts.runs)}`;
166
+ return '';
167
+ };
168
+ const ran = (x) => x.counts.runs > 0;
169
+ if (saved.length && saved.length <= 2) {
170
+ for (const ver of saved) {
171
+ const previous = versions.filter((x) => x.number < ver.number).at(-1);
172
+ const what = ver.diff ? ` (${plural(ver.diff.added.length, 'line')} added, ${ver.diff.removed.length} removed)` : '';
173
+ const first = !previous && ver.number === 1;
174
+ summary.push(first
175
+ ? `The brief was first recorded, as version 1, on ${day(ver.at)}.`
176
+ : `The brief changed to version ${ver.number} on ${day(ver.at)}${ver.by ? ` by ${ver.by}` : ''}${ver.reason ? `, ${quote(ver.reason, 60)}` : ''}${what}${effect(previous, ver)}.`);
177
+ }
178
+ }
179
+ else if (saved.length > 2) {
180
+ const latest = saved.at(-1);
181
+ const people = [...new Set(saved.map((x) => x.by).filter((b) => Boolean(b)))];
182
+ const start = versions.find((x) => !x.changedInPeriod);
183
+ const firstRan = versions.find(ran);
184
+ const lastRan = [...versions].reverse().find(ran);
185
+ const change = firstRan && lastRan && firstRan !== lastRan ? effect(firstRan, lastRan).replace(/^; /, ` From version ${firstRan.number} to ${lastRan.number}, `) : '';
186
+ summary.push(`The brief changed ${saved.length} times${start ? `, from version ${start.number}` : ''} to version ${latest.number}, last on ${day(latest.at)}${people.length ? `, by ${people.join(', ')}` : ''}.${change ? `${change}.` : ''}`);
187
+ }
188
+ else if (versions.length)
189
+ summary.push(`The brief stayed at version ${versions[0].number} all period.`);
190
+ const otherChanges = changes.filter((c) => !/^Edited the workflow$|^Restored brief version/.test(c.label));
191
+ if (otherChanges.length)
192
+ summary.push(`${plural(otherChanges.length, 'other setting change')}: ${[...new Set(otherChanges.map((c) => c.label.toLowerCase()))].slice(0, 4).join(', ')}.`);
193
+ if (cost)
194
+ summary.push(`It cost ${dollars(cost.totalUsd)} in model calls${cost.pricedRuns < total.runs ? ` (for the ${plural(cost.pricedRuns, 'run')} with a known price)` : ''}, ${dollars(cost.perRunUsd)} a run.`);
195
+ return {
196
+ workflow: input.workflow,
197
+ period: { since: input.since, until: input.until },
198
+ counts: total,
199
+ people: [...people.values()].sort((a, b) => b.approved + b.changed + b.denied + b.answered - (a.approved + a.changed + a.denied + a.answered)),
200
+ overruled,
201
+ versions,
202
+ changes,
203
+ ...(cost ? { cost } : {}),
204
+ cases,
205
+ verification: input.verification,
206
+ summary,
207
+ };
208
+ }
@@ -185,3 +185,24 @@ export interface EvalRunDeps {
185
185
  /** Runs every case once and scores it, recording progress as it goes.
186
186
  * Throws when a round is already running or there are no cases. */
187
187
  export declare function startEvalRound(deps: EvalRunDeps): Promise<EvalRound>;
188
+ /** Checklist items a run suggests (web/agents-config-page's Criteria),
189
+ * from what people corrected in it: a denial's reason, a changed
190
+ * request, a bad result's note, a question it had to ask. */
191
+ export declare function suggestedCriteria(run: WorkflowRun): {
192
+ kind: 'judge';
193
+ text: string;
194
+ }[];
195
+ /** A run worth saving as an eval case, and why. */
196
+ export interface EvalCandidate {
197
+ runId: string;
198
+ at: string;
199
+ why: 'denied' | 'changed' | 'bad' | 'asked' | 'failed' | 'typical';
200
+ /** The why in words: the reason, the change, the note. */
201
+ detail: string;
202
+ inputs: string;
203
+ }
204
+ /** Runs worth testing, from the given ones (any order), leaving out those
205
+ * already cases: where a person denied or changed what it did, a result
206
+ * marked bad, a question it had to ask, a failure; then a few typical
207
+ * good runs with different inputs. At most `max`. */
208
+ export declare function evalCandidates(runs: WorkflowRun[], evals: WorkflowEvals, max?: number): EvalCandidate[];
@@ -113,7 +113,9 @@ export function addEvalCase(agentDir, workflowId, input) {
113
113
  const evals = readEvals(agentDir, workflowId);
114
114
  if (evals.cases.length >= MAX_CASES)
115
115
  throw new EvidenceError(`A workflow keeps up to ${MAX_CASES} eval cases; remove one first.`);
116
- const reference = (typeof input.reference === 'string' && input.reference.trim() ? input.reference.trim() : input.run?.result?.trim()) ?? '';
116
+ // The good result: what was given, else the text a person actually used
117
+ // (feedback's `final`, their edit of the result), else the result.
118
+ const reference = (typeof input.reference === 'string' && input.reference.trim() ? input.reference.trim() : (input.run?.feedback?.final?.trim() || input.run?.result?.trim())) ?? '';
117
119
  const params = input.run?.params ?? input.params ?? {};
118
120
  if (!reference && !Object.keys(params).length)
119
121
  throw new EvidenceError('A case needs its inputs, a good result, or both.');
@@ -335,3 +337,84 @@ export function startEvalRound(deps) {
335
337
  return round;
336
338
  })();
337
339
  }
340
+ // ---------- choosing cases ----------
341
+ const clip = (text, max) => {
342
+ const flat = text.replace(/\s+/g, ' ').trim();
343
+ return flat.length > max ? flat.slice(0, max - 1) + '…' : flat;
344
+ };
345
+ const shown = (v) => clip(v === undefined ? '(none)' : typeof v === 'string' ? v : JSON.stringify(v), 80);
346
+ /** Checklist items a run suggests (web/agents-config-page's Criteria),
347
+ * from what people corrected in it: a denial's reason, a changed
348
+ * request, a bad result's note, a question it had to ask. */
349
+ export function suggestedCriteria(run) {
350
+ const out = [];
351
+ for (const d of run.decisions ?? []) {
352
+ if (!d.approved && d.reason)
353
+ out.push(`Doesn’t do what a person denied before (${d.tool}): “${clip(d.reason, 160)}”`);
354
+ if (d.approved && d.edited && d.before && d.after && typeof d.before === 'object' && typeof d.after === 'object') {
355
+ const b = d.before;
356
+ const a = d.after;
357
+ for (const field of [...new Set([...Object.keys(b), ...Object.keys(a)])].filter((k) => JSON.stringify(b[k]) !== JSON.stringify(a[k])).slice(0, 2)) {
358
+ out.push(`Gets ${field} right for ${d.tool}: a person changed it from ${shown(b[field])} to ${shown(a[field])}`);
359
+ }
360
+ }
361
+ }
362
+ if (run.feedback?.verdict === 'bad' && run.feedback.note)
363
+ out.push(`Avoids what made a result bad: “${clip(run.feedback.note, 160)}”`);
364
+ for (const answer of run.answers ?? [])
365
+ out.push(`Handles this without asking: “${clip(answer.question, 120)}” (the answer was “${clip(answer.answer, 80)}”)`);
366
+ return [...new Set(out)].slice(0, 4).map((text) => ({ kind: 'judge', text: text.slice(0, 300) }));
367
+ }
368
+ /** Runs worth testing, from the given ones (any order), leaving out those
369
+ * already cases: where a person denied or changed what it did, a result
370
+ * marked bad, a question it had to ask, a failure; then a few typical
371
+ * good runs with different inputs. At most `max`. */
372
+ export function evalCandidates(runs, evals, max = 10) {
373
+ const saved = new Set(evals.cases.map((c) => c.fromRun).filter(Boolean));
374
+ const inputsOf = (r) => clip(Object.entries(r.params ?? {}).map(([k, v]) => `${k}: ${v}`).join(' · '), 120);
375
+ const fresh = [...runs].filter((r) => !saved.has(r.run_id)).sort((a, b) => b.started_at.localeCompare(a.started_at));
376
+ const out = [];
377
+ const taken = new Set();
378
+ const add = (r, why, detail) => {
379
+ if (taken.has(r.run_id) || out.length >= max)
380
+ return;
381
+ taken.add(r.run_id);
382
+ out.push({ runId: r.run_id, at: r.started_at, why, detail: clip(detail, 160), inputs: inputsOf(r) });
383
+ };
384
+ for (const r of fresh) {
385
+ const denied = (r.decisions ?? []).find((d) => !d.approved);
386
+ if (denied)
387
+ add(r, 'denied', denied.reason ? `Denied ${denied.tool}: “${denied.reason}”` : `Denied ${denied.tool}`);
388
+ }
389
+ for (const r of fresh) {
390
+ const changed = (r.decisions ?? []).find((d) => d.approved && d.edited);
391
+ if (!changed)
392
+ continue;
393
+ const b = (changed.before && typeof changed.before === 'object' ? changed.before : {});
394
+ const a = (changed.after && typeof changed.after === 'object' ? changed.after : {});
395
+ const fields = [...new Set([...Object.keys(b), ...Object.keys(a)])].filter((k) => JSON.stringify(b[k]) !== JSON.stringify(a[k]));
396
+ add(r, 'changed', fields.length ? `Changed ${fields.slice(0, 2).map((k) => `${k} ${shown(b[k])} → ${shown(a[k])}`).join(', ')} for ${changed.tool}` : `Changed ${changed.tool} before approving`);
397
+ }
398
+ for (const r of fresh)
399
+ if (r.feedback?.verdict === 'bad' || r.feedback?.edit === 'heavy')
400
+ add(r, 'bad', r.feedback.note ? `Marked bad: “${r.feedback.note}”` : r.feedback.verdict === 'bad' ? 'Marked bad' : 'Heavily edited before use');
401
+ for (const r of fresh)
402
+ if (r.answers?.length)
403
+ add(r, 'asked', `Asked: “${r.answers[0].question}”`);
404
+ for (const r of fresh)
405
+ if (r.status === 'error')
406
+ add(r, 'failed', `Failed: ${r.error ?? ''}`);
407
+ // Typical good runs: done, nobody overruled them, each with other inputs.
408
+ const seenInputs = new Set();
409
+ for (const r of fresh) {
410
+ if (out.filter((c) => c.why === 'typical').length >= 3)
411
+ break;
412
+ const overruled = (r.decisions ?? []).some((d) => !d.approved || d.edited) || r.feedback?.verdict === 'bad';
413
+ const key = JSON.stringify(r.params ?? {});
414
+ if (r.status !== 'done' || !r.result || overruled || seenInputs.has(key))
415
+ continue;
416
+ seenInputs.add(key);
417
+ add(r, 'typical', r.feedback?.verdict === 'good' ? 'A good result, marked good' : r.feedback?.edit === 'none' ? 'A good result, used unedited' : 'A typical run that went through');
418
+ }
419
+ return out;
420
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "loopengine",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "type": "module",
5
5
  "description": "Runtime for tool-using AI agents with a transparent ReAct loop.",
6
6
  "license": "MIT",