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.
@@ -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 agents/<name>/.messaging/threads.jsonl, one line each.
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
- /** Appends one request's thread. Never throws: a request that can't be
11
- * mapped still works through its buttons and link. */
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
- const { app, conversation, ts, pendingId, kind, proposedArgs, choiceTs, buttonsTs } = link;
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
  }
@@ -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 FileSessionStore under .sessions (fine for local dev). */
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 {};
@@ -27,8 +27,10 @@
27
27
  // still serializes concurrent withSession calls for the same sessionId
28
28
  // itself (KeyedMutex / a Redis lock), same as before.
29
29
  import { randomUUID } from 'node:crypto';
30
+ import { existsSync, readFileSync } from 'node:fs';
30
31
  import path from 'node:path';
31
32
  import { Redis } from 'ioredis';
33
+ import { auditDb } from './audit-store.js';
32
34
  import { SessionKnit, FileStorage } from './sessionknit.js';
33
35
  /** Serializes async work per key within this process. Good enough for
34
36
  * FileSessionStore (single process); RedisSessionStore needs a real
@@ -141,6 +143,77 @@ export class FileSessionStore extends SessionKnitStore {
141
143
  super(new FileStorage(dir), (sessionId, fn) => fileMutex.run(path.resolve(dir, sessionId), fn));
142
144
  }
143
145
  }
146
+ /** SessionKnit Storage in the workspace's database (core/audit-store.ts):
147
+ * one row per entry, with when it was written. A write is durable when
148
+ * it returns, so flush() has nothing to do. A session still in
149
+ * FileStorage's JSONL under `importFrom` is copied in the first time
150
+ * it's read. */
151
+ export class SqliteEntryStorage {
152
+ db;
153
+ importFrom;
154
+ constructor(db, importFrom) {
155
+ this.db = db;
156
+ this.importFrom = importFrom;
157
+ }
158
+ async append(sessionId, entry) {
159
+ this.insert(sessionId, entry, new Date().toISOString());
160
+ }
161
+ insert(sessionId, entry, at) {
162
+ this.db.prepare('INSERT INTO session_entries (session_id, id, parent_id, at, data) VALUES (?, ?, ?, ?, ?)')
163
+ .run(sessionId, entry.id, entry.parentId, at, JSON.stringify(entry.message));
164
+ }
165
+ async flush() { }
166
+ async readAll(sessionId) {
167
+ return (await this.readTimed(sessionId)).map(({ at: _at, ...entry }) => entry);
168
+ }
169
+ /** The entries with when each was written (imported ones: the file's
170
+ * time, the same for each). */
171
+ async readTimed(sessionId) {
172
+ const read = () => this.db.prepare('SELECT id, parent_id, at, data FROM session_entries WHERE session_id = ? ORDER BY seq').all(sessionId);
173
+ let rows = read();
174
+ if (!rows.length && this.importFrom && this.importFile(sessionId))
175
+ rows = read();
176
+ return rows.map((r) => ({ id: r.id, parentId: r.parent_id, message: JSON.parse(r.data), at: r.at }));
177
+ }
178
+ importFile(sessionId) {
179
+ const file = path.join(this.importFrom, `${sessionId.replace(/[/\\]/g, '_')}.jsonl`);
180
+ if (!existsSync(file))
181
+ return false;
182
+ const entries = readFileSync(file, 'utf8').split('\n').filter(Boolean).flatMap((line) => {
183
+ try {
184
+ return [JSON.parse(line)];
185
+ }
186
+ catch {
187
+ return [];
188
+ }
189
+ });
190
+ if (!entries.length)
191
+ return false;
192
+ const at = new Date().toISOString();
193
+ this.db.exec('BEGIN');
194
+ try {
195
+ for (const entry of entries)
196
+ this.insert(sessionId, entry, at);
197
+ this.db.exec('COMMIT');
198
+ }
199
+ catch (err) {
200
+ this.db.exec('ROLLBACK');
201
+ throw err;
202
+ }
203
+ return true;
204
+ }
205
+ }
206
+ /** Sessions in the workspace's database; one process, like
207
+ * FileSessionStore. Sessions in `.sessions` files (`importFrom`) are
208
+ * copied in as they're first read. */
209
+ export class SqliteSessionStore extends SessionKnitStore {
210
+ entries;
211
+ constructor(db, options = {}) {
212
+ const entries = new SqliteEntryStorage(db, options.importFrom);
213
+ super(entries, (sessionId, fn) => fileMutex.run(`sqlite:${sessionId}`, fn));
214
+ this.entries = entries;
215
+ }
216
+ }
144
217
  /** SessionKnit Storage backed by a Redis list — one RPUSH per appended
145
218
  * entry. Redis is already durable per write, so unlike FileStorage there's
146
219
  * nothing to debounce: flush() is a no-op. */
