loopengine 0.4.13 → 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 (48) 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/system-agents/goal-planner.d.ts +3 -3
  11. package/dist/core/system-agents/goal-planner.js +9 -5
  12. package/dist/core/trace.d.ts +34 -0
  13. package/dist/core/trace.js +149 -0
  14. package/dist/core/workflow-runs.d.ts +30 -5
  15. package/dist/core/workflow-runs.js +62 -12
  16. package/dist/core/workflow-triggers.d.ts +8 -1
  17. package/dist/core/workflow-triggers.js +13 -0
  18. package/dist/core/workflows.d.ts +17 -1
  19. package/dist/core/workflows.js +72 -9
  20. package/dist/index.d.ts +6 -2
  21. package/dist/index.js +6 -2
  22. package/dist/web/agents-config-page.js +372 -67
  23. package/dist/web/audit-admin.d.ts +2 -2
  24. package/dist/web/audit-admin.js +5 -3
  25. package/dist/web/audit-page.js +7 -5
  26. package/dist/web/change-log.js +4 -2
  27. package/dist/web/console-shell.js +1 -1
  28. package/dist/web/decide-page.js +1 -1
  29. package/dist/web/goals-admin.d.ts +8 -5
  30. package/dist/web/goals-admin.js +25 -5
  31. package/dist/web/goals-page.js +28 -8
  32. package/dist/web/home-page.js +3 -3
  33. package/dist/web/inbox-page.js +143 -1
  34. package/dist/web/run-trace.d.ts +114 -0
  35. package/dist/web/run-trace.js +79 -0
  36. package/dist/web/upgrade-admin.js +19 -5
  37. package/dist/web/workflow-admin.d.ts +12 -3
  38. package/dist/web/workflow-admin.js +42 -7
  39. package/dist/web/workflow-audit-report.js +5 -5
  40. package/dist/web/workflow-audit.d.ts +3 -3
  41. package/dist/web/workflow-audit.js +12 -11
  42. package/dist/web/workflow-drafts.d.ts +75 -0
  43. package/dist/web/workflow-drafts.js +112 -0
  44. package/dist/web/workflow-evidence.d.ts +17 -4
  45. package/dist/web/workflow-evidence.js +22 -6
  46. package/dist/web/workflow-health.d.ts +2 -2
  47. package/dist/web/workflow-health.js +7 -1
  48. 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
