loopengine 0.3.101 → 0.4.2

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.
@@ -55,21 +55,45 @@ export async function listInbox(deps, filter = {}) {
55
55
  * came back, and the questions it asked with their answers. The run's
56
56
  * first message (its instructions) is left out; its inputs are shown
57
57
  * apart. */
58
- export function timelineOf(history) {
58
+ export function timelineOf(history, usage = []) {
59
59
  const steps = [];
60
60
  const byToolUse = new Map();
61
+ // Each model reply is one model call, in order, when the counts agree
62
+ // (a retried call is recorded too, and then they can't be matched).
63
+ const replies = history.filter((m) => m.role === 'assistant').length;
64
+ const calls = usage.length === replies ? usage : [];
65
+ const endOf = (u) => Date.parse(u.at);
66
+ const startOf = (u) => Date.parse(u.at) - (u.durationMs ?? 0);
67
+ let reply = -1;
61
68
  history.forEach((m, index) => {
62
69
  if (index === 0 && m.role === 'user')
63
70
  return;
71
+ const call = m.role === 'assistant' ? calls.at(++reply) : undefined;
72
+ const next = m.role === 'assistant' ? calls.at(reply + 1) : undefined;
64
73
  const blocks = typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : m.content;
74
+ // The wait after the call goes on its question when it asked one (a
75
+ // person answering is most of it), else on its first tool.
76
+ const asks = blocks.some((b) => b.type === 'tool_use' && b.name === 'system_ask_user');
77
+ let first = true;
78
+ let waitShown = false;
79
+ const mark = (step, action) => {
80
+ if (first && call)
81
+ step.call = { inputTokens: call.inputTokens, outputTokens: call.outputTokens, ...(call.durationMs != null ? { durationMs: call.durationMs } : {}), ...(call.model ? { model: call.model } : {}), ...(call.costUsd != null ? { costUsd: call.costUsd } : {}) };
82
+ if (action && !waitShown && (!asks || step.kind === 'question') && call && next) {
83
+ step.waitMs = Math.max(0, startOf(next) - endOf(call));
84
+ waitShown = true;
85
+ }
86
+ first = false;
87
+ return step;
88
+ };
65
89
  for (const b of blocks) {
66
90
  if (m.role === 'assistant' && b.type === 'text' && b.text?.trim())
67
- steps.push({ kind: 'text', text: b.text.trim() });
91
+ steps.push(mark({ kind: 'text', text: b.text.trim() }, false));
68
92
  else if (b.type === 'tool_use' && b.name) {
69
93
  const step = b.name === 'system_ask_user'
70
94
  ? { kind: 'question', question: String(b.input?.question ?? '') }
71
95
  : { kind: 'tool', tool: b.name, args: b.input ?? {} };
72
- steps.push(step);
96
+ steps.push(mark(step, true));
73
97
  if (b.id)
74
98
  byToolUse.set(b.id, step);
75
99
  }
@@ -88,6 +112,19 @@ export function timelineOf(history) {
88
112
  });
89
113
  return steps;
90
114
  }
115
+ export function totalsOf(run, usage) {
116
+ if (!usage.length)
117
+ return undefined;
118
+ const end = run.finished_at ? Date.parse(run.finished_at) : Date.now();
119
+ return {
120
+ calls: usage.length,
121
+ inputTokens: usage.reduce((n, u) => n + u.inputTokens, 0),
122
+ outputTokens: usage.reduce((n, u) => n + u.outputTokens, 0),
123
+ modelMs: usage.reduce((n, u) => n + (u.durationMs ?? 0), 0),
124
+ elapsedMs: Math.max(0, end - Date.parse(run.started_at)),
125
+ ...(usage.every((u) => u.costUsd != null) ? { costUsd: usage.reduce((n, u) => n + u.costUsd, 0) } : {}),
126
+ };
127
+ }
91
128
  export async function getInboxCase(deps, id) {
92
129
  const [runs, pending] = await Promise.all([deps.runs(), deps.pending()]);
93
130
  const full = (p) => ({
@@ -101,18 +138,20 @@ export async function getInboxCase(deps, id) {
101
138
  return undefined;
102
139
  return { id, title: short(p.kind === 'question' ? questionOf(p) : `Approve ${p.tool}`, 120), agent: p.agent, workflowId: '', workflowTitle: 'Chat', pending: [full(p)], steps: [] };
103
140
  }
104
- const run = runs.find((r) => r.run_id === id);
141
+ const run = runs.find((r) => r.run_id === id) ?? (deps.run ? await deps.run(id) : undefined);
105
142
  if (!run)
106
143
  return undefined;
107
144
  const wfTitle = deps.workflowTitle(run.agent, run.workflow_id) ?? (run.workflow_id || 'One-off job');
108
145
  const waits = run.status === 'awaiting_approval' ? pending.filter((p) => p.sessionId === run.session_id).map(full) : [];
146
+ const usage = deps.usage?.(run) ?? [];
109
147
  let steps = [];
110
148
  try {
111
- steps = timelineOf(await deps.history(run));
149
+ steps = timelineOf(await deps.history(run), usage);
112
150
  }
113
151
  catch {
114
152
  // An unreadable history still shows the run and what it waits on.
115
153
  }
116
154
  const { session_id: _s, message: _m, callbacks: _c, ...shown } = run;
117
- return { id, title: titleOf(run, wfTitle), agent: run.agent, workflowId: run.workflow_id, workflowTitle: wfTitle, run: shown, pending: waits, steps };
155
+ const totals = totalsOf(run, usage);
156
+ return { id, title: titleOf(run, wfTitle), agent: run.agent, workflowId: run.workflow_id, workflowTitle: wfTitle, run: shown, pending: waits, steps, ...(totals ? { totals } : {}) };
118
157
  }
@@ -60,8 +60,22 @@ export const inboxPageHtml = `<!doctype html>
60
60
  .ib-step { display: grid; gap: 4px; padding-left: 14px; border-left: 2px solid var(--line); font-size: 13.5px; }
61
61
  .ib-step.q { border-left-color: var(--warn); }
62
62
  .ib-step-k { font-size: 12px; font-weight: 700; color: var(--ink-muted); }
63
+ .ib-step-meta { font-weight: 400; color: var(--ink-faint); margin-left: 8px; }
64
+ .ib-totals { margin: -4px 0 10px; font-size: 12.5px; color: var(--ink-muted); }
65
+ .ib-export { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px; }
66
+ .ib-export a.ib-btn { text-decoration: none; display: inline-flex; align-items: center; }
67
+ @media print {
68
+ .le-sidebar, .ib-back, .ib-export, .ib-actions, .le-head, .le-menu-btn { display: none !important; }
69
+ .le-app { display: block !important; }
70
+ .ib-card { break-inside: avoid; }
71
+ details { display: block; }
72
+ }
63
73
  .ib-step details summary { cursor: pointer; font-size: 12.5px; color: var(--ink-muted); }
64
74
  .ib-who { font-size: 13px; display: grid; gap: 4px; }
75
+ .ib-reason { color: var(--ink-muted); margin: 2px 0 0 12px; }
76
+ .ib-change { display: grid; gap: 2px; margin: 2px 0 0 12px; font-size: 12.5px; }
77
+ .ib-change del { color: var(--bad); }
78
+ .ib-change ins { color: var(--good); text-decoration: none; }
65
79
  .hint { font-size: 12.5px; color: var(--ink-muted); }
66
80
  .ib-md { font-size: 14px; line-height: 1.55; overflow-wrap: anywhere; }
67
81
  .ib-md > :first-child { margin-top: 0; }
@@ -218,6 +232,7 @@ ${renderMarkdownScript}
218
232
  '<p class="ib-question">The agent wants to run <code>' + esc(p.tool) + '</code> with:</p>' + kvHtml(p.args) +
219
233
  (canDecide()
220
234
  ? '<textarea class="ib-args mono" hidden>' + esc(JSON.stringify(p.args, null, 2)) + '</textarea>' +
235
+ '<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
236
  '<div class="ib-actions"><button type="button" class="ib-btn" data-act="approve">Approve</button>' +
222
237
  '<button type="button" class="ib-btn plain" data-act="change">Change</button>' +
223
238
  '<button type="button" class="ib-btn bad" data-act="deny">Deny</button><span class="hint ib-result" role="status"></span></div>'
@@ -225,23 +240,55 @@ ${renderMarkdownScript}
225
240
  '</div>';
226
241
  }
227
242
 
243
+ // How long something took, in words: 850 ms, 4.2 s, 3 min, 2 h 5 min.
244
+ function duration(ms) {
245
+ if (ms < 1000) return Math.round(ms) + ' ms';
246
+ if (ms < 60000) return (ms / 1000).toFixed(1) + ' s';
247
+ var min = Math.round(ms / 60000);
248
+ return min < 60 ? min + ' min' : Math.floor(min / 60) + ' h' + (min % 60 ? ' ' + (min % 60) + ' min' : '');
249
+ }
250
+ function count(n) { return Number(n).toLocaleString(); }
251
+ // Dollars: cents to the cent, smaller amounts to a tenth of a cent.
252
+ function dollars(n) { return '$' + (n >= 0.1 ? n.toFixed(2) : n >= 0.001 ? n.toFixed(3) : n > 0 ? '<0.001' : '0'); }
253
+
254
+ // A step's model call (tokens, time) and the wait after it.
255
+ function stepMeta(s) {
256
+ var parts = [];
257
+ if (s.call) parts.push('model ' + (s.call.durationMs != null ? duration(s.call.durationMs) + ', ' : '') + count(s.call.inputTokens) + ' in ' + String.fromCharCode(183) + ' ' + count(s.call.outputTokens) + ' out tokens' + (s.call.costUsd != null ? ', ' + dollars(s.call.costUsd) : ''));
258
+ if (s.waitMs != null) parts.push((s.kind === 'question' ? 'answered after ' : 'took ') + duration(s.waitMs));
259
+ return parts.length ? '<span class="ib-step-meta">' + esc(parts.join(DOT)) + '</span>' : '';
260
+ }
261
+
228
262
  function stepHtml(s) {
229
- if (s.kind === 'text') return '<li class="ib-step"><span class="ib-step-k">Agent</span><div class="ib-md">' + renderMarkdownPreview(s.text) + '</div></li>';
230
- if (s.kind === 'question') return '<li class="ib-step q"><span class="ib-step-k">Asked</span><div class="ib-md">' + renderMarkdownPreview(s.question) + '</div>' +
263
+ if (s.kind === 'text') return '<li class="ib-step"><span class="ib-step-k">Agent' + stepMeta(s) + '</span><div class="ib-md">' + renderMarkdownPreview(s.text) + '</div></li>';
264
+ if (s.kind === 'question') return '<li class="ib-step q"><span class="ib-step-k">Asked' + stepMeta(s) + '</span><div class="ib-md">' + renderMarkdownPreview(s.question) + '</div>' +
231
265
  (s.answer != null ? '<span class="ib-step-k">Answer</span><div style="white-space:pre-wrap">' + esc(s.answer) + '</div>' : '<span class="hint">Waiting for an answer</span>') + '</li>';
232
- return '<li class="ib-step"><span class="ib-step-k">Used ' + esc(s.tool) + (s.failed ? ' (failed)' : '') + '</span>' +
266
+ return '<li class="ib-step"><span class="ib-step-k">Used ' + esc(s.tool) + (s.failed ? ' (failed)' : '') + stepMeta(s) + '</span>' +
233
267
  '<details><summary>What it sent' + (s.result != null ? ' and got back' : '') + '</summary><pre class="ib-pre">' + esc(JSON.stringify(s.args, null, 2)) + '</pre>' +
234
268
  (s.result != null ? '<pre class="ib-pre" style="margin-top:6px">' + esc(s.result) + '</pre>' : '') + '</details></li>';
235
269
  }
236
270
 
271
+ // What a person changed before approving: each field whose value
272
+ // differs, from what the agent asked for to what ran.
273
+ function changeOf(before, after) {
274
+ if (!before || !after || typeof before !== 'object' || typeof after !== 'object') return '';
275
+ var keys = Object.keys(before).concat(Object.keys(after).filter(function (k) { return !(k in before); }));
276
+ 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); };
277
+ return keys.filter(function (k) { return JSON.stringify(before[k]) !== JSON.stringify(after[k]); }).map(function (k) {
278
+ return '<div><code>' + esc(k) + '</code>: <del>' + show(before[k]) + '</del> ' + String.fromCharCode(8594) + ' <ins>' + show(after[k]) + '</ins></div>';
279
+ }).join('');
280
+ }
281
+
237
282
  function decidedHtml(run) {
238
283
  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 }); });
284
+ (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
285
  (run.answers || []).forEach(function (a) { rows.push({ at: a.at, text: 'Answered: ' + a.answer, by: a.by }); });
241
286
  rows.sort(function (a, b) { return String(a.at).localeCompare(String(b.at)); });
242
287
  if (!rows.length) return '';
243
288
  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></div>';
289
+ return '<div>' + esc(r.text) + ' <span class="hint">' + (r.by ? 'by ' + esc(r.by) + DOT : '') + esc(when(r.at)) + '</span>' +
290
+ (r.reason ? '<div class="ib-reason">' + String.fromCharCode(8220) + esc(r.reason) + String.fromCharCode(8221) + '</div>' : '') +
291
+ (r.change ? '<div class="ib-change">' + r.change + '</div>' : '') + '</div>';
245
292
  }).join('') + '</div></div>';
246
293
  }
247
294
 
@@ -254,6 +301,25 @@ ${renderMarkdownScript}
254
301
  return wf + DOT + '<a class="ib-link" href="' + agentUrl + '">' + esc(c.agent) + '</a>';
255
302
  }
256
303
 
304
+ function totalsHtml(c) {
305
+ var t = c.totals;
306
+ if (!t) return '';
307
+ return '<p class="ib-totals">' + esc([
308
+ t.calls + (t.calls === 1 ? ' model call' : ' model calls'),
309
+ count(t.inputTokens) + ' tokens in, ' + count(t.outputTokens) + ' out',
310
+ 'model time ' + duration(t.modelMs),
311
+ t.costUsd != null ? 'cost ' + dollars(t.costUsd) : '',
312
+ t.elapsedMs != null ? 'start to finish ' + duration(t.elapsedMs) : '',
313
+ ].filter(Boolean).join(DOT)) + '</p>';
314
+ }
315
+
316
+ // Keep the case: its whole record as a file, or printed (to paper or
317
+ // a PDF, from the browser's print dialog).
318
+ function exportHtml(c) {
319
+ return '<div class="ib-export"><a class="ib-btn plain" href="/inbox/cases/' + encodeURIComponent(c.id) + '/export" download>Download record</a>' +
320
+ '<button type="button" class="ib-btn plain" data-act="print">Print or save as PDF</button></div>';
321
+ }
322
+
257
323
  function renderCase(c) {
258
324
  var run = c.run;
259
325
  var status = run ? stateHtml({ waiting: c.pending.map(function (p) { return p.kind; }), status: run.status }) : stateHtml({ waiting: c.pending.map(function (p) { return p.kind; }), status: 'awaiting_approval' });
@@ -262,10 +328,13 @@ ${renderMarkdownScript}
262
328
  '<div class="ib-case-head"><h2>' + esc(c.title) + '</h2><div class="ib-chips">' + status + '<span>' + caseLinks(c) + (run ? DOT + 'started ' + esc(when(run.started_at)) + (run.source ? ' by ' + esc(run.source === 'webhook' ? 'a webhook' : run.source === 'schedule' ? 'a schedule' : run.source === 'console' ? 'Run now' : run.source === 'api' ? 'an app' : run.source) : '') : '') + '</span></div></div>' +
263
329
  c.pending.map(pendingHtml).join('') +
264
330
  (run && run.params ? '<div class="ib-card"><h3>Inputs</h3>' + kvHtml(run.params) + '</div>' : '') +
265
- (c.steps.length ? '<div class="ib-card"><h3>What the agent did</h3><ol class="ib-steps">' + c.steps.map(stepHtml).join('') + '</ol></div>' : '') +
331
+ (c.steps.length ? '<div class="ib-card"><h3>What the agent did</h3>' + totalsHtml(c) + '<ol class="ib-steps">' + c.steps.map(stepHtml).join('') + '</ol></div>' : '') +
266
332
  (run ? decidedHtml(run) : '') +
267
333
  (run && run.result ? '<div class="ib-card"><h3>Result</h3><div class="ib-md">' + renderMarkdownPreview(run.result) + '</div></div>' : '') +
268
- (run && run.error ? '<div class="ib-card"><h3>Failed</h3><p class="error">' + esc(run.error) + '</p></div>' : '');
334
+ (run && run.error ? '<div class="ib-card"><h3>Failed</h3><p class="error">' + esc(run.error) + '</p></div>' : '') +
335
+ exportHtml(c);
336
+ var print = page.querySelector('[data-act="print"]');
337
+ if (print) print.addEventListener('click', function () { window.print(); });
269
338
  wireCase(c);
270
339
  }
271
340
 
@@ -324,8 +393,11 @@ ${renderMarkdownScript}
324
393
  });
325
394
  if (deny) deny.addEventListener('click', function (ev) {
326
395
  var b = ev.currentTarget;
327
- if (b.getAttribute('data-confirming') !== '1') { b.setAttribute('data-confirming', '1'); b.textContent = 'Click again to deny'; return; }
328
- send(card, '/pending-approvals/' + encodeURIComponent(id) + '/resolve', { decision: 'deny' });
396
+ var reason = card.querySelector('.ib-deny-reason');
397
+ if (b.getAttribute('data-confirming') !== '1') { b.setAttribute('data-confirming', '1'); b.textContent = 'Deny'; reason.hidden = false; reason.focus(); return; }
398
+ var body = { decision: 'deny' };
399
+ if (reason.value.trim()) body.reason = reason.value.trim();
400
+ send(card, '/pending-approvals/' + encodeURIComponent(id) + '/resolve', body);
329
401
  });
330
402
  })(cards[i]);
331
403
  }
@@ -68,6 +68,8 @@ export interface EvalCaseResult {
68
68
  }
69
69
  export interface EvalRound {
70
70
  at: string;
71
+ /** The brief version it tested (core/audit-store.ts), when kept. */
72
+ briefVersion?: number;
71
73
  /** The workflow's model and the judge's, as "provider model". */
72
74
  model: string;
73
75
  judge: string;
@@ -155,6 +157,8 @@ export declare function draftCriteria(model: ModelCall, input: {
155
157
  export interface EvalRunDeps {
156
158
  agentDir: string;
157
159
  workflowId: string;
160
+ /** The brief version being tested, recorded on the round. */
161
+ briefVersion?: number;
158
162
  instructions: string;
159
163
  /** The workflow's model and the judge's, as "provider model". */
160
164
  model: string;
@@ -322,6 +322,7 @@ export function startEvalRound(deps) {
322
322
  }
323
323
  const round = {
324
324
  at: startedAt,
325
+ ...(deps.briefVersion ? { briefVersion: deps.briefVersion } : {}),
325
326
  model: deps.model,
326
327
  judge: deps.judgeLabel,
327
328
  cases: results,
@@ -0,0 +1,66 @@
1
+ import type { WorkflowRun } from '../core/workflow-runs.js';
2
+ export interface HealthNumbers {
3
+ runs: number;
4
+ /** Finished, done or failed. */
5
+ finished: number;
6
+ failed: number;
7
+ /** Approvals decided: approved (of which changed first) or denied. */
8
+ approved: number;
9
+ changed: number;
10
+ denied: number;
11
+ /** Questions answered in its runs. */
12
+ questions: number;
13
+ /** Feedback on results: how many, used unedited, bad. */
14
+ feedback: number;
15
+ unedited: number;
16
+ bad: number;
17
+ /** Middle start-to-finish time of finished runs. */
18
+ medianMs?: number;
19
+ /** Mean cost of the runs whose every model call has a price, and how
20
+ * many runs that is. */
21
+ costPerRunUsd?: number;
22
+ pricedRuns: number;
23
+ }
24
+ export interface HealthVersion extends HealthNumbers {
25
+ /** The brief version, or null for runs from before versions. */
26
+ version: number | null;
27
+ /** Its first and last run in the period. */
28
+ from: string;
29
+ to: string;
30
+ }
31
+ export interface HealthDay {
32
+ /** YYYY-MM-DD, UTC. */
33
+ date: string;
34
+ runs: number;
35
+ failed: number;
36
+ decided: number;
37
+ /** Denied or changed before approving. */
38
+ overruled: number;
39
+ }
40
+ export type HealthMeasure = 'failure' | 'overruled' | 'bad-feedback';
41
+ export interface HealthAlert {
42
+ measure: HealthMeasure;
43
+ /** In words, for the panel and the messaging app. */
44
+ text: string;
45
+ recent: number;
46
+ before: number;
47
+ }
48
+ export interface WorkflowHealth {
49
+ days: number;
50
+ since: string;
51
+ total: HealthNumbers;
52
+ versions: HealthVersion[];
53
+ daily: HealthDay[];
54
+ alerts: HealthAlert[];
55
+ }
56
+ /** Each run's cost in US dollars, where known. */
57
+ export type RunCosts = Map<string, number>;
58
+ /** The last 7 days against the 23 before them: an alert when a rate at
59
+ * least doubled, reached 20%, and rests on at least 5 cases. */
60
+ export declare function healthAlerts(runs: WorkflowRun[], now?: number): HealthAlert[];
61
+ /** The workflow's health over the last `days` days, from its runs in
62
+ * that period (any order) and each run's cost where known. */
63
+ export declare function workflowHealth(runs: WorkflowRun[], costs: RunCosts, options?: {
64
+ days?: number;
65
+ now?: number;
66
+ }): WorkflowHealth;
@@ -0,0 +1,76 @@
1
+ const DAY = 24 * 60 * 60 * 1000;
2
+ function numbers(runs, costs) {
3
+ const finished = runs.filter((r) => r.status === 'done' || r.status === 'error');
4
+ const decisions = runs.flatMap((r) => r.decisions ?? []);
5
+ const feedback = runs.flatMap((r) => (r.feedback ? [r.feedback] : []));
6
+ const times = finished.filter((r) => r.finished_at).map((r) => Date.parse(r.finished_at) - Date.parse(r.started_at)).sort((a, b) => a - b);
7
+ const priced = runs.filter((r) => costs.has(r.run_id));
8
+ return {
9
+ runs: runs.length,
10
+ finished: finished.length,
11
+ failed: finished.filter((r) => r.status === 'error').length,
12
+ approved: decisions.filter((d) => d.approved).length,
13
+ changed: decisions.filter((d) => d.approved && d.edited).length,
14
+ denied: decisions.filter((d) => !d.approved).length,
15
+ questions: runs.reduce((n, r) => n + (r.answers?.length ?? 0), 0),
16
+ feedback: feedback.length,
17
+ unedited: feedback.filter((f) => f.edit === 'none' && f.verdict !== 'bad').length,
18
+ bad: feedback.filter((f) => f.verdict === 'bad').length,
19
+ ...(times.length ? { medianMs: times[Math.floor((times.length - 1) / 2)] } : {}),
20
+ pricedRuns: priced.length,
21
+ ...(priced.length ? { costPerRunUsd: priced.reduce((n, r) => n + costs.get(r.run_id), 0) / priced.length } : {}),
22
+ };
23
+ }
24
+ const rate = (part, whole) => (whole ? part / whole : 0);
25
+ const pct = (r) => `${Math.round(r * 100)}%`;
26
+ /** The last 7 days against the 23 before them: an alert when a rate at
27
+ * least doubled, reached 20%, and rests on at least 5 cases. */
28
+ export function healthAlerts(runs, now = Date.now()) {
29
+ const cut = new Date(now - 7 * DAY).toISOString();
30
+ const recent = runs.filter((r) => r.started_at >= cut);
31
+ const before = runs.filter((r) => r.started_at < cut);
32
+ const alerts = [];
33
+ const check = (measure, of, text) => {
34
+ const a = of(recent);
35
+ const b = of(before);
36
+ const r = rate(a.part, a.whole);
37
+ const was = rate(b.part, b.whole);
38
+ if (a.whole >= 5 && r >= 0.2 && (b.whole === 0 ? false : r >= 2 * was))
39
+ alerts.push({ measure, text: text(pct(r), pct(was)), recent: r, before: was });
40
+ };
41
+ const finished = (rs) => rs.filter((r) => r.status === 'done' || r.status === 'error');
42
+ check('failure', (rs) => ({ part: finished(rs).filter((r) => r.status === 'error').length, whole: finished(rs).length }), (n, t) => `${n} of runs failed in the last 7 days, up from ${t}.`);
43
+ check('overruled', (rs) => {
44
+ const ds = rs.flatMap((r) => r.decisions ?? []);
45
+ return { part: ds.filter((d) => !d.approved || d.edited).length, whole: ds.length };
46
+ }, (n, t) => `People denied or changed ${n} of its requests in the last 7 days, up from ${t}.`);
47
+ check('bad-feedback', (rs) => {
48
+ const fs = rs.flatMap((r) => (r.feedback ? [r.feedback] : []));
49
+ return { part: fs.filter((f) => f.verdict === 'bad').length, whole: fs.length };
50
+ }, (n, t) => `${n} of its results were marked bad in the last 7 days, up from ${t}.`);
51
+ return alerts;
52
+ }
53
+ /** The workflow's health over the last `days` days, from its runs in
54
+ * that period (any order) and each run's cost where known. */
55
+ export function workflowHealth(runs, costs, options = {}) {
56
+ const days = options.days ?? 30;
57
+ const now = options.now ?? Date.now();
58
+ const since = new Date(now - days * DAY).toISOString();
59
+ const inPeriod = runs.filter((r) => r.started_at >= since).sort((a, b) => a.started_at.localeCompare(b.started_at));
60
+ const byVersion = new Map();
61
+ for (const r of inPeriod) {
62
+ const v = r.versions?.brief ?? null;
63
+ byVersion.set(v, [...(byVersion.get(v) ?? []), r]);
64
+ }
65
+ const versions = [...byVersion.entries()]
66
+ .map(([version, rs]) => ({ version, from: rs[0].started_at, to: rs.at(-1).started_at, ...numbers(rs, costs) }))
67
+ .sort((a, b) => b.from.localeCompare(a.from));
68
+ const daily = [];
69
+ for (let d = days - 1; d >= 0; d--) {
70
+ const date = new Date(now - d * DAY).toISOString().slice(0, 10);
71
+ const rs = inPeriod.filter((r) => r.started_at.slice(0, 10) === date);
72
+ const ds = rs.flatMap((r) => r.decisions ?? []);
73
+ daily.push({ date, runs: rs.length, failed: rs.filter((r) => r.status === 'error').length, decided: ds.length, overruled: ds.filter((x) => !x.approved || x.edited).length });
74
+ }
75
+ return { days, since, total: numbers(inPeriod, costs), versions, daily, alerts: healthAlerts(inPeriod, now) };
76
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "loopengine",
3
- "version": "0.3.101",
3
+ "version": "0.4.2",
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",