@@ -260,9 +333,14 @@ export class RedisSessionStore extends SessionKnitStore {
260
333
  }
261
334
  }
262
335
  /** Picks the store from environment so adapters don't hardcode a backend:
263
- * REDIS_URL set -> RedisSessionStore (required once you run >1 instance),
264
- * otherwise FileSessionStore under .sessions (fine for local dev). */
336
+ * REDIS_URL set -> RedisSessionStore (required once you run >1 instance);
337
+ * otherwise the workspace's database, reading what's in .sessions as
338
+ * each session is first opened; FileSessionStore under .sessions where
339
+ * there's no database. */
265
340
  export function createSessionStore() {
266
341
  const redisUrl = process.env.REDIS_URL;
267
- return redisUrl ? new RedisSessionStore(redisUrl) : new FileSessionStore('.sessions');
342
+ if (redisUrl)
343
+ return new RedisSessionStore(redisUrl);
344
+ const db = auditDb();
345
+ return db ? new SqliteSessionStore(db, { importFrom: '.sessions' }) : new FileSessionStore('.sessions');
268
346
  }
@@ -9,6 +9,13 @@ export interface UsageEvent {
9
9
  model?: string;
10
10
  inputTokens: number;
11
11
  outputTokens: number;
12
+ /** How long the call took, retries included. */
13
+ durationMs?: number;
14
+ }
15
+ export interface UsageRow extends UsageEvent {
16
+ id: number;
17
+ /** What it cost in US dollars, where the model's price is known. */
18
+ costUsd?: number;
12
19
  }
13
20
  export type UsageSink = (event: UsageEvent) => void;
14
21
  /** Replaces the sink for this whole process; undefined turns usage
@@ -16,3 +23,7 @@ export type UsageSink = (event: UsageEvent) => void;
16
23
  export declare function setUsageSink(next: UsageSink | undefined): void;
17
24
  /** Never throws — a broken sink must not fail the agent's turn. */
18
25
  export declare function recordUsage(event: UsageEvent): void;
26
+ /** A session's model calls, oldest first. */
27
+ export declare function sessionUsage(agent: string, sessionId: string): UsageRow[];
28
+ /** Several sessions' model calls, by session, oldest first. */
29
+ export declare function usageBySession(agent: string, sessionIds: string[]): Map<string, UsageRow[]>;
@@ -1,10 +1,11 @@
1
- // Token usage per model call — off unless a sink is configured, so a
2
- // self-hosted install that doesn't ask for it sees no change at all.
3
- // Configure with LOOPENGINE_USAGE_LOG (`stdout` for one JSON line per
1
+ // Token usage per model call. Kept in the workspace's database
2
+ // (core/audit-store.ts) for each run's steps and totals, and also sent
3
+ // to a sink when one is configured with LOOPENGINE_USAGE_LOG (`stdout` for one JSON line per
4
4
  // call on stdout, or a file path to append JSON lines to), or in code
5
5
  // with setUsageSink() — a host billing for model usage, or anyone
6
6
  // wanting a per-agent token count.
7
7
  import { appendFileSync } from 'node:fs';
