@wirecat/cli-core 0.687.0 → 0.688.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.
Files changed (67) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/documents/words.d.ts +1 -1
  4. package/dist/cli/envelope.js +2 -3
  5. package/dist/cli/meeting-batch.js +5 -1
  6. package/dist/cli/meeting-passage-text.d.ts +1 -1
  7. package/dist/cli/meeting-passage-text.js +3 -5
  8. package/dist/cli/messenger/conversations-command.js +4 -0
  9. package/dist/cli/messenger/messages-search-command.js +6 -1
  10. package/dist/cli/messenger/search-answers.js +2 -0
  11. package/dist/cli/search-left-out.d.ts +3 -0
  12. package/dist/cli/search-left-out.js +12 -0
  13. package/dist/cli/store-settings.js +23 -4
  14. package/dist/cli/untrusted-marks.d.ts +2 -0
  15. package/dist/cli/untrusted-marks.js +6 -0
  16. package/dist/crm/cli/files.d.ts +68 -0
  17. package/dist/crm/cli/files.js +616 -0
  18. package/dist/crm/cli/index.d.ts +1 -0
  19. package/dist/crm/cli/index.js +3 -0
  20. package/dist/crm/cli/search-all.js +3 -2
  21. package/dist/crm/file-fetch.d.ts +15 -0
  22. package/dist/crm/file-fetch.js +61 -0
  23. package/dist/crm/index.d.ts +1 -0
  24. package/dist/crm/index.js +1 -0
  25. package/dist/crm/testing/files-contract.d.ts +17 -0
  26. package/dist/crm/testing/files-contract.js +142 -0
  27. package/dist/crm/testing/index.d.ts +1 -0
  28. package/dist/crm/testing/index.js +1 -0
  29. package/dist/crm/testing/source.d.ts +5 -0
  30. package/dist/crm/testing/source.js +3 -1
  31. package/dist/entities/hit.d.ts +3 -3
  32. package/dist/entities/hit.js +14 -3
  33. package/dist/entities/index.d.ts +1 -1
  34. package/dist/errors/reasons.js +12 -1
  35. package/dist/files/safe-name.d.ts +2 -1
  36. package/dist/files/safe-name.js +21 -3
  37. package/dist/meetings/mcp/passage.d.ts +6 -2
  38. package/dist/meetings/mcp/passage.js +7 -3
  39. package/dist/search/respell.d.ts +10 -0
  40. package/dist/search/respell.js +63 -0
  41. package/dist/search/stem.d.ts +16 -3
  42. package/dist/search/stem.js +32 -4
  43. package/dist/services/embeddings-search.js +169 -141
  44. package/dist/services/embeddings.d.ts +8 -0
  45. package/dist/services/messages-archive-search.js +55 -3
  46. package/dist/services/messages-search.d.ts +2 -1
  47. package/dist/services/messages-search.js +19 -7
  48. package/dist/services/messages.d.ts +8 -0
  49. package/dist/services/metadata.d.ts +1 -1
  50. package/dist/services/named-chat.d.ts +20 -0
  51. package/dist/services/named-chat.js +63 -0
  52. package/dist/services/search-all.d.ts +7 -2
  53. package/dist/services/search-all.js +35 -1
  54. package/dist/store/exports.d.ts +1 -1
  55. package/dist/store/exports.js +1 -1
  56. package/dist/store/search-index.d.ts +2 -0
  57. package/dist/store/search-index.js +1 -0
  58. package/dist/store/sqlite/crm-files.d.ts +3 -0
  59. package/dist/store/sqlite/crm-files.js +2 -0
  60. package/dist/store/sqlite/crm-settings.d.ts +42 -1
  61. package/dist/store/sqlite/crm-settings.js +46 -2
  62. package/dist/store/sqlite/lucene-fields.d.ts +2 -0
  63. package/dist/store/sqlite/lucene-fields.js +6 -2
  64. package/dist/store/sqlite/lucene.js +2 -2
  65. package/dist/store/sqlite/stems.d.ts +2 -0
  66. package/dist/store/sqlite/stems.js +5 -0
  67. package/package.json +1 -1
