loopengine 0.4.3 → 0.4.4

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.
@@ -57,6 +57,8 @@ export interface EventFilter {
57
57
  }
58
58
  /** Events matching the filter, newest first, at most 500. */
59
59
  export declare function listEvents(filter?: EventFilter, database?: DatabaseSync | undefined): AuditEvent[];
60
+ /** Everyone named on an event, most recent first (for a filter). */
61
+ export declare function eventPeople(limit?: number, database?: DatabaseSync | undefined): string[];
60
62
  /** The version number of `content`: the latest version's when it's the
61
63
  * same text, else a new version noted now. Undefined without a database.
62
64
  * `agent` and `workflowId` are '' for the workspace's policies. */
@@ -236,6 +236,13 @@ export function listEvents(filter = {}, database = auditDb()) {
236
236
  const sql = `SELECT * FROM events${where.length ? ` WHERE ${where.join(' AND ')}` : ''} ORDER BY id DESC LIMIT ${limit}`;
237
237
  return database.prepare(sql).all(...args).map(eventOf);
238
238
  }
239
+ /** Everyone named on an event, most recent first (for a filter). */
240
+ export function eventPeople(limit = 200, database = auditDb()) {
241
+ if (!database)
242
+ return [];
243
+ 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);
244
+ return rows.map((r) => r.by);
245
+ }
239
246
  function eventOf(r) {
240
247
  return {
241
248
  id: Number(r.id),
@@ -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;
@@ -29,6 +29,18 @@ const SESSION_PREFIX = 'run-';
29
29
  const SCHEDULE_SESSION_PREFIX = 'sched-';
30
30
  export class RunError extends Error {
31
31
  }
32
+ function matchesSearch(run, f) {
33
+ const people = [...(run.decisions ?? []), ...(run.answers ?? [])].map((d) => d.by);
34
+ return (!f.agent || run.agent === f.agent)
35
+ && (!f.agents || f.agents.includes(run.agent))
36
+ && (!f.workflowId || run.workflow_id === f.workflowId)
37
+ && (!f.status || run.status === f.status)
38
+ && (!f.by || people.includes(f.by))
39
+ && (!f.since || run.started_at >= f.since)
40
+ && (!f.until || run.started_at <= f.until)
41
+ && (!f.before || run.started_at < f.before)
42
+ && (!f.q || JSON.stringify(run).toLowerCase().includes(f.q.toLowerCase()));
43
+ }
32
44
  const fileMutex = new KeyedMutex();
33
45
  /** One JSON file per run under `<dir>/runs/` — one server process. */
34
46
  export class FileRunStore {
@@ -157,6 +169,35 @@ export class SqliteRunStore {
157
169
  async since(agent, workflowId, since) {
158
170
  return this.db.prepare('SELECT data FROM runs WHERE agent = ? AND workflow_id = ? AND started_at >= ? ORDER BY started_at').all(agent, workflowId, since).map((r) => this.read(r));
159
171
  }
172
+ async search(f) {
173
+ const where = [];
174
+ const args = [];
175
+ const add = (clause, ...values) => {
176
+ where.push(clause);
177
+ args.push(...values);
178
+ };
179
+ if (f.agent)
180
+ add('agent = ?', f.agent);
181
+ if (f.agents)
182
+ add(`agent IN (${f.agents.map(() => '?').join(', ') || "''"})`, ...f.agents);
183
+ if (f.workflowId)
184
+ add('workflow_id = ?', f.workflowId);
185
+ if (f.status)
186
+ add('status = ?', f.status);
187
+ if (f.since)
188
+ add('started_at >= ?', f.since);
189
+ if (f.until)
190
+ add('started_at <= ?', f.until);
191
+ if (f.before)
192
+ add('started_at < ?', f.before);
193
+ if (f.by)
194
+ add("(EXISTS (SELECT 1 FROM json_each(runs.data, '$.decisions') WHERE json_extract(value, '$.by') = ?) OR EXISTS (SELECT 1 FROM json_each(runs.data, '$.answers') WHERE json_extract(value, '$.by') = ?))", f.by, f.by);
195
+ if (f.q)
196
+ add("data LIKE ? ESCAPE '\\'", `%${f.q.replace(/[\\%_]/g, (c) => '\\' + c)}%`);
197
+ const limit = Math.min(Math.max(f.limit ?? 50, 1), 200);
198
+ const sql = `SELECT data FROM runs${where.length ? ` WHERE ${where.join(' AND ')}` : ''} ORDER BY started_at DESC LIMIT ${limit}`;
199
+ return this.db.prepare(sql).all(...args).map((r) => this.read(r));
200
+ }
160
201
  async bySession(sessionId) {
161
202
  const row = this.db.prepare('SELECT data FROM runs WHERE session_id = ? ORDER BY started_at DESC LIMIT 1').get(sessionId);
162
203
  return row ? this.read(row) : undefined;
@@ -217,6 +258,15 @@ export async function runsSince(agent, workflowId, since) {
217
258
  return store.since(agent, workflowId, since);
218
259
  return (await listRuns(agent, { workflowId })).filter((r) => r.started_at >= since).reverse();
219
260
  }
261
+ /** Runs matching the filter, newest first: every one the store keeps
262
+ * (the console's list where it keeps no more). */
263
+ export async function searchRuns(filter) {
264
+ const store = getRunStore();
265
+ if (store.search)
266
+ return store.search(filter);
267
+ const limit = Math.min(Math.max(filter.limit ?? 50, 1), 200);
268
+ return (await store.list()).filter((r) => matchesSearch(r, filter)).slice(0, limit);
269
+ }
220
270
  /** One of an agent's runs; undefined for another agent's. */
221
271
  export async function getRun(agent, runId) {
222
272
  if (!/^[A-Za-z0-9_-]+$/.test(runId))
package/dist/index.d.ts CHANGED
@@ -8,6 +8,8 @@ export { FileSecretStore, setSecretStore, getSecretStore, type SecretStore } fro
8
8
  export { signProxyIdentity, verifyProxyIdentity, TRUSTED_PROXY_IDENTITY_HEADER, type ProxyIdentity } from '#core/trusted-proxy.js';
9
9
  export { setUsageSink, recordUsage, sessionUsage, usageBySession, type UsageEvent, type UsageSink, type UsageRow } from '#core/usage.js';
10
10
  export { changeOf, keptBody, type Change } from '#web/change-log.js';
11
+ export { eventText, eventsCsv, caseRow, type AuditCaseRow } from '#web/audit-admin.js';
12
+ export { auditPageHtml } from '#web/audit-page.js';
11
13
  export { workflowHealth, healthAlerts, type WorkflowHealth, type HealthNumbers, type HealthVersion, type HealthDay, type HealthAlert, type HealthMeasure } from '#web/workflow-health.js';
12
14
  export { setRunObserver, reportRun, usedTool, type RunEvent, type RunEventSource, type RunObserver } from '#core/run-events.js';
13
15
  export { readNotifierFile, writeNotifierFile, removeNotifierFile, validateNotifierFile, notifierConfigFromFile, NotifierFileError, NOTIFIER_SECRET_VARS, type NotifierFile, type MessagingApprover } from '#core/notifier-file.js';
@@ -59,7 +61,7 @@ export { discoverAgents, loadAgentModule, synthesizeCreateModelCall } from './co
59
61
  export { abilityDependencies, installMissingAbilityDependencies, installMissingPackages } from './core/ability-dependencies.js';
60
62
  export type { AgentModule } from './core/discover-agents.js';
61
63
  export { agentAsTool } from './core/agent-as-tool.js';
62
- export { resumeAgent, loadRules, loadDefaultTools, loadSubagentAsTools, systemTools, systemSkillsDir } from './core/run-agent.js';
64
+ export { resumeAgent, recordedCalls, type RecordedCall, type EvalModeOptions, loadRules, loadDefaultTools, loadSubagentAsTools, systemTools, systemSkillsDir } from './core/run-agent.js';
63
65
  export { Compactor, TruncatingSummarizer } from './core/compaction.js';
64
66
  export type { Summarizer, RecoverResult, RecoverAction } from './core/compaction.js';
65
67
  export { LLMSummarizer } from './core/llm-summarizer.js';
@@ -94,10 +96,10 @@ export { WORKFLOW_EXAMPLES, workflowExample, type WorkflowExample } from './core
94
96
  export { WORKFLOW_EXAMPLE_MESSAGES, type WorkflowExampleMessage } from './core/system-agents/workflow-example-messages.js';
95
97
  export { createTrigger, updateTrigger, rotateTrigger, listTriggers, findTriggerByToken, publicTrigger, checkTriggerSettings, verifySenderSignature, parsePayload, valueAt, deliveryId, passesFilter, paramsFromPayload, checkRunDelivery, fillChatNotice, resultToChat, recordDelivery as recordTriggerDelivery, FileTriggerStore, getTriggerStore, setTriggerStore, TriggerError, type WorkflowTrigger, type PublicTrigger, type TriggerSettings, type TriggerVerify, type TriggerFilter, type TriggerSender, type SignatureAlgorithm, type TriggerDelivery, type TriggerOutcome, type TriggerStore } from './core/workflow-triggers.js';
96
98
  export { checkCallbackUrl, callbackSecret, signCallback, deliverCallback, runCallbackPayload, isPrivateAddress, CallbackUrlError, type CallbackDelivery, type CallbackPending, type RunCallbackEvent } from './core/run-callbacks.js';
97
- export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, readMeta, writeMeta, type EventFilter, noteVersion, listVersions, getVersion, briefContent, briefFromContent, retentionDays, type Version, type VersionKind, type AuditEvent, type AuditEventKind } from './core/audit-store.js';
98
- export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, getRun, isUnderWay, RunError, type WorkflowRun, type WorkflowRunStatus, type RunVersions, type RunDecision, type RunStore, type ExecuteRun, type RunOutcome, type StartRunInput } from './core/workflow-runs.js';
99
+ export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, readMeta, writeMeta, type EventFilter, noteVersion, listVersions, getVersion, briefContent, briefFromContent, retentionDays, type Version, type VersionKind, type AuditEvent, type AuditEventKind } from './core/audit-store.js';
100
+ export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, searchRuns, type RunSearch, getRun, isUnderWay, RunError, type WorkflowRun, type WorkflowRunStatus, type RunVersions, type RunDecision, type RunStore, type ExecuteRun, type RunOutcome, type StartRunInput } from './core/workflow-runs.js';
99
101
  export { readWorkflows, readWorkflow, setWorkflowFields, setWorkflowDelivery, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies, type Workflow, type WorkflowFields, type WorkflowParameter, type WorkflowModel, type WorkflowDelivery, type RunMessageExtras } from './core/workflows.js';
100
- export { EvidenceError, workflowScores, runFeedbackFrom, readEvals, addEvalCase, updateEvalCase, removeEvalCase, setEvalCriteria, effectiveCriteria, codeCheck, judgeCriteria, checkCase, roundSummary, draftCriteria, startEvalRound, EVAL_CRITERIA_PROMPT, DRAFT_CRITERIA_PROMPT, REFERENCE_CRITERION, type WorkflowScores, type EvalCase, type EvalCaseResult, type EvalCheck, type EvalCriterion, type CriterionKind, type EvalRound, type WorkflowEvals, type EvalRunDeps } from './web/workflow-evidence.js';
102
+ export { EvidenceError, workflowScores, runFeedbackFrom, readEvals, addEvalCase, updateEvalCase, removeEvalCase, setEvalCriteria, effectiveCriteria, codeCheck, judgeCriteria, checkCase, roundSummary, draftCriteria, startEvalRound, EVAL_CRITERIA_PROMPT, DRAFT_CRITERIA_PROMPT, REFERENCE_CRITERION, type WorkflowScores, type EvalCase, type EvalCaseResult, type EvalCheck, type EvalCriterion, type CriterionKind, type EvalRound, type WorkflowEvals, type EvalRunDeps, type StandIn } from './web/workflow-evidence.js';
101
103
  export { globalConfigPageHtml } from './web/global-config-page.js';
102
104
  export { playgroundHtml } from './web/playground.js';
103
105
  export { readSkill, writeSkill, deleteSkill, SkillInvalidIdError, SkillNotFoundError } from './web/skills-admin.js';
package/dist/index.js CHANGED
@@ -10,6 +10,8 @@ export { FileSecretStore, setSecretStore, getSecretStore } from '#core/secret-st
10
10
  export { signProxyIdentity, verifyProxyIdentity, TRUSTED_PROXY_IDENTITY_HEADER } from '#core/trusted-proxy.js';
11
11
  export { setUsageSink, recordUsage, sessionUsage, usageBySession } from '#core/usage.js';
12
12
  export { changeOf, keptBody } from '#web/change-log.js';
13
+ export { eventText, eventsCsv, caseRow } from '#web/audit-admin.js';
14
+ export { auditPageHtml } from '#web/audit-page.js';
13
15
  export { workflowHealth, healthAlerts } from '#web/workflow-health.js';
14
16
  export { setRunObserver, reportRun, usedTool } from '#core/run-events.js';
15
17
  export { readNotifierFile, writeNotifierFile, removeNotifierFile, validateNotifierFile, notifierConfigFromFile, NotifierFileError, NOTIFIER_SECRET_VARS } from '#core/notifier-file.js';
@@ -58,7 +60,7 @@ export { agentAsTool } from './core/agent-as-tool.js';
58
60
  // create-loopengine can build the same admin surface on top of its own
59
61
  // copy of adapters/http.ts (which, like agent-registry.ts, is meant to be
60
62
  // owned/edited, not imported — see this file's own header comment).
61
- export { resumeAgent, loadRules, loadDefaultTools, loadSubagentAsTools, systemTools, systemSkillsDir } from './core/run-agent.js';
63
+ export { resumeAgent, recordedCalls, loadRules, loadDefaultTools, loadSubagentAsTools, systemTools, systemSkillsDir } from './core/run-agent.js';
62
64
  export { Compactor, TruncatingSummarizer } from './core/compaction.js';
63
65
  export { LLMSummarizer } from './core/llm-summarizer.js';
64
66
  export { createCheckpointStore, SqliteCheckpointStore } from './core/durable-approvals.js';
@@ -87,8 +89,8 @@ export { WORKFLOW_EXAMPLES, workflowExample } from './core/system-agents/workflo
87
89
  export { WORKFLOW_EXAMPLE_MESSAGES } from './core/system-agents/workflow-example-messages.js';
88
90
  export { createTrigger, updateTrigger, rotateTrigger, listTriggers, findTriggerByToken, publicTrigger, checkTriggerSettings, verifySenderSignature, parsePayload, valueAt, deliveryId, passesFilter, paramsFromPayload, checkRunDelivery, fillChatNotice, resultToChat, recordDelivery as recordTriggerDelivery, FileTriggerStore, getTriggerStore, setTriggerStore, TriggerError } from './core/workflow-triggers.js';
89
91
  export { checkCallbackUrl, callbackSecret, signCallback, deliverCallback, runCallbackPayload, isPrivateAddress, CallbackUrlError } from './core/run-callbacks.js';
90
- export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, readMeta, writeMeta, noteVersion, listVersions, getVersion, briefContent, briefFromContent, retentionDays } from './core/audit-store.js';
91
- export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, getRun, isUnderWay, RunError } from './core/workflow-runs.js';
92
+ export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, readMeta, writeMeta, noteVersion, listVersions, getVersion, briefContent, briefFromContent, retentionDays } from './core/audit-store.js';
93
+ export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, searchRuns, getRun, isUnderWay, RunError } from './core/workflow-runs.js';
92
94
  export { readWorkflows, readWorkflow, setWorkflowFields, setWorkflowDelivery, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies } from './core/workflows.js';
