@wirecat/cli-core 0.641.0 → 0.643.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 (287) hide show
  1. package/CHANGELOG.md +218 -0
  2. package/dist/analysis/provider.d.ts +1 -1
  3. package/dist/analysis/provider.js +2 -1
  4. package/dist/attachments/gateway-ocr.js +13 -8
  5. package/dist/attachments/ocr.js +27 -18
  6. package/dist/attachments/picture-reading.d.ts +51 -0
  7. package/dist/attachments/picture-reading.js +207 -0
  8. package/dist/background/backfill.d.ts +4 -2
  9. package/dist/background/backfill.js +3 -3
  10. package/dist/background/schedules.d.ts +28 -2
  11. package/dist/background/schedules.js +73 -20
  12. package/dist/background/units.d.ts +2 -0
  13. package/dist/background/units.js +8 -9
  14. package/dist/calendar/cli/index.js +10 -2
  15. package/dist/calendar/feeds.js +2 -2
  16. package/dist/calendar/mcp/index.d.ts +12 -12
  17. package/dist/calendar/server-search.js +2 -2
  18. package/dist/calendar/source.d.ts +4 -3
  19. package/dist/calendar/sync.js +12 -10
  20. package/dist/calendar/testing/source-contract.js +5 -4
  21. package/dist/calendar/testing/source.js +3 -2
  22. package/dist/cli/ai-model-command.js +6 -3
  23. package/dist/cli/analysis-choice.js +20 -4
  24. package/dist/cli/complete-command.d.ts +23 -0
  25. package/dist/cli/complete-command.js +80 -0
  26. package/dist/cli/context.js +7 -1
  27. package/dist/cli/effects.d.ts +2 -0
  28. package/dist/cli/effects.js +2 -0
  29. package/dist/cli/enrichment-consents-command.js +2 -0
  30. package/dist/cli/envelope.js +6 -1
  31. package/dist/cli/help/first-screen.js +5 -0
  32. package/dist/cli/index.d.ts +4 -2
  33. package/dist/cli/index.js +2 -1
  34. package/dist/cli/list-query.d.ts +3 -1
  35. package/dist/cli/list-query.js +5 -3
  36. package/dist/cli/local-only-command.d.ts +10 -0
  37. package/dist/cli/local-only-command.js +112 -0
  38. package/dist/cli/messenger/backfill-command.js +1 -1
  39. package/dist/cli/messenger/chat-queries.js +2 -1
  40. package/dist/cli/messenger/complete-command.d.ts +4 -7
  41. package/dist/cli/messenger/complete-command.js +31 -98
  42. package/dist/cli/messenger/contacts-command.js +4 -0
  43. package/dist/cli/messenger/conversations-command.js +1 -1
  44. package/dist/cli/messenger/guard-commands.js +1 -1
  45. package/dist/cli/messenger/images-command.js +32 -0
  46. package/dist/cli/messenger/list-result-queries.d.ts +1 -0
  47. package/dist/cli/messenger/list-result-queries.js +2 -1
  48. package/dist/cli/messenger/mentions-command.js +3 -3
  49. package/dist/cli/messenger/message-items.js +1 -0
  50. package/dist/cli/messenger/messages-command.js +7 -6
  51. package/dist/cli/messenger/people-queries.d.ts +2 -2
  52. package/dist/cli/messenger/people-queries.js +4 -4
  53. package/dist/cli/messenger/replies-consents-command.js +12 -6
  54. package/dist/cli/messenger/search-answers.js +2 -2
  55. package/dist/cli/messenger/search-command.js +3 -3
  56. package/dist/cli/messenger/searches-command.js +1 -1
  57. package/dist/cli/messenger/store-maintenance-command.js +4 -0
  58. package/dist/cli/messenger/tasks-analysis-command.js +1 -1
  59. package/dist/cli/messenger/tasks-command.js +2 -2
  60. package/dist/cli/model-catalogue-command.js +4 -0
  61. package/dist/cli/picture-reading-command.d.ts +12 -0
  62. package/dist/cli/picture-reading-command.js +82 -0
  63. package/dist/cli/program.d.ts +6 -0
  64. package/dist/cli/program.js +28 -2
  65. package/dist/cli/schedule/agent-start.d.ts +23 -0
  66. package/dist/cli/schedule/agent-start.js +115 -0
  67. package/dist/cli/schedule/harnesses.d.ts +203 -0
  68. package/dist/cli/schedule/harnesses.js +278 -0
  69. package/dist/cli/schedule/schedule-command.d.ts +9 -5
  70. package/dist/cli/schedule/schedule-command.js +89 -79
  71. package/dist/cli/search-harder-consents-command.js +16 -1
  72. package/dist/cli/shared-command-exports.d.ts +186 -0
  73. package/dist/cli/shared-command-exports.js +2 -0
  74. package/dist/cli/untrusted-marks.d.ts +25 -0
  75. package/dist/cli/untrusted-marks.js +102 -0
  76. package/dist/crm/cli/index.d.ts +1 -0
  77. package/dist/crm/cli/index.js +6 -5
  78. package/dist/crm/cli/store.d.ts +30 -0
  79. package/dist/crm/cli/store.js +63 -0
  80. package/dist/crm/source.d.ts +6 -4
  81. package/dist/crm/sync.js +10 -6
  82. package/dist/crm/testing/source-contract.js +9 -7
  83. package/dist/crm/testing/source.js +6 -2
  84. package/dist/crm/testing/sync-contract.js +4 -4
  85. package/dist/crm/writes.d.ts +5 -2
  86. package/dist/crm/writes.js +1 -1
  87. package/dist/documents.d.ts +2 -1
  88. package/dist/documents.js +2 -1
  89. package/dist/domain/addresses.d.ts +2 -0
  90. package/dist/domain/addresses.js +7 -0
  91. package/dist/domain/attachments.d.ts +2 -0
  92. package/dist/domain/attachments.js +2 -1
  93. package/dist/domain/models.d.ts +2 -0
  94. package/dist/embeddings/remote.d.ts +2 -1
  95. package/dist/embeddings/remote.js +5 -3
  96. package/dist/entities/attachment-results.d.ts +3 -0
  97. package/dist/entities/attachment-results.js +3 -0
  98. package/dist/entities/attachment.d.ts +2 -0
  99. package/dist/entities/attachment.js +8 -1
  100. package/dist/entities/hit.d.ts +1 -0
  101. package/dist/entities/index.d.ts +21 -4
  102. package/dist/entities/index.js +3 -2
  103. package/dist/entities/list-results.d.ts +33 -5
  104. package/dist/entities/list-results.js +33 -5
  105. package/dist/errors/reasons.js +38 -1
  106. package/dist/mail/cli/index.js +7 -6
  107. package/dist/mcp/agent.d.ts +2 -1
  108. package/dist/mcp/agent.js +5 -0
  109. package/dist/mcp/app-server.js +10 -0
  110. package/dist/mcp/surface.d.ts +7 -2
  111. package/dist/mcp/surface.js +49 -10
  112. package/dist/meetings/cli/index.js +6 -1
  113. package/dist/meetings/mcp/index.js +6 -3
  114. package/dist/meetings/participant-search.d.ts +2 -2
  115. package/dist/meetings/project-discovery.d.ts +1 -1
  116. package/dist/meetings/project-evidence-answer.js +2 -2
  117. package/dist/meetings/reads.d.ts +2 -2
  118. package/dist/meetings/reads.js +6 -6
  119. package/dist/meetings/store.d.ts +2 -1
  120. package/dist/meetings/testing/contract.js +6 -6
  121. package/dist/meetings/testing/memory.js +7 -2
  122. package/dist/models/ai.d.ts +17 -4
  123. package/dist/models/ai.js +22 -14
  124. package/dist/models/anthropic.js +15 -9
  125. package/dist/models/endpoint.d.ts +5 -0
  126. package/dist/models/endpoint.js +13 -0
  127. package/dist/models/index.d.ts +4 -0
  128. package/dist/models/index.js +14 -4
  129. package/dist/models/local-only.d.ts +17 -0
  130. package/dist/models/local-only.js +42 -0
  131. package/dist/models/openai.js +24 -11
  132. package/dist/models/purpose.d.ts +24 -0
  133. package/dist/models/purpose.js +26 -0
  134. package/dist/models/types.d.ts +8 -0
  135. package/dist/models/types.js +11 -1
  136. package/dist/ports/app.d.ts +17 -1
  137. package/dist/ports/app.js +63 -3
  138. package/dist/replies/rendering.js +10 -10
  139. package/dist/search/lucene/plain.js +45 -3
  140. package/dist/search/lucene/registry.d.ts +15 -4
  141. package/dist/search/lucene/registry.js +70 -12
  142. package/dist/search/lucene/types.d.ts +2 -0
  143. package/dist/search/lucene/types.js +12 -0
  144. package/dist/sends/upload.d.ts +8 -1
  145. package/dist/sends/upload.js +35 -14
  146. package/dist/services/account-groups.d.ts +11 -0
  147. package/dist/services/account-groups.js +29 -0
  148. package/dist/services/agenda.js +1 -0
  149. package/dist/services/attachments.d.ts +18 -4
  150. package/dist/services/attachments.js +66 -15
  151. package/dist/services/conversations.d.ts +2 -4
  152. package/dist/services/conversations.js +1 -1
  153. package/dist/services/deal-context.js +5 -5
  154. package/dist/services/documents/ingestion.js +3 -3
  155. package/dist/services/documents/knowledge.d.ts +6 -6
  156. package/dist/services/documents/knowledge.js +1 -2
  157. package/dist/services/embeddings-maintenance.js +4 -1
  158. package/dist/services/enrichment.d.ts +1 -1
  159. package/dist/services/enrichment.js +27 -0
  160. package/dist/services/events-search.d.ts +3 -3
  161. package/dist/services/events-search.js +7 -7
  162. package/dist/services/index.d.ts +1 -1
  163. package/dist/services/index.js +1 -1
  164. package/dist/services/meeting-model.js +1 -1
  165. package/dist/services/meeting-project-discovery.js +1 -1
  166. package/dist/services/message-resolution.js +10 -3
  167. package/dist/services/messages-search.js +6 -4
  168. package/dist/services/metadata.d.ts +1 -1
  169. package/dist/services/notes-search.d.ts +3 -3
  170. package/dist/services/notes-search.js +3 -3
  171. package/dist/services/organization-context.js +12 -9
  172. package/dist/services/people.d.ts +2 -0
  173. package/dist/services/people.js +4 -2
  174. package/dist/services/pictures.d.ts +9 -0
  175. package/dist/services/pictures.js +34 -28
  176. package/dist/services/project-status/index.js +1 -1
  177. package/dist/services/project-status/signals/payments.js +4 -2
  178. package/dist/services/project-status/signals/promises.js +5 -2
  179. package/dist/services/proposals/kinds/action.js +1 -1
  180. package/dist/services/proposals/kinds/fact.js +1 -1
  181. package/dist/services/proposals/kinds/findings.d.ts +2 -1
  182. package/dist/services/proposals/kinds/findings.js +12 -5
  183. package/dist/services/proposals/kinds/identity-link.js +1 -1
  184. package/dist/services/proposals/kinds/identity-split.js +1 -1
  185. package/dist/services/proposals/kinds/key-document.js +1 -1
  186. package/dist/services/proposals/kinds/mail-findings.d.ts +1 -1
  187. package/dist/services/proposals/kinds/mail-findings.js +11 -5
  188. package/dist/services/proposals/kinds/meeting-findings.js +10 -4
  189. package/dist/services/proposals/kinds/memory.js +1 -1
  190. package/dist/services/proposals/kinds/organization.js +1 -1
  191. package/dist/services/proposals/kinds/relationship-update.js +1 -1
  192. package/dist/services/proposals/kinds/relationship.js +1 -1
  193. package/dist/services/proposals/kinds/shared.d.ts +3 -2
  194. package/dist/services/proposals/kinds/shared.js +4 -4
  195. package/dist/services/proposals/kinds/source-review.js +1 -1
  196. package/dist/services/proposals/kinds/task-close.js +2 -2
  197. package/dist/services/proposals/registry.js +1 -1
  198. package/dist/services/proposals/types.d.ts +2 -1
  199. package/dist/services/search-all-business.js +3 -4
  200. package/dist/services/search-all.js +13 -14
  201. package/dist/services/search-harder.d.ts +11 -1
  202. package/dist/services/search-harder.js +38 -5
  203. package/dist/services/searches.d.ts +2 -4
  204. package/dist/services/searches.js +1 -4
  205. package/dist/services/stored-project-gathering.js +6 -1
  206. package/dist/services/tags.d.ts +2 -4
  207. package/dist/services/tags.js +1 -1
  208. package/dist/services/tasks.d.ts +1 -1
  209. package/dist/services/tasks.js +4 -3
  210. package/dist/speech/openai.js +2 -0
  211. package/dist/speech/transcribe.d.ts +5 -2
  212. package/dist/speech/transcribe.js +14 -5
  213. package/dist/store/account-store.d.ts +2 -1
  214. package/dist/store/account-store.js +3 -1
  215. package/dist/store/accounts.d.ts +2 -0
  216. package/dist/store/accounts.js +8 -0
  217. package/dist/store/chats.d.ts +5 -0
  218. package/dist/store/chats.js +4 -0
  219. package/dist/store/evidence-findings.d.ts +9 -0
  220. package/dist/store/exports.d.ts +1 -1
  221. package/dist/store/exports.js +1 -1
  222. package/dist/store/identity-links.d.ts +3 -1
  223. package/dist/store/mail-findings.d.ts +9 -0
  224. package/dist/store/meeting-findings.d.ts +9 -0
  225. package/dist/store/searches.d.ts +3 -2
  226. package/dist/store/sqlite/accounts.js +37 -0
  227. package/dist/store/sqlite/agent-actions.d.ts +2 -1
  228. package/dist/store/sqlite/agent-actions.js +10 -4
  229. package/dist/store/sqlite/business-contracts.d.ts +3 -1
  230. package/dist/store/sqlite/business-contracts.js +7 -3
  231. package/dist/store/sqlite/business-search.d.ts +2 -1
  232. package/dist/store/sqlite/business-search.js +6 -4
  233. package/dist/store/sqlite/deals.d.ts +6 -4
  234. package/dist/store/sqlite/deals.js +12 -7
  235. package/dist/store/sqlite/evidence-findings.js +78 -9
  236. package/dist/store/sqlite/facts.d.ts +2 -1
  237. package/dist/store/sqlite/facts.js +6 -2
  238. package/dist/store/sqlite/finance.d.ts +4 -2
  239. package/dist/store/sqlite/finance.js +13 -6
  240. package/dist/store/sqlite/findings-core.d.ts +56 -2
  241. package/dist/store/sqlite/findings-core.js +109 -22
  242. package/dist/store/sqlite/identities.d.ts +4 -0
  243. package/dist/store/sqlite/identities.js +12 -3
  244. package/dist/store/sqlite/identity-proposals.js +34 -4
  245. package/dist/store/sqlite/lucene-fields.d.ts +2 -0
  246. package/dist/store/sqlite/lucene-fields.js +28 -2
  247. package/dist/store/sqlite/lucene.js +21 -10
  248. package/dist/store/sqlite/mail-findings.js +60 -22
  249. package/dist/store/sqlite/meeting-findings.js +53 -7
  250. package/dist/store/sqlite/meeting-participant-search.js +4 -5
  251. package/dist/store/sqlite/meetings.js +7 -3
  252. package/dist/store/sqlite/memories.d.ts +4 -2
  253. package/dist/store/sqlite/memories.js +13 -6
  254. package/dist/store/sqlite/money-transactions.d.ts +3 -1
  255. package/dist/store/sqlite/money-transactions.js +7 -3
  256. package/dist/store/sqlite/name-traces.d.ts +3 -3
  257. package/dist/store/sqlite/name-traces.js +29 -2
  258. package/dist/store/sqlite/orders.d.ts +3 -1
  259. package/dist/store/sqlite/orders.js +5 -2
  260. package/dist/store/sqlite/people-list.js +67 -22
  261. package/dist/store/sqlite/person-match-scan.d.ts +3 -1
  262. package/dist/store/sqlite/person-match-scan.js +97 -7
  263. package/dist/store/sqlite/products.d.ts +3 -1
  264. package/dist/store/sqlite/products.js +5 -2
  265. package/dist/store/sqlite/proposed-actions.d.ts +2 -1
  266. package/dist/store/sqlite/proposed-actions.js +7 -3
  267. package/dist/store/sqlite/query-filter.d.ts +4 -0
  268. package/dist/store/sqlite/query-filter.js +14 -0
  269. package/dist/store/sqlite/reads.d.ts +1 -0
  270. package/dist/store/sqlite/reads.js +14 -0
  271. package/dist/store/sqlite/records.d.ts +3 -1
  272. package/dist/store/sqlite/records.js +7 -5
  273. package/dist/store/sqlite/rows-page.d.ts +3 -0
  274. package/dist/store/sqlite/rows-page.js +4 -0
  275. package/dist/store/sqlite/searches.d.ts +2 -1
  276. package/dist/store/sqlite/searches.js +3 -1
  277. package/dist/store/sqlite/subscriptions.d.ts +5 -2
  278. package/dist/store/sqlite/subscriptions.js +13 -6
  279. package/dist/store/sqlite/task-board.js +27 -0
  280. package/dist/store/sqlite/task-find.d.ts +15 -0
  281. package/dist/store/sqlite/task-find.js +1 -0
  282. package/dist/store/sqlite/wallets.d.ts +3 -1
  283. package/dist/store/sqlite/wallets.js +7 -3
  284. package/dist/store/sqlite/work-tasks.d.ts +3 -11
  285. package/dist/store/sqlite/work-tasks.js +8 -4
  286. package/package.json +2 -2
  287. package/parity.json +24 -0
