@wirecat/cli-core 1.1.0 → 1.3.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 +80 -0
- package/dist/cli/account-remove.d.ts +3 -0
- package/dist/cli/account-remove.js +1 -1
- package/dist/cli/contract-templates.js +3 -0
- package/dist/cli/documents/index.d.ts +2 -1
- package/dist/cli/documents/index.js +4 -1
- package/dist/cli/help/first-screen.js +2 -2
- package/dist/cli/index.d.ts +3 -3
- package/dist/cli/index.js +3 -3
- package/dist/cli/messenger/account-command.js +0 -10
- package/dist/cli/messenger/accounts.d.ts +1 -1
- package/dist/cli/messenger/accounts.js +1 -1
- package/dist/cli/messenger/context.d.ts +1 -1
- package/dist/cli/messenger/conversation-answers.d.ts +2 -0
- package/dist/cli/messenger/message-answers.d.ts +2 -0
- package/dist/cli/messenger/message-items.js +2 -0
- package/dist/cli/messenger/message-writes.d.ts +4 -0
- package/dist/cli/messenger/search-answers.js +2 -0
- package/dist/cli/messenger/session-commands.d.ts +1 -1
- package/dist/cli/messenger/session-commands.js +1 -1
- package/dist/cli/oauth-session.js +6 -3
- package/dist/cli/program.js +2 -2
- package/dist/cli/settings.d.ts +3 -3
- package/dist/cli/shared-command-exports.d.ts +2 -0
- package/dist/cli/shared-command-exports.js +3 -0
- package/dist/cli/token-session.d.ts +1 -4
- package/dist/cli/token-session.js +5 -1
- package/dist/domain/models.d.ts +5 -0
- package/dist/domain/person-kinds.d.ts +1 -1
- package/dist/entities/contact-context.d.ts +4 -0
- package/dist/entities/conversation-results.d.ts +4 -0
- package/dist/entities/evidence.d.ts +16 -0
- package/dist/entities/index.d.ts +36 -0
- package/dist/entities/listener.d.ts +8 -0
- package/dist/entities/message-change.d.ts +2 -0
- package/dist/entities/message-context.d.ts +6 -0
- package/dist/entities/message-write.d.ts +8 -0
- package/dist/entities/message.d.ts +4 -0
- package/dist/entities/message.js +4 -0
- package/dist/entities/store-maintenance.js +1 -1
- package/dist/entities/store-records.d.ts +2 -0
- package/dist/errors/failures.d.ts +6 -0
- package/dist/errors/failures.js +18 -4
- package/dist/errors/reasons.js +16 -0
- package/dist/errors/store-reasons.js +1 -0
- package/dist/mail/cli/index.js +1 -1
- package/dist/mail/headers.d.ts +2 -0
- package/dist/mail/headers.js +2 -1
- package/dist/mail/read.js +1 -0
- package/dist/mail/sort-rules.d.ts +58 -0
- package/dist/mail/sort-rules.js +79 -0
- package/dist/mcp/tool.js +2 -2
- package/dist/runs/recording.js +2 -2
- package/dist/search/lucene/registry.js +24 -0
- package/dist/services/messages-search.js +1 -1
- package/dist/store/areas.d.ts +2 -0
- package/dist/store/areas.js +2 -0
- package/dist/store/public.d.ts +1 -1
- package/dist/store/public.js +1 -1
- package/dist/store/queries.js +9 -2
- package/dist/store/sqlite/email-types.d.ts +8 -0
- package/dist/store/sqlite/email-types.js +45 -10
- package/dist/store/sqlite/emails.d.ts +3 -0
- package/dist/store/sqlite/emails.js +14 -5
- package/dist/store/sqlite/lucene-fields.d.ts +6 -0
- package/dist/store/sqlite/lucene-fields.js +10 -0
- package/dist/store/sqlite/lucene.js +6 -0
- package/dist/store/sqlite/mail-sorting.d.ts +122 -0
- package/dist/store/sqlite/mail-sorting.js +482 -0
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +20 -0
- package/dist/store/sqlite/people-list.js +65 -16
- package/dist/store/sqlite/schema/mail-sorting.d.ts +384 -0
- package/dist/store/sqlite/schema/mail-sorting.js +31 -0
- package/dist/store/sqlite/schema.d.ts +17 -0
- package/dist/store/sqlite/schema.js +3 -0
- package/dist/store/sqlite/sender-bots.d.ts +10 -1
- package/dist/store/sqlite/sender-bots.js +47 -8
- package/package.json +2 -2
- package/parity.json +9 -3
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { getDomain } from "tldts";
|
|
2
|
+
import { listIdOf } from "./headers.js";
|
|
3
|
+
/** What a sorting rule names, most specific first. @experimental */
|
|
4
|
+
export const SORT_SCOPES = ["mail", "list", "subject", "address", "domain"];
|
|
5
|
+
/** A List-Id and a subject pattern are one level: neither is more specific than the other. */
|
|
6
|
+
const LEVEL = { mail: 1, list: 2, subject: 2, address: 3, domain: 4 };
|
|
7
|
+
/** A subject pattern: any case, and any number stands for any other, so "Order 4411" matches "order 9". */
|
|
8
|
+
export const subjectKeyOf = (text) => text.toLowerCase().replace(/\d+/g, "0").replace(/\s+/g, " ").trim();
|
|
9
|
+
const hostOf = (address) => address.slice(address.lastIndexOf("@") + 1);
|
|
10
|
+
/** The registrable domains a host sits under, itself first: `a.mail.shop.example` → `mail.shop.example`, `shop.example`… */
|
|
11
|
+
const suffixesOf = (host) => {
|
|
12
|
+
const labels = host.split(".");
|
|
13
|
+
return labels.slice(0, -1).map((_, at) => labels.slice(at).join("."));
|
|
14
|
+
};
|
|
15
|
+
/** The owner's rule first, then the newest. */
|
|
16
|
+
const before = (a, b) => (a.author === "owner" ? 0 : 1) - (b.author === "owner" ? 0 : 1) || b.createdAt - a.createdAt || b.id - a.id;
|
|
17
|
+
const keyOf = (scope, value) => `${scope}\u0000${value}`;
|
|
18
|
+
/** @experimental */
|
|
19
|
+
export const sortIndexOf = (rules) => {
|
|
20
|
+
const byKey = new Map();
|
|
21
|
+
const subjects = [];
|
|
22
|
+
for (const rule of rules) {
|
|
23
|
+
if (rule.scope === "subject")
|
|
24
|
+
subjects.push(rule);
|
|
25
|
+
else
|
|
26
|
+
byKey.set(keyOf(rule.scope, rule.value), [...(byKey.get(keyOf(rule.scope, rule.value)) ?? []), rule]);
|
|
27
|
+
}
|
|
28
|
+
for (const list of byKey.values())
|
|
29
|
+
list.sort(before);
|
|
30
|
+
return { byKey, subjects: subjects.sort(before), size: rules.length };
|
|
31
|
+
};
|
|
32
|
+
const applies = (rule, mail) => rule.past || (mail.at !== null && mail.at >= rule.createdAt);
|
|
33
|
+
const first = (rules, mail) => rules.find((rule) => applies(rule, mail));
|
|
34
|
+
/**
|
|
35
|
+
* The rule that decides this email, the first scope that has one: the mail, its List-Id or a subject pattern, its
|
|
36
|
+
* address, its domain. Within a scope the owner's rule beats the program's and the newest wins. A domain rule marked
|
|
37
|
+
* `overAddresses` beats the address rules. Addresses match whole and domains on a label boundary, so `ann@` never
|
|
38
|
+
* matches `joann@` and `shop.example` never matches `myshop.example`. @experimental
|
|
39
|
+
*/
|
|
40
|
+
export const sortRuleFor = (index, mail) => {
|
|
41
|
+
if (index.size === 0)
|
|
42
|
+
return undefined;
|
|
43
|
+
const at = (scope, value) => value === null ? undefined : first(index.byKey.get(keyOf(scope, value)) ?? [], mail);
|
|
44
|
+
const own = at("mail", String(mail.id));
|
|
45
|
+
if (own !== undefined)
|
|
46
|
+
return own;
|
|
47
|
+
const subject = mail.subject === null ? undefined : subjectKeyOf(mail.subject);
|
|
48
|
+
const second = [
|
|
49
|
+
at("list", mail.list),
|
|
50
|
+
subject === undefined
|
|
51
|
+
? undefined
|
|
52
|
+
: first(index.subjects.filter((rule) => subject.includes(rule.value)), mail),
|
|
53
|
+
].filter((rule) => rule !== undefined);
|
|
54
|
+
if (second.length > 0)
|
|
55
|
+
return second.sort(before)[0];
|
|
56
|
+
if (mail.from === null || !mail.from.includes("@"))
|
|
57
|
+
return undefined;
|
|
58
|
+
const domain = suffixesOf(hostOf(mail.from))
|
|
59
|
+
.map((host) => at("domain", host))
|
|
60
|
+
.find((rule) => rule !== undefined);
|
|
61
|
+
if (domain?.overAddresses)
|
|
62
|
+
return domain;
|
|
63
|
+
return at("address", mail.from) ?? domain;
|
|
64
|
+
};
|
|
65
|
+
/** Whether a scope is more specific than another. @experimental */
|
|
66
|
+
export const narrower = (a, b) => LEVEL[a] < LEVEL[b];
|
|
67
|
+
/** What a rule of this scope keeps as its value, or `undefined` when the value names nothing. @experimental */
|
|
68
|
+
export const sortValueOf = (scope, value) => {
|
|
69
|
+
const text = String(value).trim();
|
|
70
|
+
if (scope === "mail")
|
|
71
|
+
return /^[1-9]\d*$/.test(text) ? text : undefined;
|
|
72
|
+
if (scope === "list")
|
|
73
|
+
return listIdOf(text);
|
|
74
|
+
if (scope === "subject")
|
|
75
|
+
return subjectKeyOf(text) || undefined;
|
|
76
|
+
if (scope === "address")
|
|
77
|
+
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text) ? text.toLowerCase() : undefined;
|
|
78
|
+
return getDomain(text.replace(/^.*@/, "").toLowerCase()) ?? undefined;
|
|
79
|
+
};
|
package/dist/mcp/tool.js
CHANGED
|
@@ -8,7 +8,7 @@ import { DEFAULT_OUTPUT_BYTES } from "../cli/execution.js";
|
|
|
8
8
|
import { MAX_BUFFERED_INPUT } from "../cli/input-policy.js";
|
|
9
9
|
import { refuseLacking } from "../cli/messenger/lacks.js";
|
|
10
10
|
import { ENTITIES } from "../entities/index.js";
|
|
11
|
-
import { storeDamaged } from "../errors/failures.js";
|
|
11
|
+
import { storeBusy, storeDamaged } from "../errors/failures.js";
|
|
12
12
|
import { failureContext } from "../errors/reasons.js";
|
|
13
13
|
import { startRecording } from "../runs/recording.js";
|
|
14
14
|
import { newRunId } from "../runs/run.js";
|
|
@@ -320,7 +320,7 @@ export const answered = (answer, maxBytes = DEFAULT_OUTPUT_BYTES, targets) => {
|
|
|
320
320
|
export const failed = (error, errors, effects) => {
|
|
321
321
|
const judged = judgedEffects(effects);
|
|
322
322
|
const context = { ...failureContext(errors), ...(judged ? { effects: judged } : {}) };
|
|
323
|
-
return mcpErrorResult(JSON.parse(agentJson(errorObjectOf(storeDamaged(error), context))));
|
|
323
|
+
return mcpErrorResult(JSON.parse(agentJson(errorObjectOf(storeBusy(storeDamaged(error)), context))));
|
|
324
324
|
};
|
|
325
325
|
/** An option's name as an MCP argument: `beforeId` is `before_id`. */
|
|
326
326
|
export const snakeOf = (key) => key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
|
package/dist/runs/recording.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { processStreams } from "@wirecat/cli-base";
|
|
2
|
-
import { isCliFailure, storeDamaged } from "../errors/failures.js";
|
|
2
|
+
import { isCliFailure, storeBusy, storeDamaged } from "../errors/failures.js";
|
|
3
3
|
import { markStoreDamaged } from "../store/marks.js";
|
|
4
4
|
import { storePath } from "../store/path.js";
|
|
5
5
|
import { endpointTemplate, errorDetailOf, framesOf } from "./error-detail.js";
|
|
@@ -118,7 +118,7 @@ export const startRecording = (options) => {
|
|
|
118
118
|
});
|
|
119
119
|
},
|
|
120
120
|
fail: async (thrown) => {
|
|
121
|
-
const error = storeDamaged(thrown);
|
|
121
|
+
const error = storeBusy(storeDamaged(thrown));
|
|
122
122
|
markStoreDamaged(thrown, {
|
|
123
123
|
store: storePath(options.env),
|
|
124
124
|
command: `${options.app.command} ${options.command}`,
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { queryAstSchema, validateQuery, walkQuery, } from "@wirecat/cli-base/query";
|
|
2
2
|
import * as v from "valibot";
|
|
3
3
|
import { tagOf } from "../../domain/tags.js";
|
|
4
|
+
import { MAIL_TYPES } from "../../mail/mail-types.js";
|
|
5
|
+
import { REACHES } from "../../store/sqlite/sender-signals.js";
|
|
4
6
|
import { MOST_WORDS_APART, QUERY_LIMITS, SEARCH_QUERY, searchError } from "./types.js";
|
|
5
7
|
export const FIELD_VERSION = 2;
|
|
6
8
|
const UNITS = {
|
|
@@ -149,6 +151,28 @@ export const QUERY_FIELDS = [
|
|
|
149
151
|
support: "A1",
|
|
150
152
|
values: ["unread", "read", "starred"],
|
|
151
153
|
},
|
|
154
|
+
{
|
|
155
|
+
name: "type",
|
|
156
|
+
example: "type:order OR type:bill",
|
|
157
|
+
index: "emails.mail_type (emails_by_mail_type)",
|
|
158
|
+
aliases: [],
|
|
159
|
+
type: "enum",
|
|
160
|
+
operators: terms,
|
|
161
|
+
normalization: "lowercase; what one email is, apart from its sender; mail not typed yet is typed before the search; mail only",
|
|
162
|
+
support: "A1",
|
|
163
|
+
values: MAIL_TYPES,
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
name: "reach",
|
|
167
|
+
example: "reach:direct",
|
|
168
|
+
index: "emails.reach",
|
|
169
|
+
aliases: [],
|
|
170
|
+
type: "enum",
|
|
171
|
+
operators: terms,
|
|
172
|
+
normalization: "lowercase; how one email reached the owner; mail only",
|
|
173
|
+
support: "A1",
|
|
174
|
+
values: REACHES,
|
|
175
|
+
},
|
|
152
176
|
{
|
|
153
177
|
name: "chat",
|
|
154
178
|
example: "chat:*fixture*",
|
|
@@ -15,7 +15,7 @@ import { mailAround, mergeMail, withMailThreads } from "./mail-search.js";
|
|
|
15
15
|
import { chatAmong, chatsMatchingIn, senderAmong, sendersMatching } from "./message-resolution.js";
|
|
16
16
|
import { accountsOfKind, listedAccounts, MAIL } from "./search-kind.js";
|
|
17
17
|
const PERSON_FIELDS = new Set(["from", "to", "cc", "bcc"]);
|
|
18
|
-
const MAIL_FIELDS = new Set(["to", "cc", "bcc", "subject", "mailbox", "label", "is", "list"]);
|
|
18
|
+
const MAIL_FIELDS = new Set(["to", "cc", "bcc", "subject", "mailbox", "label", "is", "list", "type", "reach"]);
|
|
19
19
|
import { parseLucene, timezoneOf, walkQuery, } from "@wirecat/cli-base/query";
|
|
20
20
|
import { MESSAGE_PARSING, searchError } from "../search/lucene/types.js";
|
|
21
21
|
import { rangeOf } from "../search/service-query.js";
|
package/dist/store/areas.d.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Store area types and constants some CLIs use beyond the stable `@wirecat/cli-core/store`: experimental, so a
|
|
3
3
|
* minor release may change them.
|
|
4
4
|
*/
|
|
5
|
+
export { MAIL_TYPES, type MailType } from "../mail/mail-types.js";
|
|
5
6
|
export { type AddedSource, type AddedSourceContent, type AddedSourceInput, addedSourceKeyOf, } from "./sqlite/added-sources.js";
|
|
6
7
|
export type { ContractFilter } from "./sqlite/business-contracts.js";
|
|
7
8
|
export type { CatalogEntry, CatalogInput, CatalogQuery } from "./sqlite/catalog.js";
|
|
@@ -31,6 +32,7 @@ export { PROPOSAL_STATUSES, type ProposedAction } from "./sqlite/proposed-action
|
|
|
31
32
|
export type { MatchRun, RecordKey } from "./sqlite/records.js";
|
|
32
33
|
export type { RelationListItem } from "./sqlite/relation-list.js";
|
|
33
34
|
export type { BotIdentity, BotList, BotListOptions, BotMove, SenderBot, SenderBotDetails, } from "./sqlite/sender-bots.js";
|
|
35
|
+
export { REACHES, type Reach } from "./sqlite/sender-signals.js";
|
|
34
36
|
export type { SubscriptionFilter } from "./sqlite/subscriptions.js";
|
|
35
37
|
export { PROJECT_TASK_FIELDS, TASK_SORTS, type TaskSort } from "./sqlite/task-board.js";
|
|
36
38
|
export { TASK_RELATION_KINDS, type TaskRelationKind } from "./sqlite/task-relations.js";
|
package/dist/store/areas.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Store area types and constants some CLIs use beyond the stable `@wirecat/cli-core/store`: experimental, so a
|
|
3
3
|
* minor release may change them.
|
|
4
4
|
*/
|
|
5
|
+
export { MAIL_TYPES } from "../mail/mail-types.js";
|
|
5
6
|
export { addedSourceKeyOf, } from "./sqlite/added-sources.js";
|
|
6
7
|
export { crmIdentityId } from "./sqlite/crm-rows.js";
|
|
7
8
|
export { crmSettingKey } from "./sqlite/crm-settings.js";
|
|
@@ -11,6 +12,7 @@ export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES, } from "./sqlite/knowledge.j
|
|
|
11
12
|
export { PEOPLE_SORTS } from "./sqlite/people-list.js";
|
|
12
13
|
export { parseMergeId } from "./sqlite/person-merges.js";
|
|
13
14
|
export { PROPOSAL_STATUSES } from "./sqlite/proposed-actions.js";
|
|
15
|
+
export { REACHES } from "./sqlite/sender-signals.js";
|
|
14
16
|
export { PROJECT_TASK_FIELDS, TASK_SORTS } from "./sqlite/task-board.js";
|
|
15
17
|
export { TASK_RELATION_KINDS } from "./sqlite/task-relations.js";
|
|
16
18
|
export { TASK_ROLES, } from "./sqlite/work-tasks.js";
|
package/dist/store/public.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export type { ContextEvidenceItem, ContextEvidencePage, ContextEvidenceReader, ContextEvidenceRequest, ContextEvidenceSender, ContextSource, } from "../context/evidence.js";
|
|
2
2
|
export { BUSINESS_KINDS, type BusinessKind } from "../domain/business.js";
|
|
3
3
|
export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
|
|
4
|
-
export { type KindSignal, PERSON_KINDS, type PersonKind } from "../domain/person-kinds.js";
|
|
4
|
+
export { type KindSignal, PERSON_KINDS, type PersonKind, SENDER_BOT_PREFIX } from "../domain/person-kinds.js";
|
|
5
5
|
export type { RefState, RefSummary, RefSummaryKind, RefsStore } from "../domain/ref-summaries.js";
|
|
6
6
|
export type { TagConsolidationApplyOptions, TagConsolidationOptions, TagConsolidationPreview, TagConsolidationReceipt, TagConsolidationStore, } from "../domain/tag-consolidation.js";
|
|
7
7
|
export type { TagRedirectIndex, TagRedirectResolution, TagRedirectSnapshot } from "../domain/tag-redirects.js";
|
package/dist/store/public.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { BUSINESS_KINDS } from "../domain/business.js";
|
|
2
2
|
export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
|
|
3
|
-
export { PERSON_KINDS } from "../domain/person-kinds.js";
|
|
3
|
+
export { PERSON_KINDS, SENDER_BOT_PREFIX } from "../domain/person-kinds.js";
|
|
4
4
|
export { createTagRedirectIndex } from "../domain/tag-redirects.js";
|
|
5
5
|
export { note } from "../entities/note.js";
|
|
6
6
|
export { PAYMENT_DIRECTIONS, PAYMENT_STATES, paymentTitle, validatePayment } from "../meetings/index.js";
|
package/dist/store/queries.js
CHANGED
|
@@ -1,14 +1,21 @@
|
|
|
1
|
+
import { walkQuery } from "@wirecat/cli-base/query";
|
|
1
2
|
import { adminStatisticsQuery } from "./sqlite/admin-statistics.js";
|
|
2
3
|
import { conversationEligibility } from "./sqlite/conversation-eligibility.js";
|
|
3
4
|
import { drainEmailIndex } from "./sqlite/email-index.js";
|
|
5
|
+
import { storeMailTypes } from "./sqlite/email-types.js";
|
|
4
6
|
import * as lucene from "./sqlite/lucene.js";
|
|
5
7
|
import { rankingEvidence } from "./sqlite/ranking-evidence.js";
|
|
6
8
|
import { rankQuery } from "./sqlite/rankings.js";
|
|
7
9
|
import { replyDelays, waitingChats, } from "./sqlite/reply-times.js";
|
|
10
|
+
// Outside the search's read and its time limit: the first such search after an upgrade types every email.
|
|
11
|
+
const asksMailType = ({ root }) => walkQuery(root).some(({ field }) => field === "type" || field === "reach");
|
|
8
12
|
export const queriesStoreOver = (context, stemmerFor) => {
|
|
9
13
|
const mailIndexed = (execution) => {
|
|
10
|
-
if (execution.corpus
|
|
11
|
-
|
|
14
|
+
if (execution.corpus !== "mail")
|
|
15
|
+
return execution;
|
|
16
|
+
drainEmailIndex(context.database, stemmerFor);
|
|
17
|
+
if (asksMailType(execution))
|
|
18
|
+
storeMailTypes(context.database);
|
|
12
19
|
return execution;
|
|
13
20
|
};
|
|
14
21
|
return {
|
|
@@ -33,6 +33,14 @@ export declare const typeWhere: (database: CacheDatabase, filter: TypeFilter) =>
|
|
|
33
33
|
sql: string[];
|
|
34
34
|
params: string[];
|
|
35
35
|
};
|
|
36
|
+
/**
|
|
37
|
+
* The same filter, without writing: inside a read, the mail not typed yet is worked out in memory. `check` runs
|
|
38
|
+
* between batches, so a search's time limit still stops it.
|
|
39
|
+
*/
|
|
40
|
+
export declare const typeCondition: (database: CacheDatabase, filter: TypeFilter, current?: boolean, check?: () => void) => {
|
|
41
|
+
sql: string[];
|
|
42
|
+
params: string[];
|
|
43
|
+
};
|
|
36
44
|
/** One sender's mail, counted by type and reach: a shop's receipts and its sales side by side. @experimental */
|
|
37
45
|
export interface SenderMailTypes {
|
|
38
46
|
/** `person:<id>`, `sender-bot:<id>`, or `null` when the store links the address to neither. */
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { SENDER_BOT_PREFIX } from "../../domain/person-kinds.js";
|
|
2
|
+
import { listIdOf } from "../../mail/headers.js";
|
|
2
3
|
import { MAIL_TYPES, mailTypeOf, schemaTypesOf } from "../../mail/mail-types.js";
|
|
4
|
+
import { sortRuleFor } from "../../mail/sort-rules.js";
|
|
3
5
|
import { isQueryOnly } from "../driver.js";
|
|
6
|
+
import { typeRulesOf } from "./mail-sorting.js";
|
|
7
|
+
import { NEWSLETTER_ONLY } from "./sender-bots.js";
|
|
4
8
|
import { LIST_ID, LIST_SENDERS, REACHES, senderKey } from "./sender-signals.js";
|
|
5
9
|
import { read, writeBatch } from "./transaction.js";
|
|
6
10
|
/** Bump when what decides a mail type changes in code: every stored one is worked out again on the next read. */
|
|
@@ -11,7 +15,8 @@ const RULES_KEY = "mail.type_rules";
|
|
|
11
15
|
* sooner and still hold the lock well inside another writer's 5 s wait.
|
|
12
16
|
*/
|
|
13
17
|
const BATCH = 5_000;
|
|
14
|
-
const INPUTS = "SELECT e.id, e.from_address, e.subject, e.headers, e.body_html, " +
|
|
18
|
+
const INPUTS = "SELECT e.id, e.from_address, e.subject, e.headers, e.body_html, e.outgoing, " +
|
|
19
|
+
"coalesce(e.received_at, e.sent_at) AS at, " +
|
|
15
20
|
`${LIST_ID} AS list, ` +
|
|
16
21
|
"CASE WHEN json_extract(e.metadata, '$.rule') IS NOT NULL THEN NULL ELSE " +
|
|
17
22
|
"(SELECT count(*) FROM email_recipients r WHERE r.email_id = e.id AND r.role IN ('to', 'cc')) END AS recipients, " +
|
|
@@ -19,7 +24,8 @@ const INPUTS = "SELECT e.id, e.from_address, e.subject, e.headers, e.body_html,
|
|
|
19
24
|
"WHERE a.attachable_type = 'email' AND a.attachable_id = e.id AND a.mime IS NOT NULL) AS parts, " +
|
|
20
25
|
"e.outgoing IS 1 OR EXISTS (SELECT 1 FROM email_recipients r JOIN emails o ON o.id = r.email_id " +
|
|
21
26
|
"WHERE r.identity_id = e.from_identity_id AND o.outgoing = 1) AS owner_wrote, " +
|
|
22
|
-
"EXISTS (SELECT 1 FROM sender_bot_identities b
|
|
27
|
+
"EXISTS (SELECT 1 FROM sender_bot_identities b JOIN sender_bots s ON s.id = b.bot_id " +
|
|
28
|
+
`WHERE b.identity_id = e.from_identity_id AND s.reason IS NOT '${NEWSLETTER_ONLY}') AS bot, ` +
|
|
23
29
|
"(SELECT json_extract(g.metadata, '$.sector') FROM organization_identities oi " +
|
|
24
30
|
"JOIN organizations g ON g.id = oi.organization_id " +
|
|
25
31
|
"WHERE oi.identity_id = e.from_identity_id AND g.deleted_at IS NULL ORDER BY g.id LIMIT 1) AS sector " +
|
|
@@ -47,6 +53,7 @@ export const typesOf = (database, ids, senders = new Map()) => {
|
|
|
47
53
|
if (ids.length === 0)
|
|
48
54
|
return found;
|
|
49
55
|
const rows = database.prepare(INPUTS).all(JSON.stringify(ids));
|
|
56
|
+
const rules = typeRulesOf(database);
|
|
50
57
|
const lists = [
|
|
51
58
|
...new Set(rows.flatMap((row) => (typeof row.list === "string" && !senders.has(row.list) ? [row.list] : []))),
|
|
52
59
|
];
|
|
@@ -59,8 +66,9 @@ export const typesOf = (database, ids, senders = new Map()) => {
|
|
|
59
66
|
}
|
|
60
67
|
for (const row of rows) {
|
|
61
68
|
const headers = parsed(row.headers);
|
|
62
|
-
|
|
63
|
-
|
|
69
|
+
const from = typeof row.from_address === "string" ? row.from_address.toLowerCase() : null;
|
|
70
|
+
const typed = mailTypeOf({
|
|
71
|
+
from,
|
|
64
72
|
subject: typeof row.subject === "string" ? row.subject : null,
|
|
65
73
|
headers: typeof row.list === "string" ? { ...headers, "list-id": row.list } : headers,
|
|
66
74
|
recipients: row.recipients == null ? null : Number(row.recipients),
|
|
@@ -70,7 +78,17 @@ export const typesOf = (database, ids, senders = new Map()) => {
|
|
|
70
78
|
ownerWrote: Number(row.owner_wrote) === 1,
|
|
71
79
|
bot: Number(row.bot) === 1,
|
|
72
80
|
sector: typeof row.sector === "string" ? row.sector : null,
|
|
73
|
-
})
|
|
81
|
+
});
|
|
82
|
+
const rule = Number(row.outgoing) === 1
|
|
83
|
+
? undefined
|
|
84
|
+
: sortRuleFor(rules, {
|
|
85
|
+
id: Number(row.id),
|
|
86
|
+
from,
|
|
87
|
+
subject: typeof row.subject === "string" ? row.subject : null,
|
|
88
|
+
list: typeof row.list === "string" ? (listIdOf(row.list) ?? null) : null,
|
|
89
|
+
at: row.at == null ? null : Number(row.at),
|
|
90
|
+
});
|
|
91
|
+
found.set(Number(row.id), rule?.mailType == null ? typed : { ...typed, type: rule.mailType, signal: `rule:${rule.id}` });
|
|
74
92
|
}
|
|
75
93
|
return found;
|
|
76
94
|
};
|
|
@@ -79,8 +97,11 @@ const rulesOf = (database) => {
|
|
|
79
97
|
return row === undefined ? undefined : String(row.value);
|
|
80
98
|
};
|
|
81
99
|
const anyLeft = (database) => database.prepare("SELECT 1 FROM emails WHERE mail_type IS NULL LIMIT 1").get() !== undefined;
|
|
100
|
+
const UNCHECKED = "SELECT id FROM emails WHERE mail_type IS NOT NULL AND sort_checked IS NULL";
|
|
101
|
+
/** A type a build before version 77 kept, while a sorting rule exists that it never read. */
|
|
102
|
+
const anyUnchecked = (database) => typeRulesOf(database).size > 0 && database.prepare(`${UNCHECKED} LIMIT 1`).get() !== undefined;
|
|
82
103
|
/** Whether every email's stored type is current. */
|
|
83
|
-
export const typesCurrent = (database) => rulesOf(database) === TYPE_RULES && !anyLeft(database);
|
|
104
|
+
export const typesCurrent = (database) => rulesOf(database) === TYPE_RULES && !anyLeft(database) && !anyUnchecked(database);
|
|
84
105
|
/**
|
|
85
106
|
* Works out and keeps the type of every email whose stored one the triggers cleared, or every email after the rules
|
|
86
107
|
* changed, a batch per write so another process never waits long for the lock. A query-only open keeps nothing.
|
|
@@ -101,7 +122,12 @@ export const storeMailTypes = (database) => {
|
|
|
101
122
|
"ON CONFLICT (key) DO UPDATE SET value = excluded.value, at = excluded.at")
|
|
102
123
|
.run(RULES_KEY, TYPE_RULES, Date.now());
|
|
103
124
|
});
|
|
104
|
-
|
|
125
|
+
if (anyUnchecked(database)) {
|
|
126
|
+
const clear = database.prepare(`UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE id IN (${UNCHECKED} LIMIT ?)`);
|
|
127
|
+
while (writeBatch(database, () => clear.run(BATCH).changes) === BATCH)
|
|
128
|
+
;
|
|
129
|
+
}
|
|
130
|
+
const keep = database.prepare("UPDATE emails SET mail_type = ?, reach = ?, type_signal = ?, sort_checked = 1 WHERE id = ?");
|
|
105
131
|
const senders = new Map();
|
|
106
132
|
for (;;) {
|
|
107
133
|
const more = writeBatch(database, () => {
|
|
@@ -136,7 +162,14 @@ const passes = (filter, type, reach) => (filter.types === undefined || filter.ty
|
|
|
136
162
|
* The SQL of a filter by type and reach over `e`. Types are worked out and kept first; a query-only open that finds
|
|
137
163
|
* some not worked out works those out in memory, so a filtered list is never short.
|
|
138
164
|
*/
|
|
139
|
-
export const typeWhere = (database, filter) =>
|
|
165
|
+
export const typeWhere = (database, filter) => filter.types === undefined && filter.reaches === undefined
|
|
166
|
+
? { sql: [], params: [] }
|
|
167
|
+
: typeCondition(database, filter, storeMailTypes(database));
|
|
168
|
+
/**
|
|
169
|
+
* The same filter, without writing: inside a read, the mail not typed yet is worked out in memory. `check` runs
|
|
170
|
+
* between batches, so a search's time limit still stops it.
|
|
171
|
+
*/
|
|
172
|
+
export const typeCondition = (database, filter, current = typesCurrent(database), check = () => { }) => {
|
|
140
173
|
if (filter.types === undefined && filter.reaches === undefined)
|
|
141
174
|
return { sql: [], params: [] };
|
|
142
175
|
const stored = [
|
|
@@ -147,7 +180,7 @@ export const typeWhere = (database, filter) => {
|
|
|
147
180
|
...(filter.types === undefined ? [] : [JSON.stringify(filter.types)]),
|
|
148
181
|
...(filter.reaches === undefined ? [] : [JSON.stringify(filter.reaches)]),
|
|
149
182
|
];
|
|
150
|
-
if (
|
|
183
|
+
if (current)
|
|
151
184
|
return { sql: [stored], params };
|
|
152
185
|
const pending = read(database, () => {
|
|
153
186
|
const ids = database
|
|
@@ -156,10 +189,12 @@ export const typeWhere = (database, filter) => {
|
|
|
156
189
|
.map((row) => Number(row.id));
|
|
157
190
|
const kept = [];
|
|
158
191
|
const senders = new Map();
|
|
159
|
-
for (let at = 0; at < ids.length; at += BATCH)
|
|
192
|
+
for (let at = 0; at < ids.length; at += BATCH) {
|
|
193
|
+
check();
|
|
160
194
|
for (const [id, typed] of typesOf(database, ids.slice(at, at + BATCH), senders))
|
|
161
195
|
if (passes(filter, typed.type, typed.reach))
|
|
162
196
|
kept.push(id);
|
|
197
|
+
}
|
|
163
198
|
return kept;
|
|
164
199
|
});
|
|
165
200
|
return {
|
|
@@ -8,6 +8,7 @@ import { type MailActivityStore } from "./email-activity.js";
|
|
|
8
8
|
import { type EmailLocationInput, type FolderEmail, type PartialMailStore } from "./email-locations.js";
|
|
9
9
|
import { type MailTypeStore, type TypeFilter } from "./email-types.js";
|
|
10
10
|
import { type MailRulesStore } from "./mail-rules.js";
|
|
11
|
+
import { type MailSorting } from "./mail-sorting.js";
|
|
11
12
|
import { type AttachmentInput } from "./meetings.js";
|
|
12
13
|
import type { StoreContext } from "./open.js";
|
|
13
14
|
import type { Reach } from "./sender-signals.js";
|
|
@@ -303,6 +304,8 @@ export interface MailStore extends PartialMailStore, MailActivityStore, MailType
|
|
|
303
304
|
}): Promise<EmailVectorHit[]>;
|
|
304
305
|
/** The account's mail rules, and which rule decided each email. */
|
|
305
306
|
readonly rules: MailRulesStore;
|
|
307
|
+
/** Sorting rules by mail, list, subject, address and domain, apart from the storage `rules`. @experimental */
|
|
308
|
+
readonly sorting: MailSorting;
|
|
306
309
|
}
|
|
307
310
|
/** An email as a message of its thread, the shape mail had when it was stored as messages. */
|
|
308
311
|
export declare const messageOfEmail: (email: Email, thread: string) => Message;
|
|
@@ -12,6 +12,7 @@ import { folded } from "./folded.js";
|
|
|
12
12
|
import { ensurePerson } from "./identities.js";
|
|
13
13
|
import { nearestMailPieces } from "./mail-nearest.js";
|
|
14
14
|
import { mailRulesOver } from "./mail-rules.js";
|
|
15
|
+
import { mailSortingOver, settleThreads } from "./mail-sorting.js";
|
|
15
16
|
import { attachmentOf, saveAttachment, wordsQuery } from "./meetings.js";
|
|
16
17
|
import { stemmerCache } from "./stems.js";
|
|
17
18
|
import { writeState } from "./sync.js";
|
|
@@ -391,6 +392,7 @@ const mailFieldsOf = (database, email, thread, key) => {
|
|
|
391
392
|
thread: formatReference({ type: "chat", provider: key.provider, account: key.account, chat: thread }),
|
|
392
393
|
read: email.read,
|
|
393
394
|
flagged: email.flagged,
|
|
395
|
+
...(email.mailType === null || email.reach === null ? {} : { mailType: email.mailType, reach: email.reach }),
|
|
394
396
|
...(scored === undefined
|
|
395
397
|
? {}
|
|
396
398
|
: {
|
|
@@ -407,12 +409,13 @@ export const emailHitsByPk = (database, pks) => {
|
|
|
407
409
|
const read = database.prepare(`SELECT e.*, t.external_id AS thread, t.subject AS thread_subject, a.provider, a.external_id AS account
|
|
408
410
|
FROM emails e JOIN email_threads t ON t.id = e.email_thread_id JOIN accounts a ON a.id = e.account_id
|
|
409
411
|
WHERE e.id = ?`);
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
412
|
+
const rows = pks.map((pk) => read.get(pk)).filter((row) => row !== undefined);
|
|
413
|
+
const emails = withTypes(database, rows.map((row) => emailOf(database, row)));
|
|
414
|
+
return rows.flatMap((row, at) => {
|
|
415
|
+
const email = emails[at];
|
|
416
|
+
if (!email)
|
|
413
417
|
return [];
|
|
414
418
|
const thread = String(row.thread);
|
|
415
|
-
const email = emailOf(database, row);
|
|
416
419
|
const message = messageOfEmail(email, thread);
|
|
417
420
|
const key = { provider: String(row.provider), account: String(row.account) };
|
|
418
421
|
return [
|
|
@@ -436,13 +439,19 @@ export const emailHitsByPk = (database, pks) => {
|
|
|
436
439
|
*/
|
|
437
440
|
export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache()) => ({
|
|
438
441
|
rules: mailRulesOver(database),
|
|
442
|
+
sorting: mailSortingOver({ database, orm, now }),
|
|
439
443
|
async saveThread(input) {
|
|
440
|
-
const id = write(database, () =>
|
|
444
|
+
const id = write(database, () => {
|
|
445
|
+
const saved = saveThread(database, orm, input);
|
|
446
|
+
settleThreads({ database, orm, now }, [saved]);
|
|
447
|
+
return saved;
|
|
448
|
+
});
|
|
441
449
|
return threadDetails(database, id);
|
|
442
450
|
},
|
|
443
451
|
async saveThreads(inputs, states = []) {
|
|
444
452
|
const ids = write(database, () => {
|
|
445
453
|
const saved = inputs.map((input) => saveThread(database, orm, input));
|
|
454
|
+
settleThreads({ database, orm, now }, saved);
|
|
446
455
|
for (const { accountId, name, value } of states)
|
|
447
456
|
writeState({ orm, now }, accountId, name, value);
|
|
448
457
|
return saved;
|
|
@@ -2,6 +2,7 @@ import { type Automaton, type MatchBudget } from "../../search/lucene/automaton.
|
|
|
2
2
|
import type { QueryExecution, ResolvedPredicate } from "../../search/lucene/resolved.js";
|
|
3
3
|
import { type Stemmer } from "../../search/stem.js";
|
|
4
4
|
import type { CacheDatabase, SqlValue } from "../driver.js";
|
|
5
|
+
import type { TypeFilter } from "./email-types.js";
|
|
5
6
|
export interface Fragment {
|
|
6
7
|
sql: string;
|
|
7
8
|
params: SqlValue[];
|
|
@@ -78,6 +79,11 @@ export interface FieldScope {
|
|
|
78
79
|
everywhere: (node: ResolvedPredicate, fragment: Fragment, start?: string) => Fragment;
|
|
79
80
|
/** Counts the patterns' expanded words against the query's budget. */
|
|
80
81
|
expand: (count: number) => number;
|
|
82
|
+
/** The emails that pass a filter by type and reach, as SQL over `e`; never writes. */
|
|
83
|
+
mailTypes: (filter: TypeFilter) => {
|
|
84
|
+
sql: string[];
|
|
85
|
+
params: string[];
|
|
86
|
+
};
|
|
81
87
|
}
|
|
82
88
|
/** A leaf's condition; a whole `Leaf` is a pattern already expanded by an earlier leaf, taken as it was. */
|
|
83
89
|
type Compiled = {
|
|
@@ -529,6 +529,14 @@ const list = ({ value }, { mail }) => {
|
|
|
529
529
|
json_extract(metadata, '$.listId')) AS list_id FROM emails) WHERE list_id = ? OR list_id LIKE '%.' || ? ESCAPE '\\')`, wanted, wanted.replace(/[\\%_]/g, "\\$&"))
|
|
530
530
|
: bound("0"));
|
|
531
531
|
};
|
|
532
|
+
// Mail not typed yet is worked out in memory here: a search never writes, and the fill runs before it.
|
|
533
|
+
const mailType = (key) => ({ value }, scope) => {
|
|
534
|
+
if (!scope.mail)
|
|
535
|
+
return always(bound("0"));
|
|
536
|
+
const filter = { [key]: [value.toLowerCase()] };
|
|
537
|
+
const { sql, params } = scope.mailTypes(filter);
|
|
538
|
+
return always(bound(`m.id IN (SELECT e.id FROM emails e WHERE ${sql.join(" AND ")})`, ...params));
|
|
539
|
+
};
|
|
532
540
|
const is = ({ value }, { mail }) => {
|
|
533
541
|
const state = value.toLowerCase();
|
|
534
542
|
return always(state === "starred"
|
|
@@ -634,5 +642,7 @@ export const FIELD_COMPILERS = {
|
|
|
634
642
|
label: mailbox,
|
|
635
643
|
list,
|
|
636
644
|
is,
|
|
645
|
+
type: mailType("types"),
|
|
646
|
+
reach: mailType("reaches"),
|
|
637
647
|
subject,
|
|
638
648
|
};
|
|
@@ -4,6 +4,7 @@ import { isPresence, PRESENCE } from "../../search/lucene/registry.js";
|
|
|
4
4
|
import { isStemmed } from "../../search/lucene/resolved.js";
|
|
5
5
|
import { exhausted, outOfTime, QUERY_LIMITS, searchError, sqliteLimit, tooWideTerm } from "../../search/lucene/types.js";
|
|
6
6
|
import { TIME_LIMIT_FUNCTION, TimeLimitReached } from "../driver.js";
|
|
7
|
+
import { typeCondition, typesCurrent } from "./email-types.js";
|
|
7
8
|
import { emailHitsByPk } from "./emails.js";
|
|
8
9
|
import { placeHits } from "./hit-places.js";
|
|
9
10
|
import { combine, FIELD_COMPILERS, ftsMatch, MAIL, MESSAGES, present, quoted, SPEECH, } from "./lucene-fields.js";
|
|
@@ -107,6 +108,7 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
|
|
|
107
108
|
elsewhere,
|
|
108
109
|
};
|
|
109
110
|
};
|
|
111
|
+
let current;
|
|
110
112
|
const fields = {
|
|
111
113
|
database,
|
|
112
114
|
execution,
|
|
@@ -124,6 +126,10 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
|
|
|
124
126
|
expansions += count;
|
|
125
127
|
return expansions;
|
|
126
128
|
},
|
|
129
|
+
mailTypes: (filter) => {
|
|
130
|
+
current ??= typesCurrent(database);
|
|
131
|
+
return typeCondition(database, filter, current, check);
|
|
132
|
+
},
|
|
127
133
|
};
|
|
128
134
|
const createLeaf = (node) => {
|
|
129
135
|
const compiler = isPresence(node) && PRESENCE.has(node.field) ? present : FIELD_COMPILERS[node.field];
|