@wirecat/cli-core 0.732.0 → 0.734.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 (36) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/cli/messenger/search-command.js +1 -0
  3. package/dist/cli/option-hints.d.ts +7 -0
  4. package/dist/cli/option-hints.js +25 -0
  5. package/dist/cli/program.js +13 -23
  6. package/dist/cli/steps.d.ts +2 -0
  7. package/dist/cli/steps.js +15 -0
  8. package/dist/crm/cli/activities.d.ts +12 -2
  9. package/dist/crm/cli/activities.js +101 -6
  10. package/dist/crm/cli/changes.d.ts +3 -0
  11. package/dist/crm/cli/changes.js +11 -2
  12. package/dist/crm/cli/index.d.ts +3 -2
  13. package/dist/crm/index.d.ts +2 -2
  14. package/dist/crm/index.js +2 -2
  15. package/dist/crm/testing/index.d.ts +1 -1
  16. package/dist/crm/testing/source.d.ts +8 -0
  17. package/dist/crm/testing/source.js +56 -2
  18. package/dist/crm/writer.d.ts +30 -1
  19. package/dist/crm/writer.js +4 -0
  20. package/dist/crm/writes.d.ts +34 -2
  21. package/dist/crm/writes.js +100 -0
  22. package/dist/errors/reasons.js +1 -0
  23. package/dist/ports/messenger.d.ts +1 -1
  24. package/dist/services/archive.js +3 -2
  25. package/dist/services/embeddings-search.js +29 -3
  26. package/dist/store/conversations.d.ts +16 -0
  27. package/dist/store/conversations.js +7 -0
  28. package/dist/store/sqlite/account-purge.js +8 -15
  29. package/dist/store/sqlite/conversations.d.ts +16 -0
  30. package/dist/store/sqlite/conversations.js +49 -1
  31. package/dist/store/sqlite/erase-plan.js +27 -5
  32. package/dist/store/sqlite/organization-erase.d.ts +2 -1
  33. package/dist/store/sqlite/organization-erase.js +2 -1
  34. package/dist/store/sqlite/person-erase.d.ts +6 -3
  35. package/dist/store/sqlite/person-erase.js +33 -17
  36. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,36 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.734.0 — 23.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A CRM CLI can add comments and tasks to records, and close a task.** A writer whose capabilities name
13
+ `activities: ["comment", "task"]` (either or both) and that implements `createActivity` and `completeActivity` gets
14
+ `activities create <comment|task> --subject deal:12 [--title] [--text] [--due] [--owner]` and
15
+ `activities close <task>`. Each goes through the same guarded path as `deals create`: journaled with an operation id,
16
+ checked against `activities.create` or `activities.close` (allowed by default), and against `crm.assign-others`
17
+ for a task given to another CRM user (`crmAlsoChecks` names it under `--dry-run`). The CRM's answer is stored as a
18
+ sync stores it, so `activities list` shows it at once when the activities setting is on. A CLI that does not set
19
+ `activities` in its capabilities gets no new command. The fake CRM source takes them when its capabilities name
20
+ them, and records them in `activityWrites`.
21
+
22
+ ## 0.733.0 — 23.11.2026
23
+
24
+ ### Fixed
25
+
26
+ - **Removing an account no longer erases a person its import was merged with.** A person the owner merged with an
27
+ imported one now stays when the account goes, and a person that cannot go no longer makes the whole removal fail.
28
+ - **Deleting a person also deletes the people merged into them earlier**, so their name, aliases and tags do not come
29
+ back as a new person. `PersonErasure` lists them in `merged`.
30
+ - **The owner's notes about a person or an organization go with them** and are listed in the plan, instead of
31
+ blocking the delete. Another table's row that hangs on a pointing row still blocks it.
32
+ - **Removing an account takes the relationships it reported**, and every row that points at its deals and leads
33
+ (a fact, a note, a tag), not only a fixed list of tables.
34
+ - **Thread replies answered in batches are saved again.** 0.732.0 checked for batches before awaiting the answer,
35
+ but the flood wrapper makes every adapter method async, so a messenger that answered in batches had none of its
36
+ replies saved. The answer is now awaited first, and `threadReplies` may return a promise of batches.
37
+
8
38
  ## 0.732.0 — 23.11.2026
9
39
 
10
40
  ### Fixed
@@ -198,6 +198,7 @@ export const searchCommand = (messenger, { topics = false } = {}) => {
198
198
  : {
199
199
  "--chat": `search in one chat with chat:<chat> in the query: search ${path} 'chat:<chat> words'`,
200
200
  "--around": AROUND_HINT,
201
+ "--filter": `a filter goes in the query: search ${path} 'words from:me date:7d'`,
201
202
  ...hintsFor(SENDER_FLAGS, `the sender goes in the query: search ${path} 'from:<sender> words' (from:me for you)`),
202
203
  }),
203
204
  ...(path === "all" ? {} : { "--only": ONLY_HINT }),
@@ -12,3 +12,10 @@ export declare const END_FLAGS: string[];
12
12
  /** In a message search `--from` means the sender, as `from:` does in the query, never a date. */
13
13
  export declare const SENDER_FLAGS: string[];
