@wirecat/cli-core 0.640.0 → 0.642.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 (77) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/dist/analysis/provider.d.ts +1 -1
  3. package/dist/analysis/provider.js +2 -1
  4. package/dist/attachments/gateway-ocr.js +13 -8
  5. package/dist/background/schedules.d.ts +5 -1
  6. package/dist/background/schedules.js +28 -3
  7. package/dist/calendar/mcp/index.d.ts +12 -12
  8. package/dist/cli/ai-model-command.js +6 -3
  9. package/dist/cli/analysis-choice.js +20 -4
  10. package/dist/cli/enrichment-consents-command.js +2 -0
  11. package/dist/cli/local-only-command.d.ts +10 -0
  12. package/dist/cli/local-only-command.js +103 -0
  13. package/dist/cli/messenger/backfill-command.js +16 -1
  14. package/dist/cli/messenger/conversations-command.js +1 -1
  15. package/dist/cli/messenger/replies-consents-command.js +12 -6
  16. package/dist/cli/messenger/search-answers.js +2 -0
  17. package/dist/cli/model-catalogue-command.js +2 -0
  18. package/dist/cli/search-harder-consents-command.js +16 -1
  19. package/dist/cli/store-settings.d.ts +4 -1
  20. package/dist/cli/store-settings.js +26 -9
  21. package/dist/crm/cli/csv.js +2 -0
  22. package/dist/crm/cli/index.js +8 -2
  23. package/dist/crm/cli/search-all.js +4 -4
  24. package/dist/crm/stage-tasks.d.ts +8 -0
  25. package/dist/crm/stage-tasks.js +42 -0
  26. package/dist/documents.d.ts +1 -1
  27. package/dist/documents.js +1 -1
  28. package/dist/domain/crm.d.ts +6 -0
  29. package/dist/embeddings/remote.d.ts +2 -1
  30. package/dist/embeddings/remote.js +5 -3
  31. package/dist/entities/deal.d.ts +6 -0
  32. package/dist/entities/deal.js +3 -0
  33. package/dist/entities/index.d.ts +4 -0
  34. package/dist/errors/reasons.js +8 -0
  35. package/dist/meetings/mcp/index.d.ts +15 -15
  36. package/dist/models/ai.d.ts +16 -3
  37. package/dist/models/ai.js +19 -13
  38. package/dist/models/endpoint.d.ts +5 -0
  39. package/dist/models/endpoint.js +13 -0
  40. package/dist/models/index.d.ts +4 -0
  41. package/dist/models/index.js +9 -1
  42. package/dist/models/local-only.d.ts +17 -0
  43. package/dist/models/local-only.js +42 -0
  44. package/dist/models/purpose.d.ts +24 -0
  45. package/dist/models/purpose.js +26 -0
  46. package/dist/replies/rendering.js +10 -10
  47. package/dist/runs/events.d.ts +9 -1
  48. package/dist/runs/events.js +5 -1
  49. package/dist/runs/log-events.js +2 -0
  50. package/dist/services/deal-context.js +17 -0
  51. package/dist/services/embeddings-maintenance.js +4 -1
  52. package/dist/services/enrichment.d.ts +1 -1
  53. package/dist/services/enrichment.js +27 -0
  54. package/dist/services/meeting-model.js +1 -1
  55. package/dist/services/message-resolution.d.ts +1 -1
  56. package/dist/services/message-resolution.js +2 -2
  57. package/dist/services/messages-search.js +12 -5
  58. package/dist/services/search-all.d.ts +10 -3
  59. package/dist/services/search-all.js +10 -4
  60. package/dist/services/search-harder.d.ts +11 -1
  61. package/dist/services/search-harder.js +38 -5
  62. package/dist/speech/openai.js +2 -0
  63. package/dist/speech/transcribe.d.ts +5 -2
  64. package/dist/speech/transcribe.js +14 -5
  65. package/dist/store/index.d.ts +1 -1
  66. package/dist/store/sqlite/crm-rows.js +2 -0
  67. package/dist/store/sqlite/crm-settings.d.ts +26 -1
  68. package/dist/store/sqlite/crm-settings.js +104 -1
  69. package/dist/store/sqlite/crm.d.ts +12 -0
  70. package/dist/store/sqlite/crm.js +4 -1
  71. package/dist/store/sqlite/deals.d.ts +28 -5
  72. package/dist/store/sqlite/deals.js +158 -14
  73. package/dist/store/sqlite/lucene-fields.js +56 -3
  74. package/dist/store/sqlite/tasks.js +9 -8
  75. package/dist/tasks/model.d.ts +6 -2
  76. package/dist/tasks/service.d.ts +2 -0
  77. package/package.json +1 -1
