@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
package/dist/author.js ADDED
@@ -0,0 +1,109 @@
1
+ import { openSync } from "node:fs";
2
+ import { createInterface } from "node:readline";
3
+ import { ReadStream } from "node:tty";
4
+ import { CliError } from "@wirecat/cli-base";
5
+ import { environmentOf } from "@wirecat/cli-core";
6
+ import { terminalOf } from "./terminal.js";
7
+ /**
8
+ * The bot a run is recorded as when nothing names who runs it: no agent variable, and no person at a terminal. A
9
+ * missing variable proves nothing; such a run proposes, and never decides.
10
+ */
11
+ export const UNATTENDED = "unattended";
12
+ /** Read from the terminal itself, not stdin, which may hold the command's input. */
13
+ const fromTerminal = async (question) => {
14
+ if (!process.stdin.isTTY || !process.stderr.isTTY)
15
+ return null;
16
+ let input;
17
+ try {
18
+ input = new ReadStream(openSync("/dev/tty", "r"));
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ const reader = createInterface({ input, output: process.stderr, terminal: true });
24
+ try {
25
+ return await new Promise((resolve, reject) => {
26
+ const cancel = () => reject(new CliError("cancelled", "cancelled — nothing was done"));
27
+ reader.once("SIGINT", cancel);
28
+ reader.once("close", cancel);
29
+ reader.question(question, resolve);
30
+ });
31
+ }
32
+ finally {
33
+ reader.close();
34
+ input.destroy();
35
+ }
36
+ };
37
+ /**
38
+ * The agent named by the variables cli-base's skill hint reads. `AI_AGENT` carries a version
39
+ * (`claude-code_2-1-296_agent`); one bot per release would split the agent's history, so only the name before it is
40
+ * kept.
41
+ */
42
+ const agentIn = (env) => {
43
+ if (env.AI_AGENT === "wcat-mcp")
44
+ return env.WCAT_MCP_CLIENT?.trim() || "wcat-mcp";
45
+ const agent = env.AI_AGENT?.trim().split("_")[0];
46
+ if (agent)
47
+ return agent;
48
+ return env.CLAUDECODE ? "claude-code" : undefined;
49
+ };
50
+ /** Who writes, by the environment alone; for writes that decide nothing for the owner, such as a task edit. */
51
+ export const authorOf = (env) => {
52
+ const agent = agentIn(env);
53
+ return agent === undefined ? "owner" : { bot: agent };
54
+ };
55
+ const ownerSays = async (command, question) => {
56
+ const machine = command.opts().json !== undefined;
57
+ // A harness that gives an agent a terminal would wait for ever on a question under --json.
58
+ const answer = terminalOf(command).present && !machine
59
+ ? await (terminalOf(command).answer ?? environmentOf(command).answer ?? fromTerminal)(`${question} [y/N] `)
60
+ : null;
61
+ if (answer === null)
62
+ throw new CliError("confirmation_required", "--as-owner asks at a terminal, and nobody is at one to answer; the owner runs it there, without --json", { reason: "decision.owner-unconfirmed" });
63
+ if (!/^\s*y(es)?\s*$/i.test(answer))
64
+ throw new CliError("cancelled", "not done — the answer was no");
65
+ };
66
+ /** A run for an agent through wcat's MCP server: its stdin is the server's, and its files are this computer's. */
67
+ export const isMcpRun = (command, env) => environmentOf(command).agent !== undefined || env.AI_AGENT === "wcat-mcp";
68
+ /**
69
+ * Who runs this command. An MCP call is the agent's. `--from-app` is the owner's: the app says the owner clicked, and
70
+ * wcat takes its word, even with an agent variable set (NEED-2403). An agent's terminal is the agent's; `--as-owner`
71
+ * there makes it the owner's only after a yes at a real terminal. With no agent named, the owner only when stdin and
72
+ * stdout are a terminal: anything else is an unattended run, recorded as one.
73
+ */
74
+ export const whoRuns = async (command, env, { asOwner = false, question }) => {
75
+ if (isMcpRun(command, env)) {
76
+ if (asOwner)
77
+ throw new CliError("permission_error", "an agent cannot act as the owner; the owner runs this command");
78
+ return { bot: agentIn(env) ?? "wcat-mcp" };
79
+ }
80
+ if (command.opts().fromApp)
81
+ return "owner";
82
+ const agent = agentIn(env);
83
+ if (agent === undefined && terminalOf(command).present)
84
+ return "owner";
85
+ if (!asOwner)
86
+ return { bot: agent ?? UNATTENDED };
87
+ await ownerSays(command, question);
88
+ return "owner";
89
+ };
90
+ /** The decider a store decide method takes. An unattended run is refused: it could be anyone, its own proposer too. */
91
+ export const deciderOf = async (command, env, { asOwner, reason, question }) => {
92
+ const who = await whoRuns(command, env, { asOwner, question });
93
+ if (who === "owner")
94
+ return "owner";
95
+ if (who.bot === UNATTENDED)
96
+ throw new CliError("confirmation_required", "no agent is named and nobody is at a terminal, so nothing shows who decides; the owner decides at a " +
97
+ "terminal, an agent from its own session with --reason", { reason: "decision.decider-unknown" });
98
+ if (!reason?.trim())
99
+ throw new CliError("validation_error", "an agent deciding for the owner gives --reason", {
100
+ reason: "proposal.reason-required",
101
+ param: "reason",
102
+ });
103
+ return { bot: who.bot, reason: reason.trim() };
104
+ };
105
+ /** An app's claim, not a check: anything that runs wcat can pass it, so it is no security boundary. */
106
+ export const fromAppOption = (command) => command.option("--from-app", "you did this in WireCat Desktop: record it as yours, with no terminal question");
107
+ export const byOption = (command) => fromAppOption(command.option("--as-owner", "act as you although an agent's terminal runs wcat (AI_AGENT or CLAUDECODE set); asks y/N at the terminal"));
108
+ export const reasonOption = (command) => command.option("--reason <text>", "why, in a few words; required when an agent decides for you");
109
+ //# sourceMappingURL=author.js.map
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ // cli-dev bundle loader
3
+ import * as module from "node:module"
4
+
5
+ const words = process.argv.slice(2)
6
+ // As the CLI answers it, unless a test records the argv: then the CLI writes the record too.
7
+ if (
8
+ words.length === 1 &&
9
+ (words[0] === "--version" || words[0] === "-V") &&
10
+ !Object.keys(process.env).some((key) => key.endsWith("_TEST_ARGV_LOG"))
11
+ ) {
12
+ process.stdout.write("1.1.0\n")
13
+ } else {
14
+ // Before the bundle compiles: the bundle's own call comes after its chunks.
15
+ module.enableCompileCache()
16
+ const serves = ((words) => {
17
+ const plain = words.filter((word) => !word.startsWith("-"));
18
+ return plain.slice(0, 4).some((word, at) => word === "serve" || word === "watch" || word === "mcp" && plain[at + 1] === void 0);
19
+ })(words)
20
+ if (serves && module.registerHooks) {
21
+ const bundle = new URL("../bundle/", import.meta.url).href
22
+ module.registerHooks({
23
+ resolve: (specifier, context, next) =>
24
+ specifier.startsWith("./") && context.parentURL?.startsWith(bundle)
25
+ ? { url: new URL(specifier, context.parentURL).href, format: "module", shortCircuit: true }
26
+ : next(specifier, context),
27
+ })
28
+ }
29
+ const chunks = ["../bundle/auto-O24ISPOI.js","../bundle/entry-EW5A7FYV.js","../bundle/failure-HMELJ3K5.js","../bundle/from-memo-F7NTUXAR.js","../bundle/program-7XWGFN4H.js","../bundle/server-T7RVBNRW.js","../bundle/update-JZDS7B6L.js"]
30
+ const preload = () =>
31
+ Promise.allSettled([
32
+ ...chunks.map((chunk) => import(chunk)),
33
+ ...["@wirecat/cli-core/preload","@wirecat/cli-base/preload"].map((name) => import(name).then((loaded) => loaded.preload())),
34
+ ])
35
+ if (((words) => words.filter((word) => !word.startsWith("-")).slice(0, 2).includes("upgrade"))(words)) await preload()
36
+ const running = import("../bundle/wcat-wirecat.js")
37
+ // After the server answers its first request, so it starts no later.
38
+ if (serves) setTimeout(() => void preload(), 2000).unref()
39
+ await running
40
+ }
@@ -0,0 +1,175 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { BOT_SENDS, LOCAL_READ, LOCAL_WRITE, queryTerms, SENDER_BOT_PREFIX, senderBotRef, termField, withQuery, } from "@wirecat/cli-core";
4
+ import { answers, itemAnswer, listAnswer, withStore } from "../answer.js";
5
+ import { byOption } from "../author.js";
6
+ import { oneOf, positive } from "../options.js";
7
+ import { withOwner } from "../people/owner.js";
8
+ import { asOwner } from "../people/proposal-rows.js";
9
+ import { groupOf } from "../store/group.js";
10
+ const botRow = (bot) => ({
11
+ ref: bot.bot,
12
+ name: bot.name,
13
+ display_name: bot.displayName,
14
+ organization: bot.organization,
15
+ author: bot.author,
16
+ reason: bot.reason,
17
+ identities: bot.identities.map(({ provider, id, name, username }) => ({
18
+ identity: `${provider}:${id}`,
19
+ name,
20
+ username,
21
+ })),
22
+ messages_from: bot.messagesFrom,
23
+ last_contact: bot.lastContact,
24
+ reach: bot.reach,
25
+ signals: bot.signals,
26
+ });
27
+ const moveRow = (move) => ({
28
+ identity: `${move.identity.provider}:${move.identity.id}`,
29
+ from: move.from,
30
+ to: move.to,
31
+ author: move.author,
32
+ reason: move.reason,
33
+ at: move.at,
34
+ });
35
+ // The store counts a bot's messages over every account, so a group's run would see more than its group (WC-ACCT-13).
36
+ const refuseInGroup = (env, command) => {
37
+ const group = groupOf(env);
38
+ if (group !== undefined)
39
+ throw new CliError("validation_error", `${command} reads every account; run it without group ${group.name}`, {
40
+ reason: "bots.whole-store",
41
+ });
42
+ };
43
+ // `sender-bot:<id>` is what wcat printed before cli-core 2.0; it still names the bot.
44
+ const BOT = /^(bot|sender-bot):[1-9]\d*$/;
45
+ const PERSON = /^person:([1-9]\d*|me)$/;
46
+ const IDENTITY = /^([a-z][a-z0-9-]*):(.+)$/;
47
+ /**
48
+ * Exactly what the owner typed: a move takes a whole history, so a name never resolves to the nearest sender. A bare
49
+ * address is a mail identity.
50
+ */
51
+ const subjectOf = (typed) => {
52
+ const text = typed.trim();
53
+ if (BOT.test(text))
54
+ return senderBotRef(text);
55
+ if (PERSON.test(text))
56
+ return text;
57
+ if (!text.includes(":") && text.includes("@"))
58
+ return { provider: "email", id: text.toLowerCase() };
59
+ const match = IDENTITY.exec(text);
60
+ if (match === null)
61
+ throw new CliError("validation_error", `"${typed}" is not ${SENDER_BOT_PREFIX}<id>, person:<uid>, an address or <messenger>:<id>`, { reason: "identity.no-messenger", param: "who" });
62
+ const [, provider = "", id = ""] = match;
63
+ return { provider, id: provider === "email" ? id.toLowerCase() : id };
64
+ };
65
+ const shownAs = (subject) => typeof subject === "string" ? subject : `${subject.provider}:${subject.id}`;
66
+ const KINDS = ["bot", "person"];
67
+ export const botsCommand = (program, streams, env) => {
68
+ const { print } = answers(program, streams, env);
69
+ const bots = program
70
+ .command("bots")
71
+ .description("programs that write to you, apart from people: no-reply and alert addresses, a service's mail, a messenger's " +
72
+ "bot. Not agents (agents list)")
73
+ .summary("programs that write to you, apart from people");
74
+ const query = {
75
+ entity: "sender_bot",
76
+ backend: "native",
77
+ fields: [
78
+ termField("name", "txt", "name:shop"),
79
+ termField("organization", "ref", 'organization:"organization:3"'),
80
+ termField("type", "enum", "type:receipts", { values: Object.keys(BOT_SENDS) }),
81
+ ],
82
+ };
83
+ withQuery(annotate(bots.command("list"), { effects: LOCAL_READ })
84
+ .summary("the bots, by name")
85
+ .description("the bots, by name: each with its identities, its organization, who sorted it (rules or you), its reach and " +
86
+ "the messages and mail it sent. type: is what a bot sends: alerts (security codes, sign-in and system " +
87
+ "alerts, account notices), receipts (orders, bills, shipping), newsletters, marketing, or messenger (a bot " +
88
+ "in a messenger)"), query)
89
+ .option("--limit <n>", "most bots on a page, up to 5000", positive, 500)
90
+ .option("--page <n>", "which page, from 1", positive, 1)
91
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
92
+ .action(async (words, options) => {
93
+ refuseInGroup(env, "bots list");
94
+ const terms = queryTerms(words, query, "bots list");
95
+ const name = terms.get("name");
96
+ const organization = terms.get("organization");
97
+ const type = terms.get("type");
98
+ const limit = Math.min(options.limit, 5000);
99
+ const found = await withStore(env, (store) => store.people.listBots({
100
+ limit,
101
+ offset: (options.page - 1) * limit,
102
+ ...(name === undefined ? {} : { query: name }),
103
+ ...(organization === undefined ? {} : { organization }),
104
+ ...(type === undefined ? {} : { sends: [type] }),
105
+ }));
106
+ print(options.json, listAnswer("bots list", {
107
+ items: found.items.map(botRow),
108
+ limit,
109
+ has_more: found.hasMore,
110
+ page: options.page,
111
+ total: { value: found.total, relation: "eq" },
112
+ args: words.length ? { query: words.join(" ") } : {},
113
+ }));
114
+ });
115
+ annotate(bots.command("show"), { effects: LOCAL_READ })
116
+ .summary("one bot with every move to or from it")
117
+ .description("one bot: its identities, organization and counts, and every move between it and a person, oldest first")
118
+ .argument("<bot>", `${SENDER_BOT_PREFIX}<id> as bots list prints it`)
119
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
120
+ .action(async (bot, options) => {
121
+ refuseInGroup(env, "bots show");
122
+ const shown = await withStore(env, (store) => store.people.showBot(bot.trim()));
123
+ const row = { ...botRow(shown), moves: shown.moves.map(moveRow) };
124
+ print(options.json, itemAnswer(row), [
125
+ `${row.ref} ${row.display_name ?? ""}`.trim(),
126
+ ...(row.organization ? [` organization: ${row.organization}`] : []),
127
+ ...row.identities.map(({ identity, name }) => ` ${identity}${name ? ` ${name}` : ""}`),
128
+ ...row.moves.map(({ identity, from, to, author, at }) => ` moved ${identity}: ${from ?? "none"} → ${to ?? "none"} by ${author}, ${at.slice(0, 10)}`),
129
+ ].join("\n"));
130
+ });
131
+ byOption(annotate(bots.command("move"), { effects: LOCAL_WRITE })
132
+ .summary("say a sender is a program or a person, for its whole history; only you")
133
+ .description("your word that a sender is a program (--kind bot) or a person (--kind person). Its whole history moves, past " +
134
+ "and future: every message and mail it sent stays where it is and now counts for the bot or the person, and " +
135
+ "no rule moves it back. The move is logged in bots show; moving it the other way undoes it, and a person " +
136
+ "moved back keeps their person:<uid>. Only you, never an agent")
137
+ .argument("<who>", `${SENDER_BOT_PREFIX}<id>, person:<uid>, an address, or <messenger>:<id> exactly as people show prints it`)
138
+ .requiredOption("--kind <kind>", "what the sender is: bot or person", oneOf(KINDS))
139
+ .option("--into <id>", `the ${SENDER_BOT_PREFIX}<id> or person:<uid> it joins, instead of a bot of its own or the person it came from`)
140
+ .option("--name <name>", "with --kind bot: what to call a new bot")
141
+ .option("--reason <text>", "why, kept in the move log"))
142
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
143
+ .action(async (who, options, command) => {
144
+ refuseInGroup(env, "bots move");
145
+ const into = options.into?.trim();
146
+ if (into !== undefined && !(options.kind === "bot" ? BOT : PERSON).test(into))
147
+ throw new CliError("validation_error", `--kind ${options.kind} joins a ${options.kind === "bot" ? `${SENDER_BOT_PREFIX}<id>` : "person:<uid>"}`, { param: "into" });
148
+ if (options.kind === "person" && options.name !== undefined)
149
+ throw new CliError("validation_error", "--name goes with --kind bot", { param: "name" });
150
+ const subject = subjectOf(who);
151
+ const by = await asOwner(command, env, `move ${shownAs(subject)} and its whole history to a ${options.kind}?`);
152
+ const reason = options.reason?.trim();
153
+ const moved = await withStore(env, async (store) => {
154
+ const who = typeof subject === "string" ? await withOwner(store, subject) : subject;
155
+ if (options.kind === "bot") {
156
+ const bot = await store.people.moveToBot(who, by, {
157
+ ...(into === undefined ? {} : { bot: into }),
158
+ ...(options.name === undefined ? {} : { name: options.name }),
159
+ ...(reason ? { reason } : {}),
160
+ });
161
+ return { ref: bot.bot, name: bot.displayName ?? bot.name };
162
+ }
163
+ const person = await store.people.moveToPerson(who, by, {
164
+ ...(into === undefined ? {} : { person: into }),
165
+ ...(reason ? { reason } : {}),
166
+ });
167
+ return { ref: `person:${person.uid}`, name: person.displayName ?? person.name ?? null };
168
+ });
169
+ const row = { moved: shownAs(subject), kind: options.kind, ref: moved.ref, name: moved.name, history: "whole" };
170
+ const back = options.kind === "bot" ? "person" : "bot";
171
+ print(options.json, itemAnswer(row), `moved ${row.moved} to ${row.ref}${row.name ? ` (${row.name})` : ""} with its whole history, past and ` +
172
+ `future; wcat bots move ${row.ref} --kind ${back} moves it back`);
173
+ });
174
+ };
175
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1,43 @@
1
+ import { createRequire as __bundleRequire } from "node:module";
2
+ const require = __bundleRequire(import.meta.url);
3
+ import {
4
+ DEFAULT_EVERY,
5
+ PLACE_VARIABLES,
6
+ UNIT,
7
+ applyAuto,
8
+ autoCommand,
9
+ autoNotice,
10
+ autoState,
11
+ followInstall,
12
+ globalRoots,
13
+ interval,
14
+ lastAutoRun,
15
+ placesOf,
16
+ recordAutoRun,
17
+ serviceUnit,
18
+ timerUnit,
19
+ unitDir
20
+ } from "./chunk-6BDIFKF5.js";
21
+ import "./chunk-7O7XM37N.js";
22
+ import "./chunk-FGXUH3XL.js";
23
+ import "./chunk-T7TG4JKR.js";
24
+ import "./chunk-I5JQBRRC.js";
25
+ import "./chunk-SCDNOUUR.js";
26
+ export {
27
+ DEFAULT_EVERY,
28
+ PLACE_VARIABLES,
29
+ UNIT,
30
+ applyAuto,
31
+ autoCommand,
32
+ autoNotice,
33
+ autoState,
34
+ followInstall,
35
+ globalRoots,
36
+ interval,
37
+ lastAutoRun,
38
+ placesOf,
39
+ recordAutoRun,
40
+ serviceUnit,
41
+ timerUnit,
42
+ unitDir
43
+ };
@@ -0,0 +1,31 @@
1
+ import { createRequire as __bundleRequire } from "node:module";
2
+ const require = __bundleRequire(import.meta.url);
3
+ import {
4
+ __name
5
+ } from "./chunk-SCDNOUUR.js";
6
+
7
+ // dist/terminal.js
8
+ var MACHINE_FLAGS = /* @__PURE__ */ new Set(["--json", "--jsonl"]);
9
+ var optionsOf = /* @__PURE__ */ __name((args) => {
10
+ const end = args.indexOf("--");
11
+ return end < 0 ? args : args.slice(0, end);
12
+ }, "optionsOf");
13
+ var interactiveOf = /* @__PURE__ */ __name((args, tty) => tty && !optionsOf(args).some((flag) => MACHINE_FLAGS.has(flag)), "interactiveOf");
14
+ var terminals = /* @__PURE__ */ new WeakMap();
15
+ var processTerminal = /* @__PURE__ */ __name(() => ({ present: Boolean(process.stdin.isTTY && process.stdout.isTTY) }), "processTerminal");
16
+ var provideTerminal = /* @__PURE__ */ __name((program, terminal) => {
17
+ terminals.set(program, terminal ?? processTerminal());
18
+ }, "provideTerminal");
19
+ var terminalOf = /* @__PURE__ */ __name((command) => {
20
+ let root = command;
21
+ while (root.parent)
22
+ root = root.parent;
23
+ return terminals.get(root) ?? { present: false };
24
+ }, "terminalOf");
25
+
26
+ export {
27
+ optionsOf,
28
+ interactiveOf,
29
+ provideTerminal,
30
+ terminalOf
31
+ };
@@ -0,0 +1,222 @@
1
+ import { createRequire as __bundleRequire } from "node:module";
2
+ const require = __bundleRequire(import.meta.url);
3
+ import {
4
+ answers,
5
+ itemAnswer
6
+ } from "./chunk-FGXUH3XL.js";
7
+ import {
8
+ loadConfig,
9
+ updateConfig
10
+ } from "./chunk-T7TG4JKR.js";
11
+ import {
12
+ __name
13
+ } from "./chunk-SCDNOUUR.js";
14
+
15
+ // dist/run/auto.js
16
+ import { execFile } from "node:child_process";
17
+ import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
18
+ import { homedir } from "node:os";
19
+ import { dirname, join, resolve } from "node:path";
20
+ import { fileURLToPath } from "node:url";
21
+ import { CliError, resolvePaths } from "@wirecat/cli-base";
22
+ import { annotate } from "@wirecat/cli-base/commands";
23
+ import { installerOf } from "@wirecat/cli-base/update";
24
+ import { failingNotice, LOCAL_READ, LOCAL_WRITE, recordRun } from "@wirecat/cli-core";
25
+ import { InvalidArgumentError } from "commander";
26
+ var DEFAULT_EVERY = "5m";
27
+ var UNIT = "wcat-import";
28
+ var lastRunPath = /* @__PURE__ */ __name((env) => join(resolvePaths({ appName: "wcat", prefix: "WCAT", env }).state, "auto", "last.json"), "lastRunPath");
29
+ var lastAutoRun = /* @__PURE__ */ __name((env) => {
30
+ try {
31
+ return JSON.parse(readFileSync(lastRunPath(env), "utf8"));
32
+ } catch {
33
+ return void 0;
34
+ }
35
+ }, "lastAutoRun");
36
+ var recordAutoRun = /* @__PURE__ */ __name((env, at, reason) => {
37
+ if (env.WCAT_AUTO !== "1")
38
+ return;
39
+ recordRun(lastRunPath(env), {
40
+ at: new Date(at).toISOString(),
41
+ exitCode: reason === void 0 ? 0 : 1,
42
+ output: `journalctl --user -u ${UNIT}.service`,
43
+ ...reason === void 0 ? {} : { reason }
44
+ });
45
+ }, "recordAutoRun");
46
+ var autoNotice = /* @__PURE__ */ __name((env) => env.WCAT_AUTO === "1" ? void 0 : failingNotice("wcat", [{ job: "sync", last: lastAutoRun(env) }], "wcat jobs status"), "autoNotice");
47
+ var interval = /* @__PURE__ */ __name((value) => {
48
+ const match = /^(\d+)(s|m|h)$/.exec(value.trim());
49
+ const seconds = match === null ? 0 : Number(match[1]) * { s: 1, m: 60, h: 3600 }[match[2]];
50
+ if (seconds < 60)
51
+ throw new InvalidArgumentError("an interval of a minute or more, like 5m, 90s or 1h");
52
+ return value.trim();
53
+ }, "interval");
54
+ var systemdSpan = /* @__PURE__ */ __name((every) => every.replace(/m$/, "min"), "systemdSpan");
55
+ var unitDir = /* @__PURE__ */ __name((env) => join(env.XDG_CONFIG_HOME ?? join(env.HOME ?? homedir(), ".config"), "systemd", "user"), "unitDir");
56
+ var quote = /* @__PURE__ */ __name((arg) => `"${arg.replace(/(["\\])/g, "\\$1")}"`, "quote");
57
+ var wcatBin = /* @__PURE__ */ __name(() => resolve(dirname(fileURLToPath(new URL("../run/auto.js", import.meta.url).href)), "../bin/wcat-wirecat.js"), "wcatBin");
58
+ var PLACE_VARIABLES = [
59
+ "WCAT_CONFIG_DIR",
60
+ "WCAT_STATE_DIR",
61
+ "WCAT_CACHE_DIR",
62
+ "MESSAGING_STORE",
63
+ "WIRECAT_STATE_DIR"
64
+ ];
65
+ var placesOf = /* @__PURE__ */ __name((env) => Object.fromEntries(PLACE_VARIABLES.flatMap((name) => env[name] ? [[name, env[name]]] : [])), "placesOf");
66
+ var execStart = /* @__PURE__ */ __name(() => `ExecStart=${[process.execPath, wcatBin(), "sync"].map(quote).join(" ")}`, "execStart");
67
+ var serviceUnit = /* @__PURE__ */ __name((env, places = {}) => [
68
+ "[Unit]",
69
+ "Description=wcat: sync notes into the shared store and embed stored mail",
70
+ "",
71
+ "[Service]",
72
+ "Type=oneshot",
73
+ execStart(),
74
+ // The programs wcat calls are found on the PATH wcat was set up with.
75
+ `Environment=${[`PATH=${env.PATH ?? ""}`, ...Object.entries(places).map(([name, value]) => `${name}=${value}`)].map(quote).join(" ")} WCAT_AUTO=1`,
76
+ "Nice=10",
77
+ ""
78
+ ].join("\n"), "serviceUnit");
79
+ var timerUnit = /* @__PURE__ */ __name((every) => [
80
+ "[Unit]",
81
+ `Description=wcat: sync notes and embed stored mail every ${every}`,
82
+ "",
83
+ "[Timer]",
84
+ "OnActiveSec=1min",
85
+ // From when a sync ends: counted from its start, a sync longer than the interval left no next run.
86
+ `OnUnitInactiveSec=${systemdSpan(every)}`,
87
+ "AccuracySec=30s",
88
+ "",
89
+ "[Install]",
90
+ "WantedBy=timers.target",
91
+ ""
92
+ ].join("\n"), "timerUnit");
93
+ var systemctl = /* @__PURE__ */ __name((env) => (...args) => new Promise((done, fail) => execFile(env.WCAT_SYSTEMCTL ?? "systemctl", ["--user", ...args], { env }, (error, stdout, stderr) => error === null ? done(stdout) : fail(new CliError("provider_error", `systemctl ${args.join(" ")}: ${stderr.trim() || error.message}`, {
94
+ reason: "auto.systemctl-failed"
95
+ })))), "systemctl");
96
+ var autoState = /* @__PURE__ */ __name((config) => ({
97
+ enabled: config.auto?.enabled ?? false,
98
+ every: config.auto?.every ?? DEFAULT_EVERY,
99
+ places: config.auto?.places ?? {}
100
+ }), "autoState");
101
+ var applyAuto = /* @__PURE__ */ __name(async (env, state, unit = UNIT, path = env.PATH) => {
102
+ const run = systemctl(env);
103
+ const dir = unitDir(env);
104
+ const timerPath = join(dir, `${unit}.timer`);
105
+ const servicePath = join(dir, `${unit}.service`);
106
+ if (!state.enabled) {
107
+ if (!existsSync(timerPath) && !existsSync(servicePath))
108
+ return;
109
+ await run("disable", "--now", `${unit}.timer`).catch(() => "");
110
+ rmSync(timerPath, { force: true });
111
+ rmSync(servicePath, { force: true });
112
+ await run("daemon-reload");
113
+ return;
114
+ }
115
+ const wanted = {
116
+ [servicePath]: serviceUnit({ ...env, PATH: path }, state.places),
117
+ [timerPath]: timerUnit(state.every)
118
+ };
119
+ const stale = Object.entries(wanted).filter(([path2, text]) => !existsSync(path2) || readFileSync(path2, "utf8") !== text);
120
+ if (stale.length === 0)
121
+ return;
122
+ mkdirSync(dir, { recursive: true });
123
+ for (const [path2, text] of stale)
124
+ writeFileSync(path2, text);
125
+ await run("daemon-reload");
126
+ await run("enable", "--now", `${unit}.timer`);
127
+ if (stale.some(([path2]) => path2 === timerPath))
128
+ await run("restart", `${unit}.timer`);
129
+ }, "applyAuto");
130
+ var globalRoots = /* @__PURE__ */ __name((env, execPath = process.execPath) => {
131
+ const home = env.HOME ?? homedir();
132
+ const bin = dirname(execPath);
133
+ const npmPrefix = env.npm_config_prefix ?? env.NPM_CONFIG_PREFIX;
134
+ return [
135
+ resolve(bin, "..", "lib", "node_modules"),
136
+ resolve(bin, "node_modules"),
137
+ ...npmPrefix ? [resolve(npmPrefix, "lib", "node_modules"), resolve(npmPrefix, "node_modules")] : [],
138
+ "/usr/lib/node_modules",
139
+ "/usr/local/lib/node_modules",
140
+ resolve(env.PNPM_HOME ?? join(home, ".local", "share", "pnpm"), "global"),
141
+ resolve(env.BUN_INSTALL ?? join(home, ".bun"), "install", "global")
142
+ ];
143
+ }, "globalRoots");
144
+ var isGlobal = /* @__PURE__ */ __name((scriptPath, roots) => roots.some((root) => scriptPath.startsWith(`${root}/`) || scriptPath.startsWith(`${root}\\`)), "isGlobal");
145
+ var followInstall = /* @__PURE__ */ __name(async (env, scriptPath, roots = globalRoots(env)) => {
146
+ if (env.WCAT_AUTO === "1")
147
+ return;
148
+ scriptPath ??= realpathSync(wcatBin());
149
+ if (!["npm", "pnpm", "bun"].includes(installerOf(scriptPath)))
150
+ return;
151
+ if (!isGlobal(scriptPath, roots))
152
+ return;
153
+ if (!autoState(loadConfig(env)).enabled)
154
+ return;
155
+ const servicePath = join(unitDir(env), `${UNIT}.service`);
156
+ if (!existsSync(servicePath))
157
+ return;
158
+ const current = readFileSync(servicePath, "utf8");
159
+ const moved = current.replace(/^ExecStart=.*$/m, execStart());
160
+ if (moved === current)
161
+ return;
162
+ writeFileSync(servicePath, moved);
163
+ await systemctl(env)("daemon-reload");
164
+ }, "followInstall");
165
+ var failingOf = /* @__PURE__ */ __name((last) => last && last.exitCode !== 0 ? { since: last.failingSince ?? last.at, runs: last.failures ?? 1, reason: last.reason ?? null, log: last.output } : null, "failingOf");
166
+ var autoCommand = /* @__PURE__ */ __name((program, streams, env) => {
167
+ const run = systemctl(env);
168
+ const { print } = answers(program, streams, env);
169
+ const auto = program.command("jobs").description("run wcat sync on a systemd user timer, set in the config");
170
+ annotate(auto.command("start"), { effects: LOCAL_WRITE }).description("sync every --every (default auto.every, else 5m), starting a minute from now").option("--every <duration>", "how often: 5m, 90s, 1h \u2014 a minute or more", interval).action(async (options) => {
171
+ const config = updateConfig((current) => ({
172
+ ...current,
173
+ auto: { enabled: true, every: options.every ?? autoState(current).every, places: placesOf(env) }
174
+ }), env);
175
+ await applyAuto(env, autoState(config));
176
+ streams.data(`wcat sync runs every ${autoState(config).every}.
177
+ `);
178
+ });
179
+ annotate(auto.command("stop"), { effects: LOCAL_WRITE }).description("stop syncing on a timer and remove the timer").action(async () => {
180
+ const config = updateConfig((current) => ({ ...current, auto: { ...current.auto, enabled: false } }), env);
181
+ await applyAuto(env, autoState(config));
182
+ streams.data("wcat sync no longer runs on a timer.\n");
183
+ });
184
+ annotate(auto.command("status"), { effects: LOCAL_READ }).description("whether the timer is on, its interval, its next run and how the last one ended").option("--json", "print JSON; --json=id,title keeps only those fields").action(async (options) => {
185
+ const state = autoState(loadConfig(env));
186
+ const show = /* @__PURE__ */ __name(async (unit, properties) => Object.fromEntries((await run("show", unit, "--property", properties).catch(() => "")).split("\n").filter(Boolean).map((line) => [line.slice(0, line.indexOf("=")), line.slice(line.indexOf("=") + 1)])), "show");
187
+ const timer = await show(`${UNIT}.timer`, "ActiveState");
188
+ const service = await show(`${UNIT}.service`, "Result");
189
+ const listed = JSON.parse(await run("list-timers", `${UNIT}.timer`, "--output=json").catch(() => "[]") || "[]")[0];
190
+ const when = /* @__PURE__ */ __name((micros) => typeof micros === "number" && micros > 0 ? new Date(micros / 1e3).toISOString() : null, "when");
191
+ const status = {
192
+ ...state,
193
+ timer: timer.ActiveState ?? "unknown",
194
+ next: when(listed?.next),
195
+ last: when(listed?.last),
196
+ lastResult: service.Result || null,
197
+ failing: failingOf(lastAutoRun(env))
198
+ };
199
+ print(options.json, itemAnswer(status), `${status.enabled ? `on, every ${status.every}` : "off"} \u2014 timer ${status.timer}` + (status.next ? `, next ${status.next}` : "") + (status.last ? `, last ${status.last} (${status.lastResult ?? "?"})` : "") + (status.failing ? `
200
+ failing since ${status.failing.since} (${status.failing.runs} runs)` + (status.failing.reason ? `: ${status.failing.reason}` : "") + `
201
+ the full message: ${status.failing.log}` : ""));
202
+ });
203
+ }, "autoCommand");
204
+
205
+ export {
206
+ DEFAULT_EVERY,
207
+ UNIT,
208
+ lastAutoRun,
209
+ recordAutoRun,
210
+ autoNotice,
211
+ interval,
212
+ unitDir,
213
+ PLACE_VARIABLES,
214
+ placesOf,
215
+ serviceUnit,
216
+ timerUnit,
217
+ autoState,
218
+ applyAuto,
219
+ globalRoots,
220
+ followInstall,
221
+ autoCommand
222
+ };
@@ -0,0 +1,2 @@
1
+ import { createRequire as __bundleRequire } from "node:module";
2
+ const require = __bundleRequire(import.meta.url);