/** * Command-line diagnostics and account management. * * dsh plugin --profile desktop exec heybash-xdpool * * The CLI is packaged as a separate entry (`lib/bin.js`) and must stay free of * host-injected optional-peer imports: it runs standalone, before any argument * is parsed, so a single side-effect import of `@earendil-works/pi-ai` made * every command die with ERR_MODULE_NOT_FOUND. * * @module heybash-xdpool/bin */ import { createHash } from 'node:crypto' import { existsSync } from 'node:fs' import { copyFile, mkdir, readFile, writeFile } from 'node:fs/promises' import { homedir, platform } from 'node:os' import { join, resolve } from 'node:path' import { defaultDesktopAuthDirs, parseWorkBuddyAuth, WORKBUDDY_LIVE_FILENAME, workbuddyAccountId, } from './accounts.ts' import { WORKBUDDY_APP_EXECUTABLE_ENV, workbuddyAppExecutableCandidates } from './at-rest.ts' import { createCore } from './index.ts' import { ignoreAccount, readIgnoredAccounts, unignoreAccount } from './ignored.ts' import { readPreferredId, writePreferredId } from './preferred.ts' import { formatRates, formatStatus } from './status.ts' /** Directory holding imported account snapshots. */ const ACCOUNT_DIR_NAME = '.xdpool' /** * Assemble the runtime for a CLI command, with the ignore list applied. * * Every command goes through here rather than calling `createCore()` directly, * so a command can never accidentally act on an account the user has thrown out * — `checkin all` collecting a reward for a discarded account would be exactly * the kind of silent surprise the ignore feature exists to prevent. */ async function cliCore() { const core = createCore() const ignored = await readIgnoredAccounts() core.pool.applyIgnored(ignored.map(entry => entry.id)) return core } /** Snapshot files are named by the md5 prefix of their key, so any key is safe. */ function snapshotPath(key: string, dir: string): string { return join(dir, `${createHash('md5').update(key).digest('hex').slice(0, 8)}.info`) } function dshHome(): string { const fromEnv = process.env['DSH_HOME'] if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return fromEnv.trim() return join(homedir(), '.dsh') } function accountDir(): string { return join(dshHome(), ACCOUNT_DIR_NAME) } function usage(): string { return [ 'heybash-xdpool — multi-account WorkBuddy provider for DeepSeek Harness', '', 'Usage: heybash-xdpool [options]', '', 'Commands:', ' status Account pool, credits, and shim state (add --credits, --json, --rates)', ' doctor Diagnose discovery, cooldowns, and upstream reachability', ' accounts List discovered accounts (add --json)', ' import Snapshot the current desktop login as (add --force)', ' remove Delete one imported snapshot', ' ignore Drop an account from the pool for good (id or label)', ' unignore Put an ignored account back into the pool', ' ignored List the accounts dropped from the pool (add --json)', ' prefer Try one account first (id or label); `none` clears it', ' preferred Show which account is preferred, if any', ' login Guide for adding another account (desktop app is single-sign-in)', ' checkin [all|] Daily check-in: report status, or collect with `all` / a label', ' reset Clear all rate-limit cooldowns immediately', '', 'Options:', ' --json Machine-readable output', ' --credits Query remaining credits (read-only; does not consume)', ' --rates Show per-model credit multipliers', ' --force Overwrite an existing snapshot', ].join('\n') } /** Live auth files, in probe order. */ function liveCandidates(): string[] { const fromEnv = process.env['WORKBUDDY_AUTH_FILE'] if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return [resolve(fromEnv.trim())] return defaultDesktopAuthDirs().map(dir => join(dir, WORKBUDDY_LIVE_FILENAME)) } async function readJsonFile(path: string): Promise { try { return JSON.parse(await readFile(path, 'utf8')) as unknown } catch { return undefined } } async function commandStatus(args: string[]): Promise { const asJson = args.includes('--json') const withCredits = args.includes('--credits') const withRates = args.includes('--rates') const core = await cliCore() const accounts = await core.pool.scan() const status = { ok: accounts.length > 0, accounts: accounts.map(account => { const now = Date.now() const modelCooling = Object.entries(account.modelCooldowns) .filter(([, until]) => until > now) .map(([modelId, until]) => ({ modelId, until: new Date(until).toISOString() })) return { id: account.id, label: account.label, domain: account.credential.domain, ...account.credential.expiresAtMs === 0 ? {} : { expiresAt: new Date(account.credential.expiresAtMs).toISOString() }, cooling: account.cooldownUntilMs > now, ...modelCooling.length === 0 ? {} : { modelCooldowns: modelCooling }, rateLimitHits: account.rateLimitHits, sourcePath: account.credential.sourcePath, } }), cooling: accounts.filter(account => account.cooldownUntilMs > Date.now()).length, models: core.catalogs.cn.current().map(model => ({ id: model.id, name: model.name, multiplier: model.multiplier })), shim: { running: false }, } if (asJson) { console.log(JSON.stringify(status, null, 2)) } else { console.log( `Heybash: ${status.accounts.length} account(s), ${status.cooling} cooling\n` + status.accounts .map(account => { const flag = account.cooling ? '⏸ ' : '▶ ' const hits = account.rateLimitHits > 0 ? ` (hits ${account.rateLimitHits})` : '' const modelCooling = (account.modelCooldowns ?? []) .map(mc => `\n model-cool: ${mc.modelId} until ${mc.until}`) .join('') return `${flag}${account.label} [${account.domain || 'cn'}]${hits}\n ${account.sourcePath}${modelCooling}` }) .join('\n'), ) } if (withRates) console.log(`\n${formatRates(status as never)}`) if (withCredits) { const first = accounts.find(account => account.cooldownUntilMs <= Date.now()) if (first === undefined) { console.log('\nCredits: skipped (every account is cooling down)') } else { try { const credits = await core.client.fetchCredits(first.credential) console.log(`\nCredits for ${first.label}: ` + JSON.stringify(credits)) } catch (error: unknown) { console.log(`\nCredits for ${first.label}: query failed — ${String(error).slice(0, 200)}`) } } } return status.ok ? 0 : 1 } /** * Daily check-in from the terminal. * * `checkin` with no argument reports every account's status; `checkin all` * collects wherever a reward is still available, and `checkin