@wirecat/cli-core 0.613.0 → 0.614.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,26 @@ 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.614.0 — 08.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`account remove`, built once for every tool.** `<tool> <profile> account remove --keep-data|--delete-data` signs
13
+ the profile out with the tool's own `signOut` hook, then forgets it here: its keyring entries, its
14
+ `state/accounts/<profile>.json`, the tool's own state files and its sections in the config file; other profiles stay.
15
+ `--delete-data` also purges the account from the shared store (`store.accounts.purge`) and deletes the tool's data
16
+ files; `--keep-data` leaves its messages in the store, still searchable, and says so under `kept`. It asks first, or
17
+ `--yes`; under `--json` without `--yes` it answers `confirmation_required`; `--dry-run` lists every entry, section and
18
+ file. It refuses while a serve or a sync holds the profile, a path outside the tool's own folders, and runs neither
19
+ over MCP nor under `<PREFIX>_READ_ONLY`. The answer is the entity `account_removal`; reasons `account-remove.*`.
20
+ A messenger opts in with `Messenger.accountRemoval`; any other CLI mounts `accountRemoveCommand(app, hooks)`
21
+ ([guide](docs/dev/ACCOUNT-REMOVAL.md)). `store.accounts.forgetProfile` forgets which account a profile was.
22
+ It also removes what cli-core keeps for the profile, so no tool lists it: its flood, pace, recipients, moderation,
23
+ provider log, MCP HTTP tokens, replies state and rules, `--new` points and checkpoints, its serve unit (by its exact
24
+ name) and the schedules whose environment names it. The sends journal stays, under `kept`. A tool whose files live
25
+ outside its cli-core folders names them with the `ownFolders` hook; each must be absolute and inside the home folder
26
+ (`account-remove.folder-outside`).
27
+
8
28
  ## 0.612.0 — 08.11.2026
9
29
 
10
30
  ### Changed — may break callers
