diff --git a/.agents/skills/seal-home/SKILL.md b/.agents/skills/seal-home/SKILL.md index f48e778..9027350 100644 --- a/.agents/skills/seal-home/SKILL.md +++ b/.agents/skills/seal-home/SKILL.md @@ -29,7 +29,7 @@ seal-home tools list - When returning ANY authorization, login, or delegation links (e.g. 合思授权链接, Seal授权链接/委托链接), ALWAYS provide BOTH a code block (` ```text ... ``` `) for easy copying without accidental default browser redirection, AND a clickable hyperlink. - For delegation links, always prefer `seal-home delegation create` over `users delegation` for link generation to ensure persistent token tracking. - Never treat “Seal 协助/Seal 授权/委托” as a 合思授权入口. They are different links and must use different commands. -- A delegation link belongs to the Seal tenant selected by `--corp`; omitting `--corp` uses the current tenant and is unsafe for an explicitly named enterprise. +- In the default stateless mode, every enterprise command requires `--corp `. In stateful mode, omitting `--corp` uses the configured default enterprise and is unsafe for an explicitly named enterprise. - For an explicitly named enterprise, first resolve it with `seal-home corps list`, then pass its exact `corpId` to every command. After creation, verify the returned URL host matches that enterprise's Seal tenant; if the host is the current/default tenant or cannot be verified, do not present the link as the target enterprise's link. ## Route By Intent @@ -37,31 +37,31 @@ seal-home tools list - User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-home delegation create --corp --note ''`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink. - Packaged customer feedback → approval-rule remediation: read `references/customer-feedback-rule-remediation.md`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version. - User-facing 合思 authorization link (合思/易快报授权): `seal-home auth hose-link --corp --expire 7200`; read `references/hose-enterprise-auth.md`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink. -- Delegation links management: `seal-home delegation list`, `create [--note ...]`, `revoke `. -- User & Contacts Management (用户搜索、激活与一键代生成授权): `seal-home users search [keyword]`, `users delegation ` (仅适用于 Seal 本地创建的账号 `provider: local`;对合思同步账号系统拒绝重置密码,需改用 `auth hose-link`), `users activate `, `users create --name ... --phone ...`, `reset-password `, `get `, `delete `. -- LLM Model Config & Providers: `seal-home llm config`, `seal-home llm providers`. -- System Permissions Config: `seal-home permissions available`, `seal-home permissions configs`. -- Billing & Feature Quotas: `seal-home billing status`, `seal-home billing plans`, `seal-home billing features`. +- Delegation links management: `seal-home delegation list --corp `, `create [--note ...] --corp `, `revoke --corp `. +- User & Contacts Management (用户搜索、激活与一键代生成授权): `seal-home users search [keyword] --corp `, `users delegation --corp ` (仅适用于 Seal 本地创建的账号 `provider: local`;对合思同步账号系统拒绝重置密码,需改用 `auth hose-link`), `users activate --corp `, `users create --name ... --phone ... --corp `, `reset-password --corp `, `get --corp `, `delete --corp `. +- LLM Model Config & Providers: `seal-home llm config --corp `, `seal-home llm providers --corp `. +- System Permissions Config: `seal-home permissions available --corp `, `seal-home permissions configs --corp `. +- Billing & Feature Quotas: `seal-home billing status --corp `, `seal-home billing plans --corp `, `seal-home billing features --corp `. - Full CLI inventory: read `references/cli.md`. ## High-Value Commands ```bash -seal-home approval-runs pick --sn --latest -seal-home approval-runs pick --sn --batch --latest --fields recordId,status,aiDecision,aiSummary -seal-home approval-runs get --summary -seal-home approval-runs get --fields metadata,document.fields,result.summary -seal-home approval-runs document-summary -seal-home approval-runs cited-rules -seal-home approval-runs attachments --summary -seal-home approval-runs result --summary +seal-home approval-runs pick --corp --sn --latest +seal-home approval-runs pick --corp --sn --batch --latest --fields recordId,status,aiDecision,aiSummary +seal-home approval-runs get --corp --summary +seal-home approval-runs get --corp --fields metadata,document.fields,result.summary +seal-home approval-runs document-summary --corp +seal-home approval-runs cited-rules --corp +seal-home approval-runs attachments --corp --summary +seal-home approval-runs result --corp --summary seal-home rules count --corp seal-home rules list --corp --summary seal-home rules clear --corp --dry-run seal-home rules clear --corp --yes -seal-home rules get --version 16 --code '#0038' -seal-home rules get --record-id --runtime-id rule-205 -seal-home tool seal_approval_search --json '{"keywords":["差旅","发票"],"areas":["rules"],"snippetOnly":true,"maxChars":500,"fields":["id","title","snippet"]}' +seal-home rules get --corp --version 16 --code '#0038' +seal-home rules get --corp --record-id --runtime-id rule-205 +seal-home tool seal_approval_search --corp --json '{"keywords":["差旅","发票"],"areas":["rules"],"snippetOnly":true,"maxChars":500,"fields":["id","title","snippet"]}' ``` ## Important Fields diff --git a/.agents/skills/seal-home/references/approval-attachment-trace.md b/.agents/skills/seal-home/references/approval-attachment-trace.md index e1c7fa8..540912e 100644 --- a/.agents/skills/seal-home/references/approval-attachment-trace.md +++ b/.agents/skills/seal-home/references/approval-attachment-trace.md @@ -33,9 +33,9 @@ Approval traces commonly contain these stages: Start from the Seal run and Langfuse trace. ```bash -seal-home approval-runs search --query --limit 50 -seal-home approval-runs get > /tmp/seal-run.json -seal-home approval-runs bridge --sourceDocumentSN +seal-home approval-runs search --corp --query --limit 50 +seal-home approval-runs get --corp > /tmp/seal-run.json +seal-home approval-runs bridge --corp --sourceDocumentSN ``` Refresh and inspect the Langfuse trace. diff --git a/.agents/skills/seal-home/references/approval-run-lightweight.md b/.agents/skills/seal-home/references/approval-run-lightweight.md index d2e88e8..40e49fa 100644 --- a/.agents/skills/seal-home/references/approval-run-lightweight.md +++ b/.agents/skills/seal-home/references/approval-run-lightweight.md @@ -21,16 +21,16 @@ If there are multiple candidates and `--latest` was not used, report the candida Use `--summary` for most diagnosis and support questions. ```bash -seal-home approval-runs get --summary +seal-home approval-runs get --corp --summary ``` Use `--fields` when the user needs a particular slice. ```bash -seal-home approval-runs get --fields metadata -seal-home approval-runs get --fields document.fields,result.summary -seal-home approval-runs get --fields result.summary,result.decision,result.riskPoints -seal-home approval-runs get --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber +seal-home approval-runs get --corp --fields metadata +seal-home approval-runs get --corp --fields document.fields,result.summary +seal-home approval-runs get --corp --fields result.summary,result.decision,result.riskPoints +seal-home approval-runs get --corp --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber ``` Avoid full `approval-runs get ` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads. @@ -40,7 +40,7 @@ Avoid full `approval-runs get ` unless the user specifically needs raw Before pulling the full document, use: ```bash -seal-home approval-runs document-summary +seal-home approval-runs document-summary --corp ``` This is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result. @@ -50,7 +50,7 @@ This is for quick case reading: template/title, key fields, amount, expense type Use this when the user asks "AI 用了哪条规则", "为什么命中这条", or needs the rule evidence for a specific run. ```bash -seal-home approval-runs cited-rules +seal-home approval-runs cited-rules --corp ``` Return and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present. @@ -62,7 +62,7 @@ If the user then wants the full text of one cited rule, use `rules get --record- Use: ```bash -seal-home approval-runs attachments --summary +seal-home approval-runs attachments --corp --summary ``` This should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`. @@ -72,7 +72,7 @@ This should be enough for file names, file IDs, mime types, positions, invoice/a Use: ```bash -seal-home approval-runs result --summary +seal-home approval-runs result --corp --summary ``` This is for decision, summary, risk point count, matched rule count, trace ID, and record ID. diff --git a/.agents/skills/seal-home/references/cli.md b/.agents/skills/seal-home/references/cli.md index 86bd9ea..b5b88ac 100644 --- a/.agents/skills/seal-home/references/cli.md +++ b/.agents/skills/seal-home/references/cli.md @@ -12,16 +12,30 @@ Enterprise config lookup: - Otherwise `./enterprises` and `~/.config/seal-home/enterprises` are merged. - User-level configs override same-ID local configs. +Enterprise selection is stateless by default. Commands that access an enterprise require +`--corp ` unless stateful mode is explicitly enabled: + +```bash +seal-home config mode stateful --corp +seal-home corps switch +seal-home config mode stateless +``` + +The global mode is stored in `~/.config/seal-home/config.json`; set `SEAL_HOME_CONFIG_FILE` to +override that path. The legacy `current-corp` file is not read. + ## Top-Level Commands ```bash seal-home version seal-home config paths +seal-home config get +seal-home config mode [--corp ] seal-home service seal-home update seal-home tools list seal-home corps list [--corp ] -seal-home corps current +seal-home corps current [--corp ] seal-home corps switch seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' seal-home corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}' @@ -48,16 +62,16 @@ seal-home webhook update [--name ] [--result-url ] [--mode seal-home webhook delete --yes [--corp ] seal-home source config [--corp ] seal-home tool [--corp ] [--json '{"key":"value"}'] -seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] -seal-home approval-runs search [--query text] [--limit 20] [--includeBridge true] -seal-home approval-runs get [--fields metadata|document.fields,result.summary] [--output-file file.json] -seal-home approval-runs attachments -seal-home approval-runs result [--summary] -seal-home approval-runs url -seal-home approval-runs url -seal-home approval-runs url --sourceDocumentSN -seal-home approval-runs bridge [--sourceDocumentSN ] -seal-home simulation batch-records +seal-home approval-runs summary --corp [--date YYYY-MM-DD] [--timezone Asia/Shanghai] +seal-home approval-runs search --corp [--query text] [--limit 20] [--includeBridge true] +seal-home approval-runs get --corp [--fields metadata|document.fields,result.summary] [--output-file file.json] +seal-home approval-runs attachments --corp +seal-home approval-runs result --corp [--summary] +seal-home approval-runs url --corp +seal-home approval-runs url --corp +seal-home approval-runs url --sourceDocumentSN --corp +seal-home approval-runs bridge --corp [--sourceDocumentSN ] +seal-home simulation batch-records --corp ``` ## Fine-Grained Tools @@ -77,7 +91,7 @@ seal-home simulation batch-records Identity and session: -- `seal-home auth diagnose [--corp ]` +- `seal-home auth diagnose --corp ` - `seal_whoami` - `seal_session_get` @@ -96,14 +110,14 @@ Approval rule maintenance: Approval run lightweight queries: -- `seal-home approval-runs get --fields metadata` -- `seal-home approval-runs get --summary` -- `seal-home approval-runs pick --sn <单号> --batch --latest` -- `seal-home approval-runs document-summary ` -- `seal-home approval-runs cited-rules ` -- `seal-home approval-runs get --fields document.fields,result.summary` -- `seal-home approval-runs attachments --summary` -- `seal-home approval-runs result --summary` +- `seal-home approval-runs get --corp --fields metadata` +- `seal-home approval-runs get --corp --summary` +- `seal-home approval-runs pick --corp --sn <单号> --batch --latest` +- `seal-home approval-runs document-summary --corp ` +- `seal-home approval-runs cited-rules --corp ` +- `seal-home approval-runs get --corp --fields document.fields,result.summary` +- `seal-home approval-runs attachments --corp --summary` +- `seal-home approval-runs result --corp --summary` - `seal_approval_run_get` with `fields` - `seal_approval_run_pick` - `seal_approval_run_cited_rules_get` @@ -122,8 +136,8 @@ Approval search and context: - `seal_approval_search` - `seal_approval_context_get` -- `seal-home rules get --version --code '#0038'` -- `seal-home rules get --record-id --runtime-id rule-205` +- `seal-home rules get --corp --version --code '#0038'` +- `seal-home rules get --corp --record-id --runtime-id rule-205` Style preferences: @@ -178,49 +192,49 @@ The diagnostic stages are `hose.openapi`, `hose.provisional`, `seal.sso`, and `s Search approval content: ```bash -seal-home tool seal_approval_search --json '{"keywords":["关键词"],"matchMode":"any","maxResults":20}' +seal-home tool seal_approval_search --corp --json '{"keywords":["关键词"],"matchMode":"any","maxResults":20}' ``` Get aggregated approval context: ```bash -seal-home tool seal_approval_context_get --json '{"documentLimit":20}' +seal-home tool seal_approval_context_get --corp --json '{"documentLimit":20}' ``` Create a draft approval rule: ```bash -seal-home tool seal_approval_rule_create --json '{"description":"规则描述","scope":"适用场景","strictness":"SHOULD_FOLLOW"}' +seal-home tool seal_approval_rule_create --corp --json '{"description":"规则描述","scope":"适用场景","strictness":"SHOULD_FOLLOW"}' ``` Update an approval document: ```bash -seal-home tool seal_approval_document_update --json '{"documentId":"doc-id","content":"Markdown 内容"}' +seal-home tool seal_approval_document_update --corp --json '{"documentId":"doc-id","content":"Markdown 内容"}' ``` Summarize one local date: ```bash -seal-home approval-runs summary --date 2026-06-09 --timezone Asia/Shanghai --limit 100 +seal-home approval-runs summary --corp --date 2026-06-09 --timezone Asia/Shanghai --limit 100 ``` Find a run and include Langfuse bridge rows: ```bash -seal-home approval-runs search --query --limit 20 --includeBridge true +seal-home approval-runs search --corp --query --limit 20 --includeBridge true ``` Resolve Langfuse trace/session hints: ```bash -seal-home approval-runs bridge --sourceDocumentSN +seal-home approval-runs bridge --corp --sourceDocumentSN ``` Read simulation batch records: ```bash -seal-home simulation batch-records +seal-home simulation batch-records --corp ``` ## Write Operation Payloads diff --git a/.agents/skills/seal-home/references/hose-enterprise-auth.md b/.agents/skills/seal-home/references/hose-enterprise-auth.md index 8d2bf05..95e8498 100644 --- a/.agents/skills/seal-home/references/hose-enterprise-auth.md +++ b/.agents/skills/seal-home/references/hose-enterprise-auth.md @@ -9,7 +9,7 @@ Use the CLI for normal enterprise setup. Do not inspect source code or hand-edit ```bash seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' seal-home corps list -seal-home corps current +seal-home corps current --corp seal-home corps switch ``` diff --git a/.agents/skills/seal-home/references/rule-lightweight.md b/.agents/skills/seal-home/references/rule-lightweight.md index 7be030e..bd9179e 100644 --- a/.agents/skills/seal-home/references/rule-lightweight.md +++ b/.agents/skills/seal-home/references/rule-lightweight.md @@ -19,8 +19,8 @@ Expected shape: Tool-layer equivalent: ```bash -seal-home tool seal_approval_rules_list --json '{"countOnly":true}' -seal-home tool seal_approval_rules_list --json '{"fields":["id"],"limit":0}' +seal-home tool seal_approval_rules_list --corp --json '{"countOnly":true}' +seal-home tool seal_approval_rules_list --corp --json '{"fields":["id"],"limit":0}' ``` ## List Rule Summaries @@ -36,7 +36,7 @@ Default summary should include only fields such as `id`, `scope`, `strictness`, Tool-layer equivalent: ```bash -seal-home tool seal_approval_rules_list --json '{"fields":["id","scope","strictness","status","updatedAt"]}' +seal-home tool seal_approval_rules_list --corp --json '{"fields":["id","scope","strictness","status","updatedAt"]}' ``` ## Clear Draft Rules Before Import @@ -63,8 +63,8 @@ Expected shape: Tool-layer equivalent: ```bash -seal-home tool seal_approval_rules_clear --json '{"dryRun":true}' -seal-home tool seal_approval_rules_clear --json '{"dryRun":false}' +seal-home tool seal_approval_rules_clear --corp --json '{"dryRun":true}' +seal-home tool seal_approval_rules_clear --corp --json '{"dryRun":false}' ``` ## Get One Historical Rule @@ -72,14 +72,14 @@ seal-home tool seal_approval_rules_clear --json '{"dryRun":false}' Use this when a run used a historical rule version and current rules may differ. ```bash -seal-home rules get --version 16 --code '#0038' -seal-home rules get --version latest --code '#0038' +seal-home rules get --corp --version 16 --code '#0038' +seal-home rules get --corp --version latest --code '#0038' ``` If the user starts from a run and a runtime ID such as `rule-205`, resolve against that run: ```bash -seal-home rules get --record-id --runtime-id rule-205 +seal-home rules get --corp --record-id --runtime-id rule-205 ``` Return the single rule text plus `scope`, `strictness`, `status`, `versionNumber`, and version metadata. Avoid commands that dump a whole rule version unless the user asks for the full version. @@ -89,13 +89,13 @@ Return the single rule text plus `scope`, `strictness`, `status`, `versionNumber Prefer scoped and trimmed search: ```bash -seal-home tool seal_approval_search --json '{"keywords":["关键词"],"areas":["rules"],"matchMode":"any","maxResults":20,"snippetOnly":true,"maxChars":500,"fields":["id","title","snippet"]}' +seal-home tool seal_approval_search --corp --json '{"keywords":["关键词"],"areas":["rules"],"matchMode":"any","maxResults":20,"snippetOnly":true,"maxChars":500,"fields":["id","title","snippet"]}' ``` When investigating historical behavior, search the matching rule version if the API supports it: ```bash -seal-home tool seal_approval_search --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","versionNumber":16,"snippetOnly":true,"maxChars":500}' +seal-home tool seal_approval_search --corp --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","versionNumber":16,"snippetOnly":true,"maxChars":500}' ``` Use current search only when the question is about current draft/current knowledge, not why a historical run behaved a certain way. diff --git a/AGENTS.md b/AGENTS.md index 5e417fe..d907d52 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,7 @@ Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in - `bun run dev`: run `src/server.ts` with watch mode. - `bun run start`: run the MCP server once. - `bun run cli -- `: execute CLI commands, such as `bun run cli version`. -- `bun run probe`: run the local connectivity/config probe. +- `bun run probe -- `: run the local connectivity/config probe. - `bun run check`: type-check with `tsc --noEmit`. - `bun test`: run all colocated Bun tests. - `bun run openapi:bundle`: rebuild `dist/openapi.json`. diff --git a/README.md b/README.md index 4142666..36b1fe1 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Seal-native enterprise pages can be added with a Seal Bearer token. The older `d bun install cp enterprises/example.hose.json enterprises/local.json bun run check -bun run probe +bun run probe -- bun run start ``` @@ -50,7 +50,7 @@ Create a user-level Hose enterprise config that works from any directory: ```bash mkdir -p ~/.config/seal-home/enterprises seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' -seal-home auth diagnose +seal-home auth diagnose --corp seal-home tools list ``` @@ -93,11 +93,14 @@ Use the CLI from skills, shell scripts, or agents. CLI intentionally keeps the f ```bash seal-home version seal-home config paths +seal-home config get +seal-home config mode stateless +seal-home config mode stateful --corp seal-home tools list seal-home corps list -seal-home auth diagnose -seal-home approval-runs summary --date 2026-06-08 --timezone Asia/Shanghai -seal-home tool seal_approval_runs_summary --json '{"date":"2026-06-08","timezone":"Asia/Shanghai"}' +seal-home auth diagnose --corp +seal-home approval-runs summary --corp --date 2026-06-08 --timezone Asia/Shanghai +seal-home tool seal_approval_runs_summary --corp --json '{"date":"2026-06-08","timezone":"Asia/Shanghai"}' ``` CLI output is JSON on stdout. Errors are written to stderr. @@ -108,7 +111,14 @@ Enterprise config lookup: - Otherwise `./enterprises` and `~/.config/seal-home/enterprises` are merged. - User-level configs override same-ID configs from `./enterprises`. -Use `seal-home auth diagnose [--corp ]` when login fails. 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. +Global enterprise selection is stateless by default. Its configuration is stored in +`~/.config/seal-home/config.json` (override with `SEAL_HOME_CONFIG_FILE`). In stateless mode, +every command that accesses an enterprise must receive `--corp `; no `current-corp` file +or first-config fallback is used. Run `seal-home config mode stateful --corp ` to enable +a default enterprise, then `seal-home corps switch ` to change it. Run +`seal-home config mode stateless` to require explicit enterprise selection again. + +Use `seal-home 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 @@ -222,11 +232,11 @@ These tools remain available to the CLI: - `seal_simulation_batch_records_get`: read records from one simulation batch via `api/v1/simulation/batch/{batchId}/records`. - `seal_approval_run_langfuse_bridge_get`: resolve approval run records to Langfuse lookup hints. It prefers `sourceExtendData._langfuseTraceId`; if that is missing, it returns `hosecloud-{sourceDocumentSN}` as the session fallback. -For rule list commands, prefer `seal-home rules count` or `seal-home rules list --summary` before requesting full rule descriptions. `seal-home rules list` protects large outputs and asks for `--summary`, `--count`, or explicit `--full` when the response would be too large. +For rule list commands, prefer `seal-home rules count --corp ` or `seal-home rules list --corp --summary` before requesting full rule descriptions. `seal-home rules list` protects large outputs and asks for `--summary`, `--count`, or explicit `--full` when the response would be too large. For test tenants that need a clean slate before importing another rule set, use `seal-home rules clear --corp --dry-run` first, then `seal-home rules clear --corp --yes` to delete the current draft rules and verify the remaining count. -For approval run detail commands, prefer `seal-home approval-runs pick --sn <单号> --latest`, `seal-home approval-runs get --summary`, `seal-home approval-runs document-summary `, `seal-home approval-runs cited-rules `, `seal-home approval-runs attachments --summary`, or `seal-home approval-runs result --summary` before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-home auth hose-link --corp --expire 7200`, which returns the unredacted `getProvisionalAuth` URL. +For approval run detail commands, prefer the same commands with explicit `--corp `—for example `seal-home approval-runs pick --corp --sn <单号> --latest` or `seal-home approval-runs get --corp --summary`—before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-home auth hose-link --corp --expire 7200`, which returns the unredacted `getProvisionalAuth` URL. ## Approval Run To Langfuse Bridge @@ -253,6 +263,6 @@ When `_langfuseTraceId` exists, downstream tools should fetch the trace directly - Keep CLI entry points thin. Shared behavior belongs in `src/core` and `src/domains`; `src/cli.ts` should only handle command parsing, process lifecycle, and JSON output. - Do not print diagnostic text to stdout from the MCP server. MCP uses stdout as the protocol stream; use stderr for server diagnostics. - Keep any MCP exported surface narrow. High-frequency read tools can be direct MCP tools; low-frequency maintenance should go through `seal_action` or CLI commands. -- Prefer CLI or script processing for large tool responses. For daily approval questions, call `seal-home approval-runs summary ...` instead of reading long `seal_approval_runs_search` output manually. +- Prefer CLI or script processing for large tool responses. For daily approval questions, call `seal-home approval-runs summary --corp ...` instead of reading long `seal_approval_runs_search` output manually. - Keep broad search tools compact by default. Add explicit opt-in flags such as `includeBridge` for verbose fields that are useful only in deeper debugging. - When Seal API timestamp filters are uncertain, filter again in tool code by `createdAt` and explicit timezone before presenting date-based answers. diff --git a/dist/openapi.json b/dist/openapi.json index eac97d4..9cdda8d 100644 --- a/dist/openapi.json +++ b/dist/openapi.json @@ -76,7 +76,8 @@ "type": "string", "enum": [ "hose", - "direct" + "direct", + "seal" ] }, "current": { @@ -98,6 +99,7 @@ ], "operationId": "getCurrentCorp", "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.", @@ -122,7 +124,8 @@ "type": "string", "enum": [ "hose", - "direct" + "direct", + "seal" ] }, "current": { @@ -228,7 +231,7 @@ "schema": { "type": "string" }, - "description": "Optional local enterprise config ID. Defaults to the current selected enterprise." + "description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used." } ], "responses": { @@ -284,7 +287,7 @@ "schema": { "type": "string" }, - "description": "Optional local enterprise config ID. Defaults to the current selected enterprise." + "description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used." } ], "responses": { @@ -326,7 +329,7 @@ "schema": { "type": "string" }, - "description": "Optional local enterprise config ID. Defaults to the current selected enterprise." + "description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used." } ], "responses": { @@ -392,7 +395,7 @@ "schema": { "type": "string" }, - "description": "Optional local enterprise config ID. Defaults to the current selected enterprise." + "description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used." } ], "responses": { @@ -460,7 +463,7 @@ "schema": { "type": "string" }, - "description": "Optional local enterprise config ID. Defaults to the current selected enterprise." + "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", @@ -914,7 +917,7 @@ "schema": { "type": "string" }, - "description": "Optional local enterprise config ID. Defaults to the current selected enterprise." + "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", @@ -1522,7 +1525,7 @@ "schema": { "type": "string" }, - "description": "Optional local enterprise config ID. Defaults to the current selected enterprise." + "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", @@ -1683,7 +1686,7 @@ "schema": { "type": "string" }, - "description": "Optional local enterprise config ID. Defaults to the current selected enterprise." + "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", @@ -1779,7 +1782,7 @@ "schema": { "type": "string" }, - "description": "Optional local enterprise config ID. Defaults to the current selected enterprise." + "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", @@ -1865,7 +1868,7 @@ "schema": { "type": "string" }, - "description": "Optional local enterprise config ID. Defaults to the current selected enterprise." + "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", @@ -1943,7 +1946,7 @@ "schema": { "type": "string" }, - "description": "Optional local enterprise config ID. Defaults to the current selected enterprise." + "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", @@ -2259,7 +2262,7 @@ "schema": { "type": "string" }, - "description": "Optional local enterprise config ID. Defaults to the current selected enterprise." + "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", @@ -2435,7 +2438,8 @@ "type": "string", "enum": [ "hose", - "direct" + "direct", + "seal" ] }, "current": { diff --git a/openapi/components/parameters.yaml b/openapi/components/parameters.yaml index be339ae..51f8122 100644 --- a/openapi/components/parameters.yaml +++ b/openapi/components/parameters.yaml @@ -3,7 +3,7 @@ CorpId: in: query schema: type: string - description: Optional local enterprise config ID. Defaults to the current selected enterprise. + 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 diff --git a/openapi/components/schemas/index.yaml b/openapi/components/schemas/index.yaml index 3b602a3..c967fbb 100644 --- a/openapi/components/schemas/index.yaml +++ b/openapi/components/schemas/index.yaml @@ -18,7 +18,7 @@ CorpSummary: type: string sourceType: type: string - enum: [hose, direct] + enum: [hose, direct, seal] current: type: boolean SwitchCorpRequest: diff --git a/openapi/paths/corps.yaml b/openapi/paths/corps.yaml index 1435680..ea86a3a 100644 --- a/openapi/paths/corps.yaml +++ b/openapi/paths/corps.yaml @@ -18,6 +18,7 @@ paths: tags: [Corps] operationId: getCurrentCorp 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. diff --git a/src/cli.test.ts b/src/cli.test.ts index 4e5448a..46d7e45 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -1,16 +1,26 @@ -import { describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, test } from "bun:test"; import { spawnSync } from "node:child_process"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { VERSION } from "./version.js"; const CLI_PATH = join(import.meta.dirname, "cli.ts"); +const tempDirs: string[] = []; -function runCli(args: string[]) { +function runCli(args: string[], env: Record = {}) { return spawnSync("bun", [CLI_PATH, ...args], { - encoding: "utf-8" + encoding: "utf-8", + env: { ...process.env, ...env } }); } +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + describe("CLI version & help handling", () => { test.each([ ["version"], @@ -46,4 +56,77 @@ describe("CLI version & help handling", () => { expect(result.status).toBe(1); expect(result.stderr).toContain("Unknown command: invalid-command. Run 'seal-home help' for available commands."); }); + + test("requires --corp in the default stateless mode", () => { + const env = makeConfigEnv(); + const result = runCli(["corps", "current"], env); + + expect(result.status).toBe(1); + expect(result.stderr).toContain("Stateless mode is enabled"); + expect(result.stderr).toContain("--corp "); + }); + + test("allows an explicit corp in stateless mode", () => { + const env = makeConfigEnv(); + const result = runCli(["corps", "current", "--corp", "corp-a"], env); + + expect(result.status).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ id: "corp-a" }); + }); + + test("keeps the fine-grained tool command reachable in stateless mode", () => { + const env = makeConfigEnv(); + const result = runCli(["tool", "unknown-tool", "--corp", "corp-a"], env); + + expect(result.status).toBe(1); + expect(result.stderr).toContain("Unknown Seal tool: unknown-tool"); + }); + + test("can enable stateful mode and select a default corp", () => { + const env = makeConfigEnv(); + const mode = runCli(["config", "mode", "stateful", "--corp", "corp-a"], env); + const current = runCli(["corps", "current"], env); + + expect(mode.status).toBe(0); + expect(JSON.parse(mode.stdout)).toMatchObject({ + mode: "stateful", + defaultCorpId: "corp-a" + }); + expect(current.status).toBe(0); + expect(JSON.parse(current.stdout)).toMatchObject({ id: "corp-a" }); + }); + + test("removes the default when switching back to stateless mode", () => { + const env = makeConfigEnv(); + runCli(["config", "mode", "stateful", "--corp", "corp-a"], env); + + const mode = runCli(["config", "mode", "stateless"], env); + const current = runCli(["corps", "current"], env); + + expect(mode.status).toBe(0); + expect(JSON.parse(mode.stdout)).toMatchObject({ mode: "stateless" }); + expect(JSON.parse(mode.stdout)).not.toHaveProperty("defaultCorpId"); + expect(current.status).toBe(1); + expect(current.stderr).toContain("Stateless mode is enabled"); + }); }); + +function makeConfigEnv(): Record { + const root = mkdtempSync(join(tmpdir(), "seal-home-cli-")); + tempDirs.push(root); + const enterprises = join(root, "enterprises"); + mkdirSync(enterprises, { recursive: true }); + writeFileSync(join(enterprises, "corp-a.json"), JSON.stringify({ + id: "corp-a", + name: "Corp A", + source: { + type: "direct", + token: "seal-token", + sealUrl: "https://corp-a.seal.test" + } + })); + return { + SEAL_HOME_ENTERPRISES_DIR: enterprises, + SEAL_HOME_CONFIG_FILE: join(root, "config.json") + }; +} diff --git a/src/cli.ts b/src/cli.ts index b1d3a5b..54687c9 100755 --- a/src/cli.ts +++ b/src/cli.ts @@ -1,11 +1,19 @@ #!/usr/bin/env bun import { spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { getEnterprisesDirCandidates, loadCorpConfigs, resolveWritableEnterprisesDir } from "./core/config/loader.js"; +import { + getEnterprisesDirCandidates, + loadCorpConfigs, + loadGlobalConfig, + resolveGlobalConfigFile, + resolveWritableEnterprisesDir, + saveGlobalConfig +} from "./core/config/loader.js"; +import { resolveCorpConfig } from "./core/config/manager.js"; import { createSealClient } from "./core/http/factory.js"; import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js"; import { getMe } from "./domains/seal/api.js"; @@ -19,11 +27,31 @@ import { runServiceCommand, serviceStatus } from "./cli/service.js"; const APP_ROOT = dirname(dirname(fileURLToPath(import.meta.url))); const STATE_DIR = join(homedir(), ".config", "seal-home"); -const CURRENT_CORP_FILE = join(STATE_DIR, "current-corp"); const RULE_LIST_FULL_COUNT_LIMIT = 100; const RULE_LIST_FULL_BYTES_LIMIT = 120_000; const RULE_SUMMARY_FIELDS = ["id", "status", "strictness", "scope", "createdAt", "updatedAt"]; const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000; +const KNOWN_AREAS = new Set([ + "config", + "service", + "update", + "tools", + "corps", + "tool", + "source", + "auth", + "delegation", + "users", + "llm", + "permissions", + "billing", + "webhook", + "webhooks", + "context", + "rules", + "approval-runs", + "simulation" +]); type ParsedArgs = { command: string[]; @@ -59,13 +87,50 @@ async function main() { return; } + if (!KNOWN_AREAS.has(area)) { + throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-home help' for available commands.`); + } + if (area === "config" && action === "paths") { printJson({ - candidates: getEnterprisesDirCandidates() + candidates: getEnterprisesDirCandidates(), + globalConfigFile: resolveGlobalConfigFile() }); return; } + if (area === "config" && (action === "get" || action === "status")) { + printJson(globalConfigSummary()); + return; + } + + if (area === "config" && action === "mode") { + const mode = maybeName ?? stringOption(args.options.mode); + if (!mode) { + printJson(globalConfigSummary()); + return; + } + + const stateful = parseStateMode(mode); + const requestedCorpId = stringOption(args.options.corp); + const previousConfig = loadGlobalConfig(); + const defaultCorpId = stateful + ? requestedCorpId + ? resolveCorpConfig( + loadCorpConfigs(), + { stateful: true, corpId: requestedCorpId }, + getEnterprisesDirCandidates() + ).id + : previousConfig.defaultCorpId + : undefined; + const config = saveGlobalConfig({ + stateful, + ...(defaultCorpId ? { defaultCorpId } : {}) + }); + printJson(globalConfigSummary(config)); + return; + } + if (area === "service") { await runServiceCommand(action, { appRoot: APP_ROOT, entryFile: fileURLToPath(import.meta.url), stateDir: STATE_DIR, version: VERSION }); return; @@ -84,7 +149,12 @@ async function main() { if (area === "corps" && action === "list") { const corpId = stringOption(args.options.corp); const corps = loadCorpConfigs(); - const currentCorpId = corpId ?? readCurrentCorpId() ?? corps[0]?.id; + const globalConfig = loadGlobalConfig(); + const currentCorpId = corpId ?? ( + globalConfig.stateful + ? globalConfig.defaultCorpId ?? corps[0]?.id + : undefined + ); printJson(corps.map((item) => ({ id: item.id, name: item.name, @@ -96,7 +166,7 @@ async function main() { } if (area === "corps" && action === "current") { - const corp = selectCorp(""); + const corp = selectCorp(stringOption(args.options.corp)); printJson({ id: corp.id, name: corp.name, @@ -109,9 +179,15 @@ async function main() { if (area === "corps" && action === "switch") { const corpId = maybeName; if (!corpId) throw new Error("Usage: seal-home corps switch "); + const globalConfig = loadGlobalConfig(); + if (!globalConfig.stateful) { + throw new Error( + "Cannot switch the default enterprise while stateless mode is enabled. " + + "Use `seal-home config mode stateful` first." + ); + } const corp = selectCorp(corpId); - ensureStateDir(); - writeFileSync(CURRENT_CORP_FILE, `${corp.id}\n`, { mode: 0o600 }); + saveGlobalConfig({ ...globalConfig, stateful: true, defaultCorpId: corp.id }); printJson({ current: true, id: corp.id, @@ -130,7 +206,7 @@ async function main() { return; } - const corp = selectCorp(String(args.options.corp ?? "")); + const corp = selectCorp(stringOption(args.options.corp)); if (area === "source" && action === "config") { printJson(await resolveLiveSealEnterpriseConfig(corp)); @@ -666,28 +742,36 @@ function outputOptions(options: Record): OutputOptions }; } -function selectCorp(corpId: string): CorpConfig { +function selectCorp(corpId?: string): CorpConfig { const corps = loadCorpConfigs(); - const selectedCorpId = corpId || readCurrentCorpId() || ""; - const corp = selectedCorpId - ? corps.find((item) => item.id === selectedCorpId) - : corps[0]; - - if (!corp) { - throw new Error( - selectedCorpId - ? `No enterprise config found for ${selectedCorpId}` - : `No enterprise config found. Add a non-example JSON file under one of: ${getEnterprisesDirCandidates().join(", ")}` - ); - } - - return corp; + const globalConfig = loadGlobalConfig(); + return resolveCorpConfig( + corps, + { + stateful: globalConfig.stateful, + defaultCorpId: globalConfig.defaultCorpId, + corpId + }, + getEnterprisesDirCandidates() + ); } -function readCurrentCorpId(): string | undefined { - if (!existsSync(CURRENT_CORP_FILE)) return undefined; - const value = readFileSync(CURRENT_CORP_FILE, "utf-8").trim(); - return value || undefined; +function globalConfigSummary(config = loadGlobalConfig()) { + return { + mode: config.stateful ? "stateful" : "stateless", + stateful: config.stateful, + ...(config.stateful && config.defaultCorpId + ? { defaultCorpId: config.defaultCorpId } + : {}), + configFile: resolveGlobalConfigFile() + }; +} + +function parseStateMode(value: string): boolean { + const normalized = value.trim().toLowerCase(); + if (["stateful", "state", "有状态"].includes(normalized)) return true; + if (["stateless", "无状态"].includes(normalized)) return false; + throw new Error("Invalid config mode. Use stateful or stateless."); } async function addHoseCorp(input: Record) { @@ -1321,10 +1405,6 @@ function booleanOption(value: string | boolean | undefined): boolean | undefined throw new Error(`Invalid boolean: ${value}`); } -function ensureStateDir() { - mkdirSync(STATE_DIR, { recursive: true }); -} - function printJson(value: unknown, options: OutputOptions = {}) { protectLargeOutput(value, options); const json = `${JSON.stringify(value, null, 2)}\n`; @@ -1342,11 +1422,13 @@ function printHelp() { Usage: seal-home version seal-home config paths + seal-home config get + seal-home config mode [--corp ] seal-home service seal-home update seal-home tools list seal-home corps list [--corp ] - seal-home corps current + seal-home corps current [--corp ] seal-home corps switch seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' seal-home corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}' @@ -1380,23 +1462,23 @@ Usage: seal-home rules clear [--corp ] [--dry-run|--yes] seal-home rules versions [--corp ] seal-home rules version [--corp ] - seal-home rules get --version --code '#0038' - seal-home rules get --record-id --runtime-id rule-205 - seal-home rules search [--version ] [--maxResults 20] - seal-home context [--ruleVersion ] [--documentLimit 50] - seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] - seal-home approval-runs search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] - seal-home approval-runs pick --sn [--batch ] [--latest] [--fields recordId,status,aiDecision] - seal-home approval-runs get [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] - seal-home approval-runs cited-rules - seal-home approval-runs document-summary - seal-home approval-runs attachments [--summary] - seal-home approval-runs result [--summary] - seal-home approval-runs url - seal-home approval-runs url - seal-home approval-runs url --sourceDocumentSN B26022501 - seal-home approval-runs bridge [--sourceDocumentSN B26001887] - seal-home simulation batch-records + seal-home rules get --corp --version --code '#0038' + seal-home rules get --corp --record-id --runtime-id rule-205 + seal-home rules search [--version ] [--maxResults 20] [--corp ] + seal-home context [--ruleVersion ] [--documentLimit 50] [--corp ] + seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] [--corp ] + seal-home approval-runs search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp ] + seal-home approval-runs pick --sn [--batch ] [--latest] [--fields recordId,status,aiDecision] [--corp ] + seal-home approval-runs get [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp ] + seal-home approval-runs cited-rules [--corp ] + seal-home approval-runs document-summary [--corp ] + seal-home approval-runs attachments [--summary] [--corp ] + seal-home approval-runs result [--summary] [--corp ] + seal-home approval-runs url [--corp ] + seal-home approval-runs url [--corp ] + seal-home approval-runs url --sourceDocumentSN B26022501 [--corp ] + seal-home approval-runs bridge [--sourceDocumentSN B26001887] [--corp ] + seal-home simulation batch-records [--corp ] `); } diff --git a/src/core/config/loader.test.ts b/src/core/config/loader.test.ts index b6c841b..cb4efe0 100644 --- a/src/core/config/loader.test.ts +++ b/src/core/config/loader.test.ts @@ -2,10 +2,17 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { loadCorpConfigs, resolveEnterprisesDir } from "./loader.js"; +import { + loadCorpConfigs, + loadGlobalConfig, + resolveEnterprisesDir, + resolveGlobalConfigFile, + saveGlobalConfig +} from "./loader.js"; const ORIGINAL_ENV = process.env.SEAL_HOME_ENTERPRISES_DIR; const ORIGINAL_USER_DIR_ENV = process.env.SEAL_HOME_USER_ENTERPRISES_DIR; +const ORIGINAL_CONFIG_FILE_ENV = process.env.SEAL_HOME_CONFIG_FILE; const ORIGINAL_CWD = process.cwd(); const tempDirs: string[] = []; @@ -21,6 +28,11 @@ afterEach(() => { } else { process.env.SEAL_HOME_USER_ENTERPRISES_DIR = ORIGINAL_USER_DIR_ENV; } + if (ORIGINAL_CONFIG_FILE_ENV === undefined) { + delete process.env.SEAL_HOME_CONFIG_FILE; + } else { + process.env.SEAL_HOME_CONFIG_FILE = ORIGINAL_CONFIG_FILE_ENV; + } for (const dir of tempDirs.splice(0)) { rmSync(dir, { recursive: true, force: true }); @@ -69,6 +81,24 @@ describe("loadCorpConfigs", () => { ["user-only", "User Only"] ]); }); + + test("defaults global config to stateless", () => { + process.env.SEAL_HOME_CONFIG_FILE = join(makeTempDir(), "config.json"); + + expect(loadGlobalConfig()).toEqual({ stateful: false }); + }); + + test("saves and loads the global state mode", () => { + const file = join(makeTempDir(), "nested", "config.json"); + process.env.SEAL_HOME_CONFIG_FILE = file; + + expect(saveGlobalConfig({ stateful: true, defaultCorpId: "corp-a" })).toEqual({ + stateful: true, + defaultCorpId: "corp-a" + }); + expect(resolveGlobalConfigFile()).toBe(file); + expect(loadGlobalConfig()).toEqual({ stateful: true, defaultCorpId: "corp-a" }); + }); }); function makeTempDir(): string { diff --git a/src/core/config/loader.ts b/src/core/config/loader.ts index 8565f8d..ef8e71f 100644 --- a/src/core/config/loader.ts +++ b/src/core/config/loader.ts @@ -1,11 +1,13 @@ -import { existsSync, readFileSync, readdirSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; -import { join } from "node:path"; -import { CorpConfig, CorpConfigSchema } from "./types.js"; +import { dirname, join } from "node:path"; +import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js"; const ENTERPRISES_DIR = "enterprises"; const CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR"; const USER_DIR_ENV = "SEAL_HOME_USER_ENTERPRISES_DIR"; +const GLOBAL_CONFIG_ENV = "SEAL_HOME_CONFIG_FILE"; +const GLOBAL_CONFIG_FILE = join(homedir(), ".config", "seal-home", "config.json"); export const USER_ENTERPRISES_DIR = join(homedir(), ".config", "seal-home", "enterprises"); export function loadCorpConfigs(): CorpConfig[] { @@ -56,3 +58,24 @@ export function getEnterprisesDirCandidates(): string[] { USER_ENTERPRISES_DIR ]; } + +export function resolveGlobalConfigFile(): string { + return process.env[GLOBAL_CONFIG_ENV]?.trim() || GLOBAL_CONFIG_FILE; +} + +export function loadGlobalConfig(): GlobalConfig { + const file = resolveGlobalConfigFile(); + if (!existsSync(file)) { + return GlobalConfigSchema.parse({}); + } + + return GlobalConfigSchema.parse(JSON.parse(readFileSync(file, "utf-8"))); +} + +export function saveGlobalConfig(config: GlobalConfig): GlobalConfig { + const normalized = GlobalConfigSchema.parse(config); + const file = resolveGlobalConfigFile(); + mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); + writeFileSync(file, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 }); + return normalized; +} diff --git a/src/core/config/manager.test.ts b/src/core/config/manager.test.ts index 0ca0fa4..f55126c 100644 --- a/src/core/config/manager.test.ts +++ b/src/core/config/manager.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; import { CorpConfig } from "./types.js"; -import { CorpContext } from "./manager.js"; +import { CorpContext, resolveCorpConfig } from "./manager.js"; function corp(id: string, name = id): CorpConfig { return { @@ -26,7 +26,7 @@ function corp(id: string, name = id): CorpConfig { describe("CorpContext", () => { test("refresh adds newly loaded corps", () => { - const context = new CorpContext([corp("corp-a")]); + const context = new CorpContext([corp("corp-a")], { stateful: true }); context.refresh([corp("corp-a"), corp("corp-b")]); @@ -34,7 +34,7 @@ describe("CorpContext", () => { }); test("refresh keeps the selected corp when it still exists", () => { - const context = new CorpContext([corp("corp-a"), corp("corp-b")]); + const context = new CorpContext([corp("corp-a"), corp("corp-b")], { stateful: true }); expect(context.switchCorp("corp-b")).toBe(true); context.refresh([corp("corp-a"), corp("corp-b", "Corp B updated")]); @@ -43,12 +43,51 @@ describe("CorpContext", () => { expect(context.getCurrent()?.name).toBe("Corp B updated"); }); - test("refresh falls back when the selected corp disappears", () => { - const context = new CorpContext([corp("corp-a"), corp("corp-b")]); + test("clears the default when the selected corp disappears", () => { + const context = new CorpContext([corp("corp-a"), corp("corp-b")], { stateful: true }); expect(context.switchCorp("corp-b")).toBe(true); context.refresh([corp("corp-c")]); - expect(context.getCurrent()?.id).toBe("corp-c"); + expect(context.getCurrent()).toBeNull(); + }); + + test("does not keep a current corp in stateless mode", () => { + const context = new CorpContext([corp("corp-a"), corp("corp-b")]); + + expect(context.getCurrent()).toBeNull(); + expect(context.switchCorp("corp-b")).toBe(false); + expect(context.resolve("corp-b")?.id).toBe("corp-b"); + }); + + test("uses the configured default corp in stateful mode", () => { + const context = new CorpContext( + [corp("corp-a"), corp("corp-b")], + { stateful: true, defaultCorpId: "corp-b" } + ); + + expect(context.getCurrent()?.id).toBe("corp-b"); + }); +}); + +describe("resolveCorpConfig", () => { + test("requires an explicit corp in stateless mode", () => { + expect(() => resolveCorpConfig([corp("corp-a")], { stateful: false })).toThrow( + "Every enterprise command requires --corp " + ); + }); + + test("resolves an explicit corp in stateless mode", () => { + expect(resolveCorpConfig( + [corp("corp-a"), corp("corp-b")], + { stateful: false, corpId: "corp-b" } + ).id).toBe("corp-b"); + }); + + test("resolves the configured default corp in stateful mode", () => { + expect(resolveCorpConfig( + [corp("corp-a"), corp("corp-b")], + { stateful: true, defaultCorpId: "corp-b" } + ).id).toBe("corp-b"); }); }); diff --git a/src/core/config/manager.ts b/src/core/config/manager.ts index c49300c..8b631a3 100644 --- a/src/core/config/manager.ts +++ b/src/core/config/manager.ts @@ -1,19 +1,62 @@ -import { CorpConfig } from "./types.js"; +import { CorpConfig, GlobalConfig } from "./types.js"; + +export function resolveCorpConfig( + corps: CorpConfig[], + options: Pick & { corpId?: string }, + candidates: string[] = [] +): CorpConfig { + const requestedCorpId = options.corpId?.trim() || undefined; + const configuredCorpId = options.stateful + ? options.defaultCorpId?.trim() || undefined + : undefined; + const selectedCorpId = requestedCorpId ?? configuredCorpId; + + if (selectedCorpId) { + const corp = corps.find((item) => item.id === selectedCorpId); + if (corp) return corp; + throw new Error(`No enterprise config found for ${selectedCorpId}`); + } + + if (!options.stateful) { + throw new Error( + "Stateless mode is enabled. Every enterprise command requires --corp . " + + "Use `seal-home config mode stateful` to enable a default enterprise." + ); + } + + const firstCorp = corps[0]; + if (firstCorp) return firstCorp; + + throw new Error( + "No enterprise config found. Add a non-example JSON file under one of: " + + (candidates.length ? candidates.join(", ") : "the configured enterprise directories") + ); +} + +export type CorpContextOptions = Pick; export class CorpContext { private current: CorpConfig | null = null; private corps = new Map(); + private stateful = false; + private defaultCorpId: string | undefined; - constructor(corps: CorpConfig[]) { + constructor(corps: CorpConfig[], options: CorpContextOptions = { stateful: false }) { + this.stateful = options.stateful; + this.defaultCorpId = options.defaultCorpId; this.replaceCorps(corps); - this.current = corps[0] ?? null; + this.selectCurrent(corps[0]); } - refresh(corps: CorpConfig[]): void { - const currentId = this.current?.id ?? null; + refresh(corps: CorpConfig[], options: CorpContextOptions = { + stateful: this.stateful, + defaultCorpId: this.defaultCorpId + }): void { + const currentId = this.current?.id; + this.stateful = options.stateful; + this.defaultCorpId = options.defaultCorpId; this.replaceCorps(corps); - this.current = currentId ? this.corps.get(currentId) ?? null : null; - this.current ??= corps[0] ?? null; + this.selectCurrent(currentId ? this.corps.get(currentId) ?? corps[0] : corps[0]); } private replaceCorps(corps: CorpConfig[]): void { @@ -27,10 +70,21 @@ export class CorpContext { return this.current; } + getCorp(corpId: string): CorpConfig | null { + return this.corps.get(corpId) ?? null; + } + + resolve(corpId?: string): CorpConfig | null { + if (corpId) return this.getCorp(corpId); + return this.current; + } + switchCorp(corpId: string): boolean { + if (!this.stateful) return false; const corp = this.corps.get(corpId); if (!corp) return false; this.current = corp; + this.defaultCorpId = corp.id; return true; } @@ -42,4 +96,15 @@ export class CorpContext { current: corp.id === this.current?.id })); } + + private selectCurrent(fallback?: CorpConfig): void { + if (!this.stateful) { + this.current = null; + return; + } + + this.current = this.defaultCorpId !== undefined + ? this.corps.get(this.defaultCorpId) ?? null + : fallback ?? null; + } } diff --git a/src/core/config/types.test.ts b/src/core/config/types.test.ts index e75f05b..8430d8e 100644 --- a/src/core/config/types.test.ts +++ b/src/core/config/types.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { CorpConfigSchema } from "./types.js"; +import { CorpConfigSchema, GlobalConfigSchema } from "./types.js"; describe("CorpConfigSchema", () => { test("accepts Hose key/password aliases", () => { @@ -79,3 +79,19 @@ describe("CorpConfigSchema", () => { expect(config.source.tenantSlug).toBe("xiezihao"); }); }); + +describe("GlobalConfigSchema", () => { + test("defaults to stateless mode", () => { + expect(GlobalConfigSchema.parse({})).toEqual({ stateful: false }); + }); + + test("accepts a stateful default enterprise", () => { + expect(GlobalConfigSchema.parse({ + stateful: true, + defaultCorpId: "corp-a" + })).toEqual({ + stateful: true, + defaultCorpId: "corp-a" + }); + }); +}); diff --git a/src/core/config/types.ts b/src/core/config/types.ts index 72266b2..30ccdc5 100644 --- a/src/core/config/types.ts +++ b/src/core/config/types.ts @@ -84,9 +84,15 @@ export const CorpConfigSchema = z.object({ auth: CorpAuthConfigSchema }); +export const GlobalConfigSchema = z.object({ + stateful: z.boolean().default(false), + defaultCorpId: z.string().min(1).optional() +}); + export type HoseSealSource = z.infer; export type DirectSealSource = z.infer; export type NativeSealSource = z.infer; export type SealSource = z.infer; export type CorpAuthConfig = z.infer; export type CorpConfig = z.infer; +export type GlobalConfig = z.infer; diff --git a/src/probe.ts b/src/probe.ts index 8bf9be7..3fd3c35 100644 --- a/src/probe.ts +++ b/src/probe.ts @@ -1,22 +1,23 @@ -import { getEnterprisesDirCandidates, loadCorpConfigs } from "./core/config/loader.js"; +import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from "./core/config/loader.js"; +import { resolveCorpConfig } from "./core/config/manager.js"; import { createSealClient } from "./core/http/factory.js"; import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js"; import { getApprovalContext } from "./domains/seal/api.js"; async function main() { - const corpId = Bun.argv[2]; + const args = Bun.argv.slice(2); + const corpId = args[0] === "--corp" ? args[1] : args[0]; const corps = loadCorpConfigs(); - const corp = corpId - ? corps.find((item) => item.id === corpId) - : corps[0]; - - if (!corp) { - throw new Error( + const globalConfig = loadGlobalConfig(); + const corp = resolveCorpConfig( + corps, + { + stateful: globalConfig.stateful, + defaultCorpId: globalConfig.defaultCorpId, corpId - ? `No enterprise config found for ${corpId}` - : `No enterprise config found. Add a config file under one of: ${getEnterprisesDirCandidates().join(", ")}` - ); - } + }, + getEnterprisesDirCandidates() + ); console.log(`[probe] corp=${corp.id} source=${corp.source.type}`); diff --git a/src/server.ts b/src/server.ts index c01a9e9..6fa24f2 100644 --- a/src/server.ts +++ b/src/server.ts @@ -5,7 +5,12 @@ import { ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; -import { getEnterprisesDirCandidates, loadCorpConfigs } from "./core/config/loader.js"; +import { + getEnterprisesDirCandidates, + loadCorpConfigs, + loadGlobalConfig, + saveGlobalConfig +} from "./core/config/loader.js"; import { CorpContext } from "./core/config/manager.js"; import { createSealClient } from "./core/http/factory.js"; import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js"; @@ -14,7 +19,7 @@ import { VERSION } from "./version.js"; async function main() { const corps = loadCorpConfigs(); - const corpContext = new CorpContext(corps); + const corpContext = new CorpContext(corps, loadGlobalConfig()); const server = new Server( { @@ -52,14 +57,15 @@ async function main() { ...sealMcpTools.map((tool) => ({ name: tool.name, description: tool.description, - inputSchema: z.toJSONSchema(tool.parameters) + inputSchema: mcpInputSchema(tool.parameters, loadGlobalConfig().stateful) })) ] })); server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; - corpContext.refresh(loadCorpConfigs()); + const globalConfig = loadGlobalConfig(); + corpContext.refresh(loadCorpConfigs(), globalConfig); if (name === "seal_corps_list") { return textResult(corpContext.listCorps()); @@ -67,19 +73,33 @@ async function main() { if (name === "seal_corp_switch") { const { corpId } = args as { corpId: string }; + if (!globalConfig.stateful) { + return textResult({ + success: false, + message: "Cannot switch the default enterprise while stateless mode is enabled. " + + "Set config mode to stateful first." + }, true); + } const success = corpContext.switchCorp(corpId); + if (success) { + saveGlobalConfig({ ...globalConfig, stateful: true, defaultCorpId: corpId }); + } return textResult( success ? { success: true, current: corpId } : { success: false, message: `Unknown corp: ${corpId}` }, !success ); } - const currentCorp = corpContext.getCurrent(); + const requestedCorpId = getCorpId(args); + const currentCorp = corpContext.resolve(requestedCorpId); if (!currentCorp) { return textResult( { - error: - "No enterprise config loaded. Add a non-example JSON file to an enterprises config directory.", + error: requestedCorpId + ? `No enterprise config found for ${requestedCorpId}` + : globalConfig.stateful + ? "No enterprise config loaded. Add a non-example JSON file to an enterprises config directory." + : "Stateless mode is enabled. Every enterprise tool call requires corpId.", candidates: getEnterprisesDirCandidates() }, true @@ -123,6 +143,34 @@ function textResult(value: unknown, isError = false) { }; } +function getCorpId(args: unknown): string | undefined { + if (!args || typeof args !== "object" || Array.isArray(args)) return undefined; + const value = (args as Record).corpId; + return typeof value === "string" && value.trim() ? value.trim() : undefined; +} + +function mcpInputSchema(parameters: z.ZodType, stateful: boolean) { + const schema = z.toJSONSchema(parameters) as { + type?: string; + properties?: Record; + required?: string[]; + }; + schema.type = "object"; + schema.properties = { + ...(schema.properties ?? {}), + corpId: { + type: "string", + description: stateful + ? "可选:企业配置 ID;省略时使用当前默认企业" + : "必填:企业配置 ID" + } + }; + if (!stateful) { + schema.required = [...(schema.required ?? []), "corpId"]; + } + return schema; +} + main().catch((error) => { console.error(error); process.exit(1);