@tangle-network/agent-app 0.43.24 → 0.43.26
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 +2 -0
- package/dist/assistant/index.js +3 -1
- package/dist/assistant/index.js.map +1 -1
- package/dist/chat-routes/index.d.ts +276 -0
- package/dist/chat-routes/index.js +564 -0
- package/dist/chat-routes/index.js.map +1 -0
- package/dist/chat-store/index.d.ts +194 -0
- package/dist/chat-store/index.js +198 -0
- package/dist/chat-store/index.js.map +1 -0
- package/dist/chunk-4TXDD6P2.js +163 -0
- package/dist/chunk-4TXDD6P2.js.map +1 -0
- package/dist/chunk-5EQCITY3.js +20 -0
- package/dist/chunk-5EQCITY3.js.map +1 -0
- package/dist/chunk-5SV5PSU7.js +80 -0
- package/dist/chunk-5SV5PSU7.js.map +1 -0
- package/dist/chunk-7LNGJDNA.js +1 -0
- package/dist/chunk-7LNGJDNA.js.map +1 -0
- package/dist/{chunk-77RLNLFP.js → chunk-ATRJULKZ.js} +41 -5
- package/dist/chunk-ATRJULKZ.js.map +1 -0
- package/dist/{chunk-VMY4TKMN.js → chunk-FCQP75JT.js} +936 -436
- package/dist/chunk-FCQP75JT.js.map +1 -0
- package/dist/chunk-I2R2XT4M.js +62 -0
- package/dist/chunk-I2R2XT4M.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-TKVJE63N.js +304 -0
- package/dist/chunk-TKVJE63N.js.map +1 -0
- package/dist/{chunk-SAOAAA3S.js → chunk-UHXQ3KNX.js} +1 -22
- package/dist/chunk-UHXQ3KNX.js.map +1 -0
- package/dist/chunk-Y4QHNQ75.js +203 -0
- package/dist/chunk-Y4QHNQ75.js.map +1 -0
- package/dist/contract-DYbTzEDf.d.ts +122 -0
- package/dist/core-7qIM7svy.d.ts +21 -0
- package/dist/index.d.ts +6 -2
- package/dist/index.js +179 -92
- package/dist/interactions/index.d.ts +141 -0
- package/dist/interactions/index.js +60 -0
- package/dist/interactions/index.js.map +1 -0
- package/dist/parts-BcbitSNp.d.ts +176 -0
- package/dist/platform/index.d.ts +2 -270
- package/dist/platform/index.js +14 -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-CNOsARMJ.d.ts +285 -0
- package/dist/stream/index.js +1 -1
- package/dist/teams/index.js +9 -9
- package/dist/teams/invitations-api.js +3 -3
- package/dist/web-react/index.d.ts +229 -99
- package/dist/web-react/index.js +72 -22
- package/dist/wire-BaUF66AS.d.ts +61 -0
- package/package.json +25 -1
- package/dist/chunk-3PK3T4KD.js.map +0 -1
- package/dist/chunk-77RLNLFP.js.map +0 -1
- package/dist/chunk-SAOAAA3S.js.map +0 -1
- package/dist/chunk-VMY4TKMN.js.map +0 -1
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
export { B as BULK_DELETE_MAX_THREADS, C as ChatStoreInputError, t as threadTitleFromMessage } from '../core-7qIM7svy.js';
|
|
2
|
+
import { c as ChatMessagePart } from '../parts-BcbitSNp.js';
|
|
3
|
+
export { 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 ChatSubtaskPart, j as ChatTextPart, k as ChatToolPart, l as ChatToolState, m as ChatToolStatus, n as ChatUsageTokens, S as StorableHarnessPartKind, o as isChatInteractionPart, p as isChatStepFinishPart, q as isChatTextPart, r as isChatToolPart, t as toChatMessageParts } from '../parts-BcbitSNp.js';
|
|
4
|
+
import * as drizzle_orm from 'drizzle-orm';
|
|
5
|
+
import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core';
|
|
6
|
+
import { SQLiteColumnBuilderBase, AnySQLiteTable, AnySQLiteColumn, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
|
|
7
|
+
import '@tangle-network/agent-interface';
|
|
8
|
+
import '../contract-DYbTzEDf.js';
|
|
9
|
+
|
|
10
|
+
/** A product table referenced by FK — only the `id` column is touched. */
|
|
11
|
+
type ChatParentTable = AnySQLiteTable & {
|
|
12
|
+
id: AnySQLiteColumn;
|
|
13
|
+
};
|
|
14
|
+
interface CreateChatTablesOptions<TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {}, TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {}> {
|
|
15
|
+
/** The product's workspace table — threads reference `workspaceTable.id`
|
|
16
|
+
* with cascade. Omitted: `workspace_id` stays a plain indexed text column
|
|
17
|
+
* (products whose tenant table lives in another database). */
|
|
18
|
+
workspaceTable?: ChatParentTable;
|
|
19
|
+
/** Prefixes table AND index names (`'chat_'` → `chat_thread`,
|
|
20
|
+
* `idx_chat_thread_workspace`) for products that namespace chat tables in a
|
|
21
|
+
* shared database. Default: unprefixed `thread`/`message` (legal/gtm row
|
|
22
|
+
* compatibility). */
|
|
23
|
+
tablePrefix?: string;
|
|
24
|
+
/** Product columns merged into the thread table (the `/missions` extras
|
|
25
|
+
* pattern) — e.g. a `status` lifecycle enum or gtm's scope columns. */
|
|
26
|
+
threadExtraColumns?: TThreadExtras;
|
|
27
|
+
/** Product columns merged into the message table — e.g. legal's
|
|
28
|
+
* `vault_files`. */
|
|
29
|
+
messageExtraColumns?: TMessageExtras;
|
|
30
|
+
}
|
|
31
|
+
declare function createChatTables<TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {}, TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {}>(options?: CreateChatTablesOptions<TThreadExtras, TMessageExtras>): {
|
|
32
|
+
threads: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
|
|
33
|
+
name: `${string}thread`;
|
|
34
|
+
schema: undefined;
|
|
35
|
+
columns: {
|
|
36
|
+
id: drizzle_orm.HasDefault<drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>>;
|
|
37
|
+
workspaceId: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"workspace_id", [string, ...string[]], number | undefined>>;
|
|
38
|
+
title: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"title", [string, ...string[]], number | undefined>>;
|
|
39
|
+
category: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"category", [string, ...string[]], number | undefined>;
|
|
40
|
+
isPinned: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteBooleanBuilderInitial<"is_pinned">>>;
|
|
41
|
+
createdAt: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"created_at">>>;
|
|
42
|
+
updatedAt: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"updated_at">>>;
|
|
43
|
+
} & 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, {
|
|
44
|
+
_: Omit<T[Key]["_"], "name"> & {
|
|
45
|
+
name: T[Key]["_"]["name"] extends "" ? drizzle_orm.Assume<Key, string> : T[Key]["_"]["name"];
|
|
46
|
+
};
|
|
47
|
+
}, TDialect>; } : never;
|
|
48
|
+
dialect: "sqlite";
|
|
49
|
+
}>;
|
|
50
|
+
messages: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
|
|
51
|
+
name: `${string}message`;
|
|
52
|
+
schema: undefined;
|
|
53
|
+
columns: {
|
|
54
|
+
id: drizzle_orm.HasDefault<drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>>;
|
|
55
|
+
threadId: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"thread_id", [string, ...string[]], number | undefined>>;
|
|
56
|
+
role: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"role", ["user", "assistant", "system", "tool"], number | undefined>>;
|
|
57
|
+
content: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"content", [string, ...string[]], number | undefined>>;
|
|
58
|
+
parts: drizzle_orm.HasDefault<drizzle_orm.$Type<drizzle_orm_sqlite_core.SQLiteTextJsonBuilderInitial<"parts">, ChatMessagePart[]>>;
|
|
59
|
+
toolName: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"tool_name", [string, ...string[]], number | undefined>;
|
|
60
|
+
model: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"model", [string, ...string[]], number | undefined>;
|
|
61
|
+
inputTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"input_tokens">;
|
|
62
|
+
outputTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"output_tokens">;
|
|
63
|
+
reasoningTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"reasoning_tokens">;
|
|
64
|
+
cacheReadTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"cache_read_tokens">;
|
|
65
|
+
cacheWriteTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"cache_write_tokens">;
|
|
66
|
+
costUsd: drizzle_orm_sqlite_core.SQLiteRealBuilderInitial<"cost_usd">;
|
|
67
|
+
createdAt: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"created_at">>>;
|
|
68
|
+
} & 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, {
|
|
69
|
+
_: Omit<T_1[Key_1]["_"], "name"> & {
|
|
70
|
+
name: T_1[Key_1]["_"]["name"] extends "" ? drizzle_orm.Assume<Key_1, string> : T_1[Key_1]["_"]["name"];
|
|
71
|
+
};
|
|
72
|
+
}, TDialect>; } : never;
|
|
73
|
+
dialect: "sqlite";
|
|
74
|
+
}>;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* The base (no-extras) table pair, pinned via an instantiation expression:
|
|
78
|
+
* `ReturnType<typeof createChatTables>` on the bare generic substitutes the
|
|
79
|
+
* extras params with their CONSTRAINT (`Record<string,
|
|
80
|
+
* SQLiteColumnBuilderBase>`), stamping an index signature into the column map
|
|
81
|
+
* that widens every concrete column to `unknown`/`notNull: false` — concrete
|
|
82
|
+
* factory results then fail `extends ChatTables`. (`teams`' `createTeamTables`
|
|
83
|
+
* is non-generic, so its plain `ReturnType` never hits this.)
|
|
84
|
+
*/
|
|
85
|
+
type ChatTables = ReturnType<typeof createChatTables<{}, {}>>;
|
|
86
|
+
type ChatThreadRow = ChatTables['threads']['$inferSelect'];
|
|
87
|
+
type ChatMessageRow = ChatTables['messages']['$inferSelect'];
|
|
88
|
+
type NewChatThreadRow = ChatTables['threads']['$inferInsert'];
|
|
89
|
+
type NewChatMessageRow = ChatTables['messages']['$inferInsert'];
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Typed CRUD over the tables from `createChatTables`. Works against any
|
|
93
|
+
* SQLite drizzle driver (D1, libsql, better-sqlite3) — builders are awaited,
|
|
94
|
+
* never `.run()`/`.all()`, so sync and async drivers behave identically.
|
|
95
|
+
*
|
|
96
|
+
* Access control is an injected seam, never an import: single-thread routes
|
|
97
|
+
* check workspace access themselves (they know the thread), while
|
|
98
|
+
* `bulkDeleteThreads` REQUIRES an `assertAccess` callback because one request
|
|
99
|
+
* can span workspaces — it is called once per distinct workspace and any
|
|
100
|
+
* throw rejects the whole request before a single delete runs (fail-closed;
|
|
101
|
+
* legal's bulk-delete semantics).
|
|
102
|
+
*
|
|
103
|
+
* Deletes run messages-first in ONE `db.batch` round trip when the driver has
|
|
104
|
+
* one (D1, libsql), so a partial failure never leaves orphaned rows behind a
|
|
105
|
+
* deleted thread; drivers without `batch` (better-sqlite3) fall back to
|
|
106
|
+
* sequential awaits in the same order.
|
|
107
|
+
*/
|
|
108
|
+
|
|
109
|
+
/** Any SQLite drizzle database — `any` erases the driver-specific run-result
|
|
110
|
+
* and schema generics so better-sqlite3, D1, and libsql handles all fit.
|
|
111
|
+
* `batch` is structural: present on D1/libsql drizzle instances. */
|
|
112
|
+
type ChatDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any> & {
|
|
113
|
+
batch?: (statements: [unknown, ...unknown[]]) => Promise<unknown[]>;
|
|
114
|
+
};
|
|
115
|
+
/** Product-injected access check. Throw to deny; the store never interprets
|
|
116
|
+
* users or roles itself. */
|
|
117
|
+
type WorkspaceAccessCheck = (workspaceId: string) => void | Promise<void>;
|
|
118
|
+
interface ListThreadsInput {
|
|
119
|
+
workspaceId: string;
|
|
120
|
+
/** Clamped to 1..200; default 50 (legal's list route semantics). */
|
|
121
|
+
limit?: number;
|
|
122
|
+
/** Clamped to >= 0; default 0. */
|
|
123
|
+
offset?: number;
|
|
124
|
+
}
|
|
125
|
+
interface ListThreadsResult<TThread = ChatThreadRow> {
|
|
126
|
+
threads: TThread[];
|
|
127
|
+
total: number;
|
|
128
|
+
limit: number;
|
|
129
|
+
offset: number;
|
|
130
|
+
}
|
|
131
|
+
interface CreateThreadInput {
|
|
132
|
+
workspaceId: string;
|
|
133
|
+
/** Title source when `title` is absent: first non-empty line, 80-char cap
|
|
134
|
+
* (`threadTitleFromMessage`). */
|
|
135
|
+
firstMessage?: string;
|
|
136
|
+
/** Explicit title; still normalized through `threadTitleFromMessage` so a
|
|
137
|
+
* multi-page paste never becomes a sidebar entry. */
|
|
138
|
+
title?: string;
|
|
139
|
+
category?: string | null;
|
|
140
|
+
isPinned?: boolean;
|
|
141
|
+
/** Opaque product-column values written verbatim in the SAME insert (the
|
|
142
|
+
* `/missions` extras pattern). Never read, validated, or defaulted here. */
|
|
143
|
+
extras?: Record<string, unknown>;
|
|
144
|
+
}
|
|
145
|
+
interface AppendMessageInput {
|
|
146
|
+
threadId: string;
|
|
147
|
+
role: 'user' | 'assistant' | 'system' | 'tool';
|
|
148
|
+
content: string;
|
|
149
|
+
parts?: ChatMessagePart[];
|
|
150
|
+
toolName?: string | null;
|
|
151
|
+
model?: string | null;
|
|
152
|
+
inputTokens?: number | null;
|
|
153
|
+
outputTokens?: number | null;
|
|
154
|
+
reasoningTokens?: number | null;
|
|
155
|
+
cacheReadTokens?: number | null;
|
|
156
|
+
cacheWriteTokens?: number | null;
|
|
157
|
+
costUsd?: number | null;
|
|
158
|
+
/** Opaque product-column values written verbatim in the SAME insert. */
|
|
159
|
+
extras?: Record<string, unknown>;
|
|
160
|
+
}
|
|
161
|
+
interface ListMessagesOptions {
|
|
162
|
+
limit?: number;
|
|
163
|
+
offset?: number;
|
|
164
|
+
}
|
|
165
|
+
interface BulkDeleteThreadsInput {
|
|
166
|
+
ids: string[];
|
|
167
|
+
/** Called once per distinct workspace the ids touch, before ANY delete. */
|
|
168
|
+
assertAccess: WorkspaceAccessCheck;
|
|
169
|
+
}
|
|
170
|
+
interface ChatStore<TThread = ChatThreadRow, TMessage = ChatMessageRow> {
|
|
171
|
+
listThreads(input: ListThreadsInput): Promise<ListThreadsResult<TThread>>;
|
|
172
|
+
getThread(threadId: string): Promise<TThread | null>;
|
|
173
|
+
createThread(input: CreateThreadInput): Promise<TThread>;
|
|
174
|
+
renameThread(threadId: string, title: string): Promise<TThread | null>;
|
|
175
|
+
pinThread(threadId: string, isPinned: boolean): Promise<TThread | null>;
|
|
176
|
+
/** Messages + thread in one batch. Resolves false when the thread does not
|
|
177
|
+
* exist. `assertAccess` (optional) receives the thread's workspaceId before
|
|
178
|
+
* the delete — single-thread callers usually check access themselves. */
|
|
179
|
+
deleteThread(threadId: string, options?: {
|
|
180
|
+
assertAccess?: WorkspaceAccessCheck;
|
|
181
|
+
}): Promise<boolean>;
|
|
182
|
+
bulkDeleteThreads(input: BulkDeleteThreadsInput): Promise<{
|
|
183
|
+
deleted: number;
|
|
184
|
+
}>;
|
|
185
|
+
/** Ordered oldest-first: `created_at`, then rowid (insertion order within a
|
|
186
|
+
* same-second burst — a user+assistant pair lands in one epoch second). */
|
|
187
|
+
listMessages(threadId: string, options?: ListMessagesOptions): Promise<TMessage[]>;
|
|
188
|
+
/** Inserts the message and bumps the thread's `updatedAt` in one batch so
|
|
189
|
+
* workspace recency sorts stay truthful. */
|
|
190
|
+
appendMessage(input: AppendMessageInput): Promise<TMessage>;
|
|
191
|
+
}
|
|
192
|
+
declare function createChatStore<TTables extends ChatTables>(db: ChatDatabase, tables: TTables): ChatStore<TTables['threads']['$inferSelect'], TTables['messages']['$inferSelect']>;
|
|
193
|
+
|
|
194
|
+
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,198 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BULK_DELETE_MAX_THREADS,
|
|
3
|
+
ChatStoreInputError,
|
|
4
|
+
threadTitleFromMessage
|
|
5
|
+
} from "../chunk-5EQCITY3.js";
|
|
6
|
+
import {
|
|
7
|
+
isChatInteractionPart,
|
|
8
|
+
isChatStepFinishPart,
|
|
9
|
+
isChatTextPart,
|
|
10
|
+
isChatToolPart,
|
|
11
|
+
toChatMessageParts
|
|
12
|
+
} from "../chunk-I2R2XT4M.js";
|
|
13
|
+
|
|
14
|
+
// src/chat-store/schema.ts
|
|
15
|
+
import { sql } from "drizzle-orm";
|
|
16
|
+
import { index, integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
|
17
|
+
var hexId = () => text("id").primaryKey().default(sql`(lower(hex(randomblob(16))))`);
|
|
18
|
+
var createdAt = () => integer("created_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`);
|
|
19
|
+
var updatedAt = () => integer("updated_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`);
|
|
20
|
+
function createChatTables(options = {}) {
|
|
21
|
+
const { workspaceTable, tablePrefix = "" } = options;
|
|
22
|
+
const threadExtras = options.threadExtraColumns ?? {};
|
|
23
|
+
const messageExtras = options.messageExtraColumns ?? {};
|
|
24
|
+
const threads = sqliteTable(`${tablePrefix}thread`, {
|
|
25
|
+
id: hexId(),
|
|
26
|
+
workspaceId: workspaceTable ? text("workspace_id").notNull().references(() => workspaceTable.id, { onDelete: "cascade" }) : text("workspace_id").notNull(),
|
|
27
|
+
title: text("title").notNull(),
|
|
28
|
+
category: text("category"),
|
|
29
|
+
isPinned: integer("is_pinned", { mode: "boolean" }).notNull().default(false),
|
|
30
|
+
createdAt: createdAt(),
|
|
31
|
+
updatedAt: updatedAt(),
|
|
32
|
+
...threadExtras
|
|
33
|
+
}, (table) => [
|
|
34
|
+
index(`idx_${tablePrefix}thread_workspace`).on(table.workspaceId),
|
|
35
|
+
// Supports the store's list ordering (updatedAt desc within a workspace).
|
|
36
|
+
index(`idx_${tablePrefix}thread_workspace_updated`).on(table.workspaceId, table.updatedAt)
|
|
37
|
+
]);
|
|
38
|
+
const messages = sqliteTable(`${tablePrefix}message`, {
|
|
39
|
+
id: hexId(),
|
|
40
|
+
threadId: text("thread_id").notNull().references(() => threads.id, { onDelete: "cascade" }),
|
|
41
|
+
role: text("role", { enum: ["user", "assistant", "system", "tool"] }).notNull(),
|
|
42
|
+
content: text("content").notNull(),
|
|
43
|
+
parts: text("parts", { mode: "json" }).$type().default([]),
|
|
44
|
+
toolName: text("tool_name"),
|
|
45
|
+
model: text("model"),
|
|
46
|
+
// Usage receipt, flattened from the harness's `step-finish` shape
|
|
47
|
+
// (`tokens {input, output, reasoning, cache{read, write}}` + `cost`).
|
|
48
|
+
inputTokens: integer("input_tokens"),
|
|
49
|
+
outputTokens: integer("output_tokens"),
|
|
50
|
+
reasoningTokens: integer("reasoning_tokens"),
|
|
51
|
+
cacheReadTokens: integer("cache_read_tokens"),
|
|
52
|
+
cacheWriteTokens: integer("cache_write_tokens"),
|
|
53
|
+
costUsd: real("cost_usd"),
|
|
54
|
+
createdAt: createdAt(),
|
|
55
|
+
...messageExtras
|
|
56
|
+
}, (table) => [
|
|
57
|
+
index(`idx_${tablePrefix}message_thread`).on(table.threadId),
|
|
58
|
+
index(`idx_${tablePrefix}message_thread_created`).on(table.threadId, table.createdAt)
|
|
59
|
+
]);
|
|
60
|
+
return { threads, messages };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// src/chat-store/store.ts
|
|
64
|
+
import { asc, desc, eq, inArray, sql as sql2 } from "drizzle-orm";
|
|
65
|
+
async function runStatements(db, statements) {
|
|
66
|
+
if (typeof db.batch === "function") {
|
|
67
|
+
return await db.batch(statements);
|
|
68
|
+
}
|
|
69
|
+
const results = [];
|
|
70
|
+
for (const statement of statements) results.push(await statement);
|
|
71
|
+
return results;
|
|
72
|
+
}
|
|
73
|
+
function clampLimit(limit, fallback, max) {
|
|
74
|
+
const value = Number.isFinite(limit) ? Math.trunc(limit) : fallback;
|
|
75
|
+
return Math.min(Math.max(value, 1), max);
|
|
76
|
+
}
|
|
77
|
+
function clampOffset(offset) {
|
|
78
|
+
const value = Number.isFinite(offset) ? Math.trunc(offset) : 0;
|
|
79
|
+
return Math.max(value, 0);
|
|
80
|
+
}
|
|
81
|
+
function createChatStore(db, tables) {
|
|
82
|
+
const threads = tables.threads;
|
|
83
|
+
const messages = tables.messages;
|
|
84
|
+
return {
|
|
85
|
+
async listThreads(input) {
|
|
86
|
+
const limit = clampLimit(input.limit, 50, 200);
|
|
87
|
+
const offset = clampOffset(input.offset);
|
|
88
|
+
const scope = eq(threads.workspaceId, input.workspaceId);
|
|
89
|
+
const [list, [countRow]] = await Promise.all([
|
|
90
|
+
db.select().from(threads).where(scope).orderBy(desc(threads.updatedAt), asc(threads.id)).limit(limit).offset(offset),
|
|
91
|
+
db.select({ total: sql2`count(*)` }).from(threads).where(scope)
|
|
92
|
+
]);
|
|
93
|
+
return { threads: list, total: countRow?.total ?? 0, limit, offset };
|
|
94
|
+
},
|
|
95
|
+
async getThread(threadId) {
|
|
96
|
+
const [row] = await db.select().from(threads).where(eq(threads.id, threadId)).limit(1);
|
|
97
|
+
return row ?? null;
|
|
98
|
+
},
|
|
99
|
+
async createThread(input) {
|
|
100
|
+
const title = threadTitleFromMessage(input.title ?? input.firstMessage ?? "");
|
|
101
|
+
const values = {
|
|
102
|
+
workspaceId: input.workspaceId,
|
|
103
|
+
title,
|
|
104
|
+
...input.category !== void 0 ? { category: input.category } : {},
|
|
105
|
+
...input.isPinned !== void 0 ? { isPinned: input.isPinned } : {},
|
|
106
|
+
...input.extras ?? {}
|
|
107
|
+
};
|
|
108
|
+
const [row] = await db.insert(threads).values(values).returning();
|
|
109
|
+
if (!row) throw new Error("thread insert returned no row");
|
|
110
|
+
return row;
|
|
111
|
+
},
|
|
112
|
+
async renameThread(threadId, title) {
|
|
113
|
+
const trimmed = title.trim();
|
|
114
|
+
if (!trimmed) throw new ChatStoreInputError("Missing title");
|
|
115
|
+
const [row] = await db.update(threads).set({ title: trimmed, updatedAt: /* @__PURE__ */ new Date() }).where(eq(threads.id, threadId)).returning();
|
|
116
|
+
return row ?? null;
|
|
117
|
+
},
|
|
118
|
+
async pinThread(threadId, isPinned) {
|
|
119
|
+
const [row] = await db.update(threads).set({ isPinned, updatedAt: /* @__PURE__ */ new Date() }).where(eq(threads.id, threadId)).returning();
|
|
120
|
+
return row ?? null;
|
|
121
|
+
},
|
|
122
|
+
async deleteThread(threadId, options) {
|
|
123
|
+
const [existing] = await db.select({ id: threads.id, workspaceId: threads.workspaceId }).from(threads).where(eq(threads.id, threadId)).limit(1);
|
|
124
|
+
if (!existing) return false;
|
|
125
|
+
if (options?.assertAccess) await options.assertAccess(existing.workspaceId);
|
|
126
|
+
await runStatements(db, [
|
|
127
|
+
db.delete(messages).where(eq(messages.threadId, threadId)),
|
|
128
|
+
db.delete(threads).where(eq(threads.id, threadId))
|
|
129
|
+
]);
|
|
130
|
+
return true;
|
|
131
|
+
},
|
|
132
|
+
async bulkDeleteThreads(input) {
|
|
133
|
+
const { ids, assertAccess } = input;
|
|
134
|
+
if (typeof assertAccess !== "function") throw new ChatStoreInputError("Missing assertAccess");
|
|
135
|
+
if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === "string" && id.length > 0)) {
|
|
136
|
+
throw new ChatStoreInputError("Missing ids");
|
|
137
|
+
}
|
|
138
|
+
if (ids.length > BULK_DELETE_MAX_THREADS) {
|
|
139
|
+
throw new ChatStoreInputError(`Too many ids (max ${BULK_DELETE_MAX_THREADS})`);
|
|
140
|
+
}
|
|
141
|
+
const rows = await db.select({ id: threads.id, workspaceId: threads.workspaceId }).from(threads).where(inArray(threads.id, ids));
|
|
142
|
+
if (rows.length === 0) return { deleted: 0 };
|
|
143
|
+
const workspaceIds = [...new Set(rows.map((row) => row.workspaceId))].sort();
|
|
144
|
+
for (const workspaceId of workspaceIds) {
|
|
145
|
+
await assertAccess(workspaceId);
|
|
146
|
+
}
|
|
147
|
+
const foundIds = rows.map((row) => row.id);
|
|
148
|
+
await runStatements(db, [
|
|
149
|
+
db.delete(messages).where(inArray(messages.threadId, foundIds)),
|
|
150
|
+
db.delete(threads).where(inArray(threads.id, foundIds))
|
|
151
|
+
]);
|
|
152
|
+
return { deleted: foundIds.length };
|
|
153
|
+
},
|
|
154
|
+
async listMessages(threadId, options) {
|
|
155
|
+
const query = db.select().from(messages).where(eq(messages.threadId, threadId)).orderBy(asc(messages.createdAt), sql2`rowid`).$dynamic();
|
|
156
|
+
if (options?.limit !== void 0) query.limit(clampLimit(options.limit, 1, 1e3));
|
|
157
|
+
if (options?.offset !== void 0) query.offset(clampOffset(options.offset));
|
|
158
|
+
return await query;
|
|
159
|
+
},
|
|
160
|
+
async appendMessage(input) {
|
|
161
|
+
const values = {
|
|
162
|
+
threadId: input.threadId,
|
|
163
|
+
role: input.role,
|
|
164
|
+
content: input.content,
|
|
165
|
+
...input.parts !== void 0 ? { parts: input.parts } : {},
|
|
166
|
+
...input.toolName !== void 0 ? { toolName: input.toolName } : {},
|
|
167
|
+
...input.model !== void 0 ? { model: input.model } : {},
|
|
168
|
+
...input.inputTokens !== void 0 ? { inputTokens: input.inputTokens } : {},
|
|
169
|
+
...input.outputTokens !== void 0 ? { outputTokens: input.outputTokens } : {},
|
|
170
|
+
...input.reasoningTokens !== void 0 ? { reasoningTokens: input.reasoningTokens } : {},
|
|
171
|
+
...input.cacheReadTokens !== void 0 ? { cacheReadTokens: input.cacheReadTokens } : {},
|
|
172
|
+
...input.cacheWriteTokens !== void 0 ? { cacheWriteTokens: input.cacheWriteTokens } : {},
|
|
173
|
+
...input.costUsd !== void 0 ? { costUsd: input.costUsd } : {},
|
|
174
|
+
...input.extras ?? {}
|
|
175
|
+
};
|
|
176
|
+
const [insertResult] = await runStatements(db, [
|
|
177
|
+
db.insert(messages).values(values).returning(),
|
|
178
|
+
db.update(threads).set({ updatedAt: /* @__PURE__ */ new Date() }).where(eq(threads.id, input.threadId))
|
|
179
|
+
]);
|
|
180
|
+
const row = insertResult?.[0];
|
|
181
|
+
if (!row) throw new Error("message insert returned no row");
|
|
182
|
+
return row;
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
export {
|
|
187
|
+
BULK_DELETE_MAX_THREADS,
|
|
188
|
+
ChatStoreInputError,
|
|
189
|
+
createChatStore,
|
|
190
|
+
createChatTables,
|
|
191
|
+
isChatInteractionPart,
|
|
192
|
+
isChatStepFinishPart,
|
|
193
|
+
isChatTextPart,
|
|
194
|
+
isChatToolPart,
|
|
195
|
+
threadTitleFromMessage,
|
|
196
|
+
toChatMessageParts
|
|
197
|
+
};
|
|
198
|
+
//# 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,CAAC,GAAG;AACtE,QAAM,EAAE,gBAAgB,cAAc,GAAG,IAAI;AAC7C,QAAM,eAAe,QAAQ,sBAAuB,CAAC;AACrD,QAAM,gBAAgB,QAAQ,uBAAwB,CAAC;AAEvD,QAAM,UAAU,YAAY,GAAG,WAAW,UAAU;AAAA,IAClD,IAAI,MAAM;AAAA,IACV,aAAa,iBACT,KAAK,cAAc,EAAE,QAAQ,EAAE,WAAW,MAAM,eAAe,IAAI,EAAE,UAAU,UAAU,CAAC,IAC1F,KAAK,cAAc,EAAE,QAAQ;AAAA,IACjC,OAAO,KAAK,OAAO,EAAE,QAAQ;AAAA,IAC7B,UAAU,KAAK,UAAU;AAAA,IACzB,UAAU,QAAQ,aAAa,EAAE,MAAM,UAAU,CAAC,EAAE,QAAQ,EAAE,QAAQ,KAAK;AAAA,IAC3E,WAAW,UAAU;AAAA,IACrB,WAAW,UAAU;AAAA,IACrB,GAAG;AAAA,EACL,GAAG,CAAC,UAAU;AAAA,I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MAAM,gBAAgB,IAAI,CAAC;AAAA,QACxF,GAAI,MAAM,qBAAqB,SAAY,EAAE,kBAAkB,MAAM,iBAAiB,IAAI,CAAC;AAAA,QAC3F,GAAI,MAAM,YAAY,SAAY,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,QAChE,GAAI,MAAM,UAAU,CAAC;AAAA,MACvB;AACA,YAAM,CAAC,YAAY,IAAI,MAAM,cAAc,IAAI;AAAA,QAC7C,GAAG,OAAO,QAAQ,EAAE,OAAO,MAAM,EAAE,UAAU;AAAA,QAC7C,GAAG,OAAO,OAAO,EAAE,IAAI,EAAE,WAAW,oBAAI,KAAK,EAAE,CAAC,EAAE,MAAM,GAAG,QAAQ,IAAI,MAAM,QAAQ,CAAC;AAAA,MACxF,CAAC;AACD,YAAM,MAAO,eAA0C,CAAC;AACxD,UAAI,CAAC,IAAK,OAAM,IAAI,MAAM,gCAAgC;AAC1D,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["sql","sql"]}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// src/interactions/contract.ts
|
|
2
|
+
import {
|
|
3
|
+
InteractionRequestSchema
|
|
4
|
+
} from "@tangle-network/agent-interface";
|
|
5
|
+
var INTERACTION_EVENT = "interaction";
|
|
6
|
+
var INTERACTION_CANCEL_EVENT = "interaction.cancel";
|
|
7
|
+
var INTERACTION_RESOLVED_EVENT = "interaction.resolved";
|
|
8
|
+
var RENDERABLE_INTERACTION_KINDS = /* @__PURE__ */ new Set(["question", "plan"]);
|
|
9
|
+
function isRenderableInteractionKind(kind) {
|
|
10
|
+
return RENDERABLE_INTERACTION_KINDS.has(kind);
|
|
11
|
+
}
|
|
12
|
+
function isSafeInteractionFieldKey(key) {
|
|
13
|
+
return /^[A-Za-z0-9_-]+$/.test(key) && key !== "__proto__" && key !== "constructor" && key !== "prototype";
|
|
14
|
+
}
|
|
15
|
+
function isTerminalInteractionStatus(status) {
|
|
16
|
+
return status !== "pending";
|
|
17
|
+
}
|
|
18
|
+
function canTransitionInteractionStatus(from, to) {
|
|
19
|
+
return from === "pending" && to !== from;
|
|
20
|
+
}
|
|
21
|
+
function cancelStatusFor(reason) {
|
|
22
|
+
return reason === "timeout" ? "expired" : "cancelled";
|
|
23
|
+
}
|
|
24
|
+
function stableValue(value) {
|
|
25
|
+
if (Array.isArray(value)) return value.map(stableValue);
|
|
26
|
+
if (!value || typeof value !== "object") return value;
|
|
27
|
+
return Object.fromEntries(
|
|
28
|
+
Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, nested]) => [key, stableValue(nested)])
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
function normalizedInteractionText(value) {
|
|
32
|
+
return (value ?? "").replace(/\s+/g, " ").trim();
|
|
33
|
+
}
|
|
34
|
+
function questionInteractionContentSignature(interaction) {
|
|
35
|
+
if (interaction.kind !== "question") return null;
|
|
36
|
+
return JSON.stringify(stableValue({
|
|
37
|
+
kind: interaction.kind,
|
|
38
|
+
title: normalizedInteractionText(interaction.title),
|
|
39
|
+
body: normalizedInteractionText(interaction.body),
|
|
40
|
+
fields: interaction.fields
|
|
41
|
+
}));
|
|
42
|
+
}
|
|
43
|
+
function dedupeQuestionInteractionsByContent(interactions) {
|
|
44
|
+
const seen = /* @__PURE__ */ new Set();
|
|
45
|
+
return interactions.filter((interaction) => {
|
|
46
|
+
const signature = questionInteractionContentSignature(interaction);
|
|
47
|
+
if (!signature) return true;
|
|
48
|
+
if (seen.has(signature)) return false;
|
|
49
|
+
seen.add(signature);
|
|
50
|
+
return true;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
function parseInteractionRequest(data) {
|
|
54
|
+
const request = data?.request;
|
|
55
|
+
if (!request || typeof request !== "object") {
|
|
56
|
+
return { succeeded: false, error: "interaction event carried no request object" };
|
|
57
|
+
}
|
|
58
|
+
const validation = InteractionRequestSchema.safeParse(request);
|
|
59
|
+
if (!validation.success) {
|
|
60
|
+
return { succeeded: false, error: `malformed interaction request: ${validation.error.message}` };
|
|
61
|
+
}
|
|
62
|
+
return { succeeded: true, value: request };
|
|
63
|
+
}
|
|
64
|
+
function parseInteractionCancel(data) {
|
|
65
|
+
const id = typeof data?.id === "string" && data.id ? data.id : null;
|
|
66
|
+
if (!id) return { succeeded: false, error: "interaction.cancel event carried no id" };
|
|
67
|
+
const reason = typeof data?.reason === "string" && data.reason ? data.reason : void 0;
|
|
68
|
+
return { succeeded: true, value: { id, ...reason ? { reason } : {} } };
|
|
69
|
+
}
|
|
70
|
+
function fieldAcceptsFreeText(field) {
|
|
71
|
+
if (field.type === "text") return true;
|
|
72
|
+
if (field.type === "select") return field.allowCustom === true;
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
function composerAnswerDeliveries(pending) {
|
|
76
|
+
const deliveries = [];
|
|
77
|
+
for (const interaction of pending) {
|
|
78
|
+
if (interaction.kind !== "question") continue;
|
|
79
|
+
const field = interaction.fields.find(fieldAcceptsFreeText) ?? interaction.fields[0];
|
|
80
|
+
if (!field) continue;
|
|
81
|
+
deliveries.push({ interactionId: interaction.id, field });
|
|
82
|
+
}
|
|
83
|
+
return deliveries;
|
|
84
|
+
}
|
|
85
|
+
function composerAnswerData(field, text) {
|
|
86
|
+
return { [field.name]: field.type === "select" ? [text] : text };
|
|
87
|
+
}
|
|
88
|
+
function interactionPartKey(id) {
|
|
89
|
+
return `interaction:${id}`;
|
|
90
|
+
}
|
|
91
|
+
function noticePartKey(id) {
|
|
92
|
+
return `notice:${id}`;
|
|
93
|
+
}
|
|
94
|
+
function noticePart(noticeKind, id, text) {
|
|
95
|
+
return { type: "notice", id, noticeKind, text };
|
|
96
|
+
}
|
|
97
|
+
function interactionFromWireRequest(request) {
|
|
98
|
+
return {
|
|
99
|
+
id: request.id,
|
|
100
|
+
kind: request.kind,
|
|
101
|
+
title: request.title,
|
|
102
|
+
...request.body ? { body: request.body } : {},
|
|
103
|
+
fields: request.answerSpec.fields,
|
|
104
|
+
status: "pending"
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function interactionToPersistedPart(request, status, cancelReason) {
|
|
108
|
+
return {
|
|
109
|
+
type: "interaction",
|
|
110
|
+
id: request.id,
|
|
111
|
+
kind: request.kind,
|
|
112
|
+
title: request.title,
|
|
113
|
+
...request.body ? { body: request.body } : {},
|
|
114
|
+
answerSpec: { fields: request.answerSpec.fields },
|
|
115
|
+
status,
|
|
116
|
+
...cancelReason ? { cancelReason } : {}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function persistedPartToInteraction(part) {
|
|
120
|
+
if (String(part.type ?? "") !== "interaction") return null;
|
|
121
|
+
const id = typeof part.id === "string" && part.id ? part.id : null;
|
|
122
|
+
const kind = typeof part.kind === "string" && part.kind ? part.kind : null;
|
|
123
|
+
const title = typeof part.title === "string" ? part.title : "";
|
|
124
|
+
const answerSpec = part.answerSpec;
|
|
125
|
+
const fields = Array.isArray(answerSpec?.fields) ? answerSpec.fields : null;
|
|
126
|
+
const status = part.status;
|
|
127
|
+
const validStatus = status && ["pending", "answered", "declined", "cancelled", "expired"].includes(status);
|
|
128
|
+
if (!id || !kind || !fields || !validStatus) return null;
|
|
129
|
+
return {
|
|
130
|
+
id,
|
|
131
|
+
kind,
|
|
132
|
+
title,
|
|
133
|
+
...typeof part.body === "string" && part.body ? { body: part.body } : {},
|
|
134
|
+
fields,
|
|
135
|
+
status,
|
|
136
|
+
...typeof part.cancelReason === "string" && part.cancelReason ? { cancelReason: part.cancelReason } : {}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export {
|
|
141
|
+
INTERACTION_EVENT,
|
|
142
|
+
INTERACTION_CANCEL_EVENT,
|
|
143
|
+
INTERACTION_RESOLVED_EVENT,
|
|
144
|
+
isRenderableInteractionKind,
|
|
145
|
+
isSafeInteractionFieldKey,
|
|
146
|
+
isTerminalInteractionStatus,
|
|
147
|
+
canTransitionInteractionStatus,
|
|
148
|
+
cancelStatusFor,
|
|
149
|
+
questionInteractionContentSignature,
|
|
150
|
+
dedupeQuestionInteractionsByContent,
|
|
151
|
+
parseInteractionRequest,
|
|
152
|
+
parseInteractionCancel,
|
|
153
|
+
fieldAcceptsFreeText,
|
|
154
|
+
composerAnswerDeliveries,
|
|
155
|
+
composerAnswerData,
|
|
156
|
+
interactionPartKey,
|
|
157
|
+
noticePartKey,
|
|
158
|
+
noticePart,
|
|
159
|
+
interactionFromWireRequest,
|
|
160
|
+
interactionToPersistedPart,
|
|
161
|
+
persistedPartToInteraction
|
|
162
|
+
};
|
|
163
|
+
//# sourceMappingURL=chunk-4TXDD6P2.js.map
|