@@ -6,8 +6,9 @@ import type { Ffmpeg } from "./decode.js";
6
6
  import { type SpeechModel } from "./models.js";
7
7
  import type { Recognizer } from "./recognize.js";
8
8
  /**
9
- * `messenger`: its own recognition (Telegram Premium). `local`: a model on this machine. `auto`: the first, then the
10
- * second. `openai`: OpenAI's API, only when asked by name — `auto` never sends audio off the machine.
9
+ * `messenger`: its own recognition (Telegram Premium). `local`: a model on this machine. `auto`: the local model when
10
+ * it is downloaded, else the messenger's. `openai`: OpenAI's API, only when asked by name — `auto` never sends audio
11
+ * to OpenAI, and with local only on it never asks the messenger either.
11
12
  */
12
13
  export declare const TRANSCRIBE_WITH: readonly ["auto", "messenger", "local", "openai"];
13
14
  export type TranscribeWith = (typeof TRANSCRIBE_WITH)[number];
@@ -35,6 +36,8 @@ export interface Choice {
35
36
  fetch?: (url: string, init: RequestInit) => Promise<Response>;
36
37
  /** The command's own cancel and deadline, for a request that leaves the machine. */
37
38
  signal?: AbortSignal;
39
+ /** Local only is on: `auto` never asks the messenger. */
40
+ localOnly?: boolean;
38
41
  }
