Multiplayer agent harness for work.
sessions: purge captured LLM prompts after 30 days; drop the legacy inline request column (#2485)
Regan Bellb36bafd090a2
diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.htmlindex 46d820b82..deca451b3 100644--- a/plugins/admin/public/index.html+++ b/plugins/admin/public/index.html@@ -10639,7 +10639,7 @@);}function requestBody(q) {- return q && q.promptEnvelope != null ? q.promptEnvelope : q ? q.request : null;+ return q && q.promptEnvelope != null ? q.promptEnvelope : null;}function contextSections(request, transport) {const req = request && typeof request === "object" ? request : {};diff --git a/scripts/migrate-principals-to-email.mjs b/scripts/migrate-principals-to-email.mjsindex cf0bef8c7..9a76ad53e 100644--- a/scripts/migrate-principals-to-email.mjs+++ b/scripts/migrate-principals-to-email.mjs@@ -91,7 +91,7 @@ const LIVE_COLUMNS = [["directory_channel_members", ["principal_id"]],];const HISTORY_COLUMNS = [- ["session_llm_requests", ["scope_label", "request"]],+ ["session_llm_requests", ["scope_label"]],["runs", ["request", "result"]],["tool_calls", ["output"]],["egress_events", ["scope_label", "principal_id"]],diff --git a/src/sessions/memory-session-store.ts b/src/sessions/memory-session-store.tsindex f13700fab..f68c0962f 100644--- a/src/sessions/memory-session-store.ts+++ b/src/sessions/memory-session-store.ts@@ -383,7 +383,6 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStoremodel: rec.model,scopeLabel: rec.scopeLabel as ScopeId,createdAt: now(),- request: null,promptHash: envelope?.hash ?? null,truncated: rec.truncated ?? false,ttftMs: rec.ttftMs ?? null,@@ -415,7 +414,7 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStore): all;return filtered.map((r) => {- if (opts?.omitRequest) return { ...r, request: null };+ if (opts?.omitRequest) return { ...r };const body = r.promptHash != null ? promptEnvelopes.get(r.promptHash) : undefined;return body !== undefined ? { ...r, promptEnvelope: JSON.parse(body) } : { ...r };});diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.tsindex bf2f53217..e1ccc0cce 100644--- a/src/sessions/postgres-session-store.ts+++ b/src/sessions/postgres-session-store.ts@@ -61,6 +61,9 @@ import {} from "./items.ts";import { SECURITY_SCREEN_STEP, screenPayloadFromEnvelope } from "../security/security-posture.ts";+const LLM_CAPTURE_PURGE_BATCH = 100;+const ENVELOPE_TOUCH_MS = 24 * 60 * 60_000;+const threadRefOriginExpr = (threadRef: string): string =>`COALESCE(substring(${threadRef} FROM '${stableOriginPattern(ORIGIN_ALTERNATION)}'), substring(${threadRef} FROM '${legacyOriginPattern(ORIGIN_ALTERNATION)}'), 'conversation')`;@@ -154,7 +157,6 @@ function rowToLlmRequest(r: Record<string, unknown>): LlmRequestRecord {model: r.model as string,scopeLabel: r.scope_label as ScopeId,createdAt: Number(r.created_at),- request: r.request != null ? JSON.parse(r.request as string) : null,promptHash: r.prompt_hash == null ? null : (r.prompt_hash as string),...(r.prompt_body != null ? { promptEnvelope: JSON.parse(r.prompt_body as string) } : {}),truncated: Boolean(r.truncated),@@ -382,7 +384,7 @@ export function createPostgresSessionStore(connectionString: string, opts: Store)SELECT * FROM rollup ORDER BY day, scope_id, origin, cron_id, model`;- const { pool, q } = createPgPool(+ const { pool, q, query } = createPgPool(connectionString,[...DIRECTORY_MIGRATIONS,@@ -955,6 +957,20 @@ export function createPostgresSessionStore(connectionString: string, opts: Store`ALTER INDEX items_one_call_per_kind_digest RENAME TO items_one_call_per_kind`,],},+ {+ id: "sessions/store/0041-drop-inline-llm-request",+ statements: [+ `SET LOCAL lock_timeout = '15s'`,+ `ALTER TABLE session_llm_requests DROP COLUMN IF EXISTS request`,+ ],+ },+ {+ id: "sessions/store/0042-llm-prompt-envelopes-created-at",+ statements: [+ `CREATE INDEX CONCURRENTLY IF NOT EXISTS llm_prompt_envelopes_created_at+ ON llm_prompt_envelopes(created_at)`,+ ],+ },],[{@@ -1356,7 +1372,9 @@ export function createPostgresSessionStore(connectionString: string, opts: Storeconst envelope = promptEnvelopeBody(rec.promptEnvelope);if (envelope) {await q(- "INSERT INTO llm_prompt_envelopes(hash, body, created_at) VALUES ($1,$2,$3) ON CONFLICT DO NOTHING",+ `INSERT INTO llm_prompt_envelopes(hash, body, created_at) VALUES ($1,$2,$3)+ ON CONFLICT (hash) DO UPDATE SET created_at = EXCLUDED.created_at+ WHERE llm_prompt_envelopes.created_at < EXCLUDED.created_at - ${ENVELOPE_TOUCH_MS}`,[envelope.hash, envelope.body, now()],{ signal },);@@ -1369,7 +1387,6 @@ export function createPostgresSessionStore(connectionString: string, opts: Storemodel: rec.model,scopeLabel: rec.scopeLabel as ScopeId,createdAt: now(),- request: null,promptHash: envelope?.hash ?? null,...(rec.promptEnvelope !== undefined ? { promptEnvelope: rec.promptEnvelope } : {}),truncated: rec.truncated ?? false,@@ -1470,6 +1487,23 @@ export function createPostgresSessionStore(connectionString: string, opts: Storereturn samples;},+ async purgeLlmCaptures(cutoff, opts) {+ const deadline = opts?.deadline ?? Infinity;+ let envelopes = 0;+ while (Date.now() < deadline && !opts?.stop?.()) {+ const deleted = await query(+ `DELETE FROM llm_prompt_envelopes+ WHERE hash IN (SELECT hash FROM llm_prompt_envelopes WHERE created_at < $1+ ORDER BY created_at LIMIT $2 FOR UPDATE SKIP LOCKED)+ AND created_at < $1`,+ [cutoff, LLM_CAPTURE_PURGE_BATCH],+ );+ envelopes += deleted.rowCount;+ if (deleted.rowCount < LLM_CAPTURE_PURGE_BATCH) break;+ }+ return envelopes;+ },+async addParticipant(sessionId, principalId, title, opts): Promise<void> {const includeHistory = opts?.includeHistory === true;await q(diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.tsindex 593902b09..b03c448f6 100644--- a/src/sessions/session-store.ts+++ b/src/sessions/session-store.ts@@ -3,6 +3,8 @@ import type { EntryType, ScopeId, Session, SessionEntry, SessionType, SpawnMetaimport { sleep } from "../util/async.ts";import type { GoalRecord } from "../harness/goal.ts";+export const LLM_CAPTURE_RETENTION_MS = 30 * 24 * 60 * 60_000;+export function promptEnvelopeBody(envelope: unknown): { hash: string; body: string } | null {if (envelope == null) return null;let body: string;@@ -249,7 +251,6 @@ export interface LlmRequestRecord {model: string;scopeLabel: ScopeId;createdAt: number;- request: unknown;promptHash: string | null;promptEnvelope?: unknown;truncated: boolean;@@ -580,6 +581,7 @@ export interface SessionStore {listLlmRequests(sessionId: string, opts?: ListLlmRequestsOptions): Promise<LlmRequestRecord[]>;/** The most recent security screenings across every scope, newest first. */listScreenSamples(limit: number): Promise<ScreenSample[]>;+ purgeLlmCaptures?(cutoff: number, opts?: { deadline?: number; stop?: () => boolean }): Promise<number>;addParticipant(sessionId: string, principalId: string, title?: string, opts?: AddParticipantOptions): Promise<void>;removeParticipant(sessionId: string, principalId: string): Promise<void>;diff --git a/src/wiring.ts b/src/wiring.tsindex 0ba9a4de9..ba6ccbd39 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -323,7 +323,7 @@ import { createCustomProviderStore, type CustomProviderStore } from "./model/cusimport { createMemorySessionStore } from "./sessions/memory-session-store.ts";import { createPostgresSessionStore } from "./sessions/postgres-session-store.ts";import { createMemoryToolOutputStore, createPostgresToolOutputStore } from "./sessions/tool-output.ts";-import type { SessionStore } from "./sessions/session-store.ts";+import { LLM_CAPTURE_RETENTION_MS, type SessionStore } from "./sessions/session-store.ts";import { createMockHarness } from "./harness/mock-harness.ts";import {fileCompanyChatGPTAuth,@@ -2782,12 +2782,30 @@ export function buildApp(}): null;const MONITOR_RETENTION_SWEEP_MS = 24 * 60 * 60_000;+ const LLM_CAPTURE_SWEEP_MS = 5 * 60_000;+ const LLM_CAPTURE_SWEEP_BUDGET_MS = 30_000;const spendSweeper = sessions.refreshSpendRollup? createSweeper(() => leaderLease.hold("spend:refresh", () => sessions.refreshSpendRollup!()), 60_000, {label: "spend-refresh",immediate: true,}): null;+ const llmCaptureSweeper = sessions.purgeLlmCaptures+ ? createSweeper(+ () =>+ leaderLease.hold("llm-capture:retention", async (lost) => {+ let leaseLost = false;+ void lost.then(() => (leaseLost = true));+ const purged = await sessions.purgeLlmCaptures!(Date.now() - LLM_CAPTURE_RETENTION_MS, {+ deadline: Date.now() + LLM_CAPTURE_SWEEP_BUDGET_MS,+ stop: () => leaseLost,+ });+ if (purged) console.log(`[llm-capture] purged ${purged} prompt envelope(s) past retention`);+ }),+ LLM_CAPTURE_SWEEP_MS,+ { label: "llm-capture-retention" },+ )+ : null;const monitorRetentionSweeper = createSweeper(() => leaderLease.hold("monitor:retention:sweep", () => monitors.deleteDefunct(Date.now())),MONITOR_RETENTION_SWEEP_MS,@@ -2864,6 +2882,7 @@ export function buildApp(.catch(swallowAs("wiring: monitor resume failed", undefined));monitorRetentionSweeper.start();spendSweeper?.start();+ llmCaptureSweeper?.start();semanticMemory.start();if (config.skillSyncPollMs > 0) skillSyncEngine.start(config.skillSyncPollMs);blobSweeper.start();@@ -2895,6 +2914,7 @@ export function buildApp(processReaper?.stop(),monitorRetentionSweeper.stop(),spendSweeper?.stop(),+ llmCaptureSweeper?.stop(),semanticMemory.stop(),skillSyncEngine.stop(),idleSweeper?.stop(),diff --git a/test/admin-observability.test.ts b/test/admin-observability.test.tsindex 3293aec9d..f2502131a 100644--- a/test/admin-observability.test.ts+++ b/test/admin-observability.test.ts@@ -189,7 +189,6 @@ test("an org admin sees EXACTLY what we sent the model per turn (captured requesstep: number;model: string;truncated: boolean;- request: unknown;promptEnvelope?: unknown;}[];};@@ -198,8 +197,11 @@ test("an org admin sees EXACTLY what we sent the model per turn (captured requesassert.equal(meta.step, 0, "first agent step of the turn");assert.equal(typeof meta.turnSeq, "number", "correlated to the turn's user entry");assert.equal(meta.truncated, false);- assert.equal(meta.request, null, "the bare list omits the prompt body — bodies load per turn on demand");- assert.equal(meta.promptEnvelope, undefined, "…and the prompt envelope");+ assert.equal(+ meta.promptEnvelope,+ undefined,+ "the bare list omits the prompt body — bodies load per turn on demand",+ );const tr = await get(s.base,`/v1/admin/sessions/${encodeURIComponent(conv.id)}/llm?turnSeq=${meta.turnSeq}&scope=org:default-org`,diff --git a/test/postgres-store.test.ts b/test/postgres-store.test.tsindex e6cf63d40..55f567885 100644--- a/test/postgres-store.test.ts+++ b/test/postgres-store.test.ts@@ -767,7 +767,7 @@ test("pg session store: one-per-thread, TTL/fenced lease, monotonic log, visibilconst metaOnly = await s.listLlmRequests(a.id, { omitRequest: true });assert.equal(metaOnly.length, 2, "every row still listed");assert.ok(- metaOnly.every((r) => r.request === null),+ metaOnly.every((r) => r.promptEnvelope === undefined),"bodies omitted from the projection",);assert.equal(metaOnly[1]!.ttftMs, 1200, "metadata (timing) still selected");@@ -3149,3 +3149,63 @@ test("pg late joiners start after any stored sequence gap", { skip }, async () ={ scopeId: scope, channelName: "eng", sessionCount: 0, lastActivityAt: null },]);});++test("pg LLM capture retention drops old prompt envelopes and keeps request rows", { skip }, async () => {+ const day = 86_400_000;+ let at = Date.UTC(2025, 0, 1);+ const store = createPostgresSessionStore(URL!, { now: () => at });+ const pg = (await import("pg")).default;+ const raw = new pg.Pool({ connectionString: URL });+ const tag = randomUUID();+ const scope = scopeId("personal", `retention-${tag}`);+ const session = await store.getOrCreateByThread(`retention-${tag}`, "dm", scope);+ const record = (text: string) =>+ store.recordLlmRequest(session.id, {+ turnSeq: 1,+ step: 0,+ model: "retention",+ scopeLabel: scope,+ promptEnvelope: { messages: [{ role: "user", content: `${tag} ${text}` }] },+ usage: { input: 1, output: 2, cacheRead: 3, cacheWrite: 4, totalTokens: 10, costUsd: 0.5 },+ });+ try {+ const old = await record("old");+ const reused = await record("reused");+ for (let i = 0; i < 250; i++) await record(`bulk ${i}`);+ at += 40 * day;+ const kept = await record("recent");+ await record("reused");+ const range = { from: Date.UTC(2025, 0, 1), to: Date.UTC(2025, 0, 1) + 41 * day };+ await store.refreshSpendRollup!();+ const spendBefore = (await store.spendReport!(range)).rows;+ const dirtyBefore = Number((await raw.query("SELECT count(*) AS n FROM session_spend_dirty")).rows[0].n);++ assert.equal(await store.purgeLlmCaptures!(at - 30 * day, { stop: () => true }), 0);+ assert.equal(await store.purgeLlmCaptures!(at - 30 * day), 251);+ assert.equal(await store.purgeLlmCaptures!(at - 30 * day), 0);++ const rows = new Map((await store.listLlmRequests(session.id)).map((r) => [r.id, r]));+ assert.equal(rows.size, 254);+ assert.equal(rows.get(old.id)!.promptEnvelope, undefined);+ assert.ok(rows.get(old.id)!.usage, "usage survives the purge");+ assert.ok(rows.get(reused.id)!.promptEnvelope, "an envelope reused within retention survives");+ assert.ok(rows.get(kept.id)!.promptEnvelope);+ assert.equal(+ Number((await raw.query("SELECT count(*) AS n FROM session_spend_dirty")).rows[0].n),+ dirtyBefore,+ "purging prompts does not dirty spend days",+ );+ assert.deepEqual((await store.spendReport!(range)).rows, spendBefore);+ assert.deepEqual(await store.spendRollup(range), spendBefore);+ assert.equal(+ (+ await raw.query(+ "SELECT count(*) AS n FROM information_schema.columns WHERE table_name = 'session_llm_requests' AND column_name = 'request'",+ )+ ).rows[0].n,+ "0",+ );+ } finally {+ await raw.end();+ }+});diff --git a/test/session-store.test.ts b/test/session-store.test.tsindex 0198da402..4b714d62a 100644--- a/test/session-store.test.ts+++ b/test/session-store.test.ts@@ -475,7 +475,6 @@ for (const [name, make] of backends) {);assert.equal(list[0]!.turnSeq, 0, "correlated to the turn's user entry seq");assert.equal(list[1]!.truncated, true, "truncated flag round-trips");- assert.equal(list[0]!.request, null, "message-array bodies are never stored");assert.deepEqual(list[0]!.promptEnvelope,{ system: "you are helpful", tools: [{ name: "execute" }] },@@ -550,7 +549,7 @@ for (const [name, make] of backends) {const meta = await store.listLlmRequests(s.id, { omitRequest: true });assert.equal(meta.length, 4, "every row still listed");assert.ok(- meta.every((r) => r.request === null && r.promptEnvelope === undefined),+ meta.every((r) => r.promptEnvelope === undefined),"bodies omitted",);assert.ok(