From 54895e5095b1129f9176234dabdb5348ab0e5ea8 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 30 Sep 2026 15:24:19 +0800 Subject: [PATCH] Remove the local HTTP adapter, service daemon, and OpenAPI contract --- .github/workflows/ci.yml | 4 - AGENTS.md | 11 +- README.md | 58 +- SECURITY.md | 6 - dist/openapi.json | 3615 ----------------------- openapi/components/parameters.yaml | 58 - openapi/components/responses.yaml | 18 - openapi/components/schemas/index.yaml | 407 --- openapi/openapi.yaml | 51 - openapi/paths/approval-knowledge.yaml | 368 --- openapi/paths/approval-runs.yaml | 349 --- openapi/paths/auth.yaml | 50 - openapi/paths/corps.yaml | 51 - openapi/paths/index.yaml | 80 - openapi/paths/simulation.yaml | 173 -- openapi/paths/source.yaml | 18 - package.json | 2 - scripts/bump-version.ts | 9 +- scripts/bundle-openapi.ts | 78 - scripts/generate-raw-openapi.ts | 1723 ----------- skills/seal-use/references/cli.md | 10 +- src/cli.test.ts | 9 - src/cli/commands/http.ts | 23 - src/cli/commands/openapi.ts | 8 - src/cli/commands/service.ts | 34 - src/cli/commands/update.ts | 113 +- src/cli/help.test.ts | 34 +- src/cli/help.ts | 76 - src/cli/read-only.test.ts | 7 - src/cli/read-only.ts | 6 +- src/cli/runner.ts | 29 +- src/cli/service.test.ts | 97 - src/cli/service.ts | 279 -- src/cli/types.ts | 6 +- src/core/doctor/knowledge.ts | 8 - src/core/embedded-openapi.test.ts | 12 - src/core/embedded-openapi.ts | 5 - src/http/docs.ts | 29 - src/http/openapi-implementation.test.ts | 106 - src/http/routes.ts | 485 --- src/http/server.test.ts | 111 - src/http/server.ts | 47 - 42 files changed, 61 insertions(+), 8602 deletions(-) delete mode 100644 dist/openapi.json delete mode 100644 openapi/components/parameters.yaml delete mode 100644 openapi/components/responses.yaml delete mode 100644 openapi/components/schemas/index.yaml delete mode 100644 openapi/openapi.yaml delete mode 100644 openapi/paths/approval-knowledge.yaml delete mode 100644 openapi/paths/approval-runs.yaml delete mode 100644 openapi/paths/auth.yaml delete mode 100644 openapi/paths/corps.yaml delete mode 100644 openapi/paths/index.yaml delete mode 100644 openapi/paths/simulation.yaml delete mode 100644 openapi/paths/source.yaml delete mode 100644 scripts/bundle-openapi.ts delete mode 100644 scripts/generate-raw-openapi.ts delete mode 100644 src/cli/commands/http.ts delete mode 100644 src/cli/commands/openapi.ts delete mode 100644 src/cli/commands/service.ts delete mode 100644 src/cli/service.test.ts delete mode 100644 src/cli/service.ts delete mode 100644 src/core/embedded-openapi.test.ts delete mode 100644 src/core/embedded-openapi.ts delete mode 100644 src/http/docs.ts delete mode 100644 src/http/openapi-implementation.test.ts delete mode 100644 src/http/routes.ts delete mode 100644 src/http/server.test.ts delete mode 100644 src/http/server.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f865cb3..3152b58 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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: | diff --git a/AGENTS.md b/AGENTS.md index 594c634..2b56c2e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 `: bump version across all manifest/skill/openapi files and bundle. -- `bun run openapi:bundle`: rebuild `dist/openapi.json`. +- `bun run bump `: 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 diff --git a/README.md b/README.md index b885f10..cf637ce 100644 --- a/README.md +++ b/README.md @@ -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 ` to change it. Run Use `seal-use auth diagnose --corp ` 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 ` 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 ` or `seal-use rules list --corp --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 diff --git a/SECURITY.md b/SECURITY.md index 203dd3a..910f4a2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -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 diff --git a/dist/openapi.json b/dist/openapi.json deleted file mode 100644 index 3e12d2e..0000000 --- a/dist/openapi.json +++ /dev/null @@ -1,3615 +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\n(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n\nAuthentication: none. The adapter answers every request with the enterprise credentials already\nstored on this machine, and never checks who is calling — so keep it on loopback (the default)\nand never expose the port to a network or an origin you do not control. The full trust model is\nin SECURITY.md, \"Trust model and documented limitations\".\n" - }, - "servers": [ - { - "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": { - "/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": { - "type": "object", - "required": [ - "id", - "name", - "sourceType", - "current" - ], - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "sourceType": { - "type": "string", - "enum": [ - "hose", - "seal" - ] - }, - "current": { - "type": "boolean" - } - } - } - } - } - } - } - } - } - }, - "/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": { - "type": "object", - "required": [ - "id", - "name", - "sourceType", - "current" - ], - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "sourceType": { - "type": "string", - "enum": [ - "hose", - "seal" - ] - }, - "current": { - "type": "boolean" - } - } - } - } - } - } - } - } - }, - "/v1/corps/current/switch": { - "post": { - "tags": [ - "Corps" - ], - "operationId": "switchCurrentCorp", - "x-implementation-status": "planned", - "summary": "Switch current enterprise", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "corpId" - ], - "properties": { - "corpId": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Switched enterprise.", - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "current", - "id", - "name" - ], - "properties": { - "current": { - "type": "boolean" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - } - } - } - } - }, - "404": { - "description": "Requested resource was not found.", - "content": { - "application/json": { - "schema": { - "type": "object", - "additionalProperties": true, - "required": [ - "error" - ], - "properties": { - "error": { - "type": "string" - }, - "message": { - "type": "string" - }, - "details": {} - } - } - } - } - } - } - } - }, - "/v1/source/config": { - "get": { - "tags": [ - "Source" - ], - "operationId": "getSourceConfig", - "x-implementation-status": "planned", - "summary": "Resolve source-derived Seal enterprise config", - "parameters": [ - { - "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." - } - ], - "responses": { - "200": { - "description": "Redacted Seal enterprise config.", - "content": { - "application/json": { - "schema": { - "type": "object", - "additionalProperties": true, - "description": "Redacted Seal enterprise config resolved from the configured source." - } - } - } - }, - "401": { - "description": "Local service authentication failed or downstream Seal auth failed.", - "content": { - "application/json": { - "schema": { - "type": "object", - "additionalProperties": true, - "required": [ - "error" - ], - "properties": { - "error": { - "type": "string" - }, - "message": { - "type": "string" - }, - "details": {} - } - } - } - } - } - } - } - }, - "/v1/auth/diagnose": { - "get": { - "tags": [ - "Auth" - ], - "operationId": "diagnoseAuth", - "x-implementation-status": "planned", - "summary": "Diagnose wrapped source-to-Seal authentication", - "parameters": [ - { - "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." - } - ], - "responses": { - "200": { - "description": "Authentication stage diagnosis.", - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "stages" - ], - "properties": { - "stages": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AuthStage" - } - } - } - } - } - } - } - } - } - }, - "/v1/whoami": { - "get": { - "tags": [ - "Auth" - ], - "operationId": "whoami", - "x-implementation-status": "implemented", - "summary": "Get current wrapped Seal identity", - "parameters": [ - { - "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." - } - ], - "responses": { - "200": { - "description": "Current Seal user and tenant.", - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "user", - "tenant" - ], - "properties": { - "user": { - "$ref": "#/components/schemas/SealUser" - }, - "tenant": { - "$ref": "#/components/schemas/SealTenant" - } - } - } - } - } - }, - "401": { - "description": "Local service authentication failed or downstream Seal auth failed.", - "content": { - "application/json": { - "schema": { - "type": "object", - "additionalProperties": true, - "required": [ - "error" - ], - "properties": { - "error": { - "type": "string" - }, - "message": { - "type": "string" - }, - "details": {} - } - } - } - } - } - } - } - }, - "/v1/session": { - "get": { - "tags": [ - "Auth" - ], - "operationId": "getSession", - "x-implementation-status": "implemented", - "summary": "Get current wrapped Seal session metadata", - "parameters": [ - { - "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." - } - ], - "responses": { - "200": { - "description": "Current session metadata.", - "content": { - "application/json": { - "schema": { - "type": "object", - "additionalProperties": true, - "required": [ - "user", - "session" - ], - "properties": { - "user": { - "$ref": "#/components/schemas/SealUser" - }, - "session": { - "type": "object", - "additionalProperties": true - } - } - } - } - } - }, - "401": { - "description": "Local service authentication failed or downstream Seal auth failed.", - "content": { - "application/json": { - "schema": { - "type": "object", - "additionalProperties": true, - "required": [ - "error" - ], - "properties": { - "error": { - "type": "string" - }, - "message": { - "type": "string" - }, - "details": {} - } - } - } - } - } - } - } - }, - "/v1/approval/context": { - "get": { - "tags": [ - "Approval Knowledge" - ], - "operationId": "getApprovalContext", - "x-implementation-status": "planned", - "summary": "Get rules, documents, and style preferences together", - "parameters": [ - { - "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." - }, - { - "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": { - "type": "object", - "required": [ - "rules", - "documents", - "stylePreferences" - ], - "properties": { - "rules": {}, - "documents": {}, - "stylePreferences": {} - } - } - } - } - } - } - } - }, - "/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": { - "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" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Search results with line context.", - "content": { - "application/json": { - "schema": { - "type": "object", - "additionalProperties": true - } - } - } - } - } - } - }, - "/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": { - "type": "object", - "required": [ - "rules" - ], - "properties": { - "rules": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ApprovalRule" - } - }, - "hasPendingDeletes": { - "type": "boolean" - } - } - } - } - } - } - } - }, - "post": { - "tags": [ - "Approval Knowledge" - ], - "operationId": "createApprovalRule", - "x-implementation-status": "planned", - "summary": "Create draft approval rule", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "description", - "scope", - "strictness" - ], - "properties": { - "description": { - "type": "string" - }, - "scope": { - "type": "string" - }, - "strictness": { - "type": "string", - "enum": [ - "MUST_FOLLOW", - "SHOULD_FOLLOW", - "SUGGESTION" - ] - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Created rule.", - "content": { - "application/json": { - "schema": { - "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" - } - } - } - } - } - } - } - } - }, - "/v1/approval/rules/{ruleId}": { - "parameters": [ - { - "name": "ruleId", - "in": "path", - "required": true, - "schema": { - "type": "string" - }, - "description": "Approval rule ID." - } - ], - "patch": { - "tags": [ - "Approval Knowledge" - ], - "operationId": "updateApprovalRule", - "x-implementation-status": "planned", - "summary": "Update draft approval rule", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "additionalProperties": false, - "properties": { - "description": { - "type": "string" - }, - "scope": { - "type": "string" - }, - "strictness": { - "type": "string", - "enum": [ - "MUST_FOLLOW", - "SHOULD_FOLLOW", - "SUGGESTION" - ] - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Updated rule.", - "content": { - "application/json": { - "schema": { - "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" - } - } - } - } - } - } - } - }, - "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": { - "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 - } - } - } - } - } - } - } - } - } - } - }, - "/v1/approval/rule-versions/{versionId}": { - "parameters": [ - { - "name": "versionId", - "in": "path", - "required": true, - "schema": { - "type": "string" - }, - "description": "Published rule version ID." - } - ], - "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": { - "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 - } - } - } - } - } - } - } - } - } - }, - "/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": [ - { - "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." - }, - { - "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": { - "type": "object", - "required": [ - "versionName" - ], - "properties": { - "versionName": { - "type": "string" - } - } - } - } - } - }, - "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": [ - { - "name": "offset", - "in": "query", - "schema": { - "type": "integer", - "minimum": 0, - "default": 0 - }, - "description": "Zero-based pagination 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": { - "type": "object", - "required": [ - "articles" - ], - "properties": { - "articles": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ApprovalDocument" - } - }, - "total": { - "type": "integer" - } - } - } - } - } - } - } - }, - "post": { - "tags": [ - "Approval Knowledge" - ], - "operationId": "createApprovalDocument", - "x-implementation-status": "planned", - "summary": "Create approval knowledge document", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "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" - } - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Created document.", - "content": { - "application/json": { - "schema": { - "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" - } - } - } - } - } - } - } - } - } - }, - "/v1/approval/documents/{documentId}": { - "parameters": [ - { - "name": "documentId", - "in": "path", - "required": true, - "schema": { - "type": "string" - }, - "description": "Approval knowledge document ID." - } - ], - "get": { - "tags": [ - "Approval Knowledge" - ], - "operationId": "getApprovalDocument", - "x-implementation-status": "planned", - "summary": "Get approval knowledge document", - "responses": { - "200": { - "description": "Document.", - "content": { - "application/json": { - "schema": { - "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" - } - } - } - } - } - } - } - } - }, - "patch": { - "tags": [ - "Approval Knowledge" - ], - "operationId": "updateApprovalDocument", - "x-implementation-status": "planned", - "summary": "Update approval knowledge document", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "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" - } - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Updated document.", - "content": { - "application/json": { - "schema": { - "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" - } - } - } - } - } - } - } - } - }, - "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": { - "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" - } - } - } - } - } - } - } - }, - "patch": { - "tags": [ - "Approval Knowledge" - ], - "operationId": "updateApprovalStylePreferences", - "x-implementation-status": "planned", - "summary": "Update approval style preferences", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "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" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Updated style preferences.", - "content": { - "application/json": { - "schema": { - "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" - } - } - } - } - } - } - } - } - }, - "/v1/preferences": { - "get": { - "tags": [ - "Approval Knowledge" - ], - "operationId": "getPreferences", - "x-implementation-status": "implemented", - "summary": "Get current decision, thinking-depth and rule-version preferences", - "parameters": [ - { - "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." - } - ], - "responses": { - "200": { - "description": "Decision preferences, thinking depth preference and the bound rule set version.", - "content": { - "application/json": { - "schema": { - "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" - } - } - } - } - } - } - } - } - }, - "/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": [ - { - "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." - } - ], - "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": { - "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" - } - } - } - } - } - } - } - } - }, - "/v1/approval-runs": { - "get": { - "tags": [ - "Approval Runs" - ], - "operationId": "searchApprovalRuns", - "x-implementation-status": "implemented", - "summary": "Search wrapped approval run history", - "parameters": [ - { - "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." - }, - { - "name": "offset", - "in": "query", - "schema": { - "type": "integer", - "minimum": 0, - "default": 0 - }, - "description": "Zero-based pagination offset." - }, - { - "name": "limit", - "in": "query", - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 100, - "default": 50 - }, - "description": "Maximum number of records to return." - }, - { - "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": { - "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 - } - } - } - } - } - } - } - } - } - }, - "/v1/approval-runs/summary": { - "get": { - "tags": [ - "Approval Runs" - ], - "operationId": "summarizeApprovalRuns", - "x-implementation-status": "implemented", - "summary": "Summarize approval runs by local date", - "parameters": [ - { - "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." - }, - { - "name": "date", - "in": "query", - "schema": { - "type": "string", - "format": "date" - } - }, - { - "name": "timezone", - "in": "query", - "schema": { - "type": "string", - "default": "Asia/Shanghai" - } - }, - { - "name": "limit", - "in": "query", - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 100, - "default": 50 - }, - "description": "Maximum number of records to return." - }, - { - "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": { - "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" - } - } - } - } - } - } - } - } - } - }, - "/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": [ - { - "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." - }, - { - "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": [ - { - "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." - }, - { - "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": [ - { - "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." - }, - { - "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": { - "type": "object", - "additionalProperties": true, - "properties": { - "count": { - "type": "integer" - }, - "records": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ApprovalRun" - } - }, - "bridge": { - "type": "array", - "items": { - "type": "object", - "additionalProperties": true - } - } - } - } - } - } - } - } - } - }, - "/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": [ - { - "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." - }, - { - "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": { - "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" - } - } - } - } - } - } - } - } - }, - "/v1/approval-runs/{recordId}": { - "parameters": [ - { - "name": "recordId", - "in": "path", - "required": true, - "schema": { - "type": "string" - }, - "description": "seal-use approval run record ID." - } - ], - "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": [ - { - "name": "recordId", - "in": "path", - "required": true, - "schema": { - "type": "string" - }, - "description": "seal-use approval run record ID." - } - ], - "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": [ - { - "name": "recordId", - "in": "path", - "required": true, - "schema": { - "type": "string" - }, - "description": "seal-use approval run record ID." - } - ], - "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": [ - { - "name": "recordId", - "in": "path", - "required": true, - "schema": { - "type": "string" - }, - "description": "seal-use approval run record ID." - } - ], - "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": [ - { - "name": "recordId", - "in": "path", - "required": true, - "schema": { - "type": "string" - }, - "description": "seal-use approval run record ID." - } - ], - "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 - } - } - } - } - } - } - }, - "/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": [ - { - "name": "batchId", - "in": "path", - "required": true, - "schema": { - "type": "string" - }, - "description": "Simulation batch ID." - } - ], - "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": [ - { - "name": "batchId", - "in": "path", - "required": true, - "schema": { - "type": "string" - }, - "description": "Simulation batch ID." - } - ], - "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 - } - } - } - } - } - } - } - }, - "components": { - "parameters": { - "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." - } - }, - "responses": { - "BadRequest": { - "description": "Invalid request.", - "content": { - "application/json": { - "schema": { - "type": "object", - "additionalProperties": true, - "required": [ - "error" - ], - "properties": { - "error": { - "type": "string" - }, - "message": { - "type": "string" - }, - "details": {} - } - } - } - } - }, - "Unauthorized": { - "description": "Local service authentication failed or downstream Seal auth failed.", - "content": { - "application/json": { - "schema": { - "type": "object", - "additionalProperties": true, - "required": [ - "error" - ], - "properties": { - "error": { - "type": "string" - }, - "message": { - "type": "string" - }, - "details": {} - } - } - } - } - }, - "NotFound": { - "description": "Requested resource was not found.", - "content": { - "application/json": { - "schema": { - "type": "object", - "additionalProperties": true, - "required": [ - "error" - ], - "properties": { - "error": { - "type": "string" - }, - "message": { - "type": "string" - }, - "details": {} - } - } - } - } - } - }, - "schemas": { - "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 - } - } - } - } - } - } -} diff --git a/openapi/components/parameters.yaml b/openapi/components/parameters.yaml deleted file mode 100644 index 6c14c51..0000000 --- a/openapi/components/parameters.yaml +++ /dev/null @@ -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. diff --git a/openapi/components/responses.yaml b/openapi/components/responses.yaml deleted file mode 100644 index af13923..0000000 --- a/openapi/components/responses.yaml +++ /dev/null @@ -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 diff --git a/openapi/components/schemas/index.yaml b/openapi/components/schemas/index.yaml deleted file mode 100644 index 4296c5b..0000000 --- a/openapi/components/schemas/index.yaml +++ /dev/null @@ -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 diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml deleted file mode 100644 index 4a58f2e..0000000 --- a/openapi/openapi.yaml +++ /dev/null @@ -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 diff --git a/openapi/paths/approval-knowledge.yaml b/openapi/paths/approval-knowledge.yaml deleted file mode 100644 index 187f660..0000000 --- a/openapi/paths/approval-knowledge.yaml +++ /dev/null @@ -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 diff --git a/openapi/paths/approval-runs.yaml b/openapi/paths/approval-runs.yaml deleted file mode 100644 index 1d4dd02..0000000 --- a/openapi/paths/approval-runs.yaml +++ /dev/null @@ -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 diff --git a/openapi/paths/auth.yaml b/openapi/paths/auth.yaml deleted file mode 100644 index 1634972..0000000 --- a/openapi/paths/auth.yaml +++ /dev/null @@ -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 diff --git a/openapi/paths/corps.yaml b/openapi/paths/corps.yaml deleted file mode 100644 index 056fb07..0000000 --- a/openapi/paths/corps.yaml +++ /dev/null @@ -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 diff --git a/openapi/paths/index.yaml b/openapi/paths/index.yaml deleted file mode 100644 index cc923bd..0000000 --- a/openapi/paths/index.yaml +++ /dev/null @@ -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 diff --git a/openapi/paths/simulation.yaml b/openapi/paths/simulation.yaml deleted file mode 100644 index 9a0191a..0000000 --- a/openapi/paths/simulation.yaml +++ /dev/null @@ -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 diff --git a/openapi/paths/source.yaml b/openapi/paths/source.yaml deleted file mode 100644 index db16e2e..0000000 --- a/openapi/paths/source.yaml +++ /dev/null @@ -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 diff --git a/package.json b/package.json index 9f1c81a..a7e2003 100644 --- a/package.json +++ b/package.json @@ -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" }, diff --git a/scripts/bump-version.ts b/scripts/bump-version.ts index 9a560ac..6a633b8 100644 --- a/scripts/bump-version.ts +++ b/scripts/bump-version.ts @@ -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 + "!"); diff --git a/scripts/bundle-openapi.ts b/scripts/bundle-openapi.ts deleted file mode 100644 index 6018a77..0000000 --- a/scripts/bundle-openapi.ts +++ /dev/null @@ -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): 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): 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)[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); -} diff --git a/scripts/generate-raw-openapi.ts b/scripts/generate-raw-openapi.ts deleted file mode 100644 index 725d36c..0000000 --- a/scripts/generate-raw-openapi.ts +++ /dev/null @@ -1,1723 +0,0 @@ -#!/usr/bin/env bun - -import { mkdirSync, writeFileSync } from "node:fs"; -import { dirname, resolve } from "node:path"; - -const outputFile = resolve("dist/raw-seal-openapi.json"); - -function dataResponse(description: string, dataSchema: any) { - return { - "200": { - description, - content: { - "application/json": { - schema: { - type: "object", - required: ["data"], - properties: { - data: dataSchema - } - } - } - } - }, - "401": { - description: "未授权或 Token 无效", - content: { - "application/json": { - schema: { $ref: "#/components/schemas/ErrorResponse" } - } - } - }, - "400": { - description: "请求参数错误", - content: { - "application/json": { - schema: { $ref: "#/components/schemas/ErrorResponse" } - } - } - } - }; -} - -const spec = { - openapi: "3.1.0", - info: { - title: "Seal AI Downstream Native API", - version: "1.0.0", - description: "Raw downstream Seal AI and HoseCloud business API contracts (without seal-use wrapper layer)." - }, - servers: [ - { - url: "https://{corpId}.sealai.cc", - description: "Seal AI 企业租户环境 (例如: https://id01jdq2yidnmr.sealai.cc)", - variables: { - corpId: { - default: "id01jdq2yidnmr", - description: "合思/Seal 企业租户 ID (小写)" - } - } - } - ], - security: [ - { - bearerAuth: [] - } - ], - tags: [ - { name: "Hose Auth & SSO", description: "合思开放平台鉴权与免登中转换票 (前置 Token 链路)" }, - { name: "Auth & Session", description: "身份验证、当前会话与 SSO 换票" }, - { name: "Approval Rules", description: "审批规则草稿、版本快照与发布" }, - { name: "Knowledge Documents", description: "知识库规章与文档管理" }, - { name: "Agent & Style Preferences", description: "审批偏好、深度策略与 Webhook 集成" }, - { name: "Approval Runs", description: "审批记录、AI 决策结果与原始单据" }, - { name: "Simulation & Testing", description: "仿真批次、单据模板与材料包测试" }, - { name: "Delegation", description: "转授权令牌与协助链接" }, - { name: "Contacts & Users", description: "部门架构与用户管理" }, - { name: "HoseCloud OEM Integration", description: "合思企业绑定与出站 Webhook 配置" }, - { name: "System, LLM & Billing", description: "大模型设置、系统权限与计费套餐" } - ], - paths: { - "/api/openapi/v1/auth/getAccessToken": { - post: { - tags: ["Hose Auth & SSO"], - "x-apifox-folder": "原始业务接口/Hose Auth & SSO", - summary: "合思 OpenAPI 获取企业访问令牌 (Step 1 -> hoseOpenApiToken)", - description: "调用合思开放平台凭证换取企业级 accessToken,用于后续免登换票操作。", - operationId: "getHoseOpenapiAccessToken", - requestBody: { - required: true, - content: { - "application/json": { - schema: { - type: "object", - required: ["appKey", "appSecurity"], - properties: { - appKey: { type: "string", default: "{{hoseApiKey}}", description: "合思 OpenAPI Key" }, - appSecurity: { type: "string", default: "{{hoseApiSecret}}", description: "合思 OpenAPI Secret (密钥)" } - } - }, - example: { - appKey: "{{hoseApiKey}}", - appSecurity: "{{hoseApiSecret}}" - } - } - } - }, - responses: { - "200": { - description: "合思企业 AccessToken 响应", - content: { - "application/json": { - schema: { - type: "object", - properties: { - value: { - type: "object", - properties: { - accessToken: { type: "string", description: "企业访问令牌" }, - corporation: { - type: "object", - properties: { - id: { type: "string" }, - name: { type: "string" } - } - }, - staff: { - type: "object", - properties: { - id: { type: "string" }, - name: { type: "string" } - } - } - } - } - } - } - } - } - } - } - } - }, - "/api/openapi/v1.1/provisional/getProvisionalAuth": { - post: { - tags: ["Hose Auth & SSO"], - "x-apifox-folder": "原始业务接口/Hose Auth & SSO", - summary: "合思 CloseAPI 获取免登换票令牌 (Step 2 -> hoseProvisionalToken)", - description: "使用合思企业 AccessToken 与操作人员工 ID,生成免登 Ticket URL,提取 accessToken 用于 Seal SSO 换票。", - operationId: "getHoseProvisionalAuth", - parameters: [ - { - name: "accessToken", - in: "query", - required: true, - example: "{{hoseOpenApiToken}}", - schema: { type: "string", default: "{{hoseOpenApiToken}}" }, - description: "合思企业级 accessToken" - } - ], - requestBody: { - required: true, - content: { - "application/json": { - schema: { - type: "object", - required: ["uid"], - properties: { - uid: { type: "string", default: "{{hoseUserId}}", description: "合思员工 ID / StaffId (例如: ID01Jdq2yIDnMr:ID01KsDgHaH5nN)" }, - pageType: { type: "string", default: "home", description: "免登落地页类型" }, - expireDate: { type: "integer", default: 7200, description: "临时免登凭据有效期(秒)" } - } - }, - example: { - uid: "{{hoseUserId}}", - pageType: "home", - expireDate: 7200 - } - } - } - }, - responses: { - "200": { - description: "免登中转 URL 响应", - content: { - "application/json": { - schema: { - type: "object", - properties: { - value: { - type: "object", - properties: { - message: { type: "string", description: "带 accessToken 临时中转票据的完整免登 URL" } - } - } - } - } - } - } - } - } - } - }, - "/api/v1/auth/me": { - get: { - tags: ["Auth & Session"], - "x-apifox-folder": "原始业务接口/Auth & Session", - summary: "获取当前登录用户与租户信息", - operationId: "getMe", - responses: dataResponse("当前身份信息", { $ref: "#/components/schemas/MeData" }) - } - }, - "/api/auth/get-session": { - get: { - tags: ["Auth & Session"], - "x-apifox-folder": "原始业务接口/Auth & Session", - summary: "获取当前会话及转授权信息", - operationId: "getSession", - responses: dataResponse("当前会话数据", { $ref: "#/components/schemas/SealSessionData" }) - } - }, - "/api/auth/sms-otp/sign-in-password": { - post: { - tags: ["Auth & Session"], - "x-apifox-folder": "原始业务接口/Auth & Session", - summary: "手机号与密码登录", - operationId: "loginWithPhonePassword", - requestBody: { - required: true, - content: { - "application/json": { - schema: { - type: "object", - required: ["phone", "password"], - properties: { - phone: { type: "string", description: "手机号" }, - password: { type: "string", description: "登录密码" } - } - } - } - } - }, - responses: { - "200": { - description: "登录结果与 Token", - content: { - "application/json": { - schema: { - type: "object", - properties: { - user: { type: "object" }, - session: { - type: "object", - properties: { - token: { type: "string" } - } - } - } - } - } - } - }, - "401": { - description: "认证失败", - content: { - "application/json": { - schema: { $ref: "#/components/schemas/ErrorResponse" } - } - } - } - } - } - }, - "/api/auth/oauth2/session/oem-hosecloud": { - get: { - tags: ["Hose Auth & SSO", "Auth & Session"], - "x-apifox-folder": "原始业务接口/Hose Auth & SSO", - summary: "合思 OEM SSO 换取 Seal 会话 Token (Step 3 -> sealToken)", - description: "使用合思第二层免登 Token(hoseProvisionalToken)向 Seal AI 服务换取会话 Token,并自动保存到环境变量 sealToken 中。", - operationId: "oauthHosecloudSession", - parameters: [ - { - name: "token", - in: "query", - required: true, - example: "{{hoseProvisionalToken}}", - schema: { type: "string", default: "{{hoseProvisionalToken}}" }, - description: "合思 closeapi 换票 token" - }, - { - name: "returnToken", - in: "query", - example: "1", - schema: { type: "string", default: "1" }, - description: "是否直接返回 token 字段" - } - ], - responses: { - "200": { - description: "换票会话", - content: { - "application/json": { - schema: { - type: "object", - properties: { - token: { type: "string" }, - accessToken: { type: "string" } - } - } - } - } - }, - "400": { - description: "换票失败", - content: { - "application/json": { - schema: { $ref: "#/components/schemas/ErrorResponse" } - } - } - } - } - } - }, - "/api/v1/rules": { - get: { - tags: ["Approval Rules"], - "x-apifox-folder": "原始业务接口/Approval Rules", - summary: "获取当前草稿规则列表", - operationId: "listApprovalRules", - responses: dataResponse("规则列表数据", { $ref: "#/components/schemas/ApprovalRulesData" }) - }, - post: { - tags: ["Approval Rules"], - "x-apifox-folder": "原始业务接口/Approval Rules", - summary: "新增审批规则草稿", - operationId: "createApprovalRule", - requestBody: { - required: true, - content: { - "application/json": { - schema: { $ref: "#/components/schemas/ApprovalRuleInput" } - } - } - }, - responses: dataResponse("创建成功的规则", { $ref: "#/components/schemas/ApprovalRule" }) - } - }, - "/api/v1/rules/{ruleId}": { - put: { - tags: ["Approval Rules"], - "x-apifox-folder": "原始业务接口/Approval Rules", - summary: "修改审批规则草稿", - operationId: "updateApprovalRule", - parameters: [ - { - name: "ruleId", - in: "path", - required: true, - schema: { type: "string" }, - description: "规则 ID" - } - ], - requestBody: { - required: true, - content: { - "application/json": { - schema: { $ref: "#/components/schemas/ApprovalRuleUpdate" } - } - } - }, - responses: dataResponse("更新后的规则", { $ref: "#/components/schemas/ApprovalRule" }) - }, - delete: { - tags: ["Approval Rules"], - "x-apifox-folder": "原始业务接口/Approval Rules", - summary: "删除审批规则草稿", - operationId: "deleteApprovalRule", - parameters: [ - { - name: "ruleId", - in: "path", - required: true, - schema: { type: "string" }, - description: "规则 ID" - } - ], - responses: { - "200": { - description: "删除成功" - } - } - } - }, - "/api/v1/rules/batch-recode": { - post: { - tags: ["Approval Rules"], - "x-apifox-folder": "原始业务接口/Approval Rules", - summary: "规则批量重排与重编号", - operationId: "recodeApprovalRules", - responses: { - "200": { - description: "重排结果" - } - } - } - }, - "/api/v1/rule-set-versions": { - get: { - tags: ["Approval Rules"], - "x-apifox-folder": "原始业务接口/Approval Rules", - summary: "获取已发布规则版本列表", - operationId: "listApprovalRuleVersions", - responses: dataResponse("已发布规则版本列表", { - type: "array", - items: { $ref: "#/components/schemas/RuleSetVersion" } - }) - } - }, - "/api/v1/rule-set-versions/{versionId}": { - get: { - tags: ["Approval Rules"], - "x-apifox-folder": "原始业务接口/Approval Rules", - summary: "获取单个已发布规则版本详情", - operationId: "getApprovalRuleVersion", - parameters: [ - { - name: "versionId", - in: "path", - required: true, - schema: { type: "string" }, - description: "版本 ID" - } - ], - responses: dataResponse("版本详情", { $ref: "#/components/schemas/RuleSetVersion" }) - } - }, - "/api/v1/rule-set-versions/publish": { - post: { - tags: ["Approval Rules"], - "x-apifox-folder": "原始业务接口/Approval Rules", - summary: "将当前草稿规则发布为正式版本", - operationId: "publishApprovalRuleVersion", - requestBody: { - required: true, - content: { - "application/json": { - schema: { - type: "object", - required: ["versionName"], - properties: { - versionName: { type: "string", description: "新版本名称" } - } - } - } - } - }, - responses: dataResponse("发布结果", { $ref: "#/components/schemas/PublishVersionData" }) - } - }, - "/api/v1/knowledge/articles": { - get: { - tags: ["Knowledge Documents"], - "x-apifox-folder": "原始业务接口/Knowledge Documents", - summary: "获取知识库文档列表", - operationId: "listApprovalDocuments", - parameters: [ - { name: "offset", in: "query", schema: { type: "integer", default: 0 } }, - { name: "limit", in: "query", schema: { type: "integer", default: 20 } }, - { name: "sortBy", in: "query", schema: { type: "string", default: "createdAt" } }, - { name: "sortOrder", in: "query", schema: { type: "string", enum: ["asc", "desc"], default: "desc" } } - ], - responses: dataResponse("知识文档列表", { $ref: "#/components/schemas/ApprovalDocumentListData" }) - }, - post: { - tags: ["Knowledge Documents"], - "x-apifox-folder": "原始业务接口/Knowledge Documents", - summary: "新建知识库文档", - operationId: "createApprovalDocument", - requestBody: { - required: true, - content: { - "application/json": { - schema: { $ref: "#/components/schemas/ApprovalDocumentInput" } - } - } - }, - responses: dataResponse("创建成功的文档", { $ref: "#/components/schemas/ApprovalDocument" }) - } - }, - "/api/v1/knowledge/articles/{documentId}": { - get: { - tags: ["Knowledge Documents"], - "x-apifox-folder": "原始业务接口/Knowledge Documents", - summary: "获取单个知识文档详情", - operationId: "getApprovalDocument", - parameters: [ - { name: "documentId", in: "path", required: true, schema: { type: "string" } } - ], - responses: dataResponse("知识文档详情", { $ref: "#/components/schemas/ApprovalDocument" }) - }, - patch: { - tags: ["Knowledge Documents"], - "x-apifox-folder": "原始业务接口/Knowledge Documents", - summary: "修改知识库文档", - operationId: "updateApprovalDocument", - parameters: [ - { name: "documentId", in: "path", required: true, schema: { type: "string" } } - ], - requestBody: { - required: true, - content: { - "application/json": { - schema: { - type: "object", - properties: { - attributes: { $ref: "#/components/schemas/ApprovalDocumentUpdate" } - } - } - } - } - }, - responses: dataResponse("更新后的文档", { $ref: "#/components/schemas/ApprovalDocument" }) - } - }, - "/api/v1/agent/ai-approval/config": { - get: { - tags: ["Agent & Style Preferences"], - "x-apifox-folder": "原始业务接口/Agent & Style Preferences", - summary: "获取 AI 审批配置与偏好", - operationId: "getApprovalStylePreferences", - responses: dataResponse("AI 审批偏好配置", { $ref: "#/components/schemas/ApprovalStylePreferences" }) - }, - patch: { - tags: ["Agent & Style Preferences"], - "x-apifox-folder": "原始业务接口/Agent & Style Preferences", - summary: "局部更新 AI 审批配置与偏好", - operationId: "patchApprovalStylePreferences", - requestBody: { - required: true, - content: { - "application/json": { - schema: { type: "object", description: "部分偏好字段" } - } - } - }, - responses: dataResponse("更新后的偏好配置", { $ref: "#/components/schemas/ApprovalStylePreferences" }) - }, - post: { - tags: ["Agent & Style Preferences"], - "x-apifox-folder": "原始业务接口/Agent & Style Preferences", - summary: "覆盖保存 AI 审批配置与偏好", - operationId: "saveApprovalStylePreferences", - requestBody: { - required: true, - content: { - "application/json": { - schema: { $ref: "#/components/schemas/ApprovalStylePreferences" } - } - } - }, - responses: { - "200": { - description: "保存结果" - } - } - } - }, - "/api/v1/integrations/webhook/{webhookId}/document": { - post: { - tags: ["Agent & Style Preferences"], - "x-apifox-folder": "原始业务接口/Agent & Style Preferences", - summary: "接收外部 Webhook 审批进单", - operationId: "incomingWebhookDocument", - parameters: [ - { name: "webhookId", in: "path", required: true, schema: { type: "string" } } - ], - requestBody: { - required: true, - content: { - "application/json": { - schema: { type: "object", description: "单据原始 payload" } - } - } - }, - responses: { - "200": { - description: "进单响应" - } - } - } - }, - "/api/v1/integrations/webhook/{webhookId}/manual-result": { - post: { - tags: ["Agent & Style Preferences"], - "x-apifox-folder": "原始业务接口/Agent & Style Preferences", - summary: "接收外部 Webhook 人工终审结果回传", - operationId: "incomingWebhookManualResult", - parameters: [ - { name: "webhookId", in: "path", required: true, schema: { type: "string" } } - ], - requestBody: { - required: true, - content: { - "application/json": { - schema: { type: "object", description: "人工审批结论" } - } - } - }, - responses: { - "200": { - description: "回传响应" - } - } - } - }, - "/api/v1/approvals": { - get: { - tags: ["Approval Runs"], - "x-apifox-folder": "原始业务接口/Approval Runs", - summary: "查询审批运行记录列表", - operationId: "listApprovalRuns", - parameters: [ - { name: "offset", in: "query", schema: { type: "integer", default: 0 } }, - { name: "limit", in: "query", schema: { type: "integer", default: 50 } }, - { name: "startDate", in: "query", schema: { type: "string" }, description: "开始日期 YYYY-MM-DD" }, - { name: "endDate", in: "query", schema: { type: "string" }, description: "结束日期 YYYY-MM-DD" }, - { name: "status", in: "query", schema: { type: "string" } }, - { name: "sourceSystem", in: "query", schema: { type: "string" } }, - { name: "taskMode", in: "query", schema: { type: "string" } }, - { name: "search", in: "query", schema: { type: "string" } }, - { name: "sourceDocumentSN", in: "query", schema: { type: "string" } }, - { name: "sourceDocumentId", in: "query", schema: { type: "string" } } - ], - responses: dataResponse("审批运行记录列表", { $ref: "#/components/schemas/ApprovalRunListData" }) - } - }, - "/api/v1/approvals/{runId}": { - get: { - tags: ["Approval Runs"], - "x-apifox-folder": "原始业务接口/Approval Runs", - summary: "获取单条审批运行记录详情", - operationId: "getApprovalRun", - parameters: [ - { name: "runId", in: "path", required: true, schema: { type: "string" } } - ], - responses: dataResponse("审批运行详情", { $ref: "#/components/schemas/ApprovalRun" }) - } - }, - "/api/v1/simulation/create-batch": { - post: { - tags: ["Simulation & Testing"], - "x-apifox-folder": "原始业务接口/Simulation & Testing", - summary: "创建合思指定单号/条件仿真测试批次", - operationId: "createSimulationBatch", - requestBody: { - required: true, - content: { - "application/json": { - schema: { $ref: "#/components/schemas/SimulationBatchParams" } - } - } - }, - responses: dataResponse("创建结果", { $ref: "#/components/schemas/SimulationCreateResult" }) - } - }, - "/api/v1/simulation/create-material-pack-batch": { - post: { - tags: ["Simulation & Testing"], - "x-apifox-folder": "原始业务接口/Simulation & Testing", - summary: "创建材料包仿真测试批次", - operationId: "createMaterialPackBatch", - requestBody: { - required: true, - content: { - "application/json": { - schema: { $ref: "#/components/schemas/SimulationBatchParams" } - } - } - }, - responses: dataResponse("创建结果", { $ref: "#/components/schemas/SimulationCreateResult" }) - } - }, - "/api/v1/simulation/batches": { - get: { - tags: ["Simulation & Testing"], - "x-apifox-folder": "原始业务接口/Simulation & Testing", - summary: "获取仿真测试批次列表", - operationId: "listSimulationBatches", - parameters: [ - { name: "limit", in: "query", schema: { type: "integer", default: 50 } } - ], - responses: dataResponse("仿真批次列表", { - type: "array", - items: { $ref: "#/components/schemas/SimulationBatch" } - }) - } - }, - "/api/v1/simulation/batch/{batchId}": { - get: { - tags: ["Simulation & Testing"], - "x-apifox-folder": "原始业务接口/Simulation & Testing", - summary: "获取单个仿真测试批次详情", - operationId: "getSimulationBatch", - parameters: [ - { name: "batchId", in: "path", required: true, schema: { type: "string" } } - ], - responses: dataResponse("仿真批次详情", { $ref: "#/components/schemas/SimulationBatch" }) - } - }, - "/api/v1/simulation/batch/{batchId}/records": { - get: { - tags: ["Simulation & Testing"], - "x-apifox-folder": "原始业务接口/Simulation & Testing", - summary: "获取仿真批次产生的审批记录", - operationId: "listSimulationBatchRecords", - parameters: [ - { name: "batchId", in: "path", required: true, schema: { type: "string" } } - ], - responses: dataResponse("审批记录列表", { - type: "array", - items: { $ref: "#/components/schemas/ApprovalRun" } - }) - } - }, - "/api/v1/simulation/batch/{batchId}/data": { - delete: { - tags: ["Simulation & Testing"], - "x-apifox-folder": "原始业务接口/Simulation & Testing", - summary: "清理仿真批次生成的业务测试数据", - operationId: "cleanSimulationBatchData", - parameters: [ - { name: "batchId", in: "path", required: true, schema: { type: "string" } } - ], - responses: { - "200": { - description: "清理结果" - } - } - } - }, - "/api/v1/simulation/templates": { - get: { - tags: ["Simulation & Testing"], - "x-apifox-folder": "原始业务接口/Simulation & Testing", - summary: "获取仿真单据模板列表", - operationId: "listSimulationTemplates", - responses: dataResponse("模板列表", { - type: "array", - items: { $ref: "#/components/schemas/SimulationTemplate" } - }) - } - }, - "/api/v1/simulation/integration-status": { - get: { - tags: ["Simulation & Testing"], - "x-apifox-folder": "原始业务接口/Simulation & Testing", - summary: "获取各外部系统仿真对接可用状态", - operationId: "getSimulationIntegrationStatus", - responses: dataResponse("对接可用性状态", { $ref: "#/components/schemas/SimulationIntegrationStatus" }) - } - }, - "/api/v1/simulation/hosecloud-integrations": { - get: { - tags: ["Simulation & Testing"], - "x-apifox-folder": "原始业务接口/Simulation & Testing", - summary: "获取合思企业集成实例列表", - operationId: "listSimulationHosecloudIntegrations", - responses: dataResponse("合思集成实例列表", { - type: "array", - items: { $ref: "#/components/schemas/SimulationHosecloudIntegration" } - }) - } - }, - "/api/v1/simulation/hosecloud-specifications": { - get: { - tags: ["Simulation & Testing"], - "x-apifox-folder": "原始业务接口/Simulation & Testing", - summary: "获取合思审批流规格列表", - operationId: "listSimulationSpecifications", - responses: dataResponse("审批流规格列表", { - type: "array", - items: { $ref: "#/components/schemas/SimulationSpecification" } - }) - } - }, - "/api/v1/simulation/hosecloud-specifications-by-sign-key": { - get: { - tags: ["Simulation & Testing"], - "x-apifox-folder": "原始业务接口/Simulation & Testing", - summary: "按 signKey 获取合思审批流规格", - operationId: "listSimulationSpecificationsBySignKey", - parameters: [ - { name: "signKey", in: "query", required: true, schema: { type: "string" } } - ], - responses: dataResponse("审批流规格列表", { - type: "array", - items: { $ref: "#/components/schemas/SimulationSpecification" } - }) - } - }, - "/api/v1/material-packages/upload": { - post: { - tags: ["Simulation & Testing"], - "x-apifox-folder": "原始业务接口/Simulation & Testing", - summary: "上传材料包 ZIP 文件", - operationId: "uploadMaterialPackage", - requestBody: { - required: true, - content: { - "multipart/form-data": { - schema: { - type: "object", - required: ["file"], - properties: { - file: { type: "string", format: "binary", description: "材料包压缩文件" } - } - } - } - } - }, - responses: dataResponse("上传解析结果", { $ref: "#/components/schemas/MaterialPackage" }) - } - }, - "/api/v1/delegation/list": { - get: { - tags: ["Delegation"], - "x-apifox-folder": "原始业务接口/Delegation", - summary: "获取转授权/协助令牌列表", - operationId: "listDelegations", - responses: dataResponse("转授权列表", { - type: "array", - items: { $ref: "#/components/schemas/SealDelegationItem" } - }) - } - }, - "/api/v1/delegation/create": { - post: { - tags: ["Delegation"], - "x-apifox-folder": "原始业务接口/Delegation", - summary: "创建转授权协助链接", - operationId: "createDelegation", - requestBody: { - required: false, - content: { - "application/json": { - schema: { - type: "object", - properties: { - note: { type: "string", description: "备注信息" } - } - } - } - } - }, - responses: dataResponse("创建结果与协助链接", { $ref: "#/components/schemas/SealDelegationCreateResult" }) - } - }, - "/api/v1/delegation/revoke": { - post: { - tags: ["Delegation"], - "x-apifox-folder": "原始业务接口/Delegation", - summary: "作废转授权令牌", - operationId: "revokeDelegation", - requestBody: { - required: true, - content: { - "application/json": { - schema: { - type: "object", - required: ["tokenId"], - properties: { - tokenId: { type: "string" } - } - } - } - } - }, - responses: { - "200": { - description: "作废结果" - } - } - } - }, - "/api/v1/contacts/departments/root/children": { - get: { - tags: ["Contacts & Users"], - "x-apifox-folder": "原始业务接口/Contacts & Users", - summary: "获取根部门子部门列表", - operationId: "getRootDepartmentChildren", - responses: { - "200": { - description: "根部门子节点" - } - } - } - }, - "/api/v1/contacts/local/users": { - post: { - tags: ["Contacts & Users"], - "x-apifox-folder": "原始业务接口/Contacts & Users", - summary: "创建本地用户", - operationId: "createLocalUser", - requestBody: { - required: true, - content: { - "application/json": { - schema: { - type: "object", - required: ["name", "phone"], - properties: { - name: { type: "string", description: "姓名" }, - phone: { type: "string", description: "手机号" }, - permissions: { type: "array", items: { type: "string" } }, - departmentIds: { type: "array", items: { type: "string" } } - } - } - } - } - }, - responses: dataResponse("创建结果与初始密码", { $ref: "#/components/schemas/SealUserCreateResult" }) - } - }, - "/api/v1/contacts/local/users/{userId}/reset-password": { - post: { - tags: ["Contacts & Users"], - "x-apifox-folder": "原始业务接口/Contacts & Users", - summary: "重置本地用户密码", - operationId: "resetUserPassword", - parameters: [ - { name: "userId", in: "path", required: true, schema: { type: "string" } } - ], - responses: dataResponse("重置后的临时密码", { $ref: "#/components/schemas/SealUserResetPasswordResult" }) - } - }, - "/api/v1/contacts/users/{userId}": { - get: { - tags: ["Contacts & Users"], - "x-apifox-folder": "原始业务接口/Contacts & Users", - summary: "获取用户详情", - operationId: "getUserDetail", - parameters: [ - { name: "userId", in: "path", required: true, schema: { type: "string" } } - ], - responses: dataResponse("用户详情", { $ref: "#/components/schemas/SealUserDetail" }) - } - }, - "/api/v1/contacts/search": { - get: { - tags: ["Contacts & Users"], - "x-apifox-folder": "原始业务接口/Contacts & Users", - summary: "按关键字或手机号搜索用户/部门", - operationId: "searchUsers", - parameters: [ - { name: "query", in: "query", schema: { type: "string" } } - ], - responses: dataResponse("搜索命中结果", { $ref: "#/components/schemas/SealContactSearchResult" }) - } - }, - "/api/v1/contacts/local/users/{userId}": { - delete: { - tags: ["Contacts & Users"], - "x-apifox-folder": "原始业务接口/Contacts & Users", - summary: "删除/离职本地用户", - operationId: "deleteLocalUser", - parameters: [ - { name: "userId", in: "path", required: true, schema: { type: "string" } } - ], - responses: { - "200": { - description: "操作结果" - } - } - } - }, - "/api/v1/contacts/local/users/{userId}/activate": { - post: { - tags: ["Contacts & Users"], - "x-apifox-folder": "原始业务接口/Contacts & Users", - summary: "重新激活离职用户", - operationId: "activateLocalUser", - parameters: [ - { name: "userId", in: "path", required: true, schema: { type: "string" } } - ], - responses: { - "200": { - description: "激活结果" - } - } - } - }, - "/api/hosecloud/corporation": { - post: { - tags: ["HoseCloud OEM Integration"], - "x-apifox-folder": "原始业务接口/HoseCloud OEM Integration", - summary: "验证并获取合思企业 CorporationId", - operationId: "getHosecloudCorporation", - requestBody: { - required: true, - content: { - "application/json": { - schema: { - type: "object", - required: ["apiKey", "apiSecret"], - properties: { - apiKey: { type: "string" }, - apiSecret: { type: "string" }, - apiOrigin: { type: "string", default: "production" }, - customApiUrl: { type: "string" } - } - } - } - } - }, - responses: dataResponse("企业 ID", { - type: "object", - properties: { - corporationId: { type: "string" } - } - }) - } - }, - "/api/hosecloud/outbound-config/sync": { - post: { - tags: ["HoseCloud OEM Integration"], - "x-apifox-folder": "原始业务接口/HoseCloud OEM Integration", - summary: "同步合思出站配置与回调 Webhook", - operationId: "syncHosecloudOutbound", - requestBody: { - required: true, - content: { - "application/json": { - schema: { - type: "object", - required: ["signKey", "webhookUrl", "completionWebhookUrl", "messageName", "mode"], - properties: { - signKey: { type: "string" }, - webhookUrl: { type: "string" }, - completionWebhookUrl: { type: "string" }, - messageName: { type: "string" }, - mode: { type: "string" } - } - } - } - } - }, - responses: { - "200": { - description: "同步结果" - } - } - } - }, - "/api/v1/llm/config": { - get: { - tags: ["System, LLM & Billing"], - "x-apifox-folder": "原始业务接口/System, LLM & Billing", - summary: "获取当前租户大模型配置", - operationId: "getLlmConfig", - responses: dataResponse("大模型配置", { $ref: "#/components/schemas/LlmConfig" }) - } - }, - "/api/v1/llm/providers": { - get: { - tags: ["System, LLM & Billing"], - "x-apifox-folder": "原始业务接口/System, LLM & Billing", - summary: "获取系统支持的大模型提供商列表", - operationId: "listLlmProviders", - responses: dataResponse("大模型提供商", { - type: "array", - items: { $ref: "#/components/schemas/LlmProvider" } - }) - } - }, - "/api/v1/permissions/available": { - get: { - tags: ["System, LLM & Billing"], - "x-apifox-folder": "原始业务接口/System, LLM & Billing", - summary: "获取系统可用权限列表", - operationId: "listAvailablePermissions", - responses: dataResponse("可用权限列表", { $ref: "#/components/schemas/AvailablePermissionsData" }) - } - }, - "/api/v1/permissions/configs": { - get: { - tags: ["System, LLM & Billing"], - "x-apifox-folder": "原始业务接口/System, LLM & Billing", - summary: "获取系统权限配置", - operationId: "listPermissionConfigs", - responses: dataResponse("权限配置", { $ref: "#/components/schemas/PermissionConfigsData" }) - } - }, - "/api/v1/billing/status": { - get: { - tags: ["System, LLM & Billing"], - "x-apifox-folder": "原始业务接口/System, LLM & Billing", - summary: "获取租户订阅与计费状态", - operationId: "getBillingStatus", - responses: dataResponse("计费状态", { $ref: "#/components/schemas/BillingStatusData" }) - } - }, - "/api/v1/billing/plans": { - get: { - tags: ["System, LLM & Billing"], - "x-apifox-folder": "原始业务接口/System, LLM & Billing", - summary: "获取计费套餐列表", - operationId: "listBillingPlans", - responses: { - "200": { - description: "套餐计划列表" - } - } - } - }, - "/api/v1/billing/features": { - get: { - tags: ["System, LLM & Billing"], - "x-apifox-folder": "原始业务接口/System, LLM & Billing", - summary: "获取计费功能开关与额度", - operationId: "listBillingFeatures", - responses: { - "200": { - description: "功能特性与额度" - } - } - } - } - }, - components: { - securitySchemes: { - bearerAuth: { - type: "http", - scheme: "bearer", - bearerFormat: "JWT / Session Token", - description: "Seal AI 下游原生 Bearer 认证 Token (Authorization: Bearer )" - } - }, - schemas: { - ErrorResponse: { - type: "object", - required: ["error"], - properties: { - error: { - type: "object", - required: ["code", "message"], - properties: { - code: { type: "string", description: "错误标识码 (例如: error:auth:invalid-token)" }, - message: { type: "string", description: "错误详细描述" } - } - } - } - }, - HosecloudStaff: { - type: "object", - required: ["staffId"], - properties: { - staffId: { type: "string" }, - name: { type: "string" }, - code: { type: "string", default: "" }, - bindTime: { type: "number" } - } - }, - SealUser: { - type: "object", - required: ["id", "tenantId", "name"], - properties: { - id: { type: "string" }, - tenantId: { type: "string" }, - name: { type: "string" }, - isAdmin: { type: "boolean", default: false }, - permissions: { type: "array", items: { type: "string" }, default: [] }, - providerUserId: { type: "string" }, - hosecloudStaff: { $ref: "#/components/schemas/HosecloudStaff" } - } - }, - HoseCorpConfig: { - type: "object", - properties: { - apiKey: { type: "string" }, - corporationId: { type: "string" }, - corporationName: { type: "string" } - } - }, - SealTenant: { - type: "object", - required: ["id", "name"], - properties: { - id: { type: "string" }, - name: { type: "string" }, - tenantSlug: { type: "string" }, - isDemo: { type: "boolean", default: false }, - logoUrl: { type: "string", nullable: true }, - hoseCorpConfig: { $ref: "#/components/schemas/HoseCorpConfig" } - } - }, - MeData: { - type: "object", - required: ["user", "tenant"], - properties: { - user: { $ref: "#/components/schemas/SealUser" }, - tenant: { $ref: "#/components/schemas/SealTenant" } - } - }, - SealSessionUser: { - type: "object", - required: ["id", "name"], - properties: { - id: { type: "string" }, - name: { type: "string" }, - email: { type: "string", nullable: true }, - emailVerified: { type: "boolean" }, - image: { type: "string", nullable: true }, - tenantId: { type: "string" }, - provider: { type: "string" }, - providerUserId: { type: "string" }, - mobile: { type: "string", nullable: true }, - status: { type: "string" }, - permissions: { type: "array", items: { type: "string" }, default: [] }, - isAdmin: { type: "boolean", default: false } - } - }, - SealSessionInfo: { - type: "object", - required: ["id", "expiresAt", "userId"], - properties: { - id: { type: "string" }, - token: { type: "string" }, - expiresAt: { type: "string" }, - createdAt: { type: "string" }, - updatedAt: { type: "string" }, - ipAddress: { type: "string" }, - userAgent: { type: "string" }, - userId: { type: "string" }, - delegationId: { type: "string", nullable: true } - } - }, - SealSessionData: { - type: "object", - required: ["user", "session"], - properties: { - user: { $ref: "#/components/schemas/SealSessionUser" }, - session: { $ref: "#/components/schemas/SealSessionInfo" } - } - }, - ApprovalRule: { - type: "object", - required: ["id", "description", "scope", "strictness"], - properties: { - id: { type: "string" }, - tenantId: { type: "string" }, - code: { type: "number" }, - description: { type: "string" }, - scope: { type: "string" }, - strictness: { type: "string" }, - status: { type: "string" }, - createdAt: { type: "number" }, - updatedAt: { type: "number" } - } - }, - ApprovalRuleInput: { - type: "object", - required: ["description", "scope", "strictness"], - properties: { - description: { type: "string" }, - scope: { type: "string" }, - strictness: { type: "string" } - } - }, - ApprovalRuleUpdate: { - type: "object", - properties: { - description: { type: "string" }, - scope: { type: "string" }, - strictness: { type: "string" } - } - }, - ApprovalRulesData: { - type: "object", - required: ["rules"], - properties: { - rules: { type: "array", items: { $ref: "#/components/schemas/ApprovalRule" } }, - hasPendingDeletes: { type: "boolean", default: false } - } - }, - PublishedRuleSnapshot: { - type: "object", - required: ["description", "scope", "strictness"], - properties: { - code: { type: "string" }, - description: { type: "string" }, - scope: { type: "string" }, - strictness: { type: "string" } - } - }, - RuleSetVersion: { - type: "object", - required: ["id", "versionNumber"], - properties: { - id: { type: "string" }, - tenantId: { type: "string" }, - versionNumber: { type: "number" }, - versionName: { type: "string", nullable: true }, - publishedBy: { type: "string", nullable: true }, - publishedByName: { type: "string", nullable: true }, - rules: { type: "array", items: { $ref: "#/components/schemas/PublishedRuleSnapshot" }, default: [] }, - publishedAt: { type: "number" }, - createdAt: { type: "number" } - } - }, - PublishVersionData: { - type: "object", - required: ["version", "rulesCount"], - properties: { - version: { $ref: "#/components/schemas/RuleSetVersion" }, - rulesCount: { type: "number" } - } - }, - ApprovalDocument: { - type: "object", - required: ["id", "title", "content"], - properties: { - id: { type: "string" }, - tenantId: { type: "string" }, - title: { type: "string" }, - purpose: { type: "string", default: "" }, - contentType: { type: "string", default: "policy" }, - content: { type: "string" }, - status: { type: "string", default: "published" }, - enabled: { type: "boolean", default: true }, - scenarios: { type: "array", items: { type: "string" }, default: [] }, - tags: { type: "array", items: { type: "string" }, default: [] }, - category: { type: "string", nullable: true }, - categoryTags: { type: "array", items: { type: "string" }, default: [] }, - createdBy: { type: "string", nullable: true }, - createdByName: { type: "string", nullable: true }, - createdAt: { type: "number" }, - updatedAt: { type: "number" }, - updatedBy: { type: "string", nullable: true }, - updatedByName: { type: "string", nullable: true }, - isDeleted: { type: "boolean", default: false } - } - }, - ApprovalDocumentInput: { - type: "object", - required: ["title", "purpose", "content"], - properties: { - title: { type: "string" }, - purpose: { type: "string" }, - content: { type: "string" }, - contentType: { type: "string", default: "policy" }, - status: { type: "string", default: "published" }, - scenarios: { type: "array", items: { type: "string" }, default: [] }, - tags: { type: "array", items: { type: "string" }, default: [] } - } - }, - ApprovalDocumentUpdate: { - type: "object", - 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" } } - } - }, - ApprovalDocumentListData: { - type: "object", - required: ["articles"], - properties: { - articles: { type: "array", items: { $ref: "#/components/schemas/ApprovalDocument" } }, - total: { type: "number" } - } - }, - DecisionPreferences: { - type: "object", - properties: { - explicitApprove: { type: "string", default: "" }, - explicitReject: { type: "string", default: "" }, - exemptApprove: { type: "string", default: "" }, - review: { type: "string", default: "" } - } - }, - WebhookEndpoint: { - type: "object", - required: ["id", "url"], - properties: { - id: { type: "string" }, - url: { type: "string", format: "uri" } - } - }, - WebhookIntegration: { - type: "object", - required: ["type", "id", "name", "mode", "incomingDocumentWebhook", "outgoingResultWebhook", "incomingManualResultWebhook", "secret"], - properties: { - type: { type: "string", enum: ["webhook"] }, - id: { type: "string" }, - name: { type: "string" }, - mode: { type: "string", enum: ["assisted", "semi_automatic", "fully_automatic"] }, - incomingDocumentWebhook: { $ref: "#/components/schemas/WebhookEndpoint" }, - outgoingResultWebhook: { type: "string", format: "uri" }, - incomingManualResultWebhook: { $ref: "#/components/schemas/WebhookEndpoint" }, - secret: { type: "string" }, - autoApprovalRate: { type: "integer", minimum: 0, maximum: 100 } - } - }, - ApprovalIntegration: { - type: "object", - required: ["type"], - properties: { - type: { type: "string" }, - signKey: { type: "string" }, - outboundName: { type: "string" }, - mode: { type: "string" }, - autoApprovalRate: { type: "number" }, - apiKey: { type: "string" }, - apiSecret: { type: "string" }, - apiOrigin: { type: "string" }, - corporationId: { type: "string" } - } - }, - ApprovalStylePreferences: { - type: "object", - properties: { - id: { type: "string" }, - tenantId: { type: "string" }, - tone: { type: "string" }, - language: { type: "string" }, - detailLevel: { type: "string" }, - outputFormat: { type: "string" }, - examples: { type: "array", items: { type: "string" }, default: [] }, - prohibitedPhrases: { type: "array", items: { type: "string" }, default: [] }, - customInstructions: { type: "string" }, - updatedAt: { type: "number" }, - decisionPreferences: { $ref: "#/components/schemas/DecisionPreferences" }, - integrationSystem: { type: "string" }, - integrations: { - type: "array", - items: { $ref: "#/components/schemas/ApprovalIntegration" }, - default: [] - } - } - }, - ApprovalRunDocument: { - type: "object", - properties: { - id: { type: "string" }, - sn: { type: "string" }, - title: { type: "string" }, - name: { type: "string" }, - fields: { type: "array", items: { type: "object" } } - } - }, - ApprovalRunSourceExtendData: { - type: "object", - properties: { - _langfuseTraceId: { type: "string" }, - simulation_batch_id: { type: "string" } - } - }, - ApprovalRun: { - type: "object", - required: ["id"], - properties: { - id: { type: "string" }, - tenantId: { type: "string" }, - agentId: { type: "string" }, - status: { type: "string" }, - taskMode: { type: "string" }, - finalExecutionMode: { type: "string" }, - sourceSystem: { type: "string" }, - sourceDocumentSN: { type: "string" }, - sourceDocumentId: { type: "string" }, - documentId: { type: "string" }, - document: { $ref: "#/components/schemas/ApprovalRunDocument" }, - result: { type: "object" }, - pipelineData: { type: "object" }, - sourceExtendData: { $ref: "#/components/schemas/ApprovalRunSourceExtendData" }, - ruleSetVersionNumber: { type: "number" }, - ruleSetPublishedAt: { type: "number" }, - ruleSetPublishedByName: { type: "string" }, - createdAt: { type: "string" }, - updatedAt: { type: "string" } - } - }, - ApprovalRunListData: { - type: "object", - required: ["records"], - properties: { - records: { type: "array", items: { $ref: "#/components/schemas/ApprovalRun" } }, - total: { type: "number" }, - page: { type: "number" }, - pageSize: { type: "number" } - } - }, - SealDelegationItem: { - type: "object", - required: ["id", "link"], - properties: { - id: { type: "string" }, - expiresAt: { type: "number", nullable: true }, - revokedAt: { type: "number", nullable: true }, - createdAt: { type: "number", nullable: true }, - lastUsedAt: { type: "number", nullable: true }, - useCount: { type: "number", default: 0 }, - note: { type: "string", nullable: true }, - link: { type: "string" } - } - }, - SealDelegationCreateResult: { - type: "object", - required: ["id", "token", "link"], - properties: { - id: { type: "string" }, - token: { type: "string" }, - link: { type: "string" } - } - }, - SealUserCreateResult: { - type: "object", - required: ["userId", "password"], - properties: { - userId: { type: "string" }, - password: { type: "string" } - } - }, - SealUserResetPasswordResult: { - type: "object", - required: ["password"], - properties: { - password: { type: "string" } - } - }, - SealUserDetail: { - type: "object", - required: ["_id", "name"], - properties: { - _id: { type: "string" }, - tenantId: { type: "string" }, - name: { type: "string" }, - mobile: { type: "string" }, - email: { type: "string" }, - departmentIds: { type: "array", items: { type: "string" }, default: [] }, - status: { type: "string" }, - permissions: { type: "array", items: { type: "string" }, default: [] }, - createdAt: { type: "string" }, - updatedAt: { type: "string" } - } - }, - SealContactSearchResult: { - type: "object", - required: ["departments", "users"], - properties: { - departments: { type: "array", items: { type: "object" } }, - users: { type: "array", items: { $ref: "#/components/schemas/SealUserDetail" } } - } - }, - LlmConfig: { - type: "object", - required: ["provider"], - properties: { - provider: { type: "string" }, - config: { type: "object" } - } - }, - LlmProvider: { - type: "object", - required: ["id", "name"], - properties: { - id: { type: "string" }, - name: { type: "string" }, - description: { type: "string" }, - available: { type: "boolean", default: true }, - fields: { type: "array", items: { type: "object" } } - } - }, - AvailablePermissionsData: { - type: "object", - required: ["permissions"], - properties: { - permissions: { - type: "array", - items: { - type: "object", - required: ["key", "name"], - properties: { - key: { type: "string" }, - name: { type: "string" }, - description: { type: "string" } - } - } - } - } - }, - PermissionConfigsData: { - type: "object", - required: ["configs"], - properties: { - configs: { type: "array", items: { type: "object" } } - } - }, - BillingStatusData: { - type: "object", - required: ["subscriptions", "features"], - properties: { - subscriptions: { type: "array", items: { type: "object" } }, - features: { type: "array", items: { type: "object" } } - } - }, - SimulationBatchParams: { - type: "object", - required: ["approvalCode"], - properties: { - approvalCode: { type: "string" }, - nodeId: { type: "string" }, - flowIds: { type: "array", items: { type: "string" }, maxItems: 100 }, - limit: { type: "integer", minimum: 1, maximum: 100 }, - dataCollectionMode: { type: "string" }, - signKey: { type: "string" }, - rejectNodeName: { type: "string", nullable: true }, - skipInvoiceGeneration: { type: "boolean" }, - skipExpenseExtraction: { type: "boolean" }, - disableAttachmentCache: { type: "boolean" }, - thinkingDepthOverride: { type: "string", enum: ["default", "medium", "high"] }, - templateId: { type: "string" }, - packageIds: { type: "array", items: { type: "string" } }, - packageLabel: { type: "string" }, - runMode: { type: "string" } - } - }, - SimulationBatch: { - type: "object", - required: ["id"], - properties: { - id: { type: "string" }, - tenantId: { type: "string" }, - approvalCode: { type: "string" }, - nodeId: { type: "string" }, - sourceSystem: { type: "string" }, - status: { type: "string" }, - totalCount: { type: "number", default: 0 }, - processedCount: { type: "number", default: 0 }, - successCount: { type: "number", default: 0 }, - failedCount: { type: "number", default: 0 }, - createdCount: { type: "number", default: 0 }, - createFailedCount: { type: "number", default: 0 }, - params: { $ref: "#/components/schemas/SimulationBatchParams" }, - createdAt: { type: "string" }, - updatedAt: { type: "string" } - } - }, - SimulationCreateResult: { - type: "object", - required: ["batchId"], - properties: { - batchId: { type: "string" } - } - }, - SimulationTemplate: { - type: "object", - required: ["id"], - properties: { - id: { type: "string" }, - tenantId: { type: "string" }, - name: { type: "string" }, - description: { type: "string" }, - approvalSystem: { type: "string" }, - createdAt: { type: "string" }, - updatedAt: { type: "string" } - } - }, - SimulationIntegrationStatus: { - type: "object", - required: ["hasFeishu", "hasHosecloud", "hasWeaver", "hasHelios", "hasMaycur", "hasMaycurStandard"], - properties: { - hasFeishu: { type: "boolean" }, - hasHosecloud: { type: "boolean" }, - hasWeaver: { type: "boolean" }, - hasHelios: { type: "boolean" }, - hasMaycur: { type: "boolean" }, - hasMaycurStandard: { type: "boolean" } - } - }, - SimulationHosecloudIntegration: { - type: "object", - properties: { - signKey: { type: "string" }, - displayName: { type: "string" }, - corporationId: { type: "string" } - } - }, - SimulationSpecification: { - type: "object", - properties: { - id: { type: "string" }, - code: { type: "string" }, - name: { type: "string" }, - approvalSystem: { type: "string" } - } - }, - MaterialPackage: { - type: "object", - required: ["id"], - properties: { - id: { type: "string" }, - tenantId: { type: "string" }, - name: { type: "string" }, - templateId: { type: "string" }, - originalFileName: { type: "string" }, - status: { type: "string" }, - documentCount: { type: "number" }, - attachmentCount: { type: "number" }, - uploadedBy: { type: "string" } - } - } - } - } -}; - -mkdirSync(dirname(outputFile), { recursive: true }); -writeFileSync(outputFile, `${JSON.stringify(spec, null, 2)}\n`); -console.log(`Wrote ${outputFile}`); diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index a1c369d..871dd27 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -65,9 +65,6 @@ seal-use documents search [--maxResults 20] [--corp ] seal-use documents create --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`. diff --git a/src/cli.test.ts b/src/cli.test.ts index 8ebbd9e..d9e91d5 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -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); diff --git a/src/cli/commands/http.ts b/src/cli/commands/http.ts deleted file mode 100644 index 4a5b8d1..0000000 --- a/src/cli/commands/http.ts +++ /dev/null @@ -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(() => {}); -} diff --git a/src/cli/commands/openapi.ts b/src/cli/commands/openapi.ts deleted file mode 100644 index 5d625e7..0000000 --- a/src/cli/commands/openapi.ts +++ /dev/null @@ -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 }); -} diff --git a/src/cli/commands/service.ts b/src/cli/commands/service.ts deleted file mode 100644 index f44c54e..0000000 --- a/src/cli/commands/service.ts +++ /dev/null @@ -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); -} diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.ts index 11978b6..4bf5527 100644 --- a/src/cli/commands/update.ts +++ b/src/cli/commands/update.ts @@ -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` diff --git a/src/cli/help.test.ts b/src/cli/help.test.ts index 423d9e0..d3380ce 100644 --- a/src/cli/help.test.ts +++ b/src/cli/help.test.ts @@ -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); diff --git a/src/cli/help.ts b/src/cli/help.ts index 4b9a211..6aa3c4e 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -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", diff --git a/src/cli/read-only.test.ts b/src/cli/read-only.test.ts index 2a96c5e..67ce2d2 100644 --- a/src/cli/read-only.test.ts +++ b/src/cli/read-only.test.ts @@ -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", () => { diff --git a/src/cli/read-only.ts b/src/cli/read-only.ts index 900d2f0..7d22deb 100644 --- a/src/cli/read-only.ts +++ b/src/cli/read-only.ts @@ -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: [""] }; /** diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 36af0fe..aa8b982 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -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.`); diff --git a/src/cli/service.test.ts b/src/cli/service.test.ts deleted file mode 100644 index b1a523b..0000000 --- a/src/cli/service.test.ts +++ /dev/null @@ -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"); - }); -}); diff --git a/src/cli/service.ts b/src/cli/service.ts deleted file mode 100644 index 68bc1fb..0000000 --- a/src/cli/service.ts +++ /dev/null @@ -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 }); -} diff --git a/src/cli/types.ts b/src/cli/types.ts index 74f112d..f4f8125 100644 --- a/src/cli/types.ts +++ b/src/cli/types.ts @@ -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 = { diff --git a/src/core/doctor/knowledge.ts b/src/core/doctor/knowledge.ts index a9653d6..803710e 100644 --- a/src/core/doctor/knowledge.ts +++ b/src/core/doctor/knowledge.ts @@ -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", diff --git a/src/core/embedded-openapi.test.ts b/src/core/embedded-openapi.test.ts deleted file mode 100644 index 328d2e5..0000000 --- a/src/core/embedded-openapi.test.ts +++ /dev/null @@ -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(); - }); -}); diff --git a/src/core/embedded-openapi.ts b/src/core/embedded-openapi.ts deleted file mode 100644 index 70e28f0..0000000 --- a/src/core/embedded-openapi.ts +++ /dev/null @@ -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>; -} diff --git a/src/http/docs.ts b/src/http/docs.ts deleted file mode 100644 index 9e51cab..0000000 --- a/src/http/docs.ts +++ /dev/null @@ -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}) - - - - - - -`; -} diff --git a/src/http/openapi-implementation.test.ts b/src/http/openapi-implementation.test.ts deleted file mode 100644 index 967b226..0000000 --- a/src/http/openapi-implementation.test.ts +++ /dev/null @@ -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>; - }; - 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)[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 }); - } - }); -}); diff --git a/src/http/routes.ts b/src/http/routes.ts deleted file mode 100644 index 53e094f..0000000 --- a/src/http/routes.ts +++ /dev/null @@ -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 { - // 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; - 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 { - 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 | 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> { - 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 } : {}) - }); -} diff --git a/src/http/server.test.ts b/src/http/server.test.ts deleted file mode 100644 index 676db51..0000000 --- a/src/http/server.test.ts +++ /dev/null @@ -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((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(" { - 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"); - }); -}); diff --git a/src/http/server.ts b/src/http/server.ts deleted file mode 100644 index f52744c..0000000 --- a/src/http/server.ts +++ /dev/null @@ -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 { - 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); - }); - }); -}