@tangle-network/agent-app 2.0.5 → 2.0.8
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/dist/agent-profiles/d1.js +3 -3
- package/dist/agent-profiles/index.js +3 -3
- package/dist/app-auth/index.js +2 -2
- package/dist/chat-routes/completed-sandbox-turn.d.ts +1 -1
- package/dist/chat-routes/index.js +15 -25
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/sandbox-turn-usage.d.ts +4 -0
- package/dist/chat-routes/turn-route-contracts.d.ts +3 -0
- package/dist/chat-store/core.d.ts +2 -0
- package/dist/chat-store/index.js +24 -28
- package/dist/chat-store/index.js.map +1 -1
- package/dist/chat-store/schema.d.ts +9 -0
- package/dist/{chunk-2ARZ4Y7D.js → chunk-3XVGMHCD.js} +2 -2
- package/dist/{chunk-RTJJYBVV.js → chunk-4EQWYI53.js} +2 -2
- package/dist/{chunk-JGPSBTUH.js → chunk-5DAEU3CP.js} +42 -31
- package/dist/chunk-5DAEU3CP.js.map +1 -0
- package/dist/{chunk-WQZCX4IJ.js → chunk-6GN2E5KT.js} +2 -2
- package/dist/{chunk-HFWKZHTZ.js → chunk-B2NN5BIJ.js} +5 -5
- package/dist/chunk-B2NN5BIJ.js.map +1 -0
- package/dist/{chunk-532GILWC.js → chunk-CVOEGD3Y.js} +2 -2
- package/dist/{chunk-LPW4UVAZ.js → chunk-D6UJEOZQ.js} +1 -1
- package/dist/chunk-D6UJEOZQ.js.map +1 -0
- package/dist/{chunk-N425HGJW.js → chunk-EI27JMS6.js} +1 -1
- package/dist/chunk-EI27JMS6.js.map +1 -0
- package/dist/{chunk-CU6PJO5R.js → chunk-JUQMVD4U.js} +2 -2
- package/dist/{chunk-IDRATMRZ.js → chunk-MVTLHM74.js} +5 -5
- package/dist/{chunk-IDRATMRZ.js.map → chunk-MVTLHM74.js.map} +1 -1
- package/dist/{chunk-C3JXGK3R.js → chunk-NHOQ5TMH.js} +2 -2
- package/dist/{chunk-7BRFM73D.js → chunk-PABZALSD.js} +2 -2
- package/dist/{chunk-CTQQGPHT.js → chunk-PO23GWVQ.js} +13 -17
- package/dist/chunk-PO23GWVQ.js.map +1 -0
- package/dist/{chunk-TJA5ERCP.js → chunk-STGV7DXB.js} +3 -3
- package/dist/{chunk-ORBPOLBM.js → chunk-X2NXWJ6P.js} +27 -7
- package/dist/chunk-X2NXWJ6P.js.map +1 -0
- package/dist/conformance/cli.js +2 -2
- package/dist/conformance/index.js +2 -2
- package/dist/operator/chat-adapter.d.ts +1 -0
- package/dist/operator/contract.d.ts +2 -0
- package/dist/operator/index.js +2 -1
- package/dist/operator/index.js.map +1 -1
- package/dist/platform/index.js +2 -2
- package/dist/preset-cloudflare/index.js +4 -4
- package/dist/public-consultation/index.js +9 -9
- package/dist/runtime/index.js +3 -3
- package/dist/runtime/model.d.ts +1 -1
- package/dist/runtime/router-turn.js +2 -2
- package/dist/sandbox/index.js +6 -6
- package/dist/sandbox/model.d.ts +11 -9
- package/dist/sandbox/prompt-profile.d.ts +7 -5
- package/dist/tools/index.js +4 -4
- package/dist/work-product/index.js +2 -2
- package/package.json +33 -33
- package/dist/chunk-CTQQGPHT.js.map +0 -1
- package/dist/chunk-HFWKZHTZ.js.map +0 -1
- package/dist/chunk-JGPSBTUH.js.map +0 -1
- package/dist/chunk-LPW4UVAZ.js.map +0 -1
- package/dist/chunk-N425HGJW.js.map +0 -1
- package/dist/chunk-ORBPOLBM.js.map +0 -1
- /package/dist/{chunk-2ARZ4Y7D.js.map → chunk-3XVGMHCD.js.map} +0 -0
- /package/dist/{chunk-RTJJYBVV.js.map → chunk-4EQWYI53.js.map} +0 -0
- /package/dist/{chunk-WQZCX4IJ.js.map → chunk-6GN2E5KT.js.map} +0 -0
- /package/dist/{chunk-532GILWC.js.map → chunk-CVOEGD3Y.js.map} +0 -0
- /package/dist/{chunk-CU6PJO5R.js.map → chunk-JUQMVD4U.js.map} +0 -0
- /package/dist/{chunk-C3JXGK3R.js.map → chunk-NHOQ5TMH.js.map} +0 -0
- /package/dist/{chunk-7BRFM73D.js.map → chunk-PABZALSD.js.map} +0 -0
- /package/dist/{chunk-TJA5ERCP.js.map → chunk-STGV7DXB.js.map} +0 -0
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { type JsonRecord } from '../stream/index.js';
|
|
2
2
|
import type { ChatTurnUsage } from './turn-routes.js';
|
|
3
|
+
/** Every usage field a turn can record, in column order. */
|
|
4
|
+
export declare const TURN_USAGE_KEYS: readonly ['inputTokens', 'outputTokens', 'reasoningTokens', 'cacheReadTokens', 'cacheWriteTokens', 'costUsd', 'harnessCostUsd'];
|
|
5
|
+
/** The usage fields a turn measured; unknown ones stay absent, never zero. */
|
|
6
|
+
export declare function measuredUsage(usage: ChatTurnUsage | undefined): ChatTurnUsage;
|
|
3
7
|
/** Add one canonical Sandbox `step-finish` receipt to a turn total. */
|
|
4
8
|
export declare function addStepFinishUsage(part: JsonRecord, usage: ChatTurnUsage): void;
|
|
@@ -38,7 +38,10 @@ export interface ChatTurnUsage {
|
|
|
38
38
|
reasoningTokens?: number;
|
|
39
39
|
cacheReadTokens?: number;
|
|
40
40
|
cacheWriteTokens?: number;
|
|
41
|
+
/** What the Platform ledger charged (Sandbox `PromptResult.costUsd`); absent when nothing was charged or read. */
|
|
41
42
|
costUsd?: number;
|
|
43
|
+
/** The harness's own reported token cost; a failed turn keeps its model spend here. */
|
|
44
|
+
harnessCostUsd?: number;
|
|
42
45
|
}
|
|
43
46
|
/** What the route persists — a structural subset of `/chat-store`'s
|
|
44
47
|
* `ChatStore`, so `createChatStore(db, tables)` satisfies it directly and a
|
|
@@ -33,5 +33,7 @@ export type ChatMessageValues = {
|
|
|
33
33
|
reasoningTokens?: number | null;
|
|
34
34
|
cacheReadTokens?: number | null;
|
|
35
35
|
cacheWriteTokens?: number | null;
|
|
36
|
+
/** Platform ledger charge; `harnessCostUsd` is the harness's own reported token cost. */
|
|
36
37
|
costUsd?: number | null;
|
|
38
|
+
harnessCostUsd?: number | null;
|
|
37
39
|
};
|
package/dist/chat-store/index.js
CHANGED
|
@@ -43,6 +43,7 @@ function threadTitleFromMessage(message) {
|
|
|
43
43
|
// src/chat-store/schema.ts
|
|
44
44
|
import { sql } from "drizzle-orm";
|
|
45
45
|
import { index, integer, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
46
|
+
var harnessCostColumns = () => ({ harnessCostUsd: real("harness_cost_usd") });
|
|
46
47
|
var hexId = () => text("id").primaryKey().default(sql`(lower(hex(randomblob(16))))`);
|
|
47
48
|
var createdAt = () => integer("created_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`);
|
|
48
49
|
var updatedAt = () => integer("updated_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`);
|
|
@@ -79,7 +80,8 @@ function createChatTables(options = {}) {
|
|
|
79
80
|
servedProvider: text("served_provider"),
|
|
80
81
|
servedSource: text("served_model_source"),
|
|
81
82
|
// Usage receipt, flattened from the harness's `step-finish` shape
|
|
82
|
-
// (`tokens {input, output, reasoning, cache{read, write}}`
|
|
83
|
+
// (`tokens {input, output, reasoning, cache{read, write}}`); `cost_usd` is the
|
|
84
|
+
// Platform ledger charge. The harness's `cost` needs `harnessCostColumns()`.
|
|
83
85
|
inputTokens: integer("input_tokens"),
|
|
84
86
|
outputTokens: integer("output_tokens"),
|
|
85
87
|
reasoningTokens: integer("reasoning_tokens"),
|
|
@@ -137,6 +139,24 @@ function clampOffset(offset) {
|
|
|
137
139
|
function createChatStore(db, tables) {
|
|
138
140
|
const threads = tables.threads;
|
|
139
141
|
const messages = tables.messages;
|
|
142
|
+
const messageValueKeys = [
|
|
143
|
+
"content",
|
|
144
|
+
"parts",
|
|
145
|
+
"toolName",
|
|
146
|
+
"model",
|
|
147
|
+
"requestedModel",
|
|
148
|
+
"servedModel",
|
|
149
|
+
"servedProvider",
|
|
150
|
+
"servedSource",
|
|
151
|
+
"inputTokens",
|
|
152
|
+
"outputTokens",
|
|
153
|
+
"reasoningTokens",
|
|
154
|
+
"cacheReadTokens",
|
|
155
|
+
"cacheWriteTokens",
|
|
156
|
+
"costUsd",
|
|
157
|
+
..."harnessCostUsd" in getTableColumns(tables.messages) ? ["harnessCostUsd"] : []
|
|
158
|
+
];
|
|
159
|
+
const definedMessageValues = (source) => Object.fromEntries(messageValueKeys.map((key) => [key, source[key]]).filter(([, value]) => value !== void 0));
|
|
140
160
|
return {
|
|
141
161
|
async listThreads(input) {
|
|
142
162
|
const limit = clampLimit(input.limit, 50, 200);
|
|
@@ -270,19 +290,7 @@ function createChatStore(db, tables) {
|
|
|
270
290
|
threadId: input.threadId,
|
|
271
291
|
role: input.role,
|
|
272
292
|
content: input.content,
|
|
273
|
-
...input
|
|
274
|
-
...input.toolName !== void 0 ? { toolName: input.toolName } : {},
|
|
275
|
-
...input.model !== void 0 ? { model: input.model } : {},
|
|
276
|
-
...input.requestedModel !== void 0 ? { requestedModel: input.requestedModel } : {},
|
|
277
|
-
...input.servedModel !== void 0 ? { servedModel: input.servedModel } : {},
|
|
278
|
-
...input.servedProvider !== void 0 ? { servedProvider: input.servedProvider } : {},
|
|
279
|
-
...input.servedSource !== void 0 ? { servedSource: input.servedSource } : {},
|
|
280
|
-
...input.inputTokens !== void 0 ? { inputTokens: input.inputTokens } : {},
|
|
281
|
-
...input.outputTokens !== void 0 ? { outputTokens: input.outputTokens } : {},
|
|
282
|
-
...input.reasoningTokens !== void 0 ? { reasoningTokens: input.reasoningTokens } : {},
|
|
283
|
-
...input.cacheReadTokens !== void 0 ? { cacheReadTokens: input.cacheReadTokens } : {},
|
|
284
|
-
...input.cacheWriteTokens !== void 0 ? { cacheWriteTokens: input.cacheWriteTokens } : {},
|
|
285
|
-
...input.costUsd !== void 0 ? { costUsd: input.costUsd } : {},
|
|
293
|
+
...definedMessageValues(input),
|
|
286
294
|
...input.extras ?? {}
|
|
287
295
|
};
|
|
288
296
|
const [insertResult] = await runSqliteStatements(db, [
|
|
@@ -295,20 +303,7 @@ function createChatStore(db, tables) {
|
|
|
295
303
|
},
|
|
296
304
|
async updateMessage(id, patch) {
|
|
297
305
|
const values = {
|
|
298
|
-
...patch
|
|
299
|
-
...patch.parts !== void 0 ? { parts: patch.parts } : {},
|
|
300
|
-
...patch.toolName !== void 0 ? { toolName: patch.toolName } : {},
|
|
301
|
-
...patch.model !== void 0 ? { model: patch.model } : {},
|
|
302
|
-
...patch.requestedModel !== void 0 ? { requestedModel: patch.requestedModel } : {},
|
|
303
|
-
...patch.servedModel !== void 0 ? { servedModel: patch.servedModel } : {},
|
|
304
|
-
...patch.servedProvider !== void 0 ? { servedProvider: patch.servedProvider } : {},
|
|
305
|
-
...patch.servedSource !== void 0 ? { servedSource: patch.servedSource } : {},
|
|
306
|
-
...patch.inputTokens !== void 0 ? { inputTokens: patch.inputTokens } : {},
|
|
307
|
-
...patch.outputTokens !== void 0 ? { outputTokens: patch.outputTokens } : {},
|
|
308
|
-
...patch.reasoningTokens !== void 0 ? { reasoningTokens: patch.reasoningTokens } : {},
|
|
309
|
-
...patch.cacheReadTokens !== void 0 ? { cacheReadTokens: patch.cacheReadTokens } : {},
|
|
310
|
-
...patch.cacheWriteTokens !== void 0 ? { cacheWriteTokens: patch.cacheWriteTokens } : {},
|
|
311
|
-
...patch.costUsd !== void 0 ? { costUsd: patch.costUsd } : {},
|
|
306
|
+
...definedMessageValues(patch),
|
|
312
307
|
...patch.extras ?? {}
|
|
313
308
|
};
|
|
314
309
|
if (Object.keys(values).length === 0) {
|
|
@@ -340,6 +335,7 @@ export {
|
|
|
340
335
|
createChatStore,
|
|
341
336
|
createChatTables,
|
|
342
337
|
createThreadArtifactLinksTable,
|
|
338
|
+
harnessCostColumns,
|
|
343
339
|
historyAttachmentsFromMessages,
|
|
344
340
|
historyContentWithAttachments,
|
|
345
341
|
isChatAttachmentPart,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/chat-store/core.ts","../../src/chat-store/schema.ts","../../src/chat-store/store.ts"],"sourcesContent":["/**\n * Pure (drizzle-free) pieces of the chat store: thread-title derivation, the\n * bulk-delete bound, message-write contract, and typed input error. Split from\n * `./schema`/`./store`\n * so the root barrel can re-export them without dragging the optional\n * drizzle-orm peer into every root-entry consumer.\n */\n\nimport type { ChatMessagePart } from './parts'\n\n/** Bounds a single bulk-delete request's write set; product surfaces cap\n * thread lists at far fewer, so a larger batch is a malformed or hostile\n * request. (Lifted from legal's api.threads.bulk-delete route.) */\nexport const BULK_DELETE_MAX_THREADS = 200\n\n/** Invalid caller input (missing/oversized ids, empty title). Products map it\n * to a 400; anything else out of the store is a real failure. */\nexport class ChatStoreInputError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ChatStoreInputError'\n }\n}\n\n/** Thread titles come from the first message — keep the list scannable by\n * storing only its first non-empty line, capped at 80 chars, never the whole\n * multi-page prompt. (Lifted verbatim from legal's chat.new route.) */\nexport function threadTitleFromMessage(message: string): string {\n const firstLine = message.split('\\n').find((l) => l.trim().length > 0)?.trim() ?? ''\n if (!firstLine) return 'New Thread'\n return firstLine.length > 80 ? `${firstLine.slice(0, 79)}…` : firstLine\n}\n\n/** Stored message body, model attribution and usage shared by append and patch adapters. */\nexport type ChatMessageValues = {\n content: string\n parts?: ChatMessagePart[]\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n}\n","/**\n * Drizzle schema factory for the chat thread/message tables — the same\n * injection pattern as `createTeamTables`: the product owns the workspace\n * table; the factory wires the thread FK into it so the whole graph lives in\n * one drizzle schema with real cascade semantics. Column names, types,\n * defaults, enums, and indexes mirror legal's and gtm's hand-rolled `thread`/\n * `message` tables so a product with those tables adopts the factory without\n * rewriting rows; `tablePrefix` covers products that namespace (tax's\n * `chat_messages` style).\n *\n * The core is the superset the three products agree on. Divergences dropped,\n * and why:\n * - `thread.status` ('active'|'archived', legal+gtm) — archive semantics\n * diverge (tax uses `archivedAt`); product-domain lifecycle → extra column.\n * - `thread.scopeKind`/`scopeKey`/`harness` (gtm) — artifact anchoring and\n * harness pinning are product-domain → extra columns.\n * - tax's `tax_sessions` session columns (`taxYear`, `projectRef`,\n * `agentSessionId`, `agentRuntime`, `agentHarness`, `profile`, `error`,\n * `userId`) — sandbox-session state, not chat state → extra columns.\n * - `message.toolInput`/`toolOutput` (legal+gtm) — duplicate of the tool\n * part's `state.input`/`state.output` inside `parts` (the shape `/stream`'s\n * `normalizePersistedPart` owns); keeping both invites drift.\n * - `message.vaultFiles` (legal+gtm) — vault is product-domain → extra column.\n * - tax's re-declared `turn_events`/`turn_status` DDL — deliberately NOT here;\n * `/stream`'s turn-buffer owns that DDL (`TURN_BUFFER_D1_SCHEMA_SQL`).\n *\n * Kept beyond the intersection: tax's per-message `model`/`inputTokens`/\n * `outputTokens`, extended to the full usage receipt the harness actually\n * reports in `step-finish` parts (`tokens {input, output, reasoning,\n * cache{read, write}}` + `cost`) — see `./parts`.\n *\n * `threadExtraColumns`/`messageExtraColumns` merge product columns into the\n * table definitions (the `/missions` opaque-extras pattern: the store writes\n * `extras` values verbatim in the SAME insert statement and never infers their\n * meaning). A product declaring a `metadata` column may use the store\n * metadata merge-patch operation; its fields remain opaque product data.\n *\n * SERVER-side module (D1/libsql/better-sqlite3 behind a worker or server\n * route) — but free of `node:` builtins on purpose: D1 workers have none.\n */\n\nimport { sql } from 'drizzle-orm'\nimport { index, integer, real, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core'\nimport type {\n AnySQLiteColumn,\n AnySQLiteTable,\n SQLiteColumnBuilderBase,\n SQLiteTableExtraConfigValue,\n} from 'drizzle-orm/sqlite-core'\nimport type { ChatMessagePart } from './parts'\n\n/** A product table referenced by FK — only the `id` column is touched. */\nexport type ChatParentTable = AnySQLiteTable & { id: AnySQLiteColumn }\n\n/** Define options to customize chat thread and message table creation including workspace and naming prefixes */\nexport interface CreateChatTablesOptions<\n TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n> {\n /** The product's workspace table — threads reference `workspaceTable.id`\n * with cascade. Omitted: `workspace_id` stays a plain indexed text column\n * (products whose tenant table lives in another database). */\n workspaceTable?: ChatParentTable\n /** Prefixes table AND index names (`'chat_'` → `chat_thread`,\n * `idx_chat_thread_workspace`) for products that namespace chat tables in a\n * shared database. Default: unprefixed `thread`/`message` (legal/gtm row\n * compatibility). */\n tablePrefix?: string\n /** Product columns merged into the thread table (the `/missions` extras\n * pattern) — e.g. a `status` lifecycle enum or gtm's scope columns. */\n threadExtraColumns?: TThreadExtras\n /** Product columns merged into the message table — e.g. legal's\n * `vault_files`. */\n messageExtraColumns?: TMessageExtras\n /**\n * Product indexes appended to the thread table's own, given the built\n * columns (extras included) so a product can index what it added.\n *\n * Names are used VERBATIM — `tablePrefix` is not applied — because these\n * have to byte-match indexes the product's migrations already created.\n *\n * Without this a product with one extra index cannot adopt the factory at\n * all: it keeps a hand-rolled duplicate of the same physical table, and the\n * two drift on the next factory change.\n */\n threadExtraIndexes?: ChatExtraIndexes\n /** Product indexes appended to the message table's own. Same rules as\n * `threadExtraIndexes`. */\n messageExtraIndexes?: ChatExtraIndexes\n}\n\n/**\n * Builds product indexes from a table's columns.\n *\n * The column map is passed untyped because its shape depends on the product's\n * own extras; the RETURN is drizzle's own extra-config type, so the spread\n * below stays inside the union `sqliteTable` expects and the built table keeps\n * its inferred column types. Returning `unknown[]` here would force a cast on\n * the config array, which widens every column to the cross-dialect union and\n * breaks `db.select()` at every call site.\n */\nexport type ChatExtraIndexes = (\n columns: Record<string, AnySQLiteColumn>,\n) => SQLiteTableExtraConfigValue[]\n\nconst hexId = () => text('id').primaryKey().default(sql`(lower(hex(randomblob(16))))`)\n\nconst createdAt = () => integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\nconst updatedAt = () => integer('updated_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\n/** Build chat-related SQLite tables with customizable thread and message columns */\nexport function createChatTables<\n TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n>(options: CreateChatTablesOptions<TThreadExtras, TMessageExtras> = {}) {\n const { workspaceTable, tablePrefix = '' } = options\n const threadExtras = options.threadExtraColumns ?? ({} as TThreadExtras)\n const messageExtras = options.messageExtraColumns ?? ({} as TMessageExtras)\n const extraIndexes = (\n build: ChatExtraIndexes | undefined,\n table: Record<string, AnySQLiteColumn>,\n ): SQLiteTableExtraConfigValue[] => build?.(table) ?? []\n\n const threads = sqliteTable(`${tablePrefix}thread`, {\n id: hexId(),\n workspaceId: workspaceTable\n ? text('workspace_id').notNull().references(() => workspaceTable.id, { onDelete: 'cascade' })\n : text('workspace_id').notNull(),\n title: text('title').notNull(),\n category: text('category'),\n isPinned: integer('is_pinned', { mode: 'boolean' }).notNull().default(false),\n createdAt: createdAt(),\n updatedAt: updatedAt(),\n ...threadExtras,\n }, (table) => [\n index(`idx_${tablePrefix}thread_workspace`).on(table.workspaceId),\n // Supports the store's list ordering (updatedAt desc within a workspace).\n index(`idx_${tablePrefix}thread_workspace_updated`).on(table.workspaceId, table.updatedAt),\n ...extraIndexes(options.threadExtraIndexes, table as unknown as Record<string, AnySQLiteColumn>),\n ])\n\n const messages = sqliteTable(`${tablePrefix}message`, {\n id: hexId(),\n threadId: text('thread_id').notNull().references(() => threads.id, { onDelete: 'cascade' }),\n role: text('role', { enum: ['user', 'assistant', 'system', 'tool'] }).notNull(),\n content: text('content').notNull(),\n parts: text('parts', { mode: 'json' }).$type<ChatMessagePart[]>().default([]),\n toolName: text('tool_name'),\n model: text('model'),\n requestedModel: text('requested_model'),\n servedModel: text('served_model'),\n servedProvider: text('served_provider'),\n servedSource: text('served_model_source'),\n // Usage receipt, flattened from the harness's `step-finish` shape\n // (`tokens {input, output, reasoning, cache{read, write}}` + `cost`).\n inputTokens: integer('input_tokens'),\n outputTokens: integer('output_tokens'),\n reasoningTokens: integer('reasoning_tokens'),\n cacheReadTokens: integer('cache_read_tokens'),\n cacheWriteTokens: integer('cache_write_tokens'),\n costUsd: real('cost_usd'),\n createdAt: createdAt(),\n ...messageExtras,\n }, (table) => [\n index(`idx_${tablePrefix}message_thread`).on(table.threadId),\n index(`idx_${tablePrefix}message_thread_created`).on(table.threadId, table.createdAt),\n ...extraIndexes(options.messageExtraIndexes, table as unknown as Record<string, AnySQLiteColumn>),\n ])\n\n return { threads, messages }\n}\n\n/**\n * Build the `thread_artifact_link` table: artifacts a thread mentioned or\n * touched beyond its own scope, inserted once on first reference. It powers a\n * thread's \"also discussed\" chips and the reverse \"which threads touched this\n * file\" lookup. `kinds` is the product's artifact-kind enum.\n */\nexport function createThreadArtifactLinksTable<const Kind extends string>(\n threadTable: ChatParentTable,\n kinds: readonly [Kind, ...Kind[]],\n) {\n return sqliteTable('thread_artifact_link', {\n id: hexId(),\n threadId: text('thread_id').notNull().references(() => threadTable.id, { onDelete: 'cascade' }),\n artifactKind: text('artifact_kind', { enum: kinds }).notNull(),\n artifactKey: text('artifact_key').notNull(),\n firstReferencedAt: integer('first_referenced_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),\n }, (table) => [\n index('idx_thread_artifact_link_thread').on(table.threadId),\n uniqueIndex('idx_thread_artifact_link_unique').on(table.threadId, table.artifactKind, table.artifactKey),\n index('idx_thread_artifact_link_reverse').on(table.artifactKind, table.artifactKey),\n ])\n}\n\n/**\n * Build the `agent_run` table: one row per agent run in a workspace, with the\n * product's run telemetry as JSON `metadata`. `idx_agent_run_workspace` covers\n * `(workspace_id, agent_id)`, or `workspace_id` alone with `indexAgentId: false`\n * for products whose migration created it that way.\n */\nexport function createAgentRunsTable<Metadata = Record<string, unknown>>(\n workspaceTable: ChatParentTable,\n options: { indexAgentId?: boolean } = {},\n) {\n return sqliteTable('agent_run', {\n id: hexId(),\n workspaceId: text('workspace_id').notNull().references(() => workspaceTable.id, { onDelete: 'cascade' }),\n agentId: text('agent_id').notNull(),\n status: text('status', { enum: ['running', 'completed', 'failed'] }).notNull().default('running'),\n success: integer('success', { mode: 'boolean' }).notNull().default(true),\n resultSummary: text('result_summary'),\n metadata: text('metadata', { mode: 'json' }).$type<Metadata>(),\n startedAt: integer('started_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),\n completedAt: integer('completed_at', { mode: 'timestamp' }),\n }, (table) => [\n options.indexAgentId === false\n ? index('idx_agent_run_workspace').on(table.workspaceId)\n : index('idx_agent_run_workspace').on(table.workspaceId, table.agentId),\n ])\n}\n\n/**\n * The base (no-extras) table pair, pinned via an instantiation expression:\n * `ReturnType<typeof createChatTables>` on the bare generic substitutes the\n * extras params with their CONSTRAINT (`Record<string,\n * SQLiteColumnBuilderBase>`), stamping an index signature into the column map\n * that widens every concrete column to `unknown`/`notNull: false` — concrete\n * factory results then fail `extends ChatTables`. (`teams`' `createTeamTables`\n * is non-generic, so its plain `ReturnType` never hits this.)\n */\nexport type ChatTables = ReturnType<typeof createChatTables<{}, {}>>\n\n/** Resolve the selected fields of a chat thread row from the chat threads table */\nexport type ChatThreadRow = ChatTables['threads']['$inferSelect']\n/** Resolve the selected structure of a chat message row from the messages table */\nexport type ChatMessageRow = ChatTables['messages']['$inferSelect']\n/** Resolve the type for inserting a new chat thread row into the threads table */\nexport type NewChatThreadRow = ChatTables['threads']['$inferInsert']\n/** Resolve the type for inserting a new chat message row into the messages table */\nexport type NewChatMessageRow = ChatTables['messages']['$inferInsert']\n","/**\n * Typed CRUD over the tables from `createChatTables`. Works against any\n * SQLite drizzle driver (D1, libsql, better-sqlite3) — builders are awaited,\n * never `.run()`/`.all()`, so sync and async drivers behave identically.\n *\n * Access control is an injected seam, never an import: single-thread routes\n * check workspace access themselves (they know the thread), while\n * `bulkDeleteThreads` REQUIRES an `assertAccess` callback because one request\n * can span workspaces — it is called once per distinct workspace and any\n * throw rejects the whole request before a single delete runs (fail-closed;\n * legal's bulk-delete semantics).\n *\n * Deletes run messages-first in ONE `db.batch` round trip when the driver has\n * one (D1, libsql), so a partial failure never leaves orphaned rows behind a\n * deleted thread; drivers without `batch` (better-sqlite3) fall back to\n * sequential awaits in the same order.\n */\n\nimport { and, asc, desc, eq, getTableColumns, gte, inArray, lt, sql, type SQL } from 'drizzle-orm'\nimport type { AnySQLiteColumn, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport {\n runSqliteStatements,\n type SqliteBatchDatabase,\n} from '../store'\nimport { type ChatMessageValues, BULK_DELETE_MAX_THREADS, ChatStoreInputError, threadTitleFromMessage } from './core'\nimport type { ChatMessageRow, ChatTables, ChatThreadRow, NewChatMessageRow, NewChatThreadRow } from './schema'\n\n/** Any SQLite drizzle database — `any` erases the driver-specific run-result\n * and schema generics so better-sqlite3, D1, and libsql handles all fit.\n * `batch` is structural: present on D1/libsql drizzle instances. */\nexport type ChatDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any> &\n SqliteBatchDatabase\n\n/** Product-injected access check. Throw to deny; the store never interprets\n * users or roles itself. */\nexport type WorkspaceAccessCheck = (workspaceId: string) => void | Promise<void>\n\n/** Define input parameters for listing threads within a workspace with pagination options */\nexport interface ListThreadsInput {\n workspaceId: string\n /** Clamped to 1..200; default 50 (legal's list route semantics). */\n limit?: number\n /** Clamped to >= 0; default 0. */\n offset?: number\n}\n\n/** Represent a paginated collection of chat threads with total count and pagination details */\nexport interface ListThreadsResult<TThread = ChatThreadRow> {\n threads: TThread[]\n total: number\n limit: number\n offset: number\n}\n\n/** Define input parameters required to create a new thread in a workspace */\nexport interface CreateThreadInput {\n /** Caller-assigned primary key. The agent gateway uses its validated\n * conversation id so API and browser turns share one durable thread. */\n id?: string\n workspaceId: string\n /** Title source when `title` is absent: first non-empty line, 80-char cap\n * (`threadTitleFromMessage`). */\n firstMessage?: string\n /** Explicit title; still normalized through `threadTitleFromMessage` so a\n * multi-page paste never becomes a sidebar entry. */\n title?: string\n category?: string | null\n isPinned?: boolean\n /** Opaque product-column values written verbatim in the SAME insert (the\n * `/missions` extras pattern). Never read, validated, or defaulted here. */\n extras?: Record<string, unknown>\n}\n\n/** Define input parameters for appending a message to a chat thread with optional metadata */\nexport interface AppendMessageInput extends ChatMessageValues {\n /** Caller-assigned primary key. Omitted, the column default assigns a random\n * hex id (today's behavior). Incremental assistant persistence passes a\n * DETERMINISTIC id derived from the turn's own identity, so a re-entered\n * turn (crashed worker, durable-driver retry) finds and updates the row a\n * previous attempt started instead of inserting a second one. */\n id?: string\n threadId: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n toolName?: string | null\n /** Opaque product-column values written verbatim in the SAME insert. */\n extras?: Record<string, unknown>\n}\n\n/** Fields an existing message row may be patched with. Every field is\n * optional and only DEFINED fields are written, so a partial patch never\n * clears a column it does not mention. `threadId` and `role` are absent on\n * purpose: a message never moves thread or changes speaker.\n *\n * Exists for incremental assistant persistence — the streaming turn writes\n * the row once and then patches it as content accumulates, so the durable\n * transcript is at most one cadence interval behind the live stream. */\nexport interface UpdateMessageInput extends Partial<ChatMessageValues> {\n toolName?: string | null\n /** Opaque product-column values written verbatim in the SAME update. */\n extras?: Record<string, unknown>\n}\n\n/** Define options to configure message listing with optional limit and offset parameters */\nexport interface ListMessagesOptions {\n limit?: number\n offset?: number\n}\n\n/** Define input for bulk deleting threads with access checks per workspace */\nexport interface BulkDeleteThreadsInput {\n ids: string[]\n /** Optional single-workspace fence for products whose route already resolved\n * one active workspace. Omitted preserves the multi-workspace legal route. */\n workspaceId?: string\n /** Called once per distinct workspace the ids touch, before ANY delete. */\n assertAccess: WorkspaceAccessCheck\n}\n\n/** Delete threads selected by their last activity time within one workspace.\n *\n * Products can add a lifecycle predicate such as `status = 'active'` through\n * `where`; the store still owns workspace scope, access ordering, and message\n * cleanup for every consumer. */\nexport interface BulkDeleteThreadsByUpdatedAtInput {\n workspaceId: string\n /** Exclusive upper bound: rows older than this instant. */\n updatedBefore?: Date\n /** Inclusive lower bound: rows updated at or after this instant. */\n updatedAfter?: Date\n where?: SQL\n /** Called before any delete for the requested workspace. */\n assertAccess: WorkspaceAccessCheck\n}\n\n/** Manage chat threads and messages with operations for listing, creating, updating, and deleting data */\nexport interface ChatStore<TThread = ChatThreadRow, TMessage = ChatMessageRow> {\n listThreads(input: ListThreadsInput): Promise<ListThreadsResult<TThread>>\n getThread(threadId: string): Promise<TThread | null>\n createThread(input: CreateThreadInput): Promise<TThread>\n renameThread(threadId: string, title: string): Promise<TThread | null>\n pinThread(threadId: string, isPinned: boolean): Promise<TThread | null>\n /** Messages + thread in one batch. Resolves false when the thread does not\n * exist. `assertAccess` (optional) receives the thread's workspaceId before\n * the delete — single-thread callers usually check access themselves. */\n deleteThread(threadId: string, options?: { assertAccess?: WorkspaceAccessCheck }): Promise<boolean>\n bulkDeleteThreads(input: BulkDeleteThreadsInput): Promise<{ deleted: number }>\n bulkDeleteThreadsByUpdatedAt(input: BulkDeleteThreadsByUpdatedAtInput): Promise<{ deleted: number }>\n /** Ordered oldest-first: `created_at`, then rowid (insertion order within a\n * same-second burst — a user+assistant pair lands in one epoch second). */\n listMessages(threadId: string, options?: ListMessagesOptions): Promise<TMessage[]>\n getMessage(id: string): Promise<TMessage | null>\n /** Atomic JSON Merge Patch for a product-declared metadata column. Null removes keys;\n * expected top-level fields fence the update against another attempt. Opaque values stay product-owned. */\n patchMessageMetadata(id: string, mergePatch: Record<string, unknown>, expected?: { fields: Record<string, unknown> } | { snapshot: Record<string, unknown> }): Promise<TMessage | null>\n /** Inserts the message and bumps the thread's `updatedAt` in one batch so\n * workspace recency sorts stay truthful. */\n appendMessage(input: AppendMessageInput): Promise<TMessage>\n /** Patches an existing message and bumps its thread's `updatedAt` in the\n * same batch. Resolves `null` when the id does not exist. Only defined\n * patch fields are written. */\n updateMessage(id: string, patch: UpdateMessageInput): Promise<TMessage | null>\n /** Removes one message. Resolves false when the id does not exist. Used by\n * incremental persistence to retract a draft row for a turn that ended\n * producing nothing, so an empty assistant row is never left behind. */\n deleteMessage(id: string): Promise<boolean>\n}\n\nfunction clampLimit(limit: number | undefined, fallback: number, max: number): number {\n const value = Number.isFinite(limit) ? Math.trunc(limit as number) : fallback\n return Math.min(Math.max(value, 1), max)\n}\n\nfunction clampOffset(offset: number | undefined): number {\n const value = Number.isFinite(offset) ? Math.trunc(offset as number) : 0\n return Math.max(value, 0)\n}\n\n/** Create a chat store managing threads and messages based on the provided database and tables */\nexport function createChatStore<TTables extends ChatTables>(\n db: ChatDatabase,\n tables: TTables,\n): ChatStore<TTables['threads']['$inferSelect'], TTables['messages']['$inferSelect']> {\n type TThread = TTables['threads']['$inferSelect']\n type TMessage = TTables['messages']['$inferSelect']\n const threads = tables.threads as ChatTables['threads']\n const messages = tables.messages as ChatTables['messages']\n\n return {\n async listThreads(input) {\n const limit = clampLimit(input.limit, 50, 200)\n const offset = clampOffset(input.offset)\n const scope = eq(threads.workspaceId, input.workspaceId)\n const [list, [countRow]] = await Promise.all([\n db.select().from(threads).where(scope)\n // `id` tiebreak keeps pagination stable across same-second updates.\n .orderBy(desc(threads.updatedAt), asc(threads.id))\n .limit(limit)\n .offset(offset),\n db.select({ total: sql<number>`count(*)` }).from(threads).where(scope),\n ])\n return { threads: list as TThread[], total: countRow?.total ?? 0, limit, offset }\n },\n\n async getThread(threadId) {\n const [row] = await db.select().from(threads).where(eq(threads.id, threadId)).limit(1)\n return (row as TThread | undefined) ?? null\n },\n\n async createThread(input) {\n const title = threadTitleFromMessage(input.title ?? input.firstMessage ?? '')\n const values = {\n ...(input.id !== undefined ? { id: input.id } : {}),\n workspaceId: input.workspaceId,\n title,\n ...(input.category !== undefined ? { category: input.category } : {}),\n ...(input.isPinned !== undefined ? { isPinned: input.isPinned } : {}),\n ...(input.extras ?? {}),\n } as NewChatThreadRow\n const [row] = await db.insert(threads).values(values).returning()\n if (!row) throw new Error('thread insert returned no row')\n return row as TThread\n },\n\n async renameThread(threadId, title) {\n const trimmed = title.trim()\n if (!trimmed) throw new ChatStoreInputError('Missing title')\n const [row] = await db.update(threads)\n .set({ title: trimmed, updatedAt: new Date() })\n .where(eq(threads.id, threadId))\n .returning()\n return (row as TThread | undefined) ?? null\n },\n\n async pinThread(threadId, isPinned) {\n const [row] = await db.update(threads)\n .set({ isPinned, updatedAt: new Date() })\n .where(eq(threads.id, threadId))\n .returning()\n return (row as TThread | undefined) ?? null\n },\n\n async deleteThread(threadId, options) {\n const [existing] = await db.select({ id: threads.id, workspaceId: threads.workspaceId })\n .from(threads)\n .where(eq(threads.id, threadId))\n .limit(1)\n if (!existing) return false\n if (options?.assertAccess) await options.assertAccess(existing.workspaceId)\n // Messages first so a partial failure never leaves orphaned rows behind\n // a deleted thread.\n await runSqliteStatements(db, [\n db.delete(messages).where(eq(messages.threadId, threadId)),\n db.delete(threads).where(eq(threads.id, threadId)),\n ])\n return true\n },\n\n async bulkDeleteThreads(input) {\n const { ids, workspaceId, assertAccess } = input\n if (typeof assertAccess !== 'function') throw new ChatStoreInputError('Missing assertAccess')\n if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === 'string' && id.length > 0)) {\n throw new ChatStoreInputError('Missing ids')\n }\n if (ids.length > BULK_DELETE_MAX_THREADS) {\n throw new ChatStoreInputError(`Too many ids (max ${BULK_DELETE_MAX_THREADS})`)\n }\n if (workspaceId !== undefined && !workspaceId.trim()) {\n throw new ChatStoreInputError('Invalid workspaceId')\n }\n\n const scope = workspaceId\n ? and(inArray(threads.id, ids), eq(threads.workspaceId, workspaceId))\n : inArray(threads.id, ids)\n const rows = await db.select({ id: threads.id, workspaceId: threads.workspaceId })\n .from(threads)\n .where(scope)\n if (rows.length === 0) return { deleted: 0 }\n\n // Access is verified once per workspace the ids touch. Fail-closed: one\n // inaccessible workspace rejects the whole request before any delete.\n // Sorted so the check order (and therefore which denial surfaces) is\n // deterministic — row order follows random hex ids and varies per run.\n const workspaceIds = [...new Set(rows.map((row) => row.workspaceId))].sort()\n for (const workspaceId of workspaceIds) {\n await assertAccess(workspaceId)\n }\n\n const foundIds = rows.map((row) => row.id)\n await runSqliteStatements(db, [\n db.delete(messages).where(inArray(messages.threadId, foundIds)),\n db.delete(threads).where(inArray(threads.id, foundIds)),\n ])\n return { deleted: foundIds.length }\n },\n\n async bulkDeleteThreadsByUpdatedAt(input) {\n const { workspaceId, updatedBefore, updatedAfter, where, assertAccess } = input\n if (typeof assertAccess !== 'function') throw new ChatStoreInputError('Missing assertAccess')\n if (!workspaceId.trim()) throw new ChatStoreInputError('Missing workspaceId')\n if (updatedBefore === undefined && updatedAfter === undefined) {\n throw new ChatStoreInputError('Missing updatedAt boundary')\n }\n for (const boundary of [updatedBefore, updatedAfter]) {\n if (boundary !== undefined && Number.isNaN(boundary.getTime())) {\n throw new ChatStoreInputError('Invalid updatedAt boundary')\n }\n }\n\n const conditions = [eq(threads.workspaceId, workspaceId)]\n if (updatedBefore) conditions.push(lt(threads.updatedAt, updatedBefore))\n if (updatedAfter) conditions.push(gte(threads.updatedAt, updatedAfter))\n if (where) conditions.push(where)\n const scope = and(...conditions)\n const [countRow] = await db.select({ total: sql<number>`count(*)` })\n .from(threads)\n .where(scope)\n const deleted = Number(countRow?.total ?? 0)\n if (deleted === 0) return { deleted: 0 }\n\n await assertAccess(workspaceId)\n // Keep the age path unbounded without constructing a giant host-parameter\n // list; the subquery lets SQLite/D1 stream the matching thread ids.\n const matchingThreads = db.select({ id: threads.id }).from(threads).where(scope)\n await runSqliteStatements(db, [\n db.delete(messages).where(inArray(messages.threadId, matchingThreads)),\n db.delete(threads).where(scope),\n ])\n return { deleted }\n },\n\n async listMessages(threadId, options) {\n const query = db.select().from(messages)\n .where(eq(messages.threadId, threadId))\n .orderBy(asc(messages.createdAt), sql`rowid`)\n .$dynamic()\n if (options?.limit !== undefined) query.limit(clampLimit(options.limit, 1, 1000))\n if (options?.offset !== undefined) query.offset(clampOffset(options.offset))\n return await query as TMessage[]\n },\n\n async getMessage(id) {\n const [row] = await db.select().from(messages).where(eq(messages.id, id)).limit(1)\n return (row as TMessage | undefined) ?? null\n },\n\n async patchMessageMetadata(id, mergePatch, expected) {\n const metadata = (getTableColumns(tables.messages) as Record<string, AnySQLiteColumn>).metadata\n if (!metadata) throw new Error('Chat metadata requires a product-declared metadata column')\n const guards = Object.entries(expected && 'fields' in expected ? expected.fields : {}).map(([field, value]) => {\n const encoded = JSON.stringify(value)\n if (encoded === undefined) throw new Error('Expected chat metadata must be JSON')\n return sql`json_extract(${metadata}, ${`$.${JSON.stringify(field)}`}) IS json_extract(${encoded}, '$')`\n })\n if (expected && 'snapshot' in expected) guards.push(sql`coalesce(${metadata}, '{}') = ${JSON.stringify(expected.snapshot)}`)\n const [row] = await db.update(messages).set({\n metadata: sql`json_patch(coalesce(${metadata}, '{}'), ${JSON.stringify(mergePatch)})`,\n } as Partial<NewChatMessageRow>).where(and(eq(messages.id, id), ...guards)).returning()\n return (row as TMessage | undefined) ?? null\n },\n\n async appendMessage(input) {\n const values = {\n ...(input.id !== undefined ? { id: input.id } : {}),\n threadId: input.threadId,\n role: input.role,\n content: input.content,\n ...(input.parts !== undefined ? { parts: input.parts } : {}),\n ...(input.toolName !== undefined ? { toolName: input.toolName } : {}),\n ...(input.model !== undefined ? { model: input.model } : {}),\n ...(input.requestedModel !== undefined ? { requestedModel: input.requestedModel } : {}),\n ...(input.servedModel !== undefined ? { servedModel: input.servedModel } : {}),\n ...(input.servedProvider !== undefined ? { servedProvider: input.servedProvider } : {}),\n ...(input.servedSource !== undefined ? { servedSource: input.servedSource } : {}),\n ...(input.inputTokens !== undefined ? { inputTokens: input.inputTokens } : {}),\n ...(input.outputTokens !== undefined ? { outputTokens: input.outputTokens } : {}),\n ...(input.reasoningTokens !== undefined ? { reasoningTokens: input.reasoningTokens } : {}),\n ...(input.cacheReadTokens !== undefined ? { cacheReadTokens: input.cacheReadTokens } : {}),\n ...(input.cacheWriteTokens !== undefined ? { cacheWriteTokens: input.cacheWriteTokens } : {}),\n ...(input.costUsd !== undefined ? { costUsd: input.costUsd } : {}),\n ...(input.extras ?? {}),\n } as NewChatMessageRow\n const [insertResult] = await runSqliteStatements(db, [\n db.insert(messages).values(values).returning(),\n db.update(threads).set({ updatedAt: new Date() }).where(eq(threads.id, input.threadId)),\n ])\n const row = (insertResult as TMessage[] | undefined)?.[0]\n if (!row) throw new Error('message insert returned no row')\n return row\n },\n\n async updateMessage(id, patch) {\n const values = {\n ...(patch.content !== undefined ? { content: patch.content } : {}),\n ...(patch.parts !== undefined ? { parts: patch.parts } : {}),\n ...(patch.toolName !== undefined ? { toolName: patch.toolName } : {}),\n ...(patch.model !== undefined ? { model: patch.model } : {}),\n ...(patch.requestedModel !== undefined ? { requestedModel: patch.requestedModel } : {}),\n ...(patch.servedModel !== undefined ? { servedModel: patch.servedModel } : {}),\n ...(patch.servedProvider !== undefined ? { servedProvider: patch.servedProvider } : {}),\n ...(patch.servedSource !== undefined ? { servedSource: patch.servedSource } : {}),\n ...(patch.inputTokens !== undefined ? { inputTokens: patch.inputTokens } : {}),\n ...(patch.outputTokens !== undefined ? { outputTokens: patch.outputTokens } : {}),\n ...(patch.reasoningTokens !== undefined ? { reasoningTokens: patch.reasoningTokens } : {}),\n ...(patch.cacheReadTokens !== undefined ? { cacheReadTokens: patch.cacheReadTokens } : {}),\n ...(patch.cacheWriteTokens !== undefined ? { cacheWriteTokens: patch.cacheWriteTokens } : {}),\n ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd } : {}),\n ...(patch.extras ?? {}),\n }\n if (Object.keys(values).length === 0) {\n const [current] = await db.select().from(messages).where(eq(messages.id, id))\n return (current as TMessage | undefined) ?? null\n }\n // The thread bump reads the row's own `thread_id` rather than trusting a\n // caller-supplied one: a message never moves thread, so the subquery is\n // the authoritative source and one fewer parameter to get wrong.\n const [updateResult] = await runSqliteStatements(db, [\n db.update(messages).set(values).where(eq(messages.id, id)).returning(),\n db.update(threads).set({ updatedAt: new Date() })\n .where(eq(threads.id, sql`(select ${messages.threadId} from ${messages} where ${messages.id} = ${id})`)),\n ])\n return (updateResult as TMessage[] | undefined)?.[0] ?? null\n },\n\n async deleteMessage(id) {\n const deleted = await db.delete(messages).where(eq(messages.id, id)).returning()\n return (deleted as unknown[]).length > 0\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,IAAM,0BAA0B;AAIhC,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAKO,SAAS,uBAAuB,SAAyB;AAC9D,QAAM,YAAY,QAAQ,MAAM,IAAI,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,KAAK,KAAK;AAClF,MAAI,CAAC,UAAW,QAAO;AACvB,SAAO,UAAU,SAAS,KAAK,GAAG,UAAU,MAAM,GAAG,EAAE,CAAC,WAAM;AAChE;;;ACUA,SAAS,WAAW;AACpB,SAAS,OAAO,SAAS,MAAM,aAAa,MAAM,mBAAmB;AA+DrE,IAAM,QAAQ,MAAM,KAAK,IAAI,EAAE,WAAW,EAAE,QAAQ,iCAAiC;AAErF,IAAM,YAAY,MAAM,QAAQ,cAAc,EAAE,MAAM,YAAY,CAAC,EAAE,QAAQ,EAAE,QAAQ,kBAAkB;AAEzG,IAAM,YAAY,MAAM,QAAQ,cAAc,EAAE,MAAM,YAAY,CAAC,EAAE,QAAQ,EAAE,QAAQ,kBAAkB;AAGlG,SAAS,iBAGd,UAAkE,CAAC,GAAG;AACtE,QAAM,EAAE,gBAAgB,cAAc,GAAG,IAAI;AAC7C,QAAM,eAAe,QAAQ,sBAAuB,CAAC;AACrD,QAAM,gBAAgB,QAAQ,uBAAwB,CAAC;AACvD,QAAM,eAAe,CACnB,OACA,UACkC,QAAQ,KAAK,KAAK,CAAC;AAEvD,QAAM,UAAU,YAAY,GAAG,WAAW,UAAU;AAAA,IAClD,IAAI,MAAM;AAAA,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AA,EACF;AACF;","names":["sql","sql","workspaceId"]}
|
|
1
|
+
{"version":3,"sources":["../../src/chat-store/core.ts","../../src/chat-store/schema.ts","../../src/chat-store/store.ts"],"sourcesContent":["/**\n * Pure (drizzle-free) pieces of the chat store: thread-title derivation, the\n * bulk-delete bound, message-write contract, and typed input error. Split from\n * `./schema`/`./store`\n * so the root barrel can re-export them without dragging the optional\n * drizzle-orm peer into every root-entry consumer.\n */\n\nimport type { ChatMessagePart } from './parts'\n\n/** Bounds a single bulk-delete request's write set; product surfaces cap\n * thread lists at far fewer, so a larger batch is a malformed or hostile\n * request. (Lifted from legal's api.threads.bulk-delete route.) */\nexport const BULK_DELETE_MAX_THREADS = 200\n\n/** Invalid caller input (missing/oversized ids, empty title). Products map it\n * to a 400; anything else out of the store is a real failure. */\nexport class ChatStoreInputError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ChatStoreInputError'\n }\n}\n\n/** Thread titles come from the first message — keep the list scannable by\n * storing only its first non-empty line, capped at 80 chars, never the whole\n * multi-page prompt. (Lifted verbatim from legal's chat.new route.) */\nexport function threadTitleFromMessage(message: string): string {\n const firstLine = message.split('\\n').find((l) => l.trim().length > 0)?.trim() ?? ''\n if (!firstLine) return 'New Thread'\n return firstLine.length > 80 ? `${firstLine.slice(0, 79)}…` : firstLine\n}\n\n/** Stored message body, model attribution and usage shared by append and patch adapters. */\nexport type ChatMessageValues = {\n content: string\n parts?: ChatMessagePart[]\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n /** Platform ledger charge; `harnessCostUsd` is the harness's own reported token cost. */\n costUsd?: number | null\n harnessCostUsd?: number | null\n}\n","/**\n * Drizzle schema factory for the chat thread/message tables — the same\n * injection pattern as `createTeamTables`: the product owns the workspace\n * table; the factory wires the thread FK into it so the whole graph lives in\n * one drizzle schema with real cascade semantics. Column names, types,\n * defaults, enums, and indexes mirror legal's and gtm's hand-rolled `thread`/\n * `message` tables so a product with those tables adopts the factory without\n * rewriting rows; `tablePrefix` covers products that namespace (tax's\n * `chat_messages` style).\n *\n * The core is the superset the three products agree on. Divergences dropped,\n * and why:\n * - `thread.status` ('active'|'archived', legal+gtm) — archive semantics\n * diverge (tax uses `archivedAt`); product-domain lifecycle → extra column.\n * - `thread.scopeKind`/`scopeKey`/`harness` (gtm) — artifact anchoring and\n * harness pinning are product-domain → extra columns.\n * - tax's `tax_sessions` session columns (`taxYear`, `projectRef`,\n * `agentSessionId`, `agentRuntime`, `agentHarness`, `profile`, `error`,\n * `userId`) — sandbox-session state, not chat state → extra columns.\n * - `message.toolInput`/`toolOutput` (legal+gtm) — duplicate of the tool\n * part's `state.input`/`state.output` inside `parts` (the shape `/stream`'s\n * `normalizePersistedPart` owns); keeping both invites drift.\n * - `message.vaultFiles` (legal+gtm) — vault is product-domain → extra column.\n * - tax's re-declared `turn_events`/`turn_status` DDL — deliberately NOT here;\n * `/stream`'s turn-buffer owns that DDL (`TURN_BUFFER_D1_SCHEMA_SQL`).\n *\n * Kept beyond the intersection: tax's per-message `model`/`inputTokens`/\n * `outputTokens`, extended to the full usage receipt the harness actually\n * reports in `step-finish` parts (`tokens {input, output, reasoning,\n * cache{read, write}}` + `cost`) — see `./parts`.\n *\n * `threadExtraColumns`/`messageExtraColumns` merge product columns into the\n * table definitions (the `/missions` opaque-extras pattern: the store writes\n * `extras` values verbatim in the SAME insert statement and never infers their\n * meaning). A product declaring a `metadata` column may use the store\n * metadata merge-patch operation; its fields remain opaque product data.\n *\n * SERVER-side module (D1/libsql/better-sqlite3 behind a worker or server\n * route) — but free of `node:` builtins on purpose: D1 workers have none.\n */\n\nimport { sql } from 'drizzle-orm'\nimport { index, integer, real, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core'\nimport type {\n AnySQLiteColumn,\n AnySQLiteTable,\n SQLiteColumnBuilderBase,\n SQLiteTableExtraConfigValue,\n} from 'drizzle-orm/sqlite-core'\nimport type { ChatMessagePart } from './parts'\n\n/** A product table referenced by FK — only the `id` column is touched. */\nexport type ChatParentTable = AnySQLiteTable & { id: AnySQLiteColumn }\n\n/** Define options to customize chat thread and message table creation including workspace and naming prefixes */\nexport interface CreateChatTablesOptions<\n TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n> {\n /** The product's workspace table — threads reference `workspaceTable.id`\n * with cascade. Omitted: `workspace_id` stays a plain indexed text column\n * (products whose tenant table lives in another database). */\n workspaceTable?: ChatParentTable\n /** Prefixes table AND index names (`'chat_'` → `chat_thread`,\n * `idx_chat_thread_workspace`) for products that namespace chat tables in a\n * shared database. Default: unprefixed `thread`/`message` (legal/gtm row\n * compatibility). */\n tablePrefix?: string\n /** Product columns merged into the thread table (the `/missions` extras\n * pattern) — e.g. a `status` lifecycle enum or gtm's scope columns. */\n threadExtraColumns?: TThreadExtras\n /** Product columns merged into the message table — e.g. legal's\n * `vault_files`. */\n messageExtraColumns?: TMessageExtras\n /**\n * Product indexes appended to the thread table's own, given the built\n * columns (extras included) so a product can index what it added.\n *\n * Names are used VERBATIM — `tablePrefix` is not applied — because these\n * have to byte-match indexes the product's migrations already created.\n *\n * Without this a product with one extra index cannot adopt the factory at\n * all: it keeps a hand-rolled duplicate of the same physical table, and the\n * two drift on the next factory change.\n */\n threadExtraIndexes?: ChatExtraIndexes\n /** Product indexes appended to the message table's own. Same rules as\n * `threadExtraIndexes`. */\n messageExtraIndexes?: ChatExtraIndexes\n}\n\n/**\n * Builds product indexes from a table's columns.\n *\n * The column map is passed untyped because its shape depends on the product's\n * own extras; the RETURN is drizzle's own extra-config type, so the spread\n * below stays inside the union `sqliteTable` expects and the built table keeps\n * its inferred column types. Returning `unknown[]` here would force a cast on\n * the config array, which widens every column to the cross-dialect union and\n * breaks `db.select()` at every call site.\n */\nexport type ChatExtraIndexes = (\n columns: Record<string, AnySQLiteColumn>,\n) => SQLiteTableExtraConfigValue[]\n\n/**\n * The optional `harness_cost_usd` message column: spread into\n * `messageExtraColumns` once the table has it. The store writes and reads the\n * harness's own token cost only when the table declares it, so a table without\n * the column keeps working.\n */\nexport const harnessCostColumns = () => ({ harnessCostUsd: real('harness_cost_usd') })\n\nconst hexId = () => text('id').primaryKey().default(sql`(lower(hex(randomblob(16))))`)\n\nconst createdAt = () => integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\nconst updatedAt = () => integer('updated_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\n/** Build chat-related SQLite tables with customizable thread and message columns */\nexport function createChatTables<\n TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n>(options: CreateChatTablesOptions<TThreadExtras, TMessageExtras> = {}) {\n const { workspaceTable, tablePrefix = '' } = options\n const threadExtras = options.threadExtraColumns ?? ({} as TThreadExtras)\n const messageExtras = options.messageExtraColumns ?? ({} as TMessageExtras)\n const extraIndexes = (\n build: ChatExtraIndexes | undefined,\n table: Record<string, AnySQLiteColumn>,\n ): SQLiteTableExtraConfigValue[] => build?.(table) ?? []\n\n const threads = sqliteTable(`${tablePrefix}thread`, {\n id: hexId(),\n workspaceId: workspaceTable\n ? text('workspace_id').notNull().references(() => workspaceTable.id, { onDelete: 'cascade' })\n : text('workspace_id').notNull(),\n title: text('title').notNull(),\n category: text('category'),\n isPinned: integer('is_pinned', { mode: 'boolean' }).notNull().default(false),\n createdAt: createdAt(),\n updatedAt: updatedAt(),\n ...threadExtras,\n }, (table) => [\n index(`idx_${tablePrefix}thread_workspace`).on(table.workspaceId),\n // Supports the store's list ordering (updatedAt desc within a workspace).\n index(`idx_${tablePrefix}thread_workspace_updated`).on(table.workspaceId, table.updatedAt),\n ...extraIndexes(options.threadExtraIndexes, table as unknown as Record<string, AnySQLiteColumn>),\n ])\n\n const messages = sqliteTable(`${tablePrefix}message`, {\n id: hexId(),\n threadId: text('thread_id').notNull().references(() => threads.id, { onDelete: 'cascade' }),\n role: text('role', { enum: ['user', 'assistant', 'system', 'tool'] }).notNull(),\n content: text('content').notNull(),\n parts: text('parts', { mode: 'json' }).$type<ChatMessagePart[]>().default([]),\n toolName: text('tool_name'),\n model: text('model'),\n requestedModel: text('requested_model'),\n servedModel: text('served_model'),\n servedProvider: text('served_provider'),\n servedSource: text('served_model_source'),\n // Usage receipt, flattened from the harness's `step-finish` shape\n // (`tokens {input, output, reasoning, cache{read, write}}`); `cost_usd` is the\n // Platform ledger charge. The harness's `cost` needs `harnessCostColumns()`.\n inputTokens: integer('input_tokens'),\n outputTokens: integer('output_tokens'),\n reasoningTokens: integer('reasoning_tokens'),\n cacheReadTokens: integer('cache_read_tokens'),\n cacheWriteTokens: integer('cache_write_tokens'),\n costUsd: real('cost_usd'),\n createdAt: createdAt(),\n ...messageExtras,\n }, (table) => [\n index(`idx_${tablePrefix}message_thread`).on(table.threadId),\n index(`idx_${tablePrefix}message_thread_created`).on(table.threadId, table.createdAt),\n ...extraIndexes(options.messageExtraIndexes, table as unknown as Record<string, AnySQLiteColumn>),\n ])\n\n return { threads, messages }\n}\n\n/**\n * Build the `thread_artifact_link` table: artifacts a thread mentioned or\n * touched beyond its own scope, inserted once on first reference. It powers a\n * thread's \"also discussed\" chips and the reverse \"which threads touched this\n * file\" lookup. `kinds` is the product's artifact-kind enum.\n */\nexport function createThreadArtifactLinksTable<const Kind extends string>(\n threadTable: ChatParentTable,\n kinds: readonly [Kind, ...Kind[]],\n) {\n return sqliteTable('thread_artifact_link', {\n id: hexId(),\n threadId: text('thread_id').notNull().references(() => threadTable.id, { onDelete: 'cascade' }),\n artifactKind: text('artifact_kind', { enum: kinds }).notNull(),\n artifactKey: text('artifact_key').notNull(),\n firstReferencedAt: integer('first_referenced_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),\n }, (table) => [\n index('idx_thread_artifact_link_thread').on(table.threadId),\n uniqueIndex('idx_thread_artifact_link_unique').on(table.threadId, table.artifactKind, table.artifactKey),\n index('idx_thread_artifact_link_reverse').on(table.artifactKind, table.artifactKey),\n ])\n}\n\n/**\n * Build the `agent_run` table: one row per agent run in a workspace, with the\n * product's run telemetry as JSON `metadata`. `idx_agent_run_workspace` covers\n * `(workspace_id, agent_id)`, or `workspace_id` alone with `indexAgentId: false`\n * for products whose migration created it that way.\n */\nexport function createAgentRunsTable<Metadata = Record<string, unknown>>(\n workspaceTable: ChatParentTable,\n options: { indexAgentId?: boolean } = {},\n) {\n return sqliteTable('agent_run', {\n id: hexId(),\n workspaceId: text('workspace_id').notNull().references(() => workspaceTable.id, { onDelete: 'cascade' }),\n agentId: text('agent_id').notNull(),\n status: text('status', { enum: ['running', 'completed', 'failed'] }).notNull().default('running'),\n success: integer('success', { mode: 'boolean' }).notNull().default(true),\n resultSummary: text('result_summary'),\n metadata: text('metadata', { mode: 'json' }).$type<Metadata>(),\n startedAt: integer('started_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),\n completedAt: integer('completed_at', { mode: 'timestamp' }),\n }, (table) => [\n options.indexAgentId === false\n ? index('idx_agent_run_workspace').on(table.workspaceId)\n : index('idx_agent_run_workspace').on(table.workspaceId, table.agentId),\n ])\n}\n\n/**\n * The base (no-extras) table pair, pinned via an instantiation expression:\n * `ReturnType<typeof createChatTables>` on the bare generic substitutes the\n * extras params with their CONSTRAINT (`Record<string,\n * SQLiteColumnBuilderBase>`), stamping an index signature into the column map\n * that widens every concrete column to `unknown`/`notNull: false` — concrete\n * factory results then fail `extends ChatTables`. (`teams`' `createTeamTables`\n * is non-generic, so its plain `ReturnType` never hits this.)\n */\nexport type ChatTables = ReturnType<typeof createChatTables<{}, {}>>\n\n/** Resolve the selected fields of a chat thread row from the chat threads table */\nexport type ChatThreadRow = ChatTables['threads']['$inferSelect']\n/** Resolve the selected structure of a chat message row from the messages table */\nexport type ChatMessageRow = ChatTables['messages']['$inferSelect']\n/** Resolve the type for inserting a new chat thread row into the threads table */\nexport type NewChatThreadRow = ChatTables['threads']['$inferInsert']\n/** Resolve the type for inserting a new chat message row into the messages table */\nexport type NewChatMessageRow = ChatTables['messages']['$inferInsert']\n","/**\n * Typed CRUD over the tables from `createChatTables`. Works against any\n * SQLite drizzle driver (D1, libsql, better-sqlite3) — builders are awaited,\n * never `.run()`/`.all()`, so sync and async drivers behave identically.\n *\n * Access control is an injected seam, never an import: single-thread routes\n * check workspace access themselves (they know the thread), while\n * `bulkDeleteThreads` REQUIRES an `assertAccess` callback because one request\n * can span workspaces — it is called once per distinct workspace and any\n * throw rejects the whole request before a single delete runs (fail-closed;\n * legal's bulk-delete semantics).\n *\n * Deletes run messages-first in ONE `db.batch` round trip when the driver has\n * one (D1, libsql), so a partial failure never leaves orphaned rows behind a\n * deleted thread; drivers without `batch` (better-sqlite3) fall back to\n * sequential awaits in the same order.\n */\n\nimport { and, asc, desc, eq, getTableColumns, gte, inArray, lt, sql, type SQL } from 'drizzle-orm'\nimport type { AnySQLiteColumn, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport {\n runSqliteStatements,\n type SqliteBatchDatabase,\n} from '../store'\nimport { type ChatMessageValues, BULK_DELETE_MAX_THREADS, ChatStoreInputError, threadTitleFromMessage } from './core'\nimport type { ChatMessageRow, ChatTables, ChatThreadRow, NewChatMessageRow, NewChatThreadRow } from './schema'\n\n/** Any SQLite drizzle database — `any` erases the driver-specific run-result\n * and schema generics so better-sqlite3, D1, and libsql handles all fit.\n * `batch` is structural: present on D1/libsql drizzle instances. */\nexport type ChatDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any> &\n SqliteBatchDatabase\n\n/** Product-injected access check. Throw to deny; the store never interprets\n * users or roles itself. */\nexport type WorkspaceAccessCheck = (workspaceId: string) => void | Promise<void>\n\n/** Define input parameters for listing threads within a workspace with pagination options */\nexport interface ListThreadsInput {\n workspaceId: string\n /** Clamped to 1..200; default 50 (legal's list route semantics). */\n limit?: number\n /** Clamped to >= 0; default 0. */\n offset?: number\n}\n\n/** Represent a paginated collection of chat threads with total count and pagination details */\nexport interface ListThreadsResult<TThread = ChatThreadRow> {\n threads: TThread[]\n total: number\n limit: number\n offset: number\n}\n\n/** Define input parameters required to create a new thread in a workspace */\nexport interface CreateThreadInput {\n /** Caller-assigned primary key. The agent gateway uses its validated\n * conversation id so API and browser turns share one durable thread. */\n id?: string\n workspaceId: string\n /** Title source when `title` is absent: first non-empty line, 80-char cap\n * (`threadTitleFromMessage`). */\n firstMessage?: string\n /** Explicit title; still normalized through `threadTitleFromMessage` so a\n * multi-page paste never becomes a sidebar entry. */\n title?: string\n category?: string | null\n isPinned?: boolean\n /** Opaque product-column values written verbatim in the SAME insert (the\n * `/missions` extras pattern). Never read, validated, or defaulted here. */\n extras?: Record<string, unknown>\n}\n\n/** Define input parameters for appending a message to a chat thread with optional metadata */\nexport interface AppendMessageInput extends ChatMessageValues {\n /** Caller-assigned primary key. Omitted, the column default assigns a random\n * hex id (today's behavior). Incremental assistant persistence passes a\n * DETERMINISTIC id derived from the turn's own identity, so a re-entered\n * turn (crashed worker, durable-driver retry) finds and updates the row a\n * previous attempt started instead of inserting a second one. */\n id?: string\n threadId: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n toolName?: string | null\n /** Opaque product-column values written verbatim in the SAME insert. */\n extras?: Record<string, unknown>\n}\n\n/** Fields an existing message row may be patched with. Every field is\n * optional and only DEFINED fields are written, so a partial patch never\n * clears a column it does not mention. `threadId` and `role` are absent on\n * purpose: a message never moves thread or changes speaker.\n *\n * Exists for incremental assistant persistence — the streaming turn writes\n * the row once and then patches it as content accumulates, so the durable\n * transcript is at most one cadence interval behind the live stream. */\nexport interface UpdateMessageInput extends Partial<ChatMessageValues> {\n toolName?: string | null\n /** Opaque product-column values written verbatim in the SAME update. */\n extras?: Record<string, unknown>\n}\n\n/** Define options to configure message listing with optional limit and offset parameters */\nexport interface ListMessagesOptions {\n limit?: number\n offset?: number\n}\n\n/** Define input for bulk deleting threads with access checks per workspace */\nexport interface BulkDeleteThreadsInput {\n ids: string[]\n /** Optional single-workspace fence for products whose route already resolved\n * one active workspace. Omitted preserves the multi-workspace legal route. */\n workspaceId?: string\n /** Called once per distinct workspace the ids touch, before ANY delete. */\n assertAccess: WorkspaceAccessCheck\n}\n\n/** Delete threads selected by their last activity time within one workspace.\n *\n * Products can add a lifecycle predicate such as `status = 'active'` through\n * `where`; the store still owns workspace scope, access ordering, and message\n * cleanup for every consumer. */\nexport interface BulkDeleteThreadsByUpdatedAtInput {\n workspaceId: string\n /** Exclusive upper bound: rows older than this instant. */\n updatedBefore?: Date\n /** Inclusive lower bound: rows updated at or after this instant. */\n updatedAfter?: Date\n where?: SQL\n /** Called before any delete for the requested workspace. */\n assertAccess: WorkspaceAccessCheck\n}\n\n/** Manage chat threads and messages with operations for listing, creating, updating, and deleting data */\nexport interface ChatStore<TThread = ChatThreadRow, TMessage = ChatMessageRow> {\n listThreads(input: ListThreadsInput): Promise<ListThreadsResult<TThread>>\n getThread(threadId: string): Promise<TThread | null>\n createThread(input: CreateThreadInput): Promise<TThread>\n renameThread(threadId: string, title: string): Promise<TThread | null>\n pinThread(threadId: string, isPinned: boolean): Promise<TThread | null>\n /** Messages + thread in one batch. Resolves false when the thread does not\n * exist. `assertAccess` (optional) receives the thread's workspaceId before\n * the delete — single-thread callers usually check access themselves. */\n deleteThread(threadId: string, options?: { assertAccess?: WorkspaceAccessCheck }): Promise<boolean>\n bulkDeleteThreads(input: BulkDeleteThreadsInput): Promise<{ deleted: number }>\n bulkDeleteThreadsByUpdatedAt(input: BulkDeleteThreadsByUpdatedAtInput): Promise<{ deleted: number }>\n /** Ordered oldest-first: `created_at`, then rowid (insertion order within a\n * same-second burst — a user+assistant pair lands in one epoch second). */\n listMessages(threadId: string, options?: ListMessagesOptions): Promise<TMessage[]>\n getMessage(id: string): Promise<TMessage | null>\n /** Atomic JSON Merge Patch for a product-declared metadata column. Null removes keys;\n * expected top-level fields fence the update against another attempt. Opaque values stay product-owned. */\n patchMessageMetadata(id: string, mergePatch: Record<string, unknown>, expected?: { fields: Record<string, unknown> } | { snapshot: Record<string, unknown> }): Promise<TMessage | null>\n /** Inserts the message and bumps the thread's `updatedAt` in one batch so\n * workspace recency sorts stay truthful. */\n appendMessage(input: AppendMessageInput): Promise<TMessage>\n /** Patches an existing message and bumps its thread's `updatedAt` in the\n * same batch. Resolves `null` when the id does not exist. Only defined\n * patch fields are written. */\n updateMessage(id: string, patch: UpdateMessageInput): Promise<TMessage | null>\n /** Removes one message. Resolves false when the id does not exist. Used by\n * incremental persistence to retract a draft row for a turn that ended\n * producing nothing, so an empty assistant row is never left behind. */\n deleteMessage(id: string): Promise<boolean>\n}\n\nfunction clampLimit(limit: number | undefined, fallback: number, max: number): number {\n const value = Number.isFinite(limit) ? Math.trunc(limit as number) : fallback\n return Math.min(Math.max(value, 1), max)\n}\n\nfunction clampOffset(offset: number | undefined): number {\n const value = Number.isFinite(offset) ? Math.trunc(offset as number) : 0\n return Math.max(value, 0)\n}\n\n/** Create a chat store managing threads and messages based on the provided database and tables */\nexport function createChatStore<TTables extends ChatTables>(\n db: ChatDatabase,\n tables: TTables,\n): ChatStore<TTables['threads']['$inferSelect'], TTables['messages']['$inferSelect']> {\n type TThread = TTables['threads']['$inferSelect']\n type TMessage = TTables['messages']['$inferSelect']\n const threads = tables.threads as ChatTables['threads']\n const messages = tables.messages as ChatTables['messages']\n // harness_cost_usd only when the table declares it: a patch of nothing else must stay a no-op.\n const messageValueKeys = [\n 'content', 'parts', 'toolName', 'model', 'requestedModel', 'servedModel', 'servedProvider', 'servedSource',\n 'inputTokens', 'outputTokens', 'reasoningTokens', 'cacheReadTokens', 'cacheWriteTokens', 'costUsd',\n ...('harnessCostUsd' in getTableColumns(tables.messages) ? ['harnessCostUsd'] : []),\n ]\n const definedMessageValues = (source: object) => Object.fromEntries(messageValueKeys\n .map((key) => [key, (source as Record<string, unknown>)[key]]).filter(([, value]) => value !== undefined))\n\n return {\n async listThreads(input) {\n const limit = clampLimit(input.limit, 50, 200)\n const offset = clampOffset(input.offset)\n const scope = eq(threads.workspaceId, input.workspaceId)\n const [list, [countRow]] = await Promise.all([\n db.select().from(threads).where(scope)\n // `id` tiebreak keeps pagination stable across same-second updates.\n .orderBy(desc(threads.updatedAt), asc(threads.id))\n .limit(limit)\n .offset(offset),\n db.select({ total: sql<number>`count(*)` }).from(threads).where(scope),\n ])\n return { threads: list as TThread[], total: countRow?.total ?? 0, limit, offset }\n },\n\n async getThread(threadId) {\n const [row] = await db.select().from(threads).where(eq(threads.id, threadId)).limit(1)\n return (row as TThread | undefined) ?? null\n },\n\n async createThread(input) {\n const title = threadTitleFromMessage(input.title ?? input.firstMessage ?? '')\n const values = {\n ...(input.id !== undefined ? { id: input.id } : {}),\n workspaceId: input.workspaceId,\n title,\n ...(input.category !== undefined ? { category: input.category } : {}),\n ...(input.isPinned !== undefined ? { isPinned: input.isPinned } : {}),\n ...(input.extras ?? {}),\n } as NewChatThreadRow\n const [row] = await db.insert(threads).values(values).returning()\n if (!row) throw new Error('thread insert returned no row')\n return row as TThread\n },\n\n async renameThread(threadId, title) {\n const trimmed = title.trim()\n if (!trimmed) throw new ChatStoreInputError('Missing title')\n const [row] = await db.update(threads)\n .set({ title: trimmed, updatedAt: new Date() })\n .where(eq(threads.id, threadId))\n .returning()\n return (row as TThread | undefined) ?? null\n },\n\n async pinThread(threadId, isPinned) {\n const [row] = await db.update(threads)\n .set({ isPinned, updatedAt: new Date() })\n .where(eq(threads.id, threadId))\n .returning()\n return (row as TThread | undefined) ?? null\n },\n\n async deleteThread(threadId, options) {\n const [existing] = await db.select({ id: threads.id, workspaceId: threads.workspaceId })\n .from(threads)\n .where(eq(threads.id, threadId))\n .limit(1)\n if (!existing) return false\n if (options?.assertAccess) await options.assertAccess(existing.workspaceId)\n // Messages first so a partial failure never leaves orphaned rows behind\n // a deleted thread.\n await runSqliteStatements(db, [\n db.delete(messages).where(eq(messages.threadId, threadId)),\n db.delete(threads).where(eq(threads.id, threadId)),\n ])\n return true\n },\n\n async bulkDeleteThreads(input) {\n const { ids, workspaceId, assertAccess } = input\n if (typeof assertAccess !== 'function') throw new ChatStoreInputError('Missing assertAccess')\n if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === 'string' && id.length > 0)) {\n throw new ChatStoreInputError('Missing ids')\n }\n if (ids.length > BULK_DELETE_MAX_THREADS) {\n throw new ChatStoreInputError(`Too many ids (max ${BULK_DELETE_MAX_THREADS})`)\n }\n if (workspaceId !== undefined && !workspaceId.trim()) {\n throw new ChatStoreInputError('Invalid workspaceId')\n }\n\n const scope = workspaceId\n ? and(inArray(threads.id, ids), eq(threads.workspaceId, workspaceId))\n : inArray(threads.id, ids)\n const rows = await db.select({ id: threads.id, workspaceId: threads.workspaceId })\n .from(threads)\n .where(scope)\n if (rows.length === 0) return { deleted: 0 }\n\n // Access is verified once per workspace the ids touch. Fail-closed: one\n // inaccessible workspace rejects the whole request before any delete.\n // Sorted so the check order (and therefore which denial surfaces) is\n // deterministic — row order follows random hex ids and varies per run.\n const workspaceIds = [...new Set(rows.map((row) => row.workspaceId))].sort()\n for (const workspaceId of workspaceIds) {\n await assertAccess(workspaceId)\n }\n\n const foundIds = rows.map((row) => row.id)\n await runSqliteStatements(db, [\n db.delete(messages).where(inArray(messages.threadId, foundIds)),\n db.delete(threads).where(inArray(threads.id, foundIds)),\n ])\n return { deleted: foundIds.length }\n },\n\n async bulkDeleteThreadsByUpdatedAt(input) {\n const { workspaceId, updatedBefore, updatedAfter, where, assertAccess } = input\n if (typeof assertAccess !== 'function') throw new ChatStoreInputError('Missing assertAccess')\n if (!workspaceId.trim()) throw new ChatStoreInputError('Missing workspaceId')\n if (updatedBefore === undefined && updatedAfter === undefined) {\n throw new ChatStoreInputError('Missing updatedAt boundary')\n }\n for (const boundary of [updatedBefore, updatedAfter]) {\n if (boundary !== undefined && Number.isNaN(boundary.getTime())) {\n throw new ChatStoreInputError('Invalid updatedAt boundary')\n }\n }\n\n const conditions = [eq(threads.workspaceId, workspaceId)]\n if (updatedBefore) conditions.push(lt(threads.updatedAt, updatedBefore))\n if (updatedAfter) conditions.push(gte(threads.updatedAt, updatedAfter))\n if (where) conditions.push(where)\n const scope = and(...conditions)\n const [countRow] = await db.select({ total: sql<number>`count(*)` })\n .from(threads)\n .where(scope)\n const deleted = Number(countRow?.total ?? 0)\n if (deleted === 0) return { deleted: 0 }\n\n await assertAccess(workspaceId)\n // Keep the age path unbounded without constructing a giant host-parameter\n // list; the subquery lets SQLite/D1 stream the matching thread ids.\n const matchingThreads = db.select({ id: threads.id }).from(threads).where(scope)\n await runSqliteStatements(db, [\n db.delete(messages).where(inArray(messages.threadId, matchingThreads)),\n db.delete(threads).where(scope),\n ])\n return { deleted }\n },\n\n async listMessages(threadId, options) {\n const query = db.select().from(messages)\n .where(eq(messages.threadId, threadId))\n .orderBy(asc(messages.createdAt), sql`rowid`)\n .$dynamic()\n if (options?.limit !== undefined) query.limit(clampLimit(options.limit, 1, 1000))\n if (options?.offset !== undefined) query.offset(clampOffset(options.offset))\n return await query as TMessage[]\n },\n\n async getMessage(id) {\n const [row] = await db.select().from(messages).where(eq(messages.id, id)).limit(1)\n return (row as TMessage | undefined) ?? null\n },\n\n async patchMessageMetadata(id, mergePatch, expected) {\n const metadata = (getTableColumns(tables.messages) as Record<string, AnySQLiteColumn>).metadata\n if (!metadata) throw new Error('Chat metadata requires a product-declared metadata column')\n const guards = Object.entries(expected && 'fields' in expected ? expected.fields : {}).map(([field, value]) => {\n const encoded = JSON.stringify(value)\n if (encoded === undefined) throw new Error('Expected chat metadata must be JSON')\n return sql`json_extract(${metadata}, ${`$.${JSON.stringify(field)}`}) IS json_extract(${encoded}, '$')`\n })\n if (expected && 'snapshot' in expected) guards.push(sql`coalesce(${metadata}, '{}') = ${JSON.stringify(expected.snapshot)}`)\n const [row] = await db.update(messages).set({\n metadata: sql`json_patch(coalesce(${metadata}, '{}'), ${JSON.stringify(mergePatch)})`,\n } as Partial<NewChatMessageRow>).where(and(eq(messages.id, id), ...guards)).returning()\n return (row as TMessage | undefined) ?? null\n },\n\n async appendMessage(input) {\n const values = {\n ...(input.id !== undefined ? { id: input.id } : {}),\n threadId: input.threadId,\n role: input.role,\n content: input.content,\n ...definedMessageValues(input),\n ...(input.extras ?? {}),\n } as NewChatMessageRow\n const [insertResult] = await runSqliteStatements(db, [\n db.insert(messages).values(values).returning(),\n db.update(threads).set({ updatedAt: new Date() }).where(eq(threads.id, input.threadId)),\n ])\n const row = (insertResult as TMessage[] | undefined)?.[0]\n if (!row) throw new Error('message insert returned no row')\n return row\n },\n\n async updateMessage(id, patch) {\n const values = {\n ...definedMessageValues(patch),\n ...(patch.extras ?? {}),\n }\n if (Object.keys(values).length === 0) {\n const [current] = await db.select().from(messages).where(eq(messages.id, id))\n return (current as TMessage | undefined) ?? null\n }\n // The thread bump reads the row's own `thread_id` rather than trusting a\n // caller-supplied one: a message never moves thread, so the subquery is\n // the authoritative source and one fewer parameter to get wrong.\n const [updateResult] = await runSqliteStatements(db, [\n db.update(messages).set(values).where(eq(messages.id, id)).returning(),\n db.update(threads).set({ updatedAt: new Date() })\n .where(eq(threads.id, sql`(select ${messages.threadId} from ${messages} where ${messages.id} = ${id})`)),\n ])\n return (updateResult as TMessage[] | undefined)?.[0] ?? null\n },\n\n async deleteMessage(id) {\n const deleted = await db.delete(messages).where(eq(messages.id, id)).returning()\n return (deleted as unknown[]).length > 0\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,IAAM,0BAA0B;AAIhC,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAKO,SAAS,uBAAuB,SAAyB;AAC9D,QAAM,YAAY,QAAQ,MAAM,IAAI,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,KAAK,KAAK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AAAA,QACnD,GAAG,OAAO,QAAQ,EAAE,IAAI,MAAM,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAAC,EAAE,UAAU;AAAA,QACrE,GAAG,OAAO,OAAO,EAAE,IAAI,EAAE,WAAW,oBAAI,KAAK,EAAE,CAAC,EAC7C,MAAM,GAAG,QAAQ,IAAIA,eAAc,SAAS,QAAQ,SAAS,QAAQ,UAAU,SAAS,EAAE,MAAM,EAAE,GAAG,CAAC;AAAA,MAC3G,CAAC;AACD,aAAQ,eAA0C,CAAC,KAAK;AAAA,IAC1D;AAAA,IAEA,MAAM,cAAc,IAAI;AACtB,YAAM,UAAU,MAAM,GAAG,OAAO,QAAQ,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAAC,EAAE,UAAU;AAC/E,aAAQ,QAAsB,SAAS;AAAA,IACzC;AAAA,EACF;AACF;","names":["sql","sql","workspaceId"]}
|
|
@@ -88,6 +88,15 @@ export interface CreateChatTablesOptions<TThreadExtras extends Record<string, SQ
|
|
|
88
88
|
* breaks `db.select()` at every call site.
|
|
89
89
|
*/
|
|
90
90
|
export type ChatExtraIndexes = (columns: Record<string, AnySQLiteColumn>) => SQLiteTableExtraConfigValue[];
|
|
91
|
+
/**
|
|
92
|
+
* The optional `harness_cost_usd` message column: spread into
|
|
93
|
+
* `messageExtraColumns` once the table has it. The store writes and reads the
|
|
94
|
+
* harness's own token cost only when the table declares it, so a table without
|
|
95
|
+
* the column keeps working.
|
|
96
|
+
*/
|
|
97
|
+
export declare const harnessCostColumns: () => {
|
|
98
|
+
harnessCostUsd: import("drizzle-orm/sqlite-core").SQLiteRealBuilderInitial<"harness_cost_usd">;
|
|
99
|
+
};
|
|
91
100
|
/** Build chat-related SQLite tables with customizable thread and message columns */
|
|
92
101
|
export declare function createChatTables<TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {}, TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {}>(options?: CreateChatTablesOptions<TThreadExtras, TMessageExtras>): {
|
|
93
102
|
threads: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
DEFAULT_TANGLE_ROUTER_BASE_URL
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-D6UJEOZQ.js";
|
|
4
4
|
import {
|
|
5
5
|
nextCallIndex,
|
|
6
6
|
tracedModelFetch,
|
|
@@ -985,4 +985,4 @@ export {
|
|
|
985
985
|
composeRouterTurnPrompt,
|
|
986
986
|
runRouterTurn
|
|
987
987
|
};
|
|
988
|
-
//# sourceMappingURL=chunk-
|
|
988
|
+
//# sourceMappingURL=chunk-3XVGMHCD.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
runRouterTurn
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-3XVGMHCD.js";
|
|
4
4
|
|
|
5
5
|
// src/runtime/protected-model.ts
|
|
6
6
|
var GATEWAY_ORIGIN = "https://candidate-router.tangle.tools";
|
|
@@ -217,4 +217,4 @@ export {
|
|
|
217
217
|
createRouterProtectedModelPort,
|
|
218
218
|
runProtectedRouterTurn
|
|
219
219
|
};
|
|
220
|
-
//# sourceMappingURL=chunk-
|
|
220
|
+
//# sourceMappingURL=chunk-4EQWYI53.js.map
|
|
@@ -5,6 +5,42 @@ import {
|
|
|
5
5
|
asRecord
|
|
6
6
|
} from "./chunk-JM6ANMOA.js";
|
|
7
7
|
|
|
8
|
+
// src/chat-routes/sandbox-turn-usage.ts
|
|
9
|
+
var TURN_USAGE_KEYS = [
|
|
10
|
+
"inputTokens",
|
|
11
|
+
"outputTokens",
|
|
12
|
+
"reasoningTokens",
|
|
13
|
+
"cacheReadTokens",
|
|
14
|
+
"cacheWriteTokens",
|
|
15
|
+
"costUsd",
|
|
16
|
+
"harnessCostUsd"
|
|
17
|
+
];
|
|
18
|
+
function measuredUsage(usage) {
|
|
19
|
+
const measured = {};
|
|
20
|
+
for (const key of TURN_USAGE_KEYS) if (usage?.[key] !== void 0) measured[key] = usage[key];
|
|
21
|
+
return measured;
|
|
22
|
+
}
|
|
23
|
+
function addStepFinishUsage(part, usage) {
|
|
24
|
+
const tokens = asRecord(part.tokens);
|
|
25
|
+
if (tokens) {
|
|
26
|
+
const cache = asRecord(tokens.cache);
|
|
27
|
+
const add = (current, value) => {
|
|
28
|
+
const n = Number(value);
|
|
29
|
+
if (!Number.isFinite(n)) return current;
|
|
30
|
+
return (current ?? 0) + n;
|
|
31
|
+
};
|
|
32
|
+
usage.inputTokens = add(usage.inputTokens, tokens.input);
|
|
33
|
+
usage.outputTokens = add(usage.outputTokens, tokens.output);
|
|
34
|
+
usage.reasoningTokens = add(usage.reasoningTokens, tokens.reasoning);
|
|
35
|
+
if (cache) {
|
|
36
|
+
usage.cacheReadTokens = add(usage.cacheReadTokens, cache.read);
|
|
37
|
+
usage.cacheWriteTokens = add(usage.cacheWriteTokens, cache.write);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const cost = Number(part.cost);
|
|
41
|
+
if (Number.isFinite(cost)) usage.harnessCostUsd = (usage.harnessCostUsd ?? 0) + cost;
|
|
42
|
+
}
|
|
43
|
+
|
|
8
44
|
// src/chat-routes/draft-persistence.ts
|
|
9
45
|
var CONTENT_EVENT_TYPES = /* @__PURE__ */ new Set([
|
|
10
46
|
"text",
|
|
@@ -89,12 +125,7 @@ function createAssistantDraftWriter(options) {
|
|
|
89
125
|
content,
|
|
90
126
|
...parts && parts.length > 0 ? { parts } : {},
|
|
91
127
|
...snapshot.model ? { model: snapshot.model } : {},
|
|
92
|
-
...usage
|
|
93
|
-
...usage.outputTokens !== void 0 ? { outputTokens: usage.outputTokens } : {},
|
|
94
|
-
...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
|
|
95
|
-
...usage.cacheReadTokens !== void 0 ? { cacheReadTokens: usage.cacheReadTokens } : {},
|
|
96
|
-
...usage.cacheWriteTokens !== void 0 ? { cacheWriteTokens: usage.cacheWriteTokens } : {},
|
|
97
|
-
...usage.costUsd !== void 0 ? { costUsd: usage.costUsd } : {}
|
|
128
|
+
...measuredUsage(usage)
|
|
98
129
|
};
|
|
99
130
|
}
|
|
100
131
|
async function adoptRow() {
|
|
@@ -192,34 +223,14 @@ function assistantRowIdForTurn(turnKey) {
|
|
|
192
223
|
return `assistant:${turnKey}`;
|
|
193
224
|
}
|
|
194
225
|
|
|
195
|
-
// src/chat-routes/sandbox-turn-usage.ts
|
|
196
|
-
function addStepFinishUsage(part, usage) {
|
|
197
|
-
const tokens = asRecord(part.tokens);
|
|
198
|
-
if (tokens) {
|
|
199
|
-
const cache = asRecord(tokens.cache);
|
|
200
|
-
const add = (current, value) => {
|
|
201
|
-
const n = Number(value);
|
|
202
|
-
if (!Number.isFinite(n)) return current;
|
|
203
|
-
return (current ?? 0) + n;
|
|
204
|
-
};
|
|
205
|
-
usage.inputTokens = add(usage.inputTokens, tokens.input);
|
|
206
|
-
usage.outputTokens = add(usage.outputTokens, tokens.output);
|
|
207
|
-
usage.reasoningTokens = add(usage.reasoningTokens, tokens.reasoning);
|
|
208
|
-
if (cache) {
|
|
209
|
-
usage.cacheReadTokens = add(usage.cacheReadTokens, cache.read);
|
|
210
|
-
usage.cacheWriteTokens = add(usage.cacheWriteTokens, cache.write);
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
const cost = Number(part.cost);
|
|
214
|
-
if (Number.isFinite(cost)) usage.costUsd = (usage.costUsd ?? 0) + cost;
|
|
215
|
-
}
|
|
216
|
-
|
|
217
226
|
export {
|
|
227
|
+
TURN_USAGE_KEYS,
|
|
228
|
+
measuredUsage,
|
|
229
|
+
addStepFinishUsage,
|
|
218
230
|
isDraftContentEvent,
|
|
219
231
|
createAssistantDraftWriter,
|
|
220
232
|
storeSupportsDraftPersistence,
|
|
221
233
|
rowIdOf,
|
|
222
|
-
assistantRowIdForTurn
|
|
223
|
-
addStepFinishUsage
|
|
234
|
+
assistantRowIdForTurn
|
|
224
235
|
};
|
|
225
|
-
//# sourceMappingURL=chunk-
|
|
236
|
+
//# sourceMappingURL=chunk-5DAEU3CP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/chat-routes/sandbox-turn-usage.ts","../src/chat-routes/draft-persistence.ts"],"sourcesContent":["import { asRecord, type JsonRecord } from '../stream/index'\nimport type { ChatTurnUsage } from './turn-routes'\n\n/** Every usage field a turn can record, in column order. */\nexport const TURN_USAGE_KEYS = [\n 'inputTokens', 'outputTokens', 'reasoningTokens', 'cacheReadTokens', 'cacheWriteTokens', 'costUsd', 'harnessCostUsd',\n] as const\n\n/** The usage fields a turn measured; unknown ones stay absent, never zero. */\nexport function measuredUsage(usage: ChatTurnUsage | undefined): ChatTurnUsage {\n const measured: ChatTurnUsage = {}\n for (const key of TURN_USAGE_KEYS) if (usage?.[key] !== undefined) measured[key] = usage[key]\n return measured\n}\n\n/** Add one canonical Sandbox `step-finish` receipt to a turn total. */\nexport function addStepFinishUsage(part: JsonRecord, usage: ChatTurnUsage): void {\n const tokens = asRecord(part.tokens)\n if (tokens) {\n const cache = asRecord(tokens.cache)\n const add = (current: number | undefined, value: unknown): number | undefined => {\n const n = Number(value)\n if (!Number.isFinite(n)) return current\n return (current ?? 0) + n\n }\n usage.inputTokens = add(usage.inputTokens, tokens.input)\n usage.outputTokens = add(usage.outputTokens, tokens.output)\n usage.reasoningTokens = add(usage.reasoningTokens, tokens.reasoning)\n if (cache) {\n usage.cacheReadTokens = add(usage.cacheReadTokens, cache.read)\n usage.cacheWriteTokens = add(usage.cacheWriteTokens, cache.write)\n }\n }\n const cost = Number(part.cost)\n if (Number.isFinite(cost)) usage.harnessCostUsd = (usage.harnessCostUsd ?? 0) + cost\n}\n","/**\n * Incremental (\"draft\") persistence of the assistant row WHILE a turn streams.\n *\n * Why this exists — the scale argument, not a convenience:\n *\n * A live turn is readable from two places. The hot path is the session\n * gateway's in-memory/Redis event buffer, which exists so a viewer survives a\n * network blip: it is keyed one sorted set per session, refreshed on every\n * push, and expires on a TTL. Its memory cost is `arrival_rate x TTL x\n * bytes_per_session` — strictly LINEAR in the TTL. Stretching that TTL to\n * cover \"a viewer who opens the tab later\" is a category error: it buys memory\n * proportional to the increase and still serves nothing to a viewer who\n * arrives past the new horizon.\n *\n * So the hot buffer must stay SHORT (live delivery + reconnect only), and\n * durable storage must serve history. That only works if durable storage\n * actually HAS the in-flight turn — which, before this module, it did not: the\n * assistant row was written once, after the stream drained. A viewer arriving\n * mid-turn past the hot window read an empty transcript.\n *\n * This module closes that gap: the assistant row is inserted early and patched\n * on a coalesced cadence, so the durable transcript is at most one interval\n * (default 2 s) behind the live stream and the hot buffer never has to be the\n * history tier.\n *\n * Mechanism only. It owns no vocabulary: the caller supplies the snapshot\n * function, the store, and the deterministic row id.\n *\n * Four properties the cadence guarantees:\n * - **Time-floored.** At most one write per `intervalMs`, never one per token.\n * - **Dirty-gated.** Only content-bearing events arm a write; heartbeats,\n * status pings, and lifecycle envelopes never do.\n * - **Single-flight.** A write already in flight suppresses the next trigger\n * instead of queueing; the final write is authoritative regardless of how\n * many drafts landed.\n * - **Best-effort.** A store failure is logged and swallowed — a durability\n * optimization must never kill a healthy stream (the same rule\n * `withDurableChatProjection` already states).\n */\n\nimport type { ChatMessageValues } from '../chat-store/core'\nimport { toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport type { ChatTurnUsage } from './turn-routes'\nimport { measuredUsage } from './sandbox-turn-usage'\n\n/** Message row shape the writer reads back when re-entering a turn. */\nexport interface DraftStoredMessage extends Pick<AssistantRowValues, keyof ChatTurnUsage> {\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n}\n\n/** Values written to the assistant row — the intersection of the append and\n * patch shapes, so one snapshot serves both. */\nexport interface AssistantRowValues extends ChatMessageValues {}\n\n/** The store capability incremental persistence needs on top of\n * `appendMessage`. A store without `updateMessage` cannot patch a row, so it\n * cannot draft at all — the caller keeps today's single-write behavior. */\nexport interface AssistantDraftStore {\n listMessages(threadId: string): Promise<DraftStoredMessage[]>\n appendMessage(input: AssistantRowValues & {\n id?: string\n threadId: string\n role: 'user' | 'assistant'\n }): Promise<unknown>\n updateMessage?(id: string, patch: AssistantRowValues): Promise<unknown>\n deleteMessage?(id: string): Promise<unknown>\n}\n\n/** Live snapshot of the assistant body, taken from the producer's own\n * accumulators. `parts` is the DRAFT projection (`draftParts()`), never the\n * finalized one — see `draftAssistantParts`. */\nexport interface AssistantDraftSnapshot {\n content: string\n parts?: Array<Record<string, unknown>>\n usage?: ChatTurnUsage\n model?: string\n}\n\n/** Product-tunable cadence. Defaults are stated on each field; a product with\n * a chattier or heavier workload moves them without forking the writer. */\nexport interface DraftPersistenceTuning {\n /** Minimum wall-clock gap between draft writes, in ms. Default 2000.\n *\n * Justification for 2 s, from a measured tool-heavy production run (517\n * stream events over ~90 s wall = ~5.7 events/s): a 2 s floor with the\n * dirty gate turns 517 candidate writes into <= 45, while leaving the\n * durable row at most 2 s stale — an order of magnitude below the time it\n * takes a viewer to open a tab and render, so a late viewer never perceives\n * the lag. Fleet arithmetic at 10k concurrent 60 s runs: <= 30 updates per\n * run x 167 run-starts/s = ~334 row-updates/s spread over per-tenant\n * shards. Lower it and write amplification grows with no perceptible\n * freshness gain; raise it past ~5 s and a late viewer starts seeing a\n * visibly truncated answer. */\n intervalMs?: number\n /** Serialized-parts size (bytes) past which the interval backs off, so a\n * turn accumulating a megabyte-scale `parts` blob does not rewrite it every\n * interval. Default 262144 (256 KiB) -> interval x 2.5; ten times that ->\n * interval x 5. The final write is never throttled. */\n backoffBytes?: number\n /** Per-tool-part output cap applied to DRAFTS ONLY (bytes). A tool returning\n * a large blob would otherwise be rewritten in full on every draft. The\n * final write always carries the untruncated value. Default 32768 (32 KiB);\n * 0 disables truncation. */\n maxDraftToolOutputBytes?: number\n}\n\n/** Define the inputs required to construct an assistant draft writer */\nexport interface AssistantDraftWriterOptions extends DraftPersistenceTuning {\n store: AssistantDraftStore\n threadId: string\n /** DETERMINISTIC row id for this turn's assistant message — the whole\n * idempotency mechanism. Derived from the turn's existing identity\n * (`deriveExecutionId` in the interactive lane, the turn id in the detached\n * lane), so a re-entered turn addresses the SAME row: the writer looks the\n * id up before its first insert and patches what it finds. */\n messageId: string\n /** Read the producer's live accumulators. Returns null before the producer\n * is resolved (the assembly defers box resolution into the first pull). */\n snapshot(): AssistantDraftSnapshot | null\n /** Pre-persist text transform (`/redact`'s `redactPII`). Applied to the\n * draft's scalar content AND every draft text part — parity with the final\n * write, or incremental persistence would re-open the at-rest PII leak that\n * transform closed, just seconds earlier and on every turn. */\n transformText?(text: string): string | Promise<string>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** Coalescing writer that keeps one durable assistant row in step with a\n * streaming turn. Created per turn; not reusable. */\nexport interface AssistantDraftWriter {\n /** Arm/trigger a draft write from one engine event. Synchronous by design —\n * the write itself is fire-and-forget so the stream is never blocked on\n * store latency. */\n notify(event: { type?: unknown }): void\n /** Stop drafting and settle any in-flight write. Called before the final\n * write so a late draft can never clobber the authoritative row. */\n close(): Promise<void>\n /** Write the AUTHORITATIVE completion values onto this turn's row —\n * insert-or-patch under the same deterministic id, un-throttled and\n * un-truncated. Errors propagate: the final write is the one that must not\n * fail silently. Implies {@link close}. */\n finalize(values: AssistantRowValues): Promise<void>\n /** The durable row this turn is writing, once one exists. */\n rowId(): string | undefined\n /** Retract the row for a turn that produced nothing (mirrors the final\n * write's empty-turn skip, which leaves no row at all today). Also retracts\n * a row a PREVIOUS attempt left behind, so a re-entered turn that ends\n * empty converges on \"no row\" rather than a stale partial. */\n discard(): Promise<void>\n /** Diagnostics: how many draft writes actually reached the store. */\n writeCount(): number\n}\n\n/** Event types that carry assistant content and therefore arm a draft write.\n * An allowlist on purpose: an unknown type (a product heartbeat, a bespoke\n * passthrough) must NEVER arm a write, or a silent producer would rewrite the\n * same row forever. */\nconst CONTENT_EVENT_TYPES: ReadonlySet<string> = new Set([\n 'text',\n 'reasoning',\n 'tool_call',\n 'tool_result',\n 'usage',\n 'notice',\n 'error',\n 'file',\n 'interaction',\n 'interaction.cancel',\n 'plan.submitted',\n 'message.part.updated',\n])\n\nconst DEFAULT_INTERVAL_MS = 2000\nconst DEFAULT_BACKOFF_BYTES = 262144\nconst DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES = 32768\n\n/** True when this event should arm a draft write. */\nexport function isDraftContentEvent(event: { type?: unknown }): boolean {\n return typeof event?.type === 'string' && CONTENT_EVENT_TYPES.has(event.type)\n}\n\n/** Caps one tool part's `output` for a DRAFT write. The value is replaced by a\n * truncated string plus a marker, so a reader can tell a clipped draft from a\n * real short output; the final write restores the untruncated value. */\nfunction capDraftToolOutput(part: Record<string, unknown>, maxBytes: number): Record<string, unknown> {\n if (maxBytes <= 0) return part\n if (String(part.type ?? '') !== 'tool') return part\n const state = part.state\n if (!state || typeof state !== 'object') return part\n const record = state as Record<string, unknown>\n const output = record.output\n if (output === undefined || output === null) return part\n const serialized = typeof output === 'string' ? output : safeStringify(output)\n if (serialized.length <= maxBytes) return part\n const metadata = (record.metadata && typeof record.metadata === 'object' ? record.metadata : {}) as Record<string, unknown>\n return {\n ...part,\n state: {\n ...record,\n output: `${serialized.slice(0, maxBytes)}…[draft-truncated ${serialized.length - maxBytes} chars]`,\n metadata: { ...metadata, draftTruncated: true },\n },\n }\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? ''\n } catch {\n return String(value)\n }\n}\n\n/** Build the coalescing draft writer for one turn. */\nexport function createAssistantDraftWriter(options: AssistantDraftWriterOptions): AssistantDraftWriter {\n const log = options.log ?? (() => {})\n const baseIntervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS\n const backoffBytes = options.backoffBytes ?? DEFAULT_BACKOFF_BYTES\n const maxToolOutput = options.maxDraftToolOutputBytes ?? DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES\n\n let dirty = false\n let closed = false\n let inFlight: Promise<void> | undefined\n let lastWriteAt = 0\n let lastBlobBytes = 0\n let rowId: string | undefined\n let writes = 0\n\n /** Interval for the NEXT write, backed off by the size of the last blob\n * written — a turn accumulating a huge parts array rewrites it less often. */\n function currentIntervalMs(): number {\n if (lastBlobBytes >= backoffBytes * 10) return baseIntervalMs * 5\n if (lastBlobBytes >= backoffBytes) return Math.round(baseIntervalMs * 2.5)\n return baseIntervalMs\n }\n\n async function projectValues(snapshot: AssistantDraftSnapshot): Promise<AssistantRowValues> {\n const transform = options.transformText\n const content = transform ? await transform(snapshot.content) : snapshot.content\n let parts: ChatMessagePart[] | undefined\n if (snapshot.parts) {\n const capped = snapshot.parts.map((part) => capDraftToolOutput(part, maxToolOutput))\n const redacted = transform\n ? await Promise.all(\n capped.map(async (part) =>\n String((part as { type?: unknown }).type ?? '') === 'text'\n ? { ...part, text: await transform(String((part as { text?: unknown }).text ?? '')) }\n : part,\n ),\n )\n : capped\n parts = toChatMessageParts(redacted)\n }\n const usage = snapshot.usage ?? {}\n return {\n content,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(snapshot.model ? { model: snapshot.model } : {}),\n ...measuredUsage(usage),\n }\n }\n\n /** Adopt the row a PREVIOUS attempt at this turn already inserted, if any.\n * This lookup — by the deterministic id, through the store's ordinary read\n * — is the whole crash-safety mechanism: no new state, no extra column, no\n * second index. */\n async function adoptRow(): Promise<string | undefined> {\n if (rowId) return rowId\n const existing = (await options.store.listMessages(options.threadId)).find(\n (message) => message.id === options.messageId,\n )\n if (existing) rowId = existing.id\n return rowId\n }\n\n /** Insert-or-patch one set of values onto this turn's single row. */\n async function writeOnce(values: AssistantRowValues): Promise<void> {\n if (await adoptRow()) {\n await options.store.updateMessage!(rowId!, values)\n writes += 1\n return\n }\n const inserted = await options.store.appendMessage({\n id: options.messageId,\n threadId: options.threadId,\n role: 'assistant',\n ...values,\n })\n // The `?? options.messageId` tail is valid HERE and only here: this writer\n // supplied the id, so a store that returns nothing still wrote that row.\n // A caller that did not assign an id has no such fallback — which is why\n // `rowIdOf` deliberately stops at the honest read.\n rowId = rowIdOf(inserted) ?? options.messageId\n writes += 1\n }\n\n function trigger(): void {\n if (closed) return\n if (!dirty) return\n // Single-flight: a write already in flight SUPPRESSES this trigger rather\n // than queueing behind it. `dirty` stays armed, so the next event after it\n // lands writes the newer snapshot — one write is never spent on state a\n // later one supersedes.\n if (inFlight) return\n const now = Date.now()\n // The first content event writes immediately (a late viewer sees a row at\n // once); the time floor governs every write after it.\n if (lastWriteAt !== 0 && now - lastWriteAt < currentIntervalMs()) return\n const snapshot = options.snapshot()\n if (!snapshot) return\n // Nothing to persist yet: an armed-but-empty snapshot (first event is a\n // tool call with no text and no parts) would insert a blank row.\n if (!snapshot.content && (!snapshot.parts || snapshot.parts.length === 0)) return\n dirty = false\n lastWriteAt = now\n inFlight = (async () => {\n try {\n const values = await projectValues(snapshot)\n lastBlobBytes = values.parts ? safeStringify(values.parts).length : 0\n await writeOnce(values)\n } catch (err) {\n // Best-effort by contract: a store outage degrades freshness for late\n // viewers, it does not fail a healthy turn.\n log('[chat-routes] incremental assistant persistence failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n } finally {\n inFlight = undefined\n // A trigger that arrived while this write was in flight left `dirty`\n // armed with a NEWER snapshot. Re-run it here or that state would sit\n // unwritten until the next content event — and if this was the last\n // event of a quiet stretch, until the final write.\n if (dirty && !closed) trigger()\n }\n })()\n }\n\n return {\n notify(event) {\n if (closed) return\n if (isDraftContentEvent(event)) dirty = true\n trigger()\n },\n async close() {\n closed = true\n if (inFlight) await inFlight\n },\n async finalize(values) {\n closed = true\n if (inFlight) await inFlight\n await writeOnce(values)\n },\n rowId: () => rowId,\n async discard() {\n closed = true\n if (inFlight) await inFlight\n if (!options.store.deleteMessage) return\n try {\n if (!(await adoptRow())) return\n await options.store.deleteMessage(rowId!)\n rowId = undefined\n } catch (err) {\n log('[chat-routes] draft assistant row discard failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n },\n writeCount: () => writes,\n }\n}\n\n/** True when a store can support incremental persistence at all. Without\n * `updateMessage` a draft row could never be patched, so the caller keeps\n * today's exact single-write behavior. */\nexport function storeSupportsDraftPersistence(store: AssistantDraftStore): boolean {\n return typeof store.updateMessage === 'function'\n}\n\n/** The row id an `appendMessage` actually returned, or `null` when the store\n * returned nothing usable. `ChatTurnMessageStore.appendMessage` is typed\n * `Promise<unknown>` so a product adapter is free to resolve `void`; every\n * caller that wants to NAME the row it just wrote has to read defensively.\n *\n * Deliberately no fallback to a caller-assigned id — see `writeOnce`, which\n * adds its own. A caller that let the store mint the id has nothing to fall\n * back TO, and guessing one would report a row that may not exist. */\nexport function rowIdOf(inserted: unknown): string | null {\n const id = (inserted as { id?: unknown } | null | undefined)?.id\n return typeof id === 'string' && id ? id : null\n}\n\n/** The default deterministic assistant-row id for a turn. Readable on purpose\n * (an operator grepping a transcript row id finds the run), and stable across\n * re-entries because every input already is. */\nexport function assistantRowIdForTurn(turnKey: string): string {\n return `assistant:${turnKey}`\n}\n"],"mappings":";;;;;;;;AAIO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EAAe;AAAA,EAAgB;AAAA,EAAmB;AAAA,EAAmB;AAAA,EAAoB;AAAA,EAAW;AACtG;AAGO,SAAS,cAAc,OAAiD;AAC7E,QAAM,WAA0B,CAAC;AACjC,aAAW,OAAO,gBAAiB,KAAI,QAAQ,GAAG,MAAM,OAAW,UAAS,GAAG,IAAI,MAAM,GAAG;AAC5F,SAAO;AACT;AAGO,SAAS,mBAAmB,MAAkB,OAA4B;AAC/E,QAAM,SAAS,SAAS,KAAK,MAAM;AACnC,MAAI,QAAQ;AACV,UAAM,QAAQ,SAAS,OAAO,KAAK;AACnC,UAAM,MAAM,CAAC,SAA6B,UAAuC;AAC/E,YAAM,IAAI,O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M,KAAM,UAAkD;AAC9D,SAAO,OAAO,OAAO,YAAY,KAAK,KAAK;AAC7C;AAKO,SAAS,sBAAsB,SAAyB;AAC7D,SAAO,aAAa,OAAO;AAC7B;","names":[]}
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
} from "./chunk-3CI35I4X.js";
|
|
5
5
|
import {
|
|
6
6
|
defineAppTool
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-NHOQ5TMH.js";
|
|
8
8
|
import {
|
|
9
9
|
ToolInputError
|
|
10
10
|
} from "./chunk-F4XBNR5L.js";
|
|
@@ -672,4 +672,4 @@ export {
|
|
|
672
672
|
PROFILE_MEMORY_PREFIX,
|
|
673
673
|
profileTools
|
|
674
674
|
};
|
|
675
|
-
//# sourceMappingURL=chunk-
|
|
675
|
+
//# sourceMappingURL=chunk-6GN2E5KT.js.map
|
|
@@ -37,7 +37,7 @@ import {
|
|
|
37
37
|
import {
|
|
38
38
|
resolveTangleExecutionEnvironment,
|
|
39
39
|
trimOrNull
|
|
40
|
-
} from "./chunk-
|
|
40
|
+
} from "./chunk-D6UJEOZQ.js";
|
|
41
41
|
import {
|
|
42
42
|
formatServerTiming,
|
|
43
43
|
nextCallIndex
|
|
@@ -243,13 +243,13 @@ function workersReuseStore() {
|
|
|
243
243
|
|
|
244
244
|
// src/sandbox/model.ts
|
|
245
245
|
function backendModelFields(model) {
|
|
246
|
-
return {
|
|
247
|
-
|
|
246
|
+
return { model: {
|
|
247
|
+
model: model.model,
|
|
248
248
|
provider: model.provider,
|
|
249
249
|
...model.apiKey !== void 0 ? { apiKey: model.apiKey } : {},
|
|
250
250
|
...model.apiKeyEnv !== void 0 ? { apiKeyEnv: model.apiKeyEnv } : {},
|
|
251
251
|
...model.baseUrl !== void 0 ? { baseUrl: model.baseUrl } : {}
|
|
252
|
-
};
|
|
252
|
+
} };
|
|
253
253
|
}
|
|
254
254
|
function resolveModelSelection(config, override) {
|
|
255
255
|
const c = config ?? {};
|
|
@@ -4326,4 +4326,4 @@ export {
|
|
|
4326
4326
|
deleteSecret,
|
|
4327
4327
|
mintSandboxScopedToken
|
|
4328
4328
|
};
|
|
4329
|
-
//# sourceMappingURL=chunk-
|
|
4329
|
+
//# sourceMappingURL=chunk-B2NN5BIJ.js.map
|