Compare commits

..
17 Commits
Author SHA1 Message Date
gitea 771ecf7236 Fix Gitea multipart asset upload header in CI workflow
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 16:28:39 +08:00
gitea 887d7f0a74 Fix syntax in binaries.yml GitHub release step
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 16:26:11 +08:00
gitea af5344bd66 Release v0.8.1: Automated Gitea release dual-publishing and installer visual progress feedback
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 16:24:43 +08:00
gitea d29f9413c9 Add automatic Gitea release and asset publishing step to GitHub Actions
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 16:22:16 +08:00
gitea d6825953cb Simplify skill directory log message in install.sh
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 16:15:24 +08:00
gitea 1674acce49 Display download progress bar, source host, total file size, and explicit skill sync path in install.sh
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 16:14:55 +08:00
gitea 92189cc05e Add bun run bump automated version synchronization script and update guidelines
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 16:06:09 +08:00
gitea 539941bba5 Release v0.8.0: Multi-Source High-Speed Downloads, Gitea Acceleration & Strict Anti-Rollback
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 16:05:06 +08:00
gitea 7476db2bb5 Add multi-source release download and Gitea acceleration fallback to installer and CLI update
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 16:03:22 +08:00
gitea ab7131ef2c Document Release & Publishing guidelines in README.md and AGENTS.md
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 16:00:10 +08:00
gitea d3fe4c1d84 Add CHANGELOG.md and enhance GitHub Actions to extract tag annotations and auto-generate release notes
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 15:51:48 +08:00
gitea 5dd337e671 Enforce forward-only updates with downgrade protection and latest keyword normalization
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 15:43:39 +08:00
gitea 63d579c273 Add rich update check, version diffs, and changelog release history querying
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 15:25:23 +08:00
gitea e716f069ed Release v0.7.1: Add approval-runs list alias, handle EPIPE, and improve summary hints
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 15:19:11 +08:00
gitea b998a0527e Add Chinese onboarding guidance and empty corps diagnostic
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 14:46:16 +08:00
gitea 7f3a4b0fe4 Update installer to use user-writable bin directory without sudo
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 14:36:58 +08:00
gitea f0d3477d69 Add one-line install script and quick installation guide
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 14:34:17 +08:00
20 changed files with 1018 additions and 160 deletions

No files matched your search

