@wirecat/cli-core 0.608.0 → 0.610.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 (108) hide show
  1. package/CHANGELOG.md +124 -1
  2. package/dist/background/deliver.d.ts +12 -1
  3. package/dist/background/deliver.js +38 -5
  4. package/dist/background/report/render.d.ts +61 -0
  5. package/dist/background/report/render.js +208 -0
  6. package/dist/background/report/schema.d.ts +66 -0
  7. package/dist/background/report/schema.js +191 -0
  8. package/dist/background/report/templates/morning-digest.email.en.liquid +79 -0
  9. package/dist/background/report/templates/morning-digest.email.ru.liquid +79 -0
  10. package/dist/background/report/templates/morning-digest.telegram.en.liquid +77 -0
  11. package/dist/background/report/templates/morning-digest.telegram.ru.liquid +77 -0
  12. package/dist/background/report/templates/morning-digest.text.en.liquid +76 -0
  13. package/dist/background/report/templates/morning-digest.text.ru.liquid +76 -0
  14. package/dist/background/report/view.d.ts +88 -0
  15. package/dist/background/report/view.js +152 -0
  16. package/dist/background/schedules.d.ts +6 -1
  17. package/dist/background/schedules.js +24 -7
  18. package/dist/cli/embedding-choice.d.ts +4 -1
  19. package/dist/cli/embedding-choice.js +6 -3
  20. package/dist/cli/messenger/models-command.js +46 -18
  21. package/dist/cli/messenger/search-answers.js +23 -2
  22. package/dist/cli/model-catalogue-command.d.ts +33 -0
  23. package/dist/cli/model-catalogue-command.js +110 -21
  24. package/dist/cli/schedule/schedule-command.js +18 -0
  25. package/dist/cli/search-left-out.d.ts +1 -0
  26. package/dist/cli/search-left-out.js +2 -0
  27. package/dist/cli/store-settings.js +39 -3
  28. package/dist/crm/cli/csv.d.ts +18 -5
  29. package/dist/crm/cli/csv.js +30 -19
  30. package/dist/crm/cli/index.d.ts +1 -0
  31. package/dist/crm/cli/index.js +1 -0
  32. package/dist/domain/business.d.ts +3 -0
  33. package/dist/domain/business.js +2 -0
  34. package/dist/embeddings/models.d.ts +185 -5
  35. package/dist/embeddings/models.js +119 -5
  36. package/dist/entities/hit.d.ts +13 -2
  37. package/dist/entities/hit.js +10 -2
  38. package/dist/entities/index.d.ts +31 -1
  39. package/dist/entities/index.js +2 -1
  40. package/dist/entities/model.d.ts +42 -1
  41. package/dist/entities/model.js +20 -1
  42. package/dist/errors/reasons.js +4 -0
  43. package/dist/render/liquid.d.ts +14 -0
  44. package/dist/render/liquid.js +30 -0
  45. package/dist/replies/template.js +3 -22
  46. package/dist/search/account-list.d.ts +3 -2
  47. package/dist/search/account-list.js +5 -4
  48. package/dist/search/lucene/plain.js +4 -1
  49. package/dist/search/question-plan.js +2 -1
  50. package/dist/sends/permissions.js +4 -0
  51. package/dist/services/embeddings-maintenance.d.ts +1 -1
  52. package/dist/services/embeddings-maintenance.js +6 -6
  53. package/dist/services/index.d.ts +2 -0
  54. package/dist/services/index.js +2 -0
  55. package/dist/services/link-scorers/chat-senders.d.ts +2 -1
  56. package/dist/services/link-scorers/chat-senders.js +13 -4
  57. package/dist/services/link-scorers/types.d.ts +1 -1
  58. package/dist/services/meeting-model.d.ts +1 -1
  59. package/dist/services/meeting-model.js +4 -4
  60. package/dist/services/messages-meaning.js +25 -4
  61. package/dist/services/metadata.d.ts +1 -1
  62. package/dist/services/model-downloads.js +1 -1
  63. package/dist/services/notes-search.d.ts +1 -1
  64. package/dist/services/notes-search.js +2 -2
  65. package/dist/services/proposals/kinds/relationship.js +1 -0
  66. package/dist/services/proposals/registry.js +3 -1
  67. package/dist/services/proposals/types.d.ts +2 -0
  68. package/dist/services/search-all-business.d.ts +18 -0
  69. package/dist/services/search-all-business.js +38 -0
  70. package/dist/services/search-all-meetings.d.ts +1 -1
  71. package/dist/services/search-all-meetings.js +7 -2
  72. package/dist/services/search-all.d.ts +12 -6
  73. package/dist/services/search-all.js +48 -12
  74. package/dist/services/text-model-choice.d.ts +50 -0
  75. package/dist/services/text-model-choice.js +151 -0
  76. package/dist/store/exports.d.ts +3 -0
  77. package/dist/store/exports.js +3 -0
  78. package/dist/store/index.d.ts +5 -1
  79. package/dist/store/index.js +3 -0
  80. package/dist/store/sqlite/business-search.d.ts +44 -0
  81. package/dist/store/sqlite/business-search.js +141 -0
  82. package/dist/store/sqlite/finance.d.ts +12 -0
  83. package/dist/store/sqlite/finance.js +38 -2
  84. package/dist/store/sqlite/involvement-queue.d.ts +2 -7
  85. package/dist/store/sqlite/involvement-queue.js +11 -14
  86. package/dist/store/sqlite/money-lines.d.ts +12 -1
  87. package/dist/store/sqlite/money-lines.js +50 -4
  88. package/dist/store/sqlite/orders.js +5 -25
  89. package/dist/store/sqlite/owner-languages.d.ts +13 -0
  90. package/dist/store/sqlite/owner-languages.js +49 -0
  91. package/dist/store/sqlite/proposed-actions.d.ts +2 -0
  92. package/dist/store/sqlite/proposed-actions.js +4 -3
  93. package/dist/store/sqlite/records.d.ts +21 -0
  94. package/dist/store/sqlite/records.js +74 -13
  95. package/dist/store/sqlite/ref-summaries.d.ts +3 -1
  96. package/dist/store/sqlite/ref-summaries.js +4 -1
  97. package/dist/store/sqlite/reported-relations.d.ts +1 -0
  98. package/dist/store/sqlite/reported-relations.js +5 -1
  99. package/dist/store/sqlite/vectors.d.ts +2 -0
  100. package/dist/store/sqlite/vectors.js +5 -0
  101. package/dist/store/store.d.ts +2 -0
  102. package/dist/store/store.js +4 -4
  103. package/dist/store/vectors.d.ts +2 -0
  104. package/dist/store/vectors.js +1 -0
  105. package/dist/terminal/prompt.d.ts +4 -0
  106. package/dist/terminal/prompt.js +21 -2
  107. package/package.json +2 -2
  108. package/parity.json +13 -0
