@wirecat/cli-core 0.608.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 (68) hide show
  1. package/CHANGELOG.md +67 -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 +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/render/liquid.d.ts +14 -0
  37. package/dist/render/liquid.js +30 -0
  38. package/dist/replies/template.js +3 -22
  39. package/dist/search/lucene/plain.js +4 -1
  40. package/dist/search/question-plan.js +2 -1
  41. package/dist/sends/permissions.js +4 -0
  42. package/dist/services/embeddings-maintenance.d.ts +1 -1
  43. package/dist/services/embeddings-maintenance.js +6 -6
  44. package/dist/services/index.d.ts +2 -0
  45. package/dist/services/index.js +2 -0
  46. package/dist/services/meeting-model.d.ts +1 -1
  47. package/dist/services/meeting-model.js +4 -4
  48. package/dist/services/messages-meaning.js +25 -4
  49. package/dist/services/model-downloads.js +1 -1
  50. package/dist/services/notes-search.d.ts +1 -1
  51. package/dist/services/notes-search.js +2 -2
  52. package/dist/services/search-all.d.ts +2 -0
  53. package/dist/services/search-all.js +30 -8
  54. package/dist/services/text-model-choice.d.ts +50 -0
  55. package/dist/services/text-model-choice.js +151 -0
  56. package/dist/store/exports.d.ts +1 -0
  57. package/dist/store/exports.js +1 -0
  58. package/dist/store/index.d.ts +1 -0
  59. package/dist/store/index.js +1 -0
  60. package/dist/store/sqlite/owner-languages.d.ts +13 -0
  61. package/dist/store/sqlite/owner-languages.js +49 -0
  62. package/dist/store/sqlite/reported-relations.js +5 -1
  63. package/dist/store/sqlite/vectors.d.ts +2 -0
  64. package/dist/store/sqlite/vectors.js +5 -0
  65. package/dist/store/vectors.d.ts +2 -0
  66. package/dist/store/vectors.js +1 -0
  67. package/package.json +2 -2
  68. package/parity.json +13 -0
