loopengine 0.4.14 → 0.5.0

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.
Files changed (44) hide show
  1. package/dist/core/audit-store.d.ts +71 -8
  2. package/dist/core/audit-store.js +206 -12
  3. package/dist/core/input-schema.d.ts +47 -0
  4. package/dist/core/input-schema.js +180 -0
  5. package/dist/core/output-schema.d.ts +30 -0
  6. package/dist/core/output-schema.js +105 -0
  7. package/dist/core/run-agent.js +35 -2
  8. package/dist/core/scheduler.d.ts +6 -0
  9. package/dist/core/scheduler.js +22 -16
  10. package/dist/core/trace.d.ts +34 -0
  11. package/dist/core/trace.js +149 -0
  12. package/dist/core/workflow-runs.d.ts +30 -5
  13. package/dist/core/workflow-runs.js +62 -12
  14. package/dist/core/workflow-triggers.d.ts +8 -1
  15. package/dist/core/workflow-triggers.js +13 -0
  16. package/dist/core/workflows.d.ts +17 -1
  17. package/dist/core/workflows.js +72 -9
  18. package/dist/index.d.ts +6 -2
  19. package/dist/index.js +6 -2
  20. package/dist/web/agents-config-page.js +372 -67
  21. package/dist/web/audit-admin.d.ts +2 -2
  22. package/dist/web/audit-admin.js +5 -3
  23. package/dist/web/audit-page.js +7 -5
  24. package/dist/web/change-log.js +4 -2
  25. package/dist/web/console-shell.js +1 -1
  26. package/dist/web/decide-page.js +1 -1
  27. package/dist/web/goals-admin.d.ts +8 -5
  28. package/dist/web/goals-admin.js +25 -5
  29. package/dist/web/goals-page.js +8 -2
  30. package/dist/web/inbox-page.js +143 -1
  31. package/dist/web/run-trace.d.ts +114 -0
  32. package/dist/web/run-trace.js +79 -0
  33. package/dist/web/workflow-admin.d.ts +12 -3
  34. package/dist/web/workflow-admin.js +42 -7
  35. package/dist/web/workflow-audit-report.js +5 -5
  36. package/dist/web/workflow-audit.d.ts +3 -3
  37. package/dist/web/workflow-audit.js +12 -11
  38. package/dist/web/workflow-drafts.d.ts +75 -0
  39. package/dist/web/workflow-drafts.js +112 -0
  40. package/dist/web/workflow-evidence.d.ts +17 -4
  41. package/dist/web/workflow-evidence.js +22 -6
  42. package/dist/web/workflow-health.d.ts +2 -2
  43. package/dist/web/workflow-health.js +7 -1
  44. package/package.json +9 -1
@@ -1,5 +1,5 @@
1
1
  import type { AuditEvent } from '../core/audit-store.js';
2
- import type { WorkflowRun } from '../core/workflow-runs.js';
2
+ import { type WorkflowRun } from '../core/workflow-runs.js';
3
3
  /** An event in words, as the page and the CSV file show it: what
4
4
  * happened, and any detail (a reason, an answer, a note). */
