Skip to content

WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。

24.2 KB
Raw Blame
'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');
// 用 plat 而非 platform:buildTargetFromBinary 内部已有同名局部变量(平台字符串)
const plat = require('./platform.js');

const TARGET_FILE = 'workbuddy-target.json';
const CUSTOM_PROFILES = new Set(['workbuddy-cn', 'workbuddy-ai']);

function clean(value) {
  return typeof value === 'string' ? value.trim() : '';
}

function emptyTarget(configured = false, source = 'default') {
  return { configured, binary: '', version: '', source };
}

function platformPath(platform) {
  // 注意:Windows 上 require('path') 与 path.win32 是同一引用,
  // 非 win32 平台必须显式返回 path.posix,否则 darwin 等分支会被误判为 win32。
  return platform === 'win32' ? path.win32 : path.posix;
}

function targetFile(dataDir) {
  return path.join(dataDir, TARGET_FILE);
}

function isAbsolute(value, platform) {
  return platformPath(platform).isAbsolute(clean(value));
}

function validateApiHost(value) {
  if (!value) return '';
  let parsed;
  try { parsed = new URL(value); } catch (_) { throw new Error('企业 API 地址必须是有效 HTTPS 地址'); }
  if (parsed.protocol !== 'https:' || parsed.username || parsed.password || parsed.pathname !== '/' || parsed.search || parsed.hash) {
    throw new Error('企业 API 地址必须是无账号、路径和参数的 HTTPS origin');
  }
  return parsed.origin;
}