@@ -0,0 +1,76 @@
1
+ {%- comment -%}
2
+ Plain text: the terminal, latest.txt, the desktop notice, the email's plain part. Line 2 is indented by three spaces.
3
+ {%- endcomment -%}
4
+ {%- capture nl %}
5
+ {% endcapture -%}
6
+ {%- assign weekdays = "понедельник,вторник,среду,четверг,пятницу,субботу,воскресенье" | split: "," -%}
7
+ {%- assign weekday = date.weekday | minus: 1 -%}
8
+ {{ emoji }} Сводка на {{ weekdays[weekday] }}, {{ date.date }}
9
+ {%- if summary %}{{ nl }}{{ summary }}{% endif -%}
10
+ {%- if quiet -%}
11
+ {{ nl }}{{ nl }}
12
+ {%- if health.items.size > 0 %}Новых дел нет, но {{ health.items[0].source }} не обновлялся {{ health.items[0].span }}.
13
+ {%- else %}Тихое утро: ничего срочного.{% endif -%}
14
+ {%- endif -%}
15
+ {%- for section in sections -%}
16
+ {{ nl }}{{ nl }}{{ section.emoji }}{{ " " }}
17
+ {%- case section.kind -%}
18
+ {%- when "today" %}Сегодня
19
+ {%- when "decisions" %}Ждут вашего решения
20
+ {%- when "money" %}Деньги
21
+ {%- when "meetings" %}Встречи
22
+ {%- when "projects" %}Проекты в движении
23
+ {%- when "mail" %}Новая почта
24
+ {%- endcase -%}
25
+ {%- for item in section.items -%}
26
+ {%- capture due -%}
27
+ {%- if item.due -%}
28
+ {%- if item.overdue %}просрочено на {{ item.due.span }}
29
+ {%- else %}срок {% if item.due.day == "today" %}сегодня{% elsif item.due.day == "tomorrow" %}завтра{% else %}{{ item.due.date }}{% endif %}{% if item.due.time %}, {{ item.due.time }}{% endif %}
30
+ {%- endif -%}
31
+ {%- endif -%}
32
+ {%- endcapture -%}
33
+ {{ nl }}{{ item.emoji }}{{ " " }}
34
+ {%- case item.type -%}
35
+ {%- when "reply" %}{{ item.who }} · {{ item.topic }} — {{ item.action }}
36
+ {%- when "question" %}{{ item.who }} спрашивает: {{ item.action }}
37
+ {%- when "task" %}{{ item.topic }} — {{ due }}
38
+ {%- when "fact" %}{{ item.topic }}: {{ item.detail }}
39
+ {%- when "risk" %}{{ item.topic }}: {{ item.detail }} → {{ item.action }}
40
+ {%- when "money" %}{{ item.amount.text }} · {{ item.who }} · {{ item.topic }}{% if item.action %} — {{ item.action }}{% endif %}
41
+ {%- when "decision" %}{{ item.topic }} — {% if item.count %}{{ item.count }} {% endif %}{{ item.action }}
42
+ {%- when "meeting" -%}
43
+ {%- if item.time.day == "today" %}{{ item.time.time }}
44
+ {%- elsif item.time.day == "yesterday" %}Вчера
45
+ {%- elsif item.time.day == "tomorrow" %}Завтра, {{ item.time.time }}
46
+ {%- else %}{{ item.time.date }}{% if item.time.time %}, {{ item.time.time }}{% endif %}
47
+ {%- endif %} · {{ item.topic }}{% if item.who %} · {{ item.who }}{% endif %}
48
+ {%- endcase -%}
49
+ {%- assign sep = "" -%}
50
+ {%- capture second -%}
51
+ {%- if item.since and "reply,question" contains item.type %}{{ sep }}ждёт {{ item.since.span }}{% assign sep = " · " %}{% endif -%}
52
+ {%- if due != "" and "risk,money,decision" contains item.type %}{{ sep }}{{ due }}{% assign sep = " · " %}{% endif -%}
53
+ {%- if item.action and "task,meeting" contains item.type %}{{ sep }}{{ item.action }}{% assign sep = " · " %}{% endif -%}
54
+ {%- if item.detail and "task,money,meeting,decision" contains item.type %}{{ sep }}{{ item.detail }}{% assign sep = " · " %}{% endif -%}
55
+ {%- if item.who and "task,fact,risk,decision" contains item.type %}{{ sep }}{{ item.who }}{% assign sep = " · " %}{% endif -%}
56
+ {%- if item.channel %}{{ sep }}
57
+ {%- case item.channel -%}
58
+ {%- when "telegram" %}Telegram{% when "max" %}MAX{% when "whatsapp" %}WhatsApp
59
+ {%- when "mail" %}почта{% when "meeting" %}встреча{% when "task" %}задача
60
+ {%- endcase -%}
61
+ {%- assign sep = " · " -%}
62
+ {%- endif -%}
63
+ {%- if item.quote %}{{ sep }}«{{ item.quote }}»{% assign sep = " · " %}{% endif -%}
64
+ {%- for link in item.links %}{{ sep }}{{ link.url }}{% assign sep = " · " %}{% endfor -%}
65
+ {%- endcapture -%}
66
+ {%- if second != "" %}{{ nl }} {{ second }}{% endif -%}
67
+ {%- endfor -%}
68
+ {%- if section.more > 0 %}{{ nl }}ещё {{ section.more }}{% endif -%}
69
+ {%- endfor -%}
70
+ {%- unless quiet -%}
71
+ {%- if health.items.size > 0 %}{{ nl }}{% endif -%}
72
+ {%- for source in health.items -%}
73
+ {{ nl }}{{ health.emoji }} {{ source.source }} не обновлялся {{ source.span }}
74
+ {%- for link in source.links %} · {{ link.url }}{% endfor -%}
75
+ {%- endfor -%}
76
+ {%- endunless -%}
@@ -0,0 +1,88 @@
1
+ import type { ChannelKind, ItemType, Report, ReportKind, SectionKind } from "./schema.js";
2
+ /** A link the renderer built; a template may point an `href` only at one of these. Empty until deep links exist. */
3
+ export interface ViewLink {
4
+ kind: "open" | "web";
5
+ url: string;
6
+ label: string;
7
+ }
8
+ /** A date or a date-time, already in the owner's language and time zone. */
9
+ export interface Moment {
10
+ iso: string;
11
+ /** "7 ноября", "November 7". */
12
+ date: string;
13
+ /** "18:00", or null for a date alone. */
14
+ time: string | null;
15
+ /** 1 Monday … 7 Sunday. */
16
+ weekday: number;
17
+ day: "today" | "yesterday" | "tomorrow" | null;
18
+ past: boolean;
19
+ /** How far from now, in the largest whole unit: "10 минут", "5 часов", "2 дня". */
20
+ span: string;
21
+ }
22
+ export interface ViewItem {
23
+ type: ItemType;
24
+ emoji: string;
25
+ who: string | null;
26
+ topic: string | null;
27
+ action: string | null;
28
+ detail: string | null;
29
+ quote: string | null;
30
+ channel: ChannelKind | null;
31
+ priority: "high" | "normal";
32
+ overdue: boolean;
33
+ count: number | null;
34
+ amount: {
35
+ text: string;
36
+ direction: "in" | "out";
37
+ } | null;
38
+ since: Moment | null;
39
+ due: Moment | null;
40
+ time: Moment | null;
41
+ links: ViewLink[];
42
+ }
43
+ export interface ViewSection {
44
+ kind: SectionKind;
45
+ emoji: string;
46
+ items: ViewItem[];
47
+ /** The "ещё N" count: what the agent left out plus what the cap or the Telegram fit dropped. */
48
+ more: number;
49
+ }
50
+ export interface ViewHealth {
51
+ source: string;
52
+ hours: number;
53
+ span: string;
54
+ links: ViewLink[];
55
+ }
56
+ /** What a report template gets. Every string an agent wrote is already escaped for an HTML channel. */
57
+ export interface ReportView {
58
+ kind: ReportKind;
59
+ language: string;
60
+ emoji: string;
61
+ date: Moment;
62
+ summary: string | null;
63
+ sections: ViewSection[];
64
+ health: {
65
+ emoji: string;
66
+ items: ViewHealth[];
67
+ more: number;
68
+ };
69
+ /** Nothing in the six sections: the template says so, and says a stale source if there is one. */
70
+ quiet: boolean;
71
+ counts: {
72
+ today: number;
73
+ money: number;
74
+ };
75
+ links: ViewLink[];
76
+ }
77
+ export declare const SECTION_EMOJI: Record<SectionKind, string>;
78
+ export declare const SECTION_CAPS: Record<SectionKind | "health", number>;
79
+ export declare const momentFor: (iso: string, now: number, language: string, timeZone?: string) => Moment;
80
+ /**
81
+ * The view model of a checked report: sections in their fixed order, each cut to its cap with the rest counted in
82
+ * `more`, dates and money formatted in `language` and `timeZone`. Refs never reach it.
83
+ */
84
+ export declare const reportView: (report: Report, { language, now, timeZone }: {
85
+ language: string;
86
+ now: number;
87
+ timeZone?: string;
88
+ }) => ReportView;
@@ -0,0 +1,152 @@
1
+ export const SECTION_EMOJI = {
2
+ today: "🔥",
3
+ decisions: "🗳",
4
+ money: "💰",
5
+ meetings: "📅",
6
+ projects: "🚀",
7
+ mail: "📬",
8
+ };
9
+ export const SECTION_CAPS = {
10
+ today: 7,
11
+ decisions: 5,
12
+ money: 5,
13
+ meetings: 5,
14
+ projects: 5,
15
+ mail: 5,
16
+ health: 3,
17
+ };
18
+ const STALE_HOURS = 24;
19
+ const emojiOf = (item, overdue) => {
20
+ switch (item.type) {
21
+ case "reply":
22
+ return "💬";
23
+ case "question":
24
+ return "❓";
25
+ case "task":
26
+ return overdue ? "⏰" : "📌";
27
+ case "fact":
28
+ return "ℹ️";
29
+ case "risk":
30
+ return item.priority === "high" ? "🔴" : "⚠️";
31
+ case "money":
32
+ return item.amount?.direction === "in" ? "📥" : "📤";
33
+ case "decision":
34
+ return "☑️";
35
+ case "meeting":
36
+ return "👥";
37
+ }
38
+ };
39
+ const DAY_MS = 86_400_000;
40
+ const calendarDay = (at, timeZone) => new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(at);
41
+ const utcOf = (day) => {
42
+ const [year = 0, month = 1, date = 1] = day.split("-").map(Number);
43
+ return Date.UTC(year, month - 1, date);
44
+ };
45
+ export const momentFor = (iso, now, language, timeZone) => {
46
+ const dateOnly = iso.length === 10;
47
+ const at = dateOnly ? utcOf(iso) : Date.parse(iso);
48
+ const day = dateOnly ? iso : calendarDay(at, timeZone);
49
+ const days = Math.round((utcOf(day) - utcOf(calendarDay(now, timeZone))) / DAY_MS);
50
+ const unit = (count, name) => new Intl.NumberFormat(language, { style: "unit", unit: name, unitDisplay: "long" }).format(count);
51
+ const distance = Math.abs(at - now);
52
+ const span = dateOnly
53
+ ? unit(Math.abs(days), "day")
54
+ : distance < 3_600_000
55
+ ? unit(Math.floor(distance / 60_000), "minute")
56
+ : distance < DAY_MS
57
+ ? unit(Math.floor(distance / 3_600_000), "hour")
58
+ : unit(Math.floor(distance / DAY_MS), "day");
59
+ return {
60
+ iso,
61
+ date: new Intl.DateTimeFormat(language, { day: "numeric", month: "long", timeZone: "UTC" }).format(utcOf(day)),
62
+ time: dateOnly
63
+ ? null
64
+ : new Intl.DateTimeFormat(language, { hour: "2-digit", minute: "2-digit", hourCycle: "h23", timeZone }).format(at),
65
+ weekday: ((new Date(utcOf(day)).getUTCDay() + 6) % 7) + 1,
66
+ day: days === 0 ? "today" : days === -1 ? "yesterday" : days === 1 ? "tomorrow" : null,
67
+ past: dateOnly ? days < 0 : at < now,
68
+ span,
69
+ };
70
+ };
71
+ const amountText = (amount, language) => {
72
+ const fraction = Number.isInteger(amount.value) ? 0 : 2;
73
+ const money = new Intl.NumberFormat(language, {
74
+ style: "currency",
75
+ currency: amount.currency,
76
+ minimumFractionDigits: fraction,
77
+ maximumFractionDigits: fraction,
78
+ }).format(amount.value);
79
+ return `${amount.direction === "in" ? "+" : "−"}${money}`;
80
+ };
81
+ /**
82
+ * The view model of a checked report: sections in their fixed order, each cut to its cap with the rest counted in
83
+ * `more`, dates and money formatted in `language` and `timeZone`. Refs never reach it.
84
+ */
85
+ export const reportView = (report, { language, now, timeZone }) => {
86
+ const moment = (iso) => (iso === null ? null : momentFor(iso, now, language, timeZone));
87
+ const itemOf = (item) => {
88
+ const due = moment(item.due);
89
+ const overdue = (item.type === "task" || item.type === "money" || item.type === "risk") && due?.past === true;
90
+ return {
91
+ type: item.type,
92
+ emoji: emojiOf(item, overdue),
93
+ who: item.who,
94
+ topic: item.topic,
95
+ action: item.action,
96
+ detail: item.detail,
97
+ quote: item.quote,
98
+ channel: item.channel,
99
+ priority: item.priority,
100
+ overdue,
101
+ count: item.count,
102
+ amount: item.amount ? { text: amountText(item.amount, language), direction: item.amount.direction } : null,
103
+ since: moment(item.since),
104
+ due,
105
+ time: moment(item.time),
106
+ links: [],
107
+ };
108
+ };
109
+ const order = Object.keys(SECTION_EMOJI);
110
+ const sections = order.flatMap((kind) => {
111
+ const parts = report.sections.filter((section) => section.kind === kind);
112
+ const items = parts.flatMap((section) => section.items);
113
+ const more = parts.reduce((sum, section) => sum + section.more, 0);
114
+ if (items.length === 0)
115
+ return [];
116
+ const cap = SECTION_CAPS[kind];
117
+ return [
118
+ {
119
+ kind,
120
+ emoji: SECTION_EMOJI[kind],
121
+ items: items.slice(0, cap).map(itemOf),
122
+ more: more + Math.max(items.length - cap, 0),
123
+ },
124
+ ];
125
+ });
126
+ const stale = report.health.filter((entry) => entry.staleHours > STALE_HOURS);
127
+ const count = (kind) => {
128
+ const section = sections.find((one) => one.kind === kind);
129
+ return section ? section.items.length + section.more : 0;
130
+ };
131
+ return {
132
+ kind: report.kind,
133
+ language,
134
+ emoji: "☀️",
135
+ date: momentFor(report.date, now, language, timeZone),
136
+ summary: report.summary,
137
+ sections,
138
+ health: {
139
+ emoji: "🛠",
140
+ items: stale.slice(0, SECTION_CAPS.health).map((entry) => ({
141
+ source: entry.source,
142
+ hours: entry.staleHours,
143
+ span: new Intl.NumberFormat(language, { style: "unit", unit: "day", unitDisplay: "long" }).format(Math.floor(entry.staleHours / 24)),
144
+ links: [],
145
+ })),
146
+ more: Math.max(stale.length - SECTION_CAPS.health, 0),
147
+ },
148
+ quiet: sections.length === 0,
149
+ counts: { today: count("today"), money: count("money") },
150
+ links: [],
151
+ };
152
+ };
@@ -1,5 +1,6 @@
1
1
  import { type AppIdentity } from "../ports/app.js";
