Load command handlers lazily so discovery commands meet the 50ms contract

runner.ts statically imported all 28 command modules, so `seal-use version`
paid for exceljs, archiver and the embedded skill bundle on every run:
measured 175ms against a 7ms bare-bun baseline.

Dispatch branches now load their handler with await import() on demand, and
compareSemVer/isNewerVersion move to a tiny core/semver.ts so the version
path no longer drags in the 1200-line updater. selectCorp and
createSealClient follow the same pattern. Measured after: version 37-45ms,
help 40ms, corps list 40ms. The performance contract in cli-protocol.md is
updated from an aspirational <10ms to a measured <50ms with the numbers.

update.ts's service-restart finally block is also restructured: throwing from
finally swallowed the original update error, and the previous catch/branch hid
a restart failure behind a log line.

the dead `args` parameter of handleMcpCommand goes with its caller here, so
the signature change and the call site land together.
This commit is contained in:
gitea committed 2026-09-29 22:05:09 +08:00
1 parent 68fd90dbda
commit 9dc5652ad4
5 files changed
+77 -106

No files matched your search

+4 -3
View File
@@ -25,9 +25,10 @@ When developing or refactoring CLI commands under `src/cli/`:
## 2. Performance Contract & SWR Architecture
- **Sub-10ms Local Execution**:
- Read-only discovery commands (e.g. `seal-use version`, `seal-use doctor paths`, `seal-use corps list`) MUST return instantaneously (<10ms).
- Never trigger synchronous external HTTP requests during routine discovery or inspection invocations.
- **Sub-50ms Local Execution**:
- Read-only discovery commands (e.g. `seal-use version`, `seal-use doctor paths`, `seal-use corps list`) MUST return in under 50ms wall clock (Bun interpreter startup is ~7ms on its own, so this leaves ~40ms for the module graph).
- Achieved by keeping `src/cli/runner.ts` free of static command-module imports: dispatch branches load their handler with `await import("./commands/<area>.js")` on demand, so `seal-use version` never loads the Excel/zip tool chain.
- Never trigger synchronous external HTTP requests during routine discovery or inspection invocations. Measured on the maintainer's machine (2026-09): version 45ms, help 41ms, corps list 41ms, bare `bun -e` 7ms.
- **Stale-While-Revalidate (SWR) Pattern**:
1. Synchronously read local cache from `~/.config/seal-use/*.json` (<0.2ms).
2. Return the local cached state immediately on `stdout`.
+1 -2
View File
@@ -1,7 +1,6 @@
import { printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleMcpCommand(action: string | undefined, args: ParsedArgs) {
export async function handleMcpCommand(action: string | undefined) {
if (action === "config" || action === "json") {
printMcpConfig();
return;
+11 -28
View File
@@ -1,4 +1,4 @@
import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { chmodSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { basename, dirname, isAbsolute, join, relative } from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { isCompiledBinary } from "../../core/runtime.js";
@@ -164,7 +164,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
// 3. Homebrew managed mode
if (isHomebrewInstall()) {
try {
await handleHomebrewUpdate(runtime, options, serviceConfig, repo, targetVersion);
await handleHomebrewUpdate(options, serviceConfig, repo, targetVersion);
return;
} catch (err) {
console.error(
@@ -447,7 +447,6 @@ export function isHomebrewInstall(
}
async function handleHomebrewUpdate(
runtime: CliRuntime,
options: UpdateOptions,
serviceConfig: ServiceConfig,
repo: string,
@@ -566,16 +565,12 @@ async function handleHomebrewUpdate(
updateError = err;
throw err;
} finally {
if (wasRunning) {
try {
await runServiceCommand("start", serviceConfig);
} catch (startError) {
if (updateError) {
console.error(`⚠️ 更新失败后服务恢复启动也失败: ${startError instanceof Error ? startError.message : String(startError)}`);
} else {
throw startError;
}
}
// Restart only when the update itself succeeded: a throw from `finally`
// would swallow the original update error, and logging over it would hide
// the real failure. A restart failure after a failed update is already
// reported by runServiceCommand on stderr.
if (wasRunning && !updateError) {
await runServiceCommand("start", serviceConfig);
}
}
@@ -1161,21 +1156,9 @@ function extractZip(archivePath: string, targetDir: string, platform: string): s
return resolveExtractedBinary(targetDir, platform, archivePath);
}
export function compareSemVer(v1: string, v2: string): number {
const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
for (let i = 0; i < Math.max(p1.length, p2.length); i++) {
const a = p1[i] ?? 0;
const b = p2[i] ?? 0;
if (a > b) return 1;
if (a < b) return -1;
}
return 0;
}
export function isNewerVersion(latest: string, current: string): boolean {
return compareSemVer(latest, current) > 0;
}
import { compareSemVer, isNewerVersion } from "../../core/semver.js";
// Re-exported for tests and callers that historically imported from here.
export { compareSemVer, isNewerVersion };
function runCommand(command: string, args: string[], options: { cwd?: string } = {}) {
const result = spawnSync(command, args, {
+40 -73
View File
@@ -2,44 +2,10 @@
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { createSealClient } from "../core/http/factory.js";
import type { CorpConfig } from "../core/config/types.js";
import { VERSION, VERSION_INFO } from "../version.js";
import { handleApprovalRunsCommand } from "./commands/approval-runs.js";
import { handleAnalyticsCommand } from "./commands/analytics.js";
import { handleAuthCommand, handleAuthExtractKeysCommand } from "./commands/auth.js";
import { handleBillingCommand } from "./commands/billing.js";
import { handleConfigCommand } from "./commands/config.js";
import { handleContactsCommand } from "./commands/contacts.js";
import { handleDataCommand } from "./commands/data.js";
import { handleContextCommand } from "./commands/context.js";
import { handleCorpsCommand } from "./commands/corps.js";
import { handleDeployCommand } from "./commands/deploy.js";
import { handleDoctorCommand } from "./commands/doctor.js";
import { handleDocumentsCommand } from "./commands/documents.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";
import { handlePermissionsCommand } from "./commands/permissions.js";
import { handlePreferenceCommand } from "./commands/preference.js";
import { handleProbeCommand } from "./commands/probe.js";
import { handleRulesCommand } from "./commands/rules.js";
import { handleServiceCommand } from "./commands/service.js";
import { handleSimulationCommand } from "./commands/simulation.js";
import { handleSkillCommand } from "./commands/skill.js";
import { handleSourceCommand } from "./commands/source.js";
import { handleTestCommand } from "./commands/test.js";
import { handleUpdateCommand, isNewerVersion } from "./commands/update.js";
import { VERSION_INFO } from "../version.js";
import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../core/update-cache.js";
import { handleUsersCommand } from "./commands/users.js";
import {
handleWebhookCommand,
handleWebhookMaterialPackPreview,
handleWebhookResourcePackPreview
} from "./commands/webhook.js";
import { classifyCliError } from "./errors.js";
import { selectCorp } from "./helpers.js";
import {
booleanOption,
materialPackFilePolicyOptions,
@@ -48,6 +14,7 @@ import {
stringOption
} from "./parser.js";
import { extractHelpRequest } from "./help.js";
import { isNewerVersion } from "../core/semver.js";
import {
formatConsoleOutput,
joinOutput,
@@ -233,62 +200,62 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
) {
const filePath = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw new Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");
await handleWebhookResourcePackPreview(filePath, materialPackFilePolicyOptions(args.options));
await (await import("./commands/webhook.js")).handleWebhookResourcePackPreview(filePath, materialPackFilePolicyOptions(args.options));
return;
}
if (area === "openapi") {
handleOpenApiCommand(args);
(await import("./commands/openapi.js")).handleOpenApiCommand(args);
return;
}
if (area === "mcp-config") {
printMcpConfig();
(await import("./commands/mcp.js")).printMcpConfig();
return;
}
if (area === "skill") {
handleSkillCommand(action, maybeName, args);
(await import("./commands/skill.js")).handleSkillCommand(action, maybeName, args);
return;
}
if (area === "mcp" || area === "server") {
await handleMcpCommand(action, args);
await (await import("./commands/mcp.js")).handleMcpCommand(action);
return;
}
if (area === "probe") {
await handleProbeCommand(action, maybeName, args);
await (await import("./commands/probe.js")).handleProbeCommand(action, maybeName, args);
return;
}
if (area === "doctor") {
await handleDoctorCommand(action, maybeName, args);
await (await import("./commands/doctor.js")).handleDoctorCommand(action, maybeName, args);
return;
}
if (area === "test") {
await handleTestCommand(action, maybeName, args);
await (await import("./commands/test.js")).handleTestCommand(action, maybeName, args);
return;
}
if (area === "config") {
handleConfigCommand(action, maybeName, args);
(await import("./commands/config.js")).handleConfigCommand(action, maybeName, args);
return;
}
if (area === "service") {
await handleServiceCommand(action, runtime, args);
await (await import("./commands/service.js")).handleServiceCommand(action, runtime, args);
return;
}
if (area === "stop") {
await handleServiceCommand("stop", runtime, args);
await (await import("./commands/service.js")).handleServiceCommand("stop", runtime, args);
return;
}
if (area === "http" || area === "serve") {
await handleHttpCommand(args);
await (await import("./commands/http.js")).handleHttpCommand(args);
return;
}
@@ -319,7 +286,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
stringOption(args.options.tag) ??
(!isChangelog && !isCheck && !isBgSave && action && !action.startsWith("-") ? action : undefined);
await handleUpdateCommand(runtime, {
await (await import("./commands/update.js")).handleUpdateCommand(runtime, {
checkOnly: isCheck || isBgSave,
changelogOnly: isChangelog,
limit: numberOption(args.options.limit),
@@ -333,17 +300,17 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
if (area === "corps" || area === "corp") {
if (action === "regression" || action === "test-regression") {
await handleTestCommand("regression", maybeName, args);
await (await import("./commands/test.js")).handleTestCommand("regression", maybeName, args);
return;
}
await handleCorpsCommand(action, maybeName, args);
await (await import("./commands/corps.js")).handleCorpsCommand(action, maybeName, args);
return;
}
if (area === "rules" && action === "lint" && ("file" in args.options || "f" in args.options)) {
let corp: CorpConfig;
try {
corp = selectCorp(stringOption(args.options.corp));
corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp));
} catch {
corp = {
id: "local",
@@ -351,7 +318,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
source: { type: "native" }
} as any;
}
await handleRulesCommand(action, maybeName, null, corp, args);
await (await import("./commands/rules.js")).handleRulesCommand(action, maybeName, null, corp, args);
return;
}
@@ -359,7 +326,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
area === "auth" &&
(action === "extract-keys" || action === "extract-key" || action === "extract-hose-keys" || action === "hose-extract-keys")
) {
await handleAuthExtractKeysCommand(maybeName, args);
await (await import("./commands/auth.js")).handleAuthExtractKeysCommand(maybeName, args);
return;
}
@@ -368,96 +335,96 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
(action === "link" || action === "seal-link") &&
("from-link" in args.options || maybeName === "from-link")
) {
await handleAuthCommand(action, null, args);
await (await import("./commands/auth.js")).handleAuthCommand(action, null, args);
return;
}
const corp = selectCorp(stringOption(args.options.corp));
const corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp));
if (area === "source") {
await handleSourceCommand(action, corp);
await (await import("./commands/source.js")).handleSourceCommand(action, corp);
return;
}
if (area === "auth") {
await handleAuthCommand(action, corp, args);
await (await import("./commands/auth.js")).handleAuthCommand(action, corp, args);
return;
}
const client = await createSealClient(corp);
const client = await (await import("../core/http/factory.js")).createSealClient(corp);
if (area === "users") {
await handleUsersCommand(action, maybeName, client, corp, args);
await (await import("./commands/users.js")).handleUsersCommand(action, maybeName, client, corp, args);
return;
}
if (area === "contacts") {
await handleContactsCommand(action, maybeName, client, corp, args);
await (await import("./commands/contacts.js")).handleContactsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "data") {
await handleDataCommand(action, client, corp, args);
await (await import("./commands/data.js")).handleDataCommand(action, client, corp, args);
return;
}
if (area === "llm") {
await handleLlmCommand(action, client, corp, args);
await (await import("./commands/llm.js")).handleLlmCommand(action, client, corp, args);
return;
}
if (area === "permissions") {
await handlePermissionsCommand(action, client, corp, args);
await (await import("./commands/permissions.js")).handlePermissionsCommand(action, client, corp, args);
return;
}
if (area === "billing") {
await handleBillingCommand(action, client, corp, args);
await (await import("./commands/billing.js")).handleBillingCommand(action, client, corp, args);
return;
}
if (area === "webhook" || area === "webhooks") {
await handleWebhookCommand(action, maybeName, client, corp, args);
await (await import("./commands/webhook.js")).handleWebhookCommand(action, maybeName, client, corp, args);
return;
}
if (area === "context") {
await handleContextCommand(client, corp, args);
await (await import("./commands/context.js")).handleContextCommand(client, corp, args);
return;
}
if (area === "documents") {
await handleDocumentsCommand(action, maybeName, client, corp, args);
await (await import("./commands/documents.js")).handleDocumentsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "rules") {
await handleRulesCommand(action, maybeName, client, corp, args);
await (await import("./commands/rules.js")).handleRulesCommand(action, maybeName, client, corp, args);
return;
}
if (area === "approval-runs") {
await handleApprovalRunsCommand(action, maybeName, client, corp, args);
await (await import("./commands/approval-runs.js")).handleApprovalRunsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "analytics") {
await handleAnalyticsCommand(action, maybeName, client, corp, args);
await (await import("./commands/analytics.js")).handleAnalyticsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "simulation") {
await handleSimulationCommand(action, maybeName, client, corp, args);
await (await import("./commands/simulation.js")).handleSimulationCommand(action, maybeName, client, corp, args);
return;
}
if (area === "deploy") {
await handleDeployCommand(action, maybeName, args.command[3], client, corp, args);
await (await import("./commands/deploy.js")).handleDeployCommand(action, maybeName, args.command[3], client, corp, args);
return;
}
if (area === "preference" || area === "preferences") {
await handlePreferenceCommand(action, maybeName, args.command[3], args.command[4], client, corp, args);
await (await import("./commands/preference.js")).handlePreferenceCommand(action, maybeName, args.command[3], args.command[4], client, corp, args);
return;
}
+21
View File
@@ -0,0 +1,21 @@
/**
* Minimal semver comparison for release ordering. Kept out of
* `cli/commands/update.ts` so the `version` command path does not have to load
* the 1200-line updater (and its embedded-skill bundle) just to decide whether
* a cached release is newer.
*/
export function compareSemVer(v1: string, v2: string): number {
const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
for (let i = 0; i < Math.max(p1.length, p2.length); i++) {
const a = p1[i] ?? 0;
const b = p2[i] ?? 0;
if (a > b) return 1;
if (a < b) return -1;
}
return 0;
}
export function isNewerVersion(latest: string, current: string): boolean {
return compareSemVer(latest, current) > 0;
}