@wirecat/cli-core 0.702.0 → 0.704.0
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/CHANGELOG.md +68 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/messenger/conversation-answers.d.ts +1 -1
- package/dist/cli/messenger/conversation-answers.js +4 -1
- package/dist/cli/messenger/conversations-command.js +2 -1
- package/dist/crm/cli/index.js +8 -5
- package/dist/crm/manifest/source.js +2 -2
- package/dist/crm/testing/manifest-fake.js +18 -0
- package/dist/documents/file-mirror-model.d.ts +88 -0
- package/dist/documents/file-mirror-model.js +1 -0
- package/dist/documents/index.d.ts +5 -2
- package/dist/documents/index.js +2 -0
- package/dist/documents/push-model.d.ts +3 -0
- package/dist/embeddings/onnx-runtime.d.ts +1 -1
- package/dist/embeddings/onnx-runtime.js +42 -61
- package/dist/errors/reasons.js +8 -0
- package/dist/ports/wirecat-tools.js +7 -0
- package/dist/sends/upload.js +0 -1
- package/dist/services/documents/mirror-watch.d.ts +12 -4
- package/dist/services/documents/mirror-watch.js +2 -0
- package/dist/services/documents/mirrors.d.ts +55 -35
- package/dist/services/documents/mirrors.js +63 -66
- package/dist/services/documents/push.d.ts +56 -4
- package/dist/services/documents/push.js +131 -24
- package/dist/services/embeddings-search.js +35 -10
- package/dist/services/embeddings.d.ts +2 -0
- package/dist/services/files/mirror.d.ts +145 -0
- package/dist/services/files/mirror.js +603 -0
- package/dist/services/files/versions.d.ts +50 -0
- package/dist/services/files/versions.js +142 -0
- package/dist/services/metadata.d.ts +1 -1
- package/dist/store/sqlite/vectors.d.ts +1 -0
- package/dist/store/sqlite/vectors.js +25 -2
- package/dist/store/vectors.d.ts +2 -0
- package/dist/store/vectors.js +4 -2
- package/package.json +1 -1
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { appendFileSync, createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
3
|
+
import { readdir, rename, rm, stat, utimes } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { Transform } from "node:stream";
|
|
6
|
+
import { pipeline } from "node:stream/promises";
|
|
7
|
+
import { CliError } from "@wirecat/cli-base";
|
|
8
|
+
import { assertNoLink, replaceLocal, safePath } from "../documents/push.js";
|
|
9
|
+
const RETAIN_MS = 30 * 24 * 60 * 60 * 1000;
|
|
10
|
+
/**
|
|
11
|
+
* A mirror's local version store: `<dir>/objects/<sha256>` holds each kept content once, `<dir>/log.jsonl` is
|
|
12
|
+
* append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention, one
|
|
13
|
+
* rule: a content stays while an event newer than 30 days names it, and the last content of a path whose newest
|
|
14
|
+
* event is a deletion stays for good. A content no event names stays 30 days after it was last kept, so a crash
|
|
15
|
+
* between keeping a file and logging the change loses nothing.
|
|
16
|
+
*/
|
|
17
|
+
export const fileVersions = (dir, now = Date.now) => {
|
|
18
|
+
const objects = join(dir, "objects");
|
|
19
|
+
const logPath = join(dir, "log.jsonl");
|
|
20
|
+
const events = () => {
|
|
21
|
+
try {
|
|
22
|
+
return readFileSync(logPath, "utf8")
|
|
23
|
+
.split("\n")
|
|
24
|
+
.filter(Boolean)
|
|
25
|
+
.map((line) => JSON.parse(line));
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
if (error.code === "ENOENT")
|
|
29
|
+
return [];
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
const has = (sha256) => existsSync(join(objects, sha256));
|
|
34
|
+
return {
|
|
35
|
+
keep: async (absolute) => {
|
|
36
|
+
mkdirSync(objects, { recursive: true, mode: 0o700 });
|
|
37
|
+
const temp = join(objects, `.${randomUUID()}.tmp`);
|
|
38
|
+
const hash = createHash("sha256");
|
|
39
|
+
try {
|
|
40
|
+
// Hashed while copied: the file may change under the sync, and the store is keyed by what it really holds.
|
|
41
|
+
await pipeline(createReadStream(absolute), new Transform({
|
|
42
|
+
transform(chunk, _encoding, done) {
|
|
43
|
+
hash.update(chunk);
|
|
44
|
+
done(null, chunk);
|
|
45
|
+
},
|
|
46
|
+
}), createWriteStream(temp, { flags: "wx", mode: 0o600 }));
|
|
47
|
+
const sha256 = hash.digest("hex");
|
|
48
|
+
const object = join(objects, sha256);
|
|
49
|
+
if (!has(sha256))
|
|
50
|
+
await rename(temp, object);
|
|
51
|
+
const at = now() / 1000;
|
|
52
|
+
await utimes(object, at, at);
|
|
53
|
+
return sha256;
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
await rm(temp, { force: true });
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
log: (event) => {
|
|
60
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
61
|
+
appendFileSync(logPath, `${JSON.stringify({ at: new Date(now()).toISOString(), ...event })}\n`, { mode: 0o600 });
|
|
62
|
+
},
|
|
63
|
+
list: (path) => {
|
|
64
|
+
const found = events().filter((event) => event.path === path || event.to === path);
|
|
65
|
+
return found.map((event) => ({
|
|
66
|
+
...event,
|
|
67
|
+
available: event.old !== undefined && existsSync(join(objects, event.old)),
|
|
68
|
+
}));
|
|
69
|
+
},
|
|
70
|
+
write: async (sha256, into, over) => {
|
|
71
|
+
if (!has(sha256))
|
|
72
|
+
return false;
|
|
73
|
+
const copy = (temp) => pipeline(createReadStream(join(objects, sha256)), createWriteStream(temp, { flags: "wx" }));
|
|
74
|
+
return (await replaceLocal(into, over, copy, { sha256 })) !== undefined;
|
|
75
|
+
},
|
|
76
|
+
prune: async () => {
|
|
77
|
+
const all = events();
|
|
78
|
+
const keep = new Set();
|
|
79
|
+
const last = new Map();
|
|
80
|
+
for (const event of all) {
|
|
81
|
+
last.set(event.path, event);
|
|
82
|
+
if (Date.parse(event.at) > now() - RETAIN_MS)
|
|
83
|
+
for (const hash of [event.old, event.new])
|
|
84
|
+
if (hash)
|
|
85
|
+
keep.add(hash);
|
|
86
|
+
}
|
|
87
|
+
for (const event of last.values())
|
|
88
|
+
if (event.event === "deleted" && event.old)
|
|
89
|
+
keep.add(event.old);
|
|
90
|
+
let names;
|
|
91
|
+
try {
|
|
92
|
+
names = await readdir(objects);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
for (const name of names) {
|
|
98
|
+
if (name.startsWith(".") || keep.has(name))
|
|
99
|
+
continue;
|
|
100
|
+
const object = join(objects, name);
|
|
101
|
+
const kept = await stat(object).catch((error) => {
|
|
102
|
+
if (error.code === "ENOENT")
|
|
103
|
+
return undefined;
|
|
104
|
+
throw error;
|
|
105
|
+
});
|
|
106
|
+
if (kept && kept.mtimeMs <= now() - RETAIN_MS)
|
|
107
|
+
await rm(object, { force: true });
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Puts a kept version of `path` back into the mirrored folder; the file there now is kept first. The next sync sends
|
|
114
|
+
* it like any local change. False when the store no longer has the version or the file changed meanwhile. Runs under
|
|
115
|
+
* the mirrors' sync lock, so a sync never reads the folder halfway through.
|
|
116
|
+
*/
|
|
117
|
+
export const restoreFileVersion = async (root, path, sha256, versions, lock) => {
|
|
118
|
+
if (!safePath(path))
|
|
119
|
+
throw new CliError("validation_error", `${path} is not a path inside the mirror`);
|
|
120
|
+
const held = await lock();
|
|
121
|
+
try {
|
|
122
|
+
await assertNoLink(root, path);
|
|
123
|
+
const absolute = join(root, path);
|
|
124
|
+
const current = existsSync(absolute) ? await versions.keep(absolute) : undefined;
|
|
125
|
+
if (current === sha256)
|
|
126
|
+
return true;
|
|
127
|
+
held.assertHeld();
|
|
128
|
+
if (!(await versions.write(sha256, absolute, current)))
|
|
129
|
+
return false;
|
|
130
|
+
versions.log({
|
|
131
|
+
path,
|
|
132
|
+
event: current ? "changed" : "created",
|
|
133
|
+
direction: "restored",
|
|
134
|
+
...(current ? { old: current } : {}),
|
|
135
|
+
new: sha256,
|
|
136
|
+
});
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
await held.release();
|
|
141
|
+
}
|
|
142
|
+
};
|
|
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
|
|
|
14
14
|
dryRun?: boolean;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
items: ({
|
|
17
|
-
error?: undefined;
|
|
18
17
|
chatId: string;
|
|
19
18
|
tags: import("../domain/channel-tags.js").ChannelTagMatch[];
|
|
20
19
|
algorithm: string;
|
|
21
20
|
fetchedAt: string | null;
|
|
22
21
|
source: string;
|
|
22
|
+
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
tags?: undefined;
|
|
25
25
|
algorithm?: undefined;
|
|
@@ -80,6 +80,7 @@ export declare const nearestChunks: (context: StoreContext, accountPk: number, f
|
|
|
80
80
|
projectId?: number;
|
|
81
81
|
before?: number;
|
|
82
82
|
personId?: number;
|
|
83
|
+
fromOwner?: boolean;
|
|
83
84
|
}) => NearestChunk[];
|
|
84
85
|
/** Chats in scope whose current build has vectors of another model and none of `model`: a search with it skips them. */
|
|
85
86
|
export declare const embeddedOnlyElsewhere: ({ orm }: StoreContext, accountPk: number, { chatKey, model }: {
|
|
@@ -181,7 +181,7 @@ export const dot = (query, blob) => {
|
|
|
181
181
|
*/
|
|
182
182
|
export const nearestChunks = (context, accountPk, filter) => {
|
|
183
183
|
const { orm } = context;
|
|
184
|
-
const { chatKey, model, since, limit, query, exclude, conversations, scope, projectId, before, personId } = filter;
|
|
184
|
+
const { chatKey, model, since, limit, query, exclude, conversations, scope, projectId, before, personId, fromOwner } = filter;
|
|
185
185
|
const rows = (page) => orm.all(
|
|
186
186
|
// CROSS JOIN keeps the chunks first, so each page walks their key; led by the vectors, SQLite re-read and
|
|
187
187
|
// sorted every one of them per page — 1.3 s against 140 ms at 42k chunks (bench/embeddings/README.md).
|
|
@@ -197,6 +197,7 @@ export const nearestChunks = (context, accountPk, filter) => {
|
|
|
197
197
|
${projectId === undefined ? sql `` : sql `AND k.project_id=${projectId}`}
|
|
198
198
|
${before === undefined ? sql `` : sql `AND k.occurred_at < ${before}`}
|
|
199
199
|
${personId === undefined ? sql `` : sql `AND EXISTS (SELECT 1 FROM conversation_messages pcm JOIN messages pm ON pm.id=pcm.message_id JOIN identity_links pil ON pil.identity_id=pm.sender_identity_id WHERE pcm.conversation_id=c.id AND pil.person_id=${personId})`}
|
|
200
|
+
${fromOwner ? sql `AND EXISTS (SELECT 1 FROM conversation_messages om JOIN messages m ON m.id = om.message_id WHERE om.conversation_id = c.id AND m.outgoing = 1 AND m.id BETWEEN r.first_message_id AND r.last_message_id)` : sql ``}
|
|
200
201
|
${chatKey === undefined ? sql `AND ch.searchable = 1` : sql `AND c.chat_id = ${chatKey}`}
|
|
201
202
|
${since === undefined ? sql `` : sql `AND k.occurred_at >= ${since}`}
|
|
202
203
|
${exclude === undefined ? sql `` : sql `AND c.id <> ${exclude}`}
|
|
@@ -226,7 +227,11 @@ export const nearestChunks = (context, accountPk, filter) => {
|
|
|
226
227
|
const ranked = (found) => found.sort((a, b) => b.score - a.score).slice(0, limit);
|
|
227
228
|
const plain = (found) => found.map(({ id: _, ...chunk }) => chunk);
|
|
228
229
|
// The index has no person, project, scope or conversation list; with one of those the scan stays.
|
|
229
|
-
const indexable = personId === undefined &&
|
|
230
|
+
const indexable = personId === undefined &&
|
|
231
|
+
projectId === undefined &&
|
|
232
|
+
scope === undefined &&
|
|
233
|
+
conversations === undefined &&
|
|
234
|
+
!fromOwner;
|
|
230
235
|
const indexed = indexable &&
|
|
231
236
|
searchIndex(context.database, model, {
|
|
232
237
|
kind: "conversation",
|
|
@@ -245,6 +250,24 @@ export const nearestChunks = (context, accountPk, filter) => {
|
|
|
245
250
|
});
|
|
246
251
|
if (indexed)
|
|
247
252
|
return plain(indexed);
|
|
253
|
+
if (fromOwner) {
|
|
254
|
+
// The owner's chunks are few: find them by the owner's messages, then score only those.
|
|
255
|
+
const ids = orm
|
|
256
|
+
.all(sql `SELECT DISTINCT k.id FROM messages m
|
|
257
|
+
JOIN conversation_messages om ON om.message_id = m.id
|
|
258
|
+
JOIN conversations c ON c.id = om.conversation_id
|
|
259
|
+
JOIN conversation_state s ON s.chat_id = c.chat_id AND s.current_build = c.build
|
|
260
|
+
JOIN chats ch ON ch.id = c.chat_id
|
|
261
|
+
JOIN chunks k ON k.chunkable_type = 'conversation' AND k.chunkable_id = c.id
|
|
262
|
+
JOIN chunk_messages r ON r.chunk_id = k.id AND m.id BETWEEN r.first_message_id AND r.last_message_id
|
|
263
|
+
WHERE m.outgoing = 1 AND ch.account_id = ${accountPk}
|
|
264
|
+
${chatKey === undefined ? sql `AND ch.searchable = 1` : sql `AND c.chat_id = ${chatKey}`}`)
|
|
265
|
+
.map(({ id }) => id);
|
|
266
|
+
const best = new Map();
|
|
267
|
+
for (const row of rows({ ids }))
|
|
268
|
+
keepBest(best, row);
|
|
269
|
+
return plain(ranked([...best.values()]));
|
|
270
|
+
}
|
|
248
271
|
const best = new Map();
|
|
249
272
|
let after = { conversation: 0, ordinal: -1 };
|
|
250
273
|
for (;;) {
|
package/dist/store/vectors.d.ts
CHANGED
|
@@ -120,6 +120,8 @@ export interface AccountVectors {
|
|
|
120
120
|
projectId?: string;
|
|
121
121
|
personId?: string;
|
|
122
122
|
before?: string;
|
|
123
|
+
/** Only chunks that hold one of the owner's own messages. */
|
|
124
|
+
fromOwner?: boolean;
|
|
123
125
|
}): Promise<ConversationHit[]>;
|
|
124
126
|
/**
|
|
125
127
|
* A conversation of the current build: how many chunks it has, and the vectors of `model` of those whose
|
package/dist/store/vectors.js
CHANGED
|
@@ -165,7 +165,7 @@ export const accountVectorsOver = (context, mail) => {
|
|
|
165
165
|
});
|
|
166
166
|
return cleared;
|
|
167
167
|
},
|
|
168
|
-
nearestConversations: async (key, { chatId, model, since, limit, query, exclude, conversations, scope, projectId, personId, before }) => {
|
|
168
|
+
nearestConversations: async (key, { chatId, model, since, limit, query, exclude, conversations, scope, projectId, personId, before, fromOwner }) => {
|
|
169
169
|
const accountPk = findAccountPk(key);
|
|
170
170
|
if (accountPk === undefined)
|
|
171
171
|
return [];
|
|
@@ -175,7 +175,8 @@ export const accountVectorsOver = (context, mail) => {
|
|
|
175
175
|
scope === undefined &&
|
|
176
176
|
projectId === undefined &&
|
|
177
177
|
personId === undefined &&
|
|
178
|
-
before === undefined
|
|
178
|
+
before === undefined &&
|
|
179
|
+
!fromOwner;
|
|
179
180
|
const mailHits = async () => mailToo
|
|
180
181
|
? (await mail().nearest(model, query, {
|
|
181
182
|
accountId: accountPk,
|
|
@@ -203,6 +204,7 @@ export const accountVectorsOver = (context, mail) => {
|
|
|
203
204
|
...(projectId === undefined ? {} : { projectId: Number(projectId) }),
|
|
204
205
|
...(personId === undefined ? {} : { personId: Number(personId) }),
|
|
205
206
|
...(before === undefined ? {} : { before: Date.parse(before) }),
|
|
207
|
+
...(fromOwner ? { fromOwner } : {}),
|
|
206
208
|
});
|
|
207
209
|
const found = conversationQueries.summariesOf(context, accountPk, nearest.map(({ conversationPk }) => conversationPk));
|
|
208
210
|
const ids = vectors.messageIds(context, nearest.flatMap(({ firstMessagePk, lastMessagePk }) => [firstMessagePk, lastMessagePk]));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.704.0",
|
|
4
4
|
"description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Viacheslav Ptsarev",
|