@wirecat/cli-core 0.619.0 → 0.621.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 (94) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/cli/search-all.d.ts +1 -1
  4. package/dist/calendar/cli/search-all.js +9 -10
  5. package/dist/calendar/prepare.js +1 -0
  6. package/dist/cli/base-stages-command.d.ts +1 -1
  7. package/dist/cli/base-stages-command.js +1 -1
  8. package/dist/cli/bot/buttons.d.ts +3 -0
  9. package/dist/cli/bot/buttons.js +24 -0
  10. package/dist/cli/bot/messages.js +14 -1
  11. package/dist/cli/bot/port.d.ts +8 -0
  12. package/dist/cli/contract-templates.js +31 -2
  13. package/dist/cli/messenger/contacts-command.js +2 -1
  14. package/dist/cli/messenger/conversations-command.js +2 -1
  15. package/dist/cli/messenger/message-items.js +1 -1
  16. package/dist/cli/messenger/search-answers.d.ts +5 -5
  17. package/dist/cli/messenger/search-answers.js +9 -20
  18. package/dist/cli/messenger/search-command.d.ts +2 -2
  19. package/dist/cli/messenger/search-command.js +8 -18
  20. package/dist/cli/model-catalogue-command.js +3 -1
  21. package/dist/cli/search-harder-consents-command.d.ts +21 -0
  22. package/dist/cli/search-harder-consents-command.js +112 -0
  23. package/dist/cli/steps.js +0 -6
  24. package/dist/cli/templates-command.js +4 -4
  25. package/dist/crm/cli/index.js +2 -2
  26. package/dist/crm/cli/search-all.js +7 -6
  27. package/dist/crm/source.d.ts +8 -0
  28. package/dist/crm/sync.d.ts +1 -1
  29. package/dist/crm/sync.js +13 -1
  30. package/dist/domain/models.d.ts +2 -0
  31. package/dist/domain/relations.d.ts +1 -0
  32. package/dist/domain/relations.js +5 -1
  33. package/dist/entities/contact-context.d.ts +3 -0
  34. package/dist/entities/contact-context.js +4 -0
  35. package/dist/entities/hit.d.ts +9 -2
  36. package/dist/entities/hit.js +6 -2
  37. package/dist/entities/index.d.ts +9 -1
  38. package/dist/errors/reasons.js +3 -0
  39. package/dist/meetings/hit-query.d.ts +1 -1
  40. package/dist/meetings/hit-query.js +2 -2
  41. package/dist/meetings/index.d.ts +1 -0
  42. package/dist/meetings/index.js +1 -0
  43. package/dist/meetings/store.d.ts +4 -0
  44. package/dist/meetings/store.js +2 -1
  45. package/dist/models/anthropic.js +5 -0
  46. package/dist/search/question-period.d.ts +10 -0
  47. package/dist/search/question-period.js +133 -0
  48. package/dist/sends/buttons.d.ts +2 -0
  49. package/dist/sends/buttons.js +6 -1
  50. package/dist/services/enrichment-setting.d.ts +6 -0
  51. package/dist/services/enrichment-setting.js +5 -1
  52. package/dist/services/enrichment.d.ts +5 -0
  53. package/dist/services/enrichment.js +1 -1
  54. package/dist/services/index.d.ts +4 -2
  55. package/dist/services/index.js +3 -1
  56. package/dist/services/messages.d.ts +1 -4
  57. package/dist/services/messages.js +0 -2
  58. package/dist/services/metadata.d.ts +1 -1
  59. package/dist/services/person-context.d.ts +3 -1
  60. package/dist/services/person-context.js +21 -8
  61. package/dist/services/person-preparation.d.ts +5 -1
  62. package/dist/services/person-preparation.js +10 -3
  63. package/dist/services/person-timeline.d.ts +6 -1
  64. package/dist/services/person-timeline.js +10 -2
  65. package/dist/services/search-all-deprecated.d.ts +40 -0
  66. package/dist/services/search-all-deprecated.js +10 -0
  67. package/dist/services/search-all-meetings.d.ts +50 -52
  68. package/dist/services/search-all-meetings.js +265 -272
  69. package/dist/services/search-all.d.ts +34 -6
  70. package/dist/services/search-all.js +119 -24
  71. package/dist/services/search-harder.d.ts +90 -0
  72. package/dist/services/search-harder.js +264 -0
  73. package/dist/store/chats.d.ts +3 -1
  74. package/dist/store/chats.js +6 -0
  75. package/dist/store/people.d.ts +6 -2
  76. package/dist/store/sqlite/added-sources.d.ts +15 -3
  77. package/dist/store/sqlite/added-sources.js +26 -5
  78. package/dist/store/sqlite/chats.d.ts +2 -0
  79. package/dist/store/sqlite/chats.js +6 -0
  80. package/dist/store/sqlite/involvements.d.ts +1 -1
  81. package/dist/store/sqlite/involvements.js +4 -2
  82. package/dist/store/sqlite/meeting-hit-query.d.ts +5 -0
  83. package/dist/store/sqlite/meeting-hit-query.js +33 -0
  84. package/dist/store/sqlite/meeting-hit-search.js +10 -8
  85. package/dist/store/sqlite/meetings.js +1 -1
  86. package/dist/store/sqlite/notes.d.ts +7 -0
  87. package/dist/store/sqlite/notes.js +23 -7
  88. package/dist/store/sqlite/person-preparation.d.ts +7 -3
  89. package/dist/store/sqlite/person-preparation.js +20 -6
  90. package/dist/store/sqlite/relation-list.js +4 -2
  91. package/dist/store/sqlite/reported-relations.d.ts +0 -1
  92. package/dist/store/sqlite/reported-relations.js +1 -4
  93. package/package.json +1 -1
  94. package/parity.json +26 -12
