@huyooo/ai-chat-storage 0.2.45 → 0.3.3
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/adapters/postgres/backups.d.ts +12 -0
- package/dist/adapters/postgres/backups.d.ts.map +1 -0
- package/dist/adapters/postgres/base.d.ts +12 -0
- package/dist/adapters/postgres/base.d.ts.map +1 -0
- package/dist/adapters/postgres/embeddings.d.ts +16 -0
- package/dist/adapters/postgres/embeddings.d.ts.map +1 -0
- package/dist/adapters/postgres/index.d.ts +55 -0
- package/dist/adapters/postgres/index.d.ts.map +1 -0
- package/dist/adapters/postgres/messages.d.ts +25 -0
- package/dist/adapters/postgres/messages.d.ts.map +1 -0
- package/dist/adapters/postgres/operations.d.ts +16 -0
- package/dist/adapters/postgres/operations.d.ts.map +1 -0
- package/dist/adapters/postgres/sessions.d.ts +16 -0
- package/dist/adapters/postgres/sessions.d.ts.map +1 -0
- package/dist/adapters/postgres/trash.d.ts +14 -0
- package/dist/adapters/postgres/trash.d.ts.map +1 -0
- package/dist/adapters/sqlite/backups.d.ts +12 -0
- package/dist/adapters/sqlite/backups.d.ts.map +1 -0
- package/dist/adapters/sqlite/base.d.ts +22 -0
- package/dist/adapters/sqlite/base.d.ts.map +1 -0
- package/dist/adapters/sqlite/embeddings.d.ts +16 -0
- package/dist/adapters/sqlite/embeddings.d.ts.map +1 -0
- package/dist/adapters/sqlite/index.d.ts +55 -0
- package/dist/adapters/sqlite/index.d.ts.map +1 -0
- package/dist/adapters/sqlite/messages.d.ts +25 -0
- package/dist/adapters/sqlite/messages.d.ts.map +1 -0
- package/dist/adapters/sqlite/operations.d.ts +16 -0
- package/dist/adapters/sqlite/operations.d.ts.map +1 -0
- package/dist/adapters/sqlite/sessions.d.ts +16 -0
- package/dist/adapters/sqlite/sessions.d.ts.map +1 -0
- package/dist/adapters/sqlite/trash.d.ts +14 -0
- package/dist/adapters/sqlite/trash.d.ts.map +1 -0
- package/dist/adapters/sqlite/user-settings.d.ts +22 -0
- package/dist/adapters/sqlite/user-settings.d.ts.map +1 -0
- package/dist/index.d.ts +13 -1567
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +545 -1
- package/dist/schema.d.ts +1410 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/types.d.ts +195 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +8 -4
- package/dist/chunk-EXGLTJH4.js +0 -268
- package/dist/chunk-V5E7YX6J.js +0 -1
- package/dist/postgres-JFFEO52T.js +0 -1
- package/dist/sqlite-BVA3FN4Z.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAI7D;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,aAAa,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC,CA+BlF;AAED;;GAEG;AACH,wBAAgB,qBAAqB,IAAI,MAAM,CAG9C;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,CAG5C;AAED;;GAEG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAG3C"}
|
package/dist/index.js
CHANGED
|
@@ -1 +1,545 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{index as e,integer as t,primaryKey as n,sqliteTable as r,text as i,uniqueIndex as a}from"drizzle-orm/sqlite-core";import{drizzle as o}from"drizzle-orm/better-sqlite3";import{and as s,desc as c,eq as l,gt as u,inArray as d,lt as f,sql as p}from"drizzle-orm";import m from"postgres";import{existsSync as ee,mkdirSync as h}from"fs";import{dirname as te}from"path";var g=Object.defineProperty,_=(e,t)=>()=>(e&&(t=e(e=0)),t),v=(e,t)=>{let n={};for(var r in e)g(n,r,{get:e[r],enumerable:!0});return t||g(n,Symbol.toStringTag,{value:`Module`}),n},y,b,x,S,C,w,T,E=_((()=>{y=r(`sessions`,{id:i(`id`).primaryKey(),appId:i(`app_id`),userId:i(`user_id`),title:i(`title`).notNull(),model:i(`model`).notNull(),mode:i(`mode`).notNull(),webSearchEnabled:t(`web_search_enabled`,{mode:`boolean`}).notNull().default(!0),thinkingEnabled:t(`thinking_enabled`,{mode:`boolean`}).notNull().default(!0),hidden:t(`hidden`,{mode:`boolean`}).notNull().default(!1),lastMessageSequence:t(`last_message_sequence`).notNull().default(0),createdAt:t(`created_at`,{mode:`timestamp`}).notNull(),updatedAt:t(`updated_at`,{mode:`timestamp`}).notNull()},t=>[e(`idx_sessions_tenant`).on(t.appId,t.userId),e(`idx_sessions_updated`).on(t.updatedAt)]),b=r(`messages`,{id:i(`id`).primaryKey(),clientId:i(`client_id`),sessionId:i(`session_id`).notNull(),appId:i(`app_id`),userId:i(`user_id`),role:i(`role`).notNull(),content:i(`content`).notNull(),atContextItems:i(`at_context_items`),images:i(`images`),model:i(`model`),mode:i(`mode`),webSearchEnabled:t(`web_search_enabled`,{mode:`boolean`}),thinkingEnabled:t(`thinking_enabled`,{mode:`boolean`}),operationIds:i(`operation_ids`),usage:i(`usage`),duration:t(`duration`),finishReason:i(`finish_reason`),sequence:t(`sequence`).notNull(),timestamp:t(`timestamp`,{mode:`timestamp`}).notNull()},t=>[e(`idx_messages_session`).on(t.sessionId),e(`idx_messages_tenant`).on(t.appId,t.userId),e(`idx_messages_sequence`).on(t.sessionId,t.sequence),a(`uq_messages_session_sequence`).on(t.sessionId,t.sequence)]),x=r(`message_parts`,{messageId:i(`message_id`).notNull(),sequence:t(`sequence`).notNull(),type:i(`type`).notNull(),payload:i(`payload`).notNull()},t=>[n({columns:[t.messageId,t.sequence]}),e(`idx_message_parts_message`).on(t.messageId,t.sequence)]),S=r(`operations`,{id:i(`id`).primaryKey(),sessionId:i(`session_id`).notNull(),messageId:i(`message_id`),appId:i(`app_id`),userId:i(`user_id`),command:i(`command`).notNull(),operationType:i(`operation_type`).notNull(),affectedFiles:i(`affected_files`).notNull(),backupPath:i(`backup_path`),status:i(`status`).notNull().default(`pending`),errorMessage:i(`error_message`),timestamp:t(`timestamp`,{mode:`timestamp`}).notNull()},t=>[e(`idx_operations_session`).on(t.sessionId),e(`idx_operations_message`).on(t.messageId),e(`idx_operations_tenant`).on(t.appId,t.userId)]),C=r(`backups`,{id:i(`id`).primaryKey(),operationId:i(`operation_id`).notNull(),originalPath:i(`original_path`).notNull(),backupPath:i(`backup_path`).notNull(),fileSize:t(`file_size`).notNull(),fileHash:i(`file_hash`).notNull(),createdAt:t(`created_at`,{mode:`timestamp`}).notNull(),expiresAt:t(`expires_at`,{mode:`timestamp`}).notNull()},t=>[e(`idx_backups_operation`).on(t.operationId),e(`idx_backups_expires`).on(t.expiresAt)]),w=r(`trash`,{id:i(`id`).primaryKey(),sessionId:i(`session_id`).notNull(),appId:i(`app_id`),userId:i(`user_id`),originalPath:i(`original_path`).notNull(),trashPath:i(`trash_path`).notNull(),deletedAt:t(`deleted_at`,{mode:`timestamp`}).notNull(),autoDeleteAt:t(`auto_delete_at`,{mode:`timestamp`}).notNull()},t=>[e(`idx_trash_tenant`).on(t.appId,t.userId),e(`idx_trash_auto_delete`).on(t.autoDeleteAt)]),T=r(`embeddings`,{id:i(`id`).primaryKey(),sessionId:i(`session_id`).notNull(),messageId:i(`message_id`),appId:i(`app_id`),userId:i(`user_id`),content:i(`content`).notNull(),contentType:i(`content_type`).notNull(),embedding:i(`embedding`),metadata:i(`metadata`),createdAt:t(`created_at`,{mode:`timestamp`}).notNull()},t=>[e(`idx_embeddings_session`).on(t.sessionId),e(`idx_embeddings_tenant`).on(t.appId,t.userId)])}));function ne(e,t,n){e.pragma(`table_info(messages)`).some(e=>e.name===t)||e.exec(`ALTER TABLE messages ADD COLUMN ${n}`)}function re(e){Number(e.pragma(`user_version`,{simple:!0})||0)!==A&&e.exec(`
|
|
2
|
+
DROP TABLE IF EXISTS message_parts;
|
|
3
|
+
DROP TABLE IF EXISTS messages;
|
|
4
|
+
DROP TABLE IF EXISTS operations;
|
|
5
|
+
DROP TABLE IF EXISTS backups;
|
|
6
|
+
DROP TABLE IF EXISTS trash;
|
|
7
|
+
DROP TABLE IF EXISTS embeddings;
|
|
8
|
+
DROP TABLE IF EXISTS sessions;
|
|
9
|
+
`),e.exec(`
|
|
10
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
11
|
+
id TEXT PRIMARY KEY,
|
|
12
|
+
app_id TEXT,
|
|
13
|
+
user_id TEXT,
|
|
14
|
+
title TEXT NOT NULL,
|
|
15
|
+
model TEXT NOT NULL,
|
|
16
|
+
mode TEXT NOT NULL,
|
|
17
|
+
web_search_enabled INTEGER NOT NULL DEFAULT 1,
|
|
18
|
+
thinking_enabled INTEGER NOT NULL DEFAULT 1,
|
|
19
|
+
hidden INTEGER NOT NULL DEFAULT 0,
|
|
20
|
+
last_message_sequence INTEGER NOT NULL DEFAULT 0,
|
|
21
|
+
created_at INTEGER NOT NULL,
|
|
22
|
+
updated_at INTEGER NOT NULL
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
CREATE TABLE IF NOT EXISTS messages (
|
|
26
|
+
id TEXT PRIMARY KEY,
|
|
27
|
+
client_id TEXT,
|
|
28
|
+
session_id TEXT NOT NULL,
|
|
29
|
+
app_id TEXT,
|
|
30
|
+
user_id TEXT,
|
|
31
|
+
role TEXT NOT NULL,
|
|
32
|
+
content TEXT NOT NULL,
|
|
33
|
+
at_context_items TEXT,
|
|
34
|
+
images TEXT,
|
|
35
|
+
model TEXT,
|
|
36
|
+
mode TEXT,
|
|
37
|
+
web_search_enabled INTEGER,
|
|
38
|
+
thinking_enabled INTEGER,
|
|
39
|
+
operation_ids TEXT,
|
|
40
|
+
usage TEXT,
|
|
41
|
+
duration INTEGER,
|
|
42
|
+
finish_reason TEXT,
|
|
43
|
+
sequence INTEGER NOT NULL,
|
|
44
|
+
timestamp INTEGER NOT NULL,
|
|
45
|
+
UNIQUE (session_id, sequence)
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
CREATE TABLE IF NOT EXISTS message_parts (
|
|
49
|
+
message_id TEXT NOT NULL,
|
|
50
|
+
sequence INTEGER NOT NULL,
|
|
51
|
+
type TEXT NOT NULL,
|
|
52
|
+
payload TEXT NOT NULL,
|
|
53
|
+
PRIMARY KEY (message_id, sequence)
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
CREATE TABLE IF NOT EXISTS operations (
|
|
57
|
+
id TEXT PRIMARY KEY,
|
|
58
|
+
session_id TEXT NOT NULL,
|
|
59
|
+
message_id TEXT,
|
|
60
|
+
app_id TEXT,
|
|
61
|
+
user_id TEXT,
|
|
62
|
+
command TEXT NOT NULL,
|
|
63
|
+
operation_type TEXT NOT NULL,
|
|
64
|
+
affected_files TEXT NOT NULL,
|
|
65
|
+
backup_path TEXT,
|
|
66
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
67
|
+
error_message TEXT,
|
|
68
|
+
timestamp INTEGER NOT NULL
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
CREATE TABLE IF NOT EXISTS backups (
|
|
72
|
+
id TEXT PRIMARY KEY,
|
|
73
|
+
operation_id TEXT NOT NULL,
|
|
74
|
+
original_path TEXT NOT NULL,
|
|
75
|
+
backup_path TEXT NOT NULL,
|
|
76
|
+
file_size INTEGER NOT NULL,
|
|
77
|
+
file_hash TEXT NOT NULL,
|
|
78
|
+
created_at INTEGER NOT NULL,
|
|
79
|
+
expires_at INTEGER NOT NULL
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
CREATE TABLE IF NOT EXISTS trash (
|
|
83
|
+
id TEXT PRIMARY KEY,
|
|
84
|
+
session_id TEXT NOT NULL,
|
|
85
|
+
app_id TEXT,
|
|
86
|
+
user_id TEXT,
|
|
87
|
+
original_path TEXT NOT NULL,
|
|
88
|
+
trash_path TEXT NOT NULL,
|
|
89
|
+
deleted_at INTEGER NOT NULL,
|
|
90
|
+
auto_delete_at INTEGER NOT NULL
|
|
91
|
+
);
|
|
92
|
+
|
|
93
|
+
CREATE TABLE IF NOT EXISTS embeddings (
|
|
94
|
+
id TEXT PRIMARY KEY,
|
|
95
|
+
session_id TEXT NOT NULL,
|
|
96
|
+
message_id TEXT,
|
|
97
|
+
app_id TEXT,
|
|
98
|
+
user_id TEXT,
|
|
99
|
+
content TEXT NOT NULL,
|
|
100
|
+
content_type TEXT NOT NULL,
|
|
101
|
+
embedding TEXT,
|
|
102
|
+
metadata TEXT,
|
|
103
|
+
created_at INTEGER NOT NULL
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
CREATE TABLE IF NOT EXISTS user_settings (
|
|
107
|
+
id TEXT PRIMARY KEY,
|
|
108
|
+
app_id TEXT,
|
|
109
|
+
user_id TEXT,
|
|
110
|
+
key TEXT NOT NULL,
|
|
111
|
+
value TEXT NOT NULL,
|
|
112
|
+
created_at INTEGER NOT NULL,
|
|
113
|
+
updated_at INTEGER NOT NULL,
|
|
114
|
+
UNIQUE(app_id, user_id, key)
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_tenant ON sessions(app_id, user_id);
|
|
118
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_updated ON sessions(updated_at);
|
|
119
|
+
CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id);
|
|
120
|
+
CREATE INDEX IF NOT EXISTS idx_messages_tenant ON messages(app_id, user_id);
|
|
121
|
+
CREATE INDEX IF NOT EXISTS idx_messages_sequence ON messages(session_id, sequence);
|
|
122
|
+
CREATE INDEX IF NOT EXISTS idx_message_parts_message ON message_parts(message_id, sequence);
|
|
123
|
+
CREATE INDEX IF NOT EXISTS idx_operations_session ON operations(session_id);
|
|
124
|
+
CREATE INDEX IF NOT EXISTS idx_operations_message ON operations(message_id);
|
|
125
|
+
CREATE INDEX IF NOT EXISTS idx_backups_operation ON backups(operation_id);
|
|
126
|
+
CREATE INDEX IF NOT EXISTS idx_backups_expires ON backups(expires_at);
|
|
127
|
+
CREATE INDEX IF NOT EXISTS idx_trash_tenant ON trash(app_id, user_id);
|
|
128
|
+
CREATE INDEX IF NOT EXISTS idx_trash_auto_delete ON trash(auto_delete_at);
|
|
129
|
+
CREATE INDEX IF NOT EXISTS idx_embeddings_session ON embeddings(session_id);
|
|
130
|
+
CREATE INDEX IF NOT EXISTS idx_user_settings_tenant ON user_settings(app_id, user_id);
|
|
131
|
+
CREATE INDEX IF NOT EXISTS idx_user_settings_key ON user_settings(key);
|
|
132
|
+
`),ne(e,`finish_reason`,`finish_reason TEXT`),e.pragma(`user_version = ${A}`)}function D(e){let t=[];return e.appId&&t.push(l(y.appId,e.appId)),e.userId&&t.push(l(y.userId,e.userId)),t.length>0?s(...t):void 0}function O(e){let t=[];return e.appId&&t.push(l(b.appId,e.appId)),e.userId&&t.push(l(b.userId,e.userId)),t.length>0?s(...t):void 0}function ie(e){let t=[];return e.appId&&t.push(l(S.appId,e.appId)),e.userId&&t.push(l(S.userId,e.userId)),t.length>0?s(...t):void 0}function k(e){let t=[];return e.appId&&t.push(l(w.appId,e.appId)),e.userId&&t.push(l(w.userId,e.userId)),t.length>0?s(...t):void 0}function ae(e,t){if(e.length===0||t.length===0||e.length!==t.length)return 0;let n=0,r=0,i=0;for(let a=0;a<e.length;a+=1)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];return r===0||i===0?0:n/(Math.sqrt(r)*Math.sqrt(i))}var A,j=_((()=>{E(),A=3}));function M(e){return{id:e.id,appId:e.appId,userId:e.userId,title:e.title,model:e.model,mode:e.mode,webSearchEnabled:e.webSearchEnabled,thinkingEnabled:e.thinkingEnabled,hidden:e.hidden,createdAt:e.createdAt,updatedAt:e.updatedAt}}function oe(e,t){let n=D(t);return e.select().from(y).where(n).orderBy(c(y.updatedAt)).all().map(M)}function se(e,t,n){let r=D(n),i=r?s(l(y.id,t),r):l(y.id,t),a=e.select().from(y).where(i).get();return a?M(a):null}function ce(e,t,n){let r=new Date,i={id:t.id,appId:n.appId||null,userId:n.userId||null,title:t.title,model:t.model,mode:t.mode,webSearchEnabled:t.webSearchEnabled,thinkingEnabled:t.thinkingEnabled,hidden:t.hidden??!1,createdAt:r,updatedAt:r};return e.insert(y).values({id:i.id,appId:i.appId,userId:i.userId,title:i.title,model:i.model,mode:i.mode,webSearchEnabled:i.webSearchEnabled,thinkingEnabled:i.thinkingEnabled,hidden:i.hidden,lastMessageSequence:0,createdAt:i.createdAt,updatedAt:i.updatedAt}).run(),i}function le(e,t,n,r){let i=D(r),a=i?s(l(y.id,t),i):l(y.id,t),o={updatedAt:new Date};n.title!==void 0&&(o.title=n.title),n.model!==void 0&&(o.model=n.model),n.mode!==void 0&&(o.mode=n.mode),n.webSearchEnabled!==void 0&&(o.webSearchEnabled=n.webSearchEnabled),n.thinkingEnabled!==void 0&&(o.thinkingEnabled=n.thinkingEnabled),n.hidden!==void 0&&(o.hidden=n.hidden),e.update(y).set(o).where(a).run()}function ue(e,t,n){let r=D(n),i=r?s(l(y.id,t),r):l(y.id,t);e.delete(y).where(i).run()}var de=_((()=>{E(),j()}));function N(e,t){if(typeof t==`number`&&Number.isFinite(t))return t;if(typeof t==`string`){let e=Number(t);if(Number.isFinite(e))return e}throw Error(`消息 ${e} 的序号无效: ${t}`)}function fe(e,t){if(typeof t==`number`&&Number.isFinite(t))return t;if(t instanceof Date)return t.getTime();if(typeof t==`string`){let e=Date.parse(t);if(!Number.isNaN(e))return e}throw Error(`消息 ${e} 的时间戳无效: ${t}`)}function pe(e,t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}function me(e,t){if(!t)return null;try{let e=JSON.parse(t);return Array.isArray(e)?e:null}catch{return null}}function he(e){switch(e){case`stop`:case`length`:case`tool_calls`:case`error`:case`abort`:case`max_iterations`:case`max_duration`:case`max_tool_calls`:case`max_tokens`:return e;default:return null}}function ge(e){return{messageId:e.messageId,sequence:N(e.messageId,e.sequence),type:e.type,payload:e.payload}}function P(e,t){let n=new Map;for(let e of t){let t=ge(e),r=n.get(t.messageId)??[];r.push(t),n.set(t.messageId,r)}return e.map(e=>({id:e.id,clientId:e.clientId||e.id,sessionId:e.sessionId,appId:e.appId,userId:e.userId,role:e.role,content:e.content,atContextItems:me(e.id,e.atContextItems),images:pe(e.id,e.images),model:e.model,mode:e.mode,webSearchEnabled:e.webSearchEnabled,thinkingEnabled:e.thinkingEnabled,parts:n.get(e.id)??[],operationIds:e.operationIds,usage:e.usage,duration:e.duration,finishReason:he(e.finishReason),sequence:N(e.id,e.sequence),timestamp:fe(e.id,e.timestamp)}))}function _e(e){return e?.trim().toLowerCase()??``}function F(e,t=120){let n=e?.replace(/\s+/g,` `).trim()??``;return n?n.length>t?`${n.slice(0,t-1)}...`:n:``}function I(e,t,n){let r=e.select().from(x).where(l(x.messageId,t)).orderBy(x.sequence).all(),i=new Map;for(let e of r)i.set(N(t,e.sequence),e);for(let[r,a]of n.entries()){let n=i.get(r);if(!n){e.insert(x).values({messageId:t,sequence:r,type:a.type,payload:a.payload}).run();continue}(n.type!==a.type||n.payload!==a.payload)&&e.update(x).set({type:a.type,payload:a.payload}).where(s(l(x.messageId,t),l(x.sequence,r))).run(),i.delete(r)}let a=[...i.keys()];a.length>0&&e.delete(x).where(s(l(x.messageId,t),d(x.sequence,a))).run()}function ve(e,t){let n=e.select().from(b).where(l(b.sessionId,t)).orderBy(b.sequence,b.timestamp).all();if(n.length===0)return[];let r=n.map(e=>e.id);return P(n,e.select().from(x).where(d(x.messageId,r)).orderBy(x.messageId,x.sequence).all())}function ye(e,t,n){let r=Math.max(1,Math.min(n?.limit??200,500)),i=l(b.sessionId,t),a=n?.beforeSequence==null?i:s(i,f(b.sequence,n.beforeSequence)),o=e.select().from(b).where(a).orderBy(c(b.sequence)).limit(r).all().reverse();if(o.length===0)return{messages:[],hasMore:!1,nextBeforeSequence:null};let u=o.map(e=>e.id),p=P(o,e.select().from(x).where(d(x.messageId,u)).orderBy(x.messageId,x.sequence).all()),m=p[0]?.sequence??null;return{messages:p,hasMore:m!=null&&m>1,nextBeforeSequence:m}}function be(e,t,n,r){let i=_e(t),a=Math.max(1,Math.min(n?.limit??20,100)),o=D(r??{}),u=`%${i}%`,d=p`(
|
|
133
|
+
lower(${y.title}) LIKE ${u}
|
|
134
|
+
OR EXISTS (
|
|
135
|
+
SELECT 1
|
|
136
|
+
FROM ${b}
|
|
137
|
+
WHERE ${b.sessionId} = ${y.id}
|
|
138
|
+
AND lower(${b.content}) LIKE ${u}
|
|
139
|
+
)
|
|
140
|
+
)`,f=i?o?s(o,d):d:o;return e.select({id:y.id,title:y.title,updatedAt:y.updatedAt}).from(y).where(f).orderBy(c(y.updatedAt)).limit(a).all().map(t=>{let n=!i||t.title.toLowerCase().includes(i),r=e.select({id:b.id,content:b.content}).from(b).where(l(b.sessionId,t.id)).orderBy(c(b.sequence)).limit(1).get(),a=n?null:e.select({id:b.id,content:b.content}).from(b).where(s(l(b.sessionId,t.id),p`lower(${b.content}) LIKE ${u}`)).orderBy(c(b.sequence)).limit(1).get(),o=F(a?.content??r?.content??``);return{kind:`chat`,id:t.id,sessionId:t.id,label:t.title,mention:`@chat:${t.id}`,description:o||void 0,preview:o||void 0,updatedAt:t.updatedAt.getTime(),matchedMessageId:a?.id}})}function xe(e,t,n){let r=e.select({lastMessageSequence:y.lastMessageSequence}).from(y).where(l(y.id,t)).get();if(!r)throw Error(`会话 ${t} 不存在,无法分配消息序号`);let i=(r.lastMessageSequence??0)+1;return e.update(y).set({lastMessageSequence:i,updatedAt:n}).where(l(y.id,t)).run(),i}function Se(e,t,n){let r=O(n),i=r?s(l(b.id,t),r):l(b.id,t),a=e.select().from(b).where(i).get();if(!a)return null;let o=e.select().from(x).where(l(x.messageId,t)).orderBy(x.sequence).all();return P([a],o)[0]??null}function Ce(e,t,n){let r=Date.now(),i=new Date(r);return e.transaction(e=>{let a=xe(e,t.sessionId,i),o={id:t.id,clientId:t.clientId||t.id,sessionId:t.sessionId,appId:n.appId||null,userId:n.userId||null,role:t.role,content:t.content,atContextItems:t.atContextItems||null,images:t.images||[],model:t.model,mode:t.mode,webSearchEnabled:t.webSearchEnabled,thinkingEnabled:t.thinkingEnabled,parts:(t.parts??[]).map((e,n)=>({messageId:t.id,sequence:n,type:e.type,payload:e.payload})),operationIds:t.operationIds,usage:null,duration:null,finishReason:t.finishReason??null,sequence:a,timestamp:r};return e.insert(b).values({id:o.id,clientId:o.clientId,sessionId:o.sessionId,appId:o.appId,userId:o.userId,role:o.role,content:o.content,atContextItems:o.atContextItems?JSON.stringify(o.atContextItems):null,images:o.images.length>0?JSON.stringify(o.images):null,model:o.model,mode:o.mode,webSearchEnabled:o.webSearchEnabled,thinkingEnabled:o.thinkingEnabled,operationIds:o.operationIds,usage:null,duration:null,finishReason:o.finishReason,sequence:o.sequence,timestamp:new Date(o.timestamp)}).run(),I(e,o.id,o.parts),o})}function we(e,t,n,r){e.transaction(e=>{let i=O(r),a=i?s(l(b.id,t),i):l(b.id,t),o={};n.content!==void 0&&(o.content=n.content),n.atContextItems!==void 0&&(o.atContextItems=n.atContextItems?JSON.stringify(n.atContextItems):null),n.operationIds!==void 0&&(o.operationIds=n.operationIds),n.usage!==void 0&&(o.usage=n.usage),n.duration!==void 0&&(o.duration=n.duration),n.finishReason!==void 0&&(o.finishReason=n.finishReason),Object.keys(o).length>0&&e.update(b).set(o).where(a).run(),n.parts!==void 0&&I(e,t,n.parts)})}function L(e,t){t.length!==0&&e.delete(x).where(d(x.messageId,t)).run()}function Te(e,t,n){e.transaction(e=>{L(e,e.select({id:b.id}).from(b).where(s(l(b.sessionId,t),u(b.timestamp,n))).all().map(e=>e.id)),e.delete(b).where(s(l(b.sessionId,t),u(b.timestamp,n))).run()})}function Ee(e,t,n,r){e.transaction(e=>{L(e,e.select({id:b.id}).from(b).where(s(l(b.sessionId,t),u(b.sequence,r))).all().map(e=>e.id)),e.delete(b).where(s(l(b.sessionId,t),u(b.sequence,r))).run()})}function De(e,t){e.transaction(e=>{L(e,e.select({id:b.id}).from(b).where(l(b.sessionId,t)).all().map(e=>e.id)),e.delete(b).where(l(b.sessionId,t)).run()})}var Oe=_((()=>{E(),j()}));function R(e){return{id:e.id,sessionId:e.sessionId,messageId:e.messageId,appId:e.appId,userId:e.userId,command:e.command,operationType:e.operationType,affectedFiles:e.affectedFiles,backupPath:e.backupPath,status:e.status,errorMessage:e.errorMessage,timestamp:e.timestamp}}function ke(e,t){return e.select().from(S).where(l(S.sessionId,t)).orderBy(S.timestamp).all().map(R)}function Ae(e,t,n){let r=ie(n),i=r?s(l(S.messageId,t),r):l(S.messageId,t);return e.select().from(S).where(i).all().map(R)}function je(e,t,n){let r=new Date,i={id:t.id,sessionId:t.sessionId,messageId:t.messageId,appId:n.appId||null,userId:n.userId||null,command:t.command,operationType:t.operationType,affectedFiles:t.affectedFiles,backupPath:t.backupPath,status:t.status||`pending`,errorMessage:null,timestamp:r};return e.insert(S).values({id:i.id,sessionId:i.sessionId,messageId:i.messageId,appId:i.appId,userId:i.userId,command:i.command,operationType:i.operationType,affectedFiles:i.affectedFiles,backupPath:i.backupPath,status:i.status,errorMessage:i.errorMessage,timestamp:i.timestamp}).run(),i}function Me(e,t,n,r){let i={status:n};r!==void 0&&(i.errorMessage=r),e.update(S).set(i).where(l(S.id,t)).run()}function Ne(e,t){e.delete(S).where(l(S.sessionId,t)).run()}var Pe=_((()=>{E(),j()}));function Fe(e){return{id:e.id,operationId:e.operationId,originalPath:e.originalPath,backupPath:e.backupPath,fileSize:e.fileSize,fileHash:e.fileHash,createdAt:e.createdAt,expiresAt:e.expiresAt}}function Ie(e,t){return e.select().from(C).where(l(C.operationId,t)).all().map(Fe)}function Le(e,t){let n=new Date,r={...t,createdAt:n};return e.insert(C).values({id:r.id,operationId:r.operationId,originalPath:r.originalPath,backupPath:r.backupPath,fileSize:r.fileSize,fileHash:r.fileHash,createdAt:r.createdAt,expiresAt:r.expiresAt}).run(),r}function Re(e){let t=new Date;return e.delete(C).where(f(C.expiresAt,t)).run().changes}var ze=_((()=>{E()}));function z(e){return{id:e.id,sessionId:e.sessionId,appId:e.appId,userId:e.userId,originalPath:e.originalPath,trashPath:e.trashPath,deletedAt:e.deletedAt,autoDeleteAt:e.autoDeleteAt}}function Be(e,t){let n=k(t);return e.select().from(w).where(n).orderBy(c(w.deletedAt)).all().map(z)}function Ve(e,t,n,r){let i=new Date,a=r.trashRetentionDays||30,o=new Date(i.getTime()+a*24*60*60*1e3),s={...t,appId:n.appId||null,userId:n.userId||null,deletedAt:i,autoDeleteAt:o};return e.insert(w).values({id:s.id,sessionId:s.sessionId,appId:s.appId,userId:s.userId,originalPath:s.originalPath,trashPath:s.trashPath,deletedAt:s.deletedAt,autoDeleteAt:s.autoDeleteAt}).run(),s}function He(e,t,n){let r=k(n),i=r?s(l(w.id,t),r):l(w.id,t),a=e.select().from(w).where(i).get();if(!a)throw Error(`回收站记录不存在`);return e.delete(w).where(l(w.id,t)).run(),z(a)}function Ue(e){let t=new Date;return e.delete(w).where(f(w.autoDeleteAt,t)).run().changes}var We=_((()=>{E(),j()}));function Ge(e,t,n,r,i,a){let o=new Date;e.insert(T).values({id:t,sessionId:i.sessionId,messageId:i.messageId||null,appId:a.appId||null,userId:a.userId||null,content:n,contentType:i.contentType,embedding:JSON.stringify(r),metadata:JSON.stringify(i),createdAt:o}).run()}function Ke(e,t,n,r){let{limit:i=10,threshold:a=.7,sessionId:o}=n,c=[];return r.appId&&c.push(l(T.appId,r.appId)),r.userId&&c.push(l(T.userId,r.userId)),o&&c.push(l(T.sessionId,o)),e.select().from(T).where(c.length>0?s(...c):void 0).all().map(e=>{let n=ae(t,e.embedding?JSON.parse(e.embedding):[]);return{id:e.id,content:e.content,contentType:e.contentType,similarity:n,metadata:e.metadata?JSON.parse(e.metadata):void 0}}).filter(e=>e.similarity>=a).sort((e,t)=>t.similarity-e.similarity).slice(0,i)}function qe(e,t){e.delete(T).where(l(T.sessionId,t)).run()}var Je=_((()=>{E(),j()}));function Ye(e,t,n){return e.prepare(`
|
|
141
|
+
SELECT value FROM user_settings
|
|
142
|
+
WHERE key = ? AND app_id IS ? AND user_id IS ?
|
|
143
|
+
LIMIT 1
|
|
144
|
+
`).get(t,n.appId||null,n.userId||null)?.value||null}function Xe(e,t,n,r){let i=Date.now(),a=`${r.appId||`default`}_${r.userId||`default`}_${t}`,o=e.prepare(`
|
|
145
|
+
SELECT created_at FROM user_settings WHERE id = ?
|
|
146
|
+
`).get(a)?.created_at||i;e.prepare(`
|
|
147
|
+
INSERT OR REPLACE INTO user_settings
|
|
148
|
+
(id, app_id, user_id, key, value, created_at, updated_at)
|
|
149
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
150
|
+
`).run(a,r.appId||null,r.userId||null,t,n,o,i)}function Ze(e,t){let n=e.prepare(`
|
|
151
|
+
SELECT key, value FROM user_settings
|
|
152
|
+
WHERE app_id IS ? AND user_id IS ?
|
|
153
|
+
`).all(t.appId||null,t.userId||null),r={};for(let e of n)r[e.key]=e.value;return r}function Qe(e,t,n){e.prepare(`
|
|
154
|
+
DELETE FROM user_settings
|
|
155
|
+
WHERE key = ? AND app_id IS ? AND user_id IS ?
|
|
156
|
+
`).run(t,n.appId||null,n.userId||null)}var $e=_((()=>{})),et=v({SqliteAdapter:()=>B}),B,V=_((()=>{j(),de(),Oe(),Pe(),ze(),We(),Je(),$e(),B=class{sqlite;db;config;get sqliteInstance(){return this.sqlite}constructor(e,t){this.sqlite=t.sqliteFactory(e),this.db=o(this.sqlite),this.config=t,re(this.sqlite)}async getSessions(e){return oe(this.db,e)}async getSession(e,t){return se(this.db,e,t)}async createSession(e,t){return ce(this.db,e,t)}async updateSession(e,t,n){le(this.db,e,t,n)}async deleteSession(e,t){De(this.db,e),Ne(this.db,e),qe(this.db,e),ue(this.db,e,t)}async getMessages(e,t){return await this.getSession(e,t)?ve(this.db,e):[]}async getMessagesPage(e,t,n){return await this.getSession(e,n)?ye(this.db,e,t):{messages:[],hasMore:!1,nextBeforeSequence:null}}async searchAtChats(e,t,n){return be(this.db,e,t,n)}async getMessage(e,t){return Se(this.db,e,t)}async saveMessage(e,t){return Ce(this.db,e,t)}async updateMessage(e,t,n){we(this.db,e,t,n)}async deleteMessagesAfter(e,t,n){await this.getSession(e,n)&&Te(this.db,e,t)}async deleteMessagesAfterMessageId(e,t,n){if(!await this.getSession(e,n))return;let r=await this.getMessage(t,n);if(r&&r.sessionId===e){if(r.sequence===null||r.sequence===void 0)throw Error(`消息 ${t} 缺少序号,无法删除后续消息`);Ee(this.db,e,t,r.sequence)}}async getOperations(e,t){return await this.getSession(e,t)?ke(this.db,e):[]}async getOperationsByMessage(e,t){return Ae(this.db,e,t)}async saveOperation(e,t){return je(this.db,e,t)}async updateOperationStatus(e,t,n){Me(this.db,e,t,n)}async getBackups(e){return Ie(this.db,e)}async saveBackup(e){return Le(this.db,e)}async deleteExpiredBackups(){return Re(this.db)}async getTrashItems(e){return Be(this.db,e)}async moveToTrash(e,t){return Ve(this.db,e,t,this.config)}async restoreFromTrash(e,t){return He(this.db,e,t)}async emptyExpiredTrash(){return Ue(this.db)}async saveEmbedding(e,t,n,r,i){Ge(this.db,e,t,n,r,i)}async searchSimilar(e,t,n){return Ke(this.db,e,t,n)}async getUserSetting(e,t){return Ye(this.sqlite,e,t)}async setUserSetting(e,t,n){return Xe(this.sqlite,e,t,n)}async getUserSettings(e){return Ze(this.sqlite,e)}async deleteUserSetting(e,t){return Qe(this.sqlite,e,t)}async close(){this.sqlite.close()}}}));async function tt(e){try{await e`CREATE EXTENSION IF NOT EXISTS vector`}catch{}await e`
|
|
157
|
+
CREATE TABLE IF NOT EXISTS schema_meta (
|
|
158
|
+
key TEXT PRIMARY KEY,
|
|
159
|
+
value TEXT NOT NULL
|
|
160
|
+
)
|
|
161
|
+
`,(await e`
|
|
162
|
+
SELECT value FROM schema_meta WHERE key = 'schema_version'
|
|
163
|
+
`)[0]?.value!==H&&await e`
|
|
164
|
+
DROP TABLE IF EXISTS message_parts;
|
|
165
|
+
DROP TABLE IF EXISTS messages;
|
|
166
|
+
DROP TABLE IF EXISTS operations;
|
|
167
|
+
DROP TABLE IF EXISTS backups;
|
|
168
|
+
DROP TABLE IF EXISTS trash;
|
|
169
|
+
DROP TABLE IF EXISTS embeddings;
|
|
170
|
+
DROP TABLE IF EXISTS sessions;
|
|
171
|
+
`,await e`
|
|
172
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
173
|
+
id TEXT PRIMARY KEY,
|
|
174
|
+
app_id TEXT,
|
|
175
|
+
user_id TEXT,
|
|
176
|
+
title TEXT NOT NULL,
|
|
177
|
+
model TEXT NOT NULL,
|
|
178
|
+
mode TEXT NOT NULL,
|
|
179
|
+
web_search_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
|
180
|
+
thinking_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
|
181
|
+
hidden BOOLEAN NOT NULL DEFAULT FALSE,
|
|
182
|
+
last_message_sequence INTEGER NOT NULL DEFAULT 0,
|
|
183
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
184
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
185
|
+
)
|
|
186
|
+
`,await e`
|
|
187
|
+
CREATE TABLE IF NOT EXISTS messages (
|
|
188
|
+
id TEXT PRIMARY KEY,
|
|
189
|
+
client_id TEXT,
|
|
190
|
+
session_id TEXT NOT NULL,
|
|
191
|
+
app_id TEXT,
|
|
192
|
+
user_id TEXT,
|
|
193
|
+
role TEXT NOT NULL,
|
|
194
|
+
content TEXT NOT NULL,
|
|
195
|
+
at_context_items TEXT,
|
|
196
|
+
images TEXT,
|
|
197
|
+
model TEXT,
|
|
198
|
+
mode TEXT,
|
|
199
|
+
web_search_enabled BOOLEAN,
|
|
200
|
+
thinking_enabled BOOLEAN,
|
|
201
|
+
operation_ids TEXT,
|
|
202
|
+
usage TEXT,
|
|
203
|
+
duration INTEGER,
|
|
204
|
+
finish_reason TEXT,
|
|
205
|
+
sequence INTEGER NOT NULL,
|
|
206
|
+
timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
207
|
+
UNIQUE (session_id, sequence)
|
|
208
|
+
)
|
|
209
|
+
`,await e`
|
|
210
|
+
ALTER TABLE messages
|
|
211
|
+
ADD COLUMN IF NOT EXISTS finish_reason TEXT
|
|
212
|
+
`,await e`
|
|
213
|
+
CREATE TABLE IF NOT EXISTS message_parts (
|
|
214
|
+
message_id TEXT NOT NULL,
|
|
215
|
+
sequence INTEGER NOT NULL,
|
|
216
|
+
type TEXT NOT NULL,
|
|
217
|
+
payload TEXT NOT NULL,
|
|
218
|
+
PRIMARY KEY (message_id, sequence)
|
|
219
|
+
)
|
|
220
|
+
`,await e`
|
|
221
|
+
CREATE TABLE IF NOT EXISTS operations (
|
|
222
|
+
id TEXT PRIMARY KEY,
|
|
223
|
+
session_id TEXT NOT NULL,
|
|
224
|
+
message_id TEXT,
|
|
225
|
+
app_id TEXT,
|
|
226
|
+
user_id TEXT,
|
|
227
|
+
command TEXT NOT NULL,
|
|
228
|
+
operation_type TEXT NOT NULL,
|
|
229
|
+
affected_files TEXT NOT NULL,
|
|
230
|
+
backup_path TEXT,
|
|
231
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
232
|
+
error_message TEXT,
|
|
233
|
+
timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
234
|
+
)
|
|
235
|
+
`,await e`
|
|
236
|
+
CREATE TABLE IF NOT EXISTS backups (
|
|
237
|
+
id TEXT PRIMARY KEY,
|
|
238
|
+
operation_id TEXT NOT NULL,
|
|
239
|
+
original_path TEXT NOT NULL,
|
|
240
|
+
backup_path TEXT NOT NULL,
|
|
241
|
+
file_size INTEGER NOT NULL,
|
|
242
|
+
file_hash TEXT NOT NULL,
|
|
243
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
244
|
+
expires_at TIMESTAMPTZ NOT NULL
|
|
245
|
+
)
|
|
246
|
+
`,await e`
|
|
247
|
+
CREATE TABLE IF NOT EXISTS trash (
|
|
248
|
+
id TEXT PRIMARY KEY,
|
|
249
|
+
session_id TEXT NOT NULL,
|
|
250
|
+
app_id TEXT,
|
|
251
|
+
user_id TEXT,
|
|
252
|
+
original_path TEXT NOT NULL,
|
|
253
|
+
trash_path TEXT NOT NULL,
|
|
254
|
+
deleted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
255
|
+
auto_delete_at TIMESTAMPTZ NOT NULL
|
|
256
|
+
)
|
|
257
|
+
`,await e`
|
|
258
|
+
CREATE TABLE IF NOT EXISTS user_settings (
|
|
259
|
+
id TEXT PRIMARY KEY,
|
|
260
|
+
app_id TEXT,
|
|
261
|
+
user_id TEXT,
|
|
262
|
+
key TEXT NOT NULL,
|
|
263
|
+
value TEXT NOT NULL,
|
|
264
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
265
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
266
|
+
UNIQUE(app_id, user_id, key)
|
|
267
|
+
)
|
|
268
|
+
`;try{await e`
|
|
269
|
+
CREATE TABLE IF NOT EXISTS embeddings (
|
|
270
|
+
id TEXT PRIMARY KEY,
|
|
271
|
+
session_id TEXT NOT NULL,
|
|
272
|
+
message_id TEXT,
|
|
273
|
+
app_id TEXT,
|
|
274
|
+
user_id TEXT,
|
|
275
|
+
content TEXT NOT NULL,
|
|
276
|
+
content_type TEXT NOT NULL,
|
|
277
|
+
embedding vector(1536),
|
|
278
|
+
metadata JSONB,
|
|
279
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
280
|
+
)
|
|
281
|
+
`}catch{await e`
|
|
282
|
+
CREATE TABLE IF NOT EXISTS embeddings (
|
|
283
|
+
id TEXT PRIMARY KEY,
|
|
284
|
+
session_id TEXT NOT NULL,
|
|
285
|
+
message_id TEXT,
|
|
286
|
+
app_id TEXT,
|
|
287
|
+
user_id TEXT,
|
|
288
|
+
content TEXT NOT NULL,
|
|
289
|
+
content_type TEXT NOT NULL,
|
|
290
|
+
embedding TEXT,
|
|
291
|
+
metadata JSONB,
|
|
292
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
293
|
+
)
|
|
294
|
+
`}await e`CREATE INDEX IF NOT EXISTS idx_sessions_tenant ON sessions(app_id, user_id)`,await e`CREATE INDEX IF NOT EXISTS idx_sessions_updated ON sessions(updated_at DESC)`,await e`CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id)`,await e`CREATE INDEX IF NOT EXISTS idx_messages_tenant ON messages(app_id, user_id)`,await e`CREATE INDEX IF NOT EXISTS idx_messages_sequence ON messages(session_id, sequence)`,await e`CREATE INDEX IF NOT EXISTS idx_message_parts_message ON message_parts(message_id, sequence)`,await e`CREATE INDEX IF NOT EXISTS idx_operations_session ON operations(session_id)`,await e`CREATE INDEX IF NOT EXISTS idx_operations_message ON operations(message_id)`,await e`CREATE INDEX IF NOT EXISTS idx_backups_operation ON backups(operation_id)`,await e`CREATE INDEX IF NOT EXISTS idx_backups_expires ON backups(expires_at)`,await e`CREATE INDEX IF NOT EXISTS idx_trash_tenant ON trash(app_id, user_id)`,await e`CREATE INDEX IF NOT EXISTS idx_trash_auto_delete ON trash(auto_delete_at)`,await e`CREATE INDEX IF NOT EXISTS idx_embeddings_session ON embeddings(session_id)`,await e`CREATE INDEX IF NOT EXISTS idx_embeddings_tenant ON embeddings(app_id, user_id)`,await e`CREATE INDEX IF NOT EXISTS idx_user_settings_tenant ON user_settings(app_id, user_id)`,await e`CREATE INDEX IF NOT EXISTS idx_user_settings_key ON user_settings(key)`;try{await e`CREATE INDEX IF NOT EXISTS idx_embeddings_vector ON embeddings USING hnsw (embedding vector_cosine_ops)`}catch{}await e`
|
|
295
|
+
INSERT INTO schema_meta (key, value)
|
|
296
|
+
VALUES ('schema_version', ${H})
|
|
297
|
+
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value
|
|
298
|
+
`}function nt(e,t){if(e.length===0||t.length===0||e.length!==t.length)return 0;let n=0,r=0,i=0;for(let a=0;a<e.length;a+=1)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];return r===0||i===0?0:n/(Math.sqrt(r)*Math.sqrt(i))}var H,U=_((()=>{H=`3`}));function W(e){return{id:e.id,appId:e.app_id,userId:e.user_id,title:e.title,model:e.model,mode:e.mode,webSearchEnabled:e.web_search_enabled,thinkingEnabled:e.thinking_enabled,hidden:e.hidden,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)}}async function rt(e,t){return(await e`
|
|
299
|
+
SELECT id, app_id, user_id, title, model, mode, web_search_enabled, thinking_enabled, hidden, created_at, updated_at
|
|
300
|
+
FROM sessions
|
|
301
|
+
WHERE (${t.appId||null}::TEXT IS NULL OR app_id = ${t.appId||null})
|
|
302
|
+
AND (${t.userId||null}::TEXT IS NULL OR user_id = ${t.userId||null})
|
|
303
|
+
ORDER BY updated_at DESC
|
|
304
|
+
`).map(W)}async function it(e,t,n){let r=await e`
|
|
305
|
+
SELECT id, app_id, user_id, title, model, mode, web_search_enabled, thinking_enabled, hidden, created_at, updated_at
|
|
306
|
+
FROM sessions
|
|
307
|
+
WHERE id = ${t}
|
|
308
|
+
AND (${n.appId||null}::TEXT IS NULL OR app_id = ${n.appId||null})
|
|
309
|
+
AND (${n.userId||null}::TEXT IS NULL OR user_id = ${n.userId||null})
|
|
310
|
+
`;return r[0]?W(r[0]):null}async function at(e,t,n){let r=new Date,i=t.hidden??!1;return await e`
|
|
311
|
+
INSERT INTO sessions (
|
|
312
|
+
id, app_id, user_id, title, model, mode, web_search_enabled, thinking_enabled, hidden,
|
|
313
|
+
last_message_sequence, created_at, updated_at
|
|
314
|
+
)
|
|
315
|
+
VALUES (
|
|
316
|
+
${t.id}, ${n.appId||null}, ${n.userId||null}, ${t.title}, ${t.model}, ${t.mode},
|
|
317
|
+
${t.webSearchEnabled}, ${t.thinkingEnabled}, ${i}, ${0}, ${r}, ${r}
|
|
318
|
+
)
|
|
319
|
+
`,{id:t.id,appId:n.appId||null,userId:n.userId||null,title:t.title,model:t.model,mode:t.mode,webSearchEnabled:t.webSearchEnabled,thinkingEnabled:t.thinkingEnabled,hidden:i,createdAt:r,updatedAt:r}}async function ot(e,t,n,r){await e`
|
|
320
|
+
UPDATE sessions
|
|
321
|
+
SET updated_at = ${new Date},
|
|
322
|
+
title = COALESCE(${n.title??null}, title),
|
|
323
|
+
model = COALESCE(${n.model??null}, model),
|
|
324
|
+
mode = COALESCE(${n.mode??null}, mode),
|
|
325
|
+
web_search_enabled = COALESCE(${n.webSearchEnabled??null}, web_search_enabled),
|
|
326
|
+
thinking_enabled = COALESCE(${n.thinkingEnabled??null}, thinking_enabled),
|
|
327
|
+
hidden = COALESCE(${n.hidden??null}, hidden)
|
|
328
|
+
WHERE id = ${t}
|
|
329
|
+
AND (${r.appId||null}::TEXT IS NULL OR app_id = ${r.appId||null})
|
|
330
|
+
AND (${r.userId||null}::TEXT IS NULL OR user_id = ${r.userId||null})
|
|
331
|
+
`}async function st(e,t,n){await e`
|
|
332
|
+
DELETE FROM sessions
|
|
333
|
+
WHERE id = ${t}
|
|
334
|
+
AND (${n.appId||null}::TEXT IS NULL OR app_id = ${n.appId||null})
|
|
335
|
+
AND (${n.userId||null}::TEXT IS NULL OR user_id = ${n.userId||null})
|
|
336
|
+
`}var ct=_((()=>{}));function lt(e,t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}function ut(e,t){if(!t)return null;try{let e=JSON.parse(t);return Array.isArray(e)?e:null}catch{return null}}function dt(e){switch(e){case`stop`:case`length`:case`tool_calls`:case`error`:case`abort`:case`max_iterations`:case`max_duration`:case`max_tool_calls`:case`max_tokens`:return e;default:return null}}function G(e,t){if(typeof t==`number`&&Number.isFinite(t))return t;if(t instanceof Date)return t.getTime();if(typeof t==`string`){let e=Date.parse(t);if(!Number.isNaN(e))return e}throw Error(`消息 ${e} 的时间戳无效: ${t}`)}function ft(e){return{messageId:e.message_id,sequence:e.sequence,type:e.type,payload:e.payload}}function K(e,t){let n=new Map;for(let e of t){let t=ft(e),r=n.get(t.messageId)??[];r.push(t),n.set(t.messageId,r)}return e.map(e=>({id:e.id,clientId:e.client_id||e.id,sessionId:e.session_id,appId:e.app_id,userId:e.user_id,role:e.role,content:e.content,atContextItems:ut(e.id,e.at_context_items),images:lt(e.id,e.images),model:e.model,mode:e.mode,webSearchEnabled:e.web_search_enabled,thinkingEnabled:e.thinking_enabled,parts:n.get(e.id)??[],operationIds:e.operation_ids,usage:e.usage,duration:e.duration==null?null:Number(e.duration),finishReason:dt(e.finish_reason),sequence:e.sequence,timestamp:G(e.id,e.timestamp)}))}function pt(e){return e?.trim().toLowerCase()??``}function mt(e,t=120){let n=e?.replace(/\s+/g,` `).trim()??``;return n?n.length>t?`${n.slice(0,t-1)}...`:n:``}async function q(e,t){return t.length===0?[]:e`
|
|
337
|
+
SELECT message_id, sequence, type, payload
|
|
338
|
+
FROM message_parts
|
|
339
|
+
WHERE message_id = ANY(${t}::text[])
|
|
340
|
+
ORDER BY message_id, sequence
|
|
341
|
+
`}async function J(e,t,n){let r=await e`
|
|
342
|
+
SELECT message_id, sequence, type, payload
|
|
343
|
+
FROM message_parts
|
|
344
|
+
WHERE message_id = ${t}
|
|
345
|
+
ORDER BY sequence
|
|
346
|
+
`,i=new Map;for(let e of r)i.set(e.sequence,e);let a=[],o=[];for(let[r,s]of n.entries()){let n=i.get(r);if(!n){let e=a.length;a.push(t,r,s.type,s.payload),o.push(`($${e+1}, $${e+2}, $${e+3}, $${e+4})`);continue}(n.type!==s.type||n.payload!==s.payload)&&await e`
|
|
347
|
+
UPDATE message_parts
|
|
348
|
+
SET type = ${s.type}, payload = ${s.payload}
|
|
349
|
+
WHERE message_id = ${t} AND sequence = ${r}
|
|
350
|
+
`,i.delete(r)}o.length>0&&await e.unsafe(`INSERT INTO message_parts (message_id, sequence, type, payload) VALUES ${o.join(`, `)}`,a);let s=[...i.keys()];s.length>0&&await e`
|
|
351
|
+
DELETE FROM message_parts
|
|
352
|
+
WHERE message_id = ${t}
|
|
353
|
+
AND sequence = ANY(${s}::int[])
|
|
354
|
+
`}async function ht(e,t){let n=(await e`
|
|
355
|
+
UPDATE sessions
|
|
356
|
+
SET last_message_sequence = last_message_sequence + 1,
|
|
357
|
+
updated_at = NOW()
|
|
358
|
+
WHERE id = ${t}
|
|
359
|
+
RETURNING last_message_sequence
|
|
360
|
+
`)[0]?.last_message_sequence;if(typeof n!=`number`)throw Error(`会话 ${t} 不存在,无法分配消息序号`);return n}async function gt(e,t){let n=await e`
|
|
361
|
+
SELECT id, client_id, session_id, app_id, user_id, role, content, at_context_items, images, model, mode,
|
|
362
|
+
web_search_enabled, thinking_enabled, operation_ids, usage, duration, finish_reason, sequence, timestamp
|
|
363
|
+
FROM messages
|
|
364
|
+
WHERE session_id = ${t}
|
|
365
|
+
ORDER BY sequence, timestamp
|
|
366
|
+
`;return K(n,await q(e,n.map(e=>e.id)))}async function _t(e,t,n){let r=Math.max(1,Math.min(n?.limit??200,500)),i=n?.beforeSequence??null,a=[...await e`
|
|
367
|
+
SELECT id, client_id, session_id, app_id, user_id, role, content, at_context_items, images, model, mode,
|
|
368
|
+
web_search_enabled, thinking_enabled, operation_ids, usage, duration, finish_reason, sequence, timestamp
|
|
369
|
+
FROM messages
|
|
370
|
+
WHERE session_id = ${t}
|
|
371
|
+
AND (${i}::INT IS NULL OR sequence < ${i})
|
|
372
|
+
ORDER BY sequence DESC
|
|
373
|
+
LIMIT ${r}
|
|
374
|
+
`].reverse();if(a.length===0)return{messages:[],hasMore:!1,nextBeforeSequence:null};let o=K(a,await q(e,a.map(e=>e.id))),s=o[0]?.sequence??null;return{messages:o,hasMore:s!=null&&s>1,nextBeforeSequence:s}}async function vt(e,t,n,r){let i=pt(t),a=Math.max(1,Math.min(n?.limit??20,100)),o=`%${i}%`,s=i?await e`
|
|
375
|
+
SELECT id, title, updated_at
|
|
376
|
+
FROM sessions
|
|
377
|
+
WHERE (${r.appId||null}::TEXT IS NULL OR app_id = ${r.appId||null})
|
|
378
|
+
AND (${r.userId||null}::TEXT IS NULL OR user_id = ${r.userId||null})
|
|
379
|
+
AND (
|
|
380
|
+
lower(title) LIKE ${o}
|
|
381
|
+
OR EXISTS (
|
|
382
|
+
SELECT 1
|
|
383
|
+
FROM messages
|
|
384
|
+
WHERE messages.session_id = sessions.id
|
|
385
|
+
AND lower(messages.content) LIKE ${o}
|
|
386
|
+
)
|
|
387
|
+
)
|
|
388
|
+
ORDER BY updated_at DESC
|
|
389
|
+
LIMIT ${a}
|
|
390
|
+
`:await e`
|
|
391
|
+
SELECT id, title, updated_at
|
|
392
|
+
FROM sessions
|
|
393
|
+
WHERE (${r.appId||null}::TEXT IS NULL OR app_id = ${r.appId||null})
|
|
394
|
+
AND (${r.userId||null}::TEXT IS NULL OR user_id = ${r.userId||null})
|
|
395
|
+
ORDER BY updated_at DESC
|
|
396
|
+
LIMIT ${a}
|
|
397
|
+
`,c=[];for(let t of s){let n=!i||t.title.toLowerCase().includes(i),r=await e`
|
|
398
|
+
SELECT id, content
|
|
399
|
+
FROM messages
|
|
400
|
+
WHERE session_id = ${t.id}
|
|
401
|
+
ORDER BY sequence DESC
|
|
402
|
+
LIMIT 1
|
|
403
|
+
`,a=n?[]:await e`
|
|
404
|
+
SELECT id, content
|
|
405
|
+
FROM messages
|
|
406
|
+
WHERE session_id = ${t.id}
|
|
407
|
+
AND lower(content) LIKE ${o}
|
|
408
|
+
ORDER BY sequence DESC
|
|
409
|
+
LIMIT 1
|
|
410
|
+
`,s=r[0],l=a[0],u=mt(l?.content??s?.content??``);c.push({kind:`chat`,id:t.id,sessionId:t.id,label:t.title,mention:`@chat:${t.id}`,description:u||void 0,preview:u||void 0,updatedAt:G(t.id,t.updated_at),matchedMessageId:l?.id})}return c}async function yt(e,t,n){let r=await e`
|
|
411
|
+
SELECT id, client_id, session_id, app_id, user_id, role, content, at_context_items, images, model, mode,
|
|
412
|
+
web_search_enabled, thinking_enabled, operation_ids, usage, duration, finish_reason, sequence, timestamp
|
|
413
|
+
FROM messages
|
|
414
|
+
WHERE id = ${t}
|
|
415
|
+
AND (${n.appId||null}::TEXT IS NULL OR app_id = ${n.appId||null})
|
|
416
|
+
AND (${n.userId||null}::TEXT IS NULL OR user_id = ${n.userId||null})
|
|
417
|
+
`;if(!r[0])return null;let i=await q(e,[t]);return K([r[0]],i)[0]??null}async function bt(e,t,n){let r=Date.now(),i=new Date(r),a=t.clientId||t.id;return e.begin(async e=>{let o=await ht(e,t.sessionId);return await e`
|
|
418
|
+
INSERT INTO messages (
|
|
419
|
+
id, client_id, session_id, app_id, user_id, role, content, at_context_items, images,
|
|
420
|
+
model, mode, web_search_enabled, thinking_enabled, operation_ids, usage, duration, finish_reason, sequence, timestamp
|
|
421
|
+
)
|
|
422
|
+
VALUES (
|
|
423
|
+
${t.id},
|
|
424
|
+
${a},
|
|
425
|
+
${t.sessionId},
|
|
426
|
+
${n.appId||null},
|
|
427
|
+
${n.userId||null},
|
|
428
|
+
${t.role},
|
|
429
|
+
${t.content},
|
|
430
|
+
${t.atContextItems?JSON.stringify(t.atContextItems):null},
|
|
431
|
+
${t.images&&t.images.length>0?JSON.stringify(t.images):null},
|
|
432
|
+
${t.model},
|
|
433
|
+
${t.mode},
|
|
434
|
+
${t.webSearchEnabled},
|
|
435
|
+
${t.thinkingEnabled},
|
|
436
|
+
${t.operationIds},
|
|
437
|
+
${null},
|
|
438
|
+
${null},
|
|
439
|
+
${t.finishReason??null},
|
|
440
|
+
${o},
|
|
441
|
+
${i}
|
|
442
|
+
)
|
|
443
|
+
`,t.parts&&t.parts.length>0&&await J(e,t.id,t.parts),{id:t.id,clientId:a,sessionId:t.sessionId,appId:n.appId||null,userId:n.userId||null,role:t.role,content:t.content,atContextItems:t.atContextItems||null,images:t.images||[],model:t.model,mode:t.mode,webSearchEnabled:t.webSearchEnabled,thinkingEnabled:t.thinkingEnabled,parts:(t.parts??[]).map((e,n)=>({messageId:t.id,sequence:n,type:e.type,payload:e.payload})),operationIds:t.operationIds,usage:null,duration:null,finishReason:t.finishReason??null,sequence:o,timestamp:r}})}async function xt(e,t,n,r){await e.begin(async e=>{let i=[],a=[],o=1;if(n.content!==void 0&&(i.push(`content = $${o++}`),a.push(n.content)),n.atContextItems!==void 0&&(i.push(`at_context_items = $${o++}`),a.push(n.atContextItems?JSON.stringify(n.atContextItems):null)),n.operationIds!==void 0&&(i.push(`operation_ids = $${o++}`),a.push(n.operationIds)),n.usage!==void 0&&(i.push(`usage = $${o++}`),a.push(n.usage)),n.duration!==void 0&&(i.push(`duration = $${o++}`),a.push(n.duration)),n.finishReason!==void 0&&(i.push(`finish_reason = $${o++}`),a.push(n.finishReason)),i.length>0){let n=`WHERE id = $${o++}${r.appId?` AND app_id = $${o++}`:``}${r.userId?` AND user_id = $${o++}`:``}`;a.push(t),r.appId&&a.push(r.appId),r.userId&&a.push(r.userId),await e.unsafe(`UPDATE messages SET ${i.join(`, `)} ${n}`,a)}n.parts!==void 0&&await J(e,t,n.parts)})}async function St(e,t,n){await e.begin(async e=>{let r=(await e`
|
|
444
|
+
SELECT id FROM messages
|
|
445
|
+
WHERE session_id = ${t}
|
|
446
|
+
AND timestamp > ${n}
|
|
447
|
+
`).map(e=>e.id);r.length>0&&await e`DELETE FROM message_parts WHERE message_id = ANY(${r}::text[])`,await e`
|
|
448
|
+
DELETE FROM messages
|
|
449
|
+
WHERE session_id = ${t}
|
|
450
|
+
AND timestamp > ${n}
|
|
451
|
+
`})}async function Ct(e,t,n,r){await e.begin(async e=>{let n=(await e`
|
|
452
|
+
SELECT id FROM messages
|
|
453
|
+
WHERE session_id = ${t}
|
|
454
|
+
AND sequence > ${r}
|
|
455
|
+
`).map(e=>e.id);n.length>0&&await e`DELETE FROM message_parts WHERE message_id = ANY(${n}::text[])`,await e`
|
|
456
|
+
DELETE FROM messages
|
|
457
|
+
WHERE session_id = ${t}
|
|
458
|
+
AND sequence > ${r}
|
|
459
|
+
`})}async function wt(e,t){await e.begin(async e=>{let n=(await e`
|
|
460
|
+
SELECT id FROM messages
|
|
461
|
+
WHERE session_id = ${t}
|
|
462
|
+
`).map(e=>e.id);n.length>0&&await e`DELETE FROM message_parts WHERE message_id = ANY(${n}::text[])`,await e`DELETE FROM messages WHERE session_id = ${t}`})}var Tt=_((()=>{}));function Y(e){return{id:e.id,sessionId:e.session_id,messageId:e.message_id,appId:e.app_id,userId:e.user_id,command:e.command,operationType:e.operation_type,affectedFiles:e.affected_files,backupPath:e.backup_path,status:e.status,errorMessage:e.error_message,timestamp:new Date(e.timestamp)}}async function Et(e,t){return(await e`
|
|
463
|
+
SELECT id, session_id, message_id, app_id, user_id, command, operation_type,
|
|
464
|
+
affected_files, backup_path, status, error_message, timestamp
|
|
465
|
+
FROM operations
|
|
466
|
+
WHERE session_id = ${t}
|
|
467
|
+
ORDER BY timestamp
|
|
468
|
+
`).map(Y)}async function Dt(e,t,n){return(await e`
|
|
469
|
+
SELECT id, session_id, message_id, app_id, user_id, command, operation_type,
|
|
470
|
+
affected_files, backup_path, status, error_message, timestamp
|
|
471
|
+
FROM operations
|
|
472
|
+
WHERE message_id = ${t}
|
|
473
|
+
AND (${n.appId||null}::TEXT IS NULL OR app_id = ${n.appId||null})
|
|
474
|
+
AND (${n.userId||null}::TEXT IS NULL OR user_id = ${n.userId||null})
|
|
475
|
+
`).map(Y)}async function Ot(e,t,n){let r=new Date,i=t.status||`pending`;return await e`
|
|
476
|
+
INSERT INTO operations (id, session_id, message_id, app_id, user_id, command, operation_type, affected_files, backup_path, status, timestamp)
|
|
477
|
+
VALUES (${t.id}, ${t.sessionId}, ${t.messageId||null}, ${n.appId||null}, ${n.userId||null}, ${t.command}, ${t.operationType}, ${t.affectedFiles}, ${t.backupPath||null}, ${i}, ${r})
|
|
478
|
+
`,{id:t.id,sessionId:t.sessionId,messageId:t.messageId,appId:n.appId||null,userId:n.userId||null,command:t.command,operationType:t.operationType,affectedFiles:t.affectedFiles,backupPath:t.backupPath,status:i,errorMessage:null,timestamp:r}}async function kt(e,t,n,r){await e`
|
|
479
|
+
UPDATE operations
|
|
480
|
+
SET status = ${n}, error_message = ${r||null}
|
|
481
|
+
WHERE id = ${t}
|
|
482
|
+
`}async function At(e,t){await e`DELETE FROM operations WHERE session_id = ${t}`}var jt=_((()=>{}));function Mt(e){return{id:e.id,operationId:e.operation_id,originalPath:e.original_path,backupPath:e.backup_path,fileSize:e.file_size,fileHash:e.file_hash,createdAt:new Date(e.created_at),expiresAt:new Date(e.expires_at)}}async function Nt(e,t){return(await e`
|
|
483
|
+
SELECT id, operation_id, original_path, backup_path, file_size, file_hash, created_at, expires_at
|
|
484
|
+
FROM backups
|
|
485
|
+
WHERE operation_id = ${t}
|
|
486
|
+
`).map(Mt)}async function Pt(e,t){let n=new Date;return await e`
|
|
487
|
+
INSERT INTO backups (id, operation_id, original_path, backup_path, file_size, file_hash, created_at, expires_at)
|
|
488
|
+
VALUES (${t.id}, ${t.operationId}, ${t.originalPath}, ${t.backupPath}, ${t.fileSize}, ${t.fileHash}, ${n}, ${t.expiresAt})
|
|
489
|
+
`,{...t,createdAt:n}}async function Ft(e){return(await e`DELETE FROM backups WHERE expires_at < NOW()`).count}var It=_((()=>{}));function X(e){return{id:e.id,sessionId:e.session_id,appId:e.app_id,userId:e.user_id,originalPath:e.original_path,trashPath:e.trash_path,deletedAt:new Date(e.deleted_at),autoDeleteAt:new Date(e.auto_delete_at)}}async function Lt(e,t){return(await e`
|
|
490
|
+
SELECT id, session_id, app_id, user_id, original_path, trash_path, deleted_at, auto_delete_at
|
|
491
|
+
FROM trash
|
|
492
|
+
WHERE (${t.appId||null}::TEXT IS NULL OR app_id = ${t.appId||null})
|
|
493
|
+
AND (${t.userId||null}::TEXT IS NULL OR user_id = ${t.userId||null})
|
|
494
|
+
ORDER BY deleted_at DESC
|
|
495
|
+
`).map(X)}async function Rt(e,t,n,r){let i=new Date,a=r.trashRetentionDays||30,o=new Date(i.getTime()+a*24*60*60*1e3);return await e`
|
|
496
|
+
INSERT INTO trash (id, session_id, app_id, user_id, original_path, trash_path, deleted_at, auto_delete_at)
|
|
497
|
+
VALUES (${t.id}, ${t.sessionId}, ${n.appId||null}, ${n.userId||null}, ${t.originalPath}, ${t.trashPath}, ${i}, ${o})
|
|
498
|
+
`,{...t,appId:n.appId||null,userId:n.userId||null,deletedAt:i,autoDeleteAt:o}}async function zt(e,t,n){let r=await e`
|
|
499
|
+
SELECT id, session_id, app_id, user_id, original_path, trash_path, deleted_at, auto_delete_at
|
|
500
|
+
FROM trash
|
|
501
|
+
WHERE id = ${t}
|
|
502
|
+
AND (${n.appId||null}::TEXT IS NULL OR app_id = ${n.appId||null})
|
|
503
|
+
AND (${n.userId||null}::TEXT IS NULL OR user_id = ${n.userId||null})
|
|
504
|
+
`;if(!r[0])throw Error(`回收站记录不存在`);return await e`DELETE FROM trash WHERE id = ${t}`,X(r[0])}async function Bt(e){return(await e`DELETE FROM trash WHERE auto_delete_at < NOW()`).count}var Vt=_((()=>{}));async function Z(e,t,n,r,i,a){let o=`[${r.join(`,`)}]`;try{await e`
|
|
505
|
+
INSERT INTO embeddings (id, session_id, message_id, app_id, user_id, content, content_type, embedding, metadata, created_at)
|
|
506
|
+
VALUES (${t}, ${i.sessionId}, ${i.messageId||null}, ${a.appId||null}, ${a.userId||null}, ${n}, ${i.contentType}, ${o}::vector, ${JSON.stringify(i)}, NOW())
|
|
507
|
+
`}catch{await e`
|
|
508
|
+
INSERT INTO embeddings (id, session_id, message_id, app_id, user_id, content, content_type, embedding, metadata, created_at)
|
|
509
|
+
VALUES (${t}, ${i.sessionId}, ${i.messageId||null}, ${a.appId||null}, ${a.userId||null}, ${n}, ${i.contentType}, ${o}, ${JSON.stringify(i)}, NOW())
|
|
510
|
+
`}}async function Ht(e,t,n,r){let{limit:i=10,threshold:a=.7,sessionId:o}=n,s=`[${t.join(`,`)}]`;try{return(await e`
|
|
511
|
+
SELECT id, content, content_type, metadata,
|
|
512
|
+
1 - (embedding <=> ${s}::vector) as similarity
|
|
513
|
+
FROM embeddings
|
|
514
|
+
WHERE (${r.appId||null}::TEXT IS NULL OR app_id = ${r.appId||null})
|
|
515
|
+
AND (${r.userId||null}::TEXT IS NULL OR user_id = ${r.userId||null})
|
|
516
|
+
AND (${o||null}::TEXT IS NULL OR session_id = ${o||null})
|
|
517
|
+
AND 1 - (embedding <=> ${s}::vector) > ${a}
|
|
518
|
+
ORDER BY embedding <=> ${s}::vector
|
|
519
|
+
LIMIT ${i}
|
|
520
|
+
`).map(e=>({id:e.id,content:e.content,contentType:e.content_type,similarity:e.similarity||0,metadata:e.metadata}))}catch{return(await e`
|
|
521
|
+
SELECT id, content, content_type, embedding, metadata
|
|
522
|
+
FROM embeddings
|
|
523
|
+
WHERE (${r.appId||null}::TEXT IS NULL OR app_id = ${r.appId||null})
|
|
524
|
+
AND (${r.userId||null}::TEXT IS NULL OR user_id = ${r.userId||null})
|
|
525
|
+
AND (${o||null}::TEXT IS NULL OR session_id = ${o||null})
|
|
526
|
+
`).map(e=>{let n=[];if(typeof e.embedding==`string`)try{n=JSON.parse(e.embedding.replace(/^\[|\]$/g,``).split(`,`).map(Number).join(`,`))}catch{n=e.embedding.slice(1,-1).split(`,`).map(Number)}else Array.isArray(e.embedding)&&(n=e.embedding);let r=nt(t,n);return{id:e.id,content:e.content,contentType:e.content_type,similarity:r,metadata:e.metadata}}).filter(e=>e.similarity>=a).sort((e,t)=>t.similarity-e.similarity).slice(0,i)}}async function Ut(e,t){await e`DELETE FROM embeddings WHERE session_id = ${t}`}var Wt=_((()=>{U()})),Gt=v({PostgresAdapter:()=>Q}),Q,$=_((()=>{U(),ct(),Tt(),jt(),It(),Vt(),Wt(),Q=class{sql;config;initialized=!1;constructor(e,t){this.sql=m(e),this.config=t}async ensureInitialized(){this.initialized||=(await tt(this.sql),!0)}async getSessions(e){return await this.ensureInitialized(),rt(this.sql,e)}async getSession(e,t){return await this.ensureInitialized(),it(this.sql,e,t)}async createSession(e,t){return await this.ensureInitialized(),at(this.sql,e,t)}async updateSession(e,t,n){await this.ensureInitialized(),await ot(this.sql,e,t,n)}async deleteSession(e,t){await this.ensureInitialized(),await wt(this.sql,e),await At(this.sql,e),await Ut(this.sql,e),await st(this.sql,e,t)}async getMessages(e,t){return await this.ensureInitialized(),await this.getSession(e,t)?gt(this.sql,e):[]}async getMessagesPage(e,t,n){return await this.ensureInitialized(),await this.getSession(e,n)?_t(this.sql,e,t):{messages:[],hasMore:!1,nextBeforeSequence:null}}async searchAtChats(e,t,n){return await this.ensureInitialized(),vt(this.sql,e,t,n)}async getMessage(e,t){return await this.ensureInitialized(),yt(this.sql,e,t)}async saveMessage(e,t){return await this.ensureInitialized(),bt(this.sql,e,t)}async updateMessage(e,t,n){await this.ensureInitialized(),await xt(this.sql,e,t,n)}async deleteMessagesAfter(e,t,n){await this.ensureInitialized(),await this.getSession(e,n)&&await St(this.sql,e,t)}async deleteMessagesAfterMessageId(e,t,n){if(await this.ensureInitialized(),!await this.getSession(e,n))return;let r=await this.getMessage(t,n);if(r&&r.sessionId===e){if(r.sequence===null||r.sequence===void 0)throw Error(`消息 ${t} 缺少序号,无法删除后续消息`);await Ct(this.sql,e,t,r.sequence)}}async getOperations(e,t){return await this.ensureInitialized(),await this.getSession(e,t)?Et(this.sql,e):[]}async getOperationsByMessage(e,t){return await this.ensureInitialized(),Dt(this.sql,e,t)}async saveOperation(e,t){return await this.ensureInitialized(),Ot(this.sql,e,t)}async updateOperationStatus(e,t,n){await this.ensureInitialized(),await kt(this.sql,e,t,n)}async getBackups(e){return await this.ensureInitialized(),Nt(this.sql,e)}async saveBackup(e){return await this.ensureInitialized(),Pt(this.sql,e)}async deleteExpiredBackups(){return await this.ensureInitialized(),Ft(this.sql)}async getTrashItems(e){return await this.ensureInitialized(),Lt(this.sql,e)}async moveToTrash(e,t){return await this.ensureInitialized(),Rt(this.sql,e,t,this.config)}async restoreFromTrash(e,t){return await this.ensureInitialized(),zt(this.sql,e,t)}async emptyExpiredTrash(){return await this.ensureInitialized(),Bt(this.sql)}async saveEmbedding(e,t,n,r,i){await this.ensureInitialized(),await Z(this.sql,e,t,n,r,i)}async searchSimilar(e,t,n){return await this.ensureInitialized(),Ht(this.sql,e,t,n)}async getUserSetting(e,t){await this.ensureInitialized();let n=`${t.appId||`default`}_${t.userId||`default`}_${e}`,r=await this.sql`
|
|
527
|
+
SELECT value FROM user_settings
|
|
528
|
+
WHERE id = ${n}
|
|
529
|
+
LIMIT 1
|
|
530
|
+
`;return r.length>0?r[0].value:null}async setUserSetting(e,t,n){await this.ensureInitialized();let r=`${n.appId||`default`}_${n.userId||`default`}_${e}`;await this.sql`
|
|
531
|
+
INSERT INTO user_settings (id, app_id, user_id, key, value, created_at, updated_at)
|
|
532
|
+
VALUES (${r}, ${n.appId||null}, ${n.userId||null}, ${e}, ${t}, NOW(), NOW())
|
|
533
|
+
ON CONFLICT (id) DO UPDATE SET
|
|
534
|
+
value = ${t},
|
|
535
|
+
updated_at = NOW()
|
|
536
|
+
`}async getUserSettings(e){await this.ensureInitialized();let t=await this.sql`
|
|
537
|
+
SELECT key, value FROM user_settings
|
|
538
|
+
WHERE app_id IS NOT DISTINCT FROM ${e.appId||null}
|
|
539
|
+
AND user_id IS NOT DISTINCT FROM ${e.userId||null}
|
|
540
|
+
`,n={};for(let e of t)n[e.key]=e.value;return n}async deleteUserSetting(e,t){await this.ensureInitialized(),await this.sql`
|
|
541
|
+
DELETE FROM user_settings
|
|
542
|
+
WHERE key = ${e}
|
|
543
|
+
AND app_id IS NOT DISTINCT FROM ${t.appId||null}
|
|
544
|
+
AND user_id IS NOT DISTINCT FROM ${t.userId||null}
|
|
545
|
+
`}async close(){await this.sql.end()}}}));E(),V(),$();async function Kt(e){switch(e.type){case`sqlite`:{if(!e.sqlitePath)throw Error(`SQLite 需要提供 sqlitePath 配置`);if(!e.sqliteFactory)throw Error(`SQLite 需要提供 sqliteFactory 配置`);let t=te(e.sqlitePath);ee(t)||h(t,{recursive:!0});let{SqliteAdapter:n}=await Promise.resolve().then(()=>(V(),et));return new n(e.sqlitePath,e)}case`postgres`:{if(!e.postgresUrl)throw Error(`PostgreSQL 需要提供 postgresUrl 配置`);let{PostgresAdapter:t}=await Promise.resolve().then(()=>($(),Gt));return new t(e.postgresUrl,e)}}throw Error(`不支持的存储类型`)}function qt(){return`${process.env.HOME||process.env.USERPROFILE||`.`}/.ai-chat/db.sqlite`}function Jt(){return`${process.env.HOME||process.env.USERPROFILE||`.`}/.ai-chat/backups`}function Yt(){return`${process.env.HOME||process.env.USERPROFILE||`.`}/.ai-chat/trash`}export{Q as PostgresAdapter,B as SqliteAdapter,C as backups,Kt as createStorage,T as embeddings,Jt as getDefaultBackupDir,qt as getDefaultStoragePath,Yt as getDefaultTrashDir,x as messageParts,b as messages,S as operations,y as sessions,w as trash};
|