@@ -0,0 +1,15 @@
1
+ import { type FetchLike } from "@wirecat/cli-base/http";
2
+ export interface CrmFileFetchOptions {
3
+ /** The account's own hosts, such as the Bitrix24 portal or amoCRM's `drive_url` host: the only ones asked. */
4
+ hosts: readonly string[];
5
+ /** Sent only to those hosts, such as a Bearer token. */
6
+ headers?: Record<string, string>;
7
+ signal?: AbortSignal;
8
+ fetch?: FetchLike;
9
+ }
10
+ /**
11
+ * A file's bytes behind a CRM link, for an adapter's `CrmOpenableFile.open`. https only, the account's own hosts only,
12
+ * redirects followed only on them, so the credentials go nowhere else. An HTML page is a CRM's answer to a link that is
13
+ * not a server link: refused. No error carries the link, which holds a token.
14
+ */
15
+ export declare const fetchCrmFile: (link: string, options: CrmFileFetchOptions) => Promise<ReadableStream<Uint8Array>>;
@@ -0,0 +1,61 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { hostFetch } from "@wirecat/cli-base/http";
3
+ /** A large file on a slow line; the command's own deadline and `--timeout` stop it sooner. */
4
+ const EXCHANGE_MS = 60 * 60 * 1000;
5
+ const MOST_REDIRECTS = 5;
6
+ /**
7
+ * A file's bytes behind a CRM link, for an adapter's `CrmOpenableFile.open`. https only, the account's own hosts only,
8
+ * redirects followed only on them, so the credentials go nowhere else. An HTML page is a CRM's answer to a link that is
9
+ * not a server link: refused. No error carries the link, which holds a token.
10
+ */
11
+ export const fetchCrmFile = async (link, options) => {
12
+ const send = options.fetch ?? hostFetch({ hosts: options.hosts, timeoutMs: EXCHANGE_MS });
13
+ const refused = (why) => new CliError("provider_error", `the CRM's file link was refused: ${why}`, { reason: "crm.file-unavailable" });
14
+ let at = link;
15
+ for (let hop = 0; hop <= MOST_REDIRECTS; hop += 1) {
16
+ let url;
17
+ try {
18
+ url = new URL(at);
19
+ }
20
+ catch {
21
+ throw refused("it is not a link");
22
+ }
23
+ if (url.protocol !== "https:")
24
+ throw refused("it is not https");
25
+ if (!options.hosts.includes(url.hostname.toLowerCase()))
26
+ throw refused("it points to another host than the account's");
27
+ let answer;
28
+ try {
29
+ answer = await send(url, {
30
+ redirect: "manual",
31
+ ...(options.headers ? { headers: options.headers } : {}),
32
+ ...(options.signal ? { signal: options.signal } : {}),
33
+ });
34
+ }
35
+ catch {
36
+ if (options.signal?.aborted)
37
+ throw new CliError("cancelled", "the file download was stopped");
38
+ throw new CliError("network_error", "the CRM's file server could not be reached", {
39
+ reason: "crm.file-unavailable",
40
+ });
41
+ }
42
+ const next = answer.headers.get("location");
43
+ if (answer.status >= 300 && answer.status < 400 && next) {
44
+ await answer.body?.cancel().catch(() => { });
45
+ at = new URL(next, url).href;
46
+ continue;
47
+ }
48
+ if (!answer.ok || !answer.body) {
49
+ await answer.body?.cancel().catch(() => { });
50
+ throw new CliError("provider_error", `the CRM's file server answered ${answer.status}`, {
51
+ reason: "crm.file-unavailable",
52
+ });
53
+ }
54
+ if ((answer.headers.get("content-type") ?? "").toLowerCase().startsWith("text/html")) {
55
+ await answer.body.cancel().catch(() => { });
56
+ throw refused("the CRM answered a web page, not the file");
57
+ }
58
+ return answer.body;
59
+ }
60
+ throw refused("too many redirects");
61
+ };
@@ -1,3 +1,4 @@
1
+ export { type CrmFileFetchOptions, fetchCrmFile } from "./file-fetch.js";
1
2
  export { crmFileId, LINK_REMOVED, parseCrmFileId, withoutFileLinks } from "./files.js";
2
3
  export { DAILY_FOREIGN_CONTACTS, type ForeignContacts, foreignContacts, foreignContactsPathFor, refuseForeignClientReads, } from "./foreign-contacts.js";
3
4
  export { type ProviderCallOptions, providerCall } from "./provider-call.js";
package/dist/crm/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export { fetchCrmFile } from "./file-fetch.js";
1
2
  export { crmFileId, LINK_REMOVED, parseCrmFileId, withoutFileLinks } from "./files.js";
2
3
  export { DAILY_FOREIGN_CONTACTS, foreignContacts, foreignContactsPathFor, refuseForeignClientReads, } from "./foreign-contacts.js";
3
4
  export { providerCall } from "./provider-call.js";
