loopengine 0.4.3 → 0.4.5

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.
@@ -0,0 +1,39 @@
1
+ export declare const AUDIT_ANCHORS_PATH = "/api/workspace/audit-anchors";
2
+ export interface AnchorConfig {
3
+ url: string;
4
+ slug: string;
5
+ secret: string;
6
+ }
7
+ /** Where anchors go and how to sign, or why they stay local. */
8
+ export declare function anchorConfig(env?: NodeJS.ProcessEnv): AnchorConfig | {
9
+ off: string;
10
+ };
11
+ export declare function signAnchorRequest(body: string, timestamp: number, secret: string): string;
12
+ export type AnchorResult = {
13
+ status: 'sent' | 'kept-here';
14
+ eventId: number;
15
+ } | {
16
+ status: 'nothing-new';
17
+ } | {
18
+ status: 'failed';
19
+ reason: string;
20
+ };
21
+ /** Anchors the latest event, unless it already is. Never throws. Off
22
+ * Cloud, the anchor is noted only here. */
23
+ export declare function anchorLatest(config?: AnchorConfig | {
24
+ off: string;
25
+ }, fetchImpl?: typeof fetch): Promise<AnchorResult>;
26
+ /** The anchors kept at loopengine.co, or undefined off Cloud or when
27
+ * they can't be fetched (with why). */
28
+ export declare function fetchAnchors(config?: AnchorConfig | {
29
+ off: string;
30
+ }, fetchImpl?: typeof fetch): Promise<{
31
+ anchors: {
32
+ eventId: number;
33
+ hash: string;
34
+ }[];
35
+ } | {
36
+ unavailable: string;
37
+ }>;
38
+ /** Anchors now (a minute after start) and then daily. */
39
+ export declare function startAuditAnchoring(log?: (message: string) => void): void;
@@ -0,0 +1,90 @@
1
+ // Anchors the audit log's hash chain (core/audit-store.ts) outside the
2
+ // workspace: once a day, the latest event's id and hash go to
3
+ // loopengine.co (POST /api/workspace/audit-anchors), which keeps them
4
+ // where the workspace can't rewrite them. Checking the log
5
+ // (GET /audit/verify) fetches them back (GET on the same path) and
6
+ // matches each against the chain, so rewriting the whole chain to hide a
7
+ // change still shows.
8
+ //
9
+ // Signed like the workspace's other reports (web/lever-events-sync.ts):
10
+ // X-LoopEngine-Workspace names the workspace (from LOOPENGINE_PUBLIC_URL),
11
+ // X-LoopEngine-Signature is t=<unix seconds>,v1=<HMAC-SHA256 of
12
+ // "<t>.<body>"> with LOOPENGINE_TRUSTED_PROXY_SECRET (an empty body for
13
+ // the GET). Off outside LoopEngine Cloud: the anchors are then only kept
14
+ // in the workspace's own database, which shows a changed event but not a
15
+ // rewritten chain.
16
+ import { createHmac } from 'node:crypto';
17
+ import { lastAnchor, latestEventHash, noteAnchor } from './audit-store.js';
18
+ export const AUDIT_ANCHORS_PATH = '/api/workspace/audit-anchors';
19
+ const DAY_MS = 24 * 60 * 60 * 1000;
20
+ /** Where anchors go and how to sign, or why they stay local. */
21
+ export function anchorConfig(env = process.env) {
22
+ const secret = env.LOOPENGINE_TRUSTED_PROXY_SECRET;
23
+ if (!secret)
24
+ return { off: 'not a LoopEngine Cloud workspace' };
25
+ let slug;
26
+ try {
27
+ slug = env.LOOPENGINE_PUBLIC_URL ? new URL(env.LOOPENGINE_PUBLIC_URL).hostname.split('.')[0] : undefined;
28
+ }
29
+ catch { }
30
+ if (!slug)
31
+ return { off: 'LOOPENGINE_PUBLIC_URL is needed to name the workspace' };
32
+ return { url: `${(env.LOOPENGINE_CONTROL_PLANE_URL || 'https://loopengine.co').replace(/\/+$/, '')}${AUDIT_ANCHORS_PATH}`, slug, secret };
33
+ }
34
+ export function signAnchorRequest(body, timestamp, secret) {
35
+ return `t=${timestamp},v1=${createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex')}`;
36
+ }
37
+ function headers(config, body) {
38
+ return { 'content-type': 'application/json', 'x-loopengine-workspace': config.slug, 'x-loopengine-signature': signAnchorRequest(body, Math.floor(Date.now() / 1000), config.secret) };
39
+ }
40
+ /** Anchors the latest event, unless it already is. Never throws. Off
41
+ * Cloud, the anchor is noted only here. */
42
+ export async function anchorLatest(config = anchorConfig(), fetchImpl = fetch) {
43
+ const latest = latestEventHash();
44
+ if (!latest)
45
+ return { status: 'nothing-new' };
46
+ const last = lastAnchor();
47
+ if (last && last.eventId === latest.id && (last.sentAt || 'off' in config))
48
+ return { status: 'nothing-new' };
49
+ if ('off' in config) {
50
+ noteAnchor({ eventId: latest.id, hash: latest.hash, at: latest.at });
51
+ return { status: 'kept-here', eventId: latest.id };
52
+ }
53
+ const body = JSON.stringify({ eventId: latest.id, hash: latest.hash, eventAt: latest.at });
54
+ try {
55
+ const res = await fetchImpl(config.url, { method: 'POST', headers: headers(config, body), body, signal: AbortSignal.timeout(15_000) });
56
+ if (!res.ok)
57
+ return { status: 'failed', reason: `loopengine.co answered ${res.status}` };
58
+ }
59
+ catch (err) {
60
+ return { status: 'failed', reason: `couldn't reach ${config.url}: ${err instanceof Error ? err.message : String(err)}` };
61
+ }
62
+ noteAnchor({ eventId: latest.id, hash: latest.hash, at: latest.at, sentAt: new Date().toISOString() });
63
+ return { status: 'sent', eventId: latest.id };
64
+ }
65
+ /** The anchors kept at loopengine.co, or undefined off Cloud or when
66
+ * they can't be fetched (with why). */
67
+ export async function fetchAnchors(config = anchorConfig(), fetchImpl = fetch) {
68
+ if ('off' in config)
69
+ return { unavailable: config.off };
70
+ try {
71
+ const res = await fetchImpl(config.url, { headers: headers(config, ''), signal: AbortSignal.timeout(15_000) });
72
+ if (!res.ok)
73
+ return { unavailable: `loopengine.co answered ${res.status}` };
74
+ const body = (await res.json());
75
+ const anchors = (body.anchors ?? []).flatMap((a) => (typeof a.eventId === 'number' && typeof a.hash === 'string' ? [{ eventId: a.eventId, hash: a.hash }] : []));
76
+ return { anchors };
77
+ }
78
+ catch (err) {
79
+ return { unavailable: `couldn't reach loopengine.co: ${err instanceof Error ? err.message : String(err)}` };
80
+ }
81
+ }
82
+ /** Anchors now (a minute after start) and then daily. */
83
+ export function startAuditAnchoring(log = () => { }) {
84
+ const run = () => void anchorLatest().then((r) => {
85
+ if (r.status === 'failed')
86
+ log(`[loopengine] couldn't anchor the audit log: ${r.reason}`);
87
+ });
88
+ setTimeout(run, 60_000).unref();
89
+ setInterval(run, DAY_MS).unref();
90
+ }
@@ -17,9 +17,69 @@ export interface AuditEvent {
17
17
  kind: AuditEventKind;
18
18
  by?: string;
19
19
  data: Record<string, unknown>;
20
+ /** Its place in the hash chain: the event before's hash, and its own
21
+ * (eventHash). */
22
+ prev?: string;
23
+ hash?: string;
20
24
  }
