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.
- package/dist/core/audit-store.d.ts +71 -8
- package/dist/core/audit-store.js +206 -12
- package/dist/core/input-schema.d.ts +47 -0
- package/dist/core/input-schema.js +180 -0
- package/dist/core/output-schema.d.ts +30 -0
- package/dist/core/output-schema.js +105 -0
- package/dist/core/run-agent.js +35 -2
- package/dist/core/scheduler.d.ts +6 -0
- package/dist/core/scheduler.js +22 -16
- package/dist/core/system-agents/goal-planner.d.ts +3 -3
- package/dist/core/system-agents/goal-planner.js +9 -5
- package/dist/core/trace.d.ts +34 -0
- package/dist/core/trace.js +149 -0
- package/dist/core/workflow-runs.d.ts +30 -5
- package/dist/core/workflow-runs.js +62 -12
- package/dist/core/workflow-triggers.d.ts +8 -1
- package/dist/core/workflow-triggers.js +13 -0
- package/dist/core/workflows.d.ts +17 -1
- package/dist/core/workflows.js +72 -9
- package/dist/index.d.ts +6 -2
- package/dist/index.js +6 -2
- package/dist/web/agents-config-page.js +372 -67
- package/dist/web/audit-admin.d.ts +2 -2
- package/dist/web/audit-admin.js +5 -3
- package/dist/web/audit-page.js +7 -5
- package/dist/web/change-log.js +4 -2
- package/dist/web/console-shell.js +1 -1
- package/dist/web/decide-page.js +1 -1
- package/dist/web/goals-admin.d.ts +8 -5
- package/dist/web/goals-admin.js +25 -5
- package/dist/web/goals-page.js +28 -8
- package/dist/web/home-page.js +3 -3
- package/dist/web/inbox-page.js +143 -1
- package/dist/web/run-trace.d.ts +114 -0
- package/dist/web/run-trace.js +79 -0
- package/dist/web/upgrade-admin.js +19 -5
- package/dist/web/workflow-admin.d.ts +12 -3
- package/dist/web/workflow-admin.js +42 -7
- package/dist/web/workflow-audit-report.js +5 -5
- package/dist/web/workflow-audit.d.ts +3 -3
- package/dist/web/workflow-audit.js +12 -11
- package/dist/web/workflow-drafts.d.ts +75 -0
- package/dist/web/workflow-drafts.js +112 -0
- package/dist/web/workflow-evidence.d.ts +17 -4
- package/dist/web/workflow-evidence.js +22 -6
- package/dist/web/workflow-health.d.ts +2 -2
- package/dist/web/workflow-health.js +7 -1
- package/package.json +9 -1
|
@@ -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
|
|
59
|
-
*
|
|
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
|
-
|
|
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
|
|
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
|
|
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.
|
|
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
|
-
|
|
386
|
-
|
|
387
|
-
|
|
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.
|
|
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
|
-
|
|
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) {
|
|
@@ -25,7 +25,7 @@ export interface TriggerFilter {
|
|
|
25
25
|
/** Run only when the value there is one of these. */
|
|
26
26
|
values: string[];
|
|
27
27
|
}
|
|
28
|
-
export type TriggerOutcome = 'started' | 'filtered' | 'duplicate' | 'busy' | 'rejected' | 'invalid' | 'error';
|
|
28
|
+
export type TriggerOutcome = 'started' | 'filtered' | 'duplicate' | 'busy' | 'rejected' | 'invalid' | 'error' | 'not_live';
|
|
29
29
|
export interface TriggerDelivery {
|
|
30
30
|
at: string;
|
|
31
31
|
outcome: TriggerOutcome;
|
|
@@ -43,6 +43,10 @@ export interface WorkflowTrigger {
|
|
|
43
43
|
/** The token's start, to tell triggers apart: "whk_8f3k…". */
|
|
44
44
|
token_hint: string;
|
|
45
45
|
enabled: boolean;
|
|
46
|
+
/** Added in its workflow's draft (web/workflow-drafts.ts): its URL
|
|
47
|
+
* works, so the sender can be set up, but its calls don't start runs
|
|
48
|
+
* until the draft is published. */
|
|
49
|
+
draft?: true;
|
|
46
50
|
created_at: string;
|
|
47
51
|
verify?: TriggerVerify;
|
|
48
52
|
filter?: TriggerFilter;
|
|
@@ -149,6 +153,9 @@ export declare function createTrigger(agent: string, workflow: Workflow, input:
|
|
|
149
153
|
token: string;
|
|
150
154
|
}>;
|
|
151
155
|
export declare function updateTrigger(id: string, workflow: Workflow, input: TriggerSettings): Promise<WorkflowTrigger>;
|
|
156
|
+
/** A trigger's settings as checkTriggerSettings gave them, applied (a
|
|
157
|
+
* workflow draft's change to it, on publish). */
|
|
158
|
+
export declare function applyTriggerSettings(id: string, settings: Partial<WorkflowTrigger>): Promise<WorkflowTrigger>;
|
|
152
159
|
/** A new URL for a trigger; the old one stops working. */
|
|
153
160
|
export declare function rotateTrigger(id: string): Promise<{
|
|
154
161
|
trigger: WorkflowTrigger;
|
|
@@ -273,6 +273,19 @@ export async function updateTrigger(id, workflow, input) {
|
|
|
273
273
|
await getTriggerStore().put(next);
|
|
274
274
|
return next;
|
|
275
275
|
}
|
|
276
|
+
/** A trigger's settings as checkTriggerSettings gave them, applied (a
|
|
277
|
+
* workflow draft's change to it, on publish). */
|
|
278
|
+
export async function applyTriggerSettings(id, settings) {
|
|
279
|
+
const next = await getTriggerStore().update(id, (existing) => {
|
|
280
|
+
if (!existing)
|
|
281
|
+
return undefined;
|
|
282
|
+
const { verify: _v, filter: _f, mapping: _m, payload_param: _p, notify: _n, result_to_chat: _r, callback_url: _c, decisions_to: _d, chat_notice: _t, ...kept } = existing;
|
|
283
|
+
return { ...kept, ...settings };
|
|
284
|
+
});
|
|
285
|
+
if (!next)
|
|
286
|
+
throw new TriggerError(`no trigger ${id}`);
|
|
287
|
+
return next;
|
|
288
|
+
}
|
|
276
289
|
/** A new URL for a trigger; the old one stops working. */
|
|
277
290
|
export async function rotateTrigger(id) {
|
|
278
291
|
const token = newToken();
|
package/dist/core/workflows.d.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
import { type JsonSchema } from './output-schema.js';
|
|
2
|
+
import { type InputSpec } from './input-schema.js';
|
|
3
|
+
/** One of a workflow's inputs: what it is, whether a run must give it,
|
|
4
|
+
* and optionally its type and limits (core/input-schema.ts). */
|
|
5
|
+
export interface WorkflowParameter extends InputSpec {
|
|
2
6
|
description: string;
|
|
3
7
|
required: boolean;
|
|
4
8
|
}
|
|
@@ -31,6 +35,8 @@ export interface Workflow {
|
|
|
31
35
|
model?: WorkflowModel;
|
|
32
36
|
/** What its result must look like. */
|
|
33
37
|
output?: string;
|
|
38
|
+
/** A JSON Schema its result must match (core/output-schema.ts). */
|
|
39
|
+
outputSchema?: JsonSchema;
|
|
34
40
|
/** Where every run's updates, decisions and start notice go, however
|
|
35
41
|
* it starts. A webhook or API call with its own callback_url overrides
|
|
36
42
|
* the address and decisions for its run. */
|
|
@@ -63,6 +69,9 @@ export interface WorkflowFields {
|
|
|
63
69
|
/** null (or empty) clears it; left out keeps what's saved. */
|
|
64
70
|
model?: WorkflowModel | null;
|
|
65
71
|
output?: string | null;
|
|
72
|
+
/** A JSON Schema (object or its text); null clears it. Checked with
|
|
73
|
+
* checkOutputSchema: an invalid one throws OutputSchemaError. */
|
|
74
|
+
outputSchema?: unknown;
|
|
66
75
|
delivery?: WorkflowDelivery | null;
|
|
67
76
|
}
|
|
68
77
|
export declare class WorkflowParamsError extends Error {
|
|
@@ -80,6 +89,13 @@ export declare function readWorkflow(agentDir: string, id: string): Workflow | u
|
|
|
80
89
|
/** Makes a skill a workflow, or changes how its runs start. The skill must
|
|
81
90
|
* exist; its body and other front matter are kept. */
|
|
82
91
|
export declare function setWorkflowFields(agentDir: string, id: string, fields: WorkflowFields): void;
|
|
92
|
+
/** Renames a workflow or changes its description, nothing else: these
|
|
93
|
+
* don't change what its runs do, so they're saved straight away, never
|
|
94
|
+
* drafted. */
|
|
95
|
+
export declare function setWorkflowName(agentDir: string, id: string, input: {
|
|
96
|
+
title?: string;
|
|
97
|
+
description?: string;
|
|
98
|
+
}): void;
|
|
83
99
|
/** Stops a skill being a workflow. The skill itself stays. */
|
|
84
100
|
export declare function clearWorkflowFields(agentDir: string, id: string): void;
|
|
85
101
|
/** Checks a run's parameters against what the workflow declares: every
|
package/dist/core/workflows.js
CHANGED
|
@@ -28,7 +28,8 @@
|
|
|
28
28
|
//
|
|
29
29
|
// A workflow's contract can also set, in its front matter: `model` (its
|
|
30
30
|
// own provider and model, instead of the agent's), `output` (what its
|
|
31
|
-
// result must look like, said to the agent last)
|
|
31
|
+
// result must look like, said to the agent last), `output_schema` (a JSON
|
|
32
|
+
// Schema its result must match: core/output-schema.ts) and `delivery` (an app
|
|
32
33
|
// that gets every run's updates, and maybe its approvals and questions
|
|
33
34
|
// instead of the messaging app, and a message posted to the messaging app
|
|
34
35
|
// when a run starts):
|
|
@@ -51,13 +52,28 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFile
|
|
|
51
52
|
import { dirname, join } from 'node:path';
|
|
52
53
|
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
|
|
53
54
|
import { parseSkillFile } from './skillgarden/index.js';
|
|
55
|
+
import { checkOutputSchema, outputSchemaInstructions } from './output-schema.js';
|
|
56
|
+
import { checkInputValue, inputSpecFrom } from './input-schema.js';
|
|
54
57
|
export class WorkflowParamsError extends Error {
|
|
55
58
|
}
|
|
56
59
|
const PARAMETER_NAME = /^[a-z_][a-z0-9_]*$/;
|
|
57
60
|
const WORKFLOW_KEYS = ['workflow', 'title', 'start_message', 'trigger', 'parameters', 'original_request'];
|
|
58
61
|
/** The contract's keys: kept when a save doesn't give them. `gather`
|
|
59
62
|
* (lookups done before the agent, since removed) is dropped. */
|
|
60
|
-
const CONTRACT_KEYS = ['model', 'output', 'delivery', 'gather'];
|
|
63
|
+
const CONTRACT_KEYS = ['model', 'output', 'output_schema', 'delivery', 'gather'];
|
|
64
|
+
// A saved output schema that still checks out; one that doesn't is
|
|
65
|
+
// ignored (logged), so a bad edit to the file can't stop its runs.
|
|
66
|
+
function outputSchemaFrom(value) {
|
|
67
|
+
if (value === undefined || value === null)
|
|
68
|
+
return undefined;
|
|
69
|
+
try {
|
|
70
|
+
return checkOutputSchema(value);
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
console.error(`[loopengine] ignoring a workflow's output_schema: ${err instanceof Error ? err.message : String(err)}`);
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
61
77
|
function modelFrom(value) {
|
|
62
78
|
if (!value || typeof value !== 'object')
|
|
63
79
|
return undefined;
|
|
@@ -143,7 +159,7 @@ function parametersFrom(value) {
|
|
|
143
159
|
if (!PARAMETER_NAME.test(name))
|
|
144
160
|
continue;
|
|
145
161
|
const s = spec && typeof spec === 'object' ? spec : {};
|
|
146
|
-
parameters[name] = { description: typeof s.description === 'string' ? s.description : '', required: s.required === true };
|
|
162
|
+
parameters[name] = { description: typeof s.description === 'string' ? s.description : '', required: s.required === true, ...inputSpecFrom(name, s) };
|
|
147
163
|
}
|
|
148
164
|
return parameters;
|
|
149
165
|
}
|
|
@@ -174,6 +190,7 @@ function workflowFrom(id, frontmatter, body) {
|
|
|
174
190
|
instructions: combineInstructions(startMessage, body),
|
|
175
191
|
...(modelFrom(frontmatter.model) ? { model: modelFrom(frontmatter.model) } : {}),
|
|
176
192
|
...(typeof frontmatter.output === 'string' && frontmatter.output.trim() ? { output: frontmatter.output.trim() } : {}),
|
|
193
|
+
...(outputSchemaFrom(frontmatter.output_schema) ? { outputSchema: outputSchemaFrom(frontmatter.output_schema) } : {}),
|
|
177
194
|
...(deliveryFrom(frontmatter.delivery) ? { delivery: deliveryFrom(frontmatter.delivery) } : {}),
|
|
178
195
|
};
|
|
179
196
|
}
|
|
@@ -226,6 +243,12 @@ export function setWorkflowFields(agentDir, id, fields) {
|
|
|
226
243
|
else
|
|
227
244
|
delete frontmatter.output;
|
|
228
245
|
}
|
|
246
|
+
if (fields.outputSchema !== undefined) {
|
|
247
|
+
if (fields.outputSchema === null || fields.outputSchema === '')
|
|
248
|
+
delete frontmatter.output_schema;
|
|
249
|
+
else
|
|
250
|
+
frontmatter.output_schema = checkOutputSchema(fields.outputSchema);
|
|
251
|
+
}
|
|
229
252
|
if (fields.delivery !== undefined) {
|
|
230
253
|
const saved = deliveryFrontmatter(fields.delivery);
|
|
231
254
|
if (saved)
|
|
@@ -254,6 +277,21 @@ export function setWorkflowFields(agentDir, id, fields) {
|
|
|
254
277
|
...parameters,
|
|
255
278
|
}, skill.body);
|
|
256
279
|
}
|
|
280
|
+
/** Renames a workflow or changes its description, nothing else: these
|
|
281
|
+
* don't change what its runs do, so they're saved straight away, never
|
|
282
|
+
* drafted. */
|
|
283
|
+
export function setWorkflowName(agentDir, id, input) {
|
|
284
|
+
const path = skillPath(agentDir, id);
|
|
285
|
+
const skill = readSkillFile(path, id);
|
|
286
|
+
if (!skill)
|
|
287
|
+
throw new Error(`No workflow "${id}".`);
|
|
288
|
+
const frontmatter = { ...skill.frontmatter };
|
|
289
|
+
if (input.title?.trim())
|
|
290
|
+
frontmatter.title = input.title.trim();
|
|
291
|
+
if (input.description?.trim())
|
|
292
|
+
frontmatter.description = input.description.trim().replace(/\s+/g, ' ');
|
|
293
|
+
writeSkillFile(path, frontmatter, skill.body);
|
|
294
|
+
}
|
|
257
295
|
/** Stops a skill being a workflow. The skill itself stays. */
|
|
258
296
|
export function clearWorkflowFields(agentDir, id) {
|
|
259
297
|
const path = skillPath(agentDir, id);
|
|
@@ -275,21 +313,33 @@ export function validateParams(workflow, input) {
|
|
|
275
313
|
const given = (input ?? {});
|
|
276
314
|
const params = {};
|
|
277
315
|
const problems = [];
|
|
316
|
+
// Given but not valid: said once, not also as missing.
|
|
317
|
+
const invalid = new Set();
|
|
278
318
|
for (const [name, value] of Object.entries(given)) {
|
|
279
|
-
|
|
319
|
+
const spec = workflow.parameters[name];
|
|
320
|
+
if (!spec) {
|
|
280
321
|
problems.push(`unknown parameter "${name}"`);
|
|
281
322
|
continue;
|
|
282
323
|
}
|
|
283
324
|
if (value === undefined || value === null || value === '')
|
|
284
325
|
continue;
|
|
285
|
-
|
|
286
|
-
|
|
326
|
+
// Each value checked against its type and limits, and kept as text
|
|
327
|
+
// (core/input-schema.ts); an input with no type takes text.
|
|
328
|
+
const checked = checkInputValue(name, spec, value);
|
|
329
|
+
if (!checked.ok) {
|
|
330
|
+
problems.push(checked.error);
|
|
331
|
+
invalid.add(name);
|
|
287
332
|
continue;
|
|
288
333
|
}
|
|
289
|
-
params[name] =
|
|
334
|
+
params[name] = checked.text;
|
|
335
|
+
}
|
|
336
|
+
for (const [name, spec] of Object.entries(workflow.parameters)) {
|
|
337
|
+
if (params[name] !== undefined || invalid.has(name) || spec.default === undefined)
|
|
338
|
+
continue;
|
|
339
|
+
params[name] = typeof spec.default === 'string' ? spec.default : JSON.stringify(spec.default);
|
|
290
340
|
}
|
|
291
341
|
for (const [name, spec] of Object.entries(workflow.parameters)) {
|
|
292
|
-
if (spec.required && !params[name]?.trim())
|
|
342
|
+
if (spec.required && !invalid.has(name) && !params[name]?.trim())
|
|
293
343
|
problems.push(`"${name}" is required`);
|
|
294
344
|
}
|
|
295
345
|
if (problems.length) {
|
|
@@ -348,7 +398,19 @@ export function workflowRunMessage(workflow, params = {}, extras = {}) {
|
|
|
348
398
|
const start = workflow.startMessage ? fill(workflow.startMessage) : `Run the "${workflow.title}" workflow.`;
|
|
349
399
|
const steps = fill(workflow.steps).trim();
|
|
350
400
|
const order = [...new Set([...declared, ...Object.keys(params)])];
|
|
351
|
-
|
|
401
|
+
// A list or an object reads better laid out.
|
|
402
|
+
const shown = (name) => {
|
|
403
|
+
const type = workflow.parameters[name]?.type;
|
|
404
|
+
if (type !== 'object' && type !== 'array')
|
|
405
|
+
return params[name];
|
|
406
|
+
try {
|
|
407
|
+
return JSON.stringify(JSON.parse(params[name]), null, 2);
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
return params[name];
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
const inputs = order.filter((name) => params[name]?.trim()).map((name) => inputLine(name, shown(name), workflow.parameters[name]?.description));
|
|
352
414
|
const policies = extras.policies?.trim();
|
|
353
415
|
return [
|
|
354
416
|
start,
|
|
@@ -356,6 +418,7 @@ export function workflowRunMessage(workflow, params = {}, extras = {}) {
|
|
|
356
418
|
steps ? `${workflow.startMessage ? 'These are the steps' : 'These are its instructions'}, from your "${workflow.id}" skill:\n\n${steps}` : '',
|
|
357
419
|
policies ? `Your business's policies, shared by all its workflows (always follow them; this workflow's own instructions win where they say more):\n\n${policies}` : '',
|
|
358
420
|
workflow.output ? `Your result, the reply you end with, must be:\n${workflow.output}` : '',
|
|
421
|
+
workflow.outputSchema ? outputSchemaInstructions(workflow.outputSchema) : '',
|
|
359
422
|
].filter(Boolean).join('\n\n');
|
|
360
423
|
}
|
|
361
424
|
/** The workspace's shared policies: policies.md in the project, read on
|
package/dist/index.d.ts
CHANGED
|
@@ -98,8 +98,8 @@ export { WORKFLOW_EXAMPLES, workflowExample, type WorkflowExample } from './core
|
|
|
98
98
|
export { WORKFLOW_EXAMPLE_MESSAGES, type WorkflowExampleMessage } from './core/system-agents/workflow-example-messages.js';
|
|
99
99
|
export { createTrigger, updateTrigger, rotateTrigger, listTriggers, findTriggerByToken, publicTrigger, checkTriggerSettings, verifySenderSignature, parsePayload, valueAt, deliveryId, passesFilter, paramsFromPayload, checkRunDelivery, fillChatNotice, resultToChat, recordDelivery as recordTriggerDelivery, FileTriggerStore, getTriggerStore, setTriggerStore, TriggerError, type WorkflowTrigger, type PublicTrigger, type TriggerSettings, type TriggerVerify, type TriggerFilter, type TriggerSender, type SignatureAlgorithm, type TriggerDelivery, type TriggerOutcome, type TriggerStore } from './core/workflow-triggers.js';
|
|
100
100
|
export { checkCallbackUrl, callbackSecret, signCallback, deliverCallback, runCallbackPayload, isPrivateAddress, CallbackUrlError, type CallbackDelivery, type CallbackPending, type RunCallbackEvent } from './core/run-callbacks.js';
|
|
101
|
-
export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, eventHash, verifyEventChain, latestEventHash, type ChainCheck, readMeta, writeMeta, type EventFilter, noteVersion, listVersions, getVersion,
|
|
102
|
-
export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, searchRuns, type RunSearch, getRun, isUnderWay, RunError, type WorkflowRun, type WorkflowRunStatus, type RunVersions, type RunDecision, type RunStore, type ExecuteRun, type RunOutcome, type StartRunInput } from './core/workflow-runs.js';
|
|
101
|
+
export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, eventHash, verifyEventChain, latestEventHash, type ChainCheck, readMeta, writeMeta, type EventFilter, noteVersion, listVersions, getVersion, workflowContent, workflowFromContent, type WorkflowSnapshot, recordTraceSpan, recordTracePrompt, listTraceSpans, pruneTraces, type TraceSpan, retentionDays, type Version, type VersionKind, type AuditEvent, type AuditEventKind } from './core/audit-store.js';
|
|
102
|
+
export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, searchRuns, type RunSearch, getRun, isUnderWay, RunError, type WorkflowRun, type WorkflowRunStatus, type RunVersions, workflowVersionOf, type RunDecision, type RunStore, type ExecuteRun, type RunOutcome, type StartRunInput } from './core/workflow-runs.js';
|
|
103
103
|
export { readWorkflows, readWorkflow, setWorkflowFields, setWorkflowDelivery, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies, type Workflow, type WorkflowFields, type WorkflowParameter, type WorkflowModel, type WorkflowDelivery, type RunMessageExtras } from './core/workflows.js';
|
|
104
104
|
export { EvidenceError, evalCandidates, suggestedCriteria, type EvalCandidate, workflowScores, runFeedbackFrom, readEvals, addEvalCase, updateEvalCase, removeEvalCase, setEvalCriteria, effectiveCriteria, codeCheck, judgeCriteria, checkCase, roundSummary, draftCriteria, startEvalRound, EVAL_CRITERIA_PROMPT, DRAFT_CRITERIA_PROMPT, REFERENCE_CRITERION, type WorkflowScores, type EvalCase, type EvalCaseResult, type EvalCheck, type EvalCriterion, type CriterionKind, type EvalRound, type WorkflowEvals, type EvalRunDeps, type StandIn } from './web/workflow-evidence.js';
|
|
105
105
|
export { globalConfigPageHtml } from './web/global-config-page.js';
|
|
@@ -148,3 +148,7 @@ export { workflowsOverviewPageHtml } from './web/workflows-overview-page.js';
|
|
|
148
148
|
export { homeOverview, workflowsOverview, startsOf, type HomeOverview, type WorkflowsOverview, type WorkflowOverviewRow } from './web/workflows-overview.js';
|
|
149
149
|
export { homePageHtml } from './web/home-page.js';
|
|
150
150
|
export { listInbox, getInboxCase, timelineOf, RECENT_DAYS, type InboxView, type InboxDeps, type InboxItem, type InboxCase, type InboxPending, type InboxStep } from './web/inbox-admin.js';
|
|
151
|
+
export { startTurnTrace, type TurnTrace } from './core/trace.js';
|
|
152
|
+
export { buildRunTrace, type RunTrace, type TraceToolCall, type TraceStepEvent } from './web/run-trace.js';
|
|
153
|
+
export { checkOutputSchema, checkOutput, jsonInReply, outputSchemaInstructions, outputRetryMessage, MAX_OUTPUT_RETRIES, OutputSchemaError, type JsonSchema } from './core/output-schema.js';
|
|
154
|
+
export { checkInputSpec, checkInputValue, inputSchemaOf, INPUT_TYPES, INPUT_FORMATS, InputSpecError, type InputSpec, type InputType, type InputFormat } from './core/input-schema.js';
|
package/dist/index.js
CHANGED
|
@@ -91,8 +91,8 @@ export { WORKFLOW_EXAMPLES, workflowExample } from './core/system-agents/workflo
|
|
|
91
91
|
export { WORKFLOW_EXAMPLE_MESSAGES } from './core/system-agents/workflow-example-messages.js';
|
|
92
92
|
export { createTrigger, updateTrigger, rotateTrigger, listTriggers, findTriggerByToken, publicTrigger, checkTriggerSettings, verifySenderSignature, parsePayload, valueAt, deliveryId, passesFilter, paramsFromPayload, checkRunDelivery, fillChatNotice, resultToChat, recordDelivery as recordTriggerDelivery, FileTriggerStore, getTriggerStore, setTriggerStore, TriggerError } from './core/workflow-triggers.js';
|
|
93
93
|
export { checkCallbackUrl, callbackSecret, signCallback, deliverCallback, runCallbackPayload, isPrivateAddress, CallbackUrlError } from './core/run-callbacks.js';
|
|
94
|
-
export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, eventHash, verifyEventChain, latestEventHash, readMeta, writeMeta, noteVersion, listVersions, getVersion,
|
|
95
|
-
export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, searchRuns, getRun, isUnderWay, RunError } from './core/workflow-runs.js';
|
|
94
|
+
export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, eventHash, verifyEventChain, latestEventHash, readMeta, writeMeta, noteVersion, listVersions, getVersion, workflowContent, workflowFromContent, recordTraceSpan, recordTracePrompt, listTraceSpans, pruneTraces, retentionDays } from './core/audit-store.js';
|
|
95
|
+
export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, searchRuns, getRun, isUnderWay, RunError, workflowVersionOf } from './core/workflow-runs.js';
|
|
96
96
|
export { readWorkflows, readWorkflow, setWorkflowFields, setWorkflowDelivery, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies } from './core/workflows.js';
|
|
97
97
|
export { EvidenceError, evalCandidates, suggestedCriteria, workflowScores, runFeedbackFrom, readEvals, addEvalCase, updateEvalCase, removeEvalCase, setEvalCriteria, effectiveCriteria, codeCheck, judgeCriteria, checkCase, roundSummary, draftCriteria, startEvalRound, EVAL_CRITERIA_PROMPT, DRAFT_CRITERIA_PROMPT, REFERENCE_CRITERION } from './web/workflow-evidence.js';
|
|
98
98
|
export { globalConfigPageHtml } from './web/global-config-page.js';
|
|
@@ -139,3 +139,7 @@ export { workflowsOverviewPageHtml } from './web/workflows-overview-page.js';
|
|
|
139
139
|
export { homeOverview, workflowsOverview, startsOf } from './web/workflows-overview.js';
|
|
140
140
|
export { homePageHtml } from './web/home-page.js';
|
|
141
141
|
export { listInbox, getInboxCase, timelineOf, RECENT_DAYS } from './web/inbox-admin.js';
|
|
142
|
+
export { startTurnTrace } from './core/trace.js';
|
|
143
|
+
export { buildRunTrace } from './web/run-trace.js';
|
|
144
|
+
export { checkOutputSchema, checkOutput, jsonInReply, outputSchemaInstructions, outputRetryMessage, MAX_OUTPUT_RETRIES, OutputSchemaError } from './core/output-schema.js';
|
|
145
|
+
export { checkInputSpec, checkInputValue, inputSchemaOf, INPUT_TYPES, INPUT_FORMATS, InputSpecError } from './core/input-schema.js';
|