@wirecat/cli-core 0.613.0 → 0.615.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 (48) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/background/report/render.d.ts +18 -4
  3. package/dist/background/report/render.js +59 -18
  4. package/dist/background/report/stored-templates.d.ts +64 -0
  5. package/dist/background/report/stored-templates.js +80 -0
  6. package/dist/background/report/templates/morning-digest.sample.json +150 -0
  7. package/dist/background/schedules.d.ts +4 -2
  8. package/dist/background/schedules.js +2 -1
  9. package/dist/calendar/mcp/index.d.ts +12 -12
  10. package/dist/cli/account-remove.d.ts +67 -0
  11. package/dist/cli/account-remove.js +285 -0
  12. package/dist/cli/index.d.ts +3 -1
  13. package/dist/cli/index.js +2 -1
  14. package/dist/cli/messenger/account-command.js +6 -0
  15. package/dist/cli/messenger/context.d.ts +2 -0
  16. package/dist/cli/messenger/serve-relay.d.ts +1 -0
  17. package/dist/cli/profile-files.d.ts +7 -0
  18. package/dist/cli/profile-files.js +43 -0
  19. package/dist/cli/schedule/schedule-command.d.ts +2 -0
  20. package/dist/cli/schedule/schedule-command.js +20 -2
  21. package/dist/cli/shared-command-exports.d.ts +1 -0
  22. package/dist/cli/shared-command-exports.js +2 -0
  23. package/dist/cli/templates-command.d.ts +16 -0
  24. package/dist/cli/templates-command.js +243 -0
  25. package/dist/entities/account-change.d.ts +20 -0
  26. package/dist/entities/account-change.js +12 -1
  27. package/dist/entities/index.d.ts +20 -0
  28. package/dist/entities/index.js +2 -1
  29. package/dist/errors/reasons.js +17 -0
  30. package/dist/services/metadata.d.ts +1 -1
  31. package/dist/store/accounts.d.ts +2 -0
  32. package/dist/store/accounts.js +2 -1
  33. package/dist/store/exports.d.ts +1 -0
  34. package/dist/store/exports.js +1 -0
  35. package/dist/store/index.d.ts +1 -0
  36. package/dist/store/sqlite/account-groups.d.ts +1 -0
  37. package/dist/store/sqlite/account-groups.js +14 -0
  38. package/dist/store/sqlite/manifest.js +1 -0
  39. package/dist/store/sqlite/migrations.generated.js +8 -0
  40. package/dist/store/sqlite/schema/templates.d.ts +242 -0
  41. package/dist/store/sqlite/schema/templates.js +23 -0
  42. package/dist/store/sqlite/schema.d.ts +1 -0
  43. package/dist/store/sqlite/schema.js +1 -0
  44. package/dist/store/sqlite/templates.d.ts +38 -0
  45. package/dist/store/sqlite/templates.js +69 -0
  46. package/dist/store/store.d.ts +3 -0
  47. package/dist/store/store.js +5 -0
  48. package/package.json +4 -4
@@ -4,6 +4,8 @@ import { CliError, resolvePaths, writeSecurely } from "@wirecat/cli-base";
4
4
  import { annotate } from "@wirecat/cli-base/commands";
5
5
  import { Argument, Command, Option } from "commander";
6
6
  import { parseRoute, ROUTE_HELP, routeText } from "../../background/deliver.js";
7
+ import { REPORT_CHANNELS } from "../../background/report/render.js";
8
+ import { reportKeyOf } from "../../background/report/stored-templates.js";
7
9
  import { describeWhen, findProgram, lastRun, listSchedules, NOTIFY_WHEN, notifyOf, readSchedule, recordSkip, runSchedule, SCHEDULE_DEFAULTS, SKIP_REASONS, scheduleFile, scheduleName, spentToday, timerFor, } from "../../background/schedules.js";
8
10
  import { thisMachine } from "../../background/system.js";
9
11
  import { locationVariables } from "../../background/units.js";
@@ -13,7 +15,7 @@ import { readOnlyLockOf } from "../../ports/app.js";
13
15
  import { aheadOf } from "../../services/moment.js";
14
16
  import { openCache } from "../../store/open.js";
15
17
  import { storePath } from "../../store/path.js";
16
- import { ownerLanguages } from "../../store/store.js";
18
+ import { ownerLanguages, storedTemplateBodies } from "../../store/store.js";
17
19
  import { environmentOf, setExitCode } from "../context.js";
18
20
  import { grantsAuthority, LOCAL_READ, LOCAL_WRITE, REMOTE_WRITE } from "../effects.js";
19
21
  import { itemOf, listOf, renderAnswer, snakeKeys } from "../envelope.js";
@@ -157,7 +159,7 @@ const runCapOf = (argv) => {
157
159
  return Number.isFinite(cap) ? cap : null;
158
160
  };
159
161
  /** The language a report is rendered in: the store's `owner_languages`, first one; Russian when it cannot be read. */