8
+ import { auditDb } from './audit-store.js';
8
9
  function sinkFromEnv() {
9
10
  const target = process.env.LOOPENGINE_USAGE_LOG;
10
11
  if (!target)
@@ -21,6 +22,15 @@ export function setUsageSink(next) {
21
22
  }
22
23
  /** Never throws — a broken sink must not fail the agent's turn. */
23
24
  export function recordUsage(event) {
25
+ const db = auditDb();
26
+ if (db) {
27
+ try {
28
+ db.prepare('INSERT INTO usage (at, agent, tenant, session_id, provider, model, input_tokens, output_tokens, duration_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)').run(event.at, event.agent, event.tenant, event.sessionId ?? null, event.provider ?? null, event.model ?? null, event.inputTokens, event.outputTokens, event.durationMs ?? null);
29
+ }
30
+ catch (err) {
31
+ console.error('[loopengine] could not record usage:', err);
32
+ }
33
+ }
24
34
  if (!sink)
25
35
  return;
26
36
  try {
@@ -30,3 +40,41 @@ export function recordUsage(event) {
30
40
  console.error('[loopengine] usage sink failed:', err);
31
41
  }
32
42
  }
43
+ /** A session's model calls, oldest first. */
44
+ export function sessionUsage(agent, sessionId) {
45
+ const db = auditDb();
46
+ if (!db)
47
+ return [];
48
+ const rows = db.prepare('SELECT * FROM usage WHERE agent = ? AND session_id = ? ORDER BY id').all(agent, sessionId);
49
+ return rows.map(rowOf);
50
+ }
51
+ /** Several sessions' model calls, by session, oldest first. */
52
+ export function usageBySession(agent, sessionIds) {
53
+ const out = new Map();
54
+ const db = auditDb();
55
+ if (!db || !sessionIds.length)
56
+ return out;
57
+ for (let i = 0; i < sessionIds.length; i += 500) {
58
+ const chunk = sessionIds.slice(i, i + 500);
59
+ const rows = db.prepare(`SELECT * FROM usage WHERE agent = ? AND session_id IN (${chunk.map(() => '?').join(', ')}) ORDER BY id`).all(agent, ...chunk);
60
+ for (const r of rows) {
61
+ const row = rowOf(r);
62
+ out.set(row.sessionId, [...(out.get(row.sessionId) ?? []), row]);
63
+ }
64
+ }
65
+ return out;
66
+ }
67
+ function rowOf(r) {
68
+ return {
69
+ id: Number(r.id),
70
+ at: String(r.at),
71
+ agent: String(r.agent),
72
+ tenant: String(r.tenant),
73
+ ...(r.session_id ? { sessionId: String(r.session_id) } : {}),
74
+ ...(r.provider ? { provider: String(r.provider) } : {}),
75
+ ...(r.model ? { model: String(r.model) } : {}),
76
+ inputTokens: Number(r.input_tokens),
77
+ outputTokens: Number(r.output_tokens),
78
+ ...(r.duration_ms != null ? { durationMs: Number(r.duration_ms) } : {}),
79
+ };
80
+ }
@@ -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,17 @@ 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>;
131
+ /** A workflow's runs started at or after `since`, however many. */
132
+ since?(agent: string, workflowId: string, since: string): Promise<WorkflowRun[]>;
107
133
  }
108
134
  /** One JSON file per run under `<dir>/runs/` — one server process. */
109
135
  export declare class FileRunStore implements RunStore {
@@ -116,7 +142,39 @@ export declare class FileRunStore implements RunStore {
116
142
  remove(runId: string): Promise<void>;
117
143
  update(runId: string, fn: (run: WorkflowRun | undefined) => WorkflowRun | undefined): Promise<WorkflowRun | undefined>;
118
144
  }
119
- /** The process-wide store: `runs/` in the scheduler's folder. */
145
+ /** Runs in the workspace's database (core/audit-store.ts). list() is what
146
+ * the console shows: every run under way, and each agent's latest
147
+ * `listed` finished ones; older runs stay until the retention period
148
+ * ends. */
149
+ export declare class SqliteRunStore implements RunStore {
150
+ private readonly db;
151
+ private readonly listed;
152
+ private lastPrune;
153
+ /** `importFrom`: a scheduler folder whose runs/ JSON files are copied in
154
+ * the first time. */
155
+ constructor(db: DatabaseSync, options?: {
156
+ importFrom?: string;
157
+ listed?: number;
158
+ });
159
+ private importFiles;
160
+ private write;
161
+ private read;
162
+ list(): Promise<WorkflowRun[]>;
163
+ forAgent(agent: string, filter: {
164
+ workflowId?: string;
165
+ limit?: number;
166
+ }): Promise<WorkflowRun[]>;
167
+ since(agent: string, workflowId: string, since: string): Promise<WorkflowRun[]>;
168
+ bySession(sessionId: string): Promise<WorkflowRun | undefined>;
169
+ get(runId: string): Promise<WorkflowRun | undefined>;
170
+ put(run: WorkflowRun): Promise<void>;
171
+ remove(runId: string): Promise<void>;
172
+ update(runId: string, fn: (run: WorkflowRun | undefined) => WorkflowRun | undefined): Promise<WorkflowRun | undefined>;
173
+ /** At most hourly: runs finished before the retention period. */
174
+ prune(): Promise<void>;
175
+ }
176
+ /** The process-wide store: the workspace's database, or JSON files in
177
+ * `runs/` in the scheduler's folder where there's none. */
120
178
  export declare function getRunStore(): RunStore;
121
179
  export declare function setRunStore(next: RunStore): void;
122
180
  /** An agent's runs, newest first; of one workflow when `workflowId` is given. */
@@ -124,6 +182,9 @@ export declare function listRuns(agent: string, filter?: {
124
182
  workflowId?: string;
125
183
  limit?: number;
126
184
  }): Promise<WorkflowRun[]>;
185
+ /** A workflow's runs started at or after `since` (an ISO time), oldest
186
+ * first; from the console's list where the store keeps no more. */
187
+ export declare function runsSince(agent: string, workflowId: string, since: string): Promise<WorkflowRun[]>;
127
188
  /** One of an agent's runs; undefined for another agent's. */
128
189
  export declare function getRun(agent: string, runId: string): Promise<WorkflowRun | undefined>;
129
190
  export declare function isUnderWay(run: WorkflowRun): boolean;
@@ -150,15 +211,19 @@ export declare class WorkflowRunner {
150
211
  private readonly execute;
151
212
  private readonly maxFinishedPerAgent;
152
213
  private readonly onChange?;
214
+ private readonly versionsFor?;
153
215
  private readonly inFlight;
154
216
  /** `onChange`: called with the run when it starts, and each time it
155
217
  * finishes, fails or stops for a decision (the server sends its chat
156
- * messages and callbacks). */
218
+ * messages and callbacks). `versionsFor`: the brief and policies
219
+ * versions a run of this workflow starts under. */
157
220
  constructor(options: {
158
221
  execute: ExecuteRun;
159
222
  maxFinishedPerAgent?: number;
160
223
  onChange?: (run: WorkflowRun) => void | Promise<void>;
224
+ versionsFor?: (agent: string, workflowId: string) => RunVersions | undefined;
161
225
  });
226
+ private versionsOf;
162
227
  private changed;
163
228
  /** Records a run and starts it; returns at once with the record. */
164
229
  start(input: StartRunInput): Promise<WorkflowRun>;
@@ -190,13 +255,20 @@ export declare class WorkflowRunner {
190
255
  }): Promise<void>;
191
256
  /** The run a session belongs to, if it's a workflow run's. */
192
257
  forSession(sessionId: string): Promise<WorkflowRun | undefined>;
193
- /** Records an approval decided in a run's session. */
258
+ /** Records an approval decided in a run's session: on the run, and in
259
+ * the workspace's audit events. */
194
260
  recordDecision(sessionId: string, decision: {
195
261
  tool: string;
196
262
  approved: boolean;
197
263
  by?: string;
198
264
  edited?: boolean;
265
+ before?: unknown;
266
+ after?: unknown;
267
+ reason?: string;
199
268
  }): Promise<void>;
269
+ /** Records feedback given on a run's result in the audit events (the
270
+ * run itself carries the latest). */
271
+ recordFeedback(run: WorkflowRun, feedback: RunFeedback, by?: string): void;
200
272
  /** Records a question answered in a run's session. */
201
273
  recordAnswer(sessionId: string, answer: {
202
274
  question: string;