@wirecat/cli-core 0.607.0 → 0.609.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 (69) hide show
  1. package/CHANGELOG.md +77 -0
  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 +11 -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/store-settings.js +39 -3
  26. package/dist/crm/cli/csv.d.ts +18 -5
  27. package/dist/crm/cli/csv.js +30 -19
  28. package/dist/crm/cli/index.d.ts +1 -0
  29. package/dist/crm/cli/index.js +1 -0
  30. package/dist/embeddings/models.d.ts +185 -5
  31. package/dist/embeddings/models.js +119 -5
  32. package/dist/entities/index.d.ts +24 -0
  33. package/dist/entities/index.js +2 -1
  34. package/dist/entities/model.d.ts +42 -1
  35. package/dist/entities/model.js +20 -1
  36. package/dist/errors/reasons.js +4 -4
  37. package/dist/render/liquid.d.ts +14 -0
  38. package/dist/render/liquid.js +30 -0
  39. package/dist/replies/template.js +3 -22
  40. package/dist/search/lucene/plain.js +4 -1
  41. package/dist/search/question-plan.js +2 -1
  42. package/dist/sends/permissions.js +4 -0
  43. package/dist/services/embeddings-maintenance.d.ts +1 -1
  44. package/dist/services/embeddings-maintenance.js +6 -6
  45. package/dist/services/index.d.ts +2 -0
  46. package/dist/services/index.js +2 -0
  47. package/dist/services/meeting-model.d.ts +1 -1
  48. package/dist/services/meeting-model.js +4 -4
  49. package/dist/services/messages-meaning.js +25 -4
  50. package/dist/services/model-downloads.js +1 -1
  51. package/dist/services/notes-search.d.ts +1 -1
  52. package/dist/services/notes-search.js +2 -2
  53. package/dist/services/search-all.d.ts +2 -0
  54. package/dist/services/search-all.js +30 -8
  55. package/dist/services/text-model-choice.d.ts +50 -0
  56. package/dist/services/text-model-choice.js +151 -0
  57. package/dist/store/exports.d.ts +1 -0
  58. package/dist/store/exports.js +1 -0
  59. package/dist/store/index.d.ts +1 -0
  60. package/dist/store/index.js +1 -0
  61. package/dist/store/sqlite/owner-languages.d.ts +13 -0
  62. package/dist/store/sqlite/owner-languages.js +49 -0
  63. package/dist/store/sqlite/reported-relations.js +5 -1
  64. package/dist/store/sqlite/vectors.d.ts +2 -0
  65. package/dist/store/sqlite/vectors.js +5 -0
  66. package/dist/store/vectors.d.ts +2 -0
  67. package/dist/store/vectors.js +1 -0
  68. package/package.json +2 -2
  69. package/parity.json +13 -0