160
- const ownerLanguageOf = async (env) => {
162
+ export const ownerLanguageOf = async (env) => {
161
163
  const path = storePath(env);
162
164
  if (!existsSync(path))
163
165
  return "ru";
@@ -170,6 +172,20 @@ const ownerLanguageOf = async (env) => {
170
172
  database.close();
171
173
  }
172
174
  };
175
+ /** The templates the owner saved for a report, read without migrating the store; none when there is no store. */
176
+ const reportTemplatesOf = (env) => async (kind, language) => {
177
+ const path = storePath(env);
178
+ if (!existsSync(path))
179
+ return {};
180
+ const database = await openCache(path);
181
+ try {
182
+ const bodies = storedTemplateBodies(database, reportKeyOf(kind), language);
183
+ return Object.fromEntries(REPORT_CHANNELS.flatMap((channel) => (channel in bodies ? [[channel, bodies[channel]]] : [])));
184
+ }
185
+ finally {
186
+ database.close();
187
+ }
188
+ };
173
189
  /**
174
190
  * Runs the CLI's own commands, or an agent, later or on a timer — through systemd (Linux), launchd
175
191
  * (macOS) or Task Scheduler (Windows). Every timer runs `schedule exec <file>`; the schedule file holds
@@ -446,6 +462,7 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
446
462
  timer: timer(),
447
463
  agentRuns,
448
464
  ownerLanguage: ownerLanguageOf,
465
+ reportTemplates: reportTemplatesOf,
449
466
  ...(agentInput ? { agentInput } : {}),
450
467
  ...(signal ? { signal } : {}),
451
468
  }));
@@ -483,6 +500,7 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
483
500
  timer: timer(),
484
501
  agentRuns,
485
502
  ownerLanguage: ownerLanguageOf,
503
+ reportTemplates: reportTemplatesOf,
486
504
  ...(agentInput ? { agentInput } : {}),
487
505
  untilUnlocked: true,
488
506
  ...(signal ? { signal } : {}),
@@ -815,3 +815,4 @@ export declare const runsCommand: (app: import("./entry.js").AppIdentity) => imp
815
815
  export declare const skillCommand: (app: import("./entry.js").AppIdentity, skill: URL) => import("commander").Command;
816
816
  export declare const upgradeCommand: (app: import("./entry.js").AppIdentity, packageName: string, contextFor: (command: import("commander").Command) => import("./upgrade-command.js").UpgradeContext) => import("commander").Command;
817
817
  export declare const modelCatalogueCommand: (app: import("./entry.js").AppIdentity, options: import("./model-catalogue-command.js").ModelCatalogueOptions) => import("commander").Command;
818
+ export declare const templatesCommand: (app: import("./entry.js").AppIdentity, options: import("./templates-command.js").TemplatesOptions) => import("commander").Command;
@@ -121,4 +121,6 @@ export const runsCommand = sharedCommand(runsCommandDefinition);
121
121
  export const skillCommand = sharedCommand(skillCommandDefinition);
122
122
  export const upgradeCommand = sharedCommand(upgradeCommandDefinition);
123
123
  import { modelCatalogueCommand as modelCatalogueDefinition } from "./model-catalogue-command.js";
124
+ import { templatesCommand as templatesDefinition } from "./templates-command.js";
124
125
  export const modelCatalogueCommand = sharedCommand(modelCatalogueDefinition);
126
+ export const templatesCommand = sharedCommand(templatesDefinition);
@@ -0,0 +1,16 @@
1
+ import { Command } from "commander";
2
+ import type { AppIdentity } from "../ports/app.js";
3
+ import { type Body } from "./envelope.js";
4
+ export interface TemplatesOptions {
5
+ env: () => NodeJS.ProcessEnv;
6
+ output: (answer: Body, command: Command) => void;
7
+ diagnostic: (line: string) => void;
8
+ /** Opens `path` in the owner's editor and returns when it closes; `$VISUAL` or `$EDITOR` when absent. */
9
+ editor?: (path: string, env: NodeJS.ProcessEnv) => void;
10
+ }
11
+ /**
12
+ * `templates`: the owner's own templates for the messages WireCat sends him, kept in the shared store over the ones
13
+ * cli-core ships. The platform rules (escaping, the tags each channel keeps, links only to the report's own, the
14
+ * Telegram size) stay in code and run after every render, so a template cannot break them.
15
+ */
16
+ export declare const templatesCommand: (app: AppIdentity, options: TemplatesOptions) => Command;
@@ -0,0 +1,243 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { CliError, resolvePaths } from "@wirecat/cli-base";
6
+ import { annotate } from "@wirecat/cli-base/commands";
7
+ import { Command, Option } from "commander";
8
+ import { checkTemplate, defaultTemplate, REPORT_CHANNELS, renderReport, } from "../background/report/render.js";
9
+ import { checkTemplateSave, previewView, shippedLanguages, TEMPLATE_KEYS, templateKeyOf, } from "../background/report/stored-templates.js";
10
+ import { agentOf } from "../runs/run-context.js";
11
+ import { openStore } from "../store/store.js";
12
+ import { grantsAuthority, LOCAL_READ, LOCAL_WRITE } from "./effects.js";
13
+ import { itemOf, listOf } from "./envelope.js";
14
+ import { ownerLanguageOf } from "./schedule/schedule-command.js";
15
+ const withStore = async (env, work) => {
16
+ const store = await openStore({ env });
17
+ try {
18
+ return await work(store);
19
+ }
20
+ finally {
21
+ await store.close();
22
+ }
23
+ };
24
+ const systemEditor = (path, env) => {
25
+ const editor = env.VISUAL?.trim() || env.EDITOR?.trim();
26
+ if (!editor)
27
+ throw new CliError("validation_error", "set VISUAL or EDITOR, or pass the template with --file", {
28
+ reason: "template.no-editor",
29
+ });
30
+ const [program = editor, ...args] = editor.split(/\s+/);
31
+ const ran = spawnSync(program, [...args, path], { stdio: "inherit", env });
32
+ if (ran.status !== 0)
33
+ throw new CliError("validation_error", `the editor exited with ${ran.status ?? ran.signal}; nothing was saved`);
34
+ };
35
+ const channelOption = () => new Option("--channel <channel>", "telegram (Bot API HTML), email (HTML with inline styles) or text")
36
+ .choices(REPORT_CHANNELS)
37
+ .makeOptionMandatory();
38
+ const languageOption = () => new Option("--language <code>", "the template's language, ISO 639-1; the owner's first language if not given");
39
+ /** The key, its report kind and the language, refused when nothing renders the key or cli-core ships no such language. */
40
+ const addressOf = async (key, given, env) => {
41
+ const known = templateKeyOf(key);
42
+ if (!known)
43
+ throw new CliError("validation_error", `no template ${key}; the keys are ${TEMPLATE_KEYS.map((one) => one.key).join(", ")}`, {
44
+ reason: "template.unknown-key",
45
+ });
46
+ if (known.kind === null)
47
+ throw new CliError("validation_error", `nothing renders ${key} yet (${known.about}), so a template for it cannot be checked or saved`, { reason: "template.no-renderer" });
48
+ const language = (given.language ?? (await ownerLanguageOf(env))).trim().toLowerCase();
49
+ const languages = shippedLanguages(known.kind);
50
+ if (!languages.includes(language))
51
+ throw new CliError("validation_error", `${key} has templates in ${languages.join(", ")}; a ${language} one would never be used`, { reason: "template.unknown-language" });
52
+ return { address: { key, channel: given.channel, language }, kind: known.kind, channel: given.channel };
53
+ };
54
+ const refuseAgent = (env) => {
55
+ // A template decides what every later digest says to the owner; an agent could make it hide or invent things.
56
+ if (agentOf(env))
57
+ throw new CliError("permission_error", "only the owner changes a message template, not an agent", {
58
+ reason: "template.owner-only",
59
+ });
60
+ };
61
+ const stateOf = (app, env) => resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state;
62
+ const historyOf = (store, address) => store.templates.history(address).map((entry) => ({
63
+ id: entry.id,
64
+ saved_at: new Date(entry.savedAt).toISOString(),
65
+ saved_by: entry.savedBy,
66
+ replaced_at: new Date(entry.replacedAt).toISOString(),
67
+ chars: entry.body.length,
68
+ }));
69
+ /**
70
+ * `templates`: the owner's own templates for the messages WireCat sends him, kept in the shared store over the ones
71
+ * cli-core ships. The platform rules (escaping, the tags each channel keeps, links only to the report's own, the
72
+ * Telegram size) stay in code and run after every render, so a template cannot break them.
73
+ */
74
+ export const templatesCommand = (app, options) => {
75
+ const editor = options.editor ?? systemEditor;
76
+ const templates = annotate(new Command("templates"), { effects: LOCAL_READ }).description("the templates of the digest and the other messages sent to you, per channel and language; edit, preview, reset");
77
+ annotate(templates.command("list"), {
78
+ effects: LOCAL_READ,
79
+ examples: [`${app.command} templates list`],
80
+ })
81
+ .description("every template key, channel and language, and whether yours or the shipped one applies")
82
+ .action(async function () {
83
+ const env = options.env();
84
+ const stored = await withStore(env, (store) => store.templates.list());
85
+ const items = TEMPLATE_KEYS.flatMap((known) => REPORT_CHANNELS.flatMap((channel) => (known.kind === null ? [null] : shippedLanguages(known.kind)).map((language) => {
86
+ const row = stored.find((one) => one.key === known.key && one.channel === channel && one.language === language);
87
+ return {
88
+ key: known.key,
89
+ channel,
90
+ language,
91
+ about: known.about,
92
+ renders: known.kind !== null,
93
+ source: row ? "stored" : known.kind === null ? "none" : "default",
94
+ updated_at: row ? new Date(row.updatedAt).toISOString() : null,
95
+ updated_by: row?.updatedBy ?? null,
96
+ };
97
+ })));
98
+ options.output(listOf("templates list", { items, limit: items.length, has_more: false }), this);
99
+ });
100
+ annotate(templates.command("show"), {
101
+ effects: LOCAL_READ,
102
+ examples: [`${app.command} templates show report/morning-digest --channel telegram`],
103
+ })
104
+ .description("the template that applies, yours or the shipped one, and the bodies your changes replaced")
105
+ .argument("<key>", "the template, such as report/morning-digest")
106
+ .addOption(channelOption())
107
+ .addOption(languageOption())
108
+ .action(async function (key, given) {
109
+ const env = options.env();
110
+ const { address, kind, channel } = await addressOf(key, given, env);
111
+ const item = await withStore(env, (store) => {
112
+ const row = store.templates.get(address);
113
+ return {
114
+ ...address,
115
+ source: row ? "stored" : "default",
116
+ body: row?.body ?? defaultTemplate(kind, channel, address.language),
117
+ updated_at: row ? new Date(row.updatedAt).toISOString() : null,
118
+ updated_by: row?.updatedBy ?? null,
119
+ history: historyOf(store, address),
120
+ };
121
+ });
122
+ options.output(itemOf(item), this);
123
+ });
124
+ grantsAuthority(annotate(templates.command("edit"), {
125
+ effects: LOCAL_WRITE,
126
+ examples: [
127
+ `${app.command} templates edit report/morning-digest --channel telegram`,
128
+ `${app.command} templates edit report/morning-digest --channel text --file digest.text.liquid`,
129
+ `${app.command} templates edit report/morning-digest --channel telegram --undo`,
130
+ ],
131
+ }))
132
+ .description("change a template in $EDITOR or from --file; it is checked first, and a failed check saves nothing and says why")
133
+ .argument("<key>", "the template, such as report/morning-digest")
134
+ .addOption(channelOption())
135
+ .addOption(languageOption())
136
+ .option("--file <path>", "take the new template from this file instead of opening an editor")
137
+ .addOption(new Option("--undo", "put back the body your last change replaced; twice is back where you were").conflicts("file"))
138
+ .action(async function (key, given) {
139
+ const env = options.env();
140
+ refuseAgent(env);
141
+ const { address, kind, channel } = await addressOf(key, given, env);
142
+ const { current, previous } = await withStore(env, (store) => ({
143
+ current: store.templates.get(address)?.body,
144
+ previous: store.templates.history(address, 1)[0]?.body,
145
+ }));
146
+ const effective = current ?? defaultTemplate(kind, channel, address.language);
147
+ let draft;
148
+ let body;
149
+ if (given.undo) {
150
+ if (previous === undefined)
151
+ throw new CliError("validation_error", `${key} ${channel} ${address.language} has no earlier body to put back`, {
152
+ reason: "template.no-history",
153
+ });
154
+ body = previous;
155
+ }
156
+ else if (given.file !== undefined) {
157
+ body = readFileSync(given.file, "utf8");
158
+ }
159
+ else {
160
+ draft = join(mkdtempSync(join(tmpdir(), "wirecat-template-")), `${key.replace("/", "-")}.${channel}.${address.language}.liquid`);
161
+ writeFileSync(draft, effective, { mode: 0o600 });
162
+ editor(draft, env);
163
+ body = readFileSync(draft, "utf8");
164
+ }
165
+ if (body === effective) {
166
+ if (draft)
167
+ rmSync(join(draft, ".."), { recursive: true, force: true });
168
+ options.diagnostic(`${key} ${channel} ${address.language} is unchanged; nothing saved`);
169
+ options.output(itemOf({ ...address, changed: false }), this);
170
+ return;
171
+ }
172
+ const checks = await checkTemplateSave({
173
+ kind,
174
+ channel,
175
+ language: address.language,
176
+ body,
177
+ state: stateOf(app, env),
178
+ now: Date.now(),
179
+ });
180
+ const problems = checks.flatMap((check) => check.problems.map((problem) => `${check.against}: ${problem}`));
181
+ if (problems.length > 0)
182
+ throw new CliError("validation_error", `the template was not saved — ${problems.join("; ")}${draft ? `. Your text is in ${draft}; fix it and run again with --file ${draft}` : ""}`, { reason: "template.check-failed" });
183
+ const saved = await withStore(env, (store) => store.templates.save(address, body, app.command));
184
+ if (draft)
185
+ rmSync(join(draft, ".."), { recursive: true, force: true });
186
+ options.diagnostic(`saved ${key} ${channel} ${address.language}; checked against ${checks.map((check) => check.against).join(" and ")}`);
187
+ options.output(itemOf({
188
+ ...address,
189
+ changed: true,
190
+ updated_at: new Date(saved.updatedAt).toISOString(),
191
+ updated_by: saved.updatedBy,
192
+ checked_against: checks.map((check) => check.against),
193
+ }), this);
194
+ });
195
+ annotate(templates.command("preview"), {
196
+ effects: LOCAL_READ,
197
+ examples: [
198
+ `${app.command} templates preview report/morning-digest --channel telegram`,
199
+ `${app.command} templates preview report/morning-digest --channel email --file draft.liquid`,
200
+ ],
201
+ })
202
+ .description("what would be sent on that channel, from the last real report or a synthetic one when there is none; saves nothing")
203
+ .argument("<key>", "the template, such as report/morning-digest")
204
+ .addOption(channelOption())
205
+ .addOption(languageOption())
206
+ .option("--file <path>", "preview this draft instead of the template that applies")
207
+ .action(async function (key, given) {
208
+ const env = options.env();
209
+ const { address, kind, channel } = await addressOf(key, given, env);
210
+ const stored = given.file === undefined ? await withStore(env, (store) => store.templates.get(address)?.body) : undefined;
211
+ const body = given.file === undefined ? stored : readFileSync(given.file, "utf8");
212
+ const { against, view } = previewView(stateOf(app, env), kind, address.language, Date.now());
213
+ const rendering = await renderReport(view, channel, body === undefined ? {} : { template: body });
214
+ const problems = body === undefined ? [] : (await checkTemplate(view, channel, body)).problems;
215
+ options.output(itemOf({
216
+ ...address,
217
+ template: given.file === undefined ? (stored === undefined ? "default" : "stored") : given.file,
218
+ against,
219
+ template_failed: rendering.templateFailed,
220
+ problems,
221
+ text: rendering.text,
222
+ }), this);
223
+ });
224
+ grantsAuthority(annotate(templates.command("reset"), {
225
+ effects: LOCAL_WRITE,
226
+ examples: [`${app.command} templates reset report/morning-digest --channel telegram`],
227
+ }))
228
+ .description("go back to the shipped template; yours is kept in the history, and edit --undo brings it back")
229
+ .argument("<key>", "the template, such as report/morning-digest")
230
+ .addOption(channelOption())
231
+ .addOption(languageOption())
232
+ .action(async function (key, given) {
233
+ const env = options.env();
234
+ refuseAgent(env);
235
+ const { address } = await addressOf(key, given, env);
236
+ const changed = await withStore(env, (store) => store.templates.reset(address));
237
+ options.diagnostic(changed
238
+ ? `${key} ${address.channel} ${address.language} uses the shipped template again`
239
+ : `${key} ${address.channel} ${address.language} already uses the shipped template`);
240
+ options.output(itemOf({ ...address, changed }), this);
241
+ });
242
+ return templates;
243
+ };
@@ -87,3 +87,23 @@ export declare const accountPrivacyChange: v.StrictObjectSchema<{
87
87
  readonly last_seen: v.OptionalSchema<v.PicklistSchema<["everyone", "contacts", "nobody", "contacts_except"], undefined>, undefined>;
88
88
  }, undefined>;