2
2
  import { type Delivery } from "./deliver.js";
3
+ import { type ReportRun } from "./report/render.js";
3
4
  import type { ServerSystem } from "./system.js";
4
5
  /** Minutes between runs, a daily local time, or one local moment. */
5
6
  export type When = {
@@ -84,6 +85,8 @@ export interface LastRun {
84
85
  };
85
86
  /** How the result went along each of the schedule's routes; a failed delivery never fails the run. */
86
87
  deliveries?: Delivery[];
88
+ /** An agent's answer that was a `wirecat.report/1` document: its language, leaks, and what went wrong. */
89
+ report?: ReportRun;
87
90
  }
88
91
  /** Why a timer left a run out, as an id a translation can key on; `why` stays the English sentence. */
89
92
  export declare const SKIP_REASONS: {
@@ -172,7 +175,7 @@ export declare const CREDENTIALS_UNREACHABLE = "credentials.unreachable";
172
175
  * keyring, so a run that fails for that reason is tried again, a minute then up to 15 minutes apart, for up to
173
176
  * 12 hours. A schedule that repeats every few minutes is left to its next tick; a run by hand fails at once.
174
177
  */
175
- export declare const runSchedule: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, file: string, { now, timer, signal, killAfterMs, untilUnlocked, wait, agentRuns, agentInput, }?: {
178
+ export declare const runSchedule: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, file: string, { now, timer, signal, killAfterMs, untilUnlocked, wait, agentRuns, agentInput, ownerLanguage, }?: {
176
179
  now?: () => Date;
177
180
  timer?: Timer;
178
181
  signal?: AbortSignal;
@@ -182,4 +185,6 @@ export declare const runSchedule: (app: AppIdentity, system: ServerSystem, env:
182
185
  /** The other CLIs an agent may run; each runs under its own read-only lock and knows it runs from a schedule. */
183
186
  agentRuns?: readonly AgentCli[];
184
187
  agentInput?: AgentInput;
188
+ /** The owner's first language, read only when the answer is a report; Russian when the host cannot say. */
189
+ ownerLanguage?: (env: NodeJS.ProcessEnv) => Promise<string>;
185
190
  }) => Promise<LastRun>;
@@ -6,6 +6,7 @@ import { mailHolderVariable, readOnlyLockOf } from "../ports/app.js";
6
6
  import { recordLogFor } from "../runs/record-log.js";
7
7
  import { childTrace } from "../runs/scope.js";
8
8
  import { deliver } from "./deliver.js";
9
+ import { prepareReport } from "./report/render.js";
9
10
  export const NOTIFY_WHEN = ["always", "failures", "never"];
10
11
  /** A repeating agent would otherwise notify on every tick; any other schedule runs rarely enough to say each result. */
11
12
  export const notifyOf = (schedule) => schedule.notify ?? (schedule.kind === "agent" && "every" in schedule.when ? "failures" : "always");
@@ -111,10 +112,9 @@ export const recordRun = (path, run) => {
111
112
  writeSecurely(path, `${JSON.stringify(last, null, 2)}\n`, 0o600);
112
113
  return last;
113
114
  };
114
- const recordDeliveries = (path, last, deliveries) => {
115
- const delivered = { ...last, deliveries };
116
- writeSecurely(path, `${JSON.stringify(delivered, null, 2)}\n`, 0o600);
117
- return delivered;
115
+ const rewriteRun = (path, last) => {
116
+ writeSecurely(path, `${JSON.stringify(last, null, 2)}\n`, 0o600);
117
+ return last;
118
118
  };
119
119
  /** Notes on the last run that the timer left this one out, keeping that run's result. */
120
120
  export const recordSkip = (file, why, reason, at = new Date()) => {
@@ -431,7 +431,7 @@ const pause = (ms, signal) => new Promise((resolve) => {
431
431
  * keyring, so a run that fails for that reason is tried again, a minute then up to 15 minutes apart, for up to
432
432
  * 12 hours. A schedule that repeats every few minutes is left to its next tick; a run by hand fails at once.
433
433
  */
434
- export const runSchedule = async (app, system, env, file, { now = () => new Date(), timer, signal, killAfterMs = KILL_AFTER_MS, untilUnlocked = false, wait = pause, agentRuns = [], agentInput, } = {}) => {
434
+ export const runSchedule = async (app, system, env, file, { now = () => new Date(), timer, signal, killAfterMs = KILL_AFTER_MS, untilUnlocked = false, wait = pause, agentRuns = [], agentInput, ownerLanguage = async () => "ru", } = {}) => {
435
435
  const schedule = readSchedule(file);
436
436
  const folder = join(file, "..");
437
437
  const runs = join(folder, "runs");
@@ -462,6 +462,19 @@ export const runSchedule = async (app, system, env, file, { now = () => new Date
462
462
  const errors = agent ? output.replace(/\.md$/, ".log") : output;
463
463
  if (agent && exitCode === 0)
464
464
  copyFileSync(output, join(folder, "latest.md"));
465
+ const prepared = agent && exitCode === 0
466
+ ? await prepareReport(readFileSync(output, "utf8"), {
467
+ language: await ownerLanguage({ ...env, ...schedule.environment }).catch(() => "ru"),
468
+ now: now().getTime(),
469
+ })
470
+ : undefined;
471
+ const latestText = join(folder, "latest.txt");
472
+ if (prepared) {
473
+ writeFileSync(latestText, `${prepared.text}\n`, { mode: 0o600 });
474
+ last = rewriteRun(join(folder, "last.json"), { ...last, report: prepared.run });
475
+ }
476
+ else if (agent && exitCode === 0)
477
+ rmSync(latestText, { force: true });
465
478
  const stampOf = (file) => file.split(".")[0] ?? file;
466
479
  const kept = new Set([...new Set(readdirSync(runs).map(stampOf))].sort().slice(-KEEP_RUNS));
467
480
  for (const file of readdirSync(runs))
@@ -469,7 +482,10 @@ export const runSchedule = async (app, system, env, file, { now = () => new Date
469
482
  rmSync(join(runs, file), { force: true });
470
483
  const title = `${app.command} ${schedule.name}`;
471
484
  const mode = notifyOf(schedule);
472
- if (agent && exitCode === 0 && mode === "always") {
485
+ if (prepared && mode === "always") {
486
+ await notify(system, env, title, `${prepared.notice.slice(0, 180)}\n${latestText}`);
487
+ }
488
+ else if (agent && exitCode === 0 && mode === "always") {
473
489
  const first = readFileSync(output, "utf8")
474
490
  .split("\n")
475
491
  .find((line) => line.trim()) ?? "report ready";
@@ -487,6 +503,7 @@ export const runSchedule = async (app, system, env, file, { now = () => new Date
487
503
  ? {
488
504
  title: `${title} · ${at}`,
489
505
  file: { path: output, name: `${schedule.name}-${at.replace(/[ :]/g, "-")}.${agent ? "md" : "txt"}` },
506
+ ...(prepared ? { rendered: prepared } : {}),
490
507
  }
491
508
  : {
492
509
  title: `${title} failed · ${at}`,
@@ -498,7 +515,7 @@ export const runSchedule = async (app, system, env, file, { now = () => new Date
498
515
  errorOf: reasonOf,
499
516
  ...(locked ? { locked } : {}),
500
517
  });
501
- last = recordDeliveries(join(folder, "last.json"), last, deliveries);
518
+ last = rewriteRun(join(folder, "last.json"), { ...last, deliveries });
502
519
  const lost = deliveries.filter((one) => !one.ok);
503
520
  if (lost.length > 0 && mode !== "never") {
504
521
  await notify(system, env, title, lost.map((one) => `not delivered to ${one.to}: ${one.reason}`).join("\n"));
@@ -9,7 +9,10 @@ export interface ModelOptions {
9
9
  dims?: number;
10
10
  concurrency?: number;
11
11
  }
12
- /** A local model id, or a remote model with its key from `models keys set`. */
12
+ /**
13
+ * A local model id, or a remote model with its key from `models keys set`. A flag wins, then this CLI's own
14
+ * `embedding_model`, then the shared choice of `models use`.
15
+ */
13
16
  export declare const embeddingChoice: ({ model, embeddingProvider, baseUrl, dims, concurrency }: ModelOptions, app: AppIdentity, settings: AISettings, env: NodeJS.ProcessEnv, { needKey, keyring }?: {
14
17
  needKey?: boolean;
15
18
  keyring?: KeyringStore | undefined;
@@ -1,11 +1,14 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { endpoint } from "../analysis/settings.js";
3
3
  import { embeddingKeys, endpointKeyName } from "../embeddings/keys.js";
4
- import { DEFAULT_TEXT_MODEL } from "../embeddings/models.js";
4
+ import { chosenTextModel } from "../embeddings/models.js";
5
5
  import { isLocal, remoteModel } from "../embeddings/remote.js";
6
6
  import { readOnlyLockOf, readOnlyRefusal } from "../ports/app.js";
7
7
  import { typedCommand } from "../runs/scope.js";
8
- /** A local model id, or a remote model with its key from `models keys set`. */
8
+ /**
9
+ * A local model id, or a remote model with its key from `models keys set`. A flag wins, then this CLI's own
10
+ * `embedding_model`, then the shared choice of `models use`.
11
+ */
9
12
  export const embeddingChoice = ({ model, embeddingProvider, baseUrl, dims, concurrency }, app, settings, env, { needKey = true, keyring } = {}) => {
10
13
  let provider = embeddingProvider;
11
14
  const flagsChooseProvider = (provider !== undefined && provider !== (settings.embeddingProvider ?? "local")) ||
@@ -17,7 +20,7 @@ export const embeddingChoice = ({ model, embeddingProvider, baseUrl, dims, concu
17
20
  if (provider === "local") {
18
21
  if (baseUrl !== undefined || dims !== undefined)
19
22
  throw new CliError("validation_error", "local embeddings do not take --base-url or --dims");
20
- return model ?? DEFAULT_TEXT_MODEL;
23
+ return model ?? chosenTextModel(env).id;
21
24
  }
22
25
  if (baseUrl !== undefined && !endpoint(baseUrl))
23
26
  throw new CliError("validation_error", "use an HTTP/S --base-url without credentials, query or fragment");
@@ -4,10 +4,11 @@ import { annotate } from "@wirecat/cli-base/commands";
4
4
  import { Command } from "commander";
5
5
  import { isTextModelInstalled, textModelsDirectory } from "../../embeddings/embed.js";
6
6
  import { embeddingKeys } from "../../embeddings/keys.js";
7
- import { DEFAULT_RERANK_MODEL, DEFAULT_TEXT_MODEL, RERANK_MODELS, TEXT_MODELS, } from "../../embeddings/models.js";
7
+ import { DEFAULT_RERANK_MODEL, DEFAULT_TEXT_MODEL, RERANK_MODELS, textModels, } from "../../embeddings/models.js";
8
8
  import { model as modelEntity } from "../../entities/model.js";
9
9
  import { DEFAULT_IMAGE_MODEL, IMAGE_MODELS, imageModelsDirectory, isImageModelInstalled, } from "../../images/picture/models.js";
10
10
  import { downloadImageModel, downloadRerankModel, downloadTextModel } from "../../services/model-downloads.js";
11
+ import { addCustomTextModel, useTextModel } from "../../services/text-model-choice.js";
11
12
  import { install, installedBytes, isInstalled, megabytes, modelPath, modelsDirectory, vadPath, } from "../../speech/install.js";
12
13
  import { orderedModels, speechModel, VAD } from "../../speech/models.js";
13
14
  import { choose } from "../../speech/transcribe.js";
@@ -16,7 +17,7 @@ import { baseContext, environmentOf } from "../context.js";
16
17
  import { FETCH, grantsAuthority, LOCAL_READ, LOCAL_WRITE, reachesOtherService } from "../effects.js";
17
18
  import { itemOf, listOf, renderAnswer } from "../envelope.js";
18
19
  import { listQuery, nativeTerms, typedQuery, unfilteredQuery, withQuery } from "../list-query.js";
19
- import { MODEL_CATALOGUE_QUERY } from "../model-catalogue-command.js";
20
+ import { ADD_DESCRIPTION, ADD_HELP, addExample, MODEL_CATALOGUE_QUERY, payloadOf, SET_DESCRIPTION, SET_SUMMARY, switchFields, switchNotes, textModelItem, } from "../model-catalogue-command.js";
20
21
  import { nextStep } from "../steps.js";
21
22
  /** A model list is the catalog this version ships. */
22
23
  const MODELS_QUERY = unfilteredQuery("model", modelEntity);
@@ -33,17 +34,6 @@ const audioItem = (model, directory, chosen) => ({
33
34
  default: model.id === chosen,
34
35
  path: join(directory, model.id),
35
36
  });
36
- const textItem = (model, directory) => ({
37
- id: model.id,
38
- kind: "text",
39
- title: model.title,
40
- languages: model.languages,
41
- licence: model.licence,
42
- size_bytes: model.files.reduce((sum, file) => sum + file.bytes, 0),
43
- downloaded: isTextModelInstalled(model, directory),
44
- default: model.id === DEFAULT_TEXT_MODEL,
45
- path: join(directory, model.id),
46
- });
47
37
  const rerankItem = (model, directory, chosen) => ({
48
38
  id: model.id,
49
39
  kind: "reranker",
@@ -101,7 +91,7 @@ const downloadEmbeddingModel = async (command, messenger, id, options) => {
101
91
  acceptTerms: options.acceptTerms === true,
102
92
  progress: (line) => context.renderer.note(line),
103
93
  });
104
- renderAnswer(command, context, itemOf(textItem(model, directory)), downloaded);
94
+ renderAnswer(command, context, itemOf({ ...textModelItem(model, context.env), path: join(directory, model.id) }), downloaded);
105
95
  }, { unbounded: true });
106
96
  };
107
97
  const downloadReranker = async (command, messenger, id) => {
@@ -168,8 +158,8 @@ export const modelsCommand = (messenger) => {
168
158
  const audioModels = kinds === undefined || kinds === "audio"
169
159
  ? orderedModels(messenger.speechModels).filter((model) => id === undefined || model.id === id)
170
160
  : [];
171
- const textModels = kinds === undefined || kinds === "text"
172
- ? TEXT_MODELS.filter((model) => id === undefined || model.id === id)
161
+ const textModelsListed = kinds === undefined || kinds === "text"
162
+ ? textModels(context.env).filter((model) => id === undefined || model.id === id)
173
163
  : [];
174
164
  const rerankers = kinds === undefined || kinds === "reranker"
175
165
  ? RERANK_MODELS.filter((model) => id === undefined || model.id === id)
@@ -177,7 +167,7 @@ export const modelsCommand = (messenger) => {
177
167
  const chosen = audioModels.length > 0 ? choose(messenger, context.settings, {}, context.env, context.keyring).model.id : "";
178
168
  const catalogue = [
179
169
  ...audioModels.map((model) => audioItem(model, modelsDirectory(context.env), chosen)),
180
- ...textModels.map((model) => textItem(model, textModelsDirectory(context.env))),
170
+ ...textModelsListed.map((model) => textModelItem(model, context.env)),
181
171
  ...rerankers.map((model) => rerankItem(model, textModelsDirectory(context.env), context.settings.searchReranker ?? DEFAULT_RERANK_MODEL)),
182
172
  ];
183
173
  const items = catalogue.filter((item) => kept === undefined || item.downloaded === (kept === "true"));
@@ -199,12 +189,50 @@ export const modelsCommand = (messenger) => {
199
189
  .action(async function (id, options) {
200
190
  if (orderedModels().some((model) => model.id === id))
201
191
  return downloadAudioModel(this, messenger, id);
202
- if (TEXT_MODELS.some((model) => model.id === id))
192
+ if (textModels(environmentOf(this).env ?? process.env).some((model) => model.id === id))
203
193
  return downloadEmbeddingModel(this, messenger, id, options);
204
194
  if (RERANK_MODELS.some((model) => model.id === id))
205
195
  return downloadReranker(this, messenger, id);
206
196
  throw new CliError("validation_error", "unknown model; choose an id from models list");
207
197
  });
198
+ annotate(models.command("set"), {
199
+ effects: LOCAL_WRITE,
200
+ output: { entity: "model", view: "chosen" },
201
+ examples: [`${tool} models set e5-large`],
202
+ })
203
+ .summary(SET_SUMMARY)
204
+ .description(SET_DESCRIPTION)
205
+ .argument("<model>", "a downloaded text model id from models list")
206
+ .action(async function (id) {
207
+ const context = baseContext(this, messenger.resolveSettings);
208
+ await context.run(async () => {
209
+ const done = await useTextModel(id, { env: context.env, command: messenger.app.command });
210
+ for (const line of switchNotes(done))
211
+ context.renderer.note(line);
212
+ const own = context.settings.embeddingModel;
213
+ if (own !== undefined && own !== done.model.id)
214
+ context.renderer.note(`this CLI's own embedding_model (${own}) still wins here; unset it to follow the choice`);
215
+ renderAnswer(this, context, itemOf({ ...textModelItem(done.model, context.env), ...switchFields(done) }));
216
+ });
217
+ });
218
+ // A model added here is loaded by every CLI once chosen: an agent needs the owner's mcp.authority for it.
219
+ reachesOtherService(grantsAuthority(annotate(models.command("add"), {
220
+ effects: FETCH,
221
+ output: { entity: "model" },
222
+ examples: [addExample(tool)],
223
+ })))
224
+ .description(ADD_DESCRIPTION)
225
+ .argument("<id>", "the id to give it: a-z, 0-9, . _ -")
226
+ .requiredOption("--payload <json>", "where the model is and how to run it, as JSON (below)")
227
+ .addHelpText("after", ADD_HELP)
228
+ .action(async function (id, given) {
229
+ const context = baseContext(this, messenger.resolveSettings);
230
+ await context.run(async () => {
231
+ const model = await addCustomTextModel(id, payloadOf(given.payload), { env: context.env });
232
+ context.renderer.note(`${model.id}: added — \`${messenger.app.command} models download ${model.id}\` fetches and checks it`);
233
+ renderAnswer(this, context, itemOf(textModelItem(model, context.env)));
234
+ });
235
+ });
208
236
  return models;
209
237
  };
210
238
  /** `images models`: registered with picture search, the only thing these models serve. */
@@ -1,7 +1,7 @@
1
1
  import { hitFiles } from "../../domain/attachments.js";
2
2
  import { formatLocator, parseLocator } from "../../domain/locator.js";
3
3
  import { senderIsMe } from "../../domain/models.js";
4
- import { DEFAULT_TEXT_MODEL } from "../../embeddings/models.js";
4
+ import { chosenTextModel } from "../../embeddings/models.js";
5
5
  import { excerpt } from "../../services/excerpt.js";
6
6
  import { MAX_SEARCH_OFFSET } from "../../services/messages-archive-search.js";
7
7
  import { listOf } from "../envelope.js";
@@ -333,7 +333,7 @@ export const allHitItem = (item) => item.kind === "meeting"
333
333
  const meaningGap = (skipped, exact) => skipped === undefined || exact
334
334
  ? { next: [], missing: [] }
335
335
  : {
336
- next: [nextStep("models.download", { args: { model: DEFAULT_TEXT_MODEL } })],
336
+ next: [nextStep("models.download", { args: { model: chosenTextModel().id } })],
337
337
  missing: [{ field: "found_by", why: skipped, step: "models.download" }],
338
338
  };
339
339
  /** `search notes`, CLI and MCP alike. */
@@ -392,6 +392,15 @@ leftOut = []) => {
392
392
  ...archive.missing,
393
393
  ...limited.missing,
394
394
  ...leftOut.map(({ why }) => ({ field: "items", why })),
395
+ ...(found.unmatched && !found.items.length
396
+ ? [
397
+ {
398
+ field: "items",
399
+ // Meetings are searched apart, so the words were looked up only in the other sources.
400
+ why: `every word must be in one record, and nothing in ${found.searched.filter((one) => one !== "meetings").join(", ")} holds ${found.unmatched.map((word) => `"${word}"`).join(", ")}`,
401
+ },
402
+ ]
403
+ : []),
395
404
  ],
396
405
  meta: metaOf(found.accounts, found.skipped, archive.missing.length > 0 || skips.length > 0),
397
406
  });