@wirecat/cli-core 0.682.0 → 0.684.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 CHANGED
@@ -5,6 +5,67 @@ 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.684.0 — 16.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`serviceApiCommand`, the raw API of an OpenAPI service as one shared `api` group**, from notion-cli's: `api list`
13
+ and `api show` without a request, and one command per operation of the generated manifest. A write goes through the
14
+ profile's guard on `api.<operation>`; a delete also checks the CLI's `deleteKey` (`documents.delete`) when the
15
+ operation is `destructive` or a `DELETE`, when a body field the operation lists in `deletingFields` is `true`
16
+ (`in_trash`), or when the CLI's `deletingBodies` test says so. An operation may name its own key in `deleteKey`;
17
+ neither field is in cli-base's manifest yet, so both are optional. The group refuses to build when an operation can
18
+ delete and no delete key is set. The schemas and definitions load only when a command needs them. There is no
19
+ free-form `api call`, no `--store-token` and no bot wording, and an operation that returns a credential is not
20
+ offered. `--body-file` refuses a file in a WireCat tool's own folders. `serviceApiPermissions` gives the same
21
+ operations' half of `commandPermissions`: the delete keys as `extra`, the `alsoChecks` that `--dry-run` and
22
+ discovery show, and `ask` for each delete. A CLI wires `commandPermissions(serviceApiPermissions(api))`, merging each
23
+ field with its own keys if it has any, and `serviceApiCommand({ ...api, app, configuration, … })`.
24
+ - **`withReadableDeal(store, viewers, row)`** (`@wirecat/cli-core/crm`) sets a lead's `deal` to `null` when a viewer
25
+ may not read the deal it became.
26
+
27
+ ### Fixed
28
+
29
+ - **A sign-in's token or revoke request lost to the network is sent again**, twice at most and within its 30-second
30
+ limit, when the failure is a failed DNS lookup (`EAI_AGAIN`, `ENOTFOUND`), a dropped or refused connection
31
+ (`ECONNRESET`, `ECONNREFUSED`, `EPIPE`, `ETIMEDOUT`), or `hostFetch`'s `network_error`. One network blip no longer
32
+ stops a sync with `outcome_unknown`. A provider with its own `exchange` or `revoke` keeps its own handling.
33
+ - **A task or to-do with no due date that arrives done is listed added and done again** in `changes list` and the
34
+ digest. Only a comment, call, e-mail or meeting is taken as done when it was made and listed once; a Bitrix24 task
35
+ with no deadline, closed inside the window, was missing from it.
36
+ - **`organizationContext` reads each limited CRM copy's deals with its viewer in the store query**, and the rest
37
+ without it, so more than a page of a colleague's deals no longer leaves the section empty with `hasMore`, nor
38
+ drops the profile's own deals past it.
39
+ - **A lead does not name a deal the profile may not read**: `leads list`, `leads show` and `dealContext` with
40
+ `viewing` answer its `deal` as `null`.
41
+
42
+ ## 0.683.0 — 16.11.2026
43
+
44
+ ### Changed — may break callers
45
+
46
+ - **`config set crm.<provider>:<account>.self` is refused** (`crm.self-from-sync`, also from
47
+ `parseCrmSettingValue`). Only a sync records whose copy it is; `config unset` still gives the copy to the next
48
+ sign-in's sync. A typed id could name the CRM's administrator, and offline reads of the copy by its owner's rule
49
+ (`search all` of another account, memo) then showed the whole copy.
50
+
51
+ ### Fixed
52
+
53
+ - **`changes list` and its `--format report` digest run on Node 22.16.** Their SQL numbered its values (`?13`) and
54
+ bound them from a list, which node:sqlite before Node 22.23 refuses ("column index out of range"); each value is
55
+ now a plain `?` bound in order. The old-Node CI job runs `scripts/node22-crm-changes.mjs` on 22.16.0.
56
+ - **`changes list` lists an activity that arrives done with no due date once**, as `activity_added`: an amoCRM or
57
+ Bitrix24 note or logged call was also listed as `activity_done` at the same time. Such an activity's `done_at` is
58
+ now when it was made. Rows synced before keep both lines.
59
+
60
+ ### Security
61
+
62
+ - **Business contexts and relationships follow the copy's viewer rule.** `organizationContext`,
63
+ `canonicalPersonContext` and `dealContext` take `viewing` (one `CrmViewing` per CRM account, from `crmViewerOf`):
64
+ a deal or lead the profile may not read is not listed or named, `dealContext` of one is `not_found`, and each
65
+ rule's note goes to `coverage.notRead`. `listRelations` takes `viewers` (`CopyViewer[]`) and leaves out, in its
66
+ query, every relationship with a deal or lead end a viewer may not read, so a caller titling relationship ends never
67
+ sees one. Without the options nothing changes.
68
+
8
69
  ## 0.682.0 — 16.11.2026
9
70
 
10
71
  ### Added
@@ -150,11 +150,12 @@ export { fieldsOf, projectFields } from "./result-fields.js";
150
150
  export { HARNESSES, type Harness, harnessesOn, harnessInfo, harnessOfArgv, isHarness, reportsCost, } from "./schedule/harnesses.js";
151
151
  export { type AgentScheduleSpec, agentSchedule, backfillScheduleRun, pauseSchedule, removeSchedule, runScheduleNow, SCHEDULE_SETTINGS, type ScheduleHost, type ScheduleLimits, type ScheduleSite, scheduleLimitsOf, scheduleState, slotsOfAt, writeSchedule, } from "./schedule/schedule-command.js";
152
152
  export { deniedKinds, deniedKindsOf, type LeftOut, type SearchedKind } from "./search-left-out.js";
153
+ export { type ServiceApiOperation, type ServiceApiOptions, type ServiceApiPermissionsInput, serviceApiDeletes, serviceApiPermissions, } from "./service-api.js";
153
154
  export { type DeclaredSetting, type SettingRow, settingRows, withSettingDefaults } from "./setting-defaults.js";
154
155
  export { type Config, type Configuration, count, first, flag, fromFile, type GlobalFlags, NONE_NAMED, namedProfile, type ProfileKind, plain, type ResolveOptions, type Settings, type SettingsExtension, type SettingsExtensionContext, type Source, settingsFor, } from "./settings.js";
155
156
  export { type PermissionAnswer, readSetupAnswers, type SetupAnswers, setupPermissionCeiling } from "./setup-answers.js";
156
157
  export { AGENTS, type Agent, agentFor, screenFor } from "./setup-screen.js";
157
- export { accountCommand, addMeetingBatchCommand, addMeetingPreparationCommand, addMeetingProjectCandidatesCommand, addMeetingSeriesInventoryCommand, addStoreMaintenanceCommands, appCompleteCommand, appDoctorCommand, appMcpCommand, attachmentsCommand, botAdminsCommand, botCommand, botMcpCommand, botMembersCommand, botMessagesCommand, callsCommand, chatsCommand, commandsCommand, completeCommand, configCommand, contactsCommand, conversationsCommand, deleteCommand, doctorCommand, editCommand, floodCommand, forwardCommand, generatedApiCommand, guideCommand, imagesCommand, inboxCommand, markReadCommand, mcpCommand, mentionsCommand, messagesCommand, metadataCommand, modelCatalogueCommand, modelsCommand, pinCommand, pollsCommand, projectsCommand, reactionsCommand, recipientsCommand, repliesCommand, reviewCommand, runsCommand, scheduleCommand, scheduleCommandFor, searchCommand, searchesCommand, sendCommand, sendsCommand, serveCommand, serverCommand, setupCommand, skillCommand, starCommands, statsCommand, stickersCommand, storeCommand, tagsCommand, tasksCommand, tasksStatsCommand, templatesCommand, topicsCommand, unpinCommand, upgradeCommand, watchCommand, } from "./shared-command-exports.js";
158
+ export { accountCommand, addMeetingBatchCommand, addMeetingPreparationCommand, addMeetingProjectCandidatesCommand, addMeetingSeriesInventoryCommand, addStoreMaintenanceCommands, appCompleteCommand, appDoctorCommand, appMcpCommand, attachmentsCommand, botAdminsCommand, botCommand, botMcpCommand, botMembersCommand, botMessagesCommand, callsCommand, chatsCommand, commandsCommand, completeCommand, configCommand, contactsCommand, conversationsCommand, deleteCommand, doctorCommand, editCommand, floodCommand, forwardCommand, generatedApiCommand, guideCommand, imagesCommand, inboxCommand, markReadCommand, mcpCommand, mentionsCommand, messagesCommand, metadataCommand, modelCatalogueCommand, modelsCommand, pinCommand, pollsCommand, projectsCommand, reactionsCommand, recipientsCommand, repliesCommand, reviewCommand, runsCommand, scheduleCommand, scheduleCommandFor, searchCommand, searchesCommand, sendCommand, sendsCommand, serveCommand, serverCommand, serviceApiCommand, setupCommand, skillCommand, starCommands, statsCommand, stickersCommand, storeCommand, tagsCommand, tasksCommand, tasksStatsCommand, templatesCommand, topicsCommand, unpinCommand, upgradeCommand, watchCommand, } from "./shared-command-exports.js";
158
159
  export { assertSharedContracts, customizeSharedCommand, hasSharedContract, overrideSharedContract, type SharedContractOverride, sharedContractOverrides, sharedContracts, } from "./shared-contracts.js";
159
160
  export { runnable, withSafety } from "./steps.js";
160
161
  export { type StoreInfo, sharedStoreCommand, storeInfo, storeInfoCommand } from "./store-info.js";
package/dist/cli/index.js CHANGED
@@ -139,11 +139,12 @@ export { fieldsOf, projectFields } from "./result-fields.js";
139
139
  export { HARNESSES, harnessesOn, harnessInfo, harnessOfArgv, isHarness, reportsCost, } from "./schedule/harnesses.js";