89
89
  }, undefined>;
90
+ export declare const accountRemoval: v.StrictObjectSchema<{
91
+ readonly profile: v.StringSchema<undefined>;
92
+ readonly data: v.PicklistSchema<["kept", "deleted"], undefined>;
93
+ readonly dry_run: v.BooleanSchema<undefined>;
94
+ readonly account: v.NullableSchema<v.StrictObjectSchema<{
95
+ readonly provider: v.StringSchema<undefined>;
96
+ readonly account: v.StringSchema<undefined>;
97
+ }, undefined>, undefined>;
98
+ readonly revoked: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
99
+ readonly config_file: v.StringSchema<undefined>;
100
+ readonly removed: v.ArraySchema<v.StrictObjectSchema<{
101
+ readonly kind: v.PicklistSchema<["sign_in", "keyring", "config", "file", "store", "unit", "schedule"], undefined>;
102
+ readonly target: v.StringSchema<undefined>;
103
+ }, undefined>, undefined>;
104
+ readonly kept: v.ArraySchema<v.StrictObjectSchema<{
105
+ readonly kind: v.PicklistSchema<["sign_in", "keyring", "config", "file", "store", "unit", "schedule"], undefined>;
106
+ readonly target: v.StringSchema<undefined>;
107
+ readonly reason: v.StringSchema<undefined>;
108
+ }, undefined>, undefined>;
109
+ }, undefined>;
@@ -1,7 +1,7 @@
1
1
  import * as v from "valibot";
