loopengine 0.3.101 → 0.4.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.
- package/dist/core/audit-store.d.ts +70 -0
- package/dist/core/audit-store.js +191 -0
- package/dist/core/workflow-runs.d.ts +76 -10
- package/dist/core/workflow-runs.js +175 -13
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/web/agents-config-page.js +74 -8
- package/dist/web/inbox-page.js +25 -4
- package/dist/web/workflow-evidence.d.ts +4 -0
- package/dist/web/workflow-evidence.js +1 -0
- package/package.json +3 -1
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
export type VersionKind = 'brief' | 'policies';
|
|
3
|
+
export interface Version {
|
|
4
|
+
number: number;
|
|
5
|
+
at: string;
|
|
6
|
+
by?: string;
|
|
7
|
+
reason?: string;
|
|
8
|
+
content: string;
|
|
9
|
+
}
|
|
10
|
+
export type AuditEventKind = 'decision' | 'answer' | 'feedback';
|
|
11
|
+
export interface AuditEvent {
|
|
12
|
+
id: number;
|
|
13
|
+
at: string;
|
|
14
|
+
agent: string;
|
|
15
|
+
workflow_id?: string;
|
|
16
|
+
run_id?: string;
|
|
17
|
+
kind: AuditEventKind;
|
|
18
|
+
by?: string;
|
|
19
|
+
data: Record<string, unknown>;
|
|
20
|
+
}
|
|
21
|
+
/** Opens (creating if need be) the database in `dir`. */
|
|
22
|
+
export declare function openAuditDb(dir: string): DatabaseSync | undefined;
|
|
23
|
+
export declare function schedulerDir(): string;
|
|
24
|
+
/** The process-wide database; undefined where node:sqlite isn't there,
|
|
25
|
+
* or LOOPENGINE_RUN_STORE=files asks for the JSON files. */
|
|
26
|
+
export declare function auditDb(): DatabaseSync | undefined;
|
|
27
|
+
/** Tests: use this database (or none). */
|
|
28
|
+
export declare function setAuditDb(next: DatabaseSync | undefined): void;
|
|
29
|
+
/** How long finished runs are kept, in days. */
|
|
30
|
+
export declare function retentionDays(): number;
|
|
31
|
+
/** Appends what someone did in or about a run. Never throws: the record
|
|
32
|
+
* must not stop the work it records. */
|
|
33
|
+
export declare function recordEvent(event: Omit<AuditEvent, 'id' | 'at'> & {
|
|
34
|
+
at?: string;
|
|
35
|
+
}, database?: DatabaseSync | undefined): void;
|
|
36
|
+
/** A run's events, oldest first. */
|
|
37
|
+
export declare function runEvents(runId: string, database?: DatabaseSync | undefined): AuditEvent[];
|
|
38
|
+
/** The version number of `content`: the latest version's when it's the
|
|
39
|
+
* same text, else a new version noted now. Undefined without a database.
|
|
40
|
+
* `agent` and `workflowId` are '' for the workspace's policies. */
|
|
41
|
+
export declare function noteVersion(key: {
|
|
42
|
+
agent: string;
|
|
43
|
+
workflowId: string;
|
|
44
|
+
kind: VersionKind;
|
|
45
|
+
}, content: string, about?: {
|
|
46
|
+
by?: string;
|
|
47
|
+
reason?: string;
|
|
48
|
+
}, database?: DatabaseSync | undefined): number | undefined;
|
|
49
|
+
/** Every version, newest first. */
|
|
50
|
+
export declare function listVersions(key: {
|
|
51
|
+
agent: string;
|
|
52
|
+
workflowId: string;
|
|
53
|
+
kind: VersionKind;
|
|
54
|
+
}, database?: DatabaseSync | undefined): Version[];
|
|
55
|
+
export declare function getVersion(key: {
|
|
56
|
+
agent: string;
|
|
57
|
+
workflowId: string;
|
|
58
|
+
kind: VersionKind;
|
|
59
|
+
}, number: number, database?: DatabaseSync | undefined): Version | undefined;
|
|
60
|
+
/** What a workflow's brief version holds: its instructions and the
|
|
61
|
+
* result format, as one text (the format under a heading). */
|
|
62
|
+
export declare function briefContent(workflow: {
|
|
63
|
+
instructions: string;
|
|
64
|
+
output?: string;
|
|
65
|
+
}): string;
|
|
66
|
+
/** The instructions and result format a brief version holds. */
|
|
67
|
+
export declare function briefFromContent(content: string): {
|
|
68
|
+
instructions: string;
|
|
69
|
+
output?: string;
|
|
70
|
+
};
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// The workspace's record of what its workflows did and what they ran
|
|
2
|
+
// under: one SQLite file, `<LOOPENGINE_SCHEDULER_DIR or .scheduler>/loopengine.db`,
|
|
3
|
+
// beside the scheduler's own files. It holds
|
|
4
|
+
//
|
|
5
|
+
// - runs: every workflow run (core/workflow-runs.ts's SqliteRunStore),
|
|
6
|
+
// kept for LOOPENGINE_RETENTION_DAYS (400 by default) rather than the
|
|
7
|
+
// latest 500 per agent the console lists;
|
|
8
|
+
// - events: what people did in or about a run (an approval decided, with
|
|
9
|
+
// the tool's input before and after a change and any reason; a question
|
|
10
|
+
// answered; feedback on the result), appended and never changed;
|
|
11
|
+
// - versions: each workflow's brief (its instructions and result format)
|
|
12
|
+
// and the workspace's shared policies, numbered. A new version is noted
|
|
13
|
+
// whenever the text differs from the latest, however it changed: saved
|
|
14
|
+
// in the console, restored, or edited in the file.
|
|
15
|
+
//
|
|
16
|
+
// It uses node:sqlite, built into Node 22.5 and later. Where that's
|
|
17
|
+
// missing, auditDb() is undefined: runs stay in JSON files and nothing is
|
|
18
|
+
// versioned.
|
|
19
|
+
import { createHash } from 'node:crypto';
|
|
20
|
+
import { mkdirSync } from 'node:fs';
|
|
21
|
+
import { createRequire } from 'node:module';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
const SCHEMA = `
|
|
24
|
+
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
25
|
+
CREATE TABLE IF NOT EXISTS runs (
|
|
26
|
+
run_id TEXT PRIMARY KEY,
|
|
27
|
+
agent TEXT NOT NULL,
|
|
28
|
+
workflow_id TEXT NOT NULL,
|
|
29
|
+
status TEXT NOT NULL,
|
|
30
|
+
started_at TEXT NOT NULL,
|
|
31
|
+
finished_at TEXT,
|
|
32
|
+
session_id TEXT NOT NULL,
|
|
33
|
+
data TEXT NOT NULL
|
|
34
|
+
);
|
|
35
|
+
CREATE INDEX IF NOT EXISTS runs_agent ON runs (agent, workflow_id, started_at);
|
|
36
|
+
CREATE INDEX IF NOT EXISTS runs_session ON runs (session_id);
|
|
37
|
+
CREATE INDEX IF NOT EXISTS runs_finished ON runs (finished_at);
|
|
38
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
39
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
40
|
+
at TEXT NOT NULL,
|
|
41
|
+
agent TEXT NOT NULL,
|
|
42
|
+
workflow_id TEXT,
|
|
43
|
+
run_id TEXT,
|
|
44
|
+
kind TEXT NOT NULL,
|
|
45
|
+
by TEXT,
|
|
46
|
+
data TEXT NOT NULL
|
|
47
|
+
);
|
|
48
|
+
CREATE INDEX IF NOT EXISTS events_run ON events (run_id);
|
|
49
|
+
CREATE INDEX IF NOT EXISTS events_workflow ON events (agent, workflow_id, at);
|
|
50
|
+
CREATE TABLE IF NOT EXISTS versions (
|
|
51
|
+
agent TEXT NOT NULL,
|
|
52
|
+
workflow_id TEXT NOT NULL,
|
|
53
|
+
kind TEXT NOT NULL,
|
|
54
|
+
number INTEGER NOT NULL,
|
|
55
|
+
hash TEXT NOT NULL,
|
|
56
|
+
content TEXT NOT NULL,
|
|
57
|
+
at TEXT NOT NULL,
|
|
58
|
+
by TEXT,
|
|
59
|
+
reason TEXT,
|
|
60
|
+
PRIMARY KEY (agent, workflow_id, kind, number)
|
|
61
|
+
);
|
|
62
|
+
`;
|
|
63
|
+
// node:sqlite, or undefined on a Node without it. Node 22 marks it
|
|
64
|
+
// experimental and says so once on load; that warning is dropped here.
|
|
65
|
+
function loadSqlite() {
|
|
66
|
+
const emit = process.emitWarning;
|
|
67
|
+
process.emitWarning = ((warning, ...rest) => {
|
|
68
|
+
if (/SQLite/i.test(typeof warning === 'string' ? warning : warning.message))
|
|
69
|
+
return;
|
|
70
|
+
return emit.call(process, warning, ...rest);
|
|
71
|
+
});
|
|
72
|
+
try {
|
|
73
|
+
return createRequire(import.meta.url)('node:sqlite');
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
process.emitWarning = emit;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/** Opens (creating if need be) the database in `dir`. */
|
|
83
|
+
export function openAuditDb(dir) {
|
|
84
|
+
const sqlite = loadSqlite();
|
|
85
|
+
if (!sqlite)
|
|
86
|
+
return undefined;
|
|
87
|
+
mkdirSync(dir, { recursive: true });
|
|
88
|
+
const db = new sqlite.DatabaseSync(path.join(dir, 'loopengine.db'));
|
|
89
|
+
db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;');
|
|
90
|
+
db.exec(SCHEMA);
|
|
91
|
+
return db;
|
|
92
|
+
}
|
|
93
|
+
let db;
|
|
94
|
+
export function schedulerDir() {
|
|
95
|
+
return process.env.LOOPENGINE_SCHEDULER_DIR || path.join(process.cwd(), '.scheduler');
|
|
96
|
+
}
|
|
97
|
+
/** The process-wide database; undefined where node:sqlite isn't there,
|
|
98
|
+
* or LOOPENGINE_RUN_STORE=files asks for the JSON files. */
|
|
99
|
+
export function auditDb() {
|
|
100
|
+
if (db === undefined)
|
|
101
|
+
db = process.env.LOOPENGINE_RUN_STORE === 'files' ? null : (openAuditDb(schedulerDir()) ?? null);
|
|
102
|
+
return db ?? undefined;
|
|
103
|
+
}
|
|
104
|
+
/** Tests: use this database (or none). */
|
|
105
|
+
export function setAuditDb(next) {
|
|
106
|
+
db = next ?? null;
|
|
107
|
+
}
|
|
108
|
+
/** How long finished runs are kept, in days. */
|
|
109
|
+
export function retentionDays() {
|
|
110
|
+
const n = Number(process.env.LOOPENGINE_RETENTION_DAYS);
|
|
111
|
+
return Number.isFinite(n) && n > 0 ? n : 400;
|
|
112
|
+
}
|
|
113
|
+
// ---------- events ----------
|
|
114
|
+
/** Appends what someone did in or about a run. Never throws: the record
|
|
115
|
+
* must not stop the work it records. */
|
|
116
|
+
export function recordEvent(event, database = auditDb()) {
|
|
117
|
+
if (!database)
|
|
118
|
+
return;
|
|
119
|
+
try {
|
|
120
|
+
database.prepare('INSERT INTO events (at, agent, workflow_id, run_id, kind, by, data) VALUES (?, ?, ?, ?, ?, ?, ?)').run(event.at ?? new Date().toISOString(), event.agent, event.workflow_id ?? null, event.run_id ?? null, event.kind, event.by ?? null, JSON.stringify(event.data));
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
console.error('[loopengine] could not record an audit event:', err);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/** A run's events, oldest first. */
|
|
127
|
+
export function runEvents(runId, database = auditDb()) {
|
|
128
|
+
if (!database)
|
|
129
|
+
return [];
|
|
130
|
+
const rows = database.prepare('SELECT * FROM events WHERE run_id = ? ORDER BY id').all(runId);
|
|
131
|
+
return rows.map((r) => ({
|
|
132
|
+
id: Number(r.id),
|
|
133
|
+
at: String(r.at),
|
|
134
|
+
agent: String(r.agent),
|
|
135
|
+
...(r.workflow_id ? { workflow_id: String(r.workflow_id) } : {}),
|
|
136
|
+
...(r.run_id ? { run_id: String(r.run_id) } : {}),
|
|
137
|
+
kind: String(r.kind),
|
|
138
|
+
...(r.by ? { by: String(r.by) } : {}),
|
|
139
|
+
data: JSON.parse(String(r.data)),
|
|
140
|
+
}));
|
|
141
|
+
}
|
|
142
|
+
// ---------- versions ----------
|
|
143
|
+
const hashOf = (content) => createHash('sha256').update(content).digest('hex');
|
|
144
|
+
/** The version number of `content`: the latest version's when it's the
|
|
145
|
+
* same text, else a new version noted now. Undefined without a database.
|
|
146
|
+
* `agent` and `workflowId` are '' for the workspace's policies. */
|
|
147
|
+
export function noteVersion(key, content, about = {}, database = auditDb()) {
|
|
148
|
+
if (!database)
|
|
149
|
+
return undefined;
|
|
150
|
+
try {
|
|
151
|
+
const hash = hashOf(content);
|
|
152
|
+
const latest = database.prepare('SELECT number, hash FROM versions WHERE agent = ? AND workflow_id = ? AND kind = ? ORDER BY number DESC LIMIT 1')
|
|
153
|
+
.get(key.agent, key.workflowId, key.kind);
|
|
154
|
+
if (latest && latest.hash === hash)
|
|
155
|
+
return Number(latest.number);
|
|
156
|
+
const number = (latest ? Number(latest.number) : 0) + 1;
|
|
157
|
+
database.prepare('INSERT INTO versions (agent, workflow_id, kind, number, hash, content, at, by, reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)').run(key.agent, key.workflowId, key.kind, number, hash, content, new Date().toISOString(), about.by ?? null, about.reason ?? (latest ? 'Changed outside the console' : 'First version'));
|
|
158
|
+
return number;
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
console.error('[loopengine] could not note a version:', err);
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/** Every version, newest first. */
|
|
166
|
+
export function listVersions(key, database = auditDb()) {
|
|
167
|
+
if (!database)
|
|
168
|
+
return [];
|
|
169
|
+
const rows = database.prepare('SELECT number, at, by, reason, content FROM versions WHERE agent = ? AND workflow_id = ? AND kind = ? ORDER BY number DESC')
|
|
170
|
+
.all(key.agent, key.workflowId, key.kind);
|
|
171
|
+
return rows.map((r) => ({
|
|
172
|
+
number: Number(r.number),
|
|
173
|
+
at: String(r.at),
|
|
174
|
+
...(r.by ? { by: String(r.by) } : {}),
|
|
175
|
+
...(r.reason ? { reason: String(r.reason) } : {}),
|
|
176
|
+
content: String(r.content),
|
|
177
|
+
}));
|
|
178
|
+
}
|
|
179
|
+
export function getVersion(key, number, database = auditDb()) {
|
|
180
|
+
return listVersions(key, database).find((v) => v.number === number);
|
|
181
|
+
}
|
|
182
|
+
/** What a workflow's brief version holds: its instructions and the
|
|
183
|
+
* result format, as one text (the format under a heading). */
|
|
184
|
+
export function briefContent(workflow) {
|
|
185
|
+
return workflow.output?.trim() ? `${workflow.instructions}\n\n## Result format\n\n${workflow.output.trim()}` : workflow.instructions;
|
|
186
|
+
}
|
|
187
|
+
/** The instructions and result format a brief version holds. */
|
|
188
|
+
export function briefFromContent(content) {
|
|
189
|
+
const at = content.lastIndexOf('\n\n## Result format\n\n');
|
|
190
|
+
return at < 0 ? { instructions: content } : { instructions: content.slice(0, at), output: content.slice(at + '\n\n## Result format\n\n'.length) };
|
|
191
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
1
2
|
import type { CallbackDelivery } from './run-callbacks.js';
|
|
2
3
|
export type WorkflowRunStatus = 'running' | 'awaiting_approval' | 'done' | 'error';
|
|
3
4
|
export interface WorkflowRun {
|
|
@@ -54,15 +55,12 @@ export interface WorkflowRun {
|
|
|
54
55
|
warnings?: string[];
|
|
55
56
|
/** Each callback delivery, oldest first (the latest 10). */
|
|
56
57
|
callbacks?: CallbackDelivery[];
|
|
58
|
+
/** The brief and shared policies it ran under (core/audit-store.ts's
|
|
59
|
+
* versions), when the workspace keeps versions. */
|
|
60
|
+
versions?: RunVersions;
|
|
57
61
|
/** Each approval decided while it ran, oldest first, with who decided
|
|
58
62
|
* (an email, or a chat name) when known. */
|
|
59
|
-
decisions?:
|
|
60
|
-
tool: string;
|
|
61
|
-
approved: boolean;
|
|
62
|
-
at: string;
|
|
63
|
-
by?: string;
|
|
64
|
-
edited?: boolean;
|
|
65
|
-
}[];
|
|
63
|
+
decisions?: RunDecision[];
|
|
66
64
|
/** Each question it asked that was answered, oldest first. */
|
|
67
65
|
answers?: {
|
|
68
66
|
question: string;
|
|
@@ -75,6 +73,23 @@ export interface WorkflowRun {
|
|
|
75
73
|
* much it was edited from the result, and a verdict. */
|
|
76
74
|
feedback?: RunFeedback;
|
|
77
75
|
}
|
|
76
|
+
export interface RunVersions {
|
|
77
|
+
brief?: number;
|
|
78
|
+
policies?: number;
|
|
79
|
+
}
|
|
80
|
+
export interface RunDecision {
|
|
81
|
+
tool: string;
|
|
82
|
+
approved: boolean;
|
|
83
|
+
at: string;
|
|
84
|
+
by?: string;
|
|
85
|
+
edited?: boolean;
|
|
86
|
+
/** For an approval changed before it ran: the input the agent asked
|
|
87
|
+
* for, and what ran instead. */
|
|
88
|
+
before?: unknown;
|
|
89
|
+
after?: unknown;
|
|
90
|
+
/** Why it was denied, when the person said. */
|
|
91
|
+
reason?: string;
|
|
92
|
+
}
|
|
78
93
|
export interface RunFeedback {
|
|
79
94
|
verdict?: 'good' | 'bad';
|
|
80
95
|
/** How far the text actually used is from the result. */
|
|
@@ -104,6 +119,15 @@ export interface RunStore {
|
|
|
104
119
|
put(run: WorkflowRun): Promise<void>;
|
|
105
120
|
remove(runId: string): Promise<void>;
|
|
106
121
|
update(runId: string, fn: (run: WorkflowRun | undefined) => WorkflowRun | undefined): Promise<WorkflowRun | undefined>;
|
|
122
|
+
/** An agent's runs, newest first, without reading every run. */
|
|
123
|
+
forAgent?(agent: string, filter: {
|
|
124
|
+
workflowId?: string;
|
|
125
|
+
limit?: number;
|
|
126
|
+
}): Promise<WorkflowRun[]>;
|
|
127
|
+
/** The run with this session, without reading every run. */
|
|
128
|
+
bySession?(sessionId: string): Promise<WorkflowRun | undefined>;
|
|
129
|
+
/** Drops what's past keeping, instead of the runner's per-agent cap. */
|
|
130
|
+
prune?(): Promise<void>;
|
|
107
131
|
}
|
|
108
132
|
/** One JSON file per run under `<dir>/runs/` — one server process. */
|
|
109
133
|
export declare class FileRunStore implements RunStore {
|
|
@@ -116,7 +140,38 @@ export declare class FileRunStore implements RunStore {
|
|
|
116
140
|
remove(runId: string): Promise<void>;
|
|
117
141
|
update(runId: string, fn: (run: WorkflowRun | undefined) => WorkflowRun | undefined): Promise<WorkflowRun | undefined>;
|
|
118
142
|
}
|
|
119
|
-
/**
|
|
143
|
+
/** Runs in the workspace's database (core/audit-store.ts). list() is what
|
|
144
|
+
* the console shows: every run under way, and each agent's latest
|
|
145
|
+
* `listed` finished ones; older runs stay until the retention period
|
|
146
|
+
* ends. */
|
|
147
|
+
export declare class SqliteRunStore implements RunStore {
|
|
148
|
+
private readonly db;
|
|
149
|
+
private readonly listed;
|
|
150
|
+
private lastPrune;
|
|
151
|
+
/** `importFrom`: a scheduler folder whose runs/ JSON files are copied in
|
|
152
|
+
* the first time. */
|
|
153
|
+
constructor(db: DatabaseSync, options?: {
|
|
154
|
+
importFrom?: string;
|
|
155
|
+
listed?: number;
|
|
156
|
+
});
|
|
157
|
+
private importFiles;
|
|
158
|
+
private write;
|
|
159
|
+
private read;
|
|
160
|
+
list(): Promise<WorkflowRun[]>;
|
|
161
|
+
forAgent(agent: string, filter: {
|
|
162
|
+
workflowId?: string;
|
|
163
|
+
limit?: number;
|
|
164
|
+
}): Promise<WorkflowRun[]>;
|
|
165
|
+
bySession(sessionId: string): Promise<WorkflowRun | undefined>;
|
|
166
|
+
get(runId: string): Promise<WorkflowRun | undefined>;
|
|
167
|
+
put(run: WorkflowRun): Promise<void>;
|
|
168
|
+
remove(runId: string): Promise<void>;
|
|
169
|
+
update(runId: string, fn: (run: WorkflowRun | undefined) => WorkflowRun | undefined): Promise<WorkflowRun | undefined>;
|
|
170
|
+
/** At most hourly: runs finished before the retention period. */
|
|
171
|
+
prune(): Promise<void>;
|
|
172
|
+
}
|
|
173
|
+
/** The process-wide store: the workspace's database, or JSON files in
|
|
174
|
+
* `runs/` in the scheduler's folder where there's none. */
|
|
120
175
|
export declare function getRunStore(): RunStore;
|
|
121
176
|
export declare function setRunStore(next: RunStore): void;
|
|
122
177
|
/** An agent's runs, newest first; of one workflow when `workflowId` is given. */
|
|
@@ -150,15 +205,19 @@ export declare class WorkflowRunner {
|
|
|
150
205
|
private readonly execute;
|
|
151
206
|
private readonly maxFinishedPerAgent;
|
|
152
207
|
private readonly onChange?;
|
|
208
|
+
private readonly versionsFor?;
|
|
153
209
|
private readonly inFlight;
|
|
154
210
|
/** `onChange`: called with the run when it starts, and each time it
|
|
155
211
|
* finishes, fails or stops for a decision (the server sends its chat
|
|
156
|
-
* messages and callbacks).
|
|
212
|
+
* messages and callbacks). `versionsFor`: the brief and policies
|
|
213
|
+
* versions a run of this workflow starts under. */
|
|
157
214
|
constructor(options: {
|
|
158
215
|
execute: ExecuteRun;
|
|
159
216
|
maxFinishedPerAgent?: number;
|
|
160
217
|
onChange?: (run: WorkflowRun) => void | Promise<void>;
|
|
218
|
+
versionsFor?: (agent: string, workflowId: string) => RunVersions | undefined;
|
|
161
219
|
});
|
|
220
|
+
private versionsOf;
|
|
162
221
|
private changed;
|
|
163
222
|
/** Records a run and starts it; returns at once with the record. */
|
|
164
223
|
start(input: StartRunInput): Promise<WorkflowRun>;
|
|
@@ -190,13 +249,20 @@ export declare class WorkflowRunner {
|
|
|
190
249
|
}): Promise<void>;
|
|
191
250
|
/** The run a session belongs to, if it's a workflow run's. */
|
|
192
251
|
forSession(sessionId: string): Promise<WorkflowRun | undefined>;
|
|
193
|
-
/** Records an approval decided in a run's session
|
|
252
|
+
/** Records an approval decided in a run's session: on the run, and in
|
|
253
|
+
* the workspace's audit events. */
|
|
194
254
|
recordDecision(sessionId: string, decision: {
|
|
195
255
|
tool: string;
|
|
196
256
|
approved: boolean;
|
|
197
257
|
by?: string;
|
|
198
258
|
edited?: boolean;
|
|
259
|
+
before?: unknown;
|
|
260
|
+
after?: unknown;
|
|
261
|
+
reason?: string;
|
|
199
262
|
}): Promise<void>;
|
|
263
|
+
/** Records feedback given on a run's result in the audit events (the
|
|
264
|
+
* run itself carries the latest). */
|
|
265
|
+
recordFeedback(run: WorkflowRun, feedback: RunFeedback, by?: string): void;
|
|
200
266
|
/** Records a question answered in a run's session. */
|
|
201
267
|
recordAnswer(sessionId: string, answer: {
|
|
202
268
|
question: string;
|
|
@@ -12,13 +12,16 @@
|
|
|
12
12
|
// run that pauses there is settled by settleFromResume once someone
|
|
13
13
|
// decides.
|
|
14
14
|
//
|
|
15
|
-
// Stored
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
15
|
+
// Stored in the workspace's database (core/audit-store.ts), kept for
|
|
16
|
+
// its retention period; the console lists each agent's latest
|
|
17
|
+
// MAX_FINISHED_PER_AGENT finished runs. Where there's no database (no
|
|
18
|
+
// node:sqlite), one JSON file per run under
|
|
19
|
+
// `<LOOPENGINE_SCHEDULER_DIR or .scheduler>/runs/`, keeping only those.
|
|
20
|
+
// Runs already in files are copied into the database once.
|
|
19
21
|
import { randomUUID } from 'node:crypto';
|
|
20
22
|
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
21
23
|
import path from 'node:path';
|
|
24
|
+
import { auditDb, recordEvent, retentionDays, schedulerDir } from './audit-store.js';
|
|
22
25
|
import { KeyedMutex } from './session-store.js';
|
|
23
26
|
const MAX_FINISHED_PER_AGENT = 500;
|
|
24
27
|
const SESSION_PREFIX = 'run-';
|
|
@@ -76,10 +79,119 @@ export class FileRunStore {
|
|
|
76
79
|
});
|
|
77
80
|
}
|
|
78
81
|
}
|
|
82
|
+
const UNDER_WAY = "('running', 'awaiting_approval')";
|
|
83
|
+
/** Runs in the workspace's database (core/audit-store.ts). list() is what
|
|
84
|
+
* the console shows: every run under way, and each agent's latest
|
|
85
|
+
* `listed` finished ones; older runs stay until the retention period
|
|
86
|
+
* ends. */
|
|
87
|
+
export class SqliteRunStore {
|
|
88
|
+
db;
|
|
89
|
+
listed;
|
|
90
|
+
lastPrune = 0;
|
|
91
|
+
/** `importFrom`: a scheduler folder whose runs/ JSON files are copied in
|
|
92
|
+
* the first time. */
|
|
93
|
+
constructor(db, options = {}) {
|
|
94
|
+
this.db = db;
|
|
95
|
+
this.listed = options.listed ?? MAX_FINISHED_PER_AGENT;
|
|
96
|
+
if (options.importFrom)
|
|
97
|
+
this.importFiles(options.importFrom);
|
|
98
|
+
}
|
|
99
|
+
importFiles(dir) {
|
|
100
|
+
const done = this.db.prepare("SELECT value FROM meta WHERE key = 'runs_imported'").get();
|
|
101
|
+
if (done)
|
|
102
|
+
return;
|
|
103
|
+
const runsDir = path.join(dir, 'runs');
|
|
104
|
+
let count = 0;
|
|
105
|
+
if (existsSync(runsDir)) {
|
|
106
|
+
this.db.exec('BEGIN');
|
|
107
|
+
try {
|
|
108
|
+
for (const name of readdirSync(runsDir)) {
|
|
109
|
+
if (!name.endsWith('.json'))
|
|
110
|
+
continue;
|
|
111
|
+
try {
|
|
112
|
+
const run = JSON.parse(readFileSync(path.join(runsDir, name), 'utf8'));
|
|
113
|
+
if (run.run_id && run.agent) {
|
|
114
|
+
this.write(run, 'OR IGNORE');
|
|
115
|
+
count++;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
// Not a run: skip it.
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
this.db.exec('COMMIT');
|
|
123
|
+
}
|
|
124
|
+
catch (err) {
|
|
125
|
+
this.db.exec('ROLLBACK');
|
|
126
|
+
throw err;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// The files stay, untouched, as they were.
|
|
130
|
+
this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('runs_imported', ?)").run(`${new Date().toISOString()} ${count}`);
|
|
131
|
+
}
|
|
132
|
+
write(run, conflict = 'OR REPLACE') {
|
|
133
|
+
this.db.prepare(`INSERT ${conflict} INTO runs (run_id, agent, workflow_id, status, started_at, finished_at, session_id, data) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
134
|
+
.run(run.run_id, run.agent, run.workflow_id ?? '', run.status, run.started_at, run.finished_at ?? null, run.session_id ?? '', JSON.stringify(run));
|
|
135
|
+
}
|
|
136
|
+
read(row) {
|
|
137
|
+
return JSON.parse(String(row.data));
|
|
138
|
+
}
|
|
139
|
+
async list() {
|
|
140
|
+
const rows = this.db.prepare(`
|
|
141
|
+
SELECT data, started_at FROM runs WHERE status IN ${UNDER_WAY}
|
|
142
|
+
UNION ALL
|
|
143
|
+
SELECT data, started_at FROM (
|
|
144
|
+
SELECT data, started_at, ROW_NUMBER() OVER (PARTITION BY agent ORDER BY started_at DESC) AS n
|
|
145
|
+
FROM runs WHERE status NOT IN ${UNDER_WAY}
|
|
146
|
+
) WHERE n <= ?
|
|
147
|
+
ORDER BY started_at DESC`).all(this.listed);
|
|
148
|
+
return rows.map((r) => this.read(r));
|
|
149
|
+
}
|
|
150
|
+
async forAgent(agent, filter) {
|
|
151
|
+
const limit = Math.min(filter.limit ?? this.listed, this.listed);
|
|
152
|
+
const rows = filter.workflowId
|
|
153
|
+
? this.db.prepare('SELECT data FROM runs WHERE agent = ? AND workflow_id = ? ORDER BY started_at DESC LIMIT ?').all(agent, filter.workflowId, limit)
|
|
154
|
+
: this.db.prepare('SELECT data FROM runs WHERE agent = ? ORDER BY started_at DESC LIMIT ?').all(agent, limit);
|
|
155
|
+
return rows.map((r) => this.read(r));
|
|
156
|
+
}
|
|
157
|
+
async bySession(sessionId) {
|
|
158
|
+
const row = this.db.prepare('SELECT data FROM runs WHERE session_id = ? ORDER BY started_at DESC LIMIT 1').get(sessionId);
|
|
159
|
+
return row ? this.read(row) : undefined;
|
|
160
|
+
}
|
|
161
|
+
async get(runId) {
|
|
162
|
+
const row = this.db.prepare('SELECT data FROM runs WHERE run_id = ?').get(runId);
|
|
163
|
+
return row ? this.read(row) : undefined;
|
|
164
|
+
}
|
|
165
|
+
async put(run) {
|
|
166
|
+
this.write(run);
|
|
167
|
+
}
|
|
168
|
+
async remove(runId) {
|
|
169
|
+
this.db.prepare('DELETE FROM runs WHERE run_id = ?').run(runId);
|
|
170
|
+
}
|
|
171
|
+
// node:sqlite is synchronous, so read-change-write here can't interleave.
|
|
172
|
+
async update(runId, fn) {
|
|
173
|
+
const next = fn(await this.get(runId));
|
|
174
|
+
if (next)
|
|
175
|
+
this.write(next);
|
|
176
|
+
return next;
|
|
177
|
+
}
|
|
178
|
+
/** At most hourly: runs finished before the retention period. */
|
|
179
|
+
async prune() {
|
|
180
|
+
if (Date.now() - this.lastPrune < 60 * 60 * 1000)
|
|
181
|
+
return;
|
|
182
|
+
this.lastPrune = Date.now();
|
|
183
|
+
const before = new Date(Date.now() - retentionDays() * 24 * 60 * 60 * 1000).toISOString();
|
|
184
|
+
this.db.prepare(`DELETE FROM runs WHERE status NOT IN ${UNDER_WAY} AND COALESCE(finished_at, started_at) < ?`).run(before);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
79
187
|
let store;
|
|
80
|
-
/** The process-wide store:
|
|
188
|
+
/** The process-wide store: the workspace's database, or JSON files in
|
|
189
|
+
* `runs/` in the scheduler's folder where there's none. */
|
|
81
190
|
export function getRunStore() {
|
|
82
|
-
|
|
191
|
+
if (!store) {
|
|
192
|
+
const db = auditDb();
|
|
193
|
+
store = db ? new SqliteRunStore(db, { importFrom: schedulerDir() }) : new FileRunStore(schedulerDir());
|
|
194
|
+
}
|
|
83
195
|
return store;
|
|
84
196
|
}
|
|
85
197
|
export function setRunStore(next) {
|
|
@@ -88,6 +200,9 @@ export function setRunStore(next) {
|
|
|
88
200
|
// ---------- reading ----------
|
|
89
201
|
/** An agent's runs, newest first; of one workflow when `workflowId` is given. */
|
|
90
202
|
export async function listRuns(agent, filter = {}) {
|
|
203
|
+
const store = getRunStore();
|
|
204
|
+
if (store.forAgent)
|
|
205
|
+
return store.forAgent(agent, filter);
|
|
91
206
|
const runs = (await getRunStore().list()).filter((r) => r.agent === agent && (!filter.workflowId || r.workflow_id === filter.workflowId));
|
|
92
207
|
return filter.limit ? runs.slice(0, filter.limit) : runs;
|
|
93
208
|
}
|
|
@@ -105,14 +220,29 @@ export class WorkflowRunner {
|
|
|
105
220
|
execute;
|
|
106
221
|
maxFinishedPerAgent;
|
|
107
222
|
onChange;
|
|
223
|
+
versionsFor;
|
|
108
224
|
inFlight = new Set();
|
|
109
225
|
/** `onChange`: called with the run when it starts, and each time it
|
|
110
226
|
* finishes, fails or stops for a decision (the server sends its chat
|
|
111
|
-
* messages and callbacks).
|
|
227
|
+
* messages and callbacks). `versionsFor`: the brief and policies
|
|
228
|
+
* versions a run of this workflow starts under. */
|
|
112
229
|
constructor(options) {
|
|
113
230
|
this.execute = options.execute;
|
|
114
231
|
this.maxFinishedPerAgent = options.maxFinishedPerAgent ?? MAX_FINISHED_PER_AGENT;
|
|
115
232
|
this.onChange = options.onChange;
|
|
233
|
+
this.versionsFor = options.versionsFor;
|
|
234
|
+
}
|
|
235
|
+
versionsOf(agent, workflowId) {
|
|
236
|
+
if (!this.versionsFor || !workflowId)
|
|
237
|
+
return {};
|
|
238
|
+
try {
|
|
239
|
+
const versions = this.versionsFor(agent, workflowId);
|
|
240
|
+
return versions && (versions.brief || versions.policies) ? { versions } : {};
|
|
241
|
+
}
|
|
242
|
+
catch (err) {
|
|
243
|
+
console.error('[loopengine] could not note the versions a run starts under:', err);
|
|
244
|
+
return {};
|
|
245
|
+
}
|
|
116
246
|
}
|
|
117
247
|
changed(run) {
|
|
118
248
|
if (!run || !this.onChange)
|
|
@@ -138,6 +268,7 @@ export class WorkflowRunner {
|
|
|
138
268
|
...(input.trigger_id ? { trigger_id: input.trigger_id } : {}),
|
|
139
269
|
...(input.job ? { job: input.job } : {}),
|
|
140
270
|
...(input.chained_from ? { chained_from: input.chained_from, chain_depth: input.chain_depth ?? 1 } : {}),
|
|
271
|
+
...this.versionsOf(input.agent, input.workflow_id),
|
|
141
272
|
status: 'running',
|
|
142
273
|
started_at: new Date().toISOString(),
|
|
143
274
|
message: input.message,
|
|
@@ -168,6 +299,7 @@ export class WorkflowRunner {
|
|
|
168
299
|
...(input.decisions_to ? { decisions_to: input.decisions_to } : {}),
|
|
169
300
|
...(input.chat_notice ? { chat_notice: input.chat_notice } : {}),
|
|
170
301
|
...(input.warnings?.length ? { warnings: input.warnings } : {}),
|
|
302
|
+
...this.versionsOf(input.agent, input.workflow_id),
|
|
171
303
|
status: 'running',
|
|
172
304
|
started_at: new Date().toISOString(),
|
|
173
305
|
message: input.message,
|
|
@@ -217,9 +349,7 @@ export class WorkflowRunner {
|
|
|
217
349
|
* its resolve path, for every resumed session): settle it, or record
|
|
218
350
|
* what it's waiting on now. */
|
|
219
351
|
async settleFromResume(sessionId, outcome) {
|
|
220
|
-
|
|
221
|
-
return;
|
|
222
|
-
const run = (await getRunStore().list()).find((r) => r.session_id === sessionId);
|
|
352
|
+
const run = await this.forSession(sessionId);
|
|
223
353
|
if (!run)
|
|
224
354
|
return;
|
|
225
355
|
if (outcome.pendingIds?.length) {
|
|
@@ -232,15 +362,35 @@ export class WorkflowRunner {
|
|
|
232
362
|
async forSession(sessionId) {
|
|
233
363
|
if (!sessionId.startsWith(SESSION_PREFIX) && !sessionId.startsWith(SCHEDULE_SESSION_PREFIX))
|
|
234
364
|
return undefined;
|
|
235
|
-
|
|
365
|
+
const store = getRunStore();
|
|
366
|
+
if (store.bySession)
|
|
367
|
+
return store.bySession(sessionId);
|
|
368
|
+
return (await store.list()).find((r) => r.session_id === sessionId);
|
|
236
369
|
}
|
|
237
|
-
/** Records an approval decided in a run's session
|
|
370
|
+
/** Records an approval decided in a run's session: on the run, and in
|
|
371
|
+
* the workspace's audit events. */
|
|
238
372
|
async recordDecision(sessionId, decision) {
|
|
239
373
|
const run = await this.forSession(sessionId);
|
|
240
374
|
if (!run)
|
|
241
375
|
return;
|
|
242
|
-
const
|
|
376
|
+
const reason = decision.reason?.trim().slice(0, 2000);
|
|
377
|
+
const entry = {
|
|
378
|
+
tool: decision.tool,
|
|
379
|
+
approved: decision.approved,
|
|
380
|
+
at: new Date().toISOString(),
|
|
381
|
+
...(decision.by ? { by: decision.by } : {}),
|
|
382
|
+
...(decision.edited ? { edited: true, before: clip(decision.before), after: clip(decision.after) } : {}),
|
|
383
|
+
...(reason ? { reason } : {}),
|
|
384
|
+
};
|
|
243
385
|
await getRunStore().update(run.run_id, (r) => r && { ...r, decisions: [...(r.decisions ?? []), entry].slice(-50) });
|
|
386
|
+
const { at, by, ...data } = entry;
|
|
387
|
+
recordEvent({ at, agent: run.agent, workflow_id: run.workflow_id, run_id: run.run_id, kind: 'decision', ...(by ? { by } : {}), data });
|
|
388
|
+
}
|
|
389
|
+
/** Records feedback given on a run's result in the audit events (the
|
|
390
|
+
* run itself carries the latest). */
|
|
391
|
+
recordFeedback(run, feedback, by) {
|
|
392
|
+
const { at, ...data } = feedback;
|
|
393
|
+
recordEvent({ at, agent: run.agent, workflow_id: run.workflow_id, run_id: run.run_id, kind: 'feedback', ...(by ? { by } : {}), data });
|
|
244
394
|
}
|
|
245
395
|
/** Records a question answered in a run's session. */
|
|
246
396
|
async recordAnswer(sessionId, answer) {
|
|
@@ -249,6 +399,7 @@ export class WorkflowRunner {
|
|
|
249
399
|
return;
|
|
250
400
|
const entry = { question: answer.question.slice(0, 4000), answer: answer.answer.slice(0, 4000), at: new Date().toISOString(), ...(answer.by ? { by: answer.by } : {}) };
|
|
251
401
|
await getRunStore().update(run.run_id, (r) => r && { ...r, answers: [...(r.answers ?? []), entry].slice(-50) });
|
|
402
|
+
recordEvent({ at: entry.at, agent: run.agent, workflow_id: run.workflow_id, run_id: run.run_id, kind: 'answer', ...(answer.by ? { by: answer.by } : {}), data: { question: entry.question, answer: entry.answer } });
|
|
252
403
|
}
|
|
253
404
|
/** On startup: a run a restart cut off can't continue, so it's an
|
|
254
405
|
* error. One waiting on a decision is kept: its checkpoint survives. */
|
|
@@ -259,8 +410,19 @@ export class WorkflowRunner {
|
|
|
259
410
|
}
|
|
260
411
|
}
|
|
261
412
|
async prune(agent) {
|
|
413
|
+
const store = getRunStore();
|
|
414
|
+
if (store.prune)
|
|
415
|
+
return store.prune();
|
|
262
416
|
const finished = (await listRuns(agent)).filter((r) => !isUnderWay(r));
|
|
263
417
|
for (const old of finished.slice(this.maxFinishedPerAgent))
|
|
264
418
|
await getRunStore().remove(old.run_id);
|
|
265
419
|
}
|
|
266
420
|
}
|
|
421
|
+
// A tool input kept on a decision: as given when small, else its JSON cut
|
|
422
|
+
// to 8,000 characters.
|
|
423
|
+
function clip(value) {
|
|
424
|
+
if (value === undefined)
|
|
425
|
+
return undefined;
|
|
426
|
+
const text = JSON.stringify(value);
|
|
427
|
+
return text.length <= 8000 ? value : text.slice(0, 8000);
|
|
428
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -92,7 +92,8 @@ export { WORKFLOW_EXAMPLES, workflowExample, type WorkflowExample } from './core
|
|
|
92
92
|
export { WORKFLOW_EXAMPLE_MESSAGES, type WorkflowExampleMessage } from './core/system-agents/workflow-example-messages.js';
|
|
93
93
|
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';
|
|
94
94
|
export { checkCallbackUrl, callbackSecret, signCallback, deliverCallback, runCallbackPayload, isPrivateAddress, CallbackUrlError, type CallbackDelivery, type CallbackPending, type RunCallbackEvent } from './core/run-callbacks.js';
|
|
95
|
-
export {
|
|
95
|
+
export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, noteVersion, listVersions, getVersion, briefContent, briefFromContent, retentionDays, type Version, type VersionKind, type AuditEvent, type AuditEventKind } from './core/audit-store.js';
|
|
96
|
+
export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, getRun, isUnderWay, RunError, type WorkflowRun, type WorkflowRunStatus, type RunVersions, type RunDecision, type RunStore, type ExecuteRun, type RunOutcome, type StartRunInput } from './core/workflow-runs.js';
|
|
96
97
|
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';
|
|
97
98
|
export { EvidenceError, 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 } from './web/workflow-evidence.js';
|
|
98
99
|
export { globalConfigPageHtml } from './web/global-config-page.js';
|
package/dist/index.js
CHANGED
|
@@ -85,7 +85,8 @@ export { WORKFLOW_EXAMPLES, workflowExample } from './core/system-agents/workflo
|
|
|
85
85
|
export { WORKFLOW_EXAMPLE_MESSAGES } from './core/system-agents/workflow-example-messages.js';
|
|
86
86
|
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';
|
|
87
87
|
export { checkCallbackUrl, callbackSecret, signCallback, deliverCallback, runCallbackPayload, isPrivateAddress, CallbackUrlError } from './core/run-callbacks.js';
|
|
88
|
-
export {
|
|
88
|
+
export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, noteVersion, listVersions, getVersion, briefContent, briefFromContent, retentionDays } from './core/audit-store.js';
|
|
89
|
+
export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, getRun, isUnderWay, RunError } from './core/workflow-runs.js';
|
|
89
90
|
export { readWorkflows, readWorkflow, setWorkflowFields, setWorkflowDelivery, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies } from './core/workflows.js';
|
|
90
91
|
export { EvidenceError, 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';
|
|
91
92
|
export { globalConfigPageHtml } from './web/global-config-page.js';
|
|
@@ -86,8 +86,6 @@ export const agentsConfigPageHtml = `<!doctype html>
|
|
|
86
86
|
.wf-page-starts { display: grid; gap: 2px; color: var(--ink); }
|
|
87
87
|
.wf-page-last { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; }
|
|
88
88
|
.wf-list-box.wf-page-box { border: 0; border-radius: 0; background: none; overflow: visible; }
|
|
89
|
-
.wf-page-brief { display: grid; gap: 10px; }
|
|
90
|
-
.wf-page-brief h2 { margin: 0; font-size: 15px; }
|
|
91
89
|
.wf-page .workflow-steps-text { margin: 0; padding: 14px 16px; border-radius: 10px; background: var(--surface); font-size: 13.5px; line-height: 1.6; max-height: 480px; overflow: auto; white-space: pre-wrap; }
|
|
92
90
|
.wf-page .workflow-result:empty { display: none; }
|
|
93
91
|
.wf-tab-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin: 0 0 20px; }
|
|
@@ -210,6 +208,11 @@ export const agentsConfigPageHtml = `<!doctype html>
|
|
|
210
208
|
.wf-crit { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 12px; align-items: center; padding: 8px 12px; border: 1px solid var(--line); border-radius: 8px; font-size: 13px; }
|
|
211
209
|
.wf-crit-kind { font-size: 12px; color: var(--ink-muted); }
|
|
212
210
|
.wf-crit-rate { font-variant-numeric: tabular-nums; }
|
|
211
|
+
.wf-versions { display: grid; gap: 8px; margin-bottom: 12px; font-size: 13px; }
|
|
212
|
+
.wf-versions[hidden], .wf-versions-list[hidden], .wf-version-text[hidden] { display: none; }
|
|
213
|
+
.wf-versions-line, .wf-versions-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; }
|
|
214
|
+
.wf-versions-list { margin: 0; padding: 0; list-style: none; display: grid; gap: 8px; border-left: 2px solid var(--line); padding-left: 12px; }
|
|
215
|
+
.wf-versions-list li { display: grid; gap: 6px; }
|
|
213
216
|
.wf-crit-form { display: grid; gap: 8px; padding: 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); }
|
|
214
217
|
.wf-crit-form[hidden] { display: none; }
|
|
215
218
|
.wf-crit-row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 180px auto; gap: 8px; align-items: center; }
|
|
@@ -1182,7 +1185,9 @@ ${renderMarkdownScript}
|
|
|
1182
1185
|
|
|
1183
1186
|
function workflowBriefHtml(w) {
|
|
1184
1187
|
var policies = workflowsMeta.policies;
|
|
1185
|
-
|
|
1188
|
+
// Filled by loadBriefVersions once the card is on the page.
|
|
1189
|
+
return '<div class="wf-versions" hidden></div>' +
|
|
1190
|
+
'<div class="workflow-steps-text">' + escapeHtml(w.instructions) + '</div>' +
|
|
1186
1191
|
(policies
|
|
1187
1192
|
? '<details class="wf-original"><summary>Shared policies, read by every workflow</summary><div class="workflow-steps-text">' + escapeHtml(policies) + '</div><p class="hint" style="margin:6px 0 0">Change them in <a href="/config?section=settings">Settings</a>.</p></details>'
|
|
1188
1193
|
: '<p class="hint" style="margin:0">No shared policies yet. Rules every workflow should follow, like your refund window or who signs messages, go in <a href="/config?section=settings">Settings</a>, so you write them once.</p>') +
|
|
@@ -1280,7 +1285,7 @@ ${renderMarkdownScript}
|
|
|
1280
1285
|
return tiles + feedbackHint + critSection +
|
|
1281
1286
|
'<h4 class="wf-sub">Eval cases</h4>' +
|
|
1282
1287
|
'<div class="wf-evals-bar"><button type="button" class="wf-evals-run"' + (!evals.cases.length || running ? ' disabled' : '') + '>' + (running ? 'Running ' + running.done + ' of ' + running.total + String.fromCharCode(8230) : 'Run evals') + '</button>' +
|
|
1283
|
-
'<span class="hint">' + (round ? 'Last run ' + escapeHtml(new Date(round.at).toLocaleString()) + DOT + 'model ' + escapeHtml(round.model) + DOT + 'judged by ' + escapeHtml(round.judge) : 'A test run: tools that need approval aren' + RSQ + 't run, and nobody is asked anything.') + '</span></div>' +
|
|
1288
|
+
'<span class="hint">' + (round ? 'Last run ' + escapeHtml(new Date(round.at).toLocaleString()) + (round.briefVersion ? DOT + 'brief v' + round.briefVersion : '') + DOT + 'model ' + escapeHtml(round.model) + DOT + 'judged by ' + escapeHtml(round.judge) : 'A test run: tools that need approval aren' + RSQ + 't run, and nobody is asked anything.') + '</span></div>' +
|
|
1284
1289
|
(cases ? '<ul class="wf-cases">' + cases + '</ul>' : '<p class="hint" style="margin:0">No cases yet. Save a run from History below as a case, then run the cases after each change to the instructions or model.</p>') +
|
|
1285
1290
|
'<h4 class="wf-sub">History</h4>' +
|
|
1286
1291
|
(runsHtml ? '<ul class="schedule-history">' + runsHtml + '</ul>' : '<p class="hint" style="margin:0">No runs yet.</p>');
|
|
@@ -1331,13 +1336,13 @@ ${renderMarkdownScript}
|
|
|
1331
1336
|
var formattedOutcome = outcome ? renderMarkdownPreview(outcome) : '';
|
|
1332
1337
|
return '<li class="workflow-run-entry"><div class="workflow-run-entry-head">' + pill +
|
|
1333
1338
|
'<span class="workflow-run-time">' + escapeHtml(new Date(r.started_at).toLocaleString()) + '</span>' +
|
|
1334
|
-
'<span class="workflow-run-source hint">' + escapeHtml(source) + '</span></div>' +
|
|
1339
|
+
'<span class="workflow-run-source hint">' + escapeHtml(source) + (r.versions && r.versions.brief ? DOT + 'brief v' + r.versions.brief : '') + '</span></div>' +
|
|
1335
1340
|
(values ? '<div><div class="workflow-run-entry-label">Parameters</div><div class="workflow-run-params">' + values + '</div></div>' : '') +
|
|
1336
1341
|
(outcome ? '<div><div class="workflow-run-entry-label">' + (r.status === 'error' ? 'Error' : 'Final response') + '</div><div class="schedule-result workflow-markdown">' + formattedOutcome + '</div><details class="schedule-result-details"><summary>View full ' + (r.status === 'error' ? 'error' : 'response') + '</summary><div class="schedule-result-full workflow-markdown workflow-markdown-full">' + formattedOutcome + '</div></details></div>' : '') +
|
|
1337
1342
|
runEvidenceHtml(w, r) + '</li>';
|
|
1338
1343
|
}).join('');
|
|
1339
1344
|
var last = workflowLastRun(w);
|
|
1340
|
-
var tab = workflowTabs[w.id] ||
|
|
1345
|
+
var tab = workflowTabs[w.id] || 'brief';
|
|
1341
1346
|
var open = openWorkflowId === w.id;
|
|
1342
1347
|
var panel = function (key, html) { return '<div class="wf-panel" data-panel="' + key + '"' + (tab === key ? '' : ' hidden') + '>' + html + '</div>'; };
|
|
1343
1348
|
var tabBtn = function (key, label) { return '<button type="button" role="tab" class="wf-tab" data-tab="' + key + '" aria-selected="' + (tab === key) + '">' + label + '</button>'; };
|
|
@@ -1359,8 +1364,8 @@ ${renderMarkdownScript}
|
|
|
1359
1364
|
'</div>' +
|
|
1360
1365
|
'</header>' +
|
|
1361
1366
|
'<div class="wf-row-body wf-page-body">' +
|
|
1362
|
-
'<
|
|
1363
|
-
|
|
1367
|
+
'<div class="wf-tabs" role="tablist">' + tabBtn('brief', 'Brief') + tabBtn('evidence', 'Evidence' + (runs ? ' <span class="wf-tab-count">' + w.recentRuns.length + '</span>' : '')) + tabBtn('triggers', 'Triggers') + tabBtn('messages', 'Messages') + tabBtn('contract', 'Contract') + '</div>' +
|
|
1368
|
+
panel('brief', workflowBriefHtml(w)) +
|
|
1364
1369
|
panel('evidence', workflowEvidenceHtml(w, runs)) +
|
|
1365
1370
|
panel('triggers', workflowTriggersHtml(w, name, params)) +
|
|
1366
1371
|
panel('messages', workflowMessagesHtml(w, name)) +
|
|
@@ -1937,6 +1942,66 @@ ${renderMarkdownScript}
|
|
|
1937
1942
|
render(shown ? shown.url : null, shown ? shown.id : null);
|
|
1938
1943
|
}
|
|
1939
1944
|
|
|
1945
|
+
// The Brief tab's versions: which one is in use, who saved it and why,
|
|
1946
|
+
// and every earlier one to read or restore (restoring saves it as a new
|
|
1947
|
+
// version). Hidden where the workspace keeps no versions.
|
|
1948
|
+
function loadBriefVersions(card, base) {
|
|
1949
|
+
var box = card.querySelector('.wf-versions');
|
|
1950
|
+
if (!box) return;
|
|
1951
|
+
fetch(base + '/versions', { headers: { accept: 'application/json' } })
|
|
1952
|
+
.then(function (r) { return r.ok ? r.json() : null; })
|
|
1953
|
+
.then(function (data) { if (data) renderBriefVersions(box, base, data); })
|
|
1954
|
+
.catch(function () {});
|
|
1955
|
+
}
|
|
1956
|
+
|
|
1957
|
+
function versionWhen(v) {
|
|
1958
|
+
return new Date(v.at).toLocaleString(undefined, { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' });
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
function renderBriefVersions(box, base, data) {
|
|
1962
|
+
var versions = data.versions || [];
|
|
1963
|
+
if (!versions.length) { box.hidden = true; return; }
|
|
1964
|
+
var current = versions.filter(function (v) { return v.number === data.current; })[0] || versions[0];
|
|
1965
|
+
var about = function (v) { return [v.by ? 'by ' + escapeHtml(v.by) : '', escapeHtml(versionWhen(v)), v.reason ? escapeHtml(v.reason) : ''].filter(Boolean).join(DOT); };
|
|
1966
|
+
box.innerHTML = '<div class="wf-versions-line"><strong>Version ' + current.number + '</strong><span class="hint">' + about(current) + '</span>' +
|
|
1967
|
+
(versions.length > 1 ? '<button type="button" class="wf-link wf-versions-toggle">History (' + versions.length + ')</button>' : '') + '</div>' +
|
|
1968
|
+
'<ol class="wf-versions-list" hidden>' + versions.map(function (v) {
|
|
1969
|
+
var isCurrent = v.number === current.number;
|
|
1970
|
+
return '<li data-version="' + v.number + '"><div class="wf-versions-row"><strong>v' + v.number + '</strong><span class="hint">' + about(v) + '</span>' +
|
|
1971
|
+
(isCurrent ? '<span class="le-pill good">In use</span>' : '') +
|
|
1972
|
+
'<button type="button" class="wf-link wf-version-view">View</button>' +
|
|
1973
|
+
(isCurrent ? '' : '<button type="button" class="wf-link wf-version-restore">Restore</button>') + '</div>' +
|
|
1974
|
+
'<div class="workflow-steps-text wf-version-text" hidden>' + escapeHtml(v.content) + '</div></li>';
|
|
1975
|
+
}).join('') + '</ol><span class="hint wf-versions-status" role="status"></span>';
|
|
1976
|
+
box.hidden = false;
|
|
1977
|
+
var list = box.querySelector('.wf-versions-list');
|
|
1978
|
+
var toggle = box.querySelector('.wf-versions-toggle');
|
|
1979
|
+
if (toggle) toggle.addEventListener('click', function () {
|
|
1980
|
+
list.hidden = !list.hidden;
|
|
1981
|
+
toggle.textContent = list.hidden ? 'History (' + versions.length + ')' : 'Hide history';
|
|
1982
|
+
});
|
|
1983
|
+
list.addEventListener('click', function (ev) {
|
|
1984
|
+
var item = ev.target.closest('li[data-version]');
|
|
1985
|
+
if (!item) return;
|
|
1986
|
+
if (ev.target.closest('.wf-version-view')) {
|
|
1987
|
+
var text = item.querySelector('.wf-version-text');
|
|
1988
|
+
text.hidden = !text.hidden;
|
|
1989
|
+
ev.target.textContent = text.hidden ? 'View' : 'Hide';
|
|
1990
|
+
return;
|
|
1991
|
+
}
|
|
1992
|
+
var restore = ev.target.closest('.wf-version-restore');
|
|
1993
|
+
if (!restore) return;
|
|
1994
|
+
if (restore.getAttribute('data-confirming') !== '1') { restore.setAttribute('data-confirming', '1'); restore.textContent = 'Click again to restore'; return; }
|
|
1995
|
+
restore.disabled = true;
|
|
1996
|
+
var status = box.querySelector('.wf-versions-status');
|
|
1997
|
+
status.textContent = 'Restoring' + String.fromCharCode(8230);
|
|
1998
|
+
fetch(base + '/versions/' + item.getAttribute('data-version') + '/restore', { method: 'POST' })
|
|
1999
|
+
.then(function (r) { return r.json().then(function (b) { if (!r.ok) throw new Error(b.error || 'That did not work'); return b; }); })
|
|
2000
|
+
.then(function () { location.reload(); })
|
|
2001
|
+
.catch(function (err) { status.textContent = err.message; restore.disabled = false; });
|
|
2002
|
+
});
|
|
2003
|
+
}
|
|
2004
|
+
|
|
1940
2005
|
function wireWorkflowCard(name, card) {
|
|
1941
2006
|
var id = card.dataset.workflow;
|
|
1942
2007
|
var result = card.querySelector('.workflow-result');
|
|
@@ -1956,6 +2021,7 @@ ${renderMarkdownScript}
|
|
|
1956
2021
|
}
|
|
1957
2022
|
var tabs = card.querySelectorAll('.wf-tab');
|
|
1958
2023
|
for (var t = 0; t < tabs.length; t++) tabs[t].addEventListener('click', function (ev) { showWorkflowTab(card, ev.currentTarget.dataset.tab); });
|
|
2024
|
+
loadBriefVersions(card, base);
|
|
1959
2025
|
card.querySelector('.workflow-edit').addEventListener('click', function () { openWorkflowEditor(name, card); });
|
|
1960
2026
|
// Opens the workflow's page on its Triggers tab.
|
|
1961
2027
|
var triggersBtn = card.querySelector('.workflow-triggers-open');
|
package/dist/web/inbox-page.js
CHANGED
|
@@ -62,6 +62,10 @@ export const inboxPageHtml = `<!doctype html>
|
|
|
62
62
|
.ib-step-k { font-size: 12px; font-weight: 700; color: var(--ink-muted); }
|
|
63
63
|
.ib-step details summary { cursor: pointer; font-size: 12.5px; color: var(--ink-muted); }
|
|
64
64
|
.ib-who { font-size: 13px; display: grid; gap: 4px; }
|
|
65
|
+
.ib-reason { color: var(--ink-muted); margin: 2px 0 0 12px; }
|
|
66
|
+
.ib-change { display: grid; gap: 2px; margin: 2px 0 0 12px; font-size: 12.5px; }
|
|
67
|
+
.ib-change del { color: var(--bad); }
|
|
68
|
+
.ib-change ins { color: var(--good); text-decoration: none; }
|
|
65
69
|
.hint { font-size: 12.5px; color: var(--ink-muted); }
|
|
66
70
|
.ib-md { font-size: 14px; line-height: 1.55; overflow-wrap: anywhere; }
|
|
67
71
|
.ib-md > :first-child { margin-top: 0; }
|
|
@@ -218,6 +222,7 @@ ${renderMarkdownScript}
|
|
|
218
222
|
'<p class="ib-question">The agent wants to run <code>' + esc(p.tool) + '</code> with:</p>' + kvHtml(p.args) +
|
|
219
223
|
(canDecide()
|
|
220
224
|
? '<textarea class="ib-args mono" hidden>' + esc(JSON.stringify(p.args, null, 2)) + '</textarea>' +
|
|
225
|
+
'<textarea class="ib-deny-reason" hidden placeholder="Why not? (optional) The agent reads this, and it' + String.fromCharCode(8217) + 's kept with the case."></textarea>' +
|
|
221
226
|
'<div class="ib-actions"><button type="button" class="ib-btn" data-act="approve">Approve</button>' +
|
|
222
227
|
'<button type="button" class="ib-btn plain" data-act="change">Change</button>' +
|
|
223
228
|
'<button type="button" class="ib-btn bad" data-act="deny">Deny</button><span class="hint ib-result" role="status"></span></div>'
|
|
@@ -234,14 +239,27 @@ ${renderMarkdownScript}
|
|
|
234
239
|
(s.result != null ? '<pre class="ib-pre" style="margin-top:6px">' + esc(s.result) + '</pre>' : '') + '</details></li>';
|
|
235
240
|
}
|
|
236
241
|
|
|
242
|
+
// What a person changed before approving: each field whose value
|
|
243
|
+
// differs, from what the agent asked for to what ran.
|
|
244
|
+
function changeOf(before, after) {
|
|
245
|
+
if (!before || !after || typeof before !== 'object' || typeof after !== 'object') return '';
|
|
246
|
+
var keys = Object.keys(before).concat(Object.keys(after).filter(function (k) { return !(k in before); }));
|
|
247
|
+
var show = function (v) { var t = v === undefined ? '(none)' : typeof v === 'string' ? v : JSON.stringify(v); return esc(t.length > 160 ? t.slice(0, 160) + String.fromCharCode(8230) : t); };
|
|
248
|
+
return keys.filter(function (k) { return JSON.stringify(before[k]) !== JSON.stringify(after[k]); }).map(function (k) {
|
|
249
|
+
return '<div><code>' + esc(k) + '</code>: <del>' + show(before[k]) + '</del> ' + String.fromCharCode(8594) + ' <ins>' + show(after[k]) + '</ins></div>';
|
|
250
|
+
}).join('');
|
|
251
|
+
}
|
|
252
|
+
|
|
237
253
|
function decidedHtml(run) {
|
|
238
254
|
var rows = [];
|
|
239
|
-
(run.decisions || []).forEach(function (d) { rows.push({ at: d.at, text: (d.approved ? (d.edited ? 'Approved as changed' : 'Approved') : 'Denied') + ' ' + d.tool, by: d.by }); });
|
|
255
|
+
(run.decisions || []).forEach(function (d) { rows.push({ at: d.at, text: (d.approved ? (d.edited ? 'Approved as changed' : 'Approved') : 'Denied') + ' ' + d.tool, by: d.by, reason: d.reason, change: d.edited ? changeOf(d.before, d.after) : '' }); });
|
|
240
256
|
(run.answers || []).forEach(function (a) { rows.push({ at: a.at, text: 'Answered: ' + a.answer, by: a.by }); });
|
|
241
257
|
rows.sort(function (a, b) { return String(a.at).localeCompare(String(b.at)); });
|
|
242
258
|
if (!rows.length) return '';
|
|
243
259
|
return '<div class="ib-card"><h3>Decisions</h3><div class="ib-who">' + rows.map(function (r) {
|
|
244
|
-
return '<div>' + esc(r.text) + ' <span class="hint">' + (r.by ? 'by ' + esc(r.by) + DOT : '') + esc(when(r.at)) + '</span
|
|
260
|
+
return '<div>' + esc(r.text) + ' <span class="hint">' + (r.by ? 'by ' + esc(r.by) + DOT : '') + esc(when(r.at)) + '</span>' +
|
|
261
|
+
(r.reason ? '<div class="ib-reason">' + String.fromCharCode(8220) + esc(r.reason) + String.fromCharCode(8221) + '</div>' : '') +
|
|
262
|
+
(r.change ? '<div class="ib-change">' + r.change + '</div>' : '') + '</div>';
|
|
245
263
|
}).join('') + '</div></div>';
|
|
246
264
|
}
|
|
247
265
|
|
|
@@ -324,8 +342,11 @@ ${renderMarkdownScript}
|
|
|
324
342
|
});
|
|
325
343
|
if (deny) deny.addEventListener('click', function (ev) {
|
|
326
344
|
var b = ev.currentTarget;
|
|
327
|
-
|
|
328
|
-
|
|
345
|
+
var reason = card.querySelector('.ib-deny-reason');
|
|
346
|
+
if (b.getAttribute('data-confirming') !== '1') { b.setAttribute('data-confirming', '1'); b.textContent = 'Deny'; reason.hidden = false; reason.focus(); return; }
|
|
347
|
+
var body = { decision: 'deny' };
|
|
348
|
+
if (reason.value.trim()) body.reason = reason.value.trim();
|
|
349
|
+
send(card, '/pending-approvals/' + encodeURIComponent(id) + '/resolve', body);
|
|
329
350
|
});
|
|
330
351
|
})(cards[i]);
|
|
331
352
|
}
|
|
@@ -68,6 +68,8 @@ export interface EvalCaseResult {
|
|
|
68
68
|
}
|
|
69
69
|
export interface EvalRound {
|
|
70
70
|
at: string;
|
|
71
|
+
/** The brief version it tested (core/audit-store.ts), when kept. */
|
|
72
|
+
briefVersion?: number;
|
|
71
73
|
/** The workflow's model and the judge's, as "provider model". */
|
|
72
74
|
model: string;
|
|
73
75
|
judge: string;
|
|
@@ -155,6 +157,8 @@ export declare function draftCriteria(model: ModelCall, input: {
|
|
|
155
157
|
export interface EvalRunDeps {
|
|
156
158
|
agentDir: string;
|
|
157
159
|
workflowId: string;
|
|
160
|
+
/** The brief version being tested, recorded on the round. */
|
|
161
|
+
briefVersion?: number;
|
|
158
162
|
instructions: string;
|
|
159
163
|
/** The workflow's model and the judge's, as "provider model". */
|
|
160
164
|
model: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "loopengine",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Runtime for tool-using AI agents with a transparent ReAct loop.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -45,6 +45,8 @@
|
|
|
45
45
|
"dist/core/secret-store.d.ts",
|
|
46
46
|
"dist/core/trusted-proxy.js",
|
|
47
47
|
"dist/core/trusted-proxy.d.ts",
|
|
48
|
+
"dist/core/audit-store.js",
|
|
49
|
+
"dist/core/audit-store.d.ts",
|
|
48
50
|
"dist/core/workspace-roles.js",
|
|
49
51
|
"dist/core/workspace-roles.d.ts",
|
|
50
52
|
"dist/core/unattended.js",
|