loopengine 0.4.1 → 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.
- package/dist/core/audit-store.d.ts +23 -1
- package/dist/core/audit-store.js +112 -3
- package/dist/core/durable-approvals.d.ts +28 -2
- package/dist/core/durable-approvals.js +113 -3
- package/dist/core/messaging/threads.d.ts +3 -2
- package/dist/core/messaging/threads.js +85 -6
- package/dist/core/run-agent.js +2 -0
- package/dist/core/session-store.d.ts +35 -3
- package/dist/core/session-store.js +81 -3
- package/dist/core/usage.d.ts +11 -0
- package/dist/core/usage.js +51 -3
- package/dist/core/workflow-runs.d.ts +6 -0
- package/dist/core/workflow-runs.js +11 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/models.yaml +58 -0
- package/dist/web/agents-config-page.js +115 -2
- package/dist/web/change-log.d.ts +12 -0
- package/dist/web/change-log.js +86 -0
- package/dist/web/global-config.d.ts +20 -0
- package/dist/web/global-config.js +45 -3
- package/dist/web/inbox-admin.d.ts +34 -2
- package/dist/web/inbox-admin.js +45 -6
- package/dist/web/inbox-page.js +56 -5
- package/dist/web/workflow-health.d.ts +66 -0
- package/dist/web/workflow-health.js +76 -0
- package/package.json +1 -1
|
@@ -169,7 +169,45 @@ export function readModelsFile() {
|
|
|
169
169
|
const path = modelsFilePath();
|
|
170
170
|
const own = path === defaultModelsFile ? { models: {} } : parseModelsFile(path, process.env[MODELS_FILE_ENV]?.trim() || 'models.yaml');
|
|
171
171
|
const error = [shipped.error, own.error].filter(Boolean).join(' ');
|
|
172
|
-
|
|
172
|
+
const prices = {};
|
|
173
|
+
for (const from of [shipped.prices, own.prices]) {
|
|
174
|
+
for (const [provider, models] of Object.entries(from ?? {}))
|
|
175
|
+
prices[provider] = { ...prices[provider], ...models };
|
|
176
|
+
}
|
|
177
|
+
return { models: { ...shipped.models, ...own.models }, prices, ...(error ? { error } : {}) };
|
|
178
|
+
}
|
|
179
|
+
/** The price of a provider's model, or undefined when none is listed. */
|
|
180
|
+
export function modelPrice(provider, model) {
|
|
181
|
+
if (!provider || !model)
|
|
182
|
+
return undefined;
|
|
183
|
+
return readModelsFile().prices[provider]?.[model];
|
|
184
|
+
}
|
|
185
|
+
/** What a call cost in US dollars, or undefined without a price. */
|
|
186
|
+
export function callCost(provider, model, inputTokens, outputTokens) {
|
|
187
|
+
const price = modelPrice(provider, model);
|
|
188
|
+
return price ? (inputTokens * price.input + outputTokens * price.output) / 1_000_000 : undefined;
|
|
189
|
+
}
|
|
190
|
+
function parsePrices(value, name) {
|
|
191
|
+
if (value == null)
|
|
192
|
+
return { prices: {} };
|
|
193
|
+
const bad = { prices: {}, error: `${name}: 'prices' should map each provider to its models, each { input, output } in US dollars per million tokens.` };
|
|
194
|
+
if (typeof value !== 'object' || Array.isArray(value))
|
|
195
|
+
return bad;
|
|
196
|
+
const prices = {};
|
|
197
|
+
for (const [provider, models] of Object.entries(value)) {
|
|
198
|
+
if (models == null)
|
|
199
|
+
continue;
|
|
200
|
+
if (typeof models !== 'object' || Array.isArray(models))
|
|
201
|
+
return bad;
|
|
202
|
+
for (const [model, p] of Object.entries(models)) {
|
|
203
|
+
const r = p;
|
|
204
|
+
const num = (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
|
|
205
|
+
if (!r || typeof r !== 'object' || !num(r.input) || !num(r.output) || (r.cached_input !== undefined && !num(r.cached_input)))
|
|
206
|
+
return bad;
|
|
207
|
+
(prices[provider] ??= {})[model] = { input: r.input, output: r.output, ...(r.cached_input !== undefined ? { cachedInput: r.cached_input } : {}) };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return { prices };
|
|
173
211
|
}
|
|
174
212
|
function parseModelsFile(path, name) {
|
|
175
213
|
if (!existsSync(path))
|
|
@@ -185,8 +223,12 @@ function parseModelsFile(path, name) {
|
|
|
185
223
|
return { models: {} };
|
|
186
224
|
if (typeof data !== 'object' || Array.isArray(data))
|
|
187
225
|
return { models: {}, error: `${name} should map each provider to a list of models.` };
|
|
226
|
+
const { prices: priceSection, ...lists } = data;
|
|
227
|
+
const parsedPrices = parsePrices(priceSection, name);
|
|
228
|
+
if (parsedPrices.error)
|
|
229
|
+
return { models: {}, error: parsedPrices.error };
|
|
188
230
|
const models = {};
|
|
189
|
-
for (const [provider, list] of Object.entries(
|
|
231
|
+
for (const [provider, list] of Object.entries(lists)) {
|
|
190
232
|
if (!modelKeyEnvVar(provider)) {
|
|
191
233
|
return { models: {}, error: `${name}: unknown provider '${provider}'. Use one of ${KNOWN_PROVIDERS.map((p) => p.provider).join(', ')}.` };
|
|
192
234
|
}
|
|
@@ -198,7 +240,7 @@ function parseModelsFile(path, name) {
|
|
|
198
240
|
}
|
|
199
241
|
models[provider] = [...new Set(list.map((m) => m.trim()))];
|
|
200
242
|
}
|
|
201
|
-
return { models };
|
|
243
|
+
return { models, prices: parsedPrices.prices };
|
|
202
244
|
}
|
|
203
245
|
/**
|
|
204
246
|
* The models a provider offers, for the model dropdown in the New agent
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Message } from '../core/run-agent.js';
|
|
2
|
+
import type { UsageRow } from '../core/usage.js';
|
|
2
3
|
import type { WorkflowRun } from '../core/workflow-runs.js';
|
|
3
4
|
/** An open approval or question, as listAgentPending gives it. */
|
|
4
5
|
export interface InboxPending {
|
|
@@ -16,6 +17,10 @@ export interface InboxDeps {
|
|
|
16
17
|
pending(): Promise<InboxPending[]>;
|
|
17
18
|
history(run: WorkflowRun): Promise<Message[]>;
|
|
18
19
|
workflowTitle(agent: string, workflowId: string): string | undefined;
|
|
20
|
+
/** A run by id, including one too old for runs() (an archived case). */
|
|
21
|
+
run?(runId: string): Promise<WorkflowRun | undefined>;
|
|
22
|
+
/** The run's model calls, oldest first (core/usage.ts). */
|
|
23
|
+
usage?(run: WorkflowRun): UsageRow[];
|
|
19
24
|
}
|
|
20
25
|
/** One row in the list. */
|
|
21
26
|
export interface InboxItem {
|
|
@@ -47,7 +52,7 @@ export declare function listInbox(deps: InboxDeps, filter?: {
|
|
|
47
52
|
}[];
|
|
48
53
|
}>;
|
|
49
54
|
/** A step in a case's timeline. */
|
|
50
|
-
export type InboxStep = {
|
|
55
|
+
export type InboxStep = ({
|
|
51
56
|
kind: 'text';
|
|
52
57
|
text: string;
|
|
53
58
|
} | {
|
|
@@ -60,12 +65,37 @@ export type InboxStep = {
|
|
|
60
65
|
kind: 'question';
|
|
61
66
|
question: string;
|
|
62
67
|
answer?: string;
|
|
68
|
+
}) & {
|
|
69
|
+
/** On the first step of each model reply: that model call. */
|
|
70
|
+
call?: {
|
|
71
|
+
inputTokens: number;
|
|
72
|
+
outputTokens: number;
|
|
73
|
+
durationMs?: number;
|
|
74
|
+
model?: string;
|
|
75
|
+
costUsd?: number;
|
|
76
|
+
};
|
|
77
|
+
/** On the first tool or question step of a reply: the time from the
|
|
78
|
+
* end of that model call to the start of the next (the tools running,
|
|
79
|
+
* or a person deciding). */
|
|
80
|
+
waitMs?: number;
|
|
63
81
|
};
|
|
82
|
+
/** A case's totals, from its model calls. */
|
|
83
|
+
export interface InboxTotals {
|
|
84
|
+
calls: number;
|
|
85
|
+
inputTokens: number;
|
|
86
|
+
outputTokens: number;
|
|
87
|
+
/** Time spent in model calls. */
|
|
88
|
+
modelMs: number;
|
|
89
|
+
/** Start to finish (or to now, for one still open). */
|
|
90
|
+
elapsedMs?: number;
|
|
91
|
+
/** US dollars, when every call's model has a price. */
|
|
92
|
+
costUsd?: number;
|
|
93
|
+
}
|
|
64
94
|
/** What the agent did, in order: its words, the tools it used with what
|
|
65
95
|
* came back, and the questions it asked with their answers. The run's
|
|
66
96
|
* first message (its instructions) is left out; its inputs are shown
|
|
67
97
|
* apart. */
|
|
68
|
-
export declare function timelineOf(history: Message[]): InboxStep[];
|
|
98
|
+
export declare function timelineOf(history: Message[], usage?: UsageRow[]): InboxStep[];
|
|
69
99
|
export interface InboxCase {
|
|
70
100
|
id: string;
|
|
71
101
|
title: string;
|
|
@@ -79,5 +109,7 @@ export interface InboxCase {
|
|
|
79
109
|
options?: string[];
|
|
80
110
|
})[];
|
|
81
111
|
steps: InboxStep[];
|
|
112
|
+
totals?: InboxTotals;
|
|
82
113
|
}
|
|
114
|
+
export declare function totalsOf(run: WorkflowRun, usage: UsageRow[]): InboxTotals | undefined;
|
|
83
115
|
export declare function getInboxCase(deps: InboxDeps, id: string): Promise<InboxCase | undefined>;
|
package/dist/web/inbox-admin.js
CHANGED
|
@@ -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
|
-
|
|
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
|
}
|
package/dist/web/inbox-page.js
CHANGED
|
@@ -60,6 +60,16 @@ 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; }
|
|
65
75
|
.ib-reason { color: var(--ink-muted); margin: 2px 0 0 12px; }
|
|
@@ -230,11 +240,30 @@ ${renderMarkdownScript}
|
|
|
230
240
|
'</div>';
|
|
231
241
|
}
|
|
232
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
|
+
|
|
233
262
|
function stepHtml(s) {
|
|
234
|
-
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>';
|
|
235
|
-
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>' +
|
|
236
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>';
|
|
237
|
-
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>' +
|
|
238
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>' +
|
|
239
268
|
(s.result != null ? '<pre class="ib-pre" style="margin-top:6px">' + esc(s.result) + '</pre>' : '') + '</details></li>';
|
|
240
269
|
}
|
|
@@ -272,6 +301,25 @@ ${renderMarkdownScript}
|
|
|
272
301
|
return wf + DOT + '<a class="ib-link" href="' + agentUrl + '">' + esc(c.agent) + '</a>';
|
|
273
302
|
}
|
|
274
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
|
+
|
|
275
323
|
function renderCase(c) {
|
|
276
324
|
var run = c.run;
|
|
277
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' });
|
|
@@ -280,10 +328,13 @@ ${renderMarkdownScript}
|
|
|
280
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>' +
|
|
281
329
|
c.pending.map(pendingHtml).join('') +
|
|
282
330
|
(run && run.params ? '<div class="ib-card"><h3>Inputs</h3>' + kvHtml(run.params) + '</div>' : '') +
|
|
283
|
-
(c.steps.length ? '<div class="ib-card"><h3>What the agent did</h3
|
|
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>' : '') +
|
|
284
332
|
(run ? decidedHtml(run) : '') +
|
|
285
333
|
(run && run.result ? '<div class="ib-card"><h3>Result</h3><div class="ib-md">' + renderMarkdownPreview(run.result) + '</div></div>' : '') +
|
|
286
|
-
(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(); });
|
|
287
338
|
wireCase(c);
|
|
288
339
|
}
|
|
289
340
|
|
|
@@ -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
|
+
}
|