@wirecat/cli-core 0.618.0 → 0.620.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 (335) hide show
  1. package/CHANGELOG.md +453 -1
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES +3 -0
  4. package/dist/background/deliver.d.ts +5 -2
  5. package/dist/background/deliver.js +30 -12
  6. package/dist/background/report/render.d.ts +3 -1
  7. package/dist/background/report/render.js +3 -1
  8. package/dist/calendar/cli/answers.d.ts +1 -0
  9. package/dist/calendar/cli/answers.js +6 -1
  10. package/dist/calendar/cli/index.js +2 -14
  11. package/dist/calendar/cli/people-link.d.ts +3 -0
  12. package/dist/calendar/cli/people-link.js +23 -0
  13. package/dist/calendar/cli/search-all.d.ts +1 -1
  14. package/dist/calendar/cli/search-all.js +9 -10
  15. package/dist/calendar/index.d.ts +1 -1
  16. package/dist/calendar/index.js +1 -1
  17. package/dist/calendar/mcp/index.d.ts +12 -12
  18. package/dist/calendar/prepare.js +1 -0
  19. package/dist/cli/base-stages-command.d.ts +22 -0
  20. package/dist/cli/base-stages-command.js +174 -0
  21. package/dist/cli/bot/buttons.d.ts +3 -0
  22. package/dist/cli/bot/buttons.js +24 -0
  23. package/dist/cli/bot/messages.js +14 -1
  24. package/dist/cli/bot/port.d.ts +8 -0
  25. package/dist/cli/command-runs.d.ts +2 -0
  26. package/dist/cli/command-runs.js +3 -1
  27. package/dist/cli/config-command.js +6 -1
  28. package/dist/cli/context.js +1 -0
  29. package/dist/cli/contract-templates.js +31 -2
  30. package/dist/cli/group-lock.d.ts +42 -0
  31. package/dist/cli/group-lock.js +130 -0
  32. package/dist/cli/index.d.ts +7 -2
  33. package/dist/cli/index.js +7 -2
  34. package/dist/cli/messenger/backfill-command.js +27 -15
  35. package/dist/cli/messenger/contacts-command.js +12 -4
  36. package/dist/cli/messenger/context.js +1 -0
  37. package/dist/cli/messenger/conversations-command.js +2 -1
  38. package/dist/cli/messenger/doctor-command.js +3 -1
  39. package/dist/cli/messenger/message-items.js +1 -1
  40. package/dist/cli/messenger/models-command.js +1 -1
  41. package/dist/cli/messenger/search-answers.d.ts +5 -5
  42. package/dist/cli/messenger/search-answers.js +9 -20
  43. package/dist/cli/messenger/search-command.d.ts +2 -2
  44. package/dist/cli/messenger/search-command.js +8 -18
  45. package/dist/cli/messenger/store-maintenance-command.d.ts +22 -2
  46. package/dist/cli/messenger/store-maintenance-command.js +9 -4
  47. package/dist/cli/model-catalogue-command.d.ts +3 -1
  48. package/dist/cli/model-catalogue-command.js +48 -2
  49. package/dist/cli/profile.d.ts +8 -0
  50. package/dist/cli/profile.js +25 -0
  51. package/dist/cli/program.js +2 -0
  52. package/dist/cli/runs/search-query.d.ts +1 -1
  53. package/dist/cli/runs/search-query.js +4 -0
  54. package/dist/cli/runs/search.d.ts +5 -1
  55. package/dist/cli/runs/search.js +12 -1
  56. package/dist/cli/search-harder-consents-command.d.ts +18 -0
  57. package/dist/cli/search-harder-consents-command.js +83 -0
  58. package/dist/cli/search-left-out.d.ts +6 -1
  59. package/dist/cli/search-left-out.js +9 -4
  60. package/dist/cli/settings.d.ts +8 -0
  61. package/dist/cli/settings.js +17 -2
  62. package/dist/cli/shared-command-exports.d.ts +16 -0
  63. package/dist/cli/steps.js +0 -6
  64. package/dist/cli/store-recover.d.ts +3 -3
  65. package/dist/cli/store-recover.js +26 -26
  66. package/dist/cli/store-settings.d.ts +2 -0
  67. package/dist/cli/store-settings.js +37 -9
  68. package/dist/cli/templates-command.js +4 -4
  69. package/dist/crm/cli/index.js +40 -8
  70. package/dist/crm/cli/search-all.js +7 -6
  71. package/dist/crm/group-hint.d.ts +8 -0
  72. package/dist/crm/group-hint.js +13 -0
  73. package/dist/crm/source.d.ts +12 -1
  74. package/dist/crm/sync.d.ts +31 -2
  75. package/dist/crm/sync.js +110 -3
  76. package/dist/crm/testing/acme-scenario.d.ts +40 -0
  77. package/dist/crm/testing/acme-scenario.js +170 -0
  78. package/dist/crm/testing/index.d.ts +1 -0
  79. package/dist/crm/testing/index.js +1 -0
  80. package/dist/crm/testing/source-contract.js +12 -0
  81. package/dist/crm/testing/source.d.ts +2 -0
  82. package/dist/crm/testing/source.js +1 -0
  83. package/dist/domain/addresses.d.ts +13 -0
  84. package/dist/domain/addresses.js +63 -0
  85. package/dist/domain/categories.d.ts +3 -0
  86. package/dist/domain/categories.js +2 -0
  87. package/dist/domain/crm.d.ts +23 -0
  88. package/dist/domain/crm.js +7 -0
  89. package/dist/domain/mentions.d.ts +2 -12
  90. package/dist/domain/mentions.js +2 -19
  91. package/dist/domain/models.d.ts +2 -0
  92. package/dist/domain/orders.d.ts +8 -1
  93. package/dist/domain/orders.js +6 -2
  94. package/dist/domain/phones.d.ts +26 -0
  95. package/dist/domain/phones.js +48 -0
  96. package/dist/domain/record-types.d.ts +1 -1
  97. package/dist/domain/record-types.js +1 -0
  98. package/dist/domain/records.d.ts +5 -0
  99. package/dist/domain/ref-summaries.d.ts +39 -0
  100. package/dist/domain/ref-summaries.js +51 -3
  101. package/dist/domain/relations.d.ts +12 -2
  102. package/dist/domain/relations.js +14 -3
  103. package/dist/domain/vcard.d.ts +2 -2
  104. package/dist/domain/vcard.js +4 -10
  105. package/dist/embeddings/models.d.ts +11 -3
  106. package/dist/embeddings/models.js +28 -4
  107. package/dist/entities/business-context.d.ts +149 -0
  108. package/dist/entities/business-context.js +192 -0
  109. package/dist/entities/contact-activity.d.ts +2 -0
  110. package/dist/entities/contact-activity.js +7 -1
  111. package/dist/entities/contact-context.d.ts +160 -0
  112. package/dist/entities/contact-context.js +6 -0
  113. package/dist/entities/deal.d.ts +10 -0
  114. package/dist/entities/deal.js +2 -0
  115. package/dist/entities/hit.d.ts +9 -2
  116. package/dist/entities/hit.js +6 -2
  117. package/dist/entities/index.d.ts +32 -4
  118. package/dist/entities/index.js +5 -0
  119. package/dist/entities/mention.d.ts +4 -3
  120. package/dist/entities/mention.js +2 -1
  121. package/dist/entities/message-transfer.d.ts +4 -2
  122. package/dist/entities/message-transfer.js +2 -2
  123. package/dist/entities/model.d.ts +2 -2
  124. package/dist/entities/model.js +1 -1
  125. package/dist/entities/relationship.d.ts +4 -0
  126. package/dist/entities/relationship.js +4 -0
  127. package/dist/errors/reasons.js +39 -4
  128. package/dist/fetch/page.js +2 -1
  129. package/dist/index.d.ts +3 -2
  130. package/dist/index.js +3 -2
  131. package/dist/meetings/context-store.d.ts +2 -0
  132. package/dist/meetings/findings-rules.d.ts +4 -0
  133. package/dist/meetings/findings-rules.js +5 -2
  134. package/dist/meetings/hit-query.d.ts +1 -1
  135. package/dist/meetings/hit-query.js +2 -2
  136. package/dist/meetings/index.d.ts +1 -0
  137. package/dist/meetings/index.js +1 -0
  138. package/dist/meetings/result-items.d.ts +1 -0
  139. package/dist/meetings/result-items.js +1 -0
  140. package/dist/meetings/store.d.ts +4 -0
  141. package/dist/meetings/store.js +2 -1
  142. package/dist/models/anthropic.js +5 -0
  143. package/dist/models/index.js +22 -5
  144. package/dist/runs/events.d.ts +11 -1
  145. package/dist/runs/events.js +3 -1
  146. package/dist/runs/log-attributes.js +4 -0
  147. package/dist/runs/log-events.js +2 -0
  148. package/dist/runs/recording.d.ts +3 -0
  149. package/dist/runs/recording.js +36 -12
  150. package/dist/runs/run.d.ts +12 -3
  151. package/dist/runs/run.js +32 -13
  152. package/dist/search/account-list.d.ts +6 -0
  153. package/dist/search/account-list.js +9 -3
  154. package/dist/search/groups.d.ts +68 -0
  155. package/dist/search/groups.js +172 -0
  156. package/dist/search/question-period.d.ts +10 -0
  157. package/dist/search/question-period.js +133 -0
  158. package/dist/sends/buttons.d.ts +2 -0
  159. package/dist/sends/buttons.js +6 -1
  160. package/dist/services/account-groups.d.ts +28 -0
  161. package/dist/services/account-groups.js +89 -0
  162. package/dist/services/archive.d.ts +7 -1
  163. package/dist/services/archive.js +19 -3
  164. package/dist/services/business-context.d.ts +113 -0
  165. package/dist/services/business-context.js +156 -0
  166. package/dist/services/communications.d.ts +50 -0
  167. package/dist/services/communications.js +140 -0
  168. package/dist/services/deal-context.d.ts +90 -0
  169. package/dist/services/deal-context.js +131 -0
  170. package/dist/services/deps.d.ts +2 -0
  171. package/dist/services/enrichment.d.ts +12 -2
  172. package/dist/services/enrichment.js +47 -6
  173. package/dist/services/events-search.js +2 -1
  174. package/dist/services/group-guard.d.ts +28 -0
  175. package/dist/services/group-guard.js +131 -0
  176. package/dist/services/index.d.ts +19 -4
  177. package/dist/services/index.js +12 -3
  178. package/dist/services/ingest.d.ts +12 -0
  179. package/dist/services/ingest.js +4 -0
  180. package/dist/services/meaning-model.d.ts +7 -0
  181. package/dist/services/meaning-model.js +20 -0
  182. package/dist/services/meeting-context.d.ts +6 -1
  183. package/dist/services/meeting-context.js +12 -5
  184. package/dist/services/message-resolution.js +2 -3
  185. package/dist/services/messages-meaning.js +4 -5
  186. package/dist/services/messages-search.d.ts +5 -1
  187. package/dist/services/messages-search.js +1 -1
  188. package/dist/services/messages.d.ts +1 -4
  189. package/dist/services/messages.js +0 -2
  190. package/dist/services/metadata.d.ts +1 -1
  191. package/dist/services/model-downloads.d.ts +1 -1
  192. package/dist/services/model-downloads.js +6 -4
  193. package/dist/services/money-context.d.ts +73 -0
  194. package/dist/services/money-context.js +77 -0
  195. package/dist/services/notes-search.d.ts +4 -1
  196. package/dist/services/notes-search.js +19 -7
  197. package/dist/services/organization-context.d.ts +80 -0
  198. package/dist/services/organization-context.js +154 -0
  199. package/dist/services/people.d.ts +22 -6
  200. package/dist/services/people.js +38 -8
  201. package/dist/services/person-business.d.ts +43 -0
  202. package/dist/services/person-business.js +67 -0
  203. package/dist/services/person-context.d.ts +11 -1
  204. package/dist/services/person-context.js +25 -10
  205. package/dist/services/person-preparation.d.ts +5 -1
  206. package/dist/services/person-preparation.js +10 -3
  207. package/dist/services/person-timeline.d.ts +6 -1
  208. package/dist/services/person-timeline.js +10 -2
  209. package/dist/services/proposals/kinds/identity-link.d.ts +4 -0
  210. package/dist/services/proposals/kinds/identity-link.js +48 -0
  211. package/dist/services/proposals/kinds/orders.js +1 -1
  212. package/dist/services/proposals/registry.js +2 -0
  213. package/dist/services/search-all-deprecated.d.ts +40 -0
  214. package/dist/services/search-all-deprecated.js +10 -0
  215. package/dist/services/search-all-meetings.d.ts +50 -52
  216. package/dist/services/search-all-meetings.js +265 -272
  217. package/dist/services/search-all.d.ts +34 -6
  218. package/dist/services/search-all.js +118 -24
  219. package/dist/services/search-harder.d.ts +64 -0
  220. package/dist/services/search-harder.js +194 -0
  221. package/dist/services/search-kind.d.ts +12 -5
  222. package/dist/services/search-kind.js +49 -10
  223. package/dist/services/text-model-choice.js +1 -1
  224. package/dist/store/accounts.d.ts +18 -0
  225. package/dist/store/accounts.js +18 -3
  226. package/dist/store/chats.d.ts +3 -1
  227. package/dist/store/chats.js +6 -0
  228. package/dist/store/damage.d.ts +43 -10
  229. package/dist/store/damage.js +119 -36
  230. package/dist/store/decisions.js +3 -1
  231. package/dist/store/evidence-findings.d.ts +14 -0
  232. package/dist/store/evidence-findings.js +2 -0
  233. package/dist/store/exports.d.ts +2 -1
  234. package/dist/store/identity-links.d.ts +92 -0
  235. package/dist/store/identity-links.js +6 -0
  236. package/dist/store/index.d.ts +11 -5
  237. package/dist/store/index.js +5 -2
  238. package/dist/store/journal.d.ts +10 -0
  239. package/dist/store/journal.js +33 -0
  240. package/dist/store/marks.d.ts +19 -1
  241. package/dist/store/marks.js +23 -1
  242. package/dist/store/people.d.ts +28 -2
  243. package/dist/store/people.js +15 -1
  244. package/dist/store/sqlite/accounts.js +2 -0
  245. package/dist/store/sqlite/added-sources.d.ts +15 -3
  246. package/dist/store/sqlite/added-sources.js +26 -5
  247. package/dist/store/sqlite/base-stages.d.ts +122 -0
  248. package/dist/store/sqlite/base-stages.js +443 -0
  249. package/dist/store/sqlite/base-suggest.d.ts +13 -0
  250. package/dist/store/sqlite/base-suggest.js +62 -0
  251. package/dist/store/sqlite/business-contracts.js +10 -1
  252. package/dist/store/sqlite/chats.d.ts +2 -0
  253. package/dist/store/sqlite/chats.js +6 -0
  254. package/dist/store/sqlite/crm-settings.d.ts +12 -2
  255. package/dist/store/sqlite/crm-settings.js +56 -13
  256. package/dist/store/sqlite/crm.d.ts +13 -1
  257. package/dist/store/sqlite/crm.js +20 -4
  258. package/dist/store/sqlite/deals.d.ts +33 -0
  259. package/dist/store/sqlite/deals.js +42 -4
  260. package/dist/store/sqlite/decision-requests.js +7 -3
  261. package/dist/store/sqlite/email-index.js +8 -4
  262. package/dist/store/sqlite/evidence-findings.js +29 -5
  263. package/dist/store/sqlite/findings-core.js +4 -2
  264. package/dist/store/sqlite/identity-link-rows.d.ts +50 -0
  265. package/dist/store/sqlite/identity-link-rows.js +146 -0
  266. package/dist/store/sqlite/identity-proposals.d.ts +53 -0
  267. package/dist/store/sqlite/identity-proposals.js +234 -0
  268. package/dist/store/sqlite/involvements.d.ts +1 -1
  269. package/dist/store/sqlite/involvements.js +4 -2
  270. package/dist/store/sqlite/knowledge.js +2 -2
  271. package/dist/store/sqlite/link-kinds.d.ts +1 -0
  272. package/dist/store/sqlite/link-kinds.js +1 -0
  273. package/dist/store/sqlite/link-row.d.ts +6 -0
  274. package/dist/store/sqlite/link-row.js +35 -0
  275. package/dist/store/sqlite/link-source.d.ts +10 -0
  276. package/dist/store/sqlite/link-source.js +16 -0
  277. package/dist/store/sqlite/manifest.js +1 -0
  278. package/dist/store/sqlite/meeting-context-links.js +9 -6
  279. package/dist/store/sqlite/meeting-hit-query.d.ts +5 -0
  280. package/dist/store/sqlite/meeting-hit-query.js +33 -0
  281. package/dist/store/sqlite/meeting-hit-search.js +10 -8
  282. package/dist/store/sqlite/meetings.js +1 -1
  283. package/dist/store/sqlite/memories.js +9 -7
  284. package/dist/store/sqlite/mentions.d.ts +4 -1
  285. package/dist/store/sqlite/mentions.js +14 -9
  286. package/dist/store/sqlite/migrations.generated.js +8 -0
  287. package/dist/store/sqlite/notes.d.ts +8 -2
  288. package/dist/store/sqlite/notes.js +17 -34
  289. package/dist/store/sqlite/open-store.js +3 -0
  290. package/dist/store/sqlite/open.js +11 -2
  291. package/dist/store/sqlite/orders.d.ts +2 -0
  292. package/dist/store/sqlite/orders.js +9 -3
  293. package/dist/store/sqlite/organization-categories.d.ts +18 -0
  294. package/dist/store/sqlite/organization-categories.js +34 -0
  295. package/dist/store/sqlite/organizations.d.ts +5 -1
  296. package/dist/store/sqlite/organizations.js +14 -4
  297. package/dist/store/sqlite/person-links.d.ts +19 -4
  298. package/dist/store/sqlite/person-links.js +49 -11
  299. package/dist/store/sqlite/person-match-scan.d.ts +13 -0
  300. package/dist/store/sqlite/person-match-scan.js +251 -0
  301. package/dist/store/sqlite/person-matcher.d.ts +16 -0
  302. package/dist/store/sqlite/person-matcher.js +32 -0
  303. package/dist/store/sqlite/person-preparation.d.ts +7 -3
  304. package/dist/store/sqlite/person-preparation.js +20 -6
  305. package/dist/store/sqlite/proposed-actions.js +6 -0
  306. package/dist/store/sqlite/record-matching.d.ts +2 -8
  307. package/dist/store/sqlite/record-matching.js +8 -40
  308. package/dist/store/sqlite/record-projectors-phone.js +2 -1
  309. package/dist/store/sqlite/record-relationships.d.ts +52 -0
  310. package/dist/store/sqlite/record-relationships.js +243 -0
  311. package/dist/store/sqlite/record-run.d.ts +5 -0
  312. package/dist/store/sqlite/record-run.js +62 -2
  313. package/dist/store/sqlite/record-writes.d.ts +1 -1
  314. package/dist/store/sqlite/record-writes.js +4 -2
  315. package/dist/store/sqlite/records.js +27 -2
  316. package/dist/store/sqlite/ref-accounts.d.ts +13 -0
  317. package/dist/store/sqlite/ref-accounts.js +117 -0
  318. package/dist/store/sqlite/ref-summaries.js +5 -1
  319. package/dist/store/sqlite/relation-list.d.ts +4 -1
  320. package/dist/store/sqlite/relation-list.js +22 -4
  321. package/dist/store/sqlite/relation-proposals.d.ts +6 -0
  322. package/dist/store/sqlite/relation-proposals.js +3 -0
  323. package/dist/store/sqlite/relation-roles.js +12 -6
  324. package/dist/store/sqlite/reported-relations.d.ts +11 -1
  325. package/dist/store/sqlite/reported-relations.js +59 -18
  326. package/dist/store/sqlite/schema.d.ts +32 -0
  327. package/dist/store/sqlite/schema.js +3 -0
  328. package/dist/store/sqlite/transaction.js +11 -1
  329. package/dist/store/store.d.ts +3 -0
  330. package/dist/store/store.js +5 -0
  331. package/dist/store/write-events.d.ts +18 -0
  332. package/dist/store/write-events.js +88 -0
  333. package/package.json +3 -3
  334. package/parity.json +37 -16
  335. package/schemas/records-envelope.v1.schema.json +3 -0