@@ -0,0 +1,17 @@
1
+ import type { ContractCase } from "../../meetings/index.js";
2
+ import { type CrmFileOwner, type CrmSource } from "../source.js";
3
+ /** One adapter with `files`, over recorded or faked responses, fresh for each case. */
4
+ export interface CrmFilesFixture {
5
+ source: CrmSource;
6
+ /** A record of the sign-in's own with at least one file whose text holds `word`. */
7
+ own: CrmFileOwner;
8
+ word: string;
9
+ /** A colleague's record with a file; needed when the source has `isAdmin`. */
10
+ foreign?: CrmFileOwner;
11
+ /** What every file link the fixture serves carries, such as its token: it must reach no answer, file or error. */
12
+ token: string;
13
+ /** Ids of files whose download the adapter must refuse: a link to another host, a web page instead of the file. */
14
+ refused?: readonly string[];
15
+ }
16
+ /** What every CRM adapter's `files` answers, whatever the CRM: run each case in the adapter's tests. */
17
+ export declare const crmFilesContract: (make: () => CrmFilesFixture | Promise<CrmFilesFixture>) => ContractCase[];
@@ -0,0 +1,142 @@
1
+ import assert from "node:assert/strict";
2
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { isCliError } from "@wirecat/cli-base";
6
+ import { openStore } from "../../store/store.js";
7
+ import { downloadCrmFile } from "../cli/files.js";
8
+ import { parseCrmFileId } from "../files.js";
9
+ import { DAILY_FOREIGN_CONTACTS, foreignContacts } from "../foreign-contacts.js";
10
+ import { CRM_FILE_SOURCES } from "../source.js";
11
+ const APP = {
12
+ command: "crm",
13
+ appName: "crm-files-contract",
14
+ envPrefix: "CRMFILES",
15
+ description: "contract",
16
+ version: "0.0.0",
17
+ };
18
+ const ACCOUNT = { provider: "contract-crm", account: "portal" };
19
+ const without = (token, what, value) => assert.ok(!JSON.stringify(value ?? null).includes(token) && !String(value?.message ?? "").includes(token), `${what} holds the file link's token`);
20
+ const filesOf = (root) => existsSync(root)
21
+ ? readdirSync(root, { recursive: true, withFileTypes: true })
22
+ .filter((entry) => entry.isFile())
23
+ .map((entry) => join(entry.parentPath, entry.name))
24
+ : [];
25
+ /** A store and a state folder of their own, and a run over the fixture's source. */
26
+ const runOver = async (source) => {
27
+ const home = mkdtempSync(join(tmpdir(), "crm-files-contract-"));
28
+ const path = join(home, "store.db");
29
+ const store = await openStore({ path });
30
+ const user = source.self ? String(await source.self()) : null;
31
+ const run = {
32
+ profile: "contract",
33
+ user,
34
+ account: ACCOUNT,
35
+ store,
36
+ source: () => source,
37
+ env: { HOME: home, XDG_STATE_HOME: home, CRMFILES_STATE_DIR: join(home, "state") },
38
+ };
39
+ return { run, store, path, state: join(home, "state"), context: { app: APP, run, now: () => Date.now() } };
40
+ };
41
+ /** What every CRM adapter's `files` answers, whatever the CRM: run each case in the adapter's tests. */
42
+ export const crmFilesContract = (make) => [
43
+ {
44
+ name: "files: one record's files, each with an id naming that record, a known source and no link anywhere",
45
+ async run() {
46
+ const { source, own, token } = await make();
47
+ assert.ok(source.files, "the source has files");
48
+ const found = await source.files(own);
49
+ assert.ok(found && found.files.length > 0, "the own record lists a file");
50
+ for (const file of found.files) {
51
+ const { owner, source: kind } = parseCrmFileId(file.id);
52
+ assert.deepEqual(owner, own, `${file.id} names its record`);
53
+ assert.equal(kind, file.source);
54
+ assert.ok(CRM_FILE_SOURCES.includes(file.source));
55
+ assert.ok(file.name.length > 0, "a file has a name");
56
+ assert.ok(file.size === null || file.size >= 0);
57
+ const { open: _open, ...listed } = file;
58
+ without(token, `the listed ${file.id}`, { id: listed.id, name: listed.name, owner: listed.owner });
59
+ }
60
+ assert.equal(await source.files({ kind: own.kind, id: "999999999" }), null, "a record the CRM lacks is null");
61
+ },
62
+ },
63
+ {
64
+ name: "files: a download is saved 600 in 700 folders, its text stored and found, and its token kept nowhere",
65
+ async run() {
66
+ const { source, own, word, token, refused = [] } = await make();
67
+ const { run, store, path, state, context } = await runOver(source);
68
+ try {
69
+ const found = await source.files?.(own);
70
+ assert.ok(found);
71
+ const rows = [];
72
+ for (const file of found.files.filter((one) => !refused.includes(one.id)))
73
+ rows.push(await downloadCrmFile(context, file, found.assignee, {
74
+ capBytes: 100 * 1024 * 1024,
75
+ capMb: 100,
76
+ flag: false,
77
+ limits: await store.crmFiles.limits(ACCOUNT),
78
+ }));
79
+ assert.ok(rows.some((one) => one.row.text?.toLowerCase().includes(word.toLowerCase())), `a file's text holds ${word}`);
80
+ for (const saved of filesOf(state)) {
81
+ assert.equal(statSync(saved).mode & 0o777, 0o600, `${saved} is the OS user's alone`);
82
+ without(token, saved, readFileSync(saved, "latin1"));
83
+ }
84
+ assert.equal(statSync(join(state, "crm", "files")).mode & 0o777, 0o700);
85
+ const hits = await store.crmFiles.find({ words: [word] });
86
+ assert.ok(hits.items.length > 0, "search finds the text");
87
+ if (found.assignee !== null && run.user !== null) {
88
+ const other = { account: ACCOUNT, assignee: `${ACCOUNT.account}/user/0` };
89
+ assert.equal((await store.crmFiles.find({ words: [word], viewers: [other] })).items.length, 0);
90
+ }
91
+ await store.close();
92
+ assert.ok(!readFileSync(path, "latin1").includes(token), "the store file holds the token");
93
+ }
94
+ finally {
95
+ await store.close().catch(() => { });
96
+ }
97
+ },
98
+ },
99
+ {
100
+ name: "files: a refused link (another host, a web page) fails without its token and leaves no part",
101
+ async run() {
102
+ const { source, token, refused = [] } = await make();
103
+ if (!refused.length)
104
+ return;
105
+ const { store, state, context } = await runOver(source);
106
+ try {
107
+ for (const id of refused) {
108
+ const { owner } = parseCrmFileId(id);
109
+ const found = await source.files?.(owner);
110
+ const file = found?.files.find((one) => one.id === id);
111
+ assert.ok(file, `${id} is listed for ${owner.kind} ${owner.id}`);
112
+ const error = await downloadCrmFile(context, file, found?.assignee ?? null, {
113
+ capBytes: 1024 * 1024,
114
+ capMb: 1,
115
+ flag: false,
116
+ limits: await store.crmFiles.limits(ACCOUNT),
117
+ }).then(() => undefined, (caught) => caught);
118
+ assert.ok(isCliError(error), `${id} is refused`);
119
+ without(token, `the refusal of ${id}`, error);
120
+ }
121
+ assert.deepEqual(filesOf(state), [], "a refused download keeps no file");
122
+ }
123
+ finally {
124
+ await store.close();
125
+ }
126
+ },
127
+ },
128
+ {
129
+ name: "files: a colleague's record costs one of the day's slots, and the 101st is refused",
130
+ async run() {
131
+ const { source, foreign } = await make();
132
+ if (!source.isAdmin || !foreign || (await source.isAdmin()))
133
+ return;
134
+ const found = await source.files?.(foreign);
135
+ assert.ok(found, "the colleague's record lists its files");
136
+ const file = join(mkdtempSync(join(tmpdir(), "crm-files-quota-")), "count.json");
137
+ const day = new Date().toISOString().slice(0, 10);
138
+ writeFileSync(file, JSON.stringify({ day, seen: Array.from({ length: DAILY_FOREIGN_CONTACTS }, (_, at) => `x:${at}`) }));
139
+ await assert.rejects(foreignContacts(source, () => file).spend(foreign.kind, { externalId: foreign.id, assignee: found.assignee }), (error) => isCliError(error) && error.details.reason === "crm.foreign-contacts-spent");
140
+ },
141
+ },
142
+ ];
@@ -1,4 +1,5 @@
1
1
  export { ACME_CALENDAR, ACME_MAIL, ACME_NOW, ACME_OPENED, ACME_PORTAL, ACME_TELEGRAM, type AcmeScenario, acmeScenario, } from "./acme-scenario.js";
