@wirecat/cli-core 1.3.0 → 2.0.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 (134) hide show
  1. package/CHANGELOG.md +145 -0
  2. package/dist/attachments/container.d.ts +1 -1
  3. package/dist/attachments/container.js +16 -7
  4. package/dist/attachments/limits.d.ts +10 -0
  5. package/dist/attachments/limits.js +30 -1
  6. package/dist/attachments/transfer.js +2 -2
  7. package/dist/cli/app-doctor-command.d.ts +61 -7
  8. package/dist/cli/app-doctor-command.js +24 -11
  9. package/dist/cli/documents/file-edit.js +6 -6
  10. package/dist/cli/documents/library.js +4 -2
  11. package/dist/cli/index.d.ts +6 -5
  12. package/dist/cli/index.js +2 -1
  13. package/dist/cli/messenger/context.d.ts +16 -0
  14. package/dist/cli/messenger/doctor-command.js +16 -1
  15. package/dist/cli/messenger/flooded.js +9 -1
  16. package/dist/cli/messenger/serve-relay.d.ts +2 -0
  17. package/dist/cli/oauth-session.d.ts +3 -2
  18. package/dist/cli/oauth-session.js +19 -3
  19. package/dist/cli/profile-store.d.ts +24 -10
  20. package/dist/cli/profile-store.js +43 -28
  21. package/dist/cli/shared-command-exports.d.ts +1 -1
  22. package/dist/cli/token-session.d.ts +21 -2
  23. package/dist/cli/token-session.js +27 -11
  24. package/dist/crm/cli/files.js +7 -7
  25. package/dist/documents.d.ts +1 -1
  26. package/dist/documents.js +1 -1
  27. package/dist/domain/person-kinds.d.ts +7 -3
  28. package/dist/domain/person-kinds.js +7 -3
  29. package/dist/domain/ref-summaries.js +1 -0
  30. package/dist/domain/references.d.ts +3 -2
  31. package/dist/domain/references.js +19 -10
  32. package/dist/entities/deal.d.ts +2 -2
  33. package/dist/entities/deal.js +1 -1
  34. package/dist/entities/fact.d.ts +2 -2
  35. package/dist/entities/fact.js +1 -1
  36. package/dist/entities/fields.d.ts +1 -1
  37. package/dist/entities/fields.js +1 -1
  38. package/dist/entities/index.d.ts +15 -15
  39. package/dist/entities/mail-findings.d.ts +2 -2
  40. package/dist/entities/mail-findings.js +1 -1
  41. package/dist/entities/meeting-findings.d.ts +2 -2
  42. package/dist/entities/meeting-findings.js +1 -1
  43. package/dist/entities/memory.d.ts +1 -1
  44. package/dist/entities/task-results.d.ts +5 -5
  45. package/dist/entities/task-results.js +1 -1
  46. package/dist/entities/task.d.ts +1 -1
  47. package/dist/entities/task.js +1 -1
  48. package/dist/errors/reasons.js +2 -1
  49. package/dist/fetch/page.js +1 -2
  50. package/dist/mail/headers.d.ts +4 -3
  51. package/dist/mail/headers.js +21 -3
  52. package/dist/mail/sort-rules.d.ts +13 -6
  53. package/dist/mail/sort-rules.js +20 -16
  54. package/dist/mail/sync.js +2 -0
  55. package/dist/mcp/tools/attachments.js +1 -1
  56. package/dist/office/zip.js +1 -1
  57. package/dist/ports/messenger.d.ts +31 -1
  58. package/dist/services/archive.js +61 -11
  59. package/dist/services/attachments.js +4 -4
  60. package/dist/services/documents/file-text.js +2 -2
  61. package/dist/services/metadata.d.ts +1 -1
  62. package/dist/services/proposals/kinds/shared.d.ts +1 -1
  63. package/dist/services/proposals/kinds/shared.js +2 -2
  64. package/dist/services/proposals/kinds/task-close.js +1 -1
  65. package/dist/store/areas.d.ts +2 -0
  66. package/dist/store/areas.js +1 -0
  67. package/dist/store/decisions.d.ts +1 -1
  68. package/dist/store/decisions.js +4 -4
  69. package/dist/store/evidence-findings.d.ts +2 -2
  70. package/dist/store/index.d.ts +3 -1
  71. package/dist/store/index.js +2 -1
  72. package/dist/store/mail-findings.d.ts +2 -2
  73. package/dist/store/meeting-findings.d.ts +2 -2
  74. package/dist/store/people.d.ts +4 -4
  75. package/dist/store/people.js +2 -1
  76. package/dist/store/project-transfer/manifest.js +3 -3
  77. package/dist/store/public.d.ts +1 -1
  78. package/dist/store/public.js +1 -1
  79. package/dist/store/sqlite/actors.d.ts +1 -1
  80. package/dist/store/sqlite/actors.js +6 -6
  81. package/dist/store/sqlite/agent-actions.js +2 -2
  82. package/dist/store/sqlite/agent-links.js +1 -1
  83. package/dist/store/sqlite/bot-sends.d.ts +19 -0
  84. package/dist/store/sqlite/bot-sends.js +36 -0
  85. package/dist/store/sqlite/business-contracts.js +1 -1
  86. package/dist/store/sqlite/deals.js +1 -1
  87. package/dist/store/sqlite/document-transfer/plan.js +1 -1
  88. package/dist/store/sqlite/document-transfer/snapshot.js +1 -1
  89. package/dist/store/sqlite/email-index.d.ts +11 -2
  90. package/dist/store/sqlite/email-index.js +56 -5
  91. package/dist/store/sqlite/email-types.d.ts +15 -3
  92. package/dist/store/sqlite/email-types.js +32 -1
  93. package/dist/store/sqlite/emails.d.ts +2 -1
  94. package/dist/store/sqlite/emails.js +6 -1
  95. package/dist/store/sqlite/entity-types.d.ts +1 -1
  96. package/dist/store/sqlite/entity-types.js +1 -1
  97. package/dist/store/sqlite/evidence-findings.js +1 -1
  98. package/dist/store/sqlite/facts.js +1 -1
  99. package/dist/store/sqlite/finance.js +2 -2
  100. package/dist/store/sqlite/knowledge.js +1 -0
  101. package/dist/store/sqlite/mail-findings.js +1 -1
  102. package/dist/store/sqlite/mail-sorting.d.ts +1 -1
  103. package/dist/store/sqlite/mail-sorting.js +96 -60
  104. package/dist/store/sqlite/mail-subscriptions.d.ts +70 -0
  105. package/dist/store/sqlite/mail-subscriptions.js +132 -0
  106. package/dist/store/sqlite/manifest.js +45 -0
  107. package/dist/store/sqlite/meeting-findings.js +1 -1
  108. package/dist/store/sqlite/memories.js +3 -3
  109. package/dist/store/sqlite/migrations.generated.js +80 -0
  110. package/dist/store/sqlite/money-transactions.js +1 -1
  111. package/dist/store/sqlite/note-index.d.ts +4 -1
  112. package/dist/store/sqlite/note-index.js +40 -17
  113. package/dist/store/sqlite/orders.js +1 -1
  114. package/dist/store/sqlite/payment-facts.js +2 -2
  115. package/dist/store/sqlite/products.js +1 -1
  116. package/dist/store/sqlite/project-transfer/sources.js +2 -2
  117. package/dist/store/sqlite/proposed-actions.js +3 -3
  118. package/dist/store/sqlite/record-projection.js +1 -1
  119. package/dist/store/sqlite/ref-summaries.js +2 -1
  120. package/dist/store/sqlite/relation-proposals.js +1 -1
  121. package/dist/store/sqlite/reviewed.d.ts +2 -2
  122. package/dist/store/sqlite/reviewed.js +1 -1
  123. package/dist/store/sqlite/sender-bots.d.ts +19 -4
  124. package/dist/store/sqlite/sender-bots.js +48 -4
  125. package/dist/store/sqlite/subscriptions.js +2 -2
  126. package/dist/store/sqlite/task-close.js +1 -1
  127. package/dist/store/sqlite/task-comments.js +1 -1
  128. package/dist/store/sqlite/things.js +1 -1
  129. package/dist/store/sqlite/transaction.d.ts +5 -0
  130. package/dist/store/sqlite/transaction.js +6 -1
  131. package/dist/store/sqlite/wallets.js +1 -1
  132. package/dist/store/sqlite/work-tasks.js +2 -2
  133. package/dist/tracker/tasks.js +4 -2
  134. package/package.json +7 -5
