@vellumai/assistant 0.10.7-dev.202607100720.fba456e → 0.10.7-dev.202607101106.c87f4e3
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.
- package/openapi.yaml +0 -4
- package/package.json +1 -1
- package/src/__tests__/compaction-trail-store.test.ts +2 -1
- package/src/__tests__/conversation-app-control-instantiation.test.ts +20 -3
- package/src/__tests__/conversation-runtime-assembly.test.ts +2 -0
- package/src/__tests__/conversation-skill-tools.test.ts +31 -6
- package/src/__tests__/list-messages-queued.test.ts +9 -3
- package/src/__tests__/llm-request-log-agent-loop-exit-reason.test.ts +9 -9
- package/src/__tests__/llm-request-log-call-site.test.ts +5 -5
- package/src/__tests__/llm-request-log-disabled-writes.test.ts +91 -0
- package/src/__tests__/media-generate-image.test.ts +20 -7
- package/src/__tests__/platform-bash-auto-approve.test.ts +19 -2
- package/src/__tests__/registry.test.ts +18 -0
- package/src/__tests__/require-fresh-approval.test.ts +15 -0
- package/src/__tests__/skill-projection-feature-flag.test.ts +35 -8
- package/src/__tests__/skill-projection.benchmark.test.ts +7 -2
- package/src/__tests__/subagent-detail.test.ts +1 -0
- package/src/__tests__/summarize-boundary.test.ts +1 -0
- package/src/__tests__/tool-approval-handler.test.ts +1 -0
- package/src/__tests__/tool-execution-pipeline.benchmark.test.ts +1 -0
- package/src/__tests__/tool-executor-lifecycle-events.test.ts +21 -17
- package/src/__tests__/tool-executor.test.ts +36 -18
- package/src/__tests__/tool-grant-request-escalation.test.ts +1 -0
- package/src/__tests__/trusted-contact-inline-approval-integration.test.ts +1 -0
- package/src/__tests__/verification-control-plane-policy.test.ts +13 -0
- package/src/api/responses/conversation-message.ts +0 -15
- package/src/config/schemas/__tests__/llm-request-logs.test.ts +33 -5
- package/src/config/schemas/llm-request-logs.ts +78 -27
- package/src/daemon/conversation-skill-tools.ts +27 -9
- package/src/export/__tests__/transcript-formatter.test.ts +5 -0
- package/src/permissions/checker.test.ts +3 -6
- package/src/permissions/checker.ts +2 -2
- package/src/persistence/__tests__/message-content-file.test.ts +150 -0
- package/src/persistence/__tests__/slow-query-log.test.ts +125 -0
- package/src/persistence/conversation-crud.ts +11 -1
- package/src/persistence/llm-request-log-store.ts +36 -2
- package/src/persistence/message-content-file.ts +190 -0
- package/src/persistence/migrations/324-message-finalized-column.ts +26 -0
- package/src/persistence/migrations/__tests__/297-move-llm-request-logs.test.ts +2 -2
- package/src/persistence/schema/conversations.ts +15 -0
- package/src/persistence/slow-query-log.ts +58 -21
- package/src/persistence/steps.ts +2 -0
- package/src/runtime/routes/__tests__/conversation-compaction-routes.test.ts +31 -2
- package/src/runtime/routes/__tests__/conversation-query-routes.test.ts +67 -1
- package/src/runtime/routes/conversation-compaction-routes.ts +5 -0
- package/src/runtime/routes/conversation-query-routes.ts +5 -0
- package/src/runtime/routes/conversation-routes.ts +2 -8
- package/src/runtime/routes/errors.ts +17 -0
- package/src/runtime/routes/llm-request-logs-access.ts +19 -0
- package/src/tasks/tool-sanitizer.ts +3 -1
- package/src/telemetry/turn-trace-store.test.ts +4 -0
- package/src/telemetry/turn-trace-store.ts +1 -4
- package/src/tools/registry.ts +89 -11
- package/src/tools/run-standalone.ts +5 -13
- package/src/tools/workspace-tools/loader.ts +24 -8
- package/src/util/sqlite-query-label.ts +51 -0
- package/src/util/sqlite-retry.ts +14 -2
- package/src/workflows/capabilities.ts +12 -4
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the file-backed message content module: the JSONL delta fold
|
|
3
|
+
* semantics, the append/fold roundtrip, and `resolveStoredMessageContent`'s
|
|
4
|
+
* union handling (inline passthrough, ref resolution, missing-file and
|
|
5
|
+
* workspace-escape fallbacks).
|
|
6
|
+
*/
|
|
7
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { describe, expect, test } from "bun:test";
|
|
10
|
+
|
|
11
|
+
import type { ContentBlock } from "../../providers/types.js";
|
|
12
|
+
import { getWorkspaceDir } from "../../util/platform.js";
|
|
13
|
+
import {
|
|
14
|
+
appendContentDeltas,
|
|
15
|
+
foldContentDeltas,
|
|
16
|
+
foldContentFile,
|
|
17
|
+
isMessageContentRef,
|
|
18
|
+
resolveStoredMessageContent,
|
|
19
|
+
} from "../message-content-file.js";
|
|
20
|
+
|
|
21
|
+
function textBlock(text: string): ContentBlock {
|
|
22
|
+
return { type: "text", text } as ContentBlock;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe("foldContentDeltas", () => {
|
|
26
|
+
test("keeps the highest-seq line per index, ordered by index", () => {
|
|
27
|
+
const lines = [
|
|
28
|
+
{ i: 1, seq: 1, block: textBlock("second, v1") },
|
|
29
|
+
{ i: 0, seq: 2, block: textBlock("first, v1") },
|
|
30
|
+
{ i: 1, seq: 3, block: textBlock("second, v2") },
|
|
31
|
+
{ i: 0, seq: 0, block: textBlock("first, stale") },
|
|
32
|
+
]
|
|
33
|
+
.map((l) => JSON.stringify(l))
|
|
34
|
+
.join("\n");
|
|
35
|
+
expect(foldContentDeltas(lines)).toEqual([
|
|
36
|
+
textBlock("first, v1"),
|
|
37
|
+
textBlock("second, v2"),
|
|
38
|
+
]);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("skips malformed and crash-truncated lines", () => {
|
|
42
|
+
const text =
|
|
43
|
+
JSON.stringify({ i: 0, seq: 1, block: textBlock("kept") }) +
|
|
44
|
+
"\n" +
|
|
45
|
+
"not json\n" +
|
|
46
|
+
JSON.stringify({ seq: 2, block: textBlock("missing index") }) +
|
|
47
|
+
"\n" +
|
|
48
|
+
'{"i": 1, "seq": 3, "block": {"type": "text", "te'; // truncated
|
|
49
|
+
expect(foldContentDeltas(text)).toEqual([textBlock("kept")]);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test("empty input folds to empty content", () => {
|
|
53
|
+
expect(foldContentDeltas("")).toEqual([]);
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe("appendContentDeltas + foldContentFile", () => {
|
|
58
|
+
test("roundtrips across multiple appends, creating parent dirs", () => {
|
|
59
|
+
const path = join(
|
|
60
|
+
getWorkspaceDir(),
|
|
61
|
+
"conversations",
|
|
62
|
+
"test-roundtrip",
|
|
63
|
+
"inflight",
|
|
64
|
+
"msg-1.jsonl",
|
|
65
|
+
);
|
|
66
|
+
appendContentDeltas(path, [{ i: 0, seq: 1, block: textBlock("hel") }]);
|
|
67
|
+
appendContentDeltas(path, [
|
|
68
|
+
{ i: 0, seq: 2, block: textBlock("hello") },
|
|
69
|
+
{ i: 1, seq: 3, block: textBlock("world") },
|
|
70
|
+
]);
|
|
71
|
+
expect(foldContentFile(path)).toEqual([
|
|
72
|
+
textBlock("hello"),
|
|
73
|
+
textBlock("world"),
|
|
74
|
+
]);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test("returns null for a missing file", () => {
|
|
78
|
+
expect(
|
|
79
|
+
foldContentFile(join(getWorkspaceDir(), "does-not-exist.jsonl")),
|
|
80
|
+
).toBeNull();
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
describe("isMessageContentRef", () => {
|
|
85
|
+
test("accepts exactly { ref: string }", () => {
|
|
86
|
+
expect(isMessageContentRef({ ref: "a/b.jsonl" })).toBe(true);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("rejects arrays, extra keys, empty and non-string refs", () => {
|
|
90
|
+
expect(isMessageContentRef([textBlock("x")])).toBe(false);
|
|
91
|
+
expect(isMessageContentRef({ ref: "a", other: 1 })).toBe(false);
|
|
92
|
+
expect(isMessageContentRef({ ref: "" })).toBe(false);
|
|
93
|
+
expect(isMessageContentRef({ ref: 42 })).toBe(false);
|
|
94
|
+
expect(isMessageContentRef(null)).toBe(false);
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
describe("resolveStoredMessageContent", () => {
|
|
99
|
+
test("passes inline ContentBlock[] JSON through by identity", () => {
|
|
100
|
+
const inline = JSON.stringify([textBlock("hello")]);
|
|
101
|
+
expect(resolveStoredMessageContent(inline)).toBe(inline);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("passes legacy plain strings through, including '{'-prefixed ones", () => {
|
|
105
|
+
expect(resolveStoredMessageContent("plain old text")).toBe(
|
|
106
|
+
"plain old text",
|
|
107
|
+
);
|
|
108
|
+
expect(resolveStoredMessageContent("{not json")).toBe("{not json");
|
|
109
|
+
const objectButNotRef = JSON.stringify({ some: "object" });
|
|
110
|
+
expect(resolveStoredMessageContent(objectButNotRef)).toBe(objectButNotRef);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("resolves a ref to the folded file content", () => {
|
|
114
|
+
const rel = join("conversations", "test-resolve", "inflight", "m.jsonl");
|
|
115
|
+
const abs = join(getWorkspaceDir(), rel);
|
|
116
|
+
mkdirSync(
|
|
117
|
+
join(getWorkspaceDir(), "conversations", "test-resolve", "inflight"),
|
|
118
|
+
{
|
|
119
|
+
recursive: true,
|
|
120
|
+
},
|
|
121
|
+
);
|
|
122
|
+
writeFileSync(
|
|
123
|
+
abs,
|
|
124
|
+
[
|
|
125
|
+
JSON.stringify({ i: 0, seq: 1, block: textBlock("partial") }),
|
|
126
|
+
JSON.stringify({ i: 0, seq: 2, block: textBlock("final") }),
|
|
127
|
+
].join("\n") + "\n",
|
|
128
|
+
);
|
|
129
|
+
expect(resolveStoredMessageContent(JSON.stringify({ ref: rel }))).toBe(
|
|
130
|
+
JSON.stringify([textBlock("final")]),
|
|
131
|
+
);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
test("resolves a ref to a missing file as empty content", () => {
|
|
135
|
+
expect(
|
|
136
|
+
resolveStoredMessageContent(JSON.stringify({ ref: "gone/m.jsonl" })),
|
|
137
|
+
).toBe("[]");
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("rejects refs that escape the workspace directory", () => {
|
|
141
|
+
expect(
|
|
142
|
+
resolveStoredMessageContent(
|
|
143
|
+
JSON.stringify({ ref: "../../../etc/passwd" }),
|
|
144
|
+
),
|
|
145
|
+
).toBe("[]");
|
|
146
|
+
expect(
|
|
147
|
+
resolveStoredMessageContent(JSON.stringify({ ref: "/etc/passwd" })),
|
|
148
|
+
).toBe("[]");
|
|
149
|
+
});
|
|
150
|
+
});
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { Database } from "bun:sqlite";
|
|
2
2
|
import { describe, expect, test } from "bun:test";
|
|
3
3
|
|
|
4
|
+
import { runWithSqliteQueryLabel } from "../../util/sqlite-query-label.js";
|
|
5
|
+
import { withSqliteRetry } from "../../util/sqlite-retry.js";
|
|
4
6
|
import {
|
|
5
7
|
callerFromStack,
|
|
6
8
|
SLOW_QUERY_THRESHOLD_MS,
|
|
@@ -211,6 +213,99 @@ describe("slow-query-log", () => {
|
|
|
211
213
|
const db = new Database(":memory:");
|
|
212
214
|
expect(wrapSqliteForSlowQueryLogging(db)).toBe(db);
|
|
213
215
|
});
|
|
216
|
+
|
|
217
|
+
test("an ambient label tags the event and keeps the derived caller", () => {
|
|
218
|
+
const events: SlowQueryEvent[] = [];
|
|
219
|
+
const db = new Database(":memory:");
|
|
220
|
+
db.exec("CREATE TABLE t (id INTEGER PRIMARY KEY)");
|
|
221
|
+
wrapSqliteForSlowQueryLogging(db, {
|
|
222
|
+
thresholdMs: 100,
|
|
223
|
+
now: fakeClock(0, 500),
|
|
224
|
+
onSlowQuery: (e) => events.push(e),
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
runWithSqliteQueryLabel("memory:upsertRetrospectiveState", () => {
|
|
228
|
+
db.query("SELECT * FROM t").all();
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
expect(events).toHaveLength(1);
|
|
232
|
+
expect(events[0].label).toBe("memory:upsertRetrospectiveState");
|
|
233
|
+
// Unlike an explicit `.label()`, an ambient label marks an outer boundary,
|
|
234
|
+
// so the statement's own call site is still derived from the stack.
|
|
235
|
+
expect(events[0].caller).toContain("slow-query-log.test.ts");
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
test("an explicit .label() wins over the ambient label", () => {
|
|
239
|
+
const events: SlowQueryEvent[] = [];
|
|
240
|
+
const db = new Database(":memory:");
|
|
241
|
+
db.exec("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)");
|
|
242
|
+
wrapSqliteForSlowQueryLogging(db, {
|
|
243
|
+
thresholdMs: 100,
|
|
244
|
+
now: fakeClock(0, 500),
|
|
245
|
+
onSlowQuery: (e) => events.push(e),
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
runWithSqliteQueryLabel("ambient:outer", () => {
|
|
249
|
+
db.label("schedule::claimDue")
|
|
250
|
+
.query("INSERT INTO t (v) VALUES (?)")
|
|
251
|
+
.run("a");
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
expect(events).toHaveLength(1);
|
|
255
|
+
expect(events[0].label).toBe("schedule::claimDue");
|
|
256
|
+
expect(events[0].caller).toBeUndefined();
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
test("withSqliteRetry's op labels slow queries inside it, retries included", async () => {
|
|
260
|
+
const events: SlowQueryEvent[] = [];
|
|
261
|
+
const db = new Database(":memory:");
|
|
262
|
+
db.exec("CREATE TABLE t (id INTEGER PRIMARY KEY)");
|
|
263
|
+
wrapSqliteForSlowQueryLogging(db, {
|
|
264
|
+
thresholdMs: 100,
|
|
265
|
+
now: fakeClock(0, 500),
|
|
266
|
+
onSlowQuery: (e) => events.push(e),
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
// First attempt loses the write-lock race; the retry (which runs from a
|
|
270
|
+
// stack truncated by the backoff sleep) issues the slow query.
|
|
271
|
+
let attempt = 0;
|
|
272
|
+
await withSqliteRetry(
|
|
273
|
+
() => {
|
|
274
|
+
if (attempt++ === 0) {
|
|
275
|
+
throw Object.assign(new Error("busy"), { code: "SQLITE_BUSY" });
|
|
276
|
+
}
|
|
277
|
+
return db.query("SELECT * FROM t").all();
|
|
278
|
+
},
|
|
279
|
+
{ op: "test:claimRow", baseDelayMs: 1 },
|
|
280
|
+
);
|
|
281
|
+
|
|
282
|
+
expect(events).toHaveLength(1);
|
|
283
|
+
expect(events[0].label).toBe("test:claimRow");
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
test("withSqliteRetry's op labels a lazy thenable that runs when awaited", async () => {
|
|
287
|
+
const events: SlowQueryEvent[] = [];
|
|
288
|
+
const db = new Database(":memory:");
|
|
289
|
+
db.exec("CREATE TABLE t (id INTEGER PRIMARY KEY)");
|
|
290
|
+
wrapSqliteForSlowQueryLogging(db, {
|
|
291
|
+
thresholdMs: 100,
|
|
292
|
+
now: fakeClock(0, 500),
|
|
293
|
+
onSlowQuery: (e) => events.push(e),
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
// Mirrors a Drizzle QueryPromise: fn returns immediately and the statement
|
|
297
|
+
// only executes when the thenable is assimilated by an await. The retry
|
|
298
|
+
// helper must perform that await inside its label scope.
|
|
299
|
+
const lazy = {
|
|
300
|
+
then(resolve: (value: unknown) => void) {
|
|
301
|
+
resolve(db.query("SELECT * FROM t").all());
|
|
302
|
+
},
|
|
303
|
+
} as unknown as Promise<unknown>;
|
|
304
|
+
await withSqliteRetry(() => lazy, { op: "test:lazyUpdate" });
|
|
305
|
+
|
|
306
|
+
expect(events).toHaveLength(1);
|
|
307
|
+
expect(events[0].label).toBe("test:lazyUpdate");
|
|
308
|
+
});
|
|
214
309
|
});
|
|
215
310
|
|
|
216
311
|
describe("callerFromStack", () => {
|
|
@@ -254,6 +349,36 @@ describe("callerFromStack", () => {
|
|
|
254
349
|
);
|
|
255
350
|
});
|
|
256
351
|
|
|
352
|
+
test("prefers the nearest named app frame over an anonymous callback", () => {
|
|
353
|
+
// A statement run inside `db.transaction((tx) => …)` sits in an anonymous
|
|
354
|
+
// app frame, with the accountable named function above the ORM plumbing.
|
|
355
|
+
const stack = [
|
|
356
|
+
"Error",
|
|
357
|
+
" at emit (/repo/assistant/src/persistence/slow-query-log.ts:192:5)",
|
|
358
|
+
" at <anonymous> (/repo/assistant/src/persistence/conversation-crud.ts:629:44)",
|
|
359
|
+
" at <anonymous> (/root/.bun/install/cache/drizzle-orm@0.45.2@@@1/bun-sqlite/session.js:35:16)",
|
|
360
|
+
" at transaction (bun:sqlite:416:27)",
|
|
361
|
+
" at transaction (/root/.bun/install/cache/drizzle-orm@0.45.2@@@1/bun-sqlite/session.js:37:33)",
|
|
362
|
+
" at insertMessageCore (/repo/assistant/src/persistence/conversation-crud.ts:474:10)",
|
|
363
|
+
].join("\n");
|
|
364
|
+
expect(callerFromStack(stack)).toBe(
|
|
365
|
+
"persistence/conversation-crud.ts:insertMessageCore:474",
|
|
366
|
+
);
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
test("falls back to the innermost anonymous app frame when nothing is named", () => {
|
|
370
|
+
const stack = [
|
|
371
|
+
"Error",
|
|
372
|
+
" at emit (/repo/assistant/src/persistence/slow-query-log.ts:192:5)",
|
|
373
|
+
" at <anonymous> (/repo/assistant/src/persistence/conversation-crud.ts:629:44)",
|
|
374
|
+
" at <anonymous> (/repo/assistant/src/daemon/lifecycle.ts:88:12)",
|
|
375
|
+
" at processTicksAndRejections (native:7:39)",
|
|
376
|
+
].join("\n");
|
|
377
|
+
expect(callerFromStack(stack)).toBe(
|
|
378
|
+
"persistence/conversation-crud.ts:<anonymous>:629",
|
|
379
|
+
);
|
|
380
|
+
});
|
|
381
|
+
|
|
257
382
|
test("returns undefined when no application frame is present", () => {
|
|
258
383
|
const stack = [
|
|
259
384
|
"Error",
|
|
@@ -88,6 +88,7 @@ import {
|
|
|
88
88
|
enqueueLexicalIndexForMessage,
|
|
89
89
|
enqueuePurgeConversationLexical,
|
|
90
90
|
} from "./job-handlers/message-lexical.js";
|
|
91
|
+
import { resolveStoredMessageContent } from "./message-content-file.js";
|
|
91
92
|
import {
|
|
92
93
|
rawAll,
|
|
93
94
|
rawExec,
|
|
@@ -446,20 +447,29 @@ export interface MessageRow {
|
|
|
446
447
|
id: string;
|
|
447
448
|
conversationId: string;
|
|
448
449
|
role: string;
|
|
450
|
+
/** Resolved content — always inline JSON, never a raw `{ ref }`. */
|
|
449
451
|
content: string;
|
|
450
452
|
createdAt: number;
|
|
451
453
|
metadata: string | null;
|
|
452
454
|
clientMessageId: string | null;
|
|
455
|
+
/** 1 = content is complete; 0 = message is still streaming. */
|
|
456
|
+
finalized: number;
|
|
453
457
|
}
|
|
454
458
|
|
|
455
459
|
const parseMessage = createRowMapper<typeof messages.$inferSelect, MessageRow>({
|
|
456
460
|
id: "id",
|
|
457
461
|
conversationId: "conversationId",
|
|
458
462
|
role: "role",
|
|
459
|
-
content
|
|
463
|
+
// File-backed `{ ref }` content is resolved here, at the row-fetch
|
|
464
|
+
// chokepoint, so every consumer of MessageRow sees inline content.
|
|
465
|
+
content: {
|
|
466
|
+
from: "content",
|
|
467
|
+
transform: (v) => resolveStoredMessageContent(v as string),
|
|
468
|
+
},
|
|
460
469
|
createdAt: "createdAt",
|
|
461
470
|
metadata: "metadata",
|
|
462
471
|
clientMessageId: "clientMessageId",
|
|
472
|
+
finalized: "finalized",
|
|
463
473
|
});
|
|
464
474
|
|
|
465
475
|
/**
|
|
@@ -16,6 +16,13 @@ import {
|
|
|
16
16
|
import { v4 as uuid } from "uuid";
|
|
17
17
|
|
|
18
18
|
import { CALL_SITE_SYNTHETIC_AGENT_ERROR_MESSAGE } from "../api/constants/call-sites.js";
|
|
19
|
+
// Namespace import (not a named `getConfigReadOnly` import) on purpose: the
|
|
20
|
+
// store is reached transitively by a large number of tests that stub
|
|
21
|
+
// `config/loader` with a partial mock exposing only `getConfig`. A named
|
|
22
|
+
// import would fail to link against those mocks ("Export … not found"); a
|
|
23
|
+
// namespace access degrades to `undefined` at call time instead, which the
|
|
24
|
+
// try/catch in `llmRequestLoggingEnabled` treats as "enabled".
|
|
25
|
+
import * as configLoader from "../config/loader.js";
|
|
19
26
|
import type { LLMCallSite } from "../config/schemas/llm.js";
|
|
20
27
|
import { AssistantError, ProviderError } from "../util/errors.js";
|
|
21
28
|
import {
|
|
@@ -42,6 +49,22 @@ function logsDb(): DrizzleDb {
|
|
|
42
49
|
return db;
|
|
43
50
|
}
|
|
44
51
|
|
|
52
|
+
/**
|
|
53
|
+
* Whether LLM request logging is enabled (`llmRequestLogs.enabled`, default
|
|
54
|
+
* `true`). Gates every `llm_request_logs` insert so no prompt/completion
|
|
55
|
+
* payload is written while logging is off. Read-only config access (no
|
|
56
|
+
* `ensureDataDir`/disk write) because this sits on the per-LLM-call critical
|
|
57
|
+
* path; defaults to "enabled" if config resolution throws so a config hiccup
|
|
58
|
+
* never silently drops logs.
|
|
59
|
+
*/
|
|
60
|
+
export function llmRequestLoggingEnabled(): boolean {
|
|
61
|
+
try {
|
|
62
|
+
return configLoader.getConfigReadOnly().llmRequestLogs?.enabled !== false;
|
|
63
|
+
} catch {
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
45
68
|
export type LogRow = {
|
|
46
69
|
id: string;
|
|
47
70
|
conversationId: string;
|
|
@@ -165,7 +188,13 @@ export function recordRequestLog(
|
|
|
165
188
|
provider?: string,
|
|
166
189
|
callSite?: LLMCallSite,
|
|
167
190
|
latencyBreakdown?: string,
|
|
168
|
-
): string {
|
|
191
|
+
): string | null {
|
|
192
|
+
// Master opt-out: when logging is disabled, skip the write entirely so no
|
|
193
|
+
// prompt/completion payload lands on disk. Returns null — there is no row to
|
|
194
|
+
// stamp/backfill later, and no production caller consumes the return value.
|
|
195
|
+
if (!llmRequestLoggingEnabled()) {
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
169
198
|
const db = logsDb();
|
|
170
199
|
const id = uuid();
|
|
171
200
|
// Synchronous insert of the full request/response payloads (an entire
|
|
@@ -250,7 +279,12 @@ export function recordSyntheticAgentErrorMessageLog(args: {
|
|
|
250
279
|
*/
|
|
251
280
|
preparedRequest: unknown | null;
|
|
252
281
|
createdAt: number;
|
|
253
|
-
}): string {
|
|
282
|
+
}): string | null {
|
|
283
|
+
// Synthetic error rows are `llm_request_logs` rows too — honour the same
|
|
284
|
+
// master opt-out so nothing is written while logging is disabled.
|
|
285
|
+
if (!llmRequestLoggingEnabled()) {
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
254
288
|
const db = logsDb();
|
|
255
289
|
const id = uuid();
|
|
256
290
|
const requestPayload = JSON.stringify({
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File-backed message content: the JSONL delta format and the ref resolver.
|
|
3
|
+
*
|
|
4
|
+
* A `messages.content` value is a union of two shapes:
|
|
5
|
+
* - Inline: a JSON-serialized `ContentBlock[]` (or a legacy plain string).
|
|
6
|
+
* - Ref: `{ "ref": "<workspace-relative path>" }` pointing at a JSONL
|
|
7
|
+
* delta file that folds to a `ContentBlock[]`.
|
|
8
|
+
*
|
|
9
|
+
* The delta file is append-only. Each line is `{ i, seq, block }` where `i`
|
|
10
|
+
* is the block index in the final array and `seq` is a monotonically
|
|
11
|
+
* increasing write sequence. Folding keeps the highest-`seq` line per `i`
|
|
12
|
+
* and orders the surviving blocks by `i`, so a partially-flushed or
|
|
13
|
+
* crash-truncated file still folds to the newest complete snapshot of each
|
|
14
|
+
* block.
|
|
15
|
+
*
|
|
16
|
+
* All content reads must go through {@link resolveStoredMessageContent}
|
|
17
|
+
* (wired into the message row mapper) — downstream consumers never see a
|
|
18
|
+
* raw `{ ref }` value.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
|
|
22
|
+
import { dirname, resolve, sep } from "node:path";
|
|
23
|
+
|
|
24
|
+
import type { ContentBlock } from "../providers/types.js";
|
|
25
|
+
import { getLogger } from "../util/logger.js";
|
|
26
|
+
import { getWorkspaceDir } from "../util/platform.js";
|
|
27
|
+
|
|
28
|
+
const log = getLogger("message-content-file");
|
|
29
|
+
|
|
30
|
+
/** Ref-shaped `messages.content` value pointing at a delta file. */
|
|
31
|
+
export interface MessageContentRef {
|
|
32
|
+
/** Path of the JSONL delta file, relative to the workspace directory. */
|
|
33
|
+
ref: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** One line of the append-only content delta file. */
|
|
37
|
+
export interface ContentDeltaLine {
|
|
38
|
+
/** Index of `block` in the folded `ContentBlock[]`. */
|
|
39
|
+
i: number;
|
|
40
|
+
/** Monotonic write sequence; the highest `seq` per `i` wins the fold. */
|
|
41
|
+
seq: number;
|
|
42
|
+
block: ContentBlock;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Narrow a parsed `messages.content` value to the ref shape. Strict on
|
|
47
|
+
* purpose (exactly one key) so a legacy plain-string message that happens
|
|
48
|
+
* to parse as an object can never be mistaken for a ref.
|
|
49
|
+
*/
|
|
50
|
+
export function isMessageContentRef(
|
|
51
|
+
value: unknown,
|
|
52
|
+
): value is MessageContentRef {
|
|
53
|
+
return (
|
|
54
|
+
typeof value === "object" &&
|
|
55
|
+
value !== null &&
|
|
56
|
+
!Array.isArray(value) &&
|
|
57
|
+
Object.keys(value).length === 1 &&
|
|
58
|
+
typeof (value as { ref?: unknown }).ref === "string" &&
|
|
59
|
+
(value as { ref: string }).ref.length > 0
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Resolve a workspace-relative content ref to an absolute path, rejecting
|
|
65
|
+
* anything that escapes the workspace directory. Returns null on escape.
|
|
66
|
+
*/
|
|
67
|
+
export function resolveContentRefPath(ref: string): string | null {
|
|
68
|
+
const workspaceDir = resolve(getWorkspaceDir());
|
|
69
|
+
const abs = resolve(workspaceDir, ref);
|
|
70
|
+
if (abs !== workspaceDir && !abs.startsWith(workspaceDir + sep)) {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
return abs;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Append delta lines to a content file, creating parent directories on
|
|
78
|
+
* first write. Callers own write exclusivity — a message's delta file has
|
|
79
|
+
* exactly one writer (the owning turn) for its lifetime.
|
|
80
|
+
*/
|
|
81
|
+
export function appendContentDeltas(
|
|
82
|
+
absPath: string,
|
|
83
|
+
deltas: ContentDeltaLine[],
|
|
84
|
+
): void {
|
|
85
|
+
if (deltas.length === 0) {
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
mkdirSync(dirname(absPath), { recursive: true });
|
|
89
|
+
appendFileSync(absPath, deltas.map((d) => JSON.stringify(d) + "\n").join(""));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Fold raw JSONL delta text into a `ContentBlock[]`: highest `seq` per
|
|
94
|
+
* block index wins, blocks ordered by index. Malformed lines (including a
|
|
95
|
+
* crash-truncated final line) are skipped.
|
|
96
|
+
*/
|
|
97
|
+
export function foldContentDeltas(text: string): ContentBlock[] {
|
|
98
|
+
const byIndex = new Map<number, { seq: number; block: ContentBlock }>();
|
|
99
|
+
for (const line of text.split("\n")) {
|
|
100
|
+
if (!line) {
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
let parsed: unknown;
|
|
104
|
+
try {
|
|
105
|
+
parsed = JSON.parse(line);
|
|
106
|
+
} catch {
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
const { i, seq, block } = parsed as Partial<ContentDeltaLine>;
|
|
113
|
+
if (
|
|
114
|
+
typeof i !== "number" ||
|
|
115
|
+
typeof seq !== "number" ||
|
|
116
|
+
typeof block !== "object" ||
|
|
117
|
+
block === null
|
|
118
|
+
) {
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
const existing = byIndex.get(i);
|
|
122
|
+
if (!existing || seq > existing.seq) {
|
|
123
|
+
byIndex.set(i, { seq, block });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return [...byIndex.entries()]
|
|
127
|
+
.sort(([a], [b]) => a - b)
|
|
128
|
+
.map(([, entry]) => entry.block);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Read and fold a content delta file. Returns null when the file is
|
|
133
|
+
* missing or unreadable — callers decide the fallback.
|
|
134
|
+
*/
|
|
135
|
+
export function foldContentFile(absPath: string): ContentBlock[] | null {
|
|
136
|
+
let text: string;
|
|
137
|
+
try {
|
|
138
|
+
text = readFileSync(absPath, "utf8");
|
|
139
|
+
} catch {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
return foldContentDeltas(text);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Resolve a stored `messages.content` value to its inline JSON form.
|
|
147
|
+
*
|
|
148
|
+
* Inline values (JSON `ContentBlock[]` or legacy plain strings) pass
|
|
149
|
+
* through untouched — the common case costs one character check. Ref
|
|
150
|
+
* values are resolved by folding the delta file and returning the folded
|
|
151
|
+
* blocks as a JSON string, so every consumer downstream of the row mapper
|
|
152
|
+
* sees the same shape it always has.
|
|
153
|
+
*
|
|
154
|
+
* Never throws. A missing/unreadable file or an escaping ref resolves to
|
|
155
|
+
* `"[]"` (empty content) with a warning — content reads must not take
|
|
156
|
+
* down read paths.
|
|
157
|
+
*/
|
|
158
|
+
export function resolveStoredMessageContent(raw: string): string {
|
|
159
|
+
// Inline arrays start with '[', legacy plain strings rarely start with
|
|
160
|
+
// '{' — and when one does, the parse/shape checks below reject it.
|
|
161
|
+
if (typeof raw !== "string" || raw.charCodeAt(0) !== 0x7b /* '{' */) {
|
|
162
|
+
return raw;
|
|
163
|
+
}
|
|
164
|
+
let parsed: unknown;
|
|
165
|
+
try {
|
|
166
|
+
parsed = JSON.parse(raw);
|
|
167
|
+
} catch {
|
|
168
|
+
return raw;
|
|
169
|
+
}
|
|
170
|
+
if (!isMessageContentRef(parsed)) {
|
|
171
|
+
return raw;
|
|
172
|
+
}
|
|
173
|
+
const absPath = resolveContentRefPath(parsed.ref);
|
|
174
|
+
if (!absPath) {
|
|
175
|
+
log.warn(
|
|
176
|
+
{ ref: parsed.ref },
|
|
177
|
+
"Content ref escapes the workspace directory; resolving as empty",
|
|
178
|
+
);
|
|
179
|
+
return "[]";
|
|
180
|
+
}
|
|
181
|
+
const blocks = foldContentFile(absPath);
|
|
182
|
+
if (blocks === null) {
|
|
183
|
+
log.warn(
|
|
184
|
+
{ ref: parsed.ref },
|
|
185
|
+
"Content ref file missing or unreadable; resolving as empty",
|
|
186
|
+
);
|
|
187
|
+
return "[]";
|
|
188
|
+
}
|
|
189
|
+
return JSON.stringify(blocks);
|
|
190
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { DrizzleDb } from "../db-connection.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Add the `finalized` column to `messages`.
|
|
5
|
+
*
|
|
6
|
+
* `finalized = 1` (the default, and the backfill value for every existing
|
|
7
|
+
* row) means the row's `content` is the complete, immutable value — either
|
|
8
|
+
* an inline `ContentBlock[]` or a `{ ref }` pointing at an externalized
|
|
9
|
+
* content file. `finalized = 0` means the message is still streaming: its
|
|
10
|
+
* content lives in an in-flight delta file under the conversation
|
|
11
|
+
* directory and the row's `content` holds the `{ ref }` to it. Batch
|
|
12
|
+
* readers (search, memory indexing, fork) filter on `finalized = 1`; only
|
|
13
|
+
* the live turn and crash recovery read unfinalized content.
|
|
14
|
+
*
|
|
15
|
+
* Uses ALTER TABLE ADD COLUMN with try/catch for idempotency — no registry
|
|
16
|
+
* entry needed.
|
|
17
|
+
*/
|
|
18
|
+
export function migrateMessageFinalizedColumn(database: DrizzleDb): void {
|
|
19
|
+
try {
|
|
20
|
+
database.run(
|
|
21
|
+
/*sql*/ `ALTER TABLE messages ADD COLUMN finalized INTEGER NOT NULL DEFAULT 1`,
|
|
22
|
+
);
|
|
23
|
+
} catch {
|
|
24
|
+
/* already exists */
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -63,7 +63,7 @@ describe("migration 297 — llm_request_logs lives in the logs database", () =>
|
|
|
63
63
|
"anthropic",
|
|
64
64
|
"mainAgent",
|
|
65
65
|
);
|
|
66
|
-
const row = getRequestLogById(id);
|
|
66
|
+
const row = getRequestLogById(id!);
|
|
67
67
|
expect(row?.conversationId).toBe("conv-297");
|
|
68
68
|
expect(row?.messageId).toBe("msg-297");
|
|
69
69
|
expect(row?.provider).toBe("anthropic");
|
|
@@ -75,7 +75,7 @@ describe("migration 297 — llm_request_logs lives in the logs database", () =>
|
|
|
75
75
|
{ c: number },
|
|
76
76
|
[string]
|
|
77
77
|
>(`SELECT COUNT(*) AS c FROM llm_request_logs WHERE id = ?`)
|
|
78
|
-
.get(id);
|
|
78
|
+
.get(id!);
|
|
79
79
|
expect(inLogs?.c).toBe(1);
|
|
80
80
|
});
|
|
81
81
|
|
|
@@ -104,10 +104,25 @@ export const messages = sqliteTable(
|
|
|
104
104
|
.notNull()
|
|
105
105
|
.references(() => conversations.id, { onDelete: "cascade" }),
|
|
106
106
|
role: text("role").notNull(),
|
|
107
|
+
/**
|
|
108
|
+
* Union of two JSON shapes: an inline `ContentBlock[]` (or a legacy
|
|
109
|
+
* plain string), or `{ ref: "<workspace-relative path>" }` pointing at
|
|
110
|
+
* a file-backed content payload. Always read through the message row
|
|
111
|
+
* mapper (which applies `resolveStoredMessageContent`) — never parse
|
|
112
|
+
* this column raw.
|
|
113
|
+
*/
|
|
107
114
|
content: text("content").notNull(),
|
|
108
115
|
createdAt: integer("created_at").notNull(),
|
|
109
116
|
metadata: text("metadata"),
|
|
110
117
|
clientMessageId: text("client_message_id"),
|
|
118
|
+
/**
|
|
119
|
+
* 1 (default) = `content` is the complete, immutable value (inline or
|
|
120
|
+
* `{ ref }`). 0 = the message is still streaming and `content` is a
|
|
121
|
+
* `{ ref }` to its in-flight delta file. Batch readers (search, memory
|
|
122
|
+
* indexing, fork) must filter `finalized = 1`; only the live turn and
|
|
123
|
+
* crash recovery read unfinalized rows.
|
|
124
|
+
*/
|
|
125
|
+
finalized: integer("finalized").notNull().default(1),
|
|
111
126
|
},
|
|
112
127
|
(table) => [
|
|
113
128
|
uniqueIndex("idx_messages_conv_client_msg_id")
|