@@ -145,6 +145,9 @@ const goalsPageTemplate = `<!doctype html>
145
145
  .gl-setup-more summary { cursor: pointer; color: var(--accent-ink); font-weight: 600; }
146
146
  .gl-setup-more .gl-setup { margin-top: 4px; }
147
147
  .gl-select { font: inherit; font-size: 13px; padding: 3px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--ink); }
148
+ .gl-examples { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-top: 8px; }
149
+ .gl-example { font: inherit; font-size: 12.5px; color: var(--accent-ink); background: var(--bg); border: 1px solid var(--line); border-radius: 999px; padding: 3px 10px; cursor: pointer; }
150
+ .gl-example:hover { border-color: var(--accent-ink); }
148
151
  .gl-share { display: flex; gap: 8px; align-items: flex-start; margin-top: 8px; line-height: 1.45; }
149
152
  .gl-share input { margin-top: 2px; }
150
153
  .gl-discarded-note { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding: 10px 14px; border-radius: 10px; background: var(--surface); font-size: 13.5px; }
@@ -192,6 +195,8 @@ ${consoleShellScript}
192
195
  // The focuses in use (the playbook's, and the workspace's own the
193
196
  // planner named), from the server; these until it answers.
194
197
  var FOCUS = [['new-signups', 'Getting new signups or customers'], ['activation', 'Getting new users started'], ['retention', 'Keeping users'], ['faster-support', 'Faster support'], ['revenue-recovery', 'Recovering revenue'], ['ops-hygiene', 'Smoother operations'], ['other', 'Something else']];
198
+ // Goals of every size, to show what can go in the box.
199
+ var GOAL_EXAMPLES = ['Answer every customer email within a day', 'Get 100 paying customers by March', 'Post on LinkedIn three times a week'];
195
200
  var KINDS = [['', 'Choose one'], ['ecommerce', 'Online store'], ['saas', 'Software or app'], ['agency', 'Agency or services'], ['local', 'Local business'], ['creator', 'Creator or media'], ['nonprofit', 'Nonprofit'], ['other', 'Something else']];
196
201
  var REASONS = [['not-relevant', 'Not relevant'], ['too-much-work', 'Too much work'], ['already-doing-it', 'Already doing it']];
197
202
  // Which view: the list (/goals), a new goal (?new=1, or the front page)
@@ -286,10 +291,12 @@ ${consoleShellScript}
286
291
 
287
292
  function newGoalHtml() {
288
293
  return '<div class="gl-card">' +
289
- '<label for="glGoal"><strong>What do you want to achieve?</strong></label>' +
290
- '<textarea id="glGoal" placeholder="e.g. Get 100 paying customers by the end of March">' + esc(startText) + '</textarea>' +
291
- '<details' + (state.about ? '' : ' open') + '><summary class="hint">About your business ' + (state.about ? '(saved, used for every goal)' : '(optional, makes suggestions fit you)') + '</summary>' +
292
- '<textarea id="glAbout" style="margin-top:8px" placeholder="What you sell, to whom, and the tools you use (Gmail, Shopify, Slack' + ELLIPSIS + ')">' + esc(state.about) + '</textarea>' +
294
+ '<label for="glGoal"><strong>What should your agents take care of?</strong></label>' +
295
+ '<p class="hint" style="margin:2px 0 8px">Big or small: work to hand off, or a result to reach.</p>' +
296
+ '<textarea id="glGoal" placeholder="e.g. Help me research AI industry trends and publish a weekly report">' + esc(startText) + '</textarea>' +
297
+ '<div class="gl-examples hint">Or try: ' + GOAL_EXAMPLES.map(function (x) { return '<button type="button" class="gl-example" data-example="' + esc(x) + '">' + esc(x) + '</button>'; }).join('') + '</div>' +
298
+ '<details' + (state.about ? '' : ' open') + '><summary class="hint">About you or your business ' + (state.about ? '(saved, used for every goal)' : '(optional, makes suggestions fit you)') + '</summary>' +
299
+ '<textarea id="glAbout" style="margin-top:8px" placeholder="What you do, for whom, and the tools you use (Gmail, Shopify, Slack' + ELLIPSIS + ')">' + esc(state.about) + '</textarea>' +
293
300
  '<div class="gl-row" style="margin-top:8px"><label class="hint" for="glKind">Kind of business</label><select id="glKind" class="gl-select">' + KINDS.map(function (k) { return '<option value="' + k[0] + '"' + ((state.settings.businessKind || '') === k[0] ? ' selected' : '') + '>' + k[1] + '</option>'; }).join('') + '</select></div>' +
294
301
  (state.settings.cloud ? '<label class="hint gl-share"><input type="checkbox" id="glShare"' + (state.settings.shareLeverStats ? ' checked' : '') + '> Share anonymous stats about which suggestions you save, build and keep, to improve suggestions for everyone. Never your goals, requests or data.</label>' : '') +
295
302
  '</details>' +
@@ -536,13 +543,20 @@ ${consoleShellScript}
536
543
  }
537
544
 
538
545
  function wire() {
546
+ page.querySelectorAll('[data-example]').forEach(function (b) {
547
+ b.addEventListener('click', function () {
548
+ var box = document.getElementById('glGoal');
549
+ box.value = b.dataset.example;
550
+ box.focus();
551
+ });
552
+ });
539
553
  var submit = document.getElementById('glSubmit');
540
554
  if (submit) submit.addEventListener('click', function () {
541
555
  var goal = document.getElementById('glGoal').value.trim();
542
556
  startText = '';
543
557
  var aboutBox = document.getElementById('glAbout');
544
558
  var status = document.getElementById('glSubmitStatus');
545
- if (goal.length < 5) { status.textContent = 'Say what you want to achieve first.'; return; }
559
+ if (goal.length < 5) { status.textContent = 'Say what your agents should take care of first.'; return; }
546
560
  this.disabled = true;
547
561
  status.textContent = 'Starting' + ELLIPSIS;
548
562
  api('POST', '/goals', { goal: goal, about: aboutBox ? aboutBox.value : state.about }).then(function (r) {
@@ -653,7 +667,8 @@ ${consoleShellScript}
653
667
  });
654
668
  }
655
669
 
656
- // 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
657
672
  // inputs (shown when the step's "run" changes).
658
673
  function stepInputs(card) {
659
674
  var box = card.querySelector('[data-step-inputs]');
@@ -665,9 +680,14 @@ ${consoleShellScript}
665
680
  if (!target) { box.innerHTML = '<p class="hint" style="margin:0">Loading its inputs' + ELLIPSIS + '</p>'; return; }
666
681
  var params = Object.keys(target.parameters || {});
667
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) : [];
668
686
  var choices = function (p) {
669
687
  var srcParams = source ? Object.keys(source.parameters || {}) : [];
670
- 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('') +
671
691
  srcParams.map(function (sp) { return '<option value="input:' + esc(sp) + '"' + (sp === p && !target.parameters[p].required ? ' selected' : '') + '>its input ' + esc(sp) + '</option>'; }).join('');
672
692
  };
673
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('');
@@ -788,7 +808,7 @@ ${consoleShellScript}
788
808
  </script>
789
809
  </body>
790
810
  </html>`;