93
95
  export { EvidenceError, workflowScores, runFeedbackFrom, readEvals, addEvalCase, updateEvalCase, removeEvalCase, setEvalCriteria, effectiveCriteria, codeCheck, judgeCriteria, checkCase, roundSummary, draftCriteria, startEvalRound, EVAL_CRITERIA_PROMPT, DRAFT_CRITERIA_PROMPT, REFERENCE_CRITERION } from './web/workflow-evidence.js';
94
96
  export { globalConfigPageHtml } from './web/global-config-page.js';
@@ -208,6 +208,7 @@ export const agentsConfigPageHtml = `<!doctype html>
208
208
  .wf-crit { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 12px; align-items: center; padding: 8px 12px; border: 1px solid var(--line); border-radius: 8px; font-size: 13px; }
209
209
  .wf-crit-kind { font-size: 12px; color: var(--ink-muted); }
210
210
  .wf-crit-rate { font-variant-numeric: tabular-nums; }
211
+ .wf-case-standins { margin: 0; font-size: 12.5px; color: var(--ink-muted); }
211
212
  .wf-health { display: grid; gap: 12px; margin-bottom: 8px; }
212
213
  .wf-health-alert { padding: 10px 12px; border-radius: 8px; background: var(--bad-soft); color: var(--bad); font-size: 13px; font-weight: 600; }
213
214
  .wf-health-chart { margin: 0; display: grid; gap: 4px; }
@@ -784,7 +785,7 @@ ${renderMarkdownScript}
784
785
  '<td>' + runsPill(t.name) + '</td>' +
785
786
  '<td>' + (t.safe ? 'yes' : 'no') + '</td></tr>';
786
787
  }).join('');
787
- return '<table><thead><tr><th>Name</th><th>What it does</th><th>Runs</th><th>Parallel-safe</th></tr></thead><tbody>' + rows + '</tbody></table>';
788
+ return '<table><thead><tr><th>Name</th><th>What it does</th><th>Runs</th><th>Only reads</th></tr></thead><tbody>' + rows + '</tbody></table>';
788
789
  }
789
790
 
790
791
  // Local tools' own table, unlike renderTools above (shared by Agent as
@@ -807,7 +808,7 @@ ${renderMarkdownScript}
807
808
  '<td>' + (t.safe ? 'yes' : 'no') + '</td>' +
808
809
  '<td>' + actions + '</td></tr>';
809
810
  }).join('');
810
- return '<table><thead><tr><th>Name</th><th>What it does</th><th>Runs</th><th>Parallel-safe</th><th></th></tr></thead><tbody>' + rows + '</tbody></table>';
811
+ return '<table><thead><tr><th>Name</th><th>What it does</th><th>Runs</th><th>Only reads</th><th></th></tr></thead><tbody>' + rows + '</tbody></table>';
811
812
  }
812
813
 
813
814
  // Overview's own tools table, unlike the Tools tab's three separately-
@@ -840,7 +841,7 @@ ${renderMarkdownScript}
840
841
  addRows(cfg.gatewayTools, 'Gateway');
841
842
  addRows(cfg.agentAsTools, 'Agent as Tool');
842
843
  if (!rows.length) return '<p class="muted">No tools.</p>';
843
- return '<table><thead><tr><th>Name</th><th>Description</th><th>Type</th><th>Parallel-safe</th></tr></thead><tbody>' + rows.join('') + '</tbody></table>';
844
+ return '<table><thead><tr><th>Name</th><th>Description</th><th>Type</th><th>Only reads</th></tr></thead><tbody>' + rows.join('') + '</tbody></table>';
844
845
  }
845
846
 
846
847
  function renderSkills(skills) {
@@ -1381,9 +1382,16 @@ ${renderMarkdownScript}
1381
1382
  var why = !last ? ''
1382
1383
  : last.checks ? (fails.length ? '<ul class="wf-case-fails">' + fails.map(function (x) { return '<li><strong>' + escapeHtml(critName[x.criterionId] || x.criterionId) + '</strong>' + (x.reason ? ': ' + escapeHtml(x.reason) : '') + '</li>'; }).join('') + '</ul>' : '')
1383
1384
  : '<p class="hint" style="margin:0">' + escapeHtml(last.reason || last.error || '') + '</p>';
1385
+ // The calls the test didn't make: what it would have done.
1386
+ var standIns = last && last.standIns && last.standIns.length
1387
+ ? '<p class="wf-case-standins">Not made in the test: ' + last.standIns.map(function (x) {
1388
+ var shown = JSON.stringify(x.input);
1389
+ return '<code title="' + escapeHtml(shown) + '">' + escapeHtml(x.tool) + '</code>' + (x.replayed ? ' <span class="hint">(reply from its run)</span>' : '');
1390
+ }).join(', ') + '</p>'
1391
+ : '';
1384
1392
  return '<li class="wf-case" data-case="' + escapeHtml(c.id) + '"><div class="wf-case-head"><strong>Case ' + (i + 1) + '</strong>' + pill +
1385
1393
  '<span class="hint">' + (values || 'no inputs') + '</span><button type="button" class="wf-link wf-case-remove">Remove</button></div>' +
1386
- why +
1394
+ why + standIns +
1387
1395
  '<details><summary>Good result' + (c.reference ? '' : ' (none)') + (last && last.result ? ' and its latest result' : '') + '</summary>' +
1388
1396
  '<textarea class="wf-case-ref" aria-label="Good result for case ' + (i + 1) + '" placeholder="Optional: what a good result says, to compare against">' + escapeHtml(c.reference || '') + '</textarea>' +
1389
1397
  '<div class="wf-case-actions"><button type="button" class="wf-case-save">Save good result</button></div>' +
@@ -1395,7 +1403,7 @@ ${renderMarkdownScript}
1395
1403
  tiles + feedbackHint + critSection +
1396
1404
  '<h4 class="wf-sub">Eval cases</h4>' +
1397
1405
  '<div class="wf-evals-bar"><button type="button" class="wf-evals-run"' + (!evals.cases.length || running ? ' disabled' : '') + '>' + (running ? 'Running ' + running.done + ' of ' + running.total + String.fromCharCode(8230) : 'Run evals') + '</button>' +
1398
- '<span class="hint">' + (round ? 'Last run ' + escapeHtml(new Date(round.at).toLocaleString()) + (round.briefVersion ? DOT + 'brief v' + round.briefVersion : '') + DOT + 'model ' + escapeHtml(round.model) + DOT + 'judged by ' + escapeHtml(round.judge) : 'A test run: tools that need approval aren' + RSQ + 't run, and nobody is asked anything.') + '</span></div>' +
1406
+ '<span class="hint">' + (round ? 'Last run ' + escapeHtml(new Date(round.at).toLocaleString()) + (round.briefVersion ? DOT + 'brief v' + round.briefVersion : '') + DOT + 'model ' + escapeHtml(round.model) + DOT + 'judged by ' + escapeHtml(round.judge) : 'A test run: only tools that just read data run. Anything that would send, write or change something, or need approval, isn' + RSQ + 't done, and nobody is asked anything.') + '</span></div>' +
1399
1407
  (cases ? '<ul class="wf-cases">' + cases + '</ul>' : '<p class="hint" style="margin:0">No cases yet. Save a run from History below as a case, then run the cases after each change to the instructions or model.</p>') +
1400
1408
  '<h4 class="wf-sub">History</h4>' +
1401
1409
  (runsHtml ? '<ul class="schedule-history">' + runsHtml + '</ul>' : '<p class="hint" style="margin:0">No runs yet.</p>');
@@ -5114,7 +5122,7 @@ ${renderMarkdownScript}
5114
5122
  '<button type="button" id="httpToolAddHeaderBtn" class="hint-btn">Add header</button>' +
5115
5123
  '</label>' +
5116
5124
  '<label class="http-tool-inline-label"><input type="checkbox" name="sendFieldsAsJsonBody"> Send fields as a JSON body (POST/PUT/PATCH only)</label>' +
5117
- '<label class="http-tool-inline-label"><input type="checkbox" name="safe"> Parallel-safe <span class="hint">(read-only, no side effects &mdash; safe to run alongside other calls)</span></label>' +
5125
+ '<label class="http-tool-inline-label"><input type="checkbox" name="safe"> Only reads data <span class="hint">(changes nothing: it runs in test runs, and alongside other calls)</span></label>' +
5118
5126
  '<label>Response JSON path <span class="hint">(optional &mdash; e.g. data.status; leave blank to return the raw response text)</span>' +
5119
5127
  '<input type="text" name="responseJsonPath" placeholder="data.status">' +
5120
5128
  '</label>' +
@@ -0,0 +1,28 @@
1
+ import type { AuditEvent } from '../core/audit-store.js';
2
+ import type { WorkflowRun } from '../core/workflow-runs.js';
3
+ /** An event in words, as the page and the CSV file show it: what
4
+ * happened, and any detail (a reason, an answer, a note). */
5
+ export declare function eventText(e: AuditEvent): {
6
+ what: string;
7
+ detail: string;
8
+ };
9
+ /** The events as a CSV file, one row each, in the order given. */
10
+ export declare function eventsCsv(events: AuditEvent[]): string;
11
+ /** A case in the Cases list. */
12
+ export interface AuditCaseRow {
13
+ id: string;
14
+ agent: string;
15
+ workflowId: string;
16
+ workflowTitle: string;
17
+ /** Its inputs, in a line. */
18
+ inputs: string;
19
+ status: WorkflowRun['status'];
20
+ startedAt: string;
21
+ finishedAt?: string;
22
+ briefVersion?: number;
23
+ /** Everyone who decided or answered something in it. */
24
+ people: string[];
25
+ /** The start of its result, or its error. */
26
+ outcome: string;
27
+ }
28
+ export declare function caseRow(run: WorkflowRun, workflowTitle: string | undefined): AuditCaseRow;
@@ -0,0 +1,52 @@
1
+ const short = (text, max) => {
2
+ const flat = text.replace(/\s+/g, ' ').trim();
3
+ return flat.length > max ? flat.slice(0, max - 1) + '…' : flat;
4
+ };
5
+ /** An event in words, as the page and the CSV file show it: what
6
+ * happened, and any detail (a reason, an answer, a note). */
7
+ export function eventText(e) {
8
+ const d = e.data;
9
+ const str = (v) => (typeof v === 'string' ? v : '');
10
+ if (e.kind === 'change')
11
+ return { what: str(d.label) || 'Changed a setting', detail: '' };
12
+ if (e.kind === 'decision') {
13
+ const what = `${d.approved ? (d.edited ? 'Approved as changed' : 'Approved') : 'Denied'} ${str(d.tool)}`;
14
+ return { what, detail: str(d.reason) };
15
+ }
16
+ if (e.kind === 'answer')
17
+ return { what: 'Answered a question', detail: `${short(str(d.question), 200)} → ${short(str(d.answer), 400)}` };
18
+ const verdict = d.verdict === 'good' ? 'Good' : d.verdict === 'bad' ? 'Bad' : '';
19
+ const edit = d.edit === 'none' ? 'used unedited' : d.edit ? `${str(d.edit)} edits` : '';
20
+ return { what: `Feedback${verdict || edit ? `: ${[verdict, edit].filter(Boolean).join(', ')}` : ''}`, detail: str(d.note) };
21
+ }
22
+ const CSV_COLUMNS = ['When (UTC)', 'Kind', 'Person', 'Agent', 'Workflow', 'What', 'Detail', 'Case'];
23
+ function csvCell(value) {
24
+ // A leading = + - @ would run as a formula in a spreadsheet.
25
+ const safe = /^[=+\-@]/.test(value) ? `'${value}` : value;
26
+ return /[",\n\r]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe;
27
+ }
28
+ /** The events as a CSV file, one row each, in the order given. */
29
+ export function eventsCsv(events) {
30
+ const rows = events.map((e) => {
31
+ const { what, detail } = eventText(e);
32
+ return [e.at, e.kind, e.by ?? '', e.agent, e.workflow_id ?? '', what, detail, e.run_id ?? ''].map(csvCell).join(',');
33
+ });
34
+ return [CSV_COLUMNS.join(','), ...rows].join('\r\n') + '\r\n';
35
+ }
36
+ export function caseRow(run, workflowTitle) {
37
+ const inputs = Object.entries(run.params ?? {}).map(([k, v]) => `${k}: ${v}`).join(' · ');
38
+ const people = [...new Set([...(run.decisions ?? []), ...(run.answers ?? [])].map((d) => d.by).filter((b) => Boolean(b)))];
39
+ return {
40
+ id: run.run_id,
41
+ agent: run.agent,
42
+ workflowId: run.workflow_id,
43
+ workflowTitle: workflowTitle ?? (run.workflow_id || 'One-off job'),
44
+ inputs: short(inputs, 160),
45
+ status: run.status,
46
+ startedAt: run.started_at,
47
+ ...(run.finished_at ? { finishedAt: run.finished_at } : {}),
48
+ ...(run.versions?.brief ? { briefVersion: run.versions.brief } : {}),
49
+ people,
50
+ outcome: short(run.status === 'error' ? run.error ?? '' : run.result ?? '', 200),
51
+ };
52
+ }
@@ -0,0 +1 @@
1
+ export declare const auditPageHtml: string;
@@ -0,0 +1,281 @@
1
+ // The console's Audit page (/audit): the workspace's log of who changed
2
+ // what and who decided what (Activity), and every case kept, searched
3
+ // (Cases). Its data is web/audit-admin.ts's, behind /audit/events,
4
+ // /audit/events.csv, /audit/cases and /audit/filters. Owners, admins and
5
+ // editors see it; approvers and viewers use the Inbox only. Like the
6
+ // other console pages, its inline script avoids backslashes and template
7
+ // placeholders, since it lives inside a template literal.
8
+ import { devUiCss } from './dev-ui-styles.js';
9
+ import { consoleShellScript, consoleSidebarHtml } from './console-shell.js';
10
+ export const auditPageHtml = `<!doctype html>
11
+ <html lang="en">
12
+ <head>
13
+ <meta charset="utf-8">
14
+ <meta name="viewport" content="width=device-width, initial-scale=1">
15
+ <title>Audit</title>
16
+ <style>${devUiCss}
17
+ .au { max-width: 1080px; display: grid; gap: 14px; }
18
+ .au-tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--line); }
19
+ .au-tabs button { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 8px 12px; font-size: 14px; font-weight: 600; color: var(--ink-muted); margin-bottom: -1px; }
20
+ .au-tabs button[aria-selected="true"] { color: var(--accent-ink); border-bottom-color: var(--accent); }
21
+ .au-bar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
22
+ .au-bar select, .au-bar input { font: inherit; font-size: 13px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); color: var(--ink); max-width: 220px; }
23
+ .au-bar input[type="search"] { flex: 1; min-width: 160px; max-width: none; }
24
+ .au-bar [hidden] { display: none; }
25
+ .au-export { margin-left: auto; font-size: 13px; font-weight: 600; color: var(--accent-ink); text-decoration: none; padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; }
26
+ .au-list { border: 1px solid var(--line); border-radius: 12px; overflow: hidden; background: var(--bg); }
27
+ .au-row { display: grid; grid-template-columns: 136px 80px minmax(0, 1fr) auto; gap: 12px; align-items: baseline; padding: 10px 16px; border-top: 1px solid var(--line); font-size: 13px; }
28
+ .au-row:first-child { border-top: 0; }
29
+ .au-when { color: var(--ink-muted); white-space: nowrap; font-size: 12.5px; }
30
+ .au-kind { font-size: 10.5px; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; color: var(--ink-faint); }
31
+ .au-kind.change { color: var(--accent-ink); }
32
+ .au-kind.decision.denied { color: var(--bad); }
33
+ .au-what { display: grid; gap: 2px; min-width: 0; }
34
+ .au-what strong { font-weight: 600; }
35
+ .au-detail { color: var(--ink-muted); overflow-wrap: anywhere; }
36
+ .au-where { font-size: 12.5px; color: var(--ink-muted); }
37
+ .au-open { color: var(--accent-ink); font-weight: 600; text-decoration: none; white-space: nowrap; font-size: 12.5px; }
38
+ .au-open:hover { text-decoration: underline; }
39
+ .au-case { grid-template-columns: 80px minmax(0, 1fr) auto; }
40
+ .au-state { font-size: 11.5px; font-weight: 700; padding: 1px 8px; border-radius: 999px; background: var(--surface-2); color: var(--ink-muted); justify-self: start; }
41
+ .au-state.good { background: var(--good-soft); color: var(--good); }
42
+ .au-state.bad { background: var(--bad-soft); color: var(--bad); }
43
+ .au-state.warn { background: var(--warn-soft); color: var(--warn); }
44
+ .au-state.run { background: var(--accent-soft); color: var(--accent-ink); }
45
+ .au-empty { padding: 28px 16px; text-align: center; color: var(--ink-muted); font-size: 13.5px; }
46
+ .au-more { justify-self: center; }
47
+ .error { font-size: 13px; color: var(--bad); margin: 0; }
48
+ @media (max-width: 720px) {
49
+ .au-row, .au-case { grid-template-columns: minmax(0, 1fr) auto; }
50
+ .au-when { grid-column: 1 / -1; }
51
+ }
52
+ </style>
53
+ </head>
54
+ <body data-le-page="audit">
55
+ <div class="le-app">
56
+ ${consoleSidebarHtml}
57
+ <main class="le-main">
58
+ <div class="le-head plain">
59
+ <div class="le-head-row">
60
+ <div class="le-title"><button type="button" class="le-menu-btn" data-le-menu aria-label="Open navigation">&#9776;</button>
61
+ <div><h1>Audit</h1><p>Who changed what, and who decided what, across the workspace; and every case kept, to search and open.</p></div>
62
+ </div>
63
+ </div>
64
+ </div>
65
+ <div class="le-scroll"><div class="le-page"><div class="au">
66
+ <div class="au-tabs" role="tablist">
67
+ <button type="button" role="tab" data-tab="activity" aria-selected="true">Activity</button>
68
+ <button type="button" role="tab" data-tab="cases" aria-selected="false">Cases</button>
69
+ </div>
70
+ <div class="au-bar">
71
+ <select id="auAgent" aria-label="Agent"><option value="">All agents</option></select>
72
+ <select id="auWorkflow" aria-label="Workflow"><option value="">All workflows</option></select>
73
+ <select id="auBy" aria-label="Person"><option value="">Anyone</option></select>
74
+ <select id="auKind" aria-label="Kind">
75
+ <option value="">Everything</option><option value="change">Settings changed</option><option value="decision">Approvals</option><option value="answer">Answers</option><option value="feedback">Feedback</option>
76
+ </select>
77
+ <select id="auStatus" aria-label="Status" hidden>
78
+ <option value="">Any outcome</option><option value="done">Done</option><option value="error">Failed</option><option value="awaiting_approval">Waiting for a decision</option><option value="running">Running</option>
79
+ </select>
80
+ <select id="auPeriod" aria-label="Period">
81
+ <option value="7">Last 7 days</option><option value="30" selected>Last 30 days</option><option value="90">Last 90 days</option><option value="365">Last year</option><option value="">All time</option>
82
+ </select>
83
+ <input type="search" id="auQ" placeholder="Search" aria-label="Search">
84
+ <a class="au-export" id="auExport" href="/audit/events.csv" download>Export CSV</a>
85
+ </div>
86
+ <div id="auList"><p class="hint">Loading&hellip;</p></div>
87
+ <button type="button" class="au-more" id="auMore" hidden>Load older</button>
88
+ </div></div></div>
89
+ </main>
90
+ </div>
91
+ ${consoleShellScript}
92
+ <script>
93
+ (function () {
94
+ var DOT = ' ' + String.fromCharCode(183) + ' ';
95
+ var params = new URLSearchParams(location.search);
96
+ var state = {
97
+ tab: params.get('tab') === 'cases' ? 'cases' : 'activity',
98
+ agent: params.get('agent') || '', workflow: params.get('workflow') || '', by: params.get('by') || '',
99
+ kind: params.get('kind') || '', status: params.get('status') || '',
100
+ period: params.has('period') ? params.get('period') : '30', q: params.get('q') || '',
101
+ };
102
+ var filters = { agents: [], workflows: [], people: [] };
103
+ var next = null;
104
+ var list = document.getElementById('auList');
105
+ var more = document.getElementById('auMore');
106
+ var el = {
107
+ agent: document.getElementById('auAgent'), workflow: document.getElementById('auWorkflow'), by: document.getElementById('auBy'),
108
+ kind: document.getElementById('auKind'), status: document.getElementById('auStatus'), period: document.getElementById('auPeriod'),
109
+ q: document.getElementById('auQ'), exportLink: document.getElementById('auExport'),
110
+ };
111
+
112
+ function esc(s) {
113
+ return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
114
+ return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
115
+ });
116
+ }
117
+ // The year only when it isn't this one.
118
+ function when(iso) {
119
+ var d = new Date(iso);
120
+ var opts = { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' };
121
+ if (d.getFullYear() !== new Date().getFullYear()) opts.year = 'numeric';
122
+ return d.toLocaleString(undefined, opts);
123
+ }
124
+ function agentLabel(name) {
125
+ if (!name) return 'Workspace';
126
+ var a = filters.agents.filter(function (x) { return x.name === name; })[0];
127
+ return a ? a.label : name;
128
+ }
129
+ function workflowTitle(agent, id) {
130
+ var w = filters.workflows.filter(function (x) { return x.agent === agent && x.id === id; })[0];
131
+ return w ? w.title : id;
132
+ }
133
+ function workflowHref(agent, id, tab) {
134
+ return '/agents/config?agent=' + encodeURIComponent(agent) + '&tab=workflows&workflow=' + encodeURIComponent(id) + (tab ? '&wtab=' + tab : '');
135
+ }
136
+
137
+ // The query both lists and the CSV file share.
138
+ function query(extra) {
139
+ var q = new URLSearchParams();
140
+ if (state.agent) q.set('agent', state.agent);
141
+ if (state.workflow) q.set('workflow', state.workflow);
142
+ if (state.by) q.set('by', state.by);
143
+ if (state.tab === 'activity' && state.kind) q.set('kind', state.kind);
144
+ if (state.tab === 'cases' && state.status) q.set('status', state.status);
145
+ if (state.period) q.set('since', new Date(Date.now() - Number(state.period) * 86400000).toISOString());
146
+ if (state.q) q.set('q', state.q);
147
+ Object.keys(extra || {}).forEach(function (k) { q.set(k, extra[k]); });
148
+ return q.toString();
149
+ }
150
+ // The page's own address keeps the filters, so a view can be shared.
151
+ function remember() {
152
+ var q = new URLSearchParams();
153
+ if (state.tab === 'cases') q.set('tab', 'cases');
154
+ ['agent', 'workflow', 'by', 'q'].forEach(function (k) { if (state[k]) q.set(k, state[k]); });
155
+ if (state.tab === 'activity' && state.kind) q.set('kind', state.kind);
156
+ if (state.tab === 'cases' && state.status) q.set('status', state.status);
157
+ if (state.period !== '30') q.set('period', state.period);
158
+ history.replaceState(null, '', '/audit' + (q.toString() ? '?' + q.toString() : ''));
159
+ }
160
+
161
+ // Where an event leads: its case, the workflow's version or changes,
162
+ // the agent, or the workspace setting.
163
+ function eventLink(e) {
164
+ var d = e.data || {};
165
+ if (e.run_id) return { href: '/inbox?case=' + encodeURIComponent(e.run_id), text: 'Case' };
166
+ if (e.workflow_id) return { href: workflowHref(e.agent, e.workflow_id, /brief version/i.test(d.label || '') || /Edited the workflow/.test(d.label || '') ? 'brief' : 'changes'), text: 'Workflow' };
167
+ if (e.agent) return { href: '/agents/config?agent=' + encodeURIComponent(e.agent), text: 'Agent' };
168
+ var path = String(d.path || '');
169
+ if (path.indexOf('/config/models') === 0) return { href: '/config?section=models', text: 'Models' };
170
+ if (path.indexOf('/config/apps') === 0) return { href: '/config?section=apps', text: 'Apps' };
171
+ if (path.indexOf('/abilities') === 0) return { href: '/config?section=abilities', text: 'Abilities' };
172
+ return { href: '/config?section=settings', text: 'Settings' };
173
+ }
174
+
175
+ function eventWords(e) {
176
+ var d = e.data || {};
177
+ if (e.kind === 'change') return { what: d.label || 'Changed a setting', detail: '' };
178
+ if (e.kind === 'decision') return { what: (d.approved ? (d.edited ? 'Approved as changed ' : 'Approved ') : 'Denied ') + (d.tool || ''), detail: d.reason ? String.fromCharCode(8220) + d.reason + String.fromCharCode(8221) : '' };
179
+ if (e.kind === 'answer') return { what: 'Answered ' + String.fromCharCode(8220) + String(d.answer || '').slice(0, 300) + String.fromCharCode(8221), detail: d.question ? 'to: ' + String(d.question).slice(0, 200) : '' };
180
+ var v = [d.verdict === 'good' ? 'good' : d.verdict === 'bad' ? 'bad' : '', d.edit === 'none' ? 'used unedited' : d.edit ? d.edit + ' edits' : ''].filter(Boolean).join(', ');
181
+ return { what: 'Feedback' + (v ? ': ' + v : ''), detail: d.note || '' };
182
+ }
183
+
184
+ function eventRow(e) {
185
+ var words = eventWords(e);
186
+ var link = eventLink(e);
187
+ var kind = e.kind === 'change' ? 'Setting' : e.kind === 'decision' ? 'Approval' : e.kind === 'answer' ? 'Answer' : 'Feedback';
188
+ var denied = e.kind === 'decision' && e.data && !e.data.approved ? ' denied' : '';
189
+ var where = agentLabel(e.agent) + (e.workflow_id ? DOT + workflowTitle(e.agent, e.workflow_id) : '');
190
+ return '<div class="au-row"><span class="au-when">' + esc(when(e.at)) + '</span>' +
191
+ '<span class="au-kind ' + esc(e.kind) + denied + '">' + kind + '</span>' +
192
+ '<span class="au-what"><strong>' + esc(words.what) + '</strong>' + (words.detail ? '<span class="au-detail">' + esc(words.detail) + '</span>' : '') +
193
+ '<span class="au-where">' + (e.by ? esc(e.by) + DOT : '') + esc(where) + '</span></span>' +
194
+ '<a class="au-open" href="' + esc(link.href) + '">' + esc(link.text) + ' ' + String.fromCharCode(8594) + '</a></div>';
195
+ }
196
+
197
+ function caseRow(c) {
198
+ var pill = c.status === 'done' ? ['good', 'Done'] : c.status === 'error' ? ['bad', 'Failed'] : c.status === 'awaiting_approval' ? ['warn', 'Waiting'] : ['run', 'Running'];
199
+ return '<div class="au-row au-case"><span class="au-state ' + pill[0] + '">' + pill[1] + '</span>' +
200
+ '<span class="au-what"><strong>' + esc(c.workflowTitle) + (c.inputs ? DOT + esc(c.inputs) : '') + '</strong>' +
201
+ (c.outcome ? '<span class="au-detail">' + esc(c.outcome) + '</span>' : '') +
202
+ '<span class="au-where">' + esc(when(c.startedAt)) + DOT + esc(agentLabel(c.agent)) + (c.briefVersion ? DOT + 'brief v' + c.briefVersion : '') + (c.people.length ? DOT + 'decided by ' + esc(c.people.join(', ')) : '') + '</span></span>' +
203
+ '<a class="au-open" href="/inbox?case=' + encodeURIComponent(c.id) + '">Open ' + String.fromCharCode(8594) + '</a></div>';
204
+ }
205
+
206
+ function load(append) {
207
+ var url = state.tab === 'cases' ? '/audit/cases?' : '/audit/events?';
208
+ var extra = append && next != null ? { before: String(next) } : {};
209
+ if (state.tab === 'activity') extra.limit = '100';
210
+ if (!append) list.innerHTML = '<p class="hint">Loading' + String.fromCharCode(8230) + '</p>';
211
+ more.hidden = true;
212
+ return fetch(url + query(extra), { headers: { accept: 'application/json' } })
213
+ .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
214
+ .then(function (data) {
215
+ var rows = state.tab === 'cases' ? data.cases.map(caseRow) : data.events.map(eventRow);
216
+ next = data.next;
217
+ if (state.tab === 'activity' && data.events.length < 100) next = null;
218
+ var box = list.querySelector('.au-list');
219
+ if (append && box) box.insertAdjacentHTML('beforeend', rows.join(''));
220
+ else list.innerHTML = rows.length ? '<div class="au-list">' + rows.join('') + '</div>'
221
+ : '<div class="au-list"><p class="au-empty">' + (state.tab === 'cases' ? 'No cases match.' : 'Nothing matches. Changes to settings, and every approval, answer and feedback, are listed here as they happen.') + '</p></div>';
222
+ more.hidden = next == null;
223
+ })
224
+ .catch(function (err) { list.innerHTML = '<p class="error">Could not load it: ' + esc(err.message) + '</p>'; });
225
+ }
226
+
227
+ function fillWorkflows() {
228
+ var shown = filters.workflows.filter(function (w) { return !state.agent || w.agent === state.agent; });
229
+ el.workflow.innerHTML = '<option value="">All workflows</option>' + shown.map(function (w) {
230
+ return '<option value="' + esc(w.id) + '"' + (w.id === state.workflow ? ' selected' : '') + '>' + esc(w.title) + (state.agent ? '' : ' (' + esc(agentLabel(w.agent)) + ')') + '</option>';
231
+ }).join('');
232
+ if (state.workflow && !shown.some(function (w) { return w.id === state.workflow; })) state.workflow = '';
233
+ }
234
+
235
+ function sync() {
236
+ var tabs = document.querySelectorAll('.au-tabs button');
237
+ for (var i = 0; i < tabs.length; i++) tabs[i].setAttribute('aria-selected', String(tabs[i].getAttribute('data-tab') === state.tab));
238
+ el.kind.hidden = state.tab !== 'activity';
239
+ el.status.hidden = state.tab !== 'cases';
240
+ el.exportLink.hidden = state.tab !== 'activity';
241
+ el.exportLink.href = '/audit/events.csv?' + query();
242
+ remember();
243
+ }
244
+
245
+ function changed() { sync(); load(false); }
246
+
247
+ document.querySelector('.au-tabs').addEventListener('click', function (ev) {
248
+ var b = ev.target.closest('button[data-tab]');
249
+ if (!b || b.getAttribute('data-tab') === state.tab) return;
250
+ state.tab = b.getAttribute('data-tab');
251
+ changed();
252
+ });
253
+ el.agent.addEventListener('change', function () { state.agent = el.agent.value; fillWorkflows(); changed(); });
254
+ ['workflow', 'by', 'kind', 'status', 'period'].forEach(function (k) {
255
+ el[k].addEventListener('change', function () { state[k] = el[k].value; changed(); });
256
+ });
257
+ var typing;
258
+ el.q.addEventListener('input', function () {
259
+ clearTimeout(typing);
260
+ typing = setTimeout(function () { state.q = el.q.value.trim(); changed(); }, 300);
261
+ });
262
+ more.addEventListener('click', function () { load(true); });
263
+
264
+ el.q.value = state.q;
265
+ el.kind.value = state.kind;
266
+ el.status.value = state.status;
267
+ el.period.value = state.period;
268
+ fetch('/audit/filters', { headers: { accept: 'application/json' } })
269
+ .then(function (r) { return r.ok ? r.json() : filters; })
270
+ .catch(function () { return filters; })
271
+ .then(function (f) {
272
+ filters = f;
273
+ el.agent.innerHTML = '<option value="">All agents</option>' + f.agents.map(function (a) { return '<option value="' + esc(a.name) + '"' + (a.name === state.agent ? ' selected' : '') + '>' + esc(a.label) + '</option>'; }).join('');
274
+ el.by.innerHTML = '<option value="">Anyone</option>' + f.people.map(function (p) { return '<option value="' + esc(p) + '"' + (p === state.by ? ' selected' : '') + '>' + esc(p) + '</option>'; }).join('');
275
+ fillWorkflows();
276
+ changed();
277
+ });
278
+ })();
279
+ </script>
280
+ </body>
281
+ </html>`;
@@ -34,6 +34,7 @@ const LABELS = [
34
34
  [/^\/agents\/[^/]+\/abilities/, 'Changed abilities'],
35
35
  [/^\/agents\/[^/]+\/notifier/, 'Changed the messaging app'],
36
36
  [/^\/agents\/[^/]+\/env/, 'Changed agent secrets'],
37
+ [/^\/config\/policies\/versions\/(\d+)\/restore$/, (_method, m) => `Restored shared policies version ${m[1]}`],
37
38
  [/^\/config\/policies$/, 'Changed shared policies'],
38
39
  [/^\/config\/models/, 'Changed models'],
39
40
  [/^\/config\/time-zone$/, 'Changed the time zone'],
@@ -32,9 +32,11 @@ const AGENTS_ICON = '<svg class="le-nav-icon" viewBox="3 3 18 18" fill="currentC
32
32
  const WORKFLOWS_ICON = '<svg class="le-nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/><path d="M10 6.5h4a3.5 3.5 0 0 1 3.5 3.5v4"/><path d="M14 17.5h-4A3.5 3.5 0 0 1 6.5 14v-4"/></svg>';
33
33
  // An inbox tray, for the Inbox.
34
34
  const INBOX_ICON = '<svg class="le-nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg>';
35
+ // A clipboard with a tick, for Audit.
36
+ const AUDIT_ICON = '<svg class="le-nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5" y="4" width="14" height="17" rx="2"/><path d="M9 4V3h6v1"/><path d="m9 13 2 2 4-4"/></svg>';
35
37
  // A gear, for Settings.
36
38
  const SETTINGS_ICON = '<svg class="le-nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>';
37
- // Two columns: the sections (Inbox, Agents, Workflows, Settings), and
39
+ // Two columns: the sections (Inbox, Agents, Workflows, Audit, Settings), and
38
40
  // beside them what's in the current one. Goals and Jobs stay at /goals
39
41
  // and /jobs, out of the menu: LoopEngine is about workflows. Pointing at
40
42
  // another section shows its column instead, until the pointer leaves.
@@ -46,6 +48,7 @@ export const consoleSidebarHtml = `<aside class="le-sidebar" aria-label="Console
46
48
  <a class="le-rail-item" href="/inbox" data-le-nav-head="inbox" data-le-section="inbox">${INBOX_ICON}<span>Inbox</span><span class="le-pill warn le-inbox-count" id="leInboxCount" hidden></span></a>
47
49
  <a class="le-rail-item" href="/agents" data-le-nav-head="agents" data-le-section="agents">${AGENTS_ICON}<span>Agents</span></a>
48
50
  <a class="le-rail-item" href="/workflows" data-le-nav-head="workflows" data-le-section="workflows">${WORKFLOWS_ICON}<span>Workflows</span></a>
51
+ <a class="le-rail-item" href="/audit" data-le-nav-head="audit" data-le-section="audit">${AUDIT_ICON}<span>Audit</span></a>
49
52
  <span class="le-rail-gap"></span>
50
53
  <a class="le-rail-item" href="/config?section=settings" data-le-nav-head="settings" data-le-section="settings">${SETTINGS_ICON}<span>Settings</span></a>
51
54
  <div class="le-who" id="leWho" hidden></div>
@@ -386,7 +389,8 @@ export const consoleShellScript = `<script>
386
389
  : page === 'agents' || page === 'agent-config' || page === 'chat' || page === 'interview' ? 'agents'
387
390
  : page === 'workflows' || page === 'workflows-overview' ? 'workflows'
388
391
  : page === 'config' ? 'settings'
389
- : page === 'inbox' ? 'inbox' : '';
392
+ : page === 'inbox' ? 'inbox'
393
+ : page === 'audit' ? 'audit' : '';
390
394
  var railItems = document.querySelectorAll('[data-le-section]');
391
395
  for (var ri = 0; ri < railItems.length; ri++) {
392
396
  if (railItems[ri].getAttribute('data-le-section') === section0) railItems[ri].classList.add('is-current');
@@ -29,6 +29,11 @@ export const globalConfigPageHtml = `<!doctype html>
29
29
  <meta name="viewport" content="width=device-width, initial-scale=1">
30
30
  <title>LoopEngine Settings</title>
31
31
  <style>${devUiCss}
32
+ .policy-versions { margin-top: 12px; max-width: 720px; font-size: 13px; }
33
+ .policy-versions summary { cursor: pointer; font-weight: 600; color: var(--accent-ink); }
34
+ .policy-versions ol { list-style: none; margin: 10px 0 0; padding: 0 0 0 12px; border-left: 2px solid var(--line); display: grid; gap: 10px; }
35
+ .policy-versions pre { white-space: pre-wrap; margin: 4px 0 0; }
36
+ .policy-versions .link-btn { background: none; border: 0; padding: 0; height: auto; color: var(--accent-ink); font: inherit; font-weight: 600; cursor: pointer; }
32
37
  section { margin-bottom: 28px; }
33
38
  .provider-name { display: inline-flex; align-items: center; gap: 8px; white-space: nowrap; }
34
39
  .le-provider-icon { width: 18px; height: 18px; flex: none; }
@@ -1184,7 +1189,9 @@ ${consoleShellScript}
1184
1189
  '<textarea id="policiesText" rows="8" placeholder="- Refunds within 30 days of purchase.&#10;- Never share customer details with other customers.&#10;- Reply in the language the customer wrote in.&#10;- Sign emails: The Support Team">' + escapeHtml(p.policies || '') + '</textarea>' +
1185
1190
  '<div><button type="submit" class="primary">Save</button></div>' +
1186
1191
  '<div id="policiesMsg" class="hint"></div>' +
1187
- '</form>';
1192
+ '</form>' +
1193
+ '<div id="policiesVersions" class="policy-versions"></div>';
1194
+ loadPolicyVersions();
1188
1195
  var form = document.getElementById('policiesForm');
1189
1196
  form.addEventListener('submit', function (ev) {
1190
1197
  ev.preventDefault();
@@ -1197,11 +1204,44 @@ ${consoleShellScript}
1197
1204
  .then(function (r) {
1198
1205
  btn.disabled = false;
1199
1206
  msg.innerHTML = r.ok ? 'Saved. Every workflow' + String.fromCharCode(8217) + 's next run reads them.' : '<span class="error">' + escapeHtml(r.body.error || 'Could not save') + '</span>';
1207
+ if (r.ok) loadPolicyVersions();
1200
1208
  })
1201
1209
  .catch(function (err) { btn.disabled = false; msg.innerHTML = '<span class="error">' + escapeHtml(err.message) + '</span>'; });
1202
1210
  });
1203
1211
  }
1204
1212
 
1213
+ // Every saved version of the policies: who saved it, when and why; any
1214
+ // earlier one can be read or restored (saved as a new version).
1215
+ function loadPolicyVersions() {
1216
+ var box = document.getElementById('policiesVersions');
1217
+ if (!box) return;
1218
+ fetch('/config/policies/versions', { cache: 'no-store' })
1219
+ .then(function (r) { return r.ok ? r.json() : null; })
1220
+ .then(function (data) {
1221
+ var versions = (data && data.versions) || [];
1222
+ if (versions.length < 2) { box.innerHTML = ''; return; }
1223
+ var when = function (v) { return new Date(v.at).toLocaleString(undefined, { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' }); };
1224
+ box.innerHTML = '<details><summary>History (' + versions.length + ' versions)</summary><ol>' + versions.map(function (v) {
1225
+ var current = v.number === data.current;
1226
+ return '<li data-version="' + v.number + '"><div><strong>v' + v.number + '</strong> <span class="hint">' + [v.by ? 'by ' + escapeHtml(v.by) : '', escapeHtml(when(v)), v.reason ? escapeHtml(v.reason) : ''].filter(Boolean).join(' ' + String.fromCharCode(183) + ' ') + '</span>' +
1227
+ (current ? ' <span class="le-pill good">In use</span>' : ' <button type="button" class="link-btn" data-restore>Restore</button>') + '</div>' +
1228
+ '<pre class="hint">' + escapeHtml(v.content || '(empty)') + '</pre></li>';
1229
+ }).join('') + '</ol></details>';
1230
+ box.querySelectorAll('[data-restore]').forEach(function (btn) {
1231
+ btn.addEventListener('click', function () {
1232
+ if (btn.getAttribute('data-confirming') !== '1') { btn.setAttribute('data-confirming', '1'); btn.textContent = 'Click again to restore'; return; }
1233
+ btn.disabled = true;
1234
+ var n = btn.closest('li').getAttribute('data-version');
1235
+ fetch('/config/policies/versions/' + n + '/restore', { method: 'POST' })
1236
+ .then(function (r) { return r.json().then(function (b) { if (!r.ok) throw new Error(b.error || 'Could not restore'); }); })
1237
+ .then(loadPolicies)
1238
+ .catch(function (err) { btn.disabled = false; btn.textContent = err.message; });
1239
+ });
1240
+ });
1241
+ })
1242
+ .catch(function () {});
1243
+ }
1244
+
1205
1245
  function loadPolicies() {
1206
1246
  if (!document.getElementById('policiesBox')) return;
1207
1247
  fetch('/config/policies', { cache: 'no-store' })
@@ -55,12 +55,21 @@ export interface EvalCheck {
55
55
  pass: boolean;
56
56
  reason?: string;
57
57
  }
58
+ export interface StandIn {
59
+ tool: string;
60
+ input: Record<string, unknown>;
61
+ replayed: boolean;
62
+ }
58
63
  export interface EvalCaseResult {
59
64
  caseId: string;
60
65
  result?: string;
61
66
  error?: string;
62
67
  /** The tools the test run called. */
63
68
  tools?: string[];
69
+ /** The calls a test run doesn't make (they'd change something, or
70
+ * need approval): each with whether it got its reply from the case's
71
+ * own run, or a note to assume it worked. */
72
+ standIns?: StandIn[];
64
73
  checks?: EvalCheck[];
65
74
  /** Rounds from before criteria: a 1-5 score. */
66
75
  score?: number;
@@ -164,11 +173,13 @@ export interface EvalRunDeps {
164
173
  model: string;
165
174
  judgeLabel: string;
166
175
  judge: ModelCall;
167
- /** One test run of the workflow with these inputs: its result, and
168
- * the tools it called. */
169
- runCase(params: Record<string, string>): Promise<{
176
+ /** One test run of the workflow for this case (its inputs, and the run
177
+ * it came from to replay): its result, the tools it called, and the
178
+ * calls it didn't make. */
179
+ runCase(c: EvalCase): Promise<{
170
180
  result: string;
171
181
  tools: string[];
182
+ standIns?: StandIn[];
172
183
  }>;
173
184
  }
174
185
  /** Runs every case once and scores it, recording progress as it goes.
@@ -306,7 +306,7 @@ export function startEvalRound(deps) {
306
306
  for (const c of cases) {
307
307
  let run;
308
308
  try {
309
- run = await deps.runCase(c.params);
309
+ run = await deps.runCase(c);
310
310
  }
311
311
  catch (err) {
312
312
  run = { error: err instanceof Error ? err.message : String(err) };
@@ -314,7 +314,7 @@ export function startEvalRound(deps) {
314
314
  const checks = await checkCase(deps.judge, { instructions: deps.instructions, criteria, reference: c.reference ?? '', run });
315
315
  results.push({
316
316
  caseId: c.id,
317
- ...('error' in run ? { error: run.error } : { result: run.result.slice(0, 20000), tools: [...new Set(run.tools)] }),
317
+ ...('error' in run ? { error: run.error } : { result: run.result.slice(0, 20000), tools: [...new Set(run.tools)], ...(run.standIns?.length ? { standIns: run.standIns.slice(0, 50) } : {}) }),
318
318
  checks,
319
319
  });
320
320
  const now = readEvals(deps.agentDir, deps.workflowId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "loopengine",
3
- "version": "0.4.3",
3
+ "version": "0.4.4",
4
4
  "type": "module",
5
5
  "description": "Runtime for tool-using AI agents with a transparent ReAct loop.",
6
6
  "license": "MIT",