2
+ export { type CrmFilesFixture, crmFilesContract } from "./files-contract.js";
2
3
  export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, FAKE_FILE_TOKEN, type FakeCrmFile, type FakeCrmSource, type FakeCrmSourceOptions, type FakeCrmWrite, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
3
4
  export { type CrmSourceFaults, type CrmSourceFixture, crmSourceContract } from "./source-contract.js";
4
5
  export { CRM_TRAIT_COMBINATIONS, type CrmSyncFixture, crmSyncContract } from "./sync-contract.js";
@@ -1,4 +1,5 @@
1
1
  export { ACME_CALENDAR, ACME_MAIL, ACME_NOW, ACME_OPENED, ACME_PORTAL, ACME_TELEGRAM, acmeScenario, } from "./acme-scenario.js";
2
+ export { crmFilesContract } from "./files-contract.js";
2
3
  export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, FAKE_FILE_TOKEN, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
3
4
  export { crmSourceContract } from "./source-contract.js";
4
5
  export { CRM_TRAIT_COMBINATIONS, crmSyncContract } from "./sync-contract.js";
@@ -23,6 +23,11 @@ export interface FakeCrmSourceOptions {
23
23
  * `FAKE_FILE_TOKEN`, as a careless adapter's might, so a test sees whether the token gets out.
24
24
  */
25
25
  files?: FakeCrmFile[];
26
+ /** Kinds of file the sign-in may not read: each `files()` reports them as a gap naming the scope. */
27
+ fileGaps?: {
28
+ scope: string;
29
+ message: string;
30
+ }[];
26
31
  }