package/CHANGELOG.md CHANGED
@@ -5,7 +5,130 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
- ## Unreleased
8
+ ## 0.610.0 — 08.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A scan's group senders can be found and decided together.** `chat-senders@3` names the chat and its size in its
13
+ reason ("wrote 40 messages in «Sales» (25 people) since 2026-08-10"), and its evidence leads with the chat's ref.
14
+ `ProposalFilter.via` keeps the proposals whose evidence holds a reference, and `store.proposedActions.list` takes
15
+ `evidence` to filter in the query, so `via` pages stored relationship proposals in full. A pending `chat-senders@2`
16
+ proposal takes the new reason and evidence on the next scan, under the same id.
17
+ - **`search all` has a `business` lane.** `searchAll` finds invoices, payments, orders, contracts, subscriptions,
18
+ products and wallets by the words of their numbers and names (an invoice's counterparty, a payment's payer or payee,
19
+ an order's shop and lines), each word where a word starts, folded in memory like the `crm` lane, with no index.
20
+ Each hit carries its `review` (`proposed` or `confirmed`). A row an import made (its `source` is
21
+ `import:<provider>`) carries `source_record` (`provider`, `account`, `external_id`): the oldest live record that
22
+ maps to it, else the oldest deleted one, which also decides its account; the owner's and agents' rows are
23
+ `business:internal`. `scope.business` and `--source` read the import accounts they name. Transactions, `custom:`
24
+ records and rejected rows are left out. `store.business.find` and `store.business.accounts` back it.
25
+ - **Permission key `business.list`** (or `business`): a profile that denies it leaves the `business` lane out of
26
+ `search all` and says so under `missing`, as `deals.list` does for deals (`deniedKinds`). memo reads the lane by
27
+ default once it takes this release; that key turns it off.
28
+ - **`store.finance.addInvoiceLine` and `removeInvoiceLine` change an invoice's lines, as `store.orders` does an
29
+ order's.** A `product` reference copies the product's name and price, and a later price change leaves the line as it
30
+ is. The owner changes any invoice's lines but a void, rejected or deleted one's; a bot only those of an invoice it
31
+ proposed that is still proposed (`finance.owner-only`). The total follows the lines, and the status follows the total
32
+ against what confirmed payments settled. Refused: removing the last line (`finance.line`), a position with no line
33
+ (`finance.no-line`), and lines totalling less than is paid (`finance.below-paid`).
34
+ - **`store.records.list` takes `entity`, `batch` and `deleted`, and `store.records.incoming` lists what points at a
35
+ record or an entity**, for a `records show` that shows relations both ways. `entity` is a ref and lists the records
36
+ mapped to it; `batch` is a `batch_id`; `deleted: true` lists only deleted records, `false` only live ones, and left
37
+ out lists both, as before. `incoming(key)` gives the live records whose relations resolve to that record;
38
+ `incoming({ entity })` those naming the entity by ref, from every account, and those resolved to a record mapped to
39
+ it. Each names its record's provider, account, type and id, with the role, `as` and `amount`.
40
+
41
+ ### Changed — may break callers
42
+
43
+ - **`RESOURCES_SEARCHED` ends with `business`**, so `searchAll` and `searchAllWithMeetings` read it when `only` is
44
+ left out, and `SearchAllItem.kind` and the `hit` entity's `kind` take `invoice`, `payment`, `order`, `contract`,
45
+ `subscription`, `product` and `wallet`. A switch over hit kinds needs those branches; pass `only` to keep the old
46
+ lanes. The source tools' `search all` (`SOURCE_SEARCHED`) is unchanged.
47
+ - **`MessageStore.business` is a new required member**: a hand-made store object or test double needs it.
48
+ - **`SearchedResource`, `ResourceWithMeetings` and `SearchAllRequest.scope` take `business`**, and the strict `hit`
49
+ entity takes `review` and `source_record`; an exhaustive switch or a copy of the schema needs them.
50
+
51
+ ### Fixed
52
+
53
+ - **A hidden prompt asks again when nothing arrived.** `readSecret` at a terminal took an empty Enter as the answer,
54
+ so a paste that never landed (Ctrl+V in a Linux terminal) failed at once with "no token was given", and the hidden
55
+ input showed nothing to tell it apart from a paste that worked. An empty hidden answer now prints "Nothing arrived.
56
+ To paste in a terminal, use Ctrl+Shift+V (or right-click → Paste)." (Cmd+V on macOS) and asks again, up to three
57
+ times, then fails with `validation_error`, reason `input.empty`. A piped empty answer still comes back empty at once,
58
+ an echoed prompt keeps its empty answer, and Ctrl-C still cancels at once.
59
+
60
+ - **A large CRM sync takes a third less time and a sixth of the memory** (#2682). Keeping the involvement index
61
+ current built a new SQL text for every item it recomputed, so SQLite prepared each one again and the process kept
62
+ them all. The item's id is now a bound parameter, one statement per kind of item. On the same synthetic data, the
63
+ 20,000 sync peaks at 0.6 GB instead of 3.7 GB and takes 19 s instead of 30 s, its `--rescan` 13 s instead of 21 s.
64
+
65
+ ## 0.609.0 — 08.11.2026
66
+
67
+ ### Added
68
+
69
+ - **`models set <id>` chooses the local embedding model for every WireCat CLI**, kept in the shared settings file:
70
+ every embed and every search by meaning uses it, and `models list` marks it `default`. It refuses a model that is
71
+ not downloaded, and says how many chunks the new model still lacks and about how long that takes. Vectors stay
72
+ per model, so a switch deletes nothing and switching back is instant. It asks nothing, over MCP too (permission
73
+ `models.set` is `allow`); `models add` needs `mcp.authority` there.
74
+ - **`e5-large`**, multilingual-e5-large 8-bit (MIT, 579 MB, 1024 dims), the large one beside `e5-small` (small) and
75
+ `embeddinggemma` (medium). `models list --json` gives each text model's `size`, `dims`, `terms` and
76
+ `chunks_per_second`.
77
+ - **`models add <id> --payload '<json>'` adds an ONNX embedding model from Hugging Face**, pinned to a commit with
78
+ each file's sha256, in the same shape as the built-in models. Its vectors' key carries its weights' hash.
79
+ - `chosenTextModel`, `textModels` and `useTextModel` from `@wirecat/cli-core/services`; `store.vectors.vectorCounts`.
80
+ - **`config set owner_languages ru,en` says which languages the owner reads**, store-wide and offered by every
81
+ WireCat CLI, not only the messengers: ISO 639-1 codes in his order, each once; `ru` when unset. The first is the
82
+ language everything written for him is in; a title quoted in a later one stays untranslated. An unknown code is
83
+ refused by name. `ownerLanguages(database)` from `@wirecat/cli-core/store` reads it, primary first, with
84
+ `DEFAULT_OWNER_LANGUAGES`. A scheduled agent's report is rendered in the first language.
85
+ - **A CLI's own CRM list can print the same `--format csv` table as `deals list`.** `@wirecat/cli-core/crm/cli`
86
+ exports `csvFormatOption`, `refuseCsvConflict` (the refusal of another output or an agent's run, checked before
87
+ the CRM is read), `csvColumnPaths` (`--json=a,b`, or the caller's own default columns) and `printCsv`, with
88
+ `DEAL_CSV_COLUMNS` and the `CsvPage` and `CsvField` types. `deals list` and `leads list` print through them.
89
+ - **A scheduled agent that answers with a `wirecat.report/1` document gets a rendered message, not its raw text.**
90
+ The document is one JSON object, bare or as the only fenced `json` block: dated sections (`today`, `decisions`,
91
+ `money`, `meetings`, `projects`, `mail`) of typed items, and stale sources in `health`. The Telegram route gets
92
+ HTML from a template shipped for the owner's first language (`owner_languages`; `ru` and `en`, English words for
93
+ any other), fitted under 4 096 characters by dropping the last item of the largest section, so no file is sent;
94
+ mail gets the plain-text rendering with its title as the subject; `latest.txt` beside `latest.md` keeps the same
95
+ text. Agent text is escaped before a template sees it, and after rendering only `b`, `i` and `a` survive for
96
+ Telegram (`div p b i a br span` with `style` for email), each `href` only to a link the renderer built. Store
97
+ references, backticks, `--flags` and snake_case words are taken out of agent text and counted as `report.leaks`
98
+ in `last.json`. A document that fails the check is never shown: each route gets one line in the owner's language,
99
+ with `delivery.report-invalid`. Any other answer keeps the Markdown path.
100
+
101
+ ### Changed — may break callers
102
+
103
+ - **A search with no letter or digit is refused** (`validation_error`, "search needs a letter or a digit to look
104
+ for"). `""`, a lone `?`, `()` or an emoji alone found nothing and said nothing; `-` and `+` alone were refused
105
+ before as a syntax error. A lone `*` still reads as a wildcard.
106
+
107
+ ### Fixed
108
+
109
+ - **`search all` no longer gives each source half of a ten-hit page.** Each source's best hit comes first, then every
110
+ other hit by its cosine to the question, then by its rank in its source. Ordered by rank first, the sources took
111
+ turns, so a mail at its third to fifth place fell off the page behind notes that matched far less.
112
+ - **Mail looks up by meaning with the text notes embed for the same question.** It embedded the words a picture
113
+ search keeps, which drop a question mark and a time (`10:30`), so mail and note cosines did not compare. A query
114
+ that leaves notes nothing to embed (`content:invoice`, `budg*`) keeps the old words for mail.
115
+ - **A question with a time or a `word:word` in it is searched by its words again.** Without a meaning model,
116
+ `search all`, `search notes` and `events search` sent "When is the steering committee? Answer as HH:MM" to strict
117
+ search, which needs every word in one record, so it found nothing. The quoting that keeps `HH:MM` and `10:30`
118
+ literal made the question look like a quoted phrase; a quoted single word now counts as a word of the question.
119
+ A quoted phrase of several words still sends the question to strict search.
120
+ - **`search all` says which word found nothing when every word was needed and nothing was found.** For two to
121
+ eight plain words, each word is looked up alone, only when the answer is empty; `missing` then names the word,
122
+ such as "every word must be in one record, and nothing in messages, notes holds "xyzzy"", and `SearchAllFound`
123
+ carries it as `unmatched`. Results and ranking do not change.
124
+ - **Search by meaning and every embed follow the chosen model.** Notes, mail, events, discovery's meaning lane,
125
+ `search all` and the message vectors of `conversations rebuild` used e5-small whatever was set; a CLI with no
126
+ `embedding_model` setting (memo) could not use another model at all.
127
+ - **A CSV cell prints a phone or an e-mail by its value**, where an object without a `name` was printed as JSON.
128
+ - **A CRM sync no longer slows down with every deal it saves** (#2623). Looking up a reported relationship read every
129
+ link of its busier end, such as a deal owner with thousands of deals, because SQLite could not use the
130
+ relationship's unique key. On synthetic data with 10 deal owners, a first sync of 20,000 deals, 10,000 leads and
131
+ 20,000 contacts takes 30 s instead of 61 s, and a `--rescan` 21 s instead of 71 s.
9
132
 
10
133
  ## 0.608.0 — 08.11.2026
11
134
 
@@ -23,11 +23,13 @@ export declare const DELIVERY_REASONS: {
23
23
  readonly timeout: "delivery.timeout";
24
24
  readonly failed: "delivery.failed";
25
25
  readonly htmlFallback: "delivery.html-fallback";
26
+ readonly reportInvalid: "delivery.report-invalid";
26
27
  };
27
28
  export type DeliveryReason = (typeof DELIVERY_REASONS)[keyof typeof DELIVERY_REASONS];
28
29
  /**
29
30
  * One route's outcome, kept in `last.json`. `error` is the sending CLI's error code and reason id, never its message.
30
- * A send that went as plain text because Telegram refused the HTML is `ok` with the `html-fallback` reason.
31
+ * A send that went as plain text because Telegram refused the HTML is `ok` with the `html-fallback` reason, and the
32
+ * one line sent in place of a report that failed its check is `ok` with `report-invalid`.
31
33
  */
32
34
  export interface Delivery {
33
35
  to: string;
@@ -49,6 +51,15 @@ export interface Parcel {
49
51
  };
50
52
  /** A failed run: one line, no file. */
51
53
  line?: string;
54
+ /** A report document, already rendered: the file and the title are not sent. */
55
+ rendered?: RenderedParcel;
56
+ }
57
+ export interface RenderedParcel {
58
+ telegram: string;
59
+ text: string;
60
+ subject: string;
61
+ /** The report failed its check and `text` is the one line that says so. */
62
+ invalid: boolean;
52
63
  }
53
64
  /** The caption as HTML: the head is cut in Markdown, where no tag can be split, and cut shorter until its HTML fits. */
54
65
  export declare const htmlHeadOf: (title: string, report: string, limit?: number) => string;
@@ -38,6 +38,7 @@ export const DELIVERY_REASONS = {
38
38
  timeout: "delivery.timeout",
39
39
  failed: "delivery.failed",
40
40
  htmlFallback: "delivery.html-fallback",
41
+ reportInvalid: "delivery.report-invalid",
41
42
  };
42
43
  /** Telegram's limits, in UTF-16 units as JavaScript counts them: a message's text, and a file's caption. */
43
44
  export const TELEGRAM_TEXT_CHARS = 4096;
@@ -69,6 +70,30 @@ const codeOf = (stderr) => {
69
70
  catch { }
70
71
  }
71
72
  };
73
+ /** Plain text for a bot when Telegram refused the HTML, cut where a line ends. */
74
+ const plainFit = (text) => {
75
+ if (text.length <= TELEGRAM_TEXT_CHARS)
76
+ return text;
77
+ const cut = text.slice(0, TELEGRAM_TEXT_CHARS - 2);
78
+ const line = cut.lastIndexOf("\n");
79
+ return `${line > 0 ? cut.slice(0, line) : cut}\n…`;
80
+ };
81
+ /** A rendered report needs no file: Telegram's text was fitted when it was rendered, and mail has no limit. */
82
+ const renderedArgvOf = (program, route, rendered, plain = false) => {
83
+ const lead = [program, route.profile, "--json", "--no-input"];
84
+ if (route.kind === "email")
85
+ return [...lead, "messages", "send", "--to", route.address, "--subject", rendered.subject];
86
+ return [
87
+ ...lead,
88
+ "bot",
89
+ "messages",
90
+ "send",
91
+ ...(plain ? [] : ["--html"]),
92
+ "--",
93
+ route.chat,
94
+ plain ? plainFit(rendered.text) : rendered.telegram,
95
+ ];
96
+ };
72
97
  const textOf = (title, report) => (report.trim() ? `${title}\n${report.trim()}` : title);
73
98
  /** The same text as Telegram HTML; the length that counts against the limits is this one. */
74
99
  const htmlOf = (title, report) => toTelegramHtml(textOf(title, report));
@@ -140,7 +165,8 @@ export const deliver = async (system, env, routes, parcel, { find, errorOf, lock
140
165
  out.push(failed(to, DELIVERY_REASONS.programMissing, command));
141
166
  continue;
142
167
  }
143
- const tooLong = route.kind === "telegram-bot" && htmlOf(parcel.title, report).length > TELEGRAM_TEXT_CHARS;
168
+ const { rendered } = parcel;
169
+ const tooLong = !rendered && route.kind === "telegram-bot" && htmlOf(parcel.title, report).length > TELEGRAM_TEXT_CHARS;
144
170
  // The sending CLI refuses its own and the other WireCat folders, where the report lives, so it gets a copy.
145
171
  const folder = route.kind === "telegram-bot" && parcel.file && tooLong ? mkdtempSync(join(tmpdir(), "wirecat-deliver-")) : "";
146
172
  const copy = folder && parcel.file ? join(folder, parcel.file.name) : undefined;
@@ -150,19 +176,26 @@ export const deliver = async (system, env, routes, parcel, { find, errorOf, lock
150
176
  const { [`${prefix}_PROFILE`]: _, ...childEnv } = env;
151
177
  const options = {
152
178
  timeoutMs,
153
- ...(route.kind === "email" ? { input: report.trim() ? report : parcel.title } : {}),
179
+ ...(route.kind === "email" ? { input: rendered ? rendered.text : report.trim() ? report : parcel.title } : {}),
154
180
  };
155
- let ran = await system.run(argvOf(program, route, parcel.title, report, copy), childEnv, options);
181
+ const argv = (plain = false) => rendered
182
+ ? renderedArgvOf(program, route, rendered, plain)
183
+ : argvOf(program, route, parcel.title, report, copy, plain);
184
+ let ran = await system.run(argv(), childEnv, options);
156
185
  let fellBack = "";
157
186
  if (route.kind === "telegram-bot" &&
158
187
  ran.code !== 0 &&
159
188
  ran.code !== TIMED_OUT &&
160
189
  codeOf(ran.stderr) === REFUSED_CONTENT) {
161
190
  fellBack = errorOf(ran.stderr, ran.code);
162
- ran = await system.run(argvOf(program, route, parcel.title, report, copy, true), childEnv, options);
191
+ ran = await system.run(argv(true), childEnv, options);
163
192
  }
164
193
  if (ran.code === 0) {
165
- out.push(fellBack ? { to, ok: true, reason: DELIVERY_REASONS.htmlFallback, error: fellBack } : { to, ok: true });
194
+ out.push(rendered?.invalid
195
+ ? { to, ok: true, reason: DELIVERY_REASONS.reportInvalid }
196
+ : fellBack
197
+ ? { to, ok: true, reason: DELIVERY_REASONS.htmlFallback, error: fellBack }
198
+ : { to, ok: true });
166
199
  }
167
200
  else if (ran.code === TIMED_OUT)
168
201
  out.push(failed(to, DELIVERY_REASONS.timeout));
@@ -0,0 +1,61 @@
1
+ import { type ReportView } from "./view.js";
2
+ export declare const REPORT_CHANNELS: readonly ["telegram", "email", "text"];
3
+ export type ReportChannel = (typeof REPORT_CHANNELS)[number];
4
+ export declare const REPORT_REASONS: {
5
+ readonly invalid: "delivery.report-invalid";
6
+ readonly templateFailed: "report.template-failed";
7
+ readonly templateTags: "report.template-tags";
8
+ };
9
+ /** The template shipped with cli-core for that report kind and channel, in `language` or else in English. */
10
+ export declare const defaultTemplate: (kind: string, channel: ReportChannel, language: string) => string;
11
+ /**
12
+ * What a template's HTML may keep, enforced after it rendered: the channel's tags and attributes only, a `style`
13
+ * with no `url(`, and an `href` only to a URL of the view model. Anything else goes, its text kept; `changed` counts
14
+ * what went.
15
+ */
16
+ export declare const sanitizeHtml: (channel: Exclude<ReportChannel, "text">, html: string, urls: ReadonlySet<string>) => {
17
+ html: string;
18
+ changed: number;
19
+ };
20
+ export interface Rendering {
21
+ text: string;
22
+ /** The override template failed and the default was used. */
23
+ templateFailed: boolean;
24
+ /** Tags or attributes the platform rules took out. */
25
+ templateTags: number;
26
+ }
27
+ /**
28
+ * One channel's text of a report. A failing `template` (a stored override, later) falls back to the shipped one for
29
+ * this channel only. Telegram is rendered again with an item fewer, from the largest section, until it fits.
30
+ */
31
+ export declare const renderReport: (view: ReportView, channel: ReportChannel, { template }?: {
32
+ template?: string;
33
+ }) => Promise<Rendering>;
34
+ /** What `last.json` keeps of a report run, beside the deliveries. */
35
+ export interface ReportRun {
36
+ language: string;
37
+ /** Store references, backticks, flags and snake_case words taken out of the agent's text. */
38
+ leaks: number;
39
+ /** The path of the first field that failed the check; nothing was shown. */
40
+ invalid?: string;
41
+ reasons?: string[];
42
+ }
43
+ export interface PreparedReport {
44
+ telegram: string;
45
+ text: string;
46
+ subject: string;
47
+ /** The desktop notice: the title line and the summary. */
48
+ notice: string;
49
+ invalid: boolean;
50
+ run: ReportRun;
51
+ }
52
+ /**
53
+ * A run's answer rendered for every route, or `undefined` when it is not a report. An invalid report becomes one
54
+ * line in the owner's language and is never shown raw.
55
+ */
56
+ export declare const prepareReport: (answer: string, { language, now, timeZone, templates, }: {
57
+ language: string;
58
+ now: number;
59
+ timeZone?: string;
60
+ templates?: Partial<Record<ReportChannel, string>>;
61
+ }) => Promise<PreparedReport | undefined>;
@@ -0,0 +1,208 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import { safeLiquid } from "../../render/liquid.js";
4
+ import { TELEGRAM_TEXT_CHARS } from "../deliver.js";
5
+ import { parseReport } from "./schema.js";
6
+ import { reportView } from "./view.js";
7
+ export const REPORT_CHANNELS = ["telegram", "email", "text"];
8
+ const DEFAULT_LANGUAGE = "en";
9
+ const LIMITS = { parse: 65_536, memory: 4_000_000, milliseconds: 1_000 };
10
+ export const REPORT_REASONS = {
11
+ invalid: "delivery.report-invalid",
12
+ templateFailed: "report.template-failed",
13
+ templateTags: "report.template-tags",
14
+ };
15
+ const templateFile = (kind, channel, language) => fileURLToPath(new URL(`./templates/${kind}.${channel}.${language}.liquid`, import.meta.url));
16
+ /** The template shipped with cli-core for that report kind and channel, in `language` or else in English. */
17
+ export const defaultTemplate = (kind, channel, language) => {
18
+ const file = templateFile(kind, channel, language);
19
+ return readFileSync(existsSync(file) ? file : templateFile(kind, channel, DEFAULT_LANGUAGE), "utf8");
20
+ };
21
+ const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" };
22
+ const escapeHtml = (text) => text.replace(/[&<>"]/g, (one) => ESCAPES[one]);
23
+ const escapedDeep = (value) => typeof value === "string"
24
+ ? escapeHtml(value)
25
+ : Array.isArray(value)
26
+ ? value.map(escapedDeep)
27
+ : value && typeof value === "object"
28
+ ? Object.fromEntries(Object.entries(value).map(([key, one]) => [key, escapedDeep(one)]))
29
+ : value;
30
+ const ALLOWED = {
31
+ telegram: { b: [], i: [], a: ["href"] },
32
+ email: {
33
+ div: ["style"],
34
+ p: ["style"],
35
+ b: ["style"],
36
+ i: ["style"],
37
+ a: ["href", "style"],
38
+ br: [],
39
+ span: ["style"],
40
+ },
41
+ };
42
+ const linkUrls = (view) => new Set([
43
+ ...view.links,
44
+ ...view.sections.flatMap((section) => section.items.flatMap((item) => item.links)),
45
+ ...view.health.items.flatMap((item) => item.links),
46
+ ].map((link) => link.url));
47
+ /**
48
+ * What a template's HTML may keep, enforced after it rendered: the channel's tags and attributes only, a `style`
49
+ * with no `url(`, and an `href` only to a URL of the view model. Anything else goes, its text kept; `changed` counts
50
+ * what went.
51
+ */
52
+ export const sanitizeHtml = (channel, html, urls) => {
53
+ const allowed = ALLOWED[channel];
54
+ let changed = 0;
55
+ const dropped = [];
56
+ const withoutBlocks = html.replace(/<(script|style|iframe|object)\b[\s\S]*?(<\/\1\s*>|$)/gi, () => {
57
+ changed++;
58
+ return "";
59
+ });
60
+ const out = withoutBlocks.replace(/<(\/?)([a-zA-Z][a-zA-Z0-9]*)\b([^<>]*)>|[<>]/g, (tag, close, name, rest) => {
61
+ if (name === undefined) {
62
+ changed++;
63
+ return escapeHtml(tag);
64
+ }
65
+ const lower = String(name).toLowerCase();
66
+ const attributes = allowed[lower];
67
+ if (close) {
68
+ if (lower === "a" && dropped.pop())
69
+ return "";
70
+ if (!attributes)
71
+ changed++;
72
+ return attributes ? `</${lower}>` : "";
73
+ }
74
+ if (!attributes) {
75
+ changed++;
76
+ return "";
77
+ }
78
+ const kept = [];
79
+ const all = [...String(rest).matchAll(/([a-zA-Z-]+)\s*=\s*"([^"]*)"/g)];
80
+ if (all.length !== (String(rest).match(/=/g)?.length ?? 0))
81
+ changed++;
82
+ for (const [, key = "", value = ""] of all) {
83
+ const attribute = key.toLowerCase();
84
+ const unescaped = value.replace(/&amp;/g, "&");
85
+ if (!attributes.includes(attribute))
86
+ changed++;
87
+ else if (attribute === "href" && !urls.has(unescaped))
88
+ changed++;
89
+ else if (attribute === "style" && /url\(|expression\(|javascript:/i.test(value))
90
+ changed++;
91
+ else
92
+ kept.push(`${attribute}="${value}"`);
93
+ }
94
+ if (lower === "a") {
95
+ const linked = kept.some((one) => one.startsWith("href="));
96
+ dropped.push(!linked);
97
+ if (!linked)
98
+ return "";
99
+ }
100
+ return `<${lower}${kept.map((one) => ` ${one}`).join("")}>`;
101
+ });
102
+ return { html: out, changed };
103
+ };
104
+ const renderOnce = async (view, channel, source) => {
105
+ const engine = safeLiquid(LIMITS);
106
+ if (channel !== "text")
107
+ // These would turn text an agent wrote back into markup after it was escaped.
108
+ for (const name of ["raw", "url_decode", "base64_decode"])
109
+ engine.registerFilter(name, (x) => x);
110
+ const scope = (channel === "text" ? view : escapedDeep(view));
111
+ const rendered = String(await engine.parseAndRender(source, scope)).trim();
112
+ if (!rendered)
113
+ throw new Error("empty");
114
+ if (channel === "text")
115
+ return { text: rendered, templateTags: 0 };
116
+ const { html, changed } = sanitizeHtml(channel, rendered, linkUrls(view));
117
+ return { text: html, templateTags: changed };
118
+ };
119
+ const renderWithFallback = async (view, channel, template) => {
120
+ const shipped = () => renderOnce(view, channel, defaultTemplate(view.kind, channel, view.language));
121
+ if (template === undefined)
122
+ return { ...(await shipped()), templateFailed: false };
123
+ try {
124
+ return { ...(await renderOnce(view, channel, template)), templateFailed: false };
125
+ }
126
+ catch {
127
+ return { ...(await shipped()), templateFailed: true };
128
+ }
129
+ };
130
+ /** The view with one item fewer: the last of the largest section, counted in that section's `more`. */
131
+ const dropOne = (view) => {
132
+ const lists = [...view.sections.map((section) => section.items.length), view.health.items.length];
133
+ const largest = lists.reduce((most, one) => Math.max(most, one), 0);
134
+ if (largest === 0)
135
+ return undefined;
136
+ const at = lists.lastIndexOf(largest);
137
+ if (at === view.sections.length)
138
+ return {
139
+ ...view,
140
+ health: { ...view.health, items: view.health.items.slice(0, -1), more: view.health.more + 1 },
141
+ };
142
+ return {
143
+ ...view,
144
+ sections: view.sections.map((section, s) => s === at ? { ...section, items: section.items.slice(0, -1), more: section.more + 1 } : section),
145
+ };
146
+ };
147
+ /**
148
+ * One channel's text of a report. A failing `template` (a stored override, later) falls back to the shipped one for
149
+ * this channel only. Telegram is rendered again with an item fewer, from the largest section, until it fits.
150
+ */
151
+ export const renderReport = async (view, channel, { template } = {}) => {
152
+ let current = view;
153
+ let source = template;
154
+ for (;;) {
155
+ const rendering = await renderWithFallback(current, channel, source);
156
+ if (rendering.templateFailed)
157
+ source = undefined;
158
+ const smaller = channel === "telegram" && rendering.text.length > TELEGRAM_TEXT_CHARS ? dropOne(current) : undefined;
159
+ if (!smaller)
160
+ return { ...rendering, templateFailed: rendering.templateFailed || source !== template };
161
+ current = smaller;
162
+ }
163
+ };
164
+ const INVALID_LINES = {
165
+ ru: "Сводка не собралась: ошибка формата. Подробности в WireCat.",
166
+ en: "The report could not be built: format error. Details in WireCat.",
167
+ };
168
+ /**
169
+ * A run's answer rendered for every route, or `undefined` when it is not a report. An invalid report becomes one
170
+ * line in the owner's language and is never shown raw.
171
+ */
172
+ export const prepareReport = async (answer, { language, now, timeZone, templates = {}, }) => {
173
+ const parsed = parseReport(answer);
174
+ if (!parsed)
175
+ return undefined;
176
+ if ("invalid" in parsed) {
177
+ const line = INVALID_LINES[language] ?? INVALID_LINES[DEFAULT_LANGUAGE];
178
+ return {
179
+ telegram: escapeHtml(line),
180
+ text: line,
181
+ subject: line,
182
+ notice: line,
183
+ invalid: true,
184
+ run: { language, leaks: 0, invalid: parsed.invalid, reasons: [REPORT_REASONS.invalid] },
185
+ };
186
+ }
187
+ const shipped = existsSync(templateFile(parsed.report.kind, "telegram", language)) ? language : DEFAULT_LANGUAGE;
188
+ const view = reportView(parsed.report, { language: shipped, now, ...(timeZone ? { timeZone } : {}) });
189
+ const telegram = await renderReport(view, "telegram", templateOf(templates, "telegram"));
190
+ const text = await renderReport(view, "text", templateOf(templates, "text"));
191
+ const reasons = [
192
+ ...(telegram.templateFailed || text.templateFailed ? [REPORT_REASONS.templateFailed] : []),
193
+ ...(telegram.templateTags + text.templateTags > 0 ? [REPORT_REASONS.templateTags] : []),
194
+ ];
195
+ const title = text.text.split("\n")[0] ?? "";
196
+ return {
197
+ telegram: telegram.text,
198
+ text: text.text,
199
+ subject: title,
200
+ notice: [title, parsed.report.summary].filter(Boolean).join("\n"),
201
+ invalid: false,
202
+ run: { language: shipped, leaks: parsed.leaks, ...(reasons.length ? { reasons } : {}) },
203
+ };
204
+ };
205
+ const templateOf = (templates, channel) => {
206
+ const template = templates[channel];
207
+ return template === undefined ? {} : { template };
208
+ };
@@ -0,0 +1,66 @@
1
+ export declare const REPORT_FORMAT = "wirecat.report/1";
2
+ export declare const REPORT_KINDS: readonly ["morning-digest"];
3
+ export type ReportKind = (typeof REPORT_KINDS)[number];
4
+ /** In the order they are shown; `health` is not among them, it comes from the document's `health[]` only. */
5
+ export declare const SECTION_KINDS: readonly ["today", "decisions", "money", "meetings", "projects", "mail"];
6
+ export type SectionKind = (typeof SECTION_KINDS)[number];
7
+ export declare const ITEM_TYPES: readonly ["reply", "question", "task", "fact", "risk", "money", "decision", "meeting"];
8
+ export type ItemType = (typeof ITEM_TYPES)[number];
9
+ export declare const CHANNEL_KINDS: readonly ["telegram", "max", "whatsapp", "mail", "meeting", "task"];
10
+ export type ChannelKind = (typeof CHANNEL_KINDS)[number];
11
+ export interface Amount {
12
+ value: number;
13
+ currency: string;
14
+ direction: "in" | "out";
15
+ }
16
+ export interface ReportItem {
17
+ type: ItemType;
18
+ who: string | null;
19
+ topic: string | null;
20
+ action: string | null;
21
+ detail: string | null;
22
+ quote: string | null;
23
+ since: string | null;
24
+ due: string | null;
25
+ time: string | null;
26
+ amount: Amount | null;
27
+ count: number | null;
28
+ priority: "high" | "normal";
29
+ channel: ChannelKind | null;
30
+ refs: string[];
31
+ }
32
+ export interface ReportSection {
33
+ kind: SectionKind;
34
+ items: ReportItem[];
35
+ more: number;
36
+ }
37
+ export interface HealthEntry {
38
+ source: string;
39
+ staleHours: number;
40
+ refs: string[];
41
+ }
42
+ /** A `wirecat.report/1` document as the renderers read it: checked, cut to its limits, with no `links` or `internal`. */
43
+ export interface Report {
44
+ kind: ReportKind;
45
+ date: string;
46
+ summary: string | null;
47
+ sections: ReportSection[];
48
+ health: HealthEntry[];
49
+ }
50
+ /** What a leak pattern removed from agent text: a store reference, backticks, a `--flag` or a snake_case word. */
51
+ export declare const withoutLeaks: (text: string) => {
52
+ text: string;
53
+ leaks: number;
54
+ };
55
+ export type ParsedReport = {
56
+ report: Report;
57
+ leaks: number;
58
+ } | {
59
+ invalid: string;
60
+ };
61
+ /**
62
+ * A run's answer as a report: one JSON object, bare or as the only fenced `json` block. Text that is neither is not a
63
+ * report (`undefined`) and keeps the Markdown path; a JSON answer that fails the check is `invalid`, with the path
64
+ * of the first field that failed, and is never shown.
65
+ */
66
+ export declare const parseReport: (answer: string) => ParsedReport | undefined;