Add stateful and stateless enterprise selection
This commit is contained in:
1 parent
d383b3aad8
commit
0959cef1cc
22 files changed
+609
-187
No files matched your search
@@ -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 <corpId>`. 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 <corpId> --note '<enterprise>'`; 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 <corpId> --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 <tokenId>`.
|
||||
- User & Contacts Management (用户搜索、激活与一键代生成授权): `seal-home users search [keyword]`, `users delegation <userIdOrPhone>` (仅适用于 Seal 本地创建的账号 `provider: local`;对合思同步账号系统拒绝重置密码,需改用 `auth hose-link`), `users activate <userId>`, `users create --name ... --phone ...`, `reset-password <userId>`, `get <userId>`, `delete <userId>`.
|
||||
- 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 <corpId>`, `create [--note ...] --corp <corpId>`, `revoke <tokenId> --corp <corpId>`.
|
||||
- User & Contacts Management (用户搜索、激活与一键代生成授权): `seal-home users search [keyword] --corp <corpId>`, `users delegation <userIdOrPhone> --corp <corpId>` (仅适用于 Seal 本地创建的账号 `provider: local`;对合思同步账号系统拒绝重置密码,需改用 `auth hose-link`), `users activate <userId> --corp <corpId>`, `users create --name ... --phone ... --corp <corpId>`, `reset-password <userId> --corp <corpId>`, `get <userId> --corp <corpId>`, `delete <userId> --corp <corpId>`.
|
||||
- LLM Model Config & Providers: `seal-home llm config --corp <corpId>`, `seal-home llm providers --corp <corpId>`.
|
||||
- System Permissions Config: `seal-home permissions available --corp <corpId>`, `seal-home permissions configs --corp <corpId>`.
|
||||
- Billing & Feature Quotas: `seal-home billing status --corp <corpId>`, `seal-home billing plans --corp <corpId>`, `seal-home billing features --corp <corpId>`.
|
||||
- Full CLI inventory: read `references/cli.md`.
|
||||
|
||||
## High-Value Commands
|
||||
|
||||
```bash
|
||||
seal-home approval-runs pick --sn <sourceDocumentSN> --latest
|
||||
seal-home approval-runs pick --sn <sourceDocumentSN> --batch <batchId> --latest --fields recordId,status,aiDecision,aiSummary
|
||||
seal-home approval-runs get <recordId> --summary
|
||||
seal-home approval-runs get <recordId> --fields metadata,document.fields,result.summary
|
||||
seal-home approval-runs document-summary <recordId>
|
||||
seal-home approval-runs cited-rules <recordId>
|
||||
seal-home approval-runs attachments <recordId> --summary
|
||||
seal-home approval-runs result <recordId> --summary
|
||||
seal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest
|
||||
seal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --batch <batchId> --latest --fields recordId,status,aiDecision,aiSummary
|
||||
seal-home approval-runs get <recordId> --corp <corpId> --summary
|
||||
seal-home approval-runs get <recordId> --corp <corpId> --fields metadata,document.fields,result.summary
|
||||
seal-home approval-runs document-summary <recordId> --corp <corpId>
|
||||
seal-home approval-runs cited-rules <recordId> --corp <corpId>
|
||||
seal-home approval-runs attachments <recordId> --corp <corpId> --summary
|
||||
seal-home approval-runs result <recordId> --corp <corpId> --summary
|
||||
seal-home rules count --corp <corpId>
|
||||
seal-home rules list --corp <corpId> --summary
|
||||
seal-home rules clear --corp <corpId> --dry-run
|
||||
seal-home rules clear --corp <corpId> --yes
|
||||
seal-home rules get --version 16 --code '#0038'
|
||||
seal-home rules get --record-id <recordId> --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 <corpId> --version 16 --code '#0038'
|
||||
seal-home rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205
|
||||
seal-home tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅","发票"],"areas":["rules"],"snippetOnly":true,"maxChars":500,"fields":["id","title","snippet"]}'
|
||||
```
|
||||
|
||||
## Important Fields
|
||||
|
||||
@@ -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 <sourceDocumentSN> --limit 50
|
||||
seal-home approval-runs get <recordId> > /tmp/seal-run.json
|
||||
seal-home approval-runs bridge --sourceDocumentSN <sourceDocumentSN>
|
||||
seal-home approval-runs search --corp <corpId> --query <sourceDocumentSN> --limit 50
|
||||
seal-home approval-runs get <recordId> --corp <corpId> > /tmp/seal-run.json
|
||||
seal-home approval-runs bridge --corp <corpId> --sourceDocumentSN <sourceDocumentSN>
|
||||
```
|
||||
|
||||
Refresh and inspect the Langfuse trace.
|
||||
|
||||
@@ -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 <recordId> --summary
|
||||
seal-home approval-runs get <recordId> --corp <corpId> --summary
|
||||
```
|
||||
|
||||
Use `--fields` when the user needs a particular slice.
|
||||
|
||||
```bash
|
||||
seal-home approval-runs get <recordId> --fields metadata
|
||||
seal-home approval-runs get <recordId> --fields document.fields,result.summary
|
||||
seal-home approval-runs get <recordId> --fields result.summary,result.decision,result.riskPoints
|
||||
seal-home approval-runs get <recordId> --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber
|
||||
seal-home approval-runs get <recordId> --corp <corpId> --fields metadata
|
||||
seal-home approval-runs get <recordId> --corp <corpId> --fields document.fields,result.summary
|
||||
seal-home approval-runs get <recordId> --corp <corpId> --fields result.summary,result.decision,result.riskPoints
|
||||
seal-home approval-runs get <recordId> --corp <corpId> --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber
|
||||
```
|
||||
|
||||
Avoid full `approval-runs get <recordId>` 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 <recordId>` unless the user specifically needs raw
|
||||
Before pulling the full document, use:
|
||||
|
||||
```bash
|
||||
seal-home approval-runs document-summary <recordId>
|
||||
seal-home approval-runs document-summary <recordId> --corp <corpId>
|
||||
```
|
||||
|
||||
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 <recordId>
|
||||
seal-home approval-runs cited-rules <recordId> --corp <corpId>
|
||||
```
|
||||
|
||||
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 <recordId> --summary
|
||||
seal-home approval-runs attachments <recordId> --corp <corpId> --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 <recordId> --summary
|
||||
seal-home approval-runs result <recordId> --corp <corpId> --summary
|
||||
```
|
||||
|
||||
This is for decision, summary, risk point count, matched rule count, trace ID, and record ID.
|
||||
|
||||
@@ -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 <corpId>` unless stateful mode is explicitly enabled:
|
||||
|
||||
```bash
|
||||
seal-home config mode stateful --corp <corpId>
|
||||
seal-home corps switch <corpId>
|
||||
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 <stateful|stateless> [--corp <corpId>]
|
||||
seal-home service <start|stop|restart|status>
|
||||
seal-home update
|
||||
seal-home tools list
|
||||
seal-home corps list [--corp <corpId>]
|
||||
seal-home corps current
|
||||
seal-home corps current [--corp <corpId>]
|
||||
seal-home corps switch <corpId>
|
||||
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 <idOrName> [--name <name>] [--result-url <url>] [--mode
|
||||
seal-home webhook delete <idOrName> --yes [--corp <corpId>]
|
||||
seal-home source config [--corp <corpId>]
|
||||
seal-home tool <toolName> [--corp <corpId>] [--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 <recordId> [--fields metadata|document.fields,result.summary] [--output-file file.json]
|
||||
seal-home approval-runs attachments <recordId>
|
||||
seal-home approval-runs result <recordId> [--summary]
|
||||
seal-home approval-runs url
|
||||
seal-home approval-runs url <recordId>
|
||||
seal-home approval-runs url --sourceDocumentSN <sourceDocumentSN>
|
||||
seal-home approval-runs bridge [--sourceDocumentSN <sourceDocumentSN>]
|
||||
seal-home simulation batch-records <batchId>
|
||||
seal-home approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]
|
||||
seal-home approval-runs search --corp <corpId> [--query text] [--limit 20] [--includeBridge true]
|
||||
seal-home approval-runs get <recordId> --corp <corpId> [--fields metadata|document.fields,result.summary] [--output-file file.json]
|
||||
seal-home approval-runs attachments <recordId> --corp <corpId>
|
||||
seal-home approval-runs result <recordId> --corp <corpId> [--summary]
|
||||
seal-home approval-runs url --corp <corpId>
|
||||
seal-home approval-runs url <recordId> --corp <corpId>
|
||||
seal-home approval-runs url --sourceDocumentSN <sourceDocumentSN> --corp <corpId>
|
||||
seal-home approval-runs bridge --corp <corpId> [--sourceDocumentSN <sourceDocumentSN>]
|
||||
seal-home simulation batch-records <batchId> --corp <corpId>
|
||||
```
|
||||
|
||||
## Fine-Grained Tools
|
||||
@@ -77,7 +91,7 @@ seal-home simulation batch-records <batchId>
|
||||
|
||||
Identity and session:
|
||||
|
||||
- `seal-home auth diagnose [--corp <corpId>]`
|
||||
- `seal-home auth diagnose --corp <corpId>`
|
||||
- `seal_whoami`
|
||||
- `seal_session_get`
|
||||
|
||||
@@ -96,14 +110,14 @@ Approval rule maintenance:
|
||||
|
||||
Approval run lightweight queries:
|
||||
|
||||
- `seal-home approval-runs get <recordId> --fields metadata`
|
||||
- `seal-home approval-runs get <recordId> --summary`
|
||||
- `seal-home approval-runs pick --sn <单号> --batch <batchId> --latest`
|
||||
- `seal-home approval-runs document-summary <recordId>`
|
||||
- `seal-home approval-runs cited-rules <recordId>`
|
||||
- `seal-home approval-runs get <recordId> --fields document.fields,result.summary`
|
||||
- `seal-home approval-runs attachments <recordId> --summary`
|
||||
- `seal-home approval-runs result <recordId> --summary`
|
||||
- `seal-home approval-runs get <recordId> --corp <corpId> --fields metadata`
|
||||
- `seal-home approval-runs get <recordId> --corp <corpId> --summary`
|
||||
- `seal-home approval-runs pick --corp <corpId> --sn <单号> --batch <batchId> --latest`
|
||||
- `seal-home approval-runs document-summary <recordId> --corp <corpId>`
|
||||
- `seal-home approval-runs cited-rules <recordId> --corp <corpId>`
|
||||
- `seal-home approval-runs get <recordId> --corp <corpId> --fields document.fields,result.summary`
|
||||
- `seal-home approval-runs attachments <recordId> --corp <corpId> --summary`
|
||||
- `seal-home approval-runs result <recordId> --corp <corpId> --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 <number> --code '#0038'`
|
||||
- `seal-home rules get --record-id <recordId> --runtime-id rule-205`
|
||||
- `seal-home rules get --corp <corpId> --version <number> --code '#0038'`
|
||||
- `seal-home rules get --corp <corpId> --record-id <recordId> --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 <corpId> --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 <corpId> --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 <corpId> --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 <corpId> --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 <corpId> --date 2026-06-09 --timezone Asia/Shanghai --limit 100
|
||||
```
|
||||
|
||||
Find a run and include Langfuse bridge rows:
|
||||
|
||||
```bash
|
||||
seal-home approval-runs search --query <sourceDocumentSN> --limit 20 --includeBridge true
|
||||
seal-home approval-runs search --corp <corpId> --query <sourceDocumentSN> --limit 20 --includeBridge true
|
||||
```
|
||||
|
||||
Resolve Langfuse trace/session hints:
|
||||
|
||||
```bash
|
||||
seal-home approval-runs bridge --sourceDocumentSN <sourceDocumentSN>
|
||||
seal-home approval-runs bridge --corp <corpId> --sourceDocumentSN <sourceDocumentSN>
|
||||
```
|
||||
|
||||
Read simulation batch records:
|
||||
|
||||
```bash
|
||||
seal-home simulation batch-records <batchId>
|
||||
seal-home simulation batch-records <batchId> --corp <corpId>
|
||||
```
|
||||
|
||||
## Write Operation Payloads
|
||||
|
||||
@@ -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 <corpId>
|
||||
seal-home corps switch <corpId>
|
||||
```
|
||||
|
||||
|
||||
@@ -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 <corpId> --json '{"countOnly":true}'
|
||||
seal-home tool seal_approval_rules_list --corp <corpId> --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 <corpId> --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 <corpId> --json '{"dryRun":true}'
|
||||
seal-home tool seal_approval_rules_clear --corp <corpId> --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 <corpId> --version 16 --code '#0038'
|
||||
seal-home rules get --corp <corpId> --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 <recordId> --runtime-id rule-205
|
||||
seal-home rules get --corp <corpId> --record-id <recordId> --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 <corpId> --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 <corpId> --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.
|
||||
|
||||
@@ -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 -- <args>`: execute CLI commands, such as `bun run cli version`.
|
||||
- `bun run probe`: run the local connectivity/config probe.
|
||||
- `bun run probe -- <corpId>`: 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`.
|
||||
|
||||
@@ -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 -- <corpId>
|
||||
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 <corpId>
|
||||
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 <corpId>
|
||||
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 <corpId>
|
||||
seal-home approval-runs summary --corp <corpId> --date 2026-06-08 --timezone Asia/Shanghai
|
||||
seal-home tool seal_approval_runs_summary --corp <corpId> --json '{"date":"2026-06-08","timezone":"Asia/Shanghai"}'
|
||||
```
|
||||
|
||||
CLI output is JSON on stdout. Errors are written to stderr.
|
||||
@@ -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 <corpId>]` 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 <corpId>`; no `current-corp` file
|
||||
or first-config fallback is used. Run `seal-home config mode stateful --corp <corpId>` to enable
|
||||
a default enterprise, then `seal-home corps switch <corpId>` to change it. Run
|
||||
`seal-home config mode stateless` to require explicit enterprise selection again.
|
||||
|
||||
Use `seal-home auth diagnose --corp <corpId>` when login fails in stateless mode. It reports four stages without printing tokens: `hose.openapi`, `hose.provisional`, `seal.sso`, and `seal.whoami`. A failed stage points to whether the problem is Hose app credentials, staff authorization, Seal SSO/tenant reachability, or Seal user/session access.
|
||||
|
||||
## Wrapped API Documentation
|
||||
|
||||
@@ -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 <corpId>` or `seal-home rules list --corp <corpId> --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 <corpId> --dry-run` first, then `seal-home rules clear --corp <corpId> --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 <recordId> --summary`, `seal-home approval-runs document-summary <recordId>`, `seal-home approval-runs cited-rules <recordId>`, `seal-home approval-runs attachments <recordId> --summary`, or `seal-home approval-runs result <recordId> --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 <corpId> --expire 7200`, which returns the unredacted `getProvisionalAuth` URL.
|
||||
For approval run detail commands, prefer the same commands with explicit `--corp <corpId>`—for example `seal-home approval-runs pick --corp <corpId> --sn <单号> --latest` or `seal-home approval-runs get <recordId> --corp <corpId> --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 <corpId> --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 <corpId> ...` instead of reading long `seal_approval_runs_search` output manually.
|
||||
- Keep broad search tools compact by default. Add explicit opt-in flags such as `includeBridge` for verbose fields that are useful only in deeper debugging.
|
||||
- When Seal API timestamp filters are uncertain, filter again in tool code by `createdAt` and explicit timezone before presenting date-based answers.
|
||||
Vendored
+19
-15
@@ -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": {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -18,7 +18,7 @@ CorpSummary:
|
||||
type: string
|
||||
sourceType:
|
||||
type: string
|
||||
enum: [hose, direct]
|
||||
enum: [hose, direct, seal]
|
||||
current:
|
||||
type: boolean
|
||||
SwitchCorpRequest:
|
||||
|
||||
@@ -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.
|
||||
|
||||
+86
-3
@@ -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<string, string> = {}) {
|
||||
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 <corpId>");
|
||||
});
|
||||
|
||||
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<string, string> {
|
||||
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")
|
||||
};
|
||||
}
|
||||
+132
-50
@@ -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 <corpId>");
|
||||
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<string, string | boolean>): 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<string, unknown>) {
|
||||
@@ -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 <stateful|stateless> [--corp <corpId>]
|
||||
seal-home service <start|stop|restart|status>
|
||||
seal-home update
|
||||
seal-home tools list
|
||||
seal-home corps list [--corp <corpId>]
|
||||
seal-home corps current
|
||||
seal-home corps current [--corp <corpId>]
|
||||
seal-home corps switch <corpId>
|
||||
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 <corpId>] [--dry-run|--yes]
|
||||
seal-home rules versions [--corp <corpId>]
|
||||
seal-home rules version <versionId|versionNumber|latest> [--corp <corpId>]
|
||||
seal-home rules get --version <number|latest> --code '#0038'
|
||||
seal-home rules get --record-id <recordId> --runtime-id rule-205
|
||||
seal-home rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20]
|
||||
seal-home context [--ruleVersion <versionId|versionNumber|latest>] [--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 <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision]
|
||||
seal-home approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json]
|
||||
seal-home approval-runs cited-rules <recordId>
|
||||
seal-home approval-runs document-summary <recordId>
|
||||
seal-home approval-runs attachments <recordId> [--summary]
|
||||
seal-home approval-runs result <recordId> [--summary]
|
||||
seal-home approval-runs url
|
||||
seal-home approval-runs url <recordId>
|
||||
seal-home approval-runs url --sourceDocumentSN B26022501
|
||||
seal-home approval-runs bridge [--sourceDocumentSN B26001887]
|
||||
seal-home simulation batch-records <batchId>
|
||||
seal-home rules get --corp <corpId> --version <number|latest> --code '#0038'
|
||||
seal-home rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205
|
||||
seal-home rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20] [--corp <corpId>]
|
||||
seal-home context [--ruleVersion <versionId|versionNumber|latest>] [--documentLimit 50] [--corp <corpId>]
|
||||
seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] [--corp <corpId>]
|
||||
seal-home approval-runs search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]
|
||||
seal-home approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
|
||||
seal-home approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]
|
||||
seal-home approval-runs cited-rules <recordId> [--corp <corpId>]
|
||||
seal-home approval-runs document-summary <recordId> [--corp <corpId>]
|
||||
seal-home approval-runs attachments <recordId> [--summary] [--corp <corpId>]
|
||||
seal-home approval-runs result <recordId> [--summary] [--corp <corpId>]
|
||||
seal-home approval-runs url [--corp <corpId>]
|
||||
seal-home approval-runs url <recordId> [--corp <corpId>]
|
||||
seal-home approval-runs url --sourceDocumentSN B26022501 [--corp <corpId>]
|
||||
seal-home approval-runs bridge [--sourceDocumentSN B26001887] [--corp <corpId>]
|
||||
seal-home simulation batch-records <batchId> [--corp <corpId>]
|
||||
`);
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 <corpId>"
|
||||
);
|
||||
});
|
||||
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,62 @@
|
||||
import { CorpConfig } from "./types.js";
|
||||
import { CorpConfig, GlobalConfig } from "./types.js";
|
||||
|
||||
export function resolveCorpConfig(
|
||||
corps: CorpConfig[],
|
||||
options: Pick<GlobalConfig, "stateful" | "defaultCorpId"> & { 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 <corpId>. " +
|
||||
"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<GlobalConfig, "stateful" | "defaultCorpId">;
|
||||
|
||||
export class CorpContext {
|
||||
private current: CorpConfig | null = null;
|
||||
private corps = new Map<string, CorpConfig>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<typeof HoseSealSourceSchema>;
|
||||
export type DirectSealSource = z.infer<typeof DirectSealSourceSchema>;
|
||||
export type NativeSealSource = z.infer<typeof NativeSealSourceSchema>;
|
||||
export type SealSource = z.infer<typeof SealSourceSchema>;
|
||||
export type CorpAuthConfig = z.infer<typeof CorpAuthConfigSchema>;
|
||||
export type CorpConfig = z.infer<typeof CorpConfigSchema>;
|
||||
export type GlobalConfig = z.infer<typeof GlobalConfigSchema>;
|
||||
+13
-12
@@ -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}`);
|
||||
|
||||
|
||||
+55
-7
@@ -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<string, unknown>).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<string, unknown>;
|
||||
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);
|
||||
|
||||
Reference in new issue
Block a user