2
2
  import { account } from "./account.js";
3
3
  import { accountSession } from "./account-session.js";
4
- import { id } from "./fields.js";
4
+ import { id, text } from "./fields.js";
5
5
  export const accountChange = v.strictObject({ operation_id: id, account: v.omit(account, ["provider", "scope"]) });
6
6
  export const endedAccountSessions = v.strictObject({ operation_id: id, sessions: v.array(accountSession) });
7
7
  const audience = v.picklist(["everyone", "contacts", "nobody"]);
@@ -18,3 +18,14 @@ export const accountPrivacy = v.strictObject({
18
18
  last_seen: v.optional(shownAudience),
19
19
  });
20
20
  export const accountPrivacyChange = v.strictObject({ operation_id: id, privacy: accountPrivacy });
21
+ const removalKind = v.picklist(["sign_in", "keyring", "config", "file", "store", "unit", "schedule"]);
22
+ export const accountRemoval = v.strictObject({
23
+ profile: text,
24
+ data: v.picklist(["kept", "deleted"]),
25
+ dry_run: v.boolean(),
26
+ account: v.nullable(v.strictObject({ provider: text, account: text })),
27
+ revoked: v.nullable(v.boolean()),
28
+ config_file: text,
29
+ removed: v.array(v.strictObject({ kind: removalKind, target: text })),
30
+ kept: v.array(v.strictObject({ kind: removalKind, target: text, reason: text })),
31
+ });
@@ -4041,6 +4041,26 @@ export declare const ENTITIES: {
4041
4041
  readonly created_at: v.OptionalSchema<v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>, undefined>, undefined>;
4042
4042
  }, undefined>, undefined>;