function validateProcessName(value, pathApi) {
  const name = clean(value);
  const isSafeName = /^[^\\/:*?"<>|\0]+$/.test(name) && name === pathApi.basename(name);
  if (!isSafeName || (pathApi === path.win32 && !/\.exe$/i.test(name))) {
    throw new Error(pathApi === path.win32
      ? 'WorkBuddy 进程名必须是单个 .exe 文件名'
      : 'WorkBuddy 进程名必须是单个文件名');
  }
  return name;
}

function inferredProcessNames(binary, platform) {
  const pathApi = platformPath(platform);
  const selectedName = pathApi.basename(binary);
  const names = [selectedName];
  const stem = selectedName.replace(/\.exe$/i, '');
  const enterprise = stem.match(/^workbuddy[-_ ]+(.+)$/i);
  if (enterprise) {
    const suffix = enterprise[1].split(/[-_ ]+/).filter(Boolean)
      .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join('');
    if (suffix) names.push(`WorkBuddy${suffix}.exe`);
  }
  return Array.from(new Set(names.map((name) => name.toLowerCase())))
    .map((lower) => names.find((name) => name.toLowerCase() === lower));
}

function validateTarget(target, options = {}) {
  const platform = options.platform || process.platform;
  if (!target || typeof target !== 'object' || Array.isArray(target)) throw new Error('WorkBuddy 客户端配置无效');
  const profileId = clean(target.profileId || target.profile);
  if (!CUSTOM_PROFILES.has(profileId)) throw new Error('WorkBuddy 客户端 profile 只能是 workbuddy-cn 或 workbuddy-ai');
  const clientType = target.clientType === 'official' ? 'official' : 'enterprise';
  const binary = clean(target.binary || target.executable || target.path);
  if (!isAbsolute(binary, platform)) throw new Error('WorkBuddy 客户端路径必须是 absolute path');
  const pathApi = platformPath(platform);
  const configuredNames = Array.isArray(target.processNames) ? target.processNames : [target.processName].filter(Boolean);
  const processNames = (configuredNames.length ? configuredNames : [pathApi.basename(binary)])
    .map((name) => validateProcessName(name, pathApi));
  const selectedName = pathApi.basename(binary);
  if (!processNames.some((name) => name.toLowerCase() === selectedName.toLowerCase())) {
    throw new Error('WorkBuddy 进程名必须包含所选 .exe 文件名');
  }
  const uniqueProcessNames = Array.from(new Set(processNames.map((name) => name.toLowerCase())))
    .map((lower) => processNames.find((name) => name.toLowerCase() === lower));
  if (uniqueProcessNames.length > 4) throw new Error('WorkBuddy 进程名候选不能超过 4 个');
  for (const field of ['dataRoot', 'authFile', 'sessionDb', 'modelsFile']) {
    if (target[field] && !isAbsolute(target[field], platform)) throw new Error(`${field} 路径必须是 absolute path`);
  }
  const apiHost = validateApiHost(clean(target.apiHost));
  const cdp = target.cdp || { mode: 'argument', port: profileId === 'workbuddy-ai' ? 9223 : 9222 };
  if (!cdp || (cdp.mode !== 'argument' && cdp.mode !== 'environment')) throw new Error('CDP mode 只能是 argument 或 environment');
  const cdpPort = Number(cdp.port);
  if (!Number.isInteger(cdpPort) || cdpPort < 1024 || cdpPort > 65535) throw new Error('CDP port 必须在 1024-65535 之间');
  const version = clean(target.version);
  if (version && !/^\d+(?:\.\d+){1,3}$/.test(version)) throw new Error('WorkBuddy 版本必须是数字版本号');
  const capabilities = {};
  if (target.capabilities && typeof target.capabilities === 'object' && !Array.isArray(target.capabilities)) {
    for (const name of ['accounts', 'sessions', 'models', 'stashPrompt', 'theme', 'checkin']) {
      if (typeof target.capabilities[name] === 'boolean') capabilities[name] = target.capabilities[name];
    }
  }
  return {
    schemaVersion: 1,
    clientType,
    profileId,
    binary,
    ...(version ? { version } : {}),
    // WorkBuddy updates replace the executable in place. The installation
    // path is the stable identity; never block startup on a recorded version.
    lockVersion: false,
    processNames: uniqueProcessNames,
    ...(target.dataRoot ? { dataRoot: clean(target.dataRoot) } : {}),
    ...(target.authFile ? { authFile: clean(target.authFile) } : {}),
    ...(target.sessionDb ? { sessionDb: clean(target.sessionDb) } : {}),
    ...(target.modelsFile ? { modelsFile: clean(target.modelsFile) } : {}),
    ...(apiHost ? { apiHost } : {}),
    targetHints: Array.from(new Set((Array.isArray(target.targetHints) ? target.targetHints : [])
      .map(clean).filter((value) => value && value.length <= 200))).slice(0, 8),
    cdp: { mode: cdp.mode, port: cdpPort },
    capabilities,
  };
}

function hostFromValue(value) {
  const text = clean(value);
  if (!text || text.length > 4096) return '';
  try {
    const parsed = new URL(/^https?:\/\//i.test(text) ? text : `https://${text}`);
    if (parsed.protocol !== 'https:' || !parsed.hostname.includes('.') || parsed.username || parsed.password) return '';
    return parsed.origin;
  } catch (_) { return ''; }
}

function jwtIssuer(value) {
  const parts = clean(value).split('.');
  if (parts.length !== 3 || parts[1].length > 8192) return '';
  try {
    const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
    return payload && hostFromValue(payload.iss);
  } catch (_) { return ''; }
}

function apiHostFromAuth(value) {
  const seen = new Set();
  function visit(node, key, depth) {
    if (depth > 8 || node === null || node === undefined) return '';
    if (typeof node === 'string') {
      if (/token/i.test(key || '')) return jwtIssuer(node);
      if (/^(?:iss|issuer|domain|apiHost|apiEndpoint|realm)$/i.test(key || '')) return hostFromValue(node);
      return '';
    }
    if (typeof node !== 'object' || seen.has(node)) return '';
    seen.add(node);
    for (const [childKey, child] of Object.entries(node)) {
      const found = visit(child, childKey, depth + 1);
      if (found) return found;
    }
    return '';
  }
  return visit(value, '', 0);
}

function findAuthFile(authDir, stem) {
  const exact = path.join(authDir, `workbuddy-desktop-${stem}.info`);
  try { if (fs.statSync(exact).isFile()) return exact; } catch (_) {}
  let names = [];
  try { names = fs.readdirSync(authDir); } catch (_) { return ''; }
  const tokens = stem.toLowerCase().split(/[^a-z0-9]+/).filter((token) => token.length > 2);
  const matches = names.filter((name) => name.toLowerCase().endsWith('.info') && tokens.every((token) => name.toLowerCase().includes(token)));
  return matches.length === 1 ? path.join(authDir, matches[0]) : '';
}

// macOS 企业客户端的 Electron 进程名固定为 Electron,不能像 Windows/Linux
// 一样从可执行文件名推导凭据文件。优先用 .app 名称生成精确文件名,
// 再在 auth 目录中选择唯一的带后缀凭据,避免被历史遗留的官方文件遮蔽。
function findMacAuthFile(authDir, appName, profileId) {
  const canonical = path.join(authDir, profileId === 'workbuddy-ai'
    ? 'workbuddy-desktop-ai.info'
    : 'workbuddy-desktop.info');
  let names;
  try {
    names = fs.readdirSync(authDir).filter((name) => /^workbuddy-desktop(?:-[^/]+)?\.info$/i.test(name));
  } catch (_) {
    return canonical;
  }
  const officialName = profileId === 'workbuddy-ai' ? 'WorkBuddy AI' : 'WorkBuddy';
  if (clean(appName).toLowerCase() === officialName.toLowerCase()) return canonical;
  const suffix = clean(appName).replace(/^workbuddy(?:\s*ai)?[\s_-]*/i, '').trim();
  if (suffix) {
    const exact = path.join(authDir, `workbuddy-desktop-${suffix}.info`);
    if (names.some((name) => name === path.basename(exact))) return exact;
  }
  const custom = names.filter((name) => !/^workbuddy-desktop(?:-ai)?\.info$/i.test(name));
  if (custom.length === 1) return path.join(authDir, custom[0]);
  if (suffix && custom.length > 1) {
    const tokens = suffix.toLowerCase().split(/[^a-z0-9\u0080-\uffff]+/).filter((token) => token.length > 1);
    const matched = custom.filter((name) => {
      const lower = name.toLowerCase();
      return tokens.length > 0 && tokens.every((token) => lower.includes(token));
    });
    if (matched.length === 1) return path.join(authDir, matched[0]);
  }
  return canonical;
}

function buildTargetFromBinary(options = {}) {
  const platform = options.platform || process.platform;
  const pathApi = platformPath(platform);
  const binary = clean(options.binary);
  if (!binary || !isAbsolute(binary, platform)) throw new Error(platform === 'win32' ? '请选择完整的 WorkBuddy .exe 路径' : '请选择完整的 WorkBuddy 应用可执行文件路径');
  const processName = pathApi.basename(binary);
  if (platform === 'win32' && !/\.exe$/i.test(processName)) throw new Error('请选择 WorkBuddy 的 .exe 主程序');
  // Linux:没有 .app 包,安装目录里就是 Electron 主程序(实测 5.5.4: /opt/WorkBuddy/workbuddy)。
  // 数据根沿用 ~/.workbuddy(CN)/ ~/.workbuddy-ai(AI),登录凭据在 $XDG_DATA_HOME 下,
  // 与 macOS 同构、仅根不同。海外版常以独立 HOME 启动,此时 os.homedir() 即隔离 HOME。
  // 注意末尾的 .exe 判断与 darwin 分支同理:以 .exe 结尾的路径说明这是跨平台传入的
  // Windows/企业版目标,应继续走下面的通用分支(它按 localAppData 推导数据根与 apiHost)。
  if (platform === 'linux' && !/\.exe$/i.test(processName)) {
    const posixPath = path.posix;
    const profileId = clean(options.profileId) || 'workbuddy-cn';
    const ai = profileId === 'workbuddy-ai';
    const port = Number(options.cdpPort) || (ai ? 9223 : 9222);
    const home = options.home || os.homedir();
    const xdgData = clean(options.xdgDataHome) || clean(process.env.XDG_DATA_HOME) ||
      posixPath.join(home, '.local', 'share');
    const extensionAuth = posixPath.join(xdgData, 'CodeBuddyExtension', 'Data', 'Public', 'auth');
    // 官方包(/opt/WorkBuddy/workbuddy)按 official 处理:数据源全部走 profiles.js 的
    // Linux 默认值,customTarget 保持 false,CDP 目标判定可用「标题兜底」,
    // 避免自定义目标下 targetHints 过严导致注入目标匹配不上。
    // 海外版/企业版副本路径与数据目录都不标准,按 enterprise 显式写全。
    const clientType = clean(options.clientType) || (ai ? 'enterprise' : 'official');
    if (clientType === 'official') {
      return validateTarget({
        schemaVersion: 1,
        clientType,
        profileId,
        binary,
        version: clean(options.version),
        processNames: [processName],
        cdp: { mode: 'argument', port },
      }, { platform });
    }
    // 海外版/企业版:Electron 的 userData 可能被 WORKBUDDY_CONFIG_DIR 或
    // --user-data-dir 重定向(本机海外版就是 $HOME/.config/workbuddy-ai),
    // 不能硬套 ~/.workbuddy-ai,必须按「含 workbuddy.db」探测真实数据根。
    const dataRoot = clean(options.dataRoot) || clean(process.env.WBSWITCH_TARGET_DATA_ROOT) || plat.pickLinuxDataRoot(
      plat.linuxDataRootCandidates(profileId, { home, env: options.env || process.env })
    );
    const authFile = clean(options.authFile) || plat.linuxAuthFileFor(extensionAuth, profileId);
    return validateTarget({
      schemaVersion: 1,
      clientType,
      profileId,
      binary,
      version: clean(options.version),
      processNames: [processName],
      dataRoot,
      authFile,
      sessionDb: posixPath.join(dataRoot, 'workbuddy.db'),
      modelsFile: posixPath.join(dataRoot, 'models.json'),
      apiHost: ai ? 'https://www.workbuddy.ai' : 'https://www.codebuddy.cn',
      // 归属提示必须能区分「同一应用的多个实例」。CN 与 AI 的可执行文件**同名**
      // (都叫 workbuddy),若把裸应用名写进 targetHints,海外版会把国内版的页面
      // 认成自己的注入目标,导致跨实例注入。改用「安装目录 + 端专属标记」,
      // 二者在 CN / AI 的页面 URL 之间互不包含。
      targetHints: [posixPath.dirname(binary), ai ? 'workbuddy-ai' : 'workbuddy-cn'].filter(Boolean),
      cdp: { mode: 'argument', port },
      capabilities: { accounts: true, sessions: true, models: true, stashPrompt: true, theme: true, checkin: true },
    }, { platform });
  }
  // Keep accepting legacy cross-platform test/configuration paths ending in
  // .exe; real macOS app binaries use the branch below with their native name.
  if (platform === 'darwin' && !/\.exe$/i.test(processName)) {
    // macOS 路径必须始终用 posix 拼装:Windows 上默认 path 是 win32,
    // 用它 join 会产出 C:\ 风格路径,被 darwin 的绝对路径校验拒绝。
    const posixPath = path.posix;
    const profileId = clean(options.profileId) || 'workbuddy-cn';
    const port = Number(options.cdpPort) || (profileId === 'workbuddy-ai' ? 9223 : 9222);
    const appName = posixPath.basename(binary.replace(/\/Contents\/MacOS\/[^/]+$/i, '')).replace(/\.app$/i, '');
    const home = options.home || os.homedir();
    const appSupport = posixPath.join(home, 'Library', 'Application Support');
    const extensionAuth = posixPath.join(appSupport, 'CodeBuddyExtension', 'Data', 'Public', 'auth');
    const ai = profileId === 'workbuddy-ai';
    const workbuddyRoot = posixPath.join(home, ai ? '.workbuddy-ai' : '.workbuddy');
    const authFile = findMacAuthFile(extensionAuth, appName, profileId);
    let apiHost = ai ? 'https://www.workbuddy.ai' : 'https://www.codebuddy.cn';
    try {
      if (fs.existsSync(authFile)) {
        apiHost = apiHostFromAuth(JSON.parse(fs.readFileSync(authFile, 'utf8'))) || apiHost;
      }
    } catch (_) {}
    return validateTarget({
      schemaVersion: 1,
      clientType: 'enterprise',
      profileId,
      binary,
      version: clean(options.version),
      processNames: [processName],
      authFile,
      sessionDb: posixPath.join(workbuddyRoot, 'workbuddy.db'),
      modelsFile: posixPath.join(workbuddyRoot, 'models.json'),
      apiHost,
      targetHints: [appName].filter(Boolean),
      cdp: { mode: 'argument', port },
      capabilities: { accounts: true, sessions: true, models: true, stashPrompt: true, theme: true, checkin: true },
    }, { platform });
  }
  const processNames = inferredProcessNames(binary, platform);
  const stem = processName.replace(/\.exe$/i, '').toLowerCase();
  const home = options.home || os.homedir();
  const localAppData = options.localAppData || process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
  const dataRoot = path.join(home, `.${stem}`);
  const authDir = path.join(localAppData, 'CodeBuddyExtension', 'Data', 'Public', 'auth');
  const authFile = findAuthFile(authDir, stem);
  let apiHost = '';
  if (authFile) {
    try { apiHost = apiHostFromAuth(JSON.parse(fs.readFileSync(authFile, 'utf8'))); } catch (_) {}
  }
  const profileId = clean(options.profileId) || 'workbuddy-cn';
  const port = Number(options.cdpPort) || (profileId === 'workbuddy-ai' ? 9233 : 9226);
  return validateTarget({
    schemaVersion: 1,
    clientType: 'enterprise',
    profileId,
    binary,
    version: clean(options.version),
    lockVersion: false,
    processNames,
    dataRoot,
    ...(authFile ? { authFile } : {}),
    sessionDb: path.join(dataRoot, 'workbuddy.db'),
    modelsFile: path.join(dataRoot, 'models.json'),
    ...(apiHost ? { apiHost } : {}),
    targetHints: [stem, apiHost ? new URL(apiHost).hostname : ''].filter(Boolean),
    cdp: { mode: 'environment', port },
    capabilities: { accounts: !!authFile, sessions: true, models: true, stashPrompt: true, theme: true, checkin: false },
  }, { platform });
}

function buildOfficialTargetFromBinary(options = {}) {
  const platform = options.platform || process.platform;
  const pathApi = platformPath(platform);
  const binary = clean(options.binary);
  const profileId = clean(options.profileId) || 'workbuddy-cn';
  if (!binary || !isAbsolute(binary, platform)) throw new Error('请选择完整的 WorkBuddy .exe 路径');
  const expectedName = profileId === 'workbuddy-ai' ? 'WorkBuddyAI.exe' : 'WorkBuddy.exe';
  if (pathApi.basename(binary).toLowerCase() !== expectedName.toLowerCase()) {
    throw new Error(`当前安装包的官方客户端必须是 ${expectedName}`);
  }
  return validateTarget({
    schemaVersion: 1,
    clientType: 'official',
    profileId,
    binary,
    version: clean(options.version),
    lockVersion: false,
    processNames: [pathApi.basename(binary)],
    targetHints: [],
    cdp: { mode: 'argument', port: profileId === 'workbuddy-ai' ? 9223 : 9222 },
    capabilities: {},
  }, { platform });
}

function readWorkBuddyTarget({ dataDir, profileId, env = process.env, platform = process.platform } = {}) {
  const envBinary = clean(env.WBSWITCH_WORKBUDDY_BIN);
  const envVersion = clean(env.WBSWITCH_WORKBUDDY_VERSION);
  let target = null;
  if (dataDir) {
    try { target = JSON.parse(fs.readFileSync(targetFile(dataDir), 'utf8')); } catch (error) {
      if (!error || error.code !== 'ENOENT') return emptyTarget(true, 'file');
    }
  }
  if (target && typeof target !== 'object') return emptyTarget(true, 'file');
  const configuredProfile = target && clean(target.profileId || target.profile);
  if (configuredProfile && profileId && configuredProfile !== clean(profileId)) return emptyTarget(true, 'file');
  if (target && (target.schemaVersion || target.processName || target.processNames || target.dataRoot || target.apiHost || target.cdp)) {
    const merged = { ...target };
    if (envBinary) {
      merged.binary = envBinary;
      merged.processNames = inferredProcessNames(envBinary, platform);
      delete merged.processName;
    }
    if (envVersion) merged.version = envVersion;
    // 读取须容忍跨平台目标:Windows 管理机上可能读出为 macOS 客户端写入的
    // target(进程名非 .exe),按当前平台严格校验会误报;先按当前平台尝试,
    // 失败则按另一平台校验,仅平台相关约束(.exe / 绝对路径形态)被放宽。
    try {
      return { ...validateTarget(merged, { platform }), configured: true, source: envBinary ? 'environment' : 'file' };
    } catch (error) {
      const fallbackPlatform = platform === 'win32' ? 'darwin' : 'win32';
      if (fallbackPlatform === platform) throw error;
      return { ...validateTarget(merged, { platform: fallbackPlatform }), configured: true, source: envBinary ? 'environment' : 'file' };
    }
  }
  if (envBinary) return { configured: true, binary: envBinary, version: envVersion, source: 'environment' };
  if (!target) return emptyTarget();
  return {
    configured: true,
    binary: clean(target.binary || target.executable || target.path),
    version: envVersion || clean(target.version),
    source: 'file',
  };
}

function writeWorkBuddyTarget({ dataDir, profileId, target, platform = process.platform } = {}) {
  if (!dataDir) throw new Error('缺少 WorkDaddy 数据目录');
  const normalized = validateTarget(target, { platform });
  if (profileId && normalized.profileId !== profileId) throw new Error('客户端 profile 与当前 WorkDaddy 安装包不匹配');
  fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
  const file = targetFile(dataDir);
  const temporary = `${file}.tmp.${process.pid}`;
  fs.writeFileSync(temporary, JSON.stringify(normalized, null, 2) + '\n', { mode: 0o600 });
  try {
    fs.renameSync(temporary, file);
  } catch (error) {
    if (!error || !['EEXIST', 'EPERM', 'ENOTEMPTY'].includes(error.code)) throw error;
    fs.copyFileSync(temporary, file);
    fs.unlinkSync(temporary);
  }
  try { fs.chmodSync(file, 0o600); } catch (_) {}
  return normalized;
}

function removeWorkBuddyTarget({ dataDir } = {}) {
  if (!dataDir) return false;
  try { fs.unlinkSync(targetFile(dataDir)); return true; } catch (error) {
    if (error && error.code === 'ENOENT') return false;
    throw error;
  }
}

function cliValue(argv, name) {
  const index = argv.indexOf(name);
  if (index >= 0 && index + 1 < argv.length) return argv[index + 1];
  const prefix = `${name}=`;
  const inline = argv.find((value) => typeof value === 'string' && value.startsWith(prefix));
  return inline ? inline.slice(prefix.length) : '';
}

function configureFromInstaller(argv = process.argv.slice(2)) {
  if (!argv.includes('--configure')) throw new Error('缺少 --configure');
  const profileId = clean(cliValue(argv, '--profile'));
  const binary = clean(cliValue(argv, '--binary'));
  const version = clean(cliValue(argv, '--version'));
  const dataDir = clean(cliValue(argv, '--data-dir'));
  const platform = clean(cliValue(argv, '--platform')) || process.env.WBSWITCH_TARGET_PLATFORM || 'win32';
  const pathApi = platformPath(platform);
  if (platform !== 'win32' && platform !== 'darwin' && platform !== 'linux') throw new Error('仅支持 win32 / darwin / linux 客户端配置');
  if (platform !== 'win32') {
    const target = buildTargetFromBinary({
      binary,
      version,
      profileId,
      cdpPort: profileId === 'workbuddy-ai' ? 9223 : 9222,
      platform,
    });
    const saved = writeWorkBuddyTarget({ dataDir, profileId, target, platform });
    process.stdout.write(JSON.stringify({ ok: true, name: pathApi.basename(saved.binary), version: saved.version || '', clientType: saved.clientType }) + '\n');
    return saved;
  }
  const expectedName = profileId === 'workbuddy-ai' ? 'WorkBuddyAI.exe' : 'WorkBuddy.exe';
  const official = pathApi.basename(binary).toLowerCase() === expectedName.toLowerCase();
  const target = official
    ? buildOfficialTargetFromBinary({ binary, version, profileId, platform: 'win32' })
    : buildTargetFromBinary({
      binary,
      version,
      profileId,
      cdpPort: profileId === 'workbuddy-ai' ? 9233 : 9226,
      platform: 'win32',
    });
  const saved = writeWorkBuddyTarget({ dataDir, profileId, target, platform: 'win32' });
  process.stdout.write(JSON.stringify({ ok: true, name: pathApi.basename(saved.binary), version: saved.version || '', clientType: saved.clientType }) + '\n');
  return saved;
}

function resolveFromConfig(argv = process.argv.slice(2)) {
  const profileId = clean(cliValue(argv, '--profile'));
  const dataDir = clean(cliValue(argv, '--data-dir'));
  if (!profileId || !dataDir) return '';
  const target = readWorkBuddyTarget({ dataDir, profileId, platform: process.platform });
  if (!target.configured || !target.binary) return '';
  process.stdout.write(target.binary + '\n');
  return target.binary;
}

if (require.main === module && process.argv.slice(2).includes('--resolve')) {
  try {
    resolveFromConfig();
  } catch (error) {
    process.stderr.write(String(error && error.message || error) + '\n');
    process.exitCode = 1;
  }
} else if (require.main === module && process.argv.slice(2).includes('--configure')) {
  try {
    configureFromInstaller();
  } catch (error) {
    process.stderr.write(String(error && error.message || error) + '\n');
    process.exitCode = 1;
  }
}

module.exports = {
  TARGET_FILE,
  apiHostFromAuth,
  buildOfficialTargetFromBinary,
  buildTargetFromBinary,
  configureFromInstaller,
  inferredProcessNames,
  resolveFromConfig,
  readWorkBuddyTarget,
  removeWorkBuddyTarget,
  targetFile,
  validateProcessName,
  validateTarget,
  writeWorkBuddyTarget,
};