@wirecat/cli-core 0.683.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 +34 -0
- package/dist/cli/index.d.ts +2 -1
- package/dist/cli/index.js +2 -1
- package/dist/cli/service-api.d.ts +74 -0
- package/dist/cli/service-api.js +180 -0
- package/dist/cli/shared-command-exports.d.ts +1 -0
- package/dist/cli/shared-command-exports.js +2 -0
- package/dist/crm/cli/index.js +25 -38
- package/dist/crm/index.d.ts +1 -1
- package/dist/crm/index.js +1 -1
- package/dist/crm/viewer.d.ts +14 -1
- package/dist/crm/viewer.js +38 -1
- package/dist/oauth/requests.js +48 -13
- package/dist/services/deal-context.d.ts +1 -1
- package/dist/services/deal-context.js +2 -1
- package/dist/services/organization-context.js +22 -12
- package/dist/store/sqlite/crm-activities.js +9 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,40 @@ 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
|
+
|
|
8
42
|
## 0.683.0 — 16.11.2026
|
|
9
43
|
|
|
10
44
|
### Changed — may break callers
|
package/dist/cli/index.d.ts
CHANGED
|
@@ -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);
|
package/dist/crm/cli/index.js
CHANGED
|
@@ -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
|
|
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) =>
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
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) => {
|
package/dist/crm/index.d.ts
CHANGED
|
@@ -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";
|
package/dist/crm/viewer.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
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>;
|
package/dist/crm/viewer.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import {
|
|
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
|
+
};
|
package/dist/oauth/requests.js
CHANGED
|
@@ -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
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type CrmViewing } from "../crm/index.js";
|
|
2
2
|
import type { DealKind } from "../domain/deals.js";
|
|
3
3
|
import { type Standing } from "../domain/relations.js";
|
|
4
4
|
import type { AccountKey, Deal, MessageStore, StageChange } from "../store/index.js";
|
|
@@ -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";
|
|
@@ -19,7 +20,7 @@ export const dealContext = async (store, reference, { accounts, limit = SECTION_
|
|
|
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",
|
|
@@ -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) => ({
|
|
@@ -70,18 +70,28 @@ 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
|
|
75
|
-
|
|
76
|
-
organization: ref,
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
for (const deal of
|
|
83
|
-
|
|
84
|
-
deals.push(deal);
|
|
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)
|
|
94
|
+
deals.push(deal);
|
|
85
95
|
}
|
|
86
96
|
const catalog = new Map((await store.knowledge.projects()).map((project) => [project.ref, project]));
|
|
87
97
|
const projects = new Map();
|
|
@@ -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,
|
|
@@ -65,15 +67,19 @@ export const crmActivitiesOver = (context) => {
|
|
|
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;
|
|
67
69
|
/**
|
|
68
|
-
* When it was done, as near as the copy can tell: the CRM's change that closed it, kept once seen.
|
|
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.
|
|
70
74
|
*/
|
|
71
75
|
const doneAt = (activity, held) => {
|
|
72
76
|
if (!activity.done)
|
|
73
77
|
return null;
|
|
74
78
|
if (held?.done)
|
|
75
79
|
return held.done_at ?? null;
|
|
76
|
-
return held === undefined && activity.dueAt == null
|
|
80
|
+
return held === undefined && activity.dueAt == null && LOGGED.has(activity.kind)
|
|
81
|
+
? activity.createdAt
|
|
82
|
+
: activity.updatedAt;
|
|
77
83
|
};
|
|
78
84
|
const save = (key, activities) => write(database, () => {
|
|
79
85
|
const accountId = accountPk(context, key);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "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",
|