@@ -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,22 @@ 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
+ // The model reads the question as typed, not escaped for the query parser.
400
+ const done = await reorderHarder(asked.text, ordered, { ...asking, laterPage: offset > 0 });
401
+ ordered = done.items;
402
+ harder = done.harder;
403
+ }
332
404
  const more = hasMore || ordered.length > window;
333
- const { backend: _backend, server: _server, ...local } = asked;
405
+ const { backend: _backend, server: _server, harder: _harder, ...local } = asked;
334
406
  const unmatched = [];
335
407
  if (!ordered.length && !offset && !discover)
336
408
  for (const word of strictWords(request.text)) {
@@ -353,8 +425,12 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
353
425
  ...(server === undefined ? {} : { server }),
354
426
  ...(coverage === undefined ? {} : { coverage }),
355
427
  ...(unmatched.length ? { unmatched } : {}),
428
+ ...(meetings === undefined ? {} : { meetings }),
429
+ ...(harder === undefined ? {} : { harder }),
356
430
  };
357
431
  };
432
+ /** Passages of one meeting share its `ref`, the reference evidence cites; each is still a hit of its own. */
433
+ const hitKey = (item) => item.kind === "meeting" ? `${item.ref}\u0000${item.scope}\u0000${item.id}` : item.ref;
358
434
  /**
359
435
  * 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
436
  * 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 +442,11 @@ const oneList = (lists, cosines) => {
366
442
  for (const list of lists) {
367
443
  let above = Number.NEGATIVE_INFINITY;
368
444
  list.forEach((item, rank) => {
445
+ const key = hitKey(item);
369
446
  above = cosines.get(item.ref) ?? above;
370
- const held = place.get(item.ref);
447
+ const held = place.get(key);
371
448
  if (!held || rank < held.rank)
372
- place.set(item.ref, { item, rank, cosine: above });
449
+ place.set(key, { item, rank, cosine: above });
373
450
  });
374
451
  }
375
452
  const head = (rank) => Math.min(rank, 1);
@@ -377,3 +454,21 @@ const oneList = (lists, cosines) => {
377
454
  .sort((a, b) => head(a.rank) - head(b.rank) || b.cosine - a.cosine || a.rank - b.rank)
378
455
  .map(({ item }) => item);
379
456
  };
457
+ const PERIOD_DEPTH = 100;
458
+ const PERIOD_BOOST = 0.5;
459
+ /**
460
+ * A hit dated inside the question's period gains 0.5 over its place, 1 - rank/100: by rank, because only some hits have
461
+ * a cosine to compare. One scale for every page, so paging past the first 100 never reorders what came before.
462
+ */
463
+ const insidePeriodFirst = (ordered, period) => {
464
+ if (!period)
465
+ return ordered;
466
+ const inside = ({ timestamp }) => {
467
+ const at = timestamp === null ? Number.NaN : Date.parse(timestamp);
468
+ return at >= period.from && at < period.to;
469
+ };
470
+ return ordered
471
+ .map((item, rank) => ({ item, score: 1 - rank / PERIOD_DEPTH + (inside(item) ? PERIOD_BOOST : 0) }))
472
+ .sort((a, b) => b.score - a.score)
473
+ .map(({ item }) => item);
474
+ };
@@ -0,0 +1,90 @@
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
+ import { type EnrichmentProvider } from "./enrichment-setting.js";
6
+ /**
7
+ * Each provider's model when the owner names none: small and fast for a short answer. gpt-4o-mini, not a cheaper
8
+ * reasoning model, because the OpenAI adapter cannot turn reasoning down (pricing read 2026-11-09).
9
+ */
10
+ export declare const HARDER_MODELS: Readonly<Record<EnrichmentProvider, string>>;
11
+ /** The search lab's setup (cli-testing search-lab, "Haiku rerank"): the top 30, each cut to 400 characters. */
12
+ export declare const HARDER_CANDIDATES = 30;
13
+ export declare const HARDER_CHARS = 400;
14
+ declare const Setting: v.StrictObjectSchema<{
15
+ readonly provider: v.PicklistSchema<readonly ["openai", "anthropic"], undefined>;
16
+ readonly model: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 200, undefined>]>;
17
+ readonly base_url: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "use an HTTP/S endpoint without credentials, query or fragment">]>, undefined>;
18
+ /** When the owner agreed that a `--harder` search sends its question and hits; the setting exists only with it. */
19
+ readonly consented_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, undefined>]>;
20
+ }, undefined>;
21
+ export type HarderSetting = v.InferOutput<typeof Setting>;
22
+ /** The owner's consent, or `undefined`: no section means `--harder` sends nothing. */
23
+ export declare const readHarderSetting: (env: NodeJS.ProcessEnv) => HarderSetting | undefined;
24
+ export declare const writeHarderSetting: (env: NodeJS.ProcessEnv, setting: HarderSetting | undefined) => void;
25
+ 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"];
26
+ export type HarderReasonId = (typeof HARDER_REASON_IDS)[number];
27
+ /** What `--harder` did: `applied` only when the model's order replaced the plain one. */
28
+ export interface HarderResult {
29
+ applied: boolean;
30
+ provider: string;
31
+ model: string;
32
+ /** The API the question went to, or would have. */
33
+ endpoint: string;
34
+ /** Hits sent to the model; 0 when nothing left this machine. */
35
+ sent: number;
36
+ cost_usd: number | null;
37
+ ms: number;
38
+ reason?: string;
39
+ reason_id?: HarderReasonId;
40
+ }
41
+ export interface HarderOptions {
42
+ /** The tool whose keyring entry holds the key; without it only the environment's key is read. */
43
+ app?: AppIdentity;
44
+ keyring?: KeyringStore;
45
+ /** Tests inject these; nothing in the suite reaches a provider. */
46
+ adapters?: Readonly<Record<string, ModelAdapter>>;
47
+ fetch?: typeof fetch;
48
+ key?: (provider: string) => string | undefined;
49
+ timeoutMs?: number;
50
+ }
51
+ export interface HarderHit {
52
+ title: string | null;
53
+ timestamp: string | null;
54
+ text: string;
55
+ }
56
+ type Asking = HarderOptions & {
57
+ env: NodeJS.ProcessEnv;
58
+ now: number;
59
+ command?: string;
60
+ };
61
+ /** The consent and key a call needs, or why nothing may be sent. */
62
+ export type HarderAccess = {
63
+ ready: true;
64
+ provider: EnrichmentProvider;
65
+ model: string;
66
+ endpoint: string;
67
+ custom: boolean;
68
+ key?: string;
69
+ } | {
70
+ ready: false;
71
+ provider: string;
72
+ model: string;
73
+ endpoint: string;
74
+ reason_id: HarderReasonId;
75
+ reason: string;
76
+ };
77
+ export declare const harderAccess: ({ env, command, ...options }: Asking) => HarderAccess;
78
+ /**
79
+ * `search all --harder`: a hosted model reads the question with the first 30 hits and puts the ones that answer it
80
+ * first. Any failure keeps the plain order and says why; it never fails the search. Without the owner's consent or a
81
+ * key nothing is sent.
82
+ */
83
+ export declare const reorderHarder: <T extends HarderHit>(question: string, hits: readonly T[], { laterPage, access: given, ...asking }: Asking & {
84
+ laterPage?: boolean;
85
+ access?: HarderAccess;
86
+ }) => Promise<{
87
+ items: T[];
88
+ harder: HarderResult;
89
+ }>;
90
+ export {};