@wirecat/cli-core 0.751.0 → 0.753.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 (50) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/cli/messenger/backfill-command.js +3 -1
  3. package/dist/crm/index.d.ts +1 -1
  4. package/dist/crm/index.js +1 -1
  5. package/dist/crm/manifest/writer.d.ts +23 -4
  6. package/dist/crm/manifest/writer.js +46 -8
  7. package/dist/crm/writer.d.ts +3 -2
  8. package/dist/crm/writer.js +9 -3
  9. package/dist/crm/writes.d.ts +2 -0
  10. package/dist/crm/writes.js +7 -4
  11. package/dist/domain/addresses.d.ts +8 -3
  12. package/dist/domain/addresses.js +24 -6
  13. package/dist/domain/person-kinds.d.ts +1 -1
  14. package/dist/errors/reasons.js +1 -0
  15. package/dist/mail/email-input.d.ts +1 -1
  16. package/dist/mail/email-input.js +3 -2
  17. package/dist/mail/folders.d.ts +6 -1
  18. package/dist/mail/folders.js +10 -5
  19. package/dist/mail/headers.d.ts +9 -5
  20. package/dist/mail/headers.js +63 -5
  21. package/dist/mail/own.d.ts +15 -0
  22. package/dist/mail/own.js +35 -0
  23. package/dist/mail/partial.js +4 -1
  24. package/dist/mail/server-search.js +3 -1
  25. package/dist/mail/source.d.ts +5 -1
  26. package/dist/mail/sync-types.d.ts +2 -0
  27. package/dist/mail/sync.js +16 -4
  28. package/dist/mail/testing/fake.d.ts +4 -0
  29. package/dist/mail/testing/fake.js +3 -1
  30. package/dist/mail/whole.js +3 -1
  31. package/dist/store/index.d.ts +1 -0
  32. package/dist/store/index.js +1 -0
  33. package/dist/store/messages.js +1 -0
  34. package/dist/store/sqlite/email-activity.d.ts +1 -1
  35. package/dist/store/sqlite/email-activity.js +4 -1
  36. package/dist/store/sqlite/email-state.d.ts +8 -0
  37. package/dist/store/sqlite/email-state.js +23 -0
  38. package/dist/store/sqlite/emails.d.ts +9 -0
  39. package/dist/store/sqlite/emails.js +2 -1
  40. package/dist/store/sqlite/messages.d.ts +5 -0
  41. package/dist/store/sqlite/messages.js +13 -3
  42. package/dist/store/sqlite/own-identities.d.ts +2 -0
  43. package/dist/store/sqlite/own-identities.js +24 -1
  44. package/dist/store/sqlite/people-list.d.ts +12 -0
  45. package/dist/store/sqlite/people-list.js +31 -7
  46. package/dist/store/sqlite/person-match-scan.js +34 -4
  47. package/dist/store/sqlite/record-projectors-phone.js +2 -1
  48. package/dist/store/sqlite/sender-signals.d.ts +42 -0
  49. package/dist/store/sqlite/sender-signals.js +106 -0
  50. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,56 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.753.0 — 25.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A CRM CLI built from a manifest can add notes and tasks.** `crmManifestWrites` and `crmManifestWriteCapabilities`
