@wirecat/cli-core 0.646.0 → 0.648.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 (80) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/account-remove.d.ts +5 -0
  4. package/dist/cli/account-remove.js +6 -1
  5. package/dist/cli/app-doctor-command.js +15 -55
  6. package/dist/cli/app-store.d.ts +12 -0
  7. package/dist/cli/app-store.js +25 -0
  8. package/dist/cli/commands-command.js +10 -3
  9. package/dist/cli/doctor-reports-command.d.ts +22 -0
  10. package/dist/cli/doctor-reports-command.js +82 -0
  11. package/dist/cli/help/command-help.d.ts +1 -0
  12. package/dist/cli/help/command-help.js +7 -6
  13. package/dist/cli/index.d.ts +3 -1
  14. package/dist/cli/index.js +3 -1
  15. package/dist/cli/messenger/doctor-command.js +21 -62
  16. package/dist/cli/messenger/stats-command.js +1 -1
  17. package/dist/cli/messenger/store-maintenance-command.js +3 -3
  18. package/dist/cli/messenger/tasks-command.js +1 -3
  19. package/dist/cli/permission-keys.js +4 -2
  20. package/dist/cli/program.js +26 -10
  21. package/dist/cli/settings.d.ts +2 -0
  22. package/dist/cli/settings.js +3 -2
  23. package/dist/cli/store-recover.js +2 -2
  24. package/dist/cli/store-settings.d.ts +2 -2
  25. package/dist/cli/store-settings.js +11 -5
  26. package/dist/cli/unknown-profile.d.ts +9 -0
  27. package/dist/cli/unknown-profile.js +23 -0
  28. package/dist/crm/cli/index.js +26 -4
  29. package/dist/crm/cli/search-all.js +4 -4
  30. package/dist/crm/source.d.ts +8 -2
  31. package/dist/crm/sync.d.ts +7 -1
  32. package/dist/crm/sync.js +73 -0
  33. package/dist/domain/crm.d.ts +27 -0
  34. package/dist/domain/crm.js +2 -0
  35. package/dist/entities/deal.d.ts +17 -0
  36. package/dist/entities/deal.js +16 -0
  37. package/dist/entities/index.d.ts +2 -0
  38. package/dist/errors/failures.d.ts +2 -0
  39. package/dist/errors/failures.js +6 -0
  40. package/dist/errors/reasons.js +18 -1
  41. package/dist/index.d.ts +2 -1
  42. package/dist/index.js +2 -1
  43. package/dist/kit/index.d.ts +1 -0
  44. package/dist/kit/index.js +1 -0
  45. package/dist/kit/own-catalogue.d.ts +7 -0
  46. package/dist/kit/own-catalogue.js +21 -0
  47. package/dist/oauth/index.d.ts +2 -2
  48. package/dist/oauth/index.js +2 -1
  49. package/dist/oauth/provider.d.ts +4 -0
  50. package/dist/oauth/provider.js +16 -1
  51. package/dist/oauth/storage.d.ts +5 -0
  52. package/dist/oauth/storage.js +20 -0
  53. package/dist/runs/error-detail.d.ts +1 -1
  54. package/dist/runs/error-detail.js +5 -2
  55. package/dist/runs/events.d.ts +1 -1
  56. package/dist/runs/secrets.d.ts +5 -4
  57. package/dist/runs/secrets.js +8 -4
  58. package/dist/sends/permissions.d.ts +2 -0
  59. package/dist/sends/permissions.js +4 -1
  60. package/dist/services/metadata.d.ts +1 -1
  61. package/dist/services/search-all.js +1 -1
  62. package/dist/sftp/index.d.ts +1 -0
  63. package/dist/sftp/index.js +1 -0
  64. package/dist/sftp/session.d.ts +61 -0
  65. package/dist/sftp/session.js +230 -0
  66. package/dist/sftp/ssh2.d.ts +38 -0
  67. package/dist/sftp/ssh2.js +306 -0
  68. package/dist/store/index.d.ts +1 -0
  69. package/dist/store/index.js +1 -0
  70. package/dist/store/sqlite/crm-activities.d.ts +29 -0
  71. package/dist/store/sqlite/crm-activities.js +113 -0
  72. package/dist/store/sqlite/crm-settings.d.ts +5 -1
  73. package/dist/store/sqlite/crm-settings.js +9 -1
  74. package/dist/store/sqlite/crm.d.ts +9 -1
  75. package/dist/store/sqlite/crm.js +6 -1
  76. package/dist/store/sqlite/deals.d.ts +4 -3
  77. package/dist/store/sqlite/deals.js +8 -2
  78. package/dist/store/sqlite/open-store.js +14 -1
  79. package/package.json +14 -4
  80. package/parity.json +2 -11
@@ -1,6 +1,6 @@
1
1
  import { existsSync } from "node:fs";
2
- import { dirname, resolve } from "node:path";
3
- import { configFilePath, resolvePaths, writeSecurely } from "@wirecat/cli-base";
2
+ import { dirname } from "node:path";
3
+ import { configFilePath, resolvePaths } from "@wirecat/cli-base";
4
4
  import { annotate } from "@wirecat/cli-base/commands";
5
5
  import { Command } from "commander";
6
6
  import { engineStates } from "../../attachments/extract.js";
@@ -11,16 +11,16 @@ import { FloodMemory, floodPathFor } from "../../sends/flood.js";
11
11
  import { SendJournal, sendsPathFor } from "../../sends/journal.js";
12
12
  import { storePath } from "../../store/path.js";
13
13
  import { baseContext, environmentOf, outputFor } from "../context.js";
