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
@@ -0,0 +1,112 @@
1
+ // A workflow's draft: changes to what its runs do, saved but not yet live.
2
+ // Runs keep using the published workflow until the draft is published,
3
+ // which applies it all, numbers it as the workflow's next version
4
+ // (core/audit-store.ts) with the person's note, and removes the draft.
5
+ //
6
+ // Drafted: the instructions, inputs, result format, output schema and
7
+ // model (the editor); the success criteria; where messages go; and
8
+ // adding, changing or removing a schedule or a webhook. Not drafted, as
9
+ // they don't change what a run does: the name and description, saved
10
+ // straight away; and operations: pausing or resuming a schedule, turning a
11
+ // webhook on or off, a new URL, its signing secret, and Run now.
12
+ //
13
+ // A webhook added in a draft is made at once, so its URL can be set up in
14
+ // the sending app, but marked `draft`: its calls are answered and not run
15
+ // until the draft is published (discarding the draft deletes it).
16
+ //
17
+ // Before publishing, the person sees what it changes, field by field
18
+ // (web/change-log.ts's describeChanges), and the version it will be.
19
+ // One draft per workflow, kept in the project at
20
+ // .loopengine/workflow-drafts/<agent>/<workflow>.json.
21
+ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
22
+ import { dirname, join } from 'node:path';
23
+ import { describeChanges } from './change-log.js';
24
+ import { inputSchemaOf } from '../core/input-schema.js';
25
+ const draftPath = (projectDir, agent, workflowId) => join(projectDir, '.loopengine', 'workflow-drafts', agent, `${workflowId}.json`);
26
+ export function readDraft(projectDir, agent, workflowId) {
27
+ const path = draftPath(projectDir, agent, workflowId);
28
+ if (!existsSync(path))
29
+ return undefined;
30
+ try {
31
+ return JSON.parse(readFileSync(path, 'utf8'));
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ }
37
+ /** A draft with nothing in it. */
38
+ export function isEmptyDraft(d) {
39
+ return !d.fields && !d.criteria && !d.messages &&
40
+ !d.schedules?.add.length && !d.schedules?.remove.length &&
41
+ !d.webhooks?.added.length && !Object.keys(d.webhooks?.update ?? {}).length && !d.webhooks?.remove.length;
42
+ }
43
+ /** Changes the draft (making one when there's none), saving who changed
44
+ * it and when; an empty draft is removed. `basedOn` stays the version the
45
+ * draft began from. */
46
+ export function changeDraft(projectDir, agent, workflowId, about, change) {
47
+ const before = readDraft(projectDir, agent, workflowId);
48
+ const start = before ?? { savedAt: '', ...(about.basedOn ? { basedOn: about.basedOn } : {}) };
49
+ const next = { ...change(start), savedAt: new Date().toISOString(), ...(about.by ? { savedBy: about.by } : {}) };
50
+ if (before?.basedOn !== undefined)
51
+ next.basedOn = before.basedOn;
52
+ const path = draftPath(projectDir, agent, workflowId);
53
+ if (isEmptyDraft(next)) {
54
+ if (existsSync(path))
55
+ unlinkSync(path);
56
+ return undefined;
57
+ }
58
+ mkdirSync(dirname(path), { recursive: true });
59
+ writeFileSync(`${path}.tmp`, JSON.stringify(next, null, 2) + '\n');
60
+ renameSync(`${path}.tmp`, path);
61
+ return next;
62
+ }
63
+ /** Saves a whole draft (tests, and replacing one outright). */
64
+ export function saveDraft(projectDir, agent, workflowId, draft) {
65
+ return changeDraft(projectDir, agent, workflowId, { ...(draft.savedBy ? { by: draft.savedBy } : {}), ...(draft.basedOn ? { basedOn: draft.basedOn } : {}) }, () => draft);
66
+ }
67
+ export function discardDraft(projectDir, agent, workflowId) {
68
+ const path = draftPath(projectDir, agent, workflowId);
69
+ if (existsSync(path))
70
+ unlinkSync(path);
71
+ }
72
+ /** The workflow as the draft's editor fields would make it. */
73
+ export function withDraft(workflow, fields) {
74
+ if (!fields)
75
+ return workflow;
76
+ return {
77
+ ...workflow,
78
+ ...(fields.instructions !== undefined ? { instructions: fields.instructions, steps: fields.instructions } : {}),
79
+ ...(fields.parameters ? { parameters: fields.parameters } : {}),
80
+ ...(fields.output !== undefined ? { output: fields.output ?? undefined } : {}),
81
+ ...(fields.outputSchema !== undefined ? { outputSchema: (fields.outputSchema ?? undefined) } : {}),
82
+ ...(fields.model !== undefined ? { model: fields.model ?? undefined } : {}),
83
+ };
84
+ }
85
+ /** Where messages go, in words, for comparing. */
86
+ export function messagesText(d) {
87
+ if (!d)
88
+ return 'the messaging app';
89
+ return [
90
+ d.callback_url ? `updates to ${d.callback_url}` : '',
91
+ d.decisions_to === 'callback' ? 'approvals and questions to your app' : '',
92
+ d.chat_notice ? `start notice “${d.chat_notice}”` : '',
93
+ d.result_to_chat ? 'result to chat' : '',
94
+ ].filter(Boolean).join('; ') || 'the messaging app';
95
+ }
96
+ function comparable(s) {
97
+ const w = s.workflow;
98
+ return {
99
+ instructions: w.instructions,
100
+ inputs: JSON.stringify(inputSchemaOf(w.parameters), null, 2),
101
+ 'result format': w.output ?? '',
102
+ 'output schema': w.outputSchema ? JSON.stringify(w.outputSchema, null, 2) : '',
103
+ model: w.model ? `${w.model.provider} ${w.model.model}` : 'the agent’s',
104
+ 'success criteria': s.criteria.map((c) => `[${c.kind}${c.value ? `: ${c.value}` : ''}] ${c.text}`).join('\n'),
105
+ messaging: messagesText(s.delivery),
106
+ triggers: [...s.triggers].sort().join('\n'),
107
+ };
108
+ }
109
+ /** What publishing changes: the published state against the drafted. */
110
+ export function draftChanges(published, drafted) {
111
+ return describeChanges(comparable(published), comparable(drafted));
112
+ }
@@ -1,5 +1,6 @@
1
1
  import type { ModelCall } from '#core/run-agent.js';
2
2
  import type { RunFeedback, WorkflowRun } from '#core/workflow-runs.js';
3
+ import { type JsonSchema } from '#core/output-schema.js';
3
4
  export declare class EvidenceError extends Error {
4
5
  }
5
6
  export interface WorkflowScores {
@@ -43,7 +44,10 @@ export interface EvalCase {
43
44
  * `not_contains`: `value` is or isn't in the result, ignoring case.
44
45
  * `tool_called` / `tool_not_called`: the run did or didn't call tool
45
46
  * `value` (in a test run, a call it would have made counts). */
46
- export type CriterionKind = 'judge' | 'reference' | 'contains' | 'not_contains' | 'tool_called' | 'tool_not_called';
47
+ export type CriterionKind = 'judge' | 'reference' | 'contains' | 'not_contains' | 'tool_called' | 'tool_not_called' | 'output_schema';
48
+ /** The check every round adds for a workflow with an output schema: its
49
+ * result matches the schema (core/output-schema.ts), checked in code. */
50
+ export declare const OUTPUT_SCHEMA_CRITERION: EvalCriterion;
47
51
  export interface EvalCriterion {
48
52
  id: string;
49
53
  text: string;
@@ -77,7 +81,9 @@ export interface EvalCaseResult {
77
81
  }
78
82
  export interface EvalRound {
79
83
  at: string;
80
- /** The brief version it tested (core/audit-store.ts), when kept. */
84
+ /** The workflow version it tested (core/audit-store.ts), when kept. */
85
+ workflowVersion?: number;
86
+ /** On rounds from when only the brief was versioned: the same number. */
81
87
  briefVersion?: number;
82
88
  /** The workflow's model and the judge's, as "provider model". */
83
89
  model: string;
@@ -123,6 +129,9 @@ export declare function removeEvalCase(agentDir: string, workflowId: string, cas
123
129
  /** Replaces the workflow's criteria. Each needs its words; a code check
124
130
  * needs its value. */
125
131
  export declare function setEvalCriteria(agentDir: string, workflowId: string, input: unknown): EvalCriterion[];
132
+ /** Criteria as given, checked (each its words, a value where its kind
133
+ * needs one, at most MAX_CRITERIA), without saving them. */
134
+ export declare function checkEvalCriteria(input: unknown): EvalCriterion[];
126
135
  /** The criteria a round checks: the workflow's, or with none set,
127
136
  * whether the result matches the good result. */
128
137
  export declare function effectiveCriteria(evals: Pick<WorkflowEvals, 'criteria'>): EvalCriterion[];
@@ -130,6 +139,7 @@ export declare function effectiveCriteria(evals: Pick<WorkflowEvals, 'criteria'>
130
139
  export declare function codeCheck(criterion: EvalCriterion, run: {
131
140
  result: string;
132
141
  tools: string[];
142
+ outputSchema?: JsonSchema;
133
143
  }): EvalCheck | undefined;
134
144
  export declare const EVAL_CRITERIA_PROMPT = "You check one result of an AI agent's workflow against a list of statements. For each statement, say whether it is true of the result.\n\nJudge substance, not style: the same facts and decisions in other words count. A test run doesn't make calls that need approval; a result saying it would have made one, or a call listed as attempted, counts as making it. When a statement can't be checked from what you're given, it is false, and say why.\n\nReply with JSON only: {\"checks\": [{\"id\": \"<the statement's id>\", \"pass\": true or false, \"reason\": \"<one sentence; required when false>\"}]}, one entry per statement.";
135
145
  /** The judge's answers for one result, one call for all its statements. */
@@ -147,6 +157,7 @@ export declare function checkCase(judge: ModelCall, input: {
147
157
  instructions: string;
148
158
  criteria: EvalCriterion[];
149
159
  reference: string;
160
+ outputSchema?: JsonSchema;
150
161
  run: {
151
162
  result: string;
152
163
  tools: string[];
@@ -166,8 +177,10 @@ export declare function draftCriteria(model: ModelCall, input: {
166
177
  export interface EvalRunDeps {
167
178
  agentDir: string;
168
179
  workflowId: string;
169
- /** The brief version being tested, recorded on the round. */
170
- briefVersion?: number;
180
+ /** The workflow version being tested, recorded on the round. */
181
+ workflowVersion?: number;
182
+ /** Its output schema: each case is also checked against it. */
183
+ outputSchema?: JsonSchema;
171
184
  instructions: string;
172
185
  /** The workflow's model and the judge's, as "provider model". */
173
186
  model: string;
@@ -24,6 +24,7 @@
24
24
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
25
25
  import { dirname, join } from 'node:path';
26
26
  import { randomUUID } from 'node:crypto';
27
+ import { checkOutput } from '#core/output-schema.js';
27
28
  import { editAmount } from './goals-admin.js';
28
29
  export class EvidenceError extends Error {
29
30
  }
@@ -80,6 +81,9 @@ export function runFeedbackFrom(run, body) {
80
81
  at: new Date().toISOString(),
81
82
  };
82
83
  }
84
+ /** The check every round adds for a workflow with an output schema: its
85
+ * result matches the schema (core/output-schema.ts), checked in code. */
86
+ export const OUTPUT_SCHEMA_CRITERION = { id: 'output-schema', text: 'Matches the output schema', kind: 'output_schema' };
83
87
  const MAX_CASES = 30;
84
88
  const MAX_ROUNDS = 10;
85
89
  const MAX_CRITERIA = 8;
@@ -140,6 +144,14 @@ export function removeEvalCase(agentDir, workflowId, caseId) {
140
144
  /** Replaces the workflow's criteria. Each needs its words; a code check
141
145
  * needs its value. */
142
146
  export function setEvalCriteria(agentDir, workflowId, input) {
147
+ const criteria = checkEvalCriteria(input);
148
+ const evals = readEvals(agentDir, workflowId);
149
+ writeEvals(agentDir, workflowId, { ...evals, criteria });
150
+ return criteria;
151
+ }
152
+ /** Criteria as given, checked (each its words, a value where its kind
153
+ * needs one, at most MAX_CRITERIA), without saving them. */
154
+ export function checkEvalCriteria(input) {
143
155
  if (!Array.isArray(input))
144
156
  throw new EvidenceError('criteria must be a list.');
145
157
  if (input.length > MAX_CRITERIA)
@@ -160,8 +172,6 @@ export function setEvalCriteria(agentDir, workflowId, input) {
160
172
  used.add(id);
161
173
  return { id, text, kind, ...(value && kind !== 'judge' && kind !== 'reference' ? { value } : {}) };
162
174
  });
163
- const evals = readEvals(agentDir, workflowId);
164
- writeEvals(agentDir, workflowId, { ...evals, criteria });
165
175
  return criteria;
166
176
  }
167
177
  /** The criteria a round checks: the workflow's, or with none set,
@@ -184,6 +194,12 @@ export function codeCheck(criterion, run) {
184
194
  const called = run.tools.some((t) => t.toLowerCase() === value);
185
195
  return { criterionId: criterion.id, pass: !called, ...(called ? { reason: `It called ${criterion.value}.` } : {}) };
186
196
  }
197
+ case 'output_schema': {
198
+ if (!run.outputSchema)
199
+ return { criterionId: criterion.id, pass: true };
200
+ const check = checkOutput(run.outputSchema, run.result);
201
+ return { criterionId: criterion.id, pass: check.ok, ...(check.ok ? {} : { reason: check.errors.join('; ').slice(0, 500) }) };
202
+ }
187
203
  default: return undefined;
188
204
  }
189
205
  }
@@ -228,7 +244,7 @@ export async function checkCase(judge, input) {
228
244
  const error = input.run.error;
229
245
  return applies.map((c) => ({ criterionId: c.id, pass: false, reason: `The run failed: ${error.slice(0, 200)}` }));
230
246
  }
231
- const run = input.run;
247
+ const run = { ...input.run, ...(input.outputSchema ? { outputSchema: input.outputSchema } : {}) };
232
248
  const coded = new Map(applies.flatMap((c) => { const r = codeCheck(c, run); return r ? [[c.id, r]] : []; }));
233
249
  const forJudge = applies.filter((c) => !coded.has(c.id));
234
250
  let judged = new Map();
@@ -302,7 +318,7 @@ export function startEvalRound(deps) {
302
318
  const cases = evals.cases;
303
319
  const startedAt = new Date().toISOString();
304
320
  writeEvals(deps.agentDir, deps.workflowId, { ...evals, running: { startedAt, done: 0, total: cases.length } });
305
- const criteria = effectiveCriteria(evals);
321
+ const criteria = [...effectiveCriteria(evals), ...(deps.outputSchema ? [OUTPUT_SCHEMA_CRITERION] : [])];
306
322
  return (async () => {
307
323
  const results = [];
308
324
  for (const c of cases) {
@@ -313,7 +329,7 @@ export function startEvalRound(deps) {
313
329
  catch (err) {
314
330
  run = { error: err instanceof Error ? err.message : String(err) };
315
331
  }
316
- const checks = await checkCase(deps.judge, { instructions: deps.instructions, criteria, reference: c.reference ?? '', run });
332
+ const checks = await checkCase(deps.judge, { instructions: deps.instructions, criteria, reference: c.reference ?? '', ...(deps.outputSchema ? { outputSchema: deps.outputSchema } : {}), run });
317
333
  results.push({
318
334
  caseId: c.id,
319
335
  ...('error' in run ? { error: run.error } : { result: run.result.slice(0, 20000), tools: [...new Set(run.tools)], ...(run.standIns?.length ? { standIns: run.standIns.slice(0, 50) } : {}) }),
@@ -324,7 +340,7 @@ export function startEvalRound(deps) {
324
340
  }
325
341
  const round = {
326
342
  at: startedAt,
327
- ...(deps.briefVersion ? { briefVersion: deps.briefVersion } : {}),
343
+ ...(deps.workflowVersion ? { workflowVersion: deps.workflowVersion } : {}),
328
344
  model: deps.model,
329
345
  judge: deps.judgeLabel,
330
346
  cases: results,
@@ -1,4 +1,4 @@
1
- import type { WorkflowRun } from '../core/workflow-runs.js';
1
+ import { type WorkflowRun } from '../core/workflow-runs.js';
2
2
  export interface HealthNumbers {
3
3
  runs: number;
4
4
  /** Finished, done or failed. */
@@ -22,7 +22,7 @@ export interface HealthNumbers {
22
22
  pricedRuns: number;
23
23
  }
24
24
  export interface HealthVersion extends HealthNumbers {
25
- /** The brief version, or null for runs from before versions. */
25
+ /** The workflow version, or null for runs from before versions. */
26
26
  version: number | null;
27
27
  /** Its first and last run in the period. */
28
28
  from: string;
@@ -1,3 +1,9 @@
1
+ // A workflow's health (the workflow page's Health panel): how its runs
2
+ // went over the last 30 days, per workflow version and day by day, and an
3
+ // alert when a measure suddenly gets worse. Built from the runs
4
+ // (core/workflow-runs.ts: status, decisions, answers, feedback, the brief
5
+ // version each ran under) and their model calls' cost (core/usage.ts).
6
+ import { workflowVersionOf } from '../core/workflow-runs.js';
1
7
  const DAY = 24 * 60 * 60 * 1000;
2
8
  function numbers(runs, costs) {
3
9
  const finished = runs.filter((r) => r.status === 'done' || r.status === 'error');
@@ -59,7 +65,7 @@ export function workflowHealth(runs, costs, options = {}) {
59
65
  const inPeriod = runs.filter((r) => r.started_at >= since).sort((a, b) => a.started_at.localeCompare(b.started_at));
60
66
  const byVersion = new Map();
61
67
  for (const r of inPeriod) {
62
- const v = r.versions?.brief ?? null;
68
+ const v = workflowVersionOf(r) ?? null;
63
69
  byVersion.set(v, [...(byVersion.get(v) ?? []), r]);
64
70
  }
65
71
  const versions = [...byVersion.entries()]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "loopengine",
3
- "version": "0.4.13",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "Runtime for tool-using AI agents with a transparent ReAct loop.",
6
6
  "license": "MIT",
@@ -47,6 +47,12 @@
47
47
  "dist/core/trusted-proxy.d.ts",
48
48
  "dist/core/audit-store.js",
49
49
  "dist/core/audit-store.d.ts",
50
+ "dist/core/trace.js",
51
+ "dist/core/trace.d.ts",
52
+ "dist/core/output-schema.js",
53
+ "dist/core/output-schema.d.ts",
54
+ "dist/core/input-schema.js",
55
+ "dist/core/input-schema.d.ts",
50
56
  "dist/core/workspace-roles.js",
51
57
  "dist/core/workspace-roles.d.ts",
52
58
  "dist/core/unattended.js",
@@ -166,6 +172,8 @@
166
172
  "@anthropic-ai/sdk": "^0.116.0",
167
173
  "@modelcontextprotocol/sdk": "1.32.1",
168
174
  "actauth": "^0.0.12",
175
+ "ajv": "^8.20.0",
176
+ "ajv-formats": "^3.0.1",
169
177
  "ioredis": "^6.0.0",
170
178
  "openai": "^7.4.0",
171
179
  "semver": "^7.8.5",