@@ -78,7 +78,7 @@ const conversationBuildCommand = (messenger) => boundOptions(reachesOtherService
78
78
  await consents.remember(status.chat, identity);
79
79
  }
80
80
  await services.conversations.build(chat);
81
- const request = openAnalysis(target, controller.signal);
81
+ const request = openAnalysis(target, controller.signal, context.env);
82
82
  return runAnalysis(services.conversations, chat, async (...args) => {
83
83
  if (!(await consents.has(status.chat, identity)))
84
84
  throw new CliError("permission_error", "analysis consent was revoked; no further batch was sent");
@@ -1,7 +1,8 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { annotate } from "@wirecat/cli-base/commands";
3
3
  import { Command } from "commander";
4
- import { modelTarget } from "../../models/index.js";
4
+ import { refuseModelAddress } from "../../models/local-only.js";
5
+ import { purposeModel } from "../../models/purpose.js";
5
6
  import { readReplyConsent, replyConsentPathFor, replyModelIdentity, writeReplyConsent } from "../../replies/consents.js";
6
7
  import { grantsAuthority, LOCAL_READ, LOCAL_WRITE } from "../effects.js";
7
8
  import { renderItem } from "./chat-answers.js";
@@ -26,11 +27,16 @@ export const replyConsentsCommand = (messenger) => {
26
27
  const path = replyConsentPathFor(messenger.app, settings.profile, env);
27
28
  const consent = readReplyConsent(path);
28
29
  if (grant) {
29
- const target = modelTarget(settings, "replies");
30
- if (!target)
31
- throw new CliError("configuration_error", "set models.replies.provider and models.replies.model before replies consents grant");
32
- consent.provider = replyModelIdentity(target.provider, target.baseUrl ??
33
- (target.provider === "anthropic" ? "https://api.anthropic.com" : "https://api.openai.com/v1"));
30
+ const chosen = purposeModel(settings, "replies", {
31
+ app: messenger.app,
32
+ env,
33
+ keyring: context.keyring,
34
+ });
35
+ if (!chosen)
36
+ throw new CliError("configuration_error", "set models.replies.provider and models.replies.model, or choose an AI model with `models ai set`, " +
37
+ "before replies consents grant");
38
+ refuseModelAddress(env, chosen.target.baseUrl, "incoming messages");
39
+ consent.provider = replyModelIdentity(chosen.target.provider, chosen.target.baseUrl);
34
40
  }
35
41
  else
36
42
  consent.provider = null;
@@ -332,6 +332,8 @@ export const allHitItem = (item) => item.kind === "meeting"
332
332
  sender_is_me: item.senderIsMe,
333
333
  sender_ref: item.from?.ref,
334
334
  found_by: item.foundBy,
335
+ match: item.match,
336
+ corrections: item.corrections,
335
337
  review: item.review,
336
338
  source_record: item.sourceRecord === undefined
337
339
  ? undefined
@@ -17,6 +17,7 @@ import { FETCH, grantsAuthority, LOCAL_READ, LOCAL_WRITE, NO_EFFECTS } from "./e
17
17
  import { enrichmentConsentsCommand } from "./enrichment-consents-command.js";
18
18
  import { itemOf, listOf } from "./envelope.js";
19
19
  import { listQuery, nativeTerms, termField, typedQuery, withQuery } from "./list-query.js";
20
+ import { localOnlyCommand } from "./local-only-command.js";
20
21
  import { harderConsentsCommand } from "./search-harder-consents-command.js";
21
22
  export const MODEL_CATALOGUE_QUERY = defineQuery({
22
23
  entity: "model",
@@ -147,6 +148,7 @@ export const modelCatalogueCommand = (app, options) => {
147
148
  models.addCommand(harderConsentsCommand(app, options));
148
149
  models.addCommand(providerKeysCommand(app, options));
149
150
  models.addCommand(aiModelCommand(app, options));
151
+ models.addCommand(localOnlyCommand(app, options));
150
152
  }
151
153
  if (options.jsonOption)
152
154
  for (const command of models.commands.flatMap((one) => (one.commands.length ? one.commands : [one])))
@@ -1,10 +1,12 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { annotate } from "@wirecat/cli-base/commands";
3
3
  import { Command } from "commander";
4
+ import { parseDuration } from "../domain/duration.js";
5
+ import { refuseModelAddress } from "../models/local-only.js";
4
6
  import { agentOf } from "../runs/run-context.js";
5
7
  import { keyLookup, keyVariable } from "../services/enrichment.js";
6
8
  import { ENRICHMENT_PROVIDERS, enrichmentEndpoint, enrichmentPrice, isEnrichmentProvider, readEnrichmentSetting, } from "../services/enrichment-setting.js";
7
- import { HARDER_CANDIDATES, HARDER_CHARS, HARDER_MODELS, readHarderSetting, writeHarderSetting, } from "../services/search-harder.js";
9
+ import { HARDER_CANDIDATES, HARDER_CHARS, HARDER_MODELS, HARDER_TIMEOUT_S, harderTimeoutSeconds, readHarderSetting, readHarderTimeout, writeHarderSetting, writeHarderTimeout, } from "../services/search-harder.js";
8
10
  import { grantsAuthority, LOCAL_READ, LOCAL_WRITE } from "./effects.js";
9
11
  import { itemOf } from "./envelope.js";
10
12
  // One search: 30 hits of up to 400 characters plus the prompt, and a short list of hit numbers back.
@@ -45,6 +47,8 @@ const state = (app, options, given) => {
45
47
  endpoint: enrichmentEndpoint(chosen),
46
48
  ...(enrichment ? { proposed_from: "enrichment" } : {}),
47
49
  consented_at: setting?.consented_at ?? null,
50
+ timeout_s: harderTimeoutSeconds(env, enrichmentEndpoint(chosen)),
51
+ timeout_set: readHarderTimeout(env) !== undefined,
48
52
  candidates: HARDER_CANDIDATES,
49
53
  chars_per_hit: HARDER_CHARS,
50
54
  usd_per_million: price
@@ -55,6 +59,12 @@ const state = (app, options, given) => {
55
59
  off_command: `${app.command} models search-consents revoke`,
56
60
  };
57
61
  };
62
+ const seconds = (value) => {
63
+ const ms = parseDuration(value, "--timeout");
64
+ if (ms < 1000 || ms > 600_000)
65
+ throw new CliError("validation_error", "--timeout takes 1s to 10m");
66
+ return Math.round(ms / 1000);
67
+ };
58
68
  /**
59
69
  * The owner's consent that `search all --harder` may send a question and its hits to a hosted model. Off until
60
70
  * `set … --yes`; with it, still only a search that asks with --harder sends anything.
@@ -77,6 +87,8 @@ export const harderConsentsCommand = (app, options) => {
77
87
  .argument("<provider>", `the provider that receives the question and hits: ${ENRICHMENT_PROVIDERS.join(" or ")}`)
78
88
  .option("--model <model>", `the provider's model; ${HARDER_MODELS.anthropic} or ${HARDER_MODELS.openai} if left out`)
79
89
  .option("--base-url <url>", "the address of an OpenAI-compatible model API (OpenRouter…); needs --model")
90
+ .option("--timeout <duration>", `how long a --harder search waits for the model, 1s to 10m (30s, 2m); ${HARDER_TIMEOUT_S.hosted} s for a hosted model, ` +
91
+ `${HARDER_TIMEOUT_S.local} s for one on this computer until one is set; kept until set again`, seconds)
80
92
  .option("--yes", "agree that a --harder search sends its question and hits, and allow it")
81
93
  .action(function (provider, given) {
82
94
  if (!isEnrichmentProvider(provider))
@@ -95,6 +107,7 @@ export const harderConsentsCommand = (app, options) => {
95
107
  model: given.model ?? HARDER_MODELS[provider],
96
108
  ...(given.baseUrl === undefined ? {} : { base_url: given.baseUrl }),
97
109
  };
110
+ refuseModelAddress(env, enrichmentEndpoint(chosen), "a --harder search's question and hits");
98
111
  if (!given.yes) {
99
112
  const now = state(app, options, chosen);
100
113
  options.diagnostic(`${now.consent}\nNothing changed — add --yes to allow it.`);
@@ -102,6 +115,8 @@ export const harderConsentsCommand = (app, options) => {
102
115
  return;
103
116
  }
104
117
  writeHarderSetting(env, { ...chosen, consented_at: new Date().toISOString() });
118
+ if (given.timeout !== undefined)
119
+ writeHarderTimeout(env, given.timeout);
105
120
  options.diagnostic(`search all --harder may now call ${provider} ${chosen.model}`);
106
121
  options.output(itemOf({ ...state(app, options), changed: true }), this);
107
122
  });
@@ -7,7 +7,10 @@ export declare const STORE_SETTINGS: string[];
7
7
  */
8
8
  export declare const storeSettingsOf: (app: Pick<AppIdentity, "messenger">) => string[];
9
9
  export declare const offersStoreSetting: (app: Pick<AppIdentity, "messenger">, setting: string) => boolean;
10
- /** Whose deals a CRM copy holds: the owner's to set; an agent's run is stopped from changing it by mistake. */
10
+ /**
11
+ * Whose deals a CRM copy holds and what opens the owner's tasks: the owner's to set; an agent's run is stopped from
12
+ * changing them by mistake.
13
+ */
11
14
  export declare const isOwnerOnlyStoreSetting: (setting: string) => boolean;
12
15
  export declare const isStoreSetting: (setting: string) => boolean;
13
16
  export declare const changeStoreSetting: (app: AppIdentity, env: NodeJS.ProcessEnv, setting: string, value: string | undefined) => Promise<{
@@ -33,10 +33,10 @@ export const STORE_SETTINGS = [
33
33
  ];
34
34
  const GROUP_PREFIX = `${ACCOUNT_GROUPS_SETTING}.`;
35
35
  /**
36
- * A CRM account's: whether what it reports is a relationship or waits for review, what its company types mean, and
37
- * whose deals and leads its sync copies.
36
+ * A CRM account's: whether what it reports is a relationship or waits for review, what its company types mean, whose
37
+ * deals and leads its sync copies, and which stages open a task.
38
38
  */
39
- const CRM_SETTINGS = ["links", "company-types", "scope", "unassigned", "self"].map((name) => `crm.<provider>:<account>.${name}`);
39
+ const CRM_SETTINGS = ["links", "company-types", "scope", "unassigned", "self", "stage-tasks"].map((name) => `crm.<provider>:<account>.${name}`);
40
40
  /**
41
41
  * The store settings a CLI offers. Phone countries, task rules and account groups belong to messages; a CLI that is
42
42
  * not a messenger would change them for tg and MAX without reading them itself.
@@ -45,10 +45,13 @@ export const storeSettingsOf = (app) => app.messenger === false
45
45
  ? [...Object.keys(SCRIPTS), OWNER_LANGUAGES, ...CRM_SETTINGS]
46
46
  : [...STORE_SETTINGS, `${GROUP_PREFIX}<name>`, ...CRM_SETTINGS];
47
47
  export const offersStoreSetting = (app, setting) => app.messenger !== false || setting in SCRIPTS || setting === OWNER_LANGUAGES || parseCrmSetting(setting) !== undefined;
48
- /** Whose deals a CRM copy holds: the owner's to set; an agent's run is stopped from changing it by mistake. */
48
+ /**
49
+ * Whose deals a CRM copy holds and what opens the owner's tasks: the owner's to set; an agent's run is stopped from
50
+ * changing them by mistake.
51
+ */
49
52
  export const isOwnerOnlyStoreSetting = (setting) => {
50
53
  const name = parseCrmSetting(setting)?.name;
51
- return name === "scope" || name === "self" || name === "unassigned";
54
+ return name === "scope" || name === "self" || name === "unassigned" || name === "stage-tasks";
52
55
  };
53
56
  export const isStoreSetting = (setting) => setting in SCRIPTS ||
54
57
  setting === OWNER_LANGUAGES ||
@@ -261,10 +264,19 @@ const crmValueText = (value) => typeof value === "string"
261
264
  ? value
262
265
  : Array.isArray(value)
263
266
  ? value.join(",")
264
- : Object.entries(value)
265
- .map(([type, meaning]) => `${type}=${meaning}`)
266
- .join(",");
267
- const CRM_DEFAULTS = { links: "reported", "company-types": {}, scope: "mine", unassigned: [], self: "" };
267
+ : Object.values(value).some((one) => typeof one === "object")
268
+ ? JSON.stringify(value)
269
+ : Object.entries(value)
270
+ .map(([type, meaning]) => `${type}=${meaning}`)
271
+ .join(",");
272
+ const CRM_DEFAULTS = {
273
+ links: "reported",
274
+ "company-types": {},
275
+ scope: "mine",
276
+ unassigned: [],
277
+ self: "",
278
+ "stage-tasks": {},
279
+ };
268
280
  const crmNote = (name, now) => {
269
281
  if (name === "links")
270
282
  return `store-wide — the next sync of that account writes what it reports as ${now === "review" ? "proposals for the owner to review" : "reported relationships"}; relationships already stored stay`;
@@ -277,6 +289,11 @@ const crmNote = (name, now) => {
277
289
  "of the unassigned users, and marks the others deleted here; contacts and companies stay whole";
278
290
  if (name === "unassigned")
279
291
  return "store-wide — with scope mine, the next sync also copies the deals and leads of these users";
292
+ if (name === "stage-tasks")
293
+ return Object.keys(now).length === 0
294
+ ? "store-wide — no stage opens a task"
295
+ : "store-wide — from now on, each sync opens a local task for every deal or lead that moved into one of these " +
296
+ "stages since the last sync; moves made before the rules were first set open none";
280
297
  return now === ""
281
298
  ? "store-wide — the next sync gives the account's copy to its sign-in's user, and narrows it to that user's deals"
282
299
  : "store-wide — the account's copy holds this user's deals; a sync signed in as another user is refused";
@@ -20,6 +20,8 @@ export const DEAL_CSV_COLUMNS = [
20
20
  "amount",
21
21
  "currency",
22
22
  "organization",
23
+ "contact_name",
24
+ "company_name",
23
25
  "people",
24
26
  "close_date",
25
27
  "closed_date",
@@ -15,6 +15,7 @@ import { DEAL_KINDS, DEAL_STATUSES } from "../../domain/deals.js";
15
15
  import { deal as dealEntity } from "../../entities/deal.js";
16
16
  import { count, text } from "../../entities/fields.js";
17
17
  import { CRM_SCOPES, crmSettingKey } from "../../store/sqlite/crm-settings.js";
18
+ import { openStageTasks } from "../stage-tasks.js";
18
19
  import { crmStatus, syncCrm } from "../sync.js";
19
20
  import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, pipelineOf, removeCrmItem, updateCrmItem, } from "../writes.js";
20
21
  import { csvFormatOption, renderCsv } from "./csv.js";
@@ -53,6 +54,8 @@ const DEAL_UNTRUSTED = [
53
54
  "stage",
54
55
  "pipeline_name",
55
56
  "organization.name",
57
+ "contact_name",
58
+ "company_name",
56
59
  "people.name",
57
60
  "provider_metadata",
58
61
  ];
@@ -76,6 +79,7 @@ const crmSync = v.strictObject({
76
79
  users: v.optional(count),
77
80
  skipped_owner_rejected: count,
78
81
  contacts_removed: v.optional(crmContactsRemoved),
82
+ stage_tasks: count,
79
83
  synced: v.array(v.strictObject({
80
84
  kind: v.picklist(CRM_KINDS),
81
85
  round: v.picklist(["full", "changes"]),
@@ -184,7 +188,8 @@ const addCrmCommandsDefinition = (program, options) => {
184
188
  const example = (command, ...lines) => annotate(command, { examples: lines.map((line) => `${options.app.command} work ${line}`) });
185
189
  example(answerEntity(annotate(program.command("sync"), { effects: FETCH, offline: false, cooperative: true, partial: true }), "crm_sync", crmSync).description("bring the CRM's copy in the local store up to date: pipelines, companies, contacts, deals and leads that " +
186
190
  "changed since the last sync, or everything with --rescan; a run stops before its deadline or --max-pages " +
187
- "and the next one goes on from there"), "sync", "sync --rescan", "sync --max-pages 20")
191
+ "and the next one goes on from there. Then each deal or lead that moved into a stage the stage-tasks setting " +
192
+ "names opens a local task, once per move"), "sync", "sync --rescan", "sync --max-pages 20")
188
193
  .option("--rescan", "list everything again, every id too, dropping a round in progress")
189
194
  .option("--max-pages <pages>", "at most this many requests to the CRM in this run", integer(100_000))
190
195
  .action(async (opts, command) => {
@@ -196,6 +201,7 @@ const addCrmCommandsDefinition = (program, options) => {
196
201
  ...(signal ? { signal } : {}),
197
202
  ...(opts.rescan ? { rescan: true } : {}),
198
203
  });
204
+ const stageTasks = await openStageTasks(run.store, run.account, now());
199
205
  const failed = report.synced.filter((one) => one.error !== undefined);
200
206
  // A kind that failed on a setting fails the same way again until the owner changes it: no retry is offered.
201
207
  const retried = failed.filter((one) => one.setting === undefined);
@@ -241,7 +247,7 @@ const addCrmCommandsDefinition = (program, options) => {
241
247
  })),
242
248
  ];
243
249
  const partial = report.state === "partial" || issues.length > 0;
244
- return itemOf(snakeKeys({ ...rest, ...(hint === undefined ? {} : { hint }) }), {
250
+ return itemOf(snakeKeys({ ...rest, stageTasks, ...(hint === undefined ? {} : { hint }) }), {
245
251
  ...(partial ? { meta: { complete: false, ...(issues.length ? { issues } : {}) } } : {}),
246
252
  ...(next ? { next } : {}),
247
253
  });
@@ -22,10 +22,10 @@ const DEFAULT_LIMIT = 20;
22
22
  export const addCrmSearchAll = (searches, { within, app, example, }) => {
23
23
  const all = annotate(new Command("all"), { effects: LOCAL_READ, partial: true, output: { entity: "hit" } })
24
24
  .summary("search stored deals and leads, messages, notes, calendar events and meetings")
25
- .description("search the CRM's deals and leads by the words of their title, and messages, notes, calendar events and " +
26
- "meetings other WireCat tools stored — best match first. Use it when you do not know where something was " +
27
- "written")
28
- .argument("<query...>", 'words and "phrases"; deals and leads match the words of their title')
25
+ .description("search the CRM's deals and leads by the words of their title, company and contacts, and messages, notes, " +
26
+ "calendar events and meetings other WireCat tools stored — best match first. Use it when you do not know " +
27
+ "where something was written")
28
+ .argument("<query...>", 'words and "phrases"; deals and leads match the words of their title, company and contacts')
29
29
  .addHelpText("after", SAVE_HELP);
30
30
  searches.addCommand(searchAllOptions(all, SEARCHED));
31
31
  example(all, "search all Example LLC", "search all website --only crm --json");
@@ -0,0 +1,8 @@
1
+ import type { MessageStore } from "../store/store.js";
2
+ import type { AccountKey } from "../store/types.js";
3
+ /**
4
+ * Opens the owner's task for each stage a deal or lead of the account entered that its `stage-tasks` setting names:
5
+ * one per entry, so a dismissed task never comes back and a later entry into the same stage opens a new one.
6
+ * Answers how many it opened.
7
+ */
8
+ export declare const openStageTasks: (store: MessageStore, account: AccountKey, now: number) => Promise<number>;
@@ -0,0 +1,42 @@
1
+ import { taskAccount } from "../services/task-rules.js";
2
+ import { createTaskService } from "../tasks/index.js";
3
+ const DAY = 86_400_000;
4
+ /**
5
+ * Opens the owner's task for each stage a deal or lead of the account entered that its `stage-tasks` setting names:
6
+ * one per entry, so a dismissed task never comes back and a later entry into the same stage opens a new one.
7
+ * Answers how many it opened.
8
+ */
9
+ export const openStageTasks = async (store, account, now) => {
10
+ const rules = await store.crm.stageTasks(account);
11
+ if (Object.keys(rules.deal).length + Object.keys(rules.lead).length === 0)
12
+ return 0;
13
+ const { moves, through } = await store.crm.stageMoves(account);
14
+ // Every deal entering a stage gets the same title, so the duplicate review would pair tasks of different deals.
15
+ const { reviewDuplicates: _review, ...tasks } = store.tasks;
16
+ const service = createTaskService({ store: tasks, now: () => new Date(now) });
17
+ let opened = 0;
18
+ for (const move of moves) {
19
+ const rule = rules[move.kind][move.stage];
20
+ if (!rule)
21
+ continue;
22
+ const item = await store.deals.get(move.ref);
23
+ const responsible = item.people.find((one) => one.role === "owner")?.name ??
24
+ (item.assignee === null ? "nobody" : `CRM user ${item.assignee.split("/").at(-1)}`);
25
+ const { created } = await service.add({
26
+ source: `${move.ref}/move/${move.id}`,
27
+ sourceKind: move.kind,
28
+ account: taskAccount(account),
29
+ group: move.ref,
30
+ kind: "request",
31
+ origin: "rule",
32
+ dueAt: new Date(now + rule.dueDays * DAY),
33
+ title: rule.title,
34
+ description: `${item.title} (${move.ref}) entered the stage ${move.stageName} of the pipeline ${move.pipelineName}. ` +
35
+ `Responsible: ${responsible}.`,
36
+ });
37
+ if (created)
38
+ opened += 1;
39
+ }
40
+ await store.crm.markStageMoves(account, through);
41
+ return opened;
42
+ };
@@ -8,6 +8,6 @@ export { columnName, sheetText } from "./attachments/sheets.js";
8
8
  export * from "./documents/index.js";
9
9
  export { isPublicAddress } from "./fetch/addresses.js";
10
10
  export { type FetchedPage, type FetchPageOptions, fetchPage, nodeTransport, PAGE_LIMITS, PAGE_USER_AGENT, type PageLimits, type PageLookup, type PageRequest, type PageResponse, type PageTransport, type ResolvedAddress, } from "./fetch/page.js";
11
- export { AI_PROVIDERS, type AiImageRefusal, type AiProvider, type AiSetting, type AiTextReader, type AiTextRefusal, aiImageReader, aiLeavesComputer, aiSettingPath, aiTextReader, readAiSetting, } from "./models/ai.js";
11
+ export { AI_PROVIDERS, type AiImageRefusal, type AiProvider, type AiSetting, type AiTextReader, type AiTextRefusal, aiImageReader, aiLeavesComputer, aiSettingPath, aiTextReader, readAiSetting, sharedModel, } from "./models/ai.js";
12
12
  export { registerReader } from "./readers/registry.js";
13
13
  export type { ReadContext, Reader, Section } from "./readers/types.js";
package/dist/documents.js CHANGED
@@ -6,5 +6,5 @@ export { columnName, sheetText } from "./attachments/sheets.js";
6
6
  export * from "./documents/index.js";
7
7
  export { isPublicAddress } from "./fetch/addresses.js";
8
8
  export { fetchPage, nodeTransport, PAGE_LIMITS, PAGE_USER_AGENT, } from "./fetch/page.js";
9
- export { AI_PROVIDERS, aiImageReader, aiLeavesComputer, aiSettingPath, aiTextReader, readAiSetting, } from "./models/ai.js";
9
+ export { AI_PROVIDERS, aiImageReader, aiLeavesComputer, aiSettingPath, aiTextReader, readAiSetting, sharedModel, } from "./models/ai.js";
10
10
  export { registerReader } from "./readers/registry.js";
@@ -40,6 +40,12 @@ export interface CrmItem {
40
40
  closedReason?: string | null;
41
41
  /** A company's id. */
42
42
  organization?: string | null;
43
+ /**
44
+ * A lead's own person and company, as the CRM keeps them on the item itself: a lead often has no contact or company
45
+ * linked yet, and these are then all it says of who it is.
46
+ */
47
+ contactName?: string | null;
48
+ companyName?: string | null;
43
49
  /**
44
50
  * Contacts on it, by their id, the part each plays and whether the CRM marks one its main contact. Left out, the CRM
45
51
  * did not say who is on it, and the people stored stay.
@@ -35,8 +35,9 @@ export declare const remoteModel: ({ model, baseUrl, dims, }: {
35
35
  export declare const remoteKey: ({ provider, model, dims }: RemoteModel) => string;
36
36
  export type Fetch = (url: string, init: RequestInit) => Promise<Response>;
37
37
  /** Up to `concurrency` requests at once; a 429 waits for `Retry-After`, a server error is tried again. */
38
- export declare const openRemote: (remote: RemoteModel, apiKey: string | undefined, { concurrency, fetch: post, tries }?: {
38
+ export declare const openRemote: (remote: RemoteModel, apiKey: string | undefined, { concurrency, fetch: post, tries, env, }: {
39
39
  concurrency?: number;
40
40
  fetch?: Fetch;
41
41
  tries?: number;
42
+ env?: NodeJS.ProcessEnv;
42
43
  }) => Embedder;
@@ -1,5 +1,7 @@
1
1
  import { setTimeout } from "node:timers/promises";
2
2
  import { CliError } from "@wirecat/cli-base";
3
+ import { onThisComputer } from "../models/endpoint.js";
4
+ import { refuseModelAddress } from "../models/local-only.js";
3
5
  import { unit } from "./embed.js";
4
6
  export const OPENAI_URL = "https://api.openai.com/v1";
5
7
  /** OpenAI's models, from its pricing page as read on 2026-10-02. */
@@ -10,9 +12,8 @@ export const OPENAI_MODELS = {
10
12
  export const DEFAULT_OPENAI_MODEL = "text-embedding-3-small";
11
13
  /** OpenAI's limits per request (2,048 inputs, 300,000 tokens); a chunk is at most ~400 tokens. */
12
14
  const PER_REQUEST = 256;
13
- const LOCAL = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
14
15
  /** A server on this machine: nothing leaves it, so nothing is asked. */
15
- export const isLocal = (baseUrl) => LOCAL.has(new URL(baseUrl).hostname);
16
+ export const isLocal = (baseUrl) => onThisComputer(baseUrl);
16
17
  export const remoteModel = ({ model = DEFAULT_OPENAI_MODEL, baseUrl, dims, }) => {
17
18
  const known = baseUrl === undefined ? OPENAI_MODELS[model] : undefined;
18
19
  if (baseUrl === undefined && !known) {
@@ -34,7 +35,8 @@ export const remoteModel = ({ model = DEFAULT_OPENAI_MODEL, baseUrl, dims, }) =>
34
35
  /** The vector key of a remote model, beside `local:<model>:<dims>`. */
35
36
  export const remoteKey = ({ provider, model, dims }) => `${provider}:${model}:${dims}`;
36
37
  /** Up to `concurrency` requests at once; a 429 waits for `Retry-After`, a server error is tried again. */
37
- export const openRemote = (remote, apiKey, { concurrency = 4, fetch: post = fetch, tries = 5 } = {}) => {
38
+ export const openRemote = (remote, apiKey, { concurrency = 4, fetch: post = fetch, tries = 5, env, }) => {
39
+ refuseModelAddress(env ?? process.env, remote.baseUrl, "text to embed");
38
40
  const request = async (input) => {
39
41
  for (let attempt = 1;; attempt++) {
40
42
  let response;
@@ -24,6 +24,9 @@ export declare const deal: v.StrictObjectSchema<{
24
24
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
25
25
  readonly owner: v.BooleanSchema<undefined>;
26
26
  }, undefined>, undefined>;
27
+ /** A CRM copy's own person and company as the CRM keeps them on it, such as a lead's with nobody linked yet. */
28
+ readonly contact_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
29
+ readonly company_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
27
30
  readonly currency: v.NullableSchema<v.StringSchema<undefined>, undefined>;
28
31
  readonly amount: v.NullableSchema<v.StringSchema<undefined>, undefined>;
29
32
  readonly close_date: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
@@ -90,6 +93,9 @@ export declare const lead: v.StrictObjectSchema<{
90
93
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
91
94
  readonly owner: v.BooleanSchema<undefined>;
92
95
  }, undefined>, undefined>;
96
+ /** A CRM copy's own person and company as the CRM keeps them on it, such as a lead's with nobody linked yet. */
97
+ readonly contact_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
98
+ readonly company_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
93
99
  readonly currency: v.NullableSchema<v.StringSchema<undefined>, undefined>;
94
100
  readonly amount: v.NullableSchema<v.StringSchema<undefined>, undefined>;
95
101
  readonly close_date: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
@@ -24,6 +24,9 @@ export const deal = v.strictObject({
24
24
  base_stage: v.nullable(v.strictObject({ ref: reference, name: text })),
25
25
  status: outcome,
26
26
  organization: v.nullable(party),
27
+ /** A CRM copy's own person and company as the CRM keeps them on it, such as a lead's with nobody linked yet. */
28
+ contact_name: nullableText,
29
+ company_name: nullableText,
27
30
  currency: nullableText,
28
31
  amount: nullableText,
29
32
  close_date: day,
@@ -256,6 +256,8 @@ export declare const ENTITIES: {
256
256
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
257
257
  readonly owner: v.BooleanSchema<undefined>;
258
258
  }, undefined>, undefined>;
259
+ readonly contact_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
260
+ readonly company_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
259
261
  readonly currency: v.NullableSchema<v.StringSchema<undefined>, undefined>;
260
262
  readonly amount: v.NullableSchema<v.StringSchema<undefined>, undefined>;
261
263
  readonly close_date: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
@@ -315,6 +317,8 @@ export declare const ENTITIES: {
315
317
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
316
318
  readonly owner: v.BooleanSchema<undefined>;
317
319
  }, undefined>, undefined>;
320
+ readonly contact_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
321
+ readonly company_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
318
322
  readonly currency: v.NullableSchema<v.StringSchema<undefined>, undefined>;
319
323
  readonly amount: v.NullableSchema<v.StringSchema<undefined>, undefined>;
320
324
  readonly close_date: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
@@ -63,6 +63,14 @@ const OTHERS = [
63
63
  ["model.offline", "permission_error", "downloading a model needs the network; --offline was requested"],
64
64
  ["model.key-rejected", "invalid_response", "the model provider refused the API key (401 or 403)"],
65
65
  ["model.unreachable", "invalid_response", "the model provider could not be reached over the network"],
66
+ validation("model.address-refused", "the model address must be https, or http only on this computer"),
67
+ [
68
+ "local-only.refused",
69
+ "permission_error",
70
+ "local only is on and the address is not on this computer; nothing was sent",
71
+ ],
72
+ ["local-only.owner-only", "permission_error", "only the owner turns local only off, not an agent"],
73
+ ["ai.images-not-allowed", "permission_error", "the AI model may not read pictures; models ai set --allow-remote"],
66
74
  [
67
75
  "ai.owner-only",
68
76
  "permission_error",