39
42
  /** A voice note, or an audio file someone sent — an iPhone recording reaches WhatsApp as `audio/mp4`. */
40
43
  export declare const isAudioFile: ({ kind, mime }: {
@@ -1,14 +1,16 @@
1
1
  import { CliError, isCliError } from "@wirecat/cli-base";
2
2
  import { fromFile } from "../cli/settings.js";
3
3
  import { embeddingKeys } from "../embeddings/keys.js";
4
+ import { localOnly, localOnlyRefusal } from "../models/local-only.js";
4
5
  import { readOnlyLockOf, readOnlyRefusal } from "../ports/app.js";
5
6
  import { capability } from "../ports/messenger.js";
6
7
  import { typedCommand } from "../runs/scope.js";
7
8
  import { installedBytes, isInstalled, megabytes, modelPath, modelsDirectory, vadPath } from "./install.js";
8
9
  import { OPENAI_TRANSCRIBE_MODEL, orderedModels, speechModel } from "./models.js";
9
10
  /**
10
- * `messenger`: its own recognition (Telegram Premium). `local`: a model on this machine. `auto`: the first, then the
11
- * second. `openai`: OpenAI's API, only when asked by name — `auto` never sends audio off the machine.
11
+ * `messenger`: its own recognition (Telegram Premium). `local`: a model on this machine. `auto`: the local model when
12
+ * it is downloaded, else the messenger's. `openai`: OpenAI's API, only when asked by name — `auto` never sends audio
13
+ * to OpenAI, and with local only on it never asks the messenger either.
12
14
  */
13
15
  export const TRANSCRIBE_WITH = ["auto", "messenger", "local", "openai"];
14
16
  /** A recording is read into memory whole; minutes of Opus are a few megabytes. */
@@ -23,7 +25,10 @@ export const choose = (messenger, settings, flags, env = process.env, keyring) =
23
25
  : (flags.with ?? fromFile(settings, "transcribeWith", "auto").value);
24
26
  // Refused only where something is heard: `models list` reads the same profile for its model alone.
25
27
  const known = TRANSCRIBE_WITH.includes(chosen);
28
+ const onlyHere = localOnly(env);
29
+ const offComputer = known && onlyHere && (chosen === "messenger" || chosen === "openai");
26
30
  return {
31
+ ...(onlyHere ? { localOnly: true } : {}),
27
32
  directory: modelsDirectory(env),
28
33
  with: known ? chosen : "auto",
29
34
  ...(known
@@ -33,7 +38,10 @@ export const choose = (messenger, settings, flags, env = process.env, keyring) =
33
38
  }),
34
39
  model: model === undefined ? orderedModels(messenger.speechModels)[0] : speechModel(model),
35
40
  transcribeModel: fromFile(settings, "transcribeModel", OPENAI_TRANSCRIBE_MODEL).value,
36
- ...(known && chosen === "openai" ? openaiAccess(messenger, env, keyring) : {}),
41
+ ...(known && chosen === "openai" && !offComputer ? openaiAccess(messenger, env, keyring) : {}),
42
+ ...(offComputer
43
+ ? { refusal: localOnlyRefusal("the voice message", chosen === "openai" ? "OpenAI" : messenger.provider) }
44
+ : {}),
37
45
  };
38
46
  };