14
14
  export declare const AROUND_HINT: string;
15
+ /** A flag of a sibling command: the agent picked the wrong command, and a near flag of this one would mislead. */
16
+ export declare const siblingOption: (leaf: Command | undefined, message: string) => string;
17
+ /**
18
+ * Every word after `--` is an argument, so an option left there, one the command does not take, silently became
19
+ * query text and fails as syntax far from its cause.
20
+ */
21
+ export declare const queryAfterDashes: (error: unknown, leaf: Command | undefined, argv: readonly string[]) => unknown;
@@ -1,3 +1,5 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { commandPathOf } from "./command-contract.js";
1
3
  /**
2
4
  * A flag a command does not take, but an agent is likely to type, fails with what to type instead rather than
3
5
  * commander's bare "unknown option".
@@ -22,3 +24,26 @@ export const END_FLAGS = ["--until", "--before", "--until-date", "--before-date"
22
24
  export const SENDER_FLAGS = ["--from", "--sender", "--author"];
23
25
  export const AROUND_HINT = "read the messages either side of one: messages context <hit ref> --before-n 5 --after-n 5 " +
24
26
  "(or messages context <chat> <message>)";
27
+ /** A flag of a sibling command: the agent picked the wrong command, and a near flag of this one would mislead. */
28
+ export const siblingOption = (leaf, message) => {
29
+ const flag = /^unknown option '([^'=]+)/.exec(message)?.[1];
30
+ if (!flag || !leaf?.parent || / — |\(Did you mean/.test(message))
31
+ return "";
32
+ const owners = leaf.parent.commands.filter((one) => one !== leaf && one.options.some((option) => option.long === flag));
33
+ if (owners.length === 0)
34
+ return "";
35
+ return ` — ${flag} is an option of ${owners.map((one) => commandPathOf(one).join(" ")).join(", ")}`;
36
+ };
37
+ /**
38
+ * Every word after `--` is an argument, so an option left there, one the command does not take, silently became
39
+ * query text and fails as syntax far from its cause.
40
+ */
41
+ export const queryAfterDashes = (error, leaf, argv) => {
42
+ if (!isCliError(error) || !String(error.details.reason ?? "").startsWith("query.") || !argv.includes("--"))
43
+ return error;
44
+ const query = leaf?.processedArgs.at(-1);
45
+ if (!Array.isArray(query) || query.length === 0)
46
+ return error;
47
+ return new CliError(error.code, `${error.message} — after --, every word is an argument, so "${query.join(" ")}" was read as the query; ` +
48
+ "put options before --", error.details);
49
+ };
@@ -33,6 +33,7 @@ import { installHelp } from "./help/first-screen.js";
33
33
  import { showInputFields } from "./input-fields.js";
34
34
  import { MAX_BUFFERED_INPUT, provideInputPolicy } from "./input-policy.js";
35
35
  import { checkJson, liftJson } from "./json-fields.js";
36
+ import { queryAfterDashes, siblingOption } from "./option-hints.js";
36
37
  import { tooLargeSteps } from "./output-budget.js";
37
38
  import { PreviewComplete, preview } from "./preview.js";
38
39
  import { commandWords, isProfileName, liftProfile, sampleCommand, takesProfile, valuedOptions } from "./profile.js";
@@ -42,7 +43,7 @@ import { shareShadowedOptions } from "./shadowed-options.js";
42
43
  import { assertSharedContracts } from "./shared-contracts.js";
43
44
  import { skillSourceOf } from "./skill-command.js";
44
45
  import { refreshSkills, skipsSkillRefresh } from "./skill-refresh.js";
45
- import { commandAt, failureSteps, lineOf, withLines } from "./steps.js";
46
+ import { commandAt, failureSteps, lineOf, typedCommandPath, withLines } from "./steps.js";
46
47
  import { isSignIn, unknownProfile } from "./unknown-profile.js";
