Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

sessions: replace per-step LLM request bodies with hash-deduped prompt envelopes (#484)

Regan Bell73d793b3db00
diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.html
index d06d4996a..b6debbb63 100644
--- a/plugins/admin/public/index.html
+++ b/plugins/admin/public/index.html
@@ -12060,7 +12060,7 @@
const stats = document.createElement("div");
stats.className = "context-stats";
const latest = reqs[reqs.length - 1];
- const latestSections = contextSections(latest.request, latest.transport);
+ const latestSections = contextSections(requestBody(latest), latest.transport);
stats.append(metaChip((latest.model || "?") + " · " + fmtContextSize(latest, latestSections)));
cacheMetaItems(turnCache).forEach((b) => stats.appendChild(b));
stats.appendChild(rawJsonLink(reqs));
@@ -13928,6 +13928,9 @@
"\n\n(auth + anthropic-version headers are added by the provider SDK below the capture point, so they aren't shown)"
);
}
+ function requestBody(q) {
+ return q && q.promptEnvelope != null ? q.promptEnvelope : q ? q.request : null;
+ }
function contextSections(request, transport) {
const req = request && typeof request === "object" ? request : {};
const messages = Array.isArray(req.messages) ? req.messages : [];
@@ -13947,7 +13950,9 @@
{
key: "messages",
label: "Messages",
- note: messages.length + " message" + (messages.length === 1 ? "" : "s"),
+ note: messages.length
+ ? messages.length + " message" + (messages.length === 1 ? "" : "s")
+ : "not re-captured per step — the transcript is the record",
text: messages.map(messageEntryText).join("\n\n"),
},
{
@@ -14113,8 +14118,8 @@
a.className = "context-raw";
let payload;
if (requests.length === 1) {
- payload = requests[0]?.request;
- if (requests[0]?.transport) payload = { request: requests[0].request, transport: requests[0].transport };
+ payload = requestBody(requests[0]);
+ if (requests[0]?.transport) payload = { request: requestBody(requests[0]), transport: requests[0].transport };
} else {
payload = requests.map((q) => ({
step: q.step,
@@ -14122,7 +14127,7 @@
createdAt: q.createdAt,
truncated: !!q.truncated,
...(q.transport ? { transport: q.transport } : {}),
- request: q.request,
+ request: requestBody(q),
}));
}
a.href = "#";
@@ -14139,7 +14144,7 @@
return a;
}
function renderContextRequest(q, i, totalRequests) {
- const sections = contextSections(q.request, q.transport);
+ const sections = contextSections(requestBody(q), q.transport);
const wrap = document.createElement("div");
wrap.className = "context-request";
const selection = document.createElement("div");
@@ -14181,7 +14186,7 @@
role.className = "role";
role.textContent = "sent to model";
const latest = requests[requests.length - 1] || { request: {} };
- const latestSections = opts.latestSections || contextSections(latest.request, latest.transport);
+ const latestSections = opts.latestSections || contextSections(requestBody(latest), latest.transport);
const sync = () => {
const open = !block.classList.contains("collapsed");
tog.textContent = open ? "▾" : "▸";
diff --git a/src/harness/claude-harness.ts b/src/harness/claude-harness.ts
index 0c7abcdf2..59ee01bc0 100644
--- a/src/harness/claude-harness.ts
+++ b/src/harness/claude-harness.ts
@@ -525,9 +525,8 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
const wallMs = turn.turnWallClockMs ?? defaultTurnWallClockMs;
let timer: NodeJS.Timeout | undefined;
let signalsStopped = false;
- const recordedRequest = {
+ const recordedEnvelope = {
system: turn.systemPrompt,
- prompt: text,
tools: allowSubagents ? ["Agent"] : [],
allowedTools: [...(allowSubagents ? ["Agent"] : []), ...bridgedNames],
childAgents: allowSubagents ? childAgents : {},
@@ -557,7 +556,7 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
turnSeq: userEntry.seq,
step,
model,
- request: step === 0 ? recordedRequest : { prompt: steerPrompts[step - 1] ?? "[steer]" },
+ promptEnvelope: recordedEnvelope,
truncated: false,
transport: { modelId: model },
ttftMs: message.subtype === "success" ? (message.ttft_ms ?? null) : null,
@@ -803,7 +802,7 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
turnSeq: userEntry.seq,
step: 0,
model,
- request: recordedRequest,
+ promptEnvelope: recordedEnvelope,
truncated: false,
transport: { modelId: model },
});
diff --git a/src/harness/codex-harness.ts b/src/harness/codex-harness.ts
index ba59ded20..98e041d33 100644
--- a/src/harness/codex-harness.ts
+++ b/src/harness/codex-harness.ts
@@ -250,14 +250,6 @@ function userInput(text: string): Record<string, unknown> {
return { type: "text", text, text_elements: [] };
}
-export function stripCodexImageBytes(items: readonly Record<string, unknown>[]): Record<string, unknown>[] {
- return items.map((item) =>
- item.type === "image" && typeof item.url === "string" && item.url.startsWith("data:")
- ? { ...item, url: "[image bytes omitted]" }
- : { ...item },
- );
-}
-
export function codexReplayCallId(id: string): string {
return id.length <= 64 ? id : createHash("sha256").update(id).digest("hex");
}
@@ -709,13 +701,11 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {
stopped: false,
};
active.set(threadId, state);
- const requestPayload = {
+ const promptEnvelope = {
threadStart: {
...threadStartRequest,
cwd: "[ephemeral control jail]",
},
- replay,
- input: stripCodexImageBytes(input),
};
const startedAt = Date.now();
const recordRequest = async (): Promise<void> => {
@@ -725,7 +715,7 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {
turnSeq: userEntry.seq,
step: 0,
model: selectedModel,
- request: requestPayload,
+ promptEnvelope,
truncated: Boolean(turn.images?.length),
transport: { modelId: selectedModel },
ttftMs: state.firstOutputAt ? state.firstOutputAt - startedAt : null,
diff --git a/src/harness/harness.ts b/src/harness/harness.ts
index 970642a81..77940e80a 100644
--- a/src/harness/harness.ts
+++ b/src/harness/harness.ts
@@ -19,11 +19,16 @@ interface HarnessImage {
artifactId?: string;
}
+export function envelopeWithoutMessages(payload: unknown): unknown {
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return payload;
+ return Object.fromEntries(Object.entries(payload as Record<string, unknown>).filter(([k]) => k !== "messages"));
+}
+
export interface HarnessLlmRequestRecord {
turnSeq: number | null;
step: number;
model: string;
- request: unknown;
+ promptEnvelope?: unknown;
truncated: boolean;
transport?: LlmTransportMeta | null;
ttftMs?: number | null;
diff --git a/src/harness/mock-harness.ts b/src/harness/mock-harness.ts
index 73718230a..46b913595 100644
--- a/src/harness/mock-harness.ts
+++ b/src/harness/mock-harness.ts
@@ -119,7 +119,7 @@ export function createMockHarness(): Harness {
turnSeq: userEntry.seq,
step: 0,
model: "mock",
- request: {
+ promptEnvelope: {
model: "mock",
system: turn.systemPrompt,
messages: [...mockProviderMessages(turn.history), { role: "user", content: modelPrompt }],
@@ -638,7 +638,7 @@ export function createMockHarness(): Harness {
turnSeq: userEntry.seq,
step: 1,
model: "mock",
- request: {
+ promptEnvelope: {
model: "mock",
system: turn.systemPrompt,
messages: [...mockProviderMessages(turn.history), { role: "user", content: modelPrompt }],
@@ -747,7 +747,7 @@ export function createMockHarness(): Harness {
turnSeq: null,
step: -1,
model,
- request: { system: SECURITY_SCREEN_SYSTEM_PROMPT, messages: [{ role: "user", content: payload }] },
+ promptEnvelope: { system: SECURITY_SCREEN_SYSTEM_PROMPT, messages: [{ role: "user", content: payload }] },
truncated: false,
});
if (/!security-screen-hang/i.test(payload)) {
diff --git a/src/harness/opencode-harness.ts b/src/harness/opencode-harness.ts
index 8ba72c48f..9f81d1941 100644
--- a/src/harness/opencode-harness.ts
+++ b/src/harness/opencode-harness.ts
@@ -18,7 +18,13 @@ import type { TaskStore } from "../tasks/task-store.ts";
import { errMessage, swallow } from "../util/errors.ts";
import { sleep } from "../util/async.ts";
import { NonRetryableTurnError } from "../core/turn-error.ts";
-import { defineHarness, type Harness, type HarnessTurnInput, type HarnessTurnResult } from "./harness.ts";
+import {
+ defineHarness,
+ envelopeWithoutMessages,
+ type Harness,
+ type HarnessTurnInput,
+ type HarnessTurnResult,
+} from "./harness.ts";
import { coreToolOptions, createPiTools, type PiToolsOptions, type ToolContextRef } from "./pi-tools.ts";
import { reconstructMessagesFromHistory } from "./replay.ts";
import { parseSecurityScreenVerdict, SECURITY_SCREEN_SYSTEM_PROMPT } from "../security/security-posture.ts";
@@ -962,7 +968,7 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes
turnSeq: state.userSeq,
step: capture.step,
model: capture.model,
- request: capture.request,
+ promptEnvelope: envelopeWithoutMessages(capture.request),
truncated: false,
transport: info?.providerID && info.modelID ? { modelId: `${info.providerID}/${info.modelID}` } : null,
ttftMs: null,
diff --git a/src/harness/pi-harness.ts b/src/harness/pi-harness.ts
index 288a50e2d..4b7944554 100644
--- a/src/harness/pi-harness.ts
+++ b/src/harness/pi-harness.ts
@@ -52,6 +52,7 @@ import {
import { customModelsJson, customProvidersVersion } from "../model/custom-providers.ts";
import {
defineHarness,
+ envelopeWithoutMessages,
type Harness,
type HarnessCompactInput,
type HarnessDetectInput,
@@ -769,28 +770,28 @@ export function transportFromModel(model: unknown): LlmTransportMeta | undefined
export function sanitizeLlmPayload(
payload: unknown,
model?: unknown,
-): { request: unknown; truncated: boolean; transport?: LlmTransportMeta } {
+): { envelope: unknown; truncated: boolean; transport?: LlmTransportMeta } {
const transport = transportFromModel(model);
- const withTransport = (r: { request: unknown; truncated: boolean }) => (transport ? { ...r, transport } : r);
+ const withTransport = (r: { envelope: unknown; truncated: boolean }) => (transport ? { ...r, transport } : r);
let redacted: unknown;
try {
- redacted = redactImageBytes(payload);
+ redacted = redactImageBytes(envelopeWithoutMessages(payload));
} catch {
- return withTransport({ request: { note: "payload not capturable" }, truncated: true });
+ return withTransport({ envelope: { note: "payload not capturable" }, truncated: true });
}
let json: string;
try {
json = JSON.stringify(redacted);
} catch {
- return withTransport({ request: { note: "payload not serializable" }, truncated: true });
+ return withTransport({ envelope: { note: "payload not serializable" }, truncated: true });
}
if (json.length > MAX_CAPTURED_PAYLOAD_CHARS) {
return withTransport({
- request: { truncated: true, bytes: json.length, preview: json.slice(0, MAX_CAPTURED_PAYLOAD_CHARS) },
+ envelope: { truncated: true, bytes: json.length, preview: json.slice(0, MAX_CAPTURED_PAYLOAD_CHARS) },
truncated: true,
});
}
- return withTransport({ request: redacted, truncated: false });
+ return withTransport({ envelope: redacted, truncated: false });
}
export function thinkingBlocksFromContent(
@@ -1685,7 +1686,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
turnSeq: userEntry.seq,
step,
model: captured[step]!.transport?.modelId ?? effectiveModel,
- request: captured[step]!.request,
+ promptEnvelope: captured[step]!.envelope,
truncated: captured[step]!.truncated,
transport: captured[step]!.transport ?? null,
ttftMs: stat?.ttftMs ?? null,
@@ -2019,7 +2020,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
turnSeq: null,
step: -1,
model: modelId,
- request: { system: SECURITY_SCREEN_SYSTEM_PROMPT, messages: [{ role: "user", content: payload }] },
+ promptEnvelope: { system: SECURITY_SCREEN_SYSTEM_PROMPT, messages: [{ role: "user", content: payload }] },
truncated: false,
});
return parseSecurityScreenVerdict(
diff --git a/src/harness/pi-tools.ts b/src/harness/pi-tools.ts
index 520213d5a..2ebaec991 100644
--- a/src/harness/pi-tools.ts
+++ b/src/harness/pi-tools.ts
@@ -43,7 +43,7 @@ export interface ToolContextRef {
orgScopeId?: ScopeId;
tapeResultScopes?: Map<string, ScopeId>;
llmCapture?: Array<{
- request: unknown;
+ envelope: unknown;
truncated: boolean;
transport?: { modelId?: string; headers?: Record<string, string> };
}>;
diff --git a/src/sessions/memory-session-store.ts b/src/sessions/memory-session-store.ts
index 8869b5c68..b8ae7a1f8 100644
--- a/src/sessions/memory-session-store.ts
+++ b/src/sessions/memory-session-store.ts
@@ -22,6 +22,7 @@ import type {
import {
cronIdOf,
isOverheardEntry,
+ promptEnvelopeBody,
sessionBucket,
sessionCategory,
sessionOrigin,
@@ -41,6 +42,7 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStore
const entries = new Map<string, SessionEntry[]>();
const tape = new Map<string, TapeRecord[]>();
const llmRequests = new Map<string, LlmRequestRecord[]>();
+ const promptEnvelopes = new Map<string, string>();
const byThread = new Map<string, string>();
const participants = new Map<string, Set<string>>();
const windows = new Map<
@@ -222,6 +224,8 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStore
},
async recordLlmRequest(sessionId, rec: NewLlmRequest) {
+ const envelope = promptEnvelopeBody(rec.promptEnvelope);
+ if (envelope && !promptEnvelopes.has(envelope.hash)) promptEnvelopes.set(envelope.hash, envelope.body);
const full: LlmRequestRecord = {
id: randomUUID(),
sessionId,
@@ -230,7 +234,8 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStore
model: rec.model,
scopeLabel: rec.scopeLabel as ScopeId,
createdAt: now(),
- request: rec.request,
+ request: null,
+ promptHash: envelope?.hash ?? null,
truncated: rec.truncated ?? false,
ttftMs: rec.ttftMs ?? null,
durationMs: rec.durationMs ?? null,
@@ -246,7 +251,7 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStore
llmRequests.set(sessionId, arr);
}
arr.push(full);
- return full;
+ return rec.promptEnvelope !== undefined ? { ...full, promptEnvelope: rec.promptEnvelope } : full;
},
async listLlmRequests(sessionId, opts) {
@@ -259,7 +264,11 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStore
(want != null && r.turnSeq !== null && want.has(r.turnSeq)) || (!!opts?.orphans && r.turnSeq === null),
)
: all;
- return filtered.map((r) => (opts?.omitRequest ? { ...r, request: null } : { ...r }));
+ return filtered.map((r) => {
+ if (opts?.omitRequest) return { ...r, request: null };
+ const body = r.promptHash != null ? promptEnvelopes.get(r.promptHash) : undefined;
+ return body !== undefined ? { ...r, promptEnvelope: JSON.parse(body) } : { ...r };
+ });
},
async addParticipant(sessionId, principalId, title, opts) {
diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.ts
index a6917cfbd..4d09f340c 100644
--- a/src/sessions/postgres-session-store.ts
+++ b/src/sessions/postgres-session-store.ts
@@ -30,6 +30,7 @@ import {
LEGACY_CRON_ID_PATTERN,
legacyOriginPattern,
ORIGIN_ALTERNATION,
+ promptEnvelopeBody,
sessionOrigin,
STABLE_CRON_ID_PATTERN,
stableOriginPattern,
@@ -79,6 +80,8 @@ function rowToLlmRequest(r: Record<string, unknown>): LlmRequestRecord {
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),
ttftMs: r.ttft_ms == null ? null : Number(r.ttft_ms),
durationMs: r.duration_ms == null ? null : Number(r.duration_ms),
@@ -243,6 +246,11 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
`ALTER TABLE session_llm_requests ADD COLUMN IF NOT EXISTS usage_json TEXT`,
`ALTER TABLE session_llm_requests ADD COLUMN IF NOT EXISTS transport_json TEXT`,
`ALTER TABLE session_llm_requests ADD COLUMN IF NOT EXISTS gap_phases_json TEXT`,
+ `ALTER TABLE session_llm_requests ALTER COLUMN request DROP NOT NULL`,
+ `ALTER TABLE session_llm_requests ADD COLUMN IF NOT EXISTS prompt_hash TEXT`,
+ `CREATE TABLE IF NOT EXISTS llm_prompt_envelopes(
+ hash TEXT PRIMARY KEY, body TEXT NOT NULL, created_at BIGINT NOT NULL
+ )`,
`CREATE INDEX IF NOT EXISTS sessions_by_scope ON sessions(scope_id, created_at DESC)`,
`CREATE INDEX IF NOT EXISTS sessions_by_activity ON sessions((COALESCE(last_activity, created_at)) DESC, id DESC)`,
`CREATE INDEX IF NOT EXISTS sessions_by_scope_activity
@@ -507,6 +515,14 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
},
async recordLlmRequest(sessionId, rec: NewLlmRequest): Promise<LlmRequestRecord> {
+ const 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", [
+ envelope.hash,
+ envelope.body,
+ now(),
+ ]);
+ }
const full: LlmRequestRecord = {
id: randomUUID(),
sessionId,
@@ -515,7 +531,9 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
model: rec.model,
scopeLabel: rec.scopeLabel as ScopeId,
createdAt: now(),
- request: rec.request,
+ request: null,
+ promptHash: envelope?.hash ?? null,
+ ...(rec.promptEnvelope !== undefined ? { promptEnvelope: rec.promptEnvelope } : {}),
truncated: rec.truncated ?? false,
ttftMs: rec.ttftMs ?? null,
durationMs: rec.durationMs ?? null,
@@ -526,7 +544,7 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
transport: rec.transport ?? null,
};
await q(
- "INSERT INTO session_llm_requests(id, session_id, turn_seq, step, model, scope_label, request, truncated, created_at, ttft_ms, duration_ms, step_gap_ms, tool_wall_json, usage_json, transport_json, gap_phases_json) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)",
+ "INSERT INTO session_llm_requests(id, session_id, turn_seq, step, model, scope_label, prompt_hash, truncated, created_at, ttft_ms, duration_ms, step_gap_ms, tool_wall_json, usage_json, transport_json, gap_phases_json) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)",
[
full.id,
full.sessionId,
@@ -534,7 +552,7 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
full.step,
full.model,
full.scopeLabel,
- JSON.stringify(full.request ?? null),
+ full.promptHash,
full.truncated,
full.createdAt,
full.ttftMs,
@@ -551,21 +569,26 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
async listLlmRequests(sessionId, opts): Promise<LlmRequestRecord[]> {
const cols = opts?.omitRequest
- ? "id, session_id, turn_seq, step, model, scope_label, created_at, truncated, ttft_ms, duration_ms, step_gap_ms, tool_wall_json, usage_json, transport_json, gap_phases_json"
- : "*";
- const conds = ["session_id = $1"];
+ ? "r.id, r.session_id, r.turn_seq, r.step, r.model, r.scope_label, r.created_at, r.truncated, r.prompt_hash, r.ttft_ms, r.duration_ms, r.step_gap_ms, r.tool_wall_json, r.usage_json, r.transport_json, r.gap_phases_json"
+ : "r.*, e.body AS prompt_body";
+ const from = opts?.omitRequest
+ ? "session_llm_requests r"
+ : "session_llm_requests r LEFT JOIN llm_prompt_envelopes e ON e.hash = r.prompt_hash";
+ const conds = ["r.session_id = $1"];
const args: unknown[] = [sessionId];
const turnSeqs = opts?.turnSeqs;
if (turnSeqs) {
args.push(turnSeqs);
conds.push(
- opts?.orphans ? `(turn_seq = ANY($${args.length}) OR turn_seq IS NULL)` : `turn_seq = ANY($${args.length})`,
+ opts?.orphans
+ ? `(r.turn_seq = ANY($${args.length}) OR r.turn_seq IS NULL)`
+ : `r.turn_seq = ANY($${args.length})`,
);
} else if (opts?.orphans) {
- conds.push("turn_seq IS NULL");
+ conds.push("r.turn_seq IS NULL");
}
const rows = await q(
- `SELECT ${cols} FROM session_llm_requests WHERE ${conds.join(" AND ")} ORDER BY created_at ASC, step ASC`,
+ `SELECT ${cols} FROM ${from} WHERE ${conds.join(" AND ")} ORDER BY r.created_at ASC, r.step ASC`,
args,
);
return rows.map(rowToLlmRequest);
diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.ts
index 89bd25497..eff31acfb 100644
--- a/src/sessions/session-store.ts
+++ b/src/sessions/session-store.ts
@@ -1,5 +1,18 @@
+import { createHash } from "node:crypto";
import type { EntryType, ScopeId, Session, SessionEntry, SessionType } from "../types.ts";
+export function promptEnvelopeBody(envelope: unknown): { hash: string; body: string } | null {
+ if (envelope == null) return null;
+ let body: string;
+ try {
+ body = JSON.stringify(envelope);
+ } catch {
+ return null;
+ }
+ if (body === undefined) return null;
+ return { hash: createHash("sha256").update(body).digest("hex"), body };
+}
+
export interface Lease {
sessionId: string;
token: string;
@@ -166,6 +179,8 @@ export interface LlmRequestRecord {
scopeLabel: ScopeId;
createdAt: number;
request: unknown;
+ promptHash: string | null;
+ promptEnvelope?: unknown;
truncated: boolean;
ttftMs: number | null;
durationMs: number | null;
@@ -181,7 +196,7 @@ export interface NewLlmRequest {
step: number;
model: string;
scopeLabel: ScopeId;
- request: unknown;
+ promptEnvelope?: unknown;
truncated?: boolean;
ttftMs?: number | null;
durationMs?: number | null;
diff --git a/test/admin-observability.test.ts b/test/admin-observability.test.ts
index f8db7c4c3..2356c2471 100644
--- a/test/admin-observability.test.ts
+++ b/test/admin-observability.test.ts
@@ -183,7 +183,14 @@ test("an org admin sees EXACTLY what we sent the model per turn (captured reques
const r = await get(s.base, `/v1/admin/sessions/${encodeURIComponent(conv.id)}/llm?scope=org:default-org`);
assert.equal(r.status, 200);
const d = (await r.json()) as {
- requests: { turnSeq: number | null; step: number; model: string; truncated: boolean; request: unknown }[];
+ requests: {
+ turnSeq: number | null;
+ step: number;
+ model: string;
+ truncated: boolean;
+ request: unknown;
+ promptEnvelope?: unknown;
+ }[];
};
assert.ok(d.requests.length >= 1, "at least one captured request");
const meta = d.requests[0]!;
@@ -191,6 +198,7 @@ test("an org admin sees EXACTLY what we sent the model per turn (captured reques
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");
const tr = await get(
s.base,
`/v1/admin/sessions/${encodeURIComponent(conv.id)}/llm?turnSeq=${meta.turnSeq}&scope=org:default-org`,
@@ -199,21 +207,21 @@ test("an org admin sees EXACTLY what we sent the model per turn (captured reques
const td = (await tr.json()) as {
requests: {
turnSeq: number | null;
- request: { system?: string; messages?: { role: string; content: string }[] };
+ promptEnvelope: { system?: string; messages?: { role: string; content: string }[] };
}[];
};
assert.ok(td.requests.length >= 1, "the turn's requests");
const req = td.requests[0]!;
assert.equal(req.turnSeq, meta.turnSeq, "scoped to the requested turn");
assert.ok(
- req.request.messages?.some((m) => m.content.includes("what's the weather")),
+ req.promptEnvelope.messages?.some((m) => m.content.includes("what's the weather")),
"the snapshot carries exactly what we sent — the user message",
);
assert.ok(
- !req.request.messages?.some((m) => m.role === "soul"),
+ !req.promptEnvelope.messages?.some((m) => m.role === "soul"),
"SOUL is carried in the system prompt, not as a provider message",
);
- assert.ok(typeof req.request.system === "string", "and the system prompt we sent");
+ assert.ok(typeof req.promptEnvelope.system === "string", "and the system prompt we sent");
assert.equal(
(await get(s.base, `/v1/admin/sessions/${encodeURIComponent(conv.id)}/llm?turnSeq=nope&scope=org:default-org`))
.status,
@@ -272,7 +280,7 @@ test("recipient delivery rows expose origin provenance and gated origin context"
step: 0,
model: "mock",
scopeLabel: sourceScope,
- request: { model: "mock", messages: [{ role: "user", content: "post the digest" }] },
+ promptEnvelope: { model: "mock", messages: [{ role: "user", content: "post the digest" }] },
truncated: false,
});
await s.built.sessions.recordLlmRequest(source.id, {
@@ -280,7 +288,7 @@ test("recipient delivery rows expose origin provenance and gated origin context"
step: 1,
model: "mock",
scopeLabel: sourceScope,
- request: { model: "mock", messages: [{ role: "user", content: "(system note: resume)" }] },
+ promptEnvelope: { model: "mock", messages: [{ role: "user", content: "(system note: resume)" }] },
truncated: false,
});
@@ -331,7 +339,7 @@ test("recipient delivery rows expose origin provenance and gated origin context"
assert.equal(event.sourceSession.scopeId, sourceScope);
assert.equal(event.llmRequests.length, 2);
assert.equal(event.llmRequests[0].turnSeq, sourceUser.seq);
- assert.deepEqual(event.llmRequests[0].request.messages, [{ role: "user", content: "post the digest" }]);
+ assert.deepEqual(event.llmRequests[0].promptEnvelope.messages, [{ role: "user", content: "post the digest" }]);
assert.equal(event.llmRequests[1].turnSeq, sourceResume.seq);
const scopedRead = await get(
@@ -395,7 +403,7 @@ test("recipient delivery rows expose non-cron wake provenance without cron idemp
step: 0,
model: "mock",
scopeLabel: sourceScope,
- request: { model: "mock", messages: [{ role: "user", content: "triage the webhook" }] },
+ promptEnvelope: { model: "mock", messages: [{ role: "user", content: "triage the webhook" }] },
truncated: false,
});
@@ -637,7 +645,7 @@ test("principal deliveries render as delivery events and later DM turns get stru
assert.equal((await s.built.app.turn(turn)).status, "ok");
const reqs = await s.built.sessions.listLlmRequests(session!.id);
const latest = reqs[reqs.length - 1] as any;
- const userMessage = latest.request.messages.at(-1).content;
+ const userMessage = latest.promptEnvelope.messages.at(-1).content;
assert.match(userMessage, /Recent agent-initiated deliveries to this conversation/);
assert.match(userMessage, /the deploy is done/);
} finally {
@@ -672,7 +680,7 @@ test("monitor delivery origin context is scope-gated in admin", async () => {
step: 0,
model: "mock",
scopeLabel: "personal:U-carol",
- request: { model: "mock", messages: [{ role: "user", content: "monitor wake" }] },
+ promptEnvelope: { model: "mock", messages: [{ role: "user", content: "monitor wake" }] },
truncated: false,
});
const delivery = await s.built.deliveries.enqueue({
diff --git a/test/claude-harness-turn.test.ts b/test/claude-harness-turn.test.ts
index 5b5f4654f..1a05ce2d4 100644
--- a/test/claude-harness-turn.test.ts
+++ b/test/claude-harness-turn.test.ts
@@ -244,7 +244,11 @@ test("each steered prompt gets its own LLM request record", async () => {
[0, 1],
);
assert.equal(llmRequests[1]!.truncated, false);
- assert.deepEqual(llmRequests[1]!.request, { prompt: "and another thing" });
+ assert.equal(
+ (llmRequests[1]!.promptEnvelope as { system: string }).system,
+ "be brief",
+ "steer steps reuse the turn's envelope — the steer text itself lives on the tape",
+ );
assert.equal(llmRequests[0]!.usage?.costUsd, 0.1);
assert.ok(Math.abs((llmRequests[1]!.usage?.costUsd ?? 0) - 0.2) < 1e-9);
});
@@ -268,7 +272,7 @@ test("a turn that dies before its first result still records exactly one request
assert.equal(llmRequests.length, 1);
assert.equal(llmRequests[0]!.step, 0);
assert.equal(llmRequests[0]!.truncated, false);
- assert.equal((llmRequests[0]!.request as { system: string }).system, "be brief");
+ assert.equal((llmRequests[0]!.promptEnvelope as { system: string }).system, "be brief");
});
test("the claude harness offers compaction and detection so a utility role cannot silently disable them", async () => {
diff --git a/test/codex-harness.test.ts b/test/codex-harness.test.ts
index 168d858c6..df8bac256 100644
--- a/test/codex-harness.test.ts
+++ b/test/codex-harness.test.ts
@@ -18,7 +18,6 @@ import {
codexTurnInputText,
createCodexHarness,
prepareCodexHome,
- stripCodexImageBytes,
} from "../src/harness/codex-harness.ts";
import type { HarnessLlmRequestRecord, HarnessTurnInput } from "../src/harness/harness.ts";
import { NonRetryableTurnError } from "../src/core/turn-error.ts";
@@ -312,19 +311,6 @@ test("Codex children cannot use parent surface, control, or terminal tools", ()
}
});
-test("Codex observability preserves image presence without persisting bytes", () => {
- assert.deepEqual(
- stripCodexImageBytes([
- { type: "text", text: "hello" },
- { type: "image", url: "data:image/png;base64,SECRET" },
- ]),
- [
- { type: "text", text: "hello" },
- { type: "image", url: "[image bytes omitted]" },
- ],
- );
-});
-
test("Codex interrupts the provider after a terminal QM tool", async (t) => {
const dir = mkdtempSync(join(tmpdir(), "qm-codex-stop-test-"));
const harness = createCodexHarness({
diff --git a/test/opencode-harness.test.ts b/test/opencode-harness.test.ts
index 3072fa5aa..091039139 100644
--- a/test/opencode-harness.test.ts
+++ b/test/opencode-harness.test.ts
@@ -139,7 +139,7 @@ test("OpenCode records real usage, cost, and timings for each captured model cal
assert.equal(row.step, 0);
assert.equal(row.model, "openai/gpt-5");
assert.equal(row.truncated, false);
- assert.deepEqual(row.request, { system: "s", messages: [{ role: "user" }] });
+ assert.deepEqual(row.promptEnvelope, { system: "s" }, "messages stay on the tape, not in the envelope");
assert.deepEqual(row.transport, { modelId: "openai/gpt-5" });
assert.equal(row.durationMs, 1929);
assert.deepEqual(row.usage, {
diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.ts
index 99ae8b95c..4cc98a6b7 100644
--- a/test/orchestrator.test.ts
+++ b/test/orchestrator.test.ts
@@ -110,9 +110,9 @@ test("inbound file problems ride a durable file_event entry — off the reply an
);
assert.match(payload.text, /screenshot\.png/);
- const reqs = (await sessions.listLlmRequests(res.sessionId!)) as Array<{ model: string; request: unknown }>;
+ const reqs = (await sessions.listLlmRequests(res.sessionId!)) as Array<{ model: string; promptEnvelope: unknown }>;
for (const r of reqs.filter((request) => request.model !== "mock-security")) {
- assert.doesNotMatch(JSON.stringify(r.request), /too many files|screenshot\.png/);
+ assert.doesNotMatch(JSON.stringify(r.promptEnvelope), /too many files|screenshot\.png/);
}
assert.equal((res as { fileNotes?: unknown }).fileNotes, undefined);
@@ -170,7 +170,7 @@ test("a 1:1 names the authenticated human in the prompt so the agent never asks
const res = await app.turn(dm("hi", { actor: { externalId: "[email protected]", displayName: "Ada Lovelace" } }));
assert.equal(res.status, "ok", res.reason);
const sys = (await sessions.listLlmRequests(res.sessionId!)).at(-1)! as any;
- assert.match(sys.request.system, /live, private 1:1 with Ada Lovelace \(ada@acme\.com\)/);
+ assert.match(sys.promptEnvelope.system, /live, private 1:1 with Ada Lovelace \(ada@acme\.com\)/);
});
test("a channel turn gets no 1:1 identity block", async () => {
@@ -178,7 +178,7 @@ test("a channel turn gets no 1:1 identity block", async () => {
const res = await app.turn(channel("hi", { actor: { externalId: "U1", displayName: "Ada" } }));
assert.equal(res.status, "ok", res.reason);
const sys = (await sessions.listLlmRequests(res.sessionId!)).at(-1)! as any;
- assert.doesNotMatch(sys.request.system, /## Who you're talking to/);
+ assert.doesNotMatch(sys.promptEnvelope.system, /## Who you're talking to/);
});
test("a silent cron source run stays out of normal human chat history", async () => {
@@ -259,8 +259,8 @@ test("a cron-delivered digest lands as a delivery event with origin, not recipie
});
const reqs = await built.sessions.listLlmRequests(recipient!.id);
const latest = reqs.at(-1) as any;
- assert.match(latest.request.messages.at(-1).content, /Recent agent-initiated deliveries to this conversation/);
- assert.match(latest.request.messages.at(-1).content, /deploy digest ready/);
+ assert.match(latest.promptEnvelope.messages.at(-1).content, /Recent agent-initiated deliveries to this conversation/);
+ assert.match(latest.promptEnvelope.messages.at(-1).content, /deploy digest ready/);
});
test("a setup-phase failure after the lease is acquired does NOT wedge the thread (lease released)", async () => {
@@ -2014,8 +2014,8 @@ test("Auto screens only the external event envelope and records classifier usage
(rec) => rec.model === "mock-security",
);
assert.ok(classifier, "the security classifier request is persisted beside the turn");
- assert.match(JSON.stringify(classifier.request), /customer asked for a refund/);
- assert.doesNotMatch(JSON.stringify(classifier.request), /provenance-ok/);
+ assert.match(JSON.stringify(classifier.promptEnvelope), /customer asked for a refund/);
+ assert.doesNotMatch(JSON.stringify(classifier.promptEnvelope), /provenance-ok/);
assert.ok(built.modelGateway.audit().some((rec) => rec.model === "mock-security"));
});
@@ -2110,7 +2110,7 @@ test("Auto fails open on vision attachments it cannot screen, flagging them unsc
const main = [...(await built.sessions.listLlmRequests(result.sessionId!))]
.reverse()
.find((rec) => rec.model !== "mock-security");
- assert.match(JSON.stringify(main?.request), /NOT security-screened/);
+ assert.match(JSON.stringify(main?.promptEnvelope), /NOT security-screened/);
});
test("Auto screens text attachment contents (strict quarantines) and fails open on unreadable binary files", async () => {
@@ -2137,7 +2137,7 @@ test("Auto screens text attachment contents (strict quarantines) and fails open
const classifier = (await benign.sessions.listLlmRequests(allowed.sessionId!)).find(
(rec) => rec.model === "mock-security",
);
- assert.match(JSON.stringify(classifier?.request), /quarterly revenue is 42/);
+ assert.match(JSON.stringify(classifier?.promptEnvelope), /quarterly revenue is 42/);
const binary = freshApp();
const pdf = await binary.blobTransfer.put(Buffer.from("%PDF synthetic"));
@@ -2213,8 +2213,8 @@ test("Auto does not let one quarantined thread file poison later attachments", a
const classifier = (await built.sessions.listLlmRequests(allowed.sessionId!))
.filter((rec) => rec.model === "mock-security")
.at(-1);
- assert.match(JSON.stringify(classifier?.request), /quarterly revenue is 42/);
- assert.doesNotMatch(JSON.stringify(classifier?.request), /ignore previous instructions/);
+ assert.match(JSON.stringify(classifier?.promptEnvelope), /quarterly revenue is 42/);
+ assert.doesNotMatch(JSON.stringify(classifier?.promptEnvelope), /ignore previous instructions/);
});
test("an approved automation replay preserves and re-screens its external event provenance", async () => {
@@ -2250,7 +2250,7 @@ test("an approved automation replay preserves and re-screens its external event
(rec) => rec.model === "mock-security",
);
assert.equal(screens.length, 2);
- assert.ok(screens.every((rec) => JSON.stringify(rec.request).includes("benign external marker")));
+ assert.ok(screens.every((rec) => JSON.stringify(rec.promptEnvelope).includes("benign external marker")));
});
test("Auto fails open on data-bearing turns when the security screen is unavailable", async () => {
@@ -2270,7 +2270,7 @@ test("Auto fails open on data-bearing turns when the security screen is unavaila
const main = [...(await built.sessions.listLlmRequests(result.sessionId!))]
.reverse()
.find((rec) => rec.model !== "mock-security");
- assert.match(JSON.stringify(main?.request), /NOT security-screened/);
+ assert.match(JSON.stringify(main?.promptEnvelope), /NOT security-screened/);
});
test("Auto retries a transient screen failure instead of quarantining", async () => {
@@ -2373,7 +2373,7 @@ test("Auto fails open when bounded screening omits oversize content, flagging it
const main = [...(await built.sessions.listLlmRequests(result.sessionId!))]
.reverse()
.find((rec) => rec.model !== "mock-security");
- assert.match(JSON.stringify(main?.request), /NOT security-screened/);
+ assert.match(JSON.stringify(main?.promptEnvelope), /NOT security-screened/);
});
test("an Auto-downgraded turn is quarantined from later full-authority model history", async () => {
@@ -2398,7 +2398,7 @@ test("an Auto-downgraded turn is quarantined from later full-authority model his
const requests = await built.sessions.listLlmRequests(second.sessionId!);
const latestMain = [...requests].reverse().find((rec) => rec.model !== "mock-security");
assert.ok(latestMain);
- assert.doesNotMatch(JSON.stringify(latestMain.request), /durable history/);
+ assert.doesNotMatch(JSON.stringify(latestMain.promptEnvelope), /durable history/);
});
test("Auto records quarantined overheard timestamps so they cannot poison every later mention", async () => {
diff --git a/test/pi-harness-oneshot.test.ts b/test/pi-harness-oneshot.test.ts
index ec6c8dc72..cb8e28635 100644
--- a/test/pi-harness-oneshot.test.ts
+++ b/test/pi-harness-oneshot.test.ts
@@ -399,33 +399,21 @@ test("turn-detection prompt treats implied assistant-target follow-ups as addres
assert.match(prompt, /<@U123> what do you mean by that\?[^]*NO/);
});
-test("sanitizeLlmPayload elides thinking signatures while keeping thinking text and redacting images", () => {
- const signature = "EsMM".repeat(2000);
- const imageBytes = "AAAA".repeat(1000);
+test("sanitizeLlmPayload captures the prompt envelope and drops the message array", () => {
const payload = {
model: "claude-opus-4-8",
- messages: [
- {
- role: "assistant",
- content: [
- { type: "thinking", thinking: "Let me reason about this.", signature },
- { type: "image", source: { type: "base64", media_type: "image/png", data: imageBytes } },
- ],
- },
- ],
+ system: [{ type: "text", text: "be helpful" }],
+ tools: [{ name: "execute" }],
+ messages: [{ role: "user", content: [{ type: "text", text: "hi" }] }],
};
- const { request, truncated } = sanitizeLlmPayload(payload);
+ const { envelope, truncated } = sanitizeLlmPayload(payload);
assert.equal(truncated, false);
-
- const content = (request as any).messages[0].content;
- const [thinkingBlock, imageBlock] = content;
-
- assert.equal(thinkingBlock.thinking, "Let me reason about this.", "thinking text is preserved");
- assert.equal(thinkingBlock.signature, `<signature ${signature.length} chars omitted>`);
- assert.doesNotMatch(thinkingBlock.signature, /EsMM/, "raw signature bytes are gone");
-
- assert.match(imageBlock.source.data, /<base64 image\/png omitted: \d+ chars>/, "sibling image still redacted");
+ assert.deepEqual(envelope, {
+ model: "claude-opus-4-8",
+ system: [{ type: "text", text: "be helpful" }],
+ tools: [{ name: "execute" }],
+ });
});
const imageBlock = (data: string) => ({ type: "image", source: { type: "base64", media_type: "image/png", data } });
@@ -533,16 +521,16 @@ test("sanitizeLlmPayload attaches transport from the model arg alongside the red
assert.equal(sanitizeLlmPayload({ messages: [] }).transport, undefined);
});
-test("sanitizeLlmPayload elides redacted_thinking data", () => {
- const data = "redacted".repeat(500);
+test("sanitizeLlmPayload redacts image bytes that appear outside the message array", () => {
+ const big = "AAAA".repeat(2000);
const payload = {
- messages: [{ role: "assistant", content: [{ type: "redacted_thinking", data }] }],
+ system: [{ type: "image", source: { type: "base64", media_type: "image/png", data: big } }],
+ messages: [],
};
- const { request } = sanitizeLlmPayload(payload);
- const block = (request as any).messages[0].content[0];
- assert.equal(block.data, `<redacted_thinking ${data.length} chars omitted>`);
- assert.doesNotMatch(block.data, /redactedredacted/, "raw redacted_thinking bytes are gone");
+ const { envelope } = sanitizeLlmPayload(payload);
+ const block = (envelope as any).system[0];
+ assert.match(block.source.data, /<base64 image\/png omitted: \d+ chars>/, "image bytes never persist");
});
test("renderDetectPrompt uses prior assistant replies, not assembled prior user prompts", () => {
diff --git a/test/postgres-store.test.ts b/test/postgres-store.test.ts
index 11dd772b9..e45a51ed1 100644
--- a/test/postgres-store.test.ts
+++ b/test/postgres-store.test.ts
@@ -66,14 +66,14 @@ test("pg session store: one-per-thread, TTL/fenced lease, monotonic log, visibil
step: 0,
model: "claude-x",
scopeLabel: scope,
- request: { messages: [] },
+ promptEnvelope: { system: "sys" },
});
await s.recordLlmRequest(a.id, {
turnSeq: 0,
step: 1,
model: "claude-x",
scopeLabel: scope,
- request: { messages: [] },
+ promptEnvelope: { system: "sys" },
truncated: true,
ttftMs: 1200,
durationMs: 8400,
@@ -102,7 +102,7 @@ test("pg session store: one-per-thread, TTL/fenced lease, monotonic log, visibil
step: 0,
model: "claude-x",
scopeLabel: scope,
- request: { messages: [] },
+ promptEnvelope: { system: "sys" },
});
assert.deepEqual(
(await s.listLlmRequests(a.id, { orphans: true })).map((r) => r.turnSeq),
@@ -270,7 +270,7 @@ test("pg deleteSession: hard-removes the session and its rows, leaves others", {
step: 0,
model: "claude-x",
scopeLabel: scope,
- request: { messages: [] },
+ promptEnvelope: { system: "sys" },
});
await s.deleteSession(a.id);
diff --git a/test/projects.test.ts b/test/projects.test.ts
index 5f394ba17..800ca2cdd 100644
--- a/test/projects.test.ts
+++ b/test/projects.test.ts
@@ -362,8 +362,8 @@ test("Project routes use ordinary group sessions with the durable roster as auth
assert.equal((await turn("owner", "web:owner:first", "after joining")).status, "ok");
assert.ok((await built.app.listSessions("member")).some((session) => session.id === first.id));
const latestRequest = (await built.sessions.listLlmRequests(first.id)).at(-1)!;
- assert.match(JSON.stringify(latestRequest.request), /secret-before-join/);
- assert.match(JSON.stringify(latestRequest.request), /after joining/);
+ assert.match(JSON.stringify(latestRequest.promptEnvelope), /secret-before-join/);
+ assert.match(JSON.stringify(latestRequest.promptEnvelope), /after joining/);
const sharedApproval = await turn("owner", "web:owner:shared-approval", "!run git push --force origin main");
assert.equal(sharedApproval.status, "pending_approval");
@@ -445,7 +445,7 @@ test("Project routes use ordinary group sessions with the durable roster as auth
assert.equal((await built.app.removeProjectMember(project.id, "owner", "outsider")).status, "ok");
assert.equal((await turn("owner", racingFork.session.threadRef, "continue the fork")).status, "ok");
const continuedForkRequest = (await built.sessions.listLlmRequests(racingFork.session.id)).at(-1)!;
- assert.match(JSON.stringify(continuedForkRequest.request), /after joining/);
+ assert.match(JSON.stringify(continuedForkRequest.promptEnvelope), /after joining/);
const participantOrder: string[] = [];
const acquireLease = built.sessions.acquireLease.bind(built.sessions);
@@ -505,8 +505,8 @@ test("Project routes use ordinary group sessions with the durable roster as auth
await built.identity.reactivate("member");
assert.equal((await turn("owner", "web:owner:first", "after-reactivation")).status, "ok");
const reactivatedRequest = (await built.sessions.listLlmRequests(first.id)).at(-1)!;
- assert.doesNotMatch(JSON.stringify(reactivatedRequest.request), /inactive-gap-secret/);
- assert.match(JSON.stringify(reactivatedRequest.request), /after-reactivation/);
+ assert.doesNotMatch(JSON.stringify(reactivatedRequest.promptEnvelope), /inactive-gap-secret/);
+ assert.match(JSON.stringify(reactivatedRequest.promptEnvelope), /after-reactivation/);
await built.identity.deactivate("owner");
assert.deepEqual(await built.app.listProjects("member"), []);
assert.equal((await turn("member", "web:owner:first")).status, "refused");
@@ -686,7 +686,7 @@ test("Project turns rebuild the full thread for a member who joined later", asyn
);
const session = await built.sessions.getByThread(threadRef);
assert.ok(session);
- const request = (await built.sessions.listLlmRequests(session.id)).at(-1)!.request as {
+ const request = (await built.sessions.listLlmRequests(session.id)).at(-1)!.promptEnvelope as {
tapeMode?: string;
messages?: unknown[];
};
@@ -806,7 +806,7 @@ test("a member added to a Project inherits the chats that predate them", async (
).status,
"ok",
);
- const request = (await built.sessions.listLlmRequests(session.id)).at(-1)!.request as { messages?: unknown[] };
+ const request = (await built.sessions.listLlmRequests(session.id)).at(-1)!.promptEnvelope as { messages?: unknown[] };
assert.match(JSON.stringify(request.messages), /BEFORE_JOIN_TOPIC/, "the agent keeps the project's full history");
});
diff --git a/test/session-store.test.ts b/test/session-store.test.ts
index 38797944d..3184be696 100644
--- a/test/session-store.test.ts
+++ b/test/session-store.test.ts
@@ -426,7 +426,7 @@ for (const [name, make] of backends) {
step: 0,
model: "claude-x",
scopeLabel: s.scopeId,
- request: { system: "you are helpful", messages: [{ role: "user", content: "hi" }] },
+ promptEnvelope: { system: "you are helpful", tools: [{ name: "execute" }] },
});
assert.ok(rec.id, "stamps an id");
assert.equal(rec.truncated, false, "defaults truncated to false");
@@ -438,7 +438,6 @@ for (const [name, make] of backends) {
step: 1,
model: "claude-x",
scopeLabel: s.scopeId,
- request: { messages: [] },
truncated: true,
ttftMs: 1200,
durationMs: 8400,
@@ -455,10 +454,27 @@ 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]!.request as { messages: unknown[] }).messages,
- [{ role: "user", content: "hi" }],
- "request body round-trips",
+ list[0]!.promptEnvelope,
+ { system: "you are helpful", tools: [{ name: "execute" }] },
+ "prompt envelope round-trips via its hash",
+ );
+ assert.ok(list[0]!.promptHash, "envelope rows carry the dedup hash");
+ assert.equal(list[1]!.promptHash, null, "rows recorded without an envelope stay bare");
+ const repeat = await store.recordLlmRequest(s.id, {
+ turnSeq: 1,
+ step: 0,
+ model: "claude-x",
+ scopeLabel: s.scopeId,
+ promptEnvelope: { system: "you are helpful", tools: [{ name: "execute" }] },
+ });
+ assert.equal(repeat.promptHash, list[0]!.promptHash, "identical envelopes dedupe to one stored body");
+ const rehydrated = await store.listLlmRequests(s.id, { turnSeqs: [1] });
+ assert.deepEqual(
+ rehydrated[0]!.promptEnvelope,
+ { system: "you are helpful", tools: [{ name: "execute" }] },
+ "the deduped row still hydrates its envelope",
);
assert.equal(list[1]!.ttftMs, 1200, "per-call TTFT round-trips");
assert.equal(list[1]!.durationMs, 8400, "per-call duration round-trips");
@@ -480,7 +496,7 @@ for (const [name, make] of backends) {
test(`${name}: listLlmRequests filters by turnSeq in the store (no load-all-then-filter)`, async () => {
const store = make();
const s = await store.getOrCreateByThread("t1", "dm", scopeId("personal", "U1"));
- const base = { model: "claude-x", scopeLabel: s.scopeId, request: { messages: [] } };
+ const base = { model: "claude-x", scopeLabel: s.scopeId, promptEnvelope: { system: "sys" } };
await store.recordLlmRequest(s.id, { ...base, turnSeq: 0, step: 0 });
await store.recordLlmRequest(s.id, { ...base, turnSeq: 5, step: 0 });
await store.recordLlmRequest(s.id, { ...base, turnSeq: 5, step: 1 });
@@ -513,7 +529,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),
+ meta.every((r) => r.request === null && r.promptEnvelope === undefined),
"bodies omitted",
);
assert.ok(
diff --git a/test/surface-cache-ambient.test.ts b/test/surface-cache-ambient.test.ts
index f47b4ce28..d6b125361 100644
--- a/test/surface-cache-ambient.test.ts
+++ b/test/surface-cache-ambient.test.ts
@@ -51,8 +51,8 @@ test("ingest → ambient judge engages → spawns a smart-model worker that post
const worker = await built.sessions.getByThread(`slack:${container}:ambient:100.1`);
assert.ok(worker);
const classifier = (await built.sessions.listLlmRequests(worker!.id)).find((rec) => rec.model === "mock-security");
- assert.match(JSON.stringify(classifier?.request), /did the Q3 launch slip/);
- assert.match(JSON.stringify(classifier?.request), /ambient reply/);
+ assert.match(JSON.stringify(classifier?.promptEnvelope), /did the Q3 launch slip/);
+ assert.match(JSON.stringify(classifier?.promptEnvelope), /ambient reply/);
} finally {
await built.runtime.stop();
}
diff --git a/test/surface-spine-routing.test.ts b/test/surface-spine-routing.test.ts
index 5e47b50e0..df129c03f 100644
--- a/test/surface-spine-routing.test.ts
+++ b/test/surface-spine-routing.test.ts
@@ -316,7 +316,7 @@ test("addressed + no post but a final text reply → the reply is delivered dire
const session = await built.sessions.getByThread("ch:C-shed:710.1");
const requests = await built.sessions.listLlmRequests(session!.id);
assert.ok(
- !requests.some((r) => JSON.stringify(r.request).includes("[system] You were addressed directly")),
+ !requests.some((r) => JSON.stringify(r.promptEnvelope).includes("[system] You were addressed directly")),
"no nudge model call — the existing reply text is delivered as-is",
);
await sleep(300);
@@ -340,7 +340,7 @@ test("addressed + STILL no post after the nudge → the nudge turn's text is del
assert.ok(fallback, "the shed reply was delivered as the fallback");
assert.equal(fallback.destination.target, "slack:C-shedmute:710.3", "delivered to the addressed conversation");
const session = await built.sessions.getByThread("ch:C-shedmute:710.3");
- const nudgeRequest = (await built.sessions.listLlmRequests(session!.id)).at(-1)!.request as {
+ const nudgeRequest = (await built.sessions.listLlmRequests(session!.id)).at(-1)!.promptEnvelope as {
messages?: Array<{ role?: string; content?: string }>;
};
assert.ok(
@@ -377,7 +377,7 @@ test("reply-or-decline nudge preserves the trigger image and environment", async
await pollFor(built.deliveries, (d) => d.text.startsWith("worklog: did the thing but never posted"), 15_000),
);
const session = await built.sessions.getByThread("ch:C-nudge-image:710.2");
- const request = (await built.sessions.listLlmRequests(session!.id)).at(-1)!.request as {
+ const request = (await built.sessions.listLlmRequests(session!.id)).at(-1)!.promptEnvelope as {
messages?: Array<{ role?: string; content?: string }>;
images?: Array<{ mimeType?: string; dataBase64?: string }>;
};
@@ -413,7 +413,7 @@ test("nudge tape reread failure falls back to refreshed history, never the stale
await built.app.turn(mention("!shedmute", "C-nudge-read", "711.1"));
assert.ok(await pollFor(built.deliveries, (d) => d.text === "worklog: did the thing but never posted"));
const session = await built.sessions.getByThread("ch:C-nudge-read:711.1");
- const nudgeRequest = (await built.sessions.listLlmRequests(session!.id)).at(-1)!.request as {
+ const nudgeRequest = (await built.sessions.listLlmRequests(session!.id)).at(-1)!.promptEnvelope as {
messages?: Array<{ role?: string; content?: string }>;
};
assert.ok(