@wirecat/cli-core 0.742.0 → 0.743.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 +13 -0
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/search-left-out.d.ts +1 -0
- package/dist/cli/search-left-out.js +2 -0
- package/dist/crm/cli/index.js +11 -4
- package/dist/crm/cli/search-all.js +21 -4
- package/dist/crm/cli/sync-embed.d.ts +33 -0
- package/dist/crm/cli/sync-embed.js +67 -0
- package/dist/services/crm-meaning.d.ts +21 -0
- package/dist/services/crm-meaning.js +36 -0
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/search-all.d.ts +12 -0
- package/dist/services/search-all.js +86 -22
- package/dist/store/exports.d.ts +1 -0
- package/dist/store/sqlite/crm-activities.d.ts +2 -1
- package/dist/store/sqlite/crm-activities.js +12 -5
- package/dist/store/sqlite/crm-activity-chunks.d.ts +116 -0
- package/dist/store/sqlite/crm-activity-chunks.js +297 -0
- package/dist/store/sqlite/crm.d.ts +4 -0
- package/dist/store/sqlite/crm.js +2 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,19 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
|
|
|
5
5
|
minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
|
|
6
6
|
shape of this file.
|
|
7
7
|
|
|
8
|
+
## 0.743.0 — 24.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **`search all` in a CRM CLI finds deals and leads by the meaning of their notes, calls, meetings and tasks.**
|
|
13
|
+
«кто ругался что мы опять затягиваем с запуском» finds the deal whose note says the launch slipped again, in other
|
|
14
|
+
words or another language, with the note's excerpt in the hit, merged by rank with the word hits. An agent no longer
|
|
15
|
+
has to list every note and grep it (cli-testing `performance/crm/hubspot-agents`, round 2). `sync --embed` builds
|
|
16
|
+
the vectors with a model already downloaded, as the tracker's sync does; until then `search all` says it searched
|
|
17
|
+
by words only and names `sync --embed`. A limited profile finds only its own deals, and a profile that denies
|
|
18
|
+
`activities.list` searches by words only. Activities on contacts or companies alone are not found by meaning yet
|
|
19
|
+
([CRM](docs/dev/CRM.md#activities-changes-and-the-digest), #3285).
|
|
20
|
+
|
|
8
21
|
## 0.742.0 — 24.11.2026
|
|
9
22
|
|
|
10
23
|
### Fixed
|
|
@@ -58,9 +58,9 @@ export interface CopyAge {
|
|
|
58
58
|
}
|
|
59
59
|
export declare const ageOf: (lastSync: string | undefined, now?: number) => CopyAge;
|
|
60
60
|
export declare const staleCopy: (provider: string, lastSync: string | undefined, now?: number) => {
|
|
61
|
-
next?: undefined;
|
|
62
61
|
readonly missing?: undefined;
|
|
63
62
|
meta?: undefined;
|
|
63
|
+
next?: undefined;
|
|
64
64
|
} | {
|
|
65
65
|
missing: {
|
|
66
66
|
field: string;
|
|
@@ -12,6 +12,7 @@ declare const LIST_KEYS: {
|
|
|
12
12
|
readonly events: "events.list";
|
|
13
13
|
readonly meetings: "meetings.list";
|
|
14
14
|
readonly crm_file: "files.list";
|
|
15
|
+
readonly crm_activity: "activities.list";
|
|
15
16
|
readonly tracker: "issues.list";
|
|
16
17
|
};
|
|
17
18
|
export type SearchedKind = keyof typeof LIST_KEYS;
|
package/dist/crm/cli/index.js
CHANGED
|
@@ -32,6 +32,7 @@ import { addCrmFileCommands } from "./files.js";
|
|
|
32
32
|
import { pipelineView } from "./pipeline-view.js";
|
|
33
33
|
import { addCrmRecordCommands, integer } from "./records.js";
|
|
34
34
|
import { addCrmSearchAll } from "./search-all.js";
|
|
35
|
+
import { crmSyncEmbeddings, syncEmbeddings } from "./sync-embed.js";
|
|
35
36
|
export * from "./account.js";
|
|
36
37
|
export { csvColumnPaths, csvFormatOption, DEAL_CSV_COLUMNS, printCsv, refuseCsvConflict, } from "./csv.js";
|
|
37
38
|
export { CRM_ORGANIZATIONS_QUERY, CRM_PEOPLE_QUERY, CRM_USERS_QUERY, crmOrganizationOf, crmOrganizationSchema, crmPersonOf, crmPersonSchema, crmUserOf, crmUserSchema, } from "./records.js";
|
|
@@ -133,6 +134,7 @@ const crmSync = v.strictObject({
|
|
|
133
134
|
progress: v.strictObject({ requests: count, saved: count, steps: count }),
|
|
134
135
|
hint: v.optional(text),
|
|
135
136
|
group_hint: v.optional(text),
|
|
137
|
+
embeddings: v.optional(crmSyncEmbeddings),
|
|
136
138
|
});
|
|
137
139
|
const crmSyncProgress = v.strictObject({
|
|
138
140
|
kind: v.picklist(CRM_KINDS),
|
|
@@ -222,9 +224,11 @@ const addCrmCommandsDefinition = (program, options) => {
|
|
|
222
224
|
// WireCat Desktop takes a summary of 300 characters at most; the settings' part is help only.
|
|
223
225
|
.addHelpText("after", `\nWith the activities setting on, it also copies the activities and tasks on the ${dealsAndLeads} it keeps. ` +
|
|
224
226
|
`Then each ${hasLeads ? "deal or lead" : "deal"} that moved into a stage the stage-tasks setting names ` +
|
|
225
|
-
"opens a local task, once per move.
|
|
227
|
+
"opens a local task, once per move. With --embed it then indexes the activities' text with a model " +
|
|
228
|
+
"already downloaded, so search all finds their deals and leads by meaning, not only by words."), "sync", "sync --rescan", "sync --embed")
|
|
226
229
|
.option("--rescan", "list everything again, every id too, dropping a round in progress")
|
|
227
230
|
.option("--max-pages <pages>", "at most this many requests to the CRM in this run", integer(100_000))
|
|
231
|
+
.option("--embed", "also index new activities and tasks for search all by meaning, with a model already downloaded")
|
|
228
232
|
.action(async (opts, command) => {
|
|
229
233
|
const { signal } = environmentOf(command);
|
|
230
234
|
await within(command, async (run) => {
|
|
@@ -244,6 +248,7 @@ const addCrmCommandsDefinition = (program, options) => {
|
|
|
244
248
|
const retried = failed.filter((one) => one.setting === undefined);
|
|
245
249
|
const settings = [...new Set(failed.flatMap((one) => one.setting ?? []))];
|
|
246
250
|
const timeout = command.optsWithGlobals().timeout;
|
|
251
|
+
const again = { max_pages: opts.maxPages, timeout, embed: opts.embed };
|
|
247
252
|
// The same command again, never --rescan: that would drop the round this run leaves in progress.
|
|
248
253
|
const stuck = report.state === "partial" && report.progress.steps === 0 && failed.length === 0;
|
|
249
254
|
const next = retried.length || (report.state === "partial" && !stuck && failed.length === 0)
|
|
@@ -252,7 +257,7 @@ const addCrmCommandsDefinition = (program, options) => {
|
|
|
252
257
|
kind: "command",
|
|
253
258
|
step: "crm.sync",
|
|
254
259
|
command: "sync",
|
|
255
|
-
args: Object.fromEntries(Object.entries(
|
|
260
|
+
args: Object.fromEntries(Object.entries(again).filter(([, value]) => value !== undefined)),
|
|
256
261
|
why: retried.length
|
|
257
262
|
? "a kind failed to sync; running sync again retries it"
|
|
258
263
|
: "the sync stopped before its end to answer in time; running it again goes on from there",
|
|
@@ -270,6 +275,7 @@ const addCrmCommandsDefinition = (program, options) => {
|
|
|
270
275
|
? `run sync again to continue; see progress: ${progressAt}`
|
|
271
276
|
: undefined;
|
|
272
277
|
const { hint: _hint, ...rest } = report;
|
|
278
|
+
const embedded = opts.embed ? await syncEmbeddings(command, run.store, report, options.app, again) : undefined;
|
|
273
279
|
// What the healthy kinds brought is saved and answered; each failure and each item not kept is an issue.
|
|
274
280
|
const issues = [
|
|
275
281
|
...failed.map((one) => ({
|
|
@@ -282,11 +288,12 @@ const addCrmCommandsDefinition = (program, options) => {
|
|
|
282
288
|
reason: one.reason,
|
|
283
289
|
source: one.externalId === undefined ? `crm:${one.kind}` : `crm:${one.kind}/${one.externalId}`,
|
|
284
290
|
})),
|
|
291
|
+
...(embedded?.issues ?? []),
|
|
285
292
|
];
|
|
286
293
|
const partial = report.state === "partial" || issues.length > 0;
|
|
287
|
-
return itemOf(snakeKeys({ ...rest, stageTasks, ...(hint === undefined ? {} : { hint }) }), {
|
|
294
|
+
return itemOf(snakeKeys({ ...rest, stageTasks, ...(hint === undefined ? {} : { hint }), ...embedded?.item }), {
|
|
288
295
|
...(partial ? { meta: { complete: false, ...(issues.length ? { issues } : {}) } } : {}),
|
|
289
|
-
...(next ? { next } : {}),
|
|
296
|
+
...(next || embedded?.next ? { next: next ?? embedded?.next } : {}),
|
|
290
297
|
});
|
|
291
298
|
});
|
|
292
299
|
});
|
|
@@ -7,7 +7,7 @@ import { historySkipsOf } from "../../cli/messenger/history-gaps.js";
|
|
|
7
7
|
import { allAnswer, offsetOf, SOURCE_SEARCHED } from "../../cli/messenger/search-answers.js";
|
|
8
8
|
import { searchAllOptions } from "../../cli/messenger/search-command.js";
|
|
9
9
|
import { deniedKinds } from "../../cli/search-left-out.js";
|
|
10
|
-
import { commandAt, rootOf } from "../../cli/steps.js";
|
|
10
|
+
import { commandAt, lineOf, rootOf } from "../../cli/steps.js";
|
|
11
11
|
import { DEAL_KINDS } from "../../domain/deals.js";
|
|
12
12
|
import { SAVE_HELP } from "../../meetings/index.js";
|
|
13
13
|
import { meaningLane } from "../../services/messages-meaning.js";
|
|
@@ -28,7 +28,10 @@ export const addCrmSearchAll = (searches, { within, app, example, viewerOf, lead
|
|
|
28
28
|
"messages, notes, calendar events and meetings other WireCat tools stored — best match first. Use it when " +
|
|
29
29
|
"you do not know where something was written")
|
|
30
30
|
.argument("<query...>", `words and "phrases"; ${deals} match the words of their title, company, contacts and activities`)
|
|
31
|
-
.addHelpText("after",
|
|
31
|
+
.addHelpText("after", `\nIt finds ${deals} by the meaning of their activities too, in other words or another language, once ` +
|
|
32
|
+
"`sync --embed` has built their vectors with a downloaded model; until then it says it searched by words " +
|
|
33
|
+
"only.\n" +
|
|
34
|
+
SAVE_HELP);
|
|
32
35
|
searches.addCommand(searchAllOptions(all, SEARCHED));
|
|
33
36
|
example(all, "search all Example LLC", "search all website --only crm --json");
|
|
34
37
|
all.action(async (words, _opts, leaf) => {
|
|
@@ -38,7 +41,7 @@ export const addCrmSearchAll = (searches, { within, app, example, viewerOf, lead
|
|
|
38
41
|
throw new CliError("permission_error", "this process is locked to one profile; search all reads its own CRM account only, without --source", { reason: "profile.locked" });
|
|
39
42
|
const asked = opts.only ?? SEARCHED;
|
|
40
43
|
const denied = deniedKinds(leaf, app, [
|
|
41
|
-
...(asked.includes("crm") ? [...DEAL_KINDS, "crm_file"] : []),
|
|
44
|
+
...(asked.includes("crm") ? [...DEAL_KINDS, "crm_file", "crm_activity"] : []),
|
|
42
45
|
...asked.filter((one) => one !== "crm" && one !== "mail"),
|
|
43
46
|
]);
|
|
44
47
|
const out = new Set(denied.map(({ kind }) => kind));
|
|
@@ -71,6 +74,7 @@ export const addCrmSearchAll = (searches, { within, app, example, viewerOf, lead
|
|
|
71
74
|
...(crmKinds.length < DEAL_KINDS.length ? { crmKinds } : {}),
|
|
72
75
|
crmViewers: viewers,
|
|
73
76
|
...(out.has("crm_file") ? { crmFiles: false } : {}),
|
|
77
|
+
...(out.has("crm_activity") ? { crmActivities: false } : {}),
|
|
74
78
|
...(opts.source === undefined ? {} : { source: opts.source }),
|
|
75
79
|
...(alone ? { scope: { crm: [run.account] } } : {}),
|
|
76
80
|
}, { app, hintCommand: commandAt(rootOf(leaf), "models download") ? app.command : null }, undefined, meaningLane({ env, messenger: { app }, store: async () => run.store }));
|
|
@@ -81,6 +85,18 @@ export const addCrmSearchAll = (searches, { within, app, example, viewerOf, lead
|
|
|
81
85
|
note(`${resource ?? source} not searched: ${reason}`);
|
|
82
86
|
if (!found.items.length)
|
|
83
87
|
note("nothing found in what the local store holds");
|
|
88
|
+
// Agents grepped every note when this went unsaid (cli-testing performance/crm/hubspot-agents, round 2).
|
|
89
|
+
// With the activities setting off, sync --embed has nothing to embed: an agent told only that would loop.
|
|
90
|
+
const off = found.crm?.needsVectors && !(await run.store.crm.activitiesOn(run.account));
|
|
91
|
+
const build = off
|
|
92
|
+
? `\`${lineOf(leaf, "config set activities on")}\`, then \`${lineOf(leaf, "sync --embed")}\`, copy the activities and build`
|
|
93
|
+
: `\`${lineOf(leaf, "sync --embed")}\` builds`;
|
|
94
|
+
const vectors = found.crm?.needsVectors
|
|
95
|
+
? `deals and leads were found by words only: ${found.crm.meaningSkipped}; ` +
|
|
96
|
+
`${build} the vectors that find them by the meaning of their activities`
|
|
97
|
+
: undefined;
|
|
98
|
+
if (vectors)
|
|
99
|
+
note(vectors);
|
|
84
100
|
const skips = await historySkipsOf(run.store, found.accounts).catch(() => []);
|
|
85
101
|
const again = {
|
|
86
102
|
query: words.join(" "),
|
|
@@ -88,7 +104,8 @@ export const addCrmSearchAll = (searches, { within, app, example, viewerOf, lead
|
|
|
88
104
|
...(opts.source === undefined ? {} : { source: opts.source }),
|
|
89
105
|
...(opts.exact ? { exact: true } : {}),
|
|
90
106
|
};
|
|
91
|
-
|
|
107
|
+
const body = allAnswer("search all", found, { limit, page: opts.page ?? 1, again }, opts.exact === true, skips, denied);
|
|
108
|
+
return (vectors ? { ...body, missing: [...(body.missing ?? []), { field: "found_by", why: vectors }] } : body);
|
|
92
109
|
});
|
|
93
110
|
});
|
|
94
111
|
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type ErrorCode } from "@wirecat/cli-base";
|
|
2
|
+
import type { NextStep } from "@wirecat/cli-base/standards";
|
|
3
|
+
import type { Command } from "commander";
|
|
4
|
+
import * as v from "valibot";
|
|
5
|
+
import type { AppIdentity } from "../../ports/app.js";
|
|
6
|
+
import { embedCrmActivities } from "../../services/crm-meaning.js";
|
|
7
|
+
import type { MessageStore } from "../../store/store.js";
|
|
8
|
+
import type { CrmSyncReport } from "../sync.js";
|
|
9
|
+
/** What `sync --embed` embedded of the activities and tasks: `embedCrmActivities`'s answer. */
|
|
10
|
+
export declare const crmSyncEmbeddings: v.StrictObjectSchema<{
|
|
11
|
+
readonly model: v.StringSchema<undefined>;
|
|
12
|
+
readonly embedded: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
|
|
13
|
+
readonly left: v.BooleanSchema<undefined>;
|
|
14
|
+
readonly stopped: v.OptionalSchema<v.PicklistSchema<["deadline", "cancelled"], undefined>, undefined>;
|
|
15
|
+
readonly remaining: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>, undefined>;
|
|
16
|
+
}, undefined>;
|
|
17
|
+
/**
|
|
18
|
+
* `sync --embed` after the sync saved its report: the activities' vectors, or the issue a missing model makes. A run
|
|
19
|
+
* its budget stopped has no time left for the model; the run that finishes the round embeds.
|
|
20
|
+
*/
|
|
21
|
+
export declare const syncEmbeddings: (command: Command, store: MessageStore, report: Pick<CrmSyncReport, "stopped">, app: AppIdentity,
|
|
22
|
+
/** The sync's own arguments, so the step that embeds the rest runs the same sync. */
|
|
23
|
+
again: Record<string, unknown>) => Promise<{
|
|
24
|
+
item: {
|
|
25
|
+
embeddings?: Awaited<ReturnType<typeof embedCrmActivities>>;
|
|
26
|
+
};
|
|
27
|
+
issues: {
|
|
28
|
+
code: ErrorCode;
|
|
29
|
+
reason: string;
|
|
30
|
+
source: string;
|
|
31
|
+
}[];
|
|
32
|
+
next?: NextStep[];
|
|
33
|
+
}>;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { isCliError } from "@wirecat/cli-base";
|
|
2
|
+
import * as v from "valibot";
|
|
3
|
+
import { environmentOf } from "../../cli/context.js";
|
|
4
|
+
import { commandAt, rootOf } from "../../cli/steps.js";
|
|
5
|
+
import { count, text } from "../../entities/fields.js";
|
|
6
|
+
import { embedCrmActivities } from "../../services/crm-meaning.js";
|
|
7
|
+
/** At most this many activity chunks per `sync --embed`, as the tracker's sync embeds. */
|
|
8
|
+
const EMBED_MAX = 600;
|
|
9
|
+
/** What `sync --embed` embedded of the activities and tasks: `embedCrmActivities`'s answer. */
|
|
10
|
+
export const crmSyncEmbeddings = v.strictObject({
|
|
11
|
+
model: text,
|
|
12
|
+
embedded: count,
|
|
13
|
+
left: v.boolean(),
|
|
14
|
+
stopped: v.optional(v.picklist(["deadline", "cancelled"])),
|
|
15
|
+
remaining: v.optional(count),
|
|
16
|
+
});
|
|
17
|
+
/**
|
|
18
|
+
* `sync --embed` after the sync saved its report: the activities' vectors, or the issue a missing model makes. A run
|
|
19
|
+
* its budget stopped has no time left for the model; the run that finishes the round embeds.
|
|
20
|
+
*/
|
|
21
|
+
export const syncEmbeddings = async (command, store, report, app,
|
|
22
|
+
/** The sync's own arguments, so the step that embeds the rest runs the same sync. */
|
|
23
|
+
again) => {
|
|
24
|
+
if (report.stopped)
|
|
25
|
+
return { item: {}, issues: [] };
|
|
26
|
+
const { env, deadline, signal } = environmentOf(command);
|
|
27
|
+
const ends = deadline?.();
|
|
28
|
+
try {
|
|
29
|
+
const embeddings = await embedCrmActivities(store, {
|
|
30
|
+
maxChunks: EMBED_MAX,
|
|
31
|
+
...(ends ? { deadline: ends } : {}),
|
|
32
|
+
...(signal ? { signal } : {}),
|
|
33
|
+
...(env ? { env } : {}),
|
|
34
|
+
...(commandAt(rootOf(command), "models download") ? { command: app.command } : {}),
|
|
35
|
+
});
|
|
36
|
+
// One run embeds at most EMBED_MAX: until the rest are in, a note's deal may still be missing from search all.
|
|
37
|
+
if (!embeddings.left)
|
|
38
|
+
return { item: { embeddings }, issues: [] };
|
|
39
|
+
return {
|
|
40
|
+
item: { embeddings },
|
|
41
|
+
issues: [],
|
|
42
|
+
next: [
|
|
43
|
+
{
|
|
44
|
+
kind: "command",
|
|
45
|
+
step: "crm.sync",
|
|
46
|
+
command: "sync",
|
|
47
|
+
args: Object.fromEntries(Object.entries({ ...again, embed: true }).filter(([, value]) => value !== undefined)),
|
|
48
|
+
why: `${embeddings.remaining === undefined ? "some" : embeddings.remaining} activity chunks have no vectors ` +
|
|
49
|
+
"yet, so search all may miss their deals by meaning; running sync --embed again embeds the next ones",
|
|
50
|
+
safe_to_auto_execute: true,
|
|
51
|
+
},
|
|
52
|
+
],
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
// What the sync saved is answered; a cancel still ends the command.
|
|
57
|
+
if (signal?.aborted || !isCliError(error))
|
|
58
|
+
throw error;
|
|
59
|
+
const reason = error.details.reason;
|
|
60
|
+
return {
|
|
61
|
+
item: {},
|
|
62
|
+
issues: [
|
|
63
|
+
{ code: error.code, reason: typeof reason === "string" ? reason : "sync.failed", source: "crm:embeddings" },
|
|
64
|
+
],
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { DealKind } from "../domain/deals.js";
|
|
2
|
+
import type { AccountKey, CopyViewer, CrmActivityNearest, MessageStore } from "../store/store.js";
|
|
3
|
+
import { type NearestOptions, type NotesEmbedOptions } from "./notes-search.js";
|
|
4
|
+
/**
|
|
5
|
+
* Embeds CRM activities' and tasks' chunks as notes' are embedded. Activities gone since lose theirs first, and those
|
|
6
|
+
* saved before activities were searched by meaning get theirs.
|
|
7
|
+
*/
|
|
8
|
+
export declare const embedCrmActivities: (store: MessageStore, options?: NotesEmbedOptions & {
|
|
9
|
+
command?: string;
|
|
10
|
+
}) => Promise<import("./notes-search.js").NotesEmbedded>;
|
|
11
|
+
/**
|
|
12
|
+
* The deals and leads of these accounts whose activities are nearest in meaning to plain words, nearer than the
|
|
13
|
+
* model's floor, best first; only activities already embedded are found.
|
|
14
|
+
*/
|
|
15
|
+
export declare const nearestCrmActivities: (store: MessageStore, words: string, { limit, accounts, kinds, viewers, env, command, embedders, }: Pick<NearestOptions, "env" | "command" | "embedders"> & {
|
|
16
|
+
limit: number;
|
|
17
|
+
/** Every account holding activities when left out. */
|
|
18
|
+
accounts?: readonly AccountKey[] | undefined;
|
|
19
|
+
kinds?: readonly DealKind[];
|
|
20
|
+
viewers?: readonly CopyViewer[];
|
|
21
|
+
}) => Promise<CrmActivityNearest[]>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { meaningFloor } from "../embeddings/models.js";
|
|
3
|
+
import { meaningModel } from "./meaning-model.js";
|
|
4
|
+
import { embedChunks, localModel, stopsAt, withLocal, } from "./notes-search.js";
|
|
5
|
+
/**
|
|
6
|
+
* Embeds CRM activities' and tasks' chunks as notes' are embedded. Activities gone since lose theirs first, and those
|
|
7
|
+
* saved before activities were searched by meaning get theirs.
|
|
8
|
+
*/
|
|
9
|
+
export const embedCrmActivities = async (store, options = {}) => {
|
|
10
|
+
// A missing model fails before anything is written; the refresh stops where the embedding would.
|
|
11
|
+
localModel(options.model, options.env, options.command);
|
|
12
|
+
const until = stopsAt(options.deadline);
|
|
13
|
+
const refreshed = await store.crm.activityChunks.refresh({
|
|
14
|
+
until: () => options.signal?.aborted === true || Date.now() >= until,
|
|
15
|
+
});
|
|
16
|
+
const embedded = await embedChunks(store, store.crm.activityChunks, options);
|
|
17
|
+
// Activities the refresh had no time to cut are left too, though no chunk of theirs waits yet.
|
|
18
|
+
return refreshed.left ? { ...embedded, left: true } : embedded;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The deals and leads of these accounts whose activities are nearest in meaning to plain words, nearer than the
|
|
22
|
+
* model's floor, best first; only activities already embedded are found.
|
|
23
|
+
*/
|
|
24
|
+
export const nearestCrmActivities = async (store, words, { limit, accounts, kinds, viewers, env, command, embedders, }) => {
|
|
25
|
+
const { model, directory, key } = localModel(await meaningModel(store, env), env, command);
|
|
26
|
+
if (!(await store.crm.activityChunks.embedded(key, accounts)))
|
|
27
|
+
throw new CliError("not_found", `no CRM activity has vectors of ${model.id} yet, so only words were matched`);
|
|
28
|
+
const [vector] = await withLocal(model, directory, undefined, (embedder) => embedder.embed([words], "query"), embedders);
|
|
29
|
+
const floor = meaningFloor(key);
|
|
30
|
+
return (await store.crm.activityChunks.nearest(key, vector, {
|
|
31
|
+
limit,
|
|
32
|
+
...(accounts === undefined ? {} : { accounts }),
|
|
33
|
+
...(kinds === undefined ? {} : { kinds }),
|
|
34
|
+
...(viewers === undefined ? {} : { viewers }),
|
|
35
|
+
})).filter(({ score }) => score > floor);
|
|
36
|
+
};
|
|
@@ -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;
|
|
@@ -108,6 +108,13 @@ export interface SearchAllFound {
|
|
|
108
108
|
by: "words" | "words and meaning";
|
|
109
109
|
meaningSkipped?: string;
|
|
110
110
|
};
|
|
111
|
+
/** How deals and leads were searched, when they were: by meaning too through their activities' vectors. */
|
|
112
|
+
crm?: {
|
|
113
|
+
by: "words" | "words and meaning";
|
|
114
|
+
meaningSkipped?: string;
|
|
115
|
+
/** No model, or no activity embedded yet: the CRM's `sync --embed` builds the vectors. */
|
|
116
|
+
needsVectors?: true;
|
|
117
|
+
};
|
|
111
118
|
/** How the messages were searched, when they were; never by meaning with `exact` or the server alone. */
|
|
112
119
|
messages?: {
|
|
113
120
|
by: "words" | "words and meaning";
|
|
@@ -164,6 +171,11 @@ export interface SearchAllRequest {
|
|
|
164
171
|
crmViewers?: CopyViewer[];
|
|
165
172
|
/** `crm` also reads the text of downloaded CRM files under the same viewers; false when the profile denies it. */
|
|
166
173
|
crmFiles?: boolean;
|
|
174
|
+
/**
|
|
175
|
+
* `crm` also finds deals and leads by the meaning of their activities' text, shown in the hit; false when the
|
|
176
|
+
* profile denies reading activities.
|
|
177
|
+
*/
|
|
178
|
+
crmActivities?: boolean;
|
|
167
179
|
/**
|
|
168
180
|
* Search harder: a hosted model reorders the first 30 hits, only with the owner's consent and a key. Absent, nothing
|
|
169
181
|
* is read of the consent or the key and nothing is sent.
|
|
@@ -16,6 +16,7 @@ import { plainQuery } from "../search/lucene/plain.js";
|
|
|
16
16
|
import { MESSAGE_PARSING, SEARCH_QUERY } from "../search/lucene/types.js";
|
|
17
17
|
import { questionPeriod } from "../search/question-period.js";
|
|
18
18
|
import { planQuestion, questionLookup, questionText } from "../search/question-plan.js";
|
|
19
|
+
import { nearestCrmActivities } from "./crm-meaning.js";
|
|
19
20
|
import { calendarAccounts, searchEvents } from "./events-search.js";
|
|
20
21
|
import { excerpt } from "./excerpt.js";
|
|
21
22
|
import { MAX_SEARCH_OFFSET, searchStore } from "./messages-archive-search.js";
|
|
@@ -152,7 +153,7 @@ const trackerTitle = ({ kind, record }) => {
|
|
|
152
153
|
* What the meaning half embeds: the words and phrases asked for, OR included, as notes take them. `title:` narrows to
|
|
153
154
|
* the title, which a hit by meaning cannot be held to, so such a query is searched by words only.
|
|
154
155
|
*/
|
|
155
|
-
const
|
|
156
|
+
const meaningWordsOf = (text) => {
|
|
156
157
|
try {
|
|
157
158
|
const { root } = parseLucene(text, SEARCH_QUERY);
|
|
158
159
|
const nodes = root.kind === "boolean" ? root.clauses.map(({ node }) => node) : [root];
|
|
@@ -186,6 +187,28 @@ const oneHitPerItem = (ordered, cosines, items) => {
|
|
|
186
187
|
}
|
|
187
188
|
return [...kept.values()];
|
|
188
189
|
};
|
|
190
|
+
/**
|
|
191
|
+
* One list for a lane found both ways, as notes and messages fuse theirs: each hit's rank in either list votes, a
|
|
192
|
+
* question's hit voting once; a hit found both ways keeps its words' text and is found by meaning too.
|
|
193
|
+
*/
|
|
194
|
+
const fusedLane = (byWords, byMeaning, discover, cosines) => {
|
|
195
|
+
const fused = new Map();
|
|
196
|
+
byWords.forEach((item, rank) => {
|
|
197
|
+
fused.set(item.ref, { item, score: 1 / (RRF_K + rank + 1) });
|
|
198
|
+
});
|
|
199
|
+
byMeaning.forEach(({ hit, score }, rank) => {
|
|
200
|
+
cosines.set(hit.ref, score);
|
|
201
|
+
const held = fused.get(hit.ref);
|
|
202
|
+
if (held && !held.item.foundBy.includes("meaning"))
|
|
203
|
+
held.item.foundBy = [...held.item.foundBy, "meaning"];
|
|
204
|
+
const vote = 1 / (RRF_K + rank + 1);
|
|
205
|
+
if (held && discover)
|
|
206
|
+
held.score = Math.max(held.score, vote);
|
|
207
|
+
else
|
|
208
|
+
fused.set(hit.ref, { item: held?.item ?? hit, score: (held?.score ?? 0) + vote });
|
|
209
|
+
});
|
|
210
|
+
return [...fused.values()].sort((a, b) => b.score - a.score).map(({ item }) => item);
|
|
211
|
+
};
|
|
189
212
|
/** The accounts of every CRM the store holds copies of. */
|
|
190
213
|
export const crmAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "crm"));
|
|
191
214
|
/**
|
|
@@ -219,6 +242,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
219
242
|
let notes;
|
|
220
243
|
let events;
|
|
221
244
|
let tracker;
|
|
245
|
+
let crm;
|
|
222
246
|
const by = {};
|
|
223
247
|
let server;
|
|
224
248
|
// Every word of a sentence is rarely in one record: a question finds what holds some of them, as `--discover` does.
|
|
@@ -420,7 +444,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
420
444
|
});
|
|
421
445
|
hasMore ||= found.hasMore;
|
|
422
446
|
const titled = /(?:^|[\s(+])title:/u.test(request.text);
|
|
423
|
-
|
|
447
|
+
const byWords = found.items
|
|
424
448
|
.filter((deal) => !titled || deal.matched.includes("title"))
|
|
425
449
|
.map((deal) => ({
|
|
426
450
|
kind: deal.kind,
|
|
@@ -432,7 +456,59 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
432
456
|
text: deal.summary,
|
|
433
457
|
foundBy: deal.matched.includes("title") ? ["title"] : ["words"],
|
|
434
458
|
...(deal.corrections ? { match: "corrected", corrections: deal.corrections } : {}),
|
|
435
|
-
}))
|
|
459
|
+
}));
|
|
460
|
+
const plain = titled ? undefined : meaningWordsOf(discover ? questionText(request.text) : request.text);
|
|
461
|
+
let near;
|
|
462
|
+
let meaningSkipped;
|
|
463
|
+
if (request.crmActivities === false)
|
|
464
|
+
meaningSkipped = "the profile may not read activities";
|
|
465
|
+
else if (request.exact)
|
|
466
|
+
meaningSkipped = "--exact searches words as written";
|
|
467
|
+
else if (plain === undefined)
|
|
468
|
+
meaningSkipped = "the query names a title, which meaning cannot follow";
|
|
469
|
+
else
|
|
470
|
+
try {
|
|
471
|
+
near = await nearestCrmActivities(store, plain, {
|
|
472
|
+
limit: Math.min(depth, 500),
|
|
473
|
+
accounts: chosen,
|
|
474
|
+
viewers,
|
|
475
|
+
embedders,
|
|
476
|
+
...(request.crmKinds === undefined ? {} : { kinds: request.crmKinds }),
|
|
477
|
+
...(command === undefined ? {} : { command }),
|
|
478
|
+
...(request.env === undefined ? {} : { env: request.env }),
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
catch (error) {
|
|
482
|
+
if (!(error instanceof CliError && error.code === "not_found"))
|
|
483
|
+
throw error;
|
|
484
|
+
meaningSkipped = error.message;
|
|
485
|
+
}
|
|
486
|
+
crm = {
|
|
487
|
+
by: near === undefined ? "words" : "words and meaning",
|
|
488
|
+
...(meaningSkipped === undefined ? {} : { meaningSkipped }),
|
|
489
|
+
...(near === undefined && plain !== undefined && !request.exact && request.crmActivities !== false
|
|
490
|
+
? { needsVectors: true }
|
|
491
|
+
: {}),
|
|
492
|
+
};
|
|
493
|
+
if (near === undefined)
|
|
494
|
+
lists.push(byWords);
|
|
495
|
+
else {
|
|
496
|
+
const byMeaning = await Promise.all(near.map(async ({ ref, kind, account: at, subject, body, score }) => {
|
|
497
|
+
const deal = await store.deals.get(ref);
|
|
498
|
+
const hit = {
|
|
499
|
+
kind,
|
|
500
|
+
ref,
|
|
501
|
+
provider: at.provider,
|
|
502
|
+
account: at.account,
|
|
503
|
+
title: deal.title,
|
|
504
|
+
timestamp: deal.updatedAt,
|
|
505
|
+
text: excerpt([subject, body].filter(Boolean).join("\n"), request.text),
|
|
506
|
+
foundBy: ["meaning"],
|
|
507
|
+
};
|
|
508
|
+
return { hit, score };
|
|
509
|
+
}));
|
|
510
|
+
lists.push(fusedLane(byWords, byMeaning, discover, cosines));
|
|
511
|
+
}
|
|
436
512
|
if (request.crmFiles !== false) {
|
|
437
513
|
const files = await store.crmFiles.find({
|
|
438
514
|
words,
|
|
@@ -496,7 +572,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
496
572
|
};
|
|
497
573
|
};
|
|
498
574
|
const byWords = found.items.map(({ account: at, item, excerpt: text }) => hitOf(at, item, text, ["words"]));
|
|
499
|
-
const plain =
|
|
575
|
+
const plain = meaningWordsOf(discover ? questionText(request.text) : request.text);
|
|
500
576
|
let near;
|
|
501
577
|
let meaningSkipped;
|
|
502
578
|
if (request.exact)
|
|
@@ -525,24 +601,11 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
525
601
|
if (near === undefined)
|
|
526
602
|
lists.push(oneHitPerItem(byWords, cosines, items));
|
|
527
603
|
else {
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
near.forEach(({ account: at, item, score }, rank) => {
|
|
534
|
-
const hit = hitOf(at, item, trackerExcerpt(item, request.text), ["meaning"]);
|
|
535
|
-
cosines.set(hit.ref, score);
|
|
536
|
-
const held = fused.get(hit.ref);
|
|
537
|
-
if (held)
|
|
538
|
-
held.item.foundBy = ["words", "meaning"];
|
|
539
|
-
const vote = 1 / (RRF_K + rank + 1);
|
|
540
|
-
if (held && discover)
|
|
541
|
-
held.score = Math.max(held.score, vote);
|
|
542
|
-
else
|
|
543
|
-
fused.set(hit.ref, { item: held?.item ?? hit, score: (held?.score ?? 0) + vote });
|
|
544
|
-
});
|
|
545
|
-
lists.push(oneHitPerItem([...fused.values()].sort((a, b) => b.score - a.score).map(({ item }) => item), cosines, items));
|
|
604
|
+
const byMeaning = near.map(({ account: at, item, score }) => ({
|
|
605
|
+
hit: hitOf(at, item, trackerExcerpt(item, request.text), ["meaning"]),
|
|
606
|
+
score,
|
|
607
|
+
}));
|
|
608
|
+
lists.push(oneHitPerItem(fusedLane(byWords, byMeaning, discover, cosines), cosines, items));
|
|
546
609
|
}
|
|
547
610
|
for (const { provider, account } of read)
|
|
548
611
|
accounts.push({ resource, provider, account });
|
|
@@ -633,6 +696,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
633
696
|
...(notes === undefined ? {} : { notes }),
|
|
634
697
|
...(events === undefined ? {} : { events }),
|
|
635
698
|
...(tracker === undefined ? {} : { tracker }),
|
|
699
|
+
...(crm === undefined ? {} : { crm }),
|
|
636
700
|
...(by.messages === undefined ? {} : { messages: by.messages }),
|
|
637
701
|
...(by.mail === undefined ? {} : { mail: by.mail }),
|
|
638
702
|
...(server === undefined ? {} : { server }),
|
package/dist/store/exports.d.ts
CHANGED
|
@@ -29,6 +29,7 @@ export { type ContentFilter, type ContentHit, type ContentItem, type ContentPers
|
|
|
29
29
|
export { CONVERSATION_COLUMNS } from "./sqlite/conversations.js";
|
|
30
30
|
export { type CopyViewer, seenBy } from "./sqlite/copy-viewer.js";
|
|
31
31
|
export type { CounterTarget } from "./sqlite/counters.js";
|
|
32
|
+
export type { CrmActivityChunks, CrmActivityNearest } from "./sqlite/crm.js";
|
|
32
33
|
export { type CrmFileHit, type CrmFileRow, type CrmFileSearch, type CrmFileStore, resetCrmFileWords, } from "./sqlite/crm-files.js";
|
|
33
34
|
export { CRM_FILE_LIMITS, type CrmFileLimit, type CrmFileLimits, crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting, } from "./sqlite/crm-settings.js";
|
|
34
35
|
export { type EmailMarks, MAIL_AGENDA_COLUMNS, type MarkedEmail, type NewestEmail, type ThreadActivity, } from "./sqlite/email-activity.js";
|
|
@@ -3,8 +3,9 @@ import type { DealKind } from "../../domain/deals.js";
|
|
|
3
3
|
import type { CacheDatabase } from "../driver.js";
|
|
4
4
|
import type { AccountKey } from "../types.js";
|
|
5
5
|
import { type CopyViewer } from "./copy-viewer.js";
|
|
6
|
+
import { ACTIVITY_RECORD } from "./crm-activity-chunks.js";
|
|
6
7
|
import type { StoreContext } from "./open.js";
|
|
7
|
-
export
|
|
8
|
+
export { ACTIVITY_RECORD };
|
|
8
9
|
/**
|
|
9
10
|
* Marks deleted the activities on nothing but these contacts or companies: their subject and body leave the copy with
|
|
10
11
|
* the rows they were on. Answers how many.
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { recordFingerprint } from "../../domain/records.js";
|
|
2
2
|
import { accountPk, findAccountPk } from "./accounts.js";
|
|
3
3
|
import { viewerSql } from "./copy-viewer.js";
|
|
4
|
+
import { ACTIVITY_RECORD, dropCrmActivityChunks, rechunkCrmActivities } from "./crm-activity-chunks.js";
|
|
4
5
|
import { crmAccountPrefix, crmIdentityId, SOURCE, TABLES, textOf } from "./crm-rows.js";
|
|
5
6
|
import { write } from "./transaction.js";
|
|
6
|
-
export
|
|
7
|
+
export { ACTIVITY_RECORD };
|
|
7
8
|
/**
|
|
8
9
|
* Marks deleted the activities on nothing but these contacts or companies: their subject and body leave the copy with
|
|
9
10
|
* the rows they were on. Answers how many.
|
|
@@ -11,12 +12,15 @@ export const ACTIVITY_RECORD = "crm.activity";
|
|
|
11
12
|
export const forgetActivitiesOn = (database, accountId, kind, externalIds, at) => {
|
|
12
13
|
const removed = "rr.target_type = ? AND rr.target_external_id IN (SELECT value FROM json_each(?))";
|
|
13
14
|
const ids = JSON.stringify(externalIds);
|
|
14
|
-
|
|
15
|
+
const forgotten = database
|
|
15
16
|
.prepare("UPDATE records SET deleted_at = ? WHERE account_id = ? AND type = ? AND deleted_at IS NULL " +
|
|
16
17
|
`AND EXISTS (SELECT 1 FROM record_relations rr WHERE rr.record_id = records.id AND rr.role = 'on' AND ${removed}) ` +
|
|
17
18
|
"AND NOT EXISTS (SELECT 1 FROM record_relations rr WHERE rr.record_id = records.id AND rr.role = 'on' " +
|
|
18
|
-
`AND NOT (${removed}))`)
|
|
19
|
-
.
|
|
19
|
+
`AND NOT (${removed})) RETURNING id`)
|
|
20
|
+
.all(at, accountId, ACTIVITY_RECORD, kind, ids, kind, ids)
|
|
21
|
+
.map(({ id }) => Number(id));
|
|
22
|
+
dropCrmActivityChunks(database, forgotten);
|
|
23
|
+
return forgotten.length;
|
|
20
24
|
};
|
|
21
25
|
/** A CRM's text field holds what people typed or pasted, a whole e-mail thread too. */
|
|
22
26
|
const MOST_BODY = 20_000;
|
|
@@ -94,8 +98,10 @@ export const crmActivitiesOver = (context) => {
|
|
|
94
98
|
.get(accountId, ACTIVITY_RECORD, activity.externalId);
|
|
95
99
|
if (on.length === 0) {
|
|
96
100
|
// It left every kept deal: one stored before goes with it.
|
|
97
|
-
if (held)
|
|
101
|
+
if (held) {
|
|
98
102
|
database.prepare("UPDATE records SET deleted_at = ? WHERE id = ?").run(at, Number(held.id));
|
|
103
|
+
dropCrmActivityChunks(database, [Number(held.id)]);
|
|
104
|
+
}
|
|
99
105
|
outOfScope += 1;
|
|
100
106
|
continue;
|
|
101
107
|
}
|
|
@@ -132,6 +138,7 @@ export const crmActivitiesOver = (context) => {
|
|
|
132
138
|
.prepare("INSERT INTO record_relations (record_id, role, target_type, target_external_id, created_at) " +
|
|
133
139
|
"VALUES (?, 'on', ?, ?, ?)")
|
|
134
140
|
.run(id, one.kind, one.externalId, at);
|
|
141
|
+
rechunkCrmActivities(database, [id], at);
|
|
135
142
|
saved += 1;
|
|
136
143
|
}
|
|
137
144
|
return { saved, outOfScope };
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { type DealKind } from "../../domain/deals.js";
|
|
2
|
+
import { type CacheDatabase } from "../driver.js";
|
|
3
|
+
import type { AccountKey } from "../types.js";
|
|
4
|
+
import { type CopyViewer } from "./copy-viewer.js";
|
|
5
|
+
import type { StoreContext } from "./open.js";
|
|
6
|
+
/** The `records.type` of a CRM activity or task. */
|
|
7
|
+
export declare const ACTIVITY_RECORD = "crm.activity";
|
|
8
|
+
/** `chunks.chunkable_type` of a CRM activity's pieces; `chunkable_id` is the activity's `records.id`. */
|
|
9
|
+
export declare const CRM_ACTIVITY_CHUNK = "crm_activity";
|
|
10
|
+
/**
|
|
11
|
+
* An activity whose subject and text together, spaces aside, are shorter than this is not embedded: a task's `Call`
|
|
12
|
+
* or `Follow up` says nothing alone and would sit near every query, as short tracker comments did. Its words still
|
|
13
|
+
* find its deal.
|
|
14
|
+
*/
|
|
15
|
+
export declare const SHORTEST_EMBEDDED_ACTIVITY = 16;
|
|
16
|
+
export interface ChunkedActivity {
|
|
17
|
+
id: number;
|
|
18
|
+
accountId: number;
|
|
19
|
+
subject: string;
|
|
20
|
+
body: string | null;
|
|
21
|
+
occurredAt: number;
|
|
22
|
+
scope: string | null;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Inside the caller's write: makes the activity's chunks its text's, and answers the hashes it released, or
|
|
26
|
+
* `undefined` when they already were. The caller drops the vectors of those once every new chunk is in.
|
|
27
|
+
*/
|
|
28
|
+
export declare const crmActivityChunkWriter: (database: CacheDatabase) => (activity: ChunkedActivity, at: number) => {
|
|
29
|
+
released: string[];
|
|
30
|
+
} | undefined;
|
|
31
|
+
/** Inside the caller's write: drops the chunks of these activities and the vectors no other chunk holds. */
|
|
32
|
+
export declare const dropCrmActivityChunks: (database: CacheDatabase, ids: readonly number[]) => void;
|
|
33
|
+
/** Inside the caller's write: cuts the chunks of these stored activities again, from their rows as they now are. */
|
|
34
|
+
export declare const rechunkCrmActivities: (database: CacheDatabase, ids: readonly number[], at: number) => void;
|
|
35
|
+
/**
|
|
36
|
+
* Drops the chunks of activities deleted or gone, then cuts the chunks of live activities that have none: those
|
|
37
|
+
* saved before activities were searched by meaning. Short write transactions, `until` asked before each, so a
|
|
38
|
+
* deadline stops it with `left`; nothing under a read-only store.
|
|
39
|
+
*/
|
|
40
|
+
export declare const refreshCrmActivityChunks: (database: CacheDatabase, now: number, until?: () => boolean) => {
|
|
41
|
+
dropped: number;
|
|
42
|
+
added: number;
|
|
43
|
+
left: boolean;
|
|
44
|
+
};
|
|
45
|
+
export declare const crmActivityChunksLeft: (database: CacheDatabase, model: string) => number;
|
|
46
|
+
/**
|
|
47
|
+
* Live activities' chunks with no vector of `model`, by hash from `after`, each with its text cut again. A chunk
|
|
48
|
+
* whose text no longer hashes to its hash was cut from older text: its activity is cut again (never under a
|
|
49
|
+
* read-only store) and the chunk left out, so no vector is made of other text than its hash names.
|
|
50
|
+
*/
|
|
51
|
+
export declare const crmActivityChunksToEmbed: (database: CacheDatabase, model: string, { after, limit }: {
|
|
52
|
+
after?: string;
|
|
53
|
+
limit: number;
|
|
54
|
+
}, now?: number) => {
|
|
55
|
+
hash: string;
|
|
56
|
+
text: string;
|
|
57
|
+
}[];
|
|
58
|
+
export declare const crmActivitiesEmbedded: (database: CacheDatabase, model: string, accountIds: readonly number[]) => boolean;
|
|
59
|
+
/** One deal or lead an activity found by meaning is on, with that activity's text. */
|
|
60
|
+
export interface CrmActivityNearest {
|
|
61
|
+
account: AccountKey;
|
|
62
|
+
/** The store's `deal:<id>` or `lead:<id>`. */
|
|
63
|
+
ref: string;
|
|
64
|
+
kind: DealKind;
|
|
65
|
+
subject: string;
|
|
66
|
+
body: string | null;
|
|
67
|
+
score: number;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The deals and leads of one account whose activities are nearest to `query` by their best chunk's vector of
|
|
71
|
+
* `model`, best first, each with its nearest activity. An activity counts only through a live deal or lead of `kinds`
|
|
72
|
+
* the viewer may read (SEC-197): one on contacts or companies alone, or on a hidden deal, is never found, and a hidden
|
|
73
|
+
* deal is never named. By the model's vector index, or by a scan of the account's chunks while it has none.
|
|
74
|
+
*/
|
|
75
|
+
export declare const nearestCrmActivities: (database: CacheDatabase, model: string, query: Float32Array, { account, accountId, limit, kinds, viewers, }: {
|
|
76
|
+
account: AccountKey;
|
|
77
|
+
accountId: number;
|
|
78
|
+
limit: number;
|
|
79
|
+
kinds?: readonly DealKind[];
|
|
80
|
+
viewers?: readonly CopyViewer[];
|
|
81
|
+
}) => CrmActivityNearest[];
|
|
82
|
+
/** Activities and tasks by meaning: each saved activity's subject and text are cut into chunks, embedded later. */
|
|
83
|
+
export interface CrmActivityChunks {
|
|
84
|
+
/** Drops the chunks of activities gone, then cuts those of activities saved before they were searched by meaning. */
|
|
85
|
+
refresh(options?: {
|
|
86
|
+
until?: () => boolean;
|
|
87
|
+
}): Promise<{
|
|
88
|
+
dropped: number;
|
|
89
|
+
added: number;
|
|
90
|
+
left: boolean;
|
|
91
|
+
}>;
|
|
92
|
+
/** Live activities' chunks with no vector of `model`, by hash from `after`, with their text. */
|
|
93
|
+
chunksToEmbed(model: string, options: {
|
|
94
|
+
after?: string;
|
|
95
|
+
limit: number;
|
|
96
|
+
}): Promise<{
|
|
97
|
+
hash: string;
|
|
98
|
+
text: string;
|
|
99
|
+
}[]>;
|
|
100
|
+
/** How many chunks `chunksToEmbed` would still give, at most. */
|
|
101
|
+
chunksLeft(model: string): Promise<number>;
|
|
102
|
+
/** Whether a live activity of these accounts, or of any when none are named, has a vector of `model`. */
|
|
103
|
+
embedded(model: string, accounts?: readonly AccountKey[]): Promise<boolean>;
|
|
104
|
+
/**
|
|
105
|
+
* The deals and leads of these accounts whose activities are nearest in meaning to `query`, best first, each with its
|
|
106
|
+
* nearest activity; only through a deal or lead of `kinds` every viewer may read. Vectors are unit length.
|
|
107
|
+
*/
|
|
108
|
+
nearest(model: string, query: Float32Array, options: {
|
|
109
|
+
limit: number;
|
|
110
|
+
/** Every account holding activities when left out. */
|
|
111
|
+
accounts?: readonly AccountKey[];
|
|
112
|
+
kinds?: readonly DealKind[];
|
|
113
|
+
viewers?: readonly CopyViewer[];
|
|
114
|
+
}): Promise<CrmActivityNearest[]>;
|
|
115
|
+
}
|
|
116
|
+
export declare const crmActivityChunksOver: (context: StoreContext) => CrmActivityChunks;
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { CHUNK_CHARS, chunkHash, splitText } from "../../conversations/chunks.js";
|
|
2
|
+
import { DEAL_KINDS } from "../../domain/deals.js";
|
|
3
|
+
import { isQueryOnly } from "../driver.js";
|
|
4
|
+
import { findAccountPk } from "./accounts.js";
|
|
5
|
+
import { viewerSql } from "./copy-viewer.js";
|
|
6
|
+
import { TABLES } from "./crm-rows.js";
|
|
7
|
+
import { noteIndexText } from "./index-text.js";
|
|
8
|
+
import { write } from "./transaction.js";
|
|
9
|
+
import { dropUnusedVectors, searchIndex } from "./vector-index.js";
|
|
10
|
+
import { dot } from "./vectors.js";
|
|
11
|
+
/** The `records.type` of a CRM activity or task. */
|
|
12
|
+
export const ACTIVITY_RECORD = "crm.activity";
|
|
13
|
+
/** `chunks.chunkable_type` of a CRM activity's pieces; `chunkable_id` is the activity's `records.id`. */
|
|
14
|
+
export const CRM_ACTIVITY_CHUNK = "crm_activity";
|
|
15
|
+
/**
|
|
16
|
+
* An activity whose subject and text together, spaces aside, are shorter than this is not embedded: a task's `Call`
|
|
17
|
+
* or `Follow up` says nothing alone and would sit near every query, as short tracker comments did. Its words still
|
|
18
|
+
* find its deal.
|
|
19
|
+
*/
|
|
20
|
+
export const SHORTEST_EMBEDDED_ACTIVITY = 16;
|
|
21
|
+
// SQLite's `trim` and `length` take spaces and code points; JavaScript's `trim` takes more, and `length` counts halves.
|
|
22
|
+
const EDGE = /^[ \t\n\r]+|[ \t\n\r]+$/gu;
|
|
23
|
+
/** What an activity is embedded as, from its stored fields: chunk offsets point into it. */
|
|
24
|
+
const textOf = (subject, body) => [...`${subject}${body ?? ""}`.replace(EDGE, "")].length >= SHORTEST_EMBEDDED_ACTIVITY
|
|
25
|
+
? noteIndexText(subject, body ?? "")
|
|
26
|
+
: "";
|
|
27
|
+
const piecesOf = (text) => text
|
|
28
|
+
? splitText(text, CHUNK_CHARS).map(({ start, end }) => ({ start, end, hash: chunkHash(text.slice(start, end)) }))
|
|
29
|
+
: [];
|
|
30
|
+
/**
|
|
31
|
+
* Inside the caller's write: makes the activity's chunks its text's, and answers the hashes it released, or
|
|
32
|
+
* `undefined` when they already were. The caller drops the vectors of those once every new chunk is in.
|
|
33
|
+
*/
|
|
34
|
+
export const crmActivityChunkWriter = (database) => {
|
|
35
|
+
const held = database.prepare(`SELECT start_offset AS start, end_offset AS end, content_hash AS hash FROM chunks
|
|
36
|
+
WHERE chunkable_type = '${CRM_ACTIVITY_CHUNK}' AND chunkable_id = ? ORDER BY position`);
|
|
37
|
+
const drop = database.prepare(`DELETE FROM chunks WHERE chunkable_type = '${CRM_ACTIVITY_CHUNK}' AND chunkable_id = ?`);
|
|
38
|
+
const insert = database.prepare("INSERT INTO chunks (chunkable_type, chunkable_id, position, start_offset, end_offset, content_hash, scope, " +
|
|
39
|
+
`account_id, occurred_at, created_at, updated_at) VALUES ('${CRM_ACTIVITY_CHUNK}', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
40
|
+
return (activity, at) => {
|
|
41
|
+
const wanted = piecesOf(textOf(activity.subject, activity.body));
|
|
42
|
+
const before = held.all(activity.id).map((row) => ({
|
|
43
|
+
start: Number(row.start),
|
|
44
|
+
end: Number(row.end),
|
|
45
|
+
hash: String(row.hash),
|
|
46
|
+
}));
|
|
47
|
+
const same = before.length === wanted.length &&
|
|
48
|
+
before.every((one, index) => {
|
|
49
|
+
const other = wanted[index];
|
|
50
|
+
return other !== undefined && one.start === other.start && one.end === other.end && one.hash === other.hash;
|
|
51
|
+
});
|
|
52
|
+
if (same)
|
|
53
|
+
return undefined;
|
|
54
|
+
drop.run(activity.id);
|
|
55
|
+
wanted.forEach(({ start, end, hash }, position) => {
|
|
56
|
+
insert.run(activity.id, position, start, end, hash, activity.scope, activity.accountId, activity.occurredAt, at, at);
|
|
57
|
+
});
|
|
58
|
+
return { released: before.map(({ hash }) => hash) };
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
/** Inside the caller's write: drops the chunks of these activities and the vectors no other chunk holds. */
|
|
62
|
+
export const dropCrmActivityChunks = (database, ids) => {
|
|
63
|
+
if (!ids.length)
|
|
64
|
+
return;
|
|
65
|
+
const released = database
|
|
66
|
+
.prepare(`DELETE FROM chunks WHERE chunkable_type = '${CRM_ACTIVITY_CHUNK}'
|
|
67
|
+
AND chunkable_id IN (SELECT value FROM json_each(?)) RETURNING content_hash AS hash`)
|
|
68
|
+
.all(JSON.stringify(ids))
|
|
69
|
+
.map(({ hash }) => String(hash));
|
|
70
|
+
dropUnusedVectors(database, released);
|
|
71
|
+
};
|
|
72
|
+
const COLUMNS = "r.id, r.account_id, json_extract(r.fields, '$.subject') AS subject, json_extract(r.fields, '$.body') AS body, " +
|
|
73
|
+
"coalesce(json_extract(r.fields, '$.updated_at'), r.updated_at) AS at, a.scope";
|
|
74
|
+
const chunkedOf = (row) => ({
|
|
75
|
+
id: Number(row.id),
|
|
76
|
+
accountId: Number(row.account_id),
|
|
77
|
+
subject: row.subject == null ? "" : String(row.subject),
|
|
78
|
+
body: row.body == null ? null : String(row.body),
|
|
79
|
+
occurredAt: Number(row.at),
|
|
80
|
+
scope: row.scope == null ? null : String(row.scope),
|
|
81
|
+
});
|
|
82
|
+
/** Inside the caller's write: cuts the chunks of these stored activities again, from their rows as they now are. */
|
|
83
|
+
export const rechunkCrmActivities = (database, ids, at) => {
|
|
84
|
+
if (!ids.length)
|
|
85
|
+
return;
|
|
86
|
+
const chunk = crmActivityChunkWriter(database);
|
|
87
|
+
const released = [];
|
|
88
|
+
for (const row of database
|
|
89
|
+
.prepare(`SELECT ${COLUMNS} FROM records r JOIN accounts a ON a.id = r.account_id
|
|
90
|
+
WHERE r.id IN (SELECT value FROM json_each(?))`)
|
|
91
|
+
.all(JSON.stringify(ids)))
|
|
92
|
+
for (const hash of chunk(chunkedOf(row), at)?.released ?? [])
|
|
93
|
+
released.push(hash);
|
|
94
|
+
dropUnusedVectors(database, released);
|
|
95
|
+
};
|
|
96
|
+
const BACKFILL = 200;
|
|
97
|
+
const EMBEDDED_SQL = "length(trim(coalesce(json_extract(r.fields, '$.subject'), '') || coalesce(json_extract(r.fields, '$.body'), ''), " +
|
|
98
|
+
`' ' || char(9, 10, 13))) >= ${SHORTEST_EMBEDDED_ACTIVITY}`;
|
|
99
|
+
/**
|
|
100
|
+
* Drops the chunks of activities deleted or gone, then cuts the chunks of live activities that have none: those
|
|
101
|
+
* saved before activities were searched by meaning. Short write transactions, `until` asked before each, so a
|
|
102
|
+
* deadline stops it with `left`; nothing under a read-only store.
|
|
103
|
+
*/
|
|
104
|
+
export const refreshCrmActivityChunks = (database, now, until = () => false) => {
|
|
105
|
+
if (isQueryOnly(database))
|
|
106
|
+
return { dropped: 0, added: 0, left: false };
|
|
107
|
+
const dropped = write(database, () => {
|
|
108
|
+
const gone = database
|
|
109
|
+
.prepare(`DELETE FROM chunks WHERE chunkable_type = '${CRM_ACTIVITY_CHUNK}' AND NOT EXISTS (SELECT 1 FROM records r
|
|
110
|
+
WHERE r.id = chunkable_id AND r.type = '${ACTIVITY_RECORD}' AND r.deleted_at IS NULL)
|
|
111
|
+
RETURNING content_hash AS hash`)
|
|
112
|
+
.all()
|
|
113
|
+
.map(({ hash }) => String(hash));
|
|
114
|
+
dropUnusedVectors(database, gone);
|
|
115
|
+
return gone.length;
|
|
116
|
+
});
|
|
117
|
+
const chunk = crmActivityChunkWriter(database);
|
|
118
|
+
// An activity too short to embed never gets a chunk: reading it again at every embed would find nothing.
|
|
119
|
+
const page = database.prepare(`SELECT ${COLUMNS} FROM records r JOIN accounts a ON a.id = r.account_id
|
|
120
|
+
WHERE r.id > ? AND r.type = '${ACTIVITY_RECORD}' AND r.deleted_at IS NULL AND ${EMBEDDED_SQL}
|
|
121
|
+
AND NOT EXISTS (SELECT 1 FROM chunks k
|
|
122
|
+
WHERE k.chunkable_type = '${CRM_ACTIVITY_CHUNK}' AND k.chunkable_id = r.id)
|
|
123
|
+
ORDER BY r.id LIMIT ?`);
|
|
124
|
+
let added = 0;
|
|
125
|
+
let after = 0;
|
|
126
|
+
for (;;) {
|
|
127
|
+
if (until())
|
|
128
|
+
return { dropped, added, left: page.all(after, 1).length > 0 };
|
|
129
|
+
const rows = write(database, () => {
|
|
130
|
+
const found = page.all(after, BACKFILL);
|
|
131
|
+
for (const row of found)
|
|
132
|
+
if (chunk(chunkedOf(row), now))
|
|
133
|
+
added += 1;
|
|
134
|
+
return found;
|
|
135
|
+
});
|
|
136
|
+
const last = rows.at(-1);
|
|
137
|
+
if (!last || rows.length < BACKFILL)
|
|
138
|
+
break;
|
|
139
|
+
after = Number(last.id);
|
|
140
|
+
}
|
|
141
|
+
return { dropped, added, left: false };
|
|
142
|
+
};
|
|
143
|
+
const LIVE = `k.chunkable_type = '${CRM_ACTIVITY_CHUNK}' AND EXISTS (SELECT 1 FROM records r WHERE r.id = k.chunkable_id ` +
|
|
144
|
+
`AND r.type = '${ACTIVITY_RECORD}' AND r.deleted_at IS NULL)`;
|
|
145
|
+
const UNEMBEDDED = `${LIVE} AND NOT EXISTS (SELECT 1 FROM embeddings v WHERE v.model = ? AND v.content_hash = k.content_hash)`;
|
|
146
|
+
export const crmActivityChunksLeft = (database, model) => Number(database.prepare(`SELECT count(DISTINCT k.content_hash) AS n FROM chunks k WHERE ${UNEMBEDDED}`).get(model)?.n ?? 0);
|
|
147
|
+
/**
|
|
148
|
+
* Live activities' chunks with no vector of `model`, by hash from `after`, each with its text cut again. A chunk
|
|
149
|
+
* whose text no longer hashes to its hash was cut from older text: its activity is cut again (never under a
|
|
150
|
+
* read-only store) and the chunk left out, so no vector is made of other text than its hash names.
|
|
151
|
+
*/
|
|
152
|
+
export const crmActivityChunksToEmbed = (database, model, { after, limit }, now = Date.now()) => {
|
|
153
|
+
const activity = database.prepare(`SELECT ${COLUMNS} FROM records r JOIN accounts a ON a.id = r.account_id WHERE r.id = ?`);
|
|
154
|
+
const stale = [];
|
|
155
|
+
const found = database
|
|
156
|
+
.prepare(`SELECT k.content_hash AS hash, min(k.chunkable_id) AS owner, k.start_offset AS start, k.end_offset AS end
|
|
157
|
+
FROM chunks k WHERE k.content_hash > ? AND ${UNEMBEDDED}
|
|
158
|
+
GROUP BY k.content_hash ORDER BY k.content_hash LIMIT ?`)
|
|
159
|
+
.all(after ?? "", model, limit)
|
|
160
|
+
.flatMap((row) => {
|
|
161
|
+
const owner = activity.get(Number(row.owner));
|
|
162
|
+
if (!owner)
|
|
163
|
+
return [];
|
|
164
|
+
const { subject, body, id } = chunkedOf(owner);
|
|
165
|
+
const text = textOf(subject, body).slice(Number(row.start), Number(row.end));
|
|
166
|
+
if (chunkHash(text) === String(row.hash))
|
|
167
|
+
return [{ hash: String(row.hash), text }];
|
|
168
|
+
stale.push(id);
|
|
169
|
+
return [];
|
|
170
|
+
});
|
|
171
|
+
if (stale.length && !isQueryOnly(database))
|
|
172
|
+
write(database, () => rechunkCrmActivities(database, stale, now));
|
|
173
|
+
return found;
|
|
174
|
+
};
|
|
175
|
+
export const crmActivitiesEmbedded = (database, model, accountIds) => accountIds.length > 0 &&
|
|
176
|
+
database
|
|
177
|
+
.prepare(`SELECT 1 FROM chunks k JOIN embeddings v ON v.model = ? AND v.content_hash = k.content_hash
|
|
178
|
+
WHERE ${LIVE} AND k.account_id IN (SELECT value FROM json_each(?)) LIMIT 1`)
|
|
179
|
+
.get(model, JSON.stringify(accountIds)) !== undefined;
|
|
180
|
+
const SCAN_PAGE = 5_000;
|
|
181
|
+
const ranked = (best, limit) => [...best.values()].sort((a, b) => b.score - a.score || a.owner - b.owner).slice(0, limit);
|
|
182
|
+
/**
|
|
183
|
+
* The deals and leads of one account whose activities are nearest to `query` by their best chunk's vector of
|
|
184
|
+
* `model`, best first, each with its nearest activity. An activity counts only through a live deal or lead of `kinds`
|
|
185
|
+
* the viewer may read (SEC-197): one on contacts or companies alone, or on a hidden deal, is never found, and a hidden
|
|
186
|
+
* deal is never named. By the model's vector index, or by a scan of the account's chunks while it has none.
|
|
187
|
+
*/
|
|
188
|
+
export const nearestCrmActivities = (database, model, query, { account, accountId, limit, kinds = DEAL_KINDS, viewers = [], }) => {
|
|
189
|
+
const rules = viewers
|
|
190
|
+
.filter((one) => one.account.provider === account.provider && one.account.account === account.account)
|
|
191
|
+
.map((one) => viewerSql("d", one));
|
|
192
|
+
const targetsOf = kinds.map((kind) => ({
|
|
193
|
+
kind,
|
|
194
|
+
read: database.prepare(`SELECT d.id FROM record_relations rr JOIN ${TABLES[kind]} d ON d.account_id = ?
|
|
195
|
+
AND d.external_id = rr.target_external_id AND d.deleted_at IS NULL
|
|
196
|
+
${rules.map(({ sql }) => `AND ${sql}`).join(" ")}
|
|
197
|
+
WHERE rr.record_id = ? AND rr.role = 'on' AND rr.target_type = '${kind}' ORDER BY d.id`),
|
|
198
|
+
params: rules.flatMap(({ params }) => params),
|
|
199
|
+
}));
|
|
200
|
+
const targets = new Map();
|
|
201
|
+
const targetsOfActivity = (owner) => {
|
|
202
|
+
let found = targets.get(owner);
|
|
203
|
+
if (found === undefined) {
|
|
204
|
+
found = targetsOf.flatMap(({ kind, read, params }) => read.all(accountId, ...params, owner).map((row) => ({ kind, id: Number(row.id) })));
|
|
205
|
+
targets.set(owner, found);
|
|
206
|
+
}
|
|
207
|
+
return found;
|
|
208
|
+
};
|
|
209
|
+
const columns = `k.id, k.chunkable_id AS owner, k.content_hash AS hash, v.vector
|
|
210
|
+
FROM chunks k JOIN embeddings v ON v.model = ? AND v.content_hash = k.content_hash
|
|
211
|
+
WHERE ${LIVE} AND k.account_id = ?`;
|
|
212
|
+
const keep = (best, row) => {
|
|
213
|
+
const owner = Number(row.owner);
|
|
214
|
+
if (!targetsOfActivity(owner).length)
|
|
215
|
+
return;
|
|
216
|
+
const score = dot(query, row.vector);
|
|
217
|
+
if (score > (best.get(owner)?.score ?? Number.NEGATIVE_INFINITY))
|
|
218
|
+
best.set(owner, { owner, chunk: Number(row.id), score });
|
|
219
|
+
};
|
|
220
|
+
const candidates = database.prepare(`SELECT ${columns} AND k.id IN (SELECT value FROM json_each(?)) ORDER BY k.id`);
|
|
221
|
+
const activities = searchIndex(database, model, { kind: CRM_ACTIVITY_CHUNK, account: accountId }, query, limit, (near) => {
|
|
222
|
+
const hashes = new Map(near.map(({ id, hash }) => [id, hash]));
|
|
223
|
+
const best = new Map();
|
|
224
|
+
for (const row of candidates.all(model, accountId, JSON.stringify([...hashes.keys()])))
|
|
225
|
+
if (hashes.get(Number(row.id)) === row.hash)
|
|
226
|
+
keep(best, row);
|
|
227
|
+
const results = ranked(best, limit);
|
|
228
|
+
return { results, best: results.map(({ chunk }) => chunk) };
|
|
229
|
+
}) ??
|
|
230
|
+
(() => {
|
|
231
|
+
const page = database.prepare(`SELECT ${columns} AND k.id > ? ORDER BY k.id LIMIT ?`);
|
|
232
|
+
const best = new Map();
|
|
233
|
+
let after = 0;
|
|
234
|
+
for (;;) {
|
|
235
|
+
const rows = page.all(model, accountId, after, SCAN_PAGE);
|
|
236
|
+
for (const row of rows)
|
|
237
|
+
keep(best, row);
|
|
238
|
+
const last = rows.at(-1);
|
|
239
|
+
if (!last || rows.length < SCAN_PAGE)
|
|
240
|
+
break;
|
|
241
|
+
after = Number(last.id);
|
|
242
|
+
}
|
|
243
|
+
return ranked(best, limit);
|
|
244
|
+
})();
|
|
245
|
+
const text = database.prepare("SELECT json_extract(fields, '$.subject') AS subject, json_extract(fields, '$.body') AS body FROM records " +
|
|
246
|
+
"WHERE id = ?");
|
|
247
|
+
// Several activities on one deal: the deal is found once, by its nearest.
|
|
248
|
+
const named = new Set();
|
|
249
|
+
return activities.flatMap(({ owner, score }) => {
|
|
250
|
+
const row = text.get(owner);
|
|
251
|
+
return targetsOfActivity(owner).flatMap(({ kind, id }) => {
|
|
252
|
+
const ref = `${kind}:${id}`;
|
|
253
|
+
if (named.has(ref))
|
|
254
|
+
return [];
|
|
255
|
+
named.add(ref);
|
|
256
|
+
return [
|
|
257
|
+
{
|
|
258
|
+
account,
|
|
259
|
+
ref,
|
|
260
|
+
kind,
|
|
261
|
+
subject: row?.subject == null ? "" : String(row.subject),
|
|
262
|
+
body: row?.body == null ? null : String(row.body),
|
|
263
|
+
score,
|
|
264
|
+
},
|
|
265
|
+
];
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
};
|
|
269
|
+
export const crmActivityChunksOver = (context) => {
|
|
270
|
+
const { database, now } = context;
|
|
271
|
+
const accountsOf = (accounts) => accounts === undefined
|
|
272
|
+
? database
|
|
273
|
+
.prepare("SELECT a.id, a.provider, a.external_id AS account FROM accounts a WHERE a.id IN " +
|
|
274
|
+
`(SELECT DISTINCT account_id FROM chunks WHERE chunkable_type = '${CRM_ACTIVITY_CHUNK}')`)
|
|
275
|
+
.all()
|
|
276
|
+
.map((row) => ({ id: Number(row.id), key: { provider: String(row.provider), account: String(row.account) } }))
|
|
277
|
+
: accounts.flatMap((one) => {
|
|
278
|
+
const id = findAccountPk(context, one);
|
|
279
|
+
return id === undefined ? [] : [{ id, key: { provider: one.provider, account: one.account } }];
|
|
280
|
+
});
|
|
281
|
+
return {
|
|
282
|
+
refresh: async ({ until } = {}) => refreshCrmActivityChunks(database, now(), until),
|
|
283
|
+
chunksToEmbed: async (model, options) => crmActivityChunksToEmbed(database, model, options, now()),
|
|
284
|
+
chunksLeft: async (model) => crmActivityChunksLeft(database, model),
|
|
285
|
+
embedded: async (model, accounts) => crmActivitiesEmbedded(database, model, accountsOf(accounts).map(({ id }) => id)),
|
|
286
|
+
nearest: async (model, query, { limit, accounts, kinds, viewers }) => accountsOf(accounts)
|
|
287
|
+
.flatMap(({ id, key }) => nearestCrmActivities(database, model, query, {
|
|
288
|
+
account: key,
|
|
289
|
+
accountId: id,
|
|
290
|
+
limit,
|
|
291
|
+
...(kinds === undefined ? {} : { kinds }),
|
|
292
|
+
...(viewers === undefined ? {} : { viewers }),
|
|
293
|
+
}))
|
|
294
|
+
.sort((a, b) => b.score - a.score)
|
|
295
|
+
.slice(0, limit),
|
|
296
|
+
};
|
|
297
|
+
};
|
|
@@ -3,6 +3,7 @@ import { type DealKind } from "../../domain/deals.js";
|
|
|
3
3
|
import type { AccountPeople } from "../people.js";
|
|
4
4
|
import type { AccountKey } from "../types.js";
|
|
5
5
|
import { type CrmActivitiesSaved, type StoredActivity } from "./crm-activities.js";
|
|
6
|
+
import { type CrmActivityChunks } from "./crm-activity-chunks.js";
|
|
6
7
|
import { type CrmReads } from "./crm-changes.js";
|
|
7
8
|
import { type CrmContactsRemoved } from "./crm-contacts.js";
|
|
8
9
|
import { type CrmSkipped } from "./crm-rows.js";
|
|
@@ -116,6 +117,8 @@ export interface CrmCopies extends CrmReads {
|
|
|
116
117
|
saveActivities(key: AccountKey, activities: readonly CrmActivity[]): Promise<CrmActivitiesSaved>;
|
|
117
118
|
/** One deal's or lead's activities, open ones first. */
|
|
118
119
|
activitiesOf(key: AccountKey, kind: DealKind, externalId: string, limit: number): Promise<StoredActivity[]>;
|
|
120
|
+
/** The activities' pieces searched by meaning, as `embedCrmActivities` and `search all` read them. */
|
|
121
|
+
readonly activityChunks: CrmActivityChunks;
|
|
119
122
|
/**
|
|
120
123
|
* Marks deleted every stored deal or lead of the kind assigned to a user outside `userIds`; one with no assignee
|
|
121
124
|
* stays. Reads only the store. Answers how many; `dryRun` only counts them.
|
|
@@ -146,6 +149,7 @@ export interface CrmCopies extends CrmReads {
|
|
|
146
149
|
externalIdsOf(key: AccountKey, ref: string): Promise<string[]>;
|
|
147
150
|
}
|
|
148
151
|
export type { CrmActivitiesSaved, StoredActivity } from "./crm-activities.js";
|
|
152
|
+
export type { CrmActivityChunks, CrmActivityNearest } from "./crm-activity-chunks.js";
|
|
149
153
|
export type { CrmContactsRemoved } from "./crm-contacts.js";
|
|
150
154
|
export { type CrmSkipped, crmIdentityId, crmRowsOver, type ItemWriter } from "./crm-rows.js";
|
|
151
155
|
export declare const crmCopiesOver: (context: StoreContext, people: AccountPeople) => CrmCopies;
|
package/dist/store/sqlite/crm.js
CHANGED
|
@@ -5,6 +5,7 @@ import { recordFingerprint } from "../../domain/records.js";
|
|
|
5
5
|
import { accountPk, findAccountPk } from "./accounts.js";
|
|
6
6
|
import { suggestBaseStages } from "./base-suggest.js";
|
|
7
7
|
import { crmActivitiesOver, forgetActivitiesOn, } from "./crm-activities.js";
|
|
8
|
+
import { crmActivityChunksOver } from "./crm-activity-chunks.js";
|
|
8
9
|
import { crmReadsOver } from "./crm-changes.js";
|
|
9
10
|
import { removeCrmContacts } from "./crm-contacts.js";
|
|
10
11
|
import { crmAccountPrefix, crmExternalIdsOf, crmIdentityId, crmRefOf, crmRowsOver, PERSON_RECORD, SOURCE, TABLES, textOf, } from "./crm-rows.js";
|
|
@@ -671,6 +672,7 @@ export const crmCopiesOver = (context, people) => {
|
|
|
671
672
|
activitiesOn: async (key) => crmActivitiesOn(database, key),
|
|
672
673
|
saveActivities: async (key, activities) => activityStore.save(key, activities),
|
|
673
674
|
activitiesOf: async (key, kind, externalId, limit) => activityStore.of(key, kind, externalId, limit),
|
|
675
|
+
activityChunks: crmActivityChunksOver(context),
|
|
674
676
|
...crmReadsOver(context),
|
|
675
677
|
removeOutOfScope: async (key, kind, userIds, { dryRun } = {}) => write(database, () => {
|
|
676
678
|
const keep = new Set(userIds.map((id) => crmIdentityId(key, id, "user")));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.743.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",
|