diff --git a/src/cli/commands/config.ts b/src/cli/commands/config.ts new file mode 100644 index 0000000..f7242a4 --- /dev/null +++ b/src/cli/commands/config.ts @@ -0,0 +1,127 @@ +import { + loadGlobalConfig, + saveGlobalConfig, + resolveGlobalConfigFile, +} from "../../core/config/loader.js"; +import { printJson, printKeyValue } from "../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; + +export async function handleConfigCommand( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const action = parsed.action || "show"; + + switch (action) { + case "show": + case "get": + case "list": + return handleShow(parsed, runtime); + case "mode": + return handleMode(parsed, runtime); + case "set": + return handleSet(parsed, runtime); + default: + return { + stdout: "", + stderr: `未知 config 子命令: ${action}。支持: show, mode , set \n`, + exitCode: 1, + }; + } +} + +async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const globalConfig = loadGlobalConfig(); + const currentCorp = runtime.selectedCorp; + const configPath = resolveGlobalConfigFile(); + + const summaryObj = { + mode: globalConfig.stateful ? "stateful" : "stateless", + stateful: globalConfig.stateful, + defaultCorpId: globalConfig.defaultCorpId || null, + defaultAccountId: globalConfig.defaultAccountId || null, + activeCorp: currentCorp ? { id: currentCorp.id, name: currentCorp.name } : null, + configFile: configPath, + }; + + if (runtime.jsonMode) { + return { stdout: printJson(summaryObj), stderr: "", exitCode: 0 }; + } + + const output = printKeyValue({ + "运行模式 (Mode)": globalConfig.stateful ? "有状态模式 (Stateful - 自动记忆默认企业)" : "无状态模式 (Stateless - 每次需显式传 --corp)", + "默认工作企业": globalConfig.defaultCorpId || "未设置 (使用首个可用企业)", + "当前解析企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "无", + "配置文件路径": configPath, + }); + + return { + stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose config mode \n 指定企业: hose corps switch \n`, + stderr: "", + exitCode: 0, + }; +} + +async function handleMode(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const targetMode = parsed.args[0]?.toLowerCase(); + + if (!targetMode || (targetMode !== "stateful" && targetMode !== "stateless")) { + return { + stdout: "", + stderr: "用法: hose config mode \n", + exitCode: 1, + }; + } + + const isStateful = targetMode === "stateful"; + const updated = saveGlobalConfig({ stateful: isStateful }); + + if (runtime.jsonMode) { + return { stdout: printJson(updated), stderr: "", exitCode: 0 }; + } + + return { + stdout: `[SUCCESS] 全局运行模式已切换为: ${isStateful ? "有状态模式 (Stateful)" : "无状态模式 (Stateless)"}\n`, + stderr: "", + exitCode: 0, + }; +} + +async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const key = parsed.args[0]; + const val = parsed.args[1]; + + if (!key || val === undefined) { + return { + stdout: "", + stderr: "用法: hose config set (如 hose config set defaultCorpId uzU7pcWfScck00)\n", + exitCode: 1, + }; + } + + const partial: Record = {}; + if (key === "stateful") { + partial.stateful = val === "true" || val === "1"; + } else if (key === "defaultCorpId") { + partial.defaultCorpId = val; + } else if (key === "defaultAccountId") { + partial.defaultAccountId = val; + } else { + return { + stdout: "", + stderr: `不支持配置键: ${key}。支持: stateful, defaultCorpId, defaultAccountId\n`, + exitCode: 1, + }; + } + + const updated = saveGlobalConfig(partial); + if (runtime.jsonMode) { + return { stdout: printJson(updated), stderr: "", exitCode: 0 }; + } + + return { + stdout: `[SUCCESS] 配置已更新: ${key} = ${val}\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/helpers.ts b/src/cli/helpers.ts index 38dced2..8c96874 100644 --- a/src/cli/helpers.ts +++ b/src/cli/helpers.ts @@ -1,23 +1,45 @@ import readline from "readline"; -import { loadCorpConfigs } from "../core/config/loader.js"; -import { CorpContext } from "../core/config/manager.js"; +import { loadCorpConfigs, loadGlobalConfig } 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"; import { getEasoClient } from "../core/auth/easo.js"; import { CliRuntime } from "./types.js"; -export function initCorpRuntime(corpIdOption?: string, jsonMode: boolean = false): CliRuntime { +export function initCorpRuntime( + options: { + corpId?: string; + stateless?: boolean; + stateful?: boolean; + jsonMode?: boolean; + } = {} +): CliRuntime { const corps = loadCorpConfigs(); - const corpContext = new CorpContext(corps); + const globalConfig = loadGlobalConfig(); - if (corpIdOption) { - corpContext.switchCorp(corpIdOption); + // 命令行参数 --stateless / --stateful 具有最高优先级 + const isStateful = options.stateless + ? false + : options.stateful + ? true + : globalConfig.stateful; + + const corpContext = new CorpContext(corps, { + stateful: isStateful, + defaultCorpId: globalConfig.defaultCorpId, + }); + + let selectedCorp: CorpConfig | null = null; + try { + selectedCorp = corpContext.resolve(options.corpId); + } catch { + selectedCorp = null; } return { corpContext, - selectedCorp: corpContext.getCurrent(), - jsonMode, + selectedCorp, + jsonMode: options.jsonMode ?? false, }; } diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 24cd75b..5db29bd 100644 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -4,6 +4,7 @@ import { printHelp, printJson } from "./printer.js"; import { initCorpRuntime } from "./helpers.js"; import { handleAuthCommand } from "./commands/auth.js"; import { handleCorpsCommand } from "./commands/corps.js"; +import { handleConfigCommand } from "./commands/config.js"; import { handleWorkflowCommand } from "./commands/workflow.js"; import { handlePlatformCommand } from "./commands/platform.js"; import { handleProbeCommand } from "./commands/probe.js"; @@ -26,8 +27,15 @@ export async function runCli( const jsonMode = booleanOption(parsed.options, ["json", "j"]); const corpIdOption = stringOption(parsed.options, ["corp", "c"]); + const statelessOption = booleanOption(parsed.options, ["stateless"]); + const statefulOption = booleanOption(parsed.options, ["stateful"]); - const runtime = initCorpRuntime(corpIdOption, jsonMode); + const runtime = initCorpRuntime({ + corpId: corpIdOption, + stateless: statelessOption, + stateful: statefulOption, + jsonMode, + }); try { switch (parsed.area) { @@ -37,6 +45,9 @@ export async function runCli( case "corps": case "corp": return await handleCorpsCommand(parsed, runtime); + case "config": + case "mode": + return await handleConfigCommand(parsed, runtime); case "workflow": case "workflows": case "wf": diff --git a/src/core/config/loader.ts b/src/core/config/loader.ts index 072128e..e2a6a80 100644 --- a/src/core/config/loader.ts +++ b/src/core/config/loader.ts @@ -1,13 +1,43 @@ import { readFileSync, readdirSync, writeFileSync, mkdirSync } from "fs"; -import { join } from "path"; -import { CorpConfig, CorpConfigSchema } from "./types.js"; +import { join, dirname } from "path"; +import { homedir } from "os"; +import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js"; const ENTERPRISES_DIR = "./enterprises"; +const GLOBAL_CONFIG_PATH = join(homedir(), ".cache", "ekb-mcp", "config.json"); function ensureDir(dir: string): void { mkdirSync(dir, { recursive: true }); } +export function resolveGlobalConfigFile(): string { + return GLOBAL_CONFIG_PATH; +} + +export function loadGlobalConfig(): GlobalConfig { + try { + const content = readFileSync(GLOBAL_CONFIG_PATH, "utf-8"); + return GlobalConfigSchema.parse(JSON.parse(content)); + } catch { + return { + stateful: true, + defaultCorpId: undefined, + defaultAccountId: undefined, + }; + } +} + +export function saveGlobalConfig(config: Partial): GlobalConfig { + const current = loadGlobalConfig(); + const updated = GlobalConfigSchema.parse({ + ...current, + ...config, + }); + ensureDir(dirname(GLOBAL_CONFIG_PATH)); + writeFileSync(GLOBAL_CONFIG_PATH, JSON.stringify(updated, null, 2), "utf-8"); + return updated; +} + export function loadCorpConfigs(dir: string = ENTERPRISES_DIR): CorpConfig[] { let files: string[]; try { diff --git a/src/core/config/manager.ts b/src/core/config/manager.ts index a0f6816..cd5efcd 100644 --- a/src/core/config/manager.ts +++ b/src/core/config/manager.ts @@ -1,4 +1,5 @@ -import { CorpConfig } from "./types.js"; +import { CorpConfig, GlobalConfig } from "./types.js"; +import { saveGlobalConfig } from "./loader.js"; export interface CorpSummary { id: string; @@ -10,11 +11,51 @@ export interface CorpSummary { current: boolean; } +export function resolveCorpConfig( + corps: CorpConfig[], + options: { + stateful: boolean; + defaultCorpId?: string; + corpId?: string; + } +): CorpConfig { + const requestedCorpId = options.corpId?.trim() || undefined; + const configuredCorpId = options.stateful + ? options.defaultCorpId?.trim() || undefined + : undefined; + const selectedCorpId = requestedCorpId ?? configuredCorpId; + + if (selectedCorpId) { + const corp = corps.find((item) => item.id === selectedCorpId); + if (corp) return corp; + throw new Error(`未找到企业 ID 为 ${selectedCorpId} 的企业配置`); + } + + if (!options.stateful) { + throw new Error( + "当前处于无状态模式 (Stateless Mode)。执行企业级操作必须显式指定 --corp 。\n" + + "如需设置默认企业,可执行 `hose config mode stateful` 切换为有状态模式。" + ); + } + + const firstCorp = corps[0]; + if (firstCorp) return firstCorp; + + throw new Error("未找到任何企业配置。请先运行 `hose auth login` 或在 enterprises/ 目录下添加配置。"); +} + export class CorpContext { private current: CorpConfig | null = null; private corps: Map = new Map(); + private stateful: boolean = true; + private defaultCorpId: string | undefined; - constructor(corps: CorpConfig[] = []) { + constructor( + corps: CorpConfig[] = [], + options: { stateful?: boolean; defaultCorpId?: string } = {} + ) { + this.stateful = options.stateful ?? true; + this.defaultCorpId = options.defaultCorpId; this.reload(corps); } @@ -23,7 +64,30 @@ export class CorpContext { for (const corp of corps) { this.corps.set(corp.id, corp); } - if (this.corps.size > 0 && (!this.current || !this.corps.has(this.current.id))) { + + if (!this.stateful) { + this.current = null; + return; + } + + if (this.defaultCorpId && this.corps.has(this.defaultCorpId)) { + this.current = this.corps.get(this.defaultCorpId)!; + } else if (this.corps.size > 0) { + this.current = Array.from(this.corps.values())[0]; + } else { + this.current = null; + } + } + + isStateful(): boolean { + return this.stateful; + } + + setStateful(stateful: boolean): void { + this.stateful = stateful; + if (!stateful) { + this.current = null; + } else if (!this.current && this.corps.size > 0) { this.current = Array.from(this.corps.values())[0]; } } @@ -36,17 +100,30 @@ 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, + }); + } + upsertCorp(corp: CorpConfig, setCurrent: boolean = false): void { this.corps.set(corp.id, corp); - if (setCurrent || !this.current) { + if (this.stateful && (setCurrent || !this.current)) { this.current = corp; + this.defaultCorpId = corp.id; } } - switchCorp(corpId: string): boolean { + switchCorp(corpId: string, persist: boolean = true): boolean { const corp = this.corps.get(corpId); if (!corp) return false; this.current = corp; + this.defaultCorpId = corp.id; + if (persist && this.stateful) { + saveGlobalConfig({ defaultCorpId: corp.id }); + } return true; } diff --git a/src/core/config/types.ts b/src/core/config/types.ts index be89d38..083075a 100644 --- a/src/core/config/types.ts +++ b/src/core/config/types.ts @@ -28,3 +28,13 @@ export const CorpConfigSchema = z.object({ export type CorpCredentials = z.infer; export type CorpAuthConfig = z.infer; export type CorpConfig = z.infer; + +// ── 全局运行配置(有状态/无状态模式)───────────────────────────────────────── + +export const GlobalConfigSchema = z.object({ + stateful: z.boolean().default(true).describe("是否为有状态模式 (true 记忆默认企业,false 无状态需显式传 --corp)"), + defaultCorpId: z.string().optional().describe("默认工作企业 ID"), + defaultAccountId: z.string().optional().describe("默认主账号"), +}); + +export type GlobalConfig = z.infer;