791
- const GOALS_LEAD = 'Say what you want to achieve. LoopEngine suggests workflows that move it, and groups of workflows that run in order, each with the agent that would run it. Build the ones you want, and generate more when you want new ideas.';
811
+ const GOALS_LEAD = 'LoopEngine suggests the workflows a goal needs: one for a small goal; more, or groups that run in order, for a big one. Build the ones you want.';
792
812
  function goalsPageFor(view) {
793
813
  const title = view === 'goal' ? 'Goal' : view === 'goals' ? 'Goals' : 'New goal';
794
814
  // A list or one goal shows no lead; a new goal explains itself.
@@ -72,7 +72,7 @@ ${consoleSidebarHtml}
72
72
  <div class="le-head plain">
73
73
  <div class="le-head-row">
74
74
  <div class="le-title"><button type="button" class="le-menu-btn" data-le-menu aria-label="Open navigation">&#9776;</button>
75
- <div><h1>Home</h1><p>What you want to achieve, and the workflows and groups of workflows that move it.</p></div>
75
+ <div><h1>Home</h1><p>Your goals, big or small, and the workflows and groups of workflows that take care of them.</p></div>
76
76
  </div>
77
77
  <a class="hm-new" href="/goals?new=1">New goal</a>
78
78
  </div>
@@ -136,9 +136,9 @@ ${consoleShellScript}
136
136
  function renderEmpty() {
137
137
  page.innerHTML =
138
138
  '<div class="hm-empty"><h2>Nothing set up yet</h2>' +
139
- '<p class="hint" style="margin:0">Say what you want to achieve and LoopEngine suggests workflows that move it, and groups of workflows that run in order. Or go straight to a workflow: how an agent does something again and again.</p>' +
139
+ '<p class="hint" style="margin:0">Give LoopEngine a goal, big or small, and it suggests the workflows for it, and groups of workflows that run in order. Or go straight to a workflow: how an agent does something again and again.</p>' +
140
140
  '<div class="hm-ways">' +
141
- '<a class="hm-way" href="/goals?new=1"><b>Start from a goal</b><span>Get workflows suggested for what you want to achieve.</span></a>' +
141
+ '<a class="hm-way" href="/goals?new=1"><b>Start from a goal</b><span>Work to hand off or a result to reach: get workflows suggested for it.</span></a>' +
142
142
  '<a class="hm-way" href="/workflows/new"><b>Build a workflow</b><span>Say what the agent should do, or start from an example.</span></a>' +
143
143
  '</div></div>';
144
144
  }
@@ -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.