From cf44c7dcdf21c87194847825c109956fec096311 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Thu, 3 Sep 2026 11:34:29 +0800 Subject: [PATCH] =?UTF-8?q?feat(config):=20=E6=94=AF=E6=8C=81=E5=A4=9A?= =?UTF-8?q?=E5=B1=82=E7=BA=A7=E4=BC=81=E4=B8=9A=E9=85=8D=E7=BD=AE=E5=8F=91?= =?UTF-8?q?=E7=8E=B0=E3=80=81=E8=AF=BB=E5=86=99=E5=88=86=E7=A6=BB=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E8=90=BD=E7=9B=98=E4=B8=8E=E8=B7=AF=E5=BE=84=E8=AF=8A?= =?UTF-8?q?=E6=96=AD=E5=B9=B6=E5=8F=91=E5=B8=83=20v0.4.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 +- openapi/openapi.yaml | 2 +- package.json | 2 +- skills/hose-use/SKILL.md | 3 + src/cli/commands/config.ts | 49 ++++++++++- src/cli/helpers.ts | 4 +- src/core/config/loader.test.ts | 143 +++++++++++++++++++++++++++++++ src/core/config/loader.ts | 151 +++++++++++++++++++++++++-------- src/core/config/manager.ts | 22 +++-- src/version.ts | 2 +- 10 files changed, 331 insertions(+), 54 deletions(-) create mode 100644 src/core/config/loader.test.ts diff --git a/README.md b/README.md index ba65be3..cfe9ee6 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# hose-use (v0.4.0) +# hose-use (v0.4.1) 合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。 @@ -32,8 +32,9 @@ hose-use corps list # 列出名下所有已配置企 hose-use corps switch # 切换工作企业 hose-use corps current # 查看当前激活企业 -# 3. 运行模式管理 (有状态 vs 无状态) -hose-use config show # 查看当前运行模式 +# 3. 运行模式与多级配置路径管理 (有状态 vs 无状态) +hose-use config show # 查看当前运行模式与默认企业 +hose-use config paths # 查看多级企业目录发现链与配置文件位置 hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作) hose-use config mode stateful # 切换为有状态模式 (记忆默认企业) diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml index b03e65e..bd7aea0 100644 --- a/openapi/openapi.yaml +++ b/openapi/openapi.yaml @@ -1,7 +1,7 @@ openapi: 3.1.0 info: title: hose-use API & MCP Tools Specification - version: 0.4.0 + version: 0.4.1 description: >- Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows. servers: diff --git a/package.json b/package.json index 6478bcc..9d4aa28 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hose-use", - "version": "0.4.0", + "version": "0.4.1", "module": "src/server.ts", "type": "module", "bin": { diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index cb0f8ac..f521275 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -84,6 +84,9 @@ hose-use corps current # 查看全局运行模式与配置文件路径 hose-use config show +# 查看多级企业目录发现路径与诊断 +hose-use config paths + # 切换为无状态模式 (Stateless) hose-use config mode stateless diff --git a/src/cli/commands/config.ts b/src/cli/commands/config.ts index f7242a4..fe79252 100644 --- a/src/cli/commands/config.ts +++ b/src/cli/commands/config.ts @@ -2,6 +2,9 @@ import { loadGlobalConfig, saveGlobalConfig, resolveGlobalConfigFile, + resolveEnterprisesDirs, + resolveWritableEnterprisesDir, + getEnterprisesDirCandidates, } from "../../core/config/loader.js"; import { printJson, printKeyValue } from "../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; @@ -17,6 +20,10 @@ export async function handleConfigCommand( case "get": case "list": return handleShow(parsed, runtime); + case "paths": + case "path": + case "dirs": + return handlePaths(parsed, runtime); case "mode": return handleMode(parsed, runtime); case "set": @@ -24,7 +31,7 @@ export async function handleConfigCommand( default: return { stdout: "", - stderr: `未知 config 子命令: ${action}。支持: show, mode , set \n`, + stderr: `未知 config 子命令: ${action}。支持: show, paths, mode , set \n`, exitCode: 1, }; } @@ -125,3 +132,43 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const envDir = process.env.HOSE_ENTERPRISES_DIR; + const envUserDir = process.env.HOSE_USER_ENTERPRISES_DIR; + const envConfigFile = process.env.HOSE_CONFIG_FILE; + const existingDirs = resolveEnterprisesDirs(); + const writableDir = resolveWritableEnterprisesDir(); + const configFile = resolveGlobalConfigFile(); + const candidates = getEnterprisesDirCandidates(); + + const data = { + configFile, + writableDir, + existingDirs, + env: { + HOSE_ENTERPRISES_DIR: envDir || null, + HOSE_USER_ENTERPRISES_DIR: envUserDir || null, + HOSE_CONFIG_FILE: envConfigFile || null, + }, + candidates, + }; + + if (runtime.jsonMode) { + return { stdout: printJson(data), stderr: "", exitCode: 0 }; + } + + const output = printKeyValue({ + "当前生效配置文件": configFile, + "凭证保存写入目录": writableDir, + "已发现企业目录": existingDirs.length ? existingDirs.join("\n ") : "无 (未发现任何有效企业目录)", + "环境变量指定目录": envDir || "未设置 (HOSE_ENTERPRISES_DIR)", + "全部目录候选链": candidates.join("\n "), + }); + + return { + stdout: `====== 配置路径诊断 (Config Paths) ======\n${output}\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/helpers.ts b/src/cli/helpers.ts index 8c96874..49b7c2b 100644 --- a/src/cli/helpers.ts +++ b/src/cli/helpers.ts @@ -1,5 +1,5 @@ import readline from "readline"; -import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js"; +import { loadCorpConfigs, loadGlobalConfig, getEnterprisesDirCandidates } from "../core/config/loader.js"; import { CorpContext, resolveCorpConfig } from "../core/config/manager.js"; import { CorpConfig } from "../core/config/types.js"; import { createEkbClient } from "../core/auth/ekb.js"; @@ -31,7 +31,7 @@ export function initCorpRuntime( let selectedCorp: CorpConfig | null = null; try { - selectedCorp = corpContext.resolve(options.corpId); + selectedCorp = corpContext.resolve(options.corpId, getEnterprisesDirCandidates()); } catch { selectedCorp = null; } diff --git a/src/core/config/loader.test.ts b/src/core/config/loader.test.ts new file mode 100644 index 0000000..ac8fa6d --- /dev/null +++ b/src/core/config/loader.test.ts @@ -0,0 +1,143 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + loadCorpConfigs, + saveCorpConfig, + resolveEnterprisesDirs, + resolveWritableEnterprisesDir, + loadGlobalConfig, + saveGlobalConfig, + resolveGlobalConfigFile, +} from "./loader.js"; +import type { CorpConfig } from "./types.js"; + +describe("core/config/loader", () => { + let tempDir: string; + const originalEnv = { ...process.env }; + + beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), "hose-config-test-")); + }); + + afterEach(() => { + process.env = { ...originalEnv }; + try { + rmSync(tempDir, { recursive: true, force: true }); + } catch { + // ignore + } + }); + + test("resolveEnterprisesDirs prioritizes HOSE_ENTERPRISES_DIR environment variable", () => { + const customDir = join(tempDir, "custom-enterprises"); + mkdirSync(customDir, { recursive: true }); + process.env.HOSE_ENTERPRISES_DIR = customDir; + + const dirs = resolveEnterprisesDirs(); + expect(dirs).toEqual([customDir]); + }); + + test("resolveWritableEnterprisesDir respects HOSE_ENTERPRISES_DIR", () => { + const customDir = join(tempDir, "writable-enterprises"); + mkdirSync(customDir, { recursive: true }); + process.env.HOSE_ENTERPRISES_DIR = customDir; + + expect(resolveWritableEnterprisesDir()).toBe(customDir); + }); + + const createMockCorp = (id: string, name: string, overrides: Partial = {}): CorpConfig => ({ + id, + name, + baseUrl: "https://app.ekuaibao.com", + source: "manual", + credentials: { + accessToken: `token-${id}`, + corpId: id, + staffId: `staff-${id}`, + }, + ...overrides, + }); + + test("loadCorpConfigs loads valid configs and skips example files", () => { + const dirA = join(tempDir, "dirA"); + mkdirSync(dirA, { recursive: true }); + + const validCorp = createMockCorp("corp-1", "企业1"); + + // Save valid corp + writeFileSync(join(dirA, "corp-1.json"), JSON.stringify(validCorp)); + // Save example corp + writeFileSync( + join(dirA, "example.json"), + JSON.stringify(createMockCorp("example-corp", "模板企业")) + ); + + const loaded = loadCorpConfigs([dirA]); + expect(loaded).toHaveLength(1); + expect(loaded[0]?.id).toBe("corp-1"); + expect(loaded[0]?.name).toBe("企业1"); + }); + + test("loadCorpConfigs merges multiple directories with earlier directory taking precedence", () => { + const dirA = join(tempDir, "dirA"); + const dirB = join(tempDir, "dirB"); + mkdirSync(dirA, { recursive: true }); + mkdirSync(dirB, { recursive: true }); + + const corpInA = createMockCorp("corp-common", "本地优先企业", { + credentials: { accessToken: "token-a", corpId: "corp-common", staffId: "staff-a" }, + }); + + const corpInB = createMockCorp("corp-common", "全局覆盖企业", { + credentials: { accessToken: "token-b", corpId: "corp-common", staffId: "staff-b" }, + }); + + const corpOnlyB = createMockCorp("corp-b-only", "仅在B的企业", { + credentials: { accessToken: "token-b2", corpId: "corp-b-only", staffId: "staff-b2" }, + }); + + writeFileSync(join(dirA, "corp-common.json"), JSON.stringify(corpInA)); + writeFileSync(join(dirB, "corp-common.json"), JSON.stringify(corpInB)); + writeFileSync(join(dirB, "corp-b-only.json"), JSON.stringify(corpOnlyB)); + + const loaded = loadCorpConfigs([dirA, dirB]); + expect(loaded).toHaveLength(2); + + const common = loaded.find((c) => c.id === "corp-common"); + expect(common?.name).toBe("本地优先企业"); + + const bOnly = loaded.find((c) => c.id === "corp-b-only"); + expect(bOnly?.name).toBe("仅在B的企业"); + }); + + test("saveCorpConfig writes validated JSON to target directory", () => { + const targetDir = join(tempDir, "save-target"); + const corp = createMockCorp("corp-save-test", "保存测试企业", { + credentials: { accessToken: "tok-123", corpId: "corp-save-test", staffId: "stf-1" }, + }); + + const filePath = saveCorpConfig(corp, targetDir); + expect(existsSync(filePath)).toBe(true); + + const saved = JSON.parse(readFileSync(filePath, "utf-8")); + expect(saved.id).toBe("corp-save-test"); + expect(saved.credentials.accessToken).toBe("tok-123"); + }); + + test("loadGlobalConfig and saveGlobalConfig respect HOSE_CONFIG_FILE", () => { + const customConfigFile = join(tempDir, "config.json"); + process.env.HOSE_CONFIG_FILE = customConfigFile; + + expect(resolveGlobalConfigFile()).toBe(customConfigFile); + + const initial = loadGlobalConfig(); + expect(initial.stateful).toBe(true); + + saveGlobalConfig({ stateful: false, defaultCorpId: "test-corp-123" }); + const updated = loadGlobalConfig(); + expect(updated.stateful).toBe(false); + expect(updated.defaultCorpId).toBe("test-corp-123"); + }); +}); diff --git a/src/core/config/loader.ts b/src/core/config/loader.ts index e2a6a80..bb9fecf 100644 --- a/src/core/config/loader.ts +++ b/src/core/config/loader.ts @@ -1,30 +1,96 @@ -import { readFileSync, readdirSync, writeFileSync, mkdirSync } from "fs"; -import { join, dirname } from "path"; -import { homedir } from "os"; +import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js"; -const ENTERPRISES_DIR = "./enterprises"; -const GLOBAL_CONFIG_PATH = join(homedir(), ".cache", "ekb-mcp", "config.json"); +const ENTERPRISES_DIR = "enterprises"; +const CONFIG_ENV = "HOSE_ENTERPRISES_DIR"; +const USER_DIR_ENV = "HOSE_USER_ENTERPRISES_DIR"; +const GLOBAL_CONFIG_ENV = "HOSE_CONFIG_FILE"; + +export const PRIMARY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "hose-use", "enterprises"); +export const LEGACY_USER_ENTERPRISES_DIR = join(homedir(), ".cache", "ekb-mcp", "enterprises"); +export const USER_ENTERPRISES_DIR = PRIMARY_USER_ENTERPRISES_DIR; + +export const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "hose-use", "config.json"); +export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "config.json"); function ensureDir(dir: string): void { mkdirSync(dir, { recursive: true }); } +export function resolveEnterprisesDirs(): string[] { + const configured = process.env[CONFIG_ENV]?.trim(); + if (configured) { + return existsSync(configured) ? [configured] : []; + } + + const configuredUserDir = process.env[USER_DIR_ENV]?.trim(); + if (configuredUserDir) { + return [ENTERPRISES_DIR, configuredUserDir].filter((dir) => existsSync(dir)); + } + + const dirs = [ENTERPRISES_DIR, PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR]; + const uniqueExisting: string[] = []; + for (const d of dirs) { + if (existsSync(d) && !uniqueExisting.includes(d)) { + uniqueExisting.push(d); + } + } + return uniqueExisting; +} + +export function resolvePrimaryEnterprisesDir(): string | undefined { + const configured = process.env[CONFIG_ENV]?.trim(); + if (configured) return existsSync(configured) ? configured : undefined; + if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR; + if (existsSync(PRIMARY_USER_ENTERPRISES_DIR)) return PRIMARY_USER_ENTERPRISES_DIR; + if (existsSync(LEGACY_USER_ENTERPRISES_DIR)) return LEGACY_USER_ENTERPRISES_DIR; + return undefined; +} + +export function resolveWritableEnterprisesDir(): string { + const configured = process.env[CONFIG_ENV]?.trim(); + if (configured) return configured; + const configuredUserDir = process.env[USER_DIR_ENV]?.trim(); + if (configuredUserDir) return configuredUserDir; + if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR; + return PRIMARY_USER_ENTERPRISES_DIR; +} + +export function getEnterprisesDirCandidates(): string[] { + return [ + `${CONFIG_ENV}=`, + ENTERPRISES_DIR, + PRIMARY_USER_ENTERPRISES_DIR, + LEGACY_USER_ENTERPRISES_DIR, + ]; +} + export function resolveGlobalConfigFile(): string { - return GLOBAL_CONFIG_PATH; + const configured = process.env[GLOBAL_CONFIG_ENV]?.trim(); + if (configured) return configured; + if (existsSync(PRIMARY_GLOBAL_CONFIG_FILE)) return PRIMARY_GLOBAL_CONFIG_FILE; + if (existsSync(LEGACY_GLOBAL_CONFIG_FILE)) return LEGACY_GLOBAL_CONFIG_FILE; + return PRIMARY_GLOBAL_CONFIG_FILE; } export function loadGlobalConfig(): GlobalConfig { + const file = resolveGlobalConfigFile(); try { - const content = readFileSync(GLOBAL_CONFIG_PATH, "utf-8"); - return GlobalConfigSchema.parse(JSON.parse(content)); + if (existsSync(file)) { + const content = readFileSync(file, "utf-8"); + return GlobalConfigSchema.parse(JSON.parse(content)); + } } catch { - return { - stateful: true, - defaultCorpId: undefined, - defaultAccountId: undefined, - }; + // 容错返回默认 } + + return { + stateful: true, + defaultCorpId: undefined, + defaultAccountId: undefined, + }; } export function saveGlobalConfig(config: Partial): GlobalConfig { @@ -33,50 +99,61 @@ export function saveGlobalConfig(config: Partial): GlobalConfig { ...current, ...config, }); - ensureDir(dirname(GLOBAL_CONFIG_PATH)); - writeFileSync(GLOBAL_CONFIG_PATH, JSON.stringify(updated, null, 2), "utf-8"); + + const configured = process.env[GLOBAL_CONFIG_ENV]?.trim(); + const targetFile = configured || PRIMARY_GLOBAL_CONFIG_FILE; + ensureDir(dirname(targetFile)); + writeFileSync(targetFile, JSON.stringify(updated, null, 2), "utf-8"); return updated; } -export function loadCorpConfigs(dir: string = ENTERPRISES_DIR): CorpConfig[] { - let files: string[]; - try { - ensureDir(dir); - files = readdirSync(dir).filter((f) => f.endsWith(".json")); - } catch (error) { - console.error( - `[config] failed to read enterprises directory: ${error instanceof Error ? error.message : String(error)}` - ); - return []; - } +export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] { + const dirs = overrideDirs ? overrideDirs.filter(existsSync) : resolveEnterprisesDirs(); + const byId = new Map(); - const configs: CorpConfig[] = []; - for (const file of files) { + for (const dir of dirs) { try { - const content = readFileSync(join(dir, file), "utf-8"); - const parsed = JSON.parse(content); - configs.push(CorpConfigSchema.parse(parsed)); + const files = readdirSync(dir) + .filter((item) => item.endsWith(".json")) + .filter((item) => !item.startsWith("example.")); + + for (const file of files) { + try { + const content = readFileSync(join(dir, file), "utf-8"); + const parsed = JSON.parse(content); + const corp = CorpConfigSchema.parse(parsed); + // 相同企业 ID 以先出现的为准(工作区优先于全局,全局优先于历史) + if (!byId.has(corp.id)) { + byId.set(corp.id, corp); + } + } catch (error) { + console.error( + `[config] failed to load ${file} from ${dir}: ${error instanceof Error ? error.message : String(error)}` + ); + } + } } catch (error) { console.error( - `[config] failed to load ${file}: ${error instanceof Error ? error.message : String(error)}` + `[config] failed to read enterprises directory ${dir}: ${error instanceof Error ? error.message : String(error)}` ); } } - return configs; + return Array.from(byId.values()); } -export function saveCorpConfig(config: CorpConfig, dir: string = ENTERPRISES_DIR): string { - ensureDir(dir); +export function saveCorpConfig(config: CorpConfig, dir?: string): string { + const targetDir = dir || resolveWritableEnterprisesDir(); + ensureDir(targetDir); const validated = CorpConfigSchema.parse(config); - const filePath = join(dir, `${validated.id}.json`); + const filePath = join(targetDir, `${validated.id}.json`); writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8"); return filePath; } export function saveMultipleCorpConfigs( configs: CorpConfig[], - dir: string = ENTERPRISES_DIR + dir?: string ): string[] { return configs.map((config) => saveCorpConfig(config, dir)); } diff --git a/src/core/config/manager.ts b/src/core/config/manager.ts index 6a1d7dd..8adb419 100644 --- a/src/core/config/manager.ts +++ b/src/core/config/manager.ts @@ -18,7 +18,8 @@ export function resolveCorpConfig( stateful: boolean; defaultCorpId?: string; corpId?: string; - } + }, + candidateDirs?: string[] ): CorpConfig { const requestedCorpId = options.corpId?.trim() || undefined; const configuredCorpId = options.stateful @@ -51,7 +52,8 @@ export function resolveCorpConfig( const firstCorp = corps[0]; if (firstCorp) return firstCorp; - throw new Error("未找到任何企业配置。请先运行 `hose auth login` 或在 enterprises/ 目录下添加配置。"); + const hintDirs = candidateDirs?.length ? ` (已检索路径: ${candidateDirs.join(", ")})` : ""; + throw new Error(`未找到任何企业配置。请先运行 'hose auth login' 登录或添加企业配置${hintDirs}。`); } export class CorpContext { @@ -110,12 +112,16 @@ export class CorpContext { return this.corps.get(corpId); } - resolve(corpId?: string): CorpConfig { - return resolveCorpConfig(Array.from(this.corps.values()), { - stateful: this.stateful, - defaultCorpId: this.defaultCorpId, - corpId, - }); + resolve(corpId?: string, candidateDirs?: string[]): CorpConfig { + return resolveCorpConfig( + Array.from(this.corps.values()), + { + stateful: this.stateful, + defaultCorpId: this.defaultCorpId, + corpId, + }, + candidateDirs + ); } upsertCorp(corp: CorpConfig, setCurrent: boolean = false): void { diff --git a/src/version.ts b/src/version.ts index fab1818..de04e98 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = "0.4.0"; +export const VERSION = "0.4.1";