39
47
  const openaiAccess = (messenger, env, keyring) => {
@@ -58,7 +66,8 @@ export const notDownloaded = (messenger, model) => new CliError("not_found", `th
58
66
  export const hearOnline = async (messenger, connection, chat, messageId, choice, read) => {
59
67
  if (choice.refusal)
60
68
  throw choice.refusal;
61
- if (choice.with === "auto" || choice.with === "messenger") {
69
+ const localReady = choice.with !== "openai" && isInstalled(choice.model, choice.directory);
70
+ if (choice.with === "messenger" || (choice.with === "auto" && !localReady && !choice.localOnly)) {
62
71
  const canAsk = typeof connection.transcribe === "function";
63
72
  if (choice.with === "messenger" || canAsk) {
64
73
  try {
@@ -72,7 +81,7 @@ export const hearOnline = async (messenger, connection, chat, messageId, choice,
72
81
  }
73
82
  }
74
83
  }
75
- if (choice.with !== "openai" && !isInstalled(choice.model, choice.directory))
84
+ if (choice.with !== "openai" && !localReady)
76
85
  throw notDownloaded(messenger, choice.model);
77
86
  const { files } = await capability(connection, "download", "download attachments")(chat, messageId);
78
87
  const voice = files.find(isAudioFile);
@@ -1,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import type { Page } from "../domain/models.js";
2
3
  import type { Meeting, MeetingDetails, MeetingFilter, SearchHit } from "../meetings/index.js";
3
4
  import type { AccountAccounts } from "./accounts.js";
@@ -56,7 +57,7 @@ export interface AccountMail {
56
57
  export interface AccountMeetings {
57
58
  meetings(filter?: Omit<MeetingFilter, "accountId">): Promise<Meeting[]>;
58
59
  meeting(id: number): Promise<MeetingDetails | null>;
59
- search(query: string, filter?: Omit<MeetingFilter, "accountId">): Promise<SearchHit[]>;
60
+ search(query: string, filter?: Omit<MeetingFilter, "accountId">): Promise<ListResult<SearchHit>>;
60
61
  }
61
62
  /**
62
63
  * The store with one account bound: every read and write takes the account from here, and a row id
@@ -55,7 +55,9 @@ export const bindAccount = (store, account, areas, owners) => {
55
55
  },
56
56
  search: async (query, filter = {}) => {
57
57
  const id = accountId();
58
- return id === undefined ? [] : store.meetings.search(query, { ...filter, accountId: id });
58
+ return id === undefined
59
+ ? { items: [], hasMore: false }
60
+ : store.meetings.search(query, { ...filter, accountId: id });
59
61
  },
60
62
  };
61
63
  const accounts = bound(areas.accounts);
@@ -53,6 +53,8 @@ export interface AccountsStore extends AccountAccounts {
53
53
  changeAccountGroups(change: AccountGroupChange): Promise<{
54
54
  removed: string[];
55
55
  }>;
56
+ /** Gives a saved group another name with its entries, in one write; `false` when no group of that name is saved. */
57
+ renameAccountGroup(from: string, to: string): Promise<boolean>;
56
58
  /** Per app command, each profile's account: how `--source max:default` finds a profile of another app. */
57
59
  profiles(): Promise<Profiles>;
58
60
  /** Records which account a profile of `app` is; a no-op when the store already says so. */
@@ -52,6 +52,14 @@ export const accountsStoreOver = (context, keyed) => {
52
52
  groups[name] = members;
53
53
  saveGroups(groups);
54
54
  }),
55
+ renameAccountGroup: async (from, to) => write(database, () => {
56
+ const groups = accountGroupsOf(database);
57
+ if (!Object.hasOwn(groups, from) || Object.hasOwn(groups, to))
58
+ return false;
59
+ const renamed = Object.fromEntries(Object.entries(groups).map(([name, entries]) => [name === from ? to : name, entries]));
60
+ saveGroups(renamed);
61
+ return true;
62
+ }),
55
63
  changeAccountGroups: async ({ remove, add }) => write(database, () => {
56
64
  const groups = accountGroupsOf(database);
57
65
  const saved = remove && Object.hasOwn(groups, remove.group) ? (groups[remove.group] ?? []) : [];
@@ -70,6 +70,11 @@ export interface ChatsStore {
70
70
  chatCoverage(key: AccountKey): Promise<ChatCoverage>;
71
71
  /** Per chat that has messages: how many, the oldest and newest, and when the last one was stored. */
72
72
  chatStats(key: AccountKey, chatId?: Id): Promise<ChatStats[]>;
73
+ /**
74
+ * Per chat that has messages: its title, count and newest message, as `chatStats` gives them, read off the
75
+ * trigger-kept count and the chat's time index rather than every message; what search's coverage reads.
76
+ */
77
+ chatsNewest(key: AccountKey): Promise<Pick<ChatStats, "chatId" | "title" | "messages" | "newestAt">[]>;
73
78
  /**
74
79
  * The id a chat re-keyed from `chatId` has now, from `chat_revisions`; `undefined` while a chat is stored under
75
80
  * `chatId` itself. Only for finding the chat: the old id and its history are never shown or searched.
@@ -100,6 +100,10 @@ export const chatsStoreOver = (context) => {
100
100
  const accountKey = findAccountPk(key);
101
101
  return accountKey === undefined ? [] : reads.chatStats(context, accountKey, chatId);
102
102
  },
103
+ chatsNewest: async (key) => {
104
+ const accountKey = findAccountPk(key);
105
+ return accountKey === undefined ? [] : reads.chatsNewest(context, accountKey);
106
+ },
103
107
  renamedChatId: async (key, chatId) => {
104
108
  const accountKey = findAccountPk(key);
105
109
  return accountKey === undefined ? undefined : chatQueries.renamedChatId(context, accountKey, chatId);
@@ -39,6 +39,10 @@ export interface EvidenceFindingsBatch {
39
39
  } | null;
40
40
  decidedAt: string | null;
41
41
  previous: FindingOutcome[];
42
+ /** What a review of this still waiting batch already decided; the other findings wait for the owner. */
43
+ decided: FindingOutcome[];
44
+ /** The findings the owner changed before deciding them. */
45
+ edited: string[];
42
46
  receipt: EvidenceFindingsReceipt | null;
43
47
  }
44
48
  /**
@@ -78,6 +82,11 @@ export interface EvidenceFindingsStore {
78
82
  by: EvidenceFindingsDecider;
79
83
  reason?: string;
80
84
  }): Promise<EvidenceFindingsBatch>;
85
+ /** The owner's change to one finding still waiting: its text and fields, never its evidence or project. */
86
+ edit(id: string, finding: string, changes: Record<string, unknown>, options: {
87
+ fingerprint: string;
88
+ by: "owner";
89
+ }): Promise<EvidenceFindingsBatch>;
81
90
  /** Each reference the batch cites, read back once; one gone from the store since is `missing`. */
82
91
  sources(id: string): Promise<EvidenceSource[]>;
83
92
  }
@@ -47,7 +47,7 @@ export type { PersonPreparationRead, PreparationFact, PreparationNote, Preparati
47
47
  export { savedPhoneCountries, saveStorePhoneCountries } from "./sqlite/phone-countries.js";
48
48
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
49
49
  export type { ProposedAction } from "./sqlite/proposed-actions.js";
50
- export { type ColumnMap, queryFilter, type Where } from "./sqlite/query-filter.js";
50
+ export { type ColumnMap, foldedWords, queryFilter, type Where } from "./sqlite/query-filter.js";
51
51
  export type { RankedEvidence, RankingEvidenceItem, RankingEvidenceRequest } from "./sqlite/ranking-evidence.js";
52
52
  export type { RankedStoreFound, RankedStoreRow, RankingRequest } from "./sqlite/rankings.js";
53
53
  export { AGENDA_COLUMNS } from "./sqlite/reads.js";
@@ -21,7 +21,7 @@ export { openSqlite } from "./sqlite/open.js";
21
21
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages, parseOwnerLanguages, savedOwnerLanguages, saveOwnerLanguages, } from "./sqlite/owner-languages.js";
22
22
  export { mergeId, parseMergeId } from "./sqlite/person-merges.js";
23
23
  export { savedPhoneCountries, saveStorePhoneCountries } from "./sqlite/phone-countries.js";
24
- export { queryFilter } from "./sqlite/query-filter.js";
24
+ export { foldedWords, queryFilter } from "./sqlite/query-filter.js";
25
25
  export { AGENDA_COLUMNS } from "./sqlite/reads.js";
26
26
  export { fillSearchIndex, resetSearchIndex, searchIndexState } from "./sqlite/search-index.js";
27
27
  export { savedStemmers, stemmerCache, stemmersOrigin, stemsState, } from "./sqlite/stems.js";
@@ -51,12 +51,14 @@ export interface IdentityLinkDecision {
51
51
  * With `confirm: false` on a shared-mailbox proposal: the address is this organization's, not one of the two people.
52
52
  * `organization` names one; otherwise the one holding the address or its company domain, or one of `name`, or a new
53
53
  * company named `name` or the domain. `all` closes every open proposal on the same mailbox in this one decision;
54
- * the decided proposal's result lists them all as `closed`.
54
+ * the decided proposal's result lists them all as `closed`. On a match that is not about a shared mailbox (one by
55
+ * name), `mailbox` names which of the two people's addresses is the company's.
55
56
  */
56
57
  company?: {
57
58
  organization?: number;
58
59
  name?: string;
59
60
  all?: boolean;
61
+ mailbox?: string;
60
62
  };
61
63
  }
62
64
  /** One `identity_link`, naming the people as they are now, not as they were when it was proposed. */
@@ -21,6 +21,10 @@ export interface MailFindingsBatch {
21
21
  } | null;
22
22
  decidedAt: string | null;
23
23
  previous: FindingOutcome[];
24
+ /** What a review of this still waiting batch already decided; the other findings wait for the owner. */
25
+ decided: FindingOutcome[];
26
+ /** The findings the owner changed before deciding them. */
27
+ edited: string[];
24
28
  receipt: FindingsReceipt | null;
25
29
  }
26
30
  /** What `stage` would do with a batch, found without writing anything. */
@@ -64,4 +68,9 @@ export interface MailFindingsStore {
64
68
  accept: string[];
65
69
  by: Decider;
66
70
  }): Promise<MailFindingsBatch>;
71
+ /** The owner's change to one finding still waiting: its words and the fields it names, never its evidence. */
72
+ edit(id: string, finding: string, changes: Record<string, unknown>, options: {
73
+ fingerprint: string;
74
+ by: Decider;
75
+ }): Promise<MailFindingsBatch>;
67
76
  }
@@ -18,6 +18,10 @@ export interface MeetingFindingsBatch {
18
18
  } | null;
19
19
  decidedAt: string | null;
20
20
  previous: FindingOutcome[];
21
+ /** What a review of this still waiting batch already decided; the other findings wait for the owner. */
22
+ decided: FindingOutcome[];
23
+ /** The findings the owner changed before deciding them. */
24
+ edited: string[];
21
25
  receipt: MeetingFindingsReceipt | null;
22
26
  }
23
27
  export interface MeetingFindingsStore {
@@ -39,4 +43,9 @@ export interface MeetingFindingsStore {
39
43
  accept: string[];
40
44
  by: Decider;
41
45
  }): Promise<MeetingFindingsBatch>;
46
+ /** The owner's change to one finding still waiting: its text and fields, never its evidence or project. */
47
+ edit(account: AccountKey, id: string, finding: string, changes: Record<string, unknown>, options: {
48
+ fingerprint: string;
49
+ by: Decider;
50
+ }): Promise<MeetingFindingsBatch>;
42
51
  }
@@ -1,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import type { StoreContext } from "./sqlite/open.js";
2
3
  import type { SearchCommand, SearchRecord, StoredSearch } from "./sqlite/searches.js";
3
4
  export interface SearchesStore {
@@ -13,8 +14,8 @@ export interface SearchesStore {
13
14
  storedSearch(reference: string): Promise<StoredSearch | undefined>;
14
15
  /** `commands`: only rows of these kinds; the table is shared by every CLI on the store. */
15
16
  savedSearches(commands?: readonly SearchCommand[]): Promise<StoredSearch[]>;
16
- /** Runs, newest first, one more than `limit` when there are more. */
17
- searchHistory(limit: number, offset?: number, commands?: readonly SearchCommand[]): Promise<StoredSearch[]>;
17
+ /** Runs, newest first. */
18
+ searchHistory(limit: number, offset?: number, commands?: readonly SearchCommand[]): Promise<ListResult<StoredSearch>>;
18
19
  deleteSearch(reference: string): Promise<StoredSearch>;
19
20
  /** Drops the unnamed runs; answers how many. */
20
21
  clearSearchHistory(commands?: readonly SearchCommand[]): Promise<number>;
@@ -179,6 +179,7 @@ export const purgeAccount = ({ orm, database, now }, accountKey) => {
179
179
  orm.run(sql `DELETE FROM links WHERE to_type = 'document' AND to_id IN ${documentsOf}`);
180
180
  orm.run(sql `UPDATE files SET document_id = NULL WHERE document_id IN ${documentsOf}`);
181
181
  orm.run(sql `DELETE FROM documents WHERE account_id = ${accountKey}`);
182
+ purgeCrmCopies(database, accountKey);
182
183
  orm.run(sql `DELETE FROM crm_fields WHERE account_id = ${accountKey}`);
183
184
  // An entity made from a record is the owner's and stays; only what the source said goes.
184
185
  const recordsOf = sql `(SELECT id FROM records WHERE account_id = ${accountKey})`;
@@ -188,6 +189,42 @@ export const purgeAccount = ({ orm, database, now }, accountKey) => {
188
189
  dropOrphanPeople(database, unseenBefore);
189
190
  forgetDanglingEvidence(database, at);
190
191
  dropUnusedVectors(database, hashes);
192
+ // The links' delete trigger writes a revision naming the account it is purging; the history goes with the links.
193
+ orm.run(sql `DELETE FROM link_revisions WHERE account_id = ${accountKey}`);
194
+ };
195
+ /**
196
+ * A CRM's deals, leads and pipelines with their stages, children first. Another account's lead converted from one
197
+ * of these deals, and an order or contract that names one, keep their row and lose only the link.
198
+ */
199
+ const purgeCrmCopies = (database, accountKey) => {
200
+ const run = (statement, ...params) => database.prepare(statement).run(...params);
201
+ const dealsOf = "(SELECT id FROM deals WHERE account_id = ?)";
202
+ const leadsOf = "(SELECT id FROM leads WHERE account_id = ?)";
203
+ const pipelinesOf = "(SELECT id FROM pipelines WHERE account_id = ?)";
204
+ const stagesOf = `(SELECT id FROM pipeline_stages WHERE pipeline_id IN ${pipelinesOf})`;
205
+ for (const [type, ids] of [
206
+ ["deal", dealsOf],
207
+ ["lead", leadsOf],
208
+ ]) {
209
+ run(`DELETE FROM links WHERE (from_type = ? AND from_id IN ${ids}) OR (to_type = ? AND to_id IN ${ids})`, type, accountKey, type, accountKey);
210
+ for (const [table, pointer] of [
211
+ ["taggings", "taggable"],
212
+ ["aliases", "aliasable"],
213
+ ["attachments", "attachable"],
214
+ ["link_reviews", "linkable"],
215
+ ["entity_link_events", "linkable"],
216
+ ])
217
+ run(`DELETE FROM ${table} WHERE ${pointer}_type = ? AND ${pointer}_id IN ${ids}`, type, accountKey);
218
+ run(`DELETE FROM pipeline_stage_changes WHERE item_type = ? AND item_id IN ${ids}`, type, accountKey);
219
+ }
220
+ run(`DELETE FROM pipeline_stage_changes WHERE pipeline_id IN ${pipelinesOf}`, accountKey);
221
+ for (const table of ["leads", "orders", "contracts"])
222
+ run(`UPDATE ${table} SET deal_id = NULL WHERE deal_id IN ${dealsOf}`, accountKey);
223
+ run("DELETE FROM leads WHERE account_id = ?", accountKey);
224
+ run("DELETE FROM deals WHERE account_id = ?", accountKey);
225
+ run(`UPDATE pipeline_stages SET base_stage_id = NULL WHERE base_stage_id IN ${stagesOf}`, accountKey);
226
+ run(`DELETE FROM pipeline_stages WHERE pipeline_id IN ${pipelinesOf}`, accountKey);
227
+ run("DELETE FROM pipelines WHERE account_id = ?", accountKey);
191
228
  };
192
229
  /** Identity and person rows a person's own record keeps, not evidence that anyone saw them. */
193
230
  export const OWN = new Set(["identity_links", "identity_link_events", "identity_revisions"]);
@@ -1,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import type { Actor } from "./actors.js";
2
3
  import { type Author } from "./memories.js";
3
4
  import type { StoreContext } from "./open.js";
@@ -45,6 +46,6 @@ export interface AgentActionsStore {
45
46
  agent?: string;
46
47
  limit?: number;
47
48
  offset?: number;
48
- }): Promise<AgentAction[]>;
49
+ }): Promise<ListResult<AgentAction>>;
49
50
  }
50
51
  export declare const agentActionsStoreOver: (context: StoreContext, afterRecord?: () => void) => AgentActionsStore;
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { authorActor } from "./memories.js";
3
+ import { pageOfRows } from "./rows-page.js";
3
4
  import { thingOf } from "./things.js";
4
5
  export const ACTION_TIERS = ["read", "draft", "write-private", "write-public", "destructive", "admin"];
5
6
  export const ACTION_OUTCOMES = ["ok", "refused", "failed"];
@@ -41,9 +42,14 @@ export const agentActionsStoreOver = (context, afterRecord = () => { }) => {
41
42
  afterRecord();
42
43
  return actionOf(database.prepare(`${NAMED} WHERE a.id = ?`).get(Number(row?.id)));
43
44
  },
44
- list: async ({ tool, agent, limit = 100, offset = 0 } = {}) => database
45
- .prepare(`${NAMED} WHERE (? IS NULL OR a.tool = ?) AND (? IS NULL OR b.name = ?) ORDER BY a.started_at DESC, a.id DESC LIMIT ? OFFSET ?`)
46
- .all(tool ?? null, tool ?? null, agent ?? null, agent ?? null, Math.min(Math.max(limit, 1), 500), Math.max(offset, 0))
47
- .map(actionOf),
45
+ list: async ({ tool, agent, limit: asked = 100, offset: from = 0 } = {}) => {
46
+ const limit = Math.min(Math.max(asked, 1), 500);
47
+ const offset = Math.max(from, 0);
48
+ const rows = database
49
+ .prepare(`${NAMED} WHERE (? IS NULL OR a.tool = ?) AND (? IS NULL OR b.name = ?) ORDER BY a.started_at DESC, a.id DESC LIMIT ? OFFSET ?`)
50
+ .all(tool ?? null, tool ?? null, agent ?? null, agent ?? null, limit + 1, offset)
51
+ .map(actionOf);
52
+ return pageOfRows(rows, limit, offset);
53
+ },
48
54
  };
49
55
  };
@@ -1,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import { type ContractKind, type ContractStatus, type Interval } from "../../domain/business.js";
2
3
  import { type FinanceReview } from "../../domain/finance.js";
3
4
  import type { Decider } from "../decisions.js";
@@ -67,6 +68,7 @@ export interface ContractFilter {
67
68
  expiresBy?: string;
68
69
  /** 1–500, 100 by default; newest written first. */
69
70
  limit?: number;
71
+ offset?: number;
70
72
  }
71
73
  /**
72
74
  * The contracts the owner works under. One without a value is written confirmed by anyone, as it feeds no total: its
@@ -76,7 +78,7 @@ export interface ContractFilter {
76
78
  export interface ContractsStore {
77
79
  add(input: ContractInput): Promise<Contract>;
78
80
  get(reference: string): Promise<Contract>;
79
- list(filter?: ContractFilter): Promise<Contract[]>;
81
+ list(filter?: ContractFilter): Promise<ListResult<Contract>>;
80
82
  /** The owner changes any; a bot only one it proposed that is still proposed. */
81
83
  update(reference: string, input: ContractUpdate): Promise<Contract>;
82
84
  confirm(reference: string, by: Decider, reason?: string): Promise<Contract>;
@@ -6,6 +6,7 @@ import { projectId } from "./memories.js";
6
6
  import { requiredThing } from "./notes.js";
7
7
  import { recordRelationshipsOver } from "./record-relationships.js";
8
8
  import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text } from "./reviewed.js";
9
+ import { pageOfRows } from "./rows-page.js";
9
10
  import { storedThing } from "./things.js";
10
11
  import { write } from "./transaction.js";
11
12
  const CONTRACTS = "SELECT k.*, b.name AS author_name, b.kind AS author_kind FROM contracts k " +
@@ -144,18 +145,21 @@ export const contractOperationsOver = (context) => {
144
145
  },
145
146
  get: (reference) => contractOf(rowOf(reference)),
146
147
  list: (filter = {}) => {
148
+ const limit = limitOf(filter.limit);
149
+ const offset = Math.max(filter.offset ?? 0, 0);
147
150
  const project = filter.project === undefined ? null : projectId(database, filter.project);
148
151
  const status = filter.status === undefined ? null : oneOf(filter.status, CONTRACT_STATUSES, "a status");
149
152
  const kind = filter.kind === undefined ? null : oneOf(filter.kind, CONTRACT_KINDS, "a kind");
150
153
  const review = filter.review === undefined ? null : oneOf(filter.review, FINANCE_REVIEWS, "a review");
151
154
  const expires = isoDate(filter.expiresBy, "the last expiration day");
152
155
  const by = proposedBySql("k.author_type", "k.author_id", filter.proposedBy);
153
- return database
156
+ const rows = database
154
157
  .prepare(`${CONTRACTS} WHERE k.deleted_at IS NULL AND (? IS NULL OR k.status = ?) AND (? IS NULL OR k.kind = ?) ` +
155
158
  "AND (? IS NULL OR k.review = ?) AND (? IS NULL OR k.project_id = ?) " +
156
- `AND (? IS NULL OR k.expiration_date <= ?) AND ${by.sql} ORDER BY k.created_at DESC, k.id DESC LIMIT ?`)
157
- .all(status, status, kind, kind, review, review, project, project, expires, expires, ...by.params, limitOf(filter.limit))
159
+ `AND (? IS NULL OR k.expiration_date <= ?) AND ${by.sql} ORDER BY k.created_at DESC, k.id DESC LIMIT ? OFFSET ?`)
160
+ .all(status, status, kind, kind, review, review, project, project, expires, expires, ...by.params, limit + 1, offset)
158
161
  .map((row) => contractOf(row));
162
+ return pageOfRows(rows, limit, offset);
159
163
  },
160
164
  update: (reference, { by, ...fields }) => {
161
165
  const row = rowOf(reference);
@@ -1,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import { type BusinessKind } from "../../domain/business.js";
2
3
  import type { AccountKey } from "../types.js";
3
4
  import type { StoreContext } from "./open.js";
@@ -35,7 +36,7 @@ export interface BusinessHit {
35
36
  }
36
37
  /** Invoices, payments, orders, contracts, subscriptions, products and wallets, found by their numbers and names. */
37
38
  export interface BusinessSearchStore {
38
- find(search: BusinessSearch): Promise<BusinessHit[]>;
39
+ find(search: BusinessSearch): Promise<ListResult<BusinessHit>>;
39
40
  /** Every account with a live record of a row the lane reads. */
40
41
  accounts(): Promise<AccountKey[]>;
41
42
  }
@@ -1,5 +1,6 @@
1
1
  import { BUSINESS_KINDS } from "../../domain/business.js";
2
2
  import { fold } from "../normalize.js";
3
+ import { pageOfRows } from "./rows-page.js";
3
4
  /** The most rows one `find` answers: a `search all` page read as deep as its offset allows, and one more. */
4
5
  export const BUSINESS_FIND_MAX = 2001;
5
6
  const party = (kind, id, as) => `LEFT JOIN persons ${as}p ON ${kind} = 'person' AND ${as}p.id = ${id} AND ${as}p.owner = 0 ` +
@@ -98,13 +99,13 @@ export const businessSearchOver = ({ database }) => {
98
99
  const find = ({ words, anyWord = false, accounts, limit }) => {
99
100
  const wanted = [...new Set(words.map((word) => fold(word).trim()).filter(Boolean))];
100
101
  if (!wanted.length)
101
- return [];
102
+ return { items: [], hasMore: false };
102
103
  const most = Math.min(Math.max(limit ?? 100, 1), BUSINESS_FIND_MAX);
103
104
  const within = accounts === undefined ? undefined : new Set(accounts.map(keyOf));
104
105
  // Numbers and names are short; folding them here is cheaper than an index the store would keep in step.
105
106
  const matched = BUSINESS_KINDS.flatMap((kind) => matchedOf(kind, wanted, anyWord)).sort((a, b) => b.score - a.score || b.updatedAt - a.updatedAt || a.kind.localeCompare(b.kind) || b.id - a.id);
106
107
  // Without a scope only the page needs its records; with one, every match is checked against it first.
107
- const candidates = within === undefined ? matched.slice(0, most) : matched.filter((one) => one.imported);
108
+ const candidates = within === undefined ? matched.slice(0, most + 1) : matched.filter((one) => one.imported);
108
109
  const sources = sourcesOf(candidates);
109
110
  const kept = within === undefined
110
111
  ? candidates
@@ -113,8 +114,8 @@ export const businessSearchOver = ({ database }) => {
113
114
  const source = sources.get(`${one.kind}:${one.id}`);
114
115
  return source !== undefined && within.has(keyOf(source));
115
116
  })
116
- .slice(0, most);
117
- return kept.map((one) => {
117
+ .slice(0, most + 1);
118
+ const hits = kept.map((one) => {
118
119
  const ref = `${one.kind}:${one.id}`;
119
120
  const source = sources.get(ref);
120
121
  return {
@@ -127,6 +128,7 @@ export const businessSearchOver = ({ database }) => {
127
128
  updatedAt: one.updatedAt,
128
129
  };
129
130
  });
131
+ return pageOfRows(hits, most);
130
132
  };
131
133
  const sourceAccounts = () => database
132
134
  .prepare("SELECT DISTINCT a.provider, a.external_id AS account FROM records r JOIN accounts a ON a.id = r.account_id " +
@@ -1,3 +1,4 @@
1
+ import type { ListResult } from "@wirecat/cli-base/standards";
1
2
  import type { CrmValue } from "../../domain/crm.js";
2
3
  import { type DealKind, type DealRole, type DealStatus, type StageOutcome } from "../../domain/deals.js";
3
4
  import type { AccountKey } from "../types.js";
@@ -179,6 +180,7 @@ export interface DealSearch {
179
180
  kinds?: readonly DealKind[];
180
181
  /** 1–500, 100 by default. */
181
182
  limit?: number;
183
+ offset?: number;
182
184
  }
183
185
  /** Where a deal's or a lead's words are searched: its title, its company, the people on it. */
184
186
  export type DealPart = "title" | "company" | "contact";
@@ -224,13 +226,13 @@ export interface DealsStore {
224
226
  get(reference: string): Promise<Deal>;
225
227
  /** Every stage it entered, in the order it entered them: a CRM's own stamps may run out of order. */
226
228
  stages(reference: string): Promise<StageChange[]>;
227
- list(filter?: DealFilter): Promise<Deal[]>;
229
+ list(filter?: DealFilter): Promise<ListResult<Deal>>;
228
230
  /**
229
231
  * Deals and leads together, by the words of their title, company and contacts: a query word matches a stored word
230
232
  * it begins or one of the same stem. The most words matched first, then the latest changed. When nothing matches,
231
233
  * a misspelt word is corrected to the stored words nearest to it, once.
232
234
  */
233
- find(search: DealSearch): Promise<FoundDeal[]>;
235
+ find(search: DealSearch): Promise<ListResult<FoundDeal>>;
234
236
  /**
235
237
  * The project it belongs to; `null` clears it. A CRM copy takes it too: the project is the store's own field, which
236
238
  * a CRM has none of and its sync never writes.
@@ -266,8 +268,8 @@ export declare const dealOperationsOver: (context: StoreContext) => {
266
268
  add: (input: DealInput) => Deal;
267
269
  get: (reference: string) => Deal;
268
270
  stages: (reference: string) => StageChange[];
269
- list: (filter?: DealFilter) => Deal[];
270
- find: ({ words, anyWord, exact, accounts, kinds, limit }: DealSearch) => Promise<FoundDeal[]>;
271
+ list: (filter?: DealFilter) => ListResult<Deal>;
272
+ find: (wanted: DealSearch) => Promise<ListResult<FoundDeal>>;
271
273
  setProject: (reference: string, { project, by }: {
272
274
  project: string | null;
273
275
  by: Author;
@@ -12,6 +12,7 @@ import { linkKind } from "./link-kinds.js";
12
12
  import { authorActor, authorOf, evidenceOf, linkEvidence, projectId, projectOf } from "./memories.js";
13
13
  import { requiredThing } from "./notes.js";
14
14
  import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text } from "./reviewed.js";
15
+ import { pageOfRows } from "./rows-page.js";
15
16
  import { stageAmountsOf } from "./stage-amounts.js";
16
17
  import { write } from "./transaction.js";
17
18
  const TABLES = { deal: "deals", lead: "leads" };
@@ -426,16 +427,19 @@ export const dealOperationsOver = (context) => {
426
427
  const inAccounts = keys === undefined
427
428
  ? ""
428
429
  : `AND (d.account_id IS NULL OR a.provider || ':' || a.external_id IN (${keys.map(() => "?").join(", ") || "NULL"})) `;
429
- return database
430
+ const offset = Math.max(0, Math.trunc(filter.offset ?? 0));
431
+ const rows = database
430
432
  .prepare(`${itemsSql(kind)} WHERE d.deleted_at IS NULL AND (? IS NULL OR d.status = ?) ` +
431
433
  "AND (? IS NULL OR d.project_id = ?) AND (? IS NULL OR s.name_folded = ?) AND (? IS NULL OR p.id = ?) " +
432
434
  "AND (? IS NULL OR d.organization_id = ?) AND (? = 0 OR d.account_id IS NULL) " +
433
435
  `AND (? IS NULL OR (a.provider = ? AND a.external_id = ?)) ${inAccounts}AND ${by.sql} ` +
434
436
  "ORDER BY d.created_at DESC, d.id DESC LIMIT ? OFFSET ?")
435
- .all(status, status, project, project, stage, stage, pipeline, pipeline, organization?.id ?? null, organization?.id ?? null, own, provider, provider, account, ...(keys ?? []), ...by.params, limit, Math.max(0, Math.trunc(filter.offset ?? 0)))
437
+ .all(status, status, project, project, stage, stage, pipeline, pipeline, organization?.id ?? null, organization?.id ?? null, own, provider, provider, account, ...(keys ?? []), ...by.params, limit + 1, offset)
436
438
  .map(itemOf(kind));
439
+ return pageOfRows(rows, limit, offset);
437
440
  },
438
- find: async ({ words, anyWord, exact = false, accounts, kinds = DEAL_KINDS, limit }) => {
441
+ find: async (wanted) => {
442
+ const { words, anyWord, exact = false, accounts, kinds = DEAL_KINDS, limit, offset = 0 } = wanted;
439
443
  const seen = new Set();
440
444
  const clauses = words
441
445
  .map((word) => tokensOf(word).filter((token) => fold(token)))
@@ -446,9 +450,9 @@ export const dealOperationsOver = (context) => {
446
450
  seen.add(key);
447
451
  return true;
448
452
  });
449
- if (!clauses.length)
450
- return [];
451
453
  const most = Math.min(Math.max(limit ?? 100, 1), 500);
454
+ if (!clauses.length)
455
+ return { items: [], hasMore: false };
452
456
  const within = accounts?.map(({ provider, account }) => `${provider}\u0000${account}`);
453
457
  const stored = new Map();
454
458
  const wordsOf = (text) => tokensOf(text).flatMap((token) => {
@@ -552,16 +556,17 @@ export const dealOperationsOver = (context) => {
552
556
  found = search(queryWith(fixes));
553
557
  }
554
558
  }
555
- return found
559
+ const ranked = found
556
560
  .sort((a, b) => b.score - a.score ||
557
561
  Number(b.row.updated_at) - Number(a.row.updated_at) ||
558
562
  Number(b.row.id) - Number(a.row.id))
559
- .slice(0, most)
563
+ .slice(offset, offset + most + 1)
560
564
  .map(({ kind, row, matched }) => ({
561
565
  ...read(`${kind}:${row.id}`),
562
566
  matched,
563
567
  ...(corrections ? { corrections } : {}),
564
568
  }));
569
+ return pageOfRows(ranked, most, offset);
565
570
  },
566
571
  setProject: (reference, { project, by }) => {
567
572
  authorActor(context, by);