Merge pull request #188 from yunyingk/codex/tech-debt-windows-old-and-tool-validation

Fix tech debt: update leftovers, tool param validation, stdout and docs contracts
This commit is contained in:
yunyingk authored and GitHub committed 2026-09-30 01:21:17 +08:00
commit 3d5f36fe4b
20 files changed
+765 -74

No files matched your search

+18 -15
View File
@@ -39,7 +39,7 @@ After installation:
seal-use version # Check version seal-use version # Check version
seal-use skill install # Install Agent skill to ~/.agents/skills/seal-use seal-use skill install # Install Agent skill to ~/.agents/skills/seal-use
seal-use mcp-config # Print an MCP server snippet (for Cursor / Claude Desktop / Codex) seal-use mcp-config # Print an MCP server snippet (for Cursor / Claude Desktop / Codex)
seal-use update # Future self-update directly from GitHub Release seal-use update # Self-update (GitHub Releases binary, Homebrew, or source)
``` ```
## Source Setup & Development ## Source Setup & Development
@@ -81,7 +81,7 @@ Create a user-level Hose enterprise config that works from any directory:
mkdir -p ~/.config/seal-use/enterprises mkdir -p ~/.config/seal-use/enterprises
seal-use corps add-hose-persistent --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' seal-use corps add-hose-persistent --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use auth diagnose --corp <corpId> seal-use auth diagnose --corp <corpId>
seal-use tools list seal-use corps list
``` ```
`corps add-hose-persistent` verifies by default before writing the config. It uses the Hose OpenAPI credential response to derive the corporation ID, then checks provisional auth, Seal SSO, and Seal `whoami`. Pass `"force":true` or `"verify":false` only when you intentionally want to write a config that may fail later. `corps add-hose-persistent` verifies by default before writing the config. It uses the Hose OpenAPI credential response to derive the corporation ID, then checks provisional auth, Seal SSO, and Seal `whoami`. Pass `"force":true` or `"verify":false` only when you intentionally want to write a config that may fail later.
@@ -129,7 +129,7 @@ Update an existing checkout:
seal-use update seal-use update
``` ```
`seal-use update` runs `git pull --ff-only`, installs dependencies, and restarts the local service if it was running. `seal-use update` adapts to how it was installed: from a source checkout it runs `git pull --ff-only` and refreshes dependencies with `bun install`; a standalone binary downloads the matching GitHub Release asset and replaces itself; a Homebrew install upgrades through `brew upgrade seal-use`. Each mode stops the local service while updating and starts it again on success if one was running.
Because `npm link` makes the global command a symlink into your checkout, **updating the checkout is sufficient** — no reinstall step required. The symlink continues to point to the updated source. Because `npm link` makes the global command a symlink into your checkout, **updating the checkout is sufficient** — no reinstall step required. The symlink continues to point to the updated source.
@@ -144,7 +144,7 @@ The canonical plugin skill lives at `skills/seal-use`. There is no in-repo `.age
## ZCode Plugin ## ZCode Plugin
The repository is also a ZCode plugin. Install `seal-use` from the `yingqing-plugins` marketplace in **Settings → Plugin Management**, or add this repository as a local plugin directory while developing. The plugin ships the `skills/seal-use` skill; it has no MCP surface — use `seal-use mcp` (or the `mcp-config` snippet) if you want MCP locally. The repository is also a ZCode plugin. Install `seal-use` from the `yingqing-plugins` marketplace in **Settings → Plugin Management**, or add this repository as a local plugin directory while developing. The plugin ships the `skills/seal-use` skill; it has no MCP surface. For MCP locally, paste the snippet from `seal-use mcp-config` into your host — it starts `seal-use mcp` with `SEAL_USE_MCP_ENABLED=true`, which the server needs before it exposes any tool.
The plugin exposes no MCP tools. The `seal_cli` / `seal_cli_write` tools exist only on the local MCP server started by `seal-use mcp` (or by whatever host consumes the `mcp-config` snippet), where they accept the same command syntax as the global CLI. The plugin exposes no MCP tools. The `seal_cli` / `seal_cli_write` tools exist only on the local MCP server started by `seal-use mcp` (or by whatever host consumes the `mcp-config` snippet), where they accept the same command syntax as the global CLI.
@@ -157,7 +157,7 @@ bun run build:binary
## CLI ## CLI
Use the CLI from skills, shell scripts, or agents. CLI intentionally keeps the full fine-grained tool list available through `seal-use tool <toolName>`. Use the CLI from skills, shell scripts, or agents. Domain commands such as `seal-use approval-runs ...`, `seal-use rules ...`, and `seal-use documents ...` wrap the shared tool registry, so the CLI, the HTTP adapter, and the MCP server all end up running the same tool handler with the same validation.
```bash ```bash
seal-use version seal-use version
@@ -165,11 +165,9 @@ seal-use config paths
seal-use config get seal-use config get
seal-use config mode stateless seal-use config mode stateless
seal-use config mode stateful --corp <corpId> seal-use config mode stateful --corp <corpId>
seal-use tools list
seal-use corps list seal-use corps list
seal-use auth diagnose --corp <corpId> seal-use auth diagnose --corp <corpId>
seal-use approval-runs summary --corp <corpId> --date 2026-06-08 --timezone Asia/Shanghai seal-use approval-runs summary --corp <corpId> --date 2026-06-08 --timezone Asia/Shanghai
seal-use tool seal_approval_runs_summary --corp <corpId> --json '{"date":"2026-06-08","timezone":"Asia/Shanghai"}'
``` ```
CLI output is JSON on stdout. Errors are written to stderr. CLI output is JSON on stdout. Errors are written to stderr.
@@ -177,8 +175,8 @@ CLI output is JSON on stdout. Errors are written to stderr.
Enterprise config lookup: Enterprise config lookup:
- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded. - If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.
- Otherwise `./enterprises` and `~/.config/seal-use/enterprises` are merged. - Otherwise the test directory (`seal-use config test-dir`) and `~/.config/seal-use/enterprises` are merged; a `./enterprises` folder in the working directory is **not** read unless an env var points at it.
- User-level configs override same-ID configs from `./enterprises`. - A user-level config overrides a same-ID config from the test directory.
Global enterprise selection is stateless by default. Its configuration is stored in Global enterprise selection is stateless by default. Its configuration is stored in
`~/.config/seal-use/config.json` (override with `SEAL_USE_CONFIG_FILE`). In stateless mode, `~/.config/seal-use/config.json` (override with `SEAL_USE_CONFIG_FILE`). In stateless mode,
@@ -191,7 +189,7 @@ Use `seal-use auth diagnose --corp <corpId>` when login fails in stateless mode.
## Wrapped API Documentation ## Wrapped API Documentation
The OpenAPI source under `openapi/` describes the planned HTTP contract for a seal-use wrapped API. The current implementation exposes a local MCP server over stdio (`seal-use mcp`) and does not listen on the OpenAPI server URL. It is intentionally not the raw downstream Seal API: endpoints are named around seal-use concepts such as corps, auth diagnosis, approval context, run summaries, document URLs, and Langfuse bridge hints. The OpenAPI source under `openapi/` describes the HTTP contract for the seal-use wrapped API, and the local HTTP adapter serves it live: `GET /openapi.json` returns the bundled contract and `GET /docs` serves an interactive reference, so the document is not merely aspirational. Each operation carries `x-implementation-status` — `implemented` operations are routed by `src/http/routes.ts` today (a test fails if one has no matching route), while `planned` ones are contract-only and return 404 until they are built. It is intentionally not the raw downstream Seal API: endpoints are named around seal-use concepts such as corps, auth diagnosis, approval context, run summaries, document URLs, and Langfuse bridge hints.
Source files are split by domain: Source files are split by domain:
@@ -225,7 +223,7 @@ Service state is stored under `~/.config/seal-use/`:
- `service.pid` - `service.pid`
- `service.log` - `service.log`
The service is intentionally local and currently acts as a lifecycle wrapper for a long-lived stdio/MCP process; it does not expose the HTTP/OpenAPI contract. It is useful as a stable process lifecycle for future warmed caches and update/restart workflows; normal CLI commands still work without it. The service is intentionally local: `service start` runs the same HTTP adapter as `seal-use http` in the background, serving `/docs`, `/openapi.json`, `POST /api/cli`, `POST /api/tool/:name`, `/v1/*`, and `/shutdown` on `127.0.0.1:8787` (loopback by default). It is useful as a stable process lifecycle for update/restart workflows and as a base URL for a local frontend; normal CLI commands still work without it.
## Enterprise Config ## Enterprise Config
@@ -257,7 +255,12 @@ The service is intentionally local and currently acts as a lifecycle wrapper for
Most users do not need MCP. The public/shared path is the global `seal-use` CLI plus the optional local service. Most users do not need MCP. The public/shared path is the global `seal-use` CLI plus the optional local service.
The MCP server advertises exactly one tool, `seal_cli`: The MCP server exposes two tools — and only when `SEAL_USE_MCP_ENABLED=true`, which is what the `seal-use mcp-config` snippet carries; without that flag `tools/list` answers with an empty list:
- `seal_cli` runs read-only commands and refuses anything that mutates tenant state, self-updates, or starts a server.
- `seal_cli_write` runs the same dispatcher with mutating commands available; confirm the exact command with the user before calling it.
Both take the command as a string:
```json ```json
{ {
@@ -265,11 +268,11 @@ The MCP server advertises exactly one tool, `seal_cli`:
} }
``` ```
It runs the same CLI dispatcher as the global binary, so read operations, write operations, `config`, `service`, and `update` remain available. Write-operation confirmations and explicit enterprise-ID rules continue to be defined by this skill. Both run the same CLI dispatcher as the global binary, so `config`, `service`, and `update` behave exactly as they do on the command line. Write-operation confirmations and explicit enterprise-ID rules continue to be defined by this skill.
## CLI-First Architecture ## CLI-First Architecture
All Agent and automation capabilities are accessed through standard `seal-use <command>` CLI invocations (or through the single `seal_cli` MCP tool passing the command string). Internal domain services output pure, parseable JSON on `stdout`, with human diagnostics and suggestions routed to `stderr`. All Agent and automation capabilities are accessed through standard `seal-use <command>` CLI invocations (or through the `seal_cli` / `seal_cli_write` MCP tools passing the command string). Internal domain services output pure, parseable JSON on `stdout`, with human diagnostics and suggestions routed to `stderr`.
Key CLI command groups: Key CLI command groups:
- **`seal-use corps ...`**: enterprise tenant management, onboarding, switching, and assistance link intake. - **`seal-use corps ...`**: enterprise tenant management, onboarding, switching, and assistance link intake.
@@ -312,7 +315,7 @@ When `_langfuseTraceId` exists, downstream tools should fetch the trace directly
- Prefer Bun-native commands in this repository: `bun run check`, `bun test`, and `seal-use ...`. `npm run check` may work, but Bun is the project runtime and lockfile owner. - Prefer Bun-native commands in this repository: `bun run check`, `bun test`, and `seal-use ...`. `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. - 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. - 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 to the single `seal_cli` router; command knowledge belongs in this skill and its focused references. - Keep the MCP exported surface to the `seal_cli` (read-only) and `seal_cli_write` (mutating) pair; command knowledge belongs in this skill and its focused references.
- Prefer CLI or script processing for large tool responses. For daily approval questions, call `seal-use approval-runs summary --corp <corpId> ...` instead of reading long `seal_approval_runs_search` output manually. - Prefer CLI or script processing for large tool responses. For daily approval questions, call `seal-use approval-runs summary --corp <corpId> ...` 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. - 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. - When Seal API timestamp filters are uncertain, filter again in tool code by `createdAt` and explicit timezone before presenting date-based answers.
+2 -2
View File
@@ -35,8 +35,8 @@ than described here.
`seal-use service start` serve `/api/cli`, `/v1/*` and `/shutdown` on `127.0.0.1:8787` with no `seal-use service start` serve `/api/cli`, `/v1/*` and `/shutdown` on `127.0.0.1:8787` with no
token check and `Access-Control-Allow-Origin: *`; the adapter acts with the credentials already token check and `Access-Control-Allow-Origin: *`; the adapter acts with the credentials already
stored on the machine. It is a local automation surface. Keep it bound to loopback, and do not stored on the machine. It is a local automation surface. Keep it bound to loopback, and do not
run it on a shared or multi-user host. See the `securitySchemes.localSession` note in run it on a shared or multi-user host. The OpenAPI document declares no security scheme — it
`openapi/openapi.yaml`. says so in `info.description` rather than advertising a header nothing checks.
- **Self-update and the install script do not verify signatures.** `seal-use update` downloads a - **Self-update and the install script do not verify signatures.** `seal-use update` downloads a
release binary and replaces the running executable; `scripts/install.sh` compares release binary and replaces the running executable; `scripts/install.sh` compares
`checksums.txt` but only warns on a mismatch. Prefer the direct GitHub source `checksums.txt` but only warns on a mismatch. Prefer the direct GitHub source
+1 -14
View File
@@ -3,7 +3,7 @@
"info": { "info": {
"title": "seal-use Wrapped API", "title": "seal-use Wrapped API",
"version": "0.10.40", "version": "0.10.40",
"description": "HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n" "description": "HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n\nAuthentication: none. The adapter answers every request with the enterprise credentials already\nstored on this machine, and never checks who is calling — so keep it on loopback (the default)\nand never expose the port to a network or an origin you do not control. The full trust model is\nin SECURITY.md, \"Trust model and documented limitations\".\n"
}, },
"servers": [ "servers": [
{ {
@@ -11,11 +11,6 @@
"description": "Local HTTP adapter (`seal-use http`, or the `seal-use service start` daemon). Loopback-only by default." "description": "Local HTTP adapter (`seal-use http`, or the `seal-use service start` daemon). Loopback-only by default."
} }
], ],
"security": [
{
"localSession": []
}
],
"tags": [ "tags": [
{ {
"name": "Corps", "name": "Corps",
@@ -2777,14 +2772,6 @@
} }
}, },
"components": { "components": {
"securitySchemes": {
"localSession": {
"type": "apiKey",
"in": "header",
"name": "X-Seal-Home-Session",
"description": "Reserved header. The local adapter does not currently authenticate requests: it acts with\nthe credentials already stored on this machine for the selected enterprise. Keep it bound\nto loopback (`--host 127.0.0.1`) and do not expose the port to a network or an origin you\ndo not control.\n"
}
},
"parameters": { "parameters": {
"CorpId": { "CorpId": {
"name": "corpId", "name": "corpId",
+5 -12
View File
@@ -19,11 +19,14 @@ info:
The same capabilities are reachable through the CLI, and through the optional MCP server when The same capabilities are reachable through the CLI, and through the optional MCP server when
it is enabled. it is enabled.
Authentication: none. The adapter answers every request with the enterprise credentials already
stored on this machine, and never checks who is calling — so keep it on loopback (the default)
and never expose the port to a network or an origin you do not control. The full trust model is
in SECURITY.md, "Trust model and documented limitations".
servers: servers:
- url: http://localhost:8787 - url: http://localhost:8787
description: Local HTTP adapter (`seal-use http`, or the `seal-use service start` daemon). Loopback-only by default. description: Local HTTP adapter (`seal-use http`, or the `seal-use service start` daemon). Loopback-only by default.
security:
- localSession: []
tags: tags:
- name: Corps - name: Corps
description: Local enterprise configuration selection. description: Local enterprise configuration selection.
@@ -40,16 +43,6 @@ tags:
paths: paths:
$ref: ./paths/index.yaml $ref: ./paths/index.yaml
components: components:
securitySchemes:
localSession:
type: apiKey
in: header
name: X-Seal-Home-Session
description: |
Reserved header. The local adapter does not currently authenticate requests: it acts with
the credentials already stored on this machine for the selected enterprise. Keep it bound
to loopback (`--host 127.0.0.1`) and do not expose the port to a network or an origin you
do not control.
parameters: parameters:
$ref: ./components/parameters.yaml $ref: ./components/parameters.yaml
responses: responses:
+3 -1
View File
@@ -1,8 +1,10 @@
import { runProbe } from "../../probe.js"; import { runProbe } from "../../probe.js";
import { stringOption } from "../parser.js"; import { stringOption } from "../parser.js";
import { printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js"; import type { ParsedArgs } from "../types.js";
export async function handleProbeCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) { export async function handleProbeCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) {
const corpId = maybeName ?? stringOption(args.options.corp) ?? (action && action !== "--corp" ? action : undefined); const corpId = maybeName ?? stringOption(args.options.corp) ?? (action && action !== "--corp" ? action : undefined);
await runProbe({ corpId }); // One JSON document on stdout; runProbe narrates progress on stderr only.
printJson(await runProbe({ corpId }));
} }
+57 -2
View File
@@ -1,8 +1,8 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { compareSemVer, getMirrorMode, isHomebrewInstall, isNewerVersion, matchAssetForPlatform } from "./update.js"; import { compareSemVer, getMirrorMode, isHomebrewInstall, isNewerVersion, matchAssetForPlatform, pruneUpdateLeftovers } from "./update.js";
type Asset = { name: string; downloadUrl: string; size: number }; type Asset = { name: string; downloadUrl: string; size: number };
@@ -72,6 +72,61 @@ describe("update skill install", () => {
}); });
}); });
describe("update leftover pruning", () => {
// Windows cannot rename-replace a running executable, so the win32 branch
// renames the live image to `<binary>.old.<ts>` and — before this helper —
// never removed it: one full binary leaked per update, forever. Cleanup can
// only happen once that image stops executing, i.e. on a later invocation.
test("removes stale .old backups but never the live binary", () => {
const dir = mkdtempSync(join(tmpdir(), "seal-use-prune-old-"));
try {
const binary = join(dir, "seal-use");
writeFileSync(binary, "current");
writeFileSync(join(dir, "seal-use.old.1727000000000"), "previous release");
writeFileSync(join(dir, "my-old-seal-use"), "unrelated file with 'old' in the name");
const removed = pruneUpdateLeftovers(binary);
expect(removed).toEqual(["seal-use.old.1727000000000"]);
expect(readFileSync(binary, "utf8")).toBe("current");
expect(readFileSync(join(dir, "my-old-seal-use"), "utf8")).toBe("unrelated file with 'old' in the name");
expect(() => statSync(join(dir, "seal-use.old.1727000000000"))).toThrow();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test("sweeps only stale staging dirs, leaving a concurrent update's alone", () => {
const dir = mkdtempSync(join(tmpdir(), "seal-use-prune-tmp-"));
try {
const binary = join(dir, "seal-use");
writeFileSync(binary, "current");
const fresh = join(dir, `.tmp-update-${Date.now()}`);
const orphan = join(dir, ".tmp-update-1727000000000");
mkdirSync(fresh, { recursive: true });
mkdirSync(orphan, { recursive: true });
writeFileSync(join(orphan, "half-downloaded.bin"), "x");
// Backdate the orphan past the one-hour safety window.
const old = new Date(Date.now() - 2 * 60 * 60 * 1000);
utimesSync(orphan, old, old);
const removed = pruneUpdateLeftovers(binary);
expect(removed).toEqual([".tmp-update-1727000000000"]);
expect(() => statSync(orphan)).toThrow();
// A staging dir this run (or a parallel update) may still be writing into.
expect(statSync(fresh).isDirectory()).toBe(true);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test("is a no-op when the binary directory cannot be read", () => {
expect(pruneUpdateLeftovers(join(tmpdir(), "does-not-exist", "seal-use"))).toEqual([]);
});
});
describe("update version comparator", () => { describe("update version comparator", () => {
test("correctly identifies newer semantic versions", () => { test("correctly identifies newer semantic versions", () => {
expect(isNewerVersion("0.7.0", "0.6.0")).toBe(true); expect(isNewerVersion("0.7.0", "0.6.0")).toBe(true);
+62 -1
View File
@@ -1,4 +1,4 @@
import { chmodSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; import { chmodSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import { basename, dirname, isAbsolute, join, relative } from "node:path"; import { basename, dirname, isAbsolute, join, relative } from "node:path";
import { spawn, spawnSync } from "node:child_process"; import { spawn, spawnSync } from "node:child_process";
import { isCompiledBinary } from "../../core/runtime.js"; import { isCompiledBinary } from "../../core/runtime.js";
@@ -177,6 +177,12 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
const platform = detectPlatform(); const platform = detectPlatform();
const arch = detectArch(); const arch = detectArch();
// Every binary-mode invocation sweeps here, not just real updates: the SWR
// background check (`update check --bg-save`) is the only command many users
// ever run after their last update, so it is what reclaims that update's
// `.old.<timestamp>` backup (undeletable while its image was executing).
pruneUpdateLeftovers(process.execPath);
const releases = await fetchGitHubReleases(repo, 30); const releases = await fetchGitHubReleases(repo, 30);
const release = targetVersion const release = targetVersion
? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ?? ? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ??
@@ -350,6 +356,61 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
} }
} }
/**
* Deletes the debris earlier self-updates left next to the installed binary.
*
* Windows cannot `renameSync`-replace a running executable, so the win32 branch
* first renames the live image to `<binary>.old.<timestamp>` and never removes
* it — one full binary (tens of MB) leaked per update. The same file is also
* undeletable *during* that update (it is the executing image), so cleanup runs
* at the start of the next update instead, when nothing holds it open. Orphaned
* `.tmp-update-<timestamp>` staging directories from an interrupted run are
* swept for the same reason.
*
* Best-effort: a locked or already-gone file is skipped, never fatal. Returns
* the entries removed so tests can assert the sweep.
*/
export function pruneUpdateLeftovers(binaryPath: string): string[] {
const dir = dirname(binaryPath);
const base = basename(binaryPath);
const removed: string[] = [];
let entries: string[];
try {
entries = readdirSync(dir);
} catch {
return removed;
}
const now = Date.now();
for (const entry of entries) {
// `<binary>.old.<anything>` (e.g. seal-use.exe.old.1727...) and the
// `.tmp-update-<ts>` staging dirs this command creates. Never the live
// binary itself: its name has no `.old.` / `tmp-update` marker.
const isStaleBackup = entry.startsWith(`${base}.old.`);
const isOrphanStaging = entry.startsWith(".tmp-update-");
if (!isStaleBackup && !isOrphanStaging) continue;
const fullPath = join(dir, entry);
try {
if (isOrphanStaging) {
// A staging dir younger than an hour may belong to an update running
// right now; deleting it out from under that download would break it.
// The `.old.` case needs no such gate: on Windows a live image cannot
// be deleted (the rm throws and is swallowed), and on POSIX no `.old.`
// file is ever written.
if (now - statSync(fullPath).mtimeMs < 60 * 60 * 1000) continue;
}
rmSync(fullPath, { recursive: true, force: true });
removed.push(entry);
} catch {
// Still locked (its owning process is alive); the next update retries.
}
}
return removed;
}
/** /**
* Installs the Agent Skill by running the newly installed binary as a child process, then reads * Installs the Agent Skill by running the newly installed binary as a child process, then reads
* the file back to prove which version actually landed. * the file back to prove which version actually landed.
+69
View File
@@ -0,0 +1,69 @@
import { describe, expect, test } from "bun:test";
import { readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { KNOWN_AREAS, UPDATE_ALIASES } from "./runner.js";
/**
* Documentation cross-check: every command a maintained doc shows a reader must
* still dispatch.
*
* The hand-written docs drifted once already — README kept documenting
* `seal-use tool <toolName>` and `seal-use tools list` for two releases after
* the dispatcher dropped both areas, and it described `./enterprises` as loaded
* when a test explicitly asserts it is not. Nothing failed, so nothing got
* fixed. This test turns the docs into a checked claim.
*
* Scope is deliberate: `CHANGELOG.md` records history (old commands belong
* there) and `docs/proposals/` is forward-looking by definition, so both are
* excluded. Commands are read from code spans (`` `seal-use area …` ``) and
* from example lines, which is where a reader would copy one from — bare prose
* like "the seal-use wrapped API" is not a command and is not matched.
*/
const REPO_ROOT = join(import.meta.dir, "..", "..");
const DOC_FILES = [
"README.md",
"AGENTS.md",
"SECURITY.md",
"skills/seal-use/SKILL.md",
...readdirSync(join(REPO_ROOT, "skills/seal-use/references")).map(
(name) => `skills/seal-use/references/${name}`
),
...readdirSync(join(REPO_ROOT, ".agents/rules")).map((name) => `.agents/rules/${name}`)
];
/**
* Names the dispatcher accepts before the `KNOWN_AREAS` gate — `seal-use help`,
* `seal-use version` — plus `v`. Everything else must be a known area; update
* spellings (`upgrade`, `self-update`, …) come from UPDATE_ALIASES.
*/
const EARLY_DISPATCH = new Set(["version", "v", "help"]);
function referencedAreas(markdown: string): Set<string> {
const found = new Set<string>();
// Inline code spans: `seal-use <area> …`
for (const match of markdown.matchAll(/`seal-use ([a-z][a-z0-9-]*)/g)) found.add(match[1]!);
// Example lines a reader would copy and paste.
for (const match of markdown.matchAll(/^\s*seal-use ([a-z][a-z0-9-]*)/gm)) found.add(match[1]!);
return found;
}
function isDispatchable(area: string): boolean {
return KNOWN_AREAS.has(area) || UPDATE_ALIASES.has(area) || EARLY_DISPATCH.has(area);
}
describe("documentation references live commands", () => {
test("every `seal-use <area>` in the maintained docs is dispatchable", () => {
const stale: Record<string, string[]> = {};
for (const file of DOC_FILES) {
const unknown = [...referencedAreas(readFileSync(join(REPO_ROOT, file), "utf8"))]
.filter((area) => !isDispatchable(area))
.sort();
if (unknown.length) stale[file] = unknown;
}
expect(stale).toEqual({});
});
});
+5 -1
View File
@@ -2,7 +2,7 @@ import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig, resolve
import { resolveCorpConfig } from "../core/config/manager.js"; import { resolveCorpConfig } from "../core/config/manager.js";
import { recordCorpUsage } from "../core/stats/usage-tracker.js"; import { recordCorpUsage } from "../core/stats/usage-tracker.js";
import { createSealClient } from "../core/http/factory.js"; import { createSealClient } from "../core/http/factory.js";
import { sealTools, type SealTool } from "../domains/seal/tools.js"; import { sealTools, parseToolParams, type SealTool } from "../domains/seal/tools.js";
import type { CorpConfig, GlobalConfig } from "../core/config/types.js"; import type { CorpConfig, GlobalConfig } from "../core/config/types.js";
import { printJson } from "./printer.js"; import { printJson } from "./printer.js";
import type { OutputOptions } from "./types.js"; import type { OutputOptions } from "./types.js";
@@ -60,6 +60,10 @@ export async function runToolResult(
const compactParams = Object.fromEntries( const compactParams = Object.fromEntries(
Object.entries(params).filter(([, value]) => value !== undefined) Object.entries(params).filter(([, value]) => value !== undefined)
); );
// Schema gate: a missing required field or an out-of-range value fails here
// with exit 13 instead of reaching the handler as `undefined` and surfacing
// as an opaque upstream error. Valid params pass through untouched.
parseToolParams(tool, compactParams);
const handler = tool.handler as SealTool["handler"]; const handler = tool.handler as SealTool["handler"];
return handler(client, compactParams as never, { corp }); return handler(client, compactParams as never, { corp });
} }
+8
View File
@@ -128,6 +128,14 @@ describe("CLI read-only classification", () => {
expect(isReadOnlyCliCommand(["openapi", "extra"])).toBe(false); expect(isReadOnlyCliCommand(["openapi", "extra"])).toBe(false);
}); });
test("probe is read-only bare or with its enterprise selector, but not beyond", () => {
// `seal-use probe [<corpId>]` takes a selector, not a verb: the allow-list
// entry covers the bare form and the selector form is matched separately.
expect(isReadOnlyCliCommand(["probe"])).toBe(true);
expect(isReadOnlyCliCommand(["probe", "corp-a"])).toBe(true);
expect(isReadOnlyCliCommand(["probe", "corp-a", "extra"])).toBe(false);
});
test("refuses command lines that cannot be parsed", () => { test("refuses command lines that cannot be parsed", () => {
expect(isReadOnlyCliCommand(["--json"])).toBe(false); expect(isReadOnlyCliCommand(["--json"])).toBe(false);
}); });
+13
View File
@@ -81,9 +81,20 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
skill: ["dump", "status"], skill: ["dump", "status"],
service: ["status", "logs"], service: ["status", "logs"],
doctor: ["", "guide", "paths", "tenant", "auth"], doctor: ["", "guide", "paths", "tenant", "auth"],
// Bare form only; the optional trailing `<corpId>` selector is handled by
// SELECTOR_POSITIONAL_AREAS below, since a bare entry matches no tokens.
probe: [""],
openapi: [""] openapi: [""]
}; };
/**
* Areas whose trailing positional is an enterprise selector, not a subcommand:
* `seal-use probe [<corpId>]` has no verb to list, so its read form is the bare
* command plus at most that one selector. A second token is not a form the area
* accepts at all, and falls through to the refusal below.
*/
const SELECTOR_POSITIONAL_AREAS = new Set(["probe"]);
/** /**
* Read-only commands handled by the CLI outside the help registry (no area/subcommand shape). * Read-only commands handled by the CLI outside the help registry (no area/subcommand shape).
* `help` is limited to the bare form on purpose: `help <topic>` adds nothing over the skill docs. * `help` is limited to the bare form on purpose: `help <topic>` adds nothing over the skill docs.
@@ -110,6 +121,8 @@ export function isReadOnlyCliCommand(argv: string[]): boolean {
} }
if (actionTokens.length === 0 && TOP_LEVEL_READ_ONLY.has(area)) return true; if (actionTokens.length === 0 && TOP_LEVEL_READ_ONLY.has(area)) return true;
// The `<corpId>` selector form; the bare form falls through to the `""` entry.
if (SELECTOR_POSITIONAL_AREAS.has(area) && actionTokens.length === 1) return true;
const allowed = READ_ONLY_COMMANDS[area]; const allowed = READ_ONLY_COMMANDS[area];
if (!allowed) return false; if (!allowed) return false;
+9 -2
View File
@@ -86,8 +86,15 @@ export const deployTools = [
name: "seal_deploy_hosecloud_configure", name: "seal_deploy_hosecloud_configure",
description: "自动探测平台并保存【Seal AI 审批发布到合思费控】集成配置", description: "自动探测平台并保存【Seal AI 审批发布到合思费控】集成配置",
parameters: z.object({ parameters: z.object({
apiKey: z.string().describe("合思 API Key (appKey)"), // Optional in the schema because the handler accepts two spellings of the
apiSecret: z.string().describe("合思 API Secret (appSecurity)"), // same credential (`apiKey`, or the legacy `appKey` alias) and enforces
// that one pair is present itself — see the check right below. Marking
// only `apiKey` required would reject `appKey` payloads the handler has
// always accepted.
apiKey: z.string().optional().describe("合思 API Key (appKey)"),
apiSecret: z.string().optional().describe("合思 API Secret (appSecurity)"),
appKey: z.string().optional().describe("apiKey 的旧写法,等价"),
appSecurity: z.string().optional().describe("apiSecret 的旧写法,等价"),
signKey: z.string().optional().describe("集成 signKey,不提供则自动生成"), signKey: z.string().optional().describe("集成 signKey,不提供则自动生成"),
outboundName: z.string().optional().describe("出站消息名称(合思审批流节点中显示)"), outboundName: z.string().optional().describe("出站消息名称(合思审批流节点中显示)"),
specificationId: z.string().optional(), specificationId: z.string().optional(),
+1
View File
@@ -10,6 +10,7 @@ import { deployTools } from "./deploy.js";
import { preferenceTools } from "./preference.js"; import { preferenceTools } from "./preference.js";
export * from "./helpers.js"; export * from "./helpers.js";
export * from "./validate.js";
export const sealTools = [ export const sealTools = [
...identityTools, ...identityTools,
+91
View File
@@ -0,0 +1,91 @@
import { describe, expect, test } from "bun:test";
import { CliError } from "../../../core/errors.js";
import { findSealTool, parseToolParams, type SealTool } from "./index.js";
function tool(name: string): SealTool {
const found = findSealTool(name);
if (!found) throw new Error(`test fixture missing tool: ${name}`);
return found;
}
/** Asserts rejection and returns the message so tests can check its wording. */
function rejectsWith(toolName: string, params: Record<string, unknown>): string {
try {
parseToolParams(tool(toolName), params);
} catch (error) {
expect(error).toBeInstanceOf(CliError);
expect((error as CliError).exitCode).toBe(13);
return (error as CliError).message;
}
throw new Error(`expected ${toolName} to reject ${JSON.stringify(params)}`);
}
describe("parseToolParams", () => {
test("accepts valid params and returns the exact object it was given", () => {
const target = tool("seal_user_create");
const params = { name: "张三", phone: "13800001111", departmentIds: ["d1"] };
// Identity matters: handlers read keys the schema does not declare, so the
// gate must pass its input through, never zod's (stripped) parse output.
expect(parseToolParams(target, params)).toBe(params);
});
test("names the missing required field instead of letting the handler crash on undefined", () => {
const message = rejectsWith("seal_user_create", { phone: "13800001111" });
expect(message).toContain("seal_user_create");
expect(message).toContain("name");
});
test("enforces the value bound a handler would otherwise silently accept", () => {
// limit is capped at 100 in the schema; nothing in the handler checks it.
const message = rejectsWith("seal_approval_runs_search", { limit: 9999 });
expect(message).toContain("limit");
});
test("coerces query-string values before checking, without touching the original", () => {
const target = tool("seal_approval_runs_search");
const params = { limit: "50", includeBridge: "true" } as Record<string, unknown>;
// /v1/* passes url.searchParams through: everything arrives as a string,
// but the schema declares z.number() / z.boolean(). Without coercion every
// REST route would 400 on its own documented query params.
expect(parseToolParams(target, params)).toBe(params);
expect(params.limit).toBe("50");
expect(params.includeBridge).toBe("true");
});
test("still rejects a string that merely looks like a wire value", () => {
const message = rejectsWith("seal_approval_runs_search", { limit: "abc" });
expect(message).toContain("limit");
});
test("coerces a comma-separated query value into the array the schema wants", () => {
// `?fields=id,code` on /v1/approval/rules: today the handler receives a
// string and pickRuleFields iterates its characters, returning empty
// objects. Validation splits it so the documented form actually works.
expect(parseToolParams(tool("seal_approval_rules_list"), { fields: "id,code" })).toEqual({
fields: "id,code"
});
expect(rejectsWith("seal_approval_rules_list", { fields: "id,not-a-field" })).toContain("fields");
});
test("ignores undeclared keys rather than rejecting the request", () => {
// z.object is non-strict: an extra HTTP body key is a compatibility
// non-event, not an error. This gate checks declared params only.
const target = tool("seal_approval_runs_search");
expect(parseToolParams(target, { status: "TERMINATED", corp: "corp-a", stray: 1 })).toBeTypeOf("object");
});
test("lets the legacy credential aliases through to the handler that supports them", () => {
// seal_deploy_hosecloud_configure has always accepted appKey/appSecurity
// alongside apiKey/apiSecret; a schema that declared only apiKey as
// required would have blocked that documented path.
expect(() =>
parseToolParams(tool("seal_deploy_hosecloud_configure"), {
appKey: "key-1",
appSecurity: "secret-1",
mode: "assisted"
})
).not.toThrow();
});
});
+104
View File
@@ -0,0 +1,104 @@
import { z } from "zod";
import { validationError } from "../../../core/errors.js";
import type { SealTool } from "./index.js";
/**
* Checks one invocation's params against the schema its tool declares, then
* returns the params unchanged.
*
* Both dispatch paths — `runToolResult` (every CLI command) and
* `executeSealTool` (`POST /api/tool/:name`, every `/v1/*` route) — used to
* hand `params` straight to `handler`, so a required field could be missing, a
* limit could be `999999`, or a typo'd HTTP body key could sail through and
* surface later as an opaque upstream error or a `Cannot read properties of
* undefined`. The schema is now the gate, failing fast with the offending field
* path (exit `13` on the CLI, HTTP `400` behind the adapter).
*
* Two deliberate properties:
*
* - **Original params are returned, not `result.data`.** Handlers read keys the
* schema does not declare — `seal_deploy_hosecloud_configure` accepts the
* legacy `appKey`/`appSecurity` aliases alongside `apiKey`/`apiSecret` — and
* zod's default strip would silently drop them. Validation must never change
* what a working handler receives, only block what would have failed anyway.
* - **Undeclared keys never fail.** `z.object` is non-strict, so an extra HTTP
* body key is ignored rather than rejected; this is a correctness check, not
* an API-compatibility verdict.
*
* Before rejecting, wire-format values are coerced to the shape the schema
* declares (see {@link coerceWireTypes}) because `/v1/*` query strings arrive
* entirely as strings while the schema says `z.number()`.
*/
export function parseToolParams(tool: SealTool, params: Record<string, unknown>): Record<string, unknown> {
const result = tool.parameters.safeParse(coerceWireTypes(tool.parameters, params));
if (result.success) return params;
const detail = result.error.issues
.map((issue) => `${issue.path.length ? issue.path.join(".") : "(root)"}: ${issue.message}`)
.join("; ");
throw validationError(`Invalid parameters for ${tool.name}: ${detail}`);
}
/**
* Rewrites string-shaped query/body values into the type the schema declares
* for that key: `"10"` → `10` for `z.number()`, `"true"` → `true` for
* `z.boolean()`, `"id,code"` → `["id", "code"]` for `z.array()`.
*
* Query strings carry no types, so without this every `/v1/*` route that passes
* `url.searchParams` through would fail against `z.number().int()` — while a
* value that merely looks wrong (`"abc"` for a number) is left alone so zod
* reports it instead of hiding it behind a NaN.
*
* Only top-level keys are touched: nested params arrive as parsed JSON (already
* typed), and skipping declared-but-uncoercible leaves errors to zod rather
* than guessing.
*/
function coerceWireTypes(schema: z.ZodType, params: Record<string, unknown>): Record<string, unknown> {
const shape = (schema as z.ZodObject<z.ZodRawShape>).shape;
if (!shape) return params;
const coerced = { ...params };
for (const [key, def] of Object.entries(shape)) {
const value = coerced[key];
if (typeof value !== "string" || value === "") continue;
const target = unwrapType(def);
if (target === "number" && /^[+-]?\d+(?:\.\d+)?$/.test(value.trim())) {
coerced[key] = Number(value.trim());
} else if (target === "boolean") {
if (value === "true") coerced[key] = true;
else if (value === "false") coerced[key] = false;
} else if (target === "array") {
const items = value.split(",").map((item) => item.trim()).filter(Boolean);
if (items.length) coerced[key] = items;
}
}
return coerced;
}
/**
* Resolves a field's concrete type name, stepping through `optional` /
* `default` / `nullable` wrappers: `"limit: optional"` → `"number"`.
*
* zod v4 exposes `type` on the schema instance but keeps `innerType` on
* `_def`, so both shapes are read — a wrapper reached via `_def.innerType` is
* an instance again, and an object reached by other means may be a bare def.
*/
function unwrapType(schema: unknown): string | undefined {
let current = schema as
| { type?: string; innerType?: unknown; _def?: { type?: string; innerType?: unknown } }
| undefined;
// Depth bound: wrappers nest shallowly in practice; anything deeper is a
// shape this helper should decline to interpret rather than chase.
for (let depth = 0; current && depth < 8; depth++) {
const def = current._def ?? current;
const type = def.type ?? current.type;
if (type === "optional" || type === "default" || type === "nullable") {
current = (def.innerType ?? current.innerType) as typeof current;
continue;
}
return type;
}
return undefined;
}
+42 -6
View File
@@ -8,22 +8,49 @@ import type { CorpConfig } from "../core/config/types.js";
import { getOpenApiSchema } from "../core/embedded-openapi.js"; import { getOpenApiSchema } from "../core/embedded-openapi.js";
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js"; import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
import { createSealClient } from "../core/http/factory.js"; import { createSealClient } from "../core/http/factory.js";
import { findSealTool, type SealTool } from "../domains/seal/tools.js"; import { findSealTool, parseToolParams, type SealTool } from "../domains/seal/tools.js";
import { tokenizeCommand } from "../cli/tokenize.js"; import { tokenizeCommand } from "../cli/tokenize.js";
import { redactSensitiveText } from "../core/redact.js"; import { redactSensitiveText } from "../core/redact.js";
import { CliError, type CliExitCode } from "../core/errors.js";
import { VERSION } from "../version.js"; import { VERSION } from "../version.js";
import { renderDocsHtml } from "./docs.js"; import { renderDocsHtml } from "./docs.js";
async function executeSealTool(tool: SealTool, client: KyInstance, params: any, corp: CorpConfig): Promise<unknown> { async function executeSealTool(tool: SealTool, client: KyInstance, params: any, corp: CorpConfig): Promise<unknown> {
// Schema gate for every HTTP caller: a missing required field or bad value
// is a client error (400), not an upstream failure discovered mid-handler.
parseToolParams(tool, params);
const handler = tool.handler as (client: KyInstance, params: any, context: { corp: CorpConfig }) => Promise<unknown>; const handler = tool.handler as (client: KyInstance, params: any, context: { corp: CorpConfig }) => Promise<unknown>;
return handler(client, params, { corp }); return handler(client, params, { corp });
} }
/** Maps a structured CLI exit code to the HTTP status it means for a caller. */
export function httpStatusForCliExit(exitCode: CliExitCode): number {
switch (exitCode) {
case 11:
return 401;
case 12:
return 413;
case 10:
case 14:
return 403;
case 2:
case 13:
return 400;
default:
return 500;
}
}
export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse) { export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse) {
// 1. CORS headers // 1. CORS headers
res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH"); 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"); // Mirrors the headers this adapter actually consults: `X-Seal-Corp` selects
// the enterprise (`extractCorpId`), `Authorization` is kept because generic
// clients attach it by default. The historic `X-Seal-Home-Session` is gone —
// no handler ever read it, and the adapter has no session to authenticate
// (openapi's info.description states that plainly).
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Seal-Corp");
if (req.method === "OPTIONS") { if (req.method === "OPTIONS") {
res.writeHead(204); res.writeHead(204);
@@ -133,12 +160,18 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
} }
const body = (await parseJsonBody(req)) || {}; const body = (await parseJsonBody(req)) || {};
const corpId = extractCorpId(req, url, body);
const corp = selectCorp(corpId);
const client = await createSealClient(corp);
const params = { ...body }; const params = { ...body };
delete params.corp; delete params.corp;
// Fail fast before `selectCorp`, which records usage stats to disk: a
// request that can never succeed should cause no writes. `executeSealTool`
// performs the same check afterwards — the early call exists purely to
// win this ordering, not to duplicate the guarantee.
parseToolParams(tool, params);
const corpId = extractCorpId(req, url, body);
const corp = selectCorp(corpId);
const client = await createSealClient(corp);
const output = await executeSealTool(tool, client, params, corp); const output = await executeSealTool(tool, client, params, corp);
sendJson(res, 200, output); sendJson(res, 200, output);
@@ -154,7 +187,10 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
sendError(res, 404, `Cannot ${method} ${pathname}. Visit /docs for available endpoints.`); sendError(res, 404, `Cannot ${method} ${pathname}. Visit /docs for available endpoints.`);
} catch (err: unknown) { } catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err); const message = err instanceof Error ? err.message : String(err);
sendError(res, 500, message); // A structured CLI error names the caller's mistake (bad params, missing
// auth, output too large); pass it through as the matching 4xx instead of
// letting every failure look like an adapter crash.
sendError(res, err instanceof CliError ? httpStatusForCliExit(err.exitCode) : 500, message);
} }
} }
+31
View File
@@ -1,6 +1,7 @@
import { describe, expect, test, afterAll, beforeAll } from "bun:test"; import { describe, expect, test, afterAll, beforeAll } from "bun:test";
import type { Server } from "node:http"; import type { Server } from "node:http";
import { startHttpServer } from "./server.js"; import { startHttpServer } from "./server.js";
import { httpStatusForCliExit } from "./routes.js";
describe("HTTP Server", () => { describe("HTTP Server", () => {
let server: Server; let server: Server;
@@ -64,6 +65,31 @@ describe("HTTP Server", () => {
expect(json.data.name).toBe("seal-use"); expect(json.data.name).toBe("seal-use");
}); });
test("POST /api/tool/:name rejects invalid params with 400 before touching an enterprise", async () => {
const res = await fetch(`${baseUrl}/api/tool/seal_user_create`, {
method: "POST",
headers: { "Content-Type": "application/json" },
// `name` is required by the tool's schema; without the schema gate this
// reached the handler as `undefined` and died as an opaque 500.
body: JSON.stringify({ phone: "13800001111" })
});
expect(res.status).toBe(400);
const json = (await res.json()) as any;
expect(json.error).toBe(true);
expect(json.message).toContain("seal_user_create");
expect(json.message).toContain("name");
});
test("maps structured CLI exit codes onto HTTP statuses", () => {
expect(httpStatusForCliExit(1)).toBe(500);
expect(httpStatusForCliExit(2)).toBe(400);
expect(httpStatusForCliExit(10)).toBe(403);
expect(httpStatusForCliExit(11)).toBe(401);
expect(httpStatusForCliExit(12)).toBe(413);
expect(httpStatusForCliExit(13)).toBe(400);
expect(httpStatusForCliExit(14)).toBe(403);
});
test("GET /v1/corps returns enterprise list", async () => { test("GET /v1/corps returns enterprise list", async () => {
const res = await fetch(`${baseUrl}/v1/corps`); const res = await fetch(`${baseUrl}/v1/corps`);
expect(res.status).toBe(200); expect(res.status).toBe(200);
@@ -76,5 +102,10 @@ describe("HTTP Server", () => {
const res = await fetch(`${baseUrl}/v1/corps`, { method: "OPTIONS" }); const res = await fetch(`${baseUrl}/v1/corps`, { method: "OPTIONS" });
expect(res.status).toBe(204); expect(res.status).toBe(204);
expect(res.headers.get("access-control-allow-methods")).toContain("GET"); expect(res.headers.get("access-control-allow-methods")).toContain("GET");
const allowHeaders = res.headers.get("access-control-allow-headers") ?? "";
expect(allowHeaders).toContain("X-Seal-Corp");
// Advertises only headers a handler reads: the historic reserved session
// header was never consulted, and the openapi no longer claims otherwise.
expect(allowHeaders).not.toContain("X-Seal-Home-Session");
}); });
}); });
+124
View File
@@ -0,0 +1,124 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "./cli/runner.js";
const ENV_KEYS = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_DISABLE_BG_UPDATE"] as const;
const ORIGINAL_ENV: Record<string, string | undefined> = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]]));
const ORIGINAL_FETCH = globalThis.fetch;
const tempDirs: string[] = [];
afterEach(() => {
globalThis.fetch = ORIGINAL_FETCH;
for (const key of ENV_KEYS) {
if (ORIGINAL_ENV[key] === undefined) delete process.env[key];
else process.env[key] = ORIGINAL_ENV[key]!;
}
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
function makeProbeEnv(corpId = "demo-corp"): string {
const dir = mkdtempSync(join(tmpdir(), "seal-use-probe-test-"));
tempDirs.push(dir);
writeFileSync(
join(dir, `${corpId}.json`),
JSON.stringify({
id: corpId,
name: "Demo Corp",
source: { type: "seal", token: "seal-token", sealUrl: `https://${corpId}.sealai.cc` }
})
);
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json");
process.env.SEAL_DISABLE_BG_UPDATE = "1";
return dir;
}
type Route = (url: string) => Response | undefined;
/** Routes the four upstream calls a probe makes; unhandled URLs fail loudly. */
function mockSealApi(route: Route): void {
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = input instanceof Request ? input.url : String(input);
const response = route(url);
if (!response) throw new Error(`probe test received an unexpected request: ${url}`);
return response;
}) as typeof fetch;
}
function json(payload: unknown, status = 200): Response {
return new Response(JSON.stringify(payload), {
status,
headers: { "Content-Type": "application/json" }
});
}
function okApi(): Route {
return (url) => {
if (url.includes("/api/v1/auth/me")) {
return json({
user: { id: "user-1", tenantId: "tenant-1", name: "Tester" },
tenant: { id: "tenant-1", name: "Demo Tenant" }
});
}
if (url.includes("/api/v1/rules")) {
return json({
rules: [{ id: "rule-1", description: "差旅报销规则", scope: "travel", strictness: "MUST_FOLLOW" }],
hasPendingDeletes: false
});
}
if (url.includes("/api/v1/knowledge/articles")) return json({ articles: [], total: 0 });
if (url.includes("/api/v1/agent/ai-approval/config")) return json({ tone: "precise" });
return undefined;
};
}
describe("seal-use probe stream contract", () => {
test("writes exactly one JSON document to stdout and narrates on stderr", async () => {
makeProbeEnv();
mockSealApi(okApi());
const result = await runCli(["probe", "demo-corp"]);
expect(result.exitCode).toBe(0);
// The whole contract: if the [probe] prose still reached stdout, this
// parse would throw instead of yielding the payload.
const payload = JSON.parse(result.stdout) as Record<string, any>;
expect(result.stdout).not.toContain("[probe]");
expect(payload.corp).toEqual({ id: "demo-corp", name: "Demo Corp", sourceType: "seal" });
expect(payload.enterprise).toMatchObject({
provider: "seal",
sealUrl: "https://demo-corp.sealai.cc",
tenantName: "Demo Tenant"
});
expect(payload.summary).toEqual({
rules: 1,
hasPendingRuleDeletes: false,
documents: 0,
documentsTotal: 0,
stylePreferences: "ok"
});
expect(result.stderr).toContain("[probe] corp=demo-corp source=seal");
expect(result.stderr).toContain("[probe] approval context summary");
});
test("reports a failing style-preferences endpoint in the payload instead of throwing", async () => {
makeProbeEnv();
mockSealApi((url) => {
const ok = okApi()(url);
return url.includes("/api/v1/agent/ai-approval/config") ? json({ error: "upstream broke" }, 500) : ok;
});
const result = await runCli(["probe", "demo-corp"]);
expect(result.exitCode).toBe(0);
const payload = JSON.parse(result.stdout) as Record<string, any>;
expect(payload.summary.stylePreferences).toContain("error:");
expect(payload.summary.rules).toBe(1);
});
});
+42 -18
View File
@@ -1,10 +1,25 @@
import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from "./core/config/loader.js"; import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from "./core/config/loader.js";
import { resolveCorpConfig } from "./core/config/manager.js"; import { resolveCorpConfig } from "./core/config/manager.js";
import { createSealClient } from "./core/http/factory.js"; import { createSealClient } from "./core/http/factory.js";
import type { SealEnterpriseConfig } from "./core/auth/types.js";
import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js"; import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js";
import { getApprovalContext } from "./domains/seal/api.js"; import { getApprovalContext } from "./domains/seal/api.js";
import { printJson } from "./cli/printer.js";
export async function runProbe(options: { corpId?: string } = {}) { /** One probe run's payload — the entire stdout of `seal-use probe`. */
export type ProbeResult = {
corp: { id: string; name: string; sourceType: string };
enterprise: SealEnterpriseConfig;
summary: {
rules: number;
hasPendingRuleDeletes: boolean;
documents: number;
documentsTotal?: number;
stylePreferences: string;
};
};
export async function runProbe(options: { corpId?: string } = {}): Promise<ProbeResult> {
const corps = loadCorpConfigs(); const corps = loadCorpConfigs();
const globalConfig = loadGlobalConfig(); const globalConfig = loadGlobalConfig();
const corp = resolveCorpConfig( const corp = resolveCorpConfig(
@@ -17,11 +32,13 @@ export async function runProbe(options: { corpId?: string } = {}) {
getEnterprisesDirCandidates() getEnterprisesDirCandidates()
); );
console.log(`[probe] corp=${corp.id} source=${corp.source.type}`); // Progress notes go to stderr: stdout carries the JSON payload alone, so
// `seal-use probe | jq` keeps working (it previously held three prose lines
// interleaved with three JSON blobs).
console.error(`[probe] corp=${corp.id} source=${corp.source.type}`);
const enterprise = await resolveLiveSealEnterpriseConfig(corp); const enterprise = await resolveLiveSealEnterpriseConfig(corp);
console.log("[probe] seal enterprise"); console.error("[probe] seal enterprise");
console.log(JSON.stringify(enterprise, null, 2));
const client = await createSealClient(corp); const client = await createSealClient(corp);
const context = await getApprovalContext(client, { const context = await getApprovalContext(client, {
@@ -29,23 +46,30 @@ export async function runProbe(options: { corpId?: string } = {}) {
stylePreferencesEndpoint: corp.seal.endpoints.approvalStylePreferences stylePreferencesEndpoint: corp.seal.endpoints.approvalStylePreferences
}); });
console.log("[probe] approval context summary"); console.error("[probe] approval context summary");
console.log(JSON.stringify({
rules: context.rules.rules.length, return {
hasPendingRuleDeletes: context.rules.hasPendingDeletes, corp: { id: corp.id, name: corp.name, sourceType: corp.source.type },
documents: context.documents.articles.length, enterprise,
documentsTotal: context.documents.total, summary: {
stylePreferences: context.stylePreferences.ok rules: context.rules.rules.length,
? "ok" hasPendingRuleDeletes: context.rules.hasPendingDeletes,
: `error: ${context.stylePreferences.error}` documents: context.documents.articles.length,
}, null, 2)); documentsTotal: context.documents.total,
stylePreferences: context.stylePreferences.ok
? "ok"
: `error: ${context.stylePreferences.error}`
}
};
} }
if (import.meta.main) { if (import.meta.main) {
const args = process.argv.slice(2); const args = process.argv.slice(2);
const corpId = args[0] === "--corp" ? args[1] : args[0]; const corpId = args[0] === "--corp" ? args[1] : args[0];
runProbe({ corpId }).catch((error) => { runProbe({ corpId })
console.error(error instanceof Error ? error.message : error); .then((result) => printJson(result))
process.exit(1); .catch((error) => {
}); console.error(error instanceof Error ? error.message : error);
process.exit(1);
});
} }
+78
View File
@@ -0,0 +1,78 @@
import { describe, expect, test } from "bun:test";
import { readdirSync, readFileSync } from "node:fs";
import { join, relative } from "node:path";
/**
* The stdout contract, enforced as a test rather than as review vigilance.
*
* `stdout` is the machine channel: the Agent Harness parses it directly into
* typed payloads, so a stray `console.log("[probe] …")` between two JSON blobs
* breaks every consumer (the repo shipped exactly that bug in `seal-use probe`).
* Diagnostics belong on `stderr`, which needs no permission.
*
* The allow-list below mirrors the exceptions AGENTS.md already documents:
* `printer.ts` is *the* machine-channel writer (`printJson` / `printHelp`), the
* two document-dump commands are exempt because their output *is* a document,
* and `cli.ts` / `server.ts` are the entry points that echo the captured result.
*
* Both directions are asserted: a new writer fails the test, and an exception
* whose file stopped writing fails too, so the list cannot rot.
*/
const SRC_DIR = join(import.meta.dir);
const STDOUT_WRITERS = new Set([
"cli/printer.ts",
"cli/commands/doctor.ts",
"cli/commands/skill.ts",
"cli.ts",
"server.ts"
]);
const STDOUT_CALL = /(^|[^.\w])console\.log\s*\(|process\.stdout\.write\s*\(/;
function listTypeScriptFiles(dir: string): string[] {
const found: string[] = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.name.startsWith(".")) continue;
const full = join(dir, entry.name);
if (entry.isDirectory()) found.push(...listTypeScriptFiles(full));
else if (entry.isFile() && entry.name.endsWith(".ts")) found.push(full);
}
return found;
}
function codeLines(source: string): string[] {
// Comments may legitimately discuss console.log; only executable code counts.
return source
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/^[ \t]*\/\/.*$/gm, "")
.split("\n");
}
describe("stdout stream contract", () => {
test("nothing writes to stdout outside the documented machine channel", () => {
const violations: string[] = [];
const actualWriters = new Set<string>();
for (const file of listTypeScriptFiles(SRC_DIR)) {
const rel = relative(SRC_DIR, file).split("\\").join("/");
if (rel.endsWith(".test.ts") || rel.endsWith(".generated.ts")) continue;
codeLines(readFileSync(file, "utf8")).forEach((line, index) => {
if (!STDOUT_CALL.test(line)) return;
actualWriters.add(rel);
if (!STDOUT_WRITERS.has(rel)) {
violations.push(`${rel}:${index + 1}: ${line.trim()}`);
}
});
}
expect(violations).toEqual([]);
// An allow-listed file that no longer writes to stdout has lost its reason
// to be exempt; drop it rather than let the exception outlive the code.
const staleExceptions = [...STDOUT_WRITERS].filter((file) => !actualWriters.has(file));
expect(staleExceptions).toEqual([]);
});
});