140
140
  export { agentSchedule, backfillScheduleRun, pauseSchedule, removeSchedule, runScheduleNow, SCHEDULE_SETTINGS, scheduleLimitsOf, scheduleState, slotsOfAt, writeSchedule, } from "./schedule/schedule-command.js";
141
141
  export { deniedKinds, deniedKindsOf } from "./search-left-out.js";
142
+ export { serviceApiDeletes, serviceApiPermissions, } from "./service-api.js";
142
143
  export { settingRows, withSettingDefaults } from "./setting-defaults.js";
143
144
  export { count, first, flag, fromFile, NONE_NAMED, namedProfile, plain, settingsFor, } from "./settings.js";
144
145
  export { readSetupAnswers, setupPermissionCeiling } from "./setup-answers.js";
145
146
  export { AGENTS, agentFor, screenFor } from "./setup-screen.js";
146
- export { accountCommand, addMeetingBatchCommand, addMeetingPreparationCommand, addMeetingProjectCandidatesCommand, addMeetingSeriesInventoryCommand, addStoreMaintenanceCommands, appCompleteCommand, appDoctorCommand, appMcpCommand, attachmentsCommand, botAdminsCommand, botCommand, botMcpCommand, botMembersCommand, botMessagesCommand, callsCommand, chatsCommand, commandsCommand, completeCommand, configCommand, contactsCommand, conversationsCommand, deleteCommand, doctorCommand, editCommand, floodCommand, forwardCommand, generatedApiCommand, guideCommand, imagesCommand, inboxCommand, markReadCommand, mcpCommand, mentionsCommand, messagesCommand, metadataCommand, modelCatalogueCommand, modelsCommand, pinCommand, pollsCommand, projectsCommand, reactionsCommand, recipientsCommand, repliesCommand, reviewCommand, runsCommand, scheduleCommand, scheduleCommandFor, searchCommand, searchesCommand, sendCommand, sendsCommand, serveCommand, serverCommand, setupCommand, skillCommand, starCommands, statsCommand, stickersCommand, storeCommand, tagsCommand, tasksCommand, tasksStatsCommand, templatesCommand, topicsCommand, unpinCommand, upgradeCommand, watchCommand, } from "./shared-command-exports.js";
147
+ export { accountCommand, addMeetingBatchCommand, addMeetingPreparationCommand, addMeetingProjectCandidatesCommand, addMeetingSeriesInventoryCommand, addStoreMaintenanceCommands, appCompleteCommand, appDoctorCommand, appMcpCommand, attachmentsCommand, botAdminsCommand, botCommand, botMcpCommand, botMembersCommand, botMessagesCommand, callsCommand, chatsCommand, commandsCommand, completeCommand, configCommand, contactsCommand, conversationsCommand, deleteCommand, doctorCommand, editCommand, floodCommand, forwardCommand, generatedApiCommand, guideCommand, imagesCommand, inboxCommand, markReadCommand, mcpCommand, mentionsCommand, messagesCommand, metadataCommand, modelCatalogueCommand, modelsCommand, pinCommand, pollsCommand, projectsCommand, reactionsCommand, recipientsCommand, repliesCommand, reviewCommand, runsCommand, scheduleCommand, scheduleCommandFor, searchCommand, searchesCommand, sendCommand, sendsCommand, serveCommand, serverCommand, serviceApiCommand, setupCommand, skillCommand, starCommands, statsCommand, stickersCommand, storeCommand, tagsCommand, tasksCommand, tasksStatsCommand, templatesCommand, topicsCommand, unpinCommand, upgradeCommand, watchCommand, } from "./shared-command-exports.js";
147
148
  export { assertSharedContracts, customizeSharedCommand, hasSharedContract, overrideSharedContract, sharedContractOverrides, sharedContracts, } from "./shared-contracts.js";
148
149
  export { runnable, withSafety } from "./steps.js";
149
150
  export { sharedStoreCommand, storeInfo, storeInfoCommand } from "./store-info.js";