5
5
  export declare function eventText(e: AuditEvent): {
@@ -19,7 +19,7 @@ export interface AuditCaseRow {
19
19
  status: WorkflowRun['status'];
20
20
  startedAt: string;
21
21
  finishedAt?: string;
22
- briefVersion?: number;
22
+ workflowVersion?: number;
23
23
  /** Everyone who decided or answered something in it. */
24
24
  people: string[];
25
25
  /** The start of its result, or its error. */
@@ -1,4 +1,5 @@
1
1
  import { changesSummary } from './change-log.js';
2
+ import { workflowVersionOf } from '../core/workflow-runs.js';
2
3
  const short = (text, max) => {
3
4
  const flat = text.replace(/\s+/g, ' ').trim();
4
5
  return flat.length > max ? flat.slice(0, max - 1) + '…' : flat;
@@ -9,9 +10,10 @@ export function eventText(e) {
9
10
  const d = e.data;
10
11
  const str = (v) => (typeof v === 'string' ? v : '');
11
12
  if (e.kind === 'change') {
12
- const brief = d.brief;
13
+ // The workflow's version before and after ("brief" on older events).
14
+ const version = (d.version ?? d.brief);
13
15
  const summary = Array.isArray(d.changes) ? changesSummary(d.changes) : '';
14
- return { what: str(d.label) || 'Changed a setting', detail: [brief?.from && brief.to ? `brief v${brief.from} → v${brief.to}` : '', summary].filter(Boolean).join('; ') };
16
+ return { what: str(d.label) || 'Changed a setting', detail: [version?.from && version.to ? `workflow v${version.from} → v${version.to}` : '', summary].filter(Boolean).join('; ') };
15
17
  }
16
18
  if (e.kind === 'decision') {
17
19
  const what = `${d.approved ? (d.edited ? 'Approved as changed' : 'Approved') : 'Denied'} ${str(d.tool)}`;
@@ -49,7 +51,7 @@ export function caseRow(run, workflowTitle, evalCase = false) {
49
51
  status: run.status,
50
52
  startedAt: run.started_at,
51
53
  ...(run.finished_at ? { finishedAt: run.finished_at } : {}),
52
- ...(run.versions?.brief ? { briefVersion: run.versions.brief } : {}),
54
+ ...(workflowVersionOf(run) ? { workflowVersion: workflowVersionOf(run) } : {}),
53
55
  people,
54
56
  outcome: short(run.status === 'error' ? run.error ?? '' : run.result ?? '', 200),
55
57
  ...(evalCase ? { evalCase: true } : {}),
@@ -201,7 +201,7 @@ ${consoleShellScript}
201
201
  function eventLink(e) {
202
202
  var d = e.data || {};
203
203
  if (e.run_id) return { href: '/cases/' + encodeURIComponent(e.run_id) + '?back=' + encodeURIComponent(location.pathname + location.search), text: 'Case' };
204
- if (e.workflow_id) return { href: workflowHref(e.agent, e.workflow_id, /brief version/i.test(d.label || '') || /Edited the workflow/.test(d.label || '') ? 'brief' : 'activity'), text: 'Workflow' };
204
+ if (e.workflow_id) return { href: workflowHref(e.agent, e.workflow_id, /(brief|workflow) version/i.test(d.label || '') || /Edited the workflow|Published the workflow/.test(d.label || '') ? 'brief' : 'activity'), text: 'Workflow' };
205
205
  if (e.agent) return { href: '/agents/config?agent=' + encodeURIComponent(e.agent), text: 'Agent' };
206
206
  var path = String(d.path || '');
207
207
  if (path.indexOf('/config/models') === 0) return { href: '/config?section=models', text: 'Models' };
@@ -223,20 +223,22 @@ ${consoleShellScript}
223
223
  // lines added (+) and removed (−), a few shown and the rest folded.
224
224
  function changeDetailsHtml(d) {
225
225
  var list = d.changes || [];
226
- if (!list.length && !d.brief) return '';
226
+ var version = d.version || d.brief;
227
+ if (!list.length && !version) return '';
227
228
  var MINUS = String.fromCharCode(8722);
228
229
  var lineHtml = function (sign, cls, l) { return '<div class="' + cls + '">' + sign + ' ' + esc(l) + '</div>'; };
229
230
  var rows = list.map(function (c) {
230
231
  if (c.added || c.removed) {
231
232
  var lines = (c.removed || []).map(function (l) { return lineHtml(MINUS, 'chg-del', l); }).concat((c.added || []).map(function (l) { return lineHtml('+', 'chg-ins', l); }));
232
- var head = '<strong>' + esc(c.field) + '</strong>' + (c.field === 'instructions' && d.brief ? ' <span class="chg-note">brief v' + d.brief.from + ' ' + String.fromCharCode(8594) + ' v' + d.brief.to + '</span>' : '');
233
+ var head = '<strong>' + esc(c.field) + '</strong>';
233
234
  var shown = lines.slice(0, 6).join('');
234
235
  var more = lines.length > 6 ? '<details><summary>' + (lines.length - 6) + ' more line' + (lines.length - 6 === 1 ? '' : 's') + '</summary>' + lines.slice(6).join('') + '</details>' : '';
235
236
  return '<div class="chg-field">' + head + '<div class="chg-lines">' + (shown || '<div class="chg-note">Only spacing changed.</div>') + more + '</div></div>';
236
237
  }
237
238
  return '<div class="chg-field"><strong>' + esc(c.field) + '</strong>: <del>' + esc(c.from) + '</del> ' + String.fromCharCode(8594) + ' <ins>' + esc(c.to) + '</ins></div>';
238
239
  }).join('');
239
- if (!rows && d.brief) rows = '<div class="chg-field">brief v' + d.brief.from + ' ' + String.fromCharCode(8594) + ' v' + d.brief.to + '</div>';
240
+ // The workflow's version before and after ("brief" on older changes).
241
+ if (version) rows = '<div class="chg-note">Workflow v' + version.from + ' ' + String.fromCharCode(8594) + ' v' + version.to + '</div>' + rows;
240
242
  return '<div class="chg">' + rows + '</div>';
241
243
  }
242
244
 
@@ -258,7 +260,7 @@ ${consoleShellScript}
258
260
  return '<div class="au-row au-case"><span class="au-state ' + pill[0] + '">' + pill[1] + '</span>' +
259
261
  '<span class="au-what"><strong>' + esc(c.workflowTitle) + (c.inputs ? DOT + esc(c.inputs) : '') + '</strong>' +
260
262
  (c.outcome ? '<span class="au-detail">' + esc(c.outcome) + '</span>' : '') +
261
- '<span class="au-where">' + esc(when(c.startedAt)) + DOT + esc(agentLabel(c.agent)) + (c.briefVersion ? DOT + 'brief v' + c.briefVersion : '') + (c.people.length ? DOT + 'decided by ' + esc(c.people.join(', ')) : '') + (c.evalCase ? DOT + '<span class="au-evalcase">eval case</span>' : '') + '</span></span>' +
263
+ '<span class="au-where">' + esc(when(c.startedAt)) + DOT + esc(agentLabel(c.agent)) + (c.workflowVersion ? DOT + 'workflow v' + c.workflowVersion : '') + (c.people.length ? DOT + 'decided by ' + esc(c.people.join(', ')) : '') + (c.evalCase ? DOT + '<span class="au-evalcase">eval case</span>' : '') + '</span></span>' +
262
264
  '<a class="au-open" href="/cases/' + encodeURIComponent(c.id) + '?back=' + encodeURIComponent(location.pathname + location.search) + '">Open ' + String.fromCharCode(8594) + '</a></div>';
263
265
  }
264
266
 
@@ -9,9 +9,10 @@
9
9
  // deciding, feedback) isn't: decisions and feedback are events of their
10
10
  // own. The request's body is kept with anything secret blanked, and the
11
11
  // brief's own before and after are its versions.
12
- // Doing, not changing.
12
+ // Doing, not changing. A workflow's draft isn't live until it's published.
13
13
  const NOT_CHANGES = [
14
14
  /^\/agents\/[^/]+\/messages(\/stream)?$/,
15
+ /^\/agents\/[^/]+\/workflows\/[^/]+\/draft(\/.*)?$/,
15
16
  /\/(feedback|run|preview|test|evals\/run|criteria\/draft|telegram-webhook|slack-channels|search|install-deps|refresh)$/,
16
17
  ];
17
18
  const LABELS = [
@@ -19,7 +20,8 @@ const LABELS = [
19
20
  [/^\/agents\/[^/]+$/, (method) => (method === 'DELETE' ? 'Removed the agent' : 'Changed the agent')],
20
21
  [/^\/agents\/[^/]+\/workflows$/, 'Created a workflow'],
21
22
  [/^\/agents\/[^/]+\/workflows\/[^/]+$/, (method) => (method === 'DELETE' ? 'Removed the workflow' : 'Edited the workflow')],
22
- [/^\/agents\/[^/]+\/workflows\/[^/]+\/versions\/(\d+)\/restore$/, (_method, m) => `Restored brief version ${m[1]}`],
23
+ [/^\/agents\/[^/]+\/workflows\/[^/]+\/publish$/, 'Published the workflow'],
24
+ [/^\/agents\/[^/]+\/workflows\/[^/]+\/versions\/(\d+)\/restore$/, (_method, m) => `Restored workflow version ${m[1]}`],
23
25
  [/^\/agents\/[^/]+\/workflows\/[^/]+\/messages$/, 'Changed where messages go'],
24
26
  [/^\/agents\/[^/]+\/workflows\/[^/]+\/triggers/, 'Changed webhook triggers'],
25
27
  [/^\/agents\/[^/]+\/workflows\/[^/]+\/evals\/criteria/, 'Changed the success criteria'],
@@ -99,7 +99,7 @@ export const consoleShellScript = `<script>
99
99
  // ability on the Apps tab (id 'abilities', so older links still work).
100
100
  // ?tab=tools and ?tab=skills still open Advanced.
101
101
  var TABS = [
102
- ['overview', 'Overview'], ['workflows', 'Workflows'], ['abilities', 'Apps'], ['messaging', 'Messaging'],
102
+ ['overview', 'Overview'], ['workflows', 'Workflows'], ['abilities', 'Apps'], ['messaging', 'Messaging Apps'],
103
103
  ['schedules', 'Schedules'], ['chat', 'Chat'], ['actauth', 'Permissions'], ['env', 'Environment'], ['advanced', 'Advanced']
104
104
  ];
105
105
 
@@ -53,7 +53,7 @@ ${script}
53
53
  }
54
54
  /** A link that's malformed, tampered with, or past its expiry. */
55
55
  export function renderDecideInvalidPage() {
56
- return shell('Link not valid', '<h1>This link isn&#39;t valid</h1><p class="muted">It may have expired or been copied incompletely. Ask for a new one, or decide from the agent&#39;s Messaging tab.</p>');
56
+ return shell('Link not valid', '<h1>This link isn&#39;t valid</h1><p class="muted">It may have expired or been copied incompletely. Ask for a new one, or decide from the agent&#39;s Messaging Apps tab.</p>');
57
57
  }
58
58
  /** A valid link whose decision has already been made. */
59
59
  export function renderDecideGonePage() {
@@ -38,7 +38,9 @@ export interface ChainStep {
38
38
  workflowId: string;
39
39
  };
40
40
  /** Each input of the next run: "result" (the run it follows ended
41
- * with), or "input:<name>" (one of that run's inputs). */
41
+ * with), "result.<path>" (one field of its JSON output, when its
42
+ * workflow has an output schema), or "input:<name>" (one of that run's
43
+ * inputs). */
42
44
  with: Record<string, string>;
43
45
  }
44
46
  /** Runs a chain may start one after another, after the first. */
@@ -196,6 +198,7 @@ export interface GoalsDeps {
196
198
  parameters: Record<string, {
197
199
  required: boolean;
198
200
  }>;
201
+ outputSchema?: Record<string, unknown>;
199
202
  } | undefined;
200
203
  }
201
204
  /** A goal as saved before jobs (its `workflows`, a built one's `built`
@@ -291,16 +294,16 @@ export declare function editJob(deps: GoalsDeps, id: string, jobId: string, body
291
294
  }): Goal;
292
295
  /** Whether a finished run's result meets a step's condition. */
293
296
  export declare function chainConditionMet(when: ChainStep['when'], result: string): boolean;
294
- /** The runs to start after a workflow run finished: every step, in any
295
- * active job's chain, that follows its workflow and whose condition its
296
- * result meets, with the next run's inputs filled in. None past
297
- * MAX_CHAIN_DEPTH. */
297
+ /** A field of a run's JSON output, as text: a string as it is, anything
298
+ * else as JSON; empty when the output doesn't have it. */
299
+ export declare function resultField(output: unknown, path: string): string;
298
300
  export declare function chainedRuns(deps: GoalsDeps, run: {
299
301
  run_id: string;
300
302
  agent: string;
301
303
  workflow_id: string;
302
304
  status: string;
303
305
  result?: string;
306
+ output?: unknown;
304
307
  params?: Record<string, string>;
305
308
  chain_depth?: number;
306
309
  }): {
@@ -435,9 +435,15 @@ function groupChain(deps, job, steps) {
435
435
  continue;
436
436
  const mapping = {};
437
437
  const required = Object.entries(target.parameters).filter(([, spec]) => spec.required).map(([p]) => p);
438
- for (const p of Object.keys(target.parameters))
439
- if (source?.parameters[p])
438
+ // An input named like a field of the step before's JSON output takes
439
+ // that field; else one named like its input takes that input.
440
+ const props = source?.outputSchema?.type === 'object' && source.outputSchema.properties && typeof source.outputSchema.properties === 'object' ? Object.keys(source.outputSchema.properties) : [];
441
+ for (const p of Object.keys(target.parameters)) {
442
+ if (props.includes(p))
443
+ mapping[p] = `result.${p}`;
444
+ else if (source?.parameters[p])
440
445
  mapping[p] = `input:${p}`;
446
+ }
441
447
  const unfilled = required.filter((p) => !mapping[p]);
442
448
  if (unfilled.length === 1)
443
449
  mapping[unfilled[0]] = 'result';
@@ -561,8 +567,8 @@ export function checkChain(deps, job, raw) {
561
567
  continue;
562
568
  if (!target.parameters[param])
563
569
  throw new GoalError(`${n}: ${target.title} has no input "${param}".`);
564
- if (from !== 'result' && !(from.startsWith('input:') && source.parameters[from.slice(6)]))
565
- throw new GoalError(`${n}: "${param}" comes from "result" or "input:<one of ${source.title}'s inputs>".`);
570
+ if (from !== 'result' && !RESULT_FIELD.test(from) && !(from.startsWith('input:') && source.parameters[from.slice(6)]))
571
+ throw new GoalError(`${n}: "${param}" comes from "result", "result.<field>" (a field of its JSON output) or "input:<one of ${source.title}'s inputs>".`);
566
572
  mapping[param] = from;
567
573
  }
568
574
  const missing = Object.entries(target.parameters).filter(([p, spec]) => spec.required && !mapping[p]).map(([p]) => p);
@@ -629,6 +635,20 @@ export function chainConditionMet(when, result) {
629
635
  * active job's chain, that follows its workflow and whose condition its
630
636
  * result meets, with the next run's inputs filled in. None past
631
637
  * MAX_CHAIN_DEPTH. */
638
+ /** "result.<path>": one field of a run's JSON output (its workflow's output
639
+ * schema), by a dot path: "result.lead.email", "result.items.0.id". */
640
+ const RESULT_FIELD = /^result\.[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/;
641
+ /** A field of a run's JSON output, as text: a string as it is, anything
642
+ * else as JSON; empty when the output doesn't have it. */
643
+ export function resultField(output, path) {
644
+ let at = output;
645
+ for (const key of path.split('.')) {
646
+ if (at === null || typeof at !== 'object')
647
+ return '';
648
+ at = at[key];
649
+ }
650
+ return at === undefined || at === null ? '' : typeof at === 'string' ? at : JSON.stringify(at);
651
+ }
632
652
  export function chainedRuns(deps, run) {
633
653
  if (run.status !== 'done' || !run.workflow_id)
634
654
  return [];
@@ -641,7 +661,7 @@ export function chainedRuns(deps, run) {
641
661
  .filter((st) => sameRef(st.after, from) && chainConditionMet(st.when, result))
642
662
  .map((st) => ({
643
663
  goal: goal.id, job: job.id, step: st.id, agent: st.run.agent, workflowId: st.run.workflowId, depth,
644
- params: Object.fromEntries(Object.entries(st.with).map(([param, src]) => [param, src === 'result' ? result : run.params?.[src.slice(6)] ?? ''])),
664
+ params: Object.fromEntries(Object.entries(st.with).map(([param, src]) => [param, src === 'result' ? result : RESULT_FIELD.test(src) ? resultField(run.output, src.slice(7)) : run.params?.[src.slice(6)] ?? ''])),
645
665
  }))));
646
666
  }
647
667
  /** A goal as its page shows it: its workflows and groups. One-off jobs
@@ -667,7 +667,8 @@ ${consoleShellScript}
667
667
  });
668
668
  }
669
669
 
670
- // The next run's inputs: each from the result, or one of the first run's
670
+ // The next run's inputs: each from the result, one field of it (when the
671
+ // first run's workflow has an output schema), or one of the first run's
671
672
  // inputs (shown when the step's "run" changes).
672
673
  function stepInputs(card) {
673
674
  var box = card.querySelector('[data-step-inputs]');
@@ -679,9 +680,14 @@ ${consoleShellScript}
679
680
  if (!target) { box.innerHTML = '<p class="hint" style="margin:0">Loading its inputs' + ELLIPSIS + '</p>'; return; }
680
681
  var params = Object.keys(target.parameters || {});
681
682
  if (!params.length) { box.innerHTML = '<p class="hint" style="margin:0">' + esc(target.title) + ' takes no inputs.</p>'; return; }
683
+ // With an output schema, each of its result's top-level fields too.
684
+ var schema = source && source.outputSchema;
685
+ var fields = schema && schema.type === 'object' && schema.properties ? Object.keys(schema.properties) : [];
682
686
  var choices = function (p) {
683
687
  var srcParams = source ? Object.keys(source.parameters || {}) : [];
684
- return '<option value=""' + (target.parameters[p].required ? ' disabled' : '') + '>(leave empty)</option><option value="result"' + (target.parameters[p].required ? ' selected' : '') + '>the result of the run before</option>' +
688
+ var same = fields.indexOf(p) !== -1;
689
+ return '<option value=""' + (target.parameters[p].required ? ' disabled' : '') + '>(leave empty)</option><option value="result"' + (target.parameters[p].required && !same ? ' selected' : '') + '>the result of the run before</option>' +
690
+ fields.map(function (f) { return '<option value="result.' + esc(f) + '"' + (f === p ? ' selected' : '') + '>its result' + String.fromCharCode(8217) + 's ' + esc(f) + '</option>'; }).join('') +
685
691
  srcParams.map(function (sp) { return '<option value="input:' + esc(sp) + '"' + (sp === p && !target.parameters[p].required ? ' selected' : '') + '>its input ' + esc(sp) + '</option>'; }).join('');
686
692
  };
687
693
  box.innerHTML = params.map(function (p) { return '<div class="gl-row"><span class="hint"><code>' + esc(p) + '</code>' + (target.parameters[p].required ? '' : ' (optional)') + ' from</span><select class="gl-select" data-input="' + esc(p) + '">' + choices(p) + '</select></div>'; }).join('');
@@ -50,6 +50,21 @@ export const inboxPageHtml = `<!doctype html>
50
50
  .ib-kv { display: grid; grid-template-columns: minmax(110px, max-content) 1fr; gap: 6px 14px; font-size: 13.5px; }
51
51
  .ib-kv dt { color: var(--ink-muted); font-family: var(--font-mono); font-size: 12.5px; padding-top: 1px; }
52
52
  .ib-kv dd { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
53
+ .ib-trace-sum { display: grid; grid-template-columns: max-content 1fr; gap: 4px 14px; margin: 0; font-size: 13px; padding: 10px 12px; background: var(--surface); border-radius: 10px; }
54
+ .ib-trace-sum dt { color: var(--ink-muted); }
55
+ .ib-trace-sum dd { margin: 0; overflow-wrap: anywhere; }
56
+ .ib-trace-span.event { background: var(--surface); }
57
+ .ib-trace-list { list-style: none; margin: 10px 0 0; padding: 0; display: grid; gap: 8px; }
58
+ .ib-trace-span { border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; display: grid; gap: 6px; }
59
+ .ib-trace-span.err { border-color: var(--bad); }
60
+ .ib-trace-head { display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: baseline; }
61
+ .ib-trace-kind { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; color: var(--accent-ink); }
62
+ .ib-trace-span.tool .ib-trace-kind { color: var(--ink-muted); }
63
+ .ib-trace-meta { font-size: 12.5px; color: var(--ink-muted); }
64
+ .ib-trace-span details > summary { cursor: pointer; font-size: 13px; color: var(--ink-muted); }
65
+ .ib-trace-span details .ib-pre { margin-top: 6px; }
66
+ .ib-trace-tools { display: flex; flex-wrap: wrap; gap: 4px; }
67
+ .ib-trace-tools code { font-size: 12px; background: var(--surface); padding: 1px 6px; border-radius: 6px; }
53
68
  .ib-pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13px; background: var(--surface); padding: 10px 12px; border-radius: 8px; max-height: 360px; overflow: auto; }
54
69
  .ib-question { margin: 0; font-size: 14.5px; }
55
70
  .ib-card textarea { width: 100%; box-sizing: border-box; min-height: 80px; font: inherit; font-size: 14px; padding: 10px 12px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); color: var(--ink); resize: vertical; }
@@ -375,16 +390,143 @@ ${renderMarkdownScript}
375
390
  (run && run.params ? '<div class="ib-card"><h3>Inputs</h3>' + kvHtml(run.params) + '</div>' : '') +
376
391
  (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>' : '') +
377
392
  (run ? decidedHtml(run) : '') +
378
- (run && run.result ? '<div class="ib-card"><h3>Result</h3><div class="ib-md">' + renderMarkdownPreview(run.result) + '</div></div>' : '') +
393
+ // With an output schema, the result is its JSON, shown once.
394
+ (run && run.output !== undefined ? '<div class="ib-card"><h3>Result <span class="hint">(JSON, matches its output schema' + (run.output_retries ? ', after ' + run.output_retries + (run.output_retries === 1 ? ' retry' : ' retries') : '') + ')</span></h3><pre class="ib-pre">' + esc(JSON.stringify(run.output, null, 2)) + '</pre></div>'
395
+ : run && run.result ? '<div class="ib-card"><h3>Result</h3><div class="ib-md">' + renderMarkdownPreview(run.result) + '</div></div>' : '') +
396
+ (run && run.status === 'error' && run.output_errors && run.output_errors.length ? '<div class="ib-card"><h3>Didn' + String.fromCharCode(8217) + 't match its output schema</h3><ul class="ib-schema-errors">' + run.output_errors.map(function (e) { return '<li>' + esc(e) + '</li>'; }).join('') + '</ul></div>' : '') +
379
397
  (run && run.error ? '<div class="ib-card"><h3>Failed</h3><p class="error">' + esc(run.error) + '</p></div>' : '') +
398
+ traceHtml(c) +
380
399
  exportHtml(c) +
381
400
  evalCaseHtml(c);
382
401
  var print = page.querySelector('[data-act="print"]');
383
402
  if (print) print.addEventListener('click', function () { window.print(); });
384
403
  wireEvalCase(c);
404
+ wireTrace(c);
385
405
  wireCase(c);
386
406
  }
387
407
 
408
+ // The run's trace (owners, admins and editors): the prompt it ran with,
409
+ // each model call (what was new in its input, and its output) and each
410
+ // tool call (input, output, time), word for word. Loaded when opened.
411
+ function traceHtml(c) {
412
+ if (!fullAccess || !c.run) return '';
413
+ return '<div class="ib-card ib-trace"><h3>Trace</h3>' +
414
+ '<p class="hint" style="margin:0">Every step word for word: the prompt the agent ran with, what each model call was given and answered, and what each tool was sent and returned.</p>' +
415
+ '<div class="ib-actions"><button type="button" class="ib-btn plain" data-act="trace">Show trace</button><span class="hint ib-trace-status" role="status"></span></div>' +
416
+ '<ol class="ib-trace-list" hidden></ol></div>';
417
+ }
418
+ var NL = String.fromCharCode(10);
419
+ // A traced value as text: a cut one says how much was left out.
420
+ function traceText(v) {
421
+ if (v == null) return '';
422
+ if (typeof v === 'object' && !Array.isArray(v) && v.truncated) return String(v.start) + NL + NL + '(cut: ' + count(v.chars) + ' characters in all)';
423
+ if (typeof v === 'string') return v;
424
+ if (Array.isArray(v)) return v.map(blockText).join(NL + NL);
425
+ return JSON.stringify(v, null, 2);
426
+ }
427
+ function blockText(b) {
428
+ if (b && typeof b === 'object' && 'role' in b) return b.role.toUpperCase() + NL + traceText(b.content);
429
+ if (!b || typeof b !== 'object') return String(b);
430
+ if (b.type === 'text') return b.text;
431
+ if (b.type === 'tool_use') return 'Calls ' + b.name + ' ' + JSON.stringify(b.input, null, 2);
432
+ if (b.type === 'tool_result') return 'Result for ' + b.tool_use_id + (b.is_error ? ' (error)' : '') + ':' + NL + traceText(b.content);
433
+ return JSON.stringify(b, null, 2);
434
+ }
435
+ function tracePart(label, v, open) {
436
+ var text = traceText(v);
437
+ if (!text) return '';
438
+ return '<details' + (open ? ' open' : '') + '><summary>' + esc(label) + '</summary><pre class="ib-pre">' + esc(text) + '</pre></details>';
439
+ }
440
+ // The trace's own fields at the top: which run of which version, the
441
+ // model, how long, what it cost, and the feedback on it.
442
+ function traceSummaryHtml(t) {
443
+ var rows = [
444
+ ['Execution id', t.execution_id],
445
+ ['Workflow', t.workflow_id + (t.workflow_version_id ? ' (' + t.workflow_version_id + ')' : '')],
446
+ ['Model', t.model ? (t.model.provider ? t.model.provider + ' ' : '') + t.model.model : ''],
447
+ ['Status', t.status],
448
+ ['Duration', t.duration_ms != null ? duration(t.duration_ms) : ''],
449
+ ['Cost', (t.cost.usd != null ? dollars(t.cost.usd) + DOT : '') + t.cost.model_calls + (t.cost.model_calls === 1 ? ' model call' : ' model calls') + DOT + count(t.cost.input_tokens) + ' in ' + String.fromCharCode(183) + ' ' + count(t.cost.output_tokens) + ' out tokens'],
450
+ ['Tool calls', String(t.tool_calls.length)],
451
+ ['Feedback', t.feedback ? [t.feedback.verdict, t.feedback.edit ? t.feedback.edit + ' edits' : '', t.feedback.note].filter(Boolean).join(DOT) || 'reported' : 'none yet'],
452
+ ['Error', t.error || ''],
453
+ ].filter(function (r) { return r[1]; });
454
+ return '<dl class="ib-trace-sum">' + rows.map(function (r) { return '<dt>' + esc(r[0]) + '</dt><dd>' + esc(r[1]) + '</dd>'; }).join('') + '</dl>';
455
+ }
456
+ function traceStepHtml(st, i, steps) {
457
+ var meta = [];
458
+ if (st.duration_ms != null) meta.push(duration(st.duration_ms));
459
+ var head = function (kind, name) {
460
+ return '<div class="ib-trace-head"><span class="ib-trace-kind">' + kind + '</span>' + (name ? '<strong>' + esc(name) + '</strong>' : '') +
461
+ '<span class="ib-trace-meta">' + esc(meta.join(DOT)) + '</span></div>';
462
+ };
463
+ var err = st.error ? '<p class="error" style="margin:0">' + esc(st.error) + '</p>' : '';
464
+ if (st.type === 'prompt') {
465
+ return '<li class="ib-trace-span prompt">' + head(st.resumed ? 'Prompt (resumed)' : 'Prompt', '') +
466
+ (st.tools.length ? '<div class="ib-trace-tools">' + st.tools.map(function (t) { return '<code>' + esc(t) + '</code>'; }).join('') + '</div>' : '') +
467
+ (st.prior_messages ? '<span class="ib-trace-meta">After ' + st.prior_messages + ' earlier messages in this conversation</span>' : '') +
468
+ tracePart('System prompt', st.system, false) +
469
+ tracePart(st.resumed ? 'Resumed with' : 'Input', st.input, true) + '</li>';
470
+ }
471
+ if (st.type === 'model_call') {
472
+ if (st.input_tokens != null) meta.push(count(st.input_tokens) + ' in ' + String.fromCharCode(183) + ' ' + count(st.output_tokens) + ' out tokens');
473
+ if (st.messages_sent != null) meta.push(st.messages_sent + (st.messages_sent === 1 ? ' message' : ' messages') + ' sent');
474
+ if (st.stop_reason) meta.push('stopped: ' + st.stop_reason);
475
+ var fresh = Array.isArray(st.input) && st.input.length ? st.input : null;
476
+ var afterPrompt = i > 0 && steps[i - 1].type === 'prompt';
477
+ return '<li class="ib-trace-span llm' + (st.error ? ' err' : '') + '">' + head('Model call', st.model) + err +
478
+ (fresh ? tracePart('New input', fresh, false) : '<span class="ib-trace-meta">' + (afterPrompt ? 'Given the prompt above' : 'No new input since the step before') + '</span>') +
479
+ tracePart('Output', st.output, true) + '</li>';
480
+ }
481
+ if (st.type === 'tool_call') {
482
+ if (st.status) meta.push(st.status);
483
+ return '<li class="ib-trace-span tool' + (st.error ? ' err' : '') + '">' + head('Tool call', st.name) + err +
484
+ tracePart('Input', st.input, false) + tracePart('Output', st.output, false) + '</li>';
485
+ }
486
+ var who = st.by ? ' by ' + st.by : '';
487
+ if (st.type === 'decision') {
488
+ return '<li class="ib-trace-span event">' + head('Decision', (st.approved ? (st.changed ? 'Approved as changed: ' : 'Approved: ') : 'Denied: ') + st.tool) +
489
+ '<span class="ib-trace-meta">' + esc(when(st.at) + who) + '</span>' + (st.reason ? '<div>' + esc(st.reason) + '</div>' : '') + '</li>';
490
+ }
491
+ if (st.type === 'answer') {
492
+ return '<li class="ib-trace-span event">' + head('Answer', '') + '<span class="ib-trace-meta">' + esc(when(st.at) + who) + '</span>' +
493
+ tracePart('Question', st.question, false) + '<div>' + esc(st.answer) + '</div></li>';
494
+ }
495
+ return '<li class="ib-trace-span event">' + head('Feedback', [st.verdict, st.edit ? st.edit + ' edits' : ''].filter(Boolean).join(', ')) +
496
+ '<span class="ib-trace-meta">' + esc(when(st.at) + who) + '</span>' + (st.note ? '<div>' + esc(st.note) + '</div>' : '') + '</li>';
497
+ }
498
+ function wireTrace(c) {
499
+ var btn = page.querySelector('[data-act="trace"]');
500
+ if (!btn) return;
501
+ var list = page.querySelector('.ib-trace-list');
502
+ var status = page.querySelector('.ib-trace-status');
503
+ var loaded = false;
504
+ btn.addEventListener('click', function () {
505
+ if (loaded) {
506
+ list.hidden = !list.hidden;
507
+ btn.textContent = list.hidden ? 'Show trace' : 'Hide trace';
508
+ return;
509
+ }
510
+ btn.disabled = true;
511
+ status.textContent = 'Loading' + ELLIPSIS;
512
+ fetch('/inbox/cases/' + encodeURIComponent(c.id) + '/trace', { headers: { accept: 'application/json' } })
513
+ .then(function (r) { return r.json().then(function (b) { if (!r.ok) throw new Error(b.error || 'Could not load the trace'); return b; }); })
514
+ .then(function (t) {
515
+ loaded = true;
516
+ btn.disabled = false;
517
+ var steps = t.step_events || [];
518
+ var traced = steps.some(function (x) { return x.type === 'prompt' || x.type === 'model_call'; });
519
+ status.textContent = traced ? '' : 'No step-by-step trace for this run: it ran before traces were kept.';
520
+ list.innerHTML = '<li>' + traceSummaryHtml(t) + '</li>' + steps.map(traceStepHtml).join('') +
521
+ (t.final_output ? '<li class="ib-trace-span">' + '<div class="ib-trace-head"><span class="ib-trace-kind">Final output</span></div>' + tracePart('Output', t.final_output, true) + '</li>' : '') +
522
+ '<li><a class="ib-link" href="/agents/' + encodeURIComponent(t.agent) + '/runs/' + encodeURIComponent(t.execution_id) + '/trace" download="trace-' + esc(t.execution_id.slice(0, 8)) + '.json">Download trace as JSON</a></li>';
523
+ list.hidden = false;
524
+ btn.textContent = 'Hide trace';
525
+ })
526
+ .catch(function (err) { btn.disabled = false; status.textContent = err.message; });
527
+ });
528
+ }
529
+
388
530
  // Save this run as one of its workflow's eval cases (owners, admins and
389
531
  // editors): a test it must keep passing. Then the success criteria it
390
532
  // suggests, from what people corrected in it, to add or not.
@@ -0,0 +1,114 @@
1
+ import type { AuditEvent, TraceSpan } from '../core/audit-store.js';
2
+ import type { UsageRow } from '../core/usage.js';
3
+ import { type WorkflowRun } from '../core/workflow-runs.js';
4
+ export interface TraceToolCall {
5
+ id: string;
6
+ name: string;
7
+ input: unknown;
8
+ output: unknown;
9
+ /** Allowed, approved, denied, skipped, or not run (a test run). */
10
+ status: string | null;
11
+ error: string | null;
12
+ started_at: string;
13
+ duration_ms: number | null;
14
+ }
15
+ export type TraceStepEvent = {
16
+ type: 'prompt';
17
+ at: string;
18
+ resumed: boolean;
19
+ system: string;
20
+ tools: string[];
21
+ input: unknown;
22
+ prior_messages: number;
23
+ } | {
24
+ type: 'model_call';
25
+ at: string;
26
+ duration_ms: number | null;
27
+ model: string | null;
28
+ input: unknown;
29
+ output: unknown;
30
+ input_tokens: number | null;
31
+ output_tokens: number | null;
32
+ messages_sent: number | null;
33
+ stop_reason: string | null;
34
+ error: string | null;
35
+ } | ({
36
+ type: 'tool_call';
37
+ at: string;
38
+ } & Omit<TraceToolCall, 'started_at'>) | {
39
+ type: 'decision';
40
+ at: string;
41
+ tool: string;
42
+ approved: boolean;
43
+ changed: boolean;
44
+ by: string | null;
45
+ reason: string | null;
46
+ } | {
47
+ type: 'answer';
48
+ at: string;
49
+ question: string;
50
+ answer: string;
51
+ by: string | null;
52
+ } | {
53
+ type: 'feedback';
54
+ at: string;
55
+ by: string | null;
56
+ verdict: string | null;
57
+ edit: string | null;
58
+ note: string | null;
59
+ };
60
+ export interface RunTrace {
61
+ execution_id: string;
62
+ agent: string;
63
+ workflow_id: string;
64
+ /** The workflow version it ran under (core/audit-store.ts), and that
65
+ * version's id, "<workflow>@v<number>". */
66
+ workflow_version: number | null;
67
+ workflow_version_id: string | null;
68
+ status: WorkflowRun['status'];
69
+ started_at: string;
70
+ finished_at: string | null;
71
+ input: {
72
+ params: Record<string, string>;
73
+ message: string;
74
+ };
75
+ final_output: string | null;
76
+ /** The result's JSON, for a workflow with an output schema, once it
77
+ * matched; and the check: valid (null without a schema), how many
78
+ * times the agent was asked again, and what was wrong last. */
79
+ final_output_json: unknown;
80
+ output_schema_check: {
81
+ valid: boolean | null;
82
+ retries: number;
83
+ errors: string[];
84
+ };
85
+ model: {
86
+ provider: string | null;
87
+ model: string;
88
+ } | null;
89
+ tool_calls: TraceToolCall[];
90
+ step_events: TraceStepEvent[];
91
+ error: string | null;
92
+ duration_ms: number | null;
93
+ /** usd is null unless every model call's model has a price. */
94
+ cost: {
95
+ usd: number | null;
96
+ input_tokens: number;
97
+ output_tokens: number;
98
+ model_calls: number;
99
+ model_ms: number;
100
+ };
101
+ feedback: {
102
+ verdict: string | null;
103
+ edit: string | null;
104
+ final_output_used: string | null;
105
+ note: string | null;
106
+ at: string;
107
+ } | null;
108
+ }
109
+ export declare function buildRunTrace(input: {
110
+ run: WorkflowRun;
111
+ spans: TraceSpan[];
112
+ usage: UsageRow[];
113
+ events: AuditEvent[];
114
+ }): RunTrace;
@@ -0,0 +1,79 @@
1
+ import { workflowVersionOf } from '../core/workflow-runs.js';
2
+ const str = (v) => (typeof v === 'string' && v ? v : null);
3
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
4
+ export function buildRunTrace(input) {
5
+ const { run, spans, usage } = input;
6
+ const version = workflowVersionOf(run) ?? null;
7
+ const toolCalls = [];
8
+ const steps = spans.map((s) => {
9
+ if (s.kind === 'prompt') {
10
+ const p = (s.input ?? {});
11
+ return { type: 'prompt', at: s.at, resumed: s.meta?.resumed === true, system: p.system ?? '', tools: p.tools ?? [], input: p.start ?? null, prior_messages: p.priorMessages ?? 0 };
12
+ }
13
+ if (s.kind === 'llm') {
14
+ return {
15
+ type: 'model_call', at: s.at, duration_ms: s.durationMs ?? null, model: s.name ?? null, input: s.input ?? [], output: s.output ?? null,
16
+ input_tokens: num(s.meta?.inputTokens), output_tokens: num(s.meta?.outputTokens), messages_sent: num(s.meta?.sent), stop_reason: str(s.meta?.stopReason), error: s.error ?? null,
17
+ };
18
+ }
19
+ const call = {
20
+ id: str(s.meta?.toolUseId) ?? String(s.id),
21
+ name: s.name ?? 'tool',
22
+ input: s.input ?? null,
23
+ output: s.output ?? null,
24
+ status: str(s.meta?.status),
25
+ error: s.error ?? null,
26
+ started_at: s.at,
27
+ duration_ms: s.durationMs ?? null,
28
+ };
29
+ toolCalls.push(call);
30
+ const { started_at: at, ...rest } = call;
31
+ return { type: 'tool_call', at, ...rest };
32
+ });
33
+ for (const d of run.decisions ?? [])
34
+ steps.push({ type: 'decision', at: d.at, tool: d.tool, approved: d.approved, changed: Boolean(d.edited), by: d.by ?? null, reason: d.reason ?? null });
35
+ for (const a of run.answers ?? [])
36
+ steps.push({ type: 'answer', at: a.at, question: a.question, answer: a.answer, by: a.by ?? null });
37
+ for (const e of input.events.filter((x) => x.kind === 'feedback')) {
38
+ steps.push({ type: 'feedback', at: e.at, by: e.by ?? null, verdict: str(e.data.verdict), edit: str(e.data.edit), note: str(e.data.note) });
39
+ }
40
+ // In time order; a step and a decision at the same moment keep their place.
41
+ const order = new Map(steps.map((s, i) => [s, i]));
42
+ steps.sort((a, b) => a.at.localeCompare(b.at) || order.get(a) - order.get(b));
43
+ const firstCall = spans.find((s) => s.kind === 'llm');
44
+ const firstPrompt = spans.find((s) => s.kind === 'prompt')?.input;
45
+ const modelName = str(firstCall?.meta?.model) ?? firstPrompt?.model?.model ?? usage[0]?.model ?? null;
46
+ const provider = str(firstCall?.meta?.provider) ?? firstPrompt?.model?.provider ?? usage[0]?.provider ?? null;
47
+ const priced = usage.length > 0 && usage.every((u) => u.costUsd != null);
48
+ return {
49
+ execution_id: run.run_id,
50
+ agent: run.agent,
51
+ workflow_id: run.workflow_id,
52
+ workflow_version: version,
53
+ workflow_version_id: version ? `${run.workflow_id}@v${version}` : null,
54
+ status: run.status,
55
+ started_at: run.started_at,
56
+ finished_at: run.finished_at ?? null,
57
+ input: { params: run.params ?? {}, message: run.message },
58
+ final_output: run.result ?? null,
59
+ final_output_json: run.output ?? null,
60
+ output_schema_check: {
61
+ valid: run.output !== undefined ? true : run.output_errors?.length && run.status === 'error' ? false : null,
62
+ retries: run.output_retries ?? 0,
63
+ errors: run.output_errors ?? [],
64
+ },
65
+ model: modelName ? { provider, model: modelName } : null,
66
+ tool_calls: toolCalls,
67
+ step_events: steps,
68
+ error: run.error ?? null,
69
+ duration_ms: run.finished_at ? Math.max(0, Date.parse(run.finished_at) - Date.parse(run.started_at)) : null,
70
+ cost: {
71
+ usd: priced ? usage.reduce((n, u) => n + u.costUsd, 0) : null,
72
+ input_tokens: usage.reduce((n, u) => n + u.inputTokens, 0),
73
+ output_tokens: usage.reduce((n, u) => n + u.outputTokens, 0),
74
+ model_calls: usage.length,
75
+ model_ms: usage.reduce((n, u) => n + (u.durationMs ?? 0), 0),
76
+ },
77
+ feedback: run.feedback ? { verdict: run.feedback.verdict ?? null, edit: run.feedback.edit ?? null, final_output_used: run.feedback.final ?? null, note: run.feedback.note ?? null, at: run.feedback.at } : null,
78
+ };
79
+ }