47
48
  const OUTPUT_OPTIONS = [
48
49
  ["output", "--output"],
@@ -499,7 +500,7 @@ const runOnce = async (argv, definition, options) => {
499
500
  // An agent's call builds its own argv, with its values after `--` on purpose: none of them may become an option.
500
501
  const lifted = options.agent
501
502
  ? profiled.rest
502
- : liftOptionsAfterDashes(profiled.rest, (words) => commandAt(program, commandPath(program, words)));
503
+ : liftOptionsAfterDashes(profiled.rest, (words) => commandAt(program, typedCommandPath(program, words)));
503
504
  const liftedEnd = lifted.indexOf("--");
504
505
  const liftedFlags = lifted.slice(0, liftedEnd < 0 ? undefined : liftedEnd);
505
506
  machine ||= isMachine(liftedFlags);
@@ -517,7 +518,7 @@ const runOnce = async (argv, definition, options) => {
517
518
  }
518
519
  if (profile !== undefined)
519
520
  program.setOptionValue("profile", profile);
520
- const requested = liftJson(lifted, (words) => commandAt(program, commandPath(program, words)));
521
+ const requested = liftJson(lifted, (words) => commandAt(program, typedCommandPath(program, words)));
521
522
  const rest = requested.argv;
522
523
  if (requested.fields !== undefined)
523
524
  program.setOptionValue("fields", requested.fields);
@@ -549,7 +550,7 @@ const runOnce = async (argv, definition, options) => {
549
550
  catch (caught) {
550
551
  if (caught instanceof Relayed)
551
552
  return caught.code;
552
- const error = control.failure() ?? caught;
553
+ let error = control.failure() ?? caught;
553
554
  if (error instanceof PreviewComplete)
554
555
  return 0;
555
556
  if (signalExit === 0)
@@ -568,9 +569,11 @@ const runOnce = async (argv, definition, options) => {
568
569
  streams.diagnostic(help.replace(/\n$/, ""));
569
570
  return exitCodeFor("validation_error");
570
571
  }
571
- const group = commandPath(program, rest);
572
+ const group = typedCommandPath(program, rest);
572
573
  message = `give a command — run \`${[command, group, "--help"].filter(Boolean).join(" ")}\` for the commands`;
573
574
  }
575
+ if (error.code === "commander.unknownOption")
576
+ message += siblingOption(commandAt(program, typedCommandPath(program, rest)), message);
574
577
  if (profile !== undefined &&
575
578
  error.code === "commander.unknownCommand" &&
576
579
  rest[0] !== undefined &&
@@ -583,6 +586,8 @@ const runOnce = async (argv, definition, options) => {
583
586
  const settled = await settleFailure(failure, { definition, program, rest, argv, profile, options });
584
587
  return report(streams, reporting, failed(definition, program, rest, failure, settled, debug));
585
588
  }
589
+ if (!options.agent)
590
+ error = queryAfterDashes(error, commandAt(program, typedCommandPath(program, rest)), rest);
586
591
  const settled = await settleFailure(error, { definition, program, rest, argv, profile, options });
587
592
  // An MCP call's profile is the one its server was started for, not a word typed now.
588
593
  const told = options.agent
@@ -696,7 +701,7 @@ const settleFailure = async (failure, state) => {
696
701
  */
697
702
  /** The settings a failed run had, read again without asking for a profile; `undefined` when they do not load. */
698
703
  const failureSettings = (definition, program, rest, profile, options) => {
699
- const path = commandPath(program, program.args.length > 0 ? program.args : rest);
704
+ const path = typedCommandPath(program, program.args.length > 0 ? program.args : rest);
700
705
  if (isSignIn(path))
701
706
  return undefined;
702
707
  const { resolveSettings } = definition.configuration ?? settingsFor(definition.app);
@@ -716,7 +721,7 @@ const keepFailure = async (failure, { definition, program, rest, argv, profile,
716
721
  if (wasSettled(failure))
717
722
  return;
718
723
  const env = options.env ?? process.env;
719
- const path = commandPath(program, program.args.length > 0 ? program.args : rest);
724
+ const path = typedCommandPath(program, program.args.length > 0 ? program.args : rest);
720
725
  // A configuration that will not load is a failure worth keeping too; the flags are all there is to go on.
721
726
  const settings = failureSettings(definition, program, rest, profile, options);
722
727
  const command = `${options.agent ? "mcp " : ""}${path || definition.app.command}`;
@@ -749,21 +754,6 @@ const keepFailure = async (failure, { definition, program, rest, argv, profile,
749
754
  }).catch(() => { });
750
755
  };
751
756
  /** Mounted, or reached through a command that takes no subcommand, where the rest of the path is its argument. */
752
- /** `messages list` from `messages list 111 --limit 5`: the words that name commands, up to the first that does not. */
753
- const commandPath = (program, rest) => {
754
- const words = [];
755
- let current = program;
756
- for (const token of rest) {
757
- if (token.startsWith("-"))
758
- continue;
759
- const next = current.commands.find((one) => one.name() === token || one.aliases().includes(token));
760
- if (!next)
761
- break;
762
- words.push(token);
763
- current = next;
764
- }
765
- return words.join(" ");
766
- };
767
757
  const budgetSteps = (program, path, failure) => {
768
758
  const command = path ? commandAt(program, path) : undefined;
769
759
  if (!command || !(failure instanceof CliError) || failure.details?.reason !== "output.too-large")
@@ -781,7 +771,7 @@ const damageStep = (program, cli) => {
781
771
  return doctor?.options.some((option) => option.long === "--deep") ? `${cli} doctor --deep` : undefined;
782
772
  };
783
773
  const failed = ({ app }, program, rest, error, settled, debug) => {
784
- const path = commandPath(program, program.args.length > 0 ? program.args : rest);
774
+ const path = typedCommandPath(program, program.args.length > 0 ? program.args : rest);
785
775
  const told = error instanceof NoProfileHere && !commandAt(program, "setup")
786
776
  ? error.withoutSetup(path)
787
777
  : storeDamaged(error, damageStep(program, app.command));
@@ -23,6 +23,8 @@ export declare const nextStep: (id: string, input: StepInput) => NextStep;
23
23
  /** `typedCommand` with the profile this command line named, else the run's. */
24
24
  export declare const lineOf: (command: Command, words: string) => string;
25
25
  export declare const rootOf: (command: Command) => Command;
26
+ /** `messages list` from `messages list 111 --limit 5`: the words that name commands, up to the first that does not. */
27
+ export declare const typedCommandPath: (program: Command, rest: string[]) => string;
26
28
  /** The command a path names in this program, or nothing when this CLI does not have it. */
27
29
  export declare const commandAt: (root: Command, path: string) => Command | undefined;
28
30
  export type CommandStep = Extract<NextStep, {
package/dist/cli/steps.js CHANGED
@@ -255,6 +255,21 @@ export const rootOf = (command) => {
255
255
  root = root.parent;
256
256
  return root;
257
257
  };
258
+ /** `messages list` from `messages list 111 --limit 5`: the words that name commands, up to the first that does not. */
259
+ export const typedCommandPath = (program, rest) => {
260
+ const words = [];
261
+ let current = program;
262
+ for (const token of rest) {
263
+ if (token.startsWith("-"))
264
+ continue;
265
+ const next = current.commands.find((one) => one.name() === token || one.aliases().includes(token));
266
+ if (!next)
267
+ break;
268
+ words.push(token);
269
+ current = next;
270
+ }
271
+ return words.join(" ");
272
+ };
258
273
  /** The command a path names in this program, or nothing when this CLI does not have it. */
259
274
  export const commandAt = (root, path) => {
260
275
  let at = root;
@@ -1,4 +1,5 @@
1
- import type { Command } from "commander";
1
+ import { type Command } from "commander";
2
+ import type { CrmWriteCapabilities } from "../writer.js";
2
3
  import type { CrmRun, CrmWithin } from "./index.js";
3
4
  export declare const ACTIVITIES_QUERY: {
4
5
  readonly entity: "crm_activity";
@@ -12,6 +13,15 @@ export interface CrmActivityCommandOptions {
12
13
  /** `owner:` as the identity an activity's assignee is stored as; `null` is none. */
13
14
  ownerOf: (run: CrmRun, owner: string) => Promise<string | null>;
14
15
  pathOf: (command: Command) => string[];
16
+ /** Mount `activities list`: the CLI copies the CRM's activities. */
17
+ list: boolean;
18
+ /** The writer's capabilities: `activities create` and `close` when they name activities. */
19
+ writes?: CrmWriteCapabilities;
20
+ /** The CRM has leads; true when absent. */
21
+ leads?: boolean;
15
22
  }
16
- /** `activities list`: the copy's CRM activities and tasks, mounted when the CLI copies them (WC-ARCH-5). */
23
+ /**
24
+ * `activities list`, mounted when the CLI copies the CRM's activities (WC-ARCH-5), and `activities create` and `close`
25
+ * when its writer makes them.
26
+ */
17
27
  export declare const addCrmActivityCommands: (program: Command, options: CrmActivityCommandOptions) => void;
@@ -1,15 +1,20 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { annotate } from "@wirecat/cli-base/commands";
3
3
  import { timezoneOf } from "@wirecat/cli-base/query";
4
+ import { Argument } from "commander";
4
5
  import * as v from "valibot";
5
6
  import { answerEntity } from "../../cli/answer-entity.js";
6
- import { LOCAL_READ, NO_EFFECTS } from "../../cli/effects.js";
7
- import { listOf } from "../../cli/envelope.js";
7
+ import { LOCAL_READ, NO_EFFECTS, REMOTE_WRITE } from "../../cli/effects.js";
8
+ import { itemOf, listOf } from "../../cli/envelope.js";
8
9
  import { listQuery, nativeField, nativeTerms, queryTerms, termField, timeBounds, typedQuery, withQuery, } from "../../cli/list-query.js";
10
+ import { terminalAsker } from "../../cli/messenger/ask.js";
9
11
  import { CRM_ACTIVITY_KINDS, CRM_KINDS } from "../../domain/crm.js";
12
+ import { aheadOf } from "../../domain/moment.js";
10
13
  import { text, time } from "../../entities/fields.js";
14
+ import { crmIdentityId } from "../../store/sqlite/crm-rows.js";
11
15
  import { crmSettingKey } from "../../store/sqlite/crm-settings.js";
12
16
  import { viewerOf } from "../viewer.js";
17
+ import { completeCrmActivity, createCrmActivity } from "../writes.js";
13
18
  import { integer } from "./records.js";
14
19
  const MOST = 500;
15
20
  const nullableText = v.nullable(text);
@@ -54,7 +59,7 @@ const crmActivity = v.strictObject({
54
59
  });
55
60
  const UNTRUSTED = ["subject", "body", "on.title"];
56
61
  const iso = (at) => (at === null ? null : new Date(at).toISOString());
57
- const itemOf = (one) => ({
62
+ const listedOf = (one) => ({
58
63
  external_id: one.externalId,
59
64
  kind: one.kind,
60
65
  subject: one.subject,
@@ -68,10 +73,20 @@ const itemOf = (one) => ({
68
73
  on: one.on.map(({ kind, externalId, ref, title }) => ({ kind, external_id: externalId, ref, title })),
69
74
  untrusted: UNTRUSTED,
70
75
  });
71
- /** `activities list`: the copy's CRM activities and tasks, mounted when the CLI copies them (WC-ARCH-5). */
76
+ /**
77
+ * `activities list`, mounted when the CLI copies the CRM's activities (WC-ARCH-5), and `activities create` and `close`
78
+ * when its writer makes them.
79
+ */
72
80
  export const addCrmActivityCommands = (program, options) => {
81
+ const group = annotate(program.command("activities"), { effects: NO_EFFECTS }).description(options.list
82
+ ? "the CRM's activities and tasks on deals, leads, contacts and companies, as last synced"
83
+ : `comments and tasks written to the CRM's ${options.leads === false ? "deals" : "deals, leads"}, contacts and companies`);
84
+ if (options.list)
85
+ addList(group, options);
86
+ addActivityWrites(group, options);
87
+ };
88
+ const addList = (group, options) => {
73
89
  const { within, example, now, ownerOf, pathOf } = options;
74
- const group = annotate(program.command("activities"), { effects: NO_EFFECTS }).description("the CRM's activities and tasks on deals, leads, contacts and companies, as last synced");
75
90
  example(withQuery(answerEntity(annotate(group.command("list"), { effects: LOCAL_READ }), "crm_activity", crmActivity)
76
91
  .description("activities copied from the CRM, open ones first by due time, then the rest newest first; status:open " +
77
92
  "unless a status is given; the activities setting must be on")
@@ -121,7 +136,7 @@ export const addCrmActivityCommands = (program, options) => {
121
136
  offset: (opts.page - 1) * opts.limit,
122
137
  });
123
138
  return listOf(pathOf(command).join(" "), {
124
- items: found.items.map(itemOf),
139
+ items: found.items.map(listedOf),
125
140
  ...paged,
126
141
  has_more: found.hasMore,
127
142
  ...(due.meta ? { meta: due.meta } : {}),
@@ -131,3 +146,83 @@ export const addCrmActivityCommands = (program, options) => {
131
146
  };
132
147
  /** `deal:12` as typed, or a bare id for the field it was given to. */
133
148
  const refOf = (kind, value) => (value.includes(":") ? value : `${kind}:${value}`);
149
+ const writtenActivity = v.strictObject({
150
+ operation_id: text,
151
+ stored: v.boolean(),
152
+ activity: v.omit(crmActivity, ["done_at"]),
153
+ untrusted: v.array(text),
154
+ });
155
+ /** `activities create` and `activities close`, through the same guarded path as `deals create`. */
156
+ const addActivityWrites = (group, options) => {
157
+ const { within, example, now, writes } = options;
158
+ const kinds = writes?.activities ?? [];
159
+ if (kinds.length === 0)
160
+ return;
161
+ const leads = options.leads !== false;
162
+ const contextOf = (run, command) => {
163
+ if (!run.writes)
164
+ throw new CliError("configuration_error", "this profile cannot write to its CRM");
165
+ return {
166
+ store: run.store,
167
+ account: run.account,
168
+ writes: run.writes(),
169
+ ask: terminalAsker(command),
170
+ source: run.source,
171
+ names: { id: "--operation-id" },
172
+ };
173
+ };
174
+ const answered = (run, done) => itemOf({
175
+ operation_id: done.operationId,
176
+ stored: done.stored,
177
+ activity: writtenOf(run, done.activity, done.on),
178
+ untrusted: UNTRUSTED.map((field) => `activity.${field}`),
179
+ });
180
+ const write = (name, description) => {
181
+ const command = answerEntity(annotate(group.command(name), { effects: REMOTE_WRITE, offline: false }), "crm_activity_write", writtenActivity).description(description);
182
+ if (writes?.idempotent)
183
+ command.option("--operation-id <id>", "the operation_id a write that ended in outcome_unknown named: the CRM answers the repeat from its record");
184
+ return command;
185
+ };
186
+ const idOf = (opts) => opts.operationId === undefined ? {} : { operationId: opts.operationId };
187
+ const comment = kinds.includes("comment");
188
+ const task = kinds.includes("task");
189
+ example(write("create", `add a ${kinds.join(" or ")} to records of the CRM, then store the CRM's copy of it when the activities ` +
190
+ "setting is on")
191
+ .addArgument(new Argument("<kind>", "what to add").choices(kinds))
192
+ .option("--subject <ref>", `a record it is on: ${leads ? "deal:<id> or lead:<id>" : "deal:<id>"} as a list shows it, or person:<id> or ` +
193
+ "organization:<id> by the CRM's id as people list and organizations list print it; repeat it for more", (value, previous = []) => [...previous, value],
194
+ // The empty default marks the flag as repeatable, so an agent's tool takes a list.
195
+ [])
196
+ .option("--title <title>", task ? "a task's title, needed for a task; a comment's title where the CRM keeps one" : "its title")
197
+ .option("--text <text>", comment ? "a comment's text, needed for a comment; a task's description" : "its text")
198
+ .option("--due <time>", "a task's deadline: an ISO 8601 time, a date (its end), today, or 2h, 3d from now; in your time zone")
199
+ .option("--owner <user>", "the CRM user a task is assigned to; anyone but the sign-in's own user checks crm.assign-others"), ...(comment ? ['activities create comment --subject deal:12 --text "Example: asked for a discount"'] : []), ...(task ? ['activities create task --subject deal:12 --title "Example: call back" --due 2026-12-01T10:00'] : [])).action(async (kind, opts, command) => {
200
+ await within(command, async (run) => {
201
+ const done = await createCrmActivity(contextOf(run, command), kind, {
202
+ on: opts.subject,
203
+ ...(opts.title === undefined ? {} : { title: opts.title }),
204
+ ...(opts.text === undefined ? {} : { body: opts.text }),
205
+ ...(opts.due === undefined ? {} : { dueAt: aheadOf(opts.due, "--due", now(), { end: true }) }),
206
+ ...(opts.owner === undefined ? {} : { owner: opts.owner }),
207
+ }, idOf(opts));
208
+ return answered(run, done);
209
+ });
210
+ });
211
+ if (task)
212
+ example(write("close", "mark a task done in the CRM, then store the CRM's copy of it when the activities setting is on").argument("<task>", "the task's id in the CRM, as activities list prints its external_id"), "activities close 42").action(async (id, opts, command) => {
213
+ await within(command, async (run) => answered(run, await completeCrmActivity(contextOf(run, command), id, idOf(opts))));
214
+ });
215
+ };
216
+ const writtenOf = (run, activity, on) => ({
217
+ external_id: activity.externalId,
218
+ kind: activity.kind,
219
+ subject: activity.subject,
220
+ body: activity.body ?? null,
221
+ due_at: iso(activity.dueAt ?? null),
222
+ done: activity.done,
223
+ assignee: activity.assignee ? crmIdentityId(run.account, activity.assignee, "user") : null,
224
+ created_at: new Date(activity.createdAt).toISOString(),
225
+ updated_at: new Date(activity.updatedAt).toISOString(),
226
+ on: on.map(({ kind, externalId, ref, title }) => ({ kind, external_id: externalId, ref, title })),
227
+ untrusted: UNTRUSTED,
228
+ });
@@ -1,5 +1,6 @@
1
1
  import { type Command } from "commander";
2
2
  import type { AppIdentity } from "../../ports/app.js";
3
+ import type { CrmWriteCapabilities } from "../writer.js";
3
4
  import type { CrmRun, CrmWithin } from "./index.js";
4
5
  export declare const CHANGES_QUERY: {
5
6
  readonly entity: "crm_change";
@@ -20,6 +21,8 @@ export interface CrmChangeCommandOptions {
20
21
  activities?: boolean;
21
22
  /** The CRM has leads; true when absent. */
22
23
  leads?: boolean;
24
+ /** The writer's capabilities: `activities create` and `close` when they name activities. */
25
+ writes?: CrmWriteCapabilities;
23
26
  }
24
27
  /** `changes list`: what happened in the copy in a window, newest first; `--format report` is the morning digest. */
25
28
  export declare const addCrmChangeCommands: (program: Command, options: CrmChangeCommandOptions) => void;
@@ -125,8 +125,17 @@ const digestState = (schedule) => `crm:digest:${schedule}`;
125
125
  export const addCrmChangeCommands = (program, options) => {
126
126
  const { within, example, now, ownerOf, pathOf } = options;
127
127
  const deals = options.leads === false ? "deals" : "deals and leads";
128
- if (options.activities)
129
- addCrmActivityCommands(program, { within, example, now, ownerOf, pathOf });
128
+ if (options.activities || options.writes?.activities?.length)
129
+ addCrmActivityCommands(program, {
130
+ within,
131
+ example,
132
+ now,
133
+ ownerOf,
134
+ pathOf,
135
+ list: options.activities === true,
136
+ ...(options.writes ? { writes: options.writes } : {}),
137
+ ...(options.leads === undefined ? {} : { leads: options.leads }),
138
+ });
130
139
  const group = annotate(program.command("changes"), { effects: NO_EFFECTS }).description(`what changed in the CRM's ${options.leads === false ? "deals" : "deals, leads"}, activities and contacts, ` +
131
140
  "as the syncs copied it");
132
141
  example(withQuery(answerEntity(annotate(group.command("list"), { effects: LOCAL_READ }), "crm_change", crmChange)
@@ -47,8 +47,9 @@ export interface CrmCommandOptions {
47
47
  /** The CRM has leads: mounts `leads list|show`. True when absent. */
48
48
  leads?: boolean;
49
49
  /**
50
- * The writer's capabilities: mounts `create`, `update`, `move`, `close` and `delete` of each deal kind it writes, and
51
- * `create` and `update` of `people` and `organizations` when they are mounted too.
50
+ * The writer's capabilities: mounts `create`, `update`, `move`, `close` and `delete` of each deal kind it writes,
51
+ * `create` and `update` of `people` and `organizations` when they are mounted too, and `activities create` and
52
+ * `done` for the activities it names.
52
53
  */
53
54
  writes?: CrmWriteCapabilities;
54
55
  /**
@@ -13,5 +13,5 @@ export { type CrmCursor, type CrmSyncIssue, type CrmSyncOptions, type CrmSyncRep
13
13
  export * as crmValues from "./values.js";
14
14
  export { type CrmViewing, crmViewerOf, withReadableDeal } from "./viewer.js";
15
15
  export { type CrmRows, type CrmWindow, crmWindowOf, walk } from "./walk.js";
16
- export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, type CrmDraft, type CrmDrafts, type CrmFields, type CrmOrganizationFields, type CrmPersonFields, type CrmVerb, type CrmWriteCapabilities, type CrmWriteFields, type CrmWriteOptions, type CrmWriter, crmAlsoChecks, } from "./writer.js";
17
- export { type CrmFieldsInput, type CrmRecordInput, type CrmRecordKind, type CrmRecordWritten, type CrmWriteContext, type CrmWrites, type CrmWritten, closeCrmItem, createCrmItem, createCrmRecord, crmCustomValues, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, type NamedField, optionOf, removeCrmItem, unknownField, updateCrmItem, updateCrmRecord, } from "./writes.js";
16
+ export { CRM_ACTIVITY_WRITES, CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, type CrmActivityDraft, type CrmActivityWrite, type CrmDraft, type CrmDrafts, type CrmFields, type CrmOrganizationFields, type CrmPersonFields, type CrmVerb, type CrmWriteCapabilities, type CrmWriteFields, type CrmWriteOptions, type CrmWriter, crmAlsoChecks, } from "./writer.js";
17
+ export { type CrmActivityInput, type CrmActivityTarget, type CrmActivityWritten, type CrmFieldsInput, type CrmRecordInput, type CrmRecordKind, type CrmRecordWritten, type CrmWriteContext, type CrmWrites, type CrmWritten, closeCrmItem, completeCrmActivity, createCrmActivity, createCrmItem, createCrmRecord, crmCustomValues, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, type NamedField, optionOf, removeCrmItem, unknownField, updateCrmItem, updateCrmRecord, } from "./writes.js";
package/dist/crm/index.js CHANGED
@@ -13,5 +13,5 @@ export { crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sy
13
13
  export * as crmValues from "./values.js";
14
14
  export { crmViewerOf, withReadableDeal } from "./viewer.js";
15
15
  export { crmWindowOf, walk } from "./walk.js";
16
- export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, crmAlsoChecks, } from "./writer.js";
17
- export { closeCrmItem, createCrmItem, createCrmRecord, crmCustomValues, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, optionOf, removeCrmItem, unknownField, updateCrmItem, updateCrmRecord, } from "./writes.js";
16
+ export { CRM_ACTIVITY_WRITES, CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, crmAlsoChecks, } from "./writer.js";
17
+ export { closeCrmItem, completeCrmActivity, createCrmActivity, createCrmItem, createCrmRecord, crmCustomValues, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, optionOf, removeCrmItem, unknownField, updateCrmItem, updateCrmRecord, } from "./writes.js";
@@ -1,7 +1,7 @@
1
1
  export { ACME_CALENDAR, ACME_MAIL, ACME_NOW, ACME_OPENED, ACME_PORTAL, ACME_TELEGRAM, type AcmeScenario, acmeScenario, } from "./acme-scenario.js";
2
2
  export { type CrmFilesFixture, crmFilesContract } from "./files-contract.js";
3
3
  export { type CrmManifestFake, type CrmManifestFakeOptions, type CrmManifestFixtureOptions, crmManifestContract, crmManifestFake, crmManifestFixture, crmManifestWriteContract, crmManifestWriteFixture, FAKE_MANIFEST_TOKEN, } from "./manifest-fake.js";
4
- export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, FAKE_FILE_TOKEN, type FakeCrmFile, type FakeCrmSource, type FakeCrmSourceOptions, type FakeCrmWrite, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
4
+ export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, FAKE_FILE_TOKEN, type FakeCrmActivityWrite, type FakeCrmFile, type FakeCrmSource, type FakeCrmSourceOptions, type FakeCrmWrite, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
5
5
  export { type CrmSourceFaults, type CrmSourceFixture, crmSourceContract } from "./source-contract.js";
6
6
  export { CRM_TRAIT_COMBINATIONS, type CrmSyncFixture, crmSyncContract } from "./sync-contract.js";
7
7
  export { type CrmWriteFixture, crmWriteContract } from "./write-contract.js";
@@ -59,6 +59,12 @@ export interface FakeCrmWrite {
59
59
  externalId: string | null;
60
60
  operationId: string;
61
61
  }
62
+ /** One activity write the fake CRM was sent, in order. */
63
+ export interface FakeCrmActivityWrite {
64
+ verb: "create" | "done";
65
+ externalId: string | null;
66
+ operationId: string;
67
+ }
62
68
  /**
63
69
  * A CRM held in memory, with a change feed and a write side: what the contracts sync and write against, and what a
64
70
  * CLI's tests may use. Custom field codes `stage`, `pipeline`, `owner` and `status` are refused, as an adapter refuses
@@ -95,6 +101,8 @@ export interface FakeCrmSource extends CrmSource, CrmWriter {
95
101
  };
96
102
  /** Writes sent, refused ones included. */
97
103
  readonly writes: FakeCrmWrite[];
104
+ /** Activity writes sent, refused ones included; the fake makes them only when `capabilities.activities` is set. */
105
+ readonly activityWrites: FakeCrmActivityWrite[];
98
106
  }
99
107
  /** Custom codes the fake refuses: each is a neutral field under another name. */
100
108
  export declare const FAKE_CRM_ALIASES: string[];
@@ -62,6 +62,8 @@ export const fakeCrmSource = (options = {}) => {
62
62
  ...options.capabilities,
63
63
  };
64
64
  const writes = [];
65
+ const activityWrites = [];
66
+ const madeActivities = new Map();
65
67
  const answered = new Map();
66
68
  let made = 0;
67
69
  let lose = false;
@@ -127,6 +129,9 @@ export const fakeCrmSource = (options = {}) => {
127
129
  /** Each write once: a repeated idempotent id answers its first outcome; a lost answer still made the change. */
128
130
  const write = (verb, kind, externalId, operationId, act) => {
129
131
  writes.push({ verb, kind, externalId, operationId });
132
+ return sent(`${verb} but its ${kind}`, operationId, act);
133
+ };
134
+ const sent = (what, operationId, act) => {
130
135
  if (capabilities.idempotent && answered.has(operationId))
131
136
  return answered.get(operationId);
132
137
  const done = act();
@@ -138,7 +143,7 @@ export const fakeCrmSource = (options = {}) => {
138
143
  }
139
144
  if (unread) {
140
145
  unread = false;
141
- throw new CliError("provider_error", `the CRM made the ${verb} but its ${kind} could not be read back`, {
146
+ throw new CliError("provider_error", `the CRM made the ${what} could not be read back`, {
142
147
  sent: true,
143
148
  });
144
149
  }
@@ -208,6 +213,50 @@ export const fakeCrmSource = (options = {}) => {
208
213
  reason: "query.unsupported-field",
209
214
  });
210
215
  };
216
+ /** Comments and tasks on records the fake holds; each a new change, read by `activities()` when it is given. */
217
+ const activityWriter = () => ({
218
+ async createActivity(draft, { operationId }) {
219
+ activityWrites.push({ verb: "create", externalId: null, operationId });
220
+ return sent("activity but it", operationId, () => {
221
+ for (const { kind, externalId } of draft.on)
222
+ if (kind === "deal" || kind === "lead")
223
+ held(kind, externalId);
224
+ else
225
+ liveRecord(kind, externalId);
226
+ version += 1;
227
+ made += 1;
228
+ const at = STAMPED_FROM + version * 1000;
229
+ const activity = {
230
+ externalId: `activity-new-${made}`,
231
+ kind: draft.kind,
232
+ subject: draft.subject ?? "",
233
+ body: draft.body ?? null,
234
+ dueAt: draft.dueAt ?? null,
235
+ done: draft.kind === "comment",
236
+ assignee: draft.kind === "task" ? (draft.assignee ?? options.self ?? null) : null,
237
+ createdAt: at,
238
+ updatedAt: at,
239
+ on: draft.on,
240
+ };
241
+ madeActivities.set(activity.externalId, activity);
242
+ return activity;
243
+ });
244
+ },
245
+ async completeActivity(externalId, { operationId }) {
246
+ activityWrites.push({ verb: "done", externalId, operationId });
247
+ return sent("done but the task", operationId, () => {
248
+ const found = madeActivities.get(externalId) ?? options.activities?.find((one) => one.externalId === externalId);
249
+ if (!found)
250
+ throw new CliError("not_found", `the CRM has no activity ${externalId}`);
251
+ if (found.kind !== "task")
252
+ throw new CliError("validation_error", `${externalId} is not a task`);
253
+ version += 1;
254
+ const done = { ...found, done: true, updatedAt: STAMPED_FROM + version * 1000 };
255
+ madeActivities.set(externalId, done);
256
+ return done;
257
+ });
258
+ },
259
+ });
211
260
  const fake = {
212
261
  provider: "example-crm",
213
262
  traits,
@@ -215,6 +264,7 @@ export const fakeCrmSource = (options = {}) => {
215
264
  calls,
216
265
  capabilities,
217
266
  writes,
267
+ activityWrites,
218
268
  loseNextAnswer() {
219
269
  lose = true;
220
270
  },
@@ -249,6 +299,7 @@ export const fakeCrmSource = (options = {}) => {
249
299
  });
250
300
  return answer;
251
301
  },
302
+ ...(capabilities.activities?.length ? activityWriter() : {}),
252
303
  ...(options.admin === undefined ? {} : { isAdmin: async () => options.admin }),
253
304
  ...(options.stageHistory === undefined
254
305
  ? {}
@@ -264,7 +315,10 @@ export const fakeCrmSource = (options = {}) => {
264
315
  ? {}
265
316
  : {
266
317
  activities: async (since) => {
267
- const items = options.activities.filter((one) => one.updatedAt > since);
318
+ const all = new Map(options.activities.map((one) => [one.externalId, one]));
319
+ for (const [id, one] of madeActivities)
320
+ all.set(id, one);
321
+ const items = [...all.values()].filter((one) => one.updatedAt > since);
268
322
  const newest = Math.max(since, ...items.map((one) => one.updatedAt));
269
323
  return { items, hasMore: false, cursor: String(newest) };
270
324
  },