@wirecat/cli-core 0.646.0 → 0.648.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/account-remove.d.ts +5 -0
  4. package/dist/cli/account-remove.js +6 -1
  5. package/dist/cli/app-doctor-command.js +15 -55
  6. package/dist/cli/app-store.d.ts +12 -0
  7. package/dist/cli/app-store.js +25 -0
  8. package/dist/cli/commands-command.js +10 -3
  9. package/dist/cli/doctor-reports-command.d.ts +22 -0
  10. package/dist/cli/doctor-reports-command.js +82 -0
  11. package/dist/cli/help/command-help.d.ts +1 -0
  12. package/dist/cli/help/command-help.js +7 -6
  13. package/dist/cli/index.d.ts +3 -1
  14. package/dist/cli/index.js +3 -1
  15. package/dist/cli/messenger/doctor-command.js +21 -62
  16. package/dist/cli/messenger/stats-command.js +1 -1
  17. package/dist/cli/messenger/store-maintenance-command.js +3 -3
  18. package/dist/cli/messenger/tasks-command.js +1 -3
  19. package/dist/cli/permission-keys.js +4 -2
  20. package/dist/cli/program.js +26 -10
  21. package/dist/cli/settings.d.ts +2 -0
  22. package/dist/cli/settings.js +3 -2
  23. package/dist/cli/store-recover.js +2 -2
  24. package/dist/cli/store-settings.d.ts +2 -2
  25. package/dist/cli/store-settings.js +11 -5
  26. package/dist/cli/unknown-profile.d.ts +9 -0
  27. package/dist/cli/unknown-profile.js +23 -0
  28. package/dist/crm/cli/index.js +26 -4
  29. package/dist/crm/cli/search-all.js +4 -4
  30. package/dist/crm/source.d.ts +8 -2
  31. package/dist/crm/sync.d.ts +7 -1
  32. package/dist/crm/sync.js +73 -0
  33. package/dist/domain/crm.d.ts +27 -0
  34. package/dist/domain/crm.js +2 -0
  35. package/dist/entities/deal.d.ts +17 -0
  36. package/dist/entities/deal.js +16 -0
  37. package/dist/entities/index.d.ts +2 -0
  38. package/dist/errors/failures.d.ts +2 -0
  39. package/dist/errors/failures.js +6 -0
  40. package/dist/errors/reasons.js +18 -1
  41. package/dist/index.d.ts +2 -1
  42. package/dist/index.js +2 -1
  43. package/dist/kit/index.d.ts +1 -0
  44. package/dist/kit/index.js +1 -0
  45. package/dist/kit/own-catalogue.d.ts +7 -0
  46. package/dist/kit/own-catalogue.js +21 -0
  47. package/dist/oauth/index.d.ts +2 -2
  48. package/dist/oauth/index.js +2 -1
  49. package/dist/oauth/provider.d.ts +4 -0
  50. package/dist/oauth/provider.js +16 -1
  51. package/dist/oauth/storage.d.ts +5 -0
  52. package/dist/oauth/storage.js +20 -0
  53. package/dist/runs/error-detail.d.ts +1 -1
  54. package/dist/runs/error-detail.js +5 -2
  55. package/dist/runs/events.d.ts +1 -1
  56. package/dist/runs/secrets.d.ts +5 -4
  57. package/dist/runs/secrets.js +8 -4
  58. package/dist/sends/permissions.d.ts +2 -0
  59. package/dist/sends/permissions.js +4 -1
  60. package/dist/services/metadata.d.ts +1 -1
  61. package/dist/services/search-all.js +1 -1
  62. package/dist/sftp/index.d.ts +1 -0
  63. package/dist/sftp/index.js +1 -0
  64. package/dist/sftp/session.d.ts +61 -0
  65. package/dist/sftp/session.js +230 -0
  66. package/dist/sftp/ssh2.d.ts +38 -0
  67. package/dist/sftp/ssh2.js +306 -0
  68. package/dist/store/index.d.ts +1 -0
  69. package/dist/store/index.js +1 -0
  70. package/dist/store/sqlite/crm-activities.d.ts +29 -0
  71. package/dist/store/sqlite/crm-activities.js +113 -0
  72. package/dist/store/sqlite/crm-settings.d.ts +5 -1
  73. package/dist/store/sqlite/crm-settings.js +9 -1
  74. package/dist/store/sqlite/crm.d.ts +9 -1
  75. package/dist/store/sqlite/crm.js +6 -1
  76. package/dist/store/sqlite/deals.d.ts +4 -3
  77. package/dist/store/sqlite/deals.js +8 -2
  78. package/dist/store/sqlite/open-store.js +14 -1
  79. package/package.json +14 -4
  80. package/parity.json +2 -11
@@ -154,6 +154,33 @@ export interface CrmRecords {
154
154
  person: CrmPerson;
155
155
  organization: CrmOrganization;
156
156
  }
157
+ /** What a CRM activity is: a call, an e-mail, a meeting, a to-do, a task of the CRM's task tracker, or a comment. */
158
+ export declare const CRM_ACTIVITY_KINDS: readonly ["call", "email", "meeting", "todo", "task", "comment", "other"];
159
+ export type CrmActivityKind = (typeof CRM_ACTIVITY_KINDS)[number];
160
+ /**
161
+ * An activity on the CRM's deals and leads, as the CRM has it. `externalId` is unique among the account's activities
162
+ * of every kind (a source with separate lists prefixes them). Contact data the CRM keeps on it, such as a call's
163
+ * phone number, is never part of it: it would bypass the limits on reading clients' contacts.
164
+ */
165
+ export interface CrmActivity {
166
+ externalId: string;
167
+ kind: CrmActivityKind;
168
+ subject: string;
169
+ /** The text: an e-mail's body, a comment, a task's description; `null` when it has none. */
170
+ body?: string | null;
171
+ /** Epoch milliseconds. */
172
+ dueAt?: number | null;
173
+ done: boolean;
174
+ /** The CRM user responsible for it, by the CRM's id. */
175
+ assignee?: string | null;
176
+ createdAt: number;
177
+ updatedAt: number;
178
+ /** The deals and leads it is on, by the CRM's ids; one on neither is not stored. */
179
+ on: {
180
+ kind: DealKind;
181
+ externalId: string;
182
+ }[];
183
+ }
157
184
  /** The account's scope settings: `also` are the users whose deals the owner counts as nobody's. */
