loopengine 0.3.101 → 0.4.2
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 +92 -0
- package/dist/core/audit-store.js +300 -0
- package/dist/core/durable-approvals.d.ts +28 -2
- package/dist/core/durable-approvals.js +113 -3
- package/dist/core/messaging/threads.d.ts +3 -2
- package/dist/core/messaging/threads.js +85 -6
- package/dist/core/run-agent.js +2 -0
- package/dist/core/session-store.d.ts +35 -3
- package/dist/core/session-store.js +81 -3
- package/dist/core/usage.d.ts +11 -0
- package/dist/core/usage.js +51 -3
- package/dist/core/workflow-runs.d.ts +82 -10
- package/dist/core/workflow-runs.js +186 -13
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -2
- package/dist/models.yaml +58 -0
- package/dist/web/agents-config-page.js +188 -9
- package/dist/web/change-log.d.ts +12 -0
- package/dist/web/change-log.js +86 -0
- package/dist/web/global-config.d.ts +20 -0
- package/dist/web/global-config.js +45 -3
- package/dist/web/inbox-admin.d.ts +34 -2
- package/dist/web/inbox-admin.js +45 -6
- package/dist/web/inbox-page.js +81 -9
- package/dist/web/workflow-evidence.d.ts +4 -0
- package/dist/web/workflow-evidence.js +1 -0
- package/dist/web/workflow-health.d.ts +66 -0
- package/dist/web/workflow-health.js +76 -0
- package/package.json +3 -1
|
@@ -0,0 +1,92 @@
|
|
|
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' | 'change';
|
|
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
|
+
/** A small value kept in the database's meta table (what's been
|
|
28
|
+
* imported, when an alert was last sent). */
|
|
29
|
+
export declare function readMeta(key: string, database?: DatabaseSync | undefined): string | undefined;
|
|
30
|
+
export declare function writeMeta(key: string, value: string, database?: DatabaseSync | undefined): void;
|
|
31
|
+
/** Tests: use this database (or none). */
|
|
32
|
+
export declare function setAuditDb(next: DatabaseSync | undefined): void;
|
|
33
|
+
/** How long finished runs are kept, in days. */
|
|
34
|
+
export declare function retentionDays(): number;
|
|
35
|
+
/** Appends what someone did in or about a run. Never throws: the record
|
|
36
|
+
* must not stop the work it records. */
|
|
37
|
+
export declare function recordEvent(event: Omit<AuditEvent, 'id' | 'at'> & {
|
|
38
|
+
at?: string;
|
|
39
|
+
}, database?: DatabaseSync | undefined): void;
|
|
40
|
+
/** A run's events, oldest first. */
|
|
41
|
+
export declare function runEvents(runId: string, database?: DatabaseSync | undefined): AuditEvent[];
|
|
42
|
+
export interface EventFilter {
|
|
43
|
+
agent?: string;
|
|
44
|
+
/** Only these agents' events (a person limited to some agents). */
|
|
45
|
+
agents?: string[];
|
|
46
|
+
workflowId?: string;
|
|
47
|
+
kind?: AuditEventKind;
|
|
48
|
+
by?: string;
|
|
49
|
+
/** ISO times, inclusive. */
|
|
50
|
+
since?: string;
|
|
51
|
+
until?: string;
|
|
52
|
+
/** Text anywhere in the event. */
|
|
53
|
+
q?: string;
|
|
54
|
+
/** Events older than this id (the next page). */
|
|
55
|
+
before?: number;
|
|
56
|
+
limit?: number;
|
|
57
|
+
}
|
|
58
|
+
/** Events matching the filter, newest first, at most 500. */
|
|
59
|
+
export declare function listEvents(filter?: EventFilter, database?: DatabaseSync | undefined): AuditEvent[];
|
|
60
|
+
/** The version number of `content`: the latest version's when it's the
|
|
61
|
+
* same text, else a new version noted now. Undefined without a database.
|
|
62
|
+
* `agent` and `workflowId` are '' for the workspace's policies. */
|
|
63
|
+
export declare function noteVersion(key: {
|
|
64
|
+
agent: string;
|
|
65
|
+
workflowId: string;
|
|
66
|
+
kind: VersionKind;
|
|
67
|
+
}, content: string, about?: {
|
|
68
|
+
by?: string;
|
|
69
|
+
reason?: string;
|
|
70
|
+
}, database?: DatabaseSync | undefined): number | undefined;
|
|
71
|
+
/** Every version, newest first. */
|
|
72
|
+
export declare function listVersions(key: {
|
|
73
|
+
agent: string;
|
|
74
|
+
workflowId: string;
|
|
75
|
+
kind: VersionKind;
|
|
76
|
+
}, database?: DatabaseSync | undefined): Version[];
|
|
77
|
+
export declare function getVersion(key: {
|
|
78
|
+
agent: string;
|
|
79
|
+
workflowId: string;
|
|
80
|
+
kind: VersionKind;
|
|
81
|
+
}, number: number, database?: DatabaseSync | undefined): Version | undefined;
|
|
82
|
+
/** What a workflow's brief version holds: its instructions and the
|
|
83
|
+
* result format, as one text (the format under a heading). */
|
|
84
|
+
export declare function briefContent(workflow: {
|
|
85
|
+
instructions: string;
|
|
86
|
+
output?: string;
|
|
87
|
+
}): string;
|
|
88
|
+
/** The instructions and result format a brief version holds. */
|
|
89
|
+
export declare function briefFromContent(content: string): {
|
|
90
|
+
instructions: string;
|
|
91
|
+
output?: string;
|
|
92
|
+
};
|
|
@@ -0,0 +1,300 @@
|
|
|
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
|
+
// - checkpoints and pending: turns paused on an approval or a question
|
|
12
|
+
// (core/durable-approvals.ts's SqliteCheckpointStore), removed once
|
|
13
|
+
// decided;
|
|
14
|
+
// - session_entries: every conversation's messages, in order, each with
|
|
15
|
+
// when it was written (core/session-store.ts's SqliteSessionStore);
|
|
16
|
+
// - usage: tokens and time of every model call (core/usage.ts);
|
|
17
|
+
// - threads and job_threads: which chat message each request or job is
|
|
18
|
+
// (core/messaging/threads.ts);
|
|
19
|
+
// - versions: each workflow's brief (its instructions and result format)
|
|
20
|
+
// and the workspace's shared policies, numbered. A new version is noted
|
|
21
|
+
// whenever the text differs from the latest, however it changed: saved
|
|
22
|
+
// in the console, restored, or edited in the file.
|
|
23
|
+
//
|
|
24
|
+
// It uses node:sqlite, built into Node 22.5 and later. Where that's
|
|
25
|
+
// missing, auditDb() is undefined: runs stay in JSON files and nothing is
|
|
26
|
+
// versioned.
|
|
27
|
+
import { createHash } from 'node:crypto';
|
|
28
|
+
import { mkdirSync } from 'node:fs';
|
|
29
|
+
import { createRequire } from 'node:module';
|
|
30
|
+
import path from 'node:path';
|
|
31
|
+
const SCHEMA = `
|
|
32
|
+
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
33
|
+
CREATE TABLE IF NOT EXISTS runs (
|
|
34
|
+
run_id TEXT PRIMARY KEY,
|
|
35
|
+
agent TEXT NOT NULL,
|
|
36
|
+
workflow_id TEXT NOT NULL,
|
|
37
|
+
status TEXT NOT NULL,
|
|
38
|
+
started_at TEXT NOT NULL,
|
|
39
|
+
finished_at TEXT,
|
|
40
|
+
session_id TEXT NOT NULL,
|
|
41
|
+
data TEXT NOT NULL
|
|
42
|
+
);
|
|
43
|
+
CREATE INDEX IF NOT EXISTS runs_agent ON runs (agent, workflow_id, started_at);
|
|
44
|
+
CREATE INDEX IF NOT EXISTS runs_session ON runs (session_id);
|
|
45
|
+
CREATE INDEX IF NOT EXISTS runs_finished ON runs (finished_at);
|
|
46
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
47
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
48
|
+
at TEXT NOT NULL,
|
|
49
|
+
agent TEXT NOT NULL,
|
|
50
|
+
workflow_id TEXT,
|
|
51
|
+
run_id TEXT,
|
|
52
|
+
kind TEXT NOT NULL,
|
|
53
|
+
by TEXT,
|
|
54
|
+
data TEXT NOT NULL
|
|
55
|
+
);
|
|
56
|
+
CREATE INDEX IF NOT EXISTS events_run ON events (run_id);
|
|
57
|
+
CREATE INDEX IF NOT EXISTS events_workflow ON events (agent, workflow_id, at);
|
|
58
|
+
CREATE TABLE IF NOT EXISTS checkpoints (
|
|
59
|
+
id TEXT PRIMARY KEY,
|
|
60
|
+
agent TEXT NOT NULL,
|
|
61
|
+
session_id TEXT NOT NULL,
|
|
62
|
+
created_at TEXT NOT NULL,
|
|
63
|
+
data TEXT NOT NULL
|
|
64
|
+
);
|
|
65
|
+
CREATE TABLE IF NOT EXISTS pending (
|
|
66
|
+
pending_id TEXT PRIMARY KEY,
|
|
67
|
+
checkpoint_id TEXT NOT NULL
|
|
68
|
+
);
|
|
69
|
+
CREATE INDEX IF NOT EXISTS pending_checkpoint ON pending (checkpoint_id);
|
|
70
|
+
CREATE TABLE IF NOT EXISTS threads (
|
|
71
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
72
|
+
agent TEXT NOT NULL,
|
|
73
|
+
app TEXT NOT NULL,
|
|
74
|
+
conversation TEXT NOT NULL,
|
|
75
|
+
ts TEXT NOT NULL,
|
|
76
|
+
pending_id TEXT NOT NULL,
|
|
77
|
+
data TEXT NOT NULL,
|
|
78
|
+
at TEXT NOT NULL
|
|
79
|
+
);
|
|
80
|
+
CREATE INDEX IF NOT EXISTS threads_pending ON threads (agent, pending_id);
|
|
81
|
+
CREATE INDEX IF NOT EXISTS threads_message ON threads (agent, app, conversation, ts);
|
|
82
|
+
CREATE TABLE IF NOT EXISTS job_threads (
|
|
83
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
84
|
+
agent TEXT NOT NULL,
|
|
85
|
+
app TEXT NOT NULL,
|
|
86
|
+
conversation TEXT NOT NULL,
|
|
87
|
+
ts TEXT NOT NULL,
|
|
88
|
+
session_id TEXT NOT NULL,
|
|
89
|
+
at TEXT NOT NULL
|
|
90
|
+
);
|
|
91
|
+
CREATE INDEX IF NOT EXISTS job_threads_message ON job_threads (agent, app, conversation, ts);
|
|
92
|
+
CREATE INDEX IF NOT EXISTS job_threads_session ON job_threads (agent, session_id);
|
|
93
|
+
CREATE TABLE IF NOT EXISTS session_entries (
|
|
94
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
95
|
+
session_id TEXT NOT NULL,
|
|
96
|
+
id TEXT NOT NULL,
|
|
97
|
+
parent_id TEXT,
|
|
98
|
+
at TEXT NOT NULL,
|
|
99
|
+
data TEXT NOT NULL
|
|
100
|
+
);
|
|
101
|
+
CREATE INDEX IF NOT EXISTS session_entries_session ON session_entries (session_id, seq);
|
|
102
|
+
CREATE TABLE IF NOT EXISTS usage (
|
|
103
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
104
|
+
at TEXT NOT NULL,
|
|
105
|
+
agent TEXT NOT NULL,
|
|
106
|
+
tenant TEXT NOT NULL,
|
|
107
|
+
session_id TEXT,
|
|
108
|
+
provider TEXT,
|
|
109
|
+
model TEXT,
|
|
110
|
+
input_tokens INTEGER NOT NULL,
|
|
111
|
+
output_tokens INTEGER NOT NULL,
|
|
112
|
+
duration_ms INTEGER
|
|
113
|
+
);
|
|
114
|
+
CREATE INDEX IF NOT EXISTS usage_session ON usage (session_id, id);
|
|
115
|
+
CREATE INDEX IF NOT EXISTS usage_agent ON usage (agent, at);
|
|
116
|
+
CREATE TABLE IF NOT EXISTS versions (
|
|
117
|
+
agent TEXT NOT NULL,
|
|
118
|
+
workflow_id TEXT NOT NULL,
|
|
119
|
+
kind TEXT NOT NULL,
|
|
120
|
+
number INTEGER NOT NULL,
|
|
121
|
+
hash TEXT NOT NULL,
|
|
122
|
+
content TEXT NOT NULL,
|
|
123
|
+
at TEXT NOT NULL,
|
|
124
|
+
by TEXT,
|
|
125
|
+
reason TEXT,
|
|
126
|
+
PRIMARY KEY (agent, workflow_id, kind, number)
|
|
127
|
+
);
|
|
128
|
+
`;
|
|
129
|
+
// node:sqlite, or undefined on a Node without it. Node 22 marks it
|
|
130
|
+
// experimental and says so once on load; that warning is dropped here.
|
|
131
|
+
function loadSqlite() {
|
|
132
|
+
const emit = process.emitWarning;
|
|
133
|
+
process.emitWarning = ((warning, ...rest) => {
|
|
134
|
+
if (/SQLite/i.test(typeof warning === 'string' ? warning : warning.message))
|
|
135
|
+
return;
|
|
136
|
+
return emit.call(process, warning, ...rest);
|
|
137
|
+
});
|
|
138
|
+
try {
|
|
139
|
+
return createRequire(import.meta.url)('node:sqlite');
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
process.emitWarning = emit;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** Opens (creating if need be) the database in `dir`. */
|
|
149
|
+
export function openAuditDb(dir) {
|
|
150
|
+
const sqlite = loadSqlite();
|
|
151
|
+
if (!sqlite)
|
|
152
|
+
return undefined;
|
|
153
|
+
mkdirSync(dir, { recursive: true });
|
|
154
|
+
const db = new sqlite.DatabaseSync(path.join(dir, 'loopengine.db'));
|
|
155
|
+
db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;');
|
|
156
|
+
db.exec(SCHEMA);
|
|
157
|
+
return db;
|
|
158
|
+
}
|
|
159
|
+
let db;
|
|
160
|
+
export function schedulerDir() {
|
|
161
|
+
return process.env.LOOPENGINE_SCHEDULER_DIR || path.join(process.cwd(), '.scheduler');
|
|
162
|
+
}
|
|
163
|
+
/** The process-wide database; undefined where node:sqlite isn't there,
|
|
164
|
+
* or LOOPENGINE_RUN_STORE=files asks for the JSON files. */
|
|
165
|
+
export function auditDb() {
|
|
166
|
+
if (db === undefined)
|
|
167
|
+
db = process.env.LOOPENGINE_RUN_STORE === 'files' ? null : (openAuditDb(schedulerDir()) ?? null);
|
|
168
|
+
return db ?? undefined;
|
|
169
|
+
}
|
|
170
|
+
/** A small value kept in the database's meta table (what's been
|
|
171
|
+
* imported, when an alert was last sent). */
|
|
172
|
+
export function readMeta(key, database = auditDb()) {
|
|
173
|
+
const row = database?.prepare('SELECT value FROM meta WHERE key = ?').get(key);
|
|
174
|
+
return row?.value;
|
|
175
|
+
}
|
|
176
|
+
export function writeMeta(key, value, database = auditDb()) {
|
|
177
|
+
database?.prepare('INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)').run(key, value);
|
|
178
|
+
}
|
|
179
|
+
/** Tests: use this database (or none). */
|
|
180
|
+
export function setAuditDb(next) {
|
|
181
|
+
db = next ?? null;
|
|
182
|
+
}
|
|
183
|
+
/** How long finished runs are kept, in days. */
|
|
184
|
+
export function retentionDays() {
|
|
185
|
+
const n = Number(process.env.LOOPENGINE_RETENTION_DAYS);
|
|
186
|
+
return Number.isFinite(n) && n > 0 ? n : 400;
|
|
187
|
+
}
|
|
188
|
+
// ---------- events ----------
|
|
189
|
+
/** Appends what someone did in or about a run. Never throws: the record
|
|
190
|
+
* must not stop the work it records. */
|
|
191
|
+
export function recordEvent(event, database = auditDb()) {
|
|
192
|
+
if (!database)
|
|
193
|
+
return;
|
|
194
|
+
try {
|
|
195
|
+
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));
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
console.error('[loopengine] could not record an audit event:', err);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/** A run's events, oldest first. */
|
|
202
|
+
export function runEvents(runId, database = auditDb()) {
|
|
203
|
+
if (!database)
|
|
204
|
+
return [];
|
|
205
|
+
return database.prepare('SELECT * FROM events WHERE run_id = ? ORDER BY id').all(runId).map(eventOf);
|
|
206
|
+
}
|
|
207
|
+
/** Events matching the filter, newest first, at most 500. */
|
|
208
|
+
export function listEvents(filter = {}, database = auditDb()) {
|
|
209
|
+
if (!database)
|
|
210
|
+
return [];
|
|
211
|
+
const where = [];
|
|
212
|
+
const args = [];
|
|
213
|
+
const add = (clause, ...values) => {
|
|
214
|
+
where.push(clause);
|
|
215
|
+
args.push(...values);
|
|
216
|
+
};
|
|
217
|
+
if (filter.agent)
|
|
218
|
+
add('agent = ?', filter.agent);
|
|
219
|
+
if (filter.agents)
|
|
220
|
+
add(`agent IN (${filter.agents.map(() => '?').join(', ') || "''"})`, ...filter.agents);
|
|
221
|
+
if (filter.workflowId)
|
|
222
|
+
add('workflow_id = ?', filter.workflowId);
|
|
223
|
+
if (filter.kind)
|
|
224
|
+
add('kind = ?', filter.kind);
|
|
225
|
+
if (filter.by)
|
|
226
|
+
add('by = ?', filter.by);
|
|
227
|
+
if (filter.since)
|
|
228
|
+
add('at >= ?', filter.since);
|
|
229
|
+
if (filter.until)
|
|
230
|
+
add('at <= ?', filter.until);
|
|
231
|
+
if (filter.before)
|
|
232
|
+
add('id < ?', filter.before);
|
|
233
|
+
if (filter.q)
|
|
234
|
+
add("(data LIKE ? ESCAPE '\\' OR by LIKE ? ESCAPE '\\')", ...Array(2).fill(`%${filter.q.replace(/[\\%_]/g, (c) => '\\' + c)}%`));
|
|
235
|
+
const limit = Math.min(Math.max(filter.limit ?? 100, 1), 500);
|
|
236
|
+
const sql = `SELECT * FROM events${where.length ? ` WHERE ${where.join(' AND ')}` : ''} ORDER BY id DESC LIMIT ${limit}`;
|
|
237
|
+
return database.prepare(sql).all(...args).map(eventOf);
|
|
238
|
+
}
|
|
239
|
+
function eventOf(r) {
|
|
240
|
+
return {
|
|
241
|
+
id: Number(r.id),
|
|
242
|
+
at: String(r.at),
|
|
243
|
+
agent: String(r.agent),
|
|
244
|
+
...(r.workflow_id ? { workflow_id: String(r.workflow_id) } : {}),
|
|
245
|
+
...(r.run_id ? { run_id: String(r.run_id) } : {}),
|
|
246
|
+
kind: String(r.kind),
|
|
247
|
+
...(r.by ? { by: String(r.by) } : {}),
|
|
248
|
+
data: JSON.parse(String(r.data)),
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
// ---------- versions ----------
|
|
252
|
+
const hashOf = (content) => createHash('sha256').update(content).digest('hex');
|
|
253
|
+
/** The version number of `content`: the latest version's when it's the
|
|
254
|
+
* same text, else a new version noted now. Undefined without a database.
|
|
255
|
+
* `agent` and `workflowId` are '' for the workspace's policies. */
|
|
256
|
+
export function noteVersion(key, content, about = {}, database = auditDb()) {
|
|
257
|
+
if (!database)
|
|
258
|
+
return undefined;
|
|
259
|
+
try {
|
|
260
|
+
const hash = hashOf(content);
|
|
261
|
+
const latest = database.prepare('SELECT number, hash FROM versions WHERE agent = ? AND workflow_id = ? AND kind = ? ORDER BY number DESC LIMIT 1')
|
|
262
|
+
.get(key.agent, key.workflowId, key.kind);
|
|
263
|
+
if (latest && latest.hash === hash)
|
|
264
|
+
return Number(latest.number);
|
|
265
|
+
const number = (latest ? Number(latest.number) : 0) + 1;
|
|
266
|
+
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'));
|
|
267
|
+
return number;
|
|
268
|
+
}
|
|
269
|
+
catch (err) {
|
|
270
|
+
console.error('[loopengine] could not note a version:', err);
|
|
271
|
+
return undefined;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/** Every version, newest first. */
|
|
275
|
+
export function listVersions(key, database = auditDb()) {
|
|
276
|
+
if (!database)
|
|
277
|
+
return [];
|
|
278
|
+
const rows = database.prepare('SELECT number, at, by, reason, content FROM versions WHERE agent = ? AND workflow_id = ? AND kind = ? ORDER BY number DESC')
|
|
279
|
+
.all(key.agent, key.workflowId, key.kind);
|
|
280
|
+
return rows.map((r) => ({
|
|
281
|
+
number: Number(r.number),
|
|
282
|
+
at: String(r.at),
|
|
283
|
+
...(r.by ? { by: String(r.by) } : {}),
|
|
284
|
+
...(r.reason ? { reason: String(r.reason) } : {}),
|
|
285
|
+
content: String(r.content),
|
|
286
|
+
}));
|
|
287
|
+
}
|
|
288
|
+
export function getVersion(key, number, database = auditDb()) {
|
|
289
|
+
return listVersions(key, database).find((v) => v.number === number);
|
|
290
|
+
}
|
|
291
|
+
/** What a workflow's brief version holds: its instructions and the
|
|
292
|
+
* result format, as one text (the format under a heading). */
|
|
293
|
+
export function briefContent(workflow) {
|
|
294
|
+
return workflow.output?.trim() ? `${workflow.instructions}\n\n## Result format\n\n${workflow.output.trim()}` : workflow.instructions;
|
|
295
|
+
}
|
|
296
|
+
/** The instructions and result format a brief version holds. */
|
|
297
|
+
export function briefFromContent(content) {
|
|
298
|
+
const at = content.lastIndexOf('\n\n## Result format\n\n');
|
|
299
|
+
return at < 0 ? { instructions: content } : { instructions: content.slice(0, at), output: content.slice(at + '\n\n## Result format\n\n'.length) };
|
|
300
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
1
2
|
import { Redis } from 'ioredis';
|
|
2
3
|
import type { ModelContentBlock } from './run-agent.js';
|
|
3
4
|
export interface OutstandingItem {
|
|
@@ -90,6 +91,29 @@ export declare class FileCheckpointStore implements CheckpointStore {
|
|
|
90
91
|
listOpen(): Promise<TurnCheckpoint[]>;
|
|
91
92
|
close(): Promise<void>;
|
|
92
93
|
}
|
|
94
|
+
/** Checkpoints in the workspace's database (core/audit-store.ts): one
|
|
95
|
+
* row per open checkpoint, and one per outstanding pendingId pointing at
|
|
96
|
+
* it. One process, like FileCheckpointStore (`fn` runs tools, so a
|
|
97
|
+
* checkpoint is held with a mutex, not a transaction). The files of a
|
|
98
|
+
* FileCheckpointStore in `importFrom` are copied in the first time. */
|
|
99
|
+
export declare class SqliteCheckpointStore implements CheckpointStore {
|
|
100
|
+
private readonly db;
|
|
101
|
+
constructor(db: DatabaseSync, options?: {
|
|
102
|
+
importFrom?: string;
|
|
103
|
+
});
|
|
104
|
+
private importFiles;
|
|
105
|
+
private save;
|
|
106
|
+
private load;
|
|
107
|
+
private checkpointIdOf;
|
|
108
|
+
create(input: CreateCheckpointInput): Promise<TurnCheckpoint>;
|
|
109
|
+
withCheckpoint<T>(pendingId: string, fn: (checkpoint: TurnCheckpoint | undefined) => Promise<{
|
|
110
|
+
checkpoint: TurnCheckpoint | undefined;
|
|
111
|
+
result: T;
|
|
112
|
+
}>): Promise<T>;
|
|
113
|
+
get(pendingId: string): Promise<TurnCheckpoint | undefined>;
|
|
114
|
+
listOpen(): Promise<TurnCheckpoint[]>;
|
|
115
|
+
close(): Promise<void>;
|
|
116
|
+
}
|
|
93
117
|
/** Redis-backed store for multi-instance deployments. Unlike
|
|
94
118
|
* RedisSessionStore's lock (held for an entire turn, including however
|
|
95
119
|
* long a live human takes), this one only ever needs to be held for a
|
|
@@ -116,6 +140,8 @@ export declare class RedisCheckpointStore implements CheckpointStore {
|
|
|
116
140
|
close(): Promise<void>;
|
|
117
141
|
}
|
|
118
142
|
/** Same REDIS_URL-gated pattern as session-store.ts's own
|
|
119
|
-
* createSessionStore(): set -> RedisCheckpointStore
|
|
120
|
-
*
|
|
143
|
+
* createSessionStore(): set -> RedisCheckpointStore; otherwise the
|
|
144
|
+
* workspace's database, copying in what's under .checkpoints the first
|
|
145
|
+
* time; FileCheckpointStore under .checkpoints where there's no
|
|
146
|
+
* database. */
|
|
121
147
|
export declare function createCheckpointStore(): CheckpointStore;
|
|
@@ -13,6 +13,7 @@ import { randomUUID } from 'node:crypto';
|
|
|
13
13
|
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
14
14
|
import path from 'node:path';
|
|
15
15
|
import { Redis } from 'ioredis';
|
|
16
|
+
import { auditDb } from './audit-store.js';
|
|
16
17
|
import { KeyedMutex } from './session-store.js';
|
|
17
18
|
function sortOldestFirst(list) {
|
|
18
19
|
return list.sort((a, b) => (a.createdAt ?? '').localeCompare(b.createdAt ?? ''));
|
|
@@ -100,6 +101,110 @@ export class FileCheckpointStore {
|
|
|
100
101
|
}
|
|
101
102
|
async close() { }
|
|
102
103
|
}
|
|
104
|
+
/** Checkpoints in the workspace's database (core/audit-store.ts): one
|
|
105
|
+
* row per open checkpoint, and one per outstanding pendingId pointing at
|
|
106
|
+
* it. One process, like FileCheckpointStore (`fn` runs tools, so a
|
|
107
|
+
* checkpoint is held with a mutex, not a transaction). The files of a
|
|
108
|
+
* FileCheckpointStore in `importFrom` are copied in the first time. */
|
|
109
|
+
export class SqliteCheckpointStore {
|
|
110
|
+
db;
|
|
111
|
+
constructor(db, options = {}) {
|
|
112
|
+
this.db = db;
|
|
113
|
+
if (options.importFrom)
|
|
114
|
+
this.importFiles(options.importFrom);
|
|
115
|
+
}
|
|
116
|
+
importFiles(dir) {
|
|
117
|
+
if (this.db.prepare("SELECT value FROM meta WHERE key = 'checkpoints_imported'").get())
|
|
118
|
+
return;
|
|
119
|
+
const checkpointsDir = path.join(dir, 'checkpoints');
|
|
120
|
+
let count = 0;
|
|
121
|
+
if (existsSync(checkpointsDir)) {
|
|
122
|
+
this.db.exec('BEGIN');
|
|
123
|
+
try {
|
|
124
|
+
for (const name of readdirSync(checkpointsDir)) {
|
|
125
|
+
if (!name.endsWith('.json'))
|
|
126
|
+
continue;
|
|
127
|
+
try {
|
|
128
|
+
const checkpoint = JSON.parse(readFileSync(path.join(checkpointsDir, name), 'utf8'));
|
|
129
|
+
if (checkpoint.id && !checkpoint.closed && Object.keys(checkpoint.outstanding ?? {}).length) {
|
|
130
|
+
this.save(checkpoint, true);
|
|
131
|
+
count++;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
// Not a checkpoint: skip it.
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
this.db.exec('COMMIT');
|
|
139
|
+
}
|
|
140
|
+
catch (err) {
|
|
141
|
+
this.db.exec('ROLLBACK');
|
|
142
|
+
throw err;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('checkpoints_imported', ?)").run(`${new Date().toISOString()} ${count}`);
|
|
146
|
+
}
|
|
147
|
+
save(checkpoint, index) {
|
|
148
|
+
this.db.prepare('INSERT OR REPLACE INTO checkpoints (id, agent, session_id, created_at, data) VALUES (?, ?, ?, ?, ?)')
|
|
149
|
+
.run(checkpoint.id, checkpoint.agent, checkpoint.sessionId, checkpoint.createdAt ?? '', JSON.stringify(checkpoint));
|
|
150
|
+
if (!index)
|
|
151
|
+
return;
|
|
152
|
+
const point = this.db.prepare('INSERT OR REPLACE INTO pending (pending_id, checkpoint_id) VALUES (?, ?)');
|
|
153
|
+
for (const pendingId of Object.keys(checkpoint.outstanding))
|
|
154
|
+
point.run(pendingId, checkpoint.id);
|
|
155
|
+
}
|
|
156
|
+
load(checkpointId) {
|
|
157
|
+
const row = this.db.prepare('SELECT data FROM checkpoints WHERE id = ?').get(checkpointId);
|
|
158
|
+
return row ? JSON.parse(row.data) : undefined;
|
|
159
|
+
}
|
|
160
|
+
checkpointIdOf(pendingId) {
|
|
161
|
+
const row = this.db.prepare('SELECT checkpoint_id FROM pending WHERE pending_id = ?').get(pendingId);
|
|
162
|
+
return row?.checkpoint_id;
|
|
163
|
+
}
|
|
164
|
+
async create(input) {
|
|
165
|
+
const checkpoint = { id: randomUUID(), closed: false, createdAt: new Date().toISOString(), ...input };
|
|
166
|
+
this.db.exec('BEGIN');
|
|
167
|
+
try {
|
|
168
|
+
this.save(checkpoint, true);
|
|
169
|
+
this.db.exec('COMMIT');
|
|
170
|
+
}
|
|
171
|
+
catch (err) {
|
|
172
|
+
this.db.exec('ROLLBACK');
|
|
173
|
+
throw err;
|
|
174
|
+
}
|
|
175
|
+
return checkpoint;
|
|
176
|
+
}
|
|
177
|
+
async withCheckpoint(pendingId, fn) {
|
|
178
|
+
const checkpointId = this.checkpointIdOf(pendingId);
|
|
179
|
+
if (!checkpointId)
|
|
180
|
+
return (await fn(undefined)).result;
|
|
181
|
+
return fileMutex.run(checkpointId, async () => {
|
|
182
|
+
// A sibling's resolution may have closed it while this call waited.
|
|
183
|
+
const current = this.load(checkpointId);
|
|
184
|
+
const { checkpoint, result } = await fn(current && !current.closed ? current : undefined);
|
|
185
|
+
if (checkpoint) {
|
|
186
|
+
if (checkpoint.closed) {
|
|
187
|
+
this.db.prepare('DELETE FROM checkpoints WHERE id = ?').run(checkpointId);
|
|
188
|
+
this.db.prepare('DELETE FROM pending WHERE checkpoint_id = ?').run(checkpointId);
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
this.save(checkpoint, false);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return result;
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
async get(pendingId) {
|
|
198
|
+
const checkpointId = this.checkpointIdOf(pendingId);
|
|
199
|
+
const checkpoint = checkpointId ? this.load(checkpointId) : undefined;
|
|
200
|
+
return checkpoint && !checkpoint.closed && checkpoint.outstanding[pendingId] ? checkpoint : undefined;
|
|
201
|
+
}
|
|
202
|
+
async listOpen() {
|
|
203
|
+
const rows = this.db.prepare('SELECT data FROM checkpoints ORDER BY created_at').all();
|
|
204
|
+
return sortOldestFirst(rows.map((r) => JSON.parse(r.data)).filter((c) => !c.closed && Object.keys(c.outstanding).length));
|
|
205
|
+
}
|
|
206
|
+
async close() { }
|
|
207
|
+
}
|
|
103
208
|
/** Redis-backed store for multi-instance deployments. Unlike
|
|
104
209
|
* RedisSessionStore's lock (held for an entire turn, including however
|
|
105
210
|
* long a live human takes), this one only ever needs to be held for a
|
|
@@ -208,9 +313,14 @@ export class RedisCheckpointStore {
|
|
|
208
313
|
}
|
|
209
314
|
}
|
|
210
315
|
/** Same REDIS_URL-gated pattern as session-store.ts's own
|
|
211
|
-
* createSessionStore(): set -> RedisCheckpointStore
|
|
212
|
-
*
|
|
316
|
+
* createSessionStore(): set -> RedisCheckpointStore; otherwise the
|
|
317
|
+
* workspace's database, copying in what's under .checkpoints the first
|
|
318
|
+
* time; FileCheckpointStore under .checkpoints where there's no
|
|
319
|
+
* database. */
|
|
213
320
|
export function createCheckpointStore() {
|
|
214
321
|
const redisUrl = process.env.REDIS_URL;
|
|
215
|
-
|
|
322
|
+
if (redisUrl)
|
|
323
|
+
return new RedisCheckpointStore(redisUrl);
|
|
324
|
+
const db = auditDb();
|
|
325
|
+
return db ? new SqliteCheckpointStore(db, { importFrom: '.checkpoints' }) : new FileCheckpointStore('.checkpoints');
|
|
216
326
|
}
|
|
@@ -18,8 +18,9 @@ export interface ThreadLink {
|
|
|
18
18
|
* buttons on the last: that message, when it isn't `ts`. */
|
|
19
19
|
buttonsTs?: string;
|
|
20
20
|
}
|
|
21
|
-
/**
|
|
22
|
-
* mapped still works through its
|
|
21
|
+
/** Records one request's thread; the latest record of a request wins.
|
|
22
|
+
* Never throws: a request that can't be mapped still works through its
|
|
23
|
+
* buttons and link. */
|
|
23
24
|
export declare function recordThread(agentDir: string, link: ThreadLink): void;
|
|
24
25
|
/** The thread a request was posted in, found by its pendingId. */
|
|
25
26
|
export declare function findThreadByPending(agentDir: string, pendingId: string): ThreadLink | undefined;
|