@@ -3,14 +3,18 @@ import { type HitFile } from "../domain/attachments.js";
3
3
  import type { DealKind } from "../domain/deals.js";
4
4
  import { type MailFields } from "../domain/models.js";
5
5
  import type { MessengerTraits } from "../ports/traits.js";
6
- import type { AccountKey, BusinessKind, BusinessSource, MessageStore } from "../store/store.js";
6
+ import type { AccountKey, BusinessKind, BusinessSource, MessageStore, StoredAccount } from "../store/store.js";
7
7
  import type { SearchFound, SearchQuery } from "./messages.js";
8
8
  import { type MeaningLane, type MeaningSkipped } from "./messages-discovery.js";
9
9
  import type { SearchCoverage } from "./messages-search.js";
10
+ import { type MeetingAccountCoverage, type MeetingSearchItem } from "./search-all-meetings.js";
11
+ import { type HarderOptions, type HarderResult } from "./search-harder.js";
10
12
  import type { Backend, ServerOptions, ServerSearched } from "./server-search.js";
11
- export declare const RESOURCES_SEARCHED: readonly ["messages", "mail", "notes", "events", "crm", "business"];
13
+ export declare const RESOURCES_SEARCHED: readonly ["messages", "mail", "notes", "events", "crm", "business", "meetings"];
12
14
  export type SearchedResource = (typeof RESOURCES_SEARCHED)[number];