package/CHANGELOG.md CHANGED
@@ -5,6 +5,83 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.609.0 — 08.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`models set <id>` chooses the local embedding model for every WireCat CLI**, kept in the shared settings file:
13
+ every embed and every search by meaning uses it, and `models list` marks it `default`. It refuses a model that is
14
+ not downloaded, and says how many chunks the new model still lacks and about how long that takes. Vectors stay
15
+ per model, so a switch deletes nothing and switching back is instant. It asks nothing, over MCP too (permission
16
+ `models.set` is `allow`); `models add` needs `mcp.authority` there.
17
+ - **`e5-large`**, multilingual-e5-large 8-bit (MIT, 579 MB, 1024 dims), the large one beside `e5-small` (small) and
18
+ `embeddinggemma` (medium). `models list --json` gives each text model's `size`, `dims`, `terms` and
19
+ `chunks_per_second`.
20
+ - **`models add <id> --payload '<json>'` adds an ONNX embedding model from Hugging Face**, pinned to a commit with
21
+ each file's sha256, in the same shape as the built-in models. Its vectors' key carries its weights' hash.
22
+ - `chosenTextModel`, `textModels` and `useTextModel` from `@wirecat/cli-core/services`; `store.vectors.vectorCounts`.
23
+ - **`config set owner_languages ru,en` says which languages the owner reads**, store-wide and offered by every
24
+ WireCat CLI, not only the messengers: ISO 639-1 codes in his order, each once; `ru` when unset. The first is the
25
+ language everything written for him is in; a title quoted in a later one stays untranslated. An unknown code is
26
+ refused by name. `ownerLanguages(database)` from `@wirecat/cli-core/store` reads it, primary first, with
27
+ `DEFAULT_OWNER_LANGUAGES`. A scheduled agent's report is rendered in the first language.
28
+ - **A CLI's own CRM list can print the same `--format csv` table as `deals list`.** `@wirecat/cli-core/crm/cli`
29
+ exports `csvFormatOption`, `refuseCsvConflict` (the refusal of another output or an agent's run, checked before
30
+ the CRM is read), `csvColumnPaths` (`--json=a,b`, or the caller's own default columns) and `printCsv`, with
31
+ `DEAL_CSV_COLUMNS` and the `CsvPage` and `CsvField` types. `deals list` and `leads list` print through them.
32
+ - **A scheduled agent that answers with a `wirecat.report/1` document gets a rendered message, not its raw text.**
33
+ The document is one JSON object, bare or as the only fenced `json` block: dated sections (`today`, `decisions`,
34
+ `money`, `meetings`, `projects`, `mail`) of typed items, and stale sources in `health`. The Telegram route gets
35
+ HTML from a template shipped for the owner's first language (`owner_languages`; `ru` and `en`, English words for
36
+ any other), fitted under 4 096 characters by dropping the last item of the largest section, so no file is sent;
37
+ mail gets the plain-text rendering with its title as the subject; `latest.txt` beside `latest.md` keeps the same
38
+ text. Agent text is escaped before a template sees it, and after rendering only `b`, `i` and `a` survive for
39
+ Telegram (`div p b i a br span` with `style` for email), each `href` only to a link the renderer built. Store
40
+ references, backticks, `--flags` and snake_case words are taken out of agent text and counted as `report.leaks`
41
+ in `last.json`. A document that fails the check is never shown: each route gets one line in the owner's language,
42
+ with `delivery.report-invalid`. Any other answer keeps the Markdown path.
43
+
44
+ ### Changed — may break callers
45
+
46
+ - **A search with no letter or digit is refused** (`validation_error`, "search needs a letter or a digit to look
47
+ for"). `""`, a lone `?`, `()` or an emoji alone found nothing and said nothing; `-` and `+` alone were refused
48
+ before as a syntax error. A lone `*` still reads as a wildcard.
49
+
50
+ ### Fixed
51
+
52
+ - **`search all` no longer gives each source half of a ten-hit page.** Each source's best hit comes first, then every
53
+ other hit by its cosine to the question, then by its rank in its source. Ordered by rank first, the sources took
54
+ turns, so a mail at its third to fifth place fell off the page behind notes that matched far less.
55
+ - **Mail looks up by meaning with the text notes embed for the same question.** It embedded the words a picture
56
+ search keeps, which drop a question mark and a time (`10:30`), so mail and note cosines did not compare. A query
57
+ that leaves notes nothing to embed (`content:invoice`, `budg*`) keeps the old words for mail.
58
+ - **A question with a time or a `word:word` in it is searched by its words again.** Without a meaning model,
59
+ `search all`, `search notes` and `events search` sent "When is the steering committee? Answer as HH:MM" to strict
60
+ search, which needs every word in one record, so it found nothing. The quoting that keeps `HH:MM` and `10:30`
61
+ literal made the question look like a quoted phrase; a quoted single word now counts as a word of the question.
62
+ A quoted phrase of several words still sends the question to strict search.
63
+ - **`search all` says which word found nothing when every word was needed and nothing was found.** For two to
64
+ eight plain words, each word is looked up alone, only when the answer is empty; `missing` then names the word,
65
+ such as "every word must be in one record, and nothing in messages, notes holds "xyzzy"", and `SearchAllFound`
66
+ carries it as `unmatched`. Results and ranking do not change.
67
+ - **Search by meaning and every embed follow the chosen model.** Notes, mail, events, discovery's meaning lane,
68
+ `search all` and the message vectors of `conversations rebuild` used e5-small whatever was set; a CLI with no
69
+ `embedding_model` setting (memo) could not use another model at all.
70
+ - **A CSV cell prints a phone or an e-mail by its value**, where an object without a `name` was printed as JSON.
71
+ - **A CRM sync no longer slows down with every deal it saves** (#2623). Looking up a reported relationship read every
72
+ link of its busier end, such as a deal owner with thousands of deals, because SQLite could not use the
73
+ relationship's unique key. On synthetic data with 10 deal owners, a first sync of 20,000 deals, 10,000 leads and
74
+ 20,000 contacts takes 30 s instead of 61 s, and a `--rescan` 21 s instead of 71 s.
75
+
76
+ ## 0.608.0 — 08.11.2026
77
+
78
+ ### Fixed
79
+
80
+ - **Two pairs of reasons no longer share one message**, so the command audit (`same-error-reason`) passes in a CLI
81
+ that lists cli-core's reasons, such as b24 and beeline. `oauth.missing` says the profile is not signed in to the
82
+ provider and `session.missing` that it has no API token saved; `finance.line-amount` names an invoice line and
83
+ `order.line-amount` an order line. The reason ids and codes are unchanged.
84
+
8
85
  ## 0.607.0 — 08.11.2026
9
86
 
10
87
  ### Added
@@ -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;