@wirecat/cli-core 0.648.0 → 0.650.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 (85) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/dist/analysis/anthropic.js +2 -1
  3. package/dist/background/daily-archive-timer.d.ts +1 -1
  4. package/dist/cli/account-remove.d.ts +2 -0
  5. package/dist/cli/account-remove.js +46 -10
  6. package/dist/cli/messenger/messages-search-command.js +6 -1
  7. package/dist/cli/messenger/search-answers.d.ts +3 -1
  8. package/dist/cli/messenger/search-answers.js +3 -1
  9. package/dist/cli/steps.js +9 -0
  10. package/dist/cli/unknown-profile.js +1 -0
  11. package/dist/constants/index.d.ts +6 -0
  12. package/dist/constants/index.js +14 -0
  13. package/dist/crm/cli/index.js +30 -5
  14. package/dist/crm/source.d.ts +8 -1
  15. package/dist/crm/stage-tasks.d.ts +3 -1
  16. package/dist/crm/stage-tasks.js +8 -4
  17. package/dist/crm/sync.d.ts +1 -1
  18. package/dist/crm/sync.js +54 -0
  19. package/dist/domain/crm.d.ts +15 -0
  20. package/dist/domain/phones.d.ts +2 -0
  21. package/dist/domain/phones.js +3 -0
  22. package/dist/domain/providers.d.ts +4 -1
  23. package/dist/domain/providers.js +9 -2
  24. package/dist/domain/record-types.d.ts +24 -3
  25. package/dist/domain/record-types.js +23 -2
  26. package/dist/domain/records-table.js +4 -3
  27. package/dist/domain/records.d.ts +1 -1
  28. package/dist/domain/records.js +3 -2
  29. package/dist/entities/contact-context.d.ts +6 -0
  30. package/dist/entities/contact-context.js +3 -0
  31. package/dist/entities/deal.d.ts +4 -0
  32. package/dist/entities/deal.js +3 -0
  33. package/dist/entities/index.d.ts +12 -0
  34. package/dist/entities/recorded-meeting.d.ts +17 -0
  35. package/dist/entities/recorded-meeting.js +15 -0
  36. package/dist/errors/reasons.js +3 -4
  37. package/dist/index.d.ts +1 -1
  38. package/dist/meetings/answers.d.ts +5 -0
  39. package/dist/meetings/answers.js +3 -0
  40. package/dist/meetings/index.d.ts +1 -1
  41. package/dist/meetings/participant-search.d.ts +5 -0
  42. package/dist/meetings/pull.js +2 -1
  43. package/dist/meetings/read-answers.d.ts +4 -0
  44. package/dist/meetings/read-answers.js +1 -0
  45. package/dist/meetings/source.d.ts +5 -0
  46. package/dist/meetings/store.d.ts +10 -1
  47. package/dist/models/ai.js +2 -2
  48. package/dist/models/endpoint.d.ts +7 -0
  49. package/dist/models/endpoint.js +10 -0
  50. package/dist/models/index.js +2 -2
  51. package/dist/oauth/keeper.js +1 -1
  52. package/dist/sends/guard.js +8 -6
  53. package/dist/services/communications.d.ts +2 -2
  54. package/dist/services/communications.js +24 -2
  55. package/dist/services/document-source.js +9 -1
  56. package/dist/services/meeting-model.js +2 -1
  57. package/dist/services/notes-search.d.ts +10 -5
  58. package/dist/services/notes-search.js +19 -7
  59. package/dist/services/person-context.d.ts +3 -0
  60. package/dist/services/person-context.js +9 -1
  61. package/dist/services/person-meetings.d.ts +36 -0
  62. package/dist/services/person-meetings.js +57 -0
  63. package/dist/services/search-all.js +18 -10
  64. package/dist/speech/openai.js +5 -2
  65. package/dist/store/sqlite/added-sources.d.ts +38 -0
  66. package/dist/store/sqlite/added-sources.js +80 -50
  67. package/dist/store/sqlite/crm-settings.d.ts +5 -1
  68. package/dist/store/sqlite/crm-settings.js +8 -0
  69. package/dist/store/sqlite/crm-stage-entries.d.ts +15 -0
  70. package/dist/store/sqlite/crm-stage-entries.js +74 -0
  71. package/dist/store/sqlite/crm.d.ts +8 -1
  72. package/dist/store/sqlite/crm.js +7 -1
  73. package/dist/store/sqlite/identities.js +3 -1
  74. package/dist/store/sqlite/involvements.d.ts +2 -0
  75. package/dist/store/sqlite/involvements.js +4 -1
  76. package/dist/store/sqlite/meeting-participant-search.js +9 -3
  77. package/dist/store/sqlite/meetings.js +7 -2
  78. package/dist/store/sqlite/person-match-scan.js +39 -15
  79. package/dist/store/sqlite/record-projectors-document.d.ts +12 -0
  80. package/dist/store/sqlite/record-projectors-document.js +81 -0
  81. package/dist/store/sqlite/record-projectors.js +2 -0
  82. package/dist/update/index.d.ts +1 -1
  83. package/dist/update/index.js +4 -2
  84. package/package.json +1 -1
  85. package/schemas/records-envelope.v1.schema.json +57 -2
