Add stateful and stateless enterprise selection
This commit is contained in:
1 parent
d383b3aad8
commit
0959cef1cc
22 files changed
+609
-187
No files matched your search
+86
-3
@@ -1,16 +1,26 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { VERSION } from "./version.js";
|
||||
|
||||
const CLI_PATH = join(import.meta.dirname, "cli.ts");
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function runCli(args: string[]) {
|
||||
function runCli(args: string[], env: Record<string, string> = {}) {
|
||||
return spawnSync("bun", [CLI_PATH, ...args], {
|
||||
encoding: "utf-8"
|
||||
encoding: "utf-8",
|
||||
env: { ...process.env, ...env }
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("CLI version & help handling", () => {
|
||||
test.each([
|
||||
["version"],
|
||||
@@ -46,4 +56,77 @@ describe("CLI version & help handling", () => {
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain("Unknown command: invalid-command. Run 'seal-home help' for available commands.");
|
||||
});
|
||||
|
||||
test("requires --corp in the default stateless mode", () => {
|
||||
const env = makeConfigEnv();
|
||||
const result = runCli(["corps", "current"], env);
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain("Stateless mode is enabled");
|
||||
expect(result.stderr).toContain("--corp <corpId>");
|
||||
});
|
||||
|
||||
test("allows an explicit corp in stateless mode", () => {
|
||||
const env = makeConfigEnv();
|
||||
const result = runCli(["corps", "current", "--corp", "corp-a"], env);
|
||||
|
||||
expect(result.status).toBe(0);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ id: "corp-a" });
|
||||
});
|
||||
|
||||
test("keeps the fine-grained tool command reachable in stateless mode", () => {
|
||||
const env = makeConfigEnv();
|
||||
const result = runCli(["tool", "unknown-tool", "--corp", "corp-a"], env);
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain("Unknown Seal tool: unknown-tool");
|
||||
});
|
||||
|
||||
test("can enable stateful mode and select a default corp", () => {
|
||||
const env = makeConfigEnv();
|
||||
const mode = runCli(["config", "mode", "stateful", "--corp", "corp-a"], env);
|
||||
const current = runCli(["corps", "current"], env);
|
||||
|
||||
expect(mode.status).toBe(0);
|
||||
expect(JSON.parse(mode.stdout)).toMatchObject({
|
||||
mode: "stateful",
|
||||
defaultCorpId: "corp-a"
|
||||
});
|
||||
expect(current.status).toBe(0);
|
||||
expect(JSON.parse(current.stdout)).toMatchObject({ id: "corp-a" });
|
||||
});
|
||||
|
||||
test("removes the default when switching back to stateless mode", () => {
|
||||
const env = makeConfigEnv();
|
||||
runCli(["config", "mode", "stateful", "--corp", "corp-a"], env);
|
||||
|
||||
const mode = runCli(["config", "mode", "stateless"], env);
|
||||
const current = runCli(["corps", "current"], env);
|
||||
|
||||
expect(mode.status).toBe(0);
|
||||
expect(JSON.parse(mode.stdout)).toMatchObject({ mode: "stateless" });
|
||||
expect(JSON.parse(mode.stdout)).not.toHaveProperty("defaultCorpId");
|
||||
expect(current.status).toBe(1);
|
||||
expect(current.stderr).toContain("Stateless mode is enabled");
|
||||
});
|
||||
});
|
||||
|
||||
function makeConfigEnv(): Record<string, string> {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-home-cli-"));
|
||||
tempDirs.push(root);
|
||||
const enterprises = join(root, "enterprises");
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
writeFileSync(join(enterprises, "corp-a.json"), JSON.stringify({
|
||||
id: "corp-a",
|
||||
name: "Corp A",
|
||||
source: {
|
||||
type: "direct",
|
||||
token: "seal-token",
|
||||
sealUrl: "https://corp-a.seal.test"
|
||||
}
|
||||
}));
|
||||
return {
|
||||
SEAL_HOME_ENTERPRISES_DIR: enterprises,
|
||||
SEAL_HOME_CONFIG_FILE: join(root, "config.json")
|
||||
};
|
||||
}
|
||||
+132
-50
@@ -1,11 +1,19 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { getEnterprisesDirCandidates, loadCorpConfigs, resolveWritableEnterprisesDir } from "./core/config/loader.js";
|
||||
import {
|
||||
getEnterprisesDirCandidates,
|
||||
loadCorpConfigs,
|
||||
loadGlobalConfig,
|
||||
resolveGlobalConfigFile,
|
||||
resolveWritableEnterprisesDir,
|
||||
saveGlobalConfig
|
||||
} from "./core/config/loader.js";
|
||||
import { resolveCorpConfig } from "./core/config/manager.js";
|
||||
import { createSealClient } from "./core/http/factory.js";
|
||||
import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js";
|
||||
import { getMe } from "./domains/seal/api.js";
|
||||
@@ -19,11 +27,31 @@ import { runServiceCommand, serviceStatus } from "./cli/service.js";
|
||||
|
||||
const APP_ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||
const STATE_DIR = join(homedir(), ".config", "seal-home");
|
||||
const CURRENT_CORP_FILE = join(STATE_DIR, "current-corp");
|
||||
const RULE_LIST_FULL_COUNT_LIMIT = 100;
|
||||
const RULE_LIST_FULL_BYTES_LIMIT = 120_000;
|
||||
const RULE_SUMMARY_FIELDS = ["id", "status", "strictness", "scope", "createdAt", "updatedAt"];
|
||||
const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
|
||||
const KNOWN_AREAS = new Set([
|
||||
"config",
|
||||
"service",
|
||||
"update",
|
||||
"tools",
|
||||
"corps",
|
||||
"tool",
|
||||
"source",
|
||||
"auth",
|
||||
"delegation",
|
||||
"users",
|
||||
"llm",
|
||||
"permissions",
|
||||
"billing",
|
||||
"webhook",
|
||||
"webhooks",
|
||||
"context",
|
||||
"rules",
|
||||
"approval-runs",
|
||||
"simulation"
|
||||
]);
|
||||
|
||||
type ParsedArgs = {
|
||||
command: string[];
|
||||
@@ -59,13 +87,50 @@ async function main() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!KNOWN_AREAS.has(area)) {
|
||||
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-home help' for available commands.`);
|
||||
}
|
||||
|
||||
if (area === "config" && action === "paths") {
|
||||
printJson({
|
||||
candidates: getEnterprisesDirCandidates()
|
||||
candidates: getEnterprisesDirCandidates(),
|
||||
globalConfigFile: resolveGlobalConfigFile()
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "config" && (action === "get" || action === "status")) {
|
||||
printJson(globalConfigSummary());
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "config" && action === "mode") {
|
||||
const mode = maybeName ?? stringOption(args.options.mode);
|
||||
if (!mode) {
|
||||
printJson(globalConfigSummary());
|
||||
return;
|
||||
}
|
||||
|
||||
const stateful = parseStateMode(mode);
|
||||
const requestedCorpId = stringOption(args.options.corp);
|
||||
const previousConfig = loadGlobalConfig();
|
||||
const defaultCorpId = stateful
|
||||
? requestedCorpId
|
||||
? resolveCorpConfig(
|
||||
loadCorpConfigs(),
|
||||
{ stateful: true, corpId: requestedCorpId },
|
||||
getEnterprisesDirCandidates()
|
||||
).id
|
||||
: previousConfig.defaultCorpId
|
||||
: undefined;
|
||||
const config = saveGlobalConfig({
|
||||
stateful,
|
||||
...(defaultCorpId ? { defaultCorpId } : {})
|
||||
});
|
||||
printJson(globalConfigSummary(config));
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "service") {
|
||||
await runServiceCommand(action, { appRoot: APP_ROOT, entryFile: fileURLToPath(import.meta.url), stateDir: STATE_DIR, version: VERSION });
|
||||
return;
|
||||
@@ -84,7 +149,12 @@ async function main() {
|
||||
if (area === "corps" && action === "list") {
|
||||
const corpId = stringOption(args.options.corp);
|
||||
const corps = loadCorpConfigs();
|
||||
const currentCorpId = corpId ?? readCurrentCorpId() ?? corps[0]?.id;
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const currentCorpId = corpId ?? (
|
||||
globalConfig.stateful
|
||||
? globalConfig.defaultCorpId ?? corps[0]?.id
|
||||
: undefined
|
||||
);
|
||||
printJson(corps.map((item) => ({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
@@ -96,7 +166,7 @@ async function main() {
|
||||
}
|
||||
|
||||
if (area === "corps" && action === "current") {
|
||||
const corp = selectCorp("");
|
||||
const corp = selectCorp(stringOption(args.options.corp));
|
||||
printJson({
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
@@ -109,9 +179,15 @@ async function main() {
|
||||
if (area === "corps" && action === "switch") {
|
||||
const corpId = maybeName;
|
||||
if (!corpId) throw new Error("Usage: seal-home corps switch <corpId>");
|
||||
const globalConfig = loadGlobalConfig();
|
||||
if (!globalConfig.stateful) {
|
||||
throw new Error(
|
||||
"Cannot switch the default enterprise while stateless mode is enabled. " +
|
||||
"Use `seal-home config mode stateful` first."
|
||||
);
|
||||
}
|
||||
const corp = selectCorp(corpId);
|
||||
ensureStateDir();
|
||||
writeFileSync(CURRENT_CORP_FILE, `${corp.id}\n`, { mode: 0o600 });
|
||||
saveGlobalConfig({ ...globalConfig, stateful: true, defaultCorpId: corp.id });
|
||||
printJson({
|
||||
current: true,
|
||||
id: corp.id,
|
||||
@@ -130,7 +206,7 @@ async function main() {
|
||||
return;
|
||||
}
|
||||
|
||||
const corp = selectCorp(String(args.options.corp ?? ""));
|
||||
const corp = selectCorp(stringOption(args.options.corp));
|
||||
|
||||
if (area === "source" && action === "config") {
|
||||
printJson(await resolveLiveSealEnterpriseConfig(corp));
|
||||
@@ -666,28 +742,36 @@ function outputOptions(options: Record<string, string | boolean>): OutputOptions
|
||||
};
|
||||
}
|
||||
|
||||
function selectCorp(corpId: string): CorpConfig {
|
||||
function selectCorp(corpId?: string): CorpConfig {
|
||||
const corps = loadCorpConfigs();
|
||||
const selectedCorpId = corpId || readCurrentCorpId() || "";
|
||||
const corp = selectedCorpId
|
||||
? corps.find((item) => item.id === selectedCorpId)
|
||||
: corps[0];
|
||||
|
||||
if (!corp) {
|
||||
throw new Error(
|
||||
selectedCorpId
|
||||
? `No enterprise config found for ${selectedCorpId}`
|
||||
: `No enterprise config found. Add a non-example JSON file under one of: ${getEnterprisesDirCandidates().join(", ")}`
|
||||
);
|
||||
}
|
||||
|
||||
return corp;
|
||||
const globalConfig = loadGlobalConfig();
|
||||
return resolveCorpConfig(
|
||||
corps,
|
||||
{
|
||||
stateful: globalConfig.stateful,
|
||||
defaultCorpId: globalConfig.defaultCorpId,
|
||||
corpId
|
||||
},
|
||||
getEnterprisesDirCandidates()
|
||||
);
|
||||
}
|
||||
|
||||
function readCurrentCorpId(): string | undefined {
|
||||
if (!existsSync(CURRENT_CORP_FILE)) return undefined;
|
||||
const value = readFileSync(CURRENT_CORP_FILE, "utf-8").trim();
|
||||
return value || undefined;
|
||||
function globalConfigSummary(config = loadGlobalConfig()) {
|
||||
return {
|
||||
mode: config.stateful ? "stateful" : "stateless",
|
||||
stateful: config.stateful,
|
||||
...(config.stateful && config.defaultCorpId
|
||||
? { defaultCorpId: config.defaultCorpId }
|
||||
: {}),
|
||||
configFile: resolveGlobalConfigFile()
|
||||
};
|
||||
}
|
||||
|
||||
function parseStateMode(value: string): boolean {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (["stateful", "state", "有状态"].includes(normalized)) return true;
|
||||
if (["stateless", "无状态"].includes(normalized)) return false;
|
||||
throw new Error("Invalid config mode. Use stateful or stateless.");
|
||||
}
|
||||
|
||||
async function addHoseCorp(input: Record<string, unknown>) {
|
||||
@@ -1321,10 +1405,6 @@ function booleanOption(value: string | boolean | undefined): boolean | undefined
|
||||
throw new Error(`Invalid boolean: ${value}`);
|
||||
}
|
||||
|
||||
function ensureStateDir() {
|
||||
mkdirSync(STATE_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function printJson(value: unknown, options: OutputOptions = {}) {
|
||||
protectLargeOutput(value, options);
|
||||
const json = `${JSON.stringify(value, null, 2)}\n`;
|
||||
@@ -1342,11 +1422,13 @@ function printHelp() {
|
||||
Usage:
|
||||
seal-home version
|
||||
seal-home config paths
|
||||
seal-home config get
|
||||
seal-home config mode <stateful|stateless> [--corp <corpId>]
|
||||
seal-home service <start|stop|restart|status>
|
||||
seal-home update
|
||||
seal-home tools list
|
||||
seal-home corps list [--corp <corpId>]
|
||||
seal-home corps current
|
||||
seal-home corps current [--corp <corpId>]
|
||||
seal-home corps switch <corpId>
|
||||
seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
|
||||
seal-home corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
|
||||
@@ -1380,23 +1462,23 @@ Usage:
|
||||
seal-home rules clear [--corp <corpId>] [--dry-run|--yes]
|
||||
seal-home rules versions [--corp <corpId>]
|
||||
seal-home rules version <versionId|versionNumber|latest> [--corp <corpId>]
|
||||
seal-home rules get --version <number|latest> --code '#0038'
|
||||
seal-home rules get --record-id <recordId> --runtime-id rule-205
|
||||
seal-home rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20]
|
||||
seal-home context [--ruleVersion <versionId|versionNumber|latest>] [--documentLimit 50]
|
||||
seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai]
|
||||
seal-home approval-runs search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true]
|
||||
seal-home approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision]
|
||||
seal-home approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json]
|
||||
seal-home approval-runs cited-rules <recordId>
|
||||
seal-home approval-runs document-summary <recordId>
|
||||
seal-home approval-runs attachments <recordId> [--summary]
|
||||
seal-home approval-runs result <recordId> [--summary]
|
||||
seal-home approval-runs url
|
||||
seal-home approval-runs url <recordId>
|
||||
seal-home approval-runs url --sourceDocumentSN B26022501
|
||||
seal-home approval-runs bridge [--sourceDocumentSN B26001887]
|
||||
seal-home simulation batch-records <batchId>
|
||||
seal-home rules get --corp <corpId> --version <number|latest> --code '#0038'
|
||||
seal-home rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205
|
||||
seal-home rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20] [--corp <corpId>]
|
||||
seal-home context [--ruleVersion <versionId|versionNumber|latest>] [--documentLimit 50] [--corp <corpId>]
|
||||
seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] [--corp <corpId>]
|
||||
seal-home approval-runs search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]
|
||||
seal-home approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
|
||||
seal-home approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]
|
||||
seal-home approval-runs cited-rules <recordId> [--corp <corpId>]
|
||||
seal-home approval-runs document-summary <recordId> [--corp <corpId>]
|
||||
seal-home approval-runs attachments <recordId> [--summary] [--corp <corpId>]
|
||||
seal-home approval-runs result <recordId> [--summary] [--corp <corpId>]
|
||||
seal-home approval-runs url [--corp <corpId>]
|
||||
seal-home approval-runs url <recordId> [--corp <corpId>]
|
||||
seal-home approval-runs url --sourceDocumentSN B26022501 [--corp <corpId>]
|
||||
seal-home approval-runs bridge [--sourceDocumentSN B26001887] [--corp <corpId>]
|
||||
seal-home simulation batch-records <batchId> [--corp <corpId>]
|
||||
`);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,17 @@ import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { loadCorpConfigs, resolveEnterprisesDir } from "./loader.js";
|
||||
import {
|
||||
loadCorpConfigs,
|
||||
loadGlobalConfig,
|
||||
resolveEnterprisesDir,
|
||||
resolveGlobalConfigFile,
|
||||
saveGlobalConfig
|
||||
} from "./loader.js";
|
||||
|
||||
const ORIGINAL_ENV = process.env.SEAL_HOME_ENTERPRISES_DIR;
|
||||
const ORIGINAL_USER_DIR_ENV = process.env.SEAL_HOME_USER_ENTERPRISES_DIR;
|
||||
const ORIGINAL_CONFIG_FILE_ENV = process.env.SEAL_HOME_CONFIG_FILE;
|
||||
const ORIGINAL_CWD = process.cwd();
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
@@ -21,6 +28,11 @@ afterEach(() => {
|
||||
} else {
|
||||
process.env.SEAL_HOME_USER_ENTERPRISES_DIR = ORIGINAL_USER_DIR_ENV;
|
||||
}
|
||||
if (ORIGINAL_CONFIG_FILE_ENV === undefined) {
|
||||
delete process.env.SEAL_HOME_CONFIG_FILE;
|
||||
} else {
|
||||
process.env.SEAL_HOME_CONFIG_FILE = ORIGINAL_CONFIG_FILE_ENV;
|
||||
}
|
||||
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
@@ -69,6 +81,24 @@ describe("loadCorpConfigs", () => {
|
||||
["user-only", "User Only"]
|
||||
]);
|
||||
});
|
||||
|
||||
test("defaults global config to stateless", () => {
|
||||
process.env.SEAL_HOME_CONFIG_FILE = join(makeTempDir(), "config.json");
|
||||
|
||||
expect(loadGlobalConfig()).toEqual({ stateful: false });
|
||||
});
|
||||
|
||||
test("saves and loads the global state mode", () => {
|
||||
const file = join(makeTempDir(), "nested", "config.json");
|
||||
process.env.SEAL_HOME_CONFIG_FILE = file;
|
||||
|
||||
expect(saveGlobalConfig({ stateful: true, defaultCorpId: "corp-a" })).toEqual({
|
||||
stateful: true,
|
||||
defaultCorpId: "corp-a"
|
||||
});
|
||||
expect(resolveGlobalConfigFile()).toBe(file);
|
||||
expect(loadGlobalConfig()).toEqual({ stateful: true, defaultCorpId: "corp-a" });
|
||||
});
|
||||
});
|
||||
|
||||
function makeTempDir(): string {
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { CorpConfig, CorpConfigSchema } from "./types.js";
|
||||
import { dirname, join } from "node:path";
|
||||
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
|
||||
|
||||
const ENTERPRISES_DIR = "enterprises";
|
||||
const CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR";
|
||||
const USER_DIR_ENV = "SEAL_HOME_USER_ENTERPRISES_DIR";
|
||||
const GLOBAL_CONFIG_ENV = "SEAL_HOME_CONFIG_FILE";
|
||||
const GLOBAL_CONFIG_FILE = join(homedir(), ".config", "seal-home", "config.json");
|
||||
export const USER_ENTERPRISES_DIR = join(homedir(), ".config", "seal-home", "enterprises");
|
||||
|
||||
export function loadCorpConfigs(): CorpConfig[] {
|
||||
@@ -56,3 +58,24 @@ export function getEnterprisesDirCandidates(): string[] {
|
||||
USER_ENTERPRISES_DIR
|
||||
];
|
||||
}
|
||||
|
||||
export function resolveGlobalConfigFile(): string {
|
||||
return process.env[GLOBAL_CONFIG_ENV]?.trim() || GLOBAL_CONFIG_FILE;
|
||||
}
|
||||
|
||||
export function loadGlobalConfig(): GlobalConfig {
|
||||
const file = resolveGlobalConfigFile();
|
||||
if (!existsSync(file)) {
|
||||
return GlobalConfigSchema.parse({});
|
||||
}
|
||||
|
||||
return GlobalConfigSchema.parse(JSON.parse(readFileSync(file, "utf-8")));
|
||||
}
|
||||
|
||||
export function saveGlobalConfig(config: GlobalConfig): GlobalConfig {
|
||||
const normalized = GlobalConfigSchema.parse(config);
|
||||
const file = resolveGlobalConfigFile();
|
||||
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(file, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 });
|
||||
return normalized;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { CorpConfig } from "./types.js";
|
||||
import { CorpContext } from "./manager.js";
|
||||
import { CorpContext, resolveCorpConfig } from "./manager.js";
|
||||
|
||||
function corp(id: string, name = id): CorpConfig {
|
||||
return {
|
||||
@@ -26,7 +26,7 @@ function corp(id: string, name = id): CorpConfig {
|
||||
|
||||
describe("CorpContext", () => {
|
||||
test("refresh adds newly loaded corps", () => {
|
||||
const context = new CorpContext([corp("corp-a")]);
|
||||
const context = new CorpContext([corp("corp-a")], { stateful: true });
|
||||
|
||||
context.refresh([corp("corp-a"), corp("corp-b")]);
|
||||
|
||||
@@ -34,7 +34,7 @@ describe("CorpContext", () => {
|
||||
});
|
||||
|
||||
test("refresh keeps the selected corp when it still exists", () => {
|
||||
const context = new CorpContext([corp("corp-a"), corp("corp-b")]);
|
||||
const context = new CorpContext([corp("corp-a"), corp("corp-b")], { stateful: true });
|
||||
expect(context.switchCorp("corp-b")).toBe(true);
|
||||
|
||||
context.refresh([corp("corp-a"), corp("corp-b", "Corp B updated")]);
|
||||
@@ -43,12 +43,51 @@ describe("CorpContext", () => {
|
||||
expect(context.getCurrent()?.name).toBe("Corp B updated");
|
||||
});
|
||||
|
||||
test("refresh falls back when the selected corp disappears", () => {
|
||||
const context = new CorpContext([corp("corp-a"), corp("corp-b")]);
|
||||
test("clears the default when the selected corp disappears", () => {
|
||||
const context = new CorpContext([corp("corp-a"), corp("corp-b")], { stateful: true });
|
||||
expect(context.switchCorp("corp-b")).toBe(true);
|
||||
|
||||
context.refresh([corp("corp-c")]);
|
||||
|
||||
expect(context.getCurrent()?.id).toBe("corp-c");
|
||||
expect(context.getCurrent()).toBeNull();
|
||||
});
|
||||
|
||||
test("does not keep a current corp in stateless mode", () => {
|
||||
const context = new CorpContext([corp("corp-a"), corp("corp-b")]);
|
||||
|
||||
expect(context.getCurrent()).toBeNull();
|
||||
expect(context.switchCorp("corp-b")).toBe(false);
|
||||
expect(context.resolve("corp-b")?.id).toBe("corp-b");
|
||||
});
|
||||
|
||||
test("uses the configured default corp in stateful mode", () => {
|
||||
const context = new CorpContext(
|
||||
[corp("corp-a"), corp("corp-b")],
|
||||
{ stateful: true, defaultCorpId: "corp-b" }
|
||||
);
|
||||
|
||||
expect(context.getCurrent()?.id).toBe("corp-b");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveCorpConfig", () => {
|
||||
test("requires an explicit corp in stateless mode", () => {
|
||||
expect(() => resolveCorpConfig([corp("corp-a")], { stateful: false })).toThrow(
|
||||
"Every enterprise command requires --corp <corpId>"
|
||||
);
|
||||
});
|
||||
|
||||
test("resolves an explicit corp in stateless mode", () => {
|
||||
expect(resolveCorpConfig(
|
||||
[corp("corp-a"), corp("corp-b")],
|
||||
{ stateful: false, corpId: "corp-b" }
|
||||
).id).toBe("corp-b");
|
||||
});
|
||||
|
||||
test("resolves the configured default corp in stateful mode", () => {
|
||||
expect(resolveCorpConfig(
|
||||
[corp("corp-a"), corp("corp-b")],
|
||||
{ stateful: true, defaultCorpId: "corp-b" }
|
||||
).id).toBe("corp-b");
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,62 @@
|
||||
import { CorpConfig } from "./types.js";
|
||||
import { CorpConfig, GlobalConfig } from "./types.js";
|
||||
|
||||
export function resolveCorpConfig(
|
||||
corps: CorpConfig[],
|
||||
options: Pick<GlobalConfig, "stateful" | "defaultCorpId"> & { corpId?: string },
|
||||
candidates: 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(`No enterprise config found for ${selectedCorpId}`);
|
||||
}
|
||||
|
||||
if (!options.stateful) {
|
||||
throw new Error(
|
||||
"Stateless mode is enabled. Every enterprise command requires --corp <corpId>. " +
|
||||
"Use `seal-home config mode stateful` to enable a default enterprise."
|
||||
);
|
||||
}
|
||||
|
||||
const firstCorp = corps[0];
|
||||
if (firstCorp) return firstCorp;
|
||||
|
||||
throw new Error(
|
||||
"No enterprise config found. Add a non-example JSON file under one of: " +
|
||||
(candidates.length ? candidates.join(", ") : "the configured enterprise directories")
|
||||
);
|
||||
}
|
||||
|
||||
export type CorpContextOptions = Pick<GlobalConfig, "stateful" | "defaultCorpId">;
|
||||
|
||||
export class CorpContext {
|
||||
private current: CorpConfig | null = null;
|
||||
private corps = new Map<string, CorpConfig>();
|
||||
private stateful = false;
|
||||
private defaultCorpId: string | undefined;
|
||||
|
||||
constructor(corps: CorpConfig[]) {
|
||||
constructor(corps: CorpConfig[], options: CorpContextOptions = { stateful: false }) {
|
||||
this.stateful = options.stateful;
|
||||
this.defaultCorpId = options.defaultCorpId;
|
||||
this.replaceCorps(corps);
|
||||
this.current = corps[0] ?? null;
|
||||
this.selectCurrent(corps[0]);
|
||||
}
|
||||
|
||||
refresh(corps: CorpConfig[]): void {
|
||||
const currentId = this.current?.id ?? null;
|
||||
refresh(corps: CorpConfig[], options: CorpContextOptions = {
|
||||
stateful: this.stateful,
|
||||
defaultCorpId: this.defaultCorpId
|
||||
}): void {
|
||||
const currentId = this.current?.id;
|
||||
this.stateful = options.stateful;
|
||||
this.defaultCorpId = options.defaultCorpId;
|
||||
this.replaceCorps(corps);
|
||||
this.current = currentId ? this.corps.get(currentId) ?? null : null;
|
||||
this.current ??= corps[0] ?? null;
|
||||
this.selectCurrent(currentId ? this.corps.get(currentId) ?? corps[0] : corps[0]);
|
||||
}
|
||||
|
||||
private replaceCorps(corps: CorpConfig[]): void {
|
||||
@@ -27,10 +70,21 @@ export class CorpContext {
|
||||
return this.current;
|
||||
}
|
||||
|
||||
getCorp(corpId: string): CorpConfig | null {
|
||||
return this.corps.get(corpId) ?? null;
|
||||
}
|
||||
|
||||
resolve(corpId?: string): CorpConfig | null {
|
||||
if (corpId) return this.getCorp(corpId);
|
||||
return this.current;
|
||||
}
|
||||
|
||||
switchCorp(corpId: string): boolean {
|
||||
if (!this.stateful) return false;
|
||||
const corp = this.corps.get(corpId);
|
||||
if (!corp) return false;
|
||||
this.current = corp;
|
||||
this.defaultCorpId = corp.id;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -42,4 +96,15 @@ export class CorpContext {
|
||||
current: corp.id === this.current?.id
|
||||
}));
|
||||
}
|
||||
|
||||
private selectCurrent(fallback?: CorpConfig): void {
|
||||
if (!this.stateful) {
|
||||
this.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
this.current = this.defaultCorpId !== undefined
|
||||
? this.corps.get(this.defaultCorpId) ?? null
|
||||
: fallback ?? null;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { CorpConfigSchema } from "./types.js";
|
||||
import { CorpConfigSchema, GlobalConfigSchema } from "./types.js";
|
||||
|
||||
describe("CorpConfigSchema", () => {
|
||||
test("accepts Hose key/password aliases", () => {
|
||||
@@ -79,3 +79,19 @@ describe("CorpConfigSchema", () => {
|
||||
expect(config.source.tenantSlug).toBe("xiezihao");
|
||||
});
|
||||
});
|
||||
|
||||
describe("GlobalConfigSchema", () => {
|
||||
test("defaults to stateless mode", () => {
|
||||
expect(GlobalConfigSchema.parse({})).toEqual({ stateful: false });
|
||||
});
|
||||
|
||||
test("accepts a stateful default enterprise", () => {
|
||||
expect(GlobalConfigSchema.parse({
|
||||
stateful: true,
|
||||
defaultCorpId: "corp-a"
|
||||
})).toEqual({
|
||||
stateful: true,
|
||||
defaultCorpId: "corp-a"
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -84,9 +84,15 @@ export const CorpConfigSchema = z.object({
|
||||
auth: CorpAuthConfigSchema
|
||||
});
|
||||
|
||||
export const GlobalConfigSchema = z.object({
|
||||
stateful: z.boolean().default(false),
|
||||
defaultCorpId: z.string().min(1).optional()
|
||||
});
|
||||
|
||||
export type HoseSealSource = z.infer<typeof HoseSealSourceSchema>;
|
||||
export type DirectSealSource = z.infer<typeof DirectSealSourceSchema>;
|
||||
export type NativeSealSource = z.infer<typeof NativeSealSourceSchema>;
|
||||
export type SealSource = z.infer<typeof SealSourceSchema>;
|
||||
export type CorpAuthConfig = z.infer<typeof CorpAuthConfigSchema>;
|
||||
export type CorpConfig = z.infer<typeof CorpConfigSchema>;
|
||||
export type GlobalConfig = z.infer<typeof GlobalConfigSchema>;
|
||||
+13
-12
@@ -1,22 +1,23 @@
|
||||
import { getEnterprisesDirCandidates, loadCorpConfigs } from "./core/config/loader.js";
|
||||
import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from "./core/config/loader.js";
|
||||
import { resolveCorpConfig } from "./core/config/manager.js";
|
||||
import { createSealClient } from "./core/http/factory.js";
|
||||
import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js";
|
||||
import { getApprovalContext } from "./domains/seal/api.js";
|
||||
|
||||
async function main() {
|
||||
const corpId = Bun.argv[2];
|
||||
const args = Bun.argv.slice(2);
|
||||
const corpId = args[0] === "--corp" ? args[1] : args[0];
|
||||
const corps = loadCorpConfigs();
|
||||
const corp = corpId
|
||||
? corps.find((item) => item.id === corpId)
|
||||
: corps[0];
|
||||
|
||||
if (!corp) {
|
||||
throw new Error(
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const corp = resolveCorpConfig(
|
||||
corps,
|
||||
{
|
||||
stateful: globalConfig.stateful,
|
||||
defaultCorpId: globalConfig.defaultCorpId,
|
||||
corpId
|
||||
? `No enterprise config found for ${corpId}`
|
||||
: `No enterprise config found. Add a config file under one of: ${getEnterprisesDirCandidates().join(", ")}`
|
||||
);
|
||||
}
|
||||
},
|
||||
getEnterprisesDirCandidates()
|
||||
);
|
||||
|
||||
console.log(`[probe] corp=${corp.id} source=${corp.source.type}`);
|
||||
|
||||
|
||||
+55
-7
@@ -5,7 +5,12 @@ import {
|
||||
ListToolsRequestSchema
|
||||
} from "@modelcontextprotocol/sdk/types.js";
|
||||
import { z } from "zod";
|
||||
import { getEnterprisesDirCandidates, loadCorpConfigs } from "./core/config/loader.js";
|
||||
import {
|
||||
getEnterprisesDirCandidates,
|
||||
loadCorpConfigs,
|
||||
loadGlobalConfig,
|
||||
saveGlobalConfig
|
||||
} from "./core/config/loader.js";
|
||||
import { CorpContext } from "./core/config/manager.js";
|
||||
import { createSealClient } from "./core/http/factory.js";
|
||||
import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js";
|
||||
@@ -14,7 +19,7 @@ import { VERSION } from "./version.js";
|
||||
|
||||
async function main() {
|
||||
const corps = loadCorpConfigs();
|
||||
const corpContext = new CorpContext(corps);
|
||||
const corpContext = new CorpContext(corps, loadGlobalConfig());
|
||||
|
||||
const server = new Server(
|
||||
{
|
||||
@@ -52,14 +57,15 @@ async function main() {
|
||||
...sealMcpTools.map((tool) => ({
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
inputSchema: z.toJSONSchema(tool.parameters)
|
||||
inputSchema: mcpInputSchema(tool.parameters, loadGlobalConfig().stateful)
|
||||
}))
|
||||
]
|
||||
}));
|
||||
|
||||
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||
const { name, arguments: args } = request.params;
|
||||
corpContext.refresh(loadCorpConfigs());
|
||||
const globalConfig = loadGlobalConfig();
|
||||
corpContext.refresh(loadCorpConfigs(), globalConfig);
|
||||
|
||||
if (name === "seal_corps_list") {
|
||||
return textResult(corpContext.listCorps());
|
||||
@@ -67,19 +73,33 @@ async function main() {
|
||||
|
||||
if (name === "seal_corp_switch") {
|
||||
const { corpId } = args as { corpId: string };
|
||||
if (!globalConfig.stateful) {
|
||||
return textResult({
|
||||
success: false,
|
||||
message: "Cannot switch the default enterprise while stateless mode is enabled. " +
|
||||
"Set config mode to stateful first."
|
||||
}, true);
|
||||
}
|
||||
const success = corpContext.switchCorp(corpId);
|
||||
if (success) {
|
||||
saveGlobalConfig({ ...globalConfig, stateful: true, defaultCorpId: corpId });
|
||||
}
|
||||
return textResult(
|
||||
success ? { success: true, current: corpId } : { success: false, message: `Unknown corp: ${corpId}` },
|
||||
!success
|
||||
);
|
||||
}
|
||||
|
||||
const currentCorp = corpContext.getCurrent();
|
||||
const requestedCorpId = getCorpId(args);
|
||||
const currentCorp = corpContext.resolve(requestedCorpId);
|
||||
if (!currentCorp) {
|
||||
return textResult(
|
||||
{
|
||||
error:
|
||||
"No enterprise config loaded. Add a non-example JSON file to an enterprises config directory.",
|
||||
error: requestedCorpId
|
||||
? `No enterprise config found for ${requestedCorpId}`
|
||||
: globalConfig.stateful
|
||||
? "No enterprise config loaded. Add a non-example JSON file to an enterprises config directory."
|
||||
: "Stateless mode is enabled. Every enterprise tool call requires corpId.",
|
||||
candidates: getEnterprisesDirCandidates()
|
||||
},
|
||||
true
|
||||
@@ -123,6 +143,34 @@ function textResult(value: unknown, isError = false) {
|
||||
};
|
||||
}
|
||||
|
||||
function getCorpId(args: unknown): string | undefined {
|
||||
if (!args || typeof args !== "object" || Array.isArray(args)) return undefined;
|
||||
const value = (args as Record<string, unknown>).corpId;
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function mcpInputSchema(parameters: z.ZodType, stateful: boolean) {
|
||||
const schema = z.toJSONSchema(parameters) as {
|
||||
type?: string;
|
||||
properties?: Record<string, unknown>;
|
||||
required?: string[];
|
||||
};
|
||||
schema.type = "object";
|
||||
schema.properties = {
|
||||
...(schema.properties ?? {}),
|
||||
corpId: {
|
||||
type: "string",
|
||||
description: stateful
|
||||
? "可选:企业配置 ID;省略时使用当前默认企业"
|
||||
: "必填:企业配置 ID"
|
||||
}
|
||||
};
|
||||
if (!stateful) {
|
||||
schema.required = [...(schema.required ?? []), "corpId"];
|
||||
}
|
||||
return schema;
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
|
||||
Reference in new issue
Block a user