@wirecat/cli-core 0.733.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.
- package/CHANGELOG.md +14 -0
- package/dist/cli/messenger/search-command.js +1 -0
- package/dist/cli/option-hints.d.ts +7 -0
- package/dist/cli/option-hints.js +25 -0
- package/dist/cli/program.js +13 -23
- package/dist/cli/steps.d.ts +2 -0
- package/dist/cli/steps.js +15 -0
- package/dist/crm/cli/activities.d.ts +12 -2
- package/dist/crm/cli/activities.js +101 -6
- package/dist/crm/cli/changes.d.ts +3 -0
- package/dist/crm/cli/changes.js +11 -2
- package/dist/crm/cli/index.d.ts +3 -2
- package/dist/crm/index.d.ts +2 -2
- package/dist/crm/index.js +2 -2
- package/dist/crm/testing/index.d.ts +1 -1
- package/dist/crm/testing/source.d.ts +8 -0
- package/dist/crm/testing/source.js +56 -2
- package/dist/crm/writer.d.ts +30 -1
- package/dist/crm/writer.js +4 -0
- package/dist/crm/writes.d.ts +34 -2
- package/dist/crm/writes.js +100 -0
- package/dist/errors/reasons.js +1 -0
- package/dist/services/embeddings-search.js +29 -3
- package/dist/store/conversations.d.ts +16 -0
- package/dist/store/conversations.js +7 -0
- package/dist/store/sqlite/conversations.d.ts +16 -0
- package/dist/store/sqlite/conversations.js +49 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,20 @@ 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
|
+
|
|
8
22
|
## 0.733.0 — 23.11.2026
|
|
9
23
|
|
|
10
24
|
### 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;
|
package/dist/cli/option-hints.js
CHANGED
|
@@ -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
|
+
};
|
package/dist/cli/program.js
CHANGED
|
@@ -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,
|
|
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,
|
|
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
|
-
|
|
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 =
|
|
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 =
|
|
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 =
|
|
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 =
|
|
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));
|
package/dist/cli/steps.d.ts
CHANGED
|
@@ -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
|
|
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
|
-
/**
|
|
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
|
|
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
|
-
/**
|
|
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(
|
|
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;
|
package/dist/crm/cli/changes.js
CHANGED
|
@@ -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, {
|
|
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)
|
package/dist/crm/cli/index.d.ts
CHANGED
|
@@ -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,
|
|
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
|
/**
|
package/dist/crm/index.d.ts
CHANGED
|
@@ -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 ${
|
|
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
|
|
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
|
},
|
package/dist/crm/writer.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import type { ConditionalKey } from "../cli/permission-keys.js";
|
|
2
|
-
import type { CrmItem, CrmKind, CrmRecords } from "../domain/crm.js";
|
|
2
|
+
import type { CrmActivity, CrmItem, CrmKind, CrmRecords } from "../domain/crm.js";
|
|
3
3
|
import type { DealKind, DealRole } from "../domain/deals.js";
|
|
4
4
|
import type { Level, PermissionKey } from "../sends/permissions.js";
|
|
5
5
|
export declare const CRM_VERBS: readonly ["create", "update", "move", "close", "remove"];
|
|
6
6
|
export type CrmVerb = (typeof CRM_VERBS)[number];
|
|
7
|
+
/** The activities a CRM CLI may write: a comment (a note) on a record, and a task, which it may later mark done. */
|
|
8
|
+
export declare const CRM_ACTIVITY_WRITES: readonly ["comment", "task"];
|
|
9
|
+
export type CrmActivityWrite = (typeof CRM_ACTIVITY_WRITES)[number];
|
|
7
10
|
export interface CrmWriteCapabilities {
|
|
8
11
|
/** The kinds the CRM takes writes for; a contact or a company takes only `create` and `update`. */
|
|
9
12
|
kinds: readonly CrmKind[];
|
|
@@ -14,6 +17,11 @@ export interface CrmWriteCapabilities {
|
|
|
14
17
|
* create repeated with one REST 3.0 `Idempotency-Key` a second time.
|
|
15
18
|
*/
|
|
16
19
|
idempotent: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* The activities the writer makes: mounts `activities create` for these kinds, and `activities close` for a task.
|
|
22
|
+
* Left out, the CLI gets neither, and the writer needs no `createActivity` or `completeActivity`.
|
|
23
|
+
*/
|
|
24
|
+
activities?: readonly CrmActivityWrite[];
|
|
17
25
|
}
|
|
18
26
|
/**
|
|
19
27
|
* A deal's or lead's fields in `CrmItem`'s names, each the CRM's own id; `null` clears one. `custom` holds the CRM's
|
|
@@ -81,6 +89,23 @@ export interface CrmDrafts {
|
|
|
81
89
|
name: string;
|
|
82
90
|
};
|
|
83
91
|
}
|
|
92
|
+
/** A new comment or task on one or more of the CRM's deals, leads, contacts and companies. */
|
|
93
|
+
export interface CrmActivityDraft {
|
|
94
|
+
kind: CrmActivityWrite;
|
|
95
|
+
/** A task's title; a comment's title, for a CRM that keeps one. Required for a task. */
|
|
96
|
+
subject?: string;
|
|
97
|
+
/** A comment's text, or a task's description. Required for a comment. */
|
|
98
|
+
body?: string;
|
|
99
|
+
/** A task's deadline, epoch ms. */
|
|
100
|
+
dueAt?: number;
|
|
101
|
+
/** A task's CRM user, by the CRM's id; left out, the CRM's own default (most often the sign-in's user). */
|
|
102
|
+
assignee?: string;
|
|
103
|
+
/** The records it is on, by the CRM's ids: at least one. */
|
|
104
|
+
on: {
|
|
105
|
+
kind: CrmKind;
|
|
106
|
+
externalId: string;
|
|
107
|
+
}[];
|
|
108
|
+
}
|
|
84
109
|
export interface CrmWriteOptions {
|
|
85
110
|
/** Journaled before the call; an idempotent CRM gets it as its idempotency key. */
|
|
86
111
|
operationId: string;
|
|
@@ -106,6 +131,10 @@ export interface CrmWriter {
|
|
|
106
131
|
reason?: string;
|
|
107
132
|
}): Promise<CrmItem>;
|
|
108
133
|
remove(kind: DealKind, externalId: string, options: CrmWriteOptions): Promise<void>;
|
|
134
|
+
/** Needed when `capabilities.activities` names any: the new activity as the CRM holds it. */
|
|
135
|
+
createActivity?(draft: CrmActivityDraft, options: CrmWriteOptions): Promise<CrmActivity>;
|
|
136
|
+
/** Needed when `capabilities.activities` names `task`: the task, done, as the CRM holds it. */
|
|
137
|
+
completeActivity?(externalId: string, options: CrmWriteOptions): Promise<CrmActivity>;
|
|
109
138
|
}
|
|
110
139
|
/** Giving a record to a CRM user other than the one the sign-in acts as. */
|
|
111
140
|
export declare const CRM_ASSIGN_OTHERS_KEY: PermissionKey;
|
package/dist/crm/writer.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export const CRM_VERBS = ["create", "update", "move", "close", "remove"];
|
|
2
|
+
/** The activities a CRM CLI may write: a comment (a note) on a record, and a task, which it may later mark done. */
|
|
3
|
+
export const CRM_ACTIVITY_WRITES = ["comment", "task"];
|
|
2
4
|
/** Giving a record to a CRM user other than the one the sign-in acts as. */
|
|
3
5
|
export const CRM_ASSIGN_OTHERS_KEY = "crm.assign-others";
|
|
4
6
|
/** The keys the CRM writes check beyond their command paths, for a CLI's `commandPermissions({ extra })`. */
|
|
@@ -23,6 +25,8 @@ const VERB_OF = {
|
|
|
23
25
|
*/
|
|
24
26
|
export const crmAlsoChecks = (also) => (path) => {
|
|
25
27
|
const [noun, command] = path;
|
|
28
|
+
if (noun === "activities" && command === "create" && path.length === 2)
|
|
29
|
+
return [{ key: CRM_ASSIGN_OTHERS_KEY, when: "--owner other than the sign-in's user" }];
|
|
26
30
|
const kind = noun === undefined ? undefined : PLURALS[noun];
|
|
27
31
|
const verb = command === undefined ? undefined : VERB_OF[command];
|
|
28
32
|
if (path.length !== 2 || kind === undefined || verb === undefined)
|
package/dist/crm/writes.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
-
import type
|
|
2
|
+
import { type CrmActivity, type CrmField, type CrmKind, type CrmOrganization, type CrmPerson } from "../domain/crm.js";
|
|
3
3
|
import type { DealKind } from "../domain/deals.js";
|
|
4
4
|
import type { Asker } from "../sends/guard.js";
|
|
5
5
|
import type { PermissionKey } from "../sends/permissions.js";
|
|
@@ -8,7 +8,7 @@ import type { Deal, PipelineOptions, PipelineReport } from "../store/sqlite/deal
|
|
|
8
8
|
import type { MessageStore } from "../store/store.js";
|
|
9
9
|
import type { AccountKey } from "../store/types.js";
|
|
10
10
|
import type { CrmSource } from "./source.js";
|
|
11
|
-
import { type CrmVerb, type CrmWriter } from "./writer.js";
|
|
11
|
+
import { type CrmActivityWrite, type CrmVerb, type CrmWriter } from "./writer.js";
|
|
12
12
|
/** What a CLI hands the CRM writes for one profile. */
|
|
13
13
|
export interface CrmWrites extends ProfileWrites {
|
|
14
14
|
writer: CrmWriter;
|
|
@@ -135,3 +135,35 @@ export declare const createCrmRecord: <K extends CrmRecordKind>(context: CrmWrit
|
|
|
135
135
|
export declare const updateCrmRecord: <K extends CrmRecordKind>(context: CrmWriteContext, kind: K, externalId: string, input: CrmRecordInput, options?: {
|
|
136
136
|
operationId?: string;
|
|
137
137
|
}) => Promise<CrmRecordWritten<K>>;
|
|
138
|
+
/** A comment or task as typed: `on`, the records it is on, as `deal:12`, `lead:4` (the copy's), or `person:<id>`, `organization:<id>` (the CRM's). */
|
|
139
|
+
export interface CrmActivityInput {
|
|
140
|
+
title?: string;
|
|
141
|
+
body?: string;
|
|
142
|
+
/** A task's deadline, epoch ms. */
|
|
143
|
+
dueAt?: number;
|
|
144
|
+
owner?: string;
|
|
145
|
+
on: readonly string[];
|
|
146
|
+
}
|
|
147
|
+
/** A record an activity is on: the copy's reference and title when the copy holds it. */
|
|
148
|
+
export interface CrmActivityTarget {
|
|
149
|
+
kind: CrmKind;
|
|
150
|
+
externalId: string;
|
|
151
|
+
ref: string | null;
|
|
152
|
+
title: string | null;
|
|
153
|
+
}
|
|
154
|
+
export interface CrmActivityWritten {
|
|
155
|
+
operationId: string;
|
|
156
|
+
/** The CRM's answer. */
|
|
157
|
+
activity: CrmActivity;
|
|
158
|
+
/** Whether the copy keeps it: only with the activities setting on, and on a record the copy keeps, as a sync does. */
|
|
159
|
+
stored: boolean;
|
|
160
|
+
on: CrmActivityTarget[];
|
|
161
|
+
}
|
|
162
|
+
/** A new comment or task on records of the CRM, through the guarded path; the CRM's answer is stored as a sync would. */
|
|
163
|
+
export declare const createCrmActivity: (context: CrmWriteContext, kind: CrmActivityWrite, input: CrmActivityInput, options?: {
|
|
164
|
+
operationId?: string;
|
|
165
|
+
}) => Promise<CrmActivityWritten>;
|
|
166
|
+
/** A task marked done in the CRM by its id, as `activities list` prints it; the copy is stored again. */
|
|
167
|
+
export declare const completeCrmActivity: (context: CrmWriteContext, externalId: string, options?: {
|
|
168
|
+
operationId?: string;
|
|
169
|
+
}) => Promise<CrmActivityWritten>;
|
package/dist/crm/writes.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
2
|
+
import { isItemKind, } from "../domain/crm.js";
|
|
2
3
|
import { currencyOf, minorUnits } from "../domain/money.js";
|
|
3
4
|
import { e164Of } from "../domain/phones.js";
|
|
4
5
|
import { foldName } from "../resolve.js";
|
|
@@ -511,3 +512,102 @@ export const updateCrmRecord = async (context, kind, externalId, input, options
|
|
|
511
512
|
const operationId = operationOf(context, options.operationId);
|
|
512
513
|
return writeRecord(context, kind, "update", fields, operationId, () => writer.update(kind, externalId, fields, { operationId }));
|
|
513
514
|
};
|
|
515
|
+
const MOST_SUBJECT = 500;
|
|
516
|
+
const MOST_BODY = 20_000;
|
|
517
|
+
const activityInvalid = (message, param) => new CliError("validation_error", message, { reason: "crm.activity-field", ...(param ? { param } : {}) });
|
|
518
|
+
const activityUnsupported = (what) => new CliError("validation_error", `this CRM does not take ${what}`, { reason: "crm.write-unsupported", sent: false });
|
|
519
|
+
/** `deal:12` and `lead:4` by the copy, as `deals list` shows them; a contact or company by the CRM's id. */
|
|
520
|
+
const activityTargetOf = async (context, given) => {
|
|
521
|
+
const at = given.indexOf(":");
|
|
522
|
+
const kind = given.slice(0, at);
|
|
523
|
+
const id = given.slice(at + 1);
|
|
524
|
+
if (kind === "deal" || kind === "lead") {
|
|
525
|
+
const copy = await copyOf(context, kind, given.trim());
|
|
526
|
+
return { kind, externalId: copy.externalId, ref: copy.ref, title: copy.title };
|
|
527
|
+
}
|
|
528
|
+
if ((kind === "person" || kind === "organization") && RECORD_ID.test(id))
|
|
529
|
+
return { kind, externalId: id, ref: null, title: null };
|
|
530
|
+
throw new CliError("validation_error", `--subject takes deal:<id> or lead:<id> as a list shows it, or person:<id> or organization:<id> by the CRM's id; got ${given}`, { reason: "ref.malformed", param: "--subject" });
|
|
531
|
+
};
|
|
532
|
+
const activityKeys = async (context, key, owner) => ({
|
|
533
|
+
key,
|
|
534
|
+
extra: owner !== undefined && owner !== (await selfOf(context)) ? [CRM_ASSIGN_OTHERS_KEY] : [],
|
|
535
|
+
});
|
|
536
|
+
/** The CRM's answer into the store, as a sync saves it; a failure names the activity, which the CRM has written. */
|
|
537
|
+
const keptActivity = async (context, activity, operationId) => {
|
|
538
|
+
try {
|
|
539
|
+
if (!(await context.store.crm.activitiesOn(context.account)))
|
|
540
|
+
return false;
|
|
541
|
+
return (await context.store.crm.saveActivities(context.account, [activity])).saved === 1;
|
|
542
|
+
}
|
|
543
|
+
catch (error) {
|
|
544
|
+
throw new CliError("invalid_response", `the CRM wrote activity ${activity.externalId}, but the local store did not keep it ` +
|
|
545
|
+
`(${error instanceof Error ? error.message : String(error)}); sync to store it — do not write it again`, { external_id: activity.externalId, operation_id: operationId, sent: true });
|
|
546
|
+
}
|
|
547
|
+
};
|
|
548
|
+
/** The records the CRM answered it is on; a deal or lead the copy holds by its reference too. */
|
|
549
|
+
const answeredTargets = async (context, activity, known) => Promise.all(activity.on.map(async ({ kind, externalId }) => known.find((one) => one.kind === kind && one.externalId === externalId) ?? {
|
|
550
|
+
kind,
|
|
551
|
+
externalId,
|
|
552
|
+
ref: isItemKind(kind) ? await context.store.crm.refOf(context.account, kind, externalId) : null,
|
|
553
|
+
title: null,
|
|
554
|
+
}));
|
|
555
|
+
/** A new comment or task on records of the CRM, through the guarded path; the CRM's answer is stored as a sync would. */
|
|
556
|
+
export const createCrmActivity = async (context, kind, input, options = {}) => {
|
|
557
|
+
const { writer } = context.writes;
|
|
558
|
+
const create = writer.createActivity?.bind(writer);
|
|
559
|
+
if (!create || !writer.capabilities.activities?.includes(kind))
|
|
560
|
+
throw activityUnsupported(`a new ${kind}`);
|
|
561
|
+
const subject = input.title?.trim();
|
|
562
|
+
const body = input.body?.trim();
|
|
563
|
+
if (subject !== undefined && (subject === "" || subject.length > MOST_SUBJECT))
|
|
564
|
+
throw activityInvalid(`--title is 1 to ${MOST_SUBJECT} characters`, "--title");
|
|
565
|
+
if (body !== undefined && (body === "" || body.length > MOST_BODY))
|
|
566
|
+
throw activityInvalid(`--text is 1 to ${MOST_BODY} characters`, "--text");
|
|
567
|
+
if (kind === "task" && subject === undefined)
|
|
568
|
+
throw activityInvalid("a new task needs --title", "--title");
|
|
569
|
+
if (kind === "comment" && body === undefined)
|
|
570
|
+
throw activityInvalid("a new comment needs --text", "--text");
|
|
571
|
+
if (kind === "comment" && input.dueAt !== undefined)
|
|
572
|
+
throw activityInvalid("a comment has no --due", "--due");
|
|
573
|
+
if (kind === "comment" && input.owner !== undefined)
|
|
574
|
+
throw activityInvalid("a comment has no --owner", "--owner");
|
|
575
|
+
const owner = input.owner?.trim();
|
|
576
|
+
if (owner !== undefined && !owner)
|
|
577
|
+
throw activityInvalid("--owner is the CRM user's id", "--owner");
|
|
578
|
+
if (input.on.length === 0)
|
|
579
|
+
throw activityInvalid("name the record it is on with --subject, such as deal:12", "--subject");
|
|
580
|
+
const targets = [];
|
|
581
|
+
for (const given of input.on) {
|
|
582
|
+
const target = await activityTargetOf(context, given);
|
|
583
|
+
if (!targets.some((one) => one.kind === target.kind && one.externalId === target.externalId))
|
|
584
|
+
targets.push(target);
|
|
585
|
+
}
|
|
586
|
+
const draft = {
|
|
587
|
+
kind,
|
|
588
|
+
...(subject === undefined ? {} : { subject }),
|
|
589
|
+
...(body === undefined ? {} : { body }),
|
|
590
|
+
...(input.dueAt === undefined ? {} : { dueAt: input.dueAt }),
|
|
591
|
+
...(owner === undefined ? {} : { assignee: owner }),
|
|
592
|
+
on: targets.map(({ kind, externalId }) => ({ kind, externalId })),
|
|
593
|
+
};
|
|
594
|
+
const operationId = operationOf(context, options.operationId);
|
|
595
|
+
const activity = await written(context, await activityKeys(context, "activities.create", owner), operationId, () => create(draft, { operationId }));
|
|
596
|
+
const stored = await keptActivity(context, activity, operationId);
|
|
597
|
+
return { operationId, activity, stored, on: await answeredTargets(context, activity, targets) };
|
|
598
|
+
};
|
|
599
|
+
/** A task marked done in the CRM by its id, as `activities list` prints it; the copy is stored again. */
|
|
600
|
+
export const completeCrmActivity = async (context, externalId, options = {}) => {
|
|
601
|
+
const { writer } = context.writes;
|
|
602
|
+
const complete = writer.completeActivity?.bind(writer);
|
|
603
|
+
if (!complete || !writer.capabilities.activities?.includes("task"))
|
|
604
|
+
throw activityUnsupported("a task marked done");
|
|
605
|
+
if (!RECORD_ID.test(externalId))
|
|
606
|
+
throw new CliError("validation_error", "name the task by the CRM's id, as activities list prints it", {
|
|
607
|
+
reason: "ref.malformed",
|
|
608
|
+
});
|
|
609
|
+
const operationId = operationOf(context, options.operationId);
|
|
610
|
+
const activity = await written(context, await activityKeys(context, "activities.close", undefined), operationId, () => complete(externalId, { operationId }));
|
|
611
|
+
const stored = await keptActivity(context, activity, operationId);
|
|
612
|
+
return { operationId, activity, stored, on: await answeredTargets(context, activity, []) };
|
|
613
|
+
};
|
package/dist/errors/reasons.js
CHANGED
|
@@ -567,6 +567,7 @@ const OTHERS = [
|
|
|
567
567
|
validation("field.not-filterable", "the CRM cannot filter a list by that custom field"),
|
|
568
568
|
validation("query.bad-value", "a term's value is not the kind its field takes, such as an id or a number"),
|
|
569
569
|
validation("crm.record-field", "a contact's or company's field is not valid"),
|
|
570
|
+
validation("crm.activity-field", "a comment's or task's field is not valid, or the kind does not take it"),
|
|
570
571
|
validation("crm.owner-unknown", "owner: names no CRM user: me without a known sign-in user, or not a user id"),
|
|
571
572
|
validation("crm.write-unsupported", "the CRM does not take this write, or does not recognise a repeated one"),
|
|
572
573
|
validation("crm.unlisted-held", "a list of every id would mark most of a kind deleted; nothing was, until --rescan"),
|
|
@@ -38,6 +38,8 @@ const SHOWN_HEAD = 80;
|
|
|
38
38
|
const CHUNK_READ = 60;
|
|
39
39
|
/** Replies from outside a hit's chunk read per hit; the best one is shown with its lines. */
|
|
40
40
|
const REPLIES_READ = 60;
|
|
41
|
+
/** A conversation with more chunks than this is near any question, so its nearest chunk is often another topic. */
|
|
42
|
+
const BIG_CONVERSATION = 50;
|
|
41
43
|
/** Reciprocal rank fusion's usual constant (phase 5 E9). */
|
|
42
44
|
const RRF_K = 60;
|
|
43
45
|
export const embeddingsSearch = (deps) => {
|
|
@@ -211,9 +213,10 @@ export const embeddingsSearch = (deps) => {
|
|
|
211
213
|
const meaning = texts.map(() => []);
|
|
212
214
|
const own = [];
|
|
213
215
|
const sources = words.sources;
|
|
216
|
+
let vectors = [];
|
|
214
217
|
if (target.installed && prepared.scopeAccounts.length && eligibility?.conversations.length !== 0) {
|
|
215
218
|
await withEmbedder(deps, target, choice, {}, async (embedder) => {
|
|
216
|
-
|
|
219
|
+
vectors = (await embedder.embed(texts, "query"));
|
|
217
220
|
for (const [at, vector] of vectors.entries())
|
|
218
221
|
for (const one of prepared.scopeAccounts) {
|
|
219
222
|
const scope = scopeOf(one);
|
|
@@ -300,9 +303,26 @@ export const embeddingsSearch = (deps) => {
|
|
|
300
303
|
locator: formatLocator({ ...source, chat: hit.summary.chatId, message: hit.chunk.firstMessageId }),
|
|
301
304
|
};
|
|
302
305
|
};
|
|
303
|
-
|
|
306
|
+
// Only with a made-up reply: on the question alone it moved shown answers off their chunk.
|
|
307
|
+
const stemmed = [
|
|
308
|
+
...chunkStems(query).map((stem) => ({ stem, weight: 2 })),
|
|
309
|
+
...texts.slice(1).flatMap((text) => chunkStems(text).map((stem) => ({ stem, weight: 1 }))),
|
|
310
|
+
];
|
|
311
|
+
const rechunked = async (hit) => {
|
|
312
|
+
const source = sources.get(hit.summary.id);
|
|
313
|
+
if (texts.length < 2 || hit.matchedIn || !vectors.length || !source)
|
|
314
|
+
return hit;
|
|
315
|
+
const chunk = await store.conversations.bestChunk(source, hit.summary.id, {
|
|
316
|
+
model: target.key,
|
|
317
|
+
vectors,
|
|
318
|
+
stems: stemmed,
|
|
319
|
+
over: BIG_CONVERSATION,
|
|
320
|
+
});
|
|
321
|
+
return chunk ? { ...hit, chunk } : hit;
|
|
322
|
+
};
|
|
323
|
+
const hits = (await Promise.all(fused(meaning.map((list) => list.map(({ hit }) => hit)), words.hits, meaningFloor(target.key))
|
|
304
324
|
.slice(0, limit)
|
|
305
|
-
.map(located);
|
|
325
|
+
.map(rechunked))).map(located);
|
|
306
326
|
const shown = new Set(hits.map((hit) => hit.summary.id));
|
|
307
327
|
const ownOf = (keep) => own
|
|
308
328
|
.filter(keep)
|
|
@@ -482,6 +502,12 @@ const fused = (meaning, words, minimumCosine) => {
|
|
|
482
502
|
.sort((a, b) => b.fused - a.fused || (b.score ?? -2) - (a.score ?? -2))
|
|
483
503
|
.map(({ fused: _, ...hit }) => hit);
|
|
484
504
|
};
|
|
505
|
+
/** Every word of three letters or more, stop words too, by its first five letters. */
|
|
506
|
+
const chunkStems = (text) => [
|
|
507
|
+
...new Set((text.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? [])
|
|
508
|
+
.filter((word) => word.length >= 3)
|
|
509
|
+
.map((word) => word.slice(0, 5))),
|
|
510
|
+
];
|
|
485
511
|
/** Each word's first five letters, lowercased: enough to match its other forms in Russian and English. */
|
|
486
512
|
const wordStems = (text) => [...new Set(queryWords(text).map((word) => word.slice(0, 5)))];
|
|
487
513
|
/**
|
|
@@ -58,6 +58,22 @@ export interface ConversationsStore {
|
|
|
58
58
|
text: string;
|
|
59
59
|
outgoing: boolean;
|
|
60
60
|
}[][]>;
|
|
61
|
+
/**
|
|
62
|
+
* In a conversation of more than `over` chunks, the chunk that ranks best by summed cosine to `vectors` and by the
|
|
63
|
+
* weighted rarity of `stems` among its chunks, fused; `undefined` for a smaller conversation.
|
|
64
|
+
*/
|
|
65
|
+
bestChunk(key: AccountKey, conversationId: string, search: {
|
|
66
|
+
model: string;
|
|
67
|
+
vectors: Float32Array[];
|
|
68
|
+
stems: {
|
|
69
|
+
stem: string;
|
|
70
|
+
weight: number;
|
|
71
|
+
}[];
|
|
72
|
+
over: number;
|
|
73
|
+
}): Promise<{
|
|
74
|
+
firstMessageId: Id;
|
|
75
|
+
lastMessageId: Id;
|
|
76
|
+
} | undefined>;
|
|
61
77
|
/** Every link a message has, the messenger's first. */
|
|
62
78
|
links(key: AccountKey, chatId: Id, messageId: Id, options?: {
|
|
63
79
|
limit: number;
|
|
@@ -64,6 +64,13 @@ export const conversationsStoreOver = (context) => {
|
|
|
64
64
|
? chunks.map(() => [])
|
|
65
65
|
: conversationQueries.chunkRepliesOf(context, accountPk, chunks, limit);
|
|
66
66
|
},
|
|
67
|
+
bestChunk: async (key, conversationId, search) => {
|
|
68
|
+
const accountPk = findAccountPk(key);
|
|
69
|
+
const pk = Number(conversationId);
|
|
70
|
+
return accountPk === undefined || !Number.isSafeInteger(pk)
|
|
71
|
+
? undefined
|
|
72
|
+
: conversationQueries.bestChunkOf(context, accountPk, pk, search);
|
|
73
|
+
},
|
|
67
74
|
links: async (key, chatId, messageId, options) => {
|
|
68
75
|
const chatKey = chatKeyOf(key, chatId);
|
|
69
76
|
return chatKey === undefined ? [] : conversationQueries.linksOf(context, chatKey, messageId, options?.limit);
|
|
@@ -90,6 +90,22 @@ export declare const chunkRepliesOf: ({ orm }: StoreContext, accountPk: number,
|
|
|
90
90
|
text: string;
|
|
91
91
|
outgoing: boolean;
|
|
92
92
|
}[][];
|
|
93
|
+
/**
|
|
94
|
+
* Rarity counts over the conversation's own chunks, not the store: a word every chunk holds says nothing about which
|
|
95
|
+
* one is meant. A word may sit anywhere in a chunk's text, as the shown lines match it.
|
|
96
|
+
*/
|
|
97
|
+
export declare const bestChunkOf: ({ orm }: StoreContext, accountPk: number, conversationPk: number, { model, vectors, stems, over, }: {
|
|
98
|
+
model: string;
|
|
99
|
+
vectors: Float32Array[];
|
|
100
|
+
stems: {
|
|
101
|
+
stem: string;
|
|
102
|
+
weight: number;
|
|
103
|
+
}[];
|
|
104
|
+
over: number;
|
|
105
|
+
}) => {
|
|
106
|
+
firstMessageId: Id;
|
|
107
|
+
lastMessageId: Id;
|
|
108
|
+
} | undefined;
|
|
93
109
|
/** Every link a message has, the messenger's first, then the strongest. */
|
|
94
110
|
export declare const linksOf: ({ orm }: StoreContext, chatKey: number, messageId: Id, limit?: number) => StoredLink[];
|
|
95
111
|
/** Candidates only: the caller checks which parent each child chooses, using the same link reader. */
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { setTimeout } from "node:timers/promises";
|
|
2
|
+
import { RRF_K } from "../../search/fusion.js";
|
|
2
3
|
import { and, asc, desc, eq, isNull, sql } from "./drizzle/core.js";
|
|
3
4
|
import { linkKind } from "./link-kinds.js";
|
|
4
5
|
import { bound } from "./query-filter.js";
|
|
@@ -6,7 +7,7 @@ import { selectMessages, toMessages } from "./reads.js";
|
|
|
6
7
|
import { accounts, chats, chunkMessages, chunks as chunkRows, conversationMessages, conversationState, conversations, identities, messageLinks, messages, } from "./schema.js";
|
|
7
8
|
import { writeBatch } from "./transaction.js";
|
|
8
9
|
import { toIso } from "./values.js";
|
|
9
|
-
import { purgeVectorHashes } from "./vectors.js";
|
|
10
|
+
import { dot, purgeVectorHashes } from "./vectors.js";
|
|
10
11
|
const position = (sentAt, pk) => `${sentAt}:${pk}`;
|
|
11
12
|
/** A chat's live messages for the rules, oldest first, a page at a time; `next` continues it. */
|
|
12
13
|
export const linkInputs = ({ orm }, chatKey, { after, limit }) => {
|
|
@@ -433,6 +434,53 @@ export const chunkRepliesOf = ({ orm }, accountPk, chunks, limit) => {
|
|
|
433
434
|
}
|
|
434
435
|
return found;
|
|
435
436
|
};
|
|
437
|
+
/**
|
|
438
|
+
* Rarity counts over the conversation's own chunks, not the store: a word every chunk holds says nothing about which
|
|
439
|
+
* one is meant. A word may sit anywhere in a chunk's text, as the shown lines match it.
|
|
440
|
+
*/
|
|
441
|
+
export const bestChunkOf = ({ orm }, accountPk, conversationPk, { model, vectors, stems, over, }) => {
|
|
442
|
+
const chunks = orm.all(sql `SELECT f.external_id AS first, l.external_id AS last, f.sent_at AS fs, f.id AS fi, l.sent_at AS ls, l.id AS li,
|
|
443
|
+
v.vector
|
|
444
|
+
FROM chunks k JOIN chunk_messages r ON r.chunk_id = k.id
|
|
445
|
+
JOIN conversations c ON c.id = k.chunkable_id
|
|
446
|
+
JOIN chats ch ON ch.id = c.chat_id AND ch.account_id = ${accountPk}
|
|
447
|
+
JOIN conversation_state s ON s.chat_id = c.chat_id AND s.current_build = c.build
|
|
448
|
+
JOIN messages f ON f.id = r.first_message_id JOIN messages l ON l.id = r.last_message_id
|
|
449
|
+
LEFT JOIN embeddings v ON v.model = ${model} AND v.content_hash = k.content_hash
|
|
450
|
+
WHERE k.chunkable_type = 'conversation' AND k.chunkable_id = ${conversationPk} ORDER BY k.position`);
|
|
451
|
+
if (chunks.length <= over || !vectors.length)
|
|
452
|
+
return undefined;
|
|
453
|
+
const texts = chunks.map(() => "");
|
|
454
|
+
const rows = orm.all(sql `SELECT m.sent_at AS at, m.id AS pk, m.text FROM conversation_messages cm JOIN messages m ON m.id = cm.message_id
|
|
455
|
+
WHERE cm.conversation_id = ${conversationPk} AND m.deleted_at IS NULL`);
|
|
456
|
+
const after = (at, pk, than, thanPk) => at > than || (at === than && pk >= thanPk);
|
|
457
|
+
for (const { at, pk, text } of rows)
|
|
458
|
+
chunks.forEach(({ fs, fi, ls, li }, index) => {
|
|
459
|
+
if (after(at, pk, fs, fi) && after(ls, li, at, pk))
|
|
460
|
+
texts[index] += ` ${(text ?? "").toLowerCase()}`;
|
|
461
|
+
});
|
|
462
|
+
const weights = new Map();
|
|
463
|
+
for (const { stem, weight } of stems)
|
|
464
|
+
weights.set(stem, (weights.get(stem) ?? 0) + weight);
|
|
465
|
+
const words = texts.map(() => 0);
|
|
466
|
+
for (const [stem, weight] of weights) {
|
|
467
|
+
const holding = texts.flatMap((text, index) => (text.includes(stem) ? [index] : []));
|
|
468
|
+
const rarity = Math.log(chunks.length / holding.length);
|
|
469
|
+
for (const index of holding)
|
|
470
|
+
words[index] = words[index] + weight * rarity;
|
|
471
|
+
}
|
|
472
|
+
const meaning = chunks.map(({ vector }) => vector ? vectors.reduce((sum, query) => sum + dot(query, vector), 0) : Number.NEGATIVE_INFINITY);
|
|
473
|
+
const fused = chunks.map(() => 0);
|
|
474
|
+
for (const scores of [meaning, words])
|
|
475
|
+
scores
|
|
476
|
+
.map((_, index) => index)
|
|
477
|
+
.sort((a, b) => scores[b] - scores[a] || a - b)
|
|
478
|
+
.forEach((index, rank) => {
|
|
479
|
+
fused[index] = fused[index] + 1 / (RRF_K + rank + 1);
|
|
480
|
+
});
|
|
481
|
+
const best = chunks[fused.reduce((top, score, at) => (score > fused[top] ? at : top), 0)];
|
|
482
|
+
return best && { firstMessageId: best.first, lastMessageId: best.last };
|
|
483
|
+
};
|
|
436
484
|
const staleLink = (chatKey) => sql `(${messageLinks.staleAt} IS NOT NULL
|
|
437
485
|
OR EXISTS (SELECT 1 FROM message_revisions r WHERE r.message_id IN (${messageLinks.messageId}, ${messageLinks.parentId})
|
|
438
486
|
AND r.created_at >= ${messageLinks.createdAt})
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.734.0",
|
|
4
4
|
"description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Viacheslav Ptsarev",
|