4043
4043
  }, undefined>;
4044
+ readonly account_removal: v.StrictObjectSchema<{
4045
+ readonly profile: v.StringSchema<undefined>;
4046
+ readonly data: v.PicklistSchema<["kept", "deleted"], undefined>;
4047
+ readonly dry_run: v.BooleanSchema<undefined>;
4048
+ readonly account: v.NullableSchema<v.StrictObjectSchema<{
4049
+ readonly provider: v.StringSchema<undefined>;
4050
+ readonly account: v.StringSchema<undefined>;
4051
+ }, undefined>, undefined>;
4052
+ readonly revoked: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
4053
+ readonly config_file: v.StringSchema<undefined>;
4054
+ readonly removed: v.ArraySchema<v.StrictObjectSchema<{
4055
+ readonly kind: v.PicklistSchema<["sign_in", "keyring", "config", "file", "store", "unit", "schedule"], undefined>;
4056
+ readonly target: v.StringSchema<undefined>;
4057
+ }, undefined>, undefined>;
4058
+ readonly kept: v.ArraySchema<v.StrictObjectSchema<{
4059
+ readonly kind: v.PicklistSchema<["sign_in", "keyring", "config", "file", "store", "unit", "schedule"], undefined>;
4060
+ readonly target: v.StringSchema<undefined>;
4061
+ readonly reason: v.StringSchema<undefined>;
4062
+ }, undefined>, undefined>;
4063
+ }, undefined>;
4044
4064
  readonly account_privacy: v.StrictObjectSchema<{
4045
4065
  readonly find_by_phone: v.OptionalSchema<v.PicklistSchema<["everyone", "contacts", "nobody"], undefined>, undefined>;
4046
4066
  readonly phone_number: v.OptionalSchema<v.PicklistSchema<["everyone", "contacts", "nobody"], undefined>, undefined>;
@@ -2,7 +2,7 @@ import { jsonSchemaOf } from "@wirecat/cli-base/standards";
2
2
  import * as v from "valibot";
3
3
  import { MEETING_RESULT_ENTITIES } from "../meetings/index.js";
4
4
  import { account } from "./account.js";
5
- import { accountChange, accountPrivacy, accountPrivacyChange, endedAccountSessions } from "./account-change.js";
5
+ import { accountChange, accountPrivacy, accountPrivacyChange, accountRemoval, endedAccountSessions, } from "./account-change.js";
6
6
  import { accountProfile } from "./account-profile.js";
7
7
  import { accountSession } from "./account-session.js";
8
8
  import { adminReport } from "./admin-report.js";
@@ -186,6 +186,7 @@ export const ENTITIES = {
186
186
  account_session: accountSession,
187
187
  account_change: accountChange,
188
188
  ended_account_sessions: endedAccountSessions,
189
+ account_removal: accountRemoval,
189
190
  account_privacy: accountPrivacy,
190
191
  account_privacy_change: accountPrivacyChange,
191
192
  account_profile: accountProfile,
@@ -35,6 +35,16 @@ const SIGN_IN = [
35
35
  ["oauth.scope-missing", "permission_error", "the sign-in lacks a permission this command needs"],
36
36
  ["sign-in.client-rejected", "configuration_error", "the provider rejected the OAuth client"],
37
37
  ["sign-in.secret-without-id", "configuration_error", "an OAuth client secret is set without its client id"],
38
+ validation("account-remove.no-choice", "account remove needs --keep-data or --delete-data, one of them"),
39
+ ["account-remove.unknown-profile", "not_found", "no profile by this name on this computer"],
40
+ ["account-remove.busy", "conflict", "a serve or a sync runs for this profile; stop it first"],
41
+ ["account-remove.unconfirmed", "confirmation_required", "removing an account asks first; add --yes"],
42
+ ["account-remove.path-outside", "configuration_error", "the tool named a path outside its own folders"],
43
+ [
44
+ "account-remove.folder-outside",
45
+ "configuration_error",
46
+ "the tool named a folder of its own outside the home folder",
47
+ ],
38
48
  ];
39
49
  /** Reasons every CLI over a provider's API raises alike: gcal and drive today. */
40
50
  const PROVIDER_API = [
@@ -386,6 +396,13 @@ const OTHERS = [
386
396
  validation("tag-review.required", "the tag needs the owner's review first"),
387
397
  ["tag-review.stale", "configuration_error", "the tag review changed meanwhile"],
388
398
  validation("tag.invalid", "the tag is not valid"),
399
+ validation("template.unknown-key", "there is no message template by that key"),
400
+ validation("template.no-renderer", "nothing renders that template key yet, so a template for it cannot be checked"),
401
+ validation("template.unknown-language", "cli-core ships no template in that language, so one would never be used"),
402
+ validation("template.check-failed", "the template failed its check and was not saved; the message says why"),
403
+ validation("template.no-history", "the template has no earlier body to put back"),
404
+ validation("template.no-editor", "no editor is set: set VISUAL or EDITOR, or pass the template with --file"),
405
+ ["template.owner-only", "permission_error", "only the owner changes a message template, not an agent"],
389
406
  ["reactions.list-hidden", "permission_error", "the chat does not let its members see who reacted"],
390
407
  ["reactions.broadcast", "permission_error", "a channel does not show who reacted to its posts"],
391
408
  validation("task.external-id", "an external id is <service>:<id>, such as avito:4512345678"),
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
- error?: undefined;
18
17
  chatId: string;
19
18
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
20
19
  algorithm: string;
21
20
  fetchedAt: string | null;
22
21
  source: string;
22
+ error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -30,6 +30,8 @@ export interface AccountsStore extends AccountAccounts {
30
30
  profiles(): Promise<Profiles>;
31
31
  /** Records which account a profile of `app` is; a no-op when the store already says so. */
32
32
  saveProfile(app: string, profile: string, key: AccountKey): Promise<void>;
33
+ /** Forgets which account a profile of `app` is; a no-op when the store never knew. */
34
+ forgetProfile(app: string, profile: string): Promise<void>;
33
35
  /** Writes a CLI's provider entry for every tool on this store to read; see `registerProvider`. */
34
36
  registerProvider(entry: ProviderEntry): Promise<void>;
35
37
  }
@@ -1,6 +1,6 @@
1
1
  import { ACCOUNT_GROUPS } from "../search/account-list.js";
2
2
  import { keysOver } from "./keys.js";
3
- import { accountGroupsOf, profilesOf, saveProfile } from "./sqlite/account-groups.js";
3
+ import { accountGroupsOf, forgetProfile, profilesOf, saveProfile } from "./sqlite/account-groups.js";
4
4
  import * as accounts from "./sqlite/accounts.js";
5
5
  import { linkOwnIdentities } from "./sqlite/own-identities.js";
6
6
  import { registerProvider } from "./sqlite/providers.js";
@@ -38,6 +38,7 @@ export const accountsStoreOver = (context, keyed) => {
38
38
  accountGroups: async () => accountGroupsOf(database),
39
39
  profiles: async () => profilesOf(database),
40
40
  saveProfile: async (app, profile, key) => write(database, () => saveProfile(database, app, profile, key, context.now())),
41
+ forgetProfile: async (app, profile) => write(database, () => forgetProfile(database, app, profile, context.now())),
41
42
  registerProvider: async (entry) => registerProvider(database, entry, context.now()),
42
43
  saveAccountGroup: async (name, members) => write(database, () => {
43
44
  const groups = accountGroupsOf(database);
@@ -60,6 +60,7 @@ export { savedTaskCategories } from "./sqlite/task-category-settings.js";
60
60
  export { DEFAULT_AGENT_CLOSE, savedAgentClose } from "./sqlite/task-close.js";
61
61
  export { DEFAULT_FIRST_PASS_PER_CHAT, firstPassPerChatOf, savedFirstPassPerChat } from "./sqlite/task-first-pass.js";
62
62
  export { inboxKey } from "./sqlite/tasks.js";
63
+ export { storedTemplateBodies, type TemplateAddress } from "./sqlite/templates.js";
63
64
  export { THREAD_COLUMNS } from "./sqlite/thread-columns.js";
64
65
  export { dropAllUnusedVectors, vectorIndexCounts } from "./sqlite/vector-index.js";
65
66
  export type { MatchPlace, ScoredHit } from "./sqlite/words.js";
@@ -30,5 +30,6 @@ export { savedTaskCategories } from "./sqlite/task-category-settings.js";
30
30
  export { DEFAULT_AGENT_CLOSE, savedAgentClose } from "./sqlite/task-close.js";
31
31
  export { DEFAULT_FIRST_PASS_PER_CHAT, firstPassPerChatOf, savedFirstPassPerChat } from "./sqlite/task-first-pass.js";
32
32
  export { inboxKey } from "./sqlite/tasks.js";
33
+ export { storedTemplateBodies } from "./sqlite/templates.js";
33
34
  export { THREAD_COLUMNS } from "./sqlite/thread-columns.js";
34
35
  export { dropAllUnusedVectors, vectorIndexCounts } from "./sqlite/vector-index.js";
@@ -99,6 +99,7 @@ export type { TaskRelation, TaskRelationKind, TaskRelationsStore } from "./sqlit
99
99
  export { TASK_RELATION_KINDS } from "./sqlite/task-relations.js";
100
100
  export type { TaskStatRow, TaskStatScope } from "./sqlite/task-stats.js";
101
101
  export type { StoreTaskStore } from "./sqlite/tasks.js";
102
+ export type { StoredTemplate, TemplateAddress, TemplateHistoryEntry, TemplateStore } from "./sqlite/templates.js";
102
103
  export type { TagPreflight, VocabularyAlias, VocabularyAliasReceipt, VocabularyAudit, VocabularyAuditOptions, VocabularyCatalog, VocabularyEntry, VocabularyKind, VocabularyOptions, VocabularyResolution, VocabularyStore, VocabularyTarget, } from "./sqlite/vocabulary.js";
103
104
  export type { Wallet, WalletFilter, WalletInput, WalletsStore, WalletUpdate } from "./sqlite/wallets.js";
104
105
  export type { BoardCounts, BoardOptions, EditedTask, MovedSubtask, NewWorkTask, RevisionCheck, TaskAssignment, TaskDetails, TaskEvent, TaskFields, TaskMove, TaskMoved, TaskRole, TaskType, WorkTaskType, } from "./sqlite/work-tasks.js";
@@ -8,3 +8,4 @@ export declare const saveProfile: (database: CacheDatabase, app: string, profile
8
8
  provider: string;
9
9
  account: string;
10
10
  }, now: number) => void;
11
+ export declare const forgetProfile: (database: CacheDatabase, app: string, profile: string, now: number) => void;
@@ -38,3 +38,17 @@ export const saveProfile = (database, app, profile, key, now) => {
38
38
  .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
39
39
  .run(PROFILES, JSON.stringify(profiles), now);
40
40
  };
41
+ export const forgetProfile = (database, app, profile, now) => {
42
+ const profiles = profilesOf(database);
43
+ const own = profiles[app];
44
+ if (own?.[profile] === undefined)
45
+ return;
46
+ const { [profile]: _, ...rest } = own;
47
+ if (Object.keys(rest).length === 0)
48
+ delete profiles[app];
49
+ else
50
+ profiles[app] = rest;
51
+ database
52
+ .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
53
+ .run(PROFILES, JSON.stringify(profiles), now);
54
+ };
@@ -122,6 +122,7 @@ export const MANIFEST = [
122
122
  { name: "20261108010754_version-57-business-rules", version: 57, minCompatible: 56 },
123
123
  { name: "20261108104659_version-58-enrichments", version: 58, minCompatible: 56 },
124
124
  { name: "20261108104701_version-58-enrichments-deletes", version: 58, minCompatible: 56 },
125
+ { name: "20261108165309_version-59-templates", version: 59, minCompatible: 56 },
125
126
  ];
126
127
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
127
128
  const migrations = [];
@@ -1208,5 +1208,13 @@ export const GENERATED = [
1208
1208
  "CREATE TRIGGER enrichments_note_gone AFTER DELETE ON notes BEGIN\n DELETE FROM enrichments WHERE subject_type = 'note' AND subject_id = OLD.id;\nEND;",
1209
1209
  "CREATE TRIGGER enrichments_email_gone AFTER DELETE ON emails BEGIN\n DELETE FROM enrichments WHERE subject_type = 'email' AND subject_id = OLD.id;\n DELETE FROM chunks WHERE chunkable_type = 'email_enrichment' AND chunkable_id = OLD.id;\nEND;"
1210
1210
  ]
1211
+ },
1212
+ {
1213
+ "name": "20261108165309_version-59-templates",
1214
+ "statements": [
1215
+ "CREATE TABLE `templates` (\n\t`key` text NOT NULL,\n\t`channel` text NOT NULL,\n\t`language` text NOT NULL,\n\t`body` text NOT NULL,\n\t`updated_at` integer NOT NULL,\n\t`updated_by` text NOT NULL,\n\tCONSTRAINT `templates_pk` PRIMARY KEY(`key`, `channel`, `language`)\n);",
1216
+ "CREATE TABLE `templates_history` (\n\t`id` integer PRIMARY KEY,\n\t`key` text NOT NULL,\n\t`channel` text NOT NULL,\n\t`language` text NOT NULL,\n\t`body` text NOT NULL,\n\t`saved_at` integer NOT NULL,\n\t`saved_by` text NOT NULL,\n\t`replaced_at` integer NOT NULL\n);",
1217
+ "CREATE INDEX `templates_history_by_key_channel_language_id` ON `templates_history` (`key`,`channel`,`language`,`id`);"
1218
+ ]
1211
1219
  }
1212
1220
  ];