@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,120 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { parseLucene, validateQuery } from "@wirecat/cli-base/query";
3
+ import { PROJECTS_QUERY, parseLocator, } from "@wirecat/cli-core";
4
+ import { refuseBareNumber } from "../refs.js";
5
+ import { heldMessage } from "../store/held.js";
6
+ import { canonicalProject } from "../vocabulary/project.js";
7
+ const KEYABLE = /^(note|document|msg):/;
8
+ export const projectOf = async (store, reference) => {
9
+ try {
10
+ const wanted = await canonicalProject(store, /^[1-9]\d*$/.test(reference) ? `project:${reference}` : reference);
11
+ const query = validateQuery(parseLucene(`id:${wanted.slice(8)}`), PROJECTS_QUERY);
12
+ const project = (await store.knowledge.projects(query))[0];
13
+ if (project)
14
+ return project;
15
+ }
16
+ catch (error) {
17
+ if (!(error instanceof CliError) || error.code !== "not_found")
18
+ throw error;
19
+ }
20
+ throw new CliError("not_found", `no project ${reference}; wcat projects list shows them`, {
21
+ reason: "project.not-found",
22
+ });
23
+ };
24
+ /** A key mark is a `related-to` link from the source to the project, with the role `key` and the reason. */
25
+ const isKey = (link) => link.kind === "related-to" && link.role === "key";
26
+ const firstLine = (text) => text
27
+ .trim()
28
+ .split("\n")[0]
29
+ ?.replace(/^#+\s*/, "")
30
+ .slice(0, 120) || null;
31
+ const sourceOf = async (store, ref) => {
32
+ if (ref.startsWith("msg:")) {
33
+ const { provider, account, chat, message } = parseLocator(ref);
34
+ const held = await heldMessage(store, { provider, account }, message, chat);
35
+ return held && { title: firstLine(held.text), path: null };
36
+ }
37
+ const note = await store.notes.note(ref).catch(() => undefined);
38
+ return note && note.deletedAt === null ? { title: note.title ?? firstLine(note.text), path: note.path } : undefined;
39
+ };
40
+ const describe = async (store, link) => {
41
+ const source = await sourceOf(store, link.from);
42
+ return {
43
+ id: link.id,
44
+ ref: link.from,
45
+ title: source?.title ?? null,
46
+ path: source?.path ?? null,
47
+ reason: link.evidence,
48
+ available: source !== undefined,
49
+ confirmed: link.confirmed,
50
+ origin: link.origin,
51
+ provenance: link.provenance,
52
+ markedAt: link.createdAt,
53
+ };
54
+ };
55
+ const keyLinks = async (store, project, filter = {}) => store.notes.links({ ...filter, to: project.ref, kind: "related-to", role: "key" });
56
+ export const keyDocuments = async (store, project, filter) => Promise.all((await keyLinks(store, project, filter)).map((link) => describe(store, link)));
57
+ export const markKey = async (store, project, ref, reason, author) => {
58
+ await refuseBareNumber(store, ref, ["note", "document"]);
59
+ if (!KEYABLE.test(ref))
60
+ throw new CliError("validation_error", "a key document is a note:, document: or msg: reference");
61
+ const source = await sourceOf(store, ref);
62
+ if (source === undefined)
63
+ throw new CliError("not_found", `the store holds no ${ref}`);
64
+ if (author !== "owner")
65
+ return proposeKey(store, project, ref, reason, author, source);
66
+ const link = await store.notes.addLink({
67
+ from: ref,
68
+ to: project.ref,
69
+ kind: "related-to",
70
+ role: "key",
71
+ evidence: reason,
72
+ origin: "owner",
73
+ by: "owner",
74
+ });
75
+ if (!isKey(link))
76
+ throw new CliError("validation_error", `${ref} already relates to ${project.ref} as something else; wcat relationships remove ${link.id} first`);
77
+ return describe(store, link);
78
+ };
79
+ /** An agent's mark is a `key_document` proposal the owner decides in wcat review; the same pending one is reused. */
80
+ const proposeKey = async (store, project, ref, reason, author, source) => {
81
+ const { items: pending } = await store.proposedActions.list({
82
+ kinds: ["key_document"],
83
+ status: "proposed",
84
+ project: project.ref,
85
+ });
86
+ const proposal = pending.find((one) => one.payload?.ref === ref) ??
87
+ (await store.proposedActions.propose({
88
+ kind: "key_document",
89
+ by: author,
90
+ target: ref,
91
+ payload: { ref, project: project.ref, reason },
92
+ reason,
93
+ }));
94
+ return {
95
+ id: proposal.id,
96
+ ref,
97
+ title: source.title,
98
+ path: source.path,
99
+ reason: proposal.reason,
100
+ available: true,
101
+ confirmed: false,
102
+ origin: "suggested",
103
+ provenance: `agent:${proposal.proposedBy.name ?? author.bot}`,
104
+ markedAt: proposal.createdAt,
105
+ };
106
+ };
107
+ export const unmarkKey = async (store, project, ref, by) => {
108
+ await refuseBareNumber(store, ref, ["note", "document"]);
109
+ const link = (await keyLinks(store, project)).find((one) => one.from === ref);
110
+ if (!link)
111
+ throw new CliError("not_found", `${ref} is not a key document of ${project.ref}`);
112
+ await store.notes.removeLink(link.id, by);
113
+ return { ref, project: project.ref, removed: true };
114
+ };
115
+ /** The project's key items first, labelled `key`, in their own order; nothing else is dropped. */
116
+ export const keyFirst = (items, keys) => [
117
+ ...items.filter((item) => keys.has(item.ref)).map((item) => ({ ...item, key: true })),
118
+ ...items.filter((item) => !keys.has(item.ref)),
119
+ ];
120
+ //# sourceMappingURL=key-documents.js.map
@@ -0,0 +1,20 @@
1
+ import { queryFieldsOf } from "@wirecat/cli-base/query";
2
+ import * as v from "valibot";
3
+ export const keyDocument = v.strictObject({
4
+ id: v.string(),
5
+ ref: v.string(),
6
+ title: v.nullable(v.string()),
7
+ path: v.nullable(v.string()),
8
+ reason: v.nullable(v.string()),
9
+ available: v.boolean(),
10
+ confirmed: v.boolean(),
11
+ origin: v.picklist(["file", "owner", "suggested", "message"]),
12
+ provenance: v.nullable(v.string()),
13
+ marked_at: v.string(),
14
+ });
15
+ export const KEY_DOCUMENTS_QUERY = {
16
+ entity: "memo_key_document",
17
+ backend: "native",
18
+ fields: queryFieldsOf(keyDocument, { native: ["id"], examples: { id: "id:1" } }).map((field) => field.native ? { ...field, operators: ["term", "phrase"] } : field),
19
+ };
20
+ //# sourceMappingURL=list-queries.js.map
@@ -0,0 +1,61 @@
1
+ import { annotate } from "@wirecat/cli-base/commands";
2
+ import { LOCAL_READ, LOCAL_WRITE, queryTerms, termField, withQuery, } from "@wirecat/cli-core";
3
+ import { answers, itemAnswer, listAnswer } from "../answer.js";
4
+ import { positive } from "../options.js";
5
+ import { accountName, MEETING_ACCOUNT_HELP, MEETING_WRITE_HELP, sourceOptions, theAccount, writeAccount, writeOptions, } from "../store/source-list.js";
6
+ import { canonicalProject } from "../vocabulary/project.js";
7
+ const MEETING_PROJECTS_QUERY = {
8
+ entity: "meeting_project",
9
+ backend: "native",
10
+ fields: [termField("confirmed", "bool", "confirmed:false")],
11
+ defaults: ["confirmed:true"],
12
+ };
13
+ export const meetingProjectsCommand = (projects, streams, env) => {
14
+ const group = projects.command("meetings").description("explicit account-scoped project membership");
15
+ const options = (command) => sourceOptions(command, MEETING_ACCOUNT_HELP).option("--json", "print JSON; --json=id,title keeps only those fields");
16
+ const { run } = answers(projects, streams, env);
17
+ const warn = (text) => streams.diagnostic(text);
18
+ const execute = (project, options, work, writes = false) => run(options.json, async (store) => {
19
+ const key = await (writes ? writeAccount : theAccount)(store, env, options, warn);
20
+ return work(store, (await canonicalProject(store, project)).slice(8), key);
21
+ });
22
+ withQuery(options(annotate(group.command("list"), { effects: LOCAL_READ, output: { entity: "meeting_project" } })
23
+ .description("meetings linked to a project in one account, or with confirmed:false proposed")
24
+ .argument("<project>", "project reference, key or explicit alias")), MEETING_PROJECTS_QUERY)
25
+ .option("--limit <n>", "meetings per page, at most 500", positive, 50)
26
+ .option("--page <n>", "which page, from 1", positive)
27
+ .action((project, words, given) => execute(project, given, async (store, projectId, key) => {
28
+ const confirmed = queryTerms(words, MEETING_PROJECTS_QUERY, "projects meetings list").get("confirmed");
29
+ const page = given.page ?? 1;
30
+ const found = await store.knowledge.meetingProjects(key, {
31
+ projectId,
32
+ confirmed: confirmed === "true",
33
+ limit: given.limit,
34
+ offset: (page - 1) * given.limit,
35
+ });
36
+ return listAnswer("projects meetings list", {
37
+ items: found.items,
38
+ limit: given.limit,
39
+ has_more: found.hasMore,
40
+ page,
41
+ args: {
42
+ project,
43
+ source: accountName(key),
44
+ ...(words.length === 0 ? {} : { query: words.join(" ") }),
45
+ },
46
+ });
47
+ }));
48
+ writeOptions(annotate(group.command("link"), { effects: LOCAL_WRITE })
49
+ .description("link a stored meeting to a project, or confirm a proposed link")
50
+ .argument("<project>", "project reference, key or explicit alias")
51
+ .argument("<meeting-id>", "positive stored meeting id"), MEETING_WRITE_HELP)
52
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
53
+ .option("--fingerprint <hash>", "required when confirming an existing proposal")
54
+ .option("--reason <text>", "why the reviewed meeting belongs to this project")
55
+ .action((project, meeting, given) => execute(project, given, async (store, projectId, key) => itemAnswer(await store.knowledge.linkMeetingProject(key, meeting, projectId, {
56
+ by: "owner",
57
+ ...(given.fingerprint === undefined ? {} : { expectedFingerprint: given.fingerprint }),
58
+ ...(given.reason === undefined ? {} : { provenance: given.reason }),
59
+ })), true));
60
+ };
61
+ //# sourceMappingURL=meeting-projects-command.js.map
@@ -0,0 +1,253 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
3
+ import { delimiter, join } from "node:path";
4
+ import { resolvePaths } from "@wirecat/cli-base";
5
+ import { providerNamed } from "@wirecat/cli-core";
6
+ import { InvalidArgumentError } from "commander";
7
+ /** Where each WireCat messenger CLI keeps its state, by its command. Which CLI holds a provider is the registry's. */
8
+ const STATE = {
9
+ tg: { appName: "tg-cli", envPrefix: "TG" },
10
+ max: { appName: "max-cli", envPrefix: "MAX" },
11
+ wa: { appName: "whatsapp-cli", envPrefix: "WA" },
12
+ };
13
+ /** Each WireCat messenger CLI: its command, where it keeps its state and its variables' prefix. */
14
+ export const MESSENGER_TOOLS = Object.entries(STATE).map(([tool, state]) => ({ tool, ...state }));
15
+ /** The WireCat messenger CLI that holds a provider's connection, as the provider registry names it. */
16
+ export const messengerToolOf = (provider) => {
17
+ const tool = providerNamed(provider)?.command;
18
+ const state = tool === undefined ? undefined : STATE[tool];
19
+ return tool === undefined || state === undefined ? undefined : { tool, ...state };
20
+ };
21
+ /** `--sync-profile max=default`: the profile wcat runs a messenger CLI as, one per tool. */
22
+ export const syncProfileOf = (value, previous = {}) => {
23
+ const [tool, profile] = value.split("=", 2);
24
+ const tools = Object.keys(STATE);
25
+ if (!tool || !profile || !tools.includes(tool))
26
+ throw new InvalidArgumentError(`<tool>=<profile>, where the tool is ${tools.join(", ")}: max=default`);
27
+ if (previous[tool] !== undefined && previous[tool] !== profile)
28
+ throw new InvalidArgumentError(`one profile per tool; ${tool} is already ${previous[tool]}`);
29
+ return { ...previous, [tool]: profile };
30
+ };
31
+ const accountsDir = (tool, env) => join(resolvePaths({ appName: tool.appName, prefix: tool.envPrefix, env }).state, "accounts");
32
+ /** The account a messenger CLI's profile is signed in to, from its own record (`<state>/accounts/<profile>.json`). */
33
+ export const signedInAccount = (tool, profile, env) => {
34
+ try {
35
+ return JSON.parse(readFileSync(join(accountsDir(tool, env), `${profile}.json`), "utf8"))?.account;
36
+ }
37
+ catch {
38
+ return undefined;
39
+ }
40
+ };
41
+ /**
42
+ * The profile signed in to this account, from the CLI's own record of it (`<state>/accounts/<profile>.json`). wcat
43
+ * never picks one for the owner: one signed in is used, several or none is a refusal naming them, and a profile the
44
+ * owner chose with `--sync-profile` must be signed in to this account too.
45
+ */
46
+ export const profileFor = (provider, account, env, chosen = {}) => {
47
+ const tool = messengerToolOf(provider);
48
+ if (!tool)
49
+ return undefined;
50
+ const dir = accountsDir(tool, env);
51
+ const profiles = existsSync(dir)
52
+ ? readdirSync(dir)
53
+ .filter((name) => name.endsWith(".json"))
54
+ .map((name) => name.slice(0, -".json".length))
55
+ .sort()
56
+ : [];
57
+ const accountOf = (profile) => signedInAccount(tool, profile, env);
58
+ const all = profiles.join(", ") || "none";
59
+ const pick = chosen[tool.tool];
60
+ if (pick !== undefined) {
61
+ if (!profiles.includes(pick))
62
+ return { why: `${tool.tool} profile ${pick} is not signed in here; profiles: ${all}`, profiles };
63
+ const held = accountOf(pick);
64
+ return held === account
65
+ ? { profile: pick }
66
+ : { why: `${tool.tool} profile ${pick} is signed in to account ${String(held)}, not ${account}`, profiles: [] };
67
+ }
68
+ const matching = profiles.filter((profile) => accountOf(profile) === account);
69
+ if (matching.length === 1 && matching[0])
70
+ return { profile: matching[0] };
71
+ if (matching.length > 1)
72
+ return {
73
+ why: `${matching.length} ${tool.tool} profiles are signed in to account ${account}: ${matching.join(", ")}` +
74
+ ` — choose one with --sync-profile ${tool.tool}=<profile>`,
75
+ profiles: matching,
76
+ };
77
+ return { why: `no ${tool.tool} profile here is signed in to account ${account}; profiles: ${all}`, profiles: [] };
78
+ };
79
+ const onPath = (name, env) => (env.PATH ?? "")
80
+ .split(delimiter)
81
+ .filter(Boolean)
82
+ .map((dir) => join(dir, name))
83
+ .find((path) => {
84
+ try {
85
+ return statSync(path).isFile();
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ });
91
+ /** SIGINT first, as Ctrl-C: a sync stops after its page and keeps it. */
92
+ export const runChild = (command, args, { env, signal, onStderr }) => new Promise((resolve, reject) => {
93
+ const child = spawn(command, args, { env, stdio: ["ignore", "pipe", "pipe"] });
94
+ let stdout = "";
95
+ let pending = "";
96
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
97
+ stdout += chunk;
98
+ });
99
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
100
+ const lines = (pending + chunk).split("\n");
101
+ pending = lines.pop() ?? "";
102
+ for (const line of lines)
103
+ if (line)
104
+ onStderr?.(line);
105
+ });
106
+ let hard;
107
+ const stop = () => {
108
+ child.kill("SIGINT");
109
+ hard = setTimeout(() => child.kill("SIGTERM"), 10_000);
110
+ };
111
+ signal?.addEventListener("abort", stop, { once: true });
112
+ child.on("error", reject);
113
+ child.on("close", (code) => {
114
+ clearTimeout(hard);
115
+ signal?.removeEventListener("abort", stop);
116
+ if (pending)
117
+ onStderr?.(pending);
118
+ resolve({ code, stdout });
119
+ });
120
+ });
121
+ /**
122
+ * `wcat-<tool>` when it answers `--wcat-describe` as that tool, else the short name when its file is a WireCat
123
+ * package's (its real path, or the package manager's shim, names `@wirecat/<app>`). Another program by that name is
124
+ * never run.
125
+ */
126
+ export const binaryOf = async (provider, env, run) => {
127
+ const tool = messengerToolOf(provider);
128
+ return tool ? toolBinary(tool, env, run) : undefined;
129
+ };
130
+ /** `binaryOf` for any WireCat CLI by its command and package name, mail's too. */
131
+ export const toolBinary = async (tool, env, run) => {
132
+ const umbrella = onPath(`wcat-${tool.tool}`, env);
133
+ if (umbrella) {
134
+ const described = await run(umbrella, ["--wcat-describe"], { env }).catch(() => undefined);
135
+ try {
136
+ if (described?.code === 0 && JSON.parse(described.stdout)?.name === tool.tool)
137
+ return umbrella;
138
+ }
139
+ catch { }
140
+ }
141
+ const short = onPath(tool.tool, env);
142
+ if (!short)
143
+ return undefined;
144
+ const mark = `@wirecat/${tool.appName}`;
145
+ const real = realpathSync(short);
146
+ if (real.includes(`/${mark}/`))
147
+ return short;
148
+ return statSync(real).size < 65_536 && readFileSync(real, "utf8").includes(mark) ? short : undefined;
149
+ };
150
+ const answerOf = (stdout) => {
151
+ try {
152
+ return JSON.parse(stdout.trim().split("\n").at(-1) ?? "");
153
+ }
154
+ catch {
155
+ return {};
156
+ }
157
+ };
158
+ /** Leaves the child time to save its last page and answer before the budget ends. */
159
+ const MARGIN_MS = 5_000;
160
+ /**
161
+ * Syncs a linked chat by running its messenger CLI, `<bin> <profile> messages sync <chat> --since-time <start>`:
162
+ * wcat holds no messenger connection. What the child writes to stderr is passed on as it comes.
163
+ */
164
+ export const messengerFetcher = ({ env, note, chosen = {}, run = runChild, now = Date.now, }) => {
165
+ const binaries = new Map();
166
+ return {
167
+ fetch: async ({ account, chatId, after, until, signal }) => {
168
+ const tool = messengerToolOf(account.provider);
169
+ if (!tool)
170
+ return { state: "failed", reason: `no WireCat messenger CLI syncs ${account.provider}` };
171
+ const found = profileFor(account.provider, account.account, env, chosen);
172
+ if (!found || !("profile" in found))
173
+ return { state: "failed", reason: found?.why ?? "no profile" };
174
+ if (!binaries.has(tool.tool))
175
+ binaries.set(tool.tool, binaryOf(account.provider, env, run));
176
+ const bin = await binaries.get(tool.tool);
177
+ if (!bin)
178
+ return { state: "failed", reason: `${tool.tool} is not installed, or the one on PATH is not WireCat's` };
179
+ const seconds = Math.max(1, Math.floor((until - now() - MARGIN_MS) / 1000));
180
+ const args = [
181
+ found.profile,
182
+ "messages",
183
+ "sync",
184
+ "--since-time",
185
+ new Date(after).toISOString(),
186
+ "--limit",
187
+ "1000000",
188
+ "--timeout",
189
+ `${seconds}s`,
190
+ "--json",
191
+ chatId,
192
+ ];
193
+ const done = await run(bin, args, {
194
+ env,
195
+ signal,
196
+ onStderr: (line) => {
197
+ if (!isEvent(line))
198
+ note(`${tool.tool}: ${line}`);
199
+ },
200
+ });
201
+ const answer = answerOf(done.stdout);
202
+ if (done.code !== 0) {
203
+ const why = answer.error?.message?.split("\n")[0];
204
+ const code = answer.error?.code ?? `exit ${done.code ?? "signal"}`;
205
+ return {
206
+ state: "partial",
207
+ reason: `${tool.tool} ${found.profile} messages sync: ${code}${why ? ` — ${why}` : ""}`,
208
+ };
209
+ }
210
+ const item = answer.item ?? {};
211
+ if (item.issue?.code)
212
+ return { state: "partial", reason: item.issue.code };
213
+ if (item.stopped || signal.aborted)
214
+ return { state: "partial", reason: "fetch-budget" };
215
+ return item.complete || item.reached_since ? { state: "complete" } : { state: "partial", reason: "limit" };
216
+ },
217
+ };
218
+ };
219
+ /** With `--json` the child writes each progress event twice, as a JSON line and as a sentence: the sentence is kept. */
220
+ const isEvent = (line) => {
221
+ if (!line.startsWith("{"))
222
+ return false;
223
+ try {
224
+ return typeof JSON.parse(line)?.event === "string";
225
+ }
226
+ catch {
227
+ return false;
228
+ }
229
+ };
230
+ const chatCommand = (chat, words, env, chosen) => {
231
+ const tool = messengerToolOf(chat.provider);
232
+ if (!tool)
233
+ return null;
234
+ const found = profileFor(chat.provider, chat.account, env, chosen);
235
+ const line = (profile) => `${tool.tool} ${profile} ${words}`;
236
+ if (found && "profile" in found)
237
+ return { command: line(found.profile) };
238
+ return { command: null, line: line("<profile>"), why: found?.why ?? "no profile" };
239
+ };
240
+ /** The command that syncs one chat here, or why there is none: no profile, or more than one, for its account. */
241
+ export const chatSync = (chat, since, env, chosen = {}) =>
242
+ // A negative group id needs no `--`: no WireCat CLI has a digit short option.
243
+ chatCommand(chat, `messages sync ${chat.chat} --since-time ${since}`, env, chosen);
244
+ /** The command that reads one chat's stored messages from `since` (`YYYY-MM-DD`), one line each. */
245
+ export const chatRead = (chat, since, env, chosen = {}) => chatCommand(chat, `messages list --compact ${chat.chat} "date>=${since}"`, env, chosen);
246
+ /** `chatSync` as the plain text says it. */
247
+ export const syncHint = (chat, since, env, chosen = {}) => {
248
+ const sync = chatSync(chat, since, env, chosen);
249
+ if (!sync)
250
+ return null;
251
+ return sync.command ?? `${sync.line} (${sync.why})`;
252
+ };
253
+ //# sourceMappingURL=messenger-sync.js.map
@@ -0,0 +1,16 @@
1
+ import { sectionLines } from "./business-text.js";
2
+ const totalLine = ({ status, currency, rows, total, open }) => ` ${status} ${total} ${currency}${open === undefined ? "" : `, ${open} open`} (${rows})`;
3
+ /** Invoices, payments and orders as stored: a stage named "Won" is not a payment, and none is inferred. */
4
+ export const moneyLines = (money) => [
5
+ ...sectionLines("Invoices", money.invoices, (one) => ` ${one.title} ${one.ref} ${one.status} ${one.total} ${one.currency}, ${one.open} open ${one.review} ` +
6
+ `via ${one.linkedBy.join(", ")}`),
7
+ ...sectionLines("Payments", money.payments, (one) => ` ${one.title} ${one.ref} ${one.amount} ${one.currency} ${one.date} ${one.review}`),
8
+ ...(money.orders
9
+ ? sectionLines("Orders", money.orders, (one) => ` ${one.title} ${one.ref} ${one.status} ${[one.total, one.currency].filter(Boolean).join(" ")}`)
10
+ : []),
11
+ ...(money.totals.invoices.length ? ["Invoiced, confirmed", ...money.totals.invoices.map(totalLine)] : []),
12
+ ...(money.totals.payments.length ? ["Paid, confirmed", ...money.totals.payments.map(totalLine)] : []),
13
+ ...(money.unconfirmed ? [` ${money.unconfirmed} not confirmed yet — not in the totals`] : []),
14
+ ...(money.complete ? [] : [" more rows than one read: the totals may leave some out"]),
15
+ ];
16
+ //# sourceMappingURL=money-text.js.map
@@ -0,0 +1,81 @@
1
+ import { formatReference } from "@wirecat/cli-core";
2
+ /** A file in a notes folder is a `document:`, a written note a `note:`. */
3
+ export const isNoteReference = (reference) => /^(note|document):/.test(reference);
4
+ const fold = (value) => value.normalize("NFC").toLocaleLowerCase("en").trim().replace(/^@/, "");
5
+ const refOf = (note, anchor = null) => ({
6
+ ref: note.ref,
7
+ source: note.source,
8
+ folderId: note.folderId,
9
+ path: note.path,
10
+ title: note.title,
11
+ modifiedAt: note.modifiedAt ?? note.updatedAt,
12
+ ...(anchor === null ? {} : { anchor }),
13
+ });
14
+ const PAGE = 500;
15
+ /** cli-core's list reader names a notes folder or a documents account as `notes:<id>`, never by its own provider. */
16
+ export const holdsFolder = (scope) => (id) => scope === undefined || scope.some((one) => one.provider === "notes" && one.account === id);
17
+ /**
18
+ * Every live note that reaches a subject through the links the store holds — never a name found in plain text — in a
19
+ * folder of `scope`. The owner's own notes belong to no folder, so every scope reads them.
20
+ */
21
+ export const notesReaching = async (store, subject, scope) => {
22
+ const inScope = holdsFolder(scope);
23
+ const kept = (note) => note.deletedAt === null && (note.folderId === null || inScope(note.folderId));
24
+ const refs = [
25
+ subject.ref,
26
+ ...(subject.person?.identities.map((identity) => formatReference({ type: "contact", provider: identity.provider, id: identity.id })) ?? []),
27
+ ];
28
+ const live = async (links, via) => {
29
+ const found = [];
30
+ for (const link of links) {
31
+ if (!isNoteReference(link.from))
32
+ continue;
33
+ const note = await store.notes.resolveNote(link.from);
34
+ if (note && kept(note))
35
+ found.push({ note, anchor: link.anchor, text: link.targetText, via });
36
+ }
37
+ return found;
38
+ };
39
+ const aboutOne = async (ref) => {
40
+ const notes = [];
41
+ for (let offset = 0;; offset += PAGE) {
42
+ const page = await store.notes.notes({ about: ref, limit: PAGE, offset });
43
+ notes.push(...page.items.filter(kept));
44
+ if (!page.hasMore)
45
+ return notes;
46
+ }
47
+ };
48
+ // A written note's first subject is the note's own, not a link, so only `notes({ about })` sees all of them.
49
+ const about = (await Promise.all(refs.map(aboutOne)))
50
+ .flat()
51
+ .map((note) => ({ note, anchor: null, text: null, via: "about" }));
52
+ const linking = await live((await Promise.all(refs.map((to) => store.notes.links({ to })))).flat().filter((link) => link.kind === "links-to"), "link");
53
+ const through = await live((await Promise.all(about.map(({ note }) => store.notes.links({ to: note.ref }))))
54
+ .flat()
55
+ .filter((link) => link.kind === "links-to"), "through");
56
+ const names = new Set([subject.person?.name, ...(subject.person?.identities.map(({ name }) => name) ?? [])]
57
+ .filter((name) => !!name?.trim())
58
+ .map(fold));
59
+ const waiting = names.size === 0
60
+ ? []
61
+ : await live((await store.notes.links({ unresolved: true })).filter((link) => names.has(fold(link.targetText ?? ""))), "name");
62
+ return [...about, ...linking, ...through, ...waiting];
63
+ };
64
+ /** What notes say about a subject, split by how each reaches it. */
65
+ export const notesAbout = async (store, subject, limit = 20, scope) => {
66
+ const found = await notesReaching(store, subject, scope);
67
+ const unique = (via) => [
68
+ ...new Map(found.filter((item) => item.via === via).map((item) => [`${item.note.ref}#${item.anchor ?? ""}`, item])).values(),
69
+ ].sort((a, b) => refOf(b.note).modifiedAt.localeCompare(refOf(a.note).modifiedAt));
70
+ const [about, linking, through, waiting] = ["about", "link", "through", "name"].map(unique);
71
+ return {
72
+ subject: subject.ref,
73
+ name: subject.person?.name ?? null,
74
+ about: (about ?? []).slice(0, limit).map(({ note }) => refOf(note)),
75
+ linking: (linking ?? []).slice(0, limit).map(({ note, anchor }) => refOf(note, anchor)),
76
+ throughNotes: (through ?? []).slice(0, limit).map(({ note, anchor }) => refOf(note, anchor)),
77
+ waiting: (waiting ?? []).slice(0, limit).map(({ note, text }) => ({ ...refOf(note), text: text ?? "" })),
78
+ hasMore: [about, linking, through, waiting].some((list) => (list ?? []).length > limit),
79
+ };
80
+ };
81
+ //# sourceMappingURL=notes-about.js.map
@@ -0,0 +1,44 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { LOCAL_WRITE } from "@wirecat/cli-core";
4
+ import { answers, itemAnswer, withStore } from "../answer.js";
5
+ import { byOption } from "../author.js";
6
+ import { asOwner } from "../people/proposal-rows.js";
7
+ const counts = (rows) => Object.entries(rows)
8
+ .map(([where, n]) => `${n} ${where}`)
9
+ .join(", ");
10
+ const planText = (plan) => [
11
+ `${plan.erased ? "deleted" : "this deletes"} ${plan.organization} (${plan.name})`,
12
+ ...(plan.identities.length ? [` identities it held: ${plan.identities.join(", ")}`] : []),
13
+ ...(Object.keys(plan.deleted).length ? [` deleted with it: ${counts(plan.deleted)}`] : []),
14
+ ...(Object.keys(plan.detached).length ? [` stay, without the organization: ${counts(plan.detached)}`] : []),
15
+ ].join("\n");
16
+ export const organizationDeleteCommand = (organizations, program, streams, env) => {
17
+ const { print } = answers(program, streams, env);
18
+ byOption(annotate(organizations.command("delete"), {
19
+ effects: LOCAL_WRITE,
20
+ output: { entity: "organization_erasure" },
21
+ examples: ["wcat organizations delete organization:12", "wcat organizations delete organization:12 --yes"],
22
+ })
23
+ .summary("delete an organization and what wcat knows of it alone; only you")
24
+ .description("delete an organization, your notes about it, the tags, links, aliases and mentions that name it, and which " +
25
+ "identities it held. A deal, lead, project, account or fact that names it stays and loses the name; a note " +
26
+ "that only links to it stays. One of your own " +
27
+ "companies is never deleted, and an invoice, order or subscription that names it must be changed first. " +
28
+ "Without --yes it shows what would go and changes nothing")
29
+ .argument("<organization>", "its id or organization:<id>, as organizations list prints it")
30
+ .option("--yes", "delete; nothing of the organization can be brought back"))
31
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
32
+ .action(async (reference, options, command) => {
33
+ const organization = `organization:${reference.replace(/^organization:/, "")}`;
34
+ const by = await asOwner(command, env, `delete ${organization}?`);
35
+ const plan = await withStore(env, (store) => store.knowledge.eraseOrganization(organization, by, { apply: options.yes === true }));
36
+ if (!plan.erased)
37
+ throw new CliError("confirmation_required", `${planText(plan)}\nnothing was changed — add --yes`, {
38
+ reason: "organization.delete-confirm",
39
+ plan,
40
+ });
41
+ print(options.json, itemAnswer(plan), planText(plan));
42
+ });
43
+ };
44
+ //# sourceMappingURL=organization-delete-command.js.map
@@ -0,0 +1,27 @@
1
+ import { timezone } from "../answer.js";
2
+ import { touchLine } from "../context/command.js";
3
+ import { coverageLines, sectionLines } from "./business-text.js";
4
+ import { moneyLines } from "./money-text.js";
5
+ export const organizationText = (answer) => {
6
+ const { organization, categories, communications } = answer;
7
+ return [
8
+ `${organization.name} ${organization.ref}${organization.own ? " (your own)" : ""}`,
9
+ ...(categories.length ? [`Categories ${categories.join(", ")}`] : []),
10
+ ...(answer.tags.length ? [`Tags ${answer.tags.join(", ")}`] : []),
11
+ ...sectionLines("People", answer.people),
12
+ ...sectionLines("Customers", answer.customers),
13
+ ...sectionLines("Suppliers", answer.suppliers),
14
+ ...sectionLines("Partners", answer.partners),
15
+ ...sectionLines("Projects", answer.projects, (one) => ` ${one.name} ${one.ref} via ${one.via.join(", ")}`),
16
+ ...sectionLines("Open deals and leads", answer.deals, (one) => ` ${one.title} ${one.ref} ${one.stage} ${[one.amount, one.currency].filter(Boolean).join(" ")}`),
17
+ ...moneyLines(answer.money),
18
+ `Written by its people ${communications.messages} messages, ${communications.mail} emails, ${communications.meetings} meetings`,
19
+ ...sectionLines(`History, times in ${timezone()}`, answer.history, touchLine),
20
+ ...sectionLines("Open tasks", answer.tasks, (one) => ` ${one.key} ${one.title} ${one.status}`),
21
+ ...(answer.notes.about.length ? ["Notes about it", ...answer.notes.about.map((note) => ` ${note.ref}`)] : []),
22
+ ...coverageLines(answer.coverage),
23
+ ]
24
+ .map((line) => line.trimEnd())
25
+ .join("\n");
26
+ };
27
+ //# sourceMappingURL=organization-text.js.map