21
25
  /** Opens (creating if need be) the database in `dir`. */
22
26
  export declare function openAuditDb(dir: string): DatabaseSync | undefined;
27
+ /** An event's hash: SHA-256 of the hash before it and its content. */
28
+ export declare function eventHash(prev: string, e: {
29
+ id: number;
30
+ at: string;
31
+ agent: string;
32
+ workflow_id?: string | null;
33
+ run_id?: string | null;
34
+ kind: string;
35
+ by?: string | null;
36
+ data: string;
37
+ }): string;
38
+ export interface ChainCheck {
39
+ ok: boolean;
40
+ /** Events checked. */
41
+ events: number;
42
+ /** The latest event, and its hash. */
43
+ last?: {
44
+ id: number;
45
+ at: string;
46
+ hash: string;
47
+ };
48
+ /** The first place the chain is broken, and how. */
49
+ broken?: {
50
+ id: number;
51
+ at?: string;
52
+ problem: 'changed' | 'missing-before' | 'missing-after-anchor' | 'anchor-differs';
53
+ };
54
+ /** Anchors checked against the chain. */
55
+ anchors: number;
56
+ }
57
+ /** Checks every event's hash, in order, and that each anchor (a hash
58
+ * sent away earlier: the workspace's own record, or `anchors` fetched
59
+ * back from where they were sent) still matches its event. */
60
+ export declare function verifyEventChain(anchors?: {
61
+ eventId: number;
62
+ hash: string;
63
+ }[], database?: DatabaseSync | undefined): ChainCheck;
64
+ /** The latest event's id and hash, to anchor. */
65
+ export declare function latestEventHash(database?: DatabaseSync | undefined): {
66
+ id: number;
67
+ at: string;
68
+ hash: string;
69
+ } | undefined;
70
+ /** Notes an anchor sent away (or kept only here, `sentAt` absent). */
71
+ export declare function noteAnchor(anchor: {
72
+ eventId: number;
73
+ hash: string;
74
+ at: string;
75
+ sentAt?: string;
76
+ }, database?: DatabaseSync | undefined): void;
77
+ export declare function lastAnchor(database?: DatabaseSync | undefined): {
78
+ eventId: number;
79
+ hash: string;
80
+ at: string;
81
+ sentAt?: string;
82
+ } | undefined;
23
83
  export declare function schedulerDir(): string;
