@smithers-orchestrator/accounts 0.16.9

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 William Cory
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@smithers-orchestrator/accounts",
3
+ "version": "0.16.9",
4
+ "description": "Manage multiple Claude/Codex/Gemini/Kimi subscription and API-key accounts that Smithers agents can round-robin through.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "exports": {
8
+ ".": {
9
+ "types": "./src/index.d.ts",
10
+ "import": "./src/index.js",
11
+ "default": "./src/index.js"
12
+ },
13
+ "./*": {
14
+ "types": "./src/index.d.ts",
15
+ "import": "./src/*.js",
16
+ "default": "./src/*.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "src/"
21
+ ],
22
+ "dependencies": {
23
+ "@smithers-orchestrator/errors": "0.16.9"
24
+ },
25
+ "devDependencies": {
26
+ "@types/bun": "latest",
27
+ "typescript": "~5.9.3"
28
+ },
29
+ "scripts": {
30
+ "test": "bun test tests",
31
+ "typecheck": "tsc -p tsconfig.json --noEmit",
32
+ "build": "tsup --dts-only"
33
+ }
34
+ }
package/src/Account.ts ADDED
@@ -0,0 +1,29 @@
1
+ import type { AccountProvider } from "./AccountProvider";
2
+
3
+ /**
4
+ * A single registered account. Either `configDir` (subscription providers) or
5
+ * `apiKey` (API providers) is set, never both. The CLI enforces this at
6
+ * registration time.
7
+ */
8
+ export type Account = {
9
+ /** Unique label, e.g. "claude-work". Lowercase, kebab/snake/camel-case OK. */
10
+ label: string;
11
+ /** Which CLI/API this account belongs to. */
12
+ provider: AccountProvider;
13
+ /**
14
+ * Absolute path to the per-account CLI config directory. Set for
15
+ * subscription providers (claude-code, codex, gemini, kimi).
16
+ */
17
+ configDir?: string;
18
+ /**
19
+ * Raw API key. Set for API providers (anthropic-api, openai-api,
20
+ * gemini-api). Stored in plaintext in `~/.smithers/accounts.json` (mode 600).
21
+ * For stricter handling, set this to the empty string and override at
22
+ * runtime via the matching env var.
23
+ */
24
+ apiKey?: string;
25
+ /** Optional default model to bake into the generated `agents.ts`. */
26
+ model?: string;
27
+ /** ISO timestamp of when this account was added. */
28
+ addedAt?: string;
29
+ };
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The provider behind a registered account. Subscription providers are
3
+ * authenticated by a CLI config directory; API providers are authenticated by
4
+ * an API key.
5
+ */
6
+ export type AccountProvider =
7
+ | "claude-code"
8
+ | "codex"
9
+ | "gemini"
10
+ | "kimi"
11
+ | "anthropic-api"
12
+ | "openai-api"
13
+ | "gemini-api";
@@ -0,0 +1,6 @@
1
+ import type { Account } from "./Account";
2
+
3
+ export type AccountsFile = {
4
+ version: 1;
5
+ accounts: Account[];
6
+ };
@@ -0,0 +1,44 @@
1
+ import { SmithersError } from "@smithers-orchestrator/errors/SmithersError";
2
+
3
+ /**
4
+ * Maps an account to the environment variables that the spawned CLI honors.
5
+ * Used by the agent classes' `buildCommand` and by `smithers agent test` to
6
+ * exercise an account without involving an agent.
7
+ *
8
+ * @param {import("./Account.ts").Account} account
9
+ * @returns {Record<string, string>}
10
+ */
11
+ export function accountToProviderEnv(account) {
12
+ switch (account.provider) {
13
+ case "claude-code":
14
+ if (!account.configDir) {
15
+ throw new SmithersError("ACCOUNT_INVALID", `claude-code account "${account.label}" missing configDir`);
16
+ }
17
+ return { CLAUDE_CONFIG_DIR: account.configDir };
18
+ case "codex":
19
+ if (!account.configDir) {
20
+ throw new SmithersError("ACCOUNT_INVALID", `codex account "${account.label}" missing configDir`);
21
+ }
22
+ return { CODEX_HOME: account.configDir };
23
+ case "gemini":
24
+ if (!account.configDir) {
25
+ throw new SmithersError("ACCOUNT_INVALID", `gemini account "${account.label}" missing configDir`);
26
+ }
27
+ return { GEMINI_DIR: account.configDir };
28
+ case "kimi":
29
+ if (!account.configDir) {
30
+ throw new SmithersError("ACCOUNT_INVALID", `kimi account "${account.label}" missing configDir`);
31
+ }
32
+ return { KIMI_SHARE_DIR: account.configDir };
33
+ case "anthropic-api":
34
+ return account.apiKey ? { ANTHROPIC_API_KEY: account.apiKey } : {};
35
+ case "openai-api":
36
+ return account.apiKey ? { OPENAI_API_KEY: account.apiKey } : {};
37
+ case "gemini-api":
38
+ return account.apiKey ? { GEMINI_API_KEY: account.apiKey } : {};
39
+ default: {
40
+ const exhaustive = /** @type {never} */ (account.provider);
41
+ throw new SmithersError("ACCOUNT_INVALID", `unknown provider: ${exhaustive}`);
42
+ }
43
+ }
44
+ }
@@ -0,0 +1,12 @@
1
+ import { join } from "node:path";
2
+ import { accountsRoot } from "./accountsRoot.js";
3
+
4
+ /**
5
+ * Path to the JSON registry that lists all accounts.
6
+ *
7
+ * @param {NodeJS.ProcessEnv} [env]
8
+ * @returns {string}
9
+ */
10
+ export function accountsFilePath(env = process.env) {
11
+ return join(accountsRoot(env), "accounts.json");
12
+ }
@@ -0,0 +1,16 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+
4
+ /**
5
+ * Returns the user-level Smithers root directory (~/.smithers by default).
6
+ * Honors `SMITHERS_HOME` for tests and CI.
7
+ *
8
+ * @param {NodeJS.ProcessEnv} [env]
9
+ * @returns {string}
10
+ */
11
+ export function accountsRoot(env = process.env) {
12
+ if (env.SMITHERS_HOME) {
13
+ return env.SMITHERS_HOME;
14
+ }
15
+ return join(env.HOME ?? homedir(), ".smithers");
16
+ }
@@ -0,0 +1,50 @@
1
+ import { SmithersError } from "@smithers-orchestrator/errors/SmithersError";
2
+ import { readAccounts } from "./readAccounts.js";
3
+ import { writeAccounts } from "./writeAccounts.js";
4
+ import { API_KEY_PROVIDERS, SUBSCRIPTION_PROVIDERS, VALID_PROVIDERS } from "./parseAccountsFile.js";
5
+
6
+ /** @typedef {import("./Account.ts").Account} Account */
7
+
8
+ /**
9
+ * Adds (or replaces, if a same-label account exists) an account in the
10
+ * registry. Validates the entry before persisting so a malformed call cannot
11
+ * corrupt the file.
12
+ *
13
+ * @param {Account} account
14
+ * @param {{ replace?: boolean; env?: NodeJS.ProcessEnv }} [options]
15
+ * @returns {Account}
16
+ */
17
+ export function addAccount(account, options = {}) {
18
+ const env = options.env ?? process.env;
19
+ if (!account.label || !account.label.trim()) {
20
+ throw new SmithersError("ACCOUNT_INVALID", "account.label must be a non-empty string");
21
+ }
22
+ if (!VALID_PROVIDERS.has(account.provider)) {
23
+ throw new SmithersError("ACCOUNT_INVALID", `account.provider must be one of ${[...VALID_PROVIDERS].join(", ")}, got ${JSON.stringify(account.provider)}`);
24
+ }
25
+ if (SUBSCRIPTION_PROVIDERS.has(account.provider) && (!account.configDir || !account.configDir.trim())) {
26
+ throw new SmithersError("ACCOUNT_INVALID", `${account.provider} accounts require a non-empty configDir`);
27
+ }
28
+ if (API_KEY_PROVIDERS.has(account.provider) && typeof account.apiKey !== "string") {
29
+ throw new SmithersError("ACCOUNT_INVALID", `${account.provider} accounts require apiKey (may be empty string for env-var-only)`);
30
+ }
31
+ const existing = readAccounts(env);
32
+ const conflict = existing.accounts.findIndex((entry) => entry.label === account.label);
33
+ if (conflict >= 0 && !options.replace) {
34
+ throw new SmithersError("ACCOUNT_DUPLICATE_LABEL", `An account with label "${account.label}" already exists. Pass replace: true to overwrite, or use a different label.`);
35
+ }
36
+ /** @type {Account} */
37
+ const persisted = {
38
+ label: account.label,
39
+ provider: account.provider,
40
+ addedAt: account.addedAt ?? new Date().toISOString(),
41
+ };
42
+ if (account.configDir) persisted.configDir = account.configDir;
43
+ if (account.apiKey !== undefined) persisted.apiKey = account.apiKey;
44
+ if (account.model) persisted.model = account.model;
45
+ const next = conflict >= 0
46
+ ? existing.accounts.map((entry, i) => (i === conflict ? persisted : entry))
47
+ : [...existing.accounts, persisted];
48
+ writeAccounts({ version: 1, accounts: next }, env);
49
+ return persisted;
50
+ }
@@ -0,0 +1,14 @@
1
+ import { join } from "node:path";
2
+ import { accountsRoot } from "./accountsRoot.js";
3
+
4
+ /**
5
+ * Default location for a per-account CLI config dir, e.g.
6
+ * `~/.smithers/accounts/claude-work`.
7
+ *
8
+ * @param {string} label
9
+ * @param {NodeJS.ProcessEnv} [env]
10
+ * @returns {string}
11
+ */
12
+ export function defaultConfigDir(label, env = process.env) {
13
+ return join(accountsRoot(env), "accounts", label);
14
+ }
@@ -0,0 +1,13 @@
1
+ import { listAccounts } from "./listAccounts.js";
2
+
3
+ /**
4
+ * Looks up an account by label. Returns undefined if not found (callers
5
+ * decide whether absence is an error).
6
+ *
7
+ * @param {string} label
8
+ * @param {NodeJS.ProcessEnv} [env]
9
+ * @returns {import("./Account.ts").Account | undefined}
10
+ */
11
+ export function getAccount(label, env = process.env) {
12
+ return listAccounts(env).find((account) => account.label === label);
13
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * The provider behind a registered account. Subscription providers are
3
+ * authenticated by a CLI config directory; API providers are authenticated by
4
+ * an API key.
5
+ */
6
+ type AccountProvider = "claude-code" | "codex" | "gemini" | "kimi" | "anthropic-api" | "openai-api" | "gemini-api";
7
+
8
+ /**
9
+ * A single registered account. Either `configDir` (subscription providers) or
10
+ * `apiKey` (API providers) is set, never both. The CLI enforces this at
11
+ * registration time.
12
+ */
13
+ type Account$1 = {
14
+ /** Unique label, e.g. "claude-work". Lowercase, kebab/snake/camel-case OK. */
15
+ label: string;
16
+ /** Which CLI/API this account belongs to. */
17
+ provider: AccountProvider;
18
+ /**
19
+ * Absolute path to the per-account CLI config directory. Set for
20
+ * subscription providers (claude-code, codex, gemini, kimi).
21
+ */
22
+ configDir?: string;
23
+ /**
24
+ * Raw API key. Set for API providers (anthropic-api, openai-api,
25
+ * gemini-api). Stored in plaintext in `~/.smithers/accounts.json` (mode 600).
26
+ * For stricter handling, set this to the empty string and override at
27
+ * runtime via the matching env var.
28
+ */
29
+ apiKey?: string;
30
+ /** Optional default model to bake into the generated `agents.ts`. */
31
+ model?: string;
32
+ /** ISO timestamp of when this account was added. */
33
+ addedAt?: string;
34
+ };
35
+
36
+ type AccountsFile = {
37
+ version: 1;
38
+ accounts: Account$1[];
39
+ };
40
+
41
+ /**
42
+ * Returns the user-level Smithers root directory (~/.smithers by default).
43
+ * Honors `SMITHERS_HOME` for tests and CI.
44
+ *
45
+ * @param {NodeJS.ProcessEnv} [env]
46
+ * @returns {string}
47
+ */
48
+ declare function accountsRoot(env?: NodeJS.ProcessEnv): string;
49
+
50
+ /**
51
+ * Path to the JSON registry that lists all accounts.
52
+ *
53
+ * @param {NodeJS.ProcessEnv} [env]
54
+ * @returns {string}
55
+ */
56
+ declare function accountsFilePath(env?: NodeJS.ProcessEnv): string;
57
+
58
+ /**
59
+ * Default location for a per-account CLI config dir, e.g.
60
+ * `~/.smithers/accounts/claude-work`.
61
+ *
62
+ * @param {string} label
63
+ * @param {NodeJS.ProcessEnv} [env]
64
+ * @returns {string}
65
+ */
66
+ declare function defaultConfigDir(label: string, env?: NodeJS.ProcessEnv): string;
67
+
68
+ /**
69
+ * Parses a raw JSON string into a validated AccountsFile. Throws SmithersError
70
+ * with code `ACCOUNTS_FILE_INVALID` if the shape is wrong. Tolerates missing
71
+ * accounts.json (caller passes an empty string for that).
72
+ *
73
+ * @param {string} raw
74
+ * @returns {import("./AccountsFile.ts").AccountsFile}
75
+ */
76
+ declare function parseAccountsFile(raw: string): AccountsFile;
77
+ declare const SUBSCRIPTION_PROVIDERS: Set<string>;
78
+ declare const API_KEY_PROVIDERS: Set<string>;
79
+ declare const VALID_PROVIDERS: Set<string>;
80
+
81
+ /**
82
+ * Reads ~/.smithers/accounts.json. Returns an empty registry if the file does
83
+ * not exist (a fresh install with no accounts is the normal startup state, not
84
+ * an error).
85
+ *
86
+ * @param {NodeJS.ProcessEnv} [env]
87
+ * @returns {import("./AccountsFile.ts").AccountsFile}
88
+ */
89
+ declare function readAccounts(env?: NodeJS.ProcessEnv): AccountsFile;
90
+
91
+ /**
92
+ * Atomically writes the accounts registry to ~/.smithers/accounts.json. The
93
+ * file is mode 0600 because it may contain raw API keys.
94
+ *
95
+ * @param {import("./AccountsFile.ts").AccountsFile} contents
96
+ * @param {NodeJS.ProcessEnv} [env]
97
+ * @returns {string} the file path that was written
98
+ */
99
+ declare function writeAccounts(contents: AccountsFile, env?: NodeJS.ProcessEnv): string;
100
+
101
+ /**
102
+ * Returns the array of registered accounts, in registration order.
103
+ *
104
+ * @param {NodeJS.ProcessEnv} [env]
105
+ * @returns {import("./Account.ts").Account[]}
106
+ */
107
+ declare function listAccounts(env?: NodeJS.ProcessEnv): Account$1[];
108
+
109
+ /**
110
+ * Looks up an account by label. Returns undefined if not found (callers
111
+ * decide whether absence is an error).
112
+ *
113
+ * @param {string} label
114
+ * @param {NodeJS.ProcessEnv} [env]
115
+ * @returns {import("./Account.ts").Account | undefined}
116
+ */
117
+ declare function getAccount(label: string, env?: NodeJS.ProcessEnv): Account$1 | undefined;
118
+
119
+ /** @typedef {import("./Account.ts").Account} Account */
120
+ /**
121
+ * Adds (or replaces, if a same-label account exists) an account in the
122
+ * registry. Validates the entry before persisting so a malformed call cannot
123
+ * corrupt the file.
124
+ *
125
+ * @param {Account} account
126
+ * @param {{ replace?: boolean; env?: NodeJS.ProcessEnv }} [options]
127
+ * @returns {Account}
128
+ */
129
+ declare function addAccount(account: Account, options?: {
130
+ replace?: boolean;
131
+ env?: NodeJS.ProcessEnv;
132
+ }): Account;
133
+ type Account = Account$1;
134
+
135
+ /**
136
+ * Removes an account by label. Throws if no account exists with that label
137
+ * unless `silent: true`.
138
+ *
139
+ * @param {string} label
140
+ * @param {{ silent?: boolean; env?: NodeJS.ProcessEnv }} [options]
141
+ * @returns {boolean} true if an entry was removed
142
+ */
143
+ declare function removeAccount(label: string, options?: {
144
+ silent?: boolean;
145
+ env?: NodeJS.ProcessEnv;
146
+ }): boolean;
147
+
148
+ /**
149
+ * Maps an account to the environment variables that the spawned CLI honors.
150
+ * Used by the agent classes' `buildCommand` and by `smithers agent test` to
151
+ * exercise an account without involving an agent.
152
+ *
153
+ * @param {import("./Account.ts").Account} account
154
+ * @returns {Record<string, string>}
155
+ */
156
+ declare function accountToProviderEnv(account: Account$1): Record<string, string>;
157
+
158
+ export { API_KEY_PROVIDERS, type Account$1 as Account, type AccountProvider, type AccountsFile, SUBSCRIPTION_PROVIDERS, VALID_PROVIDERS, accountToProviderEnv, accountsFilePath, accountsRoot, addAccount, defaultConfigDir, getAccount, listAccounts, parseAccountsFile, readAccounts, removeAccount, writeAccounts };
package/src/index.js ADDED
@@ -0,0 +1,11 @@
1
+ export { accountsRoot } from "./accountsRoot.js";
2
+ export { accountsFilePath } from "./accountsFilePath.js";
3
+ export { defaultConfigDir } from "./defaultConfigDir.js";
4
+ export { parseAccountsFile, SUBSCRIPTION_PROVIDERS, API_KEY_PROVIDERS, VALID_PROVIDERS } from "./parseAccountsFile.js";
5
+ export { readAccounts } from "./readAccounts.js";
6
+ export { writeAccounts } from "./writeAccounts.js";
7
+ export { listAccounts } from "./listAccounts.js";
8
+ export { getAccount } from "./getAccount.js";
9
+ export { addAccount } from "./addAccount.js";
10
+ export { removeAccount } from "./removeAccount.js";
11
+ export { accountToProviderEnv } from "./accountToProviderEnv.js";
@@ -0,0 +1,11 @@
1
+ import { readAccounts } from "./readAccounts.js";
2
+
3
+ /**
4
+ * Returns the array of registered accounts, in registration order.
5
+ *
6
+ * @param {NodeJS.ProcessEnv} [env]
7
+ * @returns {import("./Account.ts").Account[]}
8
+ */
9
+ export function listAccounts(env = process.env) {
10
+ return readAccounts(env).accounts;
11
+ }
@@ -0,0 +1,95 @@
1
+ import { SmithersError } from "@smithers-orchestrator/errors/SmithersError";
2
+
3
+ const VALID_PROVIDERS = new Set([
4
+ "claude-code",
5
+ "codex",
6
+ "gemini",
7
+ "kimi",
8
+ "anthropic-api",
9
+ "openai-api",
10
+ "gemini-api",
11
+ ]);
12
+
13
+ const SUBSCRIPTION_PROVIDERS = new Set([
14
+ "claude-code",
15
+ "codex",
16
+ "gemini",
17
+ "kimi",
18
+ ]);
19
+
20
+ const API_KEY_PROVIDERS = new Set([
21
+ "anthropic-api",
22
+ "openai-api",
23
+ "gemini-api",
24
+ ]);
25
+
26
+ /**
27
+ * Parses a raw JSON string into a validated AccountsFile. Throws SmithersError
28
+ * with code `ACCOUNTS_FILE_INVALID` if the shape is wrong. Tolerates missing
29
+ * accounts.json (caller passes an empty string for that).
30
+ *
31
+ * @param {string} raw
32
+ * @returns {import("./AccountsFile.ts").AccountsFile}
33
+ */
34
+ export function parseAccountsFile(raw) {
35
+ if (!raw.trim()) {
36
+ return { version: 1, accounts: [] };
37
+ }
38
+ /** @type {unknown} */
39
+ let parsed;
40
+ try {
41
+ parsed = JSON.parse(raw);
42
+ }
43
+ catch (cause) {
44
+ throw new SmithersError("ACCOUNTS_FILE_INVALID", `accounts.json is not valid JSON: ${cause?.message ?? String(cause)}`);
45
+ }
46
+ if (!parsed || typeof parsed !== "object") {
47
+ throw new SmithersError("ACCOUNTS_FILE_INVALID", "accounts.json must be a JSON object");
48
+ }
49
+ const obj = /** @type {Record<string, unknown>} */ (parsed);
50
+ if (obj.version !== 1) {
51
+ throw new SmithersError("ACCOUNTS_FILE_INVALID", `accounts.json: unsupported version ${JSON.stringify(obj.version)} (expected 1)`);
52
+ }
53
+ if (!Array.isArray(obj.accounts)) {
54
+ throw new SmithersError("ACCOUNTS_FILE_INVALID", "accounts.json: `accounts` must be an array");
55
+ }
56
+ const seenLabels = new Set();
57
+ /** @type {import("./Account.ts").Account[]} */
58
+ const accounts = [];
59
+ for (let i = 0; i < obj.accounts.length; i++) {
60
+ const entry = obj.accounts[i];
61
+ if (!entry || typeof entry !== "object") {
62
+ throw new SmithersError("ACCOUNTS_FILE_INVALID", `accounts.json: accounts[${i}] must be an object`);
63
+ }
64
+ const e = /** @type {Record<string, unknown>} */ (entry);
65
+ if (typeof e.label !== "string" || !e.label.trim()) {
66
+ throw new SmithersError("ACCOUNTS_FILE_INVALID", `accounts.json: accounts[${i}].label must be a non-empty string`);
67
+ }
68
+ if (typeof e.provider !== "string" || !VALID_PROVIDERS.has(e.provider)) {
69
+ throw new SmithersError("ACCOUNTS_FILE_INVALID", `accounts.json: accounts[${i}].provider must be one of ${[...VALID_PROVIDERS].join(", ")}, got ${JSON.stringify(e.provider)}`);
70
+ }
71
+ if (seenLabels.has(e.label)) {
72
+ throw new SmithersError("ACCOUNTS_FILE_INVALID", `accounts.json: duplicate label ${JSON.stringify(e.label)}`);
73
+ }
74
+ seenLabels.add(e.label);
75
+ const isSubscription = SUBSCRIPTION_PROVIDERS.has(e.provider);
76
+ const isApiKey = API_KEY_PROVIDERS.has(e.provider);
77
+ if (isSubscription && (typeof e.configDir !== "string" || !e.configDir.trim())) {
78
+ throw new SmithersError("ACCOUNTS_FILE_INVALID", `accounts.json: ${e.label} (${e.provider}) requires a non-empty configDir`);
79
+ }
80
+ if (isApiKey && typeof e.apiKey !== "string") {
81
+ throw new SmithersError("ACCOUNTS_FILE_INVALID", `accounts.json: ${e.label} (${e.provider}) requires apiKey (may be empty string for env-var-only)`);
82
+ }
83
+ accounts.push({
84
+ label: e.label,
85
+ provider: e.provider,
86
+ configDir: typeof e.configDir === "string" ? e.configDir : undefined,
87
+ apiKey: typeof e.apiKey === "string" ? e.apiKey : undefined,
88
+ model: typeof e.model === "string" ? e.model : undefined,
89
+ addedAt: typeof e.addedAt === "string" ? e.addedAt : undefined,
90
+ });
91
+ }
92
+ return { version: 1, accounts };
93
+ }
94
+
95
+ export { SUBSCRIPTION_PROVIDERS, API_KEY_PROVIDERS, VALID_PROVIDERS };
@@ -0,0 +1,20 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { accountsFilePath } from "./accountsFilePath.js";
3
+ import { parseAccountsFile } from "./parseAccountsFile.js";
4
+
5
+ /**
6
+ * Reads ~/.smithers/accounts.json. Returns an empty registry if the file does
7
+ * not exist (a fresh install with no accounts is the normal startup state, not
8
+ * an error).
9
+ *
10
+ * @param {NodeJS.ProcessEnv} [env]
11
+ * @returns {import("./AccountsFile.ts").AccountsFile}
12
+ */
13
+ export function readAccounts(env = process.env) {
14
+ const path = accountsFilePath(env);
15
+ if (!existsSync(path)) {
16
+ return { version: 1, accounts: [] };
17
+ }
18
+ const raw = readFileSync(path, "utf8");
19
+ return parseAccountsFile(raw);
20
+ }
@@ -0,0 +1,23 @@
1
+ import { SmithersError } from "@smithers-orchestrator/errors/SmithersError";
2
+ import { readAccounts } from "./readAccounts.js";
3
+ import { writeAccounts } from "./writeAccounts.js";
4
+
5
+ /**
6
+ * Removes an account by label. Throws if no account exists with that label
7
+ * unless `silent: true`.
8
+ *
9
+ * @param {string} label
10
+ * @param {{ silent?: boolean; env?: NodeJS.ProcessEnv }} [options]
11
+ * @returns {boolean} true if an entry was removed
12
+ */
13
+ export function removeAccount(label, options = {}) {
14
+ const env = options.env ?? process.env;
15
+ const existing = readAccounts(env);
16
+ const next = existing.accounts.filter((entry) => entry.label !== label);
17
+ if (next.length === existing.accounts.length) {
18
+ if (options.silent) return false;
19
+ throw new SmithersError("ACCOUNT_NOT_FOUND", `No account with label "${label}" is registered.`);
20
+ }
21
+ writeAccounts({ version: 1, accounts: next }, env);
22
+ return true;
23
+ }
@@ -0,0 +1,23 @@
1
+ import { chmodSync, mkdirSync, renameSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { accountsFilePath } from "./accountsFilePath.js";
4
+
5
+ /**
6
+ * Atomically writes the accounts registry to ~/.smithers/accounts.json. The
7
+ * file is mode 0600 because it may contain raw API keys.
8
+ *
9
+ * @param {import("./AccountsFile.ts").AccountsFile} contents
10
+ * @param {NodeJS.ProcessEnv} [env]
11
+ * @returns {string} the file path that was written
12
+ */
13
+ export function writeAccounts(contents, env = process.env) {
14
+ const path = accountsFilePath(env);
15
+ mkdirSync(dirname(path), { recursive: true });
16
+ const tmp = `${path}.tmp.${process.pid}.${Date.now()}`;
17
+ const serialized = `${JSON.stringify(contents, null, 2)}\n`;
18
+ writeFileSync(tmp, serialized, { encoding: "utf8", mode: 0o600 });
19
+ chmodSync(tmp, 0o600);
20
+ renameSync(tmp, path);
21
+ chmodSync(path, 0o600);
22
+ return path;
23
+ }