loopengine 0.4.14 → 0.5.1

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 +12 -2
  19. package/dist/index.js +14 -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
@@ -0,0 +1,105 @@
1
+ // A workflow's output schema: a JSON Schema its result must match. With
2
+ // one, the agent is told to end with JSON that matches it; each run's
3
+ // reply is checked (core/workflow-runs.ts), and when it doesn't match the
4
+ // agent is told what's wrong and asked again, up to MAX_OUTPUT_RETRIES
5
+ // times, before the run fails. A run that matches keeps the parsed JSON
6
+ // as its `output`, beside the text `result`, for apps, callbacks and the
7
+ // next workflow in a chain (which can take one field of it).
8
+ //
9
+ // Checked with Ajv (JSON Schema draft 2020-12's common keywords, and
10
+ // formats such as email, date and uri).
11
+ import { Ajv } from 'ajv';
12
+ import addFormatsModule from 'ajv-formats';
13
+ /** Times a run is asked again for a result that doesn't match. */
14
+ export const MAX_OUTPUT_RETRIES = 2;
15
+ const MAX_SCHEMA_CHARS = 20_000;
16
+ export class OutputSchemaError extends Error {
17
+ }
18
+ const ajv = new Ajv({ allErrors: true, strict: false });
19
+ const addFormats = addFormatsModule.default ?? addFormatsModule;
20
+ addFormats(ajv);
21
+ const compiled = new Map();
22
+ function validatorFor(schema) {
23
+ const key = JSON.stringify(schema);
24
+ let fn = compiled.get(key);
25
+ if (!fn) {
26
+ fn = ajv.compile(schema);
27
+ if (compiled.size > 200)
28
+ compiled.clear();
29
+ compiled.set(key, fn);
30
+ }
31
+ return fn;
32
+ }
33
+ /** A schema as saved: a JSON object (or its text) that Ajv can compile,
34
+ * describing an object or an array. Throws OutputSchemaError saying
35
+ * what's wrong. */
36
+ export function checkOutputSchema(input) {
37
+ let schema = input;
38
+ if (typeof input === 'string') {
39
+ try {
40
+ schema = JSON.parse(input);
41
+ }
42
+ catch (err) {
43
+ throw new OutputSchemaError(`The output schema isn't valid JSON: ${err instanceof Error ? err.message : String(err)}`);
44
+ }
45
+ }
46
+ if (!schema || typeof schema !== 'object' || Array.isArray(schema))
47
+ throw new OutputSchemaError('The output schema must be a JSON object, e.g. { "type": "object", "properties": { … } }.');
48
+ const s = schema;
49
+ if (JSON.stringify(s).length > MAX_SCHEMA_CHARS)
50
+ throw new OutputSchemaError(`The output schema is too long (at most ${MAX_SCHEMA_CHARS.toLocaleString('en-US')} characters).`);
51
+ if (s.type !== 'object' && s.type !== 'array')
52
+ throw new OutputSchemaError('The output schema\'s "type" must be "object" or "array": the result is one JSON value with named fields, or a list.');
53
+ try {
54
+ validatorFor(s);
55
+ }
56
+ catch (err) {
57
+ throw new OutputSchemaError(`The output schema isn't a valid JSON Schema: ${err instanceof Error ? err.message : String(err)}`);
58
+ }
59
+ return s;
60
+ }
61
+ /** The JSON in a reply: the whole reply, else its last ```json block,
62
+ * else the span from its first { or [ to its last } or ]. */
63
+ export function jsonInReply(text) {
64
+ const attempts = [text.trim()];
65
+ const fences = [...text.matchAll(/```(?:json)?\s*\n([\s\S]*?)\n?```/g)].map((m) => m[1]);
66
+ if (fences.length)
67
+ attempts.push(fences[fences.length - 1].trim());
68
+ const start = text.search(/[{[]/);
69
+ const end = Math.max(text.lastIndexOf('}'), text.lastIndexOf(']'));
70
+ if (start >= 0 && end > start)
71
+ attempts.push(text.slice(start, end + 1));
72
+ for (const candidate of attempts) {
73
+ try {
74
+ return { found: true, value: JSON.parse(candidate) };
75
+ }
76
+ catch { }
77
+ }
78
+ return { found: false };
79
+ }
80
+ function errorLine(e) {
81
+ const where = e.instancePath ? e.instancePath.replace(/^\//, '').replace(/\//g, '.') : 'the result';
82
+ const extra = e.keyword === 'additionalProperties' ? ` (${String(e.params.additionalProperty)})`
83
+ : e.keyword === 'enum' ? `: ${(e.params.allowedValues ?? []).map((v) => JSON.stringify(v)).join(', ')}`
84
+ : '';
85
+ return `${where} ${e.message ?? 'is not valid'}${extra}`;
86
+ }
87
+ /** A reply checked against a schema: its JSON when it matches, else
88
+ * what's wrong, a line each (at most 10). */
89
+ export function checkOutput(schema, text) {
90
+ const json = jsonInReply(text);
91
+ if (!json.found)
92
+ return { ok: false, errors: ['The reply has no JSON in it.'] };
93
+ const validate = validatorFor(schema);
94
+ if (validate(json.value))
95
+ return { ok: true, value: json.value };
96
+ return { ok: false, errors: (validate.errors ?? []).slice(0, 10).map(errorLine) };
97
+ }
98
+ /** What the agent is told, with the rest of its instructions. */
99
+ export function outputSchemaInstructions(schema) {
100
+ return `End with your result as JSON that matches this JSON Schema, and nothing after it (a short note before it is fine):\n\n\`\`\`json\n${JSON.stringify(schema, null, 2)}\n\`\`\``;
101
+ }
102
+ /** What the agent is told when its result didn't match. */
103
+ export function outputRetryMessage(errors) {
104
+ return `Your result doesn't match the workflow's output schema:\n${errors.map((e) => `- ${e}`).join('\n')}\n\nReply again with the corrected result as JSON matching the schema. Use what you already found; don't redo work or repeat any action that sends, posts or changes something.`;
105
+ }
@@ -24,6 +24,7 @@ import { loadMcpAbilityTools } from './mcp-abilities.js';
24
24
  import { skillsForResult, skillsInHistory, toolSkillsFor } from './ability-skills.js';
25
25
  import { systemTools, createAskUserTool, createScheduleTools, CliQuestionHandler, isDurableQuestionHandler } from './system-tools/index.js';
26
26
  import { resolveHttpNotifier } from './http-notifier.js';
27
+ import { startTurnTrace } from './trace.js';
27
28
  import { CRASH_RECOVERY_CONTINUATION } from './session-store.js';
28
29
  export { systemTools } from './system-tools/index.js';
29
30
  // Resolved relative to *this file's own location* (via import.meta.url),
@@ -504,10 +505,26 @@ async function buildTurnContext(config, modelCall, options) {
504
505
  * fresh in each case) but mutated here via pushMessage, same as the
505
506
  * single function this was split out of always did. */
506
507
  async function runLoop(ctx, messages, newMessages, starterMessage) {
507
- const { modelCall, log, scope, sessionId, skillGarden, toolSkills, skillText, toolsByName, systemToolInstances, toolSchemas, systemPrompt, budgetTracker, compactor, gate, toolLane, maxTurns, tailMessages, askUserTool, questionHandler, toolContext, modelLabel, evalMode, unattended } = ctx;
508
+ // The turn's trace (core/trace.ts): its prompt, each model call and each
509
+ // tool call, as they happen; what's left is written however it ends.
510
+ const trace = startTurnTrace(ctx.sessionId);
511
+ try {
512
+ return await runTracedLoop(ctx, trace, messages, newMessages, starterMessage);
513
+ }
514
+ finally {
515
+ trace.flush();
516
+ }
517
+ }
518
+ async function runTracedLoop(ctx, trace, messages, newMessages, starterMessage) {
519
+ const { modelCall, log: logEvent, scope, sessionId, skillGarden, toolSkills, skillText, toolsByName, systemToolInstances, toolSchemas, systemPrompt, budgetTracker, compactor, gate, toolLane, maxTurns, tailMessages, askUserTool, questionHandler, toolContext, modelLabel, evalMode, unattended } = ctx;
520
+ const log = (event) => {
521
+ trace.event(event);
522
+ logEvent(event);
523
+ };
508
524
  function pushMessage(message) {
509
525
  messages.push(message);
510
526
  newMessages.push(message);
527
+ trace.message(message);
511
528
  }
512
529
  // See known-urls.ts's own doc comment — seeded once from this
513
530
  // session's full prior history (a resumed session's own tool results,
@@ -557,6 +574,14 @@ async function runLoop(ctx, messages, newMessages, starterMessage) {
557
574
  return recovered;
558
575
  },
559
576
  });
577
+ trace.start({
578
+ system: systemPrompt,
579
+ tools: toolSchemas.map((t) => t.name),
580
+ model: modelLabel,
581
+ history: [...messages],
582
+ starter: starterMessage,
583
+ resumed: typeof starterMessage.content !== 'string' && starterMessage.content.some((b) => b.type === 'tool_result'),
584
+ });
560
585
  pushMessage(starterMessage);
561
586
  let turn = 0;
562
587
  let nudges = 0;
@@ -583,7 +608,15 @@ async function runLoop(ctx, messages, newMessages, starterMessage) {
583
608
  // spent tokens and then failed is still counted.
584
609
  const { value: response } = await recovery.call(async (msgs) => {
585
610
  const started = Date.now();
586
- const result = await modelCall(msgs, systemPrompt, toolSchemas);
611
+ let result;
612
+ try {
613
+ result = await modelCall(msgs, systemPrompt, toolSchemas);
614
+ }
615
+ catch (err) {
616
+ trace.llm({ sent: msgs, error: err, durationMs: Date.now() - started, model: modelLabel });
617
+ throw err;
618
+ }
619
+ trace.llm({ sent: msgs, response: result, durationMs: Date.now() - started, model: modelLabel });
587
620
  if (result.usage) {
588
621
  recordUsage({
589
622
  at: new Date().toISOString(),
@@ -114,6 +114,12 @@ export interface CreateScheduledTaskInput {
114
114
  task_name?: string;
115
115
  notify?: boolean;
116
116
  }
117
+ /** A schedule as a task gives it, checked: what it's saved as and when it
118
+ * first runs. Throws ScheduleError saying what's wrong. */
119
+ export declare function parseScheduleInput(requested: CreateScheduledTaskInput['schedule'], nowMs?: number): {
120
+ schedule: Schedule;
121
+ nextRunMs: number;
122
+ };
117
123
  export declare function createScheduledTask(input: CreateScheduledTaskInput, nowMs?: number): Promise<ScheduledTask>;
118
124
  export declare function listScheduledTasks(filter?: {
119
125
  agent?: string;
@@ -138,31 +138,25 @@ export function getSchedulerStore() {
138
138
  export function setSchedulerStore(next) {
139
139
  store = next;
140
140
  }
141
- export async function createScheduledTask(input, nowMs = Date.now()) {
142
- if (!input.agent)
143
- throw new ScheduleError('agent is required');
144
- const message = typeof input.message === 'string' ? input.message : '';
145
- const workflowId = typeof input.workflow_id === 'string' ? input.workflow_id.trim() : '';
146
- if (message.trim() && workflowId)
147
- throw new ScheduleError('give either a message or a workflow_id, not both');
148
- if (!message.trim() && !workflowId)
149
- throw new ScheduleError('message or workflow_id is required');
141
+ /** A schedule as a task gives it, checked: what it's saved as and when it
142
+ * first runs. Throws ScheduleError saying what's wrong. */
143
+ export function parseScheduleInput(requested, nowMs = Date.now()) {
150
144
  let schedule;
151
145
  let nextRunMs;
152
146
  const timeZone = workspaceTimeZone();
153
- if (typeof input.schedule?.run_at === 'string' && input.schedule.run_at) {
154
- const runAtMs = parseTimestamp(input.schedule.run_at, timeZone);
147
+ if (typeof requested?.run_at === 'string' && requested.run_at) {
148
+ const runAtMs = parseTimestamp(requested.run_at, timeZone);
155
149
  if (Number.isNaN(runAtMs))
156
- throw new ScheduleError(`"${input.schedule.run_at}" is not a valid ISO 8601 timestamp`);
150
+ throw new ScheduleError(`"${requested.run_at}" is not a valid ISO 8601 timestamp`);
157
151
  schedule = { run_at: new Date(runAtMs).toISOString() };
158
152
  nextRunMs = runAtMs;
159
153
  }
160
- else if (typeof input.schedule?.every === 'string' && input.schedule.every) {
161
- const every = input.schedule.every.trim();
154
+ else if (typeof requested?.every === 'string' && requested.every) {
155
+ const every = requested.every.trim();
162
156
  const intervalMs = parseEvery(every);
163
157
  const days = everyDays(every);
164
158
  const calendar = days ? { days, timeZone } : undefined;
165
- const { start_at: startAt, at, weekday } = input.schedule;
159
+ const { start_at: startAt, at, weekday } = requested;
166
160
  const given = (v) => v !== undefined && v !== null && v !== '';
167
161
  let startMs;
168
162
  if (given(at)) {
@@ -193,10 +187,22 @@ export async function createScheduledTask(input, nowMs = Date.now()) {
193
187
  }
194
188
  }
195
189
  else {
196
- if (input.schedule?.start_at || input.schedule?.at)
190
+ if (requested?.start_at || requested?.at)
197
191
  throw new ScheduleError('start_at and at go with "every" (a repeating task); a one-off task uses run_at');
198
192
  throw new ScheduleError('schedule must be { "run_at": "<ISO timestamp>" } or { "every": "<interval, e.g. 1h>", "start_at"?: "<ISO timestamp>" } or { "every": "1d", "at": "09:00" }');
199
193
  }
194
+ return { schedule, nextRunMs };
195
+ }
196
+ export async function createScheduledTask(input, nowMs = Date.now()) {
197
+ if (!input.agent)
198
+ throw new ScheduleError('agent is required');
199
+ const message = typeof input.message === 'string' ? input.message : '';
200
+ const workflowId = typeof input.workflow_id === 'string' ? input.workflow_id.trim() : '';
201
+ if (message.trim() && workflowId)
202
+ throw new ScheduleError('give either a message or a workflow_id, not both');
203
+ if (!message.trim() && !workflowId)
204
+ throw new ScheduleError('message or workflow_id is required');
205
+ const { schedule, nextRunMs } = parseScheduleInput(input.schedule, nowMs);
200
206
  const task = {
201
207
  task_id: randomUUID(),
202
208
  task_name: input.task_name?.trim() || undefined,
@@ -0,0 +1,34 @@
1
+ import type { LoopEvent } from './loop-events.js';
2
+ import type { Message, ModelResponse } from './run-agent.js';
3
+ export interface TurnTrace {
4
+ /** The turn begins: `history` is what came before it (never repeated). */
5
+ start(input: {
6
+ system: string;
7
+ tools: string[];
8
+ model: {
9
+ provider?: string;
10
+ model?: string;
11
+ };
12
+ history: Message[];
13
+ starter: Message;
14
+ resumed: boolean;
15
+ }): void;
16
+ /** A model call: the messages sent, and what came back or the error. */
17
+ llm(call: {
18
+ sent: Message[];
19
+ response?: ModelResponse;
20
+ error?: unknown;
21
+ durationMs: number;
22
+ model: {
23
+ provider?: string;
24
+ model?: string;
25
+ };
26
+ }): void;
27
+ /** A message added to the conversation (tool results among them). */
28
+ message(message: Message): void;
29
+ /** The loop's own events: tool calls starting and resolving. */
30
+ event(event: LoopEvent): void;
31
+ /** Writes what's left: tool calls that finished since the last call. */
32
+ flush(): void;
33
+ }
34
+ export declare function startTurnTrace(sessionId: string | undefined): TurnTrace;
@@ -0,0 +1,149 @@
1
+ import { auditDb, pruneTraces, recordTracePrompt, recordTraceSpan } from './audit-store.js';
2
+ const NONE = { start() { }, llm() { }, message() { }, event() { }, flush() { } };
3
+ const blocksOf = (m) => (typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : m.content);
4
+ export function startTurnTrace(sessionId) {
5
+ if (!sessionId || !auditDb())
6
+ return NONE;
7
+ pruneTraces();
8
+ // Messages (and model replies, by their content) a step already shows.
9
+ const shownSet = new WeakSet();
10
+ const shown = {
11
+ add: (v) => { if (v && typeof v === 'object')
12
+ shownSet.add(v); },
13
+ has: (v) => Boolean(v && typeof v === 'object' && shownSet.has(v)),
14
+ };
15
+ const calls = new Map();
16
+ const order = [];
17
+ // Every tool call a model reply asked for, by its id: its name and input.
18
+ const asked = new Map();
19
+ const noteAsked = (messages) => {
20
+ for (const b of messages.flatMap(blocksOf))
21
+ if (b.type === 'tool_use' && b.id)
22
+ asked.set(b.id, { ...(b.name ? { name: b.name } : {}), ...(b.input ? { input: b.input } : {}) });
23
+ };
24
+ const callFor = (id, tool) => {
25
+ let call = calls.get(id);
26
+ if (!call) {
27
+ // A call with no start event (a built-in like Skill, or one from
28
+ // before this turn, resumed after an approval): its name and input
29
+ // are on the model reply that asked for it.
30
+ const request = asked.get(id);
31
+ call = { tool: tool ?? request?.name ?? 'tool', ...(request?.input ? { args: request.input } : {}), at: new Date().toISOString() };
32
+ calls.set(id, call);
33
+ order.push(id);
34
+ }
35
+ return call;
36
+ };
37
+ const writeTools = () => {
38
+ for (const id of order) {
39
+ const call = calls.get(id);
40
+ if (call.written || (call.status === undefined && call.output === undefined))
41
+ continue;
42
+ call.written = true;
43
+ recordTraceSpan({
44
+ sessionId,
45
+ at: call.at,
46
+ kind: 'tool',
47
+ name: call.tool,
48
+ ...(call.startedAt && call.endedAt ? { durationMs: Math.max(0, call.endedAt - call.startedAt) } : {}),
49
+ ...(call.args ? { input: call.args } : {}),
50
+ ...(call.output !== undefined ? { output: call.output } : {}),
51
+ ...(call.isError ? { error: typeof call.output === 'string' ? call.output.slice(0, 500) : 'The tool returned an error.' } : {}),
52
+ // A built-in that reports no status (Skill): done, or failed.
53
+ meta: { toolUseId: id, status: call.status ?? (call.isError ? 'Failed.' : 'Done.') },
54
+ });
55
+ }
56
+ };
57
+ return safe({
58
+ start(input) {
59
+ noteAsked(input.history);
60
+ for (const m of input.history) {
61
+ shown.add(m);
62
+ shown.add(m.content);
63
+ }
64
+ shown.add(input.starter);
65
+ const systemHash = recordTracePrompt(input.system);
66
+ recordTraceSpan({
67
+ sessionId,
68
+ at: new Date().toISOString(),
69
+ kind: 'prompt',
70
+ input: { ...(systemHash ? { systemHash } : { system: input.system }), tools: input.tools, model: input.model, start: input.starter.content, priorMessages: input.history.length },
71
+ meta: { resumed: input.resumed },
72
+ });
73
+ },
74
+ llm(call) {
75
+ writeTools();
76
+ const fresh = call.sent.filter((m) => !shown.has(m) && !shown.has(m.content));
77
+ for (const m of call.sent)
78
+ shown.add(m);
79
+ if (call.response) {
80
+ shown.add(call.response.content);
81
+ noteAsked([{ role: 'assistant', content: call.response.content }]);
82
+ }
83
+ const usage = call.response?.usage;
84
+ recordTraceSpan({
85
+ sessionId,
86
+ at: new Date(Date.now() - call.durationMs).toISOString(),
87
+ kind: 'llm',
88
+ name: call.model.model ?? 'model',
89
+ durationMs: call.durationMs,
90
+ input: fresh,
91
+ ...(call.response ? { output: call.response.content } : {}),
92
+ ...(call.error !== undefined ? { error: call.error instanceof Error ? call.error.message : String(call.error) } : {}),
93
+ meta: {
94
+ ...call.model,
95
+ sent: call.sent.length,
96
+ ...(usage ? { inputTokens: usage.input_tokens, outputTokens: usage.output_tokens } : {}),
97
+ ...(call.response?.stop_reason ? { stopReason: call.response.stop_reason } : {}),
98
+ },
99
+ });
100
+ },
101
+ message(message) {
102
+ for (const b of blocksOf(message)) {
103
+ if (b.type !== 'tool_result' || !b.tool_use_id)
104
+ continue;
105
+ const call = callFor(b.tool_use_id);
106
+ call.output = b.content;
107
+ call.endedAt ??= Date.now();
108
+ if (b.is_error)
109
+ call.isError = true;
110
+ }
111
+ },
112
+ event(e) {
113
+ if (e.type === 'tool:started') {
114
+ const call = callFor(e.id, e.tool);
115
+ call.startedAt = Date.now();
116
+ call.at = new Date().toISOString();
117
+ call.args = e.args;
118
+ }
119
+ else if (e.type === 'tool:result') {
120
+ const call = callFor(e.id, e.tool);
121
+ call.status = e.statusText;
122
+ call.endedAt ??= Date.now();
123
+ if (e.args && !call.args)
124
+ call.args = e.args;
125
+ }
126
+ },
127
+ flush() {
128
+ writeTools();
129
+ },
130
+ });
131
+ }
132
+ // Every method, made unable to throw into the turn.
133
+ function safe(trace) {
134
+ const guard = (name, fn) => (...args) => {
135
+ try {
136
+ fn(...args);
137
+ }
138
+ catch (err) {
139
+ console.error(`[loopengine] trace ${name} failed:`, err instanceof Error ? err.message : err);
140
+ }
141
+ };
142
+ return {
143
+ start: guard('start', trace.start),
144
+ llm: guard('llm', trace.llm),
145
+ message: guard('message', trace.message),
146
+ event: guard('event', trace.event),
147
+ flush: guard('flush', trace.flush),
148
+ };
149
+ }
@@ -1,5 +1,6 @@
1
1
  import type { DatabaseSync } from 'node:sqlite';
2
2
  import type { CallbackDelivery } from './run-callbacks.js';
3
+ import { type JsonSchema } from './output-schema.js';
3
4
  export type WorkflowRunStatus = 'running' | 'awaiting_approval' | 'done' | 'error';
4
5
  export interface WorkflowRun {
5
6
  run_id: string;
@@ -34,6 +35,13 @@ export interface WorkflowRun {
34
35
  session_id: string;
35
36
  /** The agent's final reply, when done. */
36
37
  result?: string;
38
+ /** For a workflow with an output schema (core/output-schema.ts): the
39
+ * result's JSON, once it matched. */
40
+ output?: unknown;
41
+ /** How many times it was asked again for a result that didn't match
42
+ * the output schema, and what was wrong the last time. */
43
+ output_retries?: number;
44
+ output_errors?: string[];
37
45
  error?: string;
38
46
  /** The approvals or questions it is waiting on. */
39
47
  pending_ids?: string[];
@@ -55,8 +63,8 @@ export interface WorkflowRun {
55
63
  warnings?: string[];
56
64
  /** Each callback delivery, oldest first (the latest 10). */
57
65
  callbacks?: CallbackDelivery[];
58
- /** The brief and shared policies it ran under (core/audit-store.ts's
59
- * versions), when the workspace keeps versions. */
66
+ /** The workflow and shared policies versions it ran under
67
+ * (core/audit-store.ts), when the workspace keeps versions. */
60
68
  versions?: RunVersions;
61
69
  /** Each approval decided while it ran, oldest first, with who decided
62
70
  * (an email, or a chat name) when known. */
@@ -74,9 +82,17 @@ export interface WorkflowRun {
74
82
  feedback?: RunFeedback;
75
83
  }
76
84
  export interface RunVersions {
77
- brief?: number;
85
+ /** The workflow's version (core/audit-store.ts, kind "workflow"). */
86
+ workflow?: number;
78
87
  policies?: number;
88
+ /** On runs from when only the brief was versioned: the same number,
89
+ * now the workflow's version. Read with workflowVersionOf. */
90
+ brief?: number;
79
91
  }
92
+ /** The workflow version a run ran under, whenever it was recorded. */
93
+ export declare function workflowVersionOf(run: {
94
+ versions?: RunVersions;
95
+ }): number | undefined;
80
96
  export interface RunDecision {
81
97
  tool: string;
82
98
  approved: boolean;
@@ -239,16 +255,19 @@ export declare class WorkflowRunner {
239
255
  private readonly maxFinishedPerAgent;
240
256
  private readonly onChange?;
241
257
  private readonly versionsFor?;
258
+ /** The output schema a workflow's result must match, if it has one. */
259
+ private readonly outputSchemaFor?;
242
260
  private readonly inFlight;
243
261
  /** `onChange`: called with the run when it starts, and each time it
244
262
  * finishes, fails or stops for a decision (the server sends its chat
245
- * messages and callbacks). `versionsFor`: the brief and policies
263
+ * messages and callbacks). `versionsFor`: the workflow and policies
246
264
  * versions a run of this workflow starts under. */
247
265
  constructor(options: {
248
266
  execute: ExecuteRun;
249
267
  maxFinishedPerAgent?: number;
250
268
  onChange?: (run: WorkflowRun) => void | Promise<void>;
251
- versionsFor?: (agent: string, workflowId: string) => RunVersions | undefined;
269
+ versionsFor?: (agent: string, workflowId: string) => RunVersions | undefined | Promise<RunVersions | undefined>;
270
+ outputSchemaFor?: (agent: string, workflowId: string) => JsonSchema | undefined;
252
271
  });
253
272
  private versionsOf;
254
273
  private changed;
@@ -272,6 +291,12 @@ export declare class WorkflowRunner {
272
291
  /** How many runs are executing right now (for idle-shutdown checks). */
273
292
  get running(): number;
274
293
  private run;
294
+ /** A run's reply is in: done, unless its workflow has an output schema
295
+ * the reply doesn't match. Then the agent is told what's wrong and asked
296
+ * again in the same conversation, up to MAX_OUTPUT_RETRIES times in all
297
+ * (counted on the run, across pauses for approval), and the run fails
298
+ * if it still doesn't match. */
299
+ private complete;
275
300
  private finish;
276
301
  /** A paused run resumed after a decision (the server calls this from
277
302
  * its resolve path, for every resumed session): settle it, or record
@@ -23,6 +23,11 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, w
23
23
  import path from 'node:path';
24
24
  import { auditDb, recordEvent, retentionDays, schedulerDir } from './audit-store.js';
25
25
  import { KeyedMutex } from './session-store.js';
26
+ import { MAX_OUTPUT_RETRIES, checkOutput, outputRetryMessage } from './output-schema.js';
27
+ /** The workflow version a run ran under, whenever it was recorded. */
28
+ export function workflowVersionOf(run) {
29
+ return run.versions?.workflow ?? run.versions?.brief;
30
+ }
26
31
  const MAX_FINISHED_PER_AGENT = 500;
27
32
  const SESSION_PREFIX = 'run-';
28
33
  /** A scheduled task's sessions (core/scheduler.ts). */
@@ -291,23 +296,26 @@ export class WorkflowRunner {
291
296
  maxFinishedPerAgent;
292
297
  onChange;
293
298
  versionsFor;
299
+ /** The output schema a workflow's result must match, if it has one. */
300
+ outputSchemaFor;
294
301
  inFlight = new Set();
295
302
  /** `onChange`: called with the run when it starts, and each time it
296
303
  * finishes, fails or stops for a decision (the server sends its chat
297
- * messages and callbacks). `versionsFor`: the brief and policies
304
+ * messages and callbacks). `versionsFor`: the workflow and policies
298
305
  * versions a run of this workflow starts under. */
299
306
  constructor(options) {
300
307
  this.execute = options.execute;
308
+ this.outputSchemaFor = options.outputSchemaFor;
301
309
  this.maxFinishedPerAgent = options.maxFinishedPerAgent ?? MAX_FINISHED_PER_AGENT;
302
310
  this.onChange = options.onChange;
303
311
  this.versionsFor = options.versionsFor;
304
312
  }
305
- versionsOf(agent, workflowId) {
313
+ async versionsOf(agent, workflowId) {
306
314
  if (!this.versionsFor || !workflowId)
307
315
  return {};
308
316
  try {
309
- const versions = this.versionsFor(agent, workflowId);
310
- return versions && (versions.brief || versions.policies) ? { versions } : {};
317
+ const versions = await this.versionsFor(agent, workflowId);
318
+ return versions && (versions.workflow || versions.policies) ? { versions } : {};
311
319
  }
312
320
  catch (err) {
313
321
  console.error('[loopengine] could not note the versions a run starts under:', err);
@@ -338,7 +346,7 @@ export class WorkflowRunner {
338
346
  ...(input.trigger_id ? { trigger_id: input.trigger_id } : {}),
339
347
  ...(input.job ? { job: input.job } : {}),
340
348
  ...(input.chained_from ? { chained_from: input.chained_from, chain_depth: input.chain_depth ?? 1 } : {}),
341
- ...this.versionsOf(input.agent, input.workflow_id),
349
+ ...(await this.versionsOf(input.agent, input.workflow_id)),
342
350
  status: 'running',
343
351
  started_at: new Date().toISOString(),
344
352
  message: input.message,
@@ -369,7 +377,7 @@ export class WorkflowRunner {
369
377
  ...(input.decisions_to ? { decisions_to: input.decisions_to } : {}),
370
378
  ...(input.chat_notice ? { chat_notice: input.chat_notice } : {}),
371
379
  ...(input.warnings?.length ? { warnings: input.warnings } : {}),
372
- ...this.versionsOf(input.agent, input.workflow_id),
380
+ ...(await this.versionsOf(input.agent, input.workflow_id)),
373
381
  status: 'running',
374
382
  started_at: new Date().toISOString(),
375
383
  message: input.message,
@@ -380,11 +388,14 @@ export class WorkflowRunner {
380
388
  this.changed(run);
381
389
  try {
382
390
  const outcome = await this.execute(run.agent, run.message, run.session_id, { workflowId: run.workflow_id, ...(run.decisions_to ? { decisionsTo: run.decisions_to } : {}) });
383
- if (outcome.kind === 'pending')
391
+ if (outcome.kind === 'pending') {
384
392
  this.changed(await getRunStore().update(run.run_id, (r) => r && { ...r, status: 'awaiting_approval', pending_ids: outcome.pendingIds }));
385
- else
386
- await this.finish(run.run_id, { status: 'done', result: outcome.text });
387
- return outcome;
393
+ return outcome;
394
+ }
395
+ const ended = await this.complete(run, outcome.text);
396
+ if (ended.kind === 'failed')
397
+ throw new Error(ended.error);
398
+ return ended;
388
399
  }
389
400
  catch (err) {
390
401
  await this.finish(run.run_id, { status: 'error', error: err instanceof Error ? err.message : String(err) });
@@ -406,12 +417,46 @@ export class WorkflowRunner {
406
417
  this.changed(await getRunStore().update(run.run_id, (r) => r && { ...r, status: 'awaiting_approval', pending_ids: outcome.pendingIds }));
407
418
  return;
408
419
  }
409
- await this.finish(run.run_id, { status: 'done', result: outcome.text });
420
+ await this.complete(run, outcome.text);
410
421
  }
411
422
  catch (err) {
412
423
  await this.finish(run.run_id, { status: 'error', error: err instanceof Error ? err.message : String(err) });
413
424
  }
414
425
  }
426
+ /** A run's reply is in: done, unless its workflow has an output schema
427
+ * the reply doesn't match. Then the agent is told what's wrong and asked
428
+ * again in the same conversation, up to MAX_OUTPUT_RETRIES times in all
429
+ * (counted on the run, across pauses for approval), and the run fails
430
+ * if it still doesn't match. */
431
+ async complete(run, text) {
432
+ const schema = run.workflow_id ? this.outputSchemaFor?.(run.agent, run.workflow_id) : undefined;
433
+ if (!schema) {
434
+ await this.finish(run.run_id, { status: 'done', result: text });
435
+ return { kind: 'done', text };
436
+ }
437
+ let reply = text;
438
+ let retries = run.output_retries ?? 0;
439
+ for (;;) {
440
+ const check = checkOutput(schema, reply);
441
+ if (check.ok) {
442
+ await this.finish(run.run_id, { status: 'done', result: reply, output: check.value, output_errors: undefined });
443
+ return { kind: 'done', text: reply };
444
+ }
445
+ if (retries >= MAX_OUTPUT_RETRIES) {
446
+ const error = `The result didn't match the workflow's output schema${retries ? ` after ${retries === 1 ? 'one retry' : `${retries} retries`}` : ''}: ${check.errors.join('; ')}`;
447
+ await this.finish(run.run_id, { status: 'error', result: reply, error, output_errors: check.errors });
448
+ return { kind: 'failed', error };
449
+ }
450
+ retries++;
451
+ await getRunStore().update(run.run_id, (r) => r && { ...r, output_retries: retries, output_errors: check.errors });
452
+ const outcome = await this.execute(run.agent, outputRetryMessage(check.errors), run.session_id, { workflowId: run.workflow_id, ...(run.decisions_to ? { decisionsTo: run.decisions_to } : {}) });
453
+ if (outcome.kind === 'pending') {
454
+ this.changed(await getRunStore().update(run.run_id, (r) => r && { ...r, status: 'awaiting_approval', pending_ids: outcome.pendingIds }));
455
+ return outcome;
456
+ }
457
+ reply = outcome.text;
458
+ }
459
+ }
415
460
  async finish(runId, end) {
416
461
  this.changed(await getRunStore().update(runId, (r) => r && { ...r, ...end, pending_ids: undefined, finished_at: new Date().toISOString() }));
417
462
  }
@@ -426,7 +471,12 @@ export class WorkflowRunner {
426
471
  this.changed(await getRunStore().update(run.run_id, (r) => r && { ...r, status: 'awaiting_approval', pending_ids: outcome.pendingIds }));
427
472
  return;
428
473
  }
429
- await this.finish(run.run_id, { status: 'done', result: outcome.text });
474
+ try {
475
+ await this.complete(run, outcome.text);
476
+ }
477
+ catch (err) {
478
+ await this.finish(run.run_id, { status: 'error', error: err instanceof Error ? err.message : String(err) });
479
+ }
430
480
  }
431
481
  /** The run a session belongs to, if it's a workflow run's. */
432
482
  async forSession(sessionId) {