@tangle-network/agent-app 0.43.24 → 0.43.25
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/app-auth/index.d.ts +163 -0
- package/dist/app-auth/index.js +166 -0
- package/dist/app-auth/index.js.map +1 -0
- package/dist/assets/index.d.ts +2 -2
- package/dist/assistant/index.d.ts +1 -0
- package/dist/assistant/index.js +2 -1
- package/dist/assistant/index.js.map +1 -1
- package/dist/chat-store/index.d.ts +193 -0
- package/dist/chat-store/index.js +194 -0
- package/dist/chat-store/index.js.map +1 -0
- package/dist/chunk-4H77LX3V.js +38 -0
- package/dist/chunk-4H77LX3V.js.map +1 -0
- package/dist/chunk-4TXDD6P2.js +163 -0
- package/dist/chunk-4TXDD6P2.js.map +1 -0
- package/dist/chunk-AVBANQ67.js +295 -0
- package/dist/chunk-AVBANQ67.js.map +1 -0
- package/dist/{chunk-3PK3T4KD.js → chunk-JJGZ54EB.js} +44 -1
- package/dist/chunk-JJGZ54EB.js.map +1 -0
- package/dist/{chunk-VMY4TKMN.js → chunk-PEPXQTJ3.js} +921 -432
- package/dist/chunk-PEPXQTJ3.js.map +1 -0
- package/dist/chunk-U7DLCPJ6.js +203 -0
- package/dist/chunk-U7DLCPJ6.js.map +1 -0
- package/dist/{chunk-SAOAAA3S.js → chunk-UHXQ3KNX.js} +1 -22
- package/dist/chunk-UHXQ3KNX.js.map +1 -0
- package/dist/contract-DYbTzEDf.d.ts +122 -0
- package/dist/index.d.ts +5 -2
- package/dist/index.js +170 -88
- package/dist/interactions/index.d.ts +141 -0
- package/dist/interactions/index.js +59 -0
- package/dist/interactions/index.js.map +1 -0
- package/dist/parts-BeRnK54I.d.ts +185 -0
- package/dist/platform/index.d.ts +2 -270
- package/dist/platform/index.js +12 -278
- package/dist/platform/index.js.map +1 -1
- package/dist/preset-cloudflare/index.d.ts +0 -10
- package/dist/preset-cloudflare/index.js +1 -1
- package/dist/profile/index.d.ts +33 -2
- package/dist/profile/index.js +37 -1
- package/dist/profile/index.js.map +1 -1
- package/dist/sandbox/index.d.ts +47 -1
- package/dist/sandbox/index.js +11 -1
- package/dist/sso-Df4wtL8D.d.ts +270 -0
- package/dist/teams/index.js +9 -9
- package/dist/teams/invitations-api.js +3 -3
- package/dist/web-react/index.d.ts +206 -96
- package/dist/web-react/index.js +68 -22
- package/package.json +20 -1
- package/dist/chunk-3PK3T4KD.js.map +0 -1
- package/dist/chunk-SAOAAA3S.js.map +0 -1
- package/dist/chunk-VMY4TKMN.js.map +0 -1
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { c as ChatMessagePart } from '../parts-BeRnK54I.js';
|
|
2
|
+
export { B as BULK_DELETE_MAX_THREADS, C as ChatFilePart, a as ChatImagePart, b as ChatInteractionPart, d as ChatNoticePart, e as ChatPartTime, f as ChatReasoningPart, g as ChatStepFinishPart, h as ChatStepStartPart, i as ChatStoreInputError, j as ChatSubtaskPart, k as ChatTextPart, l as ChatToolPart, m as ChatToolState, n as ChatToolStatus, o as ChatUsageTokens, S as StorableHarnessPartKind, p as isChatInteractionPart, q as isChatStepFinishPart, r as isChatTextPart, s as isChatToolPart, t as threadTitleFromMessage } from '../parts-BeRnK54I.js';
|
|
3
|
+
import * as drizzle_orm from 'drizzle-orm';
|
|
4
|
+
import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core';
|
|
5
|
+
import { SQLiteColumnBuilderBase, AnySQLiteTable, AnySQLiteColumn, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
|
|
6
|
+
import '@tangle-network/agent-interface';
|
|
7
|
+
import '../contract-DYbTzEDf.js';
|
|
8
|
+
|
|
9
|
+
/** A product table referenced by FK — only the `id` column is touched. */
|
|
10
|
+
type ChatParentTable = AnySQLiteTable & {
|
|
11
|
+
id: AnySQLiteColumn;
|
|
12
|
+
};
|
|
13
|
+
interface CreateChatTablesOptions<TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {}, TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {}> {
|
|
14
|
+
/** The product's workspace table — threads reference `workspaceTable.id`
|
|
15
|
+
* with cascade. Omitted: `workspace_id` stays a plain indexed text column
|
|
16
|
+
* (products whose tenant table lives in another database). */
|
|
17
|
+
workspaceTable?: ChatParentTable;
|
|
18
|
+
/** Prefixes table AND index names (`'chat_'` → `chat_thread`,
|
|
19
|
+
* `idx_chat_thread_workspace`) for products that namespace chat tables in a
|
|
20
|
+
* shared database. Default: unprefixed `thread`/`message` (legal/gtm row
|
|
21
|
+
* compatibility). */
|
|
22
|
+
tablePrefix?: string;
|
|
23
|
+
/** Product columns merged into the thread table (the `/missions` extras
|
|
24
|
+
* pattern) — e.g. a `status` lifecycle enum or gtm's scope columns. */
|
|
25
|
+
threadExtraColumns?: TThreadExtras;
|
|
26
|
+
/** Product columns merged into the message table — e.g. legal's
|
|
27
|
+
* `vault_files`. */
|
|
28
|
+
messageExtraColumns?: TMessageExtras;
|
|
29
|
+
}
|
|
30
|
+
declare function createChatTables<TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {}, TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {}>(options?: CreateChatTablesOptions<TThreadExtras, TMessageExtras>): {
|
|
31
|
+
threads: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
|
|
32
|
+
name: `${string}thread`;
|
|
33
|
+
schema: undefined;
|
|
34
|
+
columns: {
|
|
35
|
+
id: drizzle_orm.HasDefault<drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>>;
|
|
36
|
+
workspaceId: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"workspace_id", [string, ...string[]], number | undefined>>;
|
|
37
|
+
title: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"title", [string, ...string[]], number | undefined>>;
|
|
38
|
+
category: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"category", [string, ...string[]], number | undefined>;
|
|
39
|
+
isPinned: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteBooleanBuilderInitial<"is_pinned">>>;
|
|
40
|
+
createdAt: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"created_at">>>;
|
|
41
|
+
updatedAt: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"updated_at">>>;
|
|
42
|
+
} & TThreadExtras extends infer T extends Record<string, drizzle_orm.ColumnBuilderBase<drizzle_orm.ColumnBuilderBaseConfig<drizzle_orm.ColumnDataType, string>, object>> ? { [Key in keyof T]: drizzle_orm.BuildColumn<TTableName, {
|
|
43
|
+
_: Omit<T[Key]["_"], "name"> & {
|
|
44
|
+
name: T[Key]["_"]["name"] extends "" ? drizzle_orm.Assume<Key, string> : T[Key]["_"]["name"];
|
|
45
|
+
};
|
|
46
|
+
}, TDialect>; } : never;
|
|
47
|
+
dialect: "sqlite";
|
|
48
|
+
}>;
|
|
49
|
+
messages: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
|
|
50
|
+
name: `${string}message`;
|
|
51
|
+
schema: undefined;
|
|
52
|
+
columns: {
|
|
53
|
+
id: drizzle_orm.HasDefault<drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>>;
|
|
54
|
+
threadId: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"thread_id", [string, ...string[]], number | undefined>>;
|
|
55
|
+
role: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"role", ["user", "assistant", "system", "tool"], number | undefined>>;
|
|
56
|
+
content: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"content", [string, ...string[]], number | undefined>>;
|
|
57
|
+
parts: drizzle_orm.HasDefault<drizzle_orm.$Type<drizzle_orm_sqlite_core.SQLiteTextJsonBuilderInitial<"parts">, ChatMessagePart[]>>;
|
|
58
|
+
toolName: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"tool_name", [string, ...string[]], number | undefined>;
|
|
59
|
+
model: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"model", [string, ...string[]], number | undefined>;
|
|
60
|
+
inputTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"input_tokens">;
|
|
61
|
+
outputTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"output_tokens">;
|
|
62
|
+
reasoningTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"reasoning_tokens">;
|
|
63
|
+
cacheReadTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"cache_read_tokens">;
|
|
64
|
+
cacheWriteTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"cache_write_tokens">;
|
|
65
|
+
costUsd: drizzle_orm_sqlite_core.SQLiteRealBuilderInitial<"cost_usd">;
|
|
66
|
+
createdAt: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"created_at">>>;
|
|
67
|
+
} & TMessageExtras extends infer T_1 extends Record<string, drizzle_orm.ColumnBuilderBase<drizzle_orm.ColumnBuilderBaseConfig<drizzle_orm.ColumnDataType, string>, object>> ? { [Key_1 in keyof T_1]: drizzle_orm.BuildColumn<TTableName, {
|
|
68
|
+
_: Omit<T_1[Key_1]["_"], "name"> & {
|
|
69
|
+
name: T_1[Key_1]["_"]["name"] extends "" ? drizzle_orm.Assume<Key_1, string> : T_1[Key_1]["_"]["name"];
|
|
70
|
+
};
|
|
71
|
+
}, TDialect>; } : never;
|
|
72
|
+
dialect: "sqlite";
|
|
73
|
+
}>;
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* The base (no-extras) table pair, pinned via an instantiation expression:
|
|
77
|
+
* `ReturnType<typeof createChatTables>` on the bare generic substitutes the
|
|
78
|
+
* extras params with their CONSTRAINT (`Record<string,
|
|
79
|
+
* SQLiteColumnBuilderBase>`), stamping an index signature into the column map
|
|
80
|
+
* that widens every concrete column to `unknown`/`notNull: false` — concrete
|
|
81
|
+
* factory results then fail `extends ChatTables`. (`teams`' `createTeamTables`
|
|
82
|
+
* is non-generic, so its plain `ReturnType` never hits this.)
|
|
83
|
+
*/
|
|
84
|
+
type ChatTables = ReturnType<typeof createChatTables<{}, {}>>;
|
|
85
|
+
type ChatThreadRow = ChatTables['threads']['$inferSelect'];
|
|
86
|
+
type ChatMessageRow = ChatTables['messages']['$inferSelect'];
|
|
87
|
+
type NewChatThreadRow = ChatTables['threads']['$inferInsert'];
|
|
88
|
+
type NewChatMessageRow = ChatTables['messages']['$inferInsert'];
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Typed CRUD over the tables from `createChatTables`. Works against any
|
|
92
|
+
* SQLite drizzle driver (D1, libsql, better-sqlite3) — builders are awaited,
|
|
93
|
+
* never `.run()`/`.all()`, so sync and async drivers behave identically.
|
|
94
|
+
*
|
|
95
|
+
* Access control is an injected seam, never an import: single-thread routes
|
|
96
|
+
* check workspace access themselves (they know the thread), while
|
|
97
|
+
* `bulkDeleteThreads` REQUIRES an `assertAccess` callback because one request
|
|
98
|
+
* can span workspaces — it is called once per distinct workspace and any
|
|
99
|
+
* throw rejects the whole request before a single delete runs (fail-closed;
|
|
100
|
+
* legal's bulk-delete semantics).
|
|
101
|
+
*
|
|
102
|
+
* Deletes run messages-first in ONE `db.batch` round trip when the driver has
|
|
103
|
+
* one (D1, libsql), so a partial failure never leaves orphaned rows behind a
|
|
104
|
+
* deleted thread; drivers without `batch` (better-sqlite3) fall back to
|
|
105
|
+
* sequential awaits in the same order.
|
|
106
|
+
*/
|
|
107
|
+
|
|
108
|
+
/** Any SQLite drizzle database — `any` erases the driver-specific run-result
|
|
109
|
+
* and schema generics so better-sqlite3, D1, and libsql handles all fit.
|
|
110
|
+
* `batch` is structural: present on D1/libsql drizzle instances. */
|
|
111
|
+
type ChatDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any> & {
|
|
112
|
+
batch?: (statements: [unknown, ...unknown[]]) => Promise<unknown[]>;
|
|
113
|
+
};
|
|
114
|
+
/** Product-injected access check. Throw to deny; the store never interprets
|
|
115
|
+
* users or roles itself. */
|
|
116
|
+
type WorkspaceAccessCheck = (workspaceId: string) => void | Promise<void>;
|
|
117
|
+
interface ListThreadsInput {
|
|
118
|
+
workspaceId: string;
|
|
119
|
+
/** Clamped to 1..200; default 50 (legal's list route semantics). */
|
|
120
|
+
limit?: number;
|
|
121
|
+
/** Clamped to >= 0; default 0. */
|
|
122
|
+
offset?: number;
|
|
123
|
+
}
|
|
124
|
+
interface ListThreadsResult<TThread = ChatThreadRow> {
|
|
125
|
+
threads: TThread[];
|
|
126
|
+
total: number;
|
|
127
|
+
limit: number;
|
|
128
|
+
offset: number;
|
|
129
|
+
}
|
|
130
|
+
interface CreateThreadInput {
|
|
131
|
+
workspaceId: string;
|
|
132
|
+
/** Title source when `title` is absent: first non-empty line, 80-char cap
|
|
133
|
+
* (`threadTitleFromMessage`). */
|
|
134
|
+
firstMessage?: string;
|
|
135
|
+
/** Explicit title; still normalized through `threadTitleFromMessage` so a
|
|
136
|
+
* multi-page paste never becomes a sidebar entry. */
|
|
137
|
+
title?: string;
|
|
138
|
+
category?: string | null;
|
|
139
|
+
isPinned?: boolean;
|
|
140
|
+
/** Opaque product-column values written verbatim in the SAME insert (the
|
|
141
|
+
* `/missions` extras pattern). Never read, validated, or defaulted here. */
|
|
142
|
+
extras?: Record<string, unknown>;
|
|
143
|
+
}
|
|
144
|
+
interface AppendMessageInput {
|
|
145
|
+
threadId: string;
|
|
146
|
+
role: 'user' | 'assistant' | 'system' | 'tool';
|
|
147
|
+
content: string;
|
|
148
|
+
parts?: ChatMessagePart[];
|
|
149
|
+
toolName?: string | null;
|
|
150
|
+
model?: string | null;
|
|
151
|
+
inputTokens?: number | null;
|
|
152
|
+
outputTokens?: number | null;
|
|
153
|
+
reasoningTokens?: number | null;
|
|
154
|
+
cacheReadTokens?: number | null;
|
|
155
|
+
cacheWriteTokens?: number | null;
|
|
156
|
+
costUsd?: number | null;
|
|
157
|
+
/** Opaque product-column values written verbatim in the SAME insert. */
|
|
158
|
+
extras?: Record<string, unknown>;
|
|
159
|
+
}
|
|
160
|
+
interface ListMessagesOptions {
|
|
161
|
+
limit?: number;
|
|
162
|
+
offset?: number;
|
|
163
|
+
}
|
|
164
|
+
interface BulkDeleteThreadsInput {
|
|
165
|
+
ids: string[];
|
|
166
|
+
/** Called once per distinct workspace the ids touch, before ANY delete. */
|
|
167
|
+
assertAccess: WorkspaceAccessCheck;
|
|
168
|
+
}
|
|
169
|
+
interface ChatStore<TThread = ChatThreadRow, TMessage = ChatMessageRow> {
|
|
170
|
+
listThreads(input: ListThreadsInput): Promise<ListThreadsResult<TThread>>;
|
|
171
|
+
getThread(threadId: string): Promise<TThread | null>;
|
|
172
|
+
createThread(input: CreateThreadInput): Promise<TThread>;
|
|
173
|
+
renameThread(threadId: string, title: string): Promise<TThread | null>;
|
|
174
|
+
pinThread(threadId: string, isPinned: boolean): Promise<TThread | null>;
|
|
175
|
+
/** Messages + thread in one batch. Resolves false when the thread does not
|
|
176
|
+
* exist. `assertAccess` (optional) receives the thread's workspaceId before
|
|
177
|
+
* the delete — single-thread callers usually check access themselves. */
|
|
178
|
+
deleteThread(threadId: string, options?: {
|
|
179
|
+
assertAccess?: WorkspaceAccessCheck;
|
|
180
|
+
}): Promise<boolean>;
|
|
181
|
+
bulkDeleteThreads(input: BulkDeleteThreadsInput): Promise<{
|
|
182
|
+
deleted: number;
|
|
183
|
+
}>;
|
|
184
|
+
/** Ordered oldest-first: `created_at`, then rowid (insertion order within a
|
|
185
|
+
* same-second burst — a user+assistant pair lands in one epoch second). */
|
|
186
|
+
listMessages(threadId: string, options?: ListMessagesOptions): Promise<TMessage[]>;
|
|
187
|
+
/** Inserts the message and bumps the thread's `updatedAt` in one batch so
|
|
188
|
+
* workspace recency sorts stay truthful. */
|
|
189
|
+
appendMessage(input: AppendMessageInput): Promise<TMessage>;
|
|
190
|
+
}
|
|
191
|
+
declare function createChatStore<TTables extends ChatTables>(db: ChatDatabase, tables: TTables): ChatStore<TTables['threads']['$inferSelect'], TTables['messages']['$inferSelect']>;
|
|
192
|
+
|
|
193
|
+
export { type AppendMessageInput, type BulkDeleteThreadsInput, type ChatDatabase, ChatMessagePart, type ChatMessageRow, type ChatParentTable, type ChatStore, type ChatTables, type ChatThreadRow, type CreateChatTablesOptions, type CreateThreadInput, type ListMessagesOptions, type ListThreadsInput, type ListThreadsResult, type NewChatMessageRow, type NewChatThreadRow, type WorkspaceAccessCheck, createChatStore, createChatTables };
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BULK_DELETE_MAX_THREADS,
|
|
3
|
+
ChatStoreInputError,
|
|
4
|
+
isChatInteractionPart,
|
|
5
|
+
isChatStepFinishPart,
|
|
6
|
+
isChatTextPart,
|
|
7
|
+
isChatToolPart,
|
|
8
|
+
threadTitleFromMessage
|
|
9
|
+
} from "../chunk-4H77LX3V.js";
|
|
10
|
+
|
|
11
|
+
// src/chat-store/schema.ts
|
|
12
|
+
import { sql } from "drizzle-orm";
|
|
13
|
+
import { index, integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
|
14
|
+
var hexId = () => text("id").primaryKey().default(sql`(lower(hex(randomblob(16))))`);
|
|
15
|
+
var createdAt = () => integer("created_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`);
|
|
16
|
+
var updatedAt = () => integer("updated_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`);
|
|
17
|
+
function createChatTables(options = {}) {
|
|
18
|
+
const { workspaceTable, tablePrefix = "" } = options;
|
|
19
|
+
const threadExtras = options.threadExtraColumns ?? {};
|
|
20
|
+
const messageExtras = options.messageExtraColumns ?? {};
|
|
21
|
+
const threads = sqliteTable(`${tablePrefix}thread`, {
|
|
22
|
+
id: hexId(),
|
|
23
|
+
workspaceId: workspaceTable ? text("workspace_id").notNull().references(() => workspaceTable.id, { onDelete: "cascade" }) : text("workspace_id").notNull(),
|
|
24
|
+
title: text("title").notNull(),
|
|
25
|
+
category: text("category"),
|
|
26
|
+
isPinned: integer("is_pinned", { mode: "boolean" }).notNull().default(false),
|
|
27
|
+
createdAt: createdAt(),
|
|
28
|
+
updatedAt: updatedAt(),
|
|
29
|
+
...threadExtras
|
|
30
|
+
}, (table) => [
|
|
31
|
+
index(`idx_${tablePrefix}thread_workspace`).on(table.workspaceId),
|
|
32
|
+
// Supports the store's list ordering (updatedAt desc within a workspace).
|
|
33
|
+
index(`idx_${tablePrefix}thread_workspace_updated`).on(table.workspaceId, table.updatedAt)
|
|
34
|
+
]);
|
|
35
|
+
const messages = sqliteTable(`${tablePrefix}message`, {
|
|
36
|
+
id: hexId(),
|
|
37
|
+
threadId: text("thread_id").notNull().references(() => threads.id, { onDelete: "cascade" }),
|
|
38
|
+
role: text("role", { enum: ["user", "assistant", "system", "tool"] }).notNull(),
|
|
39
|
+
content: text("content").notNull(),
|
|
40
|
+
parts: text("parts", { mode: "json" }).$type().default([]),
|
|
41
|
+
toolName: text("tool_name"),
|
|
42
|
+
model: text("model"),
|
|
43
|
+
// Usage receipt, flattened from the harness's `step-finish` shape
|
|
44
|
+
// (`tokens {input, output, reasoning, cache{read, write}}` + `cost`).
|
|
45
|
+
inputTokens: integer("input_tokens"),
|
|
46
|
+
outputTokens: integer("output_tokens"),
|
|
47
|
+
reasoningTokens: integer("reasoning_tokens"),
|
|
48
|
+
cacheReadTokens: integer("cache_read_tokens"),
|
|
49
|
+
cacheWriteTokens: integer("cache_write_tokens"),
|
|
50
|
+
costUsd: real("cost_usd"),
|
|
51
|
+
createdAt: createdAt(),
|
|
52
|
+
...messageExtras
|
|
53
|
+
}, (table) => [
|
|
54
|
+
index(`idx_${tablePrefix}message_thread`).on(table.threadId),
|
|
55
|
+
index(`idx_${tablePrefix}message_thread_created`).on(table.threadId, table.createdAt)
|
|
56
|
+
]);
|
|
57
|
+
return { threads, messages };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/chat-store/store.ts
|
|
61
|
+
import { asc, desc, eq, inArray, sql as sql2 } from "drizzle-orm";
|
|
62
|
+
async function runStatements(db, statements) {
|
|
63
|
+
if (typeof db.batch === "function") {
|
|
64
|
+
return await db.batch(statements);
|
|
65
|
+
}
|
|
66
|
+
const results = [];
|
|
67
|
+
for (const statement of statements) results.push(await statement);
|
|
68
|
+
return results;
|
|
69
|
+
}
|
|
70
|
+
function clampLimit(limit, fallback, max) {
|
|
71
|
+
const value = Number.isFinite(limit) ? Math.trunc(limit) : fallback;
|
|
72
|
+
return Math.min(Math.max(value, 1), max);
|
|
73
|
+
}
|
|
74
|
+
function clampOffset(offset) {
|
|
75
|
+
const value = Number.isFinite(offset) ? Math.trunc(offset) : 0;
|
|
76
|
+
return Math.max(value, 0);
|
|
77
|
+
}
|
|
78
|
+
function createChatStore(db, tables) {
|
|
79
|
+
const threads = tables.threads;
|
|
80
|
+
const messages = tables.messages;
|
|
81
|
+
return {
|
|
82
|
+
async listThreads(input) {
|
|
83
|
+
const limit = clampLimit(input.limit, 50, 200);
|
|
84
|
+
const offset = clampOffset(input.offset);
|
|
85
|
+
const scope = eq(threads.workspaceId, input.workspaceId);
|
|
86
|
+
const [list, [countRow]] = await Promise.all([
|
|
87
|
+
db.select().from(threads).where(scope).orderBy(desc(threads.updatedAt), asc(threads.id)).limit(limit).offset(offset),
|
|
88
|
+
db.select({ total: sql2`count(*)` }).from(threads).where(scope)
|
|
89
|
+
]);
|
|
90
|
+
return { threads: list, total: countRow?.total ?? 0, limit, offset };
|
|
91
|
+
},
|
|
92
|
+
async getThread(threadId) {
|
|
93
|
+
const [row] = await db.select().from(threads).where(eq(threads.id, threadId)).limit(1);
|
|
94
|
+
return row ?? null;
|
|
95
|
+
},
|
|
96
|
+
async createThread(input) {
|
|
97
|
+
const title = threadTitleFromMessage(input.title ?? input.firstMessage ?? "");
|
|
98
|
+
const values = {
|
|
99
|
+
workspaceId: input.workspaceId,
|
|
100
|
+
title,
|
|
101
|
+
...input.category !== void 0 ? { category: input.category } : {},
|
|
102
|
+
...input.isPinned !== void 0 ? { isPinned: input.isPinned } : {},
|
|
103
|
+
...input.extras ?? {}
|
|
104
|
+
};
|
|
105
|
+
const [row] = await db.insert(threads).values(values).returning();
|
|
106
|
+
if (!row) throw new Error("thread insert returned no row");
|
|
107
|
+
return row;
|
|
108
|
+
},
|
|
109
|
+
async renameThread(threadId, title) {
|
|
110
|
+
const trimmed = title.trim();
|
|
111
|
+
if (!trimmed) throw new ChatStoreInputError("Missing title");
|
|
112
|
+
const [row] = await db.update(threads).set({ title: trimmed, updatedAt: /* @__PURE__ */ new Date() }).where(eq(threads.id, threadId)).returning();
|
|
113
|
+
return row ?? null;
|
|
114
|
+
},
|
|
115
|
+
async pinThread(threadId, isPinned) {
|
|
116
|
+
const [row] = await db.update(threads).set({ isPinned, updatedAt: /* @__PURE__ */ new Date() }).where(eq(threads.id, threadId)).returning();
|
|
117
|
+
return row ?? null;
|
|
118
|
+
},
|
|
119
|
+
async deleteThread(threadId, options) {
|
|
120
|
+
const [existing] = await db.select({ id: threads.id, workspaceId: threads.workspaceId }).from(threads).where(eq(threads.id, threadId)).limit(1);
|
|
121
|
+
if (!existing) return false;
|
|
122
|
+
if (options?.assertAccess) await options.assertAccess(existing.workspaceId);
|
|
123
|
+
await runStatements(db, [
|
|
124
|
+
db.delete(messages).where(eq(messages.threadId, threadId)),
|
|
125
|
+
db.delete(threads).where(eq(threads.id, threadId))
|
|
126
|
+
]);
|
|
127
|
+
return true;
|
|
128
|
+
},
|
|
129
|
+
async bulkDeleteThreads(input) {
|
|
130
|
+
const { ids, assertAccess } = input;
|
|
131
|
+
if (typeof assertAccess !== "function") throw new ChatStoreInputError("Missing assertAccess");
|
|
132
|
+
if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === "string" && id.length > 0)) {
|
|
133
|
+
throw new ChatStoreInputError("Missing ids");
|
|
134
|
+
}
|
|
135
|
+
if (ids.length > BULK_DELETE_MAX_THREADS) {
|
|
136
|
+
throw new ChatStoreInputError(`Too many ids (max ${BULK_DELETE_MAX_THREADS})`);
|
|
137
|
+
}
|
|
138
|
+
const rows = await db.select({ id: threads.id, workspaceId: threads.workspaceId }).from(threads).where(inArray(threads.id, ids));
|
|
139
|
+
if (rows.length === 0) return { deleted: 0 };
|
|
140
|
+
const workspaceIds = [...new Set(rows.map((row) => row.workspaceId))].sort();
|
|
141
|
+
for (const workspaceId of workspaceIds) {
|
|
142
|
+
await assertAccess(workspaceId);
|
|
143
|
+
}
|
|
144
|
+
const foundIds = rows.map((row) => row.id);
|
|
145
|
+
await runStatements(db, [
|
|
146
|
+
db.delete(messages).where(inArray(messages.threadId, foundIds)),
|
|
147
|
+
db.delete(threads).where(inArray(threads.id, foundIds))
|
|
148
|
+
]);
|
|
149
|
+
return { deleted: foundIds.length };
|
|
150
|
+
},
|
|
151
|
+
async listMessages(threadId, options) {
|
|
152
|
+
const query = db.select().from(messages).where(eq(messages.threadId, threadId)).orderBy(asc(messages.createdAt), sql2`rowid`).$dynamic();
|
|
153
|
+
if (options?.limit !== void 0) query.limit(clampLimit(options.limit, 1, 1e3));
|
|
154
|
+
if (options?.offset !== void 0) query.offset(clampOffset(options.offset));
|
|
155
|
+
return await query;
|
|
156
|
+
},
|
|
157
|
+
async appendMessage(input) {
|
|
158
|
+
const values = {
|
|
159
|
+
threadId: input.threadId,
|
|
160
|
+
role: input.role,
|
|
161
|
+
content: input.content,
|
|
162
|
+
...input.parts !== void 0 ? { parts: input.parts } : {},
|
|
163
|
+
...input.toolName !== void 0 ? { toolName: input.toolName } : {},
|
|
164
|
+
...input.model !== void 0 ? { model: input.model } : {},
|
|
165
|
+
...input.inputTokens !== void 0 ? { inputTokens: input.inputTokens } : {},
|
|
166
|
+
...input.outputTokens !== void 0 ? { outputTokens: input.outputTokens } : {},
|
|
167
|
+
...input.reasoningTokens !== void 0 ? { reasoningTokens: input.reasoningTokens } : {},
|
|
168
|
+
...input.cacheReadTokens !== void 0 ? { cacheReadTokens: input.cacheReadTokens } : {},
|
|
169
|
+
...input.cacheWriteTokens !== void 0 ? { cacheWriteTokens: input.cacheWriteTokens } : {},
|
|
170
|
+
...input.costUsd !== void 0 ? { costUsd: input.costUsd } : {},
|
|
171
|
+
...input.extras ?? {}
|
|
172
|
+
};
|
|
173
|
+
const [insertResult] = await runStatements(db, [
|
|
174
|
+
db.insert(messages).values(values).returning(),
|
|
175
|
+
db.update(threads).set({ updatedAt: /* @__PURE__ */ new Date() }).where(eq(threads.id, input.threadId))
|
|
176
|
+
]);
|
|
177
|
+
const row = insertResult?.[0];
|
|
178
|
+
if (!row) throw new Error("message insert returned no row");
|
|
179
|
+
return row;
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
export {
|
|
184
|
+
BULK_DELETE_MAX_THREADS,
|
|
185
|
+
ChatStoreInputError,
|
|
186
|
+
createChatStore,
|
|
187
|
+
createChatTables,
|
|
188
|
+
isChatInteractionPart,
|
|
189
|
+
isChatStepFinishPart,
|
|
190
|
+
isChatTextPart,
|
|
191
|
+
isChatToolPart,
|
|
192
|
+
threadTitleFromMessage
|
|
193
|
+
};
|
|
194
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/chat-store/schema.ts","../../src/chat-store/store.ts"],"sourcesContent":["/**\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 reads,\n * validates, or defaults them).\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 } from 'drizzle-orm/sqlite-core'\nimport type { AnySQLiteColumn, AnySQLiteTable, SQLiteColumnBuilderBase } 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\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\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\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\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 ])\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 // 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 ])\n\n return { threads, messages }\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\nexport type ChatThreadRow = ChatTables['threads']['$inferSelect']\nexport type ChatMessageRow = ChatTables['messages']['$inferSelect']\nexport type NewChatThreadRow = ChatTables['threads']['$inferInsert']\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 { asc, desc, eq, inArray, sql } from 'drizzle-orm'\nimport type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport { BULK_DELETE_MAX_THREADS, ChatStoreInputError, threadTitleFromMessage } from './core'\nimport type { ChatMessagePart } from './parts'\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 batch?: (statements: [unknown, ...unknown[]]) => Promise<unknown[]>\n}\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\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\nexport interface ListThreadsResult<TThread = ChatThreadRow> {\n threads: TThread[]\n total: number\n limit: number\n offset: number\n}\n\nexport interface CreateThreadInput {\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\nexport interface AppendMessageInput {\n threadId: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[]\n toolName?: string | null\n model?: 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 /** Opaque product-column values written verbatim in the SAME insert. */\n extras?: Record<string, unknown>\n}\n\nexport interface ListMessagesOptions {\n limit?: number\n offset?: number\n}\n\nexport interface BulkDeleteThreadsInput {\n ids: string[]\n /** Called once per distinct workspace the ids touch, before ANY delete. */\n assertAccess: WorkspaceAccessCheck\n}\n\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 /** 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 /** 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}\n\n/** One driver round trip when `db.batch` exists; sequential awaits in the\n * given order otherwise. Statement order is the caller's integrity contract\n * (children before parents). */\nasync function runStatements(\n db: ChatDatabase,\n statements: [unknown, ...unknown[]],\n): Promise<unknown[]> {\n if (typeof db.batch === 'function') {\n return await db.batch(statements)\n }\n const results: unknown[] = []\n for (const statement of statements) results.push(await statement)\n return results\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\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 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 runStatements(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, 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\n const rows = await db.select({ id: threads.id, workspaceId: threads.workspaceId })\n .from(threads)\n .where(inArray(threads.id, ids))\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 runStatements(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 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 appendMessage(input) {\n const values = {\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.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 runStatements(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}\n"],"mappings":";;;;;;;;;;;AAwCA,SAAS,WAAW;AACpB,SAAS,OAAO,SAAS,MAAM,aAAa,YAAY;AA4BxD,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;AAElG,SAAS,iBAGd,UAAkE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|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// src/chat-store/core.ts
|
|
2
|
+
var BULK_DELETE_MAX_THREADS = 200;
|
|
3
|
+
var ChatStoreInputError = class extends Error {
|
|
4
|
+
constructor(message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "ChatStoreInputError";
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
function threadTitleFromMessage(message) {
|
|
10
|
+
const firstLine = message.split("\n").find((l) => l.trim().length > 0)?.trim() ?? "";
|
|
11
|
+
if (!firstLine) return "New Thread";
|
|
12
|
+
return firstLine.length > 80 ? `${firstLine.slice(0, 79)}\u2026` : firstLine;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// src/chat-store/parts.ts
|
|
16
|
+
function isChatToolPart(part) {
|
|
17
|
+
return part.type === "tool";
|
|
18
|
+
}
|
|
19
|
+
function isChatTextPart(part) {
|
|
20
|
+
return part.type === "text";
|
|
21
|
+
}
|
|
22
|
+
function isChatInteractionPart(part) {
|
|
23
|
+
return part.type === "interaction";
|
|
24
|
+
}
|
|
25
|
+
function isChatStepFinishPart(part) {
|
|
26
|
+
return part.type === "step-finish";
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export {
|
|
30
|
+
BULK_DELETE_MAX_THREADS,
|
|
31
|
+
ChatStoreInputError,
|
|
32
|
+
threadTitleFromMessage,
|
|
33
|
+
isChatToolPart,
|
|
34
|
+
isChatTextPart,
|
|
35
|
+
isChatInteractionPart,
|
|
36
|
+
isChatStepFinishPart
|
|
37
|
+
};
|
|
38
|
+
//# sourceMappingURL=chunk-4H77LX3V.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/chat-store/core.ts","../src/chat-store/parts.ts"],"sourcesContent":["/**\n * Pure (drizzle-free) pieces of the chat store: thread-title derivation, the\n * bulk-delete bound, and the typed input error. Split from `./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\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 * The stored shape of `message.parts` — one typed vocabulary for every part a\n * product persists into a chat transcript. NOT an ad-hoc union reverse-\n * engineered from product schemas; each member is matched field-for-field to\n * its canonical source:\n *\n * - `text` / `reasoning` / `tool`: the persisted projection `/stream`'s\n * `normalizePersistedPart` produces from the harness lane's\n * `message.part.updated` events (ADC sidecar\n * `apps/sidecar/src/events/session-events.ts:56` wraps the canonical part in\n * an `{id, sessionID, messageID}` envelope; the projection strips the\n * session/message ids and keeps the per-segment part id).\n * - `file` / `image` / `step-start` / `step-finish`: the sidecar's canonical\n * `MessagePartSchema` members (ADC\n * `apps/sidecar/src/schemas/agent-schemas.ts:50-154`); `step-finish` carries\n * the harness's per-step usage receipt — tokens\n * `{total, input, output, reasoning, cache{write, read}}` + `cost` — which is\n * also the shape the message-level token/cost columns mirror.\n * - `subtask`: `@tangle-network/agent-interface`'s `SubtaskPart` (a spawned\n * sub-agent task).\n * - `interaction` / `notice`: the persisted-part codecs in\n * `/web-react`'s chat-interactions contract (`interactionToPersistedPart`,\n * `noticePart`) — type-only imports, one source of truth for their statuses\n * and field shapes.\n *\n * `@tangle-network/agent-interface` exports the canonical wire `Part` union,\n * but its `PartBase` requires the `sessionID`/`messageID` stream envelope that\n * is deliberately NOT persisted, so the stored union is defined here as the\n * envelope-free projection (a type-level coverage check against the peer's\n * `Part['type']` lives in the tests). Contribute-down candidate: if\n * agent-interface grows envelope-free persisted-part types, re-export them\n * here and delete these definitions.\n *\n * Two transport lanes serialize into this SAME stored shape:\n * - harness lane: canonical `message.part.updated` parts, merged/normalized by\n * `/stream` (`mergePersistedPart`, `finalizeAssistantParts`);\n * - router/openai-compat lane: `text_delta`/`tool_call` stream events are\n * mapped INTO canonical part events first (`/runtime`'s `toLoopEvents` +\n * `/stream`'s `normalizeToolEvent`) and then persisted identically — the\n * store never sees a router-specific shape.\n */\n\nimport type { Part as HarnessWirePart } from '@tangle-network/agent-interface'\nimport type {\n ChatInteractionField,\n ChatInteractionStatus,\n InteractionPersistedPart,\n NoticeKind,\n NoticePersistedPart,\n} from '../web-react/chat-interactions'\n\n/** Start/end wall-clock millis, as normalized by `/stream`'s `normalizeTime`. */\nexport interface ChatPartTime {\n start?: number\n end?: number\n}\n\n/** `id` is the harness's per-segment identity; absent on legacy/router parts,\n * which collapse to a single logical text stream. Never invented client-side. */\nexport interface ChatTextPart {\n type: 'text'\n text: string\n id?: string\n}\n\nexport interface ChatReasoningPart {\n type: 'reasoning'\n text: string\n id?: string\n time?: ChatPartTime\n}\n\n/** Superset of the sidecar's status enum (`pending|running|completed|failed`)\n * and agent-interface's `ToolState` statuses; `error` is the persisted\n * terminal form `/stream`'s `normalizePersistedPart` settles on. */\nexport type ChatToolStatus = 'pending' | 'running' | 'completed' | 'error' | 'failed'\n\nexport interface ChatToolState {\n status: ChatToolStatus\n input?: unknown\n output?: unknown\n error?: string\n title?: string\n metadata?: Record<string, unknown>\n time?: ChatPartTime\n}\n\nexport interface ChatToolPart {\n type: 'tool'\n id: string\n tool: string\n callID?: string\n state: ChatToolState\n}\n\n/** Union of the sidecar's legacy (path-based) and AI-SDK (url-based) file\n * shapes; response-side every field besides `type` is optional. */\nexport interface ChatFilePart {\n type: 'file'\n id?: string\n filename?: string\n mediaType?: string\n url?: string\n path?: string\n content?: string\n}\n\nexport interface ChatImagePart {\n type: 'image'\n filename?: string\n mediaType?: string\n url?: string\n path?: string\n}\n\nexport interface ChatSubtaskPart {\n type: 'subtask'\n prompt: string\n description: string\n agent: string\n id?: string\n}\n\n/** OpenCode step-boundary marker — no renderable text; preserved so mappers\n * never coerce it into a \"[object Object]\" text part. */\nexport interface ChatStepStartPart {\n type: 'step-start'\n}\n\n/** Per-step usage receipt as the harness reports it (sidecar\n * `StepFinishPartSchema`). The message-level token/cost columns are this\n * shape flattened. */\nexport interface ChatUsageTokens {\n total?: number\n input?: number\n output?: number\n reasoning?: number\n cache?: {\n write?: number\n read?: number\n }\n}\n\nexport interface ChatStepFinishPart {\n type: 'step-finish'\n reason?: string\n tokens?: ChatUsageTokens\n cost?: number\n}\n\n/** Persisted human-in-the-loop ask — byte-matches\n * `interactionToPersistedPart` in `/web-react`'s chat-interactions contract. */\nexport interface ChatInteractionPart {\n type: 'interaction'\n id: string\n kind: string\n title: string\n body?: string\n answerSpec: { fields: ChatInteractionField[] }\n status: ChatInteractionStatus\n cancelReason?: string\n}\n\n/** Persisted one-line transcript notice — byte-matches `noticePart` in\n * `/web-react`'s chat-interactions contract. */\nexport interface ChatNoticePart {\n type: 'notice'\n id: string\n noticeKind: NoticeKind\n text: string\n}\n\n// The \"byte-matches\" claims above, enforced at compile time: the interaction\n// contract's codec output types and the stored part types must stay mutually\n// assignable, so a codec field added on one side without the other fails here.\ntype MutuallyAssignable<A extends B, B> = A\ntype _CodecEmitsStorableInteractionPart = MutuallyAssignable<InteractionPersistedPart, ChatInteractionPart>\ntype _StoredInteractionPartFeedsCodec = MutuallyAssignable<ChatInteractionPart, InteractionPersistedPart>\ntype _CodecEmitsStorableNoticePart = MutuallyAssignable<NoticePersistedPart, ChatNoticePart>\ntype _StoredNoticePartFeedsCodec = MutuallyAssignable<ChatNoticePart, NoticePersistedPart>\n\nexport type ChatMessagePart =\n | ChatTextPart\n | ChatReasoningPart\n | ChatToolPart\n | ChatFilePart\n | ChatImagePart\n | ChatSubtaskPart\n | ChatStepStartPart\n | ChatStepFinishPart\n | ChatInteractionPart\n | ChatNoticePart\n\n/** Every canonical harness wire-part kind must be storable — compile-time\n * guarantee that a new agent-interface part kind cannot silently fall out of\n * the persisted vocabulary. */\nexport type StorableHarnessPartKind = HarnessWirePart['type'] & ChatMessagePart['type']\n\nexport function isChatToolPart(part: ChatMessagePart): part is ChatToolPart {\n return part.type === 'tool'\n}\n\nexport function isChatTextPart(part: ChatMessagePart): part is ChatTextPart {\n return part.type === 'text'\n}\n\nexport function isChatInteractionPart(part: ChatMessagePart): part is ChatInteractionPart {\n return part.type === 'interaction'\n}\n\nexport function isChatStepFinishPart(part: ChatMessagePart): part is ChatStepFinishPart {\n return part.type === 'step-finish'\n}\n"],"mappings":";AAUO,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;;;AC0KO,SAAS,eAAe,MAA6C;AAC1E,SAAO,KAAK,SAAS;AACvB;AAEO,SAAS,eAAe,MAA6C;AAC1E,SAAO,KAAK,SAAS;AACvB;AAEO,SAAS,sBAAsB,MAAoD;AACxF,SAAO,KAAK,SAAS;AACvB;AAEO,SAAS,qBAAqB,MAAmD;AACtF,SAAO,KAAK,SAAS;AACvB;","names":[]}
|