Merge pull request #195 from yunyingk/codex/capability-registry-rename

Remove the local HTTP adapter, service daemon, and OpenAPI contract
This commit is contained in:
yunyingk authored and GitHub committed 2026-09-30 15:25:41 +08:00
commit 6f11b9837f
42 files changed
+61 -8602

No files matched your search

-4
View File
@@ -41,10 +41,6 @@ jobs:
- name: Colocated Unit Tests
run: bun test
- name: Build OpenAPI & Validate Sync
run: |
bun run openapi:bundle
git diff --exit-code dist/openapi.json || (echo "::error::dist/openapi.json is out of sync with openapi/openapi.yaml. Run 'bun run openapi:bundle' and commit changes." && exit 1)
- name: Verify Binary Compilation
run: |
+4 -7
View File
@@ -2,11 +2,11 @@
## Project Structure & Module Organization
This is a Bun + TypeScript toolkit for the `seal-use` CLI and a local stdio MCP server (`seal-use mcp`). Entry points are `src/cli.ts`, `src/server.ts`, and `src/probe.ts`. Shared config, auth, token, and HTTP code is under `src/core/`. Seal-specific API and logic is under `src/domains/seal/`; the capability registry under `src/domains/seal/capabilities/` holds the shared handlers dispatched by the CLI (`runCapability`), the HTTP adapter (`POST /api/tool/:name`), and the MCP gateways. `seal_*` strings are internal registry identifiers — the MCP surface only ever exposes the `seal_cli` / `seal_cli_write` gateway pair, never these names (see README "One registry, three doors").
This is a Bun + TypeScript toolkit for the `seal-use` CLI and a local stdio MCP server (`seal-use mcp`). Entry points are `src/cli.ts`, `src/server.ts`, and `src/probe.ts`. Shared config, auth, token, and HTTP code is under `src/core/`. Seal-specific API and logic is under `src/domains/seal/`; the capability registry under `src/domains/seal/capabilities/` holds the shared handlers dispatched by the CLI (`runCapability`) and allow-listed by the MCP gateways. `seal_*` strings are internal registry identifiers — the MCP surface only ever exposes the `seal_cli` / `seal_cli_write` gateway pair, never these names (see README "One registry, two doors").
The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares a skills-only plugin manifest and the agent skill lives under `skills/seal-use/`. The plugin ships no MCP surface; the local MCP runs from the CLI (`seal-use mcp`, or the `mcp-config` snippet for Cursor/Claude Desktop). The in-repo `.agents/skills/seal-use` symlink has been dropped; workspace and Codex skill loading use the global `~/.agents/skills/seal-use` copy installed by `seal-use skill install`.
Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in `openapi/`; bundled output is `dist/openapi.json`. Example enterprise configs are in `enterprises/example.*.json`; real configs must stay untracked.
Tests are colocated as `*.test.ts` files in `src/`. Example enterprise configs are in `enterprises/example.*.json`; real configs must stay untracked.
## Build, Test, and Development Commands
@@ -18,12 +18,9 @@ Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in
- `bun run check`: type-check with `tsc --noEmit` (also enforces `noUnusedLocals`/`noUnusedParameters`).
- `bun run lint`: lint with `oxlint src` (zero-warning gate; CI fails on warnings).
- `bun test`: run all colocated Bun tests.
- `bun run bump <version | patch | minor>`: bump version across all manifest/skill/openapi files and bundle.
- `bun run openapi:bundle`: rebuild `dist/openapi.json`.
- `bun run bump <version | patch | minor>`: bump version across all manifest and skill files.
- `bun run dev:override`: compile the host binary with Git dev version metadata, macOS sign, atomically override the Mac global command (`/opt/homebrew/bin/seal-use`), and sync the local Agent Skill.
> **Pre-Push Bundle Gate**: Modifying `openapi/` requires `bun run openapi:bundle` to keep `dist/openapi.json` in sync; CI strictly checks for zero diff. There is no MCP bundle anymore — the plugin is skills-only and the MCP runs from the CLI (`seal-use mcp`).
## Coding Style & Naming Conventions
Use TypeScript ES modules with explicit `.js` import extensions for local files. Validate external data with Zod or narrow types before use. Follow existing style: two-space indentation, double quotes, omitted trailing semicolons, `camelCase` variables/functions, `PascalCase` classes/types, and lowercase hyphenated filenames such as `token-store.ts`.
@@ -111,7 +108,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
Never commit real enterprise credentials, Seal tokens, service logs, or local generated state. Use `enterprises/example.hose.json` or `enterprises/example.seal.json` as templates, then place real configs in `enterprises/local.json` or `~/.config/seal-use/enterprises` (with legacy fallback to `~/.config/seal-home/enterprises`). For auth or tenant changes, verify with `bun run probe` or `seal-use auth diagnose`.
Credential files are written `0600`; a config placed by hand keeps the `0o644` default, so run `seal-use doctor` and act on its `credential_permissions` check before sharing a machine or a backup. See `SECURITY.md` for the trust model (local HTTP adapter, self-update, custom linters).
Credential files are written `0600`; a config placed by hand keeps the `0o644` default, so run `seal-use doctor` and act on its `credential_permissions` check before sharing a machine or a backup. See `SECURITY.md` for the trust model (self-update, custom linters).
## Agent-Specific Instructions
+8 -50
View File
@@ -5,7 +5,7 @@
[![Bun Version](https://img.shields.io/badge/Bun-v1.3%2B-black?logo=bun)](https://bun.sh)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
Bun + TypeScript CLI and optional local service for pulling Seal enterprise approval context from provider credentials.
Bun + TypeScript CLI for pulling Seal enterprise approval context from provider credentials.
The first provider is Hose/合思: `key`, `password`, `corpId`, `staffId`, and an optional Hose domain. The provider exchanges those credentials for a Seal enterprise session, then the Seal domain tools can read and maintain approval rules, approval documents, and approval style preferences.
@@ -129,7 +129,7 @@ Update an existing checkout:
seal-use update
```
`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.
`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`.
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.
@@ -187,44 +187,6 @@ a default enterprise, then `seal-use corps switch <corpId>` to change it. Run
Use `seal-use auth diagnose --corp <corpId>` when login fails in stateless mode. It reports four stages without printing tokens: `hose.openapi`, `hose.provisional`, `seal.sso`, and `seal.whoami`. A failed stage points to whether the problem is Hose app credentials, staff authorization, Seal SSO/tenant reachability, or Seal user/session access.
## Wrapped API Documentation
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:
```text
openapi/openapi.yaml
openapi/paths/
openapi/components/
```
Generate a single tool-friendly JSON file:
```bash
bun run openapi:bundle
```
The generated file is written to `dist/openapi.json`. Treat `openapi/*.yaml` as the editable source of truth and `dist/openapi.json` as generated output for Swagger UI, Scalar, client generators, or agents.
## Local Service
For macOS users who want a long-lived local background process and a simple restart point after updates:
```bash
seal-use service start
seal-use service status
seal-use service restart
seal-use service stop
```
Service state is stored under `~/.config/seal-use/`:
- `service.pid`
- `service.log`
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
```json
@@ -253,19 +215,18 @@ The service is intentionally local: `service start` runs the same HTTP adapter a
## Developer MCP Notes
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.
### One registry, three doors
### One registry, two doors
All approval/logic lives once in the capability registry under `src/domains/seal/capabilities/` (`src/domains/seal/capabilities.ts` re-exports it). Three surfaces enter the same handlers, each with its own naming:
All approval/logic lives once in the capability registry under `src/domains/seal/capabilities/` (`src/domains/seal/capabilities.ts` re-exports it). Two surfaces enter the same handlers, each with its own naming:
| Surface | Entry | Naming |
| --- | --- | --- |
| CLI (primary) | `seal-use <area> <verb>` via `runCapability` | Kebab verbs: `seal-use context`, `seal-use rules get` |
| Local HTTP adapter | `POST /api/tool/:name` via `findSealCapability` | Registry IDs: `seal_approval_context_get` |
| Local MCP server | `seal_cli` / `seal_cli_write` gateways that execute a CLI command string | Gateway names only — the registry IDs are the allow-list, never advertised as tools |
`seal_*` strings are internal registry identifiers: they are valid as HTTP tool IDs and dispatch IDs, and they are **not** MCP tool names — no MCP client will ever see them in `tools/list`. If you are reading code and a `seal_*` name looks like it should be an MCP tool, that instinct is the trap this note exists to prevent; check `src/server.ts` for the actual (two-gateway) MCP surface.
`seal_*` strings are internal registry identifiers: they are dispatch IDs inside the codebase and they are **not** MCP tool names — no MCP client will ever see them in `tools/list`. If you are reading code and a `seal_*` name looks like it should be an MCP tool, that instinct is the trap this note exists to prevent; check `src/server.ts` for the actual (two-gateway) MCP surface.
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:
@@ -280,7 +241,7 @@ Both take the command as a string:
}
```
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.
Both run the same CLI dispatcher as the global binary, so `config` 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
@@ -295,7 +256,6 @@ Key CLI command groups:
- **`seal-use deploy ...`**: HoseCloud review node requirement inspection, status check, configuration, and sync.
- **`seal-use preference ...`**: decision preferences and thinking depth policies.
- **`seal-use webhook ...`**: webhook integration CRUD and material pack testing.
- **`seal-use service ...`**: persistent daemon service management with embedded HTTP server.
For rule list commands, prefer `seal-use rules count --corp <corpId>` or `seal-use rules list --corp <corpId> --summary` before requesting full rule descriptions. `seal-use rules list` protects large outputs and asks for `--summary`, `--count`, or explicit `--full` when the response would be too large.
@@ -358,9 +318,7 @@ bun run bump 0.8.5
1. Updates `"version"` in `package.json`;
2. Updates `"version"` in `.zcode-plugin/plugin.json`;
3. Updates `version`, `short-description`, and title in `skills/seal-use/SKILL.md`;
4. Updates `version` in `openapi/openapi.yaml`;
5. Rebuilds the OpenAPI spec (`dist/openapi.json`);
6. Prints the exact `git commit` and `git tag` commands ready to execute.
4. Prints the exact `git commit` and `git tag` commands ready to execute.
### 2. Tag & Publish Workflow
-6
View File
@@ -31,12 +31,6 @@ configs are gitignored — never commit them.
These are deliberate trade-offs, not unknown bugs. Report them anyway if you can make one worse
than described here.
- **The local HTTP adapter does not authenticate requests.** `seal-use http` and
`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
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. The OpenAPI document declares no security scheme — it
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
release binary and replaces the running executable; `scripts/install.sh` compares
`checksums.txt` but only warns on a mismatch. Prefer the direct GitHub source
-3615
View File
File diff suppressed because it is too large. Load diff
-58
View File
@@ -1,58 +0,0 @@
CorpId:
name: corpId
in: query
schema:
type: string
description: Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used.
Offset:
name: offset
in: query
schema:
type: integer
minimum: 0
default: 0
description: Zero-based pagination offset.
Limit:
name: limit
in: query
schema:
type: integer
minimum: 1
maximum: 100
default: 50
description: Maximum number of records to return.
RuleId:
name: ruleId
in: path
required: true
schema:
type: string
description: Approval rule ID.
VersionId:
name: versionId
in: path
required: true
schema:
type: string
description: Published rule version ID.
DocumentId:
name: documentId
in: path
required: true
schema:
type: string
description: Approval knowledge document ID.
RecordId:
name: recordId
in: path
required: true
schema:
type: string
description: seal-use approval run record ID.
BatchId:
name: batchId
in: path
required: true
schema:
type: string
description: Simulation batch ID.
-18
View File
@@ -1,18 +0,0 @@
BadRequest:
description: Invalid request.
content:
application/json:
schema:
$ref: ./schemas/index.yaml#/ErrorResponse
Unauthorized:
description: Local service authentication failed or downstream Seal auth failed.
content:
application/json:
schema:
$ref: ./schemas/index.yaml#/ErrorResponse
NotFound:
description: Requested resource was not found.
content:
application/json:
schema:
$ref: ./schemas/index.yaml#/ErrorResponse
-407
View File
@@ -1,407 +0,0 @@
ErrorResponse:
type: object
additionalProperties: true
required: [error]
properties:
error:
type: string
message:
type: string
details: {}
CorpSummary:
type: object
required: [id, name, sourceType, current]
properties:
id:
type: string
name:
type: string
sourceType:
type: string
enum: [hose, seal]
current:
type: boolean
SwitchCorpRequest:
type: object
required: [corpId]
properties:
corpId:
type: string
SwitchCorpResponse:
type: object
required: [current, id, name]
properties:
current:
type: boolean
id:
type: string
name:
type: string
SourceConfig:
type: object
additionalProperties: true
description: Redacted Seal enterprise config resolved from the configured source.
AuthStage:
type: object
additionalProperties: true
required: [name, ok]
properties:
name:
type: string
examples: [hose.openapi, hose.provisional, seal.sso, seal.whoami]
ok:
type: boolean
error:
type: string
AuthDiagnosis:
type: object
required: [stages]
properties:
stages:
type: array
items:
$ref: '#/components/schemas/AuthStage'
SealUser:
type: object
additionalProperties: true
required: [id, name]
properties:
id:
type: string
tenantId:
type: string
name:
type: string
isAdmin:
type: boolean
permissions:
type: array
items:
type: string
SealTenant:
type: object
additionalProperties: true
required: [id, name]
properties:
id:
type: string
name:
type: string
tenantSlug:
type: string
WhoamiResponse:
type: object
required: [user, tenant]
properties:
user:
$ref: '#/components/schemas/SealUser'
tenant:
$ref: '#/components/schemas/SealTenant'
SessionResponse:
type: object
additionalProperties: true
required: [user, session]
properties:
user:
$ref: '#/components/schemas/SealUser'
session:
type: object
additionalProperties: true
ApprovalRule:
type: object
additionalProperties: true
required: [id, description, scope, strictness]
properties:
id:
type: string
description:
type: string
scope:
type: string
strictness:
type: string
enum: [MUST_FOLLOW, SHOULD_FOLLOW, SUGGESTION]
status:
type: string
ApprovalRuleInput:
type: object
required: [description, scope, strictness]
properties:
description:
type: string
scope:
type: string
strictness:
type: string
enum: [MUST_FOLLOW, SHOULD_FOLLOW, SUGGESTION]
ApprovalRulePatch:
type: object
additionalProperties: false
properties:
description:
type: string
scope:
type: string
strictness:
type: string
enum: [MUST_FOLLOW, SHOULD_FOLLOW, SUGGESTION]
ApprovalRulesResponse:
type: object
required: [rules]
properties:
rules:
type: array
items:
$ref: '#/components/schemas/ApprovalRule'
hasPendingDeletes:
type: boolean
RuleSetVersion:
type: object
additionalProperties: true
required: [id, versionNumber, versionName, rules]
properties:
id:
type: string
versionNumber:
type: integer
versionName:
type: string
publishedByName:
type: string
rules:
type: array
items:
type: object
additionalProperties: true
PublishRuleVersionRequest:
type: object
required: [versionName]
properties:
versionName:
type: string
ApprovalDocument:
type: object
additionalProperties: true
required: [id, title, content]
properties:
id:
type: string
title:
type: string
purpose:
type: string
content:
type: string
description: Usually Markdown.
contentType:
type: string
status:
type: string
enabled:
type: boolean
scenarios:
type: array
items:
type: string
tags:
type: array
items:
type: string
ApprovalDocumentInput:
type: object
required: [title, purpose, content]
properties:
title:
type: string
purpose:
type: string
content:
type: string
contentType:
type: string
status:
type: string
scenarios:
type: array
items:
type: string
tags:
type: array
items:
type: string
ApprovalDocumentPatch:
type: object
additionalProperties: false
properties:
title:
type: string
purpose:
type: string
content:
type: string
contentType:
type: string
status:
type: string
enabled:
type: boolean
scenarios:
type: array
items:
type: string
tags:
type: array
items:
type: string
ApprovalDocumentsResponse:
type: object
required: [articles]
properties:
articles:
type: array
items:
$ref: '#/components/schemas/ApprovalDocument'
total:
type: integer
ApprovalStylePreferences:
type: object
additionalProperties: true
properties:
tone:
type: string
language:
type: string
detailLevel:
type: string
outputFormat:
type: string
examples:
type: array
items:
type: string
prohibitedPhrases:
type: array
items:
type: string
customInstructions:
type: string
ApprovalContext:
type: object
required: [rules, documents, stylePreferences]
properties:
rules: {}
documents: {}
stylePreferences: {}
ApprovalSearchRequest:
type: object
required: [keywords]
properties:
keywords:
type: array
minItems: 1
items:
type: string
matchMode:
type: string
enum: [any, all]
areas:
type: array
items:
type: string
enum: [rules, documents, preferences]
maxResults:
type: integer
ApprovalSearchResponse:
type: object
additionalProperties: true
ApprovalRun:
type: object
additionalProperties: true
required: [id]
properties:
id:
type: string
sourceDocumentSN:
type: string
description: External document number, often Hose/易快报单号.
sourceDocumentId:
type: string
status:
type: string
taskMode:
type: string
finalExecutionMode:
type: string
ruleSetVersionNumber:
type: integer
langfuseTraceId:
type: string
langfuseSessionFallback:
type: string
ApprovalRunsResponse:
type: object
additionalProperties: true
required: [records]
properties:
records:
type: array
items:
$ref: '#/components/schemas/ApprovalRun'
total:
type: integer
bridge:
type: array
items:
type: object
additionalProperties: true
ApprovalRunsSummary:
type: object
additionalProperties: true
properties:
date:
type: string
timezone:
type: string
matched:
type: integer
statusCounts:
type: object
additionalProperties:
type: integer
taskModeCounts:
type: object
additionalProperties:
type: integer
RunUrlResponse:
type: object
additionalProperties: true
properties:
url:
type: string
sealResultUrl:
type: string
ssoUrl:
type: string
documentUrl:
type: string
hoseDocumentUrl:
type: string
recordId:
type: string
sourceDocumentSN:
type: string
BridgeResponse:
type: object
additionalProperties: true
properties:
count:
type: integer
records:
type: array
items:
$ref: '#/components/schemas/ApprovalRun'
bridge:
type: array
items:
type: object
additionalProperties: true
-51
View File
@@ -1,51 +0,0 @@
openapi: 3.1.0
info:
title: seal-use Wrapped API
version: 0.10.42
description: |
HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter
(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).
These endpoints describe the stable wrapped API for frontend developers and agents. They are
not the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,
source authentication, response compaction, and diagnostics-friendly fields.
Every operation declares `x-implementation-status`, so a caller can tell what the running
adapter actually serves:
- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`
fails when an `implemented` operation has no matching route.
- `planned` — contract-only, designed but not routed yet. Calling it returns 404.
The same capabilities are reachable through the CLI, and through the optional MCP server when
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:
- url: http://localhost:8787
description: Local HTTP adapter (`seal-use http`, or the `seal-use service start` daemon). Loopback-only by default.
tags:
- name: Corps
description: Local enterprise configuration selection.
- name: Source
description: Source-derived Seal enterprise configuration.
- name: Auth
description: Wrapped authentication diagnostics and current identity.
- name: Approval Runs
description: Wrapped approval run history, summaries, document URLs, and trace bridge helpers.
- name: Approval Knowledge
description: Wrapped approval rules, documents, preferences, and search.
- name: Simulation
description: Wrapped simulation batch record access.
paths:
$ref: ./paths/index.yaml
components:
parameters:
$ref: ./components/parameters.yaml
responses:
$ref: ./components/responses.yaml
schemas:
$ref: ./components/schemas/index.yaml
-368
View File
@@ -1,368 +0,0 @@
paths:
/v1/approval/context:
get:
tags: [Approval Knowledge]
operationId: getApprovalContext
x-implementation-status: planned
summary: Get rules, documents, and style preferences together
parameters:
- $ref: ../components/parameters.yaml#/CorpId
- name: documentLimit
in: query
schema:
type: integer
minimum: 1
- name: latestRuleVersion
in: query
schema:
type: boolean
- name: ruleVersionNumber
in: query
schema:
type: integer
responses:
"200":
description: Approval context.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalContext
/v1/approval/search:
post:
tags: [Approval Knowledge]
operationId: searchApprovalKnowledge
x-implementation-status: planned
summary: Search approval rules, documents, and preferences
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalSearchRequest
responses:
"200":
description: Search results with line context.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalSearchResponse
/v1/approval/rules:
get:
tags: [Approval Knowledge]
operationId: listApprovalRules
x-implementation-status: implemented
summary: List current draft approval rules
responses:
"200":
description: Draft rules.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalRulesResponse
post:
tags: [Approval Knowledge]
operationId: createApprovalRule
x-implementation-status: planned
summary: Create draft approval rule
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalRuleInput
responses:
"200":
description: Created rule.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalRule
/v1/approval/rules/{ruleId}:
parameters:
- $ref: ../components/parameters.yaml#/RuleId
patch:
tags: [Approval Knowledge]
operationId: updateApprovalRule
x-implementation-status: planned
summary: Update draft approval rule
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalRulePatch
responses:
"200":
description: Updated rule.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalRule
delete:
tags: [Approval Knowledge]
operationId: deleteApprovalRule
x-implementation-status: planned
summary: Delete draft approval rule
responses:
"200":
description: Deleted.
/v1/approval/rule-versions:
get:
tags: [Approval Knowledge]
operationId: listApprovalRuleVersions
x-implementation-status: planned
summary: List published approval rule versions
responses:
"200":
description: Published rule versions.
content:
application/json:
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/RuleSetVersion
/v1/approval/rule-versions/{versionId}:
parameters:
- $ref: ../components/parameters.yaml#/VersionId
get:
tags: [Approval Knowledge]
operationId: getApprovalRuleVersion
x-implementation-status: planned
summary: Get published approval rule version
responses:
"200":
description: Rule version.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/RuleSetVersion
/v1/approval/rules/by-version:
get:
tags: [Approval Knowledge]
operationId: getApprovalRuleByVersion
x-implementation-status: planned
summary: Get one wrapped rule from a published version
parameters:
- $ref: ../components/parameters.yaml#/CorpId
- name: versionNumber
in: query
schema:
type: integer
- name: versionId
in: query
schema:
type: string
- name: latest
in: query
schema:
type: boolean
- name: code
in: query
schema:
type: string
description: Display rule code such as '#0038'.
- name: runtimeId
in: query
schema:
type: string
description: Runtime rule ID such as rule-205.
- name: recordId
in: query
schema:
type: string
description: Infer versionNumber from an approval run.
responses:
"200":
description: One rule from a published version.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/approval/rule-versions/publish:
post:
tags: [Approval Knowledge]
operationId: publishApprovalRuleVersion
x-implementation-status: planned
summary: Publish current draft rules
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/PublishRuleVersionRequest
responses:
"200":
description: Published version.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/approval/documents:
get:
tags: [Approval Knowledge]
operationId: listApprovalDocuments
x-implementation-status: planned
summary: List approval knowledge documents
parameters:
- $ref: ../components/parameters.yaml#/Offset
- name: limit
in: query
schema:
type: integer
minimum: 1
default: 20
- name: scenario
in: query
schema:
type: array
items:
type: string
style: form
explode: true
responses:
"200":
description: Documents.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalDocumentsResponse
post:
tags: [Approval Knowledge]
operationId: createApprovalDocument
x-implementation-status: planned
summary: Create approval knowledge document
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalDocumentInput
responses:
"200":
description: Created document.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalDocument
/v1/approval/documents/{documentId}:
parameters:
- $ref: ../components/parameters.yaml#/DocumentId
get:
tags: [Approval Knowledge]
operationId: getApprovalDocument
x-implementation-status: planned
summary: Get approval knowledge document
responses:
"200":
description: Document.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalDocument
patch:
tags: [Approval Knowledge]
operationId: updateApprovalDocument
x-implementation-status: planned
summary: Update approval knowledge document
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalDocumentPatch
responses:
"200":
description: Updated document.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalDocument
delete:
tags: [Approval Knowledge]
operationId: deleteApprovalDocument
x-implementation-status: planned
summary: Delete approval knowledge document
responses:
"200":
description: Deleted document confirmation.
/v1/approval/style-preferences:
get:
tags: [Approval Knowledge]
operationId: getApprovalStylePreferences
x-implementation-status: planned
summary: Get approval style preferences
responses:
"200":
description: Style preferences.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalStylePreferences
patch:
tags: [Approval Knowledge]
operationId: updateApprovalStylePreferences
x-implementation-status: planned
summary: Update approval style preferences
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalStylePreferences
responses:
"200":
description: Updated style preferences.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalStylePreferences
/v1/preferences:
get:
tags: [Approval Knowledge]
operationId: getPreferences
x-implementation-status: implemented
summary: Get current decision, thinking-depth and rule-version preferences
parameters:
- $ref: ../components/parameters.yaml#/CorpId
responses:
"200":
description: Decision preferences, thinking depth preference and the bound rule set version.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalStylePreferences
/v1/preferences/decision:
post:
tags: [Approval Knowledge]
operationId: updatePreferenceDecision
x-implementation-status: implemented
summary: Update decision preferences (takes effect immediately for the running approval agent)
parameters:
- $ref: ../components/parameters.yaml#/CorpId
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
explicitApprove:
type: string
explicitReject:
type: string
exemptApprove:
type: string
review:
type: string
dryRun:
type: boolean
description: Return the before/after diff without writing.
responses:
"200":
description: Updated preferences, or the previewed diff when dryRun is set.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalStylePreferences
-349
View File
@@ -1,349 +0,0 @@
paths:
/v1/approval-runs:
get:
tags: [Approval Runs]
operationId: searchApprovalRuns
x-implementation-status: implemented
summary: Search wrapped approval run history
parameters:
- $ref: ../components/parameters.yaml#/CorpId
- $ref: ../components/parameters.yaml#/Offset
- $ref: ../components/parameters.yaml#/Limit
- name: startDate
in: query
schema:
type: string
description: Creation-time lower bound in milliseconds.
- name: endDate
in: query
schema:
type: string
description: Creation-time upper bound in milliseconds.
- name: status
in: query
schema:
type: string
- name: taskMode
in: query
schema:
type: string
- name: manualApprovalStatus
in: query
schema:
oneOf:
- type: string
- type: array
items:
type: string
- name: sourceDocumentSN
in: query
schema:
type: string
description: Hose/易快报单号 or other external source document number.
- name: sourceDocumentId
in: query
schema:
type: string
- name: humanResult
in: query
schema:
type: string
description: Local human result contains filter, such as 驳回 or 通过.
- name: query
in: query
schema:
type: string
description: Search across record ID, source document fields, document ID, and trace fields.
- name: includeBridge
in: query
schema:
type: boolean
default: false
description: Include full Langfuse bridge rows.
responses:
"200":
description: Compact wrapped approval run list.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalRunsResponse
/v1/approval-runs/summary:
get:
tags: [Approval Runs]
operationId: summarizeApprovalRuns
x-implementation-status: implemented
summary: Summarize approval runs by local date
parameters:
- $ref: ../components/parameters.yaml#/CorpId
- name: date
in: query
schema:
type: string
format: date
- name: timezone
in: query
schema:
type: string
default: Asia/Shanghai
- $ref: ../components/parameters.yaml#/Limit
- name: query
in: query
schema:
type: string
- name: humanResult
in: query
schema:
type: string
responses:
"200":
description: Date summary with counts and compact records.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalRunsSummary
/v1/approval-runs/stats:
get:
tags: [Approval Runs]
operationId: statApprovalRuns
x-implementation-status: implemented
summary: Aggregate approval run counts by status and source system
parameters:
- $ref: ../components/parameters.yaml#/CorpId
- name: since
in: query
schema:
type: string
description: Time window such as 3months, 7days or 24hours.
- name: dedupeBy
in: query
schema:
type: string
enum: [sourceDocumentSN, sourceDocumentId, id]
default: sourceDocumentSN
description: Field used to count distinct business documents.
- name: status
in: query
schema:
type: string
- name: sourceSystem
in: query
schema:
type: string
- name: taskMode
in: query
schema:
type: string
responses:
"200":
description: Counts grouped by status and source system, plus the deduplicated total.
content:
application/json:
schema:
type: object
/v1/approval-runs/pick:
get:
tags: [Approval Runs]
operationId: pickApprovalRuns
x-implementation-status: implemented
summary: Pick likely approval runs by document number or trace key
parameters:
- $ref: ../components/parameters.yaml#/CorpId
- name: query
in: query
schema:
type: string
- name: sn
in: query
schema:
type: string
description: Source document number for direct lookup.
- name: batch
in: query
schema:
type: string
description: Optional simulation batch ID.
- name: latest
in: query
schema:
type: boolean
- name: fields
in: query
schema:
type: string
description: Comma-separated response fields.
- name: limit
in: query
schema:
type: integer
default: 20
- name: maxScan
in: query
schema:
type: integer
default: 1000
responses:
"200":
description: Picked records and suggested next actions.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/approval-runs/bridge:
get:
tags: [Approval Runs]
operationId: getApprovalRunLangfuseBridge
x-implementation-status: planned
summary: Resolve approval runs to Langfuse trace or session hints
parameters:
- $ref: ../components/parameters.yaml#/CorpId
- name: recordId
in: query
schema:
type: string
- name: sourceDocumentSN
in: query
schema:
type: string
- name: sourceDocumentId
in: query
schema:
type: string
- name: simulationBatchId
in: query
schema:
type: string
responses:
"200":
description: Trace/session bridge hints.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/BridgeResponse
/v1/approval-runs/url:
get:
tags: [Approval Runs]
operationId: getApprovalRunUrl
x-implementation-status: implemented
summary: Get Seal AI result URL and optional source document URL
parameters:
- $ref: ../components/parameters.yaml#/CorpId
- name: recordId
in: query
schema:
type: string
- name: sourceDocumentSN
in: query
schema:
type: string
- name: sourceDocumentId
in: query
schema:
type: string
responses:
"200":
description: Seal AI result URL and source document URL.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/RunUrlResponse
/v1/approval-runs/{recordId}:
parameters:
- $ref: ../components/parameters.yaml#/RecordId
get:
tags: [Approval Runs]
operationId: getApprovalRun
x-implementation-status: implemented
summary: Get wrapped approval run detail
parameters:
- name: summary
in: query
schema:
type: boolean
- name: fields
in: query
schema:
type: string
description: Comma-separated field paths such as metadata,document.fields,result.summary.
responses:
"200":
description: Approval run detail plus stable aliases and human result.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/approval-runs/{recordId}/cited-rules:
parameters:
- $ref: ../components/parameters.yaml#/RecordId
get:
tags: [Approval Runs]
operationId: getApprovalRunCitedRules
x-implementation-status: implemented
summary: Extract rules cited or matched by the AI result
responses:
"200":
description: Cited rule summaries.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/approval-runs/{recordId}/document-summary:
parameters:
- $ref: ../components/parameters.yaml#/RecordId
get:
tags: [Approval Runs]
operationId: getApprovalRunDocumentSummary
x-implementation-status: implemented
summary: Get key document fields and compact AI/manual result
responses:
"200":
description: Document summary.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/approval-runs/{recordId}/attachments:
parameters:
- $ref: ../components/parameters.yaml#/RecordId
get:
tags: [Approval Runs]
operationId: getApprovalRunAttachments
x-implementation-status: implemented
summary: List compact attachment metadata
parameters:
- name: summary
in: query
schema:
type: boolean
responses:
"200":
description: Attachment metadata.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/approval-runs/{recordId}/result:
parameters:
- $ref: ../components/parameters.yaml#/RecordId
get:
tags: [Approval Runs]
operationId: getApprovalRunResult
x-implementation-status: implemented
summary: Get AI result, optionally as a compact summary
parameters:
- name: summary
in: query
schema:
type: boolean
responses:
"200":
description: AI result or summary.
content:
application/json:
schema:
type: object
additionalProperties: true
-50
View File
@@ -1,50 +0,0 @@
paths:
/v1/auth/diagnose:
get:
tags: [Auth]
operationId: diagnoseAuth
x-implementation-status: planned
summary: Diagnose wrapped source-to-Seal authentication
parameters:
- $ref: ../components/parameters.yaml#/CorpId
responses:
"200":
description: Authentication stage diagnosis.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/AuthDiagnosis
/v1/whoami:
get:
tags: [Auth]
operationId: whoami
x-implementation-status: implemented
summary: Get current wrapped Seal identity
parameters:
- $ref: ../components/parameters.yaml#/CorpId
responses:
"200":
description: Current Seal user and tenant.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/WhoamiResponse
"401":
$ref: ../components/responses.yaml#/Unauthorized
/v1/session:
get:
tags: [Auth]
operationId: getSession
x-implementation-status: implemented
summary: Get current wrapped Seal session metadata
parameters:
- $ref: ../components/parameters.yaml#/CorpId
responses:
"200":
description: Current session metadata.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/SessionResponse
"401":
$ref: ../components/responses.yaml#/Unauthorized
-51
View File
@@ -1,51 +0,0 @@
paths:
/v1/corps:
get:
tags: [Corps]
operationId: listCorps
x-implementation-status: implemented
summary: List configured enterprises
responses:
"200":
description: Configured enterprises.
content:
application/json:
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/CorpSummary
/v1/corps/current:
get:
tags: [Corps]
operationId: getCurrentCorp
x-implementation-status: planned
summary: Get current enterprise
description: Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.
responses:
"200":
description: Current enterprise.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/CorpSummary
/v1/corps/current/switch:
post:
tags: [Corps]
operationId: switchCurrentCorp
x-implementation-status: planned
summary: Switch current enterprise
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/SwitchCorpRequest
responses:
"200":
description: Switched enterprise.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/SwitchCorpResponse
"404":
$ref: ../components/responses.yaml#/NotFound
-80
View File
@@ -1,80 +0,0 @@
/v1/corps:
$ref: ./corps.yaml#/paths/~1v1~1corps
/v1/corps/current:
$ref: ./corps.yaml#/paths/~1v1~1corps~1current
/v1/corps/current/switch:
$ref: ./corps.yaml#/paths/~1v1~1corps~1current~1switch
/v1/source/config:
$ref: ./source.yaml#/paths/~1v1~1source~1config
/v1/auth/diagnose:
$ref: ./auth.yaml#/paths/~1v1~1auth~1diagnose
/v1/whoami:
$ref: ./auth.yaml#/paths/~1v1~1whoami
/v1/session:
$ref: ./auth.yaml#/paths/~1v1~1session
/v1/approval/context:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1context
/v1/approval/search:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1search
/v1/approval/rules:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1rules
/v1/approval/rules/{ruleId}:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1rules~1{ruleId}
/v1/approval/rule-versions:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1rule-versions
/v1/approval/rule-versions/{versionId}:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1rule-versions~1{versionId}
/v1/approval/rules/by-version:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1rules~1by-version
/v1/approval/rule-versions/publish:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1rule-versions~1publish
/v1/approval/documents:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1documents
/v1/approval/documents/{documentId}:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1documents~1{documentId}
/v1/approval/style-preferences:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1style-preferences
/v1/preferences:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1preferences
/v1/preferences/decision:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1preferences~1decision
/v1/approval-runs:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs
/v1/approval-runs/summary:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1summary
/v1/approval-runs/stats:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1stats
/v1/approval-runs/pick:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1pick
/v1/approval-runs/bridge:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1bridge
/v1/approval-runs/url:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1url
/v1/approval-runs/{recordId}:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1{recordId}
/v1/approval-runs/{recordId}/cited-rules:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1{recordId}~1cited-rules
/v1/approval-runs/{recordId}/document-summary:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1{recordId}~1document-summary
/v1/approval-runs/{recordId}/attachments:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1{recordId}~1attachments
/v1/approval-runs/{recordId}/result:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1{recordId}~1result
/v1/simulation/create-batch:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1create-batch
/v1/simulation/create-material-pack-batch:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1create-material-pack-batch
/v1/simulation/batches:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1batches
/v1/simulation/batch/{batchId}:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1batch~1{batchId}
/v1/simulation/batches/{batchId}/records:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1batches~1{batchId}~1records
/v1/simulation/templates:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1templates
/v1/simulation/integration-status:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1integration-status
/v1/simulation/hosecloud-integrations:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1hosecloud-integrations
/v1/material-packages/upload:
$ref: ./simulation.yaml#/paths/~1v1~1material-packages~1upload
-173
View File
@@ -1,173 +0,0 @@
paths:
/v1/simulation/create-batch:
post:
tags: [Simulation]
operationId: createSimulationBatch
x-implementation-status: implemented
summary: Create a simulation batch
requestBody:
required: true
content:
application/json:
schema:
type: object
additionalProperties: true
responses:
"200":
description: Created batch id.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/simulation/create-material-pack-batch:
post:
tags: [Simulation]
operationId: createMaterialPackBatch
x-implementation-status: planned
summary: Create a material pack simulation batch
requestBody:
required: true
content:
application/json:
schema:
type: object
additionalProperties: true
responses:
"200":
description: Created batch id.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/simulation/batches:
get:
tags: [Simulation]
operationId: listSimulationBatches
x-implementation-status: implemented
summary: List simulation batches
parameters:
- name: limit
in: query
schema:
type: integer
description: Max batches to return.
responses:
"200":
description: Simulation batches.
content:
application/json:
schema:
type: array
items:
type: object
additionalProperties: true
/v1/simulation/batch/{batchId}:
parameters:
- $ref: ../components/parameters.yaml#/BatchId
get:
tags: [Simulation]
operationId: getSimulationBatch
x-implementation-status: implemented
summary: Get a simulation batch detail including echoed create params
responses:
"200":
description: Simulation batch detail.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/simulation/batches/{batchId}/records:
parameters:
- $ref: ../components/parameters.yaml#/BatchId
get:
tags: [Simulation]
operationId: getSimulationBatchRecords
x-implementation-status: planned
summary: Get wrapped simulation batch records
parameters:
- name: query
in: query
schema:
type: string
description: Optional local contains filter for record/document/trace identifiers.
responses:
"200":
description: Compact simulation records and bridge hints.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/simulation/templates:
get:
tags: [Simulation]
operationId: listSimulationTemplates
x-implementation-status: planned
summary: List simulation test templates
responses:
"200":
description: Simulation templates.
content:
application/json:
schema:
type: array
items:
type: object
additionalProperties: true
/v1/simulation/integration-status:
get:
tags: [Simulation]
operationId: getSimulationIntegrationStatus
x-implementation-status: planned
summary: Get available source integration status for simulation
responses:
"200":
description: Integration status.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/simulation/hosecloud-integrations:
get:
tags: [Simulation]
operationId: listSimulationHosecloudIntegrations
x-implementation-status: planned
summary: List hosecloud source integrations available for simulation
responses:
"200":
description: Hosecloud integrations.
content:
application/json:
schema:
type: array
items:
type: object
additionalProperties: true
/v1/material-packages/upload:
post:
tags: [Simulation]
operationId: uploadMaterialPackage
x-implementation-status: planned
summary: Upload a material package ZIP for simulation
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
properties:
file:
type: string
format: binary
responses:
"200":
description: Parsed material package with schema config.
content:
application/json:
schema:
type: object
additionalProperties: true
-18
View File
@@ -1,18 +0,0 @@
paths:
/v1/source/config:
get:
tags: [Source]
operationId: getSourceConfig
x-implementation-status: planned
summary: Resolve source-derived Seal enterprise config
parameters:
- $ref: ../components/parameters.yaml#/CorpId
responses:
"200":
description: Redacted Seal enterprise config.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/SourceConfig
"401":
$ref: ../components/responses.yaml#/Unauthorized
-2
View File
@@ -32,8 +32,6 @@
"release": "bun run scripts/release.ts",
"dev:override": "bun run scripts/dev-override.ts",
"dev:link": "bun run scripts/dev-override.ts",
"openapi:bundle": "bun run scripts/bundle-openapi.ts",
"openapi:raw": "bun run scripts/generate-raw-openapi.ts",
"test": "bun test",
"prepare": "git config core.hooksPath .githooks"
},
+1 -8
View File
@@ -85,12 +85,6 @@ skillContent = skillContent.replace(/\(v[\d.]+\)/g, `(v${nextVersion})`);
writeFileSync(skillPath, skillContent);
console.log("✓ Updated skills/seal-use/SKILL.md");
// 4. openapi/openapi.yaml
const openapiPath = join(ROOT, "openapi", "openapi.yaml");
let openapiContent = readFileSync(openapiPath, "utf-8");
openapiContent = openapiContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
writeFileSync(openapiPath, openapiContent);
console.log("✓ Updated openapi/openapi.yaml");
// 5. Sync to global ~/.agents/skills/seal-use/ if present
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "seal-use");
@@ -105,8 +99,7 @@ if (existsSync(globalSkillDir)) {
}
// 6. Rebuild bundles
console.log("==> Rebuilding OpenAPI and binary bundles...");
execSync("bun run openapi:bundle", { cwd: ROOT, stdio: "inherit" });
console.log("==> Rebuilding binary bundle...");
execSync("bun run build:binary", { cwd: ROOT, stdio: "inherit" });
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
-78
View File
@@ -1,78 +0,0 @@
#!/usr/bin/env bun
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import YAML from "yaml";
type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
const inputFile = resolve("openapi/openapi.yaml");
const outputFile = resolve("dist/openapi.json");
const bundled = bundle(inputFile, new Set());
mkdirSync(dirname(outputFile), { recursive: true });
writeFileSync(outputFile, `${JSON.stringify(bundled, null, 2)}\n`);
console.log(`Wrote ${outputFile}`);
function bundle(filePath: string, seen: Set<string>): Json {
const absolutePath = resolve(filePath);
if (seen.has(absolutePath)) {
throw new Error(`Circular OpenAPI reference: ${absolutePath}`);
}
const parsed = YAML.parse(readFileSync(absolutePath, "utf8")) as Json;
return resolveReferences(parsed, absolutePath, new Set([...seen, absolutePath]));
}
function resolveReferences(value: Json, currentFile: string, seen: Set<string>): Json {
if (Array.isArray(value)) {
return value.map((item) => resolveReferences(item, currentFile, seen));
}
if (!isObject(value)) return value;
if (typeof value.$ref === "string" && isFileReference(value.$ref)) {
const [refPath, pointer = ""] = value.$ref.split("#");
const refFile = refPath ? resolve(dirname(currentFile), refPath) : currentFile;
const target = pointer ? resolvePointer(bundle(refFile, seen), pointer) : bundle(refFile, seen);
return resolveReferences(target, refFile, seen);
}
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [
key,
resolveReferences(item as Json, currentFile, seen)
])
);
}
function isFileReference(ref: string) {
return !ref.startsWith("#") && !/^[a-z][a-z0-9+.-]*:/i.test(ref);
}
function resolvePointer(document: Json, pointer: string): Json {
const path = pointer.replace(/^#/, "");
if (!path) return document;
return path
.split("/")
.filter(Boolean)
.map((part) => part.replace(/~1/g, "/").replace(/~0/g, "~"))
.reduce((target: Json, key) => {
if (!isObject(target) && !Array.isArray(target)) {
throw new Error(`Invalid JSON pointer segment "${key}" in ${pointer}`);
}
const next = (target as Record<string, Json>)[key];
if (next === undefined) {
throw new Error(`Missing JSON pointer segment "${key}" in ${pointer}`);
}
return next;
}, document);
}
function isObject(value: Json): value is { [key: string]: Json } {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
File diff suppressed because it is too large. Load diff
+2 -8
View File
@@ -65,9 +65,6 @@ seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]
seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]
seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]
seal-use documents delete <documentId> --yes [--corp <corpId>]
seal-use service <start|stop|restart|status|logs> [--port 8787] [--host 127.0.0.1] [--lines 50]
seal-use http [--port 8787] [--host 127.0.0.1]
seal-use serve [--port 8787]
seal-use update [--check] [--force] [--version <v>]
seal-use update check
seal-use update changelog [--limit <n>]
@@ -203,13 +200,11 @@ seal-use simulation package-upload <材料包.zip> --corp <corpId>
}
```
`seal-use service <start|stop|restart|status|logs>` manages the persistent background service daemon with embedded HTTP server (serving `/docs`, `/openapi.json`, and `POST /api/cli`). `status` returns the PID, version, host, port, active HTTP URL, state directory, PID file, and log file.
`seal-use update` checks and installs the latest official release, preserves the service state when needed, and refreshes the installed Agent Skill. The installation method is handled automatically and should not be exposed in user-facing explanations. `seal-use update --check` only reports available releases, and `seal-use update changelog` reads release history.
`seal-use update` checks and installs the latest official release, and refreshes the installed Agent Skill. The installation method is handled automatically and should not be exposed in user-facing explanations. `seal-use update --check` only reports available releases, and `seal-use update changelog` reads release history.
System diagnostic & embedded architecture specifications:
- `seal-use doctor [--quiet]` executes a comprehensive read-only environment diagnostic health check (runtime executable, filesystem paths health, enterprise assets summary, daemon status) with zero disk footprint.
- `seal-use doctor [--quiet]` executes a comprehensive read-only environment diagnostic health check (runtime executable, filesystem paths health, enterprise assets summary) with zero disk footprint.
- `seal-use doctor tenant [--corp <corpId>] [--quiet]` probes the tenant-level health contract: verifies user identity and administrative permissions, checks AI approval quota balance (`balance` and `deductionAmount`), inspects active rules count and unreleased draft safety, validates webhook integration readiness, and verifies 1-to-1 environment pairing with test staging. Outputs clean JSON on `stdout` and a visual terminal dashboard on `stderr`.
- `seal-use doctor guide` reads the complete embedded system architecture & directory specification whitepaper directly from binary memory without touching disk.
- `seal-use doctor paths` outputs compact JSON audit of all filesystem paths touched by the CLI.
@@ -452,7 +447,6 @@ seal-use simulation integrations --corp <corpId>
## Failure Handling
- CLI commands are short-lived processes. In-memory auth/search caches only live for that single process. Use `seal-use service restart` after updates so the optional local service picks up new code.
- If no run is found by `sourceDocumentSN`, retry with `sourceDocumentId` or a broader `query`.
- If date-based summaries look wrong, pass `--timezone Asia/Shanghai` and an explicit `--date`.
- If `langfuseTraceId` is missing, use `langfuseSessionFallback`.
-9
View File
@@ -196,15 +196,6 @@ describe("CLI version & help handling", () => {
expect(parsed.fileCount).toBeGreaterThan(5);
});
test("openapi command outputs embedded OpenAPI specification", () => {
const result = runCli(["openapi"]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.openapi).toBe("3.1.0");
expect(parsed.info.title).toContain("seal-use");
expect(parsed.paths).toHaveProperty("/v1/corps");
});
test("update check subcommand outputs structured check payload", () => {
const result = runCli(["update", "check"]);
expect(result.status).toBe(0);
-23
View File
@@ -1,23 +0,0 @@
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(() => {});
}
-8
View File
@@ -1,8 +0,0 @@
import { getOpenApiSchema } from "../../core/embedded-openapi.js";
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export function handleOpenApiCommand(args: ParsedArgs) {
const schema = getOpenApiSchema();
printJson(schema, { ...outputOptions(args.options), allowFull: true });
}
-34
View File
@@ -1,34 +0,0 @@
import { homedir } from "node:os";
import { join } from "node:path";
import { VERSION } from "../../version.js";
import { runServiceCommand } from "../service.js";
import { printJson } from "../printer.js";
import { numberOption, stringOption } from "../parser.js";
import type { CliRuntime, ParsedArgs } from "../types.js";
export const STATE_DIR = join(homedir(), ".config", "seal-use");
export async function handleServiceCommand(
action: string | undefined,
runtime: CliRuntime,
args?: ParsedArgs
) {
const port = args ? numberOption(args.options.port) ?? numberOption(args.options.p) : undefined;
const host = args ? stringOption(args.options.host) ?? stringOption(args.options.h) : undefined;
const maxLines = args ? numberOption(args.options.lines) ?? numberOption(args.options.n) : undefined;
const result = await runServiceCommand(
action,
{
appRoot: runtime.appRoot,
entryFile: runtime.entryFile,
stateDir: STATE_DIR,
version: VERSION,
launcher: runtime.launcher,
port,
host
},
{ maxLines }
);
if (result !== undefined) printJson(result);
}
+36 -77
View File
@@ -6,9 +6,7 @@ import { normalizeBeijingIso } from "../../core/config/timestamps.js";
import { readInstalledSkillVersion } from "../../core/embedded-skill.js";
import { saveUpdateCache } from "../../core/update-cache.js";
import { VERSION, IS_RELEASE } from "../../version.js";
import { runServiceCommand, serviceStatus, type ServiceConfig } from "../service.js";
import { printJson } from "../printer.js";
import { STATE_DIR } from "./service.js";
import type { CliRuntime } from "../types.js";
const DEFAULT_GITHUB_REPO = "yunyingk/seal-use";
@@ -27,14 +25,6 @@ export type UpdateOptions = {
};
export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOptions = {}) {
const serviceConfig = {
appRoot: runtime.appRoot,
entryFile: runtime.entryFile,
stateDir: STATE_DIR,
version: VERSION,
launcher: runtime.launcher
};
const repo = options.repo
|| process.env[GITHUB_REPO_ENV]?.trim()
|| process.env[LEGACY_GITHUB_REPO_ENV]?.trim()
@@ -140,9 +130,6 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
return;
}
const wasRunning = serviceStatus(serviceConfig).running;
if (wasRunning) await runServiceCommand("stop", serviceConfig);
try {
runCommand("git", ["-C", runtime.appRoot, "pull", "--ff-only"]);
} catch (err) {
@@ -150,11 +137,8 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
}
runCommand("bun", ["install"], { cwd: runtime.appRoot });
if (wasRunning) await runServiceCommand("start", serviceConfig);
printJson({
updated: true,
serviceRestarted: wasRunning,
version: VERSION,
mode: "source"
});
@@ -164,7 +148,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
// 3. Homebrew managed mode
if (isHomebrewInstall()) {
try {
await handleHomebrewUpdate(options, serviceConfig, repo, targetVersion);
await handleHomebrewUpdate(options, repo, targetVersion);
return;
} catch (err) {
console.error(
@@ -276,9 +260,6 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
}
// Download binary or archive
const wasRunning = serviceStatus(serviceConfig).running;
if (wasRunning) await runServiceCommand("stop", serviceConfig);
const execPath = process.execPath;
const execDir = dirname(execPath);
const tmpDir = join(execDir, `.tmp-update-${Date.now()}`);
@@ -320,8 +301,6 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
renameSync(newBinaryPath, execPath);
}
if (wasRunning) await runServiceCommand("start", serviceConfig);
// Refresh the Agent Skill from the binary that is now on disk — never from this process.
//
// `renameSync` above advanced the file at `execPath`, but this process keeps executing the
@@ -342,7 +321,6 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
updated: true,
fromVersion: VERSION,
toVersion: latestVersion,
serviceRestarted: wasRunning,
skillSynced: skillSync.targetDir ?? false,
skillVersion: skillSync.version ?? false,
mode: "binary"
@@ -509,7 +487,6 @@ export function isHomebrewInstall(
async function handleHomebrewUpdate(
options: UpdateOptions,
serviceConfig: ServiceConfig,
repo: string,
targetVersion?: string
): Promise<void> {
@@ -575,66 +552,49 @@ async function handleHomebrewUpdate(
console.error("ℹ️ 检测到当前 seal-use 由 Homebrew 管理。");
console.error("📦 正在通过 Homebrew 极速更新: brew update && brew upgrade seal-use ...");
const wasRunning = serviceStatus(serviceConfig).running;
if (wasRunning) await runServiceCommand("stop", serviceConfig);
const installedBefore = homebrewInstalledVersion();
const alreadyLatestBeforeUpdate = installedBefore
? !isNewerVersion(latestVersion, installedBefore)
: false;
let alreadyLatest = alreadyLatestBeforeUpdate;
let updateError: unknown;
try {
// `brew update` refreshes all configured taps. Passing a tap name here is
// parsed as a formula upgrade by newer Homebrew versions (and fails with
// "No available formula ... tap").
const tapUpdate = await runHomebrewCommand(
["update"],
"🔄 [1/2] 正在刷新 Homebrew 软件源(可能需要几分钟)..."
);
// `brew update` refreshes all configured taps. Passing a tap name here is
// parsed as a formula upgrade by newer Homebrew versions (and fails with
// "No available formula ... tap").
const tapUpdate = await runHomebrewCommand(
["update"],
"🔄 [1/2] 正在刷新 Homebrew 软件源(可能需要几分钟)..."
);
if (tapUpdate.status !== 0) {
const msg = tapUpdate.stderr?.trim() || tapUpdate.stdout?.trim();
throw new Error(`brew update failed (exit ${tapUpdate.status}): ${msg || "unknown error"}`);
}
// 2. Upgrade the formula
const upgradeRes = await runHomebrewCommand(
["upgrade", "seal-use"],
"⬆️ [2/2] 正在升级 seal-use..."
);
const outCombined = `${upgradeRes.stdout || ""} ${upgradeRes.stderr || ""}`;
const brewReportsAlreadyLatest =
outCombined.includes("already installed") || outCombined.includes("latest version already installed");
if (upgradeRes.status !== 0 && !brewReportsAlreadyLatest) {
throw new Error(
`brew upgrade seal-use failed (exit ${upgradeRes.status}): ${upgradeRes.stderr.trim() || upgradeRes.stdout.trim()}`
);
}
const installedVersion = homebrewInstalledVersion();
if (installedVersion && isNewerVersion(latestVersion, installedVersion)) {
throw new Error(
`Homebrew still has seal-use v${installedVersion}; expected v${latestVersion}. ` +
"Refresh the tap and run `brew upgrade seal-use` again."
);
}
alreadyLatest = alreadyLatestBeforeUpdate;
} catch (err) {
updateError = err;
throw err;
} finally {
// 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);
}
if (tapUpdate.status !== 0) {
const msg = tapUpdate.stderr?.trim() || tapUpdate.stdout?.trim();
throw new Error(`brew update failed (exit ${tapUpdate.status}): ${msg || "unknown error"}`);
}
// 2. Upgrade the formula
const upgradeRes = await runHomebrewCommand(
["upgrade", "seal-use"],
"⬆️ [2/2] 正在升级 seal-use..."
);
const outCombined = `${upgradeRes.stdout || ""} ${upgradeRes.stderr || ""}`;
const brewReportsAlreadyLatest =
outCombined.includes("already installed") || outCombined.includes("latest version already installed");
if (upgradeRes.status !== 0 && !brewReportsAlreadyLatest) {
throw new Error(
`brew upgrade seal-use failed (exit ${upgradeRes.status}): ${upgradeRes.stderr.trim() || upgradeRes.stdout.trim()}`
);
}
const installedVersion = homebrewInstalledVersion();
if (installedVersion && isNewerVersion(latestVersion, installedVersion)) {
throw new Error(
`Homebrew still has seal-use v${installedVersion}; expected v${latestVersion}. ` +
"Refresh the tap and run `brew upgrade seal-use` again."
);
}
alreadyLatest = alreadyLatestBeforeUpdate;
// Refresh installed skill through new binary
try {
spawnSync("seal-use", ["skill", "install"], { stdio: "ignore" });
@@ -653,7 +613,6 @@ async function handleHomebrewUpdate(
previousVersion: VERSION,
latestVersion,
mode: "homebrew",
serviceRestarted: wasRunning,
message: alreadyLatest
? `seal-use is already at the latest version v${latestVersion} in Homebrew`
: `Successfully upgraded seal-use to v${latestVersion} via Homebrew`
+4 -30
View File
@@ -202,25 +202,14 @@ describe("help coverage", () => {
}
});
test("service lifecycle exposes area and command help", () => {
const area = renderHelp(["service"]);
expect(area).toContain("seal-use service - Background HTTP service lifecycle");
expect(area).toContain("seal-use service start");
expect(area).toContain("seal-use service logs");
expect(renderHelp(["service", "logs"])).toContain("seal-use service logs");
});
test("stop shortcut and server alias resolve to help", () => {
expect(renderHelp(["stop"])).toContain("seal-use stop");
expect(renderHelp(["server"])).toContain("seal-use mcp");
});
test("global help is generated from the registry and lists lifecycle commands", () => {
test("global help is generated from the registry", () => {
const help = renderHelp([]);
expect(help).toContain("seal-use CLI");
expect(help).toContain("seal-use version");
expect(help).toContain("seal-use service start");
expect(help).toContain("seal-use stop");
});
test("config aliases resolve to the documented commands", () => {
@@ -229,28 +218,13 @@ describe("help coverage", () => {
});
test("singleton areas do not advertise a nonexistent subcommand help", () => {
expect(renderHelp(["http"])).not.toContain("<command> --help");
expect(renderHelp(["stop"])).not.toContain("<command> --help");
expect(renderHelp(["mcp-config"])).not.toContain("<command> --help");
expect(renderHelp(["probe"])).not.toContain("<command> --help");
expect(renderHelp(["corps"])).toContain("Run 'seal-use corps <command> --help'");
});
});
describe("CLI help execution for lifecycle commands", () => {
test("seal-use service --help prints service commands with exitCode 0", async () => {
const result = await runCli(["service", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("seal-use service start");
expect(result.stdout).toContain("seal-use service status");
});
test("seal-use stop --help prints stop help with exitCode 0", async () => {
const result = await runCli(["stop", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("seal-use stop");
});
describe("CLI help execution for domain commands", () => {
test("approval-runs --help prints updated count and export parameter usage", async () => {
const result = await runCli(["approval-runs", "--help"]);
expect(result.exitCode).toBe(0);
-76
View File
@@ -1166,82 +1166,6 @@ export const HELP_REGISTRY: AreaHelp[] = [
}
]
},
{
area: "http",
title: "HTTP server",
description: "Run interactive HTTP server.",
commands: [
{
name: "",
summary: "Start HTTP daemon",
usage: [
"seal-use http [--port 8787] [--host 127.0.0.1]",
"seal-use serve [--port 8787]"
]
}
]
},
{
area: "service",
title: "Background HTTP service lifecycle",
description: "Start, stop, restart, inspect, and read logs from the standalone seal-use HTTP service daemon.",
commands: [
{
name: "start",
summary: "Start the background service daemon",
usage: ["seal-use service start [--port 8787] [--host 127.0.0.1]"]
},
{
name: "stop",
summary: "Stop the background service daemon",
usage: ["seal-use service stop"]
},
{
name: "restart",
summary: "Restart the background service daemon",
usage: ["seal-use service restart [--port 8787] [--host 127.0.0.1]"]
},
{
name: "status",
summary: "Show service daemon status",
usage: ["seal-use service status"]
},
{
name: "logs",
summary: "Print recent service daemon logs",
usage: ["seal-use service logs [--lines 50]"]
},
{
name: "run",
summary: "Run the service in the foreground",
usage: ["seal-use service run [--port 8787] [--host 127.0.0.1]"]
}
]
},
{
area: "stop",
title: "Stop the background service",
description: "Shortcut for stopping the background seal-use HTTP service daemon.",
commands: [
{
name: "",
summary: "Stop the background service daemon",
usage: ["seal-use stop"]
}
]
},
{
area: "openapi",
title: "OpenAPI specification",
description: "Output embedded OpenAPI JSON specification.",
commands: [
{
name: "",
summary: "Print OpenAPI schema",
usage: ["seal-use openapi"]
}
]
},
{
area: "doctor",
title: "System diagnostic and environment health check",
-7
View File
@@ -61,7 +61,6 @@ describe("CLI read-only classification", () => {
["deploy", "hosecloud", "status", "--corp", "corp-a"],
["preferences", "get"],
["doctor", "tenant", "--corp", "corp-a"],
["openapi"],
["version"],
["mcp-config"]
]) {
@@ -93,12 +92,8 @@ describe("CLI read-only classification", () => {
["users", "create"],
["config", "test-dir", "corp-a"],
["skill", "install"],
["service", "start"],
["service", "run"],
["mcp"],
["http"],
["update"],
["stop"],
["auth", "keys"],
["analytics", "analyze", "record-1"],
["tool", "seal_approval_rule_create", "--json", "{}"],
@@ -124,8 +119,6 @@ describe("CLI read-only classification", () => {
expect(isReadOnlyCliCommand(["doctor"])).toBe(true);
expect(isReadOnlyCliCommand(["doctor", "guide"])).toBe(true);
expect(isReadOnlyCliCommand(["doctor", "unknown-subcommand"])).toBe(false);
// `openapi` is allow-listed as the bare form only.
expect(isReadOnlyCliCommand(["openapi", "extra"])).toBe(false);
});
test("probe is read-only bare or with its enterprise selector, but not beyond", () => {
+2 -4
View File
@@ -24,7 +24,7 @@ const AREA_ALIASES: Record<string, string> = {
* Deliberately excluded even though they look harmless: anything that writes local config
* (`corps switch`, `config test-dir`, `config mode <value>`, `config lint <subaction>`), mints
* or prints credentials (`auth keys`, `corps keys`),
* self-updates (`update`), or stands up a long-running server (`http`, `mcp`, `service run`).
* self-updates (`update`), or stands up a long-running server (`mcp`).
*/
const READ_ONLY_COMMANDS: Record<string, string[]> = {
corps: ["list", "search", "get", "current"],
@@ -80,12 +80,10 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
analytics: ["insight", "risks", "performance", "export"],
source: ["config"],
skill: ["dump", "status"],
service: ["status", "logs"],
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: [""]
probe: [""]
};
/**
+1 -28
View File
@@ -35,10 +35,6 @@ export const UPDATE_ALIASES = new Set([
export const KNOWN_AREAS = new Set([
"config",
"service",
"stop",
"http",
"serve",
"update",
"corps",
"corp",
@@ -65,7 +61,6 @@ export const KNOWN_AREAS = new Set([
"server",
"mcp-config",
"skill",
"openapi",
"probe",
"doctor",
"changelog",
@@ -74,14 +69,12 @@ export const KNOWN_AREAS = new Set([
export type { CliResult, CliRunOptions } from "./types.js";
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
const STANDING_COMMANDS = new Set(["server", "mcp"]);
function isStandingCommand(argv: string[]): boolean {
if (!argv.length) return false;
const first = argv[0]?.toLowerCase();
const second = argv[1]?.toLowerCase();
if (first && STANDING_COMMANDS.has(first)) return true;
if ((first === "service" || first === "daemon") && second === "run") return true;
return false;
}
@@ -204,11 +197,6 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "openapi") {
(await import("./commands/openapi.js")).handleOpenApiCommand(args);
return;
}
if (area === "mcp-config") {
(await import("./commands/mcp.js")).printMcpConfig();
return;
@@ -244,21 +232,6 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "service") {
await (await import("./commands/service.js")).handleServiceCommand(action, runtime, args);
return;
}
if (area === "stop") {
await (await import("./commands/service.js")).handleServiceCommand("stop", runtime, args);
return;
}
if (area === "http" || area === "serve") {
await (await import("./commands/http.js")).handleHttpCommand(args);
return;
}
if (isUpdate || area === "changelog") {
if (isUpdate && rawArea !== "update") {
console.error(`⚠️ Notice: '${rawArea}' is an alias for 'seal-use update'. Please use 'seal-use update' instead.`);
-97
View File
@@ -1,97 +0,0 @@
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 { serviceStatus, readServiceLogs, runServiceCommand } from "./service.js";
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("service lifecycle state", () => {
test("clears a stale pid file instead of reporting another process as running", () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
writeFileSync(join(stateDir, "service.pid"), "999999\n");
const status = serviceStatus({
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir,
version: "0.4.2"
});
expect(status.running).toBe(false);
expect(status.pid).toBeUndefined();
expect(status.port).toBe(8787);
expect(status.host).toBe("127.0.0.1");
expect(status.url).toBeUndefined();
});
test("respects custom port and host configuration", () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
const status = serviceStatus({
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir,
version: "0.10.7",
port: 9090,
host: "0.0.0.0"
});
expect(status.port).toBe(9090);
expect(status.host).toBe("0.0.0.0");
});
test("reads service log file lines safely", () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
const emptyLogs = readServiceLogs({
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
});
expect(emptyLogs.lines).toEqual([]);
expect(emptyLogs.totalLines).toBe(0);
const logFile = join(stateDir, "service.log");
writeFileSync(logFile, "line 1\nline 2\nline 3\nline 4\nline 5\n");
const logs = readServiceLogs(
{
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
},
3
);
expect(logs.totalLines).toBe(5);
expect(logs.lines).toEqual(["line 3", "line 4", "line 5"]);
});
test("runServiceCommand handles logs and status actions", async () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
const status = await runServiceCommand("status", {
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
});
expect(status).toHaveProperty("running");
const logs = await runServiceCommand("logs", {
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
});
expect(logs).toHaveProperty("lines");
});
});
-279
View File
@@ -1,279 +0,0 @@
import { spawn, execFileSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { formatBeijingIso } from "../core/config/timestamps.js";
import { startHttpServer, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST } from "../http/server.js";
export type ServiceConfig = {
appRoot: string;
entryFile: string;
stateDir: string;
version?: string;
launcher?: {
command: string;
args?: string[];
};
port?: number;
host?: string;
};
export async function runServiceCommand(
action: string | undefined,
config: ServiceConfig,
options: { quiet?: boolean; maxLines?: number } = {}
) {
switch (action) {
case "run":
await runService(config);
return undefined;
case "start":
return startService(config);
case "stop":
case "kill":
case "down":
case "shutdown":
return stopService(config, options);
case "restart":
stopService(config, { quiet: true });
return startService(config);
case "logs":
case "log":
return readServiceLogs(config, options.maxLines);
case "status":
case undefined:
return serviceStatus(config);
default:
throw new Error("Usage: seal-use service <start|stop|restart|status|logs>");
}
}
export function serviceStatus(config: ServiceConfig) {
const pidFile = getPidFile(config);
const metaFile = getMetaFile(config);
const pid = readServicePid(pidFile);
const running = pid ? isSealHomeProcess(pid, config.appRoot) : false;
if (!running) {
if (pid) rmSync(pidFile, { force: true });
if (existsSync(metaFile)) rmSync(metaFile, { force: true });
}
let storedMeta: { port?: number; host?: string; version?: string } | undefined;
if (running && existsSync(metaFile)) {
try {
storedMeta = JSON.parse(readFileSync(metaFile, "utf8"));
} catch {
// ignore
}
}
const port = config.port ?? storedMeta?.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = config.host ?? storedMeta?.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
const version = config.version ?? storedMeta?.version;
return {
running,
pid: running ? pid : undefined,
version,
port,
host,
url: running ? `http://${host}:${port}` : undefined,
appRoot: config.appRoot,
stateDir: config.stateDir,
pidFile,
logFile: getLogFile(config)
};
}
export function readServiceLogs(config: ServiceConfig, maxLines = 50) {
const logFile = getLogFile(config);
if (!existsSync(logFile)) {
return {
logFile,
lines: [],
totalLines: 0
};
}
const content = readFileSync(logFile, "utf8");
const allLines = content.split("\n").filter(Boolean);
const lines = allLines.slice(-maxLines);
return {
logFile,
lines,
totalLines: allLines.length
};
}
async function runService(config: ServiceConfig) {
const pidFile = getPidFile(config);
const metaFile = getMetaFile(config);
const logFile = getLogFile(config);
ensureStateDir(config.stateDir);
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
writeFileSync(
metaFile,
JSON.stringify(
{
pid: process.pid,
port,
host,
version: config.version,
startedAt: formatBeijingIso()
},
null,
2
),
{ mode: 0o600 }
);
appendLog(logFile, `service starting on http://${host}:${port} pid=${process.pid}`);
let server: Awaited<ReturnType<typeof startHttpServer>> | null = null;
try {
server = await startHttpServer({ port, host, silent: true });
appendLog(logFile, `service listening pid=${process.pid}`);
} catch (err: unknown) {
appendLog(logFile, `service failed to bind port ${port}: ${err instanceof Error ? err.message : String(err)}`);
if (readServicePid(pidFile) === process.pid) {
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
}
throw err;
}
const cleanup = () => {
if (server) {
server.close();
server = null;
}
if (readServicePid(pidFile) === process.pid) {
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
}
appendLog(logFile, `stopped pid=${process.pid}`);
};
await new Promise<void>((resolve) => {
let stopped = false;
const stop = () => {
if (stopped) return;
stopped = true;
cleanup();
process.off("SIGTERM", stop);
process.off("SIGINT", stop);
resolve();
};
process.once("SIGTERM", stop);
process.once("SIGINT", stop);
});
}
function startService(config: ServiceConfig) {
ensureStateDir(config.stateDir);
const current = serviceStatus(config);
if (current.running) {
return current;
}
const launcher = config.launcher ?? { command: process.execPath, args: [config.entryFile] };
const serviceArgs = [
...(launcher.args ?? []),
"service",
"run"
];
if (config.port) serviceArgs.push("--port", String(config.port));
if (config.host) serviceArgs.push("--host", String(config.host));
const child = spawn(launcher.command, serviceArgs, {
cwd: config.appRoot,
detached: true,
stdio: ["ignore", "ignore", "ignore"],
env: process.env
});
child.unref();
const pidFile = getPidFile(config);
writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 });
appendLog(getLogFile(config), `started pid=${child.pid}`);
return { started: true, ...serviceStatus(config) };
}
function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
const pidFile = getPidFile(config);
const metaFile = getMetaFile(config);
const pid = readServicePid(pidFile);
if (!pid || !isSealHomeProcess(pid, config.appRoot)) {
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
return options.quiet ? undefined : { stopped: false, reason: "not running" };
}
process.kill(pid, "SIGTERM");
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
appendLog(getLogFile(config), `stop requested pid=${pid}`);
return options.quiet ? undefined : { stopped: true, pid };
}
/**
* A pid file only proves that *some* process holds that pid. Match the recorded identity as argv
* tokens — the exact `service run` subcommand pair plus a path to this app or a seal-use launcher
* — instead of as substrings anywhere in the command line, so a stale pid cannot make an
* unrelated process look like our daemon and get signalled by `service stop`.
*/
function isSealHomeProcess(pid: number, appRoot: string) {
if (!isProcessRunning(pid)) return false;
try {
const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
const tokens = command.trim().split(/\s+/).filter(Boolean);
const serviceIndex = tokens.indexOf("service");
const runsService = serviceIndex !== -1 && tokens[serviceIndex + 1] === "run";
const isSealUse =
command.includes(appRoot) || tokens.some((token) => /(^|[\\/])(seal-use|seal-home)(\.exe)?$/.test(token));
return runsService && isSealUse;
} catch {
return false;
}
}
function isProcessRunning(pid: number) {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function getPidFile(config: ServiceConfig) {
return join(config.stateDir, "service.pid");
}
function getMetaFile(config: ServiceConfig) {
return join(config.stateDir, "service.json");
}
function getLogFile(config: ServiceConfig) {
return join(config.stateDir, "service.log");
}
function readServicePid(path: string): number | undefined {
if (!existsSync(path)) return undefined;
const pid = Number(readFileSync(path, "utf8").trim());
return Number.isInteger(pid) && pid > 0 ? pid : undefined;
}
function ensureStateDir(stateDir: string) {
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
}
function appendLog(path: string, message: string) {
writeFileSync(path, `${formatBeijingIso()} ${message}\n`, { flag: "a", mode: 0o600 });
}
+3 -3
View File
@@ -1,4 +1,4 @@
import type { ServiceConfig } from "./service.js";
import type { LauncherConfig } from "../core/runtime.js";
export type ParsedArgs = {
command: string[];
@@ -21,13 +21,13 @@ export type CliResult = {
export type CliRunOptions = {
appRoot?: string;
entryFile?: string;
launcher?: ServiceConfig["launcher"];
launcher?: LauncherConfig;
};
export type CliRuntime = {
appRoot: string;
entryFile: string;
launcher?: ServiceConfig["launcher"];
launcher?: LauncherConfig;
};
export type CommandContext = {
-8
View File
@@ -68,14 +68,6 @@ export const EMBEDDED_DIRECTORY_SPECS: DirectorySpec[] = [
accessMode: "read-write",
retention: "persistent"
},
{
name: "后台守护服务日志",
category: "config",
standardPath: "~/.config/seal-use/service.log",
purpose: "常驻后台 HTTP 服务守护进程运行输出日志。",
accessMode: "read-write",
retention: "persistent"
},
{
name: "全局命令行程序",
category: "binary",
-12
View File
@@ -1,12 +0,0 @@
import { describe, expect, test } from "bun:test";
import { getOpenApiSchema } from "./embedded-openapi.js";
describe("embedded-openapi", () => {
test("returns valid OpenAPI 3.x schema object", () => {
const schema = getOpenApiSchema();
expect(schema).toBeDefined();
expect(schema.openapi).toBe("3.1.0");
expect(schema.info).toHaveProperty("title");
expect(schema.paths).toBeDefined();
});
});
-5
View File
@@ -1,5 +0,0 @@
import openapiSchema from "../../dist/openapi.json" with { type: "json" };
export function getOpenApiSchema(): Record<string, unknown> {
return openapiSchema as Record<string, unknown>;
}
-29
View File
@@ -1,29 +0,0 @@
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>`;
}
-106
View File
@@ -1,106 +0,0 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { getOpenApiSchema } from "../core/embedded-openapi.js";
// The bundled contract is what consumers read: `seal-use http` serves it at /openapi.json and
// `dist/openapi.json` is committed. It had drifted from the adapter in both directions — it
// documented /v1/approval/rules/{ruleId} PATCH/DELETE and /v1/approval/documents* that no route
// serves (a caller following it gets 404), and it omitted /v1/approval-runs/stats, which the
// adapter does serve. Marking each operation here turns that drift into a failing test.
//
// What this proves: every operation claimed `implemented` has a matching route in routes.ts, and
// every exact /v1 route in routes.ts is in the contract. What it does not prove: that a
// `planned` operation's *placeholder* prefix is unrouted (prefix branches are matched loosely),
// nor that an operation's request/response schema matches its handler.
const IMPLEMENTATION_KEY = "x-implementation-status";
const OPERATION_METHODS = ["get", "post", "put", "patch", "delete"] as const;
const VALID_STATUSES = ["implemented", "planned"];
type Operation = { method: string; path: string; status: string };
function collectOperations(): Operation[] {
const schema = getOpenApiSchema() as {
paths?: Record<string, Record<string, unknown>>;
};
const operations: Operation[] = [];
for (const [path, pathItem] of Object.entries(schema.paths ?? {})) {
for (const method of OPERATION_METHODS) {
const operation = pathItem[method];
if (operation === undefined) continue;
if (typeof operation !== "object" || operation === null) continue;
const status = (operation as Record<string, unknown>)[IMPLEMENTATION_KEY];
operations.push({ method, path, status: typeof status === "string" ? status : "" });
}
}
return operations;
}
const routesSource = readFileSync(join(import.meta.dir, "routes.ts"), "utf8");
/** Literals compared with `pathname === "…"`, i.e. routes with no path parameters. */
function exactRouteLiterals(): string[] {
return Array.from(routesSource.matchAll(/pathname === "([^"]+)"/g), (match) => match[1]!).filter(
(literal) => literal.startsWith("/v1/")
);
}
/** Prefix literals compared with `pathname.startsWith("…")`, which carry the path parameters. */
function prefixRouteLiterals(): string[] {
return Array.from(routesSource.matchAll(/pathname\.startsWith\("([^"]+)"\)/g), (match) => match[1]!);
}
describe("OpenAPI contract vs HTTP adapter", () => {
test("every operation declares its implementation status", () => {
const operations = collectOperations();
expect(operations.length).toBeGreaterThan(40);
for (const { method, path, status } of operations) {
expect({ method, path, status, valid: VALID_STATUSES.includes(status) }).toEqual({
method,
path,
status,
valid: true
});
}
});
test("both statuses are in use, so the marking cannot go vacuous", () => {
const operations = collectOperations();
const implemented = operations.filter((operation) => operation.status === "implemented");
const planned = operations.filter((operation) => operation.status === "planned");
// A minimum count fails loudly if `planned` operations are mass-promoted by accident.
expect(implemented.length).toBeGreaterThanOrEqual(15);
expect(planned.length).toBeGreaterThanOrEqual(15);
});
test("every operation claimed implemented is actually routed", () => {
const exactLiterals = new Set(exactRouteLiterals());
const prefixLiterals = new Set(prefixRouteLiterals());
for (const { method, path, status } of collectOperations()) {
if (status !== "implemented") continue;
// `/v1/approval-runs/{recordId}/result` is served by the `/v1/approval-runs/` prefix
// branch, so a placeholder path is proven by its static prefix rather than by equality.
const hasPlaceholder = path.includes("{");
const prefix = path.split("/{")[0]!;
const routed = hasPlaceholder
? prefixLiterals.has(`${prefix}/`)
: exactLiterals.has(path);
expect({ method, path, routed }).toEqual({ method, path, routed: true });
}
});
test("every exact /v1 route is documented", () => {
const documented = new Set(collectOperations().map((operation) => operation.path));
for (const literal of exactRouteLiterals()) {
expect({ literal, documented: documented.has(literal) }).toEqual({ literal, documented: true });
}
});
});
-485
View File
@@ -1,485 +0,0 @@
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 { formatBeijingIso } from "../core/config/timestamps.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 { findSealCapability, parseCapabilityParams, type SealCapability } from "../domains/seal/capabilities.js";
import { tokenizeCommand } from "../cli/tokenize.js";
import { redactSensitiveText } from "../core/redact.js";
import { CliError, type CliExitCode } from "../core/errors.js";
import { VERSION } from "../version.js";
import { renderDocsHtml } from "./docs.js";
async function executeSealCapability(tool: SealCapability, 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.
parseCapabilityParams(tool, params);
const handler = tool.handler as (client: KyInstance, params: any, context: { corp: CorpConfig }) => Promise<unknown>;
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) {
// 1. CORS headers
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
// 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") {
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-use",
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") {
sendJson(res, 200, getOpenApiSchema());
return;
}
if (method === "GET" && pathname === "/health") {
sendJson(res, 200, {
status: "ok",
version: VERSION,
name: "seal-use",
timestamp: formatBeijingIso()
});
return;
}
if (method === "POST" && (pathname === "/shutdown" || pathname === "/api/shutdown")) {
sendJson(res, 200, {
success: true,
message: "Shutting down seal-use background daemon",
pid: process.pid
});
setTimeout(() => {
process.kill(process.pid, "SIGTERM");
}, 50);
return;
}
// 3. Command Execution Endpoint: POST /api/cli
if (method === "POST" && pathname === "/api/cli") {
const body = await parseJsonBody(req);
const command = (typeof body?.command === "string" ? body.command : "").trim();
if (!command) {
sendError(res, 400, "Missing 'command' property in request body");
return;
}
const tokens = tokenizeCommand(command);
const cliArgs = tokens[0] === "seal-use" || tokens[0] === "seal-home" || tokens[0]?.endsWith("/seal-use") || 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 = findSealCapability(toolName);
if (!tool) {
sendError(res, 404, `Tool not found: '${toolName}'`);
return;
}
const body = (await parseJsonBody(req)) || {};
const params = { ...body };
delete params.corp;
// Fail fast before `selectCorp`, which records usage stats to disk: a
// request that can never succeed should cause no writes. `executeSealCapability`
// performs the same check afterwards — the early call exists purely to
// win this ordering, not to duplicate the guarantee.
parseCapabilityParams(tool, params);
const corpId = extractCorpId(req, url, body);
const corp = selectCorp(corpId);
const client = await createSealClient(corp);
const output = await executeSealCapability(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);
// 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);
}
}
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 = findSealCapability("seal_whoami")!;
const data = await executeSealCapability(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 = findSealCapability("seal_session_get")!;
const data = await executeSealCapability(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 = findSealCapability("seal_approval_runs_summary")!;
const data = await executeSealCapability(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 = findSealCapability("seal_approval_runs_stats")!;
const data = await executeSealCapability(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 = findSealCapability("seal_approval_run_pick")!;
const data = await executeSealCapability(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 = findSealCapability("seal_approval_run_url_get")!;
const data = await executeSealCapability(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 = findSealCapability("seal_approval_run_get")!;
const data = await executeSealCapability(tool, client, { recordId, ...queryParams }, corp);
sendJson(res, 200, data);
return true;
}
if (sub === "attachments") {
const tool = findSealCapability("seal_approval_run_attachments_get")!;
const data = await executeSealCapability(tool, client, { recordId, ...queryParams }, corp);
sendJson(res, 200, data);
return true;
}
if (sub === "cited-rules") {
const tool = findSealCapability("seal_approval_run_cited_rules_get")!;
const data = await executeSealCapability(tool, client, { recordId, ...queryParams }, corp);
sendJson(res, 200, data);
return true;
}
if (sub === "document-summary") {
const tool = findSealCapability("seal_approval_run_document_summary_get")!;
const data = await executeSealCapability(tool, client, { recordId, ...queryParams }, corp);
sendJson(res, 200, data);
return true;
}
if (sub === "result") {
const tool = findSealCapability("seal_approval_run_result_get")!;
const data = await executeSealCapability(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 = findSealCapability("seal_approval_runs_search")!;
const data = await executeSealCapability(
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 = findSealCapability("seal_approval_rules_list")!;
const data = await executeSealCapability(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 = findSealCapability("seal_simulation_batches_list")!;
const data = await executeSealCapability(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 = findSealCapability("seal_simulation_batch_create")!;
const data = await executeSealCapability(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 = findSealCapability("seal_simulation_batch_get")!;
const data = await executeSealCapability(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 = findSealCapability("seal_preference_get")!;
const data = await executeSealCapability(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 = findSealCapability("seal_preference_decision_update")!;
const data = await executeSealCapability(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>> {
let raw = "";
for await (const chunk of req) {
raw += chunk;
if (raw.length > 20 * 1024 * 1024) {
throw new Error("Payload too large");
}
}
if (!raw.trim()) return {};
try {
return JSON.parse(raw);
} catch (err) {
throw new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`);
}
}
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: redactSensitiveText(message),
...(details !== undefined ? { details } : {})
});
}
-111
View File
@@ -1,111 +0,0 @@
import { describe, expect, test, afterAll, beforeAll } from "bun:test";
import type { Server } from "node:http";
import { startHttpServer } from "./server.js";
import { httpStatusForCliExit } from "./routes.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-use");
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-use");
});
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-use 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-use 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-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 () => {
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");
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");
});
});
-47
View File
@@ -1,47 +0,0 @@
import { createServer, type Server } from "node:http";
import { handleHttpRequest } from "./routes.js";
import { redactSensitiveText } from "../core/redact.js";
import { VERSION } from "../version.js";
export type HttpServerOptions = {
port?: number;
host?: string;
silent?: boolean;
};
export const DEFAULT_HTTP_PORT = 8787;
export const DEFAULT_HTTP_HOST = "127.0.0.1";
export async function startHttpServer(options: HttpServerOptions = {}): Promise<Server> {
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = options.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
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: redactSensitiveText(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-use 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);
});
});
}