@@ -0,0 +1,74 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import type { ManifestOperation, SchemaNode } from "@wirecat/cli-base/codegen";
3
+ import type { FetchLike } from "@wirecat/cli-base/http";
4
+ import { Command } from "commander";
5
+ import type * as v from "valibot";
6
+ import type { AppIdentity } from "../ports/app.js";
7
+ import type { Level, PermissionKey } from "../sends/permissions.js";
8
+ import type { ConditionalKey } from "./permission-keys.js";
9
+ import type { Configuration } from "./settings.js";
10
+ /**
11
+ * A generated operation, with what the generator may know about deleting. Both fields are optional until cli-base's
12
+ * manifest writes them; a CLI may add them by hand meanwhile.
13
+ */
14
+ export interface ServiceApiOperation extends ManifestOperation {
15
+ /** The key a delete through this operation also checks, `pages.delete`; the CLI's `deleteKey` otherwise. */
16
+ deleteKey?: string;
17
+ /** Body fields that delete when `true`, as `in_trash` or `archived`. */
18
+ deletingFields?: readonly string[];
19
+ }
20
+ /** What both halves of the group, the permissions and the command, are built from. */
21
+ export interface ServiceApiPermissionsInput {
22
+ operations: readonly ServiceApiOperation[];
23
+ /** The key every delete also checks, `documents.delete`, so denying it holds over `api` as over the CLI's own commands. */
24
+ deleteKey?: string;
25
+ /**
26
+ * Operations, by command name, whose body can delete in a way no top-level field names: `agent-batch` with an action
27
+ * `delete`. The body comes parsed by lossless-json, so a number is a `LosslessNumber`.
28
+ */
29
+ deletingBodies?: Readonly<Record<string, (body: unknown) => boolean>>;
30
+ }
31
+ export interface ServiceApiOptions extends ServiceApiPermissionsInput {
32
+ app: AppIdentity;
33
+ configuration: Configuration;
34
+ /** The service's name in messages: "Notion". */
35
+ service: string;
36
+ /** The server the spec names; a path template is appended to its path. */
37
+ baseUrl: string;
38
+ /** The host-checked fetch with the CLI's pace and its retry of reads (cli-base `retrying` over `hostFetch`). */
39
+ fetch: (command: Command) => FetchLike;
40
+ /** The sign-in headers; read before any guard asks, so a missing sign-in fails first. */
41
+ headers: (command: Command, operation: ManifestOperation) => Record<string, string> | Promise<Record<string, string>>;
42
+ /** Loaded only once an operation is about to check its input: a large spec is megabytes of code. */
43
+ schemas: () => Promise<Readonly<Record<string, v.GenericSchema>>>;
44
+ /** Loaded only by `api show`. */
45
+ definitions: () => Promise<Readonly<Record<string, SchemaNode>>>;
46
+ /** Operations the spec has and the CLI does not offer, each with why; `api show` names the reason. */
47
+ excluded?: readonly {
48
+ id: string;
49
+ reason: string;
50
+ }[];
51
+ /** Fields `api show` adds to every answer, such as the API version the commands send. */
52
+ shown?: Readonly<Record<string, unknown>>;
53
+ failure?: (status: number, answer: unknown, operation: ManifestOperation) => CliError | undefined;
54
+ }
55
+ /** Whether one call deletes: by its method, a deleting field set to `true`, or the CLI's own test of the body. */
56
+ export declare const serviceApiDeletes: (input: ServiceApiPermissionsInput, operation: ServiceApiOperation, body: unknown) => boolean;
57
+ /**
58
+ * The group's half of `commandPermissions`: the delete key each operation also checks, for `--dry-run` and discovery,
59
+ * and the levels a delete starts at. A CLI with keys of its own merges each field with its own, never spreads one
60
+ * over the other. `ask` stops at a terminal; over MCP it goes ahead, so `deny` is what stops an agent.
61
+ */
62
+ export declare const serviceApiPermissions: (input: ServiceApiPermissionsInput) => {
63
+ alsoChecks: (path: readonly string[]) => readonly (PermissionKey | ConditionalKey)[];
64
+ defaults: Readonly<Record<PermissionKey, Level>>;
65
+ /** The delete keys, so a profile may name one that no command path spells. */
66
+ extra: readonly PermissionKey[];
67
+ };
68
+ /**
69
+ * The raw API of an OpenAPI service as one group: `api list` and `api show` without a request, and one command per
70
+ * operation. Every write goes through the profile's guard on `api.<operation>` and, when it deletes, on the delete key
71
+ * too; the journal records that it ran, never its body. There is no free-form `api call`: a request is always one
72
+ * operation of the spec, with its own key (SEC-196).
73
+ */
74
+ export declare const serviceApiCommand: (options: ServiceApiOptions) => Command;
@@ -0,0 +1,180 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { Command } from "commander";
4
+ import { guardFor } from "../sends/guard.js";
5
+ import { guardedWrite } from "../sends/guarded.js";
6
+ import { keyedGuard } from "../sends/keyed-guard.js";
7
+ import { levelFor } from "../sends/permissions.js";
8
+ import { newOperationId } from "../sends/send-id.js";
9
+ import { refusedPlace } from "../sends/upload.js";
10
+ import { generatedApiCommand } from "./bot/api.js";
11
+ import { httpApiExecutor, httpApiRequest } from "./bot/api-http.js";
12
+ import { checkApiBody, checkApiParameter, parseApiJson, readApiBody } from "./bot/api-input.js";
13
+ import { baseContext, outputFor } from "./context.js";
14
+ import { NO_EFFECTS } from "./effects.js";
15
+ import { itemOf, listOf, renderAnswer } from "./envelope.js";
16
+ import { queryTerms, termField, withQuery } from "./list-query.js";
17
+ import { terminalAsker } from "./messenger/ask.js";
18
+ const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
19
+ const keyOf = (operation) => `api.${operation.command}`;
20
+ const deleteKeyOf = (input, operation) => operation.deleteKey ?? input.deleteKey;
21
+ /** By its method too: an override may have marked a DELETE as a plain write. */
22
+ const destructive = (operation) => operation.effect === "destructive" || (operation.binding.kind === "http" && operation.binding.method === "DELETE");
23
+ const bodyMayDelete = (input, operation) => (operation.deletingFields?.length ?? 0) > 0 || input.deletingBodies?.[operation.command] !== undefined;
24
+ /** Whether one call deletes: by its method, a deleting field set to `true`, or the CLI's own test of the body. */
25
+ export const serviceApiDeletes = (input, operation, body) => destructive(operation) ||
26
+ (isObject(body) && (operation.deletingFields ?? []).some((field) => body[field] === true)) ||
27
+ input.deletingBodies?.[operation.command]?.(body) === true;
28
+ /**
29
+ * The group's half of `commandPermissions`: the delete key each operation also checks, for `--dry-run` and discovery,
30
+ * and the levels a delete starts at. A CLI with keys of its own merges each field with its own, never spreads one
31
+ * over the other. `ask` stops at a terminal; over MCP it goes ahead, so `deny` is what stops an agent.
32
+ */
33
+ export const serviceApiPermissions = (input) => {
34
+ const deleting = input.operations.filter((operation) => destructive(operation) || bodyMayDelete(input, operation));
35
+ const keys = new Set(deleting.map((operation) => deleteKeyOf(input, operation)).filter((key) => key !== undefined));
36
+ return {
37
+ extra: [...keys],
38
+ alsoChecks: (path) => {
39
+ if (path[0] !== "api" || path.length !== 2)
40
+ return [];
41
+ const operation = deleting.find((one) => one.command === path[1]);
42
+ const key = operation && deleteKeyOf(input, operation);
43
+ if (!operation || !key)
44
+ return [];
45
+ return destructive(operation) ? [key] : [{ key, when: "the body deletes, trashes or archives" }];
46
+ },
47
+ defaults: {
48
+ ...Object.fromEntries([...keys].map((key) => [key, "ask"])),
49
+ ...Object.fromEntries(input.operations.filter(destructive).map((operation) => [keyOf(operation), "ask"])),
50
+ },
51
+ };
52
+ };
53
+ const rowOf = (operation) => ({
54
+ command: operation.command,
55
+ method: operation.binding.kind === "http" ? operation.binding.method : "",
56
+ path: operation.binding.kind === "http" ? operation.binding.path : "",
57
+ effect: operation.effect,
58
+ summary: operation.summary ?? "",
59
+ });
60
+ const API_QUERY = {
61
+ entity: "api_operation",
62
+ backend: "native",
63
+ fields: [
64
+ termField("effect", "enum", "effect:destructive", { values: ["read", "write", "destructive"] }),
65
+ termField("tag", "kw", "tag:Pages"),
66
+ ],
67
+ };
68
+ /**
69
+ * The raw API of an OpenAPI service as one group: `api list` and `api show` without a request, and one command per
70
+ * operation. Every write goes through the profile's guard on `api.<operation>` and, when it deletes, on the delete key
71
+ * too; the journal records that it ran, never its body. There is no free-form `api call`: a request is always one
72
+ * operation of the spec, with its own key (SEC-196).
73
+ */
74
+ export const serviceApiCommand = (options) => {
75
+ const { app, configuration } = options;
76
+ // A credential-returning operation needs a bot's `--store-token`; a service CLI signs in through `session` instead.
77
+ const operations = options.operations.filter((operation) => !operation.response?.sensitive);
78
+ const own = serviceApiPermissions(options);
79
+ // The group's own levels hold even where the CLI's permissions left them out.
80
+ const defaults = { ...own.defaults, ...configuration.permissions?.defaults };
81
+ const keyless = options.operations.filter((operation) => (destructive(operation) || bodyMayDelete(options, operation)) && !deleteKeyOf(options, operation));
82
+ if (keyless.length > 0)
83
+ throw new CliError("configuration_error", `${keyless.map(({ command }) => command).join(", ")} can delete, but no delete key is set: give the api a deleteKey`);
84
+ let schemas;
85
+ const loaded = () => {
86
+ if (!schemas)
87
+ throw new CliError("configuration_error", "the api schemas were not loaded before the command ran");
88
+ return schemas;
89
+ };
90
+ const operationOf = (name) => {
91
+ const found = operations.find((operation) => operation.command === name || operation.id === name);
92
+ if (found)
93
+ return found;
94
+ const left = options.excluded?.find((one) => one.id === name) ??
95
+ (options.operations.some((one) => one.command === name || one.id === name)
96
+ ? { reason: "it returns a credential, which is never printed" }
97
+ : undefined);
98
+ throw new CliError("not_found", left
99
+ ? `${name} is not offered: ${left.reason}`
100
+ : `no ${options.service} API operation ${name}; see ${app.command} api list`);
101
+ };
102
+ const write = (extra) => async (command, operation, send) => {
103
+ const { settings, env, renderer, run } = baseContext(command, configuration.resolveSettings);
104
+ const operationId = newOperationId();
105
+ const guard = keyedGuard((ask) => guardFor(app, { ...settings, sendsPerHour: Number.MAX_SAFE_INTEGER, permissionDefaults: defaults }, renderer.warn, env, ask), terminalAsker(command), (key) => levelFor(settings.permissions, key, defaults).level, extra);
106
+ const request = { chatId: null, kind: "edit", key: keyOf(operation), operationId };
107
+ guard.refuse(request);
108
+ try {
109
+ return { operation_id: operationId, result: await guardedWrite(guard, request, () => run(() => send())) };
110
+ }
111
+ catch (error) {
112
+ if (isCliError(error) && error.code === "outcome_unknown")
113
+ throw new CliError("outcome_unknown", error.message, { ...error.details, operation_id: operationId });
114
+ throw error;
115
+ }
116
+ };
117
+ const executorFor = (extra) => httpApiExecutor({
118
+ service: options.service,
119
+ baseUrl: options.baseUrl,
120
+ fetch: options.fetch,
121
+ headers: options.headers,
122
+ write: write(extra),
123
+ read: (command, _operation, send) => baseContext(command, configuration.resolveSettings).run(() => send()),
124
+ ...(options.failure ? { failure: options.failure } : {}),
125
+ });
126
+ const generated = generatedApiCommand({
127
+ operations,
128
+ checkParameter: (name, schema, raw) => checkApiParameter(name, schema, raw, loaded()),
129
+ checkBody: (operation, text) => checkApiBody(operation, text, loaded()),
130
+ readBody: (command, body) => {
131
+ if (body.bodyFile !== undefined && body.bodyFile !== "-") {
132
+ const { env } = baseContext(command, configuration.resolveSettings);
133
+ if (refusedPlace(body.bodyFile, app, env))
134
+ throw new CliError("validation_error", `--body-file may not read ${body.bodyFile}: it holds sign-ins or state`);
135
+ }
136
+ return readApiBody(body);
137
+ },
138
+ execute: (command, operation, input) => {
139
+ const text = httpApiRequest(operation, input, options.baseUrl).body;
140
+ const key = deleteKeyOf(options, operation);
141
+ const body = text === undefined ? undefined : parseApiJson(text);
142
+ const deletes = key !== undefined && serviceApiDeletes(options, operation, body);
143
+ return executorFor(deletes ? [key] : [])(command, operation, input);
144
+ },
145
+ });
146
+ const list = withQuery(annotate(new Command("list"), {
147
+ effects: NO_EFFECTS,
148
+ examples: [`${app.command} api list`, `${app.command} api list effect:destructive --json=command,path`],
149
+ }), API_QUERY)
150
+ .description(`list every ${options.service} API operation this CLI offers, without calling ${options.service}`)
151
+ .action(function (words) {
152
+ const terms = queryTerms(words, API_QUERY, "api list");
153
+ const effect = terms.get("effect");
154
+ const tag = terms.get("tag");
155
+ const items = operations
156
+ .filter((one) => (!effect || one.effect === effect) && (!tag || one.tags.includes(tag)))
157
+ .map(rowOf);
158
+ renderAnswer(this, outputFor(this), listOf("api list", { items, limit: items.length, has_more: false }));
159
+ });
160
+ const show = annotate(new Command("show"), {
161
+ effects: NO_EFFECTS,
162
+ examples: [`${app.command} api show ${operations[0]?.command ?? "<operation>"} --json`],
163
+ })
164
+ .description(`show one operation's parameters and request schema, without calling ${options.service}`)
165
+ .argument("<operation>", "the operation, as api list prints it")
166
+ .action(async function (name) {
167
+ const operation = operationOf(name);
168
+ const definitions = await options.definitions();
169
+ const schema = operation.request?.schema ? definitions[operation.request.schema] : undefined;
170
+ renderAnswer(this, outputFor(this), itemOf({ operation, ...options.shown, ...(schema ? { request_schema: schema } : {}) }));
171
+ });
172
+ const group = annotate(new Command("api"), { effects: NO_EFFECTS }).description(`the raw ${options.service} API, one command per operation of its OpenAPI document`);
173
+ group.addCommand(list).addCommand(show);
174
+ const load = async () => {
175
+ schemas ??= await options.schemas();
176
+ };
177
+ for (const child of generated.commands)
178
+ group.addCommand(child.hook("preAction", load));
179
+ return group;
180
+ };
@@ -563,6 +563,7 @@ export declare const appMcpCommand: (app: import("./entry.js").AppIdentity, conf
563
563
  export declare const botAdminsCommand: (bot: import("./index.js").BotMessenger) => import("commander").Command;
564
564
  export declare const botMembersCommand: (bot: import("./index.js").BotMessenger) => import("commander").Command;
565
565
  export declare const generatedApiCommand: (api: import("./bot/api.js").ApiCommands) => import("commander").Command;
566
+ export declare const serviceApiCommand: (options: import("./service-api.js").ServiceApiOptions) => import("commander").Command;
566
567
  export declare const botCommand: (bot: import("./index.js").BotMessenger) => import("commander").Command;
567
568
  export declare const botMcpCommand: (bot: import("./index.js").BotMessenger) => import("commander").Command;
568
569
  export declare const botMessagesCommand: (bot: import("./index.js").BotMessenger) => import("commander").Command;
@@ -55,6 +55,7 @@ import { topicsCommand as topicsCommandDefinition } from "./messenger/topics-com
55
55
  import { watchCommand as watchCommandDefinition } from "./messenger/watch-command.js";
56
56
  import { runsCommand as runsCommandDefinition } from "./runs/command.js";
57
57
  import { scheduleCommandFor as scheduleCommandForDefinition } from "./schedule/schedule-command.js";
58
+ import { serviceApiCommand as serviceApiCommandDefinition } from "./service-api.js";
58
59
  import { setupCommand as setupCommandDefinition } from "./setup-command.js";
59
60
  import { sharedCommand as protectedCommand } from "./shared-contracts.js";
60
61
  import { skillCommand as skillCommandDefinition } from "./skill-command.js";
@@ -67,6 +68,7 @@ export const appMcpCommand = sharedCommand(appMcpCommandDefinition);
67
68
  export const botAdminsCommand = sharedCommand(botAdminsCommandDefinition);
68
69
  export const botMembersCommand = sharedCommand(botMembersCommandDefinition);
69
70
  export const generatedApiCommand = sharedCommand(generatedApiCommandDefinition);
71
+ export const serviceApiCommand = sharedCommand(serviceApiCommandDefinition);
70
72
  export const botCommand = sharedCommand(botCommandDefinition);
71
73
  export const botMcpCommand = sharedCommand(botMcpCommandDefinition);
72
74
  export const botMessagesCommand = sharedCommand(botMessagesCommandDefinition);
@@ -302,9 +302,7 @@ const crmNote = (name, now) => {
302
302
  ? "store-wide — no stage opens a task"
303
303
  : "store-wide — from now on, each sync opens a local task for every deal or lead that moved into one of these " +
304
304
  "stages since the last sync; moves made before the rules were first set open none";
305
- return now === ""
306
- ? "store-wide — the next sync gives the account's copy to its sign-in's user, and narrows it to that user's deals"
307
- : "store-wide — the account's copy holds this user's deals; a sync signed in as another user is refused";
305
+ return "store-wide — the next sync gives the account's copy to its sign-in's user, and narrows it to that user's deals";
308
306
  };
309
307
  const changeCrm = async (env, setting, value) => {
310
308
  const { name } = parseCrmSetting(setting);
@@ -12,19 +12,18 @@ import { listQuery, nativeField, nativeTerms, queryTerms, termField, timeBounds,
12
12
  import { terminalAsker } from "../../cli/messenger/ask.js";
13
13
  import { addStoreMaintenanceCommands } from "../../cli/messenger/store-maintenance-command.js";
14
14
  import { lineOf } from "../../cli/steps.js";
15
- import { CRM_KINDS, isCrmUserId, normalCrmUserId } from "../../domain/crm.js";
15
+ import { CRM_KINDS } from "../../domain/crm.js";
16
16
  import { DEAL_KINDS, DEAL_STATUSES } from "../../domain/deals.js";
17
17
  import { deal as dealEntity } from "../../entities/deal.js";
18
18
  import { count, text } from "../../entities/fields.js";
19
19
  import { dateWindow } from "../../services/moment.js";
20
20
  import { readableAccounts } from "../../services/person-context.js";
21
21
  import { personMeetings } from "../../services/person-meetings.js";
22
- import { crmIdentityId } from "../../store/sqlite/crm-rows.js";
23
22
  import { CRM_SCOPES, crmSettingKey } from "../../store/sqlite/crm-settings.js";
24
23
  import { seenBy } from "../../store/store.js";
25
24
  import { openStageTasks } from "../stage-tasks.js";
26
25
  import { crmStatus, syncRecorded } from "../sync.js";
27
- import { shortened, viewerOf } from "../viewer.js";
26
+ import { ownerOf, shortened, viewerOf, withReadableDeal } from "../viewer.js";
28
27
  import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, pipelineOf, removeCrmItem, updateCrmItem, } from "../writes.js";
29
28
  import { addCrmChangeCommands } from "./changes.js";
30
29
  import { csvFormatOption, renderCsv } from "./csv.js";
@@ -187,25 +186,6 @@ const collect = (value, previous = []) => {
187
186
  throw new InvalidArgumentError("expected key=value");
188
187
  return [...previous, value];
189
188
  };
190
- /** `owner:` as the identity a deal's assignee is stored as; `none` is no assignee. */
191
- const ownerOf = async (run, owner) => {
192
- if (owner === "none")
193
- return null;
194
- if (owner === "me") {
195
- const self = run.user ?? (await run.store.crm.ownUser(run.account));
196
- if (!self)
197
- throw new CliError("validation_error", "this CRM names no user for the sign-in: use owner:<user id>", {
198
- reason: "crm.owner-unknown",
199
- });
200
- return crmIdentityId(run.account, normalCrmUserId(self), "user");
201
- }
202
- if (!isCrmUserId(owner))
203
- throw new CliError("validation_error", `owner takes me, none or the CRM's user id, not ${owner}`, {
204
- reason: "crm.owner-unknown",
205
- });
206
- return crmIdentityId(run.account, normalCrmUserId(owner), "user");
207
- };
208
- /** Whose deals and leads of the copy this profile reads offline; undefined is every one. */
209
189
  /** The words below the program, as `page.next` and `sync`'s next step run it again. */
210
190
  const pathOf = (command) => command.parent?.parent ? [...pathOf(command.parent), command.name()] : [command.name()];
211
191
  /** A CRM's own field codes are its keys, never ours to rename. */
@@ -349,21 +329,28 @@ const addCrmCommandsDefinition = (program, options) => {
349
329
  const timezone = metas.find((one) => one.timezone)?.timezone;
350
330
  // One window names one field's bounds; with two time terms it would name only the first.
351
331
  const window = metas.length === 1 ? metas[0] : timezone ? { timezone } : undefined;
352
- const read = async (run) => run.store.deals.list({
353
- kind,
354
- account: run.account,
355
- viewer: await viewerOf(run),
356
- ...(terms.has("status") ? { status: terms.get("status") } : {}),
357
- ...(terms.has("stage") ? { stage: terms.get("stage") } : {}),
358
- ...(terms.has("pipeline") ? { pipeline: terms.get("pipeline") } : {}),
359
- ...(terms.has("organization") ? { organization: terms.get("organization") } : {}),
360
- ...(terms.has("owner") ? { owner: await ownerOf(run, terms.get("owner")) } : {}),
361
- ...(times.has("updated") ? { updated: bounds.updated } : {}),
362
- ...(times.has("created") ? { created: bounds.created } : {}),
363
- ...(times.has("closed") ? { closed: bounds.closed, zone: window?.timezone } : {}),
364
- limit: Math.min(opts.limit, MOST),
365
- offset: (opts.page - 1) * opts.limit,
366
- });
332
+ const read = async (run) => {
333
+ const viewer = await viewerOf(run);
334
+ const found = await run.store.deals.list({
335
+ kind,
336
+ account: run.account,
337
+ viewer,
338
+ ...(terms.has("status") ? { status: terms.get("status") } : {}),
339
+ ...(terms.has("stage") ? { stage: terms.get("stage") } : {}),
340
+ ...(terms.has("pipeline") ? { pipeline: terms.get("pipeline") } : {}),
341
+ ...(terms.has("organization") ? { organization: terms.get("organization") } : {}),
342
+ ...(terms.has("owner") ? { owner: await ownerOf(run, terms.get("owner")) } : {}),
343
+ ...(times.has("updated") ? { updated: bounds.updated } : {}),
344
+ ...(times.has("created") ? { created: bounds.created } : {}),
345
+ ...(times.has("closed") ? { closed: bounds.closed, zone: window?.timezone } : {}),
346
+ limit: Math.min(opts.limit, MOST),
347
+ offset: (opts.page - 1) * opts.limit,
348
+ });
349
+ return {
350
+ ...found,
351
+ items: await Promise.all(found.items.map((one) => withReadableDeal(run.store, [viewer], one))),
352
+ };
353
+ };
367
354
  if (opts.format === "csv")
368
355
  return renderCsv(command, options.open, async (run) => {
369
356
  const found = await read(run);
@@ -454,7 +441,7 @@ const addCrmCommandsDefinition = (program, options) => {
454
441
  const viewer = await viewerOf(run);
455
442
  if (!seenBy(viewer, { ...run.account, assignee: found.assignee }))
456
443
  throw new CliError("not_found", `${reference} is not a copy this profile may read${shortened.has(run) ? `: ${shortened.get(run)}` : ""}`);
457
- return found;
444
+ return withReadableDeal(run.store, [viewer], found);
458
445
  };
459
446
  const writes = options.writes;
460
447
  const addWrites = (group, kind) => {
@@ -5,7 +5,7 @@ export type { CrmCallContext, CrmChanges, CrmCondition, CrmGap, CrmIdPage, CrmLi
5
5
  export { type CrmCursor, type CrmSyncIssue, type CrmSyncOptions, type CrmSyncReport, type CrmSyncResult, crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
6
6
  /** An adapter's readers of a CRM's raw JSON: `crmValues.text(raw.name)`, `crmValues.time(raw.created_at)`. */
7
7
  export * as crmValues from "./values.js";
8
- export { type CrmViewing, crmViewerOf } from "./viewer.js";
8
+ export { type CrmViewing, crmViewerOf, withReadableDeal } from "./viewer.js";
9
9
  export { type CrmRows, type CrmWindow, crmWindowOf, walk } from "./walk.js";
10
10
  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";
11
11
  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";
package/dist/crm/index.js CHANGED
@@ -4,7 +4,7 @@ export { conditionsOf, customConditions, customNames, filterableFields, selected
4
4
  export { crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
5
5
  /** An adapter's readers of a CRM's raw JSON: `crmValues.text(raw.name)`, `crmValues.time(raw.created_at)`. */
6
6
  export * as crmValues from "./values.js";
7
- export { crmViewerOf } from "./viewer.js";
7
+ export { crmViewerOf, withReadableDeal } from "./viewer.js";
8
8
  export { crmWindowOf, walk } from "./walk.js";
9
9
  export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, crmAlsoChecks, } from "./writer.js";
10
10
  export { closeCrmItem, createCrmItem, createCrmRecord, crmCustomValues, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, optionOf, removeCrmItem, unknownField, updateCrmItem, updateCrmRecord, } from "./writes.js";
@@ -1,4 +1,4 @@
1
- import type { CopyViewer, MessageStore } from "../store/store.js";
1
+ import { type CopyViewer, type MessageStore } from "../store/store.js";
2
2
  import type { AccountKey } from "../store/types.js";
3
3
  import type { CrmSource } from "./source.js";
4
4
  /**
@@ -26,3 +26,16 @@ export declare const viewerOf: (run: {
26
26
  account: AccountKey;
27
27
  user: string | null;
28
28
  }) => Promise<CopyViewer | undefined>;
29
+ /**
30
+ * The row with `deal`, the deal a lead became, left out when a viewer may not read that deal (SEC-197): a lead the
31
+ * profile reads must not name a colleague's deal.
32
+ */
33
+ export declare const withReadableDeal: <T extends {
34
+ deal: string | null;
35
+ }>(store: MessageStore, viewers: readonly (CopyViewer | undefined)[], row: T) => Promise<T>;
36
+ /** `owner:` as the identity a deal's assignee is stored as; `none` is no assignee. */
37
+ export declare const ownerOf: (run: {
38
+ store: MessageStore;
39
+ account: AccountKey;
40
+ user: string | null;
41
+ }, owner: string) => Promise<string | null>;
@@ -1,5 +1,7 @@
1
- import { normalCrmUserId } from "../domain/crm.js";
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { isCrmUserId, normalCrmUserId } from "../domain/crm.js";
2
3
  import { crmIdentityId } from "../store/sqlite/crm-rows.js";
4
+ import { seenBy } from "../store/store.js";
3
5
  // A sync state, not a CRM setting: `config set` must never make a profile the administrator.
4
6
  const VIEWERS = "crm:viewers";
5
7
  const viewersOf = async (store, account) => {
@@ -61,3 +63,38 @@ export const viewerOf = async (run) => {
61
63
  shortened.set(run, note);
62
64
  return viewer;
63
65
  };
66
+ /**
67
+ * The row with `deal`, the deal a lead became, left out when a viewer may not read that deal (SEC-197): a lead the
68
+ * profile reads must not name a colleague's deal.
69
+ */
70
+ export const withReadableDeal = async (store, viewers, row) => {
71
+ const limiting = viewers.filter((one) => one !== undefined);
72
+ if (row.deal === null || limiting.length === 0)
73
+ return row;
74
+ const target = await store.deals.get(row.deal).catch(() => undefined);
75
+ const seen = target !== undefined &&
76
+ limiting.every((viewer) => seenBy(viewer, {
77
+ provider: target.account?.provider,
78
+ account: target.account?.account,
79
+ assignee: target.assignee,
80
+ }));
81
+ return seen ? row : { ...row, deal: null };
82
+ };
83
+ /** `owner:` as the identity a deal's assignee is stored as; `none` is no assignee. */
84
+ export const ownerOf = async (run, owner) => {
85
+ if (owner === "none")
86
+ return null;
87
+ if (owner === "me") {
88
+ const self = run.user ?? (await run.store.crm.ownUser(run.account));
89
+ if (!self)
90
+ throw new CliError("validation_error", "this CRM names no user for the sign-in: use owner:<user id>", {
91
+ reason: "crm.owner-unknown",
92
+ });
93
+ return crmIdentityId(run.account, normalCrmUserId(self), "user");
94
+ }
95
+ if (!isCrmUserId(owner))
96
+ throw new CliError("validation_error", `owner takes me, none or the CRM's user id, not ${owner}`, {
97
+ reason: "crm.owner-unknown",
98
+ });
99
+ return crmIdentityId(run.account, normalCrmUserId(owner), "user");
100
+ };
@@ -417,6 +417,7 @@ const OTHERS = [
417
417
  validation("deal.field", "a field of the deal or lead is not valid"),
418
418
  ["deal.denied", "permission_error", "the profile denies listing deals or leads, so none is answered"],
419
419
  ["deal.out-of-scope", "not_found", "the deal or lead is a copy from an account outside the accounts asked for"],
420
+ ["deal.not-readable", "not_found", "the deal or lead is a copy the profile's CRM sign-in may not read"],
420
421
  validation("deal.ref", "the reference names no deal or lead"),
421
422
  validation("deal.stage", "no stage of that name, or a stage name more than one pipeline has"),
422
423
  validation("stage.base-field", "a base stage needs a name its set has once and a position within the set"),
@@ -438,6 +439,7 @@ const OTHERS = [
438
439
  validation("pipeline.duplicate", "a pipeline of that name and kind is already stored"),
439
440
  validation("pipeline.field", "a pipeline needs a name and at least one stage, each named once"),
440
441
  ["pipeline.not-found", "not_found", "no stored pipeline has that name or reference"],
442
+ validation("crm.self-from-sync", "only a sync records whose CRM copy it is; config unset hands the copy to the next sync"),
441
443
  validation("crm.stage-unknown", "a CRM item stands in a stage the store does not hold; it was not kept"),
442
444
  validation("crm.item-invalid", "a CRM item has a field the store refuses, such as a status it does not know"),
443
445
  validation("crm.amount-unkept", "a CRM deal's amount is in a currency or with decimals the store cannot hold: the deal is kept without it"),
@@ -1,4 +1,4 @@
1
- import { CliError, isCliError } from "@wirecat/cli-base";
1
+ import { CliError, isCliError, realSleep } from "@wirecat/cli-base";
2
2
  import { withTimeLimit } from "../http/time-limit.js";
3
3
  const REQUEST_LIMIT_MS = 30_000;
4
4
  export const TOKEN_LOG_EVENT = "oauth.token";
@@ -15,20 +15,55 @@ const cancelledBy = (signal) => {
15
15
  return;
16
16
  throw isCliError(signal.reason) ? signal.reason : new CliError("cancelled", "sign-in was cancelled");
17
17
  };
18
- const post = async (url, body, context, deadline) => {
19
- cancelledBy(context.signal);
20
- try {
21
- return await context.fetch(url, {
22
- method: "POST",
23
- headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
24
- body,
25
- signal: requestSignal(deadline, context.signal),
26
- redirect: "error",
27
- });
18
+ const TRANSIENT = new Set([
19
+ "EAI_AGAIN",
20
+ "ENOTFOUND",
21
+ "ECONNRESET",
22
+ "ECONNREFUSED",
23
+ "ETIMEDOUT",
24
+ "EPIPE",
25
+ "UND_ERR_SOCKET",
26
+ ]);
27
+ const ATTEMPTS = 3;
28
+ /** A dropped network or a DNS lookup that failed: Node's fetch puts the system's code on the cause. */
29
+ const transientNetworkError = (error) => {
30
+ if (isCliError(error))
31
+ return error.code === "network_error";
32
+ for (let at = error, depth = 0; at instanceof Error && depth < 4; at = at.cause, depth++) {
33
+ const code = at.code;
34
+ if (typeof code === "string" && TRANSIENT.has(code))
35
+ return true;
28
36
  }
29
- catch {
37
+ return false;
38
+ };
39
+ /**
40
+ * A token request lost to a network blip (a DNS lookup that failed, a dropped connection) is sent again while the time
41
+ * limit lasts, or one blip stops a whole sync. Sending it again is safe: a refresh the provider already took is
42
+ * refused as the next run's would be, a used code is refused and the owner signs in again, as after a lost answer, and
43
+ * a revoke of a revoked token succeeds (RFC 7009).
44
+ */
45
+ const post = async (url, body, context, deadline) => {
46
+ const signal = requestSignal(deadline, context.signal);
47
+ for (let attempt = 1;; attempt++) {
30
48
  cancelledBy(context.signal);
31
- return undefined;
49
+ try {
50
+ return await context.fetch(url, {
51
+ method: "POST",
52
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
53
+ body,
54
+ signal,
55
+ redirect: "error",
56
+ });
57
+ }
58
+ catch (error) {
59
+ cancelledBy(context.signal);
60
+ if (attempt >= ATTEMPTS || signal.aborted || !transientNetworkError(error))
61
+ return undefined;
62
+ const waited = await realSleep(500 * attempt, signal).then(() => true, () => false);
63
+ cancelledBy(context.signal);
64
+ if (!waited)
65
+ return undefined;
66
+ }
32
67
  }
33
68
  };
34
69
  const clientFields = ({ client }) => ({
@@ -1,7 +1,9 @@
1
+ import { type CrmViewing } from "../crm/index.js";
1
2
  import { CATEGORIES, type Category } from "../domain/categories.js";
2
3
  import type { DealKind } from "../domain/deals.js";
3
4
  import { type Standing } from "../domain/relations.js";
4
5
  import type { AccountKey, KnowledgeRelation, MessageStore } from "../store/index.js";
6
+ import { type CopyViewer } from "../store/store.js";
5
7
  /** Items a context section lists before it says `hasMore`. */
6
8
  export declare const SECTION_LIMIT = 20;
7
9
  /** What one store list answers at most: a read that fills it may hold more. */
@@ -26,7 +28,9 @@ export declare const keyOf: ({ provider, account }: AccountKey) => string;
26
28
  * The accounts a context reads, the caller's `--source` or group already resolved; every account when none is
27
29
  * given. A row no account reported — the owner's, an agent's — is always in it. `left` collects every account whose
28
30
  * rows were kept out, so `coverage` can say so. `denied` holds the kinds the profile denies (`deals.list`,
29
- * `leads.list`): no row, title or count of them is answered, and `coverage` says they were denied.
31
+ * `leads.list`): no row, title or count of them is answered, and `coverage` says they were denied. `viewers` are the
32
+ * CRM copies' rules for the profile (SEC-197, `crmViewerOf`): a deal or lead one may not read is never named, and each
33
+ * note on why a copy shows less goes to `coverage`.
30
34
  */
31
35
  export interface Scope {
32
36
  accounts: AccountKey[] | undefined;
@@ -35,8 +39,18 @@ export interface Scope {
35
39
  denied: ReadonlySet<DealKind>;
36
40
  /** A ref the answer may name: none of a denied kind. */
37
41
  allows(ref: string): boolean;
42
+ viewers: CopyViewer[];
43
+ viewerNotes: {
44
+ source: string;
45
+ reason: string;
46
+ }[];
47
+ /** A deal or lead row every viewer may read. */
48
+ sees(deal: {
49
+ account: AccountKey | null;
50
+ assignee: string | null;
51
+ }): boolean;
38
52
  }
39
- export declare const scopeOf: (accounts: AccountKey[] | undefined, denied?: readonly DealKind[]) => Scope;
53
+ export declare const scopeOf: (accounts: AccountKey[] | undefined, denied?: readonly DealKind[], viewing?: readonly CrmViewing[]) => Scope;
40
54
  export declare const notRejected: <T extends {
41
55
  review: string;
42
56
  }>(rows: T[]) => T[];
@@ -1,6 +1,7 @@
1
1
  import { crmGapsOf } from "../crm/index.js";
2
2
  import { CATEGORIES } from "../domain/categories.js";
3
3
  import { isUsable } from "../domain/relations.js";
4
+ import { seenBy } from "../store/store.js";
4
5
  /** Items a context section lists before it says `hasMore`. */
5
6
  export const SECTION_LIMIT = 20;
6
7
  /** What one store list answers at most: a read that fills it may hold more. */
@@ -15,14 +16,18 @@ export const sectionOf = (all, limit, next, { more = false, total = all.length,
15
16
  };
16
17
  };
17
18
  export const keyOf = ({ provider, account }) => `${provider}:${account}`;
18
- export const scopeOf = (accounts, denied = []) => {
19
+ export const scopeOf = (accounts, denied = [], viewing = []) => {
19
20
  const asked = accounts && new Set(accounts.map(keyOf));
20
21
  const left = new Set();
21
22
  const kinds = new Set(denied);
23
+ const viewers = viewing.flatMap(({ viewer }) => (viewer ? [viewer] : []));
22
24
  return {
23
25
  accounts,
24
26
  left,
25
27
  denied: kinds,
28
+ viewers,
29
+ viewerNotes: viewing.flatMap(({ viewer, note }) => viewer && note ? [{ source: keyOf(viewer.account), reason: note }] : []),
30
+ sees: ({ account, assignee }) => viewers.every((viewer) => seenBy(viewer, { provider: account?.provider, account: account?.account, assignee })),
26
31
  has: (account) => {
27
32
  if (account == null)
28
33
  return true;
@@ -57,6 +62,7 @@ export const edgesOf = async (store, ref, scope) => {
57
62
  about: ref,
58
63
  includeEnded: true,
59
64
  deniedKinds: [...scope.denied],
65
+ ...(scope.viewers.length ? { viewers: scope.viewers } : {}),
60
66
  limit: STORE_PAGE,
61
67
  ...(scope.accounts === undefined ? {} : { accounts: scope.accounts }),
62
68
  });
@@ -139,6 +145,8 @@ export const coverageFor = async (store, base, scope) => {
139
145
  const named = new Set(notRead.map((one) => one.source));
140
146
  for (const kind of scope.denied)
141
147
  notRead.push({ source: `${kind}s`, reason: "denied" });
148
+ for (const note of scope.viewerNotes)
149
+ notRead.push(note);
142
150
  if (scope.accounts !== undefined)
143
151
  for (const key of await store.accounts.accounts())
144
152
  if (!scope.has(key))
@@ -1,3 +1,4 @@
1
+ import { type CrmViewing } from "../crm/index.js";
1
2
  import type { DealKind } from "../domain/deals.js";
2
3
  import { type Standing } from "../domain/relations.js";
3
4
  import type { AccountKey, Deal, MessageStore, StageChange } from "../store/index.js";
@@ -48,13 +49,17 @@ export interface DealContextOptions {
48
49
  now?: number;
49
50
  /** The kinds the profile denies: a deal or lead of one is not answered. */
50
51
  deniedKinds?: readonly DealKind[];
52
+ /**
53
+ * Each CRM copy's rule for the profile (`crmViewerOf`, SEC-197): a deal or lead it may not read is not found.
54
+ */
55
+ viewing?: readonly CrmViewing[];
51
56
  }
52
57
  /**
53
58
  * One answer about a deal or a lead from the store: the row, how it moved, its client, people, project, money and
54
59
  * what its people said within its lifetime. Nothing is inferred from a stage's name. A CRM's copy outside
55
60
  * `accounts` is not answered, and a CRM's relationships outside it are left out.
56
61
  */
57
- export declare const dealContext: (store: MessageStore, reference: string, { accounts, limit, now, deniedKinds }?: DealContextOptions) => Promise<DealContext>;
62
+ export declare const dealContext: (store: MessageStore, reference: string, { accounts, limit, now, deniedKinds, viewing }?: DealContextOptions) => Promise<DealContext>;
58
63
  /** The compact form for a model's context: names, roles and standings, totals and counts, no row detail. */
59
64
  export interface DealBrief {
60
65
  ref: string;
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { withReadableDeal } from "../crm/index.js";
2
3
  import { isUsable } from "../domain/relations.js";
3
4
  import { isClosedState } from "../tasks/index.js";
4
5
  import { coverageFor, edgesOf, grouped, namesOf, notRejected, organizationCategories, SECTION_LIMIT, STORE_PAGE, scopeOf, sectionOf, } from "./business-context.js";
@@ -11,19 +12,23 @@ const DAY = 86_400_000;
11
12
  * what its people said within its lifetime. Nothing is inferred from a stage's name. A CRM's copy outside
12
13
  * `accounts` is not answered, and a CRM's relationships outside it are left out.
13
14
  */
14
- export const dealContext = async (store, reference, { accounts, limit = SECTION_LIMIT, now = Date.now(), deniedKinds = [] } = {}) => {
15
- const scope = scopeOf(accounts, deniedKinds);
15
+ export const dealContext = async (store, reference, { accounts, limit = SECTION_LIMIT, now = Date.now(), deniedKinds = [], viewing = [] } = {}) => {
16
+ const scope = scopeOf(accounts, deniedKinds, viewing);
16
17
  const kind = /^lead:/.test(reference.trim()) ? "lead" : "deal";
17
18
  if (scope.denied.has(kind))
18
19
  throw new CliError("permission_error", `the profile denies ${kind}s.list, so no ${kind} is answered`, {
19
20
  reason: "deal.denied",
20
21
  });
21
22
  const row = await store.deals.get(reference);
22
- const deal = row.deal !== null && !scope.allows(row.deal) ? { ...row, deal: null } : row;
23
+ const deal = await withReadableDeal(store, scope.viewers, row.deal !== null && !scope.allows(row.deal) ? { ...row, deal: null } : row);
23
24
  if (!scope.has(deal.account))
24
25
  throw new CliError("not_found", `${deal.ref} is a copy from an account outside the accounts asked for`, {
25
26
  reason: "deal.out-of-scope",
26
27
  });
28
+ if (!scope.sees(deal))
29
+ throw new CliError("not_found", `${deal.ref} is not a copy this profile's CRM sign-in may read`, {
30
+ reason: "deal.not-readable",
31
+ });
27
32
  const { edges, full } = await edgesOf(store, deal.ref, scope);
28
33
  const people = edges.filter((edge) => edge.role.kind === "related-to" && edge.from === deal.ref && edge.to.startsWith("person:"));
29
34
  const names = await namesOf(store, people.map(({ to }) => to));
@@ -1,3 +1,4 @@
1
+ import type { CrmViewing } from "../crm/index.js";
1
2
  import { type DealKind } from "../domain/deals.js";
2
3
  import type { AccountKey, Deal, MessageStore, Organization } from "../store/index.js";
3
4
  import { type Category, type Coverage, type Related, type Section } from "./business-context.js";
@@ -62,6 +63,11 @@ export interface OrganizationContextOptions {
62
63
  limit?: number;
63
64
  /** The kinds the profile denies: none of their rows, titles or counts is answered. */
64
65
  deniedKinds?: readonly DealKind[];
66
+ /**
67
+ * Each CRM copy's rule for the profile (`crmViewerOf`, SEC-197): a deal or lead it may not read is left out, and
68
+ * `coverage.notRead` carries the rule's note.
69
+ */
70
+ viewing?: readonly CrmViewing[];
65
71
  }
66
72
  export declare const dealLine: (deal: Deal) => DealLine;
67
73
  /** Open tasks of these projects, the soonest due first, and the command that lists them when it is one project's. */
@@ -79,4 +85,4 @@ export declare const openTasksOf: (store: MessageStore, projects: {
79
85
  * nobody confirmed is `reported`, one that stopped is `ended`, one waiting for the owner `proposed`. A CRM's rows
80
86
  * outside `accounts` are left out, and `coverage` names that CRM.
81
87
  */
82
- export declare const organizationContext: (store: MessageStore, reference: string, { accounts, limit, deniedKinds }?: OrganizationContextOptions) => Promise<OrganizationContext>;
88
+ export declare const organizationContext: (store: MessageStore, reference: string, { accounts, limit, deniedKinds, viewing }?: OrganizationContextOptions) => Promise<OrganizationContext>;
@@ -3,7 +3,7 @@ import { parseLucene } from "@wirecat/cli-base/query";
3
3
  import { DEAL_KINDS } from "../domain/deals.js";
4
4
  import { isUsable } from "../domain/relations.js";
5
5
  import { isClosedState } from "../tasks/index.js";
6
- import { coverageFor, edgesOf, grouped, namesOf, notRejected, organizationCategories, SECTION_LIMIT, STORE_PAGE, scopeOf, sectionOf, } from "./business-context.js";
6
+ import { coverageFor, edgesOf, grouped, keyOf, namesOf, notRejected, organizationCategories, SECTION_LIMIT, STORE_PAGE, scopeOf, sectionOf, } from "./business-context.js";
7
7
  import { communicationsOf } from "./communications.js";
8
8
  import { moneyOf } from "./money-context.js";
9
9
  export const dealLine = (deal) => ({
@@ -51,7 +51,7 @@ const oneKind = (rows, commands) => commands.find(([fits]) => rows.every(fits))?
51
51
  * nobody confirmed is `reported`, one that stopped is `ended`, one waiting for the owner `proposed`. A CRM's rows
52
52
  * outside `accounts` are left out, and `coverage` names that CRM.
53
53
  */
54
- export const organizationContext = async (store, reference, { accounts, limit = SECTION_LIMIT, deniedKinds = [] } = {}) => {
54
+ export const organizationContext = async (store, reference, { accounts, limit = SECTION_LIMIT, deniedKinds = [], viewing = [] } = {}) => {
55
55
  const id = /^(?:organization:)?(\d+)$/.exec(reference.trim())?.[1];
56
56
  if (id === undefined)
57
57
  throw new CliError("validation_error", "an organization is organization:<id>");
@@ -59,7 +59,7 @@ export const organizationContext = async (store, reference, { accounts, limit =
59
59
  const [organization] = await store.knowledge.organizations(parseLucene(`id:${id}`));
60
60
  if (!organization)
61
61
  throw new CliError("not_found", `no ${ref} in the store`);
62
- const scope = scopeOf(accounts, deniedKinds);
62
+ const scope = scopeOf(accounts, deniedKinds, viewing);
63
63
  const own = (await store.knowledge.ownOrganizations()).some((one) => one.ref === ref);
64
64
  const { edges, full } = await edgesOf(store, ref, scope);
65
65
  const names = await namesOf(store, edges.flatMap(({ from, to }) => [from, to]));
@@ -70,16 +70,27 @@ export const organizationContext = async (store, reference, { accounts, limit =
70
70
  const partners = grouped(edges, (edge) => (edge.role.kind !== "partner-of" ? undefined : edge.from === ref ? edge.to : edge.from), names);
71
71
  const deals = [];
72
72
  let dealsFull = false;
73
+ // A viewer's `deals.list` filter hides every row not assigned to it, so each limited copy is read on its own and
74
+ // the rest without it: a page then holds only rows the profile may read.
75
+ const limited = new Set(scope.viewers.map(({ account }) => keyOf(account)));
76
+ const reads = limited.size
77
+ ? [
78
+ { accounts: (accounts ?? (await store.accounts.accounts())).filter((one) => !limited.has(keyOf(one))) },
79
+ ...scope.viewers
80
+ .filter(({ account }) => scope.has(account))
81
+ .map((viewer) => ({ account: viewer.account, viewer })),
82
+ ]
83
+ : [accounts === undefined ? {} : { accounts }];
73
84
  for (const kind of DEAL_KINDS.filter((one) => !scope.denied.has(one))) {
74
- const found = await store.deals.list({
75
- kind,
76
- organization: ref,
77
- status: "open",
78
- limit: STORE_PAGE,
79
- ...(accounts === undefined ? {} : { accounts }),
80
- });
81
- dealsFull ||= found.hasMore;
82
- for (const deal of found.items)
85
+ const ofKind = [];
86
+ for (const read of reads) {
87
+ const found = await store.deals.list({ kind, organization: ref, status: "open", limit: STORE_PAGE, ...read });
88
+ dealsFull ||= found.hasMore;
89
+ for (const deal of found.items)
90
+ ofKind.push(deal);
91
+ }
92
+ ofKind.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || Number(b.id) - Number(a.id));
93
+ for (const deal of ofKind)
83
94
  deals.push(deal);
84
95
  }
85
96
  const catalog = new Map((await store.knowledge.projects()).map((project) => [project.ref, project]));
@@ -1,3 +1,4 @@
1
+ import type { CrmViewing } from "../crm/index.js";
1
2
  import type { DealKind } from "../domain/deals.js";
2
3
  import type { AccountKey, MessageStore, PersonRecord } from "../store/store.js";
3
4
  import { type Category, type Coverage, type Related, type Scope, type Section } from "./business-context.js";
@@ -30,6 +31,11 @@ export interface CanonicalContextOptions extends ContextOptions {
30
31
  limit?: number;
31
32
  /** The kinds the profile denies: no deal or lead of theirs is named. */
32
33
  deniedKinds?: readonly DealKind[];
34
+ /**
35
+ * Each CRM copy's rule for the profile (`crmViewerOf`, SEC-197): a deal or lead it may not read is not named, and
36
+ * `coverage.notRead` carries the rule's note.
37
+ */
38
+ viewing?: readonly CrmViewing[];
33
39
  }
34
40
  export declare const personBusiness: (store: MessageStore, uid: string, { limit, scope }?: {
35
41
  limit?: number;
@@ -40,4 +46,4 @@ export declare const personBusiness: (store: MessageStore, uid: string, { limit,
40
46
  * someone seen by several accounts alike. Every identity is read in every account in scope that saw it — never one
41
47
  * picked for them (WC-ACCT-9) — and `coverage` says what was read and what was not.
42
48
  */
43
- export declare const canonicalPersonContext: (store: MessageStore, reference: string, { accounts, limit, deniedKinds, ...options }?: CanonicalContextOptions) => Promise<CanonicalPersonContext>;
49
+ export declare const canonicalPersonContext: (store: MessageStore, reference: string, { accounts, limit, deniedKinds, viewing, ...options }?: CanonicalContextOptions) => Promise<CanonicalPersonContext>;
@@ -37,14 +37,14 @@ export const personBusiness = async (store, uid, { limit = SECTION_LIMIT, scope
37
37
  * someone seen by several accounts alike. Every identity is read in every account in scope that saw it — never one
38
38
  * picked for them (WC-ACCT-9) — and `coverage` says what was read and what was not.
39
39
  */
40
- export const canonicalPersonContext = async (store, reference, { accounts, limit, deniedKinds, ...options } = {}) => {
40
+ export const canonicalPersonContext = async (store, reference, { accounts, limit, deniedKinds, viewing, ...options } = {}) => {
41
41
  const uid = /^person:(\d+)$/.exec(reference.trim())?.[1];
42
42
  if (uid === undefined)
43
43
  throw new CliError("validation_error", "a person is person:<id>");
44
44
  const record = await store.people.personByUid(uid);
45
45
  if (!record)
46
46
  throw new CliError("not_found", `no person:${uid} in the store`);
47
- const scope = scopeOf(accounts, deniedKinds);
47
+ const scope = scopeOf(accounts, deniedKinds, viewing);
48
48
  const stored = await store.accounts.storedAccounts();
49
49
  // The scope is the caller's: every stored account it holds is readable, whatever its personal or work scope.
50
50
  const readable = stored.filter((one) => scope.has(one));
@@ -21,6 +21,8 @@ export const forgetActivitiesOn = (database, accountId, kind, externalIds, at) =
21
21
  /** A CRM's text field holds what people typed or pasted, a whole e-mail thread too. */
22
22
  const MOST_BODY = 20_000;
23
23
  const MOST_SUBJECT = 500;
24
+ /** The kinds that record something already done rather than ask for it. */
25
+ const LOGGED = new Set(["comment", "call", "email", "meeting"]);
24
26
  const activityOf = (externalId, fields) => ({
25
27
  externalId,
26
28
  kind: fields.kind,
@@ -64,6 +66,21 @@ export const crmActivitiesOver = (context) => {
64
66
  : database
65
67
  .prepare(`SELECT 1 FROM ${TABLES[kind]} WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL`)
66
68
  .get(accountId, externalId)) !== undefined;
69
+ /**
70
+ * When it was done, as near as the copy can tell: the CRM's change that closed it, kept once seen. A record of
71
+ * something already done — a comment, a logged call, mail or meeting — that arrives done with no due date was done
72
+ * when it was made, and `changes list` lists it once. A task or to-do may be closed long after it was made, often
73
+ * with no deadline in Bitrix24, so it keeps the CRM's change.
74
+ */
75
+ const doneAt = (activity, held) => {
76
+ if (!activity.done)
77
+ return null;
78
+ if (held?.done)
79
+ return held.done_at ?? null;
80
+ return held === undefined && activity.dueAt == null && LOGGED.has(activity.kind)
81
+ ? activity.createdAt
82
+ : activity.updatedAt;
83
+ };
67
84
  const save = (key, activities) => write(database, () => {
68
85
  const accountId = accountPk(context, key);
69
86
  const at = now();
@@ -88,8 +105,7 @@ export const crmActivitiesOver = (context) => {
88
105
  body: textOf(activity.body, MOST_BODY),
89
106
  due_at: activity.dueAt ?? null,
90
107
  done: activity.done,
91
- // When it was done, as near as the copy can tell: the CRM's change that closed it, kept once seen.
92
- done_at: activity.done ? (held?.done ? (held.done_at ?? null) : activity.updatedAt) : null,
108
+ done_at: doneAt(activity, held),
93
109
  assignee: activity.assignee ? crmIdentityId(key, activity.assignee, "user") : null,
94
110
  created_at: activity.createdAt,
95
111
  updated_at: activity.updatedAt,
@@ -52,6 +52,14 @@ export interface ChangeFilter {
52
52
  limit: number;
53
53
  offset: number;
54
54
  }
55
+ /**
56
+ * `sql` with each `?N` as a plain `?`, and its values in the order they appear. node:sqlite before Node 22.23 binds
57
+ * no `?N` from a list of values ("column index out of range"), and every version refuses a value the SQL never uses.
58
+ */
59
+ export declare const usedParams: <T>(sql: string, params: readonly T[]) => {
60
+ sql: string;
61
+ params: T[];
62
+ };
55
63
  /** How many changes of each kind `filter`'s window holds, every page together. */
56
64
  export declare const crmChangeCounts: (context: StoreContext, key: AccountKey, filter: Omit<ChangeFilter, "limit" | "offset">) => Record<CrmChangeKind, number>;
57
65
  /**
@@ -16,6 +16,14 @@ export const CRM_CHANGES = [
16
16
  const HALF_DAY = 43_200_000;
17
17
  const DAY = 86_400_000;
18
18
  const utcDay = (at) => new Date(at).toISOString().slice(0, 10);
19
+ /**
20
+ * `sql` with each `?N` as a plain `?`, and its values in the order they appear. node:sqlite before Node 22.23 binds
21
+ * no `?N` from a list of values ("column index out of range"), and every version refuses a value the SQL never uses.
22
+ */
23
+ export const usedParams = (sql, params) => ({
24
+ sql: sql.replace(/\?\d+/g, "?"),
25
+ params: [...sql.matchAll(/\?(\d+)/g)].map((one) => params[Number(one[1]) - 1]),
26
+ });
19
27
  /** The SQL of every change in `filter`'s window, unordered, and its numbered parameters (`?13`, `?14` page it). */
20
28
  const changesQuery = (context, key, filter) => {
21
29
  const accountId = findAccountPk(context, key);
@@ -73,7 +81,13 @@ const changesQuery = (context, key, filter) => {
73
81
  `FROM (SELECT r.id, r.fields, ${itemOf("r.id")} AS item, (SELECT target_type FROM record_relations ` +
74
82
  "WHERE record_id = r.id AND role = 'on' LIMIT 1) AS target FROM records r WHERE r.account_id = ?1 " +
75
83
  `AND r.type = ?4 AND r.deleted_at IS NULL AND json_extract(r.fields, '$.${field}') ` +
76
- "BETWEEN ?6 AND ?7) a " +
84
+ "BETWEEN ?6 AND ?7" +
85
+ // One that arrived done with no due date was done as it was made: its `activity_added` says it.
86
+ (field === "done_at"
87
+ ? " AND NOT (json_extract(r.fields, '$.due_at') IS NULL AND " +
88
+ "json_extract(r.fields, '$.done_at') = json_extract(r.fields, '$.created_at'))"
89
+ : "") +
90
+ ") a " +
77
91
  // A viewer reads an activity on its own deal or lead, or one on contacts alone that is assigned to it.
78
92
  `WHERE ?15 IS NULL OR a.item IS NOT NULL OR (NOT ${onDealOrLead} AND json_extract(a.fields, '$.assignee') = ?16)`),
79
93
  "SELECT 'person_added', CAST(json_extract(r.fields, '$.created_at') AS INTEGER), 'person', NULL, r.id, NULL, " +
@@ -119,9 +133,8 @@ export const crmChangeCounts = (context, key, filter) => {
119
133
  const query = changesQuery(context, key, { ...filter, limit: 0, offset: 0 });
120
134
  if (!query)
121
135
  return counts;
122
- for (const row of context.database
123
- .prepare(`SELECT change, count(*) AS n FROM (${query.sql}) GROUP BY change`)
124
- .all(...query.params))
136
+ const counted = usedParams(`SELECT change, count(*) AS n FROM (${query.sql}) GROUP BY change`, query.params);
137
+ for (const row of context.database.prepare(counted.sql).all(...counted.params))
125
138
  counts[row.change] = Number(row.n);
126
139
  return counts;
127
140
  };
@@ -136,9 +149,8 @@ export const crmChanges = (context, key, filter) => {
136
149
  const query = changesQuery(context, key, filter);
137
150
  if (!query)
138
151
  return { items: [], hasMore: false };
139
- const rows = database
140
- .prepare(`${query.sql} ORDER BY at DESC, change, kind, item DESC, record DESC LIMIT ?13 OFFSET ?14`)
141
- .all(...query.params);
152
+ const paged = usedParams(`${query.sql} ORDER BY at DESC, change, kind, item DESC, record DESC LIMIT ?13 OFFSET ?14`, query.params);
153
+ const rows = database.prepare(paged.sql).all(...paged.params);
142
154
  const stageName = database.prepare("SELECT name FROM pipeline_stages WHERE id = ?");
143
155
  const nameOf = (id) => id == null ? null : (stageName.get(Number(id))?.name ?? null);
144
156
  const itemStatements = Object.fromEntries(["deal", "lead"].map((kind) => [
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { isCrmUserId, normalCrmUserId } from "../../domain/crm.js";
2
+ import { isCrmUserId } from "../../domain/crm.js";
3
3
  /** `reported`: what a CRM account says is a relationship nobody confirmed; `review`: it waits as a proposal. */
4
4
  export const CRM_LINK_MODES = ["reported", "review"];
5
5
  /** What a CRM company type may mean: the company buys from the own company, sells to it, or partners with it. */
@@ -179,11 +179,10 @@ export const parseCrmSettingValue = (name, value) => {
179
179
  return picked(name, text, CRM_SCOPES);
180
180
  if (name === "activities")
181
181
  return picked(name, text, CRM_ACTIVITIES);
182
- if (name === "self") {
183
- if (!isCrmUserId(text))
184
- throw new CliError("validation_error", `self takes the CRM's numeric user id: not "${text}"`);
185
- return normalCrmUserId(text);
186
- }
182
+ // The copy's viewers read their rule by it (SEC-201): a typed id could name the administrator.
183
+ if (name === "self")
184
+ throw new CliError("validation_error", "self is whose copy it is, and only the copy's first sync records it: unset it to give the copy to the next " +
185
+ "sign-in's sync", { reason: "crm.self-from-sync" });
187
186
  if (name === "unassigned") {
188
187
  const ids = [...new Set(text.split(",").map((one) => one.trim()))];
189
188
  const bad = ids.find((one) => !isCrmUserId(one));
@@ -1,5 +1,6 @@
1
1
  import { type RelationKind, type RoleList, type Standing } from "../../domain/relations.js";
2
2
  import type { AccountKey } from "../types.js";
3
+ import type { CopyViewer } from "./copy-viewer.js";
3
4
  import type { StoreContext } from "./open.js";
4
5
  import { type KnowledgeRelation } from "./relation-proposals.js";
5
6
  export interface RelationFilter {
@@ -22,6 +23,8 @@ export interface RelationFilter {
22
23
  accounts?: AccountKey[];
23
24
  /** No row with an end of these types, such as `deal` and `lead` a profile denies. */
24
25
  deniedKinds?: string[];
26
+ /** No row with a deal or lead end that one of these may not read (SEC-197); each limits only its own account. */
27
+ viewers?: readonly CopyViewer[];
25
28
  limit?: number;
26
29
  /** 1-based. */
27
30
  page?: number;
@@ -83,6 +83,22 @@ export const relationListOver = (context) => {
83
83
  const list = filter.deniedKinds.map(() => "?").join(", ");
84
84
  add(`r.from_type NOT IN (${list}) AND r.to_type NOT IN (${list})`, ...filter.deniedKinds, ...filter.deniedKinds);
85
85
  }
86
+ for (const viewer of filter.viewers ?? []) {
87
+ const account = database
88
+ .prepare("SELECT id FROM accounts WHERE provider = ? AND external_id = ?")
89
+ .get(viewer.account.provider, viewer.account.account);
90
+ if (!account)
91
+ continue;
92
+ // `IS NOT` keeps an unassigned row hidden: `<>` would compare with null and let it through.
93
+ const other = viewer.assignee === null ? "" : " AND json_extract(e.metadata, '$.assignee') IS NOT ?";
94
+ for (const side of ["from", "to"])
95
+ for (const [type, table] of [
96
+ ["deal", "deals"],
97
+ ["lead", "leads"],
98
+ ])
99
+ add(`NOT (r.${side}_type = '${type}' AND EXISTS (SELECT 1 FROM ${table} e WHERE e.id = r.${side}_id ` +
100
+ `AND e.account_id = ?${other}))`, Number(account.id), ...(viewer.assignee === null ? [] : [viewer.assignee]));
101
+ }
86
102
  const rows = database
87
103
  .prepare(`SELECT r.source, r.id FROM (
88
104
  SELECT 'link' AS source, id, from_type, from_id, to_type, to_id, kind, role, account_id, starts_at, ends_at,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.682.0",
3
+ "version": "0.684.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",