@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,210 @@
1
+ import { open, readFile } from "node:fs/promises";
2
+ import { basename } from "node:path";
3
+ import { text as streamText } from "node:stream/consumers";
4
+ import { CliError } from "@wirecat/cli-base";
5
+ import { envelopeOfCsv, envelopeOfText, ingest, ingestLines, ingestVcard, isVcard, jsonlLines, TABLE_RECORD_TYPES, TableError, } from "@wirecat/cli-core";
6
+ import { sourceOf } from "./mapping.js";
7
+ /** A vCard address book is a phone's contacts: they go under the seeded `phone` provider, one account per device. */
8
+ const PHONE = "phone";
9
+ const BOM = /^\uFEFF/;
10
+ const errnoOf = (error) => typeof error === "object" && error !== null && "code" in error ? String(error.code) : undefined;
11
+ /** A file opened now, so a missing one fails before anything is read; its errors come as answers, not as errno. */
12
+ const linesOf = async (file, stdin) => {
13
+ if (file === "-")
14
+ return jsonlLines(stdin);
15
+ try {
16
+ const handle = await open(file);
17
+ if (!(await handle.stat()).isFile()) {
18
+ await handle.close();
19
+ throw Object.assign(new Error(`${file} is a folder`), { code: "EISDIR" });
20
+ }
21
+ return jsonlLines(handle.createReadStream({ encoding: "utf8" }));
22
+ }
23
+ catch (error) {
24
+ if (errnoOf(error) === "ENOENT")
25
+ throw new CliError("not_found", `no records file ${file}: give a file that exists, or - for stdin`, {
26
+ reason: "records.file-missing",
27
+ path: file,
28
+ });
29
+ const why = errnoOf(error) === "EISDIR" ? "it is a folder" : errnoOf(error) === "EACCES" ? "no permission" : "unreadable";
30
+ throw new CliError("validation_error", `the records file ${file} cannot be read: ${why}`, {
31
+ reason: "records.file-unreadable",
32
+ path: file,
33
+ why,
34
+ });
35
+ }
36
+ };
37
+ /** A JSONL file's first line: an object holding no `records`. */
38
+ const headerOf = (line) => {
39
+ try {
40
+ const value = JSON.parse(line);
41
+ return value && typeof value === "object" && !Array.isArray(value) && !("records" in value)
42
+ ? value
43
+ : undefined;
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ };
49
+ /** `sheet:rentals` names the envelope's provider and account, as records list and link take it. */
50
+ const accountIn = (envelope, given) => {
51
+ const provider = envelope?.source?.provider;
52
+ return typeof provider === "string" && given.startsWith(`${provider}:`) ? given.slice(provider.length + 1) : given;
53
+ };
54
+ const deviceOf = (given) => {
55
+ const at = given.indexOf(":");
56
+ if (at < 0)
57
+ return given;
58
+ if (given.slice(0, at) !== PHONE)
59
+ throw new CliError("validation_error", "a vCard file holds a phone's contacts: --account phone:<device>", {
60
+ param: "--account",
61
+ });
62
+ return given.slice(at + 1);
63
+ };
64
+ /**
65
+ * Imports a records file or stdin. JSONL streams, a record at a time, so a file of any length fits in memory; a JSON
66
+ * envelope and a vCard address book are read whole, as one envelope each. `onIssue` hears every refusal as it
67
+ * happens, also those past the receipt's capped lists.
68
+ */
69
+ export const importRecords = async (store, { file, stdin, account, dryRun, onIssue, region, type, }) => {
70
+ if (type !== undefined || file.toLowerCase().endsWith(".csv"))
71
+ return importSheet(store, { file, stdin, account, dryRun, onIssue, type });
72
+ const iterator = (await linesOf(file, stdin))[Symbol.asyncIterator]();
73
+ const before = [];
74
+ let next = await iterator.next();
75
+ while (!next.done && next.value.replace(BOM, "").trim() === "") {
76
+ before.push(next.value);
77
+ next = await iterator.next();
78
+ }
79
+ async function* rest() {
80
+ for (let line = await iterator.next(); !line.done; line = await iterator.next())
81
+ yield line.value;
82
+ }
83
+ const whole = async (first) => {
84
+ const lines = [...before, ...first];
85
+ for await (const line of rest())
86
+ lines.push(line);
87
+ return lines.join("\n");
88
+ };
89
+ if (next.done)
90
+ return ingest(store, envelopeOfText(before.join("\n")), { account, dryRun, onIssue });
91
+ const first = next.value.replace(BOM, "");
92
+ if (isVcard(first)) {
93
+ const { vcard, ...receipt } = await ingestVcard(store, await whole([first]), {
94
+ account: deviceOf(account),
95
+ provider: PHONE,
96
+ batchId: `vcard-${new Date().toISOString()}`,
97
+ dryRun,
98
+ onIssue,
99
+ // cli-core checks the code against its phone plans; its list is lower case.
100
+ ...(region === undefined ? {} : { region: region.trim().toLowerCase() }),
101
+ });
102
+ const badRegion = receipt.errors.find((one) => one.pointer === "/options/phone_region");
103
+ if (badRegion)
104
+ throw new CliError("validation_error", badRegion.message.replace("options.phone_region", "--region"), {
105
+ param: "--region",
106
+ reason: badRegion.code,
107
+ });
108
+ return { ...receipt, vcard: vcard.map((one) => ({ ...one, card: one.card + 1 })) };
109
+ }
110
+ if (region !== undefined)
111
+ throw new CliError("validation_error", "--region is for a vCard file; an envelope names options.phone_region", {
112
+ param: "--region",
113
+ });
114
+ const header = headerOf(first);
115
+ if (header !== undefined) {
116
+ async function* all() {
117
+ // A refused header stops the stream at its first line; the file is closed here, not when it is collected.
118
+ try {
119
+ yield first;
120
+ yield* rest();
121
+ }
122
+ finally {
123
+ await iterator.return?.();
124
+ }
125
+ }
126
+ return ingestLines(store, all(), { account: accountIn(header, account), dryRun, onIssue });
127
+ }
128
+ const envelope = envelopeOfText(await whole([first]));
129
+ return ingest(store, envelope, { account: accountIn(envelope, account), dryRun, onIssue });
130
+ };
131
+ const placed = (items, placeOf) => items.map((item) => {
132
+ const place = placeOf(item.pointer);
133
+ return place ? { ...item, place } : item;
134
+ });
135
+ const sheetText = async (file, stdin) => {
136
+ if (file === "-")
137
+ return streamText(stdin);
138
+ try {
139
+ return await readFile(file, "utf8");
140
+ }
141
+ catch (error) {
142
+ if (errnoOf(error) === "ENOENT")
143
+ throw new CliError("not_found", `no records file ${file}: give a file that exists, or - for stdin`, {
144
+ reason: "records.file-missing",
145
+ path: file,
146
+ });
147
+ throw new CliError("validation_error", `the records file ${file} cannot be read`, {
148
+ reason: "records.file-unreadable",
149
+ path: file,
150
+ });
151
+ }
152
+ };
153
+ /** `line 3, column total`: where a sheet's refusal is, as the owner finds it in a spreadsheet. */
154
+ export const placeText = (place) => place ? `line ${place.line}${place.column ? `, column ${place.column}` : ""}` : "";
155
+ /** A sheet that cannot be read as records is refused whole, as an envelope is: nothing is written. */
156
+ const refusedSheet = (dryRun, source, errors) => ({
157
+ dryRun,
158
+ source,
159
+ created: 0,
160
+ updated: 0,
161
+ unchanged: 0,
162
+ deleted: 0,
163
+ refused: errors.length,
164
+ proposed: [],
165
+ waiting: [],
166
+ flagged: [],
167
+ unmatched: [],
168
+ ignored: [],
169
+ relationships: { added: 0, kept: 0, restored: 0, withdrawn: 0, proposed: 0, skippedOwnerRejected: 0 },
170
+ notices: [],
171
+ errors,
172
+ truncated: false,
173
+ });
174
+ /**
175
+ * A CSV sheet of one type, read whole, as an envelope of `<provider>:<account>`; every pointer of the receipt also
176
+ * names the sheet's line and column.
177
+ */
178
+ const importSheet = async (store, { file, stdin, account, dryRun, onIssue, type, }) => {
179
+ if (!type || !TABLE_RECORD_TYPES.includes(type))
180
+ throw new CliError("validation_error", `a CSV sheet holds one type: --type ${TABLE_RECORD_TYPES.join("|")}`, {
181
+ param: "--type",
182
+ });
183
+ const source = sourceOf(account);
184
+ const batch = `${file === "-" ? "stdin" : basename(file)}-${new Date().toISOString()}`;
185
+ let read;
186
+ try {
187
+ read = envelopeOfCsv(await sheetText(file, stdin), { type, source: { ...source, batch_id: batch } });
188
+ }
189
+ catch (error) {
190
+ if (!(error instanceof TableError))
191
+ throw error;
192
+ for (const one of error.errors)
193
+ onIssue(one);
194
+ return refusedSheet(dryRun, { ...source, batchId: batch }, error.errors);
195
+ }
196
+ const receipt = await ingest(store, read.envelope, {
197
+ account: source.account,
198
+ dryRun,
199
+ onIssue: (issue) => onIssue({ ...issue, ...(read.placeOf(issue.pointer) ? { place: read.placeOf(issue.pointer) } : {}) }),
200
+ });
201
+ return {
202
+ ...receipt,
203
+ waiting: placed(receipt.waiting, read.placeOf),
204
+ flagged: placed(receipt.flagged, read.placeOf),
205
+ unmatched: placed(receipt.unmatched, read.placeOf),
206
+ ignored: placed(receipt.ignored, read.placeOf),
207
+ errors: placed(receipt.errors, read.placeOf),
208
+ };
209
+ };
210
+ //# sourceMappingURL=input.js.map
@@ -0,0 +1,80 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { LOCAL_READ, LOCAL_WRITE, queryTerms, termField, withQuery } from "@wirecat/cli-core";
4
+ import { answers, itemAnswer } from "../answer.js";
5
+ import { byOption, whoRuns } from "../author.js";
6
+ import { positive } from "../options.js";
7
+ import { pageOf } from "../page.js";
8
+ export const RECORD_QUERY = {
9
+ entity: "source_record",
10
+ backend: "native",
11
+ fields: [
12
+ termField("type", "kw", "type:organization"),
13
+ termField("waiting", "bool", "waiting:true"),
14
+ termField("flagged", "bool", "flagged:true"),
15
+ termField("unmatched", "bool", "unmatched:true"),
16
+ termField("entity", "ref", 'entity:"organization:3"'),
17
+ termField("batch", "kw", "batch:2026-11-07"),
18
+ termField("deleted", "bool", "deleted:true"),
19
+ ],
20
+ };
21
+ /** `sheet:rentals`: records are kept per source, so a read or a mapping names its provider and account. */
22
+ export const sourceOf = (account) => {
23
+ const [provider = "", ...rest] = (account ?? "").trim().split(":");
24
+ const name = rest.join(":");
25
+ if (!provider || !name)
26
+ throw new CliError("validation_error", "name the source as --account <provider>:<account>, such as sheet:rentals", {
27
+ param: "--account",
28
+ });
29
+ return { provider, account: name };
30
+ };
31
+ /**
32
+ * `organization:client` or `custom:quote:Q-7`: the record's type and its id at the source, as the envelope gave them.
33
+ * Only a `custom:` type holds a colon; any other id may hold one.
34
+ */
35
+ export const recordOf = (record) => {
36
+ const from = record.startsWith("custom:") ? "custom:".length : 0;
37
+ const at = record.indexOf(":", from);
38
+ if (at <= from || at === record.length - 1)
39
+ throw new CliError("validation_error", `${record} is not <type>:<external_id>, such as organization:client or custom:quote:Q-7`, { param: "record" });
40
+ return { type: record.slice(0, at), externalId: record.slice(at + 1) };
41
+ };
42
+ export const RECORD_HELP = "<type>:<external_id> as the source names it, such as organization:client or custom:quote:Q-7";
43
+ export const ACCOUNT_HELP = "the source, <provider>:<account> as the envelope's source names it, such as sheet:rentals";
44
+ export const recordMappingCommands = (records, program, streams, env) => {
45
+ const { run } = answers(program, streams, env);
46
+ withQuery(annotate(records.command("list"), { effects: LOCAL_READ }).description("a source's records, newest first; waiting:true lists those that wait for a record they name, unmatched:true " +
47
+ "the people, organizations and projects whose identifiers fit more than one of yours, entity: those mapped " +
48
+ "to one of your entries"), RECORD_QUERY)
49
+ .summary("a source's records; waiting:true lists what needs records link")
50
+ .option("--account <account>", ACCOUNT_HELP)
51
+ .option("--limit <n>", "most records, up to 500", positive, 100)
52
+ .option("--json", "print JSON; --json=type,external_id,entity keeps only those fields")
53
+ .action((words, given) => run(given.json, async (store) => {
54
+ const source = sourceOf(given.account);
55
+ const terms = queryTerms(words, RECORD_QUERY, "records list");
56
+ const filter = {
57
+ ...source,
58
+ ...(terms.has("type") ? { type: terms.get("type") } : {}),
59
+ ...(terms.get("waiting") === "true" ? { waiting: true } : {}),
60
+ ...(terms.get("flagged") === "true" ? { flagged: true } : {}),
61
+ ...(terms.get("unmatched") === "true" ? { unmatched: true } : {}),
62
+ ...(terms.has("entity") ? { entity: terms.get("entity") } : {}),
63
+ ...(terms.has("batch") ? { batch: terms.get("batch") } : {}),
64
+ ...(terms.has("deleted") ? { deleted: terms.get("deleted") === "true" } : {}),
65
+ };
66
+ return pageOf("records list", given.limit, (most) => store.records.list({ ...filter, limit: most }));
67
+ }));
68
+ byOption(annotate(records.command("link"), { effects: LOCAL_WRITE, output: { entity: "source_record" } })
69
+ .description("say which of your entries a source's record is (organization:client is organization:3); never done by " +
70
+ "name. Records that waited for it become proposals in wcat review. Only you link; an agent is refused")
71
+ .summary("say which of your entries a source's record is")
72
+ .argument("<record>", RECORD_HELP)
73
+ .argument("<ref>", "your entry of the same type: person:<id>, organization:<id> or project:<id>")
74
+ .option("--account <account>", ACCOUNT_HELP)
75
+ .option("--json", "print JSON; --json=type,external_id,entity keeps only those fields")).action(async (record, ref, given, command) => {
76
+ const by = await whoRuns(command, env, { asOwner: given.asOwner, question: `link ${record} to ${ref} as you?` });
77
+ await run(given.json, async (store) => itemAnswer(await store.records.map({ ...sourceOf(given.account), ...recordOf(record) }, ref, by)));
78
+ });
79
+ };
80
+ //# sourceMappingURL=mapping.js.map
@@ -0,0 +1,125 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { CORE_REASONS, ingest, LOCAL_READ, LOCAL_WRITE, providerNamed, RECORDS_SCHEMA_VERSION, } from "@wirecat/cli-core";
4
+ import { itemAnswer } from "../answer.js";
5
+ import { jsonOption } from "../options.js";
6
+ import { ACCOUNT_HELP, RECORD_HELP, recordOf, sourceOf } from "./mapping.js";
7
+ const INCOMING = 100;
8
+ /** The CLI code cli-core registers for an import's refusal, such as `record.stale-revision`. */
9
+ export const codeOf = (reason) => {
10
+ const code = CORE_REASONS.find((one) => one.reason === reason)?.code;
11
+ return code === undefined || code === "internal_error" ? "validation_error" : code;
12
+ };
13
+ const storedRecord = async (store, account, record) => {
14
+ const key = { ...sourceOf(account), ...recordOf(record) };
15
+ const found = await store.records.get(key);
16
+ if (found === undefined)
17
+ throw new CliError("not_found", `no record ${record} from ${key.provider}:${key.account}; records list shows them`, {
18
+ reason: "records.not-stored",
19
+ record,
20
+ });
21
+ return found;
22
+ };
23
+ const matchText = (run) => [
24
+ `matched ${run.linked}, created ${run.created}`,
25
+ ...(run.proposed.length ? [`proposed for your review: ${run.proposed.join(" ")}`] : []),
26
+ ...run.unmatched.map((one) => `unmatched ${one.key.type}:${one.key.externalId}: ` +
27
+ `${one.candidates.length ? `could be ${one.candidates.join(" or ")}` : one.reason}`),
28
+ ...run.errors.map((one) => `refused ${one.pointer} · ${one.message} (${one.code})`),
29
+ ...(run.truncated ? ["the lists stop at 1000 entries each; the counts are exact"] : []),
30
+ ].join("\n");
31
+ /** `records show`, `records delete`, `records clear` and `records match`: one record, a whole source, and its waiting identities. */
32
+ export const recordCommands = (records, { run, print }, withStore) => {
33
+ jsonOption(annotate(records.command("show"), { effects: LOCAL_READ, output: { entity: "source_record" } })
34
+ .argument("<record>", RECORD_HELP)
35
+ .option("--account <account>", ACCOUNT_HELP), "fields,relations,incoming,entity")
36
+ .description("one record as its source said it: its fields, the records it names, the records that name it (incoming, " +
37
+ `the first ${INCOMING}) and the entry made from it`)
38
+ .summary("one record as its source said it")
39
+ .action((record, given) => run(given.json, async (store) => {
40
+ const found = await storedRecord(store, given.account, record);
41
+ const incoming = await store.records.incoming(found, { limit: INCOMING + 1 });
42
+ return itemAnswer({
43
+ ...found,
44
+ incoming: { items: incoming.slice(0, INCOMING), hasMore: incoming.length > INCOMING },
45
+ });
46
+ }));
47
+ jsonOption(annotate(records.command("delete"), { effects: LOCAL_WRITE, output: { entity: "records_receipt" } })
48
+ .argument("<record>", RECORD_HELP)
49
+ .option("--account <account>", ACCOUNT_HELP), "deleted,flagged,errors")
50
+ .description("say a source no longer has a record, as an import's delete does: the record is kept as deleted, and the " +
51
+ "entry made from it stays, flagged for you to reject or keep")
52
+ .summary("mark a source's record deleted")
53
+ .action(async (record, given) => {
54
+ const receipt = await withStore(async (store) => {
55
+ const found = await storedRecord(store, given.account, record);
56
+ return ingest(store, {
57
+ schema_version: RECORDS_SCHEMA_VERSION,
58
+ source: {
59
+ provider: found.provider,
60
+ account: found.account,
61
+ batch_id: `delete-${new Date().toISOString()}`,
62
+ },
63
+ records: [
64
+ {
65
+ key: "delete",
66
+ type: found.type,
67
+ external_id: found.externalId,
68
+ operation: "delete",
69
+ ...(found.revision === null ? {} : { revision: found.revision }),
70
+ },
71
+ ],
72
+ }, { account: found.account });
73
+ });
74
+ const [refused] = receipt.errors;
75
+ if (refused)
76
+ throw new CliError(codeOf(refused.code), refused.message, { reason: refused.code });
77
+ print(given.json, itemAnswer(receipt), receipt.deleted === 0
78
+ ? `${record} was already deleted`
79
+ : `deleted ${record}${receipt.flagged.length ? `; ${receipt.flagged.map((one) => one.entity).join(" ")} kept, flagged for you` : ""}`);
80
+ });
81
+ jsonOption(annotate(records.command("clear"), {
82
+ effects: LOCAL_WRITE,
83
+ output: { entity: "records_clear" },
84
+ examples: ["wcat records clear --account n8n:test", "wcat records clear --account n8n:test --yes"],
85
+ })
86
+ .option("--account <account>", ACCOUNT_HELP)
87
+ .option("--yes", "confirm: nothing of the source can be brought back but by importing it again"), "account,records")
88
+ .description("delete everything one source said: its records, the leads, deals and pipelines made from them, and the people " +
89
+ "only it made. Anyone you tagged or gave a task to, or another source knows, stays; people delete " +
90
+ "removes them. For a test or a wrong import; a WireCat tool's account, such as tg or a CRM, is removed by " +
91
+ "that tool. Without --yes nothing changes")
92
+ .summary("delete a source's records and its leads and deals")
93
+ .action(async (given) => {
94
+ const source = sourceOf(given.account);
95
+ const name = `${source.provider}:${source.account}`;
96
+ const cleared = await withStore(async (store) => {
97
+ const tool = providerNamed(source.provider);
98
+ if (tool && !tool.imported)
99
+ throw new CliError("validation_error", `${name} is an account of ${tool.command ?? "a WireCat tool"}, not an import; remove it with that tool`, { reason: "records.clear-synced", account: name });
100
+ let held = 0;
101
+ for (;;) {
102
+ const page = await store.records.list({ ...source, limit: 500, offset: held });
103
+ held += page.items.length;
104
+ if (page.items.length < 500)
105
+ break;
106
+ }
107
+ if (held === 0)
108
+ throw new CliError("not_found", `no records from ${name}; records list shows a source's records`, {
109
+ reason: "records.not-stored",
110
+ account: name,
111
+ });
112
+ if (given.yes !== true)
113
+ throw new CliError("confirmation_required", `this deletes ${held} records of ${name} and its leads, deals and pipelines; nothing was changed — add --yes`, { reason: "records.clear-confirm", records: held });
114
+ await store.accounts.purge(source);
115
+ return { account: name, records: held };
116
+ });
117
+ print(given.json, itemAnswer(cleared), `cleared ${name}: ${cleared.records} records, with its leads, deals and pipelines`);
118
+ });
119
+ jsonOption(annotate(records.command("match"), { effects: LOCAL_WRITE, output: { entity: "records_match" } }).option("--account <account>", ACCOUNT_HELP), "linked,created,unmatched")
120
+ .description("link every waiting person, organization and project of a source to the one entry its e-mail, phone or other " +
121
+ "identifier names, or make one, as an import does; never by name. Two or more fits wait for records link")
122
+ .summary("match a source's waiting people and organizations")
123
+ .action((given) => withStore(async (store) => store.records.match(sourceOf(given.account))).then((found) => print(given.json, itemAnswer(found), matchText(found))));
124
+ };
125
+ //# sourceMappingURL=record-commands.js.map
@@ -0,0 +1,73 @@
1
+ import { grantedLevel } from "../mcp/granted.js";
2
+ import { readableDeal, readablePipeline } from "../store/crm-viewer.js";
3
+ const MOST = 100;
4
+ /** Each kind an import makes, and the read that tells where one came from. */
5
+ const READS = {
6
+ product: (store, ref) => store.products.get(ref),
7
+ contract: (store, ref) => store.contracts.get(ref),
8
+ subscription: (store, ref) => store.subscriptions.get(ref),
9
+ wallet: (store, ref) => store.wallets.get(ref),
10
+ transaction: (store, ref) => store.transactions.get(ref),
11
+ invoice: (store, ref) => store.finance.invoice(ref),
12
+ payment: (store, ref) => store.finance.payment(ref),
13
+ order: (store, ref) => store.orders.get(ref),
14
+ deal: readableDeal,
15
+ lead: readableDeal,
16
+ pipeline: (store, ref) => readablePipeline(store, ref),
17
+ };
18
+ export const SOURCED = new Set(Object.keys(READS));
19
+ export const readSourced = (store, kind, ref) => READS[kind]?.(store, ref);
20
+ const IMPORT = "import:";
21
+ /** Whether an import or a CRM made it, so its title is the source's words, not the owner's. */
22
+ export const imported = ({ source, account }) => (account ?? null) !== null || !!source?.startsWith(IMPORT);
23
+ /** The accounts whose records can be mapped to the entity: its CRM account, or every account of its import provider. */
24
+ export const sourceAccounts = async (store, { source, account }) => {
25
+ if (account)
26
+ return [account];
27
+ if (!source?.startsWith(IMPORT))
28
+ return [];
29
+ const provider = source.slice(IMPORT.length);
30
+ return (await store.accounts.accounts()).filter((key) => key.provider === provider);
31
+ };
32
+ const named = (key) => ({
33
+ record: `${key.type}:${key.externalId}`,
34
+ account: `${key.provider}:${key.account}`,
35
+ });
36
+ /**
37
+ * Where an entity came from: the records of its source's accounts mapped to it, and the live records of any account
38
+ * whose relations name it, such as a quote `quoted-for` a deal.
39
+ */
40
+ export const sourcesOf = async (store, entity) => {
41
+ const { ref } = entity;
42
+ const records = [];
43
+ for (const { provider, account } of await sourceAccounts(store, entity)) {
44
+ if (records.length > MOST)
45
+ break;
46
+ for (const one of (await store.records.list({ provider, account, entity: ref, limit: MOST + 1 })).items)
47
+ records.push({
48
+ ...named(one),
49
+ ...(one.flagged ? { flagged: true } : {}),
50
+ ...(one.deletedAt === null ? {} : { deleted: true }),
51
+ });
52
+ }
53
+ const incoming = await store.records.incoming({ entity: ref }, { limit: MOST + 1 });
54
+ return {
55
+ records: { items: records.slice(0, MOST), hasMore: records.length > MOST },
56
+ incoming: {
57
+ items: incoming.slice(0, MOST).map(({ record, role, as }) => ({ ...named(record), role, as })),
58
+ hasMore: incoming.length > MOST,
59
+ },
60
+ };
61
+ };
62
+ export const sourcesText = (ref, { records, incoming }, indent = " ") => [
63
+ ...records.items.map((one) => `${indent}from ${one.account} ${one.record}${one.flagged ? " (flagged)" : ""}${one.deleted ? " (deleted)" : ""}`),
64
+ ...incoming.items.map((one) => `${indent}named by ${one.account} ${one.record} as ${one.role}${one.as === null ? "" : ` (${one.as})`}`),
65
+ ...(records.hasMore || incoming.hasMore
66
+ ? [`${indent}more: wcat records list entity:${ref} --account <account>`]
67
+ : []),
68
+ ];
69
+ /** `sources` names source records, which `records show` reads: an MCP client denied that gets none. */
70
+ export const recordsHidden = (command) => grantedLevel(command, "records.show") === "deny";
71
+ /** An entity's `show` answer with where it came from beside it. */
72
+ export const withSources = async (command, store, item) => recordsHidden(command) ? item : { ...item, sources: await sourcesOf(store, item) };
73
+ //# sourceMappingURL=sources.js.map
package/dist/refs.js ADDED
@@ -0,0 +1,28 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ const BARE = /^\d+$/;
3
+ const either = (words) => words.length < 2 ? (words[0] ?? "") : `${words.slice(0, -1).join(", ")} or ${words.at(-1)}`;
4
+ /**
5
+ * An argument that takes several kinds refuses a bare number (NEED-2140 A): the same words would change meaning as
6
+ * the store grows. The refusal names only the references that exist, from one read of the store.
7
+ */
8
+ export const refuseBareNumber = async (store, text, kinds, options = {}) => {
9
+ const value = text.trim();
10
+ if (!BARE.test(value))
11
+ return;
12
+ const candidates = kinds.map((kind) => `${kind}:${value}`);
13
+ const found = await store.refs.summaries(candidates);
14
+ const existing = candidates.filter((ref) => {
15
+ const state = found.get(ref)?.state;
16
+ return state !== undefined && state !== "unavailable";
17
+ });
18
+ const guess = existing.length
19
+ ? `did you mean ${either(existing)}?`
20
+ : `no ${either(kinds.map((kind) => (kind === "msg" ? "message" : kind)))} has id ${value}`;
21
+ const path = options.path ? `; to read a file named ${value}, give its path: ./${value}` : "";
22
+ throw new CliError("validation_error", `"${value}" is a bare number; ${guess}${path}`, {
23
+ reason: "ref.bare-number",
24
+ value,
25
+ suggestion: existing[0] ?? candidates[0],
26
+ });
27
+ };
28
+ //# sourceMappingURL=refs.js.map