24
84
  /** The process-wide database; undefined where node:sqlite isn't there,
25
85
  * or LOOPENGINE_RUN_STORE=files asks for the JSON files. */
@@ -34,7 +94,7 @@ export declare function setAuditDb(next: DatabaseSync | undefined): void;
34
94
  export declare function retentionDays(): number;
35
95
  /** Appends what someone did in or about a run. Never throws: the record
36
96
  * must not stop the work it records. */
37
- export declare function recordEvent(event: Omit<AuditEvent, 'id' | 'at'> & {
97
+ export declare function recordEvent(event: Omit<AuditEvent, 'id' | 'at' | 'prev' | 'hash'> & {
38
98
  at?: string;
39
99
  }, database?: DatabaseSync | undefined): void;
40
100
  /** A run's events, oldest first. */
@@ -57,6 +117,8 @@ export interface EventFilter {
57
117
  }
58
118
  /** Events matching the filter, newest first, at most 500. */
59
119
  export declare function listEvents(filter?: EventFilter, database?: DatabaseSync | undefined): AuditEvent[];
120
+ /** Everyone named on an event, most recent first (for a filter). */
121
+ export declare function eventPeople(limit?: number, database?: DatabaseSync | undefined): string[];
60
122
  /** The version number of `content`: the latest version's when it's the
61
123
  * same text, else a new version noted now. Undefined without a database.
62
124
  * `agent` and `workflowId` are '' for the workspace's policies. */
@@ -154,8 +154,105 @@ export function openAuditDb(dir) {
154
154
  const db = new sqlite.DatabaseSync(path.join(dir, 'loopengine.db'));
155
155
  db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;');
156
156
  db.exec(SCHEMA);
157
+ chainEvents(db);
157
158
  return db;
158
159
  }
160
+ // ---------- the hash chain ----------
161
+ //
162
+ // Each event carries a hash of its own content and of the event before's
163
+ // hash, so changing or removing any event breaks every link after it
164
+ // (verifyEventChain finds where). The latest hash is also sent away each
165
+ // day (core/audit-anchor.ts), so rewriting the whole chain doesn't pass
166
+ // either. It shows tampering; it can't prevent it.
167
+ const GENESIS = '';
168
+ /** An event's hash: SHA-256 of the hash before it and its content. */
169
+ export function eventHash(prev, e) {
170
+ const content = JSON.stringify([e.id, e.at, e.agent, e.workflow_id ?? null, e.run_id ?? null, e.kind, e.by ?? null, e.data]);
171
+ return createHash('sha256').update(prev).update('\n').update(content).digest('hex');
172
+ }
173
+ // Adds the chain's columns to a database from before them, and chains any
174
+ // event without a hash (those recorded before), in order.
175
+ function chainEvents(db) {
176
+ const columns = db.prepare('PRAGMA table_info(events)').all().map((c) => c.name);
177
+ if (!columns.includes('hash')) {
178
+ db.exec('ALTER TABLE events ADD COLUMN prev TEXT; ALTER TABLE events ADD COLUMN hash TEXT;');
179
+ }
180
+ db.exec("CREATE TABLE IF NOT EXISTS audit_anchors (event_id INTEGER PRIMARY KEY, hash TEXT NOT NULL, at TEXT NOT NULL, sent_at TEXT)");
181
+ const first = db.prepare('SELECT MIN(id) AS id FROM events WHERE hash IS NULL').get();
182
+ if (first.id == null)
183
+ return;
184
+ const before = db.prepare('SELECT hash FROM events WHERE id < ? ORDER BY id DESC LIMIT 1').get(first.id);
185
+ let prev = before?.hash ?? GENESIS;
186
+ const rows = db.prepare('SELECT * FROM events WHERE id >= ? ORDER BY id').all(first.id);
187
+ const set = db.prepare('UPDATE events SET prev = ?, hash = ? WHERE id = ?');
188
+ db.exec('BEGIN');
189
+ try {
190
+ for (const row of rows) {
191
+ const hash = eventHash(prev, row);
192
+ set.run(prev, hash, row.id);
193
+ prev = hash;
194
+ }
195
+ db.exec('COMMIT');
196
+ }
197
+ catch (err) {
198
+ db.exec('ROLLBACK');
199
+ throw err;
200
+ }
201
+ writeMeta('events_chained', `${new Date().toISOString()} ${rows.length}`, db);
202
+ }
203
+ /** Checks every event's hash, in order, and that each anchor (a hash
204
+ * sent away earlier: the workspace's own record, or `anchors` fetched
205
+ * back from where they were sent) still matches its event. */
206
+ export function verifyEventChain(anchors, database = auditDb()) {
207
+ if (!database)
208
+ return { ok: true, events: 0, anchors: 0 };
209
+ let prev = GENESIS;
210
+ let count = 0;
211
+ let last;
212
+ let after = 0;
213
+ const byId = new Map();
214
+ const kept = anchors ?? database.prepare('SELECT event_id AS eventId, hash FROM audit_anchors').all();
215
+ const wanted = new Set(kept.map((a) => a.eventId));
216
+ for (;;) {
217
+ const rows = database.prepare('SELECT * FROM events WHERE id > ? ORDER BY id LIMIT 5000').all(after);
218
+ if (!rows.length)
219
+ break;
220
+ for (const row of rows) {
221
+ if ((row.prev ?? GENESIS) !== prev)
222
+ return { ok: false, events: count, broken: { id: row.id, at: row.at, problem: 'missing-before' }, anchors: 0, ...(last ? { last } : {}) };
223
+ const hash = eventHash(prev, row);
224
+ if (hash !== row.hash)
225
+ return { ok: false, events: count, broken: { id: row.id, at: row.at, problem: 'changed' }, anchors: 0, ...(last ? { last } : {}) };
226
+ if (wanted.has(row.id))
227
+ byId.set(row.id, hash);
228
+ prev = hash;
229
+ count++;
230
+ last = { id: row.id, at: row.at, hash };
231
+ }
232
+ after = rows.at(-1).id;
233
+ }
234
+ for (const anchor of [...kept].sort((a, b) => a.eventId - b.eventId)) {
235
+ const hash = byId.get(anchor.eventId);
236
+ if (hash === undefined)
237
+ return { ok: false, events: count, broken: { id: anchor.eventId, problem: 'missing-after-anchor' }, anchors: kept.length, ...(last ? { last } : {}) };
238
+ if (hash !== anchor.hash)
239
+ return { ok: false, events: count, broken: { id: anchor.eventId, problem: 'anchor-differs' }, anchors: kept.length, ...(last ? { last } : {}) };
240
+ }
241
+ return { ok: true, events: count, anchors: kept.length, ...(last ? { last } : {}) };
242
+ }
243
+ /** The latest event's id and hash, to anchor. */
244
+ export function latestEventHash(database = auditDb()) {
245
+ const row = database?.prepare('SELECT id, at, hash FROM events WHERE hash IS NOT NULL ORDER BY id DESC LIMIT 1').get();
246
+ return row ? { id: Number(row.id), at: row.at, hash: row.hash } : undefined;
247
+ }
248
+ /** Notes an anchor sent away (or kept only here, `sentAt` absent). */
249
+ export function noteAnchor(anchor, database = auditDb()) {
250
+ database?.prepare('INSERT OR REPLACE INTO audit_anchors (event_id, hash, at, sent_at) VALUES (?, ?, ?, ?)').run(anchor.eventId, anchor.hash, anchor.at, anchor.sentAt ?? null);
251
+ }
252
+ export function lastAnchor(database = auditDb()) {
253
+ const row = database?.prepare('SELECT event_id, hash, at, sent_at FROM audit_anchors ORDER BY event_id DESC LIMIT 1').get();
254
+ return row ? { eventId: Number(row.event_id), hash: row.hash, at: row.at, ...(row.sent_at ? { sentAt: row.sent_at } : {}) } : undefined;
255
+ }
159
256
  let db;
160
257
  export function schedulerDir() {
161
258
  return process.env.LOOPENGINE_SCHEDULER_DIR || path.join(process.cwd(), '.scheduler');
@@ -192,7 +289,20 @@ export function recordEvent(event, database = auditDb()) {
192
289
  if (!database)
193
290
  return;
194
291
  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));
292
+ // Written and chained in one step, so no other event comes between.
293
+ database.exec('BEGIN IMMEDIATE');
294
+ try {
295
+ const prev = database.prepare('SELECT hash FROM events ORDER BY id DESC LIMIT 1').get()?.hash ?? GENESIS;
296
+ const row = { at: event.at ?? new Date().toISOString(), agent: event.agent, workflow_id: event.workflow_id ?? null, run_id: event.run_id ?? null, kind: event.kind, by: event.by ?? null, data: JSON.stringify(event.data) };
297
+ const { lastInsertRowid } = database.prepare('INSERT INTO events (at, agent, workflow_id, run_id, kind, by, data) VALUES (?, ?, ?, ?, ?, ?, ?)').run(row.at, row.agent, row.workflow_id, row.run_id, row.kind, row.by, row.data);
298
+ const id = Number(lastInsertRowid);
299
+ database.prepare('UPDATE events SET prev = ?, hash = ? WHERE id = ?').run(prev, eventHash(prev, { id, ...row }), id);
300
+ database.exec('COMMIT');
301
+ }
302
+ catch (err) {
303
+ database.exec('ROLLBACK');
304
+ throw err;
305
+ }
196
306
  }
197
307
  catch (err) {
198
308
  console.error('[loopengine] could not record an audit event:', err);
@@ -236,6 +346,13 @@ export function listEvents(filter = {}, database = auditDb()) {
236
346
  const sql = `SELECT * FROM events${where.length ? ` WHERE ${where.join(' AND ')}` : ''} ORDER BY id DESC LIMIT ${limit}`;
237
347
  return database.prepare(sql).all(...args).map(eventOf);
238
348
  }
349
+ /** Everyone named on an event, most recent first (for a filter). */
350
+ export function eventPeople(limit = 200, database = auditDb()) {
351
+ if (!database)
352
+ return [];
353
+ const rows = database.prepare('SELECT by, MAX(id) AS last FROM events WHERE by IS NOT NULL GROUP BY by ORDER BY last DESC LIMIT ?').all(limit);
354
+ return rows.map((r) => r.by);
355
+ }
239
356
  function eventOf(r) {
240
357
  return {
241
358
  id: Number(r.id),
@@ -246,6 +363,8 @@ function eventOf(r) {
246
363
  kind: String(r.kind),
247
364
  ...(r.by ? { by: String(r.by) } : {}),
248
365
  data: JSON.parse(String(r.data)),
366
+ ...(r.prev != null ? { prev: String(r.prev) } : {}),
367
+ ...(r.hash ? { hash: String(r.hash) } : {}),
249
368
  };
250
369
  }
251
370
  // ---------- versions ----------
@@ -265,21 +265,26 @@ export async function loadMcpAbilityTools(dir, agentName) {
265
265
  for (const [abilityName, record] of entries) {
266
266
  const errorKey = `${dir}\0${abilityName}`;
267
267
  let cached = cache[abilityName]?.version === record.version ? cache[abilityName].tools : undefined;
268
- if (!cached || record.mcp.tools.some((t) => !cached[t.remote])) {
268
+ // Cached before the server's hints were kept: worth one more fetch,
269
+ // but what's cached still serves if the server can't be reached.
270
+ const unhinted = cached && record.mcp.tools.every((t) => cached[t.remote]) && record.mcp.tools.some((t) => !cached[t.remote].hinted);
271
+ if (!cached || unhinted || record.mcp.tools.some((t) => !cached[t.remote])) {
269
272
  try {
270
273
  cached = await fetchSchemas(dir, abilityName, record.mcp, createAgentEnv(agentName, dir));
271
274
  cache[abilityName] = { version: record.version, tools: cached };
272
275
  cacheChanged = true;
273
276
  }
274
277
  catch (err) {
275
- loadErrors.set(errorKey, err instanceof Error ? err.message : String(err));
276
- continue;
278
+ if (!unhinted) {
279
+ loadErrors.set(errorKey, err instanceof Error ? err.message : String(err));
280
+ continue;
281
+ }
277
282
  }
278
283
  }
279
284
  loadErrors.delete(errorKey);
280
285
  const env = createAgentEnv(agentName, dir);
281
286
  for (const tool of record.mcp.tools) {
282
- const schema = cached[tool.remote];
287
+ const schema = cached?.[tool.remote];
283
288
  if (schema)
284
289
  tools.push(toolDefinition(dir, abilityName, record.mcp, tool, schema, env));
285
290
  }
@@ -297,8 +302,10 @@ async function fetchSchemas(dir, abilityName, mcp, env) {
297
302
  do {
298
303
  const page = await client.listTools(cursor ? { cursor } : undefined);
299
304
  for (const tool of page.tools) {
300
- if (wanted.has(tool.name))
301
- found[tool.name] = { description: tool.description ?? '', input_schema: tool.inputSchema };
305
+ if (!wanted.has(tool.name))
306
+ continue;
307
+ const hints = (tool.annotations ?? {});
308
+ found[tool.name] = { description: tool.description ?? '', input_schema: tool.inputSchema, ...(hints.readOnlyHint === true ? { readOnly: true } : {}), hinted: true };
302
309
  }
303
310
  cursor = page.nextCursor;
304
311
  } while (cursor);
@@ -355,6 +362,7 @@ function toolDefinition(dir, abilityName, mcp, tool, schema, env) {
355
362
  name: tool.name,
356
363
  description: schema.description || tool.remote,
357
364
  input_schema: env ? withDefaults(schema.input_schema, defaultValues(mcp.server.defaults, env)) : schema.input_schema,
365
+ ...(schema.readOnly ? { safe: true } : {}),
358
366
  async execute(input, ctx) {
359
367
  const server = resolveServer(mcp.server, ctx.env);
360
368
  const args = { ...input };
@@ -138,12 +138,16 @@ export interface RunAgentOptions {
138
138
  * that genuinely has an answering mechanism (adapters/http.ts, for both
139
139
  * its routes) should pass this. */
140
140
  onQuestionPending?: (question: PendingQuestion) => void;
141
- /** A test run (a workflow's eval cases, web/workflow-evals.ts): tools
142
- * its rules allow run as usual; any other call, and the schedule tools,
143
- * aren't run and aren't asked about. The model is told so and carries
144
- * on, so the run still reaches a result instead of stopping at a
145
- * denial. */
146
- evalMode?: boolean;
141
+ /** A test run (a workflow's eval cases, web/workflow-evidence.ts):
142
+ * only calls that just read (a tool marked `safe`, or isSafeTool) and
143
+ * that its rules allow are made. Every other call (anything that sends,
144
+ * writes or changes something, one that would need approval, the
145
+ * schedule tools) isn't made and isn't asked about: the model gets
146
+ * the reply that call got in the run the case came from (`replay`,
147
+ * the same tool with the same input), else a note to assume it worked,
148
+ * and carries on, so a test never touches the outside world and still
149
+ * reaches a result. `true` is a test run with nothing to replay. */
150
+ evalMode?: boolean | EvalModeOptions;
147
151
  /** Nobody is watching this run (core/unattended.ts): a final reply that
148
152
  * asks the person something is sent back for the agent to make the
149
153
  * call (the tool, or system_ask_user) instead. */
@@ -334,3 +338,25 @@ export declare function runAgent(config: AgentConfig, modelCall: ModelCall, user
334
338
  * one), 'denied', 'max_turns', or a genuine finish — runLoop handles all
335
339
  * of those uniformly regardless of how this turn started. */
336
340
  export declare function resumeAgent(config: AgentConfig, modelCall: ModelCall, history: Message[], resolution: ModelContentBlock[], options?: RunAgentOptions): Promise<RunAgentResult>;
341
+ /** A call made in a real run, with what came back: replayed in a test
342
+ * run of the same case (RunAgentOptions.evalMode). */
343
+ export interface RecordedCall {
344
+ tool: string;
345
+ input: Record<string, unknown>;
346
+ result: string;
347
+ failed?: boolean;
348
+ }
349
+ export interface EvalModeOptions {
350
+ /** The case's own run's calls, each replayed at most once. */
351
+ replay?: RecordedCall[];
352
+ /** Told of each call that wasn't made, and whether its reply was
353
+ * replayed. */
354
+ onStandIn?: (call: {
355
+ tool: string;
356
+ input: Record<string, unknown>;
357
+ replayed: boolean;
358
+ }) => void;
359
+ }
360
+ /** What a run's session shows of its calls, for replaying them in a test
361
+ * run: each tool call with the reply it got. Questions are left out. */
362
+ export declare function recordedCalls(history: Message[]): RecordedCall[];
@@ -477,7 +477,15 @@ async function buildTurnContext(config, modelCall, options) {
477
477
  questionHandler,
478
478
  httpNotifier,
479
479
  modelLabel: { provider: config.model?.provider, model: config.model?.model },
480
- ...(options.evalMode ? { evalMode: { rules, neverRun: new Set(scheduleTools) } } : {}),
480
+ ...(options.evalMode ? {
481
+ evalMode: {
482
+ rules,
483
+ neverRun: new Set(scheduleTools),
484
+ readOnly: isSafeTool,
485
+ replay: [...(typeof options.evalMode === 'object' ? options.evalMode.replay ?? [] : [])],
486
+ ...(typeof options.evalMode === 'object' && options.evalMode.onStandIn ? { onStandIn: options.evalMode.onStandIn } : {}),
487
+ },
488
+ } : {}),
481
489
  ...(options.unattended ? { unattended: true } : {}),
482
490
  toolContext: {
483
491
  agentName: config.name,
@@ -665,15 +673,23 @@ async function runLoop(ctx, messages, newMessages, starterMessage) {
665
673
  resultBlocks.push({ type: 'tool_result', tool_use_id: block.id, content: body });
666
674
  continue;
667
675
  }
668
- // A test run: a call its rules don't allow (or a schedule tool) isn't
669
- // run or asked about; the model hears what happened and carries on.
676
+ // A test run: only an allowed call that just reads is made. Any
677
+ // other gets what it got in the case's own run (same tool, same
678
+ // input), else a note; it never reaches the outside world.
670
679
  if (evalMode) {
671
680
  const tool = toolsByName.get(block.name);
672
- const blocked = tool && (evalMode.neverRun.has(tool) || (!systemToolInstances.has(tool) && evalMode.rules.resolve(block.name, block.input ?? {}, scope)[0] !== 'allow'));
673
- if (blocked) {
674
- const note = "not run: this is a test run, and this call would need approval (or isn't allowed) in a real one. Assume it would have been approved as you asked, carry on, and say in your result that you would have made it.";
675
- resultBlocks.push({ type: 'tool_result', tool_use_id: block.id, content: note });
676
- log({ type: 'tool:result', id: block.id, tool: block.name, args: block.input ?? {}, detailText: 'test run', statusText: 'Not run (test run).' });
681
+ const input = block.input ?? {};
682
+ const reads = tool && !evalMode.neverRun.has(tool) && evalMode.readOnly({ id: block.id, name: block.name, execute: async () => undefined });
683
+ const standIn = tool && !(systemToolInstances.has(tool) && !evalMode.neverRun.has(tool)) && !(reads && evalMode.rules.resolve(block.name, input, scope)[0] === 'allow');
684
+ if (standIn) {
685
+ const at = evalMode.replay.findIndex((c) => c.tool === block.name && sameInput(c.input, input));
686
+ const recorded = at >= 0 ? evalMode.replay.splice(at, 1)[0] : undefined;
687
+ const content = recorded
688
+ ? recorded.result
689
+ : "not run: this is a test run, so a call that changes something, or would need approval, isn't made. Assume it worked as you asked, carry on, and say in your result that you would have made it.";
690
+ resultBlocks.push({ type: 'tool_result', tool_use_id: block.id, content, ...(recorded?.failed ? { is_error: true } : {}) });
691
+ evalMode.onStandIn?.({ tool: block.name, input, replayed: Boolean(recorded) });
692
+ log({ type: 'tool:result', id: block.id, tool: block.name, args: input, detailText: 'test run', statusText: recorded ? 'Not run (test run): replayed its reply from the original run.' : 'Not run (test run).' });
677
693
  continue;
678
694
  }
679
695
  }
@@ -1007,3 +1023,32 @@ export async function resumeAgent(config, modelCall, history, resolution, option
1007
1023
  }
1008
1024
  return result;
1009
1025
  }
1026
+ // The same input, whatever order its keys are in.
1027
+ function sameInput(a, b) {
1028
+ const norm = (v) => (Array.isArray(v) ? v.map(norm) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).sort(([x], [y]) => x.localeCompare(y)).map(([k, x]) => [k, norm(x)])) : v);
1029
+ return JSON.stringify(norm(a)) === JSON.stringify(norm(b));
1030
+ }
1031
+ /** What a run's session shows of its calls, for replaying them in a test
1032
+ * run: each tool call with the reply it got. Questions are left out. */
1033
+ export function recordedCalls(history) {
1034
+ const calls = [];
1035
+ const byId = new Map();
1036
+ for (const m of history) {
1037
+ if (typeof m.content === 'string')
1038
+ continue;
1039
+ for (const b of m.content) {
1040
+ if (b.type === 'tool_use' && b.name && b.id && b.name !== 'system_ask_user') {
1041
+ const call = { tool: b.name, input: (b.input ?? {}), result: '' };
1042
+ byId.set(b.id, call);
1043
+ calls.push(call);
1044
+ }
1045
+ else if (b.type === 'tool_result' && b.tool_use_id && byId.has(b.tool_use_id)) {
1046
+ const call = byId.get(b.tool_use_id);
1047
+ call.result = typeof b.content === 'string' ? b.content : JSON.stringify(b.content ?? '');
1048
+ if (b.is_error)
1049
+ call.failed = true;
1050
+ }
1051
+ }
1052
+ }
1053
+ return calls.filter((c) => c.result);
1054
+ }
@@ -130,6 +130,26 @@ export interface RunStore {
130
130
  prune?(): Promise<void>;
131
131
  /** A workflow's runs started at or after `since`, however many. */
132
132
  since?(agent: string, workflowId: string, since: string): Promise<WorkflowRun[]>;
133
+ /** Every kept run matching the filter, newest first. */
134
+ search?(filter: RunSearch): Promise<WorkflowRun[]>;
135
+ }
136
+ /** What to look for among the runs kept (the Audit page's Cases). */
137
+ export interface RunSearch {
138
+ /** Text anywhere in the run: inputs, result, error, decisions. */
139
+ q?: string;
140
+ agent?: string;
141
+ /** Only these agents' runs. */
142
+ agents?: string[];
143
+ workflowId?: string;
144
+ status?: WorkflowRunStatus;
145
+ /** Someone who decided or answered something in it. */
146
+ by?: string;
147
+ /** Started within these ISO times, inclusive. */
148
+ since?: string;
149
+ until?: string;
150
+ /** Started before this ISO time (the next page). */
151
+ before?: string;
152
+ limit?: number;
133
153
  }
134
154
  /** One JSON file per run under `<dir>/runs/` — one server process. */
135
155
  export declare class FileRunStore implements RunStore {
@@ -165,6 +185,7 @@ export declare class SqliteRunStore implements RunStore {
165
185
  limit?: number;
166
186
  }): Promise<WorkflowRun[]>;
167
187
  since(agent: string, workflowId: string, since: string): Promise<WorkflowRun[]>;
188
+ search(f: RunSearch): Promise<WorkflowRun[]>;
168
189
  bySession(sessionId: string): Promise<WorkflowRun | undefined>;
169
190
  get(runId: string): Promise<WorkflowRun | undefined>;
170
191
  put(run: WorkflowRun): Promise<void>;
@@ -185,6 +206,9 @@ export declare function listRuns(agent: string, filter?: {
185
206
  /** A workflow's runs started at or after `since` (an ISO time), oldest
186
207
  * first; from the console's list where the store keeps no more. */
187
208
  export declare function runsSince(agent: string, workflowId: string, since: string): Promise<WorkflowRun[]>;
209
+ /** Runs matching the filter, newest first: every one the store keeps
210
+ * (the console's list where it keeps no more). */
211
+ export declare function searchRuns(filter: RunSearch): Promise<WorkflowRun[]>;
188
212
  /** One of an agent's runs; undefined for another agent's. */
189
213
  export declare function getRun(agent: string, runId: string): Promise<WorkflowRun | undefined>;
190
214
  export declare function isUnderWay(run: WorkflowRun): boolean;