+51 -1
View File
@@ -58,5 +58,55 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
run: |
gh release view "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" --title "${GITHUB_REF_NAME}" --notes "Automated binary release for ${GITHUB_REF_NAME}."
TAG_MSG=$(git tag -l --format='%(contents)' "${GITHUB_REF_NAME}" | sed '/^$/d')
if [ -n "$TAG_MSG" ]; then
gh release view "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" --title "${GITHUB_REF_NAME}" --notes "$TAG_MSG" --generate-notes
else
gh release view "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" --title "${GITHUB_REF_NAME}" --generate-notes
fi
gh release upload "${GITHUB_REF_NAME}" dist/bin/seal-home-* --repo "${GITHUB_REPOSITORY}" --clobber
- name: Publish Gitea Release
if: startsWith(github.ref, 'refs/tags/v')
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_HOST: "https://git.ying-qing.cn"
GITEA_REPO: "gitea/seal-home"
run: |
if [ -z "$GITEA_TOKEN" ]; then
echo "::notice::GITEA_TOKEN secret not configured, skipping Gitea upload."
exit 0
fi
TAG_NAME="${GITHUB_REF_NAME}"
TAG_MSG=$(git tag -l --format='%(contents)' "${TAG_NAME}" | sed '/^$/d')
NOTES="${TAG_MSG:-Automated release for ${TAG_NAME}}"
echo "==> Creating release on Gitea for ${TAG_NAME}..."
RELEASE_RESP=$(curl -s -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases" \
-H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
-d "{\"tag_name\":\"${TAG_NAME}\",\"name\":\"${TAG_NAME}\",\"body\":$(echo "$NOTES" | jq -Rsa .),\"draft\":false,\"prerelease\":false}")
RELEASE_ID=$(echo "$RELEASE_RESP" | jq -r '.id // empty')
if [ -z "$RELEASE_ID" ]; then
# Release might already exist, fetch its ID
RELEASE_ID=$(curl -s -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/tags/${TAG_NAME}" | jq -r '.id // empty')
fi
if [ -z "$RELEASE_ID" ]; then
echo "::warning::Failed to create or find Gitea release ID. Response: $RELEASE_RESP"
exit 0
fi
echo "==> Uploading assets to Gitea release ID ${RELEASE_ID}..."
for file in dist/bin/seal-home-*; do
filename=$(basename "$file")
echo " Uploading ${filename} to Gitea..."
RESP=$(curl -s -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
-H "Authorization: token ${GITEA_TOKEN}" \
-F "attachment=@${file}")
echo " Upload response: $(echo "$RESP" | tail -n 1)"
done
echo "✓ Successfully published release assets to Gitea!"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-home",
"version": "0.7.0",
"version": "0.8.1",
"description": "Seal Home tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+16 -1
View File
@@ -17,6 +17,7 @@ Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in
- `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 bump <version | patch | minor>`: bump version across all manifest/skill/openapi files and bundle.
- `bun run openapi:bundle`: rebuild `dist/openapi.json`.
- `bun run build:binary`: compile the standalone `seal-home` binary to `dist/bin/seal-home` (gitignored).
- `bun run build:plugin`: bundle the MCP server to `dist/mcp/server.js` (tracked, used by `.mcp.json`).
@@ -35,7 +36,20 @@ Use `bun:test` with `describe`, `test`, and `expect`. Place tests next to covere
Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`, such as `Add compact approval rule listing`. Keep subjects under roughly 72 characters.
Pull requests should include a short summary, tests run, and any config or OpenAPI regeneration notes. Link related issues when available. Add screenshots only for UI or documentation rendering changes.
## Release & Publishing Guidelines
1. **Version Bump Checklist**:
- Run `bun run bump <new-version | patch | minor>` (automatically updates `package.json`, `.zcode-plugin/plugin.json`, `skills/seal-home/SKILL.md`, `openapi/openapi.yaml`, and bundles `dist/`).
- Update `CHANGELOG.md` with new features and fixes.
- Run `bun test && bun run check`.
2. **Tag & Release**:
- Create an annotated Git tag with a descriptive release summary:
```bash
git commit -am "Release vX.Y.Z: ..."
git tag -a vX.Y.Z -m "🚀 Release summary text describing key changes"
git push origin master --tags && git push home master --tags
```
- GitHub Actions will automatically extract the tag message, append commit notes via `--generate-notes`, cross-compile all 5 target binaries in ~50s, and publish the GitHub Release.
## Security & Configuration Tips
@@ -44,3 +58,4 @@ Never commit real enterprise credentials, Seal tokens, service logs, or local ge
## Agent-Specific Instructions
Do not create `.codex/skills`; Codex is compatible with `.agents/skills`, and this project treats `.agents/` as authoritative. At project scope, prefer `AGENT.md` instructions when present.
+59
View File
@@ -0,0 +1,59 @@
# Changelog
All notable changes to `seal-home` will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
---
## [0.8.1] - 2026-08-25
### Added
- **Automated Gitea Releases Dual-Publishing**: Automated cross-publishing of compiled standalone binary assets to both GitHub Releases and Gitea (`git.ying-qing.cn`) via GitHub Actions.
- **Enhanced Installer Visuals**: Added real-time progress bar, source host identifier, and human-readable byte size indicators to `install.sh`.
- **One-Command Version Bumping**: Added `bun run bump <version|patch|minor>` script to automatically synchronize all manifest, documentation, OpenAPI, and bundled assets.
---
## [0.8.0] - 2026-08-25
### Added
- **Multi-Source Download & Gitea Acceleration**: Enhanced `install.sh` and `seal-home update` with intelligent multi-source racing and automatic fallback across Gitea (`git.ying-qing.cn`), GitHub Releases, and CDN mirrors, achieving lightning-fast downloads in mainland China.
- **Strict Anti-Rollback & Forward-Only Enforcement**: Guarded update commands against downgrades to prevent state schema and skill definition corruption.
- **Release History & Changelog Introspection**: Integrated `seal-home changelog` and `update check` with publish timestamps, author identity, and intermediate version diff calculations.
- **Automated CI Tag Release Notes**: Updated GitHub Actions release workflow to extract annotated git tag messages and append GitHub-generated PR and commit notes.
---
## [0.7.1] - 2026-08-25
### Added
- **Release History & Changelog Query**: Added `seal-home changelog` and `seal-home update check` with release publish timestamps, author info, and changelog body.
- **Cross-Version Diff Tracking**: Automatically computes skipped/intermediate versions (`pendingReleases`) with commit notes when local version is behind.
- **Strict Downgrade Protection (Anti-rollback Guard)**: Enforced forward-only updates. Attempts to downgrade to an older version (e.g. `seal-home update 0.3.3`) are strictly blocked with explicit guidance.
- **Latest Keyword Normalization**: Normalized `seal-home update latest` and `--version latest` to point cleanly to the newest release.
- **Approval Runs List Alias**: Added `seal-home approval-runs list` as a friendly alias for `approval-runs search`.
### Fixed
- **UNIX Pipe EPIPE Handling**: Handled `EPIPE` broken pipe errors on `process.stdout` so piped commands (e.g. `seal-home openapi | head`) exit cleanly without dumping stack traces.
- **Empty Filter Guidance**: Added friendly stderr diagnostics when queries (e.g. `approval-runs summary` or `corps list`) find no records for the current date/filter.
---
## [0.7.0] - 2026-08-25
### Added
- **Zero-Dependency Native Binaries**: Compiled standalone native executables for macOS (arm64/x64), Linux (x64/arm64), and Windows (x64) via Bun compiled standalone target.
- **High-Speed Release Pipeline**: GitHub Actions multi-target cross-compilation pipeline delivering release assets in under 60 seconds.
- **Sudo-Free One-Line Installer**: Created `scripts/install.sh` with automatic writable path detection (`/opt/homebrew/bin` → `/usr/local/bin` → `~/.local/bin`) and macOS ad-hoc code-signing.
- **Strict POSIX Stream Isolation**: Guaranteed `stdout` emits 100% pure, parseable JSON for AI agents and scripts, while diagnostics and human onboarding tips route to `stderr`.
- **Simulation Batch Management**: Added `simulation create` for both HoseCloud flow IDs and material package ZIP imports.
- **In-place Self-Update**: `seal-home update` atomic binary replacement with automatic global skill directory synchronization.
---
## [0.3.3] - 2026-06-13
### Added
- Initial proof-of-concept release for Seal tenant operations and Hose approval automation.
+46 -6
View File
@@ -6,16 +6,35 @@ The first provider is Hose/合思: `key`, `password`, `corpId`, `staffId`, and a
Seal-native enterprise pages can be added with a Seal Bearer token. The older `direct` source remains available for existing configs that already provide a Seal Bearer token.
## Setup
## Quick Install (Standalone Binary)
No Node.js, Bun, or external runtime required. Run the one-line installer for macOS and Linux:
```bash
bun install
cp enterprises/example.hose.json enterprises/local.json
bun run check
bun run probe -- <corpId>
bun run start
curl -fsSL https://raw.githubusercontent.com/yunyingk/seal-home/master/scripts/install.sh | bash
```
Or download the native binary directly from [GitHub Releases](https://github.com/yunyingk/seal-home/releases/latest):
- **macOS (Apple Silicon)**: `curl -fsSL https://github.com/yunyingk/seal-home/releases/latest/download/seal-home-darwin-arm64 -o /usr/local/bin/seal-home && chmod +x /usr/local/bin/seal-home`
- **macOS (Intel)**: `curl -fsSL https://github.com/yunyingk/seal-home/releases/latest/download/seal-home-darwin-x64 -o /usr/local/bin/seal-home && chmod +x /usr/local/bin/seal-home`
- **Linux (x86_64)**: `curl -fsSL https://github.com/yunyingk/seal-home/releases/latest/download/seal-home-linux-x64 -o /usr/local/bin/seal-home && chmod +x /usr/local/bin/seal-home`
- **Linux (ARM64)**: `curl -fsSL https://github.com/yunyingk/seal-home/releases/latest/download/seal-home-linux-arm64 -o /usr/local/bin/seal-home && chmod +x /usr/local/bin/seal-home`
- **Windows (x64)**: Download `seal-home-windows-x64.zip` from Releases and extract `seal-home-windows-x64.exe`.
After installation:
```bash
seal-home version # Check version
seal-home skill install # Install Agent skill to ~/.agents/skills/seal-home
seal-home mcp-config # Print .mcp.json snippet for Cursor / Claude Desktop / Codex
seal-home update # Future self-update directly from GitHub Release
```
## Source Setup & Development
For local development from source with Bun:
For an already-authenticated Seal-native source, use `seal-home corps add-seal` or copy `enterprises/example.seal.json`. Existing `direct` configs remain supported via `enterprises/example.direct.json`.
## Public Usage
@@ -269,3 +288,24 @@ When `_langfuseTraceId` exists, downstream tools should fetch the trace directly
- 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.
## Release & Publishing
To release a new version of `seal-home`:
1. **Version Bump Checklist**:
- Run `bun run bump <new-version | patch | minor>` (automatically updates `package.json`, `.zcode-plugin/plugin.json`, `skills/seal-home/SKILL.md`, `openapi/openapi.yaml`, and bundles `dist/`).
- Update `CHANGELOG.md` with release notes and highlights.
- Run verification tests:
```bash
bun test && bun run check
```
2. **Tag & Publish**:
- Commit changes and create an annotated Git tag with release notes:
```bash
git commit -am "Release vX.Y.Z: ..."
git tag -a vX.Y.Z -m "🚀 版本更新文案与主要特性说明"
git push origin master --tags && git push home master --tags
```
- GitHub Actions will automatically extract your tag annotation message, append the auto-generated commit list via `--generate-notes`, cross-compile all 5 target standalone binaries in under 60 seconds, and publish the release to [GitHub Releases](https://github.com/yunyingk/seal-home/releases).
+235 -67
View File
@@ -24943,7 +24943,7 @@ async function createSealClientForToken(corp, token) {
// package.json
var package_default = {
name: "seal-home",
version: "0.7.0",
version: "0.8.1",
type: "module",
module: "src/server.ts",
bin: {
@@ -24957,6 +24957,7 @@ var package_default = {
check: "tsc --noEmit",
"build:binary": "node scripts/build-binary.mjs",
"build:plugin": "node scripts/build-plugin.mjs",
bump: "bun run scripts/bump-version.ts",
"openapi:bundle": "bun run scripts/bundle-openapi.ts",
test: "bun test"
},
@@ -28745,8 +28746,10 @@ Usage:
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 update [--check] [--force] [--version <v>]
seal-home update check
seal-home update changelog [--limit <n>]
seal-home changelog [--limit <n>]
seal-home tools list
seal-home corps list [--corp <corpId>]
seal-home corps current [--corp <corpId>]
@@ -28788,7 +28791,7 @@ Usage:
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 list|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>]
@@ -28843,7 +28846,7 @@ async function runToolResult(name, client, corp, params) {
// src/cli/commands/approval-runs.ts
async function handleApprovalRunsCommand(action, maybeName, client, corp, args) {
if (action === "summary") {
await runTool("seal_approval_runs_summary", client, corp, {
const result = await runToolResult("seal_approval_runs_summary", client, corp, {
date: stringOption(args.options.date),
timezone: stringOption(args.options.timezone),
limit: numberOption(args.options.limit),
@@ -28856,10 +28859,14 @@ async function handleApprovalRunsCommand(action, maybeName, client, corp, args)
sourceDocumentId: stringOption(args.options.sourceDocumentId),
humanResult: stringOption(args.options.humanResult),
query: stringOption(args.options.query)
}, outputOptions(args.options));
});
if (result?.matched === 0 && result?.total > 0) {
console.error(`提示:在 ${result.date} 未匹配到记录(该企业共有 ${result.total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-home approval-runs list --limit 10 查看最近记录。`);
}
printJson(result, outputOptions(args.options));
return;
}
if (action === "search") {
if (action === "search" || action === "list") {
await runTool("seal_approval_runs_search", client, corp, {
limit: numberOption(args.options.limit),
offset: numberOption(args.options.offset),
@@ -29279,6 +29286,9 @@ async function handleCorpsCommand(action, maybeName, args) {
const corps = loadCorpConfigs();
const globalConfig2 = loadGlobalConfig();
const currentCorpId = corpId ?? (globalConfig2.stateful ? globalConfig2.defaultCorpId ?? corps[0]?.id : undefined);
if (corps.length === 0) {
console.error("提示:当前未检测到企业配置。你可以使用 seal-home corps add-hose 或 seal-home corps add-seal 添加企业,或运行 seal-home help 查看说明。");
}
printJson(corps.map((item) => ({
id: item.id,
name: item.name,
@@ -29556,7 +29566,7 @@ var openapi_default = {
openapi: "3.1.0",
info: {
title: "seal-home Wrapped API",
version: "0.7.0",
version: "0.8.1",
description: `Planned HTTP contract for the seal-home wrapped backend API.
These endpoints describe the intended stable API for frontend developers and agents once
@@ -33283,13 +33293,13 @@ import { dirname as dirname3, join as join6 } from "node:path";
// skills/seal-home/SKILL.md
var SKILL_default = `---
name: seal-home
description: "v0.7.0: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search."
description: "v0.8.1: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search."
metadata:
version: 0.7.0
short-description: Seal tenant and Hose approval automation (v0.7.0)
version: 0.8.1
short-description: Seal tenant and Hose approval automation (v0.8.1)
---
# Seal Home (v0.7.0)
# Seal Home (v0.8.1)
Use the \`seal_cli\` MCP tool when it is available; pass the command string as its \`command\` argument. If MCP is unavailable, fall back to the global \`seal-home\` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
@@ -34477,11 +34487,77 @@ async function handleUpdateCommand(runtime, options = {}) {
version: VERSION,
launcher: runtime.launcher
};
if (!isCompiledBinary()) {
if (options.checkOnly) {
const repo = options.repo || process.env[GITHUB_REPO_ENV]?.trim() || DEFAULT_GITHUB_REPO;
const rawTarget = options.targetVersion?.trim();
const targetVersion = rawTarget && rawTarget.toLowerCase() !== "latest" ? rawTarget : undefined;
if (targetVersion) {
const cleanTarget = targetVersion.replace(/^v/, "");
const cmp = compareSemVer(cleanTarget, VERSION);
if (cmp < 0) {
printJson({
updated: false,
version: VERSION,
currentVersion: VERSION,
targetVersion: cleanTarget,
mode: isCompiledBinary() ? "binary" : "source",
message: `Cannot downgrade seal-home from v${VERSION} to older version v${cleanTarget}. Updates must be forward-only.`
});
return;
}
if (cmp === 0 && !options.force) {
printJson({
updated: false,
currentVersion: VERSION,
targetVersion: cleanTarget,
mode: isCompiledBinary() ? "binary" : "source",
message: `seal-home is already at version v${VERSION}. Use --force to reinstall.`
});
return;
}
}
if (options.changelogOnly) {
const releases2 = await fetchGitHubReleases(repo, options.limit ?? 10);
printJson({
currentVersion: VERSION,
totalQueried: releases2.length,
releases: releases2.map((r) => ({
version: r.version,
tagName: r.tagName,
publishedAt: r.publishedAt,
author: r.author,
releaseNotes: r.notes,
releaseUrl: r.htmlUrl,
isCurrent: r.version === VERSION,
isNewer: isNewerVersion(r.version, VERSION)
}))
});
return;
}
if (!isCompiledBinary()) {
if (options.checkOnly) {
const releases2 = await fetchGitHubReleases(repo, 30);
const latestRelease = releases2[0];
const latestVersion2 = latestRelease?.version ?? VERSION;
const currentRelease2 = releases2.find((r) => r.version === VERSION);
const isUpgrade2 = isNewerVersion(latestVersion2, VERSION);
const pendingReleases2 = releases2.filter((r) => isNewerVersion(r.version, VERSION));
printJson({
updated: false,
updateAvailable: isUpgrade2,
currentVersion: VERSION,
currentVersionPublishedAt: currentRelease2?.publishedAt,
latestVersion: latestVersion2,
latestVersionPublishedAt: latestRelease?.publishedAt,
behindCount: pendingReleases2.length,
pendingReleases: pendingReleases2.map((r) => ({
version: r.version,
tagName: r.tagName,
publishedAt: r.publishedAt,
author: r.author,
releaseNotes: r.notes,
releaseUrl: r.htmlUrl
})),
releaseNotes: latestRelease?.notes ?? "",
releaseUrl: latestRelease?.htmlUrl ?? "",
mode: "source",
message: "Running in source development mode. Run 'seal-home update' to git pull & bun install."
});
@@ -34506,10 +34582,10 @@ async function handleUpdateCommand(runtime, options = {}) {
});
return;
}
const repo = options.repo || process.env[GITHUB_REPO_ENV]?.trim() || DEFAULT_GITHUB_REPO;
const platform = detectPlatform();
const arch = detectArch();
const release = await fetchGitHubRelease(repo, options.targetVersion);
const releases = await fetchGitHubReleases(repo, 30);
const release = targetVersion ? releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ?? await fetchGitHubRelease(repo, targetVersion) : releases[0] ?? await fetchGitHubRelease(repo);
if (!release) {
printJson({
updated: false,
@@ -34520,14 +34596,27 @@ async function handleUpdateCommand(runtime, options = {}) {
return;
}
const latestVersion = release.version;
const currentRelease = releases.find((r) => r.version === VERSION);
const isUpgrade = isNewerVersion(latestVersion, VERSION);
const shouldUpdate = options.force || Boolean(options.targetVersion) || isUpgrade;
const shouldUpdate = isUpgrade || Boolean(options.force);
const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION));
if (options.checkOnly) {
printJson({
updated: false,
updateAvailable: isUpgrade,
currentVersion: VERSION,
currentVersionPublishedAt: currentRelease?.publishedAt,
latestVersion,
latestVersionPublishedAt: release.publishedAt,
behindCount: pendingReleases.length,
pendingReleases: pendingReleases.map((r) => ({
version: r.version,
tagName: r.tagName,
publishedAt: r.publishedAt,
author: r.author,
releaseNotes: r.notes,
releaseUrl: r.htmlUrl
})),
releaseNotes: release.notes,
releaseUrl: release.htmlUrl,
mode: "binary"
@@ -34538,7 +34627,9 @@ async function handleUpdateCommand(runtime, options = {}) {
printJson({
updated: false,
currentVersion: VERSION,
currentVersionPublishedAt: currentRelease?.publishedAt,
latestVersion,
latestVersionPublishedAt: release.publishedAt,
mode: "binary",
message: `seal-home is already up to date (v${VERSION})`
});
@@ -34607,40 +34698,96 @@ function detectPlatform() {
function detectArch() {
return process.arch === "arm64" ? "arm64" : "x64";
}
async function fetchGitHubRelease(repo, targetVersion) {
const url2 = targetVersion ? `https://api.github.com/repos/${repo}/releases/tags/${targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`}` : `https://api.github.com/repos/${repo}/releases/latest`;
async function fetchGitHubReleases(repo, limit = 20) {
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
const headers = {
"User-Agent": `seal-home/${VERSION}`,
Accept: "application/vnd.github.v3+json"
Accept: "application/vnd.github.v3+json",
...token ? { Authorization: `Bearer ${token}` } : {}
};
const urls = [
`https://api.github.com/repos/${repo}/releases?per_page=${limit}`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases?per_page=${limit}`
];
for (const url2 of urls) {
try {
const res = await fetch(url2, { headers, signal: AbortSignal.timeout(5000) });
if (!res.ok)
continue;
const json2 = await res.json();
if (!Array.isArray(json2) || json2.length === 0)
continue;
const list = [];
for (const item of json2) {
const tagName = item.tag_name ?? "";
const version2 = tagName.replace(/^v/, "");
if (!version2)
continue;
const assets = (item.assets ?? []).map((a) => ({
name: a.name,
downloadUrl: a.browser_download_url,
size: a.size ?? 0
}));
list.push({
version: version2,
tagName,
name: item.name ?? tagName,
publishedAt: item.published_at,
author: item.author?.login,
notes: item.body ?? "",
htmlUrl: item.html_url ?? "",
assets
});
}
if (list.length > 0)
return list;
} catch {}
}
return [];
}
async function fetchGitHubRelease(repo, targetVersion) {
const tag = targetVersion ? targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}` : undefined;
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
if (token) {
headers.Authorization = `Bearer ${token}`;
}
try {
const res = await fetch(url2, { headers });
if (!res.ok)
return;
const json2 = await res.json();
const tagName = json2.tag_name ?? "";
const version2 = tagName.replace(/^v/, "");
if (!version2)
return;
const assets = (json2.assets ?? []).map((item) => ({
name: item.name,
downloadUrl: item.browser_download_url,
size: item.size ?? 0
}));
return {
version: version2,
tagName,
notes: json2.body ?? "",
htmlUrl: json2.html_url ?? "",
assets
};
} catch {
return;
const headers = {
"User-Agent": `seal-home/${VERSION}`,
Accept: "application/vnd.github.v3+json",
...token ? { Authorization: `Bearer ${token}` } : {}
};
const urls = tag ? [
`https://api.github.com/repos/${repo}/releases/tags/${tag}`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/tags/${tag}`
] : [
`https://api.github.com/repos/${repo}/releases/latest`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/latest`
];
for (const url2 of urls) {
try {
const res = await fetch(url2, { headers, signal: AbortSignal.timeout(5000) });
if (!res.ok)
continue;
const json2 = await res.json();
const tagName = json2.tag_name ?? "";
const version2 = tagName.replace(/^v/, "");
if (!version2)
continue;
const assets = (json2.assets ?? []).map((item) => ({
name: item.name,
downloadUrl: item.browser_download_url,
size: item.size ?? 0
}));
return {
version: version2,
tagName,
name: json2.name ?? tagName,
publishedAt: json2.published_at,
author: json2.author?.login,
notes: json2.body ?? "",
htmlUrl: json2.html_url ?? "",
assets
};
} catch {}
}
return;
}
function matchAssetForPlatform(assets, platform, arch) {
const platformKeywords = {
@@ -34667,12 +34814,25 @@ function matchAssetForPlatform(assets, platform, arch) {
return archive || matched[0];
}
async function downloadFile(url2, destPath) {
const res = await fetch(url2);
if (!res.ok) {
throw new Error(`Failed to download asset from ${url2}: ${res.status} ${res.statusText}`);
const candidates = [url2];
if (url2.includes("github.com")) {
candidates.push(`https://ghfast.top/${url2}`);
}
const buffer = Buffer.from(await res.arrayBuffer());
writeFileSync7(destPath, buffer);
let lastError;
for (const candidate of candidates) {
try {
const res = await fetch(candidate, { signal: AbortSignal.timeout(15000) });
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText}`);
}
const buffer = Buffer.from(await res.arrayBuffer());
writeFileSync7(destPath, buffer);
return;
} catch (err) {
lastError = err instanceof Error ? err : new Error(String(err));
}
}
throw new Error(`Failed to download asset from ${url2}: ${lastError?.message}`);
}
function extractTarGz(archivePath, targetDir, platform) {
const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" });
@@ -34702,18 +34862,21 @@ function extractZip(archivePath, targetDir, platform) {
return exact;
return files[0] || archivePath;
}
function isNewerVersion(latest, current) {
const lParts = latest.split(".").map(Number);
const cParts = current.split(".").map(Number);
for (let i = 0;i < Math.max(lParts.length, cParts.length); i++) {
const l = lParts[i] ?? 0;
const c = cParts[i] ?? 0;
if (l > c)
return true;
if (l < c)
return false;
function compareSemVer(v1, v2) {
const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
for (let i = 0;i < Math.max(p1.length, p2.length); i++) {
const a = p1[i] ?? 0;
const b = p2[i] ?? 0;
if (a > b)
return 1;
if (a < b)
return -1;
}
return false;
return 0;
}
function isNewerVersion(latest, current) {
return compareSemVer(latest, current) > 0;
}
function runCommand(command, args, options = {}) {
const result = spawnSync(command, args, {
@@ -34891,7 +35054,8 @@ var KNOWN_AREAS = new Set([
"mcp-config",
"skill",
"openapi",
"probe"
"probe",
"changelog"
]);
var runQueue = Promise.resolve();
function runCli(argv, options = {}) {
@@ -34985,10 +35149,14 @@ async function dispatch(argv, runtime) {
await handleServiceCommand(action, runtime);
return;
}
if (area === "update") {
const targetVersion = stringOption(args.options.version) ?? stringOption(args.options.tag) ?? (action && !action.startsWith("-") ? action : undefined);
if (area === "update" || area === "changelog") {
const isChangelog = area === "changelog" || action === "changelog" || action === "log" || action === "history" || booleanOption(args.options.changelog) === true;
const isCheck = action === "check" || booleanOption(args.options.check) === true || booleanOption(args.options["check-only"]) === true;
const targetVersion = stringOption(args.options.version) ?? stringOption(args.options.tag) ?? (!isChangelog && !isCheck && action && !action.startsWith("-") ? action : undefined);
await handleUpdateCommand(runtime, {
checkOnly: booleanOption(args.options.check) ?? booleanOption(args.options["check-only"]),
checkOnly: isCheck,
changelogOnly: isChangelog,
limit: numberOption(args.options.limit),
force: booleanOption(args.options.force),
targetVersion,
repo: stringOption(args.options.repo)
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "seal-home Wrapped API",
"version": "0.7.0",
"version": "0.8.1",
"description": "Planned HTTP contract for the seal-home wrapped backend API.\n\nThese endpoints describe the intended stable API for frontend developers and agents once\nthe HTTP adapter is implemented.\nThey are not the raw downstream Seal endpoints. seal-home is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n"
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: seal-home Wrapped API
version: 0.7.0
version: 0.8.1
description: |
Planned HTTP contract for the seal-home wrapped backend API.
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-home",
"version": "0.7.0",
"version": "0.8.1",
"type": "module",
"module": "src/server.ts",
"bin": {
@@ -14,6 +14,7 @@
"check": "tsc --noEmit",
"build:binary": "node scripts/build-binary.mjs",
"build:plugin": "node scripts/build-plugin.mjs",
"bump": "bun run scripts/bump-version.ts",
"openapi:bundle": "bun run scripts/bundle-openapi.ts",
"test": "bun test"
},
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env bun
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { execSync } from "node:child_process";
const ROOT = join(import.meta.dirname, "..");
const pkgPath = join(ROOT, "package.json");
const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
const currentVersion: string = pkg.version;
const input = process.argv[2]?.trim();
if (!input) {
console.error("Usage: bun run bump <version | patch | minor | major>");
console.error(`Current version: ${currentVersion}`);
process.exit(1);
}
let nextVersion = input.replace(/^v/, "");
if (input === "patch" || input === "minor" || input === "major") {
const [major, minor, patch] = currentVersion.split(".").map(Number);
if (input === "patch") nextVersion = `${major}.${minor}.${patch + 1}`;
if (input === "minor") nextVersion = `${major}.${minor + 1}.0`;
if (input === "major") nextVersion = `${major + 1}.0.0`;
}
if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/.test(nextVersion)) {
console.error(`Invalid SemVer format: '${nextVersion}'`);
process.exit(1);
}
console.log(`==> Bumping version: ${currentVersion} -> ${nextVersion}`);
// 1. package.json
pkg.version = nextVersion;
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
console.log("✓ Updated package.json");
// 2. .zcode-plugin/plugin.json
const pluginPath = join(ROOT, ".zcode-plugin", "plugin.json");
const plugin = JSON.parse(readFileSync(pluginPath, "utf-8"));
plugin.version = nextVersion;
writeFileSync(pluginPath, JSON.stringify(plugin, null, 2) + "\n");
console.log("✓ Updated .zcode-plugin/plugin.json");
// 3. skills/seal-home/SKILL.md
const skillPath = join(ROOT, "skills", "seal-home", "SKILL.md");
let skillContent = readFileSync(skillPath, "utf-8");
skillContent = skillContent.replace(/description: "v[\d.]+: /g, `description: "v${nextVersion}: `);
skillContent = skillContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
skillContent = skillContent.replace(/# Seal Home \(v[\d.]+\)/g, `# Seal Home (v${nextVersion})`);
skillContent = skillContent.replace(/\(v[\d.]+\)/g, `(v${nextVersion})`);
writeFileSync(skillPath, skillContent);
console.log("✓ Updated skills/seal-home/SKILL.md");
// 4. openapi/openapi.yaml
const openapiPath = join(ROOT, "openapi", "openapi.yaml");
let openapiContent = readFileSync(openapiPath, "utf-8");
openapiContent = openapiContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
writeFileSync(openapiPath, openapiContent);
console.log("✓ Updated openapi/openapi.yaml");
// 5. Rebuild bundles
console.log("==> Rebuilding OpenAPI and plugin bundles...");
execSync("bun run openapi:bundle", { cwd: ROOT, stdio: "inherit" });
execSync("bun run build:plugin", { cwd: ROOT, stdio: "inherit" });
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
console.log("\nNext steps to publish:");
console.log(` 1. Update CHANGELOG.md`);
console.log(` 2. git commit -am "Release v${nextVersion}: <Summary>"`);
console.log(` 3. git tag -a v${nextVersion} -m "🚀 <Release notes>"`);
console.log(` 4. git push origin master --tags && git push home master --tags\n`);
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env bash
set -e
REPO="yunyingk/seal-home"
echo "==> Detecting platform and architecture..."
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
case "$OS" in
darwin)
PLATFORM="darwin"
;;
linux)
PLATFORM="linux"
;;
*)
echo "Unsupported operating system: $OS" >&2
exit 1
;;
esac
case "$ARCH" in
x86_64|amd64)
ARCH_NAME="x64"
;;
arm64|aarch64)
ARCH_NAME="arm64"
;;
*)
echo "Unsupported architecture: $ARCH" >&2
exit 1
;;
esac
# Resolve best writable bin directory without requiring sudo
TARGET_DIR=""
for candidate in "/opt/homebrew/bin" "/usr/local/bin" "$HOME/.local/bin" "$HOME/bin"; do
if [ -d "$candidate" ] && [ -w "$candidate" ]; then
TARGET_DIR="$candidate"
break
fi
done
if [ -z "$TARGET_DIR" ]; then
mkdir -p "$HOME/.local/bin"
TARGET_DIR="$HOME/.local/bin"
fi
ASSET_NAME="seal-home-${PLATFORM}-${ARCH_NAME}"
TARGET_PATH="${TARGET_DIR}/seal-home"
get_file_size() {
local file="$1"
if [ ! -f "$file" ]; then
echo "0"
return
fi
local sz
sz=$(stat -f%z "$file" 2>/dev/null || stat -c%s "$file" 2>/dev/null || wc -c < "$file" | tr -d ' ')
echo "$sz"
}
format_bytes() {
local bytes="$1"
if [ -z "$bytes" ] || [ "$bytes" -le 0 ]; then
echo "0 B"
return
fi
if [ "$bytes" -ge 1048576 ]; then
awk "BEGIN {printf \"%.2f MB (%'d bytes)\", $bytes / 1048576, $bytes}" 2>/dev/null || awk "BEGIN {printf \"%.2f MB (%d bytes)\", $bytes / 1048576, $bytes}"
elif [ "$bytes" -ge 1024 ]; then
awk "BEGIN {printf \"%.2f KB (%d bytes)\", $bytes / 1024, $bytes}"
else
echo "${bytes} bytes"
fi
}
extract_host() {
local url="$1"
echo "$url" | sed -e 's|^[^/]*//||' -e 's|/.*$||'
}
download_candidate() {
local url="$1"
local dest="$2"
local label="$3"
local host
host="$(extract_host "$url")"
echo "==> Downloading from ${label}"
echo " Source Host: ${host}"
echo " Source URL: ${url}"
# Test connectivity & headers first
if ! curl -fIs --connect-timeout 4 "$url" >/dev/null 2>&1; then
echo " ↳ Source unreachable or asset not ready (404), falling back to next mirror..."
return 1
fi
# Download with progress bar (-# / --progress-bar)
if curl -fL --progress-bar "$url" -o "$dest"; then
local size_bytes
size_bytes="$(get_file_size "$dest")"
if [ "$size_bytes" -gt 1000000 ]; then
echo "✓ Download complete! Total size: $(format_bytes "$size_bytes")"
echo "✓ Successfully fetched from host: ${host}"
return 0
fi
fi
rm -f "$dest"
return 1
}
echo "==> Target install location: ${TARGET_PATH}"
TMP_FILE="$(mktemp)"
DOWNLOAD_SUCCESS=false
# Candidate mirrors
GITEA_URL="https://git.ying-qing.cn/gitea/seal-home/releases/download/latest/${ASSET_NAME}"
GITHUB_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
GHPROXY_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
# 1. Try Gitea mirror
if [ "${SEAL_HOME_MIRROR:-auto}" = "gitea" ] || [ "${SEAL_HOME_MIRROR:-auto}" = "auto" ]; then
if download_candidate "$GITEA_URL" "$TMP_FILE" "Gitea High-Speed Mirror"; then
DOWNLOAD_SUCCESS=true
fi
fi
# 2. Try direct GitHub Releases
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
if download_candidate "$GITHUB_URL" "$TMP_FILE" "GitHub Releases (Direct)"; then
DOWNLOAD_SUCCESS=true
fi
fi
# 3. Try GitHub CDN Proxy Fallback
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
if download_candidate "$GHPROXY_URL" "$TMP_FILE" "Fast CDN Mirror (Fallback)"; then
DOWNLOAD_SUCCESS=true
fi
fi
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
echo "Error: Failed to download ${ASSET_NAME} from all candidate mirrors." >&2
rm -f "$TMP_FILE"
exit 1
fi
chmod +x "$TMP_FILE"
mv "$TMP_FILE" "$TARGET_PATH"
# Ad-hoc sign on macOS
if [ "$PLATFORM" = "darwin" ] && command -v codesign >/dev/null 2>&1; then
echo "==> Applying macOS code signature..."
codesign --force --sign - "$TARGET_PATH" 2>/dev/null || true
fi
echo "==> Initializing agent skill to ~/.agents/skills/seal-home..."
"$TARGET_PATH" skill install >/dev/null 2>&1 || true
echo "✓ Agent skill installed to ~/.agents/skills/seal-home"
echo ""
echo "✨ seal-home successfully installed to ${TARGET_PATH}!"
"$TARGET_PATH" version
echo ""
echo "Quick start:"
echo " 1. Add enterprise: seal-home corps add-hose --json '{...}'"
echo " 2. View MCP config: seal-home mcp-config"
echo " 3. Self-update: seal-home update"
echo ""
+4 -4
View File
@@ -1,12 +1,12 @@
---
name: seal-home
description: "v0.7.0: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search."
description: "v0.8.1: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search."
metadata:
version: 0.7.0
short-description: Seal tenant and Hose approval automation (v0.7.0)
version: 0.8.1
short-description: Seal tenant and Hose approval automation (v0.8.1)
---
# Seal Home (v0.7.0)
# Seal Home (v0.8.1)
Use the `seal_cli` MCP tool when it is available; pass the command string as its `command` argument. If MCP is unavailable, fall back to the global `seal-home` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
+38
View File
@@ -165,6 +165,44 @@ describe("CLI version & help handling", () => {
expect(parsed.info.title).toContain("seal-home");
expect(parsed.paths).toHaveProperty("/v1/corps");
});
test("update check subcommand outputs structured check payload", () => {
const result = runCli(["update", "check"]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed).toHaveProperty("currentVersion");
expect(parsed).toHaveProperty("latestVersion");
expect(parsed).toHaveProperty("updateAvailable");
expect(parsed).toHaveProperty("behindCount");
expect(parsed).toHaveProperty("pendingReleases");
expect(Array.isArray(parsed.pendingReleases)).toBe(true);
});
test("changelog command outputs release history list", () => {
const result = runCli(["changelog", "--limit", "5"]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.currentVersion).toBe(VERSION);
expect(Array.isArray(parsed.releases)).toBe(true);
});
test("rejects downgrade to older version when target version is lower", () => {
const result = runCli(["update", "0.3.3"]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.updated).toBe(false);
expect(parsed.currentVersion).toBe(VERSION);
expect(parsed.targetVersion).toBe("0.3.3");
expect(parsed.message).toContain("Cannot downgrade seal-home");
});
test("treats latest keyword as latest release without downgrade error", () => {
const result = runCli(["update", "latest", "--check"]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed).toHaveProperty("latestVersion");
expect(parsed.updated).toBe(false);
});
});
function makeConfigEnv(): Record<string, string> {
+19 -2
View File
@@ -4,6 +4,13 @@ import { fileURLToPath } from "node:url";
import { runCli } from "./cli/runner.js";
import { isCompiledBinary, resolveAppRoot, resolveDefaultLauncher } from "./core/runtime.js";
process.stdout.on("error", (err: any) => {
if (err?.code === "EPIPE") process.exit(0);
});
process.stderr.on("error", (err: any) => {
if (err?.code === "EPIPE") process.exit(0);
});
const entryFile = fileURLToPath(import.meta.url);
const isCompiled = isCompiledBinary();
const appRoot = resolveAppRoot(entryFile, isCompiled);
@@ -15,6 +22,16 @@ const result = await runCli(Bun.argv.slice(2), {
launcher
});
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(`${result.stderr}${result.stderr.endsWith("\n") ? "" : "\n"}`);
try {
if (result.stdout) process.stdout.write(result.stdout);
} catch (err: any) {
if (err?.code !== "EPIPE") throw err;
}
try {
if (result.stderr) process.stderr.write(`${result.stderr}${result.stderr.endsWith("\n") ? "" : "\n"}`);
} catch (err: any) {
if (err?.code !== "EPIPE") throw err;
}
process.exitCode = result.exitCode;
+11 -6
View File
@@ -1,8 +1,8 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { runTool, runToolResult } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleApprovalRunsCommand(
@@ -13,7 +13,7 @@ export async function handleApprovalRunsCommand(
args: ParsedArgs
) {
if (action === "summary") {
await runTool(
const result = await runToolResult(
"seal_approval_runs_summary",
client,
corp,
@@ -30,13 +30,18 @@ export async function handleApprovalRunsCommand(
sourceDocumentId: stringOption(args.options.sourceDocumentId),
humanResult: stringOption(args.options.humanResult),
query: stringOption(args.options.query)
},
outputOptions(args.options)
}
);
if ((result as any)?.matched === 0 && (result as any)?.total > 0) {
console.error(
`提示:在 ${(result as any).date} 未匹配到记录(该企业共有 ${(result as any).total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-home approval-runs list --limit 10 查看最近记录。`
);
}
printJson(result, outputOptions(args.options));
return;
}
if (action === "search") {
if (action === "search" || action === "list") {
await runTool(
"seal_approval_runs_search",
client,
+3
View File
@@ -33,6 +33,9 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
? globalConfig.defaultCorpId ?? corps[0]?.id
: undefined
);
if (corps.length === 0) {
console.error("提示:当前未检测到企业配置。你可以使用 seal-home corps add-hose 或 seal-home corps add-seal 添加企业,或运行 seal-home help 查看说明。");
}
printJson(corps.map((item) => ({
id: item.id,
name: item.name,
+9 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { isNewerVersion } from "./update.js";
import { compareSemVer, isNewerVersion } from "./update.js";
describe("update version comparator", () => {
test("correctly identifies newer semantic versions", () => {
@@ -10,4 +10,12 @@ describe("update version comparator", () => {
expect(isNewerVersion("0.5.9", "0.6.0")).toBe(false);
expect(isNewerVersion("0.6.0", "0.7.0")).toBe(false);
});
test("compareSemVer handles tags, major, minor, and patch", () => {
expect(compareSemVer("v0.7.1", "0.7.0")).toBe(1);
expect(compareSemVer("0.7.0", "v0.7.1")).toBe(-1);
expect(compareSemVer("v0.7.1", "v0.7.1")).toBe(0);
expect(compareSemVer("1.0.0", "0.9.9")).toBe(1);
expect(compareSemVer("0.3.3", "0.7.1")).toBe(-1);
});
});
+248 -60
View File
@@ -15,6 +15,8 @@ const GITHUB_REPO_ENV = "SEAL_HOME_GITHUB_REPO";
export type UpdateOptions = {
checkOnly?: boolean;
changelogOnly?: boolean;
limit?: number;
force?: boolean;
targetVersion?: string;
repo?: string;
@@ -29,12 +31,84 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
launcher: runtime.launcher
};
// 1. Source development mode (running via bun/node)
if (!isCompiledBinary()) {
if (options.checkOnly) {
const repo = options.repo || process.env[GITHUB_REPO_ENV]?.trim() || DEFAULT_GITHUB_REPO;
const rawTarget = options.targetVersion?.trim();
const targetVersion = rawTarget && rawTarget.toLowerCase() !== "latest" ? rawTarget : undefined;
// Validate targetVersion: prevent downgrade to older versions
if (targetVersion) {
const cleanTarget = targetVersion.replace(/^v/, "");
const cmp = compareSemVer(cleanTarget, VERSION);
if (cmp < 0) {
printJson({
updated: false,
version: VERSION,
currentVersion: VERSION,
targetVersion: cleanTarget,
mode: isCompiledBinary() ? "binary" : "source",
message: `Cannot downgrade seal-home from v${VERSION} to older version v${cleanTarget}. Updates must be forward-only.`
});
return;
}
if (cmp === 0 && !options.force) {
printJson({
updated: false,
currentVersion: VERSION,
targetVersion: cleanTarget,
mode: isCompiledBinary() ? "binary" : "source",
message: `seal-home is already at version v${VERSION}. Use --force to reinstall.`
});
return;
}
}
// 1. Changelog / Release History query
if (options.changelogOnly) {
const releases = await fetchGitHubReleases(repo, options.limit ?? 10);
printJson({
currentVersion: VERSION,
totalQueried: releases.length,
releases: releases.map((r) => ({
version: r.version,
tagName: r.tagName,
publishedAt: r.publishedAt,
author: r.author,
releaseNotes: r.notes,
releaseUrl: r.htmlUrl,
isCurrent: r.version === VERSION,
isNewer: isNewerVersion(r.version, VERSION)
}))
});
return;
}
// 2. Source development mode (running via bun/node)
if (!isCompiledBinary()) {
if (options.checkOnly) {
const releases = await fetchGitHubReleases(repo, 30);
const latestRelease = releases[0];
const latestVersion = latestRelease?.version ?? VERSION;
const currentRelease = releases.find((r) => r.version === VERSION);
const isUpgrade = isNewerVersion(latestVersion, VERSION);
const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION));
printJson({
updated: false,
updateAvailable: isUpgrade,
currentVersion: VERSION,
currentVersionPublishedAt: currentRelease?.publishedAt,
latestVersion,
latestVersionPublishedAt: latestRelease?.publishedAt,
behindCount: pendingReleases.length,
pendingReleases: pendingReleases.map((r) => ({
version: r.version,
tagName: r.tagName,
publishedAt: r.publishedAt,
author: r.author,
releaseNotes: r.notes,
releaseUrl: r.htmlUrl
})),
releaseNotes: latestRelease?.notes ?? "",
releaseUrl: latestRelease?.htmlUrl ?? "",
mode: "source",
message: "Running in source development mode. Run 'seal-home update' to git pull & bun install."
});
@@ -62,12 +136,16 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
return;
}
// 2. Standalone binary mode: check GitHub Releases
const repo = options.repo || process.env[GITHUB_REPO_ENV]?.trim() || DEFAULT_GITHUB_REPO;
// 3. Standalone binary mode: check GitHub Releases
const platform = detectPlatform();
const arch = detectArch();
const release = await fetchGitHubRelease(repo, options.targetVersion);
const releases = await fetchGitHubReleases(repo, 30);
const release = targetVersion
? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ??
await fetchGitHubRelease(repo, targetVersion))
: (releases[0] ?? await fetchGitHubRelease(repo));
if (!release) {
printJson({
updated: false,
@@ -79,15 +157,28 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
}
const latestVersion = release.version;
const currentRelease = releases.find((r) => r.version === VERSION);
const isUpgrade = isNewerVersion(latestVersion, VERSION);
const shouldUpdate = options.force || Boolean(options.targetVersion) || isUpgrade;
const shouldUpdate = isUpgrade || Boolean(options.force);
const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION));
if (options.checkOnly) {
printJson({
updated: false,
updateAvailable: isUpgrade,
currentVersion: VERSION,
currentVersionPublishedAt: currentRelease?.publishedAt,
latestVersion,
latestVersionPublishedAt: release.publishedAt,
behindCount: pendingReleases.length,
pendingReleases: pendingReleases.map((r) => ({
version: r.version,
tagName: r.tagName,
publishedAt: r.publishedAt,
author: r.author,
releaseNotes: r.notes,
releaseUrl: r.htmlUrl
})),
releaseNotes: release.notes,
releaseUrl: release.htmlUrl,
mode: "binary"
@@ -99,7 +190,9 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
printJson({
updated: false,
currentVersion: VERSION,
currentVersionPublishedAt: currentRelease?.publishedAt,
latestVersion,
latestVersionPublishedAt: release.publishedAt,
mode: "binary",
message: `seal-home is already up to date (v${VERSION})`
});
@@ -200,56 +293,132 @@ type GitHubAsset = {
type GitHubRelease = {
version: string;
tagName: string;
name?: string;
publishedAt?: string;
author?: string;
notes: string;
htmlUrl: string;
assets: GitHubAsset[];
};
async function fetchGitHubRelease(repo: string, targetVersion?: string): Promise<GitHubRelease | undefined> {
const url = targetVersion
? `https://api.github.com/repos/${repo}/releases/tags/${targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`}`
: `https://api.github.com/repos/${repo}/releases/latest`;
async function fetchGitHubReleases(repo: string, limit = 20): Promise<GitHubRelease[]> {
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
const headers: Record<string, string> = {
"User-Agent": `seal-home/${VERSION}`,
Accept: "application/vnd.github.v3+json"
Accept: "application/vnd.github.v3+json",
...(token ? { Authorization: `Bearer ${token}` } : {})
};
const urls = [
`https://api.github.com/repos/${repo}/releases?per_page=${limit}`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases?per_page=${limit}`
];
for (const url of urls) {
try {
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
if (!res.ok) continue;
const json = (await res.json()) as Array<{
tag_name?: string;
name?: string;
body?: string;
html_url?: string;
published_at?: string;
author?: { login?: string };
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
}>;
if (!Array.isArray(json) || json.length === 0) continue;
const list: GitHubRelease[] = [];
for (const item of json) {
const tagName = item.tag_name ?? "";
const version = tagName.replace(/^v/, "");
if (!version) continue;
const assets: GitHubAsset[] = (item.assets ?? []).map((a) => ({
name: a.name,
downloadUrl: a.browser_download_url,
size: a.size ?? 0
}));
list.push({
version,
tagName,
name: item.name ?? tagName,
publishedAt: item.published_at,
author: item.author?.login,
notes: item.body ?? "",
htmlUrl: item.html_url ?? "",
assets
});
}
if (list.length > 0) return list;
} catch {
// try next source
}
}
return [];
}
async function fetchGitHubRelease(repo: string, targetVersion?: string): Promise<GitHubRelease | undefined> {
const tag = targetVersion ? (targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`) : undefined;
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
if (token) {
headers.Authorization = `Bearer ${token}`;
const headers: Record<string, string> = {
"User-Agent": `seal-home/${VERSION}`,
Accept: "application/vnd.github.v3+json",
...(token ? { Authorization: `Bearer ${token}` } : {})
};
const urls = tag
? [
`https://api.github.com/repos/${repo}/releases/tags/${tag}`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/tags/${tag}`
]
: [
`https://api.github.com/repos/${repo}/releases/latest`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/latest`
];
for (const url of urls) {
try {
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
if (!res.ok) continue;
const json = (await res.json()) as {
tag_name?: string;
name?: string;
body?: string;
html_url?: string;
published_at?: string;
author?: { login?: string };
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
};
const tagName = json.tag_name ?? "";
const version = tagName.replace(/^v/, "");
if (!version) continue;
const assets: GitHubAsset[] = (json.assets ?? []).map((item) => ({
name: item.name,
downloadUrl: item.browser_download_url,
size: item.size ?? 0
}));
return {
version,
tagName,
name: json.name ?? tagName,
publishedAt: json.published_at,
author: json.author?.login,
notes: json.body ?? "",
htmlUrl: json.html_url ?? "",
assets
};
} catch {
// try next source
}
}
try {
const res = await fetch(url, { headers });
if (!res.ok) return undefined;
const json = (await res.json()) as {
tag_name?: string;
body?: string;
html_url?: string;
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
};
const tagName = json.tag_name ?? "";
const version = tagName.replace(/^v/, "");
if (!version) return undefined;
const assets: GitHubAsset[] = (json.assets ?? []).map((item) => ({
name: item.name,
downloadUrl: item.browser_download_url,
size: item.size ?? 0
}));
return {
version,
tagName,
notes: json.body ?? "",
htmlUrl: json.html_url ?? "",
assets
};
} catch {
return undefined;
}
return undefined;
}
function matchAssetForPlatform(
@@ -291,12 +460,27 @@ function matchAssetForPlatform(
}
async function downloadFile(url: string, destPath: string) {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Failed to download asset from ${url}: ${res.status} ${res.statusText}`);
const candidates = [url];
if (url.includes("github.com")) {
candidates.push(`https://ghfast.top/${url}`);
}
const buffer = Buffer.from(await res.arrayBuffer());
writeFileSync(destPath, buffer);
let lastError: Error | undefined;
for (const candidate of candidates) {
try {
const res = await fetch(candidate, { signal: AbortSignal.timeout(15000) });
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText}`);
}
const buffer = Buffer.from(await res.arrayBuffer());
writeFileSync(destPath, buffer);
return;
} catch (err) {
lastError = err instanceof Error ? err : new Error(String(err));
}
}
throw new Error(`Failed to download asset from ${url}: ${lastError?.message}`);
}
function extractTarGz(archivePath: string, targetDir: string, platform: string): string {
@@ -336,16 +520,20 @@ function extractZip(archivePath: string, targetDir: string, platform: string): s
return files[0] || archivePath;
}
export function isNewerVersion(latest: string, current: string): boolean {
const lParts = latest.split(".").map(Number);
const cParts = current.split(".").map(Number);
for (let i = 0; i < Math.max(lParts.length, cParts.length); i++) {
const l = lParts[i] ?? 0;
const c = cParts[i] ?? 0;
if (l > c) return true;
if (l < c) return false;
export function compareSemVer(v1: string, v2: string): number {
const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
for (let i = 0; i < Math.max(p1.length, p2.length); i++) {
const a = p1[i] ?? 0;
const b = p2[i] ?? 0;
if (a > b) return 1;
if (a < b) return -1;
}
return false;
return 0;
}
export function isNewerVersion(latest: string, current: string): boolean {
return compareSemVer(latest, current) > 0;
}
function runCommand(command: string, args: string[], options: { cwd?: string } = {}) {
+5 -3
View File
@@ -85,8 +85,10 @@ Usage:
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 update [--check] [--force] [--version <v>]
seal-home update check
seal-home update changelog [--limit <n>]
seal-home changelog [--limit <n>]
seal-home tools list
seal-home corps list [--corp <corpId>]
seal-home corps current [--corp <corpId>]
@@ -128,7 +130,7 @@ Usage:
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 list|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>]
+24 -5
View File
@@ -27,7 +27,7 @@ import { handleUpdateCommand } from "./commands/update.js";
import { handleUsersCommand } from "./commands/users.js";
import { handleWebhookCommand } from "./commands/webhook.js";
import { selectCorp } from "./helpers.js";
import { booleanOption, parseArgs, stringOption } from "./parser.js";
import { booleanOption, numberOption, parseArgs, stringOption } from "./parser.js";
import {
formatConsoleOutput,
joinOutput,
@@ -63,7 +63,8 @@ const KNOWN_AREAS = new Set([
"mcp-config",
"skill",
"openapi",
"probe"
"probe",
"changelog"
]);
export type { CliResult, CliRunOptions } from "./types.js";
@@ -181,10 +182,28 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "update") {
const targetVersion = stringOption(args.options.version) ?? stringOption(args.options.tag) ?? (action && !action.startsWith("-") ? action : undefined);
if (area === "update" || area === "changelog") {
const isChangelog =
area === "changelog" ||
action === "changelog" ||
action === "log" ||
action === "history" ||
booleanOption(args.options.changelog) === true;
const isCheck =
action === "check" ||
booleanOption(args.options.check) === true ||
booleanOption(args.options["check-only"]) === true;
const targetVersion =
stringOption(args.options.version) ??
stringOption(args.options.tag) ??
(!isChangelog && !isCheck && action && !action.startsWith("-") ? action : undefined);
await handleUpdateCommand(runtime, {
checkOnly: booleanOption(args.options.check) ?? booleanOption(args.options["check-only"]),
checkOnly: isCheck,
changelogOnly: isChangelog,
limit: numberOption(args.options.limit),
force: booleanOption(args.options.force),
targetVersion,
repo: stringOption(args.options.repo)