14
+ import { doctorReportsCommand } from "../doctor-reports-command.js";
14
15
  import { DOCTOR_ONLINE_OPTION, DOCTOR_SUMMARY } from "../doctor-text.js";
15
- import { destroysNothing, LOCAL_WRITE, NO_EFFECTS, REMOTE_READ } from "../effects.js";
16
+ import { REMOTE_READ } from "../effects.js";
16
17
  import { itemOf, renderAnswer, snakeKeys } from "../envelope.js";
17
18
  import { unknownPermissionIssues } from "../permission-keys.js";
18
19
  import { NONE_NAMED } from "../settings.js";
19
- import { lineOf, nextStep, rootOf } from "../steps.js";
20
+ import { nextStep } from "../steps.js";
20
21
  import { recalledAccount } from "./accounts.js";
21
22
  import { messengerContext } from "./context.js";
22
23
  import { privateFiles, withSqliteSidecars } from "./private-files.js";
23
- import { buildReport, reportFileName } from "./report.js";
24
24
  import { DAY_MS } from "./serve-members.js";
25
25
  import { storeSummary } from "./store-maintenance-command.js";
26
26
  /**
@@ -84,63 +84,22 @@ const INCLUDES = [
84
84
  "every chat, message and account id replaced by a label that means nothing outside the file",
85
85
  ];
86
86
  const EXCLUDES = ["message text", "chat titles", "names", "phone numbers", "the session", "the app credentials"];
87
- const reportCommand = (messenger) => {
88
- const { app } = messenger;
89
- const report = new Command("reports").description("problem reports");
90
- annotate(report.command("show"), {
91
- effects: NO_EFFECTS,
92
- examples: [`${app.command} doctor reports show`],
93
- })
94
- .description("what a problem report holds; writes nothing")
95
- .action(function () {
96
- const output = outputFor(this);
97
- const create = lineOf(this, "doctor reports create");
98
- renderAnswer(this, output, itemOf({ includes: INCLUDES, excludes: EXCLUDES, ...(app.issues ? { send_to: app.issues } : {}) }, { next: [nextStep("doctor.report-create", { args: {} })] }), () => [
99
- `A problem report is one file for the author of ${app.command}.`,
100
- "",
101
- "It holds:",
102
- ...INCLUDES.map((line) => `- ${line}`),
103
- "",
104
- `It never holds: ${EXCLUDES.join(", ")}.`,
105
- "",
106
- `Create one: ${create}`,
107
- `About a given run: ${create} --run <id> (ids: ${lineOf(this, "runs list")})`,
108
- ].join("\n"));
109
- });
110
- destroysNothing(annotate(report.command("create"), {
111
- effects: LOCAL_WRITE,
112
- examples: [`${app.command} personal doctor reports create --output ./problem-report.json`],
113
- }))
114
- .description("write a problem report to a file, and say where to send it")
115
- .option("--run <id>", "the run the report is about; the newest failed one if not given")
116
- .option("--output <file>", "where to write it; a new file in this directory if not given")
117
- .action(async function () {
118
- const options = this.opts();
119
- const env = environmentOf(this).env ?? process.env;
120
- const { report: doctor, renderer, profile } = await diagnose(this, messenger);
121
- const now = new Date();
122
- const built = buildReport({
123
- doctor,
124
- runsDir: runsDirFor(app, env),
125
- command: app.command,
126
- sends: profile ? new SendJournal(sendsPathFor(app, profile, env)).entries() : [],
127
- now,
128
- home: env.HOME ?? env.USERPROFILE,
129
- program: rootOf(this),
130
- ...(options.run === undefined ? {} : { runId: options.run }),
131
- });
132
- const path = resolve(options.output ?? reportFileName(app.command, now));
133
- writeSecurely(path, `${JSON.stringify(built, null, 2)}\n`, 0o600);
134
- const output = outputFor(this);
135
- const out = renderer ?? output.renderer;
136
- renderAnswer(this, { ...output, renderer: out }, itemOf({ path, run: built.run?.metadata.runId ?? null, ...(app.issues ? { send_to: app.issues } : {}) }));
137
- if (!built.run) {
138
- out.note("no failed run is recorded — run the failing command again, and the failure is kept by itself");
139
- }
140
- out.note(`read it before sending: no message text, and ids are labels${app.issues ? ` — attach it to a new issue at ${app.issues}` : ""}`);
141
- });
142
- return report;
143
- };
87
+ const reportCommand = (messenger) => doctorReportsCommand({
88
+ app: messenger.app,
89
+ includes: INCLUDES,
90
+ excludes: EXCLUDES,
91
+ example: `${messenger.app.command} personal`,
92
+ check: "no message text, and ids are labels",
93
+ collect: async (command) => {
94
+ const env = environmentOf(command).env ?? process.env;
95
+ const { report, renderer, profile } = await diagnose(command, messenger);
96
+ return {
97
+ doctor: report,
98
+ sends: profile ? new SendJournal(sendsPathFor(messenger.app, profile, env)).entries() : [],
99
+ ...(renderer ? { renderer } : {}),
100
+ };
101
+ },
102
+ });
144
103
  const rememberedOf = (report) => report.account?.remembered ?? undefined;
145
104
  /**
146
105
  * What `doctor` answers, as data. A configuration that will not load is a field, not an exception:
@@ -105,7 +105,7 @@ export const statsCommand = (messenger, loadRenderer = chartRenderer) => {
105
105
  "messages top": 'chat:"Book club" --limit 10',
106
106
  "messages unanswered": 'chat:"Project room"',
107
107
  "messages waiting": "kind:private",
108
- "tasks show": '--chat "Project room"',
108
+ "tasks show": '-- chat:"Project room"',
109
109
  };
110
110
  for (const [path, args] of Object.entries(examples)) {
111
111
  const command = commandAt(stats, path);
@@ -18,7 +18,7 @@ import { storePath } from "../../store/path.js";
18
18
  import { deleteCopy, repairStore } from "../../store/repair.js";
19
19
  import { drainNoteIndex, dropAllUnusedVectors, fillSearchIndex, fillStems, involvementStoreOver, noteIndexState, openSqlite, openStore, orphanPointers, pendingNormalization, resetAttachmentWords, resetNoteIndex, resetSearchIndex, resetStems, rollBack, searchIndexState, stemmerCache, stemsState, vectorIndexCounts, } from "../../store/store.js";
20
20
  import { environmentOf, outputFor } from "../context.js";
21
- import { destroysNothing, LOCAL_READ, LOCAL_WRITE } from "../effects.js";
21
+ import { destroysNothing, grantsAuthority, LOCAL_READ, LOCAL_WRITE } from "../effects.js";
22
22
  import { itemOf, renderAnswer, snakeKeys } from "../envelope.js";
23
23
  import { commandAt, lineOf, nextStep } from "../steps.js";
24
24
  import { storeInfoCommand } from "../store-info.js";
@@ -627,7 +627,7 @@ const decryptCommand = () => annotate(new Command("decrypt"), { output: { entity
627
627
  * process has the file open — it would go on writing to the file set aside — or while this CLI's
628
628
  * `serve` runs: that opens the store on its first write, so until then it holds nothing to see.
629
629
  */
