@wirecat/cli-core 0.600.0 → 0.602.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 +83 -1
- package/dist/calendar/cli/search-all.js +9 -2
- package/dist/cli/app-doctor-command.js +18 -10
- package/dist/cli/bot/api-input.js +8 -2
- package/dist/cli/context.d.ts +2 -0
- package/dist/cli/contract-templates.js +2 -1
- package/dist/cli/effects.d.ts +5 -0
- package/dist/cli/effects.js +5 -0
- package/dist/cli/index.d.ts +2 -1
- package/dist/cli/index.js +2 -1
- package/dist/cli/messenger/search-answers.d.ts +5 -1
- package/dist/cli/messenger/search-answers.js +4 -1
- package/dist/cli/messenger/store-maintenance-command.d.ts +2 -0
- package/dist/cli/messenger/store-maintenance-command.js +1 -0
- package/dist/cli/new-file.d.ts +2 -0
- package/dist/cli/new-file.js +13 -0
- package/dist/cli/program.js +3 -0
- package/dist/cli/search-left-out.d.ts +27 -0
- package/dist/cli/search-left-out.js +31 -0
- package/dist/cli/store-recover.d.ts +2 -0
- package/dist/cli/store-recover.js +2 -0
- package/dist/crm/cli/index.js +2 -7
- package/dist/crm/cli/search-all.js +17 -2
- package/dist/crm/index.d.ts +1 -1
- package/dist/crm/index.js +1 -1
- package/dist/crm/writes.d.ts +17 -0
- package/dist/crm/writes.js +31 -16
- package/dist/errors/reasons.js +16 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/meetings/cli/index.d.ts +14 -0
- package/dist/meetings/cli/index.js +18 -6
- package/dist/meetings/hit-query.d.ts +2 -0
- package/dist/meetings/hit-query.js +2 -0
- package/dist/meetings/index.d.ts +2 -2
- package/dist/meetings/index.js +1 -1
- package/dist/meetings/mcp/index.d.ts +15 -15
- package/dist/meetings/pull.d.ts +13 -1
- package/dist/meetings/pull.js +34 -8
- package/dist/meetings/source.d.ts +5 -0
- package/dist/resolve.d.ts +2 -2
- package/dist/resolve.js +4 -3
- package/dist/search/lucene/plain.d.ts +9 -0
- package/dist/search/lucene/plain.js +124 -0
- package/dist/services/events-search.js +2 -0
- package/dist/services/index.d.ts +1 -0
- package/dist/services/index.js +1 -0
- package/dist/services/meeting-hit-search.js +3 -2
- package/dist/services/messages-archive-search.js +3 -0
- package/dist/services/notes-search.js +3 -0
- package/dist/services/search-all.d.ts +4 -1
- package/dist/services/search-all.js +6 -3
- package/dist/speech/local.d.ts +2 -1
- package/dist/speech/local.js +12 -1
- package/dist/speech/recognize.d.ts +2 -0
- package/dist/speech/recognize.js +15 -0
- package/dist/store/damage.js +6 -1
- package/dist/store/decision-requests.d.ts +10 -0
- package/dist/store/decision-requests.js +16 -0
- package/dist/store/health.d.ts +15 -0
- package/dist/store/health.js +31 -1
- package/dist/store/index.d.ts +3 -1
- package/dist/store/index.js +1 -0
- package/dist/store/recover.d.ts +14 -2
- package/dist/store/recover.js +179 -95
- package/dist/store/sqlite/deals.d.ts +3 -1
- package/dist/store/sqlite/deals.js +2 -2
- package/dist/store/sqlite/decision-requests.d.ts +59 -0
- package/dist/store/sqlite/decision-requests.js +111 -0
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/meeting-hit-search.js +3 -2
- package/dist/store/sqlite/migrations.generated.js +12 -0
- package/dist/store/sqlite/schema/decision-requests.d.ts +233 -0
- package/dist/store/sqlite/schema/decision-requests.js +20 -0
- package/dist/store/sqlite/schema.d.ts +1 -0
- package/dist/store/sqlite/schema.js +1 -0
- package/dist/store/store.d.ts +3 -0
- package/dist/store/store.js +5 -0
- package/docs/search/recipes.json +0 -1
- package/package.json +2 -2
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { isCliError } from "@wirecat/cli-base";
|
|
2
|
+
import { parseLucene, walkQuery } from "@wirecat/cli-base/query";
|
|
3
|
+
import { QUERY_FIELDS } from "./registry.js";
|
|
4
|
+
import { MESSAGE_PARSING } from "./types.js";
|
|
5
|
+
// The parser's own mistakes about plain text: a character it read as syntax. Errors about a field's value stay errors.
|
|
6
|
+
const REPAIRED = new Set([
|
|
7
|
+
"query.invalid-syntax",
|
|
8
|
+
"query.unclosed-literal",
|
|
9
|
+
"query.unsupported-operator",
|
|
10
|
+
"query.invalid-escape",
|
|
11
|
+
]);
|
|
12
|
+
// Every source's fields are message fields; after: and before: are refused with a hint to write date:.
|
|
13
|
+
const SEARCH_FIELDS = new Set([...QUERY_FIELDS.map(({ name }) => name), "after", "before"]);
|
|
14
|
+
const FIELD_PREFIX = /^[+-]?([\p{L}\p{N}_.]+)(?:[:=]|[<>]=?)/u;
|
|
15
|
+
const space = (c) => c !== undefined && /[ \t\n\r\u3000]/u.test(c);
|
|
16
|
+
// A quoted word is read as words, whatever it holds; only its quote marks and a trailing backslash need escaping.
|
|
17
|
+
const quoted = (text) => {
|
|
18
|
+
let out = "";
|
|
19
|
+
for (let at = 0; at < text.length; at++) {
|
|
20
|
+
const c = text[at];
|
|
21
|
+
if (c === "\\" && at + 1 < text.length && (text[at + 1] !== "u" || /^u[0-9a-fA-F]{4}/u.test(text.slice(at + 1)))) {
|
|
22
|
+
out += c + text[at + 1];
|
|
23
|
+
at++;
|
|
24
|
+
}
|
|
25
|
+
else
|
|
26
|
+
out += c === '"' || c === "\\" ? `\\${c}` : c;
|
|
27
|
+
}
|
|
28
|
+
return `"${out}"`;
|
|
29
|
+
};
|
|
30
|
+
/** One word as a phrase, so the parser reads none of it as syntax; a known `field:` and modifiers stay outside. */
|
|
31
|
+
const literal = (word, keepParens, fields) => {
|
|
32
|
+
const prefix = FIELD_PREFIX.exec(word);
|
|
33
|
+
const field = prefix && fields.has(prefix[1] ?? "") ? prefix[0] : "";
|
|
34
|
+
const rest = word.slice(field.length);
|
|
35
|
+
const opening = keepParens ? (/^[(+-]*/u.exec(rest)?.[0] ?? "") : "";
|
|
36
|
+
const closing = keepParens ? (/\)*$/u.exec(rest.slice(opening.length))?.[0] ?? "") : "";
|
|
37
|
+
const body = rest.slice(opening.length, rest.length - closing.length);
|
|
38
|
+
if (!body)
|
|
39
|
+
return keepParens ? literal(word, false, fields) : `${field}${quoted(rest)}`;
|
|
40
|
+
return `${field}${opening}${quoted(body)}${closing}`;
|
|
41
|
+
};
|
|
42
|
+
const wordAround = (text, at) => {
|
|
43
|
+
let start = at;
|
|
44
|
+
while (start > 0 && !space(text[start - 1]))
|
|
45
|
+
start--;
|
|
46
|
+
let end = at;
|
|
47
|
+
while (end < text.length && !space(text[end]))
|
|
48
|
+
end++;
|
|
49
|
+
return { start, end };
|
|
50
|
+
};
|
|
51
|
+
const everyWordLiteral = (text, fields) => text.replace(/[^ \t\n\r\u3000]+/gu, (word) => literal(word, false, fields));
|
|
52
|
+
/** Where `text` stops being a search query (-1: somewhere unknown), or the bare words the index holds nothing for. */
|
|
53
|
+
const read = (text, fields) => {
|
|
54
|
+
try {
|
|
55
|
+
const leaves = walkQuery(parseLucene(text, MESSAGE_PARSING).root);
|
|
56
|
+
const unknown = leaves.find(({ field }) => !fields.has(field));
|
|
57
|
+
if (unknown)
|
|
58
|
+
return { at: text.lastIndexOf(unknown.field, unknown.span.start) };
|
|
59
|
+
// An emoji or a lone `^` is no word of the index, so ANDed with the rest it would find nothing at all.
|
|
60
|
+
const wordless = leaves.filter(({ implicit, operator, value }) => implicit && (operator === "term" || operator === "phrase") && !/[\p{L}\p{N}]/u.test(value));
|
|
61
|
+
const words = wordless.length < leaves.length;
|
|
62
|
+
return { wordless: words ? wordless : [], words };
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
const details = isCliError(error) ? error.details : undefined;
|
|
66
|
+
if (!details?.span || !REPAIRED.has(details.reason ?? ""))
|
|
67
|
+
throw error;
|
|
68
|
+
// `word~1` is Lucene's fuzzy search, which the error answers with the prefix search to use instead.
|
|
69
|
+
if (/^~\d/u.test(text.slice(details.span.start)))
|
|
70
|
+
throw error;
|
|
71
|
+
return { at: details.span.start };
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
const without = (text, leaves) => [...leaves]
|
|
75
|
+
.sort((a, b) => b.span.start - a.span.start)
|
|
76
|
+
.reduce((left, { span }) => left.slice(0, span.start) + left.slice(span.end), text)
|
|
77
|
+
.trim();
|
|
78
|
+
/**
|
|
79
|
+
* Free text as the search reads it: a character the query language takes as syntax where it cannot be syntax — the
|
|
80
|
+
* colon of `10:30` or `HH:MM`, a URL's slashes, an unbalanced quote or bracket — is made literal by quoting the word
|
|
81
|
+
* that holds it, a `word:` that names no search field is that word, and a bare emoji or punctuation mark beside other
|
|
82
|
+
* words is dropped. A query that already reads well comes back unchanged, so this can run again on its own output;
|
|
83
|
+
* field queries and Boolean operators keep their meaning. A field's own mistake (`kind:nonsense`) is left for the
|
|
84
|
+
* search to report. `fields` are the names a list of its own (memories: `text`, `scope`) reads as fields.
|
|
85
|
+
*/
|
|
86
|
+
export const plainQuery = (text, fields = SEARCH_FIELDS) => {
|
|
87
|
+
let current = text;
|
|
88
|
+
let whole = false;
|
|
89
|
+
for (let tries = 0; tries <= 64; tries++) {
|
|
90
|
+
let reading;
|
|
91
|
+
try {
|
|
92
|
+
reading = read(current, fields);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return text;
|
|
96
|
+
}
|
|
97
|
+
if ("wordless" in reading) {
|
|
98
|
+
// Punctuation alone (`!!!`) is no search; the parser's error says so better than an empty answer.
|
|
99
|
+
if (!reading.words && current !== text)
|
|
100
|
+
return text;
|
|
101
|
+
if (!reading.wordless.length)
|
|
102
|
+
return current;
|
|
103
|
+
current = without(current, reading.wordless);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
// At the end, the parser is still waiting for a `)` or a term, and no one word is to blame.
|
|
107
|
+
const word = reading.at < 0 || reading.at >= current.length ? undefined : wordAround(current, reading.at);
|
|
108
|
+
const paren = "()".includes(current[reading.at] ?? "");
|
|
109
|
+
const repaired = word
|
|
110
|
+
? current.slice(0, word.start) +
|
|
111
|
+
literal(current.slice(word.start, word.end), !paren, fields) +
|
|
112
|
+
current.slice(word.end)
|
|
113
|
+
: current;
|
|
114
|
+
if (repaired !== current) {
|
|
115
|
+
current = repaired;
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (whole)
|
|
119
|
+
return text;
|
|
120
|
+
whole = true;
|
|
121
|
+
current = everyWordLiteral(text, fields);
|
|
122
|
+
}
|
|
123
|
+
return text;
|
|
124
|
+
};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
2
|
import { kindIn } from "../domain/providers.js";
|
|
3
3
|
import { meaningFloor } from "../embeddings/models.js";
|
|
4
|
+
import { plainQuery } from "../search/lucene/plain.js";
|
|
4
5
|
import { questionLookup, questionText } from "../search/question-plan.js";
|
|
5
6
|
import { excerpt } from "./excerpt.js";
|
|
6
7
|
import { localModel, RRF_K, storeQuery, withLocal } from "./notes-search.js";
|
|
@@ -55,6 +56,7 @@ const keyOf = ({ event }) => event.eventSeriesId === null ? `e${event.id}` : `s$
|
|
|
55
56
|
export const searchEvents = async (store, query, { limit = 20, offset = 0, accounts, exact, discover, newest, timezone, signal, candidates, env, command, embedders, } = {}) => {
|
|
56
57
|
if (!query.trim())
|
|
57
58
|
throw new CliError("validation_error", "say what to find in the events");
|
|
59
|
+
query = plainQuery(query);
|
|
58
60
|
const asked = discover && !exact && !newest ? questionLookup(query) : undefined;
|
|
59
61
|
const { root, stemmer } = await storeQuery(store, asked ?? query, {
|
|
60
62
|
...(exact ? { exact: true } : {}),
|
package/dist/services/index.d.ts
CHANGED
|
@@ -152,6 +152,7 @@ export type Override = (base: Services, deps: ServiceDeps) => Partial<Services>;
|
|
|
152
152
|
/** The shared services, with the messenger's `services` override applied — commands and MCP tools alike. */
|
|
153
153
|
export declare const servicesFor: (deps: ServiceDeps) => Services;
|
|
154
154
|
export { entriesOfList, type ListContext, type ListedEntry } from "../search/account-list.js";
|
|
155
|
+
export { plainQuery } from "../search/lucene/plain.js";
|
|
155
156
|
export { FIELD_VERSION, QUERY_FIELDS, QUERY_OPERATORS, validateAst } from "../search/lucene/registry.js";
|
|
156
157
|
export { QUERY_LIMITS, QUERY_VERSION } from "../search/lucene/types.js";
|
|
157
158
|
export { questionLookup } from "../search/question-plan.js";
|
package/dist/services/index.js
CHANGED
|
@@ -117,6 +117,7 @@ export const servicesFor = (deps) => {
|
|
|
117
117
|
return deps.messenger.services ? { ...base, ...deps.messenger.services(base, deps) } : base;
|
|
118
118
|
};
|
|
119
119
|
export { entriesOfList } from "../search/account-list.js";
|
|
120
|
+
export { plainQuery } from "../search/lucene/plain.js";
|
|
120
121
|
export { FIELD_VERSION, QUERY_FIELDS, QUERY_OPERATORS, validateAst } from "../search/lucene/registry.js";
|
|
121
122
|
export { QUERY_LIMITS, QUERY_VERSION } from "../search/lucene/types.js";
|
|
122
123
|
export { questionLookup } from "../search/question-plan.js";
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
-
import { liftMeetingFields } from "../meetings/index.js";
|
|
2
|
+
import { liftMeetingFields, MEETING_FIELD_NAMES } from "../meetings/index.js";
|
|
3
|
+
import { plainQuery } from "../search/lucene/plain.js";
|
|
3
4
|
/** Each batch commits on its own, so a search cut short by its deadline keeps the progress it made. */
|
|
4
5
|
export const refreshMeetingIndex = async (meetings, accountId, signal) => {
|
|
5
6
|
let before = Number.POSITIVE_INFINITY;
|
|
@@ -55,7 +56,7 @@ export const resolveMeetingSelection = async (store, request) => {
|
|
|
55
56
|
return { input, selection };
|
|
56
57
|
};
|
|
57
58
|
export const searchMeetingHits = async (store, query, request, options = {}) => {
|
|
58
|
-
const lifted = liftMeetingFields(query, request);
|
|
59
|
+
const lifted = liftMeetingFields(plainQuery(query, MEETING_FIELD_NAMES), request);
|
|
59
60
|
const { input, selection } = await resolveMeetingSelection(store, lifted.request);
|
|
60
61
|
if (options.refreshIndex !== false)
|
|
61
62
|
await refreshMeetingIndex(store.meetings, input.accountId, input.signal);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
2
|
import { parseLocator } from "../domain/locator.js";
|
|
3
|
+
import { plainQuery } from "../search/lucene/plain.js";
|
|
3
4
|
import { isQueryLimit } from "../search/lucene/types.js";
|
|
4
5
|
import { TOTAL_CAP, totalOf } from "../search/total.js";
|
|
5
6
|
import { discoveryRequest, searchDiscovery } from "./messages-discovery.js";
|
|
@@ -46,6 +47,8 @@ export const MAX_SEARCH_OFFSET = 1000;
|
|
|
46
47
|
* the next page starts. A page is the hits up to `offset + limit` read again and cut, so deep pages cost more.
|
|
47
48
|
*/
|
|
48
49
|
export const searchStore = async (store, account, request, messenger = {}, meaning, rerank) => {
|
|
50
|
+
if (request.text !== undefined)
|
|
51
|
+
request = { ...request, text: plainQuery(request.text) };
|
|
49
52
|
const offset = request.offset ?? 0;
|
|
50
53
|
if (!Number.isInteger(offset) || offset < 0 || offset > MAX_SEARCH_OFFSET)
|
|
51
54
|
throw new CliError("validation_error", `offset takes a whole number from 0 to ${MAX_SEARCH_OFFSET}`);
|
|
@@ -7,6 +7,7 @@ import { DEFAULT_TEXT_MODEL, meaningFloor, textModel, vectorModelKey } from "../
|
|
|
7
7
|
import { DEFAULT_IMAGE_MODEL, imageModel } from "../images/picture/models.js";
|
|
8
8
|
import { entriesOfList, fitting } from "../search/account-list.js";
|
|
9
9
|
import { fieldsOfQuery as fieldsOf, meaningWords } from "../search/lucene/meaning-parts.js";
|
|
10
|
+
import { plainQuery } from "../search/lucene/plain.js";
|
|
10
11
|
import { validateFields } from "../search/lucene/registry.js";
|
|
11
12
|
import { hasStems } from "../search/lucene/resolved.js";
|
|
12
13
|
import { isQueryLimit, SEARCH_QUERY } from "../search/lucene/types.js";
|
|
@@ -326,6 +327,7 @@ const notesTotal = async (store, text, { exact, scope, shown, hasMore, }, others
|
|
|
326
327
|
* of `filter` holds for every hit, found by words or by meaning; a query of fields alone is not searched by meaning.
|
|
327
328
|
*/
|
|
328
329
|
export const searchNotes = async (store, query, { limit = 20, offset = 0, tag, filter: expression, folderIds, withInternal, source: given, exact = false, discover = false, timezone, env, command, embedders, pictures: withPictures = false, pictureLimit = 5, pictureEmbedder, } = {}) => {
|
|
330
|
+
query = plainQuery(query);
|
|
329
331
|
const typed = noteSourceOfQuery(query);
|
|
330
332
|
const source = given ?? typed.source;
|
|
331
333
|
const rest = typed.source !== undefined && typed.source === source ? typed.rest : query;
|
|
@@ -517,6 +519,7 @@ export const notesScopeOf = (accounts) => {
|
|
|
517
519
|
* — and every entry naming none of them in `skipped`. Without a list, every notes account `type` leaves in.
|
|
518
520
|
*/
|
|
519
521
|
export const searchNotesOf = async (store, account, text, { accounts: list, app, ...query }) => {
|
|
522
|
+
text = plainQuery(text);
|
|
520
523
|
const own = app?.command ?? query.command;
|
|
521
524
|
const what = `${own === undefined ? "" : `${own} `}search notes`;
|
|
522
525
|
const held = [
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type ErrorCode } from "@wirecat/cli-base";
|
|
2
2
|
import { type HitFile } from "../domain/attachments.js";
|
|
3
|
+
import type { DealKind } from "../domain/deals.js";
|
|
3
4
|
import { type MailFields } from "../domain/models.js";
|
|
4
5
|
import type { MessengerTraits } from "../ports/traits.js";
|
|
5
6
|
import type { AccountKey, MessageStore } from "../store/store.js";
|
|
@@ -104,6 +105,8 @@ export interface SearchAllRequest {
|
|
|
104
105
|
signal?: AbortSignal;
|
|
105
106
|
/** The accounts `--source` chose, per kind; a kind left out reads every account of its own. */
|
|
106
107
|
scope?: Partial<Record<SearchedResource, AccountKey[]>>;
|
|
108
|
+
/** The CRM kinds `crm` reads; absent, deals and leads. */
|
|
109
|
+
crmKinds?: readonly DealKind[];
|
|
107
110
|
}
|
|
108
111
|
export type SearchAllMessenger = Partial<Pick<MessengerTraits, "savedChatId" | "app">> & {
|
|
109
112
|
/**
|
|
@@ -127,4 +130,4 @@ export declare const crmAccounts: (store: MessageStore) => Promise<AccountKey[]>
|
|
|
127
130
|
* server, as `search messages` asks it — each list best first, merged by reciprocal rank so no
|
|
128
131
|
* resource's own scores have to be compared with another's. Events are read only when the store holds a calendar.
|
|
129
132
|
*/
|
|
130
|
-
export declare const searchAll: (store: MessageStore, account: AccountKey,
|
|
133
|
+
export declare const searchAll: (store: MessageStore, account: AccountKey, asked: SearchAllRequest, messenger?: SearchAllMessenger, searchMessages?: (query: SearchQuery) => Promise<SearchFound>, meaning?: MeaningLane) => Promise<SearchAllFound>;
|
|
@@ -6,6 +6,7 @@ import { senderIsMe } from "../domain/models.js";
|
|
|
6
6
|
import { INTERNAL_NOTES, kindIn } from "../domain/providers.js";
|
|
7
7
|
import { runEmbedders } from "../embeddings/embed.js";
|
|
8
8
|
import { DEFAULT_TEXT_MODEL } from "../embeddings/models.js";
|
|
9
|
+
import { plainQuery } from "../search/lucene/plain.js";
|
|
9
10
|
import { MESSAGE_PARSING, SEARCH_QUERY } from "../search/lucene/types.js";
|
|
10
11
|
import { planQuestion, questionLookup } from "../search/question-plan.js";
|
|
11
12
|
import { calendarAccounts, searchEvents } from "./events-search.js";
|
|
@@ -54,9 +55,10 @@ export const crmAccounts = async (store) => (await store.accounts.accounts()).fi
|
|
|
54
55
|
* server, as `search messages` asks it — each list best first, merged by reciprocal rank so no
|
|
55
56
|
* resource's own scores have to be compared with another's. Events are read only when the store holds a calendar.
|
|
56
57
|
*/
|
|
57
|
-
export const searchAll = async (store, account,
|
|
58
|
-
if (!
|
|
58
|
+
export const searchAll = async (store, account, asked, messenger = {}, searchMessages = (query) => searchStore(store, account, query, messenger), meaning) => {
|
|
59
|
+
if (!asked.text.trim())
|
|
59
60
|
throw new CliError("validation_error", "say what to find");
|
|
61
|
+
const request = { ...asked, text: plainQuery(asked.text) };
|
|
60
62
|
const offset = request.offset ?? 0;
|
|
61
63
|
if (!Number.isInteger(offset) || offset < 0 || offset > MAX_SEARCH_OFFSET)
|
|
62
64
|
throw new CliError("validation_error", `offset takes a whole number from 0 to ${MAX_SEARCH_OFFSET}`);
|
|
@@ -257,6 +259,7 @@ export const searchAll = async (store, account, request, messenger = {}, searchM
|
|
|
257
259
|
const found = await store.deals.find({
|
|
258
260
|
words,
|
|
259
261
|
anyWord: anyWord || discover,
|
|
262
|
+
...(request.crmKinds === undefined ? {} : { kinds: request.crmKinds }),
|
|
260
263
|
limit: Math.min(window + 1, 500),
|
|
261
264
|
...(chosen === undefined ? {} : { accounts: chosen }),
|
|
262
265
|
});
|
|
@@ -292,7 +295,7 @@ export const searchAll = async (store, account, request, messenger = {}, searchM
|
|
|
292
295
|
const ordered = oneList(lists, cosines);
|
|
293
296
|
const more = hasMore || ordered.length > window;
|
|
294
297
|
return {
|
|
295
|
-
query:
|
|
298
|
+
query: asked.text,
|
|
296
299
|
items: ordered.slice(offset, window),
|
|
297
300
|
hasMore: more,
|
|
298
301
|
...(more && window <= MAX_SEARCH_OFFSET ? { nextOffset: window } : {}),
|
package/dist/speech/local.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ export interface LocalSpeechRecognitionModel {
|
|
|
13
13
|
export interface LocalSpeechBackend {
|
|
14
14
|
recognize(pcm: Float32Array): string;
|
|
15
15
|
pieces?(pcm: Float32Array): TimedText[];
|
|
16
|
+
piecesUntil?(pcm: Float32Array, signal: AbortSignal): Promise<TimedText[]>;
|
|
16
17
|
free(): void;
|
|
17
18
|
}
|
|
18
19
|
export interface LocalSpeechRecognizer extends LocalSpeechRecognitionModel {
|
|
@@ -34,6 +35,6 @@ export declare const localSpeechRecognitionModel: (id: string) => Readonly<Local
|
|
|
34
35
|
* A whole recording, one channel of it, cut at pauses by the voice detector: each piece's text with where it lies,
|
|
35
36
|
* in seconds. Two channels heard this way merge into a dialogue by `start`. Existing installed models only.
|
|
36
37
|
*/
|
|
37
|
-
export declare const recognizeLocalPieces: (id: string, audio: Pcm, options?: Pick<LocalSpeechRecognizerOptions, "directory" | "env" | "open">) => Promise<TimedText[]>;
|
|
38
|
+
export declare const recognizeLocalPieces: (id: string, audio: Pcm, options?: Pick<LocalSpeechRecognizerOptions, "directory" | "env" | "open" | "signal">) => Promise<TimedText[]>;
|
|
38
39
|
/** Existing installed models only. Synchronous inference cancels between bounded windows. */
|
|
39
40
|
export declare const openLocalSpeechRecognizer: (id: string, input?: LocalSpeechRecognizerOptions) => Promise<LocalSpeechRecognizer>;
|
package/dist/speech/local.js
CHANGED
|
@@ -47,7 +47,18 @@ export const recognizeLocalPieces = async (id, audio, options = {}) => {
|
|
|
47
47
|
try {
|
|
48
48
|
if (!engine.pieces)
|
|
49
49
|
throw new CliError("configuration_error", "this speech backend gives no timed pieces");
|
|
50
|
-
|
|
50
|
+
const pcm = toModelRate(audio.samples, audio.rate);
|
|
51
|
+
const { signal } = options;
|
|
52
|
+
if (!signal)
|
|
53
|
+
return engine.pieces(pcm);
|
|
54
|
+
cancelled(signal);
|
|
55
|
+
try {
|
|
56
|
+
return engine.piecesUntil ? await engine.piecesUntil(pcm, signal) : engine.pieces(pcm);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
cancelled(signal);
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
51
62
|
}
|
|
52
63
|
finally {
|
|
53
64
|
engine.free();
|
|
@@ -10,6 +10,8 @@ export interface Recognizer {
|
|
|
10
10
|
recognize(pcm: Float32Array): string;
|
|
11
11
|
/** Each stretch of speech the voice detector cut, with where it lies; the same input as `recognize`. */
|
|
12
12
|
pieces?(pcm: Float32Array): TimedText[];
|
|
13
|
+
/** `pieces`, giving the event loop a turn between pieces, so `signal` can stop a long recording between two. */
|
|
14
|
+
piecesUntil?(pcm: Float32Array, signal: AbortSignal): Promise<TimedText[]>;
|
|
13
15
|
free(): void;
|
|
14
16
|
}
|
|
15
17
|
export declare const SAMPLE_RATE = 16000;
|
package/dist/speech/recognize.js
CHANGED
|
@@ -152,11 +152,26 @@ export const openRecognizer = (model, path, vadModel) => {
|
|
|
152
152
|
});
|
|
153
153
|
return heard;
|
|
154
154
|
};
|
|
155
|
+
// Decoding is synchronous: without a turn of the event loop between pieces no abort could ever be seen.
|
|
156
|
+
const piecesUntil = async (pcm, signal) => {
|
|
157
|
+
const spans = [];
|
|
158
|
+
cut(vad, pcm, (span) => spans.push(span));
|
|
159
|
+
const heard = [];
|
|
160
|
+
for (const { start, end, samples } of spans) {
|
|
161
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
162
|
+
signal.throwIfAborted();
|
|
163
|
+
const text = piece(samples);
|
|
164
|
+
if (text)
|
|
165
|
+
heard.push({ start, end, text });
|
|
166
|
+
}
|
|
167
|
+
return heard;
|
|
168
|
+
};
|
|
155
169
|
return {
|
|
156
170
|
recognize: (pcm) => pieces(pcm)
|
|
157
171
|
.map(({ text }) => text)
|
|
158
172
|
.join(" "),
|
|
159
173
|
pieces,
|
|
174
|
+
piecesUntil,
|
|
160
175
|
free: () => {
|
|
161
176
|
vad.free();
|
|
162
177
|
engine.free();
|
package/dist/store/damage.js
CHANGED
|
@@ -17,13 +17,15 @@ export const explainDamage = (health, command) => {
|
|
|
17
17
|
const sources = tables.filter((table) => !isDerivedTable(table, indexNames));
|
|
18
18
|
const derived = [...new Set([...tables.filter((table) => isDerivedTable(table, indexNames)), ...badIndexes])];
|
|
19
19
|
const unopened = health.error !== undefined;
|
|
20
|
+
const json = (health.invalidJson ?? []).map(({ table, column }) => `${table}.${column}`);
|
|
20
21
|
const what = unopened
|
|
21
22
|
? `the store file cannot be opened: ${health.error}`
|
|
22
23
|
: health.checked === "quick"
|
|
23
24
|
? "the store file's header or schema is damaged"
|
|
24
25
|
: `the store file is damaged: ${health.problems ?? 0} problems` +
|
|
25
26
|
(sources.length ? ` in the data of ${named(sources)}` : "") +
|
|
26
|
-
(derived.length ? `${sources.length ? ", and" : " in"} the search data of ${named(derived)}` : "")
|
|
27
|
+
(derived.length ? `${sources.length ? ", and" : " in"} the search data of ${named(derived)}` : "") +
|
|
28
|
+
(json.length ? `; values that are not valid JSON in ${named(json)}` : "");
|
|
27
29
|
const impact = [
|
|
28
30
|
...(sources.length
|
|
29
31
|
? [`some rows of ${named(sources)} cannot be read; a recovery keeps every row it can read and names the rest`]
|
|
@@ -31,6 +33,9 @@ export const explainDamage = (health, command) => {
|
|
|
31
33
|
...(derived.length
|
|
32
34
|
? [`searches may miss results or fail; ${named(derived)} hold nothing that is not elsewhere, and are rebuilt`]
|
|
33
35
|
: []),
|
|
36
|
+
...(json.length
|
|
37
|
+
? [`a read of a row with a broken JSON value fails ("malformed JSON"); a recovery clears those values`]
|
|
38
|
+
: []),
|
|
34
39
|
"reads that do not touch a damaged page work; a write that touches one fails until the store is recovered",
|
|
35
40
|
];
|
|
36
41
|
return {
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare const DECISION_ACTIONS: readonly ["confirm", "reject", "ask-confirm", "ask-reject", "back", "later"];
|
|
2
|
+
export type DecisionAction = (typeof DECISION_ACTIONS)[number];
|
|
3
|
+
/** Seventy-two hours: a press after that finds nothing to take. */
|
|
4
|
+
export declare const DECISION_TTL_MS: number;
|
|
5
|
+
export declare const CALLBACK_PREFIX = "wcr1:";
|
|
6
|
+
export declare const isDecisionToken: (value: unknown) => value is string;
|
|
7
|
+
/** The 27 bytes a button carries: Telegram allows 64. */
|
|
8
|
+
export declare const callbackDataOf: (token: string) => string;
|
|
9
|
+
/** The token in a button's data, or `undefined` for anything else; the data is only ever looked up, never read further. */
|
|
10
|
+
export declare const parseCallbackData: (data: unknown) => string | undefined;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export const DECISION_ACTIONS = ["confirm", "reject", "ask-confirm", "ask-reject", "back", "later"];
|
|
2
|
+
/** Seventy-two hours: a press after that finds nothing to take. */
|
|
3
|
+
export const DECISION_TTL_MS = 72 * 60 * 60 * 1000;
|
|
4
|
+
export const CALLBACK_PREFIX = "wcr1:";
|
|
5
|
+
// 16 random bytes in base64url are 22 characters, and the last one carries 2 data bits: only these four can end a token.
|
|
6
|
+
const TOKEN = /^[A-Za-z0-9_-]{21}[AQgw]$/;
|
|
7
|
+
const CALLBACK = /^wcr1:([A-Za-z0-9_-]{21}[AQgw])$/;
|
|
8
|
+
export const isDecisionToken = (value) => typeof value === "string" && TOKEN.test(value);
|
|
9
|
+
/** The 27 bytes a button carries: Telegram allows 64. */
|
|
10
|
+
export const callbackDataOf = (token) => {
|
|
11
|
+
if (!isDecisionToken(token))
|
|
12
|
+
throw new TypeError("not a decision token");
|
|
13
|
+
return `${CALLBACK_PREFIX}${token}`;
|
|
14
|
+
};
|
|
15
|
+
/** The token in a button's data, or `undefined` for anything else; the data is only ever looked up, never read further. */
|
|
16
|
+
export const parseCallbackData = (data) => typeof data === "string" ? CALLBACK.exec(data)?.[1] : undefined;
|
package/dist/store/health.d.ts
CHANGED
|
@@ -27,8 +27,23 @@ export interface StoreHealth {
|
|
|
27
27
|
/** Lines `quick_check` gave in all, capped at `QUICK_CHECK_LIMIT`. */
|
|
28
28
|
problems?: number;
|
|
29
29
|
searchIndexes?: SearchIndexHealth[];
|
|
30
|
+
/** Deep only: values the tools read as JSON that SQLite's JSON functions refuse, so a read of the row fails. */
|
|
31
|
+
invalidJson?: InvalidJson[];
|
|
30
32
|
ms: number;
|
|
31
33
|
}
|
|
34
|
+
export interface InvalidJson {
|
|
35
|
+
table: string;
|
|
36
|
+
column: string;
|
|
37
|
+
rows: number;
|
|
38
|
+
/** The column may not be NULL, so a recovery drops the row instead of clearing the value. */
|
|
39
|
+
required: boolean;
|
|
40
|
+
}
|
|
41
|
+
export declare const jsonColumns: (database: CacheDatabase) => {
|
|
42
|
+
table: string;
|
|
43
|
+
column: string;
|
|
44
|
+
required: boolean;
|
|
45
|
+
}[];
|
|
46
|
+
export declare const invalidJson: (database: CacheDatabase) => InvalidJson[];
|
|
32
47
|
export declare const QUICK_CHECK_LIMIT = 10000;
|
|
33
48
|
/** What `doctor` checks by default, said where it answers. */
|
|
34
49
|
export declare const QUICK_HEALTH_CHECKS = "the file header, its size against its page count, and the schema's own pages";
|
package/dist/store/health.js
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
1
1
|
import { existsSync, statSync } from "node:fs";
|
|
2
2
|
import { openSqlite } from "./sqlite/open.js";
|
|
3
|
+
/** Besides every `metadata` column: the TEXT columns the tools read with SQLite's JSON functions or JSON.parse. */
|
|
4
|
+
const JSON_COLUMNS = {
|
|
5
|
+
accounts: ["settings"],
|
|
6
|
+
account_identities: ["mail_signals"],
|
|
7
|
+
bot_updates: ["payload"],
|
|
8
|
+
documents: ["front_matter"],
|
|
9
|
+
emails: ["headers"],
|
|
10
|
+
meeting_participants: ["sessions"],
|
|
11
|
+
messages: ["mentions", "reply_to"],
|
|
12
|
+
proposed_actions: ["payload", "result"],
|
|
13
|
+
searches: ["params"],
|
|
14
|
+
tag_consolidations: ["source_member_ids", "survivor_member_ids"],
|
|
15
|
+
task_events: ["changes"],
|
|
16
|
+
};
|
|
17
|
+
export const jsonColumns = (database) => database
|
|
18
|
+
.prepare(`SELECT m.name AS "table", c.name AS "column", c."notnull" AS required FROM sqlite_master m, pragma_table_info(m.name) c
|
|
19
|
+
WHERE m.type = 'table' AND m.sql NOT LIKE 'CREATE VIRTUAL%' ORDER BY 1, 2`)
|
|
20
|
+
.all()
|
|
21
|
+
.map((row) => ({ table: String(row.table), column: String(row.column), required: Number(row.required) === 1 }))
|
|
22
|
+
.filter(({ table, column }) => column === "metadata" || JSON_COLUMNS[table]?.includes(column));
|
|
23
|
+
export const invalidJson = (database) => jsonColumns(database)
|
|
24
|
+
.map((one) => ({
|
|
25
|
+
...one,
|
|
26
|
+
rows: Number(database
|
|
27
|
+
.prepare(`SELECT count(*) AS n FROM "${one.table}" WHERE "${one.column}" IS NOT NULL AND NOT json_valid("${one.column}")`)
|
|
28
|
+
.get()?.n),
|
|
29
|
+
}))
|
|
30
|
+
.filter(({ rows }) => rows > 0);
|
|
3
31
|
export const QUICK_CHECK_LIMIT = 10_000;
|
|
4
32
|
/** What `doctor` checks by default, said where it answers. */
|
|
5
33
|
export const QUICK_HEALTH_CHECKS = "the file header, its size against its page count, and the schema's own pages";
|
|
@@ -153,12 +181,14 @@ export const storeHealth = async (path, { deep = false } = {}) => {
|
|
|
153
181
|
const lines = checkLines(database);
|
|
154
182
|
const pagesOk = lines.length === 1 && lines[0] === "ok";
|
|
155
183
|
const indexes = searchIndexHealth(database);
|
|
184
|
+
const json = pagesOk ? invalidJson(database) : [];
|
|
156
185
|
return done({
|
|
157
|
-
ok: pagesOk && problems.length === 0 && indexes.every((index) => index.ok),
|
|
186
|
+
ok: pagesOk && problems.length === 0 && indexes.every((index) => index.ok) && json.length === 0,
|
|
158
187
|
file,
|
|
159
188
|
problems: pagesOk ? 0 : lines.length,
|
|
160
189
|
damagedTables: pagesOk ? [] : damagedTables(database, lines),
|
|
161
190
|
searchIndexes: indexes,
|
|
191
|
+
invalidJson: json,
|
|
162
192
|
});
|
|
163
193
|
}
|
|
164
194
|
catch (error) {
|
package/dist/store/index.d.ts
CHANGED
|
@@ -10,13 +10,14 @@ export { PAYMENT_DIRECTIONS, PAYMENT_STATES, type Payment, paymentTitle, validat
|
|
|
10
10
|
export { CLOSED_STATES, isClosedState, PRIORITY_LABELS, type PriorityLabel, priorityLabel, priorityOf, priorityOption, TASK_STATES, type TaskState, } from "../tasks/index.js";
|
|
11
11
|
export type { AccountMail, AccountMeetings, AccountStore } from "./account-store.js";
|
|
12
12
|
export { type DamageExplanation, explainDamage } from "./damage.js";
|
|
13
|
+
export { CALLBACK_PREFIX, callbackDataOf, DECISION_ACTIONS, DECISION_TTL_MS, type DecisionAction, isDecisionToken, parseCallbackData, } from "./decision-requests.js";
|
|
13
14
|
export { assertMayDecide, DEFAULT_DECISION_POLICY, type Decider, type DecisionPolicy, isOwnerOnlyKind, mayDecide, type Proposer, type Refusal, } from "./decisions.js";
|
|
14
15
|
export type { DocumentTransferOptions, DocumentTransferPreview, DocumentTransferReceipt, } from "./document-transfer/index.js";
|
|
15
16
|
export { applyDocumentTransfer, previewDocumentTransfer } from "./document-transfer/index.js";
|
|
16
17
|
export type { CacheDatabase, CacheStatement, OpenDatabase, SqlValue } from "./driver.js";
|
|
17
18
|
export { PRAGMAS } from "./driver.js";
|
|
18
19
|
export { EVIDENCE_FINDINGS_KIND, type EvidenceFindingsBatch, type EvidenceFindingsDecider, type EvidenceFindingsReceipt, type EvidenceFindingsStore, validateEvidenceFindings, } from "./evidence-findings.js";
|
|
19
|
-
export { type DamagedTable, QUICK_HEALTH_CHECKS, type SearchIndexHealth, type StoreHealth, storeHealth, } from "./health.js";
|
|
20
|
+
export { type DamagedTable, type InvalidJson, QUICK_HEALTH_CHECKS, type SearchIndexHealth, type StoreHealth, storeHealth, } from "./health.js";
|
|
20
21
|
export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
|
|
21
22
|
export { MAIL_FINDINGS_KIND, type MailFindingsBatch, type MailFindingsCheck, type MailFindingsStore, } from "./mail-findings.js";
|
|
22
23
|
export type { MeetingFindingsBatch, MeetingFindingsStore } from "./meeting-findings.js";
|
|
@@ -38,6 +39,7 @@ export { CATALOG_QUERY } from "./sqlite/catalog.js";
|
|
|
38
39
|
export type { ChatMetadata } from "./sqlite/chats.js";
|
|
39
40
|
export { type CrmCopies, type CrmSaved, type CrmSkipped, crmIdentityId } from "./sqlite/crm.js";
|
|
40
41
|
export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, } from "./sqlite/deals.js";
|
|
42
|
+
export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
|
|
41
43
|
export type { Email, EmailAddress, EmailAttachment, EmailFacts, EmailFilter, EmailInput, EmailInThread, EmailLocationInput, EmailRecipient, EmailRef, EmailThread, EmailVectorHit, FolderEmail, Mailbox, MailboxInput, MailFilter, MailStore, PartialEmail, SenderScore, ThreadDetails, ThreadSave, } from "./sqlite/emails.js";
|
|
42
44
|
export { EVENT_FIELDS, type EventChunkToEmbed, type EventHit, type EventQuery, type EventSearch, type NearestEvent, } from "./sqlite/event-search.js";
|
|
43
45
|
export type { EvidenceSource } from "./sqlite/evidence-sources.js";
|
package/dist/store/index.js
CHANGED
|
@@ -4,6 +4,7 @@ export { note } from "../entities/note.js";
|
|
|
4
4
|
export { PAYMENT_DIRECTIONS, PAYMENT_STATES, paymentTitle, validatePayment } from "../meetings/index.js";
|
|
5
5
|
export { CLOSED_STATES, isClosedState, PRIORITY_LABELS, priorityLabel, priorityOf, priorityOption, TASK_STATES, } from "../tasks/index.js";
|
|
6
6
|
export { explainDamage } from "./damage.js";
|
|
7
|
+
export { CALLBACK_PREFIX, callbackDataOf, DECISION_ACTIONS, DECISION_TTL_MS, isDecisionToken, parseCallbackData, } from "./decision-requests.js";
|
|
7
8
|
export { assertMayDecide, DEFAULT_DECISION_POLICY, isOwnerOnlyKind, mayDecide, } from "./decisions.js";
|
|
8
9
|
export { applyDocumentTransfer, previewDocumentTransfer } from "./document-transfer/index.js";
|
|
9
10
|
export { PRAGMAS } from "./driver.js";
|
package/dist/store/recover.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { CacheDatabase } from "./driver.js";
|
|
2
|
-
import { type StoreHealth } from "./health.js";
|
|
2
|
+
import { type InvalidJson, type StoreHealth } from "./health.js";
|
|
3
3
|
/** `contentless_delete`, which every word index uses, came in SQLite 3.43. */
|
|
4
4
|
export declare const SQLITE3_MINIMUM: readonly [3, 43, 0];
|
|
5
5
|
export declare const sqlite3Program: (program?: string) => {
|
|
@@ -9,7 +9,12 @@ export declare const sqlite3Program: (program?: string) => {
|
|
|
9
9
|
};
|
|
10
10
|
/** The WireCat timers still scheduled: each may open the store while it is being recovered. Linux only. */
|
|
11
11
|
export declare const activeTimers: () => string[] | undefined;
|
|
12
|
-
/**
|
|
12
|
+
/** The process recovering the store now, from the lock file it keeps beside it; a lock whose process ended is none. */
|
|
13
|
+
export declare const runningRecovery: (path: string) => number | null;
|
|
14
|
+
/**
|
|
15
|
+
* Processes that have any of the store's files open, by PID and program name, never their arguments, and the one
|
|
16
|
+
* recovering it.
|
|
17
|
+
*/
|
|
13
18
|
export declare const storeHolders: (path: string) => {
|
|
14
19
|
pid: number;
|
|
15
20
|
name: string;
|
|
@@ -53,6 +58,11 @@ export interface DanglingRows {
|
|
|
53
58
|
}
|
|
54
59
|
/** Rows that point at a row the store does not hold: after a recovery, mostly rows that could not be read. */
|
|
55
60
|
export declare const danglingRows: (database: CacheDatabase) => DanglingRows[];
|
|
61
|
+
/**
|
|
62
|
+
* Sets each value the tools read as JSON that SQLite's JSON functions refuse to NULL, or drops its row where the
|
|
63
|
+
* column may not be NULL: `.recover` copies a damaged value that still reads, and a JSON read of it fails.
|
|
64
|
+
*/
|
|
65
|
+
export declare const clearInvalidJson: (database: CacheDatabase) => InvalidJson[];
|
|
56
66
|
export interface LostRows {
|
|
57
67
|
table: string;
|
|
58
68
|
before: number | null;
|
|
@@ -69,6 +79,8 @@ export interface Recovery {
|
|
|
69
79
|
*/
|
|
70
80
|
lost: LostRows[];
|
|
71
81
|
dangling: DanglingRows[];
|
|
82
|
+
/** Values that were not valid JSON: set to NULL, or the row dropped where `required`. */
|
|
83
|
+
invalidJson: InvalidJson[];
|
|
72
84
|
mailToFetch: {
|
|
73
85
|
account: string;
|
|
74
86
|
emails: number;
|