package/CHANGELOG.md CHANGED
@@ -5,6 +5,103 @@ 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.650.0 — 13.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A call links to the CRM contact with the same phone.** A meeting source gives a participant's number
13
+ in `SourceParticipant.phone` (written with `+`); the store keeps it in `identities.phone`. The people scan then
14
+ joins the call's person and one other person when exactly the two hold the number, one of them is keyed by the
15
+ number itself (`phone:<E.164>`, as a phone line keeps a call's other side) and the number is a mobile; a landline
16
+ only proposes the pair, since an office's main line is everyone's who works there. The scan reads a CRM's number
17
+ written without `+` (`8 (912) 345-67-89`) in the store's `phone_countries`, and the contact's other numbers too.
18
+ See [MEETINGS.md, "Calls and the people they link to"](docs/dev/MEETINGS.md#calls-and-the-people-they-link-to).
19
+ - **`meetings show` and `meetings people` name each participant's person**: `person: { ref, name }`, `null` when the
20
+ identity is linked to no one; `meetings people` also finds a participant by that name.
21
+ - **A person's, an organization's and a deal's context list their recorded calls.** `contacts context` and the
22
+ canonical person context answer `meetings[]` (`personMeetings`); `communicationsOf`, and so the deal and
23
+ organization contexts, counts each call as a `meeting` touch with its `meeting:` ref; `deals show` and `leads show`
24
+ of a CRM copy answer `meetings[]`, the newest 10 of the people on it. Each item opens with `meetings show
25
+ <meeting_id>` of the CLI that owns its `account`.
26
+ - **`CORE_HOSTS` in `@wirecat/cli-core/constants`**: the hosts cli-core itself reaches in any tool (npm for
27
+ `upgrade`, the default model providers, the model downloads and the hosts they redirect to). A tool spreads them
28
+ into its WCAT identity's `hosts`, so `cli-dev manifest` lists them.
29
+ - **Stage tasks open on every stage a deal or lead entered, also one passed between two syncs.** A CRM source may
30
+ give `stageHistory(kind, since, after, context)`: the CRM's own record of each entry into a stage. While the
31
+ account has `stage-tasks` rules for the kind, `sync` reads it after the last entry it read (the first read from
32
+ when stage tasks last ran), keeps the entries on kept deals and leads as `crm.stage-entry` records, and the stage
33
+ tasks open from them: a deal moved A→B→C between two syncs gets the tasks of B and C. A source without it keeps
34
+ comparing the copy between syncs. A failed read is the issue `crm.stage-history-failed`; the deals and leads are
35
+ still synced. The funnel still counts the copy's own stage changes.
36
+
37
+ ### Changed — may break callers
38
+
39
+ - **`oauth.missing` is now `session.missing`, and `ai.address-refused` is now `model.address-refused`.**
40
+ One reason for each: a profile that is not signed in, and a model address WireCat refuses. A CLI that raises or
41
+ checks the old names moves to the new ones.
42
+ - **The output schemas of `meetings show`, `meetings people`, `contacts context`, the person context and `deals
43
+ show` / `leads show` gain the fields above.** A CLI that pins its MCP output schemas updates its contract.
44
+
45
+ ### Fixed
46
+
47
+ - **The read-only lock lets server search and fetches through.** `<PREFIX>_READ_ONLY` promises "can read and sync but
48
+ never send", yet it refused every key the send guard checks, reads included: `search messages --backend server`
49
+ failed with `permission_error`, and the default `--backend both` dropped the server without a word. The keys that
50
+ only read from the messenger or work locally (`messages.server-search`, `messages.sync-first`, the stats syncs,
51
+ `conversations.embeddings`, `conversations.links`, `attachments.extract`, `store.gaps.repair`) now pass the lock, as
52
+ they already passed a flood hold. The profile's permission level still applies to each. Found by an agent test in
53
+ which tg under `TG_READ_ONLY` answered 6 of 10 questions and a Telegram MCP server 9
54
+ (tg-cli [#874](https://github.com/WireCatLabs/tg-cli/issues/874)).
55
+ - **An archive-only search over a partial history points at the server's search.** `search messages --backend
56
+ archive` on a messenger with its own search now leads `next` with `search.server` (the same query, `--backend
57
+ server`) when the local store misses part of a chat. Agents told to stay on the archive stopped there and answered
58
+ "not found" for messages the store never held
59
+ (tg-cli [#873](https://github.com/WireCatLabs/tg-cli/issues/873)).
60
+
61
+ ### Security
62
+
63
+ - **The update check, the model calls, the meeting embeddings and OpenAI transcription reach only their own host.**
64
+ They go through cli-base's `hostFetch`: npm's registry, or the host of the model address the person set. A
65
+ redirect to another host is refused, and each exchange has a deadline (2 minutes; 10 for a transcription).
66
+
67
+ - **A run with moved folders removes nothing in the owner's folders (WC-SECR-24).** With only `<PREFIX>_CONFIG_DIR`
68
+ moved, `account remove` deleted the account file, the profile files and a stale serve lock in the owner's real
69
+ state folder, and `--delete-data` purged the account from the owner's store. Now each of them is kept, with its
70
+ reason under `kept`; the serve unit and schedules stay while `HOME` is the owner's.
71
+ [ACCOUNT-REMOVAL.md](docs/dev/ACCOUNT-REMOVAL.md)
72
+
73
+ ## 0.649.0 — 13.11.2026
74
+
75
+ ### Added
76
+
77
+ - **A records envelope carries text search finds: the record type `document`.** Fields `text`, `title`, `created_at`,
78
+ `updated_at`, `url` and `metadata`; relations `about` people, organizations, deals and events (a call, or a meeting's calendar event). It
79
+ becomes a document of the envelope's own account, keyed by the record's external id: the same record again is
80
+ `unchanged`, changed text is the same document's next revision, and a `delete` empties it. Like an SMS or a call, it
81
+ is taken only under an import-only provider. A document's `fields` may take 1 MiB; every other type keeps 64 KiB.
82
+ - **The seeded import-only provider `import`** holds what any other source brings in: `import:crm-notes`,
83
+ `import:obsidian-export`. It holds documents, SMS and calls.
84
+ - **Search reads the documents of import-only accounts under their own name.** An import-only provider (`phone`,
85
+ `import`) holds `documents` beside its other kinds: notes search, `search all` and meaning search read them,
86
+ `--source phone:office-pbx` reads only that account's, and a hit names `phone:office-pbx` with kind `document`.
87
+ The account's SMS and calls stay listed under the same name.
88
+
89
+ ### Changed — may break callers
90
+
91
+ - **An import-only provider holds `documents` beside its own kinds.** `kindsIn("phone")` is now
92
+ `["messages", "events", "documents"]`, and `holdsKind(provider, "documents")` is true for `phone` and `import`. So
93
+ `--source documents` reaches their accounts, and `search notes --source phone:<account>` is read where it was refused.
94
+ - **`searchNotesOf(...).accounts` names an import's account by its own key** (`{ provider: "phone", account:
95
+ "office-pbx" }`): its `provider` is a `string`, no longer only `"notes"`. Every import-only account is in the list
96
+ of what an unscoped notes search read, one that holds only SMS and calls included.
97
+ - **`TABLE_RECORD_TYPES` holds `document`**, so a CSV sheet and `records templates` offer it. SMS and calls still
98
+ have no sheet.
99
+
100
+ ### Fixed
101
+
102
+ - `searchNotesOf` hands its `env` to the search, so meaning search finds the models of the caller's state folder
103
+ instead of the process's.
104
+
8
105
  ## 0.648.0 — 13.11.2026
9
106
 
10
107
  ### Added
@@ -1,2 +1,3 @@
1
1
  import { anthropic } from "../models/anthropic.js";
2
- export const analyze = async (target, system, input, maxTokens) => anthropic.complete(target, { purpose: "analysis", system, prompt: input, maxTokens }, {}, target.apiKey, fetch);
2
+ import { endpointFetch } from "../models/endpoint.js";
3
+ export const analyze = async (target, system, input, maxTokens) => anthropic.complete(target, { purpose: "analysis", system, prompt: input, maxTokens }, {}, target.apiKey, endpointFetch(target.baseUrl, 120_000));
@@ -24,12 +24,12 @@ export interface DailyArchiveTimerInput {
24
24
  }
25
25
  export declare const dailyArchiveTimer: (input: DailyArchiveTimerInput) => DailyArchiveTimer;
26
26
  export declare const manageDailyArchiveTimer: (plan: DailyArchiveTimer, action: "install" | "start" | "stop" | "status" | "uninstall", system: Pick<ServerSystem, "platform" | "run">, env: NodeJS.ProcessEnv, signal?: AbortSignal) => Promise<{
27
- action?: undefined;
28
27
  name: string;
29
28
  installed: boolean;
30
29
  active: boolean;
31
30
  servicePath: string;
32
31
  timerPath: string;
32
+ action?: undefined;
33
33
  } | {
34
34
  active?: undefined;
35
35
  name: string;
@@ -63,6 +63,8 @@ export interface AccountRemoveOptions {
63
63
  provider?: Provider;
64
64
  /** Unset: the one `run()` set. */
65
65
  resolveSettings?: (flags: GlobalFlags, options?: ResolveOptions) => Settings;
66
+ /** The owner's own home; unset, the account's from the user database. A test names its sandbox. */
67
+ ownerHome?: string;
66
68
  }
67
69
  /**
68
70
  * `<tool> <profile> account remove --keep-data|--delete-data`: signs the profile out the tool's way, forgets it on
@@ -11,7 +11,7 @@ import { thisMachine } from "../background/system.js";
11
11
  import { locationVariables, platformFor } from "../background/units.js";
12
12
  import { httpLockFile } from "../mcp/http/state.js";
13
13
  import { sendsPathFor } from "../sends/journal.js";
14
- import { storePath } from "../store/path.js";
14
+ import { accountHome, inOwnerFolder, storePath } from "../store/path.js";
15
15
  import { openStore } from "../store/store.js";
16
16
  import { readConfigFile, withoutPath } from "./config-issues.js";
17
17
  import { baseContext, environmentOf } from "./context.js";
@@ -46,6 +46,20 @@ const insideOwnFolders = (app, env, extra) => {
46
46
  return full;
47
47
  };
48
48
  };
49
+ const within = (path, root) => path === root || path.startsWith(`${root}${sep}`);
50
+ /**
51
+ * WC-SECR-24: the tool's folders as the owner's own run has them. A run with moved folders shares the rest with the
52
+ * owner (only the config folder moved leaves the state folder the owner's), so it removes nothing inside these.
53
+ */
54
+ const ownerFolders = (app, removal, hooks, home) => {
55
+ if (home === undefined)
56
+ return [];
57
+ const env = { HOME: home, USERPROFILE: home };
58
+ return [
59
+ ...Object.values(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env })),
60
+ ...(removal.ownFolders?.({ ...hooks, env }) ?? []),
61
+ ].map((root) => absolute(root));
62
+ };
49
63
  /** The profile's own serve unit, by its exact name, when one is installed; never a pattern over the unit folder. */
50
64
  const serveUnit = (app, system, profile, env) => {
51
65
  if (!env.HOME)
@@ -142,16 +156,32 @@ export const accountRemoveCommand = (app, removal, options = {}) => logsInOrOut(
142
156
  if (holder)
143
157
  throw new CliError("conflict", `${holder} is running for ${profile} — stop it first (\`${app.command} ${profile} server stop\`), then remove the account`, { reason: "account-remove.busy" });
144
158
  const own = insideOwnFolders(app, env, removal.ownFolders?.(hooks) ?? []);
145
- const schedules = listSchedules(state).filter((schedule) => schedule.environment[`${app.envPrefix}_PROFILE`] === profile);
159
+ const ownerHome = options.ownerHome ?? accountHome();
160
+ const movedFolders = isMovedRun({ appName: app.appName, prefix: app.envPrefix, env });
161
+ const owners = movedFolders ? ownerFolders(app, removal, hooks, ownerHome) : [];
162
+ const inOwners = (path) => owners.some((root) => within(absolute(path), root));
163
+ const ownerHomeHere = movedFolders && ownerHome !== undefined && absolute(env.HOME ?? "") === absolute(ownerHome);
164
+ const ownersReason = "a run with moved folders never removes what lies in the owner's own folders";
165
+ const ownersKept = [];
166
+ const theRun = (paths) => paths.flatMap((path) => {
167
+ if (!inOwners(path))
168
+ return [own(path)];
169
+ if (existsSync(path))
170
+ ownersKept.push({ kind: "file", target: absolute(path), reason: ownersReason });
171
+ return [];
172
+ });
173
+ const schedules = movedFolders && (inOwners(state) || ownerHomeHere)
174
+ ? []
175
+ : listSchedules(state).filter((schedule) => schedule.environment[`${app.envPrefix}_PROFILE`] === profile);
146
176
  const serveLock = lockPath(app, profile, env);
147
177
  const staleLock = readLock(serveLock);
148
- const stateFiles = [
178
+ const stateFiles = theRun([
149
179
  accountFile,
150
180
  ...profileFiles(app, profile, env, listSchedules(state)),
151
181
  ...(staleLock && !alive(staleLock.pid) ? [serveLock] : []),
152
182
  ...(removal.stateFiles?.(profile, hooks) ?? []),
153
- ].map(own);
154
- const dataFiles = (removal.dataFiles?.(profile, hooks) ?? []).map(own);
183
+ ]);
184
+ const dataFiles = theRun(removal.dataFiles?.(profile, hooks) ?? []);
155
185
  const account = removal.account?.(profile, hooks) ??
156
186
  (options.provider === undefined ? undefined : recalledAccount(app, options.provider, profile, env));
157
187
  const secrets = (removal.secrets?.(profile, hooks) ?? []).map(({ credentials, accounts }) => ({
@@ -163,14 +193,18 @@ export const accountRemoveCommand = (app, removal, options = {}) => logsInOrOut(
163
193
  }),
164
194
  accounts,
165
195
  }));
166
- const sections = removal.forgetConfig ? [] : configSections(settings.configPath, profile);
196
+ const ownersConfig = inOwners(settings.configPath);
197
+ const sections = removal.forgetConfig || ownersConfig ? [] : configSections(settings.configPath, profile);
198
+ if (ownersConfig)
199
+ ownersKept.push({ kind: "config", target: settings.configPath, reason: ownersReason });
200
+ const ownersStore = movedFolders && inOwnerFolder(storePath(env), ownerHome);
167
201
  const storeHere = existsSync(storePath(env));
168
202
  const system = environmentOf(this).system ?? thisMachine();
169
- const unit = serveUnit(app, system, profile, env);
203
+ const unit = ownerHomeHere ? undefined : serveUnit(app, system, profile, env);
170
204
  if (unit && (await platformFor(app, system, env).state(unit)).active)
171
205
  throw new CliError("conflict", `${unit.name} is running for ${profile} — stop it first (\`${app.command} ${profile} server stop\`), then remove the account`, { reason: "account-remove.busy" });
172
206
  const removed = [{ kind: "sign_in", target: `${app.command} sign-in of ${profile}` }];
173
- const kept = [];
207
+ const kept = [...ownersKept];
174
208
  // An entry the environment supplies is not this tool's to remove.
175
209
  const saved = (store, name) => (store.read(name)?.source ?? "environment") !== "environment";
176
210
  for (const { store, accounts } of secrets)
@@ -193,7 +227,9 @@ export const accountRemoveCommand = (app, removal, options = {}) => logsInOrOut(
193
227
  if (data === "deleted") {
194
228
  for (const file of dataFiles.filter(present))
195
229
  removed.push({ kind: "file", target: file });
196
- if (accountName && storeHere)
230
+ if (accountName && storeHere && ownersStore)
231
+ kept.push({ kind: "store", target: accountName, reason: ownersReason });
232
+ else if (accountName && storeHere)
197
233
  removed.push({ kind: "store", target: accountName });
198
234
  else
199
235
  kept.push({
@@ -276,7 +312,7 @@ export const accountRemoveCommand = (app, removal, options = {}) => logsInOrOut(
276
312
  for (const entry of removed)
277
313
  if (entry.kind === "file")
278
314
  rmSync(entry.target, { recursive: true, force: true });
279
- if (removal.forgetConfig)
315
+ if (removal.forgetConfig && !ownersConfig)
280
316
  for (const target of removal.forgetConfig(profile, hooks))
281
317
  removed.push({ kind: "config", target });
282
318
  else if (sections.length > 0)
@@ -215,7 +215,12 @@ const searchAction = (messenger) => async function (given) {
215
215
  const skips = await context
216
216
  .withStore((store) => historySkipsOf(store, found.coverage?.accounts ?? found.accounts ?? []))
217
217
  .catch(() => []);
218
- renderAnswer(this, context, messagesAnswer("search messages", found, { limit, page: page ?? 1, again }, given.join(" "), skips), view);
218
+ renderAnswer(this, context, messagesAnswer("search messages", found, {
219
+ limit,
220
+ page: page ?? 1,
221
+ again,
222
+ archiveOnly: !discover && Boolean(messenger.serverSearch) && backendRequest(this).backend === "archive",
223
+ }, given.join(" "), skips), view);
219
224
  };
220
225
  const withOffset = (page, limit) => {
221
226
  const offset = offsetOf(page, limit);
@@ -40,11 +40,13 @@ export interface Paging {
40
40
  page?: number;
41
41
  /** The query and options `page.next` repeats. */
42
42
  again?: Record<string, unknown>;
43
+ /** Asked for the archive alone where the messenger's server could search too. */
44
+ archiveOnly?: boolean;
43
45
  }
44
46
  /** "showing 20 of 144", for the human view under a page of hits; `+` when the total is a lower bound. */
45
47
  export declare const shownOf: (shown: number, offset: number, total: SearchTotal | undefined) => string | undefined;
46
48
  /** `search messages` and `search mail`, CLI and MCP alike. */
47
- export declare const messagesAnswer: (command: string, found: SearchFound, { limit, page, again }: Paging, query?: string, skips?: StoredHistorySkip[]) => ListBody<MessageHitItem>;
49
+ export declare const messagesAnswer: (command: string, found: SearchFound, { limit, page, again, archiveOnly }: Paging, query?: string, skips?: StoredHistorySkip[]) => ListBody<MessageHitItem>;
48
50
  export declare const noteHitItem: (hit: FoundNote) => NoteHitItem;
49
51
  export declare const allHitItem: (item: SearchAllItem) => HitItem;
50
52
  /** `search notes`, CLI and MCP alike. */
@@ -258,10 +258,12 @@ export const shownOf = (shown, offset, total) => total === undefined || shown ==
258
258
  ? undefined
259
259
  : `showing ${offset + 1}–${offset + shown} of ${total.value}${total.relation === "gte" ? "+" : ""}`;
260
260
  /** `search messages` and `search mail`, CLI and MCP alike. */
261
- export const messagesAnswer = (command, found, { limit, page, again }, query = "", skips = []) => {
261
+ export const messagesAnswer = (command, found, { limit, page, again, archiveOnly }, query = "", skips = []) => {
262
262
  const accounts = found.coverage?.accounts ?? found.accounts ?? [];
263
263
  const gaps = gapsOf(found);
264
264
  const limited = historyLimitGaps(skips);
265
+ if (archiveOnly && query !== "" && gaps.missing.length + limited.missing.length > 0)
266
+ gaps.next.unshift(nextStep("search.server", { args: { query, backend: "server" } }));
265
267
  return listOf(command, {
266
268
  items: [...found.items.map((hit) => messageHitItem(hit, query)), ...pictureItems(found)],
267
269
  limit,
package/dist/cli/steps.js CHANGED
@@ -20,6 +20,15 @@ export const STEPS = defineSteps([
20
20
  ],
21
21
  why: "the local copy is missing messages; syncing brings them in",
22
22
  },
23
+ {
24
+ id: "search.server",
25
+ command: "search messages",
26
+ args: [
27
+ { name: "query", required: true },
28
+ { name: "backend", required: true },
29
+ ],
30
+ why: "only the local copy was searched, and it does not hold every message; the messenger's own search reaches the rest",
31
+ },
23
32
  {
24
33
  id: "messages.transcribe",
25
34
  command: "messages transcribe",
@@ -1,4 +1,5 @@
1
1
  import { CliError, isCliError } from "@wirecat/cli-base";
2
+ // gcal-cli raised its own oauth.missing before cli-core merged it into session.missing (FIND-2583).
2
3
  const NOT_SIGNED_IN = new Set([undefined, "session.missing", "oauth.missing"]);
3
4
  /**
4
5
  * A "not signed in" failure for a first word this computer has never seen as a profile is most likely a typo: it
@@ -81,3 +81,9 @@ export declare const oauthClientReport: (app: {
81
81
  source?: AppSource | undefined;
82
82
  } | undefined, reason?: string) => OAuthClientReport;
83
83
  export type { AppSource };
84
+ /**
85
+ * The hosts cli-core itself reaches in any tool: npm for `upgrade`, the default model providers, and the model
86
+ * downloads with the hosts they redirect to. A tool spreads them into its WCAT identity's `hosts`, so `cli-dev manifest`
87
+ * lists them; a model endpoint or calendar feed the person configures belongs in `userHosts`.
88
+ */
89
+ export declare const CORE_HOSTS: readonly string[];
@@ -75,3 +75,17 @@ export const microsoftApp = (options) => {
75
75
  export const oauthClientReport = (app, reason) => app?.source
76
76
  ? { client: app.source === "constants" ? "wirecat" : "own", source: app.source }
77
77
  : { client: null, source: null, ...(reason ? { reason } : {}) };
78
+ /**
79
+ * The hosts cli-core itself reaches in any tool: npm for `upgrade`, the default model providers, and the model
80
+ * downloads with the hosts they redirect to. A tool spreads them into its WCAT identity's `hosts`, so `cli-dev manifest`
81
+ * lists them; a model endpoint or calendar feed the person configures belongs in `userHosts`.
82
+ */
83
+ export const CORE_HOSTS = [
84
+ "registry.npmjs.org",
85
+ "api.openai.com",
86
+ "api.anthropic.com",
87
+ "huggingface.co",
88
+ "*.hf.co",
89
+ "github.com",
90
+ "release-assets.githubusercontent.com",
91
+ ];
@@ -15,6 +15,8 @@ import { CRM_KINDS } from "../../domain/crm.js";
15
15
  import { DEAL_KINDS, DEAL_STATUSES } from "../../domain/deals.js";
16
16
  import { deal as dealEntity } from "../../entities/deal.js";
17
17
  import { count, text } from "../../entities/fields.js";
18
+ import { readableAccounts } from "../../services/person-context.js";
19
+ import { personMeetings } from "../../services/person-meetings.js";
18
20
  import { CRM_SCOPES, crmSettingKey } from "../../store/sqlite/crm-settings.js";
19
21
  import { openStageTasks } from "../stage-tasks.js";
20
22
  import { crmStatus, syncCrm } from "../sync.js";
@@ -63,6 +65,8 @@ const DEAL_UNTRUSTED = [
63
65
  ];
64
66
  /** `show` lists this many of a deal's activities: the open ones come first, so a long history does not hide them. */
65
67
  const SHOWN_ACTIVITIES = 20;
68
+ /** The newest recorded meetings and calls of the people on a deal or lead that `show` lists. */
69
+ const SHOWN_MEETINGS = 10;
66
70
  const PIPELINE_UNTRUSTED = ["name", "stages.name"];
67
71
  const STAGE_UNTRUSTED = ["name", "pipeline_name"];
68
72
  const crmContactsRemoved = v.strictObject({
@@ -201,13 +205,16 @@ const addCrmCommandsDefinition = (program, options) => {
201
205
  .action(async (opts, command) => {
202
206
  const { signal } = environmentOf(command);
203
207
  await within(command, async (run) => {
204
- const report = await syncCrm(run.source(), run.store, run.account, {
208
+ const source = run.source();
209
+ const report = await syncCrm(source, run.store, run.account, {
205
210
  now: now(),
206
211
  budget: runBudgetOf(command, opts.maxPages),
207
212
  ...(signal ? { signal } : {}),
208
213
  ...(opts.rescan ? { rescan: true } : {}),
209
214
  });
210
- const stageTasks = await openStageTasks(run.store, run.account, now());
215
+ const stageTasks = await openStageTasks(run.store, run.account, now(), {
216
+ history: source.stageHistory !== undefined,
217
+ });
211
218
  const failed = report.synced.filter((one) => one.error !== undefined);
212
219
  // A kind that failed on a setting fails the same way again until the owner changes it: no retry is offered.
213
220
  const retried = failed.filter((one) => one.setting === undefined);
@@ -327,8 +334,9 @@ const addCrmCommandsDefinition = (program, options) => {
327
334
  });
328
335
  });
329
336
  example(annotate(group.command("show"), { effects: LOCAL_READ, output: { entity: kind } })
330
- .description(`one ${kind} with its pipeline, stage, status, amount and the people on it; with the activities setting ` +
331
- "on, its activities and tasks too")
337
+ .description(`one ${kind} with its pipeline, stage, status, amount and the people on it, and the newest recorded ` +
338
+ "meetings and calls of those people in this account's scope; with the activities setting on, its " +
339
+ "activities and tasks too")
332
340
  .argument(`<${kind}>`, `${kind}:<id>, as a list shows it`), `${plural} show ${kind}:12`).action(async (reference, _opts, command) => {
333
341
  await within(command, async (run) => {
334
342
  const found = await ownCopy(run, kind, reference);
@@ -345,10 +353,27 @@ const addCrmCommandsDefinition = (program, options) => {
345
353
  updated_at: new Date(one.updatedAt).toISOString(),
346
354
  }))
347
355
  : undefined;
356
+ const recorded = await personMeetings(run.store, found.people.filter(({ owner }) => !owner).map(({ ref }) => ref.slice("person:".length)), await readableAccounts(run.store, run.account), { limit: SHOWN_MEETINGS });
357
+ const meetings = recorded.items.map((one) => ({
358
+ ref: one.ref,
359
+ meeting_id: one.meetingId,
360
+ account: one.account,
361
+ title: one.title,
362
+ started_at: one.startedAt,
363
+ duration_ms: one.durationMs,
364
+ has_transcript: one.hasTranscript,
365
+ event: one.event,
366
+ people: one.people,
367
+ }));
348
368
  return itemOf({
349
369
  ...dealKeys(found),
370
+ meetings,
350
371
  ...(activities ? { activities } : {}),
351
- untrusted: activities ? [...DEAL_UNTRUSTED, "activities.subject", "activities.body"] : DEAL_UNTRUSTED,
372
+ untrusted: [
373
+ ...DEAL_UNTRUSTED,
374
+ "meetings.title",
375
+ ...(activities ? ["activities.subject", "activities.body"] : []),
376
+ ],
352
377
  });
353
378
  });
354
379
  });
@@ -1,4 +1,4 @@
1
- import type { CrmActivity, CrmDepartment, CrmField, CrmKind, CrmPipeline, CrmRecords, CrmScope, CrmUser } from "../domain/crm.js";
1
+ import type { CrmActivity, CrmDepartment, CrmField, CrmKind, CrmPipeline, CrmRecords, CrmScope, CrmStageEntry, CrmUser } from "../domain/crm.js";
2
2
  import type { DealKind } from "../domain/deals.js";
3
3
  export interface CrmSourceTraits {
4
4
  /** What this CRM has: one without leads leaves `lead` out. Contacts and companies come before the items on them. */
@@ -102,4 +102,11 @@ export interface CrmSource {
102
102
  * them leaves it out. A list the sign-in may not read is a `gap`, and the others are still read.
103
103
  */
104
104
  activities?(since: number, page?: string, context?: CrmCallContext): Promise<CrmPage<CrmActivity>>;
105
+ /**
106
+ * The kind's entries into a stage that the CRM's own history recorded, oldest first, a page at a time: after the
107
+ * entry `after` (its `externalId`), or from `since` (epoch ms) without it; the last page's `cursor` is the last entry
108
+ * read, or `after` when none came. With it, stage tasks open on each stage entered, one passed between two syncs too.
109
+ * Read only while the account has `stage-tasks` rules for the kind.
110
+ */
111
+ stageHistory?(kind: DealKind, since: number, after?: string, context?: CrmCallContext): Promise<CrmPage<CrmStageEntry>>;
105
112
  }
@@ -5,4 +5,6 @@ import type { AccountKey } from "../store/types.js";
5
5
  * one per entry, so a dismissed task never comes back and a later entry into the same stage opens a new one.
6
6
  * Answers how many it opened.
7
7
  */
8
- export declare const openStageTasks: (store: MessageStore, account: AccountKey, now: number) => Promise<number>;
8
+ export declare const openStageTasks: (store: MessageStore, account: AccountKey, now: number, { history }?: {
9
+ history?: boolean;
10
+ }) => Promise<number>;
@@ -6,11 +6,13 @@ const DAY = 86_400_000;
6
6
  * one per entry, so a dismissed task never comes back and a later entry into the same stage opens a new one.
7
7
  * Answers how many it opened.
8
8
  */
9
- export const openStageTasks = async (store, account, now) => {
9
+ export const openStageTasks = async (store, account, now, { history = false } = {}) => {
10
10
  const rules = await store.crm.stageTasks(account);
11
11
  if (Object.keys(rules.deal).length + Object.keys(rules.lead).length === 0)
12
12
  return 0;
13
- const { moves, through } = await store.crm.stageMoves(account);
13
+ const changes = await store.crm.stageMoves(account);
14
+ // A CRM with a stage history names every stage entered; the copy's own changes miss one passed between two syncs.
15
+ const moves = history ? await store.crm.stageEntries(account) : changes.moves;
14
16
  // Every deal entering a stage gets the same title, so the duplicate review would pair tasks of different deals.
15
17
  const { reviewDuplicates: _review, ...tasks } = store.tasks;
16
18
  const service = createTaskService({ store: tasks, now: () => new Date(now) });
@@ -23,7 +25,7 @@ export const openStageTasks = async (store, account, now) => {
23
25
  const responsible = item.people.find((one) => one.role === "owner")?.name ??
24
26
  (item.assignee === null ? "nobody" : `CRM user ${item.assignee.split("/").at(-1)}`);
25
27
  const { created } = await service.add({
26
- source: `${move.ref}/move/${move.id}`,
28
+ source: move.source,
27
29
  sourceKind: move.kind,
28
30
  account: taskAccount(account),
29
31
  group: move.ref,
@@ -37,6 +39,8 @@ export const openStageTasks = async (store, account, now) => {
37
39
  if (created)
38
40
  opened += 1;
39
41
  }
40
- await store.crm.markStageMoves(account, through);
42
+ if (history)
43
+ await store.crm.handleStageEntries(moves.map(({ id }) => id));
44
+ await store.crm.markStageMoves(account, changes.through);
41
45
  return opened;
42
46
  };
@@ -50,7 +50,7 @@ export interface CrmSyncOptions {
50
50
  export interface CrmSyncIssue {
51
51
  /** `user`: the account's users and departments. */
52
52
  kind: CrmKind | "user";
53
- reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.unassigned-dropped" | "crm.not-reported" | "crm.pending-dropped" | "crm.activities-failed";
53
+ reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.unassigned-dropped" | "crm.not-reported" | "crm.pending-dropped" | "crm.activities-failed" | "crm.stage-history-failed";
54
54
  message: string;
55
55
  externalId?: string;
56
56
  }
package/dist/crm/sync.js CHANGED
@@ -214,6 +214,45 @@ const readActivities = async (run) => {
214
214
  return null;
215
215
  }
216
216
  };
217
+ const STAGE_HISTORY = "crm:stage-history:";
218
+ /**
219
+ * The CRM's own stage history of each kind with `stage-tasks` rules, after the last entry read: the first read goes
220
+ * from when stage tasks were last opened, so no entry is missed and none before the rules counts. Without rules the
221
+ * history is not read, and its place is dropped, so rules set again later start from then.
222
+ */
223
+ const readStageHistory = async (run) => {
224
+ const { source, store, account } = run;
225
+ if (!source.stageHistory)
226
+ return null;
227
+ const rules = await store.crm.stageTasks(account);
228
+ const since = await store.crm.stageTasksSince(account);
229
+ for (const kind of DEAL_KINDS) {
230
+ const key = `${STAGE_HISTORY}${kind}`;
231
+ if (since === null || Object.keys(rules[kind]).length === 0) {
232
+ await store.sync.clearSyncState(account, key);
233
+ continue;
234
+ }
235
+ let after = (await store.sync.syncState(account, key))?.value;
236
+ for (;;) {
237
+ const why = run.budget.take();
238
+ if (why)
239
+ return why;
240
+ const page = await source.stageHistory.call(source, kind, since, after, run.context);
241
+ await store.crm.saveStageEntries(account, page.items);
242
+ run.moved();
243
+ const next = page.hasMore ? page.nextCursor : (page.cursor ?? after);
244
+ if (next !== undefined && next !== null) {
245
+ after = next;
246
+ await store.sync.setSyncState(account, key, next);
247
+ }
248
+ if (!page.hasMore || page.nextCursor === undefined)
249
+ break;
250
+ if (run.signal?.aborted)
251
+ return "cancelled";
252
+ }
253
+ }
254
+ return null;
255
+ };
217
256
  /** Runs a step whose source call may spend the budget mid-way: a spent budget is a stop, not a failure. */
218
257
  const stopping = async (step) => {
219
258
  try {
@@ -601,6 +640,21 @@ export const syncCrm = async (source, store, account, options = {}) => {
601
640
  });
602
641
  }
603
642
  }
643
+ if (!stopped && kinds.some(isItemKind)) {
644
+ try {
645
+ stopped = await stopping(() => readStageHistory(run));
646
+ }
647
+ catch (error) {
648
+ if (options.signal?.aborted)
649
+ stopped = "cancelled";
650
+ else
651
+ report.issues.push({
652
+ kind: "deal",
653
+ reason: "crm.stage-history-failed",
654
+ message: isCliFailure(error) ? error.message : "the stage history could not be read",
655
+ });
656
+ }
657
+ }
604
658
  const narrowed = report.synced.some((one) => one.outOfScope > 0);
605
659
  const whole = report.synced.every((one) => one.state === "complete" && one.error === undefined && !one.held && one.pass !== "held");
606
660
  // Contacts have no scope of their own and no deletion check: they leave with the last deal or lead naming them.
@@ -206,3 +206,18 @@ export declare const isCrmUserId: (id: string) => boolean;
206
206
  /** One spelling per user id, so `015`, ` 15` and `15` are one user wherever they come from. */
207
207
  export declare const normalCrmUserId: (id: string) => string;
208
208
  export declare const isItemKind: (kind: CrmKind) => kind is DealKind;
209
+ /**
210
+ * One entry of a deal or lead into a stage, as the CRM's own history recorded it: also a stage passed between two
211
+ * syncs, which the copy never stood in. A row's first stage is no entry.
212
+ */
213
+ export interface CrmStageEntry {
214
+ /** The history row's id in the CRM, ascending within a kind: the next read goes on after the last one. */
215
+ externalId: string;
216
+ kind: DealKind;
217
+ /** The deal's or lead's own id. */
218
+ item: string;
219
+ pipeline: string;
220
+ stage: string;
221
+ /** When it entered the stage, epoch ms. */
222
+ at: number;
223
+ }
@@ -38,6 +38,8 @@ export declare const typedPhone: (typed: string, { phoneCountries }?: PhoneOptio
38
38
  * `phone_countries` setting reads `4155550100` as Russian, so it never decides an identifier.
39
39
  */
40
40
  export declare const e164Of: (phone: string, region: string | undefined) => string | null | undefined;
41
+ /** An E.164 number that some country's plan reads as a mobile: a person's own line, not an office's. */
42
+ export declare const isMobilePhone: (e164: string) => boolean;
41
43
  /** The messengers that keep a contact's number as bare international digits, the `+` left off. */
42
44
  export declare const BARE_INTERNATIONAL_PROVIDERS: readonly string[];
43
45
  /**
@@ -83,6 +83,9 @@ export const e164Of = (phone, region) => {
83
83
  const digits = phone.replace(/\(0\)/, "").replace(/\D/g, "");
84
84
  return nationalPhone(digits, [region], { anyType: true })?.value;
85
85
  };
86
+ /** An E.164 number that some country's plan reads as a mobile: a person's own line, not an office's. */
87
+ export const isMobilePhone = (e164) => /^\+\d+$/.test(e164) &&
88
+ PHONE_COUNTRIES.some((country) => nationalPhone(e164.slice(1), [country], { anyType: false })?.value === e164);
86
89
  /** The messengers that keep a contact's number as bare international digits, the `+` left off. */
87
90
  export const BARE_INTERNATIONAL_PROVIDERS = ["telegram", "max", "whatsapp"];
88
91
  /**
@@ -89,7 +89,10 @@ export declare const isKind: (word: string) => word is Kind;
89
89
  export declare const providerNamed: (word: string) => ProviderEntry | undefined;
90
90
  /** The kind of a provider the registry knows; `undefined` for one no entry names, which a search skips. */
91
91
  export declare const kindIn: (provider: Provider) => Kind | undefined;
92
- /** Every kind a provider's accounts hold, its `kind` first; empty for one no entry names. */
92
+ /**
93
+ * Every kind a provider's accounts hold, its `kind` first; empty for one no entry names. An import-only provider's
94
+ * accounts hold documents too: a records import writes them beside its calls and SMS.
95
+ */
93
96
  export declare const kindsIn: (provider: Provider) => readonly Kind[];
94
97
  /**
95
98
  * Whether an entry may carry `imported`, beside one stored before (`held`): never for a built-in a sync writes, only