loopengine 0.4.1 → 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 +23 -1
- package/dist/core/audit-store.js +112 -3
- 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 +6 -0
- package/dist/core/workflow-runs.js +11 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/models.yaml +58 -0
- package/dist/web/agents-config-page.js +115 -2
- 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 +56 -5
- package/dist/web/workflow-health.d.ts +66 -0
- package/dist/web/workflow-health.js +76 -0
- package/package.json +1 -1
|
@@ -7,7 +7,7 @@ export interface Version {
|
|
|
7
7
|
reason?: string;
|
|
8
8
|
content: string;
|
|
9
9
|
}
|
|
10
|
-
export type AuditEventKind = 'decision' | 'answer' | 'feedback';
|
|
10
|
+
export type AuditEventKind = 'decision' | 'answer' | 'feedback' | 'change';
|
|
11
11
|
export interface AuditEvent {
|
|
12
12
|
id: number;
|
|
13
13
|
at: string;
|
|
@@ -24,6 +24,10 @@ export declare function schedulerDir(): string;
|
|
|
24
24
|
/** The process-wide database; undefined where node:sqlite isn't there,
|
|
25
25
|
* or LOOPENGINE_RUN_STORE=files asks for the JSON files. */
|
|
26
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;
|
|
27
31
|
/** Tests: use this database (or none). */
|
|
28
32
|
export declare function setAuditDb(next: DatabaseSync | undefined): void;
|
|
29
33
|
/** How long finished runs are kept, in days. */
|
|
@@ -35,6 +39,24 @@ export declare function recordEvent(event: Omit<AuditEvent, 'id' | 'at'> & {
|
|
|
35
39
|
}, database?: DatabaseSync | undefined): void;
|
|
36
40
|
/** A run's events, oldest first. */
|
|
37
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[];
|
|
38
60
|
/** The version number of `content`: the latest version's when it's the
|
|
39
61
|
* same text, else a new version noted now. Undefined without a database.
|
|
40
62
|
* `agent` and `workflowId` are '' for the workspace's policies. */
|
package/dist/core/audit-store.js
CHANGED
|
@@ -8,6 +8,14 @@
|
|
|
8
8
|
// - events: what people did in or about a run (an approval decided, with
|
|
9
9
|
// the tool's input before and after a change and any reason; a question
|
|
10
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);
|
|
11
19
|
// - versions: each workflow's brief (its instructions and result format)
|
|
12
20
|
// and the workspace's shared policies, numbered. A new version is noted
|
|
13
21
|
// whenever the text differs from the latest, however it changed: saved
|
|
@@ -47,6 +55,64 @@ CREATE TABLE IF NOT EXISTS events (
|
|
|
47
55
|
);
|
|
48
56
|
CREATE INDEX IF NOT EXISTS events_run ON events (run_id);
|
|
49
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);
|
|
50
116
|
CREATE TABLE IF NOT EXISTS versions (
|
|
51
117
|
agent TEXT NOT NULL,
|
|
52
118
|
workflow_id TEXT NOT NULL,
|
|
@@ -101,6 +167,15 @@ export function auditDb() {
|
|
|
101
167
|
db = process.env.LOOPENGINE_RUN_STORE === 'files' ? null : (openAuditDb(schedulerDir()) ?? null);
|
|
102
168
|
return db ?? undefined;
|
|
103
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
|
+
}
|
|
104
179
|
/** Tests: use this database (or none). */
|
|
105
180
|
export function setAuditDb(next) {
|
|
106
181
|
db = next ?? null;
|
|
@@ -127,8 +202,42 @@ export function recordEvent(event, database = auditDb()) {
|
|
|
127
202
|
export function runEvents(runId, database = auditDb()) {
|
|
128
203
|
if (!database)
|
|
129
204
|
return [];
|
|
130
|
-
|
|
131
|
-
|
|
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 {
|
|
132
241
|
id: Number(r.id),
|
|
133
242
|
at: String(r.at),
|
|
134
243
|
agent: String(r.agent),
|
|
@@ -137,7 +246,7 @@ export function runEvents(runId, database = auditDb()) {
|
|
|
137
246
|
kind: String(r.kind),
|
|
138
247
|
...(r.by ? { by: String(r.by) } : {}),
|
|
139
248
|
data: JSON.parse(String(r.data)),
|
|
140
|
-
}
|
|
249
|
+
};
|
|
141
250
|
}
|
|
142
251
|
// ---------- versions ----------
|
|
143
252
|
const hashOf = (content) => createHash('sha256').update(content).digest('hex');
|
|
@@ -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;
|
|
@@ -1,19 +1,76 @@
|
|
|
1
1
|
// The thread map: which approval request or question each posted message
|
|
2
2
|
// is, so a reply in its thread reaches the right one after a restart or a
|
|
3
3
|
// sleep. A notifier reports where it posted (SlackNotifier's onThread);
|
|
4
|
-
// this keeps it in
|
|
4
|
+
// this keeps it in the workspace's database (core/audit-store.ts), keyed
|
|
5
|
+
// by the agent's folder name, and looks it up by index. What an agent
|
|
6
|
+
// had in agents/<name>/.messaging/threads.jsonl and jobs.jsonl, one line
|
|
7
|
+
// each, is copied in the first time; where there's no database, those
|
|
8
|
+
// files are still where it's kept.
|
|
5
9
|
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
6
|
-
import { join } from 'node:path';
|
|
10
|
+
import { basename, join, resolve } from 'node:path';
|
|
11
|
+
import { auditDb } from '../audit-store.js';
|
|
7
12
|
function threadsFile(agentDir) {
|
|
8
13
|
return join(agentDir, '.messaging', 'threads.jsonl');
|
|
9
14
|
}
|
|
10
|
-
|
|
11
|
-
|
|
15
|
+
// The database, with this agent's old .messaging files copied in (once
|
|
16
|
+
// per agent; noted in meta so a restart doesn't copy them again).
|
|
17
|
+
const imported = new Set();
|
|
18
|
+
function dbFor(agentDir) {
|
|
19
|
+
const db = auditDb();
|
|
20
|
+
if (!db)
|
|
21
|
+
return undefined;
|
|
22
|
+
const agent = basename(resolve(agentDir));
|
|
23
|
+
if (!imported.has(agent)) {
|
|
24
|
+
imported.add(agent);
|
|
25
|
+
try {
|
|
26
|
+
importFiles(db, agentDir, agent);
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
console.error(`[loopengine] could not copy ${agent}'s message threads into the database:`, err instanceof Error ? err.message : err);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return { db, agent };
|
|
33
|
+
}
|
|
34
|
+
function importFiles(db, agentDir, agent) {
|
|
35
|
+
const key = `threads_imported:${agent}`;
|
|
36
|
+
if (db.prepare('SELECT value FROM meta WHERE key = ?').get(key))
|
|
37
|
+
return;
|
|
38
|
+
db.exec('BEGIN');
|
|
39
|
+
try {
|
|
40
|
+
for (const link of readLinks(agentDir))
|
|
41
|
+
insertThread(db, agent, link, link.at);
|
|
42
|
+
for (const job of readJobs(agentDir))
|
|
43
|
+
insertJob(db, agent, job, job.at);
|
|
44
|
+
db.prepare('INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)').run(key, new Date().toISOString());
|
|
45
|
+
db.exec('COMMIT');
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
db.exec('ROLLBACK');
|
|
49
|
+
throw err;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function linkData(link) {
|
|
53
|
+
const { app, conversation, ts, pendingId, kind, proposedArgs, choiceTs, buttonsTs } = link;
|
|
54
|
+
return { app, conversation, ts, pendingId, kind, ...(proposedArgs ? { proposedArgs } : {}), ...(choiceTs ? { choiceTs } : {}), ...(buttonsTs ? { buttonsTs } : {}) };
|
|
55
|
+
}
|
|
56
|
+
function insertThread(db, agent, link, at = new Date().toISOString()) {
|
|
57
|
+
db.prepare('INSERT INTO threads (agent, app, conversation, ts, pending_id, data, at) VALUES (?, ?, ?, ?, ?, ?, ?)')
|
|
58
|
+
.run(agent, link.app, link.conversation, link.ts, link.pendingId, JSON.stringify(linkData(link)), at);
|
|
59
|
+
}
|
|
60
|
+
function insertJob(db, agent, job, at = new Date().toISOString()) {
|
|
61
|
+
db.prepare('INSERT INTO job_threads (agent, app, conversation, ts, session_id, at) VALUES (?, ?, ?, ?, ?, ?)')
|
|
62
|
+
.run(agent, job.app, job.conversation, job.ts, job.sessionId, at);
|
|
63
|
+
}
|
|
64
|
+
/** Records one request's thread; the latest record of a request wins.
|
|
65
|
+
* Never throws: a request that can't be mapped still works through its
|
|
66
|
+
* buttons and link. */
|
|
12
67
|
export function recordThread(agentDir, link) {
|
|
13
68
|
try {
|
|
69
|
+
const store = dbFor(agentDir);
|
|
70
|
+
if (store)
|
|
71
|
+
return insertThread(store.db, store.agent, link);
|
|
14
72
|
mkdirSync(join(agentDir, '.messaging'), { recursive: true });
|
|
15
|
-
|
|
16
|
-
appendFileSync(threadsFile(agentDir), JSON.stringify({ app, conversation, ts, pendingId, kind, ...(proposedArgs ? { proposedArgs } : {}), ...(choiceTs ? { choiceTs } : {}), ...(buttonsTs ? { buttonsTs } : {}), at: new Date().toISOString() }) + '\n');
|
|
73
|
+
appendFileSync(threadsFile(agentDir), JSON.stringify({ ...linkData(link), at: new Date().toISOString() }) + '\n');
|
|
17
74
|
}
|
|
18
75
|
catch (err) {
|
|
19
76
|
console.error('[loopengine] could not record the thread:', err instanceof Error ? err.message : err);
|
|
@@ -21,6 +78,11 @@ export function recordThread(agentDir, link) {
|
|
|
21
78
|
}
|
|
22
79
|
/** The thread a request was posted in, found by its pendingId. */
|
|
23
80
|
export function findThreadByPending(agentDir, pendingId) {
|
|
81
|
+
const store = dbFor(agentDir);
|
|
82
|
+
if (store) {
|
|
83
|
+
const row = store.db.prepare('SELECT data FROM threads WHERE agent = ? AND pending_id = ? ORDER BY id DESC LIMIT 1').get(store.agent, pendingId);
|
|
84
|
+
return row ? JSON.parse(row.data) : undefined;
|
|
85
|
+
}
|
|
24
86
|
return readLinks(agentDir).filter((link) => link.pendingId === pendingId).at(-1);
|
|
25
87
|
}
|
|
26
88
|
function readLinks(agentDir) {
|
|
@@ -40,6 +102,11 @@ function readLinks(agentDir) {
|
|
|
40
102
|
}
|
|
41
103
|
/** The request a thread belongs to, or undefined for any other thread. */
|
|
42
104
|
export function findThread(agentDir, app, conversation, ts) {
|
|
105
|
+
const store = dbFor(agentDir);
|
|
106
|
+
if (store) {
|
|
107
|
+
const row = store.db.prepare('SELECT data FROM threads WHERE agent = ? AND app = ? AND conversation = ? AND ts = ? ORDER BY id DESC LIMIT 1').get(store.agent, app, conversation, ts);
|
|
108
|
+
return row ? JSON.parse(row.data) : undefined;
|
|
109
|
+
}
|
|
43
110
|
return readLinks(agentDir).filter((link) => link.app === app && link.conversation === conversation && link.ts === ts).at(-1);
|
|
44
111
|
}
|
|
45
112
|
function jobsFile(agentDir) {
|
|
@@ -63,6 +130,9 @@ function readJobs(agentDir) {
|
|
|
63
130
|
/** Never throws, like recordThread. */
|
|
64
131
|
export function recordJobThread(agentDir, job) {
|
|
65
132
|
try {
|
|
133
|
+
const store = dbFor(agentDir);
|
|
134
|
+
if (store)
|
|
135
|
+
return insertJob(store.db, store.agent, job);
|
|
66
136
|
mkdirSync(join(agentDir, '.messaging'), { recursive: true });
|
|
67
137
|
const { app, conversation, ts, sessionId } = job;
|
|
68
138
|
appendFileSync(jobsFile(agentDir), JSON.stringify({ app, conversation, ts, sessionId, at: new Date().toISOString() }) + '\n');
|
|
@@ -71,10 +141,19 @@ export function recordJobThread(agentDir, job) {
|
|
|
71
141
|
console.error('[loopengine] could not record the job thread:', err instanceof Error ? err.message : err);
|
|
72
142
|
}
|
|
73
143
|
}
|
|
144
|
+
function jobOf(row) {
|
|
145
|
+
return row ? { app: String(row.app), conversation: String(row.conversation), ts: String(row.ts), sessionId: String(row.session_id) } : undefined;
|
|
146
|
+
}
|
|
74
147
|
export function findJobThread(agentDir, app, conversation, ts) {
|
|
148
|
+
const store = dbFor(agentDir);
|
|
149
|
+
if (store)
|
|
150
|
+
return jobOf(store.db.prepare('SELECT * FROM job_threads WHERE agent = ? AND app = ? AND conversation = ? AND ts = ? ORDER BY id DESC LIMIT 1').get(store.agent, app, conversation, ts));
|
|
75
151
|
return readJobs(agentDir).filter((job) => job.app === app && job.conversation === conversation && job.ts === ts).at(-1);
|
|
76
152
|
}
|
|
77
153
|
/** The session's latest job thread: where its last message came from. */
|
|
78
154
|
export function findJobThreadBySession(agentDir, sessionId) {
|
|
155
|
+
const store = dbFor(agentDir);
|
|
156
|
+
if (store)
|
|
157
|
+
return jobOf(store.db.prepare('SELECT * FROM job_threads WHERE agent = ? AND session_id = ? ORDER BY id DESC LIMIT 1').get(store.agent, sessionId));
|
|
79
158
|
return readJobs(agentDir).filter((job) => job.sessionId === sessionId).at(-1);
|
|
80
159
|
}
|
package/dist/core/run-agent.js
CHANGED
|
@@ -574,6 +574,7 @@ async function runLoop(ctx, messages, newMessages, starterMessage) {
|
|
|
574
574
|
// Recorded inside the retried call, not after it, so a retry that
|
|
575
575
|
// spent tokens and then failed is still counted.
|
|
576
576
|
const { value: response } = await recovery.call(async (msgs) => {
|
|
577
|
+
const started = Date.now();
|
|
577
578
|
const result = await modelCall(msgs, systemPrompt, toolSchemas);
|
|
578
579
|
if (result.usage) {
|
|
579
580
|
recordUsage({
|
|
@@ -584,6 +585,7 @@ async function runLoop(ctx, messages, newMessages, starterMessage) {
|
|
|
584
585
|
...modelLabel,
|
|
585
586
|
inputTokens: result.usage.input_tokens,
|
|
586
587
|
outputTokens: result.usage.output_tokens,
|
|
588
|
+
durationMs: Date.now() - started,
|
|
587
589
|
});
|
|
588
590
|
}
|
|
589
591
|
return result;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
1
2
|
import { Redis } from 'ioredis';
|
|
2
|
-
import { type Storage } from './sessionknit.js';
|
|
3
|
+
import { type Storage, type SessionEntry } from './sessionknit.js';
|
|
3
4
|
import type { Message } from '#core/run-agent.js';
|
|
4
5
|
export interface SessionResult<T> {
|
|
5
6
|
/** Exactly what this turn added — durably appended as-is, in order.
|
|
@@ -61,6 +62,35 @@ declare class SessionKnitStore implements SessionStore {
|
|
|
61
62
|
export declare class FileSessionStore extends SessionKnitStore {
|
|
62
63
|
constructor(dir: string);
|
|
63
64
|
}
|
|
65
|
+
/** SessionKnit Storage in the workspace's database (core/audit-store.ts):
|
|
66
|
+
* one row per entry, with when it was written. A write is durable when
|
|
67
|
+
* it returns, so flush() has nothing to do. A session still in
|
|
68
|
+
* FileStorage's JSONL under `importFrom` is copied in the first time
|
|
69
|
+
* it's read. */
|
|
70
|
+
export declare class SqliteEntryStorage implements Storage<Message> {
|
|
71
|
+
private readonly db;
|
|
72
|
+
private readonly importFrom?;
|
|
73
|
+
constructor(db: DatabaseSync, importFrom?: string | undefined);
|
|
74
|
+
append(sessionId: string, entry: SessionEntry<Message>): Promise<void>;
|
|
75
|
+
private insert;
|
|
76
|
+
flush(): Promise<void>;
|
|
77
|
+
readAll(sessionId: string): Promise<SessionEntry<Message>[]>;
|
|
78
|
+
/** The entries with when each was written (imported ones: the file's
|
|
79
|
+
* time, the same for each). */
|
|
80
|
+
readTimed(sessionId: string): Promise<(SessionEntry<Message> & {
|
|
81
|
+
at: string;
|
|
82
|
+
})[]>;
|
|
83
|
+
private importFile;
|
|
84
|
+
}
|
|
85
|
+
/** Sessions in the workspace's database; one process, like
|
|
86
|
+
* FileSessionStore. Sessions in `.sessions` files (`importFrom`) are
|
|
87
|
+
* copied in as they're first read. */
|
|
88
|
+
export declare class SqliteSessionStore extends SessionKnitStore {
|
|
89
|
+
readonly entries: SqliteEntryStorage;
|
|
90
|
+
constructor(db: DatabaseSync, options?: {
|
|
91
|
+
importFrom?: string;
|
|
92
|
+
});
|
|
93
|
+
}
|
|
64
94
|
export interface RedisSessionStoreOptions {
|
|
65
95
|
lockTtlMs?: number;
|
|
66
96
|
lockRetryDelayMs?: number;
|
|
@@ -92,7 +122,9 @@ export declare class RedisSessionStore extends SessionKnitStore {
|
|
|
92
122
|
private withLock;
|
|
93
123
|
}
|
|
94
124
|
/** Picks the store from environment so adapters don't hardcode a backend:
|
|
95
|
-
* REDIS_URL set -> RedisSessionStore (required once you run >1 instance)
|
|
96
|
-
* otherwise
|
|
125
|
+
* REDIS_URL set -> RedisSessionStore (required once you run >1 instance);
|
|
126
|
+
* otherwise the workspace's database, reading what's in .sessions as
|
|
127
|
+
* each session is first opened; FileSessionStore under .sessions where
|
|
128
|
+
* there's no database. */
|
|
97
129
|
export declare function createSessionStore(): SessionStore;
|
|
98
130
|
export {};
|