@@ -227,6 +227,22 @@ export interface Messenger extends ServiceMessenger {
227
227
  skill?: URL;
228
228
  /** What only this messenger can say about itself for `doctor`, read from disk — never a secret. */
229
229
  diagnose?: (command: Command, context: BaseContext) => Promise<Record<string, unknown>>;
230
+ /**
231
+ * What a person should do about this messenger's `diagnose` block, printed under doctor's answer and never in the
232
+ * JSON: a script reads the block itself. @experimental
233
+ */
234
+ doctorNotes?: (block: Record<string, unknown>) => readonly string[];
235
+ /**
236
+ * Checks `doctor --online` runs after the login, answered under `online.checks`. They only read. A failed one is a
237
+ * field, as a failed login is, never an exit code. @experimental
238
+ */
239
+ doctorOnline?: (command: Command) => Promise<readonly DoctorCheck[]>;
240
+ }
241
+ /** One check of `doctor --online` beyond the login. @experimental */
242
+ export interface DoctorCheck {
243
+ name: string;
244
+ ok: boolean;
245
+ detail: string;
230
246
  }
231
247
  /**
232
248
  * The messenger's connection — or, in a command serve runs for a client, serve's own, borrowed. Every connect
@@ -38,7 +38,8 @@ export const doctorCommand = (messenger) => {
38
38
  const { report, renderer, fixes = [] } = await diagnose(this, messenger);
39
39
  if (online && renderer) {
40
40
  const checked = await onlineCheck(this, messenger, rememberedOf(report));
41
- report.online = checked;
41
+ const checks = await extraChecks(this, messenger);
42
+ report.online = checks.length > 0 ? { ...checked, checks } : checked;
42
43
  report.login = { state: checked.ok ? "ok" : "failed" };
43
44
  const flood = report.flood;
44
45
  if (flood)
@@ -51,6 +52,10 @@ export const doctorCommand = (messenger) => {
51
52
  (renderer ?? output.renderer).note(`to make it private: ${fix}`);
52
53
  for (const line of damageNotes(report.store))
53
54
  (renderer ?? output.renderer).note(line);
55
+ const block = report[messenger.provider];
56
+ if (messenger.doctorNotes && block && typeof block === "object" && !("error" in block))
57
+ for (const line of messenger.doctorNotes(block))
58
+ (renderer ?? output.renderer).note(line);
54
59
  });
55
60
  command.addCommand(reportCommand(messenger));
56
61
  return command;
@@ -325,6 +330,16 @@ const onlineCheck = async (command, messenger, remembered) => {
325
330
  };
326
331
  }
327
332
  };
333
+ const extraChecks = async (command, messenger) => {
334
+ if (!messenger.doctorOnline)
335
+ return [];
336
+ try {
337
+ return await messenger.doctorOnline(command);
338
+ }
339
+ catch (error) {
340
+ return [{ name: messenger.provider, ok: false, detail: messageOf(error) }];
341
+ }
342
+ };
328
343
  const codeOf = (error) => {
329
344
  const code = error?.code;
330
345
  return typeof code === "string" ? code : "generic_failure";
@@ -4,7 +4,15 @@ import { throughWrapper } from "../../ports/messenger.js";
4
4
  import { providerErrorKey } from "../../runs/events.js";
5
5
  import { holdEnd } from "../../sends/flood.js";
6
6
  import { waitForTurn } from "../../sends/pace.js";
7
- const LONG_LIVED = new Set(["self", "newSendId", "close", "formatMarkdown", "formatHtml", "storedChats"]);
7
+ const LONG_LIVED = new Set([
8
+ "self",
9
+ "newSendId",
10
+ "close",
11
+ "formatMarkdown",
12
+ "formatHtml",
13
+ "storedChats",
14
+ "threadRootsIn",
15
+ ]);
8
16
  /** Neither held nor paced, as they listen for as long as the run does; what ends them is still remembered. */
