loopengine 0.4.5 → 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.
@@ -1,3 +1,18 @@
1
+ export const RECENT_DAYS = 7;
2
+ // A case's outcome in words, from its status and the last decision.
3
+ function outcomeOf(run, waiting) {
4
+ if (waiting)
5
+ return 'Waiting';
6
+ if (run.status === 'error')
7
+ return 'Failed';
8
+ if (run.status === 'running')
9
+ return 'Running';
10
+ const last = [...(run.decisions ?? []).map((d) => ({ at: d.at, by: d.by, what: d.approved ? (d.edited ? 'Changed' : 'Approved') : 'Denied' })), ...(run.answers ?? []).map((a) => ({ at: a.at, by: a.by, what: 'Answered' }))]
11
+ .sort((a, b) => a.at.localeCompare(b.at)).pop();
12
+ if (!last)
13
+ return 'Done automatically';
14
+ return last.by ? `${last.what} by ${last.by}` : last.what;
15
+ }
1
16
  const OUTSIDE = 'p-';
2
17
  function short(text, max) {
3
18
  const flat = text.replace(/\s+/g, ' ').trim();
@@ -13,6 +28,9 @@ function titleOf(run, workflowTitle) {
13
28
  function questionOf(p) {
14
29
  return typeof p.args.question === 'string' ? p.args.question : p.reason;
15
30
  }
31
+ /** `view`: "needs" (waiting on a person, oldest first, however long),
32
+ * "recent" (the last RECENT_DAYS days, latest first), or "auto" (needs
33
+ * when anything waits, else recent). `open` is the older name for needs. */
16
34
  export async function listInbox(deps, filter = {}) {
17
35
  const [runs, pending] = await Promise.all([deps.runs(), deps.pending()]);
18
36
  const bySession = new Map();
@@ -22,34 +40,41 @@ export async function listInbox(deps, filter = {}) {
22
40
  const items = runs.map((run) => {
23
41
  const wfTitle = deps.workflowTitle(run.agent, run.workflow_id) ?? (run.workflow_id || 'One-off job');
24
42
  const waits = run.status === 'awaiting_approval' ? (bySession.get(run.session_id) ?? []) : [];
25
- const lastBy = [...(run.decisions ?? []), ...(run.answers ?? [])].sort((a, b) => a.at.localeCompare(b.at)).pop()?.by;
43
+ const decided = [...(run.decisions ?? []), ...(run.answers ?? [])].sort((a, b) => a.at.localeCompare(b.at));
44
+ const lastBy = decided.at(-1)?.by;
45
+ const since = waits.map((p) => p.createdAt).filter((t) => Boolean(t)).sort()[0];
46
+ const lastActivity = [run.started_at, run.finished_at, decided.at(-1)?.at].filter((t) => Boolean(t)).sort().at(-1);
26
47
  return {
27
48
  id: run.run_id, title: titleOf(run, wfTitle), agent: run.agent, workflowId: run.workflow_id, workflowTitle: wfTitle, status: run.status,
28
49
  waiting: [...new Set(waits.map((p) => p.kind))], startedAt: run.started_at, ...(run.finished_at ? { finishedAt: run.finished_at } : {}), ...(lastBy ? { lastBy } : {}),
50
+ ...(waits.length ? { waitingSince: since ?? run.started_at } : {}), lastActivity, outcome: outcomeOf(run, waits.length > 0),
29
51
  };
30
52
  });
31
53
  for (const p of pending) {
32
54
  if (runSessions.has(p.sessionId))
33
55
  continue;
56
+ const at = p.createdAt ?? new Date(0).toISOString();
34
57
  items.push({
35
58
  id: OUTSIDE + p.pendingId, title: short(p.kind === 'question' ? questionOf(p) : `Approve ${p.tool}`, 120), agent: p.agent, workflowId: '', workflowTitle: 'Chat',
36
- status: 'awaiting_approval', waiting: [p.kind], startedAt: p.createdAt ?? new Date(0).toISOString(),
59
+ status: 'awaiting_approval', waiting: [p.kind], startedAt: at, waitingSince: at, lastActivity: at, outcome: 'Waiting',
37
60
  });
38
61
  }
39
62
  const open = items.filter((i) => i.waiting.length).length;
63
+ const view = filter.open || filter.view === 'needs' ? 'needs' : filter.view === 'recent' ? 'recent' : open ? 'needs' : 'recent';
64
+ const recentSince = new Date((filter.now ?? Date.now()) - RECENT_DAYS * 24 * 60 * 60 * 1000).toISOString();
40
65
  const q = filter.q?.trim().toLowerCase();
41
66
  const runParams = new Map(runs.map((r) => [r.run_id, Object.values(r.params ?? {}).join(' ')]));
42
67
  const shown = items
43
- .filter((i) => !filter.open || i.waiting.length)
68
+ .filter((i) => (view === 'needs' ? i.waiting.length > 0 : !i.waiting.length && i.lastActivity >= recentSince))
44
69
  .filter((i) => !filter.workflow || i.workflowId === filter.workflow)
45
- .filter((i) => !q || `${i.title} ${i.agent} ${i.workflowTitle} ${runParams.get(i.id) ?? ''} ${i.lastBy ?? ''}`.toLowerCase().includes(q))
46
- // Waiting first, newest first within each.
47
- .sort((a, b) => (b.waiting.length ? 1 : 0) - (a.waiting.length ? 1 : 0) || b.startedAt.localeCompare(a.startedAt));
70
+ .filter((i) => !q || `${i.title} ${i.agent} ${i.workflowTitle} ${runParams.get(i.id) ?? ''} ${i.lastBy ?? ''} ${i.outcome}`.toLowerCase().includes(q))
71
+ // Waiting: the longest-waiting first. Recent: the latest first.
72
+ .sort((a, b) => (view === 'needs' ? (a.waitingSince ?? '').localeCompare(b.waitingSince ?? '') : b.lastActivity.localeCompare(a.lastActivity)));
48
73
  // Every workflow with a case, whatever the filter, for the workflow picker.
49
74
  const workflows = [...new Map(items.filter((i) => i.workflowId).map((i) => [i.workflowId, i.workflowTitle])).entries()]
50
75
  .map(([id, title]) => ({ id, title }))
51
76
  .sort((a, b) => a.title.localeCompare(b.title));
52
- return { items: shown.slice(0, filter.limit ?? 200), open, workflows };
77
+ return { items: shown.slice(0, filter.limit ?? 200), open, view, workflows };
53
78
  }
54
79
  /** What the agent did, in order: its words, the tools it used with what
55
80
  * came back, and the questions it asked with their answers. The run's
@@ -1,8 +1,11 @@
1
- // The console's Inbox: /inbox lists every workflow run as a case, the ones
2
- // waiting on a person first (?open=1 shows only those); /inbox?case=<id> opens one, with what it was
3
- // given, what the agent did, what it asks now (answer, approve, approve
4
- // as changed, deny) and who decided what (web/inbox-admin.ts behind
5
- // /inbox/*). An approver or viewer sees only this page; a viewer can't
1
+ // The console's Inbox, for acting: /inbox shows what needs a person
2
+ // (Needs you, however long it has waited, the longest first) and every
3
+ // case from the last 7 days (Recent: done automatically, decided by
4
+ // someone, or failed); older cases are searched in Audit. A case is its
5
+ // own page, /cases/<id> (?back= is where its back link goes): what it
6
+ // was given, what the agent did, what it asks now (answer, approve,
7
+ // approve as changed, deny), who decided what, and Save as eval case
8
+ // (web/inbox-admin.ts behind /inbox/*). An approver or viewer sees only this page; a viewer can't
6
9
  // decide. Like the other console pages, its inline script avoids
7
10
  // backslashes and template placeholders, since it lives inside a template
8
11
  // literal.
@@ -72,6 +75,12 @@ export const inboxPageHtml = `<!doctype html>
72
75
  }
73
76
  .ib-step details summary { cursor: pointer; font-size: 12.5px; color: var(--ink-muted); }
74
77
  .ib-who { font-size: 13px; display: grid; gap: 4px; }
78
+ .ib-late { color: var(--warn); font-weight: 700; }
79
+ .ib-older { margin: 0; font-size: 12.5px; }
80
+ .ib-suggest { display: grid; gap: 8px; border-top: 1px solid var(--line); padding-top: 10px; }
81
+ .ib-suggest[hidden] { display: none; }
82
+ .ib-suggest h4 { margin: 0; font-size: 13px; }
83
+ .ib-suggest-row { display: flex; gap: 10px; align-items: flex-start; justify-content: space-between; font-size: 13px; }
75
84
  .ib-reason { color: var(--ink-muted); margin: 2px 0 0 12px; }
76
85
  .ib-change { display: grid; gap: 2px; margin: 2px 0 0 12px; font-size: 12.5px; }
77
86
  .ib-change del { color: var(--bad); }
@@ -119,7 +128,15 @@ ${renderMarkdownScript}
119
128
  var ELLIPSIS = String.fromCharCode(8230);
120
129
  var DOT = ' ' + String.fromCharCode(183) + ' ';
121
130
  var params = new URLSearchParams(location.search);
122
- var state = { open: params.get('open') === '1', q: params.get('q') || '', workflow: params.get('workflow') || '' };
131
+ // Needs you (waiting on a person, however long) or Recent (the last 7
132
+ // days); none asked: needs you when anything waits.
133
+ var state = { view: params.get('open') === '1' ? 'needs' : params.get('view') || '', q: params.get('q') || '', workflow: params.get('workflow') || '' };
134
+ // A case's own page is /cases/<id>; ?back= is where its back link goes.
135
+ var caseMatch = location.pathname.match(/^[/]cases[/]([^/]+)$/);
136
+ var caseId = caseMatch ? decodeURIComponent(caseMatch[1]) : '';
137
+ var back = params.get('back');
138
+ if (!back || back.charAt(0) !== '/' || back.charAt(1) === '/') back = '/inbox';
139
+ var fullAccess = !document.querySelector('.le-app.le-inbox-only');
123
140
  var role = 'owner';
124
141
  var workflows = {};
125
142
 
@@ -139,6 +156,27 @@ ${renderMarkdownScript}
139
156
  function when(iso) { return iso ? new Date(iso).toLocaleString() : ''; }
140
157
  function canDecide() { return role !== 'viewer'; }
141
158
 
159
+ // How long a case has waited: "Waiting 3 h", "Waiting 12 days".
160
+ function waitedFor(ms) {
161
+ var h = Math.floor(ms / 3600000);
162
+ if (h < 1) return 'Waiting ' + Math.max(1, Math.floor(ms / 60000)) + ' min';
163
+ if (h < 48) return 'Waiting ' + h + ' h';
164
+ return 'Waiting ' + Math.floor(h / 24) + ' days';
165
+ }
166
+ // What happened in a recent case.
167
+ function outcomeHtml(item) {
168
+ var o = item.outcome || '';
169
+ var cls = o === 'Failed' ? 'bad' : o === 'Running' ? 'run' : /^Denied/.test(o) ? 'bad' : /^Changed/.test(o) ? 'warn' : 'good';
170
+ return '<span class="ib-state ' + cls + '">' + esc(o) + '</span>';
171
+ }
172
+ // A case's page, coming back here.
173
+ function caseHref(id) {
174
+ return '/cases/' + encodeURIComponent(id) + '?back=' + encodeURIComponent(pageUrl());
175
+ }
176
+ function backLabel() {
177
+ return back.indexOf('/audit') === 0 ? 'Audit' : back.indexOf('/agents') === 0 ? 'Workflow' : 'Inbox';
178
+ }
179
+
142
180
  function stateHtml(item) {
143
181
  if (item.waiting && item.waiting.length) return '<span class="ib-state warn">' + (item.waiting.indexOf('approval') !== -1 ? 'Needs approval' : 'Question') + '</span>';
144
182
  if (item.status === 'running') return '<span class="ib-state run">Running</span>';
@@ -149,14 +187,14 @@ ${renderMarkdownScript}
149
187
 
150
188
  function listUrl() {
151
189
  var q = new URLSearchParams();
152
- if (state.open) q.set('open', '1');
190
+ q.set('view', state.view || 'auto');
153
191
  if (state.q) q.set('q', state.q);
154
192
  if (state.workflow) q.set('workflow', state.workflow);
155
193
  return '/inbox/items?' + q.toString();
156
194
  }
157
195
  function pageUrl() {
158
196
  var q = new URLSearchParams();
159
- if (state.open) q.set('open', '1');
197
+ if (state.view) q.set('view', state.view);
160
198
  if (state.q) q.set('q', state.q);
161
199
  if (state.workflow) q.set('workflow', state.workflow);
162
200
  var s = q.toString();
@@ -167,23 +205,30 @@ ${renderMarkdownScript}
167
205
  var items = data.items || [];
168
206
  (data.workflows || []).forEach(function (w) { workflows[w.id] = w.title; });
169
207
  var options = Object.keys(workflows).sort(function (a, b) { return workflows[a].localeCompare(workflows[b]); }).map(function (id) { return '<option value="' + esc(id) + '"' + (id === state.workflow ? ' selected' : '') + '>' + esc(workflows[id]) + '</option>'; }).join('');
208
+ state.view = data.view || state.view || 'recent';
209
+ var needs = state.view === 'needs';
170
210
  var rows = items.map(function (i) {
171
- return '<a class="ib-row" href="/inbox?case=' + encodeURIComponent(i.id) + '">' +
211
+ var waited = i.waitingSince ? Date.now() - new Date(i.waitingSince).getTime() : 0;
212
+ var side = needs
213
+ ? stateHtml(i) + '<span class="' + (waited > 3 * 86400000 ? 'ib-late' : '') + '">' + esc(waitedFor(waited)) + '</span>'
214
+ : outcomeHtml(i) + '<span>' + esc(ago(i.lastActivity)) + '</span>';
215
+ return '<a class="ib-row" href="' + caseHref(i.id) + '">' +
172
216
  '<span class="le-dot' + (i.waiting.length ? ' warn' : i.status === 'running' ? '' : ' idle') + '" aria-hidden="true"></span>' +
173
217
  '<span style="min-width:0"><div class="ib-row-title">' + esc(i.title) + '</div>' +
174
- '<div class="ib-row-meta">' + esc(i.workflowTitle) + DOT + esc(i.agent) + (i.lastBy ? DOT + 'last decided by ' + esc(i.lastBy) : '') + '</div></span>' +
175
- '<span class="ib-row-side">' + stateHtml(i) + '<span>' + esc(ago(i.startedAt)) + '</span></span></a>';
218
+ '<div class="ib-row-meta">' + esc(i.workflowTitle) + DOT + esc(i.agent) + DOT + 'started ' + esc(ago(i.startedAt)) + '</div></span>' +
219
+ '<span class="ib-row-side">' + side + '</span></a>';
176
220
  }).join('');
177
221
  page.innerHTML =
178
222
  '<div class="ib-bar">' +
179
- '<span class="ib-filter" role="group" aria-label="Show"><button type="button" data-open="0" aria-pressed="' + !state.open + '">All</button><button type="button" data-open="1" aria-pressed="' + state.open + '">Needs you (' + (data.open || 0) + ')</button></span>' +
223
+ '<span class="ib-filter" role="group" aria-label="Show"><button type="button" data-view="needs" aria-pressed="' + needs + '">Needs you (' + (data.open || 0) + ')</button><button type="button" data-view="recent" aria-pressed="' + !needs + '">Recent</button></span>' +
180
224
  '<select id="ibWorkflow" aria-label="Workflow"><option value="">All workflows</option>' + options + '</select>' +
181
225
  '<input id="ibSearch" type="search" placeholder="Search cases, inputs or people" value="' + esc(state.q) + '" aria-label="Search">' +
182
226
  '</div>' +
183
227
  (items.length ? '<div class="ib-list">' + rows + '</div>'
184
- : '<div class="ib-list"><p class="ib-empty">' + (state.open ? 'Nothing needs you right now. Questions and approvals from your agents land here.' : 'No cases yet. Each workflow run shows here.') + '</p></div>');
185
- var buttons = page.querySelectorAll('[data-open]');
186
- for (var b = 0; b < buttons.length; b++) buttons[b].addEventListener('click', function (ev) { state.open = ev.currentTarget.getAttribute('data-open') === '1'; refreshList(); });
228
+ : '<div class="ib-list"><p class="ib-empty">' + (needs ? 'Nothing needs you right now. Questions and approvals from your agents land here, however long ago they were asked.' : 'Nothing in the last 7 days. Every run shows here for a week: done automatically, decided by someone, or failed.') + '</p></div>') +
229
+ (needs ? '' : '<p class="hint ib-older">Showing the last 7 days.' + (fullAccess ? ' Older cases: <a class="ib-link" href="/audit?tab=cases">search all cases in Audit</a>.' : '') + '</p>');
230
+ var buttons = page.querySelectorAll('[data-view]');
231
+ for (var b = 0; b < buttons.length; b++) buttons[b].addEventListener('click', function (ev) { state.view = ev.currentTarget.getAttribute('data-view'); refreshList(); });
187
232
  page.querySelector('#ibWorkflow').addEventListener('change', function (ev) { state.workflow = ev.currentTarget.value; refreshList(); });
188
233
  var search = page.querySelector('#ibSearch');
189
234
  var timer = null;
@@ -324,7 +369,7 @@ ${renderMarkdownScript}
324
369
  var run = c.run;
325
370
  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' });
326
371
  page.innerHTML =
327
- '<a class="ib-back" href="' + pageUrl() + '">' + String.fromCharCode(8592) + ' Inbox</a>' +
372
+ '<a class="ib-back" href="' + esc(back) + '">' + String.fromCharCode(8592) + ' ' + backLabel() + '</a>' +
328
373
  '<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>' +
329
374
  c.pending.map(pendingHtml).join('') +
330
375
  (run && run.params ? '<div class="ib-card"><h3>Inputs</h3>' + kvHtml(run.params) + '</div>' : '') +
@@ -332,12 +377,78 @@ ${renderMarkdownScript}
332
377
  (run ? decidedHtml(run) : '') +
333
378
  (run && run.result ? '<div class="ib-card"><h3>Result</h3><div class="ib-md">' + renderMarkdownPreview(run.result) + '</div></div>' : '') +
334
379
  (run && run.error ? '<div class="ib-card"><h3>Failed</h3><p class="error">' + esc(run.error) + '</p></div>' : '') +
335
- exportHtml(c);
380
+ exportHtml(c) +
381
+ evalCaseHtml(c);
336
382
  var print = page.querySelector('[data-act="print"]');
337
383
  if (print) print.addEventListener('click', function () { window.print(); });
384
+ wireEvalCase(c);
338
385
  wireCase(c);
339
386
  }
340
387
 
388
+ // Save this run as one of its workflow's eval cases (owners, admins and
389
+ // editors): a test it must keep passing. Then the checklist items it
390
+ // suggests, from what people corrected in it, to add or not.
391
+ function evalCaseHtml(c) {
392
+ var run = c.run;
393
+ if (!fullAccess || !run || !run.workflow_id || run.status !== 'done') return '';
394
+ return '<div class="ib-card ib-eval"><h3>Eval case</h3>' +
395
+ '<p class="hint" style="margin:0">Save this run as a test its workflow must keep passing after every change to its brief. Runs where a person denied or changed something, or that went wrong, make the best tests.</p>' +
396
+ '<div class="ib-actions"><button type="button" class="ib-btn plain" data-act="save-case">Save as eval case</button><span class="hint ib-eval-result" role="status"></span></div>' +
397
+ '<div class="ib-suggest" hidden></div></div>';
398
+ }
399
+ function evalBase(c) {
400
+ return '/agents/' + encodeURIComponent(c.agent) + '/workflows/' + encodeURIComponent(c.workflowId) + '/evals';
401
+ }
402
+ function wireEvalCase(c) {
403
+ var btn = page.querySelector('[data-act="save-case"]');
404
+ if (!btn) return;
405
+ var result = page.querySelector('.ib-eval-result');
406
+ var suggest = page.querySelector('.ib-suggest');
407
+ // Already a case: say so.
408
+ fetch(evalBase(c), { headers: { accept: 'application/json' } })
409
+ .then(function (r) { return r.ok ? r.json() : null; })
410
+ .then(function (ev) {
411
+ if (ev && (ev.cases || []).some(function (k) { return k.fromRun === c.id; })) { btn.disabled = true; btn.textContent = 'Saved as an eval case'; }
412
+ }).catch(function () {});
413
+ btn.addEventListener('click', function () {
414
+ btn.disabled = true;
415
+ result.textContent = 'Saving' + ELLIPSIS;
416
+ fetch(evalBase(c) + '/cases', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ runId: c.id }) })
417
+ .then(function (r) { return r.json().then(function (b) { if (!r.ok) throw new Error(b.error || 'Could not save'); return b; }); })
418
+ .then(function (b) {
419
+ btn.textContent = 'Saved as an eval case';
420
+ result.innerHTML = 'Saved. <a class="ib-link" href="/agents/config?agent=' + encodeURIComponent(c.agent) + '&tab=workflows&workflow=' + encodeURIComponent(c.workflowId) + '&wtab=evidence">See its eval cases</a>';
421
+ showSuggestions(c, b.suggestions || [], b.criteria || []);
422
+ })
423
+ .catch(function (err) { btn.disabled = false; result.textContent = err.message; });
424
+ });
425
+ }
426
+ function showSuggestions(c, suggestions, criteria) {
427
+ var box = page.querySelector('.ib-suggest');
428
+ var have = criteria.map(function (k) { return k.text; });
429
+ var fresh = suggestions.filter(function (s) { return have.indexOf(s.text) === -1; });
430
+ if (!fresh.length) return;
431
+ box.hidden = false;
432
+ box.innerHTML = '<h4>Add to its checklist?</h4><p class="hint" style="margin:0">From what people corrected in this run. Each becomes a check every eval case is judged on.</p>' +
433
+ fresh.map(function (s, i) { return '<div class="ib-suggest-row"><span>' + esc(s.text) + '</span><button type="button" class="ib-btn plain" data-suggest="' + i + '">Add</button></div>'; }).join('');
434
+ box.addEventListener('click', function (ev) {
435
+ var b = ev.target.closest('[data-suggest]');
436
+ if (!b) return;
437
+ b.disabled = true;
438
+ var s = fresh[Number(b.getAttribute('data-suggest'))];
439
+ fetch(evalBase(c), { headers: { accept: 'application/json' } })
440
+ .then(function (r) { return r.json(); })
441
+ .then(function (ev2) {
442
+ var list = (ev2.criteria || []).map(function (k) { return { text: k.text, kind: k.kind, value: k.value }; });
443
+ list.push({ text: s.text, kind: s.kind });
444
+ return fetch(evalBase(c) + '/criteria', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ criteria: list }) });
445
+ })
446
+ .then(function (r) { return r.json().then(function (body) { if (!r.ok) throw new Error(body.error || 'Could not add it'); }); })
447
+ .then(function () { b.textContent = 'Added'; })
448
+ .catch(function (err) { b.disabled = false; b.textContent = err.message; });
449
+ });
450
+ }
451
+
341
452
  function send(card, path, body) {
342
453
  var result = card.querySelector('.ib-result');
343
454
  var buttons = card.querySelectorAll('button');
@@ -404,19 +515,25 @@ ${renderMarkdownScript}
404
515
  }
405
516
 
406
517
  function openCase() {
407
- var id = new URLSearchParams(location.search).get('case');
408
- return fetch('/inbox/cases/' + encodeURIComponent(id), { headers: { accept: 'application/json' } })
518
+ return fetch('/inbox/cases/' + encodeURIComponent(caseId), { headers: { accept: 'application/json' } })
409
519
  .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
410
- .then(renderCase)
411
- .catch(function (err) { page.innerHTML = '<a class="ib-back" href="/inbox">' + String.fromCharCode(8592) + ' Inbox</a><p class="error">Could not open this case: ' + esc(err.message) + '</p>'; });
520
+ .then(function (c) { document.title = c.title + ' ' + String.fromCharCode(183) + ' Case'; renderCase(c); })
521
+ .catch(function (err) { page.innerHTML = '<a class="ib-back" href="' + esc(back) + '">' + String.fromCharCode(8592) + ' ' + backLabel() + '</a><p class="error">Could not open this case: ' + esc(err.message) + '</p>'; });
412
522
  }
413
523
 
414
524
  function start() {
415
- if (new URLSearchParams(location.search).get('case')) openCase();
525
+ // A case's page is about that case, wherever it was opened from.
526
+ if (caseId) {
527
+ var head = document.querySelector('.le-head h1');
528
+ var lede = document.querySelector('.le-head p');
529
+ if (head) head.textContent = 'Case';
530
+ if (lede) lede.textContent = 'One run in full: what it was given, what the agent did step by step, who decided what, and what came of it.';
531
+ }
532
+ if (caseId) openCase();
416
533
  else refreshList();
417
534
  // The list keeps itself current while it's open.
418
535
  setInterval(function () {
419
- if (document.hidden || new URLSearchParams(location.search).get('case')) return;
536
+ if (document.hidden || caseId) return;
420
537
  if (document.activeElement && document.activeElement.id === 'ibSearch') return;
421
538
  refreshList();
422
539
  }, 15000);
@@ -86,7 +86,7 @@ export function workflowAuditReportHtml(audit, options) {
86
86
 
87
87
  <section>
88
88
  <div class="ar-check${v.ok ? '' : ' bad'}">${v.ok
89
- ? `Audit log verified: ${v.events.toLocaleString('en-US')} events check out${v.anchors ? `, and ${v.anchors} anchor${v.anchors === 1 ? '' : 's'} kept at ${esc(v.anchoredAt ?? 'loopengine.co')} match` : ''}.${v.last ? ` <span class="hint">Latest event #${v.last.id}, hash ${esc(v.last.hash)}</span>` : ''}`
89
+ ? `Audit log verified: ${v.events.toLocaleString('en-US')} events check out.${v.last ? ` <span class="hint">Latest event #${v.last.id}, hash ${esc(v.last.hash)}</span>` : ''}`
90
90
  : `Audit log broken at event #${v.broken?.id}: the record after it can't be relied on.`}</div>
91
91
  </section>
92
92
 
@@ -89,9 +89,7 @@ export interface WorkflowAudit {
89
89
  pricedRuns: number;
90
90
  };
91
91
  cases: AuditCase[];
92
- verification: ChainCheck & {
93
- anchoredAt?: string;
94
- };
92
+ verification: ChainCheck;
95
93
  /** The audit in sentences, most important first. */
96
94
  summary: string[];
97
95
  }
@@ -107,9 +105,7 @@ export interface WorkflowAuditInput {
107
105
  versions: Version[];
108
106
  /** Its settings changes (events of kind "change") in the period. */
109
107
  changes: AuditEvent[];
110
- verification: ChainCheck & {
111
- anchoredAt?: string;
112
- };
108
+ verification: ChainCheck;
113
109
  }
114
110
  /** Lines in `after` and not `before`, and the reverse (a line diff by
115
111
  * longest common subsequence, for briefs of a few hundred lines). */
@@ -131,7 +131,7 @@ export function buildWorkflowAudit(input) {
131
131
  const summary = [];
132
132
  const v = input.verification;
133
133
  summary.push(v.ok
134
- ? `The audit log checks out: ${plural(v.events, 'event')} verified${v.anchors ? `, matching ${plural(v.anchors, 'anchor')} kept at ${v.anchoredAt ?? 'loopengine.co'}` : ''}.`
134
+ ? `The audit log checks out: ${plural(v.events, 'event')} verified.`
135
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
136
  if (!total.runs)
137
137
  summary.push('It didn’t run in this period.');
@@ -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.5",
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",
@@ -45,8 +45,6 @@
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-anchor.js",
49
- "dist/core/audit-anchor.d.ts",
50
48
  "dist/core/audit-store.js",
51
49
  "dist/core/audit-store.d.ts",
52
50
  "dist/core/workspace-roles.js",
@@ -1,39 +0,0 @@
1
- export declare const AUDIT_ANCHORS_PATH = "/api/workspace/audit-anchors";
2
- export interface AnchorConfig {
3
- url: string;
4
- slug: string;
5
- secret: string;
6
- }
7
- /** Where anchors go and how to sign, or why they stay local. */
8
- export declare function anchorConfig(env?: NodeJS.ProcessEnv): AnchorConfig | {
9
- off: string;
10
- };
11
- export declare function signAnchorRequest(body: string, timestamp: number, secret: string): string;
12
- export type AnchorResult = {
13
- status: 'sent' | 'kept-here';
14
- eventId: number;
15
- } | {
16
- status: 'nothing-new';
17
- } | {
18
- status: 'failed';
19
- reason: string;
20
- };
21
- /** Anchors the latest event, unless it already is. Never throws. Off
22
- * Cloud, the anchor is noted only here. */
23
- export declare function anchorLatest(config?: AnchorConfig | {
24
- off: string;
25
- }, fetchImpl?: typeof fetch): Promise<AnchorResult>;
26
- /** The anchors kept at loopengine.co, or undefined off Cloud or when
27
- * they can't be fetched (with why). */
28
- export declare function fetchAnchors(config?: AnchorConfig | {
29
- off: string;
30
- }, fetchImpl?: typeof fetch): Promise<{
31
- anchors: {
32
- eventId: number;
33
- hash: string;
34
- }[];
35
- } | {
36
- unavailable: string;
37
- }>;
38
- /** Anchors now (a minute after start) and then daily. */
39
- export declare function startAuditAnchoring(log?: (message: string) => void): void;