13
+ take `activities`: the CLI's own functions for a comment, a task and a task marked done, and the operation each
14
+ sends. They mount `activities create` and `activities close` under the same guard and journal as any CRM write.
15
+ Each also checks its operation's `api` keys, so `api.<operation>: deny` stops it, and `crmAlsoChecks` takes
16
+ `crmManifestActivityKeys` so `--dry-run` names them ([CRM](docs/dev/CRM.md#writes-from-a-manifest)).
17
+
18
+ ### Fixed
19
+
20
+ - **Mail to one of the owner's aliases is owed an answer.** `review --unanswered` and `tasks agenda` took mail as
21
+ addressed to the owner only when the account's own address was in To or Cc, so mail sent to an alias was never owed.
22
+ Now any address under `mail_own_addresses` counts: those configured in `MailAccount.addresses` and the senders of
23
+ Sent mail.
24
+ - **A long sync stays fast as the chat grows.** Each saved message looked through the whole chat for replies
25
+ waiting for it as their thread's root, so a page of 100 took 78 ms at 10,000 stored messages and 919 ms at 90,000.
26
+ That search now runs once per page (tg-cli [#917](https://github.com/WireCatLabs/tg-cli/issues/917)).
27
+
28
+ ## 0.752.0 — 25.11.2026
29
+
30
+ ### Added
31
+
32
+ - **A mail source names the IMAP Sent folder.** `MailSource.folders()` may answer `sent`: the folder the server marks
33
+ `\Sent` (RFC 6154), else one by a common name when the server marks none. `mailFolders` then reads `INBOX` and that
34
+ folder for `mode: "imap"`, and `MailAccount.addresses` takes the owner's other addresses on the mailbox, such as
35
+ aliases ([MAIL.md](docs/dev/MAIL.md#syncmailsource-store-options)).
36
+
37
+ ### Fixed
38
+
39
+ - **Mail the owner sent from an alias is outgoing, and the alias is the owner's.** Mail in Sent or under Gmail's `Sent`
40
+ label, and mail from one of the owner's addresses, counted as incoming when its From was not the account's address,
41
+ so the people the owner wrote to from an alias had no mail tie and showed as strangers. Now it is outgoing, mail stored
42
+ earlier is marked too, the senders of Sent mail are kept under `mail_own_addresses`, and their identities join the
43
+ owner when the account's own identity is the owner's. An IMAP adapter that answers `sent` gets the same for its Sent
44
+ folder.
45
+ - **`people.list` finds no-reply and notification senders by any part of the address.** `noreply-12345@`,
46
+ `service-noreply@` and `bank.no-reply@` are no-reply addresses now, and `notify@`, `alerts@` or `bank-notifications@`
47
+ make a sender `automated` (signal `notification-address`), so banks and service alerts no longer show under
48
+ strangers. `bounce` counts only as a whole part (`bounce-8812@`), so `bouncer.joe@` stays a person. Someone the owner
49
+ answers in a private chat stays a `person`. Every stored kind is worked out again on the next list.
50
+ - **The people scan never proposes a bot, an automated sender or an organization as the same person by name.** One
51
+ newsletter that sends from many `+tag` addresses under one name no longer fills the review with pairs. The next scan
52
+ deletes the open `name` proposals that name such a sender, and is a full pass once.
53
+ - **`messages sync <chat> --full-history --background` reads the chat in full.** The background job was started
54
+ without `--full-history`, so a group above `history_group_members_max` ended at once with `fetched: 0` and
55
+ `limited: "group_too_large"`, and its log asked for the flag that was given. The job now gets the flag, and
56
+ `store jobs retry` keeps it (tg-cli [#916](https://github.com/WireCatLabs/tg-cli/issues/916)).
57
+
8
58
  ## 0.751.0 — 25.11.2026
9
59
 
10
60
  ### Fixed
@@ -148,6 +148,7 @@ export const syncCommand = (messenger) => {
148
148
  pageSize,
149
149
  pause,
150
150
  catchUp: prepare,
151
+ ...(include ? { fullHistory: true } : {}),
151
152
  ...(withMuted ? { withMuted } : {}),
152
153
  ...(catchUpChunks === undefined ? {} : { catchUpChunks }),
153
154
  ...(catchUpMessages === undefined ? {} : { catchUpMessages }),
@@ -402,7 +403,7 @@ const findJob = (messenger, context, id) => {
402
403
  }
403
404
  return job;
404
405
  };
405
- const fetchArgv = (command, { chat, limit, pageSize, pause, since, last, catchUp, withMuted, catchUpChunks, catchUpMessages, catchUpTime, }) => {
406
+ const fetchArgv = (command, { chat, limit, pageSize, pause, since, last, catchUp, fullHistory, withMuted, catchUpChunks, catchUpMessages, catchUpTime, }) => {
406
407
  const { timeout } = command.optsWithGlobals();
407
408
  return [
408
409
  "messages",
@@ -417,6 +418,7 @@ const fetchArgv = (command, { chat, limit, pageSize, pause, since, last, catchUp
417
418
  ...(since === undefined ? [] : ["--since-time", since]),
418
419
  ...(last === undefined ? [] : ["--last", String(last)]),
419
420
  ...(catchUp === undefined ? [] : [catchUp ? "--catch-up" : "--no-catch-up"]),
421
+ ...(fullHistory ? ["--full-history"] : []),
420
422
  ...(withMuted ? ["--with-muted"] : []),
421
423
  ...(catchUpChunks === undefined ? [] : ["--catch-up-chunks", String(catchUpChunks)]),
422
424
  ...(catchUpMessages === undefined ? [] : ["--catch-up-messages", String(catchUpMessages)]),
@@ -4,7 +4,7 @@ export { DAILY_FOREIGN_CONTACTS, type ForeignContacts, foreignContacts, foreignC
4
4
  export { type CrmAfterHook, type CrmChangesCall, type CrmFixedValue, type CrmManifest, type CrmManifestEntity, type CrmManifestFields, type CrmManifestHooks, type CrmManifestPipelines, type CrmManifestWrite, type CrmOperationCall, type CrmRule, type CrmWriteRule, parseCrmManifest, } from "./manifest/manifest.js";
5
5
  export { crmManifestProblems } from "./manifest/paths.js";
6
6
  export { type CrmManifestSource, type CrmManifestSourceOptions, crmSourceFromManifest } from "./manifest/source.js";
7
- export { type CrmManifestWritesOptions, crmManifestWriteCapabilities, crmManifestWriteKeys, crmManifestWrites, } from "./manifest/writer.js";
7
+ export { type CrmManifestActivities, type CrmManifestWritesOptions, crmManifestActivityKeys, crmManifestWriteCapabilities, crmManifestWriteKeys, crmManifestWrites, } from "./manifest/writer.js";
8
8
  export { type ProviderCallOptions, providerCall } from "./provider-call.js";
9
9
  export { type CrmConditionHooks, type CrmQueryField, conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
10
10
  export { CRM_FILE_SOURCES, type CrmCallContext, type CrmChanges, type CrmCondition, type CrmFile, type CrmFileOwner, type CrmFileSourceKind, type CrmFiles, type CrmGap, type CrmIdPage, type CrmLiveKind, type CrmLiveQuery, type CrmOpenableFile, type CrmPage, type CrmSource, type CrmSourceTraits, } from "./source.js";
package/dist/crm/index.js CHANGED
@@ -4,7 +4,7 @@ export { DAILY_FOREIGN_CONTACTS, foreignContacts, foreignContactsPathFor, refuse
4
4
  export { parseCrmManifest, } from "./manifest/manifest.js";
5
5
  export { crmManifestProblems } from "./manifest/paths.js";
6
6
  export { crmSourceFromManifest } from "./manifest/source.js";
7
- export { crmManifestWriteCapabilities, crmManifestWriteKeys, crmManifestWrites, } from "./manifest/writer.js";
7
+ export { crmManifestActivityKeys, crmManifestWriteCapabilities, crmManifestWriteKeys, crmManifestWrites, } from "./manifest/writer.js";
8
8
  export { providerCall } from "./provider-call.js";
9
9
  export { conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
10
10
  export { CRM_FILE_SOURCES, } from "./source.js";
@@ -1,11 +1,26 @@
1
1
  import { type ServiceApiPermissionsInput } from "../../cli/service-api.js";
2
2
  import { type ServiceApiCall, type ServiceApiCallOptions } from "../../cli/service-api-call.js";
3
3
  import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
4
- import type { CrmKind } from "../../domain/crm.js";
4
+ import type { CrmActivity, CrmKind } from "../../domain/crm.js";
5
5
  import type { PermissionKey } from "../../sends/permissions.js";
6
- import { type CrmVerb, type CrmWriteCapabilities, type CrmWriter } from "../writer.js";
6
+ import { type CrmActivityDraft, type CrmActivityWrite, type CrmVerb, type CrmWriteCapabilities, type CrmWriter } from "../writer.js";
7
7
  import { type CrmWrites } from "../writes.js";
8
8
  import { type CrmManifestSource } from "./source.js";
9
+ /**
10
+ * Activities the manifest does not describe, written by the CLI's own functions over `send`: a comment, a task and a
11
+ * task marked done. Each answers the activity as the source's `activities` maps it, with the same id, or the next full
12
+ * sync takes it for one the CRM deleted.
13
+ */
14
+ export interface CrmManifestActivities {
15
+ /** The operation each sends, whose `api` keys the write checks too; a task needs `close` as well. */
16
+ operations: {
17
+ readonly comment?: string;
18
+ readonly task?: string;
19
+ readonly close?: string;
20
+ };
21
+ create(draft: CrmActivityDraft, send: ServiceApiCall): Promise<CrmActivity>;
22
+ complete?(externalId: string, send: ServiceApiCall): Promise<CrmActivity>;
23
+ }
9
24
  export interface CrmManifestWriterOptions {
10
25
  api: ServiceApiManifest;
11
26
  /** The service's name in messages: "Attio". */
@@ -14,14 +29,17 @@ export interface CrmManifestWriterOptions {
14
29
  send: ServiceApiCall;
15
30
  /** The source over the same manifest: the read-back after each write, and the pipelines a close looks in. */
16
31
  source: () => CrmManifestSource;
32
+ activities?: CrmManifestActivities;
17
33
  }
18
- /** What the manifest's writes take, for `addCrmCommands({ writes })`; none when it describes no writes. */
19
- export declare const crmManifestWriteCapabilities: (input: unknown, api: ServiceApiManifest) => CrmWriteCapabilities | undefined;
34
+ /** What the manifest's writes and the CLI's activities take, for `addCrmCommands({ writes })`; none when neither. */
35
+ export declare const crmManifestWriteCapabilities: (input: unknown, api: ServiceApiManifest, activities?: CrmManifestActivities) => CrmWriteCapabilities | undefined;
20
36
  /**
21
37
  * The `api` keys each CRM write also checks, those of the operation it sends, so `api.<operation>: deny` stops the
22
38
  * write too: for `CrmWrites.alsoChecks` and `crmAlsoChecks`, so `--dry-run` names them.
23
39
  */
24
40
  export declare const crmManifestWriteKeys: (input: unknown, api: ServiceApiManifest, bodyPermissions?: ServiceApiPermissionsInput["bodyPermissions"]) => ((kind: CrmKind, verb: CrmVerb) => PermissionKey[]);
41
+ /** The `api` keys of the operation each activity write sends, for `CrmWrites.activityChecks` and `crmAlsoChecks`. */
42
+ export declare const crmManifestActivityKeys: (api: ServiceApiManifest, activities: CrmManifestActivities | undefined, bodyPermissions?: ServiceApiPermissionsInput["bodyPermissions"]) => ((write: CrmActivityWrite | "close") => PermissionKey[]);
25
43
  /**
26
44
  * A `CrmWriter` from a manifest's `writes`: each of our fields goes to the service by its rule, a field with no rule is
27
45
  * refused before anything is sent, and every write is sent once and read back by the entity's `get`, as a sync maps
@@ -31,6 +49,7 @@ export declare const crmWriterFromManifest: (input: unknown, options: CrmManifes
31
49
  export interface CrmManifestWritesOptions extends ServiceApiCallOptions, Pick<ServiceApiPermissionsInput, "bodyPermissions">, Omit<CrmWrites, "writer" | "alsoChecks"> {
32
50
  /** The CLI's source over the same manifest (`crmSourceFromManifest`). */
33
51
  source: () => CrmManifestSource;
52
+ activities?: CrmManifestActivities;
34
53
  }
35
54
  /**
36
55
  * `CrmRun.writes` for a CLI whose writes its manifest describes: the writer over the CLI's fetch and token, and the
@@ -3,11 +3,21 @@ import { serviceApiOwnKeys } from "../../cli/service-api.js";
3
3
  import { serviceApiSend } from "../../cli/service-api-call.js";
4
4
  import { DEAL_KINDS } from "../../domain/deals.js";
5
5
  import { fullName, id, isRaw, text } from "../values.js";
6
- import { CRM_VERBS } from "../writer.js";
6
+ import { CRM_VERBS, } from "../writer.js";
7
7
  import { foldFieldName } from "../writes.js";
8
8
  import { parseCrmManifest, } from "./manifest.js";
9
9
  import { at } from "./map.js";
10
10
  import { fill, inputOf } from "./source.js";
11
+ const activityWritesOf = (activities) => {
12
+ if (!activities)
13
+ return [];
14
+ const { operations, complete } = activities;
15
+ if (operations.task !== undefined && (operations.close === undefined || complete === undefined))
16
+ throw new CliError("configuration_error", "source manifest: activities: a task needs close and complete", {
17
+ reason: "manifest.invalid",
18
+ });
19
+ return ["comment", "task"].filter((write) => operations[write] !== undefined);
20
+ };
11
21
  const CALL_OF = {
12
22
  create: "create",
13
23
  update: "update",
@@ -21,12 +31,13 @@ const ruleOf = (one, field) => one.fields[field];
21
31
  const takes = (kind, one, verb) => verb === "move" || verb === "close"
22
32
  ? isDealKind(kind) && one.update !== undefined && typeof ruleOf(one, "stage") === "object"
23
33
  : one[CALL_OF[verb]] !== undefined;
24
- const capabilitiesOf = (manifest) => {
34
+ const capabilitiesOf = (manifest, activities) => {
25
35
  const written = manifest.kinds.flatMap((kind) => {
26
36
  const one = manifest.writes?.[kind];
27
37
  return one ? [{ kind, one }] : [];
28
38
  });
29
- if (written.length === 0)
39
+ const activityWrites = activityWritesOf(activities);
40
+ if (written.length === 0 && activityWrites.length === 0)
30
41
  return undefined;
31
42
  return {
32
43
  kinds: written.map(({ kind }) => kind),
@@ -34,10 +45,11 @@ const capabilitiesOf = (manifest) => {
34
45
  // No slot sends the operation id, so a repeated write would be made again.
35
46
  idempotent: false,
36
47
  fields: Object.fromEntries(written.map(({ kind, one }) => [kind, [...Object.keys(one.fields), ...(one.custom ? ["custom"] : [])]])),
48
+ ...(activityWrites.length === 0 ? {} : { activities: activityWrites }),
37
49
  };
38
50
  };
39
- /** What the manifest's writes take, for `addCrmCommands({ writes })`; none when it describes no writes. */
40
- export const crmManifestWriteCapabilities = (input, api) => capabilitiesOf(parseCrmManifest(input, api));
51
+ /** What the manifest's writes and the CLI's activities take, for `addCrmCommands({ writes })`; none when neither. */
52
+ export const crmManifestWriteCapabilities = (input, api, activities) => capabilitiesOf(parseCrmManifest(input, api), activities);
41
53
  /**
42
54
  * The `api` keys each CRM write also checks, those of the operation it sends, so `api.<operation>: deny` stops the
43
55
  * write too: for `CrmWrites.alsoChecks` and `crmAlsoChecks`, so `--dry-run` names them.
@@ -51,6 +63,19 @@ export const crmManifestWriteKeys = (input, api, bodyPermissions) => {
51
63
  return operation ? serviceApiOwnKeys(operation, bodyPermissions) : [];
52
64
  };
53
65
  };
66
+ /** The `api` keys of the operation each activity write sends, for `CrmWrites.activityChecks` and `crmAlsoChecks`. */
67
+ export const crmManifestActivityKeys = (api, activities, bodyPermissions) => {
68
+ const operations = new Map(api.operations.map((one) => [one.id, one]));
69
+ return (write) => {
70
+ const id = activities?.operations[write];
71
+ const operation = id === undefined ? undefined : operations.get(id);
72
+ if (id !== undefined && !operation)
73
+ throw new CliError("configuration_error", `source manifest: activities: no operation ${id}`, {
74
+ reason: "manifest.invalid",
75
+ });
76
+ return operation ? serviceApiOwnKeys(operation, bodyPermissions) : [];
77
+ };
78
+ };
54
79
  const refused = (message, param) => new CliError("validation_error", message, { reason: "crm.record-field", sent: false, ...(param ? { param } : {}) });
55
80
  /** Our fields that write one key of the service together, by that key: Attio's name and its parts. */
56
81
  const sharedOf = (one) => {
@@ -81,7 +106,7 @@ const merged = (entries, list) => {
81
106
  */
82
107
  export const crmWriterFromManifest = (input, options) => {
83
108
  const manifest = parseCrmManifest(input, options.api);
84
- const capabilities = capabilitiesOf(manifest);
109
+ const capabilities = capabilitiesOf(manifest, options.activities);
85
110
  if (!capabilities)
86
111
  throw new CliError("configuration_error", "source manifest: writes: it describes no writes", {
87
112
  reason: "manifest.invalid",
@@ -255,9 +280,15 @@ export const crmWriterFromManifest = (input, options) => {
255
280
  throw refused(`the ${kind}'s pipeline ${item.pipeline} has no ${outcome} stage in ${service}`);
256
281
  return stage.externalId;
257
282
  };
283
+ const { activities } = options;
284
+ const complete = activities?.complete?.bind(activities);
258
285
  return {
259
286
  provider: manifest.provider,
260
287
  capabilities,
288
+ ...(activities ? { createActivity: (draft) => activities.create(draft, send) } : {}),
289
+ ...(complete && capabilities.activities?.includes("task")
290
+ ? { completeActivity: (externalId) => complete(externalId, send) }
291
+ : {}),
261
292
  async create(kind, draft, written) {
262
293
  const one = specOf(kind, "create");
263
294
  const answer = await sent(one.create, { values: await valuesOf(kind, one, draft) });
@@ -289,10 +320,17 @@ export const crmWriterFromManifest = (input, options) => {
289
320
  * `api` keys of each operation it sends as `alsoChecks`. The writes' guard asks before each one and journals it.
290
321
  */
291
322
  export const crmManifestWrites = (input, options) => {
292
- const { manifest: api, service, source, app, settings, self, ownedByDefault, env, warn } = options;
323
+ const { manifest: api, service, source, app, settings, self, ownedByDefault, env, warn, activities } = options;
293
324
  return {
294
- writer: crmWriterFromManifest(input, { api, service, send: serviceApiSend(options), source }),
325
+ writer: crmWriterFromManifest(input, {
326
+ api,
327
+ service,
328
+ send: serviceApiSend(options),
329
+ source,
330
+ ...(activities ? { activities } : {}),
331
+ }),
295
332
  alsoChecks: crmManifestWriteKeys(input, api, options.bodyPermissions),
333
+ ...(activities ? { activityChecks: crmManifestActivityKeys(api, activities, options.bodyPermissions) } : {}),
296
334
  app,
297
335
  settings,
298
336
  ...(self === undefined ? {} : { self }),
@@ -150,9 +150,10 @@ export declare const CRM_WRITE_KEYS: readonly PermissionKey[];
150
150
  /**
151
151
  * Every key a CRM write command may check beyond its own path, for `commandPermissions({ alsoChecks })`, so its
152
152
  * `--dry-run` names each: a stage implies the move key and a won or lost one the close key, an owner other than the
153
- * sign-in's `crm.assign-others`, and `also` the CLI's own (the same `CrmWrites.alsoChecks` the real run checks).
153
+ * sign-in's `crm.assign-others`, and `also` the CLI's own (the same `CrmWrites.alsoChecks` the real run checks), and
154
+ * `activities` those of an activity write (`CrmWrites.activityChecks`).
154
155
  */
155
- export declare const crmAlsoChecks: (also?: (kind: CrmKind, verb: CrmVerb) => readonly PermissionKey[]) => (path: readonly string[]) => readonly (PermissionKey | ConditionalKey)[];
156
+ export declare const crmAlsoChecks: (also?: (kind: CrmKind, verb: CrmVerb) => readonly PermissionKey[], activities?: (write: CrmActivityWrite | "close") => readonly PermissionKey[]) => (path: readonly string[]) => readonly (PermissionKey | ConditionalKey)[];
156
157
  /**
157
158
  * Built in, and only ever tightening (WC-PERM-7): an ordinary change goes ahead, a deletion asks, and a record is not
158
159
  * given to somebody else until the owner allows it.
@@ -21,12 +21,18 @@ const VERB_OF = {
21
21
  /**
22
22
  * Every key a CRM write command may check beyond its own path, for `commandPermissions({ alsoChecks })`, so its
23
23
  * `--dry-run` names each: a stage implies the move key and a won or lost one the close key, an owner other than the
24
- * sign-in's `crm.assign-others`, and `also` the CLI's own (the same `CrmWrites.alsoChecks` the real run checks).
24
+ * sign-in's `crm.assign-others`, and `also` the CLI's own (the same `CrmWrites.alsoChecks` the real run checks), and
25
+ * `activities` those of an activity write (`CrmWrites.activityChecks`).
25
26
  */
26
- export const crmAlsoChecks = (also) => (path) => {
27
+ export const crmAlsoChecks = (also, activities) => (path) => {
27
28
  const [noun, command] = path;
29
+ if (noun === "activities" && command === "close" && path.length === 2)
30
+ return activities?.("close") ?? [];
28
31
  if (noun === "activities" && command === "create" && path.length === 2)
29
- return [{ key: CRM_ASSIGN_OTHERS_KEY, when: "--owner other than the sign-in's user" }];
32
+ return [
33
+ { key: CRM_ASSIGN_OTHERS_KEY, when: "--owner other than the sign-in's user" },
34
+ ...["comment", "task"].flatMap((write) => (activities?.(write) ?? []).map((key) => ({ key, when: `a ${write}` }))),
35
+ ];
30
36
  const kind = noun === undefined ? undefined : PLURALS[noun];
31
37
  const verb = command === undefined ? undefined : VERB_OF[command];
32
38
  if (path.length !== 2 || kind === undefined || verb === undefined)
@@ -24,6 +24,8 @@ export interface CrmWrites extends ProfileWrites {
24
24
  * `crmAlsoChecks` so `--dry-run` names them.
25
25
  */
26
26
  alsoChecks?: (kind: CrmKind, verb: CrmVerb) => readonly PermissionKey[];
27
+ /** The same for an activity write, a comment, a task or a task marked done; pass it to `crmAlsoChecks` too. */
28
+ activityChecks?: (write: CrmActivityWrite | "close") => readonly PermissionKey[];
27
29
  }
28
30
  export interface CrmWriteContext {
29
31
  store: MessageStore;
@@ -552,9 +552,12 @@ const activityTargetOf = async (context, given) => {
552
552
  throw new CliError("validation_error", `--subject takes deal:<id>, lead:<id>, person:<id> or organization:<id> as the copy's lists and deals show give ` +
553
553
  `them, or person:crm:<id> or organization:crm:<id> by the CRM's id; got ${given}`, { reason: "ref.malformed", param: "--subject" });
554
554
  };
555
- const activityKeys = async (context, key, owner) => ({
555
+ const activityKeys = async (context, key, owner, write) => ({
556
556
  key,
557
- extra: owner !== undefined && owner !== (await selfOf(context)) ? [CRM_ASSIGN_OTHERS_KEY] : [],
557
+ extra: [
558
+ ...(owner !== undefined && owner !== (await selfOf(context)) ? [CRM_ASSIGN_OTHERS_KEY] : []),
559
+ ...(context.writes.activityChecks?.(write) ?? []),
560
+ ],
558
561
  });
559
562
  /** The CRM's answer into the store, as a sync saves it; a failure names the activity, which the CRM has written. */
560
563
  const keptActivity = async (context, activity, operationId) => {
@@ -615,7 +618,7 @@ export const createCrmActivity = async (context, kind, input, options = {}) => {
615
618
  on: targets.map(({ kind, externalId }) => ({ kind, externalId })),
616
619
  };
617
620
  const operationId = operationOf(context, options.operationId);
618
- const activity = await written(context, await activityKeys(context, "activities.create", owner), operationId, () => create(draft, { operationId }));
621
+ const activity = await written(context, await activityKeys(context, "activities.create", owner, kind), operationId, () => create(draft, { operationId }));
619
622
  const stored = await keptActivity(context, activity, operationId);
620
623
  return { operationId, activity, stored, on: await answeredTargets(context, activity, targets) };
621
624
  };
@@ -630,7 +633,7 @@ export const completeCrmActivity = async (context, externalId, options = {}) =>
630
633
  reason: "ref.malformed",
631
634
  });
632
635
  const operationId = operationOf(context, options.operationId);
633
- const activity = await written(context, await activityKeys(context, "activities.close", undefined), operationId, () => complete(externalId, { operationId }));
636
+ const activity = await written(context, await activityKeys(context, "activities.close", undefined, "close"), operationId, () => complete(externalId, { operationId }));
634
637
  const stored = await keptActivity(context, activity, operationId);
635
638
  return { operationId, activity, stored, on: await answeredTargets(context, activity, []) };
636
639
  };
@@ -7,9 +7,14 @@ export declare const ROLE_ADDRESS_WORDS: {
7
7
  readonly noReply: readonly ["noreply", "no-reply", "donotreply", "do-not-reply", "mailer-daemon", "bounce", "bounces"];
8
8
  readonly shared: readonly ["info", "hello", "hi", "contact", "contacts", "support", "help", "helpdesk", "service", "sales", "office", "admin", "team", "billing", "accounts", "accounting", "invoices", "finance", "hr", "jobs", "careers", "press", "media", "marketing", "partners", "legal", "privacy", "security", "abuse", "postmaster", "webmaster", "mail", "inbox", "enquiries", "inquiries", "booking", "reservations", "orders", "feedback", "newsletter", "notifications", "alerts"];
9
9
  };
10
- /** Whether the whole local part, `+tag` and `.`/`-`/`_` aside, is a role word: `info@`, `Hello+news@`, `no_reply@`. */
10
+ /** Whether the address is a no-reply one, which belongs to no person: `noreply-12345@`, `service.no-reply@`. */
11
+ export declare const isNoReplyAddress: (address: string) => boolean;
12
+ /**
13
+ * Whether the whole local part, `+tag` and `.`/`-`/`_` aside, is a role word (`info@`, `Hello+news@`, `no_reply@`),
14
+ * or the address is a no-reply one.
15
+ */
11
16
  export declare const isRoleAddress: (address: string) => boolean;
12
17
  /** Whether the address is a role address that one person often reads alone, such as `hr@`. */
13
18
  export declare const isPersonLikeRoleAddress: (address: string) => boolean;
14
- /** Whether the address is a no-reply one, which belongs to no person. */
15
- export declare const isNoReplyAddress: (address: string) => boolean;
19
+ /** Whether a program sends from the address: `notify@`, `alerts@`, `bank-notifications@`. */
20
+ export declare const isNotificationAddress: (address: string) => boolean;
@@ -53,12 +53,30 @@ export const ROLE_ADDRESS_WORDS = {
53
53
  const bare = (word) => word.replace(/[.\-_]/gu, "");
54
54
  const NO_REPLY = new Set(ROLE_ADDRESS_WORDS.noReply.map(bare));
55
55
  const ROLE = new Set([...ROLE_ADDRESS_WORDS.shared, ...ROLE_ADDRESS_WORDS.noReply].map(bare));
56
- const localWord = (address) => {
56
+ /** Words people's names start with too (`bouncer.joe@`), so they count only as a whole part of the address. */
57
+ const PART_ONLY = new Set(["bounce", "bounces"]);
58
+ const NOTIFY = new Set(["notify", "notification", "notifications", "alert", "alerts"]);
59
+ const localPart = (address) => {
57
60
  const local = address.trim().toLowerCase().split("@")[0] ?? "";
58
- return bare(local.split("+")[0] ?? "");
61
+ return local.split("+")[0] ?? "";
59
62
  };
60
- /** Whether the whole local part, `+tag` and `.`/`-`/`_` aside, is a role word: `info@`, `Hello+news@`, `no_reply@`. */
61
- export const isRoleAddress = (address) => ROLE.has(localWord(address));
63
+ const localWord = (address) => bare(localPart(address));
64
+ const SEPARATORS = /[.\-_]/u;
65
+ const partsOf = (address) => localPart(address).split(SEPARATORS);
66
+ const NO_REPLY_PARTS = ROLE_ADDRESS_WORDS.noReply.map((word) => `.${word.split(SEPARATORS).join(".")}.`);
67
+ /** Whether the address is a no-reply one, which belongs to no person: `noreply-12345@`, `service.no-reply@`. */
68
+ export const isNoReplyAddress = (address) => {
69
+ const word = localWord(address);
70
+ const parts = `.${partsOf(address).join(".")}.`;
71
+ if (NO_REPLY_PARTS.some((one) => parts.includes(one)))
72
+ return true;
73
+ return [...NO_REPLY].some((one) => !PART_ONLY.has(one) && (word.startsWith(one) || word.endsWith(one)));
74
+ };
75
+ /**
76
+ * Whether the whole local part, `+tag` and `.`/`-`/`_` aside, is a role word (`info@`, `Hello+news@`, `no_reply@`),
77
+ * or the address is a no-reply one.
78
+ */
79
+ export const isRoleAddress = (address) => ROLE.has(localWord(address)) || isNoReplyAddress(address);
62
80
  /**
63
81
  * Role words that one person often reads alone: a small company's `hr@` is its HR manager. Still a role address, so it
64
82
  * joins no one, but weaker evidence of a company's mailbox than `info@`, and it never makes a contact a company.
@@ -66,5 +84,5 @@ export const isRoleAddress = (address) => ROLE.has(localWord(address));
66
84
  const PERSON_LIKE = new Set(["hr"]);
67
85
  /** Whether the address is a role address that one person often reads alone, such as `hr@`. */
68
86
  export const isPersonLikeRoleAddress = (address) => PERSON_LIKE.has(localWord(address));
69
- /** Whether the address is a no-reply one, which belongs to no person. */
70
- export const isNoReplyAddress = (address) => NO_REPLY.has(localWord(address));
87
+ /** Whether a program sends from the address: `notify@`, `alerts@`, `bank-notifications@`. */
88
+ export const isNotificationAddress = (address) => partsOf(address).some((part) => NOTIFY.has(part));
@@ -5,7 +5,7 @@
5
5
  export declare const PERSON_KINDS: readonly ["person", "organization", "automated", "stranger", "unsorted", "test"];
6
6
  export type PersonKind = (typeof PERSON_KINDS)[number];
7
7
  /** What decided a kind, besides the ties that make someone a `person`. */
8
- export type KindSignal = "test-data" | "bot" | "no-reply" | "bulk-mail" | "bulk-never-replied" | "automated-name" | "organization" | "role-address" | "company-name" | "no-tie" | "no-name";
8
+ export type KindSignal = "test-data" | "bot" | "no-reply" | "notification-address" | "auto-submitted" | "null-return-path" | "bulk-mail" | "bulk-never-replied" | "automated-name" | "organization" | "role-address" | "company-name" | "no-tie" | "no-name";
9
9
  /** A sender that is a program: «Notifications», «Рассылка», «no-reply». */
10
10
  export declare const isAutomatedName: (name: string | null) => boolean;
11
11
  /** A legal form or a word only a business calls itself: «ООО Ромашка», «CZECH AIRLINES», «OpenWeather Team». */
@@ -689,6 +689,7 @@ const OTHERS = [
689
689
  validation("organization.ambiguous", "more than one organization matches; name the one meant as a reference"),
690
690
  validation("identity.shared-phone", "more than six people share the phone number, so it proposes no one"),
691
691
  validation("identity.common-name", "more than six people have the name, so it proposes no one"),
692
+ validation("identity.not-a-person", "a bot, a program or an organization is never proposed as a person by name"),
692
693
  validation("identity.owner", "one side is the owner's person, and only the owner joins anyone to themselves"),
693
694
  validation("identity.shared-email", "more than six people share the address, so it proposes no one"),
694
695
  validation("identity-link.dedicated-review", "an identity link is staged and decided through the people review"),
@@ -4,4 +4,4 @@ import type { Listed } from "./source.js";
4
4
  /** The Date header, or the server's internal date when the header is missing or unreadable. */
5
5
  export declare const sentAtOf: (date: string | null, receivedAt: string) => number;
6
6
  /** What one read email stores of itself, whichever run read it; where it is filed is the caller's. */
7
- export declare const parsedEmail: (mail: ParsedMail, item: Listed, header: Record<string, string | boolean>, address: string) => Omit<EmailInput, "mailboxes">;
7
+ export declare const parsedEmail: (mail: ParsedMail, item: Listed, header: Record<string, string | boolean>, own: ReadonlySet<string>, inSent?: boolean) => Omit<EmailInput, "mailboxes">;
@@ -1,11 +1,12 @@
1
1
  import { addressOf } from "./attachments.js";
2
+ import { sentByOwner } from "./own.js";
2
3
  /** The Date header, or the server's internal date when the header is missing or unreadable. */
3
4
  export const sentAtOf = (date, receivedAt) => {
4
5
  const sent = date === null ? Number.NaN : Date.parse(date);
5
6
  return Number.isNaN(sent) ? Date.parse(receivedAt) : sent;
6
7
  };
7
8
  /** What one read email stores of itself, whichever run read it; where it is filed is the caller's. */
8
- export const parsedEmail = (mail, item, header, address) => ({
9
+ export const parsedEmail = (mail, item, header, own, inSent = false) => ({
9
10
  externalId: item.messageId,
10
11
  subject: mail.subject,
11
12
  from: mail.from === null ? null : addressOf(mail.from),
@@ -17,5 +18,5 @@ export const parsedEmail = (mail, item, header, address) => ({
17
18
  bodyText: mail.text || null,
18
19
  size: item.size ?? null,
19
20
  ...(Object.keys(header).length ? { headers: header } : {}),
20
- outgoing: mail.from === null ? null : mail.from.email === address,
21
+ outgoing: sentByOwner(mail.from?.email, own, inSent),
21
22
  });
@@ -1,8 +1,13 @@
1
1
  import type { MailSource } from "./source.js";
2
2
  export declare const GMAIL_ALL_MAIL = "[Gmail]/All Mail";
3
+ /** The IMAP folder of mail the owner sent, as the source names it; Gmail's sent mail is in All Mail. */
4
+ export declare const sentFolder: (account: {
5
+ mode?: string;
6
+ }, source?: Pick<MailSource, "folders">) => Promise<string | undefined>;
3
7
  /**
4
8
  * The folders to read. Gmail names All Mail in the account's language, so it is found by its role; a source that
5
- * cannot say, or a listing without it, falls back to the English name and the read reports a missing folder.
9
+ * cannot say, or a listing without it, falls back to the English name and the read reports a missing folder. IMAP
10
+ * reads INBOX and the Sent folder, since a contact's tie is mail the owner wrote.
6
11
  */
7
12
  export declare const mailFolders: (account: {
8
13
  mode?: string;
@@ -1,13 +1,18 @@
1
1
  export const GMAIL_ALL_MAIL = "[Gmail]/All Mail";
2
+ const listedFolders = (source) => source?.folders?.().then((found) => found, () => undefined);
3
+ /** The IMAP folder of mail the owner sent, as the source names it; Gmail's sent mail is in All Mail. */
4
+ export const sentFolder = async (account, source) => (account.mode === "imap" ? (await listedFolders(source))?.sent : undefined);
2
5
  /**
3
6
  * The folders to read. Gmail names All Mail in the account's language, so it is found by its role; a source that
4
- * cannot say, or a listing without it, falls back to the English name and the read reports a missing folder.
7
+ * cannot say, or a listing without it, falls back to the English name and the read reports a missing folder. IMAP
8
+ * reads INBOX and the Sent folder, since a contact's tie is mail the owner wrote.
5
9
  */
6
10
  export const mailFolders = async (account, source) => {
7
11
  if (account.folders)
8
12
  return account.folders;
9
- if (account.mode === "imap")
10
- return ["INBOX"];
11
- const all = await source?.folders?.().then(({ all }) => all, () => undefined);
12
- return [all ?? GMAIL_ALL_MAIL];
13
+ if (account.mode === "imap") {
14
+ const sent = await sentFolder(account, source);
15
+ return sent === undefined || sent === "INBOX" ? ["INBOX"] : ["INBOX", sent];
16
+ }
17
+ return [(await listedFolders(source))?.all ?? GMAIL_ALL_MAIL];
13
18
  };
@@ -28,18 +28,22 @@ export interface MailHeaders {
28
28
  }
29
29
  export declare const unfold: (text: string) => string;
30
30
  export declare const field: (unfolded: string, name: string) => string | undefined;
31
+ /** The verdicts in Gmail's own Authentication-Results. */
32
+ export declare const authOf: (unfolded: string) => AuthVerdicts | undefined;
31
33
  /**
32
- * The verdicts in Gmail's own Authentication-Results. Only the copy Gmail stamps as mx.google.com counts: a sender
33
- * can add one under any other name, and Gmail removes forged copies under its own (RFC 8601 §5).
34
+ * The header fields a DKIM signature Gmail passed covers, when that signature's domain is the From's own (its
35
+ * registrable domain). A sender writes every header itself; only a signature of its own domain vouches for one.
36
+ * Without Gmail's stamp nothing is trusted: other servers' Authentication-Results may be the sender's own.
34
37
  */
35
- export declare const authOf: (unfolded: string) => AuthVerdicts | undefined;
38
+ export declare const signedFieldsOf: (unfolded: string, from: string | undefined) => Set<string>;
36
39
  export declare const addressesOf: (value: string | undefined) => string[];
37
40
  /** The header fields of one email, from its header text. */
38
41
  export declare const headersOf: (text: string) => MailHeaders;
39
42
  /** The header fields of a whole email, as `headersOf` reads them from a listing. */
40
43
  export declare const headersOfRaw: (raw: Uint8Array) => MailHeaders;
41
44
  /**
42
- * List-Id, the bulk-mail fields, Reply-To and Gmail's SPF, DKIM and DMARC verdicts of a whole email, kept on mail
43
- * stored in full so a rule or a sender score can be worked out from the store later. Names are lower case.
45
+ * List-Id, the bulk-mail fields, Reply-To, Gmail's SPF, DKIM and DMARC verdicts and what marks a program or a list
46
+ * (`programSignalsOf`) of a whole email, kept on mail stored in full so a rule, a sender score or a person's kind can
47
+ * be worked out from the store later. Names are lower case.
44
48
  */
45
49
  export declare const mailHeadersOf: (raw: Uint8Array) => Record<string, string | boolean>;