@wirecat/wirecat 0.0.0-stage → 1.1.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 (230) hide show
  1. package/LICENSE +204 -0
  2. package/README.md +399 -2
  3. package/THIRD_PARTY_NOTICES +2 -0
  4. package/contracts/wirecat.json +4612 -0
  5. package/dist/actions/actions.js +269 -0
  6. package/dist/actions/command.js +102 -0
  7. package/dist/agents/command.js +17 -0
  8. package/dist/agents/log.js +23 -0
  9. package/dist/answer.js +100 -0
  10. package/dist/answers/command.js +128 -0
  11. package/dist/app.js +15 -0
  12. package/dist/author.js +109 -0
  13. package/dist/bin/wcat-wirecat.js +40 -0
  14. package/dist/bots/command.js +175 -0
  15. package/dist/bundle/auto-O24ISPOI.js +43 -0
  16. package/dist/bundle/chunk-2A3YPENI.js +31 -0
  17. package/dist/bundle/chunk-6BDIFKF5.js +222 -0
  18. package/dist/bundle/chunk-7O7XM37N.js +2 -0
  19. package/dist/bundle/chunk-AYHZY24E.js +120 -0
  20. package/dist/bundle/chunk-CKBTMZUX.js +72 -0
  21. package/dist/bundle/chunk-FGXUH3XL.js +416 -0
  22. package/dist/bundle/chunk-I5JQBRRC.js +807 -0
  23. package/dist/bundle/chunk-RKVAWMZT.js +38 -0
  24. package/dist/bundle/chunk-SCDNOUUR.js +395 -0
  25. package/dist/bundle/chunk-T7TG4JKR.js +312 -0
  26. package/dist/bundle/chunk-XBUCXQKT.js +51 -0
  27. package/dist/bundle/entry-EW5A7FYV.js +64 -0
  28. package/dist/bundle/failure-HMELJ3K5.js +19 -0
  29. package/dist/bundle/from-memo-F7NTUXAR.js +314 -0
  30. package/dist/bundle/program-7XWGFN4H.js +14994 -0
  31. package/dist/bundle/server-T7RVBNRW.js +303 -0
  32. package/dist/bundle/update-JZDS7B6L.js +22 -0
  33. package/dist/bundle/wcat-wirecat.js +83 -0
  34. package/dist/config-command.js +39 -0
  35. package/dist/config-issues.js +15 -0
  36. package/dist/config.js +187 -0
  37. package/dist/context/command.js +162 -0
  38. package/dist/context/context.js +197 -0
  39. package/dist/contract-overrides/commands.js +81 -0
  40. package/dist/contract-overrides/mcp.js +241 -0
  41. package/dist/contract-overrides/meetings.js +344 -0
  42. package/dist/contract-overrides/search.js +508 -0
  43. package/dist/contract-overrides/skill.js +85 -0
  44. package/dist/contract-overrides.js +7 -0
  45. package/dist/digest/backfill.js +175 -0
  46. package/dist/digest/brief.js +189 -0
  47. package/dist/digest/catch-up-record.js +30 -0
  48. package/dist/digest/catch-up.js +86 -0
  49. package/dist/digest/command.js +110 -0
  50. package/dist/digest/digest-commands.js +327 -0
  51. package/dist/digest/digest.js +560 -0
  52. package/dist/digest/digests.js +213 -0
  53. package/dist/digest/history.js +202 -0
  54. package/dist/digest/input.js +30 -0
  55. package/dist/digest/known.js +28 -0
  56. package/dist/digest/sources.js +155 -0
  57. package/dist/digest/sync-health.js +158 -0
  58. package/dist/digest/task-proposals.js +67 -0
  59. package/dist/digest/tasks.js +145 -0
  60. package/dist/digest/text.js +49 -0
  61. package/dist/discovery/command.js +107 -0
  62. package/dist/doctor/command.js +167 -0
  63. package/dist/documents/command.js +107 -0
  64. package/dist/domain-lists/command.js +13 -0
  65. package/dist/events/command.js +35 -0
  66. package/dist/events/events.js +196 -0
  67. package/dist/examples.js +609 -0
  68. package/dist/facts/command.js +100 -0
  69. package/dist/facts/fact.js +54 -0
  70. package/dist/facts/facts.js +15 -0
  71. package/dist/failure.js +58 -0
  72. package/dist/finance/command.js +121 -0
  73. package/dist/finance/contracts-command.js +109 -0
  74. package/dist/finance/deal-text.js +34 -0
  75. package/dist/finance/deals-command.js +346 -0
  76. package/dist/finance/finance.js +129 -0
  77. package/dist/finance/lines-command.js +70 -0
  78. package/dist/finance/orders-command.js +94 -0
  79. package/dist/finance/products-command.js +98 -0
  80. package/dist/finance/subscriptions-command.js +152 -0
  81. package/dist/finance/transactions-command.js +136 -0
  82. package/dist/finance/wallets-command.js +105 -0
  83. package/dist/finance/written.js +36 -0
  84. package/dist/findings/command.js +102 -0
  85. package/dist/findings-input.js +23 -0
  86. package/dist/identity.js +20 -0
  87. package/dist/install/postinstall.js +47 -0
  88. package/dist/json-fields.js +48 -0
  89. package/dist/knowledge/business-text.js +19 -0
  90. package/dist/knowledge/command.js +435 -0
  91. package/dist/knowledge/document-context.js +33 -0
  92. package/dist/knowledge/key-documents.js +120 -0
  93. package/dist/knowledge/list-queries.js +20 -0
  94. package/dist/knowledge/meeting-projects-command.js +61 -0
  95. package/dist/knowledge/messenger-sync.js +253 -0
  96. package/dist/knowledge/money-text.js +16 -0
  97. package/dist/knowledge/notes-about.js +81 -0
  98. package/dist/knowledge/organization-delete-command.js +44 -0
  99. package/dist/knowledge/organization-text.js +27 -0
  100. package/dist/knowledge/project-actions-command.js +130 -0
  101. package/dist/knowledge/project-actions.js +104 -0
  102. package/dist/knowledge/project-activity-command.js +70 -0
  103. package/dist/knowledge/project-context.js +101 -0
  104. package/dist/knowledge/project-findings.js +41 -0
  105. package/dist/knowledge/project-gather-command.js +100 -0
  106. package/dist/knowledge/project-status-command.js +129 -0
  107. package/dist/knowledge/project-transfer-command.js +58 -0
  108. package/dist/knowledge/project-transfer.js +107 -0
  109. package/dist/knowledge/relationships-scan.js +116 -0
  110. package/dist/knowledge/relationships.js +115 -0
  111. package/dist/knowledge/roles-command.js +67 -0
  112. package/dist/mail/command.js +20 -0
  113. package/dist/mail/findings-command.js +143 -0
  114. package/dist/mail/findings-duplicates.js +159 -0
  115. package/dist/mail/messages-command.js +77 -0
  116. package/dist/mail/review-command.js +59 -0
  117. package/dist/mail/subscriptions-command.js +84 -0
  118. package/dist/mcp/catalogue.js +159 -0
  119. package/dist/mcp/command.js +125 -0
  120. package/dist/mcp/granted.js +18 -0
  121. package/dist/mcp/permissions.js +61 -0
  122. package/dist/mcp/server.js +128 -0
  123. package/dist/meetings/command.js +31 -0
  124. package/dist/meetings/list-command.js +59 -0
  125. package/dist/meetings/preparation-command.js +42 -0
  126. package/dist/meetings/preparation-text.js +44 -0
  127. package/dist/meetings/preparation.js +50 -0
  128. package/dist/meetings/read.js +32 -0
  129. package/dist/memories/command.js +105 -0
  130. package/dist/memories/memories.js +17 -0
  131. package/dist/memories/memory.js +89 -0
  132. package/dist/memories/sources.js +111 -0
  133. package/dist/mentions/command.js +91 -0
  134. package/dist/migrate/check.js +48 -0
  135. package/dist/migrate/from-memo.js +345 -0
  136. package/dist/migrate/skill.js +35 -0
  137. package/dist/models/command.js +19 -0
  138. package/dist/options.js +35 -0
  139. package/dist/output.js +17 -0
  140. package/dist/page.js +14 -0
  141. package/dist/people/command.js +144 -0
  142. package/dist/people/delete-command.js +53 -0
  143. package/dist/people/doubts-command.js +81 -0
  144. package/dist/people/identities-command.js +188 -0
  145. package/dist/people/identity.js +42 -0
  146. package/dist/people/owner.js +14 -0
  147. package/dist/people/proposal-rows.js +70 -0
  148. package/dist/people/proposals-command.js +248 -0
  149. package/dist/people/review-context.js +108 -0
  150. package/dist/people/subject.js +19 -0
  151. package/dist/program.js +875 -0
  152. package/dist/read-only.js +51 -0
  153. package/dist/reasons.js +368 -0
  154. package/dist/records/import.js +135 -0
  155. package/dist/records/input.js +210 -0
  156. package/dist/records/mapping.js +80 -0
  157. package/dist/records/record-commands.js +125 -0
  158. package/dist/records/sources.js +73 -0
  159. package/dist/refs.js +28 -0
  160. package/dist/review/command.js +171 -0
  161. package/dist/review/kinds.js +44 -0
  162. package/dist/review/review.js +299 -0
  163. package/dist/review/status.js +93 -0
  164. package/dist/rows.js +219 -0
  165. package/dist/run/auto.js +237 -0
  166. package/dist/run/entry.js +62 -0
  167. package/dist/run/files.js +51 -0
  168. package/dist/run/import.js +253 -0
  169. package/dist/run/lock.js +20 -0
  170. package/dist/save-help.js +3 -0
  171. package/dist/schedule/command.js +58 -0
  172. package/dist/schedule/mail-triage-input.js +152 -0
  173. package/dist/schedule/task-triage-input.js +152 -0
  174. package/dist/search/answers.js +176 -0
  175. package/dist/search/command.js +257 -0
  176. package/dist/search/denied.js +9 -0
  177. package/dist/search/embed.js +126 -0
  178. package/dist/search/hits.js +4 -0
  179. package/dist/search/lane-gates.js +76 -0
  180. package/dist/search/notes-text.js +18 -0
  181. package/dist/search/people.js +88 -0
  182. package/dist/search/search.js +306 -0
  183. package/dist/show/command.js +179 -0
  184. package/dist/store/crm-viewer.js +102 -0
  185. package/dist/store/group.js +112 -0
  186. package/dist/store/groups-command.js +136 -0
  187. package/dist/store/guard.js +94 -0
  188. package/dist/store/held.js +21 -0
  189. package/dist/store/info-command.js +37 -0
  190. package/dist/store/scope.js +53 -0
  191. package/dist/store/source-list.js +222 -0
  192. package/dist/store/source-target.js +28 -0
  193. package/dist/tags/command.js +176 -0
  194. package/dist/tasks/command.js +174 -0
  195. package/dist/tasks/context.js +74 -0
  196. package/dist/tasks/list.js +199 -0
  197. package/dist/tasks/proposal-duplicates.js +70 -0
  198. package/dist/tasks/relations-command.js +28 -0
  199. package/dist/tasks/shared.js +105 -0
  200. package/dist/tasks/tasks.js +197 -0
  201. package/dist/templates/command.js +18 -0
  202. package/dist/terminal.js +23 -0
  203. package/dist/update.js +35 -0
  204. package/dist/version.js +2 -0
  205. package/dist/vocabulary/command.js +103 -0
  206. package/dist/vocabulary/inspect.js +23 -0
  207. package/dist/vocabulary/inspection.js +18 -0
  208. package/dist/vocabulary/list.js +18 -0
  209. package/dist/vocabulary/project.js +19 -0
  210. package/dist/wcat.js +3 -0
  211. package/install/postinstall.mjs +9 -0
  212. package/package.json +89 -4
  213. package/scenarios/decision-trail.md +21 -0
  214. package/scenarios/person-brief.md +35 -0
  215. package/scenarios/prepare-meeting.md +17 -0
  216. package/scenarios/project-state.md +26 -0
  217. package/scenarios/set-up.md +18 -0
  218. package/scenarios/start-the-day.md +19 -0
  219. package/skills/mail-triage/SKILL.md +208 -0
  220. package/skills/morning-digest/SKILL.md +147 -0
  221. package/skills/task-triage/SKILL.md +79 -0
  222. package/skills/wcat/SKILL.md +65 -0
  223. package/skills/wcat/topics/mail.md +32 -0
  224. package/skills/wcat/topics/mcp.md +22 -0
  225. package/skills/wcat/topics/meetings.md +37 -0
  226. package/skills/wcat/topics/money.md +52 -0
  227. package/skills/wcat/topics/projects.md +54 -0
  228. package/skills/wcat/topics/proposals.md +113 -0
  229. package/skills/wcat/topics/search.md +85 -0
  230. package/skills/wcat/topics/vocabulary.md +8 -0