27
32
  /** The token in every fake file link: it must reach no output, store, file or error. */
28
33
  export declare const FAKE_FILE_TOKEN = "fake-file-token-5f2a9c";
@@ -272,8 +272,10 @@ export const fakeCrmSource = (options = {}) => {
272
272
  ...(options.files === undefined
273
273
  ? {}
274
274
  : {
275
- files: async (owner) => {
275
+ files: async (owner, context) => {
276
276
  calls.files += 1;
277
+ for (const gap of options.fileGaps ?? [])
278
+ context?.gap({ kind: owner.kind, ...gap });
277
279
  const record = of(owner.kind).get(owner.id);
278
280
  if (!record || record.deleted)
279
281
  return null;
@@ -1,10 +1,10 @@
1
1
  import * as v from "valibot";
2
2
  /**
3
- * One result of `search all`: a message, a mail, a note, a calendar event, a meeting passage, a deal, a lead, or an
4
- * invoice, payment, order, contract, subscription, product or wallet.
3
+ * One result of `search all`: a message, a mail, a note, a calendar event, a meeting passage, a deal, a lead, the text
4
+ * of a downloaded CRM file, or an invoice, payment, order, contract, subscription, product or wallet.
5
5
  */
6
6
  export declare const hit: v.StrictObjectSchema<{
7
- readonly kind: v.PicklistSchema<["message", "mail", "note", "document", "event", "meeting", "deal", "lead", "invoice", "payment", "order", "contract", "subscription", "product", "wallet"], undefined>;
7
+ readonly kind: v.PicklistSchema<["message", "mail", "note", "document", "event", "meeting", "deal", "lead", "crm_file", "invoice", "payment", "order", "contract", "subscription", "product", "wallet"], undefined>;
8
8
  readonly ref: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>;
9
9
  readonly provider: v.StringSchema<undefined>;
10
10
  readonly url: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
@@ -3,11 +3,22 @@ import { BUSINESS_KINDS } from "../domain/business.js";
3
3
  import { hitFile } from "./attachment.js";
4
4
  import { count, reference, text, time, untrusted } from "./fields.js";
5
5
  /**
6
- * One result of `search all`: a message, a mail, a note, a calendar event, a meeting passage, a deal, a lead, or an
7
- * invoice, payment, order, contract, subscription, product or wallet.
6
+ * One result of `search all`: a message, a mail, a note, a calendar event, a meeting passage, a deal, a lead, the text
7
+ * of a downloaded CRM file, or an invoice, payment, order, contract, subscription, product or wallet.
8
8
  */
9
9
  export const hit = v.strictObject({
10
- kind: v.picklist(["message", "mail", "note", "document", "event", "meeting", "deal", "lead", ...BUSINESS_KINDS]),
10
+ kind: v.picklist([
11
+ "message",
12
+ "mail",
13
+ "note",
14
+ "document",
15
+ "event",
16
+ "meeting",
17
+ "deal",
18
+ "lead",
19
+ "crm_file",
20
+ ...BUSINESS_KINDS,
21
+ ]),
11
22
  ref: reference,
12
23
  provider: text,
13
24
  url: v.optional(text),
@@ -4371,7 +4371,7 @@ export declare const ENTITIES: {
4371
4371
  readonly untrusted: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
4372
4372
  }, undefined>;
4373
4373
  readonly hit: v.StrictObjectSchema<{
4374
- readonly kind: v.PicklistSchema<["message", "mail", "note", "document", "event", "meeting", "deal", "lead", "invoice", "payment", "order", "contract", "subscription", "product", "wallet"], undefined>;
4374
+ readonly kind: v.PicklistSchema<["message", "mail", "note", "document", "event", "meeting", "deal", "lead", "crm_file", "invoice", "payment", "order", "contract", "subscription", "product", "wallet"], undefined>;
4375
4375
  readonly ref: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>;
4376
4376
  readonly provider: v.StringSchema<undefined>;
4377
4377
  readonly url: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
@@ -453,8 +453,19 @@ const OTHERS = [
453
453
  [
454
454
  "crm.foreign-contacts-spent",
455
455
  "permission_error",
456
- "the day's views of contacts and companies that are not yours are spent",
456
+ "the day's reads of records that are not yours (contacts, companies, other people's files) are spent",
457
457
  ],
458
+ validation("crm.files-limit-range", "a files setting takes a whole number within its range; it is never clamped"),
459
+ validation("crm.file-too-large", "the file is larger than the download may take; --max-size raises it up to 2048 MB"),
460
+ validation("crm.files-disk-full", "the account's files folder is at its files.max_total_mb even after dropping"),
461
+ ["crm.file-unavailable", "provider_error", "the CRM did not give the file; its link is never shown"],
462
+ ["crm.files-denied", "permission_error", "the profile's files.download level stops downloading files"],
463
+ [
464
+ "crm.file-exists",
465
+ "conflict",
466
+ "the --dir folder already holds a file of that name, which a download never overwrites",
467
+ ],
468
+ ["crm.scope-missing", "permission_error", "the CRM sign-in lacks a scope one kind of a record's files needs"],
458
469
  [
459
470
  "crm.client-reads-admin-only",
460
471
  "permission_error",
@@ -1,5 +1,6 @@
1
1
  /**
2
2
  * A name another person chose cannot climb out of the folder, cannot be a dot file we would then
3
- * hide, and carries no control or direction character to rewrite the terminal or disguise its extension.
3
+ * hide, carries no control or direction character to rewrite the terminal or disguise its extension, and is at most
4
+ * 200 bytes, its extension kept.
4
5
  */
5
6
  export declare const safeName: (name: string | undefined, platform?: NodeJS.Platform) => string | undefined;
@@ -1,7 +1,25 @@
1
- import { basename } from "node:path";
1
+ import { basename, extname } from "node:path";
2
+ /** Below the 255 bytes most file systems allow a name, leaving room for a prefix such as a provider id. */
3
+ const MOST_NAME_BYTES = 200;
4
+ const bytesOf = (text) => Buffer.byteLength(text, "utf8");
5
+ /** A name cut to `most` bytes at a whole character, its extension kept. */
6
+ const shortened = (name, most) => {
7
+ if (bytesOf(name) <= most)
8
+ return name;
9
+ const extension = extname(name);
10
+ const kept = bytesOf(extension) <= 32 ? extension : "";
11
+ let stem = "";
12
+ for (const character of name.slice(0, name.length - kept.length)) {
13
+ if (bytesOf(stem + character) + bytesOf(kept) > most)
14
+ break;
15
+ stem += character;
16
+ }
17
+ return stem + kept;
18
+ };
2
19
  /**
3
20
  * A name another person chose cannot climb out of the folder, cannot be a dot file we would then
4
- * hide, and carries no control or direction character to rewrite the terminal or disguise its extension.
21
+ * hide, carries no control or direction character to rewrite the terminal or disguise its extension, and is at most
22
+ * 200 bytes, its extension kept.
5
23
  */
6
24
  export const safeName = (name, platform = process.platform) => {
7
25
  let plain = name === undefined
@@ -14,5 +32,5 @@ export const safeName = (name, platform = process.platform) => {
14
32
  if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(plain))
15
33
  return undefined;
16
34
  }
17
- return plain === "" ? undefined : plain;
35
+ return plain === "" ? undefined : shortened(plain, MOST_NAME_BYTES);
18
36
  };
@@ -1,5 +1,5 @@
1
1
  import { type FailureContext } from "@wirecat/cli-base";
2
- import { type MeetingPassageReader } from "../passage.js";
2
+ import { type MeetingPassageOutputFormat, type MeetingPassageReader, type MeetingPassageResult } from "../passage.js";
3
3
  export declare const meetingPassageTool: {
4
4
  name: string;
5
5
  description: string;
@@ -50,7 +50,11 @@ export declare const meetingPassageTool: {
50
50
  additionalProperties: boolean;
51
51
  };
52
52
  };
53
- export declare const callMeetingPassageTool: (read: MeetingPassageReader, input: unknown, signal?: AbortSignal, failure?: FailureContext) => Promise<({
53
+ /**
54
+ * `forRun` is how the host prints the passage in this run: `passageForRun` from `@wirecat/cli-core/cli`, which marks
55
+ * the cues in a scheduled agent's run. This module cannot read the run's mark.
56
+ */
57
+ export declare const callMeetingPassageTool: (read: MeetingPassageReader, input: unknown, signal?: AbortSignal, failure?: FailureContext, forRun?: (result: MeetingPassageResult, format: MeetingPassageOutputFormat) => MeetingPassageResult) => Promise<({
54
58
  content: {
55
59
  type: "text";
56
60
  text: string;
@@ -1,5 +1,5 @@
1
1
  import { CliError, errorObjectOf, isCliError, mcpErrorResult } from "@wirecat/cli-base";
2
- import { markedPassage, validateMeetingPassage } from "../passage.js";
2
+ import { markedPassage, validateMeetingPassage, } from "../passage.js";
3
3
  import { agentResult, UNTRUSTED_NEUTRAL } from "./agent-text.js";
4
4
  const count = { type: "integer", minimum: 0, maximum: 999 };
5
5
  export const meetingPassageTool = {
@@ -21,7 +21,11 @@ export const meetingPassageTool = {
21
21
  additionalProperties: false,
22
22
  },
23
23
  };
24
- export const callMeetingPassageTool = async (read, input, signal, failure = {}) => {
24
+ /**
25
+ * `forRun` is how the host prints the passage in this run: `passageForRun` from `@wirecat/cli-core/cli`, which marks
26
+ * the cues in a scheduled agent's run. This module cannot read the run's mark.
27
+ */
28
+ export const callMeetingPassageTool = async (read, input, signal, failure = {}, forRun = (result) => result) => {
25
29
  try {
26
30
  if (!input || typeof input !== "object" || Array.isArray(input))
27
31
  throw new CliError("validation_error", "expected passage arguments");
@@ -40,7 +44,7 @@ export const callMeetingPassageTool = async (read, input, signal, failure = {})
40
44
  const reference = args.reference;
41
45
  validateMeetingPassage(reference, options);
42
46
  signal?.throwIfAborted();
43
- const result = markedPassage(await read(reference, options));
47
+ const result = forRun(markedPassage(await read(reference, options)), options.format);
44
48
  signal?.throwIfAborted();
45
49
  return agentResult({ content: [{ type: "text", text: result.content }], structuredContent: result.packet });
46
50
  }
@@ -0,0 +1,10 @@
1
+ import { type Vocabulary } from "./correct.js";
2
+ /** A Cyrillic word as Latin letters, the way a Latin name is written in Russian («хецнер», «ноксвел» for noxvel). */
3
+ export declare const latinSpellings: (word: string) => string[];
4
+ /**
5
+ * For each word no message holds, not even as the beginning of a longer one, the words the store does hold that it
6
+ * may stand for: its Latin spelling or the nearest known spellings of that, and only when there are none, its own
7
+ * nearest known spellings (up to two edits, as `correctWords` allows). A word any message holds is left alone, so a
8
+ * correct word never turns into another.
9
+ */
10
+ export declare const respelled: (vocabulary: Vocabulary, words: string[]) => Promise<Map<string, string[]>>;
@@ -0,0 +1,63 @@
1
+ import { normalize } from "../store/normalize.js";
2
+ import { correctWords } from "./correct.js";
3
+ const LATIN = {
4
+ а: "a",
5
+ б: "b",
6
+ в: "v",
7
+ г: "g",
8
+ д: "d",
9
+ е: "e",
10
+ ж: "zh",
11
+ з: "z",
12
+ и: "i",
13
+ к: "k",
14
+ л: "l",
15
+ м: "m",
16
+ н: "n",
17
+ о: "o",
18
+ п: "p",
19
+ р: "r",
20
+ с: "s",
21
+ т: "t",
22
+ у: "u",
23
+ ф: "f",
24
+ х: "h",
25
+ ц: "ts",
26
+ ч: "ch",
27
+ ш: "sh",
28
+ щ: "sch",
29
+ ъ: "",
30
+ ы: "y",
31
+ ь: "",
32
+ э: "e",
33
+ ю: "yu",
34
+ я: "ya",
35
+ };
36
+ /** A Cyrillic word as Latin letters, the way a Latin name is written in Russian («хецнер», «ноксвел» for noxvel). */
37
+ export const latinSpellings = (word) => {
38
+ if (!/\p{Script=Cyrillic}/u.test(word))
39
+ return [];
40
+ const plain = [...normalize(word)].map((letter) => LATIN[letter] ?? letter).join("");
41
+ return [...new Set([plain, plain.replaceAll("ks", "x")])];
42
+ };
43
+ /**
44
+ * For each word no message holds, not even as the beginning of a longer one, the words the store does hold that it
45
+ * may stand for: its Latin spelling or the nearest known spellings of that, and only when there are none, its own
46
+ * nearest known spellings (up to two edits, as `correctWords` allows). A word any message holds is left alone, so a
47
+ * correct word never turns into another.
48
+ */
49
+ export const respelled = async (vocabulary, words) => {
50
+ const known = await vocabulary.knownTerms(words);
51
+ const found = new Map();
52
+ for (const word of words.filter((one) => !known.has(one))) {
53
+ const latin = latinSpellings(word);
54
+ const held = await vocabulary.knownTerms(latin);
55
+ const nearLatin = await correctWords(vocabulary, latin.filter((one) => !held.has(one)));
56
+ const asLatin = [...new Set([...held, ...[...nearLatin.values()].flat()])];
57
+ // A Latin name found in Latin letters says what the word was; its Cyrillic neighbours are then other words.
58
+ const forms = asLatin.length ? asLatin : ((await correctWords(vocabulary, [word])).get(normalize(word)) ?? []);
59
+ if (forms.length)
60
+ found.set(word, forms);
61
+ }
62
+ return found;
63
+ };
@@ -20,6 +20,8 @@ export declare const DEFAULT_STEMMERS_VERSION = 2;
20
20
  * Between the stem sequences of one text when several Latin stemmers give different ones, so a phrase
21
21
  * never matches across two sequences. Letters and digits, so `unicode61` keeps it as one token.
22
22
  */
23
+ /** The fewest letters a searched word has for the longer words it begins to count too: `рост` finds `ростовщик`. */
24
+ export declare const START_LETTERS = 4;
23
25
  export declare const STEM_SEPARATOR = "0stemsep0";
24
26
  /** Clear-all rather than LRU: the 1M benchmark corpus holds 523k distinct words, and a Map stays cheap below this. */
25
27
  export declare const STEM_CACHE_LIMIT = 200000;
@@ -40,8 +42,13 @@ export type Stemmer = {
40
42
  indexText(text: string): string;
41
43
  /** An FTS5 expression for a text as phrases of stems, one per sequence; `undefined` when no word stems. */
42
44
  phrases(text: string): string | undefined;
43
- /** Each word of a text with its stem and the stemmer its script chose — what a search answer shows. */
44
- explain(text: string): {
45
+ /**
46
+ * Each word of a text with its stem and the stemmer its script chose — what a search answer shows. With `query`, the
47
+ * stem `phrases` searches, which keeps a word whole where its stem would be another word.
48
+ */
49
+ explain(text: string, options?: {
50
+ query?: boolean;
51
+ }): {
45
52
  word: string;
46
53
  stem: string;
47
54
  stemmer: CyrillicStemmer | LatinStemmer;
@@ -53,6 +60,12 @@ export type Stemmer = {
53
60
  * (`Москвa` with a Latin `a`) are usually homoglyph spoofing or code, and `covid19` is a name, not a word form.
54
61
  * Ukrainian and other Cyrillic languages go through the Russian stemmer — there is no language detection.
55
62
  */
56
- export declare const createStemmer: (stemmers?: Stemmers, { cacheLimit }?: {
63
+ /**
64
+ * Whether Snowball cuts a word to a stem so short that it may be another word's: «домен» → «дом», the stem of «дом»
65
+ * and «дома». The search keeps such a word whole when the stems show it is a stem itself («доменов» → «домен»).
66
+ */
67
+ export declare const cutsDeep: (stemmer: Stemmer, token: string) => boolean;
68
+ export declare const createStemmer: (stemmers?: Stemmers, { cacheLimit, whole }?: {
57
69
  cacheLimit?: number;
70
+ whole?: ReadonlySet<string>;
58
71
  }) => Stemmer;