@@ -10,13 +10,13 @@ export declare const calendarTools: ({
10
10
  inputSchema: {
11
11
  type: string;
12
12
  properties: {
13
- limit?: undefined;
14
13
  account_id: {
15
14
  type: string;
16
15
  minimum: number;
17
16
  };
18
17
  query?: undefined;
19
18
  timezone?: undefined;
19
+ limit?: undefined;
20
20
  page?: undefined;
21
21
  event?: undefined;
22
22
  } | {
@@ -45,9 +45,9 @@ export declare const calendarTools: ({
45
45
  };
46
46
  event?: undefined;
47
47
  } | {
48
- limit?: undefined;
49
48
  query?: undefined;
50
49
  timezone?: undefined;
50
+ limit?: undefined;
51
51
  page?: undefined;
52
52
  event: {
53
53
  type: string;
@@ -58,9 +58,9 @@ export declare const calendarTools: ({
58
58
  minimum: number;
59
59
  };
60
60
  } | {
61
- limit?: undefined;
62
61
  query?: undefined;
63
62
  timezone?: undefined;
63
+ limit?: undefined;
64
64
  page?: undefined;
65
65
  event?: undefined;
66
66
  account_id?: undefined;
@@ -80,13 +80,13 @@ export declare const calendarTools: ({
80
80
  inputSchema: {
81
81
  type: string;
82
82
  properties: {
83
- limit?: undefined;
84
83
  account_id: {
85
84
  type: string;
86
85
  minimum: number;
87
86
  };
88
87
  query?: undefined;
89
88
  timezone?: undefined;
89
+ limit?: undefined;
90
90
  page?: undefined;
91
91
  event?: undefined;
92
92
  } | {
@@ -115,9 +115,9 @@ export declare const calendarTools: ({
115
115
  };
116
116
  event?: undefined;
117
117
  } | {
118
- limit?: undefined;
119
118
  query?: undefined;
120
119
  timezone?: undefined;
120
+ limit?: undefined;
121
121
  page?: undefined;
122
122
  event: {
123
123
  type: string;
@@ -128,9 +128,9 @@ export declare const calendarTools: ({
128
128
  minimum: number;
129
129
  };
130
130
  } | {
131
- limit?: undefined;
132
131
  query?: undefined;
133
132
  timezone?: undefined;
133
+ limit?: undefined;
134
134
  page?: undefined;
135
135
  event?: undefined;
136
136
  account_id?: undefined;
@@ -150,13 +150,13 @@ export declare const calendarTools: ({
150
150
  inputSchema: {
151
151
  type: string;
152
152
  properties: {
153
- limit?: undefined;
154
153
  account_id: {
155
154
  type: string;
156
155
  minimum: number;
157
156
  };
158
157
  query?: undefined;
159
158
  timezone?: undefined;
159
+ limit?: undefined;
160
160
  page?: undefined;
161
161
  event?: undefined;
162
162
  } | {
@@ -185,9 +185,9 @@ export declare const calendarTools: ({
185
185
  };
186
186
  event?: undefined;
187
187
  } | {
188
- limit?: undefined;
189
188
  query?: undefined;
190
189
  timezone?: undefined;
190
+ limit?: undefined;
191
191
  page?: undefined;
192
192
  event: {
193
193
  type: string;
@@ -198,9 +198,9 @@ export declare const calendarTools: ({
198
198
  minimum: number;
199
199
  };
200
200
  } | {
201
- limit?: undefined;
202
201
  query?: undefined;
203
202
  timezone?: undefined;
203
+ limit?: undefined;
204
204
  page?: undefined;
205
205
  event?: undefined;
206
206
  account_id?: undefined;
@@ -220,13 +220,13 @@ export declare const calendarTools: ({
220
220
  inputSchema: {
221
221
  type: string;
222
222
  properties: {
223
- limit?: undefined;
224
223
  account_id: {
225
224
  type: string;
226
225
  minimum: number;
227
226
  };
228
227
  query?: undefined;
229
228
  timezone?: undefined;
229
+ limit?: undefined;
230
230
  page?: undefined;
231
231
  event?: undefined;
232
232
  } | {
@@ -255,9 +255,9 @@ export declare const calendarTools: ({
255
255
  };
256
256
  event?: undefined;
257
257
  } | {
258
- limit?: undefined;
259
258
  query?: undefined;
260
259
  timezone?: undefined;
260
+ limit?: undefined;
261
261
  page?: undefined;
262
262
  event: {
263
263
  type: string;
@@ -268,9 +268,9 @@ export declare const calendarTools: ({
268
268
  minimum: number;
269
269
  };
270
270
  } | {
271
- limit?: undefined;
272
271
  query?: undefined;
273
272
  timezone?: undefined;
273
+ limit?: undefined;
274
274
  page?: undefined;
275
275
  event?: undefined;
276
276
  account_id?: undefined;
@@ -0,0 +1,67 @@
1
+ import { type CredentialsOptions, type KeyringStore } from "@wirecat/cli-base";
2
+ import { Command } from "commander";
3
+ import type { Provider } from "../domain/models.js";
4
+ import type { AppIdentity } from "../ports/app.js";
5
+ import type { AccountKey } from "../store/types.js";
6
+ import type { GlobalFlags, ResolveOptions, Settings } from "./settings.js";
7
+ export interface AccountRemovalContext {
8
+ env: NodeJS.ProcessEnv;
9
+ /** The run's keyring; `undefined` is the system one. A test hands in `memoryKeyring()`. */
10
+ keyring?: KeyringStore;
11
+ /**
12
+ * False in a run with moved folders (WC-SECR-24): it shares the owner's keyring entry and must not revoke the
13
+ * owner's sign-in at the provider, only forget its own copy.
14
+ */
15
+ mayRevoke: boolean;
16
+ }
17
+ export interface SignedOut {
18
+ /** Whether the provider confirmed it took the sign-in back; `null` when the tool does not revoke. */
19
+ revoked: boolean | null;
20
+ /** What the sign-out deleted, in words or paths the owner recognises: "the Telegram session", a session file. */
21
+ removed: string[];
22
+ }
23
+ /** One set of keyring entries of the profile, at the options the tool reads them with. */
24
+ export interface AccountSecrets {
25
+ credentials: CredentialsOptions;
26
+ accounts: readonly string[];
27
+ }
28
+ /**
29
+ * What a tool hands `account remove`. Only `signOut` is required: the tool alone knows what its sign-in is. Every
30
+ * path a hook names must lie inside the tool's own config, state or cache folder; the command refuses one outside.
31
+ */
32
+ export interface AccountRemoval {
33
+ /**
34
+ * Signs the profile out the tool's own way: ends the session at the provider, deletes the token or the device keys,
35
+ * revokes when `mayRevoke`. It runs before anything is forgotten, so a throw stops the removal with everything kept.
36
+ */
37
+ signOut(profile: string, context: AccountRemovalContext): Promise<SignedOut>;
38
+ /** The profile's account in the shared store. Unset: the account `rememberAccount` recorded for it. */
39
+ account?(profile: string, context: AccountRemovalContext): AccountKey | undefined;
40
+ /** Keyring entries of this profile the sign-out leaves: app keys, a bot token. Removing a missing one is fine. */
41
+ secrets?(profile: string, context: AccountRemovalContext): AccountSecrets[];
42
+ /** The tool's own files and folders for this profile that hold no messages: cursors, a device id. Always removed. */
43
+ stateFiles?(profile: string, context: AccountRemovalContext): string[];
44
+ /** Files and folders holding this account's data outside the store: removed only with `--delete-data`. */
45
+ dataFiles?(profile: string, context: AccountRemovalContext): string[];
46
+ /** Removes the profile from a config file the tool keeps itself. Unset: cli-core's config file, as `settingsFor` reads it. */
47
+ forgetConfig?(profile: string, context: AccountRemovalContext): string[];
48
+ /** What holds this profile now, beyond a serve cli-core sees itself: "a sync", or `undefined`. */
49
+ busy?(profile: string, context: AccountRemovalContext): string | undefined;
50
+ /**
51
+ * Folders the tool keeps outside the ones its cli-core identity names, where its hooks' paths may also lie: zoom's
52
+ * `~/.config/zm` and `~/.local/share/zm`. Each must be absolute and inside the home folder.
53
+ */
54
+ ownFolders?(context: AccountRemovalContext): string[];
55
+ }
56
+ export interface AccountRemoveOptions {
57
+ /** The provider of the remembered account. Needed only when `account` is unset. */
58
+ provider?: Provider;
59
+ /** Unset: the one `run()` set. */
60
+ resolveSettings?: (flags: GlobalFlags, options?: ResolveOptions) => Settings;
61
+ }
62
+ /**
63
+ * `<tool> <profile> account remove --keep-data|--delete-data`: signs the profile out the tool's way, forgets it on
64
+ * this computer, and keeps or deletes what the store holds of its account. Asks first, or `--yes`; `--dry-run` lists
65
+ * every entry, file and section it would remove.
66
+ */
67
+ export declare const accountRemoveCommand: (app: AppIdentity, removal: AccountRemoval, options?: AccountRemoveOptions) => Command;
@@ -0,0 +1,285 @@
1
+ import { existsSync, rmSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { resolve as absolute, isAbsolute, join, sep } from "node:path";
4
+ import { CliError, Credentials, isMovedRun, resolvePaths, saveConfigFile, } from "@wirecat/cli-base";
5
+ import { annotate } from "@wirecat/cli-base/commands";
6
+ import { Command } from "commander";
7
+ import { lockPath, readLock, servingProfiles } from "../background/lock.js";
8
+ import { alive } from "../background/processes.js";
9
+ import { listSchedules, scheduleFile, timerFor } from "../background/schedules.js";
10
+ import { thisMachine } from "../background/system.js";
11
+ import { locationVariables, platformFor } from "../background/units.js";
12
+ import { httpLockFile } from "../mcp/http/state.js";
13
+ import { sendsPathFor } from "../sends/journal.js";
14
+ import { storePath } from "../store/path.js";
15
+ import { openStore } from "../store/store.js";
16
+ import { readConfigFile, withoutPath } from "./config-issues.js";
17
+ import { baseContext, environmentOf } from "./context.js";
18
+ import { logsInOrOut, REMOTE_WRITE } from "./effects.js";
19
+ import { itemOf, renderAnswer } from "./envelope.js";
20
+ import { accountFileFor, recalledAccount } from "./messenger/accounts.js";
21
+ import { answerOf } from "./messenger/ask.js";
22
+ import { profileFiles } from "./profile-files.js";
23
+ const choiceOf = ({ keepData, deleteData }) => {
24
+ if (keepData === deleteData)
25
+ throw new CliError("validation_error", keepData
26
+ ? "--keep-data and --delete-data ask for opposite things — pick one"
27
+ : "say what happens to this account's data: --keep-data leaves it searchable, --delete-data deletes it", { reason: "account-remove.no-choice" });
28
+ return keepData ? "kept" : "deleted";
29
+ };
30
+ /** Inside the tool's own folders and not one of them: a hook's mistake must not reach the home folder. */
31
+ const insideOwnFolders = (app, env, extra) => {
32
+ const home = absolute(env.HOME ?? env.USERPROFILE ?? homedir());
33
+ for (const root of extra)
34
+ if (!isAbsolute(root) || !absolute(root).startsWith(`${home}${sep}`))
35
+ throw new CliError("configuration_error", `${app.command} named ${root} as one of its folders, but it is not an absolute path inside ${home} — nothing was removed; report this as a bug`, { reason: "account-remove.folder-outside" });
36
+ const roots = [...Object.values(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env })), ...extra].map((root) => absolute(root));
37
+ return (path) => {
38
+ const full = absolute(path);
39
+ if (!roots.some((root) => full.startsWith(`${root}${sep}`)))
40
+ throw new CliError("configuration_error", `${app.command} named ${full} for removal, outside its own folders — nothing was removed; report this as a bug`, { reason: "account-remove.path-outside" });
41
+ return full;
42
+ };
43
+ };
44
+ /** The profile's own serve unit, by its exact name, when one is installed; never a pattern over the unit folder. */
45
+ const serveUnit = (app, system, profile, env) => {
46
+ if (!env.HOME)
47
+ return undefined;
48
+ const unit = platformFor(app, system, env).unit({
49
+ profile,
50
+ command: [],
51
+ environment: { [`${app.envPrefix}_PROFILE`]: profile, ...locationVariables(app, env) },
52
+ });
53
+ return unit.path && existsSync(unit.path) ? unit : undefined;
54
+ };
55
+ const removeUnit = async (app, system, unit, env) => {
56
+ const platform = platformFor(app, system, env);
57
+ for (const argv of platform.uninstall(unit)) {
58
+ const ran = await system.run(argv, env);
59
+ if (ran.code !== 0)
60
+ throw new CliError("configuration_error", `${argv.join(" ")} failed: ${ran.stderr.trim()}`);
61
+ }
62
+ rmSync(unit.path, { force: true });
63
+ };
64
+ /** As `schedule remove` does: the timer and the schedule's file go, its past output stays. */
65
+ const removeSchedules = async (app, system, state, schedules, env) => {
66
+ const timer = timerFor(app, system, env);
67
+ for (const { name } of schedules) {
68
+ await timer.remove(name);
69
+ rmSync(scheduleFile(state, name), { force: true });
70
+ }
71
+ };
72
+ /** The profile's sections in cli-core's config file; a profile's shared section stays while its bot side uses it. */
73
+ const configSections = (path, profile) => {
74
+ const read = readConfigFile(path);
75
+ if ("issue" in read || typeof read.raw !== "object" || read.raw === null)
76
+ return [];
77
+ const raw = read.raw;
78
+ const has = (...at) => at.reduce((node, key) => node?.[key], raw);
79
+ const bot = has("bot", "profiles", profile) !== undefined;
80
+ return [
81
+ ...(has("personal", "profiles", profile) === undefined ? [] : [["personal", "profiles", profile]]),
82
+ ...(has("profiles", profile) === undefined || bot ? [] : [["profiles", profile]]),
83
+ ];
84
+ };
85
+ const removeSections = (path, sections) => {
86
+ const read = readConfigFile(path);
87
+ if ("issue" in read)
88
+ return;
89
+ saveConfigFile(path, sections.reduce((config, at) => withoutPath(config, at).config, read.raw));
90
+ };
91
+ /**
92
+ * `<tool> <profile> account remove --keep-data|--delete-data`: signs the profile out the tool's way, forgets it on
93
+ * this computer, and keeps or deletes what the store holds of its account. Asks first, or `--yes`; `--dry-run` lists
94
+ * every entry, file and section it would remove.
95
+ */
96
+ export const accountRemoveCommand = (app, removal, options = {}) => logsInOrOut(annotate(new Command("remove"), {
97
+ effects: REMOTE_WRITE,
98
+ mcp: false,
99
+ output: { entity: "account_removal" },
100
+ examples: [
101
+ `${app.command} personal account remove --keep-data --dry-run`,
102
+ `${app.command} personal account remove --delete-data --yes`,
103
+ ],
104
+ }))
105
+ .summary("sign this profile out and forget it, keeping or deleting its data")
106
+ .description("sign the profile out, then forget it on this computer: its settings, its saved sign-in and its files; " +
107
+ "--keep-data leaves its messages in the store, where search still finds them, --delete-data deletes them; " +
108
+ "asks first, or --yes")
109
+ .option("--keep-data", "leave what the store holds of this account, still searchable")
110
+ .option("--delete-data", "delete what the store and the tool's own files hold of this account")
111
+ .option("--dry-run", "list what it would remove and keep, and change nothing")
112
+ .action(async function () {
113
+ const given = this.opts();
114
+ const data = choiceOf(given);
115
+ const resolveSettings = options.resolveSettings ?? environmentOf(this).resolveSettings;
116
+ if (!resolveSettings)
117
+ throw new Error("account remove runs inside run(), or is given resolveSettings");
118
+ const context = baseContext(this, resolveSettings);
119
+ const { env, settings } = context;
120
+ const profile = settings.profile;
121
+ const accountFile = accountFileFor(app, profile, env);
122
+ if (!settings.profilesHere.includes(profile) && !existsSync(accountFile))
123
+ throw new CliError("not_found", `no profile ${profile} on this computer — ${settings.profilesHere.join(", ") || "there is none"}`, { reason: "account-remove.unknown-profile", profiles: settings.profilesHere });
124
+ const moved = context.keyring === undefined && isMovedRun({ appName: app.appName, prefix: app.envPrefix, env });
125
+ const hooks = {
126
+ env,
127
+ ...(context.keyring ? { keyring: context.keyring } : {}),
128
+ mayRevoke: !moved,
129
+ };
130
+ const state = resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state;
131
+ const httpLock = readLock(httpLockFile(join(state, "mcp-http", `${profile}.json`)));
132
+ const holder = servingProfiles(app, env).includes(profile)
133
+ ? `\`${app.command} serve\``
134
+ : httpLock && alive(httpLock.pid)
135
+ ? `\`${app.command} mcp serve --http\``
136
+ : removal.busy?.(profile, hooks);
137
+ if (holder)
138
+ throw new CliError("conflict", `${holder} is running for ${profile} — stop it first (\`${app.command} ${profile} server stop\`), then remove the account`, { reason: "account-remove.busy" });
139
+ const own = insideOwnFolders(app, env, removal.ownFolders?.(hooks) ?? []);
140
+ const schedules = listSchedules(state).filter((schedule) => schedule.environment[`${app.envPrefix}_PROFILE`] === profile);
141
+ const serveLock = lockPath(app, profile, env);
142
+ const staleLock = readLock(serveLock);
143
+ const stateFiles = [
144
+ accountFile,
145
+ ...profileFiles(app, profile, env, listSchedules(state)),
146
+ ...(staleLock && !alive(staleLock.pid) ? [serveLock] : []),
147
+ ...(removal.stateFiles?.(profile, hooks) ?? []),
148
+ ].map(own);
149
+ const dataFiles = (removal.dataFiles?.(profile, hooks) ?? []).map(own);
150
+ const account = removal.account?.(profile, hooks) ??
151
+ (options.provider === undefined ? undefined : recalledAccount(app, options.provider, profile, env));
152
+ const secrets = (removal.secrets?.(profile, hooks) ?? []).map(({ credentials, accounts }) => ({
153
+ store: new Credentials({
154
+ ...credentials,
155
+ ...(context.keyring && !credentials.keyring ? { keyring: context.keyring } : {}),
156
+ ...(credentials.isolated === undefined ? { isolated: moved } : {}),
157
+ warn: (line) => context.renderer.warn(line),
158
+ }),
159
+ accounts,
160
+ }));
161
+ const sections = removal.forgetConfig ? [] : configSections(settings.configPath, profile);
162
+ const storeHere = existsSync(storePath(env));
163
+ const system = environmentOf(this).system ?? thisMachine();
164
+ const unit = serveUnit(app, system, profile, env);
165
+ if (unit && (await platformFor(app, system, env).state(unit)).active)
166
+ throw new CliError("conflict", `${unit.name} is running for ${profile} — stop it first (\`${app.command} ${profile} server stop\`), then remove the account`, { reason: "account-remove.busy" });
167
+ const removed = [{ kind: "sign_in", target: `${app.command} sign-in of ${profile}` }];
168
+ const kept = [];
169
+ // An entry the environment supplies is not this tool's to remove.
170
+ const saved = (store, name) => (store.read(name)?.source ?? "environment") !== "environment";
171
+ for (const { store, accounts } of secrets)
172
+ for (const name of accounts)
173
+ if (saved(store, name))
174
+ removed.push({ kind: "keyring", target: name });
175
+ for (const at of sections)
176
+ removed.push({ kind: "config", target: at.join(".") });
177
+ const present = (path) => existsSync(path);
178
+ for (const file of stateFiles.filter(present))
179
+ removed.push({ kind: "file", target: file });
180
+ if (unit)
181
+ removed.push({ kind: "unit", target: unit.path });
182
+ for (const { name } of schedules)
183
+ removed.push({ kind: "schedule", target: name });
184
+ const journal = sendsPathFor(app, profile, env);
185
+ if (existsSync(journal))
186
+ kept.push({ kind: "file", target: journal, reason: "the record of what was sent for this account" });
187
+ const accountName = account ? `${account.provider}:${account.account}` : undefined;
188
+ if (data === "deleted") {
189
+ for (const file of dataFiles.filter(present))
190
+ removed.push({ kind: "file", target: file });
191
+ if (accountName && storeHere)
192
+ removed.push({ kind: "store", target: accountName });
193
+ else
194
+ kept.push({
195
+ kind: "store",
196
+ target: accountName ?? profile,
197
+ reason: accountName
198
+ ? "the store does not exist yet, so it holds nothing of this account"
199
+ : "this profile never recorded which account it is, so nothing in the store can be told apart as its",
200
+ });
201
+ }
202
+ else {
203
+ for (const file of dataFiles.filter(present))
204
+ kept.push({ kind: "file", target: file, reason: "--keep-data keeps the account's files" });
205
+ if (accountName)
206
+ kept.push({
207
+ kind: "store",
208
+ target: accountName,
209
+ reason: "--keep-data: its messages stay in the store, and search still finds them",
210
+ });
211
+ }
212
+ const answer = (dryRun, signedOut) => renderAnswer(this, context, itemOf({
213
+ profile,
214
+ data,
215
+ dry_run: dryRun,
216
+ account: account ? { provider: account.provider, account: account.account } : null,
217
+ revoked: signedOut?.revoked ?? null,
218
+ config_file: settings.configPath,
219
+ removed,
220
+ kept,
221
+ }));
222
+ if (given.dryRun) {
223
+ answer(true);
224
+ return;
225
+ }
226
+ if (this.optsWithGlobals().yes !== true) {
227
+ const what = `this signs ${profile} out and forgets it, and ${data === "deleted" ? "deletes" : "keeps"} its data`;
228
+ const lines = removed.map((one) => ` ${one.kind}: ${one.target}`).join("\n");
229
+ const reply = await answerOf(this, `${what}:\n${lines}\nGo ahead? [y/N] `);
230
+ if (reply === null)
231
+ throw new CliError("confirmation_required", `${what} — add --yes to go ahead, or --dry-run to see the list`, {
232
+ reason: "account-remove.unconfirmed",
233
+ });
234
+ if (!/^\s*y(es)?\s*$/i.test(reply))
235
+ throw new CliError("cancelled", `cancelled — ${profile} is unchanged`);
236
+ }
237
+ await context.run(async () => {
238
+ const signedOut = await removal.signOut(profile, hooks);
239
+ removed.splice(0, 1, ...signedOut.removed.map((target) => ({ kind: "sign_in", target })));
240
+ const keyringEntries = removed.filter((one) => one.kind === "keyring");
241
+ const gone = new Set();
242
+ for (const { store, accounts } of secrets)
243
+ for (const name of accounts)
244
+ if (store.remove(name).length > 0)
245
+ gone.add(name);
246
+ for (const entry of keyringEntries) {
247
+ if (gone.has(entry.target))
248
+ continue;
249
+ removed.splice(removed.indexOf(entry), 1);
250
+ if (moved)
251
+ kept.push({
252
+ kind: "keyring",
253
+ target: entry.target,
254
+ reason: "a run with moved folders never removes the owner's sign-in",
255
+ });
256
+ }
257
+ if (removed.some((one) => one.kind === "store") && account) {
258
+ const store = await openStore({ env, command: app.command });
259
+ try {
260
+ await store.accounts.purge(account);
261
+ await store.accounts.forgetProfile(app.command, profile);
262
+ }
263
+ finally {
264
+ await store.close();
265
+ }
266
+ }
267
+ if (unit)
268
+ await removeUnit(app, system, unit, env);
269
+ if (schedules.length > 0)
270
+ await removeSchedules(app, system, state, schedules, env);
271
+ for (const entry of removed)
272
+ if (entry.kind === "file")
273
+ rmSync(entry.target, { recursive: true, force: true });
274
+ if (removal.forgetConfig)
275
+ for (const target of removal.forgetConfig(profile, hooks))
276
+ removed.push({ kind: "config", target });
277
+ else if (sections.length > 0)
278
+ removeSections(settings.configPath, sections);
279
+ answer(false, signedOut);
280
+ if (context.format === "pretty")
281
+ context.renderer.success(data === "deleted"
282
+ ? `removed ${profile} and deleted its data`
283
+ : `removed ${profile}; its messages stay in the store, and search still finds them`);
284
+ });
285
+ });
@@ -42,6 +42,7 @@ export { unanswered } from "../services/questions.js";
42
42
  export { openRequestTask } from "../services/task-rules.js";
43
43
  export { TASK_PAIR_QUERY, TASK_QUERY } from "../services/tasks.js";
44
44
  export { answerStdinOption, type Need, type SignInSteps, type SignInStepsOptions, signInSteps, } from "../terminal/sign-in-steps.js";
45
+ export { type AccountRemoval, type AccountRemovalContext, type AccountRemoveOptions, type AccountSecrets, accountRemoveCommand, type SignedOut, } from "./account-remove.js";
45
46
  export { liftOptionsAfterDashes } from "./after-dashes.js";
46
47
  export { type AgentPolicy, type AgentTask, type EvaluationResult, evaluateAgent, type Observation, } from "./agent-evaluation.js";
47
48
  export { answerEntity } from "./answer-entity.js";
package/dist/cli/index.js CHANGED
@@ -37,6 +37,7 @@ export { unanswered } from "../services/questions.js";
37
37
  export { openRequestTask } from "../services/task-rules.js";
38
38
  export { TASK_PAIR_QUERY, TASK_QUERY } from "../services/tasks.js";
39
39
  export { answerStdinOption, signInSteps, } from "../terminal/sign-in-steps.js";
40
+ export { accountRemoveCommand, } from "./account-remove.js";
40
41
  export { liftOptionsAfterDashes } from "./after-dashes.js";
41
42
  export { evaluateAgent, } from "./agent-evaluation.js";
42
43
  export { answerEntity } from "./answer-entity.js";
@@ -4,6 +4,7 @@ import { Command } from "commander";
4
4
  import { withoutPhone } from "../../services/people.js";
5
5
  import { storePath } from "../../store/path.js";
6
6
  import { openStore } from "../../store/store.js";
7
+ import { accountRemoveCommand } from "../account-remove.js";
7
8
  import { REMOTE_READ, REMOTE_WRITE } from "../effects.js";
8
9
  import { itemOf, renderAnswer } from "../envelope.js";
9
10
  import { queryTerms, withQuery } from "../list-query.js";
@@ -99,6 +100,11 @@ export const accountCommand = (messenger) => {
99
100
  renderItem(this, context, hidePhone ? { ...changed, account: withoutPhone(changed.account) } : changed);
100
101
  }))
101
102
  .addCommand(accountSessionsCommand(messenger));
103
+ if (messenger.accountRemoval)
104
+ account.addCommand(accountRemoveCommand(messenger.app, messenger.accountRemoval, {
105
+ provider: messenger.provider,
106
+ resolveSettings: messenger.resolveSettings,
107
+ }));
102
108
  if (messenger.privacy === true)
103
109
  account.addCommand(privacyCommand(messenger));
104
110
  return hideNever(messenger, account);
@@ -75,6 +75,8 @@ export interface Messenger extends ServiceMessenger {
75
75
  * signed in; `account list` and the profile errors say so too. Unset: every profile counts as signed in.
76
76
  */
77
77
  profileState?: (profile: string, env: NodeJS.ProcessEnv) => ProfileState;
78
+ /** Opts in to `account remove`: what signing out and forgetting a profile means for this messenger. */
79
+ accountRemoval?: import("../account-remove.js").AccountRemoval;
78
80
  /** The help for a `<chat>` argument, in this messenger's words. */
79
81
  chatArgument: string;
80
82
  /** The chat purposes `projects evidence` and `projects status` know; core's built-in ones when unset. */
@@ -40,6 +40,7 @@ export declare const serveRelay: (command: Command, messenger: Messenger) => {
40
40
  pace?: import("../../sends/pace.js").PaceRate;
41
41
  resolveSettings: (flags: import("../settings.js").GlobalFlags, options?: import("../settings.js").ResolveOptions) => import("../settings.js").Settings;
42
42
  profileState?: (profile: string, env: NodeJS.ProcessEnv) => import("./context.js").ProfileState;
43
+ accountRemoval?: import("../account-remove.js").AccountRemoval;
43
44
  chatArgument: string;
44
45
  purposes?: import("../../services/project-purposes.js").PurposeConfig;
45
46
  groupSettings?: readonly import("../../domain/models.js").GroupSettingKey[];
@@ -0,0 +1,7 @@
1
+ import type { Schedule } from "../background/schedules.js";
2
+ import type { AppIdentity } from "../ports/app.js";
3
+ /**
4
+ * The files cli-core itself writes for one profile, so a tool's `account remove` need not list them. The sends
5
+ * journal is not among them: it is the record of what was sent, and it stays.
6
+ */
7
+ export declare const profileFiles: (app: AppIdentity, profile: string, env: NodeJS.ProcessEnv, schedules: readonly Schedule[]) => string[];
@@ -0,0 +1,43 @@
1
+ import { join } from "node:path";
2
+ import { resolvePaths } from "@wirecat/cli-base";
3
+ import { httpLockFile } from "../mcp/http/state.js";
4
+ import { moderationPathFor } from "../moderation/rules.js";
5
+ import { replyConsentPathFor } from "../replies/consents.js";
6
+ import { repliesPathFor } from "../replies/rules.js";
7
+ import { repliesStatePathFor } from "../replies/state.js";
8
+ import { providerLogPathFor } from "../runs/provider-log.js";
9
+ import { floodPathFor } from "../sends/flood.js";
10
+ import { pacePathFor } from "../sends/pace.js";
11
+ import { recipientsPathFor } from "../sends/recipients.js";
12
+ /** Where `--new` keeps its points: the owner's, an agent's over MCP, and each schedule's own (`pointsOf`). */
13
+ const pointFolders = (schedules) => [
14
+ "mentions",
15
+ ...["inbox", "review"].flatMap((name) => [
16
+ name,
17
+ `mcp-${name}`,
18
+ ...schedules.map(({ name: schedule }) => `schedule-${schedule.replace(/[^a-z0-9-]/gi, "_")}-${name}`),
19
+ ]),
20
+ ];
21
+ /**
22
+ * The files cli-core itself writes for one profile, so a tool's `account remove` need not list them. The sends
23
+ * journal is not among them: it is the record of what was sent, and it stays.
24
+ */
25
+ export const profileFiles = (app, profile, env, schedules) => {
26
+ const { state } = resolvePaths({ appName: app.appName, prefix: app.envPrefix, env });
27
+ const tokens = join(state, "mcp-http", `${profile}.json`);
28
+ return [
29
+ floodPathFor(app, profile, env),
30
+ pacePathFor(app, profile, env),
31
+ recipientsPathFor(app, profile, env),
32
+ moderationPathFor(app, profile, env),
33
+ providerLogPathFor(app, profile, env),
34
+ tokens,
35
+ httpLockFile(tokens),
36
+ repliesPathFor(app, profile, env),
37
+ replyConsentPathFor(app, profile, env),
38
+ repliesStatePathFor(app, profile, env),
39
+ join(state, "serve", `${profile}.log`),
40
+ join(state, "checkpoints", profile),
41
+ ...pointFolders(schedules).map((folder) => join(state, folder, `${profile}.json`)),
42
+ ];
43
+ };
@@ -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 = [
@@ -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);
@@ -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
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.613.0",
3
+ "version": "0.614.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",