630
- const restoreCommand = (owner) => annotate(new Command("restore"), { output: { entity: "store_restore" }, effects: LOCAL_WRITE })
630
+ const restoreCommand = (owner) => grantsAuthority(annotate(new Command("restore"), { output: { entity: "store_restore" }, effects: LOCAL_WRITE }))
631
631
  .summary("restore a backup and keep the current store, or roll back a breaking upgrade")
632
632
  .description("put a backup in place of the store; the store it replaces is kept beside it, never deleted. Given a rollback " +
633
633
  "copy (backups/<store>-rollback-schema-<version>-<time>.db, kept for a day before an upgrade older tools " +
@@ -791,7 +791,7 @@ const quiesce = async (path, owner, then, warn, waitMs = STORE_LOCK_WAIT_MS) =>
791
791
  * the delete. A new file rather than `DELETE FROM` every table: deleted rows would stay readable in free
792
792
  * pages until a VACUUM, and every table comes back in this build's shape.
793
793
  */
794
- const resetCommand = (owner) => annotate(new Command("reset"), { output: { entity: "store_reset" }, effects: LOCAL_WRITE })
794
+ const resetCommand = (owner) => annotate(new Command("reset"), { output: { entity: "store_reset" }, effects: LOCAL_WRITE, mcp: false })
795
795
  .summary(`back up the ${archive(owner)} and replace it with an empty one`)
796
796
  .description("back the store up beside itself, then delete it and start an empty one at this build's schema; asks first, or --yes")
797
797
  .option("--no-backup", "delete the store without backing it up first")
@@ -558,19 +558,17 @@ export const tasksStatsCommand = (messenger) => {
558
558
  .description("tasks per chat, meeting or project: open now, and opened and closed in the period (created: in the query), " +
559
559
  "with the median time to close and the mean age of the open ones")
560
560
  .option("--by <group>", "chat (default) or meeting: this account's tasks; project: the owner's project tasks, every project", statsByOf)
561
- .option("--chat <chat>", `only this chat; ${messenger.chatArgument}`)
562
561
  .option("--type <type>", "only this type: question, request, mention or promise", taskTypeOf)
563
562
  .option("--timezone <zone>", "the IANA timezone for calendar days in the period, such as created>=today")
564
563
  .action(async function (words) {
565
564
  const context = messengerContext(this, messenger);
566
- const { by, chat, type, timezone } = this.opts();
565
+ const { by, type, timezone } = this.opts();
567
566
  refuseJsonl(context.format);
568
567
  const query = listQuery(typedQuery(words), TASK_STATS_QUERY, "stats tasks show");
569
568
  const accounts = messenger.accountsOf?.(this);
570
569
  const { stats, account } = await context.withServices(async (services) => ({
571
570
  stats: await services.tasks.stats({
572
571
  ...(by === undefined ? {} : { by }),
573
- ...(chat === undefined ? {} : { chat }),
574
572
  ...(type === undefined ? {} : { kind: type }),
575
573
  ...(query === undefined ? {} : { query }),
576
574
  ...(timezone === undefined ? {} : { timezone }),
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { AUTHORITY_KEY, CEILING_KEY, DEFAULT_PERMISSIONS, keyForCommand, WRITE_KEYS, } from "../sends/permissions.js";
2
+ import { AUTHORITY_KEY, CEILING_KEY, DEFAULT_PERMISSIONS, KEYED_UNDER_HOUSEKEEPING, keyForCommand, WRITE_KEYS, } from "../sends/permissions.js";
3
3
  import { issueMessage, permissionIssues, publicIssue } from "./config-issues.js";
4
4
  const HOUSEKEEPING = new Set([
5
5
  "help",
@@ -15,7 +15,9 @@ const HOUSEKEEPING = new Set([
15
15
  "runs",
16
16
  ]);
17
17
  /** A command's own path is its key; the commands that look after the tool have none. */
18
- export const commandPathKey = (path) => path[0] === undefined || HOUSEKEEPING.has(path[0]) ? null : path.join(".");
18
+ export const commandPathKey = (path) => path[0] === undefined || (HOUSEKEEPING.has(path[0]) && !KEYED_UNDER_HOUSEKEEPING.has(path.join(".")))
19
+ ? null
20
+ : path.join(".");
19
21
  export const commandPermissions = ({ keyOf = commandPathKey, extra = [], defaults = {}, alsoChecks, } = {}) => ({
20
22
  keyOf,
21
23
  extra: [AUTHORITY_KEY, ...extra],
@@ -7,7 +7,7 @@ import { Command, Help } from "commander";
7
7
  import { relayCommand } from "../background/relay.js";
8
8
  import { failingNotice, scheduledRuns } from "../background/schedules.js";
9
9
  import { parseDuration } from "../domain/duration.js";
10
- import { isCliFailure, isCommanderFailure, storeDamaged } from "../errors/failures.js";
10
+ import { isCliFailure, isCommanderFailure, storeDamaged, usageReason } from "../errors/failures.js";
11
11
  import { failureContext } from "../errors/reasons.js";
12
12
  import { envName, readOnlyLockOf, readOnlyRefusal } from "../ports/app.js";
13
13
  import { recorded, wasSettled } from "../runs/recording.js";
@@ -42,6 +42,7 @@ import { assertSharedContracts } from "./shared-contracts.js";
42
42
  import { skillSourceOf } from "./skill-command.js";
43
43
  import { refreshSkills, skipsSkillRefresh } from "./skill-refresh.js";
44
44
  import { commandAt, failureSteps, lineOf, withLines } from "./steps.js";
45
+ import { unknownProfile } from "./unknown-profile.js";
45
46
  const OUTPUT_OPTIONS = [
46
47
  ["output", "--output"],
47
48
  ["outputDir", "--output-dir"],
@@ -579,12 +580,17 @@ const runOnce = async (argv, definition, options) => {
579
580
  message = message.trimEnd();
580
581
  message += ` — "${profile}" is not a command, so it was read as a profile name — which left "${rest[0]}" to be one.`;
581
582
  }
582
- const failure = new CliError("validation_error", message);
583
+ const reason = usageReason(error.code);
584
+ const failure = new CliError("validation_error", message, reason ? { reason } : {});
583
585
  const settled = await settleFailure(failure, { definition, program, rest, argv, profile, options });
584
586
  return report(streams, reporting, failed(definition, program, rest, failure, settled, debug));
585
587
  }
586
588
  const settled = await settleFailure(error, { definition, program, rest, argv, profile, options });
587
- const exit = report(streams, reporting, failed(definition, program, rest, error, settled, debug));
589
+ // An MCP call's profile is the one its server was started for, not a word typed now.
590
+ const told = options.agent
591
+ ? error
592
+ : unknownProfile(error, () => failureSettings(definition, program, rest, profile, options));
593
+ const exit = report(streams, reporting, failed(definition, program, rest, told, settled, debug));
588
594
  return signalExit ?? exit;
589
595
  }
590
596
  finally {
@@ -690,19 +696,29 @@ const settleFailure = async (failure, state) => {
690
696
  * Its words are kept as `record_input` says (`maskArgv`); a configuration that did not load masks them, since it may
691
697
  * be the one that turned recording input off.
692
698
  */
693
- const keepFailure = async (failure, { definition, program, rest, argv, profile, options }) => {
694
- if (wasSettled(failure))
695
- return;
696
- const env = options.env ?? process.env;
699
+ /** The settings a failed run had, read again without asking for a profile; `undefined` when they do not load. */
700
+ const failureSettings = (definition, program, rest, profile, options) => {
697
701
  const path = commandPath(program, program.args.length > 0 ? program.args : rest);
698
702
  const { resolveSettings } = definition.configuration ?? settingsFor(definition.app);
699
- let settings;
700
703
  try {
701
- settings = resolveSettings({ ...program.opts(), ...(profile === undefined ? {} : { profile }) }, { env, kind: path.split(" ")[0] === "bot" ? "bot" : "personal", needsProfile: false, readOnly: true });
704
+ return resolveSettings({ ...program.opts(), ...(profile === undefined ? {} : { profile }) }, {
705
+ env: options.env ?? process.env,
706
+ kind: path.split(" ")[0] === "bot" ? "bot" : "personal",
707
+ needsProfile: false,
708
+ readOnly: true,
709
+ });
702
710
  }
703
711
  catch {
704
- // A configuration that will not load is a failure worth keeping too; the flags are all there is to go on.
712
+ return undefined;
705
713
  }
714
+ };
715
+ const keepFailure = async (failure, { definition, program, rest, argv, profile, options }) => {
716
+ if (wasSettled(failure))
717
+ return;
718
+ const env = options.env ?? process.env;
719
+ const path = commandPath(program, program.args.length > 0 ? program.args : rest);
720
+ // A configuration that will not load is a failure worth keeping too; the flags are all there is to go on.
721
+ const settings = failureSettings(definition, program, rest, profile, options);
706
722
  const command = `${options.agent ? "mcp " : ""}${path || definition.app.command}`;
707
723
  await recorded({
708
724
  app: definition.app,
@@ -31,6 +31,8 @@ export interface SettingsExtension<T extends object = Record<never, never>> {
31
31
  sources: Record<string, Source>;
32
32
  };
33
33
  profile?: v.ObjectEntries;
34
+ /** Like `profile`, but a bot's section refuses them: settings only a personal account reads. */
35
+ personal?: v.ObjectEntries;
34
36
  /** For the whole program only, never per profile. */
35
37
  defaults?: v.ObjectEntries;
36
38
  /** Its own scalar settings, written into the file's `defaults` beside the shared ones (WC-CMD-30). */
@@ -227,11 +227,12 @@ export const fromFile = (settings, key, fallback) => first([
227
227
  */
228
228
  export const settingsFor = (app, extension = {}) => {
229
229
  const declared = extension.permissions;
230
- const profileEntries = {
230
+ const botEntries = {
231
231
  ...SHARED_PROFILE_ENTRIES,
232
232
  ...(declared ? { permissions: v.optional(commandPathLevels) } : {}),
233
233
  ...extension.profile,
234
234
  };
235
+ const profileEntries = { ...botEntries, ...extension.personal };
235
236
  const defaultsOnly = { ...SHARED_DEFAULTS_ONLY, ...extension.defaults };
236
237
  const defaultsEntries = { ...profileEntries, ...defaultsOnly };
237
238
  const strictOf = (entries) => v.strictObject(entries, objectMessage);
@@ -243,7 +244,7 @@ export const settingsFor = (app, extension = {}) => {
243
244
  defaults: v.optional(strictOf(defaultsEntries)),
244
245
  profiles: v.optional(v.record(v.string(), strictOf(profileEntries), "has to be an object of profiles, by name"), {}),
245
246
  personal: v.optional(kindSection(profileEntries)),
246
- bot: v.optional(kindSection({ ...profileEntries, ...BOT_ONLY_ENTRIES })),
247
+ bot: v.optional(kindSection({ ...botEntries, ...BOT_ONLY_ENTRIES })),
247
248
  };
248
249
  const schema = strictOf(configEntries);
249
250
  const defaultsOnlyKeys = Object.keys(defaultsOnly);
@@ -10,7 +10,7 @@ import { storePath } from "../store/path.js";
10
10
  import { activeTimers, recoverStore, sqlite3Program, storeHolders, tableRows, } from "../store/recover.js";
11
11
  import { openSqlite } from "../store/store.js";
12
12
  import { environmentOf, outputFor } from "./context.js";
13
- import { LOCAL_READ, LOCAL_WRITE } from "./effects.js";
13
+ import { grantsAuthority, LOCAL_READ, LOCAL_WRITE } from "./effects.js";
14
14
  import { itemOf, renderAnswer, snakeKeys } from "./envelope.js";
15
15
  /** The tables whose counts say what the store holds; every other table is in `store info`. */
16
16
  const COUNTED = [
@@ -173,7 +173,7 @@ export const storeRecoverCommand = ({ command, version }) => {
173
173
  for (const line of recoveryNotes(answer))
174
174
  output.renderer.note(line);
175
175
  });
176
- recover.addCommand(annotate(new Command("run"), { effects: LOCAL_WRITE, examples: [`${command} store recover run`] })
176
+ recover.addCommand(grantsAuthority(annotate(new Command("run"), { effects: LOCAL_WRITE, examples: [`${command} store recover run`] }))
177
177
  .summary("rebuild a damaged store from every row it can read")
178
178
  .description("copy every readable row into a new file with the sqlite3 program, rebuild the search indexes, mentions and vector index, " +
179
179
  "check it, and put it in place of the store; the damaged file is kept beside it. Refuses while a WireCat timer or process has the store")
@@ -8,8 +8,8 @@ export declare const STORE_SETTINGS: string[];
8
8
  export declare const storeSettingsOf: (app: Pick<AppIdentity, "messenger">) => string[];
9
9
  export declare const offersStoreSetting: (app: Pick<AppIdentity, "messenger">, setting: string) => boolean;
10
10
  /**
11
- * Whose deals a CRM copy holds and what opens the owner's tasks: the owner's to set; an agent's run is stopped from
12
- * changing them by mistake.
11
+ * Whose deals a CRM copy holds, what opens the owner's tasks and whether clients' activities are copied: the owner's
12
+ * to set; an agent's run is stopped from changing them by mistake.
13
13
  */
14
14
  export declare const isOwnerOnlyStoreSetting: (setting: string) => boolean;
15
15
  export declare const isStoreSetting: (setting: string) => boolean;
@@ -34,9 +34,9 @@ export const STORE_SETTINGS = [
34
34
  const GROUP_PREFIX = `${ACCOUNT_GROUPS_SETTING}.`;
35
35
  /**
36
36
  * A CRM account's: whether what it reports is a relationship or waits for review, what its company types mean, whose
37
- * deals and leads its sync copies, and which stages open a task.
37
+ * deals and leads its sync copies, which stages open a task, and whether activities and tasks are read.
38
38
  */
39
- const CRM_SETTINGS = ["links", "company-types", "scope", "unassigned", "self", "stage-tasks"].map((name) => `crm.<provider>:<account>.${name}`);
39
+ const CRM_SETTINGS = ["links", "company-types", "scope", "unassigned", "self", "stage-tasks", "activities"].map((name) => `crm.<provider>:<account>.${name}`);
40
40
  /**
41
41
  * The store settings a CLI offers. Phone countries, task rules and account groups belong to messages; a CLI that is
42
42
  * not a messenger would change them for tg and MAX without reading them itself.
@@ -46,12 +46,12 @@ export const storeSettingsOf = (app) => app.messenger === false
46
46
  : [...STORE_SETTINGS, `${GROUP_PREFIX}<name>`, ...CRM_SETTINGS];
47
47
  export const offersStoreSetting = (app, setting) => app.messenger !== false || setting in SCRIPTS || setting === OWNER_LANGUAGES || parseCrmSetting(setting) !== undefined;
48
48
  /**
49
- * Whose deals a CRM copy holds and what opens the owner's tasks: the owner's to set; an agent's run is stopped from
50
- * changing them by mistake.
49
+ * Whose deals a CRM copy holds, what opens the owner's tasks and whether clients' activities are copied: the owner's
50
+ * to set; an agent's run is stopped from changing them by mistake.
51
51
  */
52
52
  export const isOwnerOnlyStoreSetting = (setting) => {
53
53
  const name = parseCrmSetting(setting)?.name;
54
- return name === "scope" || name === "self" || name === "unassigned" || name === "stage-tasks";
54
+ return name === "scope" || name === "self" || name === "unassigned" || name === "stage-tasks" || name === "activities";
55
55
  };
56
56
  export const isStoreSetting = (setting) => setting in SCRIPTS ||
57
57
  setting === OWNER_LANGUAGES ||
@@ -276,6 +276,7 @@ const CRM_DEFAULTS = {
276
276
  unassigned: [],
277
277
  self: "",
278
278
  "stage-tasks": {},
279
+ activities: "off",
279
280
  };
280
281
  const crmNote = (name, now) => {
281
282
  if (name === "links")
@@ -289,6 +290,11 @@ const crmNote = (name, now) => {
289
290
  "of the unassigned users, and marks the others deleted here; contacts and companies stay whole";
290
291
  if (name === "unassigned")
291
292
  return "store-wide — with scope mine, the next sync also copies the deals and leads of these users";
293
+ if (name === "activities")
294
+ return now === "on"
295
+ ? "store-wide — the next sync also reads the activities and tasks on the deals and leads it keeps, from the " +
296
+ "last 90 days on its first run; `deals show` lists them"
297
+ : "store-wide — no activity or task is read; those already stored stay";
292
298
  if (name === "stage-tasks")
293
299
  return Object.keys(now).length === 0
294
300
  ? "store-wide — no stage opens a task"
@@ -0,0 +1,9 @@
1
+ import type { Settings } from "./settings.js";
2
+ /**
3
+ * A "not signed in" failure for a first word this computer has never seen as a profile is most likely a typo: it
4
+ * answers `not_found` with the profiles here (FIND-2583), and keeps the sign-in hint for a profile that is new on
5
+ * purpose. Only after a command failed, so a working profile and the `setup` or `session start` that makes a new one
6
+ * never reach it; a profile set in the environment is a script's deliberate choice and keeps its refusal, and a bot
7
+ * gets its token with `bot auth set` under any new name.
8
+ */
9
+ export declare const unknownProfile: (error: unknown, settingsOf: () => (Pick<Settings, "profile"> & Partial<Pick<Settings, "sources" | "profilesHere" | "kind">>) | undefined) => unknown;
@@ -0,0 +1,23 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ const NOT_SIGNED_IN = new Set([undefined, "session.missing", "oauth.missing"]);
3
+ /**
4
+ * A "not signed in" failure for a first word this computer has never seen as a profile is most likely a typo: it
5
+ * answers `not_found` with the profiles here (FIND-2583), and keeps the sign-in hint for a profile that is new on
6
+ * purpose. Only after a command failed, so a working profile and the `setup` or `session start` that makes a new one
7
+ * never reach it; a profile set in the environment is a script's deliberate choice and keeps its refusal, and a bot
8
+ * gets its token with `bot auth set` under any new name.
9
+ */
10
+ export const unknownProfile = (error, settingsOf) => {
11
+ if (!isCliError(error) || error.code !== "authentication_error")
12
+ return error;
13
+ if (!NOT_SIGNED_IN.has(error.details.reason))
14
+ return error;
15
+ const settings = settingsOf();
16
+ const here = settings?.profilesHere;
17
+ if (!settings || !here || settings.kind === "bot" || settings.sources?.profile !== "first word")
18
+ return error;
19
+ if (here.includes(settings.profile))
20
+ return error;
21
+ return new CliError("not_found", `no profile named ${settings.profile} on this computer — profiles here: ${here.join(", ") || "none"}; ` +
22
+ `if ${settings.profile} is a new one: ${error.message}`, { reason: "profile.unknown", profiles: here });
23
+ };
@@ -61,6 +61,8 @@ const DEAL_UNTRUSTED = [
61
61
  "people.name",
62
62
  "provider_metadata",
63
63
  ];
64
+ /** `show` lists this many of a deal's activities: the open ones come first, so a long history does not hide them. */
65
+ const SHOWN_ACTIVITIES = 20;
64
66
  const PIPELINE_UNTRUSTED = ["name", "stages.name"];
65
67
  const STAGE_UNTRUSTED = ["name", "pipeline_name"];
66
68
  const crmContactsRemoved = v.strictObject({
@@ -82,6 +84,7 @@ const crmSync = v.strictObject({
82
84
  skipped_owner_rejected: count,
83
85
  contacts_removed: v.optional(crmContactsRemoved),
84
86
  stage_tasks: count,
87
+ activities: v.optional(v.strictObject({ saved: count, out_of_scope: count, state: v.picklist(["partial", "complete"]) })),
85
88
  synced: v.array(v.strictObject({
86
89
  kind: v.picklist(CRM_KINDS),
87
90
  round: v.picklist(["full", "changes"]),
@@ -190,8 +193,9 @@ const addCrmCommandsDefinition = (program, options) => {
190
193
  const example = (command, ...lines) => annotate(command, { examples: lines.map((line) => `${options.app.command} work ${line}`) });
191
194
  example(answerEntity(annotate(program.command("sync"), { effects: FETCH, offline: false, cooperative: true, partial: true }), "crm_sync", crmSync).description("bring the CRM's copy in the local store up to date: pipelines, companies, contacts, deals and leads that " +
192
195
  "changed since the last sync, or everything with --rescan; a run stops before its deadline or --max-pages " +
193
- "and the next one goes on from there. Then each deal or lead that moved into a stage the stage-tasks setting " +
194
- "names opens a local task, once per move"), "sync", "sync --rescan", "sync --max-pages 20")
196
+ "and the next one goes on from there. With the activities setting on, also the activities and tasks on the " +
197
+ "deals and leads it keeps. Then each deal or lead that moved into a stage the stage-tasks setting names " +
198
+ "opens a local task, once per move"), "sync", "sync --rescan", "sync --max-pages 20")
195
199
  .option("--rescan", "list everything again, every id too, dropping a round in progress")
196
200
  .option("--max-pages <pages>", "at most this many requests to the CRM in this run", integer(100_000))
197
201
  .action(async (opts, command) => {
@@ -323,11 +327,29 @@ const addCrmCommandsDefinition = (program, options) => {
323
327
  });
324
328
  });
325
329
  example(annotate(group.command("show"), { effects: LOCAL_READ, output: { entity: kind } })
326
- .description(`one ${kind} with its pipeline, stage, status, amount and the people on it`)
330
+ .description(`one ${kind} with its pipeline, stage, status, amount and the people on it; with the activities setting ` +
331
+ "on, its activities and tasks too")
327
332
  .argument(`<${kind}>`, `${kind}:<id>, as a list shows it`), `${plural} show ${kind}:12`).action(async (reference, _opts, command) => {
328
333
  await within(command, async (run) => {
329
334
  const found = await ownCopy(run, kind, reference);
330
- return itemOf({ ...dealKeys(found), untrusted: DEAL_UNTRUSTED });
335
+ const activities = found.externalId !== null && (await run.store.crm.activitiesOn(run.account))
336
+ ? (await run.store.crm.activitiesOf(run.account, kind, found.externalId, SHOWN_ACTIVITIES)).map((one) => ({
337
+ external_id: one.externalId,
338
+ kind: one.kind,
339
+ subject: one.subject,
340
+ body: one.body,
341
+ due_at: one.dueAt === null ? null : new Date(one.dueAt).toISOString(),
342
+ done: one.done,
343
+ assignee: one.assignee,
344
+ created_at: new Date(one.createdAt).toISOString(),
345
+ updated_at: new Date(one.updatedAt).toISOString(),
346
+ }))
347
+ : undefined;
348
+ return itemOf({
349
+ ...dealKeys(found),
350
+ ...(activities ? { activities } : {}),
351
+ untrusted: activities ? [...DEAL_UNTRUSTED, "activities.subject", "activities.body"] : DEAL_UNTRUSTED,
352
+ });
331
353
  });
332
354
  });
333
355
  addWrites(group, kind);
@@ -22,10 +22,10 @@ const DEFAULT_LIMIT = 20;
22
22
  export const addCrmSearchAll = (searches, { within, app, example, }) => {
23
23
  const all = annotate(new Command("all"), { effects: LOCAL_READ, partial: true, output: { entity: "hit" } })
24
24
  .summary("search stored deals and leads, messages, notes, calendar events and meetings")
25
- .description("search the CRM's deals and leads by the words of their title, company and contacts, and messages, notes, " +
26
- "calendar events and meetings other WireCat tools stored — best match first. Use it when you do not know " +
27
- "where something was written")
28
- .argument("<query...>", 'words and "phrases"; deals and leads match the words of their title, company and contacts')
25
+ .description("search the CRM's deals and leads by the words of their title, company, contacts and activities, and the " +
26
+ "messages, notes, calendar events and meetings other WireCat tools stored — best match first. Use it when " +
27
+ "you do not know where something was written")
28
+ .argument("<query...>", 'words and "phrases"; deals and leads match the words of their title, company, contacts and activities')
29
29
  .addHelpText("after", SAVE_HELP);
30
30
  searches.addCommand(searchAllOptions(all, SEARCHED));
31
31
  example(all, "search all Example LLC", "search all website --only crm --json");
@@ -1,4 +1,4 @@
1
- import type { CrmDepartment, CrmField, CrmKind, CrmPipeline, CrmRecords, CrmScope, CrmUser } from "../domain/crm.js";
1
+ import type { CrmActivity, CrmDepartment, CrmField, CrmKind, CrmPipeline, CrmRecords, CrmScope, CrmUser } from "../domain/crm.js";
2
2
  import type { DealKind } from "../domain/deals.js";
3
3
  export interface CrmSourceTraits {
4
4
  /** What this CRM has: one without leads leaves `lead` out. Contacts and companies come before the items on them. */
@@ -34,7 +34,7 @@ export interface CrmIdPage {
34
34
  * said it could not read.
35
35
  */
36
36
  export interface CrmGap {
37
- kind: CrmKind | "users" | "departments";
37
+ kind: CrmKind | "users" | "departments" | "activities";
38
38
  reason: "not-listed" | "refused" | "partial";
39
39
  code?: string;
40
40
  scope?: string;
@@ -96,4 +96,10 @@ export interface CrmSource {
96
96
  users?(context?: CrmCallContext): Promise<CrmUser[]>;
97
97
  /** Every department; left out, reporting lines are unknown and none stored is withdrawn. */
98
98
  departments?(context?: CrmCallContext): Promise<CrmDepartment[]>;
99
+ /**
100
+ * Activities and tasks on deals and leads changed after `since` (epoch ms), a page at a time; the last page's `cursor`
101
+ * is the time the next sync reads after. Read only when the account's `activities` setting is on; a CRM without
102
+ * them leaves it out. A list the sign-in may not read is a `gap`, and the others are still read.
103
+ */
104
+ activities?(since: number, page?: string, context?: CrmCallContext): Promise<CrmPage<CrmActivity>>;
99
105
  }
@@ -50,7 +50,7 @@ export interface CrmSyncOptions {
50
50
  export interface CrmSyncIssue {
51
51
  /** `user`: the account's users and departments. */
52
52
  kind: CrmKind | "user";
53
- reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.unassigned-dropped" | "crm.not-reported" | "crm.pending-dropped";
53
+ reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.unassigned-dropped" | "crm.not-reported" | "crm.pending-dropped" | "crm.activities-failed";
54
54
  message: string;
55
55
  externalId?: string;
56
56
  }
@@ -103,6 +103,12 @@ export interface CrmSyncReport {
103
103
  /** Pages saved: 0 means this run moved nothing on. */
104
104
  steps: number;
105
105
  };
106
+ /** With the `activities` setting on: what this run read of the activities and tasks on kept deals and leads. */
107
+ activities?: {
108
+ saved: number;
109
+ outOfScope: number;
110
+ state: "partial" | "complete";
111
+ };
106
112
  hint?: string;
107
113
  /**
108
114
  * On the first sync of an account no saved group lists: how to add it to a work group. Not `next`, which in an answer
package/dist/crm/sync.js CHANGED
@@ -156,6 +156,64 @@ const readUsers = async (run) => {
156
156
  run.report.users = users.length;
157
157
  return null;
158
158
  };
159
+ const ACTIVITIES = "crm:activities";
160
+ /** A first read goes this far back: older calls and e-mails rarely matter, and a busy portal holds years of them. */
161
+ const ACTIVITY_DAYS = 90;
162
+ const activityCursor = (value) => {
163
+ try {
164
+ const parsed = value === undefined ? undefined : JSON.parse(value);
165
+ return typeof parsed?.since === "number" ? parsed : undefined;
166
+ }
167
+ catch {
168
+ return undefined;
169
+ }
170
+ };
171
+ /**
172
+ * Activities and tasks changed since the last read, after every deal and lead of the run is stored: each is kept only
173
+ * on the deals and leads this copy holds. Pages go on from where a stopped run left them.
174
+ */
175
+ const readActivities = async (run) => {
176
+ const { source, store, account } = run;
177
+ if (!source.activities || !(await store.crm.activitiesOn(account)))
178
+ return null;
179
+ const read = { saved: 0, outOfScope: 0, state: "partial" };
180
+ run.report.activities = read;
181
+ const saved = activityCursor((await store.sync.syncState(account, ACTIVITIES))?.value);
182
+ const cursor = saved ?? { since: run.now - ACTIVITY_DAYS * DAY, newest: 0 };
183
+ for (;;) {
184
+ const why = run.budget.take();
185
+ if (why)
186
+ return why;
187
+ let page;
188
+ try {
189
+ page = await source.activities.call(source, cursor.since, cursor.page, run.context);
190
+ }
191
+ catch (error) {
192
+ if (run.signal?.aborted || error instanceof BudgetSpent)
193
+ throw error;
194
+ if (!scopeOf(error))
195
+ throw error;
196
+ run.gaps.push(refusal("activities", "no activity or task was read", error, source.provider));
197
+ return null;
198
+ }
199
+ const done = await store.crm.saveActivities(account, page.items);
200
+ read.saved += done.saved;
201
+ read.outOfScope += done.outOfScope;
202
+ cursor.newest = Math.max(cursor.newest, ...page.items.map((one) => one.updatedAt));
203
+ run.moved();
204
+ if (page.hasMore && page.nextCursor !== undefined) {
205
+ cursor.page = page.nextCursor;
206
+ await store.sync.setSyncState(account, ACTIVITIES, JSON.stringify(cursor));
207
+ if (run.signal?.aborted)
208
+ return "cancelled";
209
+ continue;
210
+ }
211
+ const next = page.cursor != null ? Number(page.cursor) : cursor.newest || cursor.since;
212
+ await store.sync.setSyncState(account, ACTIVITIES, JSON.stringify({ since: next, newest: 0 }));
213
+ read.state = "complete";
214
+ return null;
215
+ }
216
+ };
159
217
  /** Runs a step whose source call may spend the budget mid-way: a spent budget is a stop, not a failure. */
160
218
  const stopping = async (step) => {
161
219
  try {
@@ -528,6 +586,21 @@ export const syncCrm = async (source, store, account, options = {}) => {
528
586
  }
529
587
  // A relationship held back for an end a later page or kind brought is written now; it costs no request.
530
588
  run.droppedPending += (await store.crm.retryPending(account)).dropped;
589
+ if (!stopped && kinds.some(isItemKind)) {
590
+ try {
591
+ stopped = await stopping(() => readActivities(run));
592
+ }
593
+ catch (error) {
594
+ if (options.signal?.aborted)
595
+ stopped = "cancelled";
596
+ else
597
+ report.issues.push({
598
+ kind: "deal",
599
+ reason: "crm.activities-failed",
600
+ message: isCliFailure(error) ? error.message : "the activities could not be read",
601
+ });
602
+ }
603
+ }
531
604
  const narrowed = report.synced.some((one) => one.outOfScope > 0);
532
605
  const whole = report.synced.every((one) => one.state === "complete" && one.error === undefined && !one.held && one.pass !== "held");
533
606
  // Contacts have no scope of their own and no deletion check: they leave with the last deal or lead naming them.