9
17
  const LISTENING = new Set(["watch", "feed", "listen", "listenHistory"]);
10
18
  const BLOCKING = new Set(["frozen", "limited", "banned"]);
@@ -99,6 +99,8 @@ export declare const serveRelay: (command: Command, messenger: Messenger) => {
99
99
  permissionKey?: import("../permission-keys.js").PermissionKeyOf;
100
100
  skill?: URL;
101
101
  diagnose?: (command: Command, context: import("../context.js").BaseContext) => Promise<Record<string, unknown>>;
102
+ doctorNotes?: (block: Record<string, unknown>) => readonly string[];
103
+ doctorOnline?: (command: Command) => Promise<readonly import("./context.js").DoctorCheck[]>;
102
104
  services?: import("../../services/index.js").Override;
103
105
  connect: (...args: Parameters<Messenger["connect"]>) => Promise<MessengerAdapter>;
104
106
  };
@@ -72,9 +72,10 @@ export interface OAuthSessionOptions {
72
72
  preset: (command: Command, steps?: SignInSteps) => OAuthPreset | Promise<OAuthPreset>;
73
73
  /**
74
74
  * Asks the service whose the access token is; `id` names the account, `account` is what start and status show.
75
- * `extra` is saved in the entry by the codec at sign-in, such as drive's `principal`.
75
+ * `extra` is saved in the entry by the codec at sign-in, such as drive's `principal`. `scopes` are the ones the
76
+ * service granted, so a CLI can refuse a sign-in that lacks one before it is kept (the account may untick a scope).
76
77
  */
77
- verify: (command: Command, accessToken: string, events: EventSink) => Promise<{
78
+ verify: (command: Command, accessToken: string, events: EventSink, scopes: readonly string[]) => Promise<{
78
79
  id: string;
79
80
  account: Readonly<Record<string, unknown>>;
80
81
  extra?: Record<string, unknown>;
@@ -168,7 +168,7 @@ export const oauthSessionCommand = (options) => {
168
168
  accept: async (tokens) => {
169
169
  if (!tokens.accessToken)
170
170
  throw new CliError("authentication_error", `${service} returned no access token`);
171
- const { id, account, extra } = await options.verify(this, tokens.accessToken, events);
171
+ const { id, account, extra } = await options.verify(this, tokens.accessToken, events, tokens.scopes);
172
172
  (options.claim ?? ((env, profile, key) => rememberAccount(app, profile, key, env)))(context.env, context.profile, id);
173
173
  shown = account;
174
174
  accountId = id;
@@ -217,7 +217,12 @@ export const oauthSessionCommand = (options) => {
217
217
  return answer(this, { ...state, verified: false });
218
218
  refuseOffline(this, service);
219
219
  const { keeper } = await context.keeperOf();
220
- const { account } = await context.run(async (events) => options.verify(this, await keeper.accessToken(), events));
220
+ const { account } = await context.run(async (events) => {
221
+ const tokens = await keeper.tokens();
222
+ if (!tokens.accessToken)
223
+ throw new CliError("authentication_error", `${service} returned no access token`);
224
+ return options.verify(this, tokens.accessToken, events, tokens.scopes);
225
+ });
221
226
  answer(this, { ...account, ...state, verified: true });
222
227
  });
223
228
  const end = logsInOrOut(annotate(new Command("end"), {
@@ -233,7 +238,18 @@ export const oauthSessionCommand = (options) => {
233
238
  if (!context.saved())
234
239
  return answer(this, { profile: context.profile, ended: false });
235
240
  const { removed } = await (await context.keeperOf()).keeper.signOut();
236
- if (!context.saved())
241
+ const left = () => {
242
+ try {
243
+ return context.saved();
244
+ }
245
+ catch (error) {
246
+ // No keyring answers: the sign-in was in the file, which is now empty, and only the keyring read fails.
247
+ if (removed.includes("file"))
248
+ return undefined;
249
+ throw error;
250
+ }
251
+ };
252
+ if (!left())
237
253
  return answer(this, { profile: context.profile, ended: true, removed });
238
254
  answer(this, {
239
255
  profile: context.profile,
@@ -13,19 +13,33 @@ export interface ProfileStoreOptions {
13
13
  open: (env: NodeJS.ProcessEnv, options?: {
14
14
  readOnly?: boolean;
15
15
  }) => Promise<MessageStore>;
16
- /** The profile's account from its sign-in; asked only when no earlier run saved it. */
17
- account: () => AccountKey;
16
+ /**
17
+ * The profile's account from its sign-in; asked only when no earlier run saved it. Without it the account is the
18
+ * profile itself (`{ provider, account: profile }`, a phone system's), which a read also finds with no saved profile.
19
+ */
20
+ account?: () => AccountKey;
21
+ /**
22
+ * `false`: this open never saves the account. A profile no run saved, or no store at all, reads an empty store in a
23
+ * temporary folder, so a mistyped profile saves nothing; a store that needs a migration is still migrated. By
24
+ * default a write saves the account, and so does the first read of a profile.
25
+ */
26
+ saves?: boolean;
27
+ /** The name a new account is saved with. */
28
+ name?: string;
29
+ }
30
+ export interface ProfileStore {
31
+ store: MessageStore;
32
+ account: AccountKey;
33
+ /** The store's id for the account, which `meetings` and `mail` take. */
34
+ accountId: number;
18
35
  }
19
36
  /**
20
- * The store a command over one service account reads (a CRM's, a blog's), and the profile's account in it. A read takes
21
- * the account an earlier run saved, so it never reads the sign-in; the first read of a profile, a store that is missing
22
- * or needs a migration, and every sync and write open it for writing and save the account (scope work, which the owner
23
- * may change) and the profile.
37
+ * The store a command over one service account reads (a CRM's, a blog's, a phone system's), and the profile's account
38
+ * in it. A read takes the account an earlier run saved, so it never reads the sign-in; the first read of a profile, a
39
+ * store that is missing or needs a migration, and every sync and write open it for writing and save the account (scope
40
+ * work, which the owner may change) and the profile, unless `saves` is `false`.
24
41
  *
25
42
  * Under `<PREFIX>_READ_ONLY` a read with no store or no saved profile reads an empty store in a temporary folder, so
26
43
  * the lock creates no `wirecat.db`; the folder goes when the store closes. A sync still writes, as a fetch may.
27
44
  */
28
- export declare const openProfileStore: (options: ProfileStoreOptions) => Promise<{
29
- store: MessageStore;
30
- account: AccountKey;
31
- }>;
45
+ export declare const openProfileStore: (options: ProfileStoreOptions) => Promise<ProfileStore>;
@@ -4,58 +4,73 @@ import { join } from "node:path";
4
4
  import { isCliError } from "@wirecat/cli-base";
5
5
  import { readOnlyLockOf } from "../ports/app.js";
6
6
  /**
7
- * The store a command over one service account reads (a CRM's, a blog's), and the profile's account in it. A read takes
8
- * the account an earlier run saved, so it never reads the sign-in; the first read of a profile, a store that is missing
9
- * or needs a migration, and every sync and write open it for writing and save the account (scope work, which the owner
10
- * may change) and the profile.
7
+ * The store a command over one service account reads (a CRM's, a blog's, a phone system's), and the profile's account
8
+ * in it. A read takes the account an earlier run saved, so it never reads the sign-in; the first read of a profile, a
9
+ * store that is missing or needs a migration, and every sync and write open it for writing and save the account (scope
10
+ * work, which the owner may change) and the profile, unless `saves` is `false`.
11
11
  *
12
12
  * Under `<PREFIX>_READ_ONLY` a read with no store or no saved profile reads an empty store in a temporary folder, so
13
13
  * the lock creates no `wirecat.db`; the folder goes when the store closes. A sync still writes, as a fetch may.
14
14
  */
15
15
  export const openProfileStore = async (options) => {
16
- const { app, env, profile, readOnly, open } = options;
16
+ const { app, env, readOnly, open } = options;
17
17
  const locked = readOnly && readOnlyLockOf(app, env) !== undefined;
18
+ const saves = options.saves !== false;
18
19
  if (readOnly) {
20
+ let missing = false;
19
21
  const store = await open(env, { readOnly: true }).catch((error) => {
20
- if (locked && !(isCliError(error) && error.code === "not_found"))
22
+ missing = isCliError(error) && error.code === "not_found";
23
+ if (locked && !missing)
21
24
  throw error;
22
25
  return undefined;
23
26
  });
24
- if (store) {
25
- const saved = await store.accounts
26
- .profiles()
27
- .then((all) => all[app.command]?.[profile])
28
- .catch(() => undefined);
29
- if (saved)
30
- return { store, account: { provider: saved.provider, account: saved.account } };
31
- await store.close();
32
- }
27
+ if (store)
28
+ return (await known(store, options)) ?? (locked || !saves ? empty(options) : saved(options, env));
29
+ if (missing && !saves)
30
+ return empty(options);
33
31
  }
34
- if (!locked)
35
- return withProfile(options, env, options.account());
36
- const folder = mkdtempSync(join(tmpdir(), `${app.command}-empty-`));
32
+ if (locked)
33
+ return empty(options);
34
+ if (saves)
35
+ return saved(options, env);
36
+ return (await known(await open(env), options)) ?? empty(options);
37
+ };
38
+ const profileKey = ({ provider, profile }) => ({ provider, account: profile });
39
+ const known = async (store, options) => {
40
+ const found = await savedAccount(store, options).catch(() => undefined);
41
+ if (found)
42
+ return { store, account: { provider: found.provider, account: found.account }, accountId: found.id };
43
+ await store.close();
44
+ return undefined;
45
+ };
46
+ const savedAccount = async (store, options) => {
47
+ const profile = (await store.accounts.profiles())[options.app.command]?.[options.profile];
48
+ if (profile)
49
+ return store.accounts.storedAccount({ provider: profile.provider, account: profile.account });
50
+ return options.account ? undefined : store.accounts.storedAccount(profileKey(options));
51
+ };
52
+ const saved = (options, env) => withProfile(options, env, options.account?.() ?? profileKey(options));
53
+ const empty = async (options) => {
54
+ const folder = mkdtempSync(join(tmpdir(), `${options.app.command}-empty-`));
37
55
  const removing = () => rmSync(folder, { recursive: true, force: true });
38
56
  try {
39
- const empty = await withProfile(options, { ...env, MESSAGING_STORE: join(folder, "wirecat.db") }, {
40
- provider: options.provider,
41
- account: profile,
42
- });
43
- const close = empty.store.close.bind(empty.store);
44
- empty.store.close = () => close().finally(removing);
45
- return empty;
57
+ const opened = await withProfile(options, { ...options.env, MESSAGING_STORE: join(folder, "wirecat.db") }, profileKey(options));
58
+ const close = opened.store.close.bind(opened.store);
59
+ opened.store.close = () => close().finally(removing);
60
+ return opened;
46
61
  }
47
62
  catch (error) {
48
63
  removing();
49
64
  throw error;
50
65
  }
51
66
  };
52
- const withProfile = async ({ app, profile, open }, env, account) => {
67
+ const withProfile = async ({ app, profile, open, name }, env, account) => {
53
68
  const store = await open(env);
54
69
  try {
55
70
  // An account already stored keeps the scope the owner gave it.
56
- await store.accounts.saveAccount(account, { name: null, scope: "work" });
71
+ const accountId = await store.accounts.saveAccount(account, { name: name ?? null, scope: "work" });
57
72
  await store.accounts.saveProfile(app.command, profile, account);
58
- return { store, account };
73
+ return { store, account, accountId };
59
74
  }
60
75
  catch (error) {
61
76
  await store.close();
@@ -186,7 +186,7 @@ export declare const appDoctorCommand: (app: import("./entry.js").AppIdentity, c
186
186
  }, (issue: import("valibot").StrictObjectIssue) => string>, undefined>;
187
187
  }, (issue: import("valibot").StrictObjectIssue) => string>;
188
188
  permissions?: import("./permission-keys.js").CommandPermissions | undefined;
189
- }, options?: import("./app-doctor-command.js").AppDoctorOptions | undefined) => import("commander").Command;
189
+ } | null, options?: import("./app-doctor-command.js").AppDoctorOptions | undefined) => import("commander").Command;
190
190
  export declare const appCompleteCommand: (app: Pick<import("./entry.js").AppIdentity, "command" | "envPrefix">, config: Pick<{
191
191
  resolveSettings: (flags?: import("./settings.js").GlobalFlags, options?: import("./settings.js").ResolveOptions) => import("./settings.js").Settings & object;
192
192
  configuredProfiles: (options?: import("./settings.js").ResolveOptions) => string[];
@@ -1,4 +1,4 @@
1
- import { type KeyringStore } from "@wirecat/cli-base";
1
+ import { type KeyringStore, type StoredCredential } from "@wirecat/cli-base";
2
2
  import type { FetchLike } from "@wirecat/cli-base/http";
3
3
  import { Command } from "commander";
4
4
  import type { CliVerify } from "../manifest/index.js";
@@ -56,6 +56,25 @@ export interface TokenSessionOptions {
56
56
  guide?: string;
57
57
  /** One sentence more for `session end --help`, such as what of the service's own tools it leaves alone. */
58
58
  endNote?: string;
59
+ /**
60
+ * The profile's entry keeps more than the token, as hubspot keeps the account id, its UI domain and time zone beside
61
+ * its key: `write` makes the stored value from the token and `verify`'s answer, and `read` gets the token back with
62
+ * the account `session status` and `session list` show. A token from `<PREFIX>_TOKEN` comes to `read` as it is.
63
+ * Unset, the entry is the token alone. Not with `site`.
64
+ */
65
+ entry?: TokenEntry;
66
+ }
67
+ /** How a profile's entry holds the token and what is kept beside it (`TokenSessionOptions.entry`). */
68
+ export interface TokenEntry {
69
+ write: (token: string, verified: {
70
+ id: string;
71
+ account: Readonly<Record<string, unknown>>;
72
+ }) => string;
73
+ /** Throws a `CliError` with the reason `session.unreadable` for an entry it cannot read. */
74
+ read: (saved: StoredCredential, env: NodeJS.ProcessEnv) => {
75
+ token: string;
76
+ account?: string;
77
+ };
59
78
  }
60
79
  export interface ManifestVerifyOptions {
61
80
  manifest: ServiceApiManifest;
@@ -76,7 +95,7 @@ export interface ManifestVerifyOptions {
76
95
  export declare const manifestVerify: ({ manifest, service, verify, fetch }: ManifestVerifyOptions) => TokenSessionOptions["verify"];
77
96
  /**
78
97
  * `session list`'s row for a profile whose sign-in cannot be read: a keyring this run cannot reach or a broken entry
79
- * must not hide the other profiles (WC-ACCT-12), and `session status` names the cause. Warns once per cause.
98
+ * must not hide the other profiles (WC-ACCT-12), and `session status` names the cause. Warns once per reason.
80
99
  */
81
100
  export declare const unknownSignIn: (warn: (message: string) => void) => (profile: string, error: unknown) => {
82
101
  readonly profile: string;
@@ -43,16 +43,18 @@ export const manifestVerify = ({ manifest, service, verify, fetch }) => async (c
43
43
  const UNREADABLE = new Set(["keyring.unreachable", "oauth.not-saved", "oauth.invalid", "session.unreadable"]);
44
44
  /**
45
45
  * `session list`'s row for a profile whose sign-in cannot be read: a keyring this run cannot reach or a broken entry
46
- * must not hide the other profiles (WC-ACCT-12), and `session status` names the cause. Warns once per cause.
46
+ * must not hide the other profiles (WC-ACCT-12), and `session status` names the cause. Warns once per reason.
47
47
  */
48
48
  export const unknownSignIn = (warn) => {
49
49
  const warned = new Set();
50
50
  return (profile, error) => {
51
51
  if (!(error instanceof CliError) || !UNREADABLE.has(String(error.details.reason)))
52
52
  throw error;
53
- if (!warned.has(error.message))
53
+ // By reason, not message: cli-base's keyring.unreachable names the profile, and the cause is the same for all.
54
+ const reason = String(error.details.reason);
55
+ if (!warned.has(reason))
54
56
  warn(error.message);
55
- warned.add(error.message);
57
+ warned.add(reason);
56
58
  return { profile, signed_in: null, state: "unknown" };
57
59
  };
58
60
  };
@@ -66,8 +68,12 @@ export const storageOf = (raw) => {
66
68
  * or read from stdin, checked with the service, and only then kept in the keyring or a private file.
67
69
  */
68
70
  const tokenSessionCommandDefinition = (options) => {
69
- const { app, service } = options;
71
+ const { app, service, entry } = options;
72
+ if (entry && options.site)
73
+ throw new CliError("configuration_error", "tokenSessionCommand takes entry or site, not both");
70
74
  const word = options.token ?? (options.login ? "password" : "API token");
75
+ const held = (saved, env) => entry ? entry.read(saved, env) : { token: saved.secret };
76
+ const accountOf = (account) => (entry ? { account: account ?? null } : {});
71
77
  const contextOf = (command) => {
72
78
  const base = baseContext(command, options.resolveSettings);
73
79
  const tokens = new ProfileTokenStore({
@@ -129,9 +135,11 @@ const tokenSessionCommandDefinition = (options) => {
129
135
  if (!secret)
130
136
  throw new CliError("validation_error", `no ${word} was given`);
131
137
  const token = login === undefined ? secret : `${login}:${secret}`;
132
- const { id, account } = await run((events) => options.verify(this, token, events, site));
138
+ const verified = await run((events) => options.verify(this, token, events, site));
139
+ const { id, account } = verified;
133
140
  (options.claim ?? ((at, name, key) => rememberAccount(app, name, key, at)))(env, profile, siteAccount(site, id), tokens, keyring);
134
- const storedIn = tokens.write(profile, token, args.credentialStorage, site === undefined ? {} : { site });
141
+ const kept = entry ? entry.write(token, verified) : token;
142
+ const storedIn = tokens.write(profile, kept, args.credentialStorage, site === undefined ? {} : { site });
135
143
  answer(this, { profile, state: "saved", stored_in: storedIn, verified: true, ...siteOf(site), ...account });
136
144
  });
137
145
  const status = annotate(new Command("status"), {
@@ -143,16 +151,23 @@ const tokenSessionCommandDefinition = (options) => {
143
151
  `--check asks ${service} whose token it is`)
144
152
  .option("--check", `ask ${service} whether the token still works, and whose it is`)
145
153
  .action(async function (args) {
146
- const { profile, tokens, run } = contextOf(this);
154
+ const { env, profile, tokens, run } = contextOf(this);
147
155
  const saved = tokens.read(profile);
156
+ const found = saved ? held(saved, env) : undefined;
148
157
  const site = options.site ? tokens.readWith(profile, SITE)?.secret : undefined;
149
- const state = { profile, state: saved ? "saved" : "missing", token_from: saved?.source ?? null, ...siteOf(site) };
150
- if (!args.check || !saved)
158
+ const state = {
159
+ profile,
160
+ state: saved ? "saved" : "missing",
161
+ token_from: saved?.source ?? null,
162
+ ...siteOf(site),
163
+ ...accountOf(found?.account),
164
+ };
165
+ if (!args.check || !found)
151
166
  return answer(this, { ...state, verified: false });
152
167
  if (options.site && site === undefined)
153
168
  throw noSite(app, profile);
154
169
  refuseOffline(this, service);
155
- const { account } = await run((events) => options.verify(this, saved.secret, events, site));
170
+ const { account } = await run((events) => options.verify(this, found.token, events, site));
156
171
  answer(this, { ...state, verified: true, ...account });
157
172
  });
158
173
  const end = logsInOrOut(annotate(new Command("end"), {
@@ -193,10 +208,11 @@ const tokenSessionCommandDefinition = (options) => {
193
208
  signed_in: saved !== undefined,
194
209
  state: saved ? "saved" : "missing",
195
210
  token_from: saved?.source ?? null,
211
+ ...accountOf(saved ? held(saved, env).account : undefined),
196
212
  };
197
213
  }
198
214
  catch (error) {
199
- return { ...unknown(profile, error), token_from: null };
215
+ return { ...unknown(profile, error), token_from: null, ...accountOf(undefined) };
200
216
  }
201
217
  });
202
218
  renderAnswer(this, outputFor(this), listOf("session list", { items, limit: Math.max(1, items.length), has_more: false }));
@@ -1,12 +1,12 @@
1
1
  import { createHash } from "node:crypto";
2
- import { chmodSync, constants, copyFileSync, existsSync, linkSync, mkdirSync, readFileSync, renameSync, rmSync, } from "node:fs";
2
+ import { chmodSync, constants, copyFileSync, existsSync, linkSync, mkdirSync, renameSync, rmSync } from "node:fs";
3
3
  import { open } from "node:fs/promises";
4
4
  import { join, resolve, sep } from "node:path";
5
5
  import { CliError, isCliError, resolvePaths } from "@wirecat/cli-base";
6
6
  import { annotate } from "@wirecat/cli-base/commands";
7
7
  import * as v from "valibot";
8
8
  import { extractText, importEngine, MAX_TEXT_CHARS } from "../../attachments/extract.js";
9
- import { attachmentMaxBytes } from "../../attachments/limits.js";
9
+ import { attachmentMaxBytes, readWhole } from "../../attachments/limits.js";
10
10
  import { answerEntity } from "../../cli/answer-entity.js";
11
11
  import { environmentOf, outputFor, runBudgetOf } from "../../cli/context.js";
12
12
  import { FETCH, REMOTE_READ } from "../../cli/effects.js";
@@ -277,9 +277,10 @@ export const downloadCrmFile = async (context, file, assignee, { capBytes, capMb
277
277
  await discard();
278
278
  throw diskFull(limits, top, setting);
279
279
  }
280
+ const overBudget = saved.bytes > attachmentMaxBytes(run.env ?? process.env);
280
281
  let bytes;
281
282
  try {
282
- bytes = readFileSync(target);
283
+ bytes = overBudget ? Buffer.alloc(0) : await readWhole(target);
283
284
  }
284
285
  catch {
285
286
  await discard();
@@ -295,10 +296,9 @@ export const downloadCrmFile = async (context, file, assignee, { capBytes, capMb
295
296
  };
296
297
  let extraction;
297
298
  try {
298
- extraction =
299
- saved.bytes > attachmentMaxBytes(run.env ?? process.env)
300
- ? { status: "too-large" }
301
- : await extractText(bytes, { kind: "file", name: file.name, mime: file.mime, path: target }, importEngine, signal, run.env ?? process.env);
299
+ extraction = overBudget
300
+ ? { status: "too-large" }
301
+ : await extractText(bytes, { kind: "file", name: file.name, mime: file.mime, path: target }, importEngine, signal, run.env ?? process.env);
302
302
  }
303
303
  catch (error) {
304
304
  if (signal?.aborted)
@@ -1,7 +1,7 @@
1
1
  export { readSpreadsheet } from "./attachments/documents.js";
2
2
  export type { Engine, Extraction, FileHint, LoadEngine } from "./attachments/extract.js";
3
3
  export { extractText, importEngine, MAX_FILE_BYTES, MAX_TEXT_CHARS } from "./attachments/extract.js";
4
- export { attachmentMaxBytes } from "./attachments/limits.js";
4
+ export { asBytes, attachmentMaxBytes, readWhole, sizeText } from "./attachments/limits.js";
5
5
  export { type OcrPipeline, ocrImage } from "./attachments/ocr.js";
6
6
  export { agentPictureReader, PICTURE_AGENTS, type PictureAgent, type PictureReadingSetting, pictureExtractor, pictureReaderOf, readPictureReading, readPictureWithAgent, } from "./attachments/picture-reading.js";
7
7
  export type { Sheet, SheetCell } from "./attachments/sheets.js";
package/dist/documents.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export { readSpreadsheet } from "./attachments/documents.js";
2
2
  export { extractText, importEngine, MAX_FILE_BYTES, MAX_TEXT_CHARS } from "./attachments/extract.js";
3
- export { attachmentMaxBytes } from "./attachments/limits.js";
3
+ export { asBytes, attachmentMaxBytes, readWhole, sizeText } from "./attachments/limits.js";
4
4
  export { ocrImage } from "./attachments/ocr.js";
5
5
  export { agentPictureReader, PICTURE_AGENTS, pictureExtractor, pictureReaderOf, readPictureReading, readPictureWithAgent, } from "./attachments/picture-reading.js";
6
6
  export { columnName, sheetText } from "./attachments/sheets.js";
@@ -9,10 +9,14 @@ export type PersonKind = (typeof PERSON_KINDS)[number];
9
9
  /** What decided a kind, besides the ties that make someone a `person`. @experimental */
10
10
  export type KindSignal = "test-data" | "bot" | "no-reply" | "notification-address" | "auto-submitted" | "null-return-path" | "bulk-mail" | "bulk-never-replied" | "newsletter-only" | "automated-name" | "organization" | "role-address" | "company-name" | "no-tie" | "no-name";
11
11
  /**
12
- * A sender bot's reference, `sender-bot:<id>`: a program that writes to the owner, an entity apart from people.
13
- * `bot:` names the agents of the `bots` table. @experimental
12
+ * A sender bot's reference, `bot:<id>`: a program that writes to the owner, an entity apart from people. The agents of
13
+ * the `bots` table are `agent:<id>` since store version 78. @experimental
14
14
  */
15
- export declare const SENDER_BOT_PREFIX = "sender-bot:";
15
+ export declare const SENDER_BOT_PREFIX = "bot:";
16
+ /** A sender bot's reference before store version 78, still read. @experimental */
17
+ export declare const OLD_SENDER_BOT_PREFIX = "sender-bot:";
18
+ /** `sender-bot:<id>` as `bot:<id>`; any other text as it is. @experimental */
19
+ export declare const senderBotRef: (ref: string) => string;
16
20
  /** A sender that is a program: «Notifications», «Рассылка», «no-reply». */
17
21
  export declare const isAutomatedName: (name: string | null) => boolean;
18
22
  /** A legal form or a word only a business calls itself: «ООО Ромашка», «CZECH AIRLINES», «OpenWeather Team». */
@@ -5,10 +5,14 @@
5
5
  */
6
6
  export const PERSON_KINDS = ["person", "organization", "automated", "stranger", "unsorted", "test"];
7
7
  /**
8
- * A sender bot's reference, `sender-bot:<id>`: a program that writes to the owner, an entity apart from people.
9
- * `bot:` names the agents of the `bots` table. @experimental
8
+ * A sender bot's reference, `bot:<id>`: a program that writes to the owner, an entity apart from people. The agents of
9
+ * the `bots` table are `agent:<id>` since store version 78. @experimental
10
10
  */
11
- export const SENDER_BOT_PREFIX = "sender-bot:";
11
+ export const SENDER_BOT_PREFIX = "bot:";
12
+ /** A sender bot's reference before store version 78, still read. @experimental */
13
+ export const OLD_SENDER_BOT_PREFIX = "sender-bot:";
14
+ /** `sender-bot:<id>` as `bot:<id>`; any other text as it is. @experimental */
15
+ export const senderBotRef = (ref) => ref.startsWith(OLD_SENDER_BOT_PREFIX) ? `${SENDER_BOT_PREFIX}${ref.slice(OLD_SENDER_BOT_PREFIX.length)}` : ref;
12
16
  const AUTOMATED_WORDS = new Set([
13
17
  "noreply",
14
18
  "notification",
@@ -103,6 +103,7 @@ const WORDS = {
103
103
  task: "Task",
104
104
  memory: "Memory",
105
105
  fact: "Fact",
106
+ agent: "Agent",
106
107
  bot: "Bot",
107
108
  invoice: "Invoice",
108
109
  payment: "Payment",
@@ -31,9 +31,10 @@ export type Reference = {
31
31
  } | MeetingReference;
32
32
  /**
33
33
  * Things named by their store id (a task also by its key or the task package's id). `entity` is the name
34
- * before organizations and projects: it still parses, so an old file's reference resolves as not found.
34
+ * before organizations and projects: it still parses, so an old file's reference resolves as not found. `agent` is an
35
+ * agent of the `bots` table, `bot` a sender bot (`bot:` named agents before store version 78).
35
36
  */
36
- export declare const SIMPLE_REFERENCES: readonly ["note", "document", "person", "organization", "project", "task", "memory", "fact", "bot", "event", "invoice", "payment", "order", "deal", "lead", "pipeline", "product", "contract", "subscription", "wallet", "transaction", "entity"];
37
+ export declare const SIMPLE_REFERENCES: readonly ["note", "document", "person", "organization", "project", "task", "memory", "fact", "agent", "bot", "event", "invoice", "payment", "order", "deal", "lead", "pipeline", "product", "contract", "subscription", "wallet", "transaction", "entity"];
37
38
  export type SimpleReference = (typeof SIMPLE_REFERENCES)[number];
38
39
  export type RefKindName = Exclude<Reference["type"], "entity">;
39
40
  /** @experimental */
@@ -3,7 +3,8 @@ import { formatMeetingReference, parseMeetingReference } from "../meetings/index
3
3
  import { formatLocator, parseLocator } from "./locator.js";
4
4
  /**
5
5
  * Things named by their store id (a task also by its key or the task package's id). `entity` is the name
6
- * before organizations and projects: it still parses, so an old file's reference resolves as not found.
6
+ * before organizations and projects: it still parses, so an old file's reference resolves as not found. `agent` is an
7
+ * agent of the `bots` table, `bot` a sender bot (`bot:` named agents before store version 78).
7
8
  */
8
9
  export const SIMPLE_REFERENCES = [
9
10
  "note",
@@ -14,6 +15,7 @@ export const SIMPLE_REFERENCES = [
14
15
  "task",
15
16
  "memory",
16
17
  "fact",
18
+ "agent",
17
19
  "bot",
18
20
  "event",
19
21
  "invoice",
@@ -57,19 +59,23 @@ const folderPath = (path) => {
57
59
  };
58
60
  const MEETING_SHAPE = "meeting:<account>/<meeting>[/<transcript>[/<cue>]] with safe integer ids";
59
61
  const kind = (spec) => spec;
60
- const simple = (prefix) => kind({
62
+ /** `agent:claude` is an author's name, stored long before `agent:` named a row: only an id makes it a reference. */
63
+ const BY_NUMBER_ONLY = new Set(["agent"]);
64
+ const simple = (prefix, type = prefix) => kind({
61
65
  prefix,
62
- type: prefix,
63
- shape: `${prefix}:<id>`,
66
+ type,
67
+ shape: BY_NUMBER_ONLY.has(prefix) ? `${prefix}:<number>` : `${prefix}:<id>`,
64
68
  parse: (rest, text) => {
65
- if (!rest.trim())
69
+ if (!rest.trim() || (BY_NUMBER_ONLY.has(prefix) && !/^[1-9]\d*$/.test(rest)))
66
70
  throw new CliError("validation_error", `"${singleLine(text)}" names no ${prefix}`, {
67
71
  reason: "ref.malformed",
68
72
  });
69
- return { type: prefix, id: rest };
73
+ return { type, id: rest };
70
74
  },
71
75
  format: (reference) => `${reference.type}:${reference.id}`,
72
76
  });
77
+ /** Prefixes still read and never offered: a sender bot's ref before store version 78. */
78
+ const ALIASES = new Set(["sender-bot"]);
73
79
  /** Every kind of reference. A new kind is one row here; nothing else switches on the prefix. @experimental */
74
80
  export const REF_KINDS = [
75
81
  kind({
@@ -134,12 +140,13 @@ export const REF_KINDS = [
134
140
  },
135
141
  format: formatMeetingReference,
136
142
  }),
137
- ...SIMPLE_REFERENCES.map(simple),
143
+ simple("sender-bot", "bot"),
144
+ ...SIMPLE_REFERENCES.map((prefix) => simple(prefix)),
138
145
  ];
139
146
  const byPrefix = new Map(REF_KINDS.map((spec) => [spec.prefix, spec]));
140
147
  const byType = new Map(REF_KINDS.map((spec) => [spec.type, spec]));
141
148
  /** The prefixes people are told about: `entity` only still parses. */
142
- const offered = REF_KINDS.map(({ prefix }) => prefix).filter((prefix) => prefix !== "entity");
149
+ const offered = REF_KINDS.map(({ prefix }) => prefix).filter((prefix) => prefix !== "entity" && !ALIASES.has(prefix));
143
150
  const distance = (a, b) => {
144
151
  let row = Array.from({ length: b.length + 1 }, (_, at) => at);
145
152
  for (const [i, x] of [...a].entries()) {
@@ -183,6 +190,8 @@ export const canonicalReference = (text) => formatReference(parseReference(text)
183
190
  * @experimental
184
191
  */
185
192
  export const looksLikeReference = (text) => {
186
- const match = /^([a-z]+):\S+$/.exec(text.trim());
187
- return match !== null && byPrefix.has(match[1]);
193
+ const match = /^([a-z][a-z-]*):(\S+)$/.exec(text.trim());
194
+ if (match === null || !byPrefix.has(match[1]))
195
+ return false;
196
+ return !BY_NUMBER_ONLY.has(match[1]) || /^[1-9]\d*$/.test(match[2]);
188
197
  };