Support global CLI service workflow

This commit is contained in:
gitea committed 2026-06-09 12:09:03 +08:00
1 parent aa6f6321e5
commit 0dce586266
8 files changed
+410 -102

No files matched your search

+189 -2
View File
@@ -1,12 +1,21 @@
#!/usr/bin/env bun
import { loadCorpConfigs } from "./core/config/loader.js";
import { spawn, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { getEnterprisesDirCandidates, loadCorpConfigs } from "./core/config/loader.js";
import { createSealClient } from "./core/http/factory.js";
import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js";
import { sealTools, type SealTool } from "./domains/seal/tools.js";
import { CorpConfig } from "./core/config/types.js";
const VERSION = "0.3.0";
const APP_ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
const STATE_DIR = join(homedir(), ".config", "seal-home");
const SERVICE_PID_FILE = join(STATE_DIR, "service.pid");
const SERVICE_LOG_FILE = join(STATE_DIR, "service.log");
type ParsedArgs = {
command: string[];
@@ -31,6 +40,23 @@ async function main() {
return;
}
if (area === "config" && action === "paths") {
printJson({
candidates: getEnterprisesDirCandidates()
});
return;
}
if (area === "service") {
await runServiceCommand(action);
return;
}
if (area === "update") {
updateAndRestart();
return;
}
if (area === "tools" && action === "list") {
printJson(sealTools.map((tool) => ({ name: tool.name, description: tool.description })));
return;
@@ -116,6 +142,140 @@ async function main() {
throw new Error(`Unknown command: ${args.command.join(" ")}`);
}
async function runServiceCommand(action?: string) {
switch (action) {
case "run":
await runService();
return;
case "start":
startService();
return;
case "stop":
stopService();
return;
case "restart":
stopService({ quiet: true });
startService();
return;
case "status":
case undefined:
printJson(serviceStatus());
return;
default:
throw new Error("Usage: seal-home service <start|stop|restart|status>");
}
}
async function runService() {
ensureStateDir();
writeFileSync(SERVICE_PID_FILE, `${process.pid}\n`);
appendLog(`running pid=${process.pid}`);
const cleanup = () => {
if (readServicePid() === process.pid) {
rmSync(SERVICE_PID_FILE, { force: true });
}
appendLog(`stopped pid=${process.pid}`);
};
process.on("SIGTERM", () => {
cleanup();
process.exit(0);
});
process.on("SIGINT", () => {
cleanup();
process.exit(0);
});
setInterval(() => {
// Keep the process alive for warmed auth/search caches in this runtime.
}, 60_000);
await new Promise(() => {});
}
function startService() {
ensureStateDir();
const current = serviceStatus();
if (current.running) {
printJson(current);
return;
}
const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "service", "run"], {
cwd: APP_ROOT,
detached: true,
stdio: ["ignore", "ignore", "ignore"],
env: process.env
});
child.unref();
writeFileSync(SERVICE_PID_FILE, `${child.pid}\n`);
appendLog(`started pid=${child.pid}`);
printJson({
started: true,
...serviceStatus()
});
}
function stopService(options: { quiet?: boolean } = {}) {
const pid = readServicePid();
if (!pid) {
if (!options.quiet) printJson({ stopped: false, reason: "not running" });
return;
}
if (isProcessRunning(pid)) {
process.kill(pid, "SIGTERM");
}
rmSync(SERVICE_PID_FILE, { force: true });
appendLog(`stop requested pid=${pid}`);
if (!options.quiet) {
printJson({ stopped: true, pid });
}
}
function serviceStatus() {
const pid = readServicePid();
return {
running: pid ? isProcessRunning(pid) : false,
pid,
version: VERSION,
appRoot: APP_ROOT,
stateDir: STATE_DIR,
pidFile: SERVICE_PID_FILE,
logFile: SERVICE_LOG_FILE
};
}
function updateAndRestart() {
const wasRunning = serviceStatus().running;
if (wasRunning) stopService({ quiet: true });
runCommand("git", ["-C", APP_ROOT, "pull", "--ff-only"]);
runCommand("bun", ["install"], { cwd: APP_ROOT });
if (wasRunning) startService();
printJson({
updated: true,
serviceRestarted: wasRunning,
version: VERSION
});
}
function runCommand(command: string, args: string[], options: { cwd?: string } = {}) {
const result = spawnSync(command, args, {
cwd: options.cwd,
stdio: "inherit"
});
if (result.status !== 0) {
throw new Error(`${command} ${args.join(" ")} failed with status ${result.status}`);
}
}
async function runTool(
name: string,
client: Awaited<ReturnType<typeof createSealClient>>,
@@ -143,7 +303,7 @@ function selectCorp(corpId: string): CorpConfig {
throw new Error(
corpId
? `No enterprise config found for ${corpId}`
: "No enterprise config found. Add a non-example JSON file under enterprises/."
: `No enterprise config found. Add a non-example JSON file under one of: ${getEnterprisesDirCandidates().join(", ")}`
);
}
@@ -212,6 +372,30 @@ function booleanOption(value: string | boolean | undefined): boolean | undefined
throw new Error(`Invalid boolean: ${value}`);
}
function ensureStateDir() {
mkdirSync(STATE_DIR, { recursive: true });
}
function readServicePid(): number | undefined {
if (!existsSync(SERVICE_PID_FILE)) return undefined;
const pid = Number(readFileSync(SERVICE_PID_FILE, "utf-8").trim());
return Number.isInteger(pid) && pid > 0 ? pid : undefined;
}
function isProcessRunning(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function appendLog(message: string) {
ensureStateDir();
writeFileSync(SERVICE_LOG_FILE, `${new Date().toISOString()} ${message}\n`, { flag: "a" });
}
function printJson(value: unknown) {
console.log(JSON.stringify(value, null, 2));
}
@@ -221,6 +405,9 @@ function printHelp() {
Usage:
seal-home version
seal-home config paths
seal-home service <start|stop|restart|status>
seal-home update
seal-home tools list
seal-home corps list [--corp <corpId>]
seal-home source config [--corp <corpId>]
+54
View File
@@ -0,0 +1,54 @@
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";
const ORIGINAL_ENV = process.env.SEAL_HOME_ENTERPRISES_DIR;
const tempDirs: string[] = [];
afterEach(() => {
if (ORIGINAL_ENV === undefined) {
delete process.env.SEAL_HOME_ENTERPRISES_DIR;
} else {
process.env.SEAL_HOME_ENTERPRISES_DIR = ORIGINAL_ENV;
}
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("loadCorpConfigs", () => {
test("loads configs from SEAL_HOME_ENTERPRISES_DIR", () => {
const dir = makeTempDir();
writeFileSync(join(dir, "example.hose.json"), "{}");
writeFileSync(join(dir, "local.json"), JSON.stringify({
id: "direct",
name: "Direct",
source: {
type: "direct",
token: "seal-token",
sealUrl: "https://direct.sealai.cc"
}
}));
process.env.SEAL_HOME_ENTERPRISES_DIR = dir;
expect(resolveEnterprisesDir()).toBe(dir);
expect(loadCorpConfigs().map((corp) => corp.id)).toEqual(["direct"]);
});
test("returns no configs when explicit env directory does not exist", () => {
process.env.SEAL_HOME_ENTERPRISES_DIR = join(makeTempDir(), "missing");
expect(resolveEnterprisesDir()).toBeUndefined();
expect(loadCorpConfigs()).toEqual([]);
});
});
function makeTempDir(): string {
const dir = mkdtempSync(join(tmpdir(), "seal-home-loader-"));
mkdirSync(dir, { recursive: true });
tempDirs.push(dir);
return dir;
}
+24 -3
View File
@@ -1,19 +1,40 @@
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { CorpConfig, CorpConfigSchema } from "./types.js";
const ENTERPRISES_DIR = "enterprises";
const CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR";
export function loadCorpConfigs(): CorpConfig[] {
if (!existsSync(ENTERPRISES_DIR)) {
const dir = resolveEnterprisesDir();
if (!dir) {
return [];
}
return readdirSync(ENTERPRISES_DIR)
return readdirSync(dir)
.filter((file) => file.endsWith(".json"))
.filter((file) => !file.startsWith("example."))
.map((file) => {
const content = readFileSync(join(ENTERPRISES_DIR, file), "utf-8");
const content = readFileSync(join(dir, file), "utf-8");
return CorpConfigSchema.parse(JSON.parse(content));
});
}
export function resolveEnterprisesDir(): string | undefined {
const configured = process.env[CONFIG_ENV]?.trim();
if (configured) return existsSync(configured) ? configured : undefined;
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
const userConfigDir = join(homedir(), ".config", "seal-home", "enterprises");
return existsSync(userConfigDir) ? userConfigDir : undefined;
}
export function getEnterprisesDirCandidates(): string[] {
return [
`${CONFIG_ENV}=<path>`,
ENTERPRISES_DIR,
join(homedir(), ".config", "seal-home", "enterprises")
];
}
+2 -2
View File
@@ -1,4 +1,4 @@
import { loadCorpConfigs } from "./core/config/loader.js";
import { getEnterprisesDirCandidates, loadCorpConfigs } from "./core/config/loader.js";
import { createSealClient } from "./core/http/factory.js";
import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js";
import { getApprovalContext } from "./domains/seal/api.js";
@@ -14,7 +14,7 @@ async function main() {
throw new Error(
corpId
? `No enterprise config found for ${corpId}`
: "No enterprise config found. Add enterprises/local.json first."
: `No enterprise config found. Add a config file under one of: ${getEnterprisesDirCandidates().join(", ")}`
);
}
+3 -2
View File
@@ -5,7 +5,7 @@ import {
ListToolsRequestSchema
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import { loadCorpConfigs } from "./core/config/loader.js";
import { getEnterprisesDirCandidates, loadCorpConfigs } 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";
@@ -70,7 +70,8 @@ async function main() {
return textResult(
{
error:
"No enterprise config loaded. Add a non-example JSON file under enterprises/."
"No enterprise config loaded. Add a non-example JSON file to an enterprises config directory.",
candidates: getEnterprisesDirCandidates()
},
true
);