158
185
  export type CrmScopeSetting = {
159
186
  mode: "all";
@@ -1,5 +1,7 @@
1
1
  /** What a CRM holds that the store copies: its deals and leads, and the contacts and companies on them. */
2
2
  export const CRM_KINDS = ["organization", "person", "deal", "lead"];
3
+ /** What a CRM activity is: a call, an e-mail, a meeting, a to-do, a task of the CRM's task tracker, or a comment. */
4
+ export const CRM_ACTIVITY_KINDS = ["call", "email", "meeting", "todo", "task", "comment", "other"];
3
5
  /** A CRM's user id as `unassigned` takes it: digits, as every CRM core syncs numbers its users. */
4
6
  export const isCrmUserId = (id) => /^\d{1,20}$/.test(id);
5
7
  /** One spelling per user id, so `015`, ` 15` and `15` are one user wherever they come from. */
@@ -1,4 +1,17 @@
1
1
  import * as v from "valibot";
2
+ import { type CrmActivityKind } from "../domain/crm.js";
3
+ /** A call, e-mail, meeting, to-do, task or comment the CRM keeps on a deal or lead: what `show` lists. */
4
+ export interface DealActivity {
5
+ external_id: string;
6
+ kind: CrmActivityKind;
7
+ subject: string;
8
+ body: string | null;
9
+ due_at: string | null;
10
+ done: boolean;
11
+ assignee: string | null;
12
+ created_at: string;
13
+ updated_at: string;
14
+ }
2
15
  /**
3
16
  * A deal (`deal:<id>`), the owner's own or a CRM's copy: one shape for memo and every CRM CLI. Money is a decimal
4
17
  * string in its currency, both `null` when no amount is expected.
@@ -69,6 +82,8 @@ export declare const deal: v.StrictObjectSchema<{
69
82
  readonly project_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
70
83
  readonly created_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
71
84
  readonly updated_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
85
+ /** `show` of a CRM copy whose `activities` setting is on: its activities and tasks, open ones first. */
86
+ readonly activities: v.OptionalSchema<v.ArraySchema<v.GenericSchema<DealActivity>, undefined>, undefined>;
72
87
  readonly untrusted: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
73
88
  }, undefined>;
74
89
  /** A lead (`lead:<id>`): a deal's shape, in a lead pipeline. */
@@ -138,6 +153,8 @@ export declare const lead: v.StrictObjectSchema<{
138
153
  readonly project_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
139
154
  readonly created_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
140
155
  readonly updated_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
156
+ /** `show` of a CRM copy whose `activities` setting is on: its activities and tasks, open ones first. */
157
+ readonly activities: v.OptionalSchema<v.ArraySchema<v.GenericSchema<DealActivity>, undefined>, undefined>;
141
158
  readonly untrusted: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
142
159
  }, undefined>;
143
160
  /** A pipeline (`pipeline:<id>`) with its stages in order; `pipelines show` adds the funnel. */
@@ -1,4 +1,5 @@
1
1
  import * as v from "valibot";
2
+ import { CRM_ACTIVITY_KINDS } from "../domain/crm.js";
2
3
  import { DEAL_ROLES } from "../domain/deals.js";
3
4
  import { count, id, reference, text, time, untrusted } from "./fields.js";
4
5
  const nullableText = v.nullable(text);
@@ -6,6 +7,19 @@ const party = v.strictObject({ ref: reference, name: nullableText, owner: v.bool
6
7
  const outcome = v.picklist(["open", "won", "lost"]);
7
8
  const crmAccount = v.nullable(v.strictObject({ provider: text, account: text }));
8
9
  const day = v.nullable(v.pipe(v.string(), v.regex(/^\d{4}-\d{2}-\d{2}$/)));
10
+ // Typed by name: inferred, it makes every entity map that holds a deal too long for the compiler to write out.
11
+ const activity = v.strictObject({
12
+ external_id: text,
13
+ kind: v.picklist(CRM_ACTIVITY_KINDS),
14
+ subject: text,
15
+ body: nullableText,
16
+ due_at: v.nullable(time),
17
+ done: v.boolean(),
18
+ /** The identity `<account>/user/<id>` responsible for it. */
19
+ assignee: nullableText,
20
+ created_at: time,
21
+ updated_at: time,
22
+ });
9
23
  /**
10
24
  * A deal (`deal:<id>`), the owner's own or a CRM's copy: one shape for memo and every CRM CLI. Money is a decimal
11
25
  * string in its currency, both `null` when no amount is expected.
@@ -61,6 +75,8 @@ export const deal = v.strictObject({
61
75
  project_name: nullableText,
62
76
  created_at: time,
63
77
  updated_at: time,
78
+ /** `show` of a CRM copy whose `activities` setting is on: its activities and tasks, open ones first. */
79
+ activities: v.optional(v.array(activity)),
64
80
  untrusted,
65
81
  });
66
82
  /** A lead (`lead:<id>`): a deal's shape, in a lead pipeline. */
@@ -296,6 +296,7 @@ export declare const ENTITIES: {
296
296
  readonly project_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
297
297
  readonly created_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
298
298
  readonly updated_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
299
+ readonly activities: v.OptionalSchema<v.ArraySchema<v.GenericSchema<import("./deal.js").DealActivity>, undefined>, undefined>;
299
300
  readonly untrusted: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
300
301
  }, undefined>;