13
- export interface SearchAllItem {
15
+ /** One hit of `search all`: a stored record, or a passage of a meeting. */
16
+ export type SearchAllItem = SearchAllRecordItem | MeetingSearchItem;
17
+ export interface SearchAllRecordItem {
14
18
  kind: "message" | "mail" | "note" | "document" | "event" | "deal" | "lead" | BusinessKind;
15
19
  /** `msg:…` for a message or a mail, `note:…`, `event:…`, `deal:…`, `lead:…`, or a business ref: `invoice:…`. */
16
20
  ref: string;
@@ -101,6 +105,10 @@ export interface SearchAllFound {
101
105
  coverage?: SearchCoverage;
102
106
  /** When nothing was found by all the words: the words that alone find nothing in `searched` either. */
103
107
  unmatched?: string[];
108
+ /** What each meeting account read could answer; absent when no meeting account was read. */
109
+ meetings?: MeetingAccountCoverage[];
110
+ /** What `harder` did, when it was asked: reordered, or kept the plain order and why. */
111
+ harder?: HarderResult;
104
112
  }
105
113
  export interface SearchAllRequest {
106
114
  text: string;
@@ -110,6 +118,8 @@ export interface SearchAllRequest {
110
118
  only?: readonly SearchedResource[];
111
119
  exact?: boolean;
112
120
  timezone?: string;
121
+ /** The clock a question's "last week" or "in March" is read on; absent, the time of the call. */
122
+ now?: number;
113
123
  /** For messages only; mail, notes, events and CRM copies are always the local store's. */
114
124
  backend?: Backend;
115
125
  server?: ServerOptions;
@@ -117,8 +127,25 @@ export interface SearchAllRequest {
117
127
  signal?: AbortSignal;
118
128
  /** The accounts `--source` chose, per kind; a kind left out reads every account of its own. */
119
129
  scope?: Partial<Record<SearchedResource, AccountKey[]>>;
130
+ /**
131
+ * `--source` as typed: each kind reads the accounts the list names of it, and a kind it names none of is skipped.
132
+ * It replaces `scope`.
133
+ */
134
+ source?: string;
135
+ /** The scopes whose meeting accounts are read; absent, the scope of the caller's stored account only. */
136
+ meetingScopes?: readonly StoredAccount["scope"][];
137
+ /**
138
+ * The caller named meetings (`--only meetings`), so none to read is a skip that makes the answer incomplete; else
139
+ * a store with no meeting account says nothing about them, as one with no calendar says nothing of events.
140
+ */
141
+ meetingsAsked?: boolean;
120
142
  /** The CRM kinds `crm` reads; absent, deals and leads. */
121
143
  crmKinds?: readonly DealKind[];
144
+ /**
145
+ * Search harder: a hosted model reorders the first 30 hits, only with the owner's consent and a key. Absent, nothing
146
+ * is read of the consent or the key and nothing is sent.
147
+ */
148
+ harder?: HarderOptions;
122
149
  }
123
150
  export type SearchAllMessenger = Partial<Pick<MessengerTraits, "savedChatId" | "app">> & {
124
151
  /**
@@ -138,8 +165,9 @@ export declare const titleWords: (text: string, refused?: string) => {
138
165
  /** The accounts of every CRM the store holds copies of. */
139
166
  export declare const crmAccounts: (store: MessageStore) => Promise<AccountKey[]>;
140
167
  /**
141
- * `search all`: messages, mail, notes, calendar events, CRM deals and leads, and business data from the local store — messages also from the messenger's
142
- * server, as `search messages` asks it — each list best first, merged by reciprocal rank so no
143
- * resource's own scores have to be compared with another's. Events are read only when the store holds a calendar.
168
+ * `search all`: messages, mail, notes, calendar events, CRM deals and leads, business data and meeting passages from
169
+ * the local store — messages also from the messenger's server, as `search messages` asks it — each list best first,
170
+ * merged by rank so no resource's own scores have to be compared with another's. Events are read only when the store
171
+ * holds a calendar, meetings only when it holds a meeting account.
144
172
  */
145
173
  export declare const searchAll: (store: MessageStore, account: AccountKey, asked: SearchAllRequest, messenger?: SearchAllMessenger, searchMessages?: (query: SearchQuery) => Promise<SearchFound>, meaning?: MeaningLane) => Promise<SearchAllFound>;
@@ -1,13 +1,15 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { parseLucene } from "@wirecat/cli-base/query";
2
+ import { parseLucene, timezoneOf } from "@wirecat/cli-base/query";
3
3
  import { hitFiles } from "../domain/attachments.js";
4
4
  import { parseLocator } from "../domain/locator.js";
5
5
  import { senderIsMe } from "../domain/models.js";
6
6
  import { holdsKind, INTERNAL_NOTES } from "../domain/providers.js";
7
7
  import { runEmbedders } from "../embeddings/embed.js";
8
8
  import { chosenTextModel } from "../embeddings/models.js";
9
+ import { entriesOfList, fitting, listedHolds } from "../search/account-list.js";
9
10
  import { plainQuery } from "../search/lucene/plain.js";
10
11
  import { MESSAGE_PARSING, SEARCH_QUERY } from "../search/lucene/types.js";
12
+ import { questionPeriod } from "../search/question-period.js";
11
13
  import { planQuestion, questionLookup } from "../search/question-plan.js";
12
14
  import { calendarAccounts, searchEvents } from "./events-search.js";
13
15
  import { excerpt } from "./excerpt.js";
@@ -15,7 +17,10 @@ import { MAX_SEARCH_OFFSET, searchStore } from "./messages-archive-search.js";
15
17
  import { nearEligible } from "./messages-discovery.js";
16
18
  import { notesScopeOf, RRF_K, searchNotes } from "./notes-search.js";
17
19
  import { BUSINESS_WORDS_ONLY, searchBusiness } from "./search-all-business.js";
18
- export const RESOURCES_SEARCHED = ["messages", "mail", "notes", "events", "crm", "business"];
20
+ import { meetingLane } from "./search-all-meetings.js";
21
+ import { HARDER_CANDIDATES, reorderHarder } from "./search-harder.js";
22
+ import { listContextOf } from "./search-kind.js";
23
+ export const RESOURCES_SEARCHED = ["messages", "mail", "notes", "events", "crm", "business", "meetings"];
19
24
  const refusal = (error, text) => {
20
25
  const { reason, span } = (error.details ?? {});
21
26
  const why = typeof reason === "string" ? reason : undefined;
@@ -71,12 +76,36 @@ const strictWords = (text) => {
71
76
  throw error;
72
77
  }
73
78
  };
79
+ const accountKeyOf = ({ provider, account }) => `${provider}\u0000${account}`;
80
+ /** `--source` as the accounts each kind reads; a kind it names no account of is skipped, not read in full. */
81
+ const sourceScope = async (store, account, source, asked, messenger) => {
82
+ const entries = entriesOfList(source, await listContextOf(store, account, messenger.app));
83
+ // Any provider's import may write business data, so its accounts are the ones that hold some, whatever their kind.
84
+ const imported = asked.includes("business")
85
+ ? new Set((await store.business.accounts()).map(accountKeyOf))
86
+ : new Set();
87
+ const holdsBusiness = (one) => imported.has(accountKeyOf(one));
88
+ const { skipped } = fitting(entries, asked.filter((one) => one !== "business"), "search all", (kind) => `--only leaves ${kind} out`, holdsBusiness);
89
+ const named = (resource) => [
90
+ ...new Map(entries
91
+ .flatMap(({ accounts }) => accounts)
92
+ .filter((one) => (resource === "business" ? holdsBusiness(one) : listedHolds(one, resource)))
93
+ .map(({ provider, account }) => [`${provider}\u0000${account}`, { provider, account }])).values(),
94
+ ];
95
+ const scope = Object.fromEntries(asked.map((resource) => [resource, named(resource)]));
96
+ const only = asked.filter((resource) => scope[resource]?.length);
97
+ const unnamed = asked
98
+ .filter((resource) => !only.includes(resource))
99
+ .map((resource) => ({ resource, code: "not_found", reason: `--source names no ${resource} account` }));
100
+ return { only, scope, skipped: [...skipped, ...unnamed] };
101
+ };
74
102
  /** The accounts of every CRM the store holds copies of. */
75
103
  export const crmAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "crm"));
76
104
  /**
77
- * `search all`: messages, mail, notes, calendar events, CRM deals and leads, and business data from the local store — messages also from the messenger's
78
- * server, as `search messages` asks it — each list best first, merged by reciprocal rank so no
79
- * resource's own scores have to be compared with another's. Events are read only when the store holds a calendar.
105
+ * `search all`: messages, mail, notes, calendar events, CRM deals and leads, business data and meeting passages from
106
+ * the local store — messages also from the messenger's server, as `search messages` asks it — each list best first,
107
+ * merged by rank so no resource's own scores have to be compared with another's. Events are read only when the store
108
+ * holds a calendar, meetings only when it holds a meeting account.
80
109
  */
81
110
  export const searchAll = async (store, account, asked, messenger = {}, searchMessages = (query) => searchStore(store, account, query, messenger), meaning) => {
82
111
  if (!asked.text.trim())
@@ -85,14 +114,20 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
85
114
  const offset = request.offset ?? 0;
86
115
  if (!Number.isInteger(offset) || offset < 0 || offset > MAX_SEARCH_OFFSET)
87
116
  throw new CliError("validation_error", `offset takes a whole number from 0 to ${MAX_SEARCH_OFFSET}`);
88
- // Each resource is read deep enough for the merged page, then the merge is cut.
117
+ const period = questionPeriod(request.text, request.now ?? Date.now(), timezoneOf(request.timezone));
118
+ // Each resource is read deep enough for the merged page, then the merge is cut; a named period reads deeper, so a
119
+ // hit inside it can move up from below the page.
89
120
  const window = offset + request.limit;
90
- const only = request.only ?? RESOURCES_SEARCHED;
121
+ const depth = Math.max(window, period ? PERIOD_DEPTH : 0, request.harder ? HARDER_CANDIDATES : 0);
122
+ const chosen = request.source === undefined
123
+ ? { only: request.only ?? RESOURCES_SEARCHED, scope: request.scope, skipped: [] }
124
+ : await sourceScope(store, account, request.source, request.only ?? RESOURCES_SEARCHED, messenger);
125
+ const { only, scope } = chosen;
91
126
  const command = messenger.hintCommand === undefined ? messenger.app?.command : (messenger.hintCommand ?? undefined);
92
127
  const lists = [];
93
128
  const searched = [];
94
129
  const accounts = [];
95
- const skipped = [];
130
+ const skipped = [...chosen.skipped];
96
131
  let hasMore = false;
97
132
  let notes;
98
133
  let events;
@@ -103,8 +138,9 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
103
138
  /** Each hit found by meaning, by its cosine: one model for every source, so these compare across them. */
104
139
  const cosines = new Map();
105
140
  let coverage;
141
+ let meetings;
106
142
  const messagesOf = async (kind) => {
107
- const given = request.scope?.[kind];
143
+ const given = scope?.[kind];
108
144
  // The server still gets the question as typed: a query that is not a sentence still finds what it holds.
109
145
  const discovers = discover && (kind === "mail" || request.backend !== "server");
110
146
  const query = {
@@ -119,7 +155,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
119
155
  ...(request.server === undefined ? {} : { server: request.server }),
120
156
  }
121
157
  : {}),
122
- limit: window,
158
+ limit: depth,
123
159
  ...(request.exact ? { exact: true } : {}),
124
160
  ...(discovers ? { discover: true } : {}),
125
161
  ...(request.timezone === undefined ? {} : { timezone: request.timezone }),
@@ -202,9 +238,9 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
202
238
  for (const resource of only) {
203
239
  try {
204
240
  if (resource === "notes") {
205
- const chosen = request.scope?.notes;
241
+ const chosen = scope?.notes;
206
242
  const found = await searchNotes(store, request.text, {
207
- limit: window,
243
+ limit: depth,
208
244
  command,
209
245
  embedders,
210
246
  ...(chosen === undefined ? {} : notesScopeOf(chosen)),
@@ -241,11 +277,11 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
241
277
  accounts.push(...read.map((account) => ({ resource, provider: "notes", account })));
242
278
  }
243
279
  else if (resource === "events") {
244
- const read = request.scope?.events ?? (await calendarAccounts(store));
280
+ const read = scope?.events ?? (await calendarAccounts(store));
245
281
  if (!read.length)
246
282
  continue;
247
283
  const found = await searchEvents(store, request.text, {
248
- limit: window,
284
+ limit: depth,
249
285
  accounts: read,
250
286
  embedders,
251
287
  ...(command === undefined ? {} : { command }),
@@ -278,16 +314,16 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
278
314
  }
279
315
  else if (resource === "crm") {
280
316
  const { words, anyWord } = titleWords(request.text);
281
- const chosen = request.scope?.crm;
317
+ const chosen = scope?.crm;
282
318
  const found = await store.deals.find({
283
319
  words,
284
320
  anyWord: anyWord || discover,
285
321
  ...(request.crmKinds === undefined ? {} : { kinds: request.crmKinds }),
286
- limit: Math.min(window + 1, 500),
322
+ limit: Math.min(depth + 1, 500),
287
323
  ...(chosen === undefined ? {} : { accounts: chosen }),
288
324
  });
289
- hasMore ||= found.length > window;
290
- lists.push(found.slice(0, window).map((deal) => ({
325
+ hasMore ||= found.length > depth;
326
+ lists.push(found.slice(0, depth).map((deal) => ({
291
327
  kind: deal.kind,
292
328
  ref: deal.ref,
293
329
  provider: deal.account?.provider ?? "crm",
@@ -306,10 +342,33 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
306
342
  const found = await searchBusiness(store, {
307
343
  words,
308
344
  anyWord: anyWord || discover,
309
- window,
310
- accounts: request.scope?.business,
345
+ window: depth,
346
+ accounts: scope?.business,
347
+ });
348
+ hasMore ||= found.hasMore;
349
+ lists.push(found.items);
350
+ for (const { provider, account } of found.read)
351
+ accounts.push({ resource, provider, account });
352
+ }
353
+ else if (resource === "meetings") {
354
+ const found = await meetingLane(store, account, {
355
+ // A question finds passages that hold some of its words, as every other source does.
356
+ text: (discover ? questionLookup(request.text) : undefined) ?? request.text,
357
+ ...(discover ? { question: true } : {}),
358
+ window: depth,
359
+ ...(scope?.meetings === undefined ? {} : { accounts: scope.meetings }),
360
+ ...(request.meetingScopes === undefined ? {} : { scopes: request.meetingScopes }),
361
+ ...(request.meetingsAsked ? { asked: true } : {}),
362
+ ...(request.exact ? { exact: true } : {}),
363
+ ...(request.timezone === undefined ? {} : { timezone: request.timezone }),
364
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
311
365
  });
366
+ for (const one of found.skipped)
367
+ skipped.push(one);
368
+ if (!found.read.length)
369
+ continue;
312
370
  hasMore ||= found.hasMore;
371
+ meetings = found.coverage;
313
372
  lists.push(found.items);
314
373
  for (const { provider, account } of found.read)
315
374
  accounts.push({ resource, provider, account });
@@ -328,9 +387,21 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
328
387
  finally {
329
388
  await embedders.close();
330
389
  }
331
- const ordered = oneList(lists, cosines);
390
+ let ordered = insidePeriodFirst(oneList(lists, cosines), period);
391
+ let harder;
392
+ if (request.harder) {
393
+ const asking = {
394
+ ...request.harder,
395
+ env: request.env ?? process.env,
396
+ now: request.now ?? Date.now(),
397
+ ...(command === undefined ? {} : { command }),
398
+ };
399
+ const done = await reorderHarder(request.text, ordered, { ...asking, laterPage: offset > 0 });
400
+ ordered = done.items;
401
+ harder = done.harder;
402
+ }
332
403
  const more = hasMore || ordered.length > window;
333
- const { backend: _backend, server: _server, ...local } = asked;
404
+ const { backend: _backend, server: _server, harder: _harder, ...local } = asked;
334
405
  const unmatched = [];
335
406
  if (!ordered.length && !offset && !discover)
336
407
  for (const word of strictWords(request.text)) {
@@ -353,8 +424,12 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
353
424
  ...(server === undefined ? {} : { server }),
354
425
  ...(coverage === undefined ? {} : { coverage }),
355
426
  ...(unmatched.length ? { unmatched } : {}),
427
+ ...(meetings === undefined ? {} : { meetings }),
428
+ ...(harder === undefined ? {} : { harder }),
356
429
  };
357
430
  };
431
+ /** Passages of one meeting share its `ref`, the reference evidence cites; each is still a hit of its own. */
432
+ const hitKey = (item) => item.kind === "meeting" ? `${item.ref}\u0000${item.scope}\u0000${item.id}` : item.ref;
358
433
  /**
359
434
  * Every source's hits as one list: each source's best hit first, then every other hit by cosine, then by its rank in
360
435
  * its source. Taking turns by rank (MEMO-37) gave each of two sources half of a ten-hit page however weak its hits;
@@ -366,10 +441,11 @@ const oneList = (lists, cosines) => {
366
441
  for (const list of lists) {
367
442
  let above = Number.NEGATIVE_INFINITY;
368
443
  list.forEach((item, rank) => {
444
+ const key = hitKey(item);
369
445
  above = cosines.get(item.ref) ?? above;
370
- const held = place.get(item.ref);
446
+ const held = place.get(key);
371
447
  if (!held || rank < held.rank)
372
- place.set(item.ref, { item, rank, cosine: above });
448
+ place.set(key, { item, rank, cosine: above });
373
449
  });
374
450
  }
375
451
  const head = (rank) => Math.min(rank, 1);
@@ -377,3 +453,21 @@ const oneList = (lists, cosines) => {
377
453
  .sort((a, b) => head(a.rank) - head(b.rank) || b.cosine - a.cosine || a.rank - b.rank)
378
454
  .map(({ item }) => item);
379
455
  };
456
+ const PERIOD_DEPTH = 100;
457
+ const PERIOD_BOOST = 0.5;
458
+ /**
459
+ * A hit dated inside the question's period gains 0.5 over its place, 1 - rank/100: by rank, because only some hits have
460
+ * a cosine to compare. One scale for every page, so paging past the first 100 never reorders what came before.
461
+ */
462
+ const insidePeriodFirst = (ordered, period) => {
463
+ if (!period)
464
+ return ordered;
465
+ const inside = ({ timestamp }) => {
466
+ const at = timestamp === null ? Number.NaN : Date.parse(timestamp);
467
+ return at >= period.from && at < period.to;
468
+ };
469
+ return ordered
470
+ .map((item, rank) => ({ item, score: 1 - rank / PERIOD_DEPTH + (inside(item) ? PERIOD_BOOST : 0) }))
471
+ .sort((a, b) => b.score - a.score)
472
+ .map(({ item }) => item);
473
+ };
@@ -0,0 +1,64 @@
1
+ import { type KeyringStore } from "@wirecat/cli-base";
2
+ import * as v from "valibot";
3
+ import { type ModelAdapter } from "../models/index.js";
4
+ import type { AppIdentity } from "../ports/app.js";
5
+ export declare const HARDER_PROVIDER = "anthropic";
6
+ export declare const DEFAULT_HARDER_MODEL = "claude-haiku-5-5";
7
+ export declare const HARDER_ENDPOINT = "https://api.anthropic.com";
8
+ /** The search lab's setup (cli-testing search-lab, "Haiku rerank"): the top 30, each cut to 400 characters. */
9
+ export declare const HARDER_CANDIDATES = 30;
10
+ export declare const HARDER_CHARS = 400;
11
+ declare const Setting: v.StrictObjectSchema<{
12
+ readonly provider: v.LiteralSchema<"anthropic", undefined>;
13
+ readonly model: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 200, undefined>]>;
14
+ /** When the owner agreed that a `--harder` search sends its question and hits; the setting exists only with it. */
15
+ readonly consented_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, undefined>]>;
16
+ }, undefined>;
17
+ export type HarderSetting = v.InferOutput<typeof Setting>;
18
+ /** The owner's consent, or `undefined`: no section means `--harder` sends nothing. */
19
+ export declare const readHarderSetting: (env: NodeJS.ProcessEnv) => HarderSetting | undefined;
20
+ export declare const writeHarderSetting: (env: NodeJS.ProcessEnv, setting: HarderSetting | undefined) => void;
21
+ export declare const HARDER_REASON_IDS: readonly ["harder.no-consent", "harder.no-key", "harder.bad-setting", "harder.later-page", "harder.too-few", "harder.timeout", "harder.key-rejected", "harder.unreachable", "harder.rate-limited", "harder.bad-reply", "harder.error"];
22
+ export type HarderReasonId = (typeof HARDER_REASON_IDS)[number];
23
+ /** What `--harder` did: `applied` only when the model's order replaced the plain one. */
24
+ export interface HarderResult {
25
+ applied: boolean;
26
+ provider: string;
27
+ model: string;
28
+ /** Hits sent to the model; 0 when nothing left this machine. */
29
+ sent: number;
30
+ cost_usd: number | null;
31
+ ms: number;
32
+ reason?: string;
33
+ reason_id?: HarderReasonId;
34
+ }
35
+ export interface HarderOptions {
36
+ /** The tool whose keyring entry holds the key; without it only the environment's key is read. */
37
+ app?: AppIdentity;
38
+ keyring?: KeyringStore;
39
+ /** Tests inject these; nothing in the suite reaches a provider. */
40
+ adapters?: Readonly<Record<string, ModelAdapter>>;
41
+ fetch?: typeof fetch;
42
+ key?: (provider: string) => string | undefined;
43
+ timeoutMs?: number;
44
+ }
45
+ export interface HarderHit {
46
+ title: string | null;
47
+ timestamp: string | null;
48
+ text: string;
49
+ }
50
+ /**
51
+ * `search all --harder`: a hosted model reads the question with the first 30 hits and puts the ones that answer it
52
+ * first. Any failure keeps the plain order and says why; it never fails the search. Without the owner's consent or a
53
+ * key nothing is sent.
54
+ */
55
+ export declare const reorderHarder: <T extends HarderHit>(question: string, hits: readonly T[], { env, now, command, laterPage, ...options }: HarderOptions & {
56
+ env: NodeJS.ProcessEnv;
57
+ now: number;
58
+ command?: string;
59
+ laterPage?: boolean;
60
+ }) => Promise<{
61
+ items: T[];
62
+ harder: HarderResult;
63
+ }>;
64
+ export {};
@@ -0,0 +1,194 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import * as v from "valibot";
3
+ import { modelGateway } from "../models/index.js";
4
+ import { readSharedSection, writeSharedSection } from "../store/shared-config.js";
5
+ import { keyLookup, keyVariable } from "./enrichment.js";
6
+ import { costOf, enrichmentSettingPath } from "./enrichment-setting.js";
7
+ const SECTION = "search_harder";
8
+ export const HARDER_PROVIDER = "anthropic";
9
+ export const DEFAULT_HARDER_MODEL = "claude-haiku-5-5";
10
+ export const HARDER_ENDPOINT = "https://api.anthropic.com";
11
+ /** The search lab's setup (cli-testing search-lab, "Haiku rerank"): the top 30, each cut to 400 characters. */
12
+ export const HARDER_CANDIDATES = 30;
13
+ export const HARDER_CHARS = 400;
14
+ const TIMEOUT_MS = 5_000;
15
+ const Setting = v.strictObject({
16
+ provider: v.literal(HARDER_PROVIDER),
17
+ model: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(200)),
18
+ /** When the owner agreed that a `--harder` search sends its question and hits; the setting exists only with it. */
19
+ consented_at: v.pipe(v.string(), v.isoTimestamp()),
20
+ });
21
+ /** The owner's consent, or `undefined`: no section means `--harder` sends nothing. */
22
+ export const readHarderSetting = (env) => {
23
+ const path = enrichmentSettingPath(env);
24
+ const section = readSharedSection(path, SECTION);
25
+ if (section === undefined || section === null)
26
+ return undefined;
27
+ const checked = v.safeParse(Setting, section);
28
+ if (!checked.success)
29
+ throw new CliError("configuration_error", `${path}: ${SECTION}.${v.getDotPath(checked.issues[0]) ?? "settings"} is invalid — ${checked.issues[0].message}`);
30
+ return checked.output;
31
+ };
32
+ export const writeHarderSetting = (env, setting) => writeSharedSection(enrichmentSettingPath(env), SECTION, setting === undefined ? undefined : v.parse(Setting, setting));
33
+ export const HARDER_REASON_IDS = [
34
+ "harder.no-consent",
35
+ "harder.no-key",
36
+ "harder.bad-setting",
37
+ "harder.later-page",
38
+ "harder.too-few",
39
+ "harder.timeout",
40
+ "harder.key-rejected",
41
+ "harder.unreachable",
42
+ "harder.rate-limited",
43
+ "harder.bad-reply",
44
+ "harder.error",
45
+ ];
46
+ // The search lab's prompt, word for word, except that the records travel as the gateway's untrusted data.
47
+ const PROMPT = "Today is {as_of}. A person searches their own archive of messages, mails, notes, calendar entries and phone " +
48
+ "records with the question below. Here are {n} candidate records, numbered, in the data.\n\n" +
49
+ "Question: {question}\n\n" +
50
+ "Which records help answer the question? List their numbers, most useful first, at most ten; an empty list if " +
51
+ "none does.";
52
+ const FORMAT = {
53
+ type: "json_schema",
54
+ schema: {
55
+ type: "object",
56
+ properties: { records: { type: "array", items: { type: "integer" } } },
57
+ required: ["records"],
58
+ additionalProperties: false,
59
+ },
60
+ };
61
+ const Reply = v.object({ records: v.array(v.pipe(v.number(), v.integer())) });
62
+ const recordLine = (hit, i) => `[${i}] (${hit.timestamp?.slice(0, 10) ?? "undated"}) ${`${hit.title ? `${hit.title}\n` : ""}${hit.text.slice(0, HARDER_CHARS)}`.replace(/\s*\n\s*/g, " ")}`;
63
+ const REASON_TEXT = {
64
+ "harder.no-consent": "the owner has not agreed to send searches to a hosted model",
65
+ "harder.no-key": "no Anthropic key",
66
+ "harder.bad-setting": "the search_harder setting cannot be read; nothing was sent",
67
+ "harder.later-page": "--harder reorders the first page only; nothing was sent",
68
+ "harder.too-few": "fewer than two hits to reorder; nothing was sent",
69
+ "harder.timeout": `the model did not answer within ${TIMEOUT_MS / 1000} s`,
70
+ "harder.key-rejected": "the provider refused the key",
71
+ "harder.unreachable": "the provider could not be reached",
72
+ "harder.rate-limited": "the provider's rate limit was reached",
73
+ "harder.bad-reply": "the model's answer could not be read",
74
+ "harder.error": "the provider failed",
75
+ };
76
+ const reasonOf = (error, timedOut) => {
77
+ if (timedOut)
78
+ return "harder.timeout";
79
+ if (!(error instanceof CliError))
80
+ return "harder.bad-reply";
81
+ if (error.details.reason === "model.key-rejected")
82
+ return "harder.key-rejected";
83
+ if (error.details.reason === "model.unreachable")
84
+ return "harder.unreachable";
85
+ if (error.code === "rate_limited")
86
+ return "harder.rate-limited";
87
+ return "harder.error";
88
+ };
89
+ /**
90
+ * `search all --harder`: a hosted model reads the question with the first 30 hits and puts the ones that answer it
91
+ * first. Any failure keeps the plain order and says why; it never fails the search. Without the owner's consent or a
92
+ * key nothing is sent.
93
+ */
94
+ export const reorderHarder = async (question, hits, { env, now, command, laterPage, ...options }) => {
95
+ const started = Date.now();
96
+ let setting;
97
+ let unreadable;
98
+ try {
99
+ setting = readHarderSetting(env);
100
+ }
101
+ catch (error) {
102
+ unreadable = error instanceof CliError ? error.message : REASON_TEXT["harder.bad-setting"];
103
+ }
104
+ const model = setting?.model ?? DEFAULT_HARDER_MODEL;
105
+ const plain = (reason_id, extra = {}, reason = REASON_TEXT[reason_id]) => ({
106
+ items: [...hits],
107
+ harder: {
108
+ applied: false,
109
+ provider: HARDER_PROVIDER,
110
+ model,
111
+ sent: 0,
112
+ cost_usd: 0,
113
+ ms: Date.now() - started,
114
+ ...extra,
115
+ reason,
116
+ reason_id,
117
+ },
118
+ });
119
+ if (laterPage)
120
+ return plain("harder.later-page");
121
+ if (unreadable !== undefined)
122
+ return plain("harder.bad-setting", {}, `${unreadable}; nothing was sent`);
123
+ const tool = command ?? "memo";
124
+ if (!setting)
125
+ return plain("harder.no-consent", {}, `${REASON_TEXT["harder.no-consent"]}: \`${tool} models search-consents set anthropic --yes\`; nothing was sent`);
126
+ let apiKey;
127
+ try {
128
+ apiKey = keyLookup({ env, ...options }, { provider: HARDER_PROVIDER })?.key;
129
+ }
130
+ catch {
131
+ return plain("harder.error", {}, "the Anthropic key could not be read; nothing was sent");
132
+ }
133
+ if (apiKey === undefined)
134
+ return plain("harder.no-key", {}, `no Anthropic key: \`${tool} models keys set anthropic\` or set ${keyVariable(HARDER_PROVIDER)}; nothing was sent`);
135
+ const candidates = hits.slice(0, HARDER_CANDIDATES);
136
+ if (candidates.length < 2)
137
+ return plain("harder.too-few");
138
+ const limit = new AbortController();
139
+ const timer = setTimeout(() => limit.abort(), options.timeoutMs ?? TIMEOUT_MS);
140
+ const gateway = modelGateway({
141
+ resolve: () => ({ provider: HARDER_PROVIDER, model: setting.model, baseUrl: HARDER_ENDPOINT }),
142
+ consent: (_request, chosen) => chosen.provider === HARDER_PROVIDER && chosen.baseUrl === HARDER_ENDPOINT,
143
+ key: () => apiKey,
144
+ signal: limit.signal,
145
+ ...(options.adapters ? { adapters: options.adapters } : {}),
146
+ ...(options.fetch ? { fetch: options.fetch } : {}),
147
+ });
148
+ const sent = { sent: candidates.length };
149
+ try {
150
+ const answer = await gateway.complete({
151
+ purpose: "search-harder",
152
+ prompt: PROMPT.replace("{as_of}", new Date(now).toISOString().slice(0, 10))
153
+ .replace("{n}", String(candidates.length))
154
+ .replace("{question}", question),
155
+ data: candidates.map(recordLine).join("\n"),
156
+ maxTokens: 300,
157
+ options: { thinking: { type: "disabled" }, output_config: { effort: "low", format: FORMAT } },
158
+ });
159
+ const cost = costOf(answer.usage ?? { input: answer.tokens, output: 0 }, {
160
+ provider: HARDER_PROVIDER,
161
+ model: setting.model,
162
+ });
163
+ let picked;
164
+ try {
165
+ picked = v.parse(Reply, JSON.parse(answer.text)).records;
166
+ }
167
+ catch {
168
+ return plain("harder.bad-reply", { ...sent, cost_usd: cost });
169
+ }
170
+ const first = [...new Set(picked.filter((i) => i >= 0 && i < candidates.length))];
171
+ const chosen = new Set(first);
172
+ return {
173
+ items: [
174
+ ...first.map((i) => candidates[i]),
175
+ ...candidates.filter((_, i) => !chosen.has(i)),
176
+ ...hits.slice(HARDER_CANDIDATES),
177
+ ],
178
+ harder: {
179
+ applied: true,
180
+ provider: HARDER_PROVIDER,
181
+ model: setting.model,
182
+ ...sent,
183
+ cost_usd: cost,
184
+ ms: Date.now() - started,
185
+ },
186
+ };
187
+ }
188
+ catch (error) {
189
+ return plain(reasonOf(error, limit.signal.aborted), { ...sent, cost_usd: null });
190
+ }
191
+ finally {
192
+ clearTimeout(timer);
193
+ }
194
+ };
@@ -1,16 +1,23 @@
1
- import type { AppIdentity } from "../ports/app.js";
2
- import { type ListContext, type SkippedSource } from "../search/account-list.js";
1
+ import { type AppIdentity } from "../ports/app.js";
2
+ import { type SkippedSource } from "../search/account-list.js";
3
+ import { type GroupContext } from "../search/groups.js";
3
4
  import type { AccountKey, MessageStore, StoredAccount } from "../store/store.js";
4
5
  export type SearchKind = "messages" | "mail";
5
6
  export declare const NO_MAIL = "no_mail";
6
7
  export declare const MAIL = "email";
7
- /** What a `--source` list is resolved against: the store's accounts, groups and profiles, and the app running. */
8
- export declare const listContextOf: (store: MessageStore, account: AccountKey, app: AppIdentity | undefined, stored?: StoredAccount[]) => Promise<ListContext>;
8
+ /** The group `<PREFIX>_GROUP_LOCK` pins this process to; `all`, every account, locks nothing. */
9
+ export declare const groupLockOf: (app: AppIdentity | undefined, env: NodeJS.ProcessEnv | undefined) => string | undefined;
10
+ /**
11
+ * What a `--source` list is resolved against: the store's accounts, profiles and groups — the saved ones and `all`
12
+ * (WC-ACCT-13) — and the app running. Under a group lock in the run's `env` it holds only that group's
13
+ * accounts, so a reader that never scoped its run to the group still cannot name an account outside it.
14
+ */
15
+ export declare const listContextOf: (store: MessageStore, account: AccountKey, app: AppIdentity | undefined, stored?: StoredAccount[], env?: NodeJS.ProcessEnv) => Promise<GroupContext>;
9
16
  /**
10
17
  * `--source` as a list of accounts and groups: `undefined` when it is a bare word like `all` or `telegram`. The
11
18
  * accounts are those of `kind` the list names; an entry naming none of them is in `skipped`.
12
19
  */
13
- export declare const listedAccounts: (store: MessageStore, account: AccountKey, source: string | undefined, app: AppIdentity | undefined, kind?: SearchKind) => Promise<{
20
+ export declare const listedAccounts: (store: MessageStore, account: AccountKey, source: string | undefined, app: AppIdentity | undefined, kind?: SearchKind, env?: NodeJS.ProcessEnv) => Promise<{
14
21
  accounts: AccountKey[];
15
22
  skipped: SkippedSource[];
16
23
  } | undefined>;