Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a17cd081b | ||
|
|
013a788077 | ||
|
|
3c085456b0 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-home",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.2",
|
||||
"description": "Seal Home tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
---
|
||||
|
||||
## [0.9.2] - 2026-08-25
|
||||
|
||||
### Fixed & Enhanced
|
||||
- **Real-Time Streaming Download Progress in Self-Update**: Upgraded `seal-home update` to stream download progress, mirror probe status, and live percentages directly to `stderr` in real-time, eliminating silent waiting and terminal stalling during binary upgrades.
|
||||
- **Fast Mirror Connectivity Probes**: Added fast 10s connection timeouts and stream chunk tracking for Gitea, fast CDN proxies, and GitHub download candidates.
|
||||
|
||||
---
|
||||
|
||||
## [0.9.1] - 2026-08-25
|
||||
|
||||
### Added
|
||||
- **Native HTTP REST API & Documentation Server**: Added `seal-home http [--port 8787] [--host 127.0.0.1]` and `seal-home serve` to start a zero-dependency local HTTP API server.
|
||||
- **Interactive API Reference (`/docs`)**: Built-in interactive Scalar API documentation rendering the full OpenAPI 3.1.0 specification.
|
||||
- **Agent CLI & Tool Execution Endpoints**: Added `POST /api/cli` (executing arbitrary seal-home commands over HTTP with JSON responses) and `POST /api/tool/:name` (invoking granular tools directly).
|
||||
- **Standard RESTful API Endpoints (`/v1/*`)**: Exposed OpenAPI-mapped RESTful endpoints for corps, whoami, approval runs, rules, simulations, and decision preferences.
|
||||
- **Full CORS & Enterprise Header Routing**: Enabled out-of-the-box CORS support and `X-Seal-Corp` header routing for web frontends, Dify, FastGPT, and external automation workflows.
|
||||
|
||||
---
|
||||
|
||||
## [0.9.0] - 2026-08-25
|
||||
|
||||
### Added
|
||||
|
||||
Vendored
+564
-53
@@ -24943,7 +24943,7 @@ async function createSealClientForToken(corp, token) {
|
||||
// package.json
|
||||
var package_default = {
|
||||
name: "seal-home",
|
||||
version: "0.9.0",
|
||||
version: "0.9.2",
|
||||
type: "module",
|
||||
module: "src/server.ts",
|
||||
bin: {
|
||||
@@ -27987,6 +27987,12 @@ var sealMcpTools = [
|
||||
handler: async (client, params, context) => runSealAction(client, params, context)
|
||||
}
|
||||
];
|
||||
function findSealTool(name, options = {}) {
|
||||
if (options.includeMcpAliases && name === "seal_runs_search") {
|
||||
return requiredTool("seal_approval_runs_search");
|
||||
}
|
||||
return sealToolByName.get(name);
|
||||
}
|
||||
async function runSealAction(client, params, context) {
|
||||
const action = params.action?.trim();
|
||||
if (!action || action === "help") {
|
||||
@@ -29306,6 +29312,8 @@ Usage:
|
||||
seal-home skill dump
|
||||
seal-home skill install [--dir <path>|--local]
|
||||
seal-home skill status
|
||||
seal-home http [--port 8787] [--host 127.0.0.1]
|
||||
seal-home serve [--port 8787]
|
||||
seal-home openapi
|
||||
seal-home probe [<corpId>]
|
||||
seal-home config paths
|
||||
@@ -30175,47 +30183,17 @@ async function handleDeployCommand(systemOrAction, actionOrTarget, maybeTarget,
|
||||
throw new Error(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync.`);
|
||||
}
|
||||
|
||||
// src/cli/commands/llm.ts
|
||||
async function handleLlmCommand(action, client, corp, args) {
|
||||
if (action === "config" || action === "get") {
|
||||
await runTool("seal_llm_config_get", client, corp, {}, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
if (action === "providers" || action === "list") {
|
||||
await runTool("seal_llm_providers_list", client, corp, {}, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
throw new Error(`Unknown llm command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
|
||||
}
|
||||
// src/http/server.ts
|
||||
import { createServer } from "node:http";
|
||||
|
||||
// src/cli/commands/mcp.ts
|
||||
async function handleMcpCommand(action, args) {
|
||||
if (action === "config" || action === "json") {
|
||||
printMcpConfig();
|
||||
return;
|
||||
}
|
||||
await startServer();
|
||||
}
|
||||
function printMcpConfig() {
|
||||
printJson({
|
||||
mcpServers: {
|
||||
"seal-home": {
|
||||
type: "stdio",
|
||||
command: "seal-home",
|
||||
args: ["mcp"],
|
||||
env: {
|
||||
SEAL_HOME_MCP_ENABLED: "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
// src/http/routes.ts
|
||||
import { URL as URL2 } from "node:url";
|
||||
// dist/openapi.json
|
||||
var openapi_default = {
|
||||
openapi: "3.1.0",
|
||||
info: {
|
||||
title: "seal-home Wrapped API",
|
||||
version: "0.9.0",
|
||||
version: "0.9.2",
|
||||
description: `Planned HTTP contract for the seal-home wrapped backend API.
|
||||
|
||||
These endpoints describe the intended stable API for frontend developers and agents once
|
||||
@@ -33560,6 +33538,486 @@ function getOpenApiSchema() {
|
||||
return openapi_default;
|
||||
}
|
||||
|
||||
// src/http/docs.ts
|
||||
function renderDocsHtml() {
|
||||
return `<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
|
||||
<title>Seal Home API Docs (v${VERSION})</title>
|
||||
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>\uD83E\uDDAD</text></svg>" />
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: #0f172a;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<script
|
||||
id="api-reference"
|
||||
data-url="/openapi.json"
|
||||
data-configuration='{"theme":"purple","layout":"modern","showSidebar":true}'
|
||||
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
|
||||
></script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
// src/http/routes.ts
|
||||
async function executeSealTool(tool, client, params, corp) {
|
||||
const handler = tool.handler;
|
||||
return handler(client, params, { corp });
|
||||
}
|
||||
async function handleHttpRequest(req, res) {
|
||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session");
|
||||
if (req.method === "OPTIONS") {
|
||||
res.writeHead(204);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
const host = req.headers.host || "localhost";
|
||||
const protocol = req.headers["x-forwarded-proto"] || "http";
|
||||
const url2 = new URL2(req.url || "/", `${protocol}://${host}`);
|
||||
const pathname = url2.pathname.replace(/\/+$/, "") || "/";
|
||||
const method = (req.method || "GET").toUpperCase();
|
||||
try {
|
||||
if (method === "GET" && pathname === "/") {
|
||||
sendJson(res, 200, {
|
||||
name: "seal-home",
|
||||
version: VERSION,
|
||||
description: "Seal tenant operations and approval automation HTTP API",
|
||||
docs: "/docs",
|
||||
openapi: "/openapi.json",
|
||||
health: "/health",
|
||||
endpoints: {
|
||||
cli: "POST /api/cli",
|
||||
tools: "GET /api/tools",
|
||||
toolInvoke: "POST /api/tool/:name",
|
||||
restV1: "GET/POST /v1/*"
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (method === "GET" && pathname === "/docs") {
|
||||
sendHtml(res, 200, renderDocsHtml());
|
||||
return;
|
||||
}
|
||||
if (method === "GET" && (pathname === "/openapi.json" || pathname === "/openapi")) {
|
||||
const schema = getOpenApiSchema();
|
||||
sendJson(res, 200, schema);
|
||||
return;
|
||||
}
|
||||
if (method === "GET" && (pathname === "/health" || pathname === "/version")) {
|
||||
sendJson(res, 200, {
|
||||
status: "ok",
|
||||
name: "seal-home",
|
||||
version: VERSION,
|
||||
uptimeSeconds: Math.floor(process.uptime()),
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (method === "GET" && pathname === "/api/tools") {
|
||||
sendJson(res, 200, {
|
||||
count: sealTools.length,
|
||||
tools: sealTools.map((t) => ({
|
||||
name: t.name,
|
||||
description: t.description
|
||||
}))
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (method === "POST" && pathname === "/api/cli") {
|
||||
const body = await parseJsonBody(req);
|
||||
const commandStr = typeof body?.command === "string" ? body.command.trim() : "";
|
||||
if (!commandStr) {
|
||||
sendError(res, 400, "Missing or empty 'command' field in request body");
|
||||
return;
|
||||
}
|
||||
const tokens = tokenizeCommand(commandStr);
|
||||
const cliArgs = tokens[0] === "seal-home" || tokens[0]?.endsWith("/seal-home") ? tokens.slice(1) : tokens;
|
||||
const result = await runCli(cliArgs);
|
||||
let parsedData = undefined;
|
||||
try {
|
||||
if (result.stdout.trim().startsWith("{") || result.stdout.trim().startsWith("[")) {
|
||||
parsedData = JSON.parse(result.stdout);
|
||||
}
|
||||
} catch {}
|
||||
sendJson(res, result.isError ? 400 : 200, {
|
||||
success: !result.isError,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
exitCode: result.exitCode,
|
||||
data: parsedData
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (method === "POST" && pathname.startsWith("/api/tool/")) {
|
||||
const toolName = pathname.slice("/api/tool/".length).trim();
|
||||
const tool = findSealTool(toolName, { includeMcpAliases: true });
|
||||
if (!tool) {
|
||||
sendError(res, 404, `Tool not found: '${toolName}'`);
|
||||
return;
|
||||
}
|
||||
const body = await parseJsonBody(req) || {};
|
||||
const corpId = extractCorpId(req, url2, body);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const params = { ...body };
|
||||
delete params.corp;
|
||||
const output = await executeSealTool(tool, client, params, corp);
|
||||
sendJson(res, 200, output);
|
||||
return;
|
||||
}
|
||||
if (pathname.startsWith("/v1/")) {
|
||||
const handled = await handleRestV1(req, res, method, pathname, url2);
|
||||
if (handled)
|
||||
return;
|
||||
}
|
||||
sendError(res, 404, `Cannot ${method} ${pathname}. Visit /docs for available endpoints.`);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
sendError(res, 500, message);
|
||||
}
|
||||
}
|
||||
async function handleRestV1(req, res, method, pathname, url2) {
|
||||
const queryParams = Object.fromEntries(url2.searchParams.entries());
|
||||
if (method === "GET" && pathname === "/v1/corps") {
|
||||
const configs = loadCorpConfigs();
|
||||
const globalConfig2 = loadGlobalConfig();
|
||||
sendJson(res, 200, {
|
||||
count: configs.length,
|
||||
mode: globalConfig2.stateful ? "stateful" : "stateless",
|
||||
defaultCorpId: globalConfig2.defaultCorpId,
|
||||
corps: configs.map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
sourceType: c.source.type,
|
||||
sealUrl: c.seal?.url
|
||||
}))
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (method === "GET" && pathname === "/v1/whoami") {
|
||||
const corpId = extractCorpId(req, url2, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_whoami");
|
||||
const data = await executeSealTool(tool, client, {}, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (method === "GET" && pathname === "/v1/session") {
|
||||
const corpId = extractCorpId(req, url2, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_session_get");
|
||||
const data = await executeSealTool(tool, client, {}, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (method === "GET" && pathname === "/v1/approval-runs/summary") {
|
||||
const corpId = extractCorpId(req, url2, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_approval_runs_summary");
|
||||
const data = await executeSealTool(tool, client, queryParams, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (method === "GET" && pathname === "/v1/approval-runs/stats") {
|
||||
const corpId = extractCorpId(req, url2, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_approval_runs_stats");
|
||||
const data = await executeSealTool(tool, client, queryParams, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (method === "GET" && pathname === "/v1/approval-runs/pick") {
|
||||
const corpId = extractCorpId(req, url2, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_approval_run_pick");
|
||||
const data = await executeSealTool(tool, client, queryParams, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (method === "GET" && pathname === "/v1/approval-runs/url") {
|
||||
const corpId = extractCorpId(req, url2, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_approval_run_url_get");
|
||||
const data = await executeSealTool(tool, client, queryParams, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (pathname.startsWith("/v1/approval-runs/")) {
|
||||
const parts = pathname.slice("/v1/approval-runs/".length).split("/");
|
||||
const recordId = parts[0];
|
||||
const sub = parts[1];
|
||||
if (recordId && !["summary", "pick", "stats", "url", "bridge"].includes(recordId)) {
|
||||
const corpId = extractCorpId(req, url2, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
if (!sub) {
|
||||
const tool = findSealTool("seal_approval_run_get");
|
||||
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (sub === "attachments") {
|
||||
const tool = findSealTool("seal_approval_run_attachments_get");
|
||||
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (sub === "cited-rules") {
|
||||
const tool = findSealTool("seal_approval_run_cited_rules_get");
|
||||
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (sub === "document-summary") {
|
||||
const tool = findSealTool("seal_approval_run_document_summary_get");
|
||||
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (sub === "result") {
|
||||
const tool = findSealTool("seal_approval_run_result_get");
|
||||
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (method === "GET" && pathname === "/v1/approval-runs") {
|
||||
const corpId = extractCorpId(req, url2, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_approval_runs_search");
|
||||
const data = await executeSealTool(tool, client, {
|
||||
...queryParams,
|
||||
limit: queryParams.limit ? Number(queryParams.limit) : undefined,
|
||||
offset: queryParams.offset ? Number(queryParams.offset) : undefined,
|
||||
includeBridge: queryParams.includeBridge === "true"
|
||||
}, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (method === "GET" && pathname === "/v1/approval/rules") {
|
||||
const corpId = extractCorpId(req, url2, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_approval_rules_list");
|
||||
const data = await executeSealTool(tool, client, queryParams, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (method === "GET" && pathname === "/v1/simulation/batches") {
|
||||
const corpId = extractCorpId(req, url2, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_simulation_batches_list");
|
||||
const data = await executeSealTool(tool, client, queryParams, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (method === "POST" && pathname === "/v1/simulation/create-batch") {
|
||||
const body = await parseJsonBody(req) || {};
|
||||
const corpId = extractCorpId(req, url2, body);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_simulation_batch_create");
|
||||
const data = await executeSealTool(tool, client, body, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (method === "GET" && pathname.startsWith("/v1/simulation/batch/")) {
|
||||
const parts = pathname.slice("/v1/simulation/batch/".length).split("/");
|
||||
const batchId = parts[0];
|
||||
if (batchId) {
|
||||
const corpId = extractCorpId(req, url2, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_simulation_batch_get");
|
||||
const data = await executeSealTool(tool, client, { batchId }, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (method === "GET" && pathname === "/v1/preferences") {
|
||||
const corpId = extractCorpId(req, url2, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_preference_get");
|
||||
const data = await executeSealTool(tool, client, {}, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (method === "POST" && pathname === "/v1/preferences/decision") {
|
||||
const body = await parseJsonBody(req) || {};
|
||||
const corpId = extractCorpId(req, url2, body);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_preference_decision_update");
|
||||
const data = await executeSealTool(tool, client, body, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function extractCorpId(req, url2, body) {
|
||||
const header = req.headers["x-seal-corp"];
|
||||
if (typeof header === "string" && header.trim())
|
||||
return header.trim();
|
||||
const query = url2.searchParams.get("corp");
|
||||
if (query?.trim())
|
||||
return query.trim();
|
||||
if (body && typeof body.corp === "string" && body.corp.trim()) {
|
||||
return body.corp.trim();
|
||||
}
|
||||
return;
|
||||
}
|
||||
async function parseJsonBody(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let raw = "";
|
||||
req.on("data", (chunk) => {
|
||||
raw += chunk;
|
||||
if (raw.length > 20 * 1024 * 1024) {
|
||||
reject(new Error("Payload too large"));
|
||||
}
|
||||
});
|
||||
req.on("end", () => {
|
||||
if (!raw.trim()) {
|
||||
resolve({});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
resolve(JSON.parse(raw));
|
||||
} catch (err) {
|
||||
reject(new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`));
|
||||
}
|
||||
});
|
||||
req.on("error", reject);
|
||||
});
|
||||
}
|
||||
function sendJson(res, statusCode, data) {
|
||||
const json2 = JSON.stringify(data, null, 2);
|
||||
res.writeHead(statusCode, {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Content-Length": Buffer.byteLength(json2)
|
||||
});
|
||||
res.end(json2);
|
||||
}
|
||||
function sendHtml(res, statusCode, html) {
|
||||
res.writeHead(statusCode, {
|
||||
"Content-Type": "text/html; charset=utf-8",
|
||||
"Content-Length": Buffer.byteLength(html)
|
||||
});
|
||||
res.end(html);
|
||||
}
|
||||
function sendError(res, statusCode, message, details) {
|
||||
sendJson(res, statusCode, {
|
||||
error: true,
|
||||
statusCode,
|
||||
message,
|
||||
...details !== undefined ? { details } : {}
|
||||
});
|
||||
}
|
||||
|
||||
// src/http/server.ts
|
||||
async function startHttpServer(options = {}) {
|
||||
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : 8787);
|
||||
const host = options.host ?? (process.env.HOST ? process.env.HOST : "127.0.0.1");
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
await handleHttpRequest(req, res);
|
||||
} catch (err) {
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(500, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: true, message: err instanceof Error ? err.message : String(err) }));
|
||||
}
|
||||
}
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
server.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
server.listen(port, host, () => {
|
||||
if (!options.silent) {
|
||||
console.error(`
|
||||
\uD83D\uDE80 seal-home HTTP Server (v${VERSION}) started`);
|
||||
console.error(` URL: http://${host}:${port}`);
|
||||
console.error(` Docs: http://${host}:${port}/docs`);
|
||||
console.error(` OpenAPI: http://${host}:${port}/openapi.json`);
|
||||
console.error(` CLI Exec: POST http://${host}:${port}/api/cli`);
|
||||
console.error(` REST API: http://${host}:${port}/v1/...
|
||||
`);
|
||||
}
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// src/cli/commands/http.ts
|
||||
async function handleHttpCommand(args) {
|
||||
const port = numberOption(args.options.port) ?? numberOption(args.options.p);
|
||||
const host = stringOption(args.options.host) ?? stringOption(args.options.h);
|
||||
const server = await startHttpServer({ port, host });
|
||||
const shutdown = () => {
|
||||
server.close(() => {
|
||||
process.exit(0);
|
||||
});
|
||||
};
|
||||
process.on("SIGINT", shutdown);
|
||||
process.on("SIGTERM", shutdown);
|
||||
await new Promise(() => {});
|
||||
}
|
||||
|
||||
// src/cli/commands/llm.ts
|
||||
async function handleLlmCommand(action, client, corp, args) {
|
||||
if (action === "config" || action === "get") {
|
||||
await runTool("seal_llm_config_get", client, corp, {}, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
if (action === "providers" || action === "list") {
|
||||
await runTool("seal_llm_providers_list", client, corp, {}, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
throw new Error(`Unknown llm command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
|
||||
}
|
||||
|
||||
// src/cli/commands/mcp.ts
|
||||
async function handleMcpCommand(action, args) {
|
||||
if (action === "config" || action === "json") {
|
||||
printMcpConfig();
|
||||
return;
|
||||
}
|
||||
await startServer();
|
||||
}
|
||||
function printMcpConfig() {
|
||||
printJson({
|
||||
mcpServers: {
|
||||
"seal-home": {
|
||||
type: "stdio",
|
||||
command: "seal-home",
|
||||
args: ["mcp"],
|
||||
env: {
|
||||
SEAL_HOME_MCP_ENABLED: "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// src/cli/commands/openapi.ts
|
||||
function handleOpenApiCommand(args) {
|
||||
const schema = getOpenApiSchema();
|
||||
@@ -34037,13 +34495,13 @@ import { dirname as dirname3, join as join6 } from "node:path";
|
||||
// skills/seal-home/SKILL.md
|
||||
var SKILL_default = `---
|
||||
name: seal-home
|
||||
description: "v0.9.0: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search."
|
||||
description: "v0.9.2: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search."
|
||||
metadata:
|
||||
version: 0.9.0
|
||||
short-description: Seal tenant and Hose approval automation (v0.9.0)
|
||||
version: 0.9.2
|
||||
short-description: Seal tenant and Hose approval automation (v0.9.2)
|
||||
---
|
||||
|
||||
# Seal Home (v0.9.0)
|
||||
# Seal Home (v0.9.2)
|
||||
|
||||
Use the \`seal_cli\` MCP tool when it is available; pass the command string as its \`command\` argument. If MCP is unavailable, fall back to the global \`seal-home\` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
|
||||
|
||||
@@ -34084,6 +34542,7 @@ seal-home tools list
|
||||
- System Permissions Config: \`seal-home permissions available --corp <corpId>\`, \`seal-home permissions configs --corp <corpId>\`.
|
||||
- Billing & Feature Quotas: \`seal-home billing status --corp <corpId>\`, \`seal-home billing plans --corp <corpId>\`, \`seal-home billing features --corp <corpId>\`.
|
||||
- Webhook 审批回调管理: \`seal-home webhook <list|get|add|update|delete> --corp <corpId>\`.
|
||||
- HTTP REST API & Docs Server: \`seal-home http [--port 8787] [--host 127.0.0.1]\` (提供 \`/docs\` 交互文档、\`/openapi.json\`、\`POST /api/cli\` 与 \`/v1/*\` REST API)。
|
||||
- Full CLI inventory: read \`references/cli.md\`.
|
||||
|
||||
## High-Value Commands
|
||||
@@ -34341,6 +34800,8 @@ 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 http [--port 8787] [--host 127.0.0.1]
|
||||
seal-home serve [--port 8787]
|
||||
seal-home update
|
||||
seal-home tools list
|
||||
seal-home corps list [--corp <corpId>]
|
||||
@@ -35579,12 +36040,18 @@ function matchAssetForPlatform(assets, platform, arch) {
|
||||
const archive = matched.find((asset) => asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz") || asset.name.endsWith(".zip"));
|
||||
return archive || matched[0];
|
||||
}
|
||||
function logProgress(msg) {
|
||||
try {
|
||||
process.stderr.write(`${msg}
|
||||
`);
|
||||
} catch {}
|
||||
console.error(msg);
|
||||
}
|
||||
async function downloadFile(url2, destPath, tagName, assetName) {
|
||||
const candidates = [];
|
||||
if (tagName && assetName) {
|
||||
const tag = tagName.startsWith("v") ? tagName : `v${tagName}`;
|
||||
candidates.push(`https://git.ying-qing.cn/gitea/seal-home/releases/download/${tag}/${assetName}`);
|
||||
candidates.push(`https://git.ying-qing.cn/gitea/seal-home/releases/download/latest/${assetName}`);
|
||||
}
|
||||
if (url2.startsWith("https://git.ying-qing.cn")) {
|
||||
candidates.unshift(url2);
|
||||
@@ -35599,23 +36066,61 @@ async function downloadFile(url2, destPath, tagName, assetName) {
|
||||
}
|
||||
const uniqueCandidates = Array.from(new Set(candidates));
|
||||
let lastError;
|
||||
for (const candidate of uniqueCandidates) {
|
||||
for (let i = 0;i < uniqueCandidates.length; i++) {
|
||||
const candidate = uniqueCandidates[i];
|
||||
try {
|
||||
console.error(`==> Trying download mirror: ${candidate}`);
|
||||
const res = await fetch(candidate, { signal: AbortSignal.timeout(30000) });
|
||||
logProgress(`==> [${i + 1}/${uniqueCandidates.length}] Downloading via: ${candidate}`);
|
||||
const res = await fetch(candidate, { signal: AbortSignal.timeout(1e4) });
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status} ${res.statusText}`);
|
||||
}
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
if (buffer.length < 1000) {
|
||||
throw new Error(`Downloaded content is suspiciously small (${buffer.length} bytes)`);
|
||||
const totalBytes = Number(res.headers.get("content-length")) || 0;
|
||||
const reader = res.body?.getReader();
|
||||
if (!reader) {
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
if (buffer.length < 1000) {
|
||||
throw new Error(`Downloaded content is suspiciously small (${buffer.length} bytes)`);
|
||||
}
|
||||
writeFileSync7(destPath, buffer);
|
||||
logProgress(`✓ Download succeeded (${(buffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
||||
return;
|
||||
}
|
||||
writeFileSync7(destPath, buffer);
|
||||
console.error(`✓ Download succeeded from: ${candidate} (${buffer.length} bytes)`);
|
||||
const chunks = [];
|
||||
let receivedBytes = 0;
|
||||
let lastReport = 0;
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done)
|
||||
break;
|
||||
if (value) {
|
||||
chunks.push(value);
|
||||
receivedBytes += value.length;
|
||||
const now = Date.now();
|
||||
if (now - lastReport > 200) {
|
||||
lastReport = now;
|
||||
const percent = totalBytes ? Math.round(receivedBytes / totalBytes * 100) : 0;
|
||||
const receivedMb = (receivedBytes / (1024 * 1024)).toFixed(1);
|
||||
const totalMb = totalBytes ? (totalBytes / (1024 * 1024)).toFixed(1) : "?";
|
||||
try {
|
||||
process.stderr.write(`\r ↳ Progress: ${percent}% (${receivedMb} / ${totalMb} MB)...`);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
process.stderr.write(`
|
||||
`);
|
||||
} catch {}
|
||||
const completeBuffer = Buffer.concat(chunks);
|
||||
if (completeBuffer.length < 1000) {
|
||||
throw new Error(`Downloaded content is suspiciously small (${completeBuffer.length} bytes)`);
|
||||
}
|
||||
writeFileSync7(destPath, completeBuffer);
|
||||
logProgress(`✓ Download completed successfully (${(completeBuffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
||||
return;
|
||||
} catch (err) {
|
||||
lastError = err instanceof Error ? err : new Error(String(err));
|
||||
console.error(` ↳ Mirror failed: ${lastError.message}`);
|
||||
logProgress(` ↳ Mirror failed: ${lastError.message}`);
|
||||
}
|
||||
}
|
||||
throw new Error(`Failed to download asset from all mirrors: ${lastError?.message}`);
|
||||
@@ -35818,6 +36323,8 @@ var DEFAULT_APP_ROOT = dirname5(dirname5(dirname5(fileURLToPath(import.meta.url)
|
||||
var KNOWN_AREAS = new Set([
|
||||
"config",
|
||||
"service",
|
||||
"http",
|
||||
"serve",
|
||||
"update",
|
||||
"tools",
|
||||
"corps",
|
||||
@@ -35938,6 +36445,10 @@ async function dispatch(argv, runtime) {
|
||||
await handleServiceCommand(action, runtime);
|
||||
return;
|
||||
}
|
||||
if (area === "http" || area === "serve") {
|
||||
await handleHttpCommand(args);
|
||||
return;
|
||||
}
|
||||
if (area === "update" || area === "changelog") {
|
||||
const isChangelog = area === "changelog" || action === "changelog" || action === "log" || action === "history" || booleanOption(args.options.changelog) === true;
|
||||
const isCheck = action === "check" || booleanOption(args.options.check) === true || booleanOption(args.options["check-only"]) === true;
|
||||
@@ -36035,7 +36546,7 @@ function resolveMcpEnabled(value = process.env[SEAL_MCP_ENABLED_ENV]) {
|
||||
return false;
|
||||
return ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
|
||||
}
|
||||
function createServer(options = {}) {
|
||||
function createServer2(options = {}) {
|
||||
const enableCli = options.enableCli ?? true;
|
||||
const server = new Server({
|
||||
name: "seal-home",
|
||||
@@ -36103,7 +36614,7 @@ function createServer(options = {}) {
|
||||
}
|
||||
async function startServer() {
|
||||
const enableCli = resolveMcpEnabled();
|
||||
const server = createServer({ enableCli });
|
||||
const server = createServer2({ enableCli });
|
||||
await server.connect(new StdioServerTransport);
|
||||
console.error(enableCli ? "seal-home MCP server running on stdio" : "seal-home MCP server connected with seal_cli disabled by configuration");
|
||||
}
|
||||
@@ -36210,7 +36721,7 @@ export {
|
||||
tokenizeCommand,
|
||||
startServer,
|
||||
resolveMcpEnabled,
|
||||
createServer,
|
||||
createServer2 as createServer,
|
||||
SEAL_MCP_ENABLED_ENV,
|
||||
SEAL_CLI_TOOL_NAME
|
||||
};
|
||||
Vendored
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "seal-home Wrapped API",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.2",
|
||||
"description": "Planned HTTP contract for the seal-home wrapped backend API.\n\nThese endpoints describe the intended stable API for frontend developers and agents once\nthe HTTP adapter is implemented.\nThey are not the raw downstream Seal endpoints. seal-home is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n"
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: seal-home Wrapped API
|
||||
version: 0.9.0
|
||||
version: 0.9.2
|
||||
description: |
|
||||
Planned HTTP contract for the seal-home wrapped backend API.
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-home",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.2",
|
||||
"type": "module",
|
||||
"module": "src/server.ts",
|
||||
"bin": {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
---
|
||||
name: seal-home
|
||||
description: "v0.9.0: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search."
|
||||
description: "v0.9.2: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search."
|
||||
metadata:
|
||||
version: 0.9.0
|
||||
short-description: Seal tenant and Hose approval automation (v0.9.0)
|
||||
version: 0.9.2
|
||||
short-description: Seal tenant and Hose approval automation (v0.9.2)
|
||||
---
|
||||
|
||||
# Seal Home (v0.9.0)
|
||||
# Seal Home (v0.9.2)
|
||||
|
||||
Use the `seal_cli` MCP tool when it is available; pass the command string as its `command` argument. If MCP is unavailable, fall back to the global `seal-home` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
|
||||
|
||||
@@ -47,6 +47,7 @@ seal-home tools list
|
||||
- System Permissions Config: `seal-home permissions available --corp <corpId>`, `seal-home permissions configs --corp <corpId>`.
|
||||
- Billing & Feature Quotas: `seal-home billing status --corp <corpId>`, `seal-home billing plans --corp <corpId>`, `seal-home billing features --corp <corpId>`.
|
||||
- Webhook 审批回调管理: `seal-home webhook <list|get|add|update|delete> --corp <corpId>`.
|
||||
- HTTP REST API & Docs Server: `seal-home http [--port 8787] [--host 127.0.0.1]` (提供 `/docs` 交互文档、`/openapi.json`、`POST /api/cli` 与 `/v1/*` REST API)。
|
||||
- Full CLI inventory: read `references/cli.md`.
|
||||
|
||||
## High-Value Commands
|
||||
|
||||
@@ -32,6 +32,8 @@ 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 http [--port 8787] [--host 127.0.0.1]
|
||||
seal-home serve [--port 8787]
|
||||
seal-home update
|
||||
seal-home tools list
|
||||
seal-home corps list [--corp <corpId>]
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import { startHttpServer } from "../../http/server.js";
|
||||
|
||||
export async function handleHttpCommand(args: ParsedArgs) {
|
||||
const port = numberOption(args.options.port) ?? numberOption(args.options.p);
|
||||
const host = stringOption(args.options.host) ?? stringOption(args.options.h);
|
||||
|
||||
const server = await startHttpServer({ port, host });
|
||||
|
||||
// Handle graceful shutdown
|
||||
const shutdown = () => {
|
||||
server.close(() => {
|
||||
process.exit(0);
|
||||
});
|
||||
};
|
||||
|
||||
process.on("SIGINT", shutdown);
|
||||
process.on("SIGTERM", shutdown);
|
||||
|
||||
// Keep alive
|
||||
await new Promise(() => {});
|
||||
}
|
||||
+63
-10
@@ -459,6 +459,15 @@ function matchAssetForPlatform(
|
||||
return archive || matched[0];
|
||||
}
|
||||
|
||||
function logProgress(msg: string) {
|
||||
try {
|
||||
process.stderr.write(`${msg}\n`);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
console.error(msg);
|
||||
}
|
||||
|
||||
async function downloadFile(url: string, destPath: string, tagName?: string, assetName?: string) {
|
||||
const candidates: string[] = [];
|
||||
|
||||
@@ -466,7 +475,6 @@ async function downloadFile(url: string, destPath: string, tagName?: string, ass
|
||||
if (tagName && assetName) {
|
||||
const tag = tagName.startsWith("v") ? tagName : `v${tagName}`;
|
||||
candidates.push(`https://git.ying-qing.cn/gitea/seal-home/releases/download/${tag}/${assetName}`);
|
||||
candidates.push(`https://git.ying-qing.cn/gitea/seal-home/releases/download/latest/${assetName}`);
|
||||
}
|
||||
|
||||
// 2. Direct url if it's not already Gitea
|
||||
@@ -488,23 +496,68 @@ async function downloadFile(url: string, destPath: string, tagName?: string, ass
|
||||
const uniqueCandidates = Array.from(new Set(candidates));
|
||||
|
||||
let lastError: Error | undefined;
|
||||
for (const candidate of uniqueCandidates) {
|
||||
for (let i = 0; i < uniqueCandidates.length; i++) {
|
||||
const candidate = uniqueCandidates[i]!;
|
||||
try {
|
||||
console.error(`==> Trying download mirror: ${candidate}`);
|
||||
const res = await fetch(candidate, { signal: AbortSignal.timeout(30000) });
|
||||
logProgress(`==> [${i + 1}/${uniqueCandidates.length}] Downloading via: ${candidate}`);
|
||||
const res = await fetch(candidate, { signal: AbortSignal.timeout(10000) });
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status} ${res.statusText}`);
|
||||
}
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
if (buffer.length < 1000) {
|
||||
throw new Error(`Downloaded content is suspiciously small (${buffer.length} bytes)`);
|
||||
|
||||
const totalBytes = Number(res.headers.get("content-length")) || 0;
|
||||
const reader = res.body?.getReader();
|
||||
if (!reader) {
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
if (buffer.length < 1000) {
|
||||
throw new Error(`Downloaded content is suspiciously small (${buffer.length} bytes)`);
|
||||
}
|
||||
writeFileSync(destPath, buffer);
|
||||
logProgress(`✓ Download succeeded (${(buffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
||||
return;
|
||||
}
|
||||
writeFileSync(destPath, buffer);
|
||||
console.error(`✓ Download succeeded from: ${candidate} (${buffer.length} bytes)`);
|
||||
|
||||
const chunks: Uint8Array[] = [];
|
||||
let receivedBytes = 0;
|
||||
let lastReport = 0;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (value) {
|
||||
chunks.push(value);
|
||||
receivedBytes += value.length;
|
||||
const now = Date.now();
|
||||
if (now - lastReport > 200) {
|
||||
lastReport = now;
|
||||
const percent = totalBytes ? Math.round((receivedBytes / totalBytes) * 100) : 0;
|
||||
const receivedMb = (receivedBytes / (1024 * 1024)).toFixed(1);
|
||||
const totalMb = totalBytes ? (totalBytes / (1024 * 1024)).toFixed(1) : "?";
|
||||
try {
|
||||
process.stderr.write(`\r ↳ Progress: ${percent}% (${receivedMb} / ${totalMb} MB)...`);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
process.stderr.write("\n");
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
const completeBuffer = Buffer.concat(chunks);
|
||||
if (completeBuffer.length < 1000) {
|
||||
throw new Error(`Downloaded content is suspiciously small (${completeBuffer.length} bytes)`);
|
||||
}
|
||||
writeFileSync(destPath, completeBuffer);
|
||||
logProgress(`✓ Download completed successfully (${(completeBuffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
||||
return;
|
||||
} catch (err) {
|
||||
lastError = err instanceof Error ? err : new Error(String(err));
|
||||
console.error(` ↳ Mirror failed: ${lastError.message}`);
|
||||
logProgress(` ↳ Mirror failed: ${lastError.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -80,6 +80,8 @@ Usage:
|
||||
seal-home skill dump
|
||||
seal-home skill install [--dir <path>|--local]
|
||||
seal-home skill status
|
||||
seal-home http [--port 8787] [--host 127.0.0.1]
|
||||
seal-home serve [--port 8787]
|
||||
seal-home openapi
|
||||
seal-home probe [<corpId>]
|
||||
seal-home config paths
|
||||
|
||||
@@ -12,6 +12,7 @@ import { handleContextCommand } from "./commands/context.js";
|
||||
import { handleCorpsCommand } from "./commands/corps.js";
|
||||
import { handleDelegationCommand } from "./commands/delegation.js";
|
||||
import { handleDeployCommand } from "./commands/deploy.js";
|
||||
import { handleHttpCommand } from "./commands/http.js";
|
||||
import { handleLlmCommand } from "./commands/llm.js";
|
||||
import { handleMcpCommand, printMcpConfig } from "./commands/mcp.js";
|
||||
import { handleOpenApiCommand } from "./commands/openapi.js";
|
||||
@@ -43,6 +44,8 @@ const DEFAULT_APP_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))
|
||||
const KNOWN_AREAS = new Set([
|
||||
"config",
|
||||
"service",
|
||||
"http",
|
||||
"serve",
|
||||
"update",
|
||||
"tools",
|
||||
"corps",
|
||||
@@ -187,6 +190,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "http" || area === "serve") {
|
||||
await handleHttpCommand(args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "update" || area === "changelog") {
|
||||
const isChangelog =
|
||||
area === "changelog" ||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { VERSION } from "../version.js";
|
||||
|
||||
export function renderDocsHtml(): string {
|
||||
return `<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
|
||||
<title>Seal Home API Docs (v${VERSION})</title>
|
||||
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🦭</text></svg>" />
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: #0f172a;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<script
|
||||
id="api-reference"
|
||||
data-url="/openapi.json"
|
||||
data-configuration='{"theme":"purple","layout":"modern","showSidebar":true}'
|
||||
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
|
||||
></script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { URL } from "node:url";
|
||||
import type { KyInstance } from "ky";
|
||||
import { selectCorp } from "../cli/helpers.js";
|
||||
import { runCli } from "../cli/runner.js";
|
||||
import type { CorpConfig } from "../core/config/types.js";
|
||||
import { getOpenApiSchema } from "../core/embedded-openapi.js";
|
||||
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
|
||||
import { createSealClient } from "../core/http/factory.js";
|
||||
import { findSealTool, sealTools, type SealTool } from "../domains/seal/tools.js";
|
||||
import { tokenizeCommand } from "../server.js";
|
||||
import { VERSION } from "../version.js";
|
||||
import { renderDocsHtml } from "./docs.js";
|
||||
|
||||
async function executeSealTool(tool: SealTool, client: KyInstance, params: any, corp: CorpConfig): Promise<unknown> {
|
||||
const handler = tool.handler as (client: KyInstance, params: any, context: { corp: CorpConfig }) => Promise<unknown>;
|
||||
return handler(client, params, { corp });
|
||||
}
|
||||
|
||||
export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse) {
|
||||
// 1. CORS headers
|
||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session");
|
||||
|
||||
if (req.method === "OPTIONS") {
|
||||
res.writeHead(204);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const host = req.headers.host || "localhost";
|
||||
const protocol = req.headers["x-forwarded-proto"] || "http";
|
||||
const url = new URL(req.url || "/", `${protocol}://${host}`);
|
||||
const pathname = url.pathname.replace(/\/+$/, "") || "/";
|
||||
const method = (req.method || "GET").toUpperCase();
|
||||
|
||||
try {
|
||||
// 2. Documentation & Metadata
|
||||
if (method === "GET" && pathname === "/") {
|
||||
sendJson(res, 200, {
|
||||
name: "seal-home",
|
||||
version: VERSION,
|
||||
description: "Seal tenant operations and approval automation HTTP API",
|
||||
docs: "/docs",
|
||||
openapi: "/openapi.json",
|
||||
health: "/health",
|
||||
endpoints: {
|
||||
cli: "POST /api/cli",
|
||||
tools: "GET /api/tools",
|
||||
toolInvoke: "POST /api/tool/:name",
|
||||
restV1: "GET/POST /v1/*"
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && pathname === "/docs") {
|
||||
sendHtml(res, 200, renderDocsHtml());
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && (pathname === "/openapi.json" || pathname === "/openapi")) {
|
||||
const schema = getOpenApiSchema();
|
||||
sendJson(res, 200, schema);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && (pathname === "/health" || pathname === "/version")) {
|
||||
sendJson(res, 200, {
|
||||
status: "ok",
|
||||
name: "seal-home",
|
||||
version: VERSION,
|
||||
uptimeSeconds: Math.floor(process.uptime()),
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Tool Listing
|
||||
if (method === "GET" && pathname === "/api/tools") {
|
||||
sendJson(res, 200, {
|
||||
count: sealTools.length,
|
||||
tools: sealTools.map((t) => ({
|
||||
name: t.name,
|
||||
description: t.description
|
||||
}))
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 4. CLI Execution endpoint (POST /api/cli)
|
||||
if (method === "POST" && pathname === "/api/cli") {
|
||||
const body = await parseJsonBody(req);
|
||||
const commandStr = typeof body?.command === "string" ? body.command.trim() : "";
|
||||
if (!commandStr) {
|
||||
sendError(res, 400, "Missing or empty 'command' field in request body");
|
||||
return;
|
||||
}
|
||||
|
||||
const tokens = tokenizeCommand(commandStr);
|
||||
const cliArgs = tokens[0] === "seal-home" || tokens[0]?.endsWith("/seal-home") ? tokens.slice(1) : tokens;
|
||||
const result = await runCli(cliArgs);
|
||||
|
||||
let parsedData: unknown = undefined;
|
||||
try {
|
||||
if (result.stdout.trim().startsWith("{") || result.stdout.trim().startsWith("[")) {
|
||||
parsedData = JSON.parse(result.stdout);
|
||||
}
|
||||
} catch {
|
||||
// keep string
|
||||
}
|
||||
|
||||
sendJson(res, result.isError ? 400 : 200, {
|
||||
success: !result.isError,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
exitCode: result.exitCode,
|
||||
data: parsedData
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 5. Generic Tool Invocation endpoint (POST /api/tool/:name)
|
||||
if (method === "POST" && pathname.startsWith("/api/tool/")) {
|
||||
const toolName = pathname.slice("/api/tool/".length).trim();
|
||||
const tool = findSealTool(toolName, { includeMcpAliases: true });
|
||||
if (!tool) {
|
||||
sendError(res, 404, `Tool not found: '${toolName}'`);
|
||||
return;
|
||||
}
|
||||
|
||||
const body = (await parseJsonBody(req)) || {};
|
||||
const corpId = extractCorpId(req, url, body);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
|
||||
const params = { ...body };
|
||||
delete params.corp;
|
||||
|
||||
const output = await executeSealTool(tool, client, params, corp);
|
||||
sendJson(res, 200, output);
|
||||
return;
|
||||
}
|
||||
|
||||
// 6. RESTful /v1/* endpoints mapped from OpenAPI
|
||||
if (pathname.startsWith("/v1/")) {
|
||||
const handled = await handleRestV1(req, res, method, pathname, url);
|
||||
if (handled) return;
|
||||
}
|
||||
|
||||
sendError(res, 404, `Cannot ${method} ${pathname}. Visit /docs for available endpoints.`);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
sendError(res, 500, message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRestV1(
|
||||
req: IncomingMessage,
|
||||
res: ServerResponse,
|
||||
method: string,
|
||||
pathname: string,
|
||||
url: URL
|
||||
): Promise<boolean> {
|
||||
const queryParams = Object.fromEntries(url.searchParams.entries());
|
||||
|
||||
// GET /v1/corps
|
||||
if (method === "GET" && pathname === "/v1/corps") {
|
||||
const configs = loadCorpConfigs();
|
||||
const globalConfig = loadGlobalConfig();
|
||||
sendJson(res, 200, {
|
||||
count: configs.length,
|
||||
mode: globalConfig.stateful ? "stateful" : "stateless",
|
||||
defaultCorpId: globalConfig.defaultCorpId,
|
||||
corps: configs.map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
sourceType: c.source.type,
|
||||
sealUrl: c.seal?.url
|
||||
}))
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
// GET /v1/whoami
|
||||
if (method === "GET" && pathname === "/v1/whoami") {
|
||||
const corpId = extractCorpId(req, url, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_whoami")!;
|
||||
const data = await executeSealTool(tool, client, {}, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// GET /v1/session
|
||||
if (method === "GET" && pathname === "/v1/session") {
|
||||
const corpId = extractCorpId(req, url, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_session_get")!;
|
||||
const data = await executeSealTool(tool, client, {}, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// GET /v1/approval-runs/summary
|
||||
if (method === "GET" && pathname === "/v1/approval-runs/summary") {
|
||||
const corpId = extractCorpId(req, url, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_approval_runs_summary")!;
|
||||
const data = await executeSealTool(tool, client, queryParams, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// GET /v1/approval-runs/stats
|
||||
if (method === "GET" && pathname === "/v1/approval-runs/stats") {
|
||||
const corpId = extractCorpId(req, url, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_approval_runs_stats")!;
|
||||
const data = await executeSealTool(tool, client, queryParams, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// GET /v1/approval-runs/pick
|
||||
if (method === "GET" && pathname === "/v1/approval-runs/pick") {
|
||||
const corpId = extractCorpId(req, url, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_approval_run_pick")!;
|
||||
const data = await executeSealTool(tool, client, queryParams, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// GET /v1/approval-runs/url
|
||||
if (method === "GET" && pathname === "/v1/approval-runs/url") {
|
||||
const corpId = extractCorpId(req, url, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_approval_run_url_get")!;
|
||||
const data = await executeSealTool(tool, client, queryParams, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// GET /v1/approval-runs/:recordId/*
|
||||
if (pathname.startsWith("/v1/approval-runs/")) {
|
||||
const parts = pathname.slice("/v1/approval-runs/".length).split("/");
|
||||
const recordId = parts[0];
|
||||
const sub = parts[1];
|
||||
|
||||
if (recordId && !["summary", "pick", "stats", "url", "bridge"].includes(recordId)) {
|
||||
const corpId = extractCorpId(req, url, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
|
||||
if (!sub) {
|
||||
const tool = findSealTool("seal_approval_run_get")!;
|
||||
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (sub === "attachments") {
|
||||
const tool = findSealTool("seal_approval_run_attachments_get")!;
|
||||
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (sub === "cited-rules") {
|
||||
const tool = findSealTool("seal_approval_run_cited_rules_get")!;
|
||||
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (sub === "document-summary") {
|
||||
const tool = findSealTool("seal_approval_run_document_summary_get")!;
|
||||
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
if (sub === "result") {
|
||||
const tool = findSealTool("seal_approval_run_result_get")!;
|
||||
const data = await executeSealTool(tool, client, { recordId, ...queryParams }, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GET /v1/approval-runs
|
||||
if (method === "GET" && pathname === "/v1/approval-runs") {
|
||||
const corpId = extractCorpId(req, url, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_approval_runs_search")!;
|
||||
const data = await executeSealTool(
|
||||
tool,
|
||||
client,
|
||||
{
|
||||
...queryParams,
|
||||
limit: queryParams.limit ? Number(queryParams.limit) : undefined,
|
||||
offset: queryParams.offset ? Number(queryParams.offset) : undefined,
|
||||
includeBridge: queryParams.includeBridge === "true"
|
||||
},
|
||||
corp
|
||||
);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// GET /v1/approval/rules
|
||||
if (method === "GET" && pathname === "/v1/approval/rules") {
|
||||
const corpId = extractCorpId(req, url, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_approval_rules_list")!;
|
||||
const data = await executeSealTool(tool, client, queryParams, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// GET /v1/simulation/batches
|
||||
if (method === "GET" && pathname === "/v1/simulation/batches") {
|
||||
const corpId = extractCorpId(req, url, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_simulation_batches_list")!;
|
||||
const data = await executeSealTool(tool, client, queryParams, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// POST /v1/simulation/create-batch
|
||||
if (method === "POST" && pathname === "/v1/simulation/create-batch") {
|
||||
const body = (await parseJsonBody(req)) || {};
|
||||
const corpId = extractCorpId(req, url, body);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_simulation_batch_create")!;
|
||||
const data = await executeSealTool(tool, client, body, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// GET /v1/simulation/batch/:batchId
|
||||
if (method === "GET" && pathname.startsWith("/v1/simulation/batch/")) {
|
||||
const parts = pathname.slice("/v1/simulation/batch/".length).split("/");
|
||||
const batchId = parts[0];
|
||||
if (batchId) {
|
||||
const corpId = extractCorpId(req, url, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_simulation_batch_get")!;
|
||||
const data = await executeSealTool(tool, client, { batchId }, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// GET /v1/preferences
|
||||
if (method === "GET" && pathname === "/v1/preferences") {
|
||||
const corpId = extractCorpId(req, url, queryParams);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_preference_get")!;
|
||||
const data = await executeSealTool(tool, client, {}, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// POST /v1/preferences/decision
|
||||
if (method === "POST" && pathname === "/v1/preferences/decision") {
|
||||
const body = (await parseJsonBody(req)) || {};
|
||||
const corpId = extractCorpId(req, url, body);
|
||||
const corp = selectCorp(corpId);
|
||||
const client = await createSealClient(corp);
|
||||
const tool = findSealTool("seal_preference_decision_update")!;
|
||||
const data = await executeSealTool(tool, client, body, corp);
|
||||
sendJson(res, 200, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function extractCorpId(
|
||||
req: IncomingMessage,
|
||||
url: URL,
|
||||
body?: Record<string, unknown>
|
||||
): string | undefined {
|
||||
const header = req.headers["x-seal-corp"];
|
||||
if (typeof header === "string" && header.trim()) return header.trim();
|
||||
const query = url.searchParams.get("corp");
|
||||
if (query?.trim()) return query.trim();
|
||||
if (body && typeof body.corp === "string" && body.corp.trim()) {
|
||||
return body.corp.trim();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export async function parseJsonBody(req: IncomingMessage): Promise<Record<string, unknown>> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let raw = "";
|
||||
req.on("data", (chunk) => {
|
||||
raw += chunk;
|
||||
if (raw.length > 20 * 1024 * 1024) {
|
||||
// 20MB limit
|
||||
reject(new Error("Payload too large"));
|
||||
}
|
||||
});
|
||||
req.on("end", () => {
|
||||
if (!raw.trim()) {
|
||||
resolve({});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
resolve(JSON.parse(raw));
|
||||
} catch (err) {
|
||||
reject(new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`));
|
||||
}
|
||||
});
|
||||
req.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
export function sendJson(res: ServerResponse, statusCode: number, data: unknown) {
|
||||
const json = JSON.stringify(data, null, 2);
|
||||
res.writeHead(statusCode, {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Content-Length": Buffer.byteLength(json)
|
||||
});
|
||||
res.end(json);
|
||||
}
|
||||
|
||||
export function sendHtml(res: ServerResponse, statusCode: number, html: string) {
|
||||
res.writeHead(statusCode, {
|
||||
"Content-Type": "text/html; charset=utf-8",
|
||||
"Content-Length": Buffer.byteLength(html)
|
||||
});
|
||||
res.end(html);
|
||||
}
|
||||
|
||||
export function sendError(res: ServerResponse, statusCode: number, message: string, details?: unknown) {
|
||||
sendJson(res, statusCode, {
|
||||
error: true,
|
||||
statusCode,
|
||||
message,
|
||||
...(details !== undefined ? { details } : {})
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, test, afterAll, beforeAll } from "bun:test";
|
||||
import type { Server } from "node:http";
|
||||
import { startHttpServer } from "./server.js";
|
||||
|
||||
describe("HTTP Server", () => {
|
||||
let server: Server;
|
||||
const testPort = 18787;
|
||||
const baseUrl = `http://127.0.0.1:${testPort}`;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await startHttpServer({ port: testPort, host: "127.0.0.1", silent: true });
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
test("GET / returns service overview and CORS headers", async () => {
|
||||
const res = await fetch(`${baseUrl}/`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("access-control-allow-origin")).toBe("*");
|
||||
const json = (await res.json()) as any;
|
||||
expect(json.name).toBe("seal-home");
|
||||
expect(json.docs).toBe("/docs");
|
||||
expect(json.openapi).toBe("/openapi.json");
|
||||
expect(json.health).toBe("/health");
|
||||
});
|
||||
|
||||
test("GET /health returns status ok", async () => {
|
||||
const res = await fetch(`${baseUrl}/health`);
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as any;
|
||||
expect(json.status).toBe("ok");
|
||||
expect(json.name).toBe("seal-home");
|
||||
});
|
||||
|
||||
test("GET /openapi.json returns valid OpenAPI 3.1 schema", async () => {
|
||||
const res = await fetch(`${baseUrl}/openapi.json`);
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as any;
|
||||
expect(json.openapi).toBe("3.1.0");
|
||||
expect(json.info.title).toBe("seal-home Wrapped API");
|
||||
});
|
||||
|
||||
test("GET /docs returns HTML API reference page", async () => {
|
||||
const res = await fetch(`${baseUrl}/docs`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toContain("text/html");
|
||||
const html = await res.text();
|
||||
expect(html).toContain("<html");
|
||||
expect(html).toContain("api-reference");
|
||||
});
|
||||
|
||||
test("POST /api/cli executes seal-home commands", async () => {
|
||||
const res = await fetch(`${baseUrl}/api/cli`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ command: "version" })
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as any;
|
||||
expect(json.success).toBe(true);
|
||||
expect(json.exitCode).toBe(0);
|
||||
expect(json.data.name).toBe("seal-home");
|
||||
});
|
||||
|
||||
test("GET /v1/corps returns enterprise list", async () => {
|
||||
const res = await fetch(`${baseUrl}/v1/corps`);
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as any;
|
||||
expect(json).toHaveProperty("count");
|
||||
expect(Array.isArray(json.corps)).toBe(true);
|
||||
});
|
||||
|
||||
test("OPTIONS / handles CORS preflight", async () => {
|
||||
const res = await fetch(`${baseUrl}/v1/corps`, { method: "OPTIONS" });
|
||||
expect(res.status).toBe(204);
|
||||
expect(res.headers.get("access-control-allow-methods")).toContain("GET");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { createServer, type Server } from "node:http";
|
||||
import { handleHttpRequest } from "./routes.js";
|
||||
import { VERSION } from "../version.js";
|
||||
|
||||
export type HttpServerOptions = {
|
||||
port?: number;
|
||||
host?: string;
|
||||
silent?: boolean;
|
||||
};
|
||||
|
||||
export async function startHttpServer(options: HttpServerOptions = {}): Promise<Server> {
|
||||
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : 8787);
|
||||
const host = options.host ?? (process.env.HOST ? process.env.HOST : "127.0.0.1");
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
await handleHttpRequest(req, res);
|
||||
} catch (err) {
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(500, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: true, message: err instanceof Error ? err.message : String(err) }));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
server.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
|
||||
server.listen(port, host, () => {
|
||||
if (!options.silent) {
|
||||
console.error(`\n🚀 seal-home HTTP Server (v${VERSION}) started`);
|
||||
console.error(` URL: http://${host}:${port}`);
|
||||
console.error(` Docs: http://${host}:${port}/docs`);
|
||||
console.error(` OpenAPI: http://${host}:${port}/openapi.json`);
|
||||
console.error(` CLI Exec: POST http://${host}:${port}/api/cli`);
|
||||
console.error(` REST API: http://${host}:${port}/v1/...\n`);
|
||||
}
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user