301
302
  readonly lead: v.StrictObjectSchema<{
@@ -357,6 +358,7 @@ export declare const ENTITIES: {
357
358
  readonly project_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
358
359
  readonly created_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
359
360
  readonly updated_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
361
+ readonly activities: v.OptionalSchema<v.ArraySchema<v.GenericSchema<import("./deal.js").DealActivity>, undefined>, undefined>;
360
362
  readonly untrusted: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
361
363
  }, undefined>;
362
364
  readonly pipeline: v.StrictObjectSchema<{
@@ -12,6 +12,8 @@ export declare const isCommanderFailure: (value: unknown) => value is Error & {
12
12
  code: string;
13
13
  exitCode: number;
14
14
  };
15
+ /** The reason of a commander usage error a caller matches instead of commander's English, when it has one. */
16
+ export declare const usageReason: (code: string) => string | undefined;
15
17
  /** What failed, never what it said: a messenger's refusal can quote the message back. */
16
18
  export declare const failureKey: (error: unknown) => string;
17
19
  /**
@@ -14,6 +14,12 @@ export const isCommanderFailure = (value) => {
14
14
  const { code, exitCode } = (value ?? {});
15
15
  return (value instanceof Error && typeof code === "string" && code.startsWith("commander.") && typeof exitCode === "number");
16
16
  };
17
+ const USAGE_REASONS = {
18
+ "commander.unknownCommand": "usage.unknown-command",
19
+ "commander.unknownOption": "usage.unknown-option",
20
+ };
21
+ /** The reason of a commander usage error a caller matches instead of commander's English, when it has one. */
22
+ export const usageReason = (code) => USAGE_REASONS[code];
17
23
  /** What failed, never what it said: a messenger's refusal can quote the message back. */
18
24
  export const failureKey = (error) => isCliFailure(error) ? error.code : error instanceof Error ? error.name : "error";
19
25
  const SQLITE_CORRUPT = 11;
@@ -41,6 +41,7 @@ const SIGN_IN = [
41
41
  ["sign-in.secret-without-id", "configuration_error", "an OAuth client secret is set without its client id"],
42
42
  validation("account-remove.no-choice", "account remove needs --keep-data or --delete-data, one of them"),
43
43
  ["account-remove.unknown-profile", "not_found", "no profile by this name on this computer"],
44
+ ["profile.unknown", "not_found", "no profile by this name on this computer; details.profiles lists the ones here"],
44
45
  ["account-remove.busy", "conflict", "a serve or a sync runs for this profile; stop it first"],
45
46
  ["account-remove.unconfirmed", "confirmation_required", "removing an account asks first; add --yes"],
46
47
  ["account-remove.path-outside", "configuration_error", "the tool named a path outside its own folders"],
@@ -60,7 +61,21 @@ const PROVIDER_API = [
60
61
  validation("file.not-a-file", "the path names a folder or another thing that is not a file"),
61
62
  ["file.denied", "permission_error", "the file cannot be opened: permission denied"],
62
63
  ];
64
+ /** The read-only SFTP client (`./sftp`). */
65
+ const SFTP = [
66
+ ["sftp.host-key-missing", "configuration_error", "no host key is pinned for the SFTP server"],
67
+ ["sftp.host-key-mismatch", "authentication_error", "the SFTP server's host key is not the pinned one"],
68
+ ["sftp.auth-missing", "configuration_error", "an SFTP connection needs a password or a private key"],
69
+ ["sftp.key-invalid", "configuration_error", "the SFTP private key or its passphrase cannot be read"],
70
+ ["sftp.library-missing", "configuration_error", "SFTP needs the ssh2 package in the CLI's dependencies"],
71
+ ["sftp.timeout", "timeout", "the SFTP server did not answer in time"],
72
+ validation("sftp.too-large", "the file is larger than the read's byte limit"),
73
+ validation("sftp.closed", "the SFTP connection was closed before the operation"),
74
+ ];
63
75
  const OTHERS = [
76
+ validation("doctor.report-exists", "the report's file exists; a problem report never overwrites a file"),
77
+ validation("usage.unknown-command", "no command by this name; the CLI's help lists them"),
78
+ validation("usage.unknown-option", "the command takes no option by this name; its help lists them"),
64
79
  ["query.time-limit", "timeout", "the search took longer than its time limit; the query itself is valid"],
65
80
  ["enrichment.owner-only", "permission_error", "only the owner turns enrichment on, not an agent"],
66
81
  ["search-harder.owner-only", "permission_error", "only the owner allows search all --harder, not an agent"],
@@ -251,6 +266,7 @@ const OTHERS = [
251
266
  "another program deleted or replaced the store's journal file while it was open; store recover says what to do",
252
267
  ],
253
268
  validation("store.file-damaged", "the named store file is damaged or not a database"),
269
+ ["store.unopenable", "configuration_error", "the store file cannot be opened at its path; details.path names it"],
254
270
  [
255
271
  "store.unreadable",
256
272
  "configuration_error",
@@ -375,6 +391,7 @@ const OTHERS = [
375
391
  validation("crm.not-reported", "the CRM did not list users or departments; what they would say is unknown, nothing withdrawn"),
376
392
  validation("crm.reference-unknown", "a CRM row names a contact, company or user the store does not hold; that link was not made"),
377
393
  validation("crm.pending-dropped", "relationships waited too long for an end that never came; they were dropped"),
394
+ validation("crm.activities-failed", "the activities and tasks could not be read; the deals and leads were synced"),
378
395
  validation("crm.email-ambiguous", "a CRM contact's email belongs to more than one person; the owner decides"),
379
396
  validation("crm.own-unknown", "no own company of the CRM account is stored, so its users are no one's employees yet"),
380
397
  validation("relationship.reference-unknown", "a reported relationship names something the store does not hold"),
@@ -571,7 +588,7 @@ export const INPUT_FIELD_REASONS = defineReasons([
571
588
  export const REASONS = defineReasons([
572
589
  ...QUERY_REASONS,
573
590
  ...INPUT_FIELD_REASONS,
574
- ...[...QUERY, ...SIGN_IN, ...PROVIDER_API, ...OTHERS].map(([reason, code, message]) => ({
591
+ ...[...QUERY, ...SIGN_IN, ...PROVIDER_API, ...SFTP, ...OTHERS].map(([reason, code, message]) => ({
575
592
  reason,
576
593
  code,
577
594
  message,
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ export { CATALOG_KINDS, type CatalogKind, CONTRACT_KINDS, CONTRACT_STATUSES, typ
3
3
  export { bareCheck, type CheckWords, checkWords } from "./domain/checks.js";
4
4
  export type { CounterField, CounterObservation, CounterObservations, CounterState } from "./domain/counters.js";
5
5
  export { COUNTER_FIELDS, counterValue, observedCounters } from "./domain/counters.js";
6
- export { CRM_KINDS, type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmRecords, type CrmScope, type CrmScopeSetting, type CrmStage, type CrmUser, type CrmValue, isCrmUserId, isItemKind, normalCrmUserId, } from "./domain/crm.js";
6
+ export { CRM_ACTIVITY_KINDS, CRM_KINDS, type CrmActivity, type CrmActivityKind, type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmRecords, type CrmScope, type CrmScopeSetting, type CrmStage, type CrmUser, type CrmValue, isCrmUserId, isItemKind, normalCrmUserId, } from "./domain/crm.js";
7
7
  export { DEAL_KINDS, DEAL_ROLES, DEAL_STATUSES, type DealKind, type DealRole, type DealStatus, STAGE_OUTCOMES, type StageOutcome, } from "./domain/deals.js";
8
8
  export { displayName, type NameFallbacks, nameKey } from "./domain/display-names.js";
9
9
  export { FINANCE_REVIEWS, type FinanceReview, INVOICE_DIRECTIONS, INVOICE_STATUSES, type InvoiceDirection, type InvoiceStatus, MONEY_DIRECTIONS, type MoneyDirection, } from "./domain/finance.js";
@@ -16,6 +16,7 @@ export type { MessageLink, MessagePermalink } from "./domain/message-link.js";
16
16
  export type * from "./domain/models.js";
17
17
  export { CURRENCY_SCALES, currencyOf, formatDecimal, type Money, minorUnits, moneyLabel, moneyOf, signedMinorUnits, } from "./domain/money.js";
18
18
  export { ORDER_PURPOSES, ORDER_STATUSES, type OrderPurpose, type OrderStatus, } from "./domain/orders.js";
19
+ export { e164Of, PHONE_COUNTRIES, type PhoneCountry } from "./domain/phones.js";
19
20
  export { countedPoll } from "./domain/polls.js";
20
21
  export { ADDED_ACCOUNT, ADDED_PROVIDER, CRM_OPENS, FOLDER_PROVIDERS, holdsKind, isFolderProvider, isKind, KINDS, type Kind, kindIn, kindOf, kindsIn, PROVIDERS, type ProviderEntry, providerNamed, providers, UNKNOWN_PROVIDER, useProviders, } from "./domain/providers.js";
21
22
  export type { RankingGraphEvidence, RankingGraphLink } from "./domain/rankings-graph.js";
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ export { isNoReplyAddress, isRoleAddress, ROLE_ADDRESS_WORDS } from "./domain/ad
2
2
  export { CATALOG_KINDS, CONTRACT_KINDS, CONTRACT_STATUSES, intervalOf, intervalText, ORDER_DIRECTIONS, PERIOD_UNITS, SUBSCRIPTION_STATUSES, TRANSACTION_STATUSES, WALLET_KINDS, } from "./domain/business.js";
3
3
  export { bareCheck, checkWords } from "./domain/checks.js";
4
4
  export { COUNTER_FIELDS, counterValue, observedCounters } from "./domain/counters.js";
5
- export { CRM_KINDS, isCrmUserId, isItemKind, normalCrmUserId, } from "./domain/crm.js";
5
+ export { CRM_ACTIVITY_KINDS, CRM_KINDS, isCrmUserId, isItemKind, normalCrmUserId, } from "./domain/crm.js";
6
6
  export { DEAL_KINDS, DEAL_ROLES, DEAL_STATUSES, STAGE_OUTCOMES, } from "./domain/deals.js";
7
7
  export { displayName, nameKey } from "./domain/display-names.js";
8
8
  export { FINANCE_REVIEWS, INVOICE_DIRECTIONS, INVOICE_STATUSES, MONEY_DIRECTIONS, } from "./domain/finance.js";
@@ -13,6 +13,7 @@ export { parseMarkdown } from "./domain/markdown.js";
13
13
  export { parseMarkdownSpans } from "./domain/markdown-spans.js";
14
14
  export { CURRENCY_SCALES, currencyOf, formatDecimal, minorUnits, moneyLabel, moneyOf, signedMinorUnits, } from "./domain/money.js";
15
15
  export { ORDER_PURPOSES, ORDER_STATUSES, } from "./domain/orders.js";
16
+ export { e164Of, PHONE_COUNTRIES } from "./domain/phones.js";
16
17
  export { countedPoll } from "./domain/polls.js";
17
18
  export { ADDED_ACCOUNT, ADDED_PROVIDER, CRM_OPENS, FOLDER_PROVIDERS, holdsKind, isFolderProvider, isKind, KINDS, kindIn, kindOf, kindsIn, PROVIDERS, providerNamed, providers, UNKNOWN_PROVIDER, useProviders, } from "./domain/providers.js";
18
19
  export { rankingOptions } from "./domain/rankings-options.js";
@@ -2,6 +2,7 @@ export { ARGV_LOG, argvLogSetup } from "./argv-log.js";
2
2
  export { type ContractCase, type ContractOptions, contractCases, OPTIONAL_METHODS } from "./contract.js";
3
3
  export { type FakeAdapter, fakeAdapter } from "./fake.js";
4
4
  export { type McpStdio, type McpStdioStreams, type McpToolResult, mcpOverStdio } from "./mcp-stdio.js";
5
+ export { ownCatalogue } from "./own-catalogue.js";
5
6
  export { neverAnswers, type RunScopeCase, type RunScopeOptions, runScopeCases } from "./run-scope.js";
6
7
  export { type SearchRecipes, searchRecipes, seedSearchRecipes } from "./search-recipes.js";
7
8
  export { BUSY_PAGE, contractSeed, digitIds, type IdKind, type IdMaker, type Seed, wordIds } from "./seed.js";
package/dist/kit/index.js CHANGED
@@ -2,6 +2,7 @@ export { ARGV_LOG, argvLogSetup } from "./argv-log.js";
2
2
  export { contractCases, OPTIONAL_METHODS } from "./contract.js";
3
3
  export { fakeAdapter } from "./fake.js";
4
4
  export { mcpOverStdio } from "./mcp-stdio.js";
5
+ export { ownCatalogue } from "./own-catalogue.js";
5
6
  export { neverAnswers, runScopeCases } from "./run-scope.js";
6
7
  export { searchRecipes, seedSearchRecipes } from "./search-recipes.js";
7
8
  export { BUSY_PAGE, contractSeed, digitIds, wordIds } from "./seed.js";
@@ -0,0 +1,7 @@
1
+ import type { Command } from "commander";
2
+ import { type CatalogueOptions } from "../mcp/agent.js";
3
+ /**
4
+ * The MCP catalogue of a CLI's own commands, by path, as `read` or `write`: what cli-core mounted is left out, since
5
+ * cli-core pins it. A CLI's contract test pins this and the few shared commands it changes on purpose.
6
+ */
7
+ export declare const ownCatalogue: (program: Command, options?: CatalogueOptions) => Record<string, "read" | "write">;
@@ -0,0 +1,21 @@
1
+ import { describeProgram, hasSharedContract } from "@wirecat/cli-base/commands";
2
+ import { toolsFromCommands } from "../mcp/agent.js";
3
+ const sharedPaths = (command, parents = [], into = new Set()) => {
4
+ for (const child of command.commands) {
5
+ const path = [...parents, child.name()];
6
+ if (hasSharedContract(child))
7
+ into.add(path.join(" "));
8
+ sharedPaths(child, path, into);
9
+ }
10
+ return into;
11
+ };
12
+ /**
13
+ * The MCP catalogue of a CLI's own commands, by path, as `read` or `write`: what cli-core mounted is left out, since
14
+ * cli-core pins it. A CLI's contract test pins this and the few shared commands it changes on purpose.
15
+ */
16
+ export const ownCatalogue = (program, options = {}) => {
17
+ const shared = sharedPaths(program);
18
+ return Object.fromEntries(toolsFromCommands(describeProgram(program), options)
19
+ .filter((tool) => !shared.has([...(options.root ?? []), tool.command].join(" ")))
20
+ .map((tool) => [tool.command, tool.writes ? "write" : "read"]));
21
+ };
@@ -1,6 +1,6 @@
1
1
  export { type Authorization, type AuthorizeOptions, authorize } from "./authorize.js";
2
2
  export { type ClientFileOptions, readClientFile } from "./client-file.js";
3
3
  export { type SignInOptions, type TokenKeeper, type TokenKeeperOptions, type TokensOptions, tokenKeeper, } from "./keeper.js";
4
- export type { AppSource, ExchangeContext, OAuthClient, OAuthProvider, RequestContext, TokenSet } from "./provider.js";
4
+ export { type AppSource, type ExchangeContext, googleProvider, type OAuthClient, type OAuthProvider, type RequestContext, type TokenSet, } from "./provider.js";
5
5
  export { requestTokens, revokeToken, TOKEN_LOG_ALLOW, TOKEN_LOG_EVENT } from "./requests.js";
6
- export { type CredentialStorageOptions, credentialStorage, driveSessionCodec, type EncodeInput, oauthAccount, type StoredTokens, standardCodec, type TokenCodec, type TokenStorage, zoomTokenCodec, } from "./storage.js";
6
+ export { type CredentialStorageOptions, credentialStorage, driveSessionCodec, type EncodeInput, googleTokenCodec, oauthAccount, type StoredTokens, standardCodec, type TokenCodec, type TokenStorage, zoomTokenCodec, } from "./storage.js";
@@ -1,5 +1,6 @@
1
1
  export { authorize } from "./authorize.js";
2
2
  export { readClientFile } from "./client-file.js";
3
3
  export { tokenKeeper, } from "./keeper.js";
4
+ export { googleProvider, } from "./provider.js";
4
5
  export { requestTokens, revokeToken, TOKEN_LOG_ALLOW, TOKEN_LOG_EVENT } from "./requests.js";
5
- export { credentialStorage, driveSessionCodec, oauthAccount, standardCodec, zoomTokenCodec, } from "./storage.js";
6
+ export { credentialStorage, driveSessionCodec, googleTokenCodec, oauthAccount, standardCodec, zoomTokenCodec, } from "./storage.js";
@@ -59,3 +59,7 @@ export interface OAuthProvider {
59
59
  exchange?: (params: Record<string, string>, context: ExchangeContext) => Promise<TokenSet>;
60
60
  revoke?: (tokens: TokenSet, context: RequestContext) => Promise<void>;
61
61
  }
62
+ /** Google's endpoints for a Desktop client; `loginHint` preselects the account the browser offers. */
63
+ export declare const googleProvider: (client: OAuthClient, { loginHint }?: {
64
+ loginHint?: string;
65
+ }) => OAuthProvider;
@@ -1 +1,16 @@
1
- export {};
1
+ /** Google's endpoints for a Desktop client; `loginHint` preselects the account the browser offers. */
2
+ export const googleProvider = (client, { loginHint } = {}) => ({
3
+ id: "google",
4
+ name: "Google",
5
+ authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth",
6
+ tokenUrl: "https://oauth2.googleapis.com/token",
7
+ revokeUrl: "https://oauth2.googleapis.com/revoke",
8
+ client,
9
+ redirect: { kind: "loopback" },
10
+ // Without offline access Google returns no refresh token; without consent it does not return one again.
11
+ authorizeParams: {
12
+ access_type: "offline",
13
+ prompt: "select_account consent",
14
+ ...(loginHint ? { login_hint: loginHint } : {}),
15
+ },
16
+ });
@@ -41,6 +41,11 @@ export declare const standardCodec: (providerId: string) => TokenCodec;
41
41
  * refresh_token, expiry_date, scope, token_type, …}}`. A write keeps every field it does not own.
42
42
  */
43
43
  export declare const driveSessionCodec: TokenCodec;
44
+ /**
45
+ * Google's entry: the standard one plus the client secret, which a Google Desktop client needs to refresh while its
46
+ * client file is read only at sign-in. A client without a secret drops the one the profile signed in with before.
47
+ */
48
+ export declare const googleTokenCodec: TokenCodec;
44
49
  /** zm's entry as zoom-cli writes it today: `{accessToken, refreshToken, expiresAt, scopes}`, all four required. */
45
50
  export declare const zoomTokenCodec: TokenCodec;
46
51
  export interface CredentialStorageOptions {
@@ -122,6 +122,26 @@ export const driveSessionCodec = {
122
122
  return JSON.stringify(session);
123
123
  },
124
124
  };
125
+ const googleStandard = standardCodec("google");
126
+ /**
127
+ * Google's entry: the standard one plus the client secret, which a Google Desktop client needs to refresh while its
128
+ * client file is read only at sign-in. A client without a secret drops the one the profile signed in with before.
129
+ */
130
+ export const googleTokenCodec = {
131
+ decode: (raw) => {
132
+ const stored = googleStandard.decode(raw);
133
+ const clientSecret = text(parse(raw).clientSecret);
134
+ return clientSecret ? { ...stored, client: { clientId: stored.client?.clientId ?? "", clientSecret } } : stored;
135
+ },
136
+ encode: (input) => {
137
+ const entry = parse(googleStandard.encode(input));
138
+ if (input.client.clientSecret)
139
+ entry.clientSecret = input.client.clientSecret;
140
+ else
141
+ delete entry.clientSecret;
142
+ return JSON.stringify(entry);
143
+ },
144
+ };
125
145
  /** zm's entry as zoom-cli writes it today: `{accessToken, refreshToken, expiresAt, scopes}`, all four required. */
126
146
  export const zoomTokenCodec = {
127
147
  decode: (raw) => {
@@ -33,7 +33,7 @@ export declare const errorDetailOf: (error: unknown, response?: RequestEvent) =>
33
33
  export declare const framesOf: (error: unknown, limit?: number) => string[];
34
34
  /**
35
35
  * Where a request went, with nothing in it that names a person or opens an account: no query string, no user, an id
36
- * or a token in the path as `:id` / `:token`. The host stays — which service refused is the point.
36
+ * or a token in the path as `:id` / `:token`, a webhook's secret after `/rest/<user id>/` among them. The host stays — which service refused is the point.
37
37
  */
38
38
  export declare const endpointTemplate: (raw: string) => string;
39
39
  /** A phone number as people type it with its country code, and one written as digits only without the "+". */
@@ -94,16 +94,19 @@ const fileOf = (path) => {
94
94
  };
95
95
  /**
96
96
  * Where a request went, with nothing in it that names a person or opens an account: no query string, no user, an id
97
- * or a token in the path as `:id` / `:token`. The host stays — which service refused is the point.
97
+ * or a token in the path as `:id` / `:token`, a webhook's secret after `/rest/<user id>/` among them. The host stays — which service refused is the point.
98
98
  */
99
99
  export const endpointTemplate = (raw) => {
100
100
  const trimmed = raw.trim().split(/[?#]/)[0] ?? "";
101
101
  const origin = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]*@)?([^/]*)/i.exec(trimmed);
102
102
  const path = origin ? trimmed.slice(origin[0].length) : trimmed;
103
103
  const scheme = origin ? `${trimmed.slice(0, trimmed.indexOf("://"))}://${origin[1]}` : "";
104
- const segments = path.split("/").map((segment) => {
104
+ const parts = path.split("/");
105
+ const segments = parts.map((segment, at) => {
105
106
  if (segment === "" || /^[:{].+/.test(segment))
106
107
  return segment;
108
+ if (at >= 2 && parts[at - 2] === "rest" && /^\d+$/.test(parts[at - 1] ?? ""))
109
+ return ":token";
107
110
  if (/^bot\d+:/.test(segment) || /^\d{6,}:[\w-]{20,}$/.test(segment))
108
111
  return ":token";
109
112
  if (/^-?\d+$/.test(segment) || /^[0-9a-f-]{16,}$/i.test(segment))
@@ -37,7 +37,7 @@ export interface RequestEvent {
37
37
  * requests when it has any, so one operation over three frames is three requests, never four.
38
38
  */
39
39
  level?: "operation" | "wire";
40
- transport?: "http" | "mtproto" | "max-ws" | "wa-engine";
40
+ transport?: "http" | "mtproto" | "max-ws" | "wa-engine" | "sftp";
41
41
  /** 1 for the first try, 2 and up for a retry of the same call. */
42
42
  attempt?: number;
43
43
  /** How long the client waited before this attempt: a flood wait or a `Retry-After`. */
@@ -7,9 +7,10 @@ export declare const holdsCredential: (text: string) => boolean;
7
7
  */
8
8
  export declare const looksRandom: (run: string) => boolean;
9
9
  /**
10
- * Text with each secret inside it replaced by `mark` and the words around it kept: a token of a known vendor format,
11
- * a private key, a `Bearer`/`Basic` credential, the value of a secret-named `name=value`, `name: value`, `name => value`
12
- * or `name value`, a random-looking string of 20 or more printable characters (`looksRandom`), and a run of 20 or more
13
- * lower-case hex characters with a Shannon entropy of 3 bits per character or more.
10
+ * Text with each secret inside it replaced by `mark` and the words around it kept: a webhook secret in a URL path, a
11
+ * token of a known vendor format, a private key, a `Bearer`/`Basic` credential, the value of a secret-named
12
+ * `name=value`, `name: value`, `name => value` or `name value`, a random-looking string of 20 or more printable
13
+ * characters (`looksRandom`), and a run of 20 or more lower-case hex characters with a Shannon entropy of 3 bits per
14
+ * character or more.
14
15
  */
15
16
  export declare const withoutSecrets: (text: string, mark?: string) => string;
@@ -49,6 +49,8 @@ const KNOWN_TOKENS = new RegExp(`${[
49
49
  ]
50
50
  .map((pattern) => `${START}${pattern}${END}`)
51
51
  .join("|")}|(?<!\\d)\\d{8,10}:[A-Za-z0-9_-]{35}${END}`, "g");
52
+ // A Bitrix24 inbound webhook carries its secret as a path segment: `/rest/<user id>/<secret>/<method>`.
53
+ const WEBHOOK_PATH = /(\/rest\/\d+\/)[^/\s?#"']+/g;
52
54
  const PRIVATE_KEY = /-----BEGIN[A-Z ]* PRIVATE KEY-----[\s\S]*?(?:-----END[A-Z ]* PRIVATE KEY-----|$)/g;
53
55
  // Capitalised, as in a header, and not followed by a plain word: "the Basic plan" is somebody's words.
54
56
  const SCHEME = /(?<![A-Za-z])(Bearer|Basic)(\s+)(?![A-Z]?[a-z]+(?![A-Za-z0-9]))[A-Za-z0-9._~+/=-]{8,}/g;
@@ -89,12 +91,14 @@ const entropy = (text) => {
89
91
  return bits;
90
92
  };
91
93
  /**
92
- * Text with each secret inside it replaced by `mark` and the words around it kept: a token of a known vendor format,
93
- * a private key, a `Bearer`/`Basic` credential, the value of a secret-named `name=value`, `name: value`, `name => value`
94
- * or `name value`, a random-looking string of 20 or more printable characters (`looksRandom`), and a run of 20 or more
95
- * lower-case hex characters with a Shannon entropy of 3 bits per character or more.
94
+ * Text with each secret inside it replaced by `mark` and the words around it kept: a webhook secret in a URL path, a
95
+ * token of a known vendor format, a private key, a `Bearer`/`Basic` credential, the value of a secret-named
96
+ * `name=value`, `name: value`, `name => value` or `name value`, a random-looking string of 20 or more printable
97
+ * characters (`looksRandom`), and a run of 20 or more lower-case hex characters with a Shannon entropy of 3 bits per
98
+ * character or more.
96
99
  */
97
100
  export const withoutSecrets = (text, mark = "[redacted]") => text
101
+ .replace(WEBHOOK_PATH, `$1${mark}`)
98
102
  .replace(PRIVATE_KEY, mark)
99
103
  .replace(KNOWN_TOKENS, mark)
100
104
  .replace(SCHEME, `$1$2${mark}`)
@@ -8,6 +8,8 @@ export type PermissionKey = string;
8
8
  export declare const skipFlagFor: (key: string) => "--allow-dangerous" | "--yes";
9
9
  /** Only what cannot be undone asks; the tool is meant to work without questions (owner, NEED-460). */
10
10
  export declare const DEFAULT_PERMISSIONS: Readonly<Record<PermissionKey, Level>>;
11
+ /** Commands under a housekeeping word, or store maintenance, that still have a key of their own: their path. */
12
+ export declare const KEYED_UNDER_HOUSEKEEPING: ReadonlySet<PermissionKey>;
11
13
  /** Lets an MCP server offer the commands that change what a later run may do (`grantsAuthority`). */
12
14
  export declare const AUTHORITY_KEY: PermissionKey;
13
15
  /** Whether these levels let an agent run a command that changes what a later run may do; `ask` does, as for any write. */
@@ -28,6 +28,7 @@ export const DEFAULT_PERMISSIONS = {
28
28
  "store.clear": "ask",
29
29
  "store.decrypt": "ask",
30
30
  "store.copies.delete": "ask",
31
+ "store.recover.run": "ask",
31
32
  "server.start": "ask",
32
33
  "server.stop": "ask",
33
34
  "server.restart": "ask",
@@ -42,7 +43,7 @@ export const DEFAULT_PERMISSIONS = {
42
43
  "doctor.reports.create": "ask",
43
44
  };
44
45
  /** Commands under a housekeeping word, or store maintenance, that still have a key of their own: their path. */
45
- const KEYED_UNDER_HOUSEKEEPING = new Set(Object.keys(DEFAULT_PERMISSIONS).filter((key) => /^(store|server|models|images|schedule|doctor)\./.test(key)));
46
+ export const KEYED_UNDER_HOUSEKEEPING = new Set(Object.keys(DEFAULT_PERMISSIONS).filter((key) => /^(store|server|models|images|schedule|doctor)\./.test(key)));
46
47
  /** Lets an MCP server offer the commands that change what a later run may do (`grantsAuthority`). */
47
48
  export const AUTHORITY_KEY = "mcp.authority";
48
49
  /** Whether these levels let an agent run a command that changes what a later run may do; `ask` does, as for any write. */
@@ -350,6 +351,8 @@ export const readKeysForCommand = (path) => {
350
351
  // Checked as `messages` before they had keys of their own: `deny messages` keeps stopping them.
351
352
  if (path[0] === "store" && ["reset", "clear", "decrypt"].includes(path[1] ?? ""))
352
353
  return [key, "messages"];
354
+ if (key === "store.recover.run")
355
+ return [key, "messages"];
353
356
  // A search shows what people wrote, so `deny messages` reaches every leaf that reads messages.
354
357
  if (path[0] === "search") {
355
358
  if (path[1] === "notes")
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
- error?: undefined;
18
17
  chatId: string;
19
18
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
20
19
  algorithm: string;
21
20
  fetchedAt: string | null;
22
21
  source: string;
22
+ error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -49,7 +49,7 @@ const filtersBeside = (text) => {
49
49
  * What a deal or a lead is found by: plain words or phrases, all of them, or any with OR. Anything else is refused,
50
50
  * so `search all` skips deals with the reason instead of matching a field they do not have.
51
51
  */
52
- export const titleWords = (text, refused = "deals and leads are found by the words of their title, company and contacts only") => {
52
+ export const titleWords = (text, refused = "deals and leads are found by the words of their title, company, contacts and activities only") => {
53
53
  const { root } = parseLucene(text, SEARCH_QUERY);
54
54
  const clauses = root.kind === "boolean" ? root.clauses : [{ node: root, occur: "must" }];
55
55
  const words = clauses.map(({ node, occur }) => occur !== "must_not" &&
@@ -0,0 +1 @@
1
+ export { type HostKey, openSftp, SFTP_CONNECT_TIMEOUT_MS, SFTP_OPERATION_TIMEOUT_MS, SFTP_RETRY, type SftpAuth, type SftpClient, type SftpEntry, type SftpKind, type SftpOptions, type SftpReadOptions, type SftpTarget, sftpHostKey, } from "./session.js";
@@ -0,0 +1 @@
1
+ export { openSftp, SFTP_CONNECT_TIMEOUT_MS, SFTP_OPERATION_TIMEOUT_MS, SFTP_RETRY, sftpHostKey, } from "./session.js";
@@ -0,0 +1,61 @@
1
+ import type { Duplex } from "node:stream";
2
+ import { type RetryConfig, type SleepLike } from "@wirecat/cli-base";
3
+ import type { RequestEvent } from "../runs/events.js";
4
+ import { type HostKey, type SftpEntry } from "./ssh2.js";
5
+ export type SftpAuth = {
6
+ password: string;
7
+ } | {
8
+ privateKey: string | Uint8Array;
9
+ passphrase?: string;
10
+ };
11
+ export interface SftpTarget {
12
+ host: string;
13
+ /** 22 when not given. */
14
+ port?: number;
15
+ /** Seams for a test or a tunnel: a stream already connected to the server, one per connection attempt. */
16
+ socket?: () => Duplex | Promise<Duplex>;
17
+ /** The run's signal: aborting it stops every operation and closes the connection. */
18
+ signal?: AbortSignal;
19
+ /** The run's events (WC-LIFE-17); the current command's run when not given. */
20
+ events?: (event: RequestEvent) => void;
21
+ /** How long a connection may take up to an open SFTP channel. */
22
+ connectTimeoutMs?: number;
23
+ retry?: RetryConfig;
24
+ sleep?: SleepLike;
25
+ random?: () => number;
26
+ }
27
+ export interface SftpOptions extends SftpTarget {
28
+ username: string;
29
+ auth: SftpAuth;
30
+ /** The host key fingerprint the owner confirmed, `SHA256:…` as `sftpHostKey` or `ssh-keygen -lf` print it. */
31
+ hostKey: string;
32
+ /** How long one list or stat may take, and how long a read may go without receiving a byte. */
33
+ operationTimeoutMs?: number;
34
+ }
35
+ export interface SftpReadOptions {
36
+ /** A larger file is refused before its first byte is read, and a file that grows past it while read is too. */
37
+ maxBytes: number;
38
+ }
39
+ export interface SftpClient {
40
+ /** The entries of a folder, without `.` and `..`. */
41
+ list(path: string): Promise<SftpEntry[]>;
42
+ stat(path: string): Promise<SftpEntry>;
43
+ readFile(path: string, options: SftpReadOptions): Promise<Uint8Array>;
44
+ close(): Promise<void>;
45
+ }
46
+ export type { HostKey, SftpEntry, SftpKind } from "./ssh2.js";
47
+ export declare const SFTP_CONNECT_TIMEOUT_MS = 20000;
48
+ export declare const SFTP_OPERATION_TIMEOUT_MS = 30000;
49
+ /** Every operation only reads, so a transient failure is tried again: three attempts in all. */
50
+ export declare const SFTP_RETRY: RetryConfig;
51
+ /**
52
+ * The server's host key, for a sign-in to show the owner before the fingerprint is pinned: the connection stops at
53
+ * the key exchange and sends no credential.
54
+ */
55
+ export declare const sftpHostKey: (target: SftpTarget) => Promise<HostKey>;
56
+ /**
57
+ * A read-only SFTP connection: list, stat and read, nothing that writes. The host key must match the pinned
58
+ * fingerprint before a credential is sent. Each operation is a request in the run's events (host and operation,
59
+ * never a path or file content) and is tried again on a transient failure over a fresh connection.
60
+ */
61
+ export declare const openSftp: (input: SftpOptions) => Promise<SftpClient>;