diff --git a/README.md b/README.md index 4130b29..927e606 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Version: `0.3.0` -Bun + TypeScript MCP server for pulling Seal enterprise approval context from provider credentials. +Bun + TypeScript CLI and optional local service for pulling Seal enterprise approval context from provider credentials. The first provider is Hose/合思: `key`, `password`, `corpId`, `staffId`, and an optional Hose domain. The provider exchanges those credentials for a Seal enterprise session, then the Seal domain tools can read and maintain approval rules, approval documents, and approval style preferences. @@ -22,27 +22,38 @@ For an already-authenticated Seal source, copy `enterprises/example.direct.json` ## Public Usage -This repository is intended to be published as a local agent toolkit. Users run the CLI and MCP server on their own machine with their own enterprise credentials; do not deploy the stdio MCP server as a shared public service without adding authentication, tenant isolation, credential storage, audit logging, and write-operation controls. +This repository is intended to be published as a macOS local agent toolkit. Users run the global `seal-home` CLI on their own machine with their own enterprise credentials. Do not deploy it as a shared public service without adding authentication, tenant isolation, credential storage, audit logging, and write-operation controls. + +Install the global CLI from a checkout: ```bash git clone cd seal-home bun install -cp enterprises/example.hose.json enterprises/local.json -# Edit enterprises/local.json with your own Hose/Seal credentials. -bun run cli -- source config -bun run cli -- tools list +bun link +seal-home version ``` +Create a user-level enterprise config that works from any directory: + +```bash +mkdir -p ~/.config/seal-home/enterprises +cp enterprises/example.hose.json ~/.config/seal-home/enterprises/local.json +# Edit ~/.config/seal-home/enterprises/local.json with your own Hose/Seal credentials. +seal-home source config +seal-home tools list +``` + +For custom config locations, set `SEAL_HOME_ENTERPRISES_DIR` to a directory containing non-example `*.json` enterprise config files. + Update an existing checkout: ```bash -git pull -bun install -bun run cli -- version -bun run cli -- tools list +seal-home update ``` +`seal-home update` runs `git pull --ff-only`, installs dependencies, and restarts the local service if it was running. + Local enterprise config files are ignored by git: ```text @@ -54,17 +65,43 @@ The standard Codex skill lives at `skills/seal-home`. Install or copy that folde ## CLI -The MCP server and CLI are separate entry points. Use MCP for protocol-native clients; use the CLI from skills, shell scripts, or agents that prefer command execution. CLI intentionally keeps the full fine-grained tool list available through `seal-home tool `; only the MCP exported tool surface is narrowed for model context size. +Use the CLI from skills, shell scripts, or agents. CLI intentionally keeps the full fine-grained tool list available through `seal-home tool `. ```bash -bun run cli -- tools list -bun run cli -- corps list -bun run cli -- approval-runs summary --date 2026-06-08 --timezone Asia/Shanghai -bun run cli -- tool seal_approval_runs_summary --json '{"date":"2026-06-08","timezone":"Asia/Shanghai"}' +seal-home version +seal-home config paths +seal-home tools list +seal-home corps list +seal-home approval-runs summary --date 2026-06-08 --timezone Asia/Shanghai +seal-home tool seal_approval_runs_summary --json '{"date":"2026-06-08","timezone":"Asia/Shanghai"}' ``` CLI output is JSON on stdout. Errors are written to stderr. +Enterprise config lookup order: + +1. `SEAL_HOME_ENTERPRISES_DIR` +2. `./enterprises` in the current working directory +3. `~/.config/seal-home/enterprises` + +## Local Service + +For macOS users who want a long-lived local background process and a simple restart point after updates: + +```bash +seal-home service start +seal-home service status +seal-home service restart +seal-home service stop +``` + +Service state is stored under `~/.config/seal-home/`: + +- `service.pid` +- `service.log` + +The service is intentionally local. It is useful as a stable process lifecycle for future warmed caches and update/restart workflows; normal CLI commands still work without it. + ## Enterprise Config ```json @@ -91,7 +128,11 @@ CLI output is JSON on stdout. Errors are written to stderr. } ``` -## MCP Tools +## Developer MCP Notes + +Most users do not need MCP. The public/shared path is the global `seal-home` CLI plus the optional local service. + +For protocol-native development clients, the MCP server intentionally keeps a narrow exported surface: - `seal_corp_switch`: switch the active local enterprise config. - `seal_whoami`: current Seal user and tenant. @@ -111,12 +152,12 @@ CLI output is JSON on stdout. Errors are written to stderr. } ``` -## CLI/Internal Tools +## CLI Tools -These tools remain available to the CLI and are also accepted by the MCP call handler for compatibility, but most are no longer advertised by MCP `tools/list`: +These tools remain available to the CLI: - `seal_source_config`: resolve current Seal enterprise config from the configured source. -- `seal_approval_runs_search`: full internal name behind the MCP `seal_runs_search` alias. +- `seal_approval_runs_search`: search approval run history and optional bridge rows. - `seal_session_get`: current Seal Bearer session and expiration. - `seal_approval_rules_list`: current draft approval rules. - `seal_approval_rule_create`, `seal_approval_rule_update`, `seal_approval_rule_delete`: maintain approval rules. @@ -148,10 +189,10 @@ When `_langfuseTraceId` exists, downstream tools should fetch the trace directly ## Engineering Notes -- Prefer Bun-native commands in this repository: `bun run check`, `bun test`, and `bun run cli -- ...`. `npm run check` may work, but Bun is the project runtime and lockfile owner. -- Keep MCP and CLI as thin entry points. Shared behavior belongs in `src/core` and `src/domains`; `src/server.ts` should only handle MCP protocol concerns, and `src/cli.ts` should only handle command parsing and JSON output. +- Prefer Bun-native commands in this repository: `bun run check`, `bun test`, and `seal-home ...`. `npm run check` may work, but Bun is the project runtime and lockfile owner. +- Keep CLI entry points thin. Shared behavior belongs in `src/core` and `src/domains`; `src/cli.ts` should only handle command parsing, process lifecycle, and JSON output. - Do not print diagnostic text to stdout from the MCP server. MCP uses stdout as the protocol stream; use stderr for server diagnostics. -- Keep the MCP exported surface narrow. High-frequency read tools can be direct MCP tools; low-frequency maintenance should go through `seal_action` or CLI commands. -- Prefer CLI or script processing for large tool responses. For daily approval questions, call `seal_action` with `runs.summary` or `bun run cli -- approval-runs summary ...` instead of reading long `seal_approval_runs_search` output manually. +- Keep any MCP exported surface narrow. High-frequency read tools can be direct MCP tools; low-frequency maintenance should go through `seal_action` or CLI commands. +- Prefer CLI or script processing for large tool responses. For daily approval questions, call `seal-home approval-runs summary ...` instead of reading long `seal_approval_runs_search` output manually. - Keep broad search tools compact by default. Add explicit opt-in flags such as `includeBridge` for verbose fields that are useful only in deeper debugging. - When Seal API timestamp filters are uncertain, filter again in tool code by `createdAt` and explicit timezone before presenting date-based answers. diff --git a/skills/seal-home/SKILL.md b/skills/seal-home/SKILL.md index c4abd5b..d7cd54a 100644 --- a/skills/seal-home/SKILL.md +++ b/skills/seal-home/SKILL.md @@ -1,32 +1,46 @@ --- name: seal-home -description: Use when working with Seal Home / seal-home approval automation: querying Seal enterprise identity, approval rules, approval knowledge documents, approval style preferences, approval run history, simulation batch records, and Langfuse trace/session bridge hints. Prefer this skill when the user mentions Seal, seal_home MCP, 合思/易快报 approval runs, approval rule/document maintenance, approval simulations, or debugging Seal approval execution traces. +description: Use when working with the Seal Home / seal-home CLI and local service for approval automation: querying Seal enterprise identity, approval rules, approval knowledge documents, approval style preferences, approval run history, simulation batch records, and Langfuse trace/session bridge hints. Prefer this skill when the user mentions Seal, seal-home, 合思/易快报 approval runs, approval rule/document maintenance, approval simulations, updating/restarting the seal-home service, or debugging Seal approval execution traces. --- # Seal Home ## Quick Start -Run commands from the seal-home repository root: +Use the global `seal-home` CLI. It should work from any directory after installation: ```bash -bun run cli -- help -bun run cli -- version -bun run cli -- tools list +seal-home help +seal-home version +seal-home tools list ``` -Use CLI for broad or detailed operations. Use MCP for narrow, high-frequency agent entry points only. The CLI intentionally exposes the full fine-grained tool list; MCP intentionally advertises a small surface to reduce model context. +Use CLI for broad or detailed operations. The CLI intentionally exposes the full fine-grained tool list and is the primary interface for shared/public use. + +Enterprise configs are loaded from `SEAL_HOME_ENTERPRISES_DIR`, `./enterprises`, or `~/.config/seal-home/enterprises`, in that order. Prefer user-level config for shared/public installs so commands do not depend on the repository working directory. + +Optional local service commands: + +```bash +seal-home service start +seal-home service status +seal-home service restart +seal-home service stop +seal-home update +``` + +Use `seal-home update` after pulling new versions; it restarts the service if it was running so new code is picked up. ## Decision Guide -- For current identity or tenant: use `bun run cli -- tool seal_whoami`. -- For configured enterprises: use `bun run cli -- corps list`. -- For source-derived enterprise config: use `bun run cli -- source config`. -- For daily approval run questions: use `bun run cli -- approval-runs summary --date YYYY-MM-DD --timezone Asia/Shanghai`. -- For approval run lookup by document SN, ID, status, mode, or trace: use `bun run cli -- approval-runs search`. -- For Langfuse lookup hints: use `bun run cli -- approval-runs bridge`. -- For one simulation batch: use `bun run cli -- simulation batch-records `. -- For approval rule/document/style maintenance: use `bun run cli -- tool --json '{...}'`. +- For current identity or tenant: use `seal-home tool seal_whoami`. +- For configured enterprises: use `seal-home corps list`. +- For source-derived enterprise config: use `seal-home source config`. +- For daily approval run questions: use `seal-home approval-runs summary --date YYYY-MM-DD --timezone Asia/Shanghai`. +- For approval run lookup by document SN, ID, status, mode, or trace: use `seal-home approval-runs search`. +- For Langfuse lookup hints: use `seal-home approval-runs bridge`. +- For one simulation batch: use `seal-home simulation batch-records `. +- For approval rule/document/style maintenance: use `seal-home tool --json '{...}'`. ## Task Playbooks @@ -37,13 +51,13 @@ Use when the user gives a 合思/易快报单号, Seal source document SN, sourc 1. Search runs: ```bash -bun run cli -- approval-runs search --query --limit 50 +seal-home approval-runs search --query --limit 50 ``` 2. If a likely record is found, get bridge hints: ```bash -bun run cli -- approval-runs bridge --sourceDocumentSN +seal-home approval-runs bridge --sourceDocumentSN ``` 3. Report `status`, `taskMode`, `finalExecutionMode`, `recordId`, `simulationBatchId`, `langfuseTraceId`, and `langfuseSessionFallback`. If `langfuseTraceId` is absent, tell the caller to use the session fallback. @@ -53,7 +67,7 @@ bun run cli -- approval-runs bridge --sourceDocumentSN Use explicit local date and timezone: ```bash -bun run cli -- approval-runs summary --date YYYY-MM-DD --timezone Asia/Shanghai --limit 100 +seal-home approval-runs summary --date YYYY-MM-DD --timezone Asia/Shanghai --limit 100 ``` Report matched count, status counts, task mode counts, and the most relevant failed or simulated records. If `matched` is unexpectedly low, rerun with broader `limit` or targeted `query`. @@ -61,7 +75,7 @@ Report matched count, status counts, task mode counts, and the most relevant fai ### Inspect a simulation batch ```bash -bun run cli -- simulation batch-records +seal-home simulation batch-records ``` Summarize count, statuses, source document identifiers, and bridge hints. For failures, preserve record IDs so another tool can inspect the trace. @@ -71,10 +85,10 @@ Summarize count, statuses, source document identifiers, and bridge hints. For fa Use for "which rule/document mentions X" or before changing rule/document content: ```bash -bun run cli -- tool seal_approval_search --json '{"keywords":["关键词"],"matchMode":"any","maxResults":20}' +seal-home tool seal_approval_search --json '{"keywords":["关键词"],"matchMode":"any","maxResults":20}' ``` -Use `areas` to narrow to `rules`, `documents`, or `preferences`. Use `refresh:true` when recent edits may not be reflected in the MCP server's in-memory cache. Separate CLI invocations are short-lived processes and do not share this cache. +Use `areas` to narrow to `rules`, `documents`, or `preferences`. Separate CLI invocations are short-lived processes and do not share in-memory search caches. Use the local service as the restartable long-lived process for future cached workflows. ### Update approval rules @@ -104,13 +118,13 @@ There is no dedicated delete command in the current CLI. If deactivation is inte Read first: ```bash -bun run cli -- tool seal_approval_style_preferences_get +seal-home tool seal_approval_style_preferences_get ``` Then update only explicit fields: ```bash -bun run cli -- tool seal_approval_style_preferences_update --json '{"tone":"...","language":"..."}' +seal-home tool seal_approval_style_preferences_update --json '{"tone":"...","language":"..."}' ``` Verify by reading again. @@ -127,29 +141,6 @@ Verify by reading again. - `langfuseTraceId`: direct Langfuse trace lookup key when present. - `langfuseSessionFallback`: fallback session key, usually `hosecloud-{sourceDocumentSN}`, when direct trace ID is absent. -## MCP Boundary - -The MCP server advertises only these tools: - -- `seal_corp_switch` -- `seal_whoami` -- `seal_approval_search` -- `seal_approval_context_get` -- `seal_runs_search` -- `seal_action` - -Do not add every backend API operation as an MCP tool. Add stable, frequent read operations directly; route low-frequency management through `seal_action` or CLI. - -`seal_action` examples: - -```json -{ "action": "help", "payload": { "topic": "rule" } } -{ "action": "rule.create", "payload": { "description": "...", "scope": "...", "strictness": "SHOULD_FOLLOW" } } -{ "action": "doc.update", "payload": { "documentId": "...", "content": "..." } } -{ "action": "runs.summary", "payload": { "date": "2026-06-09", "timezone": "Asia/Shanghai" } } -{ "action": "langfuse.bridge.get", "payload": { "sourceDocumentSN": "B26001887" } } -``` - ## CLI Patterns Read `references/cli.md` when you need the full tool list, parameter examples, or maintenance commands. @@ -157,10 +148,10 @@ Read `references/cli.md` when you need the full tool list, parameter examples, o Preferred command forms: ```bash -bun run cli -- approval-runs summary --date 2026-06-09 --timezone Asia/Shanghai -bun run cli -- approval-runs search --query B26001887 --limit 20 --includeBridge true -bun run cli -- approval-runs bridge --sourceDocumentSN B26001887 -bun run cli -- tool seal_approval_search --json '{"keywords":["差旅","发票"],"areas":["rules","documents"]}' +seal-home approval-runs summary --date 2026-06-09 --timezone Asia/Shanghai +seal-home approval-runs search --query B26001887 --limit 20 --includeBridge true +seal-home approval-runs bridge --sourceDocumentSN B26001887 +seal-home tool seal_approval_search --json '{"keywords":["差旅","发票"],"areas":["rules","documents"]}' ``` ## Output Handling diff --git a/skills/seal-home/references/cli.md b/skills/seal-home/references/cli.md index 073c744..bc2cab7 100644 --- a/skills/seal-home/references/cli.md +++ b/skills/seal-home/references/cli.md @@ -1,28 +1,37 @@ # Seal Home CLI Reference -Run from the repository root: +Run from any directory after installing the global CLI: ```bash -bun run cli -- +seal-home ``` +Enterprise config lookup order: + +1. `SEAL_HOME_ENTERPRISES_DIR` +2. `./enterprises` in the current working directory +3. `~/.config/seal-home/enterprises` + ## Top-Level Commands ```bash -bun run cli -- version -bun run cli -- tools list -bun run cli -- corps list [--corp ] -bun run cli -- source config [--corp ] -bun run cli -- tool [--corp ] [--json '{"key":"value"}'] -bun run cli -- approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] -bun run cli -- approval-runs search [--query text] [--limit 20] [--includeBridge true] -bun run cli -- approval-runs bridge [--sourceDocumentSN B26001887] -bun run cli -- simulation batch-records +seal-home version +seal-home config paths +seal-home service +seal-home update +seal-home tools list +seal-home corps list [--corp ] +seal-home source config [--corp ] +seal-home tool [--corp ] [--json '{"key":"value"}'] +seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] +seal-home approval-runs search [--query text] [--limit 20] [--includeBridge true] +seal-home approval-runs bridge [--sourceDocumentSN B26001887] +seal-home simulation batch-records ``` ## Fine-Grained Tools -`bun run cli -- version` returns: +`seal-home version` returns: ```json { @@ -31,6 +40,10 @@ bun run cli -- simulation batch-records } ``` +`seal-home service status` returns the PID, version, state directory, PID file, and log file for the optional local background process. + +`seal-home update` updates the git checkout, runs `bun install`, and restarts the local service if it was running. + Identity and session: - `seal_whoami` @@ -74,49 +87,49 @@ Approval runs, simulations, and Langfuse bridge: Search approval content: ```bash -bun run cli -- tool seal_approval_search --json '{"keywords":["关键词"],"matchMode":"any","maxResults":20}' +seal-home tool seal_approval_search --json '{"keywords":["关键词"],"matchMode":"any","maxResults":20}' ``` Get aggregated approval context: ```bash -bun run cli -- tool seal_approval_context_get --json '{"documentLimit":20}' +seal-home tool seal_approval_context_get --json '{"documentLimit":20}' ``` Create a draft approval rule: ```bash -bun run cli -- tool seal_approval_rule_create --json '{"description":"规则描述","scope":"适用场景","strictness":"SHOULD_FOLLOW"}' +seal-home tool seal_approval_rule_create --json '{"description":"规则描述","scope":"适用场景","strictness":"SHOULD_FOLLOW"}' ``` Update an approval document: ```bash -bun run cli -- tool seal_approval_document_update --json '{"documentId":"doc-id","content":"Markdown 内容"}' +seal-home tool seal_approval_document_update --json '{"documentId":"doc-id","content":"Markdown 内容"}' ``` Summarize one local date: ```bash -bun run cli -- approval-runs summary --date 2026-06-09 --timezone Asia/Shanghai --limit 100 +seal-home approval-runs summary --date 2026-06-09 --timezone Asia/Shanghai --limit 100 ``` Find a run and include Langfuse bridge rows: ```bash -bun run cli -- approval-runs search --query B26001887 --limit 20 --includeBridge true +seal-home approval-runs search --query B26001887 --limit 20 --includeBridge true ``` Resolve Langfuse trace/session hints: ```bash -bun run cli -- approval-runs bridge --sourceDocumentSN B26001887 +seal-home approval-runs bridge --sourceDocumentSN B26001887 ``` Read simulation batch records: ```bash -bun run cli -- simulation batch-records +seal-home simulation batch-records ``` ## Write Operation Payloads @@ -194,7 +207,7 @@ Update style preferences: ## Failure Handling -- CLI commands are short-lived processes. In-memory auth/search caches only live for that single process. The MCP server is long-lived, so it can reuse in-memory caches across tool calls until refresh or TTL expiry. +- CLI commands are short-lived processes. In-memory auth/search caches only live for that single process. Use `seal-home service restart` after updates so the optional local service picks up new code. - If no run is found by `sourceDocumentSN`, retry with `sourceDocumentId` or a broader `query`. - If date-based summaries look wrong, pass `--timezone Asia/Shanghai` and an explicit `--date`. - If `langfuseTraceId` is missing, use `langfuseSessionFallback`. diff --git a/src/cli.ts b/src/cli.ts index 26c5e9e..6a519dc 100755 --- a/src/cli.ts +++ b/src/cli.ts @@ -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 "); + } +} + +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>, @@ -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 + seal-home update seal-home tools list seal-home corps list [--corp ] seal-home source config [--corp ] diff --git a/src/core/config/loader.test.ts b/src/core/config/loader.test.ts new file mode 100644 index 0000000..cf23bb6 --- /dev/null +++ b/src/core/config/loader.test.ts @@ -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; +} diff --git a/src/core/config/loader.ts b/src/core/config/loader.ts index 281b8e2..85e659f 100644 --- a/src/core/config/loader.ts +++ b/src/core/config/loader.ts @@ -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}=`, + ENTERPRISES_DIR, + join(homedir(), ".config", "seal-home", "enterprises") + ]; +} diff --git a/src/probe.ts b/src/probe.ts index 1018f1b..8bf9be7 100644 --- a/src/probe.ts +++ b/src/probe.ts @@ -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(", ")}` ); } diff --git a/src/server.ts b/src/server.ts index 8ffe81e..57629e9 100644 --- a/src/server.ts +++ b/src/server.ts @@ -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 );