@@ -0,0 +1,18 @@
1
+ import { shownOf } from "@wirecat/cli-core";
2
+ export { searchNotes, } from "@wirecat/cli-core";
3
+ export const searchText = (result, offset = 0) => [
4
+ ...(result.items.length === 0
5
+ ? [`No note holds "${result.query}". Run wcat sync --only notes if notes changed.`]
6
+ : []),
7
+ ...result.items.map((hit) => `${"key" in hit ? "key " : ""}${hit.path ?? hit.ref}${hit.found_by.length === 1 && hit.found_by[0] === "meaning" ? " (by meaning)" : ""}\n ${hit.excerpt}`),
8
+ ...[shownOf(result.items.length, offset, result.total)].filter((line) => line !== undefined),
9
+ ...(result.hasMore ? ["More notes match; raise --limit or ask for --page with the next number."] : []),
10
+ ...(result.linked.length === 0
11
+ ? []
12
+ : [
13
+ "",
14
+ "Linked from these notes",
15
+ ...result.linked.map(({ ref, name, notes }) => ` ${name ?? ref} ${ref ?? "(nobody by that name yet)"} (${notes})`),
16
+ ]),
17
+ ].join("\n");
18
+ //# sourceMappingURL=notes-text.js.map
@@ -0,0 +1,88 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { formatReference, isFolderProvider, } from "@wirecat/cli-core";
3
+ import { listAnswer } from "../answer.js";
4
+ import { scopedAccounts } from "../store/group.js";
5
+ import { accountsOf } from "../store/source-list.js";
6
+ /** Notes folders hold no people; Drive's account does, its files' owners and editors. */
7
+ const holdsNoPeople = (provider) => provider === "notes" || isFolderProvider(provider);
8
+ /** Case, accents, ё and emoji variation marks fold away; SQLite's lower() folds ASCII only, so this runs here. */
9
+ export const fold = (text) => text.normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase();
10
+ const scopeOf = async (store, env, source) => {
11
+ const keys = source === undefined ? await scopedAccounts(store, env) : await accountsOf(store, env, source);
12
+ const held = keys.filter((key) => !holdsNoPeople(key.provider));
13
+ if (source !== undefined && held.length === 0)
14
+ throw new CliError("validation_error", `${source} names no messenger, mail or meeting account that holds people`, {
15
+ param: "source",
16
+ });
17
+ return held;
18
+ };
19
+ export const searchPeople = async (store, env, words, { limit, source }) => {
20
+ const wanted = words.flatMap((word) => fold(word).split(/\s+/)).filter(Boolean);
21
+ if (wanted.length === 0)
22
+ throw new CliError("validation_error", "give a part of the name to find");
23
+ const accounts = await scopeOf(store, env, source);
24
+ const hits = new Map();
25
+ const record = new Map();
26
+ for (const key of accounts) {
27
+ for (const contact of (await store.people.people(key.provider, { account: key.account })).all()) {
28
+ const alias = contact.alias ?? null;
29
+ const text = fold([contact.name, contact.username, alias].filter(Boolean).join(" "));
30
+ if (!wanted.every((word) => text.includes(word)))
31
+ continue;
32
+ const identityKey = `${key.provider}\u0000${contact.id}`;
33
+ if (!record.has(identityKey))
34
+ record.set(identityKey, await store.people.personOf({ provider: key.provider, id: contact.id }));
35
+ const person = record.get(identityKey);
36
+ const ref = person
37
+ ? `person:${person.uid}`
38
+ : formatReference({ type: "contact", provider: key.provider, id: contact.id });
39
+ const hit = hits.get(ref) ?? { ref, name: person?.name ?? contact.name, identities: [], aliases: [], ties: [] };
40
+ hit.identities.push({
41
+ provider: key.provider,
42
+ account: key.account,
43
+ id: contact.id,
44
+ name: contact.name,
45
+ username: contact.username,
46
+ alias,
47
+ });
48
+ if (alias !== null && !hit.aliases.includes(alias))
49
+ hit.aliases.push(alias);
50
+ hits.set(ref, hit);
51
+ }
52
+ }
53
+ // A person added by name alone has no identity in any account, so no account above lists them; they are the owner's.
54
+ // `--source` names accounts, which such a person is in none of.
55
+ for (const { person, name } of source === undefined ? await store.tasks.taskPeople({ limit: 5000 }) : []) {
56
+ if (hits.has(person) || name === null || !wanted.every((word) => fold(name).includes(word)))
57
+ continue;
58
+ const known = await store.people.personByUid(person.slice("person:".length));
59
+ if (known && known.identities.length === 0)
60
+ hits.set(person, { ref: person, name, identities: [], aliases: [], ties: [] });
61
+ }
62
+ for (const { person } of (await store.people.list({ kind: "test", limit: 5000 })).items)
63
+ hits.delete(person);
64
+ const people = [...hits.keys()].filter((ref) => ref.startsWith("person:"));
65
+ const ties = people.length === 0 ? {} : await store.people.ties(people);
66
+ for (const hit of hits.values())
67
+ hit.ties = ties[hit.ref] ?? [];
68
+ const first = wanted.join(" ");
69
+ const rank = (hit) => (fold(hit.name ?? "").startsWith(first) ? 0 : 1);
70
+ const sorted = [...hits.values()].sort((a, b) => Number(b.ties.length > 0) - Number(a.ties.length > 0) ||
71
+ rank(a) - rank(b) ||
72
+ (a.name ?? "").localeCompare(b.name ?? "") ||
73
+ a.ref.localeCompare(b.ref));
74
+ return { items: sorted.slice(0, limit), hasMore: sorted.length > limit, accounts };
75
+ };
76
+ export const peopleAnswer = (found, limit) => listAnswer("search people", {
77
+ items: found.items,
78
+ limit,
79
+ has_more: found.hasMore,
80
+ meta: { accounts: found.accounts.map(({ provider, account }) => `${provider}:${account}`) },
81
+ });
82
+ export const peopleText = (found) => found.items
83
+ .map((hit) => [
84
+ `${hit.ref} ${hit.name ?? "(no name)"}${hit.aliases.length ? ` alias ${hit.aliases.join(", ")}` : ""}${hit.ties.length ? "" : " no tie"}`,
85
+ ...hit.identities.map((one) => ` ${one.provider}:${one.account} ${one.id} ${one.name ?? ""}${one.username ? ` @${one.username}` : ""}`),
86
+ ].join("\n"))
87
+ .join("\n") || "nobody found";
88
+ //# sourceMappingURL=people.js.map
@@ -0,0 +1,306 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { parseLucene } from "@wirecat/cli-base/query";
3
+ import { meaningLane, parseLocator, plainQuery, questionLookup, RESOURCES_SEARCHED, searchAll, searchNotesOf, searchNotesQuery, searchStore, } from "@wirecat/cli-core";
4
+ import { demotedSenders, lowerSuspicious, searchMail } from "@wirecat/cli-core/mail";
5
+ import { APP } from "../app.js";
6
+ import { keyDocuments, keyFirst, projectOf } from "../knowledge/key-documents.js";
7
+ import { crmViewers as viewersOf } from "../store/crm-viewer.js";
8
+ import { accountsByKind, groupScopeOf, scopedAccounts, WCAT_ACCOUNT } from "../store/group.js";
9
+ import { accountsOf } from "../store/source-list.js";
10
+ import { taskPage } from "../tasks/context.js";
11
+ const CHATS_CHECKED = 500;
12
+ /** wcat's searches run as its own notes, never a stored account picked for the owner; the query sets the scope. */
13
+ const MEMO = WCAT_ACCOUNT;
14
+ export const unifiedSearch = async (store, query, options) => {
15
+ const limit = options.limit ?? 20, offset = options.offset ?? 0;
16
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100 || !Number.isInteger(offset) || offset < 0 || offset > 1000)
17
+ throw new CliError("validation_error", "limit takes 1–100; offset takes 0–1000");
18
+ if ((!options.keys.length && !options.notes) || options.keys.length > 50)
19
+ throw new CliError("validation_error", "select 1–50 accounts, or notes");
20
+ const answer = options.keys.length
21
+ ? await searchStore(store, MEMO, {
22
+ text: query,
23
+ accounts: options.keys,
24
+ limit: Math.min(2000, offset + limit + 1),
25
+ newest: true,
26
+ })
27
+ : { items: [], hasMore: false };
28
+ const items = answer.items.map((hit) => {
29
+ const key = parseLocator(hit.locator);
30
+ return {
31
+ kind: key.provider === "email" ? "email" : "message",
32
+ locator: hit.locator,
33
+ provider: key.provider,
34
+ account: key.account,
35
+ timestamp: hit.timestamp,
36
+ text: hit.text.slice(0, 2000),
37
+ match: "structured-words",
38
+ };
39
+ });
40
+ const matched = new Set(items.map((hit) => hit.locator));
41
+ const coverage = [];
42
+ let incomplete = answer.hasMore;
43
+ const noteItem = (note, match) => ({
44
+ kind: "note",
45
+ locator: note.ref,
46
+ provider: "notes",
47
+ account: note.folderId ?? "internal",
48
+ timestamp: note.modifiedAt ?? note.updatedAt,
49
+ text: note.text.slice(0, 2000),
50
+ match,
51
+ });
52
+ if (options.notes) {
53
+ try {
54
+ const notes = await searchNotesQuery(store, { text: query, limit: Math.min(500, offset + limit + 1) });
55
+ incomplete ||= notes.hasMore;
56
+ items.push(...notes.items.map(({ note }) => noteItem(note, "structured-words")));
57
+ coverage.push({ notes: "searched" });
58
+ }
59
+ catch (error) {
60
+ // A field only messages have (`from:`, `after:`) is refused by notes; the messages still answer.
61
+ if (!isCliError(error) || error.code !== "validation_error" || !options.keys.length)
62
+ throw error;
63
+ coverage.push({ notes: `not searched: ${error.message}` });
64
+ incomplete = true;
65
+ }
66
+ }
67
+ if (options.noteText !== undefined) {
68
+ const notes = await store.notes.notes({
69
+ source: "internal",
70
+ search: options.noteText,
71
+ limit: Math.min(500, offset + limit + 1),
72
+ });
73
+ incomplete ||= notes.hasMore;
74
+ items.push(...notes.items.map((note) => noteItem(note, "note-text")));
75
+ }
76
+ for (const item of items)
77
+ matched.add(item.locator);
78
+ for (const key of options.keys) {
79
+ const taskResults = await taskPage(store, key, {
80
+ state: "open",
81
+ sources: [...matched],
82
+ limit: Math.min(500, offset + limit + 1),
83
+ });
84
+ incomplete ||= taskResults.hasMore;
85
+ for (const task of taskResults.items) {
86
+ if (matched.has(task.source))
87
+ items.push({
88
+ kind: "task",
89
+ locator: `task:${task.id}`,
90
+ ...key,
91
+ timestamp: task.createdAt.toISOString(),
92
+ text: task.kind,
93
+ source: task.source,
94
+ match: "task-source",
95
+ });
96
+ }
97
+ if (key.provider === "email")
98
+ coverage.push({ ...key, mail: (await store.sync.syncState(key, "mail_coverage"))?.value ?? null });
99
+ else {
100
+ // Counts, not one row per chat: an account of hundreds of chats made the rows most of an answer.
101
+ const chats = await store.chats.chats(key, { limit: CHATS_CHECKED });
102
+ const archives = await store.chats.chatCompleteness(key, chats.items.map((chat) => chat.id));
103
+ const count = (test) => archives.filter(test).length;
104
+ coverage.push({
105
+ ...key,
106
+ chats: {
107
+ checked: archives.length,
108
+ more: chats.hasMore,
109
+ complete: count(({ state }) => state === "complete"),
110
+ partial: count(({ state }) => state === "partial"),
111
+ neverFetched: count(({ state }) => state === "unknown"),
112
+ behind: count(({ upToDate }) => upToDate === false),
113
+ withGaps: count(({ gaps }) => gaps),
114
+ },
115
+ });
116
+ }
117
+ }
118
+ items.sort((a, b) => b.timestamp.localeCompare(a.timestamp) || a.kind.localeCompare(b.kind) || a.locator.localeCompare(b.locator));
119
+ const unique = [...new Map(items.map((item) => [item.locator, item])).values()];
120
+ const hasMore = unique.length > offset + limit;
121
+ return {
122
+ query,
123
+ items: unique.slice(offset, offset + limit),
124
+ hasMore,
125
+ ...(hasMore && offset + limit <= 1000 ? { nextOffset: offset + limit } : {}),
126
+ incomplete: incomplete || (hasMore && offset + limit > 1000),
127
+ accounts: options.keys,
128
+ coverage,
129
+ };
130
+ };
131
+ /** Notes are no account's: `--all` takes them with every account, `--provider notes` alone. */
132
+ /** `--all`, or the accounts a `--source` list names; notes count as one source, whichever folder is named. */
133
+ export const searchAccounts = async (store, env, options) => {
134
+ if (options.all && options.source !== undefined)
135
+ throw new CliError("validation_error", "use --all alone, or name the accounts with --source");
136
+ if (options.all)
137
+ return { keys: (await scopedAccounts(store, env)).filter(({ provider }) => provider !== "notes"), notes: true };
138
+ if (options.source === undefined)
139
+ throw new CliError("validation_error", "give --all, or name the accounts with --source: telegram:1,email,notes");
140
+ const keys = await accountsOf(store, env, options.source);
141
+ return {
142
+ keys: keys.filter(({ provider }) => provider !== "notes"),
143
+ notes: keys.some(({ provider }) => provider === "notes"),
144
+ };
145
+ };
146
+ export const hasSource = (node) => node.kind === "predicate"
147
+ ? node.field === "in"
148
+ : node.clauses.some(({ occur, node }) => occur !== "must_not" && hasSource(node));
149
+ /** Pages read past hits the caller may not see; a page short of `limit` after them says `hasMore`. */
150
+ const PAGES_PAST_HIDDEN = 5;
151
+ /**
152
+ * A page of `limit` hits the caller may see, reading the next pages while hidden hits leave it short, so `--limit`
153
+ * is not spent on what is left out.
154
+ */
155
+ const allowedPage = async (ask, limit, shows) => {
156
+ const first = await ask();
157
+ let items = first.items.filter(shows);
158
+ let page = first;
159
+ for (let read = 1; items.length < limit && page.hasMore && page.nextOffset !== undefined; read++) {
160
+ if (read > PAGES_PAST_HIDDEN)
161
+ break;
162
+ page = await ask(page.nextOffset);
163
+ items = items.concat(page.items.filter(shows));
164
+ }
165
+ const { nextOffset: _, ...rest } = first;
166
+ return { ...rest, items: items.slice(0, limit), hasMore: items.length > limit || page.hasMore };
167
+ };
168
+ /**
169
+ * In a group, each kind reads only the group's accounts of it; a kind it holds none of is left out and named, never
170
+ * read whole: an empty list would mean "every account" to some readers.
171
+ */
172
+ const groupScoped = async (store, env, only) => {
173
+ const scope = await groupScopeOf(store, env);
174
+ if (scope === undefined)
175
+ return undefined;
176
+ const byKind = accountsByKind(scope, await store.business.accounts());
177
+ // cli-core may search a kind a group holds no accounts of here (meetings); such a kind is left out, not read whole.
178
+ const kinds = (kind) => byKind[kind] ?? [];
179
+ const wanted = only ?? RESOURCES_SEARCHED;
180
+ const kept = wanted.filter((kind) => kinds(kind).length > 0);
181
+ if (kept.length === 0)
182
+ throw new CliError("validation_error", `group ${scope.run.name} holds no account of ${wanted.join(", ")}`);
183
+ return {
184
+ only: kept,
185
+ scope: Object.fromEntries(kept.map((kind) => [kind, kinds(kind)])),
186
+ skipped: wanted
187
+ .filter((kind) => !kept.includes(kind))
188
+ .map((resource) => ({
189
+ resource,
190
+ code: "not_found",
191
+ reason: `group ${scope.run.name} holds no account of it`,
192
+ })),
193
+ };
194
+ };
195
+ /**
196
+ * Messages, mail, notes, calendar events, CRM deals and leads, business data and meeting passages ranked together,
197
+ * with the open tasks that point at a hit. Meetings come from every meeting account, through each one's search index.
198
+ */
199
+ export const searchEverywhere = async (store, env, { text, limit, only, crmKinds, source, exact, timezone, plainOrder, shows, harder, }) => {
200
+ const accounts = await scopedAccounts(store, env);
201
+ const group = await groupScoped(store, env, only);
202
+ const crmViewers = await viewersOf(store, accounts);
203
+ // Group lists belong to tg; model downloads belong to wcat.
204
+ const messenger = { app: { ...APP, command: "tg" }, hintCommand: "wcat" };
205
+ // Hits a permission hides are dropped after the search, so they would already have gone to the model.
206
+ const harderSkipped = harder && shows !== undefined ? "a permission hides some kinds here, so no hit was sent to the model" : undefined;
207
+ const ask = (offset) => searchAll(store, MEMO, {
208
+ text,
209
+ limit,
210
+ env,
211
+ ...(offset === undefined ? {} : { offset }),
212
+ ...(group === undefined ? (only === undefined ? {} : { only }) : { only: group.only, scope: group.scope }),
213
+ ...(crmKinds === undefined ? {} : { crmKinds }),
214
+ ...(source === undefined ? {} : { source }),
215
+ ...(crmViewers.length ? { crmViewers } : {}),
216
+ // wcat is the owner's own view of every account, personal and work alike.
217
+ meetingScopes: ["personal", "work"],
218
+ ...(only?.includes("meetings") ? { meetingsAsked: true } : {}),
219
+ ...(exact ? { exact: true } : {}),
220
+ ...(timezone === undefined ? {} : { timezone }),
221
+ ...(harder && harderSkipped === undefined ? { harder: { app: APP } } : {}),
222
+ }, messenger, (query) => searchStore(store, MEMO, query, messenger), meaningLane({ env, store: async () => store, messenger: { app: { command: "wcat" } } }));
223
+ const searched = shows === undefined ? await ask() : await allowedPage(ask, limit, shows);
224
+ const found = group === undefined ? searched : { ...searched, skipped: [...group.skipped, ...searched.skipped] };
225
+ const tasks = [];
226
+ let tasksIncomplete = false;
227
+ const sources = found.items.map((item) => item.ref);
228
+ for (const account of accounts) {
229
+ const page = await taskPage(store, account, { state: "open", sources, limit: Math.min(limit, 500) });
230
+ tasks.push(...page.items.map((task) => ({ ...task, heldBy: account })));
231
+ tasksIncomplete ||= page.hasMore;
232
+ }
233
+ const suspicious = plainOrder ? new Set() : await suspiciousRefs(store, found.items);
234
+ return {
235
+ ...found,
236
+ items: lowerSuspicious(found.items, (item) => suspicious.has(item.ref)),
237
+ tasks: tasks.slice(0, limit),
238
+ tasksIncomplete: tasksIncomplete || tasks.length > limit,
239
+ ...(harderSkipped === undefined ? {} : { harderSkipped }),
240
+ };
241
+ };
242
+ /** The mail on a page whose sender's mail search ranks lower; the page's items carry no sender address. */
243
+ const suspiciousRefs = async (store, items) => {
244
+ const demoted = await demotedSenders(store);
245
+ const refs = new Set();
246
+ if (demoted.size === 0)
247
+ return refs;
248
+ for (const { kind, ref } of items) {
249
+ if (kind !== "mail")
250
+ continue;
251
+ const { provider, account, message } = parseLocator(ref);
252
+ const stored = await store.accounts.storedAccount({ provider, account }).catch(() => null);
253
+ const email = stored === null || message === undefined ? null : await store.mail.email(stored.id, message);
254
+ if (email?.fromAddress && demoted.has(email.fromAddress.toLowerCase()))
255
+ refs.add(ref);
256
+ }
257
+ return refs;
258
+ };
259
+ /** One kind with all its fields: messenger messages from every messenger, or imported mail. */
260
+ export const searchKind = async (store, kind, { text, limit, account, accounts, exact, timezone, plainOrder, }) => {
261
+ const held = (await store.accounts.accounts()).some(({ provider }) => provider !== "notes" && (kind === "mail" ? provider === "email" : provider !== "email"));
262
+ if (!held)
263
+ throw new CliError("not_found", kind === "mail" ? "no imported mail; run wcat sync --only mail" : "no stored messenger messages");
264
+ const scope = {
265
+ ...(accounts === undefined ? {} : { accounts }),
266
+ ...(exact ? { exact: true } : {}),
267
+ ...(timezone === undefined ? {} : { timezone }),
268
+ };
269
+ if (kind === "mail")
270
+ return searchMail(store, MEMO, {
271
+ text,
272
+ limit,
273
+ ...scope,
274
+ ...(account === undefined ? {} : { mailAccount: account }),
275
+ ...(plainOrder ? { plainOrder: true } : {}),
276
+ }, { app: APP });
277
+ const plain = plainQuery(text);
278
+ return searchStore(store, MEMO, {
279
+ text,
280
+ kind,
281
+ ...(hasSource(parseLucene(plain).root) || accounts !== undefined ? {} : { source: "all" }),
282
+ limit,
283
+ ...scope,
284
+ // As search all does: a question finds a short reply by the message it answers, and records holding some words.
285
+ ...(!exact && questionLookup(plain) !== undefined ? { discover: true } : {}),
286
+ }, { app: APP });
287
+ };
288
+ const keyRefs = async (store, project) => new Set((await keyDocuments(store, await projectOf(store, project))).map((item) => item.ref));
289
+ /** A project's key documents first, labelled key; nothing is left out. */
290
+ export const keyDocumentsFirst = async (store, items, project) => (project === undefined ? items : keyFirst(items, await keyRefs(store, project)));
291
+ export const searchNotes = async (store, env, text, options) => {
292
+ const found = await searchNotesOf(store, MEMO, text, {
293
+ limit: options.limit,
294
+ offset: (options.page - 1) * options.limit,
295
+ env,
296
+ app: APP,
297
+ ...(options.filter === undefined ? {} : { filter: options.filter }),
298
+ ...(options.source === undefined ? {} : { accounts: options.source }),
299
+ ...(options.exact ? { exact: true } : {}),
300
+ ...(options.timezone === undefined ? {} : { timezone: options.timezone }),
301
+ });
302
+ return options.project === undefined
303
+ ? found
304
+ : { ...found, items: await keyDocumentsFirst(store, found.items, options.project) };
305
+ };
306
+ //# sourceMappingURL=search.js.map
@@ -0,0 +1,179 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { LOCAL_READ, openOf, parseReference, } from "@wirecat/cli-core";
4
+ import { answers, shortenedBy, wholeList, withStore } from "../answer.js";
5
+ import { profileFor } from "../knowledge/messenger-sync.js";
6
+ import { grantedLevel } from "../mcp/granted.js";
7
+ import { imported, readSourced, recordsHidden, sourcesOf, sourcesText } from "../records/sources.js";
8
+ import { refuseBareNumber } from "../refs.js";
9
+ import { crmNotes } from "../store/crm-viewer.js";
10
+ const MAX_REFS = 100;
11
+ /** The kinds a bare number could name: every kind whose store id is a number. */
12
+ const NUMBERED = ["note", "document", "person", "organization", "project", "task", "fact", "memory"];
13
+ /**
14
+ * wcat's own read for each kind it holds, and the files CLI's for notes; a messenger's kinds open in the CLI the
15
+ * provider registry names.
16
+ */
17
+ export const LOCAL_OPENS = {
18
+ note: ["files", "notes", "show"],
19
+ document: ["files", "notes", "show"],
20
+ person: ["wcat", "context"],
21
+ organization: ["wcat", "organizations", "context"],
22
+ project: ["wcat", "projects", "context"],
23
+ task: ["wcat", "tasks", "show"],
24
+ fact: ["wcat", "facts", "show"],
25
+ memory: ["wcat", "memories", "show"],
26
+ message: ["wcat", "messages", "show"],
27
+ invoice: ["wcat", "invoices", "show"],
28
+ payment: ["wcat", "payments", "show"],
29
+ order: ["wcat", "orders", "show"],
30
+ deal: ["wcat", "deals", "show"],
31
+ lead: ["wcat", "leads", "show"],
32
+ pipeline: ["wcat", "pipelines", "show"],
33
+ product: ["wcat", "products", "show"],
34
+ contract: ["wcat", "contracts", "show"],
35
+ subscription: ["wcat", "subscriptions", "show"],
36
+ wallet: ["wcat", "wallets", "show"],
37
+ transaction: ["wcat", "transactions", "show"],
38
+ event: ["wcat", "events", "show"],
39
+ };
40
+ /** The permission key of the wcat command that opens a kind, such as `invoices.show`. */
41
+ export const openKeyOf = (kind) => LOCAL_OPENS[kind]?.slice(1).join(".");
42
+ /**
43
+ * `wcat show` tells what the command that opens a reference would, so an MCP client denied that command is refused
44
+ * here too, rather than read the title past it.
45
+ */
46
+ const refuseDenied = (command, summaries) => {
47
+ for (const { ref, kind } of summaries) {
48
+ const key = openKeyOf(kind);
49
+ if (key !== undefined && grantedLevel(command, key) === "deny")
50
+ throw new CliError("permission_error", `${ref}: wcat's MCP server denies ${key}`, {
51
+ reason: "access.denied",
52
+ permission: key,
53
+ });
54
+ }
55
+ };
56
+ /** Titles of these kinds are written by other people: a chat's title, a sender's name, a shared file's name. */
57
+ const OTHERS = new Set([
58
+ "message",
59
+ "chat",
60
+ "contact",
61
+ "email",
62
+ "email_thread",
63
+ "document",
64
+ "event",
65
+ "meeting",
66
+ "agent",
67
+ "bot",
68
+ ]);
69
+ const ACCOUNT_KEY = /^[a-z][a-z-]*:\S+$/;
70
+ /**
71
+ * cli-core's `tasks show` takes a task's id, not its `task:` ref, and a task from a message lives in that message's
72
+ * account, which it asks for: wcat never picks one.
73
+ */
74
+ const taskOpen = (summary, open) => {
75
+ if (summary.kind !== "task" || open.argv === null)
76
+ return open;
77
+ const argv = [...open.argv.slice(0, -1), summary.ref.slice("task:".length)];
78
+ return {
79
+ ...open,
80
+ argv: summary.in !== null && ACCOUNT_KEY.test(summary.in) ? [...argv, "--source", summary.in] : argv,
81
+ };
82
+ };
83
+ const shellWord = (word) => (/^[\w@%+=:,./<>~-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`);
84
+ const profilesFor = (env) => (provider, account) => {
85
+ if (account === null)
86
+ return { why: `${provider} names no account here`, profiles: [] };
87
+ return (profileFor(provider, account, env) ?? { why: `wcat cannot read which profiles ${provider} has`, profiles: [] });
88
+ };
89
+ /** A deal or lead the viewer rule hides reads as `null`, so that reference alone is unavailable. */
90
+ const hidden = (error) => {
91
+ if (isCliError(error) && error.details.reason === "deal.not-readable")
92
+ return null;
93
+ throw error;
94
+ };
95
+ /** What each reference names, in the order given, and the command that opens it; never runs that command. */
96
+ export const showReferences = async (store, env, texts, command) => {
97
+ if (texts.length > MAX_REFS)
98
+ throw new CliError("validation_error", `at most ${MAX_REFS} references at once`);
99
+ for (const text of texts)
100
+ await refuseBareNumber(store, text, NUMBERED);
101
+ for (const text of texts)
102
+ parseReference(text);
103
+ const summaries = await store.refs.summaries(texts);
104
+ if (command !== undefined)
105
+ refuseDenied(command, [...summaries.values()]);
106
+ const ports = { profilesFor: profilesFor(env), local: LOCAL_OPENS };
107
+ const shown = texts.map((text) => {
108
+ const summary = summaries.get(text) ?? {
109
+ ref: text,
110
+ kind: "unknown",
111
+ title: null,
112
+ in: null,
113
+ at: null,
114
+ provider: null,
115
+ account: null,
116
+ tool: null,
117
+ state: "unavailable",
118
+ };
119
+ const open = taskOpen(summary, openOf(summary, ports));
120
+ return {
121
+ ref: summary.ref,
122
+ kind: summary.kind,
123
+ title: summary.title,
124
+ in: summary.in,
125
+ at: summary.at,
126
+ provider: summary.provider,
127
+ tool: summary.tool ?? open.argv?.[0] ?? null,
128
+ state: summary.state,
129
+ open: { ...open, line: open.argv?.map(shellWord).join(" ") ?? null },
130
+ ...(OTHERS.has(summary.kind) ? { untrusted: ["title", "in"] } : {}),
131
+ };
132
+ });
133
+ const withRecords = command === undefined || !recordsHidden(command);
134
+ for (const one of shown) {
135
+ const entity = one.state === "available" ? await readSourced(store, one.kind, one.ref)?.catch(hidden) : undefined;
136
+ if (entity === null) {
137
+ Object.assign(one, { title: null, in: null, at: null, state: "unavailable" });
138
+ delete one.untrusted;
139
+ continue;
140
+ }
141
+ if (entity === undefined)
142
+ continue;
143
+ if (withRecords)
144
+ one.sources = await sourcesOf(store, entity);
145
+ // An imported entry's title is the source system's words, as a chat title is its members'.
146
+ if (imported(entity))
147
+ one.untrusted = ["title"];
148
+ }
149
+ return shown;
150
+ };
151
+ const minute = (at) => (at === null ? null : at.slice(0, 16).replace("T", " "));
152
+ const blockOf = (one) => [
153
+ `${one.ref} ${one.title ?? ""}`.trimEnd(),
154
+ ` ${[one.kind, one.in, one.state, minute(one.at)].filter((part) => part !== null).join(" · ")}`,
155
+ ` open: ${one.open.line ?? "none"}`,
156
+ ...(one.open.why === null ? [] : [` ${one.open.why}`]),
157
+ ...(one.sources === undefined ? [] : sourcesText(one.ref, one.sources)),
158
+ ].join("\n");
159
+ export const showCommand = (program, streams, env) => {
160
+ const { print } = answers(program, streams, env);
161
+ annotate(program.command("show"), { effects: LOCAL_READ, partial: true })
162
+ .description("what any reference names, and the command that opens it")
163
+ .argument("<ref...>", "1 to 100 references any WireCat CLI printed: chat:, msg:, note:, document:, person:, task:…")
164
+ .option("--json", "print JSON; --json=ref,title keeps only those fields")
165
+ .action(async (refs, options, command) => {
166
+ const { items, notes } = await withStore(env, async (store) => ({
167
+ items: await showReferences(store, env, refs, command),
168
+ notes: crmNotes(store),
169
+ }));
170
+ const gone = items.filter((one) => one.state !== "available");
171
+ const body = shortenedBy(notes, wholeList("show", items));
172
+ if (gone.length > 0) {
173
+ body.missing = gone.map((one) => ({ field: "state", why: `${one.ref} is ${one.state}` }));
174
+ body.meta = { ...body.meta, complete: false };
175
+ }
176
+ print(options.json, body, items.map(blockOf).join("\n"));
177
+ });
178
+ };
179
+ //# sourceMappingURL=command.js.map