fix: harden CLI parsing, MCP startup and release integrity
This commit is contained in:
1 parent
f0902f5f20
commit
103ead0fe5
53 files changed
+3713
-1945
No files matched your search
@@ -0,0 +1,36 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: 1.3.14
|
||||
- run: bun install --frozen-lockfile
|
||||
- run: bun run check:version
|
||||
- run: bun run check
|
||||
- run: bun test
|
||||
- run: bun run build:binary
|
||||
- run: bun run scripts/verify-binary.ts dist/bin/hose-use
|
||||
- run: bun run build:plugin
|
||||
- run: git diff --exit-code -- dist/mcp/server.js
|
||||
- run: bun run scripts/verify-binary.ts dist/mcp/server.js --plugin
|
||||
@@ -5,26 +5,53 @@ on:
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Release tag already merged into main (e.g. v0.8.14)
|
||||
required: true
|
||||
type: string
|
||||
|
||||
concurrency:
|
||||
group: release-${{ inputs.tag || github.ref_name }}
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build-and-publish:
|
||||
name: 🚀 Build & Publish Multi-Platform Binaries
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.tag || github.ref_name }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
ref: ${{ inputs.tag || github.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: 1.3.14
|
||||
|
||||
# A tag alone does not prove review. Also verify the commit actually being
|
||||
# compiled, so manual dispatch cannot validate one tag and ship another ref.
|
||||
- name: Verify release commit and version
|
||||
run: |
|
||||
git fetch --no-tags origin main:refs/remotes/origin/main
|
||||
bun run scripts/verify-release.ts "$RELEASE_TAG"
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Check committed version consistency
|
||||
run: bun run check:version
|
||||
|
||||
- name: Generate & bundle OpenAPI
|
||||
run: bun run openapi:all
|
||||
|
||||
@@ -37,7 +64,15 @@ jobs:
|
||||
- name: Compile multi-target binaries
|
||||
run: |
|
||||
mkdir -p dist/bin
|
||||
node scripts/build-binary.mjs --all
|
||||
node scripts/build-binary.mjs --all --release
|
||||
|
||||
- name: Verify packaged MCP entrypoint
|
||||
run: bun run scripts/verify-binary.ts dist/bin/hose-use-linux-x64
|
||||
|
||||
- name: Verify plugin bundle runtime
|
||||
run: |
|
||||
bun run build:plugin
|
||||
bun run scripts/verify-binary.ts dist/mcp/server.js --plugin
|
||||
|
||||
- name: Package release archives
|
||||
run: |
|
||||
@@ -64,17 +99,19 @@ jobs:
|
||||
(cd "${stage}" && zip -q "${GITHUB_WORKSPACE}/dist/bin/hose-use-windows-x64.zip" hose-use-windows-x64.exe hose-aipro.cmd)
|
||||
rm -rf "${stage}"
|
||||
|
||||
(cd dist/bin && sha256sum hose-use-* > checksums.txt)
|
||||
|
||||
- name: Publish GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
TAG_MSG=$(git tag -l --format='%(contents)' "${GITHUB_REF_NAME}" | sed '/^$/d')
|
||||
TAG_MSG=$(git tag -l --format='%(contents)' "${RELEASE_TAG}" | 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
|
||||
gh release view "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" --title "${RELEASE_TAG}" --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
|
||||
gh release view "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" --title "${RELEASE_TAG}" --generate-notes
|
||||
fi
|
||||
gh release upload "${GITHUB_REF_NAME}" dist/bin/hose-use-* --repo "${GITHUB_REPOSITORY}" --clobber
|
||||
gh release upload "${RELEASE_TAG}" dist/bin/hose-use-* dist/bin/checksums.txt --repo "${GITHUB_REPOSITORY}" --clobber
|
||||
|
||||
- name: Publish Gitea Release
|
||||
env:
|
||||
@@ -87,7 +124,7 @@ jobs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
TAG_NAME="${GITHUB_REF_NAME}"
|
||||
TAG_NAME="${RELEASE_TAG}"
|
||||
TAG_MSG=$(git tag -l --format='%(contents)' "${TAG_NAME}" | sed '/^$/d')
|
||||
NOTES="${TAG_MSG:-Automated release for ${TAG_NAME}}"
|
||||
|
||||
@@ -103,8 +140,8 @@ jobs:
|
||||
fi
|
||||
|
||||
if [ -z "$RELEASE_ID" ]; then
|
||||
echo "::warning::Failed to create or find Gitea release ID. Response: $RELEASE_RESP"
|
||||
exit 0
|
||||
echo "::error::Failed to create or find Gitea release ID. Response: $RELEASE_RESP"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "==> Uploading assets to Gitea release ID ${RELEASE_ID}..."
|
||||
@@ -113,7 +150,12 @@ jobs:
|
||||
local filename
|
||||
filename=$(basename "$file")
|
||||
echo " [start] Uploading ${filename} to Gitea..."
|
||||
RESP=$(curl -s -m 600 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
|
||||
# Match GitHub --clobber when retrying the same verified release.
|
||||
existing=$(curl -fsS -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}" | jq -r --arg name "$filename" '.assets[]? | select(.name == $name) | .id')
|
||||
for asset_id in $existing; do
|
||||
curl -fsS -X DELETE -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets/${asset_id}"
|
||||
done
|
||||
RESP=$(curl -fsS -m 600 -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}")
|
||||
STATUS=$(echo "$RESP" | tail -n 1)
|
||||
@@ -121,12 +163,17 @@ jobs:
|
||||
}
|
||||
|
||||
pids=()
|
||||
for file in dist/bin/hose-use-*; do
|
||||
for file in dist/bin/hose-use-* dist/bin/checksums.txt; do
|
||||
upload_asset "$file" &
|
||||
pids+=($!)
|
||||
done
|
||||
|
||||
failed=0
|
||||
for pid in "${pids[@]}"; do
|
||||
wait "$pid" || true
|
||||
wait "$pid" || failed=1
|
||||
done
|
||||
if [ "$failed" -ne 0 ]; then
|
||||
echo "::error::One or more Gitea assets failed to upload."
|
||||
exit 1
|
||||
fi
|
||||
echo "✓ Successfully published release assets to Gitea!"
|
||||
@@ -2,7 +2,7 @@
|
||||
"mcpServers": {
|
||||
"hose-use": {
|
||||
"type": "stdio",
|
||||
"command": "node",
|
||||
"command": "bun",
|
||||
"args": [
|
||||
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
|
||||
],
|
||||
|
||||
@@ -22,7 +22,7 @@ CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/h
|
||||
cli/registry.ts & cli/commands/* (命令分发与视图渲染)
|
||||
│
|
||||
▼
|
||||
domains/ (14 个业务子域:编排 tools/services + 传输 api)
|
||||
domains/ (业务子域:编排 tools/services + 传输 api;清单见域层说明)
|
||||
│
|
||||
▼
|
||||
core/ (严格基础设施白名单)
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
curl -fsSL https://raw.githubusercontent.com/yunyingk/hose-use/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
安装与自更新会校验 Release 的 SHA-256 清单;版本固定、镜像设置及发布流程见 [构建与分发说明](./src/packaging/README.packaging.md)。
|
||||
|
||||
### 方式二:本地 Bun 源码开发
|
||||
|
||||
```bash
|
||||
@@ -92,7 +94,7 @@ hose-use service logs # 查看守护进程日志
|
||||
hose-use service stop # 优雅停止常驻守护进程
|
||||
|
||||
# 8. Agent Skill 与连通性诊断
|
||||
hose-use skill install # 一键将 Agent Skill 安装到 ~/.agents/skills/
|
||||
hose-use skill install --yes # 一键将 Agent Skill 安装到 ~/.agents/skills/
|
||||
hose-use probe # 诊断当前企业主站 Session、EASO 握手与接口连通性
|
||||
|
||||
# 9. MCP Server (单工具网关模式)
|
||||
@@ -105,14 +107,14 @@ hose-use mcp # 启动 MCP Server (默认暴露
|
||||
- 避免数十个业务工具占用大量 Prompt Tokens;
|
||||
- 业务语义完全收敛在 `skills/hose-use/SKILL.md` 与 `references/` 专卷中,Agent 按需学习;
|
||||
- 内部同进程调用 CLI 分发层,零子进程开销;
|
||||
- 若需要传统细粒度工具,可通过环境变量 `HOSE_MCP_MODE=all` 开启兼容模式。
|
||||
- `HOSE_MCP_MODE` 始终采用 `single`;通过 `HOSE_USE_MCP_ENABLED=false` 可关闭工具暴露,写操作沿用 CLI 的预览与确认约定。
|
||||
|
||||
### 模块化 Agent Skill 与 IDE 插件规范
|
||||
|
||||
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装到统一的 `~/.agents/skills/hose-use`;如需安装到其他位置,必须显式使用 `--dir`;
|
||||
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install --yes` 自动递归安装到统一的 `~/.agents/skills/hose-use`;如需安装到其他位置,必须显式使用 `--dir`;
|
||||
- **开发环境检查**:Git 工作树、分支、无引用提交、canonical Skill 与全局开发版可通过 `bun run dev:status`、`bun run dev:check` 检查;清理必须先 `bun run dev:clean --dry-run`,再追加 `--yes`;
|
||||
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `.mcp.json` 清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;
|
||||
- **MCP 单文件产物**:支持通过 `bun run build:plugin` 快速编译 Node.js 兼容的轻量单文件 `dist/mcp/server.js`。
|
||||
- **MCP 单文件产物**:`bun run build:plugin` 生成 `dist/mcp/server.js`,插件使用 Bun 1.3.14+ 运行,以支持共享 CLI 的 `bun:sqlite`。独立二进制的 `hose-use mcp` 已内嵌运行时,可直接启动。
|
||||
|
||||
## 架构
|
||||
|
||||
|
||||
Vendored
+1505
-1240
File diff suppressed because it is too large.
Load diff
@@ -19,6 +19,7 @@ function run(args) {
|
||||
|
||||
const mcpOutput = resolve(root, "dist/mcp/server.js");
|
||||
mkdirSync(dirname(mcpOutput), { recursive: true });
|
||||
run(["build", "src/server.ts", "--minify", "--target=node", "--outfile", mcpOutput]);
|
||||
// The shared CLI uses bun:sqlite; the plugin manifest must use this runtime too.
|
||||
run(["build", "src/server.ts", "--minify", "--target=bun", "--outfile", mcpOutput]);
|
||||
writeFileSync(mcpOutput, readFileSync(mcpOutput, "utf8").replace(/[ \t]+$/gm, ""));
|
||||
console.log(`✓ Successfully bundled MCP server: ${mcpOutput}`);
|
||||
+113
-85
@@ -1,93 +1,121 @@
|
||||
#!/usr/bin/env bun
|
||||
import { readFileSync, writeFileSync, existsSync, cpSync, readdirSync } from "node:fs";
|
||||
import { readFileSync, writeFileSync, existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { execSync } from "node:child_process";
|
||||
import { execFileSync } 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;
|
||||
export function bumpVersion(ROOT: string, input: string, rebuild = () => {
|
||||
execFileSync(process.execPath, ["run", "openapi:all"], { cwd: ROOT, stdio: "inherit" });
|
||||
execFileSync(process.execPath, ["run", "build:plugin"], { cwd: ROOT, stdio: "inherit" });
|
||||
execFileSync(process.execPath, ["run", "check:version"], { cwd: ROOT, stdio: "inherit" });
|
||||
}): string {
|
||||
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. README.md
|
||||
const readmePath = join(ROOT, "README.md");
|
||||
let readmeContent = readFileSync(readmePath, "utf-8");
|
||||
readmeContent = readmeContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`);
|
||||
writeFileSync(readmePath, readmeContent);
|
||||
console.log("✓ Updated README.md");
|
||||
|
||||
// 3. skills/hose-use/SKILL.md
|
||||
const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md");
|
||||
let skillContent = readFileSync(skillPath, "utf-8");
|
||||
skillContent = skillContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`);
|
||||
skillContent = skillContent.replace(/v[\d.]+: 合思/g, `v${nextVersion}: 合思`);
|
||||
skillContent = skillContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
|
||||
skillContent = skillContent.replace(/\(v[\d.]+\)/g, `(v${nextVersion})`);
|
||||
writeFileSync(skillPath, skillContent);
|
||||
console.log("✓ Updated skills/hose-use/SKILL.md");
|
||||
|
||||
// 4. specs/openapi/openapi.yaml
|
||||
const openapiPath = join(ROOT, "specs", "openapi", "openapi.yaml");
|
||||
if (existsSync(openapiPath)) {
|
||||
let openapiContent = readFileSync(openapiPath, "utf-8");
|
||||
openapiContent = openapiContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
|
||||
writeFileSync(openapiPath, openapiContent);
|
||||
console.log("✓ Updated specs/openapi/openapi.yaml");
|
||||
}
|
||||
|
||||
// 4.5 .zcode-plugin/plugin.json
|
||||
const pluginJsonPath = join(ROOT, ".zcode-plugin", "plugin.json");
|
||||
if (existsSync(pluginJsonPath)) {
|
||||
const pluginJson = JSON.parse(readFileSync(pluginJsonPath, "utf-8"));
|
||||
pluginJson.version = nextVersion;
|
||||
writeFileSync(pluginJsonPath, JSON.stringify(pluginJson, null, 2) + "\n");
|
||||
console.log("✓ Updated .zcode-plugin/plugin.json");
|
||||
}
|
||||
|
||||
// 5. Sync to global ~/.agents/skills/hose-use/ if present
|
||||
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "hose-use");
|
||||
if (existsSync(globalSkillDir)) {
|
||||
const srcDir = join(ROOT, "skills", "hose-use");
|
||||
for (const item of readdirSync(srcDir)) {
|
||||
cpSync(join(srcDir, item), join(globalSkillDir, item), { recursive: true, force: true });
|
||||
if (!input) {
|
||||
console.error("Usage: bun run bump <version | patch | minor | major>");
|
||||
console.error(`Current version: ${currentVersion}`);
|
||||
throw new Error("A release version is required");
|
||||
}
|
||||
console.log("✓ Synchronized ~/.agents/skills/hose-use/");
|
||||
|
||||
let nextVersion = input.replace(/^v/, "");
|
||||
if (input === "patch" || input === "minor" || input === "major") {
|
||||
const [major, minor, patch] = currentVersion.split("-")[0].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 (!isReleaseVersion(nextVersion)) throw new Error(`Invalid SemVer format: '${nextVersion}'`);
|
||||
if (Bun.semver.order(nextVersion, currentVersion) <= 0) throw new Error(`Version must increase: ${currentVersion} -> ${nextVersion}`);
|
||||
const git = (args: string[]) => execFileSync("git", args, { cwd: ROOT, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
||||
if (git(["status", "--porcelain"])) throw new Error("Release preparation requires a clean working tree");
|
||||
const branch = git(["branch", "--show-current"]);
|
||||
if (!["codex/release-v", "release/v"].some(prefix => branch === `${prefix}${nextVersion}`)) {
|
||||
throw new Error(`Prepare the release on codex/release-v${nextVersion} or release/v${nextVersion}; current branch: ${branch || "detached HEAD"}`);
|
||||
}
|
||||
if (git(["tag", "--list", `v${nextVersion}`])) throw new Error(`Tag v${nextVersion} already exists`);
|
||||
// Read all versioned sources before writing any of them.
|
||||
for (const file of ["README.md", "skills/hose-use/SKILL.md"]) readFileSync(join(ROOT, file), "utf8");
|
||||
for (const file of ["specs/openapi/openapi.yaml", ".zcode-plugin/plugin.json"]) {
|
||||
if (existsSync(join(ROOT, file))) {
|
||||
const content = readFileSync(join(ROOT, file), "utf8");
|
||||
if (file.endsWith(".json")) JSON.parse(content);
|
||||
}
|
||||
}
|
||||
|
||||
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. README.md
|
||||
const readmePath = join(ROOT, "README.md");
|
||||
let readmeContent = readFileSync(readmePath, "utf-8");
|
||||
readmeContent = readmeContent.replace(/# hose-use \(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `# hose-use (v${nextVersion})`);
|
||||
writeFileSync(readmePath, readmeContent);
|
||||
console.log("✓ Updated README.md");
|
||||
|
||||
// 3. skills/hose-use/SKILL.md
|
||||
const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md");
|
||||
let skillContent = readFileSync(skillPath, "utf-8");
|
||||
skillContent = skillContent.replace(/# hose-use \(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `# hose-use (v${nextVersion})`);
|
||||
skillContent = skillContent.replace(/v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?: 合思/g, `v${nextVersion}: 合思`);
|
||||
skillContent = skillContent.replace(/version: \d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?/g, `version: ${nextVersion}`);
|
||||
skillContent = skillContent.replace(/\(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `(v${nextVersion})`);
|
||||
writeFileSync(skillPath, skillContent);
|
||||
console.log("✓ Updated skills/hose-use/SKILL.md");
|
||||
|
||||
// 4. specs/openapi/openapi.yaml
|
||||
const openapiPath = join(ROOT, "specs", "openapi", "openapi.yaml");
|
||||
if (existsSync(openapiPath)) {
|
||||
let openapiContent = readFileSync(openapiPath, "utf-8");
|
||||
openapiContent = openapiContent.replace(/version: \d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?/g, `version: ${nextVersion}`);
|
||||
writeFileSync(openapiPath, openapiContent);
|
||||
console.log("✓ Updated specs/openapi/openapi.yaml");
|
||||
}
|
||||
|
||||
// 4.5 .zcode-plugin/plugin.json
|
||||
const pluginJsonPath = join(ROOT, ".zcode-plugin", "plugin.json");
|
||||
if (existsSync(pluginJsonPath)) {
|
||||
const pluginJson = JSON.parse(readFileSync(pluginJsonPath, "utf-8"));
|
||||
pluginJson.version = nextVersion;
|
||||
writeFileSync(pluginJsonPath, JSON.stringify(pluginJson, null, 2) + "\n");
|
||||
console.log("✓ Updated .zcode-plugin/plugin.json");
|
||||
}
|
||||
|
||||
// 5. Sync to global ~/.agents/skills/hose-use/ is now an explicit dev:override step.
|
||||
// A version bump must not overwrite personal Skill files in the user's environment.
|
||||
|
||||
// 7. Rebuild OpenAPI and plugin bundles so generated artifacts stay in lockstep.
|
||||
console.log("==> Rebuilding OpenAPI and plugin bundles...");
|
||||
rebuild();
|
||||
|
||||
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
|
||||
console.log("\nNext steps to publish:");
|
||||
console.log(` 1. Review the diff, then run bun test && bun run check && bun run check:version`);
|
||||
console.log(` 2. Commit on ${branch}, push that branch and open a PR to main`);
|
||||
console.log(` 3. Wait for CI and review, then merge the PR`);
|
||||
console.log(` 4. Switch to main; git pull --ff-only origin main; git push home main`);
|
||||
console.log(` 5. Create annotated tag v${nextVersion} on the merged release commit`);
|
||||
console.log(` 6. git push home refs/tags/v${nextVersion} (first), then git push origin refs/tags/v${nextVersion}`);
|
||||
console.log(` 7. Verify the Release build, binary archives and checksums on both sources`);
|
||||
console.log(` Optional: bun run dev:override to explicitly sync your global development binary and Skill`);
|
||||
return nextVersion;
|
||||
}
|
||||
|
||||
// 7. Rebuild OpenAPI and plugin bundles so generated artifacts stay in lockstep.
|
||||
console.log("==> Rebuilding OpenAPI and plugin bundles...");
|
||||
execSync("bun run openapi:all", { cwd: ROOT, stdio: "inherit" });
|
||||
execSync("bun run build:plugin", { cwd: ROOT, stdio: "inherit" });
|
||||
export function isReleaseVersion(value: string): boolean {
|
||||
const match = value.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*))?$/);
|
||||
return !!match && (!match[4] || match[4].split(".").every(part => !/^0\d+$/.test(part)));
|
||||
}
|
||||
|
||||
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
|
||||
console.log("\nNext steps to publish:");
|
||||
console.log(` 1. Update CHANGELOG.md (if exists)`);
|
||||
console.log(` 2. git commit -am "chore(release): bump version to v${nextVersion}"`);
|
||||
console.log(` 3. git tag -a v${nextVersion} -m "🚀 Release v${nextVersion}"`);
|
||||
console.log(` 4. git push origin <feature-branch>\n`);
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
bumpVersion(join(import.meta.dirname, ".."), process.argv[2]?.trim() || "");
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : String(error));
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
+119
-78
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
set -e
|
||||
set -euo pipefail
|
||||
|
||||
REPO="yunyingk/hose-use"
|
||||
|
||||
@@ -34,9 +34,10 @@ case "$ARCH" in
|
||||
esac
|
||||
|
||||
# Resolve best writable bin directory without requiring sudo
|
||||
TARGET_DIR=""
|
||||
TARGET_DIR="${HOSE_USE_INSTALL_DIR:-}"
|
||||
if [ -n "$TARGET_DIR" ]; then mkdir -p "$TARGET_DIR"; fi
|
||||
for candidate in "/opt/homebrew/bin" "/usr/local/bin" "$HOME/.local/bin" "$HOME/bin"; do
|
||||
if [ -d "$candidate" ] && [ -w "$candidate" ]; then
|
||||
if [ -z "$TARGET_DIR" ] && [ -d "$candidate" ] && [ -w "$candidate" ]; then
|
||||
TARGET_DIR="$candidate"
|
||||
break
|
||||
fi
|
||||
@@ -49,6 +50,10 @@ fi
|
||||
|
||||
ASSET_NAME="hose-use-${PLATFORM}-${ARCH_NAME}"
|
||||
TARGET_PATH="${TARGET_DIR}/hose-use"
|
||||
if [ -d "$TARGET_PATH" ] || { [ -d "${TARGET_DIR}/hose-aipro" ] && [ ! -L "${TARGET_DIR}/hose-aipro" ]; }; then
|
||||
echo "Error: an install target is a directory; refusing to replace it." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
get_file_size() {
|
||||
local file="$1"
|
||||
@@ -102,7 +107,7 @@ download_candidate() {
|
||||
if curl -fL --progress-bar "$url" -o "$dest"; then
|
||||
local size_bytes
|
||||
size_bytes="$(get_file_size "$dest")"
|
||||
if [ "$size_bytes" -gt 1000000 ]; then
|
||||
if [ "$size_bytes" -gt 0 ]; then
|
||||
echo "✓ Download complete! Total size: $(format_bytes "$size_bytes")"
|
||||
echo "✓ Successfully fetched from host: ${host}"
|
||||
return 0
|
||||
@@ -114,103 +119,139 @@ download_candidate() {
|
||||
}
|
||||
|
||||
echo "==> Target install location: ${TARGET_PATH}"
|
||||
TMP_FILE="$(mktemp)"
|
||||
TMP_DIR="$(mktemp -d)"
|
||||
TMP_FILE="${TMP_DIR}/download"
|
||||
CHECKSUM_FILE="${TMP_DIR}/checksums.txt"
|
||||
INSTALL_STAGE=""
|
||||
trap 'rm -rf "$TMP_DIR"; if [ -n "$INSTALL_STAGE" ]; then rm -f "$INSTALL_STAGE"; fi' EXIT
|
||||
DOWNLOAD_SUCCESS=false
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
|
||||
# Resolve latest Gitea tag if available
|
||||
GITEA_API_URL="https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest"
|
||||
LATEST_TAG=""
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
LATEST_TAG="$(curl -sL --connect-timeout 3 "$GITEA_API_URL" | sed -n 's/.*"tag_name":"\([^"]*\)".*/\1/p' || true)"
|
||||
if ! command -v curl >/dev/null 2>&1; then
|
||||
echo "Error: curl is required." >&2
|
||||
exit 1
|
||||
fi
|
||||
[ -z "$LATEST_TAG" ] && LATEST_TAG="v0.8.9"
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
hash_file() { sha256sum "$1" | awk '{ print tolower($1) }'; }
|
||||
elif command -v shasum >/dev/null 2>&1; then
|
||||
hash_file() { shasum -a 256 "$1" | awk '{ print tolower($1) }'; }
|
||||
else
|
||||
echo "Error: SHA-256 verification requires sha256sum or shasum." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
MIRROR="${HOSE_USE_MIRROR:-auto}"
|
||||
case "$MIRROR" in auto|github|gitea) ;; *) echo "Invalid HOSE_USE_MIRROR: $MIRROR" >&2; exit 1 ;; esac
|
||||
|
||||
# Resolve latest Gitea tag if available. Resolve once, then pin every mirror and
|
||||
# checksum request to that exact version instead of guessing an old release.
|
||||
GITEA_API_URL="https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest"
|
||||
GITHUB_API_URL="https://api.github.com/repos/${REPO}/releases/latest"
|
||||
LATEST_TAG="${HOSE_USE_VERSION:-}"
|
||||
if [ -n "$LATEST_TAG" ]; then
|
||||
LATEST_TAG="v${LATEST_TAG#v}"
|
||||
else
|
||||
api_urls=()
|
||||
if [ "$MIRROR" != "github" ]; then api_urls+=("$GITEA_API_URL"); fi
|
||||
if [ "$MIRROR" != "gitea" ]; then api_urls+=("$GITHUB_API_URL"); fi
|
||||
for api_url in "${api_urls[@]}"; do
|
||||
if release_json=$(curl -fsSL --connect-timeout 4 --max-time 15 "$api_url"); then
|
||||
LATEST_TAG=$(printf '%s' "$release_json" | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^" ]*\)".*/\1/p' | head -n 1)
|
||||
if [ -n "$LATEST_TAG" ]; then break; fi
|
||||
fi
|
||||
done
|
||||
fi
|
||||
if ! [[ "$LATEST_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ ]]; then
|
||||
echo "Error: could not resolve a release version; set HOSE_USE_VERSION explicitly." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
release_bases=()
|
||||
if [ "$MIRROR" != "github" ]; then release_bases+=("https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}"); fi
|
||||
if [ "$MIRROR" != "gitea" ]; then
|
||||
release_bases+=("https://github.com/${REPO}/releases/download/${LATEST_TAG}")
|
||||
release_bases+=("https://ghfast.top/https://github.com/${REPO}/releases/download/${LATEST_TAG}")
|
||||
fi
|
||||
|
||||
verified_download() {
|
||||
local base="$1" asset="$2" expected actual
|
||||
if ! download_candidate "${base}/checksums.txt" "$CHECKSUM_FILE" "Release checksums"; then
|
||||
echo " ↳ Missing checksums.txt for ${LATEST_TAG}; refusing an unverified install." >&2
|
||||
return 1
|
||||
fi
|
||||
expected=$(awk -v name="$asset" '{ sub(/\r$/, "") } $2 == name || $2 == "*" name { count++; if (length($1) == 64 && $1 ~ /^[0-9a-fA-F]+$/) value=tolower($1); else invalid=1 } END { if (count == 1 && !invalid) print value; else exit 1 }' "$CHECKSUM_FILE") || {
|
||||
echo " ↳ Missing or ambiguous checksum for ${asset}." >&2
|
||||
return 1
|
||||
}
|
||||
if ! download_candidate "${base}/${asset}" "$TMP_FILE" "Release ${LATEST_TAG}"; then return 1; fi
|
||||
actual=$(hash_file "$TMP_FILE")
|
||||
if [ "$actual" != "$expected" ]; then
|
||||
echo " ↳ SHA-256 mismatch for ${asset}; refusing this download." >&2
|
||||
return 1
|
||||
fi
|
||||
echo "✓ SHA-256 verified: ${asset}"
|
||||
}
|
||||
|
||||
# 1. First priority: Compressed Archives (.tar.gz) - fast download & includes aliases
|
||||
GITEA_ARCHIVE_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}/${ASSET_NAME}.tar.gz"
|
||||
GITHUB_ARCHIVE_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}.tar.gz"
|
||||
GHPROXY_ARCHIVE_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}.tar.gz"
|
||||
|
||||
if [ "${HOSE_USE_MIRROR:-auto}" = "gitea" ] || [ "${HOSE_USE_MIRROR:-auto}" = "auto" ]; then
|
||||
if download_candidate "$GITEA_ARCHIVE_URL" "$TMP_FILE" "Gitea High-Speed Mirror (Archive)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GITHUB_ARCHIVE_URL" "$TMP_FILE" "GitHub Releases (Archive Direct)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GHPROXY_ARCHIVE_URL" "$TMP_FILE" "Fast CDN Mirror (Archive Fallback)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 2. Second priority: Raw Executable (Fallback)
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
GITEA_RAW_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}/${ASSET_NAME}"
|
||||
GITHUB_RAW_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
GHPROXY_RAW_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
|
||||
if [ "${HOSE_USE_MIRROR:-auto}" = "gitea" ] || [ "${HOSE_USE_MIRROR:-auto}" = "auto" ]; then
|
||||
if download_candidate "$GITEA_RAW_URL" "$TMP_FILE" "Gitea High-Speed Mirror (Raw Binary)"; then
|
||||
# 2. Second priority: Raw Executable (Fallback), with the same checksum requirement.
|
||||
for format in archive raw; do
|
||||
asset="$ASSET_NAME"
|
||||
if [ "$format" = "archive" ]; then asset="${asset}.tar.gz"; fi
|
||||
for base in "${release_bases[@]}"; do
|
||||
if verified_download "$base" "$asset"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
DOWNLOADED_FORMAT="$format"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GITHUB_RAW_URL" "$TMP_FILE" "GitHub Releases (Raw Direct)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GHPROXY_RAW_URL" "$TMP_FILE" "Fast CDN Mirror (Raw Fallback)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
done
|
||||
if [ "$DOWNLOAD_SUCCESS" = "true" ]; then break; fi
|
||||
done
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
echo "Error: Failed to download ${ASSET_NAME} from all candidate mirrors." >&2
|
||||
rm -f "$TMP_FILE"
|
||||
echo "Error: Failed to obtain a verified ${ASSET_NAME} for ${LATEST_TAG} from all candidate mirrors." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOADED_FORMAT" = "archive" ]; then
|
||||
echo "==> Extracting archive to ${TARGET_DIR}..."
|
||||
tar -xzf "$TMP_FILE" -C "$TARGET_DIR"
|
||||
rm -f "$TMP_FILE"
|
||||
chmod +x "$TARGET_PATH"
|
||||
[ -f "${TARGET_DIR}/hose-aipro" ] && chmod +x "${TARGET_DIR}/hose-aipro"
|
||||
echo "==> Extracting selected binary in temporary staging..."
|
||||
member=""
|
||||
listing=$(tar -tzf "$TMP_FILE")
|
||||
for candidate in "$ASSET_NAME" "./$ASSET_NAME" hose-use ./hose-use; do
|
||||
if printf '%s\n' "$listing" | awk -v name="$candidate" '$0 == name { count++ } END { exit count != 1 }'; then
|
||||
member="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ -z "$member" ]; then echo "Error: release archive has no expected platform binary." >&2; exit 1; fi
|
||||
# Stream only the exact member; archive paths and aliases never get written to bin.
|
||||
tar -xOzf "$TMP_FILE" "$member" > "${TMP_DIR}/hose-use"
|
||||
if [ ! -s "${TMP_DIR}/hose-use" ]; then echo "Error: release binary is empty." >&2; exit 1; fi
|
||||
else
|
||||
chmod +x "$TMP_FILE"
|
||||
mv "$TMP_FILE" "$TARGET_PATH"
|
||||
# Create hose-aipro multicall alias pointing at the single binary.
|
||||
if [ -w "$TARGET_DIR" ]; then
|
||||
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
|
||||
fi
|
||||
mv "$TMP_FILE" "${TMP_DIR}/hose-use"
|
||||
fi
|
||||
|
||||
# Stage on the target filesystem so the final rename is atomic.
|
||||
INSTALL_STAGE=$(mktemp "${TARGET_DIR}/.hose-use-install.XXXXXX")
|
||||
cp "${TMP_DIR}/hose-use" "$INSTALL_STAGE"
|
||||
chmod 755 "$INSTALL_STAGE"
|
||||
# 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
|
||||
[ -f "${TARGET_DIR}/hose-aipro" ] && codesign --force --sign - "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
|
||||
codesign --force --sign - "$INSTALL_STAGE" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
mv -f "$INSTALL_STAGE" "$TARGET_PATH"
|
||||
INSTALL_STAGE=""
|
||||
# Create hose-aipro multicall alias pointing at the single binary.
|
||||
ln -sfn hose-use "${TARGET_DIR}/hose-aipro"
|
||||
|
||||
echo "==> Initializing agent skill to ~/.agents/skills/hose-use..."
|
||||
"$TARGET_PATH" skill install >/dev/null 2>&1 || true
|
||||
echo "✓ Agent skill installed to ~/.agents/skills/hose-use"
|
||||
if "$TARGET_PATH" skill install --yes; then
|
||||
echo "✓ Agent skill installed to ~/.agents/skills/hose-use"
|
||||
else
|
||||
echo "Error: binary installed to ${TARGET_PATH}, but Agent Skill installation failed. Retry: hose-use skill install --yes" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "✨ hose-use successfully installed to ${TARGET_PATH}!"
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdtempSync, mkdirSync, readFileSync, readlinkSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
const fixtures: string[] = [];
|
||||
afterEach(() => { for (const root of fixtures.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
const hash = (data: Buffer | string) => createHash("sha256").update(data).digest("hex");
|
||||
|
||||
function fixture(options: { badHash?: boolean; missingEntry?: boolean; duplicate?: boolean; rawOnly?: boolean } = {}) {
|
||||
const root = mkdtempSync(join(tmpdir(), "hose-installer-test-"));
|
||||
fixtures.push(root);
|
||||
const tools = join(root, "tools"), source = join(root, "release"), target = join(root, "bin");
|
||||
for (const dir of [tools, source, target]) mkdirSync(dir);
|
||||
const binary = `#!/bin/sh
|
||||
if [ "$1" = "skill" ]; then
|
||||
printf '%s\\n' "$*" > "$HOSE_FIXTURE_LOG"
|
||||
[ "$2" = "install" ] && [ "$3" = "--yes" ] || exit 10
|
||||
[ "\${HOSE_FIXTURE_SKILL_FAIL:-0}" != "1" ] || exit 3
|
||||
else
|
||||
printf 'hose-use v9.9.9\\n'
|
||||
fi
|
||||
`;
|
||||
const asset = "hose-use-linux-x64";
|
||||
writeFileSync(join(source, asset), binary, { mode: 0o755 });
|
||||
symlinkSync(asset, join(source, "hose-aipro"));
|
||||
writeFileSync(join(source, "unrelated.txt"), "must not reach the install directory");
|
||||
const archive = `${asset}.tar.gz`;
|
||||
expect(spawnSync("tar", ["-czf", join(source, archive), "-C", source, asset, "hose-aipro", "unrelated.txt"]).status).toBe(0);
|
||||
const entry = `${options.badHash ? "0".repeat(64) : hash(readFileSync(join(source, archive)))} ${archive}\n`;
|
||||
writeFileSync(join(source, "checksums.txt"), (options.missingEntry ? "" : entry + (options.duplicate ? entry : "")) + `${options.badHash ? "0".repeat(64) : hash(binary)} ${asset}\n`);
|
||||
if (options.rawOnly) rmSync(join(source, archive));
|
||||
const curl = `#!/bin/bash
|
||||
set -eu
|
||||
url=""; dest=""; head_only=false
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
-o) dest="$2"; shift 2 ;;
|
||||
--connect-timeout|--max-time) shift 2 ;;
|
||||
-fIs) head_only=true; shift ;;
|
||||
https://*) url="$1"; shift ;;
|
||||
*) shift ;;
|
||||
esac
|
||||
done
|
||||
printf '%s\\n' "$url" >> "$HOSE_FIXTURE_REQUESTS"
|
||||
if [ "\${HOSE_FIXTURE_GITEA_FAIL:-0}" = "1" ] && [[ "$url" == *git.ying-qing.cn* ]]; then exit 22; fi
|
||||
if [[ "$url" == */releases/latest ]]; then
|
||||
[ "\${HOSE_FIXTURE_NO_TAG:-0}" != "1" ] || exit 22
|
||||
printf '{"tag_name": "v9.9.9"}'
|
||||
exit 0
|
||||
fi
|
||||
name="\${url##*/}"
|
||||
if [ "$name" = "checksums.txt" ] && [ "\${HOSE_FIXTURE_NO_MANIFEST:-0}" = "1" ]; then exit 22; fi
|
||||
file="$HOSE_FIXTURE_SOURCE/$name"
|
||||
[ -f "$file" ] || exit 22
|
||||
if [ "$head_only" = "true" ]; then exit 0; fi
|
||||
if [ -n "$dest" ]; then cp "$file" "$dest"; else cat "$file"; fi
|
||||
`;
|
||||
writeFileSync(join(tools, "curl"), curl, { mode: 0o755 });
|
||||
writeFileSync(join(tools, "uname"), '#!/bin/sh\nif [ "$1" = "-s" ]; then echo Linux; else echo x86_64; fi\n', { mode: 0o755 });
|
||||
const run = (env: Record<string, string> = {}) => spawnSync("bash", [resolve(import.meta.dir, "install.sh")], {
|
||||
cwd: root,
|
||||
env: { ...process.env, PATH: `${tools}:${process.env.PATH}`, HOSE_USE_INSTALL_DIR: target, HOSE_USE_VERSION: "9.9.9", HOSE_USE_MIRROR: "auto", HOSE_FIXTURE_SOURCE: source, HOSE_FIXTURE_LOG: join(root, "skill.log"), HOSE_FIXTURE_REQUESTS: join(root, "requests.log"), ...env },
|
||||
encoding: "utf8", timeout: 10_000,
|
||||
});
|
||||
return { root, source, target, run, binary };
|
||||
}
|
||||
|
||||
describe("verified standalone installer", () => {
|
||||
test("installs a platform-named archive and alias, then explicitly confirms Skill setup", () => {
|
||||
const f = fixture();
|
||||
const result = f.run();
|
||||
expect(result.status).toBe(0);
|
||||
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe(f.binary);
|
||||
expect(readlinkSync(join(f.target, "hose-aipro"))).toBe("hose-use");
|
||||
expect(readFileSync(join(f.root, "skill.log"), "utf8").trim()).toBe("skill install --yes");
|
||||
expect(readdirSync(f.target).sort()).toEqual(["hose-aipro", "hose-use"]);
|
||||
});
|
||||
|
||||
for (const options of [{ badHash: true }, { missingEntry: true }, { duplicate: true }]) {
|
||||
test(`rejects an invalid manifest/archive and preserves the old binary: ${JSON.stringify(options)}`, () => {
|
||||
const f = fixture(options);
|
||||
// Remove raw fallback, so a missing archive entry cannot be hidden by another valid asset.
|
||||
rmSync(join(f.source, "hose-use-linux-x64"));
|
||||
writeFileSync(join(f.target, "hose-use"), "old binary");
|
||||
const result = f.run();
|
||||
expect(result.status).toBe(1);
|
||||
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe("old binary");
|
||||
expect(existsSync(join(f.root, "skill.log"))).toBe(false);
|
||||
});
|
||||
}
|
||||
|
||||
test("does not silently bypass missing checksums or guess an old tag", () => {
|
||||
const f = fixture();
|
||||
expect(f.run({ HOSE_FIXTURE_NO_MANIFEST: "1" }).status).toBe(1);
|
||||
const unknown = f.run({ HOSE_USE_VERSION: "", HOSE_FIXTURE_NO_TAG: "1" });
|
||||
expect(unknown.status).toBe(1);
|
||||
expect(unknown.stderr).toContain("could not resolve");
|
||||
expect(existsSync(join(f.target, "hose-use"))).toBe(false);
|
||||
expect(readFileSync(join(f.root, "requests.log"), "utf8")).not.toContain("v0.8.9");
|
||||
});
|
||||
|
||||
test("uses a verified raw fallback and a fixed tag when the first mirror fails", () => {
|
||||
const f = fixture({ rawOnly: true });
|
||||
const result = f.run({ HOSE_FIXTURE_GITEA_FAIL: "1", HOSE_USE_VERSION: "" });
|
||||
expect(result.status).toBe(0);
|
||||
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe(f.binary);
|
||||
const requests = readFileSync(join(f.root, "requests.log"), "utf8");
|
||||
expect(requests).toContain("/download/v9.9.9/");
|
||||
expect(requests).not.toContain("/latest/download/");
|
||||
});
|
||||
|
||||
test("reports Skill failure without claiming it was installed", () => {
|
||||
const f = fixture();
|
||||
const result = f.run({ HOSE_FIXTURE_SKILL_FAIL: "1" });
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain("binary installed");
|
||||
expect(result.stdout).not.toContain("Agent skill installed");
|
||||
expect(result.stdout).not.toContain("successfully installed");
|
||||
});
|
||||
|
||||
test("does not replace directories or follow an existing alias into a directory", () => {
|
||||
const f = fixture();
|
||||
mkdirSync(join(f.root, "personal"));
|
||||
symlinkSync(join(f.root, "personal"), join(f.target, "hose-aipro"));
|
||||
expect(f.run().status).toBe(0);
|
||||
expect(readdirSync(join(f.root, "personal"))).toEqual([]);
|
||||
expect(readlinkSync(join(f.target, "hose-aipro"))).toBe("hose-use");
|
||||
rmSync(join(f.target, "hose-aipro"));
|
||||
mkdirSync(join(f.target, "hose-aipro"));
|
||||
writeFileSync(join(f.target, "hose-use"), "old binary");
|
||||
expect(f.run().status).toBe(1);
|
||||
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe("old binary");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { parse } from "yaml";
|
||||
import { bumpVersion } from "./bump-version.js";
|
||||
import { verifyReleaseTag } from "./verify-release.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
|
||||
function repository() {
|
||||
const root = mkdtempSync(join(tmpdir(), "hose-release-test-"));
|
||||
roots.push(root);
|
||||
const git = (...args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
||||
git("init", "--initial-branch=main");
|
||||
git("config", "user.name", "Release fixture");
|
||||
git("config", "user.email", "fixture@example.test");
|
||||
git("config", "core.hooksPath", "/dev/null");
|
||||
git("config", "commit.gpgsign", "false");
|
||||
git("config", "tag.gpgsign", "false");
|
||||
for (const dir of ["skills/hose-use", "specs/openapi", ".zcode-plugin"]) mkdirSync(join(root, dir), { recursive: true });
|
||||
writeFileSync(join(root, "package.json"), '{"version":"1.0.0"}\n');
|
||||
writeFileSync(join(root, "README.md"), "# hose-use (v1.0.0)\n");
|
||||
writeFileSync(join(root, "skills/hose-use/SKILL.md"), "version: 1.0.0\n# hose-use (v1.0.0)\n");
|
||||
writeFileSync(join(root, "specs/openapi/openapi.yaml"), "info:\n version: 1.0.0\n");
|
||||
writeFileSync(join(root, ".zcode-plugin/plugin.json"), '{"version":"1.0.0"}\n');
|
||||
git("add", ".");
|
||||
git("commit", "-m", "fixture");
|
||||
git("update-ref", "refs/remotes/origin/main", "HEAD");
|
||||
return { root, git, version: () => JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version };
|
||||
}
|
||||
|
||||
describe("release preparation and publication guards", () => {
|
||||
test("bump rejects wrong branches, dirty trees and invalid/non-increasing versions before writes", () => {
|
||||
const f = repository();
|
||||
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("release-v1.0.1");
|
||||
f.git("switch", "-c", "codex/release-v1.0.1");
|
||||
writeFileSync(join(f.root, "untracked.txt"), "work in progress");
|
||||
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("clean working tree");
|
||||
rmSync(join(f.root, "untracked.txt"));
|
||||
for (const version of ["1.0.0", "0.9.9", "1.0.01", "1.0.1-rc.01", "invalid"]) expect(() => bumpVersion(f.root, version, () => {})).toThrow();
|
||||
expect(f.version()).toBe("1.0.0");
|
||||
expect(f.git("status", "--porcelain")).toBe("");
|
||||
});
|
||||
|
||||
test("bump updates sources on its release branch and explicitly invokes regeneration", () => {
|
||||
const f = repository();
|
||||
f.git("switch", "-c", "release/v1.0.1");
|
||||
let rebuilt = false;
|
||||
expect(bumpVersion(f.root, "patch", () => { rebuilt = true; })).toBe("1.0.1");
|
||||
expect(rebuilt).toBe(true);
|
||||
expect(f.version()).toBe("1.0.1");
|
||||
expect(readFileSync(join(f.root, "skills/hose-use/SKILL.md"), "utf8")).toContain("version: 1.0.1");
|
||||
expect(parse(readFileSync(join(f.root, "specs/openapi/openapi.yaml"), "utf8")).info.version).toBe("1.0.1");
|
||||
});
|
||||
|
||||
test("an existing release tag cannot be reused during bump", () => {
|
||||
const f = repository();
|
||||
f.git("switch", "-c", "release/v1.0.1");
|
||||
f.git("tag", "v1.0.1");
|
||||
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("already exists");
|
||||
expect(f.version()).toBe("1.0.0");
|
||||
});
|
||||
|
||||
test("publication validates the actual HEAD, main ancestry and package version", () => {
|
||||
const f = repository();
|
||||
f.git("tag", "v1.0.0");
|
||||
expect(() => verifyReleaseTag(f.root, "v1.0.0")).not.toThrow();
|
||||
expect(() => verifyReleaseTag(f.root, "main")).toThrow("Invalid release tag");
|
||||
f.git("tag", "v9.9.9");
|
||||
expect(() => verifyReleaseTag(f.root, "v9.9.9")).toThrow("does not match");
|
||||
f.git("switch", "-c", "unmerged");
|
||||
writeFileSync(join(f.root, "change"), "unreviewed");
|
||||
f.git("add", "."); f.git("commit", "-m", "unmerged fixture");
|
||||
expect(() => verifyReleaseTag(f.root, "v1.0.0")).toThrow("exact tagged commit");
|
||||
f.git("tag", "v1.0.1");
|
||||
expect(() => verifyReleaseTag(f.root, "v1.0.1")).toThrow("ancestor");
|
||||
});
|
||||
|
||||
test("workflows validate committed versions before generation and ship the checksum manifest", () => {
|
||||
const root = join(import.meta.dir, "..");
|
||||
const ci = parse(readFileSync(join(root, ".github/workflows/ci.yml"), "utf8"));
|
||||
const release = parse(readFileSync(join(root, ".github/workflows/release.yml"), "utf8"));
|
||||
expect(ci.on.pull_request.branches).toContain("main");
|
||||
expect(ci.permissions.contents).toBe("read");
|
||||
const steps = release.jobs["build-and-publish"].steps;
|
||||
const runs = steps.map((s: { run?: string }) => s.run || "");
|
||||
expect(runs.findIndex((s: string) => s.includes("check:version"))).toBeLessThan(runs.findIndex((s: string) => s.includes("openapi:all")));
|
||||
expect(steps[0].with.ref).toContain("inputs.tag");
|
||||
expect(runs.some((s: string) => s.includes("verify-release.ts"))).toBe(true);
|
||||
expect(runs.some((s: string) => s.includes("sha256sum hose-use-* > checksums.txt"))).toBe(true);
|
||||
for (const step of [...ci.jobs.validate.steps, ...steps]) if (step.uses) expect(step.uses).toMatch(/@[a-f0-9]{40}$/);
|
||||
expect(JSON.parse(readFileSync(join(root, ".mcp.json"), "utf8")).mcpServers["hose-use"].command).toBe("bun");
|
||||
});
|
||||
|
||||
test("a failed background Gitea upload makes the Release step fail", () => {
|
||||
const f = repository();
|
||||
const workflow = parse(readFileSync(join(import.meta.dir, "../.github/workflows/release.yml"), "utf8"));
|
||||
const step = workflow.jobs["build-and-publish"].steps.find((s: { name?: string }) => s.name === "Publish Gitea Release");
|
||||
mkdirSync(join(f.root, "tools")); mkdirSync(join(f.root, "dist/bin"), { recursive: true });
|
||||
writeFileSync(join(f.root, "dist/bin/hose-use-linux-x64"), "fixture");
|
||||
writeFileSync(join(f.root, "dist/bin/checksums.txt"), "fixture checksums");
|
||||
writeFileSync(join(f.root, "tools/curl"), `#!/bin/sh
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
*/assets?*) exit 22 ;;
|
||||
*/releases) printf '{"id":42}'; exit 0 ;;
|
||||
*/releases/42) printf '{"assets":[]}'; exit 0 ;;
|
||||
esac
|
||||
done
|
||||
exit 22
|
||||
`, { mode: 0o755 });
|
||||
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 5000 });
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toContain("assets failed to upload");
|
||||
expect(result.stdout).not.toContain("Successfully published");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env bun
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { resolve, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
|
||||
const binary = resolve(process.argv[2] || "dist/bin/hose-use");
|
||||
const plugin = process.argv.includes("--plugin");
|
||||
const command = plugin ? process.execPath : binary;
|
||||
const prefix = plugin ? [binary] : [];
|
||||
const cwd = mkdtempSync(join(tmpdir(), "hose-binary-smoke-"));
|
||||
// The binary must work without Bun on PATH or a source checkout in cwd.
|
||||
const env = { PATH: process.platform === "win32" ? process.env.SystemRoot || "C:\\Windows" : "/usr/bin:/bin", HOSE_USE_MCP_ENABLED: "true", HOSE_CONFIG_FILE: join(cwd, "config.json"), HOSE_ENTERPRISES_DIR: cwd };
|
||||
const client = new Client({ name: "hose-binary-smoke", version: "1.0.0" });
|
||||
const transport = new StdioClientTransport({ command, args: plugin ? prefix : ["mcp", "serve"], cwd, env, stderr: "pipe" });
|
||||
let stderr = "";
|
||||
transport.stderr?.on("data", chunk => { stderr += chunk.toString(); });
|
||||
const deadline = setTimeout(() => { void client.close(); }, 15_000);
|
||||
try {
|
||||
const version = spawnSync(command, [...prefix, ...(plugin ? ["--hose-use-cli"] : []), "version", "--json"], { cwd, env, encoding: "utf8", timeout: 5000 });
|
||||
assert.equal(version.status, 0, version.stderr);
|
||||
assert.ok(JSON.parse(version.stdout).version);
|
||||
await client.connect(transport, { timeout: 5000 });
|
||||
const tools = await client.listTools();
|
||||
assert.deepEqual(tools.tools.map(tool => tool.name), ["hose_cli"]);
|
||||
const result = await client.callTool({ name: "hose_cli", arguments: { command: "version --json" } });
|
||||
assert.ok(!result.isError, JSON.stringify(result));
|
||||
const text = (result.content as Array<{ type: string; text?: string }>).find(c => c.type === "text")?.text;
|
||||
assert.equal(JSON.parse(text || "").version, JSON.parse(version.stdout).version);
|
||||
const invalid = await client.callTool({ name: "hose_cli", arguments: { command: "bill list --limitt 5 --json" } });
|
||||
assert.equal(invalid.isError, true);
|
||||
assert.match(JSON.stringify(invalid.content), /未知选项/);
|
||||
console.log(plugin ? "Plugin bundle version and MCP stdio verified with its Bun runtime." : "Binary version and MCP stdio verified without Bun or source files.");
|
||||
} catch (error) {
|
||||
throw new Error(`Binary smoke failed: ${error instanceof Error ? error.message : error}\n${stderr}`);
|
||||
} finally {
|
||||
clearTimeout(deadline);
|
||||
await client.close();
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bun
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { isReleaseVersion } from "./bump-version.js";
|
||||
|
||||
export function verifyReleaseTag(root: string, tag: string): void {
|
||||
if (!tag.startsWith("v") || !isReleaseVersion(tag.slice(1))) throw new Error(`Invalid release tag: ${tag}`);
|
||||
const git = (args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
||||
const taggedCommit = git(["rev-parse", "--verify", `refs/tags/${tag}^{commit}`]);
|
||||
if (git(["rev-parse", "HEAD"]) !== taggedCommit) throw new Error("Release HEAD must be the exact tagged commit");
|
||||
try {
|
||||
git(["merge-base", "--is-ancestor", taggedCommit, "refs/remotes/origin/main"]);
|
||||
} catch {
|
||||
throw new Error("Release tag must be an ancestor of origin/main; merge the PR before tagging");
|
||||
}
|
||||
const { version } = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8"));
|
||||
if (tag !== `v${version}`) throw new Error(`Release tag ${tag} does not match package.json v${version}`);
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
verifyReleaseTag(resolve(import.meta.dir, ".."), process.argv[2] || "");
|
||||
console.log("Release tag, HEAD, main ancestry and package version verified.");
|
||||
}
|
||||
+17
-4
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env bun
|
||||
import { parseArgs, stringOption, booleanOption } from "./cli/parser.js";
|
||||
import { printJson, redactSensitiveText } from "./cli/printer.js";
|
||||
import { parseArgs, stringOption, booleanOption, isJsonRequested } from "./cli/parser.js";
|
||||
import { cliErrorResult } from "./cli/runner.js";
|
||||
import { printHelp, printJson, redactSensitiveText } from "./cli/printer.js";
|
||||
import { getSessionClientForRuntime, initCorpRuntime, requireSelectedCorp } from "./cli/helpers.js";
|
||||
import {
|
||||
ApprovalService,
|
||||
@@ -27,10 +28,22 @@ import type { AiProExecutionContext } from "./cli/commands/aipro/types.js";
|
||||
export async function runAiProCli(
|
||||
rawArgs: string[]
|
||||
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
const parsed = parseArgs(rawArgs);
|
||||
try {
|
||||
return await runAiProCliOnce(rawArgs);
|
||||
} catch (error) {
|
||||
return cliErrorResult(error, isJsonRequested(rawArgs));
|
||||
}
|
||||
}
|
||||
|
||||
async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
const parsed = parseArgs(rawArgs, "aipro");
|
||||
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
|
||||
if (booleanOption(parsed.options, ["help", "h", "?"])) {
|
||||
const help = printHelp(["aipro", ...(parsed.area && parsed.area !== "help" ? [parsed.area] : [])]);
|
||||
return { stdout: jsonMode ? printJson({ help }) : `${help}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
const runtime = initCorpRuntime({
|
||||
corpId: stringOption(parsed.options, ["corp", "c"]),
|
||||
corpId: stringOption(parsed.options, ["corp"]),
|
||||
jsonMode,
|
||||
});
|
||||
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
|
||||
## 文件职责
|
||||
|
||||
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层命令唯一声明式注册表(`area` / `aliases` / `standing` 常驻属性 / `handler`)。新增命令先在此注册。
|
||||
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层处理器注册表(`area` / 共享命令元数据 / `standing` 常驻属性 / `handler`)。新增命令先声明元数据,再在此注册处理器。
|
||||
- `command-metadata.ts`:命令描述、用法、子命令及别名、布尔/取值选项的共享静态定义;不导入处理器,供分发、解析与帮助共用。
|
||||
- `runner.ts`:`runCli` 分发入口。按注册表查命令;非常驻命令经 `runQueue` 串行化执行,避免并发写冲突。
|
||||
- `parser.ts`:参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`)。
|
||||
- `parser.ts`:严格参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`);未知选项和缺值返回用法错误 `2`,相近拼写给出建议。同名参数按命令语境确定类型,例如 `bill --fields` 取值、`feetype --fields` 为布尔值,`workflow create -f` 取模板、`workflow tail -f` 为持续监听。
|
||||
- `printer.ts`:输出渲染(`printJson` / `printHelp` / `redactSensitiveText` 敏感信息脱敏)。
|
||||
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
|
||||
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
|
||||
@@ -25,3 +26,9 @@
|
||||
## 嵌入调用与流式输出
|
||||
|
||||
`runCli` 默认通过 `CliResult` 返回结果,不直接写进进程 stdout。终端入口可显式传入 `CliRunOptions.writeStdout` 异步回调;处理器必须等待回调完成,保证慢管道有背压。MCP / HTTP 不提供该回调,流式记录应使用 `--output-file`,否则返回用法错误。普通命令的返回结构保持不变。
|
||||
|
||||
参数解析与运行时初始化也经过统一异常边界。`--json` 的错误对象继续写入 `stdout`,保留退出码和恢复建议;人类日志写入 `stderr`。`help <域>`、`<域> --help` 支持同一份域别名,帮助主题不存在时返回用法错误。处理器自身保留的详细用法说明仍可供直接嵌入调用使用。
|
||||
|
||||
优先用 `--corp` 明确指定企业。短参数 `-c` 在命令之前表示全局企业选择;在声明了同名参数的命令之后,遵循该命令的含义(例如 `bill list -c` 为单号)。布尔值可写 `--active=false` 或 `--active false`;数字形式使用 `=0` / `=1`,空格后的数字保留为可能的位置 ID。`--` 之后的内容全部作为位置参数。
|
||||
|
||||
`hose-use mcp [serve]` 在当前进程启动服务,不派生 Bun 或访问源码脚本;MCP 调用继续只通过 `hose_cli` 分发,流式终端回调不会被注入协议通道。
|
||||
@@ -39,6 +39,17 @@ function resolveImportRelativeToSrc(fromFile: string, specifier: string): string
|
||||
}
|
||||
|
||||
describe("Architecture Layering Boundaries", () => {
|
||||
test("workflow imports use the module directories after the platform migration", () => {
|
||||
const legacy = /domains\/platform\/(?:analysis|workflow-(?:alert-store|branch|nodes|script|state|watch))$/;
|
||||
const violations: string[] = [];
|
||||
for (const file of collectTsFiles(SRC_ROOT, true)) {
|
||||
for (const specifier of extractImportSpecifiers(readFileSync(file, "utf8"))) {
|
||||
const target = resolveImportRelativeToSrc(file, specifier);
|
||||
if (target && legacy.test(target)) violations.push(`${relative(SRC_ROOT, file)} -> ${target}`);
|
||||
}
|
||||
}
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
test("Entrypoints (src/cli, src/http, server.ts, cli.ts, aipro-cli.ts) must never import domains/*/api directly", () => {
|
||||
const entrypointFiles = [
|
||||
...collectTsFiles(join(SRC_ROOT, "cli")),
|
||||
|
||||
@@ -0,0 +1,809 @@
|
||||
/** Static command vocabulary shared by dispatch, parsing and help. No handler imports. */
|
||||
export type FlagKind = "boolean" | "value" | "boolean-or-value";
|
||||
export interface HelpTopic {
|
||||
summary: string; usage: string; commands: Record<string, string>; options?: string[];
|
||||
}
|
||||
export interface CliCommandMetadata extends HelpTopic {
|
||||
aliases: string[]; commandAliases: Record<string, string>; flags: Record<string, FlagKind>;
|
||||
}
|
||||
|
||||
export const GLOBAL_FLAGS: Record<string, FlagKind> = {
|
||||
...Object.fromEntries("json j help h ? version v V full allow-full allowFull summary stateless stateful dry-run dryRun dryrun yes y confirm force-write forceWrite force".split(" ").map(k => [k, "boolean" as const])),
|
||||
...Object.fromEntries("corp c output-file outputFile o".split(" ").map(k => [k, "value" as const])),
|
||||
};
|
||||
|
||||
function flagList(keys: string, kind: FlagKind): Record<string, FlagKind> {
|
||||
return Object.fromEntries(keys.split(" ").filter(Boolean).map(key => [key, kind]));
|
||||
}
|
||||
|
||||
export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"context": {
|
||||
"summary": "全局运行上下文与身份诊断",
|
||||
"usage": "hose-use context [--json]",
|
||||
"commands": {
|
||||
"context": "输出当前企业、账号、运行模式与认证状态"
|
||||
},
|
||||
"aliases": [
|
||||
"status",
|
||||
"whoami",
|
||||
"env"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { }
|
||||
},
|
||||
"aipro": {
|
||||
"summary": "AI PRO 确定性审批仲裁",
|
||||
"usage": "hose-use aipro <子命令>",
|
||||
"commands": {
|
||||
"status": "查看网关状态",
|
||||
"bind": "绑定单据",
|
||||
"review": "核验要点",
|
||||
"decide": "执行仲裁",
|
||||
"init": "初始化审批上下文",
|
||||
"scopes": "列出审批规则场景",
|
||||
"translate": "转译单据",
|
||||
"rules": "查看审批规则",
|
||||
"points": "查看审核要点",
|
||||
"checklist": "查看核验清单",
|
||||
"logs": "查看审批日志",
|
||||
"help": "help 命令"
|
||||
},
|
||||
"aliases": [],
|
||||
"commandAliases": {
|
||||
"whoami": "status",
|
||||
"context": "status",
|
||||
"info": "status",
|
||||
"start": "init",
|
||||
"index": "scopes",
|
||||
"indexes": "scopes",
|
||||
"doc": "translate",
|
||||
"markdown": "translate",
|
||||
"render": "translate",
|
||||
"rule": "rules",
|
||||
"mount": "bind",
|
||||
"clauses": "points",
|
||||
"list": "checklist",
|
||||
"eval": "review",
|
||||
"evaluate": "review",
|
||||
"approve": "decide",
|
||||
"reject": "decide",
|
||||
"log": "logs",
|
||||
"history": "logs",
|
||||
"trail": "logs"
|
||||
},
|
||||
flags: { ...flagList("apply confirm do execute j json v version y yes", "boolean"), ...flagList("run a action c code codes comment corp e eval evidence findings i id index indexes limit m message n opinion p point proof r reason reasoning rule rules s scope scopes sn state status target 审批意见 意见", "value") }
|
||||
},
|
||||
"auth": {
|
||||
"summary": "认证与凭证管理(支持主账号登录与企业级 OpenAPI 持久化)",
|
||||
"usage": "hose-use auth <子命令>",
|
||||
"commands": {
|
||||
"login": "登录并保存企业凭证",
|
||||
"status": "查看当前认证状态",
|
||||
"refresh": "刷新账号或企业 AccessToken",
|
||||
"link": "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从协助链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
"elevate": "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
"accounts": "列出已保存账号",
|
||||
"switch-account": "切换默认账号",
|
||||
"import": "导入抓包或协助凭证",
|
||||
"hose-link": "生成企业免密登录链接",
|
||||
"sync-seal": "导入已保存的企业配置"
|
||||
},
|
||||
"aliases": [
|
||||
"login"
|
||||
],
|
||||
"commandAliases": {
|
||||
"whoami": "status",
|
||||
"current": "status",
|
||||
"renew": "refresh",
|
||||
"add": "import",
|
||||
"import-link": "add-link",
|
||||
"auth-link": "hose-link",
|
||||
"login-link": "hose-link",
|
||||
"add-hose-persistent": "add-persistent",
|
||||
"add-openapi": "add-persistent",
|
||||
"add-hose": "add-persistent",
|
||||
"extract-key": "extract-keys",
|
||||
"hose-extract-keys": "extract-keys",
|
||||
"extract-hose-keys": "extract-keys",
|
||||
"elevate-hose": "elevate",
|
||||
"sync-from-seal": "sync-seal",
|
||||
"import-seal": "sync-seal",
|
||||
"list": "accounts",
|
||||
"account": "accounts",
|
||||
"accs": "accounts",
|
||||
"switch": "switch-account",
|
||||
"use-account": "switch-account"
|
||||
},
|
||||
flags: { ...flagList("a p app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user accessToken account curl headers phone pwd raw token", "value"), ...flagList("add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite persist plain prod production r refresh reveal save save-staff t test upgrade-all verify i interactive sms sync", "boolean") }
|
||||
},
|
||||
"corps": {
|
||||
"summary": "多企业租户管理",
|
||||
"usage": "hose-use corps <子命令>",
|
||||
"commands": {
|
||||
"list": "列出本地企业配置",
|
||||
"search": "搜索企业与员工",
|
||||
"switch": "切换当前工作企业",
|
||||
"current": "查看当前企业",
|
||||
"link": "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
"elevate": "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
"tag": "标记企业环境",
|
||||
"hose-link": "生成企业免密登录链接",
|
||||
"sync-seal": "导入已有企业配置",
|
||||
"probe-hose": "检查企业接口连通性",
|
||||
"hose-staffs": "查询企业员工",
|
||||
"help": "help 命令"
|
||||
},
|
||||
"aliases": [
|
||||
"corp"
|
||||
],
|
||||
"commandAliases": {
|
||||
"ls": "list",
|
||||
"find": "search",
|
||||
"query": "search",
|
||||
"filter": "search",
|
||||
"set-env": "tag",
|
||||
"mark": "tag",
|
||||
"use": "switch",
|
||||
"whoami": "current",
|
||||
"status": "current",
|
||||
"active": "current",
|
||||
"import-link": "add-link",
|
||||
"auth-link": "hose-link",
|
||||
"login-link": "hose-link",
|
||||
"add-hose-persistent": "add-persistent",
|
||||
"add-openapi": "add-persistent",
|
||||
"add-hose": "add-persistent",
|
||||
"extract-key": "extract-keys",
|
||||
"hose-extract-keys": "extract-keys",
|
||||
"extract-hose-keys": "extract-keys",
|
||||
"elevate-hose": "elevate",
|
||||
"sync-from-seal": "sync-seal",
|
||||
"import-seal": "sync-seal"
|
||||
},
|
||||
flags: { ...flagList("a add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite p persist plain prod production r refresh reveal save save-staff t test upgrade-all verify", "boolean"), ...flagList("app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user", "value") }
|
||||
},
|
||||
"config": {
|
||||
"summary": "全局运行模式与路径配置",
|
||||
"usage": "hose-use config <子命令>",
|
||||
"commands": {
|
||||
"paths": "诊断配置目录链",
|
||||
"get": "查看全局配置",
|
||||
"mode": "切换 stateful/stateless",
|
||||
"set": "更新指定配置项",
|
||||
"test-dir": "设置测试企业目录"
|
||||
},
|
||||
"aliases": [
|
||||
"mode"
|
||||
],
|
||||
"commandAliases": {
|
||||
"path": "paths",
|
||||
"dirs": "paths",
|
||||
"show": "paths",
|
||||
"list": "paths",
|
||||
"status": "get",
|
||||
"info": "get",
|
||||
"test-enterprises-dir": "test-dir"
|
||||
},
|
||||
flags: { ...flagList("clear", "boolean") }
|
||||
},
|
||||
"workflow": {
|
||||
"summary": "工作流查询、草稿、运行排障与生命周期管理",
|
||||
"usage": "hose-use workflow <子命令> [参数] [选项]",
|
||||
"commands": {
|
||||
"list": "列出工作流",
|
||||
"get": "查看工作流详情",
|
||||
"find": "按节点类型搜索",
|
||||
"analyze": "静态分析工作流(含禁用/SKIP/联动覆盖检查)",
|
||||
"job": "查看单次运行实例树、报错节点与MVEL日志",
|
||||
"diff": "对比两个工作流快照的结构与脚本差异",
|
||||
"diff-job": "对比两次执行的节点分支与报错发散点",
|
||||
"test": "端到端一键调试单据(替代前端手工调测)",
|
||||
"node": "声明式节点编排与增删改 (list|get|add|edit|rm)",
|
||||
"tail": "实时监听任务派发与节点执行日志流 (watch|follow)",
|
||||
"create": "从零新建工作流草稿",
|
||||
"copy": "复制克隆工作流",
|
||||
"delete": "删除工作流",
|
||||
"patch": "生成草稿字段补丁",
|
||||
"save": "保存草稿到远端",
|
||||
"toggle": "切换启停状态",
|
||||
"publish": "发布并启用工作流",
|
||||
"history": "查看版本历史",
|
||||
"logs": "查看运行日志",
|
||||
"check": "检查错误管道",
|
||||
"enum": "查询在线枚举字典(不可用时使用内置字典)",
|
||||
"lint-script": "静态检查 JavaScript / MVEL 脚本",
|
||||
"eval-script": "在本地沙箱中模拟执行脚本"
|
||||
},
|
||||
"options": [
|
||||
"--flow=<单号> 指定测试单据",
|
||||
"--file=<workflow.json> 指定工作流快照",
|
||||
"--failed 只看失败节点",
|
||||
"--parent=<executionId> 展开循环/分支子节点",
|
||||
"--logs=<executionId> 查看节点执行日志",
|
||||
"--dry-run 只预览写操作",
|
||||
"--yes/--confirm 确认写操作"
|
||||
],
|
||||
"aliases": [
|
||||
"workflows",
|
||||
"wf"
|
||||
],
|
||||
"commandAliases": {
|
||||
"list-all": "list",
|
||||
"ls": "list",
|
||||
"detail": "get",
|
||||
"info": "get",
|
||||
"search": "find",
|
||||
"enable": "publish",
|
||||
"update": "save",
|
||||
"snapshots": "history",
|
||||
"log": "logs",
|
||||
"execution": "job",
|
||||
"health": "check",
|
||||
"analyse": "analyze",
|
||||
"diff-snapshot": "diff",
|
||||
"diff-snapshots": "diff",
|
||||
"compare": "diff",
|
||||
"diff-jobs": "diff-job",
|
||||
"compare-job": "diff-job",
|
||||
"debug": "test",
|
||||
"run-test": "test",
|
||||
"cp": "copy",
|
||||
"clone": "copy",
|
||||
"rm": "delete",
|
||||
"remove": "delete",
|
||||
"new": "create",
|
||||
"add": "create",
|
||||
"nodes": "node",
|
||||
"watch": "tail",
|
||||
"follow": "tail",
|
||||
"lint": "lint-script",
|
||||
"lint-code": "lint-script",
|
||||
"eval": "eval-script",
|
||||
"eval-code": "eval-script",
|
||||
"run-script": "eval-script",
|
||||
"enums": "enum",
|
||||
"dictionary": "enum",
|
||||
"dict": "enum"
|
||||
},
|
||||
flags: { ...flagList("allow-prod allow-production auto-publish autoPublish detail empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose", "boolean"), ...flagList("a after app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId l label log logs max-jobs maxJobs n name node node-id nodeId output output-file outputFile p page page-size pageSize parent parent-id parentId path payload pipeline pipeline-id pipelineId platform-id platformId record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type value workflowId", "value") }
|
||||
},
|
||||
"bill": {
|
||||
"summary": "单据检索、表单规格诊断与审批动作",
|
||||
"usage": "hose-use bill <子命令> [单号|ID] [选项]",
|
||||
"commands": {
|
||||
"list": "查询单据",
|
||||
"get": "查看单据详情",
|
||||
"spec": "查看单据模板字段配置与联动覆盖规则",
|
||||
"flow": "查看审批流程",
|
||||
"approve": "同意审批",
|
||||
"reject": "驳回审批",
|
||||
"transfer": "转交审批",
|
||||
"add-node": "加签审批",
|
||||
"comment": "添加评论",
|
||||
"trace": "穿透诊断单据与当前待办",
|
||||
"schema": "查看单据实体模型",
|
||||
"risk": "查看风险信息",
|
||||
"budget": "查看预算状态",
|
||||
"refs": "解析关联人员与部门",
|
||||
"relations": "查看关联单据",
|
||||
"attachments": "列出附件",
|
||||
"download": "下载附件",
|
||||
"link": "生成单据详情链接"
|
||||
},
|
||||
"options": [
|
||||
"--dry-run 只预览审批动作",
|
||||
"--yes/--confirm 确认执行审批动作",
|
||||
"--comment=<原因> 驳回或评论内容"
|
||||
],
|
||||
"aliases": [
|
||||
"bills",
|
||||
"fee",
|
||||
"fees",
|
||||
"invoice",
|
||||
"invoices"
|
||||
],
|
||||
"commandAliases": {
|
||||
"agree": "approve",
|
||||
"deny": "reject",
|
||||
"shift": "transfer",
|
||||
"addnode": "add-node",
|
||||
"countersign": "add-node",
|
||||
"counter-sign": "add-node",
|
||||
"remark": "comment",
|
||||
"search": "list",
|
||||
"show": "get",
|
||||
"find": "get",
|
||||
"inspect": "trace",
|
||||
"diagnose": "trace",
|
||||
"schemas": "schema",
|
||||
"entities": "schema",
|
||||
"records": "flow",
|
||||
"timeline": "flow",
|
||||
"review": "risk",
|
||||
"warnings": "risk",
|
||||
"budgets": "budget",
|
||||
"references": "refs",
|
||||
"resolve": "refs",
|
||||
"relation": "relations",
|
||||
"links": "relations",
|
||||
"attachment": "attachments",
|
||||
"files": "attachments",
|
||||
"file-download": "download",
|
||||
"url": "link",
|
||||
"specification": "spec"
|
||||
},
|
||||
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
},
|
||||
"flow": {
|
||||
"summary": "审批流全域透视与穿透诊断",
|
||||
"usage": "hose-use flow <子命令> [单号|ID]",
|
||||
"commands": {
|
||||
"get": "穿透诊断单据流转",
|
||||
"history": "查看审批流转时间线",
|
||||
"risk": "查看风险信息",
|
||||
"list": "查询单据",
|
||||
"approve": "审批同意",
|
||||
"reject": "审批驳回"
|
||||
},
|
||||
"aliases": [
|
||||
"flows",
|
||||
"trace"
|
||||
],
|
||||
"commandAliases": {
|
||||
"records": "history",
|
||||
"timeline": "history",
|
||||
"search": "list",
|
||||
"agree": "approve",
|
||||
"deny": "reject",
|
||||
"trace": "get",
|
||||
"inspect": "get",
|
||||
"diagnose": "get",
|
||||
"show": "get",
|
||||
"find": "get"
|
||||
},
|
||||
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
},
|
||||
"contact": {
|
||||
"summary": "企业通讯录与人员检索",
|
||||
"usage": "hose-use contact <子命令>",
|
||||
"commands": {
|
||||
"list": "列出员工",
|
||||
"search": "搜索员工",
|
||||
"get": "查看员工详情"
|
||||
},
|
||||
"aliases": [
|
||||
"contacts",
|
||||
"staff",
|
||||
"staffs"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("id k keyword l limit query staff-id", "value") }
|
||||
},
|
||||
"task": {
|
||||
"summary": "待办中心与审批任务",
|
||||
"usage": "hose-use task <子命令>",
|
||||
"commands": {
|
||||
"todo": "待我审批",
|
||||
"approved": "我已审批",
|
||||
"submitted": "我发起的",
|
||||
"records": "审批记录",
|
||||
"cc": "抄送任务"
|
||||
},
|
||||
"aliases": [
|
||||
"tasks",
|
||||
"todo"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("read unread", "boolean"), ...flagList("count end-date from limit n offset staff staff-id staffId start start-date to", "value") }
|
||||
},
|
||||
"dimension": {
|
||||
"summary": "系统与自定义档案维度",
|
||||
"usage": "hose-use dimension <子命令>",
|
||||
"commands": {
|
||||
"list": "列出维度",
|
||||
"items": "列出维度项"
|
||||
},
|
||||
"aliases": [
|
||||
"dimensions",
|
||||
"archive",
|
||||
"archives"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("code count dimension id keyword limit n name q query", "value") }
|
||||
},
|
||||
"feetype": {
|
||||
"summary": "费用类型全生命周期管理与模板规格查询",
|
||||
"usage": "hose-use feetype <子命令> [参数]",
|
||||
"commands": {
|
||||
"list": "查看费用类型树",
|
||||
"get": "查看详情与字段",
|
||||
"spec": "查看单据/申请模板字段与联动规则",
|
||||
"create": "新建费用类型",
|
||||
"update": "修改属性",
|
||||
"disable": "停用",
|
||||
"enable": "启用",
|
||||
"move": "移动层级",
|
||||
"fields": "查看字段配置"
|
||||
},
|
||||
"options": [
|
||||
"--dry-run 只预览写操作",
|
||||
"--yes/--confirm 确认写操作"
|
||||
],
|
||||
"aliases": [
|
||||
"feetypes",
|
||||
"fee-type",
|
||||
"fee-types",
|
||||
"expense-type",
|
||||
"expense-types",
|
||||
"costtype"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("a all fields flat flatten include-disabled r recursive spec specs table", "boolean"), ...flagList("code color desc description en-name enName icon id keyword name parent parent-id parentId q query target title to", "value") }
|
||||
},
|
||||
"role": {
|
||||
"summary": "企业角色定义与成员",
|
||||
"usage": "hose-use role <子命令>",
|
||||
"commands": {
|
||||
"list": "列出角色",
|
||||
"groups": "列出角色组",
|
||||
"members": "查看角色成员"
|
||||
},
|
||||
"aliases": [
|
||||
"roles"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("code count id keyword limit n name q query role", "value") }
|
||||
},
|
||||
"permission": {
|
||||
"summary": "权限模型快照",
|
||||
"usage": "hose-use permission get",
|
||||
"commands": {
|
||||
"get": "查看角色权限开关"
|
||||
},
|
||||
"aliases": [
|
||||
"permissions"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { }
|
||||
},
|
||||
"rule": {
|
||||
"summary": "本地审批规约管理",
|
||||
"usage": "hose-use rule <子命令> [参数]",
|
||||
"commands": {
|
||||
"scopes": "列出适用场景",
|
||||
"scope": "查看场景明细",
|
||||
"list": "列出规则",
|
||||
"get": "查看规则详情",
|
||||
"add": "新增规则",
|
||||
"delete": "删除规则"
|
||||
},
|
||||
"options": [
|
||||
"--dry-run 只预览增删",
|
||||
"--yes/--confirm 确认增删"
|
||||
],
|
||||
"aliases": [
|
||||
"rules"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("all", "boolean"), ...flagList("b body code id index name s scope status target", "value") }
|
||||
},
|
||||
"approval": {
|
||||
"summary": "确定性审批网关与要点仲裁",
|
||||
"usage": "hose-use approval audit <子命令> [单号]",
|
||||
"commands": {
|
||||
"points": "查看审核要点",
|
||||
"checklist": "查看核验清单",
|
||||
"review": "核验事实",
|
||||
"decide": "生成或执行仲裁决定",
|
||||
"audit": "审批核验与仲裁入口"
|
||||
},
|
||||
"options": [
|
||||
"--apply --yes 执行真实审批流转"
|
||||
],
|
||||
"aliases": [
|
||||
"approvals",
|
||||
"audit"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("apply confirm do execute run y yes", "boolean"), ...flagList("action code comment data e eval evidence findings i id index m message p point proof r reason reasoning s scope sn state status target", "value") }
|
||||
},
|
||||
"message": {
|
||||
"summary": "消息中心与通知管理",
|
||||
"usage": "hose-use message <子命令>",
|
||||
"commands": {
|
||||
"list": "查询消息",
|
||||
"count": "查看未读数",
|
||||
"read": "标记消息已读",
|
||||
"read-all": "全部标记已读"
|
||||
},
|
||||
"aliases": [
|
||||
"messages",
|
||||
"notify",
|
||||
"notifications"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("all read unread", "boolean"), ...flagList("count id limit message-id message-type n offset start type", "value") }
|
||||
},
|
||||
"platform": {
|
||||
"summary": "自建应用、业务对象、全量记录安全更新与台账体检",
|
||||
"usage": "hose-use platform <子命令> [参数]",
|
||||
"commands": {
|
||||
"list": "列出自建应用",
|
||||
"entities": "列出业务对象",
|
||||
"schema": "查看字段定义",
|
||||
"records": "查询记录(支持 --all / --ndjson 流式 / --stats 画像)",
|
||||
"record": "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)",
|
||||
"audit": "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)",
|
||||
"permissions": "查看权限",
|
||||
"imports": "查看导入任务",
|
||||
"get": "查看应用详情"
|
||||
},
|
||||
"options": [
|
||||
"--all 自动翻页拉取全量记录",
|
||||
"--ndjson 流式逐行下发 JSON Lines ($O(1)内存)",
|
||||
"--flat 剥离底层实体动态字段前缀并提取引用",
|
||||
"--stats 输出总数/启停/重名/编码规则聚类画像",
|
||||
"--dry-run 只预览记录写操作",
|
||||
"--yes/--confirm 确认记录写操作",
|
||||
"--raw 跳过安全合并直接发送原始补丁"
|
||||
],
|
||||
"aliases": [
|
||||
"platforms",
|
||||
"datalink",
|
||||
"data-link"
|
||||
],
|
||||
"commandAliases": {
|
||||
"ls": "list",
|
||||
"apps": "list",
|
||||
"show": "get",
|
||||
"objects": "entities",
|
||||
"fields": "schema",
|
||||
"data": "records",
|
||||
"search": "records",
|
||||
"stats": "records",
|
||||
"profile": "records",
|
||||
"check": "audit",
|
||||
"health": "audit",
|
||||
"record-get": "record",
|
||||
"record-toggle": "record",
|
||||
"record-edit": "record",
|
||||
"record-batch-edit": "record",
|
||||
"batch-edit": "record",
|
||||
"record-update": "record",
|
||||
"update": "record",
|
||||
"batch-update": "record",
|
||||
"record-recompute": "record",
|
||||
"permission": "permissions",
|
||||
"auth": "permissions",
|
||||
"import-jobs": "imports"
|
||||
},
|
||||
flags: { ...flagList("a active active-only activeOnly all flat ndjson normalize normalized profile raw state stats stream w workbench", "boolean"), ...flagList("aggregate baseline c check-continuous check-fields checkContinuous checkFields concurrency continuous count d data expect expect-value expectValue f field fields file filter filter-by filterBy form group-by groupBy id ids keyword limit name offset page-size pageSize q query select seq sequence set start sum where", "value") }
|
||||
},
|
||||
"app": {
|
||||
"summary": "桌面端工作台应用管理",
|
||||
"usage": "hose-use app <子命令>",
|
||||
"commands": {
|
||||
"list": "列出应用",
|
||||
"get": "查看应用详情"
|
||||
},
|
||||
"aliases": [
|
||||
"apps",
|
||||
"workbench"
|
||||
],
|
||||
"commandAliases": {
|
||||
"ls": "list",
|
||||
"apps": "list",
|
||||
"workbench": "list",
|
||||
"show": "get"
|
||||
},
|
||||
flags: { ...flagList("app id k keyword name q query", "value") }
|
||||
},
|
||||
"menu": {
|
||||
"summary": "桌面端主导航菜单树",
|
||||
"usage": "hose-use menu list",
|
||||
"commands": {
|
||||
"list": "查看主导航",
|
||||
"apps": "查看应用入口"
|
||||
},
|
||||
"aliases": [
|
||||
"menus"
|
||||
],
|
||||
"commandAliases": {
|
||||
"workbench": "apps",
|
||||
"ls": "list",
|
||||
"tree": "list"
|
||||
},
|
||||
flags: { }
|
||||
},
|
||||
"skill": {
|
||||
"summary": "Agent Skill 管理",
|
||||
"usage": "hose-use skill <install|status|dump>",
|
||||
"commands": {
|
||||
"install": "安装内嵌 Skill",
|
||||
"status": "查看安装状态",
|
||||
"dump": "导出 Skill 文件"
|
||||
},
|
||||
"aliases": [
|
||||
"skills"
|
||||
],
|
||||
"commandAliases": {
|
||||
"cat": "dump",
|
||||
"show": "dump",
|
||||
"init": "install",
|
||||
"sync": "install",
|
||||
"get": "status"
|
||||
},
|
||||
flags: { ...flagList("local workspace", "boolean"), ...flagList("dir target", "value") }
|
||||
},
|
||||
"probe": {
|
||||
"summary": "企业连通性诊断",
|
||||
"usage": "hose-use probe [corpId]",
|
||||
"commands": {
|
||||
"probe": "检查认证与 API 连通性"
|
||||
},
|
||||
"aliases": [
|
||||
"diagnose"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("a add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite p persist plain prod production r refresh reveal save save-staff t test upgrade-all verify", "boolean"), ...flagList("app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user", "value") }
|
||||
},
|
||||
"update": {
|
||||
"summary": "版本自更新与发布记录",
|
||||
"usage": "hose-use update [check|--changelog]",
|
||||
"commands": {
|
||||
"update": "检查并升级版本",
|
||||
"check": "只检查可用版本",
|
||||
"changelog": "查看发布记录"
|
||||
},
|
||||
"aliases": [
|
||||
"upgrade",
|
||||
"self-update",
|
||||
"changelog"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("c changelog check check-only f force gh gitea github l log mirror yingqing", "boolean"), ...flagList("limit n repo t tag target version", "value") }
|
||||
},
|
||||
"openapi": {
|
||||
"summary": "OpenAPI 规范导出与路径查询",
|
||||
"usage": "hose-use openapi [paths|info|--raw|keys]",
|
||||
"commands": {
|
||||
"paths": "列出路径概要",
|
||||
"info": "查看规范元数据",
|
||||
"keys": "查看企业接入密钥",
|
||||
"dump": "导出规范"
|
||||
},
|
||||
"aliases": [
|
||||
"schema",
|
||||
"spec"
|
||||
],
|
||||
"commandAliases": {
|
||||
"list": "paths",
|
||||
"ls": "paths",
|
||||
"summary": "info",
|
||||
"export": "dump",
|
||||
"raw": "dump"
|
||||
},
|
||||
flags: { ...flagList("raw elevate f force persist plain r reveal save", "boolean"), ...flagList("app-key appKey key-id keyId", "value") }
|
||||
},
|
||||
"keys": {
|
||||
"summary": "企业 OpenAPI 接入凭证",
|
||||
"usage": "hose-use keys [--json] [--reveal] [--save]",
|
||||
"commands": {
|
||||
"keys": "读取当前企业密钥(默认脱敏)"
|
||||
},
|
||||
"options": [
|
||||
"--reveal 仅在明确授权后查看明文",
|
||||
"--save --yes 提取并持久化保存到本地企业配置"
|
||||
],
|
||||
"aliases": [
|
||||
"key",
|
||||
"secret",
|
||||
"secrets"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("elevate f force persist plain r reveal save", "boolean"), ...flagList("app-key appKey key-id keyId", "value") }
|
||||
},
|
||||
"store": {
|
||||
"summary": "已购应用与应用商店探查",
|
||||
"usage": "hose-use store <list|search|get>",
|
||||
"commands": {
|
||||
"list": "列出已购应用",
|
||||
"search": "搜索应用商店",
|
||||
"get": "查看应用详情",
|
||||
"keys": "查看企业接入密钥"
|
||||
},
|
||||
"aliases": [
|
||||
"market"
|
||||
],
|
||||
"commandAliases": {
|
||||
"key": "keys",
|
||||
"ls": "list",
|
||||
"find": "search",
|
||||
"info": "get",
|
||||
"detail": "get"
|
||||
},
|
||||
flags: { ...flagList("a all elevate f force persist plain r reveal save", "boolean"), ...flagList("id k keyword name app-key appKey key-id keyId", "value") }
|
||||
},
|
||||
"http": {
|
||||
"summary": "轻量 HTTP Server 与交互文档",
|
||||
"usage": "hose-use http [--port=<port>]",
|
||||
"commands": {
|
||||
"http": "启动 HTTP 服务"
|
||||
},
|
||||
"aliases": [
|
||||
"server",
|
||||
"web"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("h", "boolean-or-value"), ...flagList("host p port", "value") }
|
||||
},
|
||||
"service": {
|
||||
"summary": "常驻守护进程管理",
|
||||
"usage": "hose-use service <start|stop|restart|status|logs|poll>",
|
||||
"commands": {
|
||||
"start": "启动服务",
|
||||
"stop": "停止服务",
|
||||
"restart": "重启服务",
|
||||
"status": "查看服务状态",
|
||||
"logs": "查看服务日志",
|
||||
"poll": "轮询事件"
|
||||
},
|
||||
"aliases": [
|
||||
"daemon"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("count host limit n p port state-file stateFile", "value"), ...flagList("h", "boolean-or-value") }
|
||||
},
|
||||
"mcp": {
|
||||
"summary": "MCP Server",
|
||||
"usage": "hose-use mcp serve",
|
||||
"commands": {
|
||||
"serve": "启动 MCP 服务"
|
||||
},
|
||||
"aliases": [],
|
||||
"commandAliases": {},
|
||||
flags: { }
|
||||
}
|
||||
};
|
||||
|
||||
export function resolveCommandMetadata(area?: string): { area: string; metadata: CliCommandMetadata } | undefined {
|
||||
if (!area) return undefined;
|
||||
const normalized = area.toLowerCase();
|
||||
for (const [name, metadata] of Object.entries(COMMAND_METADATA)) {
|
||||
if (name === normalized || metadata.aliases.includes(normalized)) return { area: name, metadata };
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveCommandAction(area: string | undefined, action?: string): string | undefined {
|
||||
const metadata = resolveCommandMetadata(area)?.metadata;
|
||||
const key = action?.toLowerCase();
|
||||
return key ? (metadata && Object.hasOwn(metadata.commandAliases, key) ? metadata.commandAliases[key] : key) : undefined;
|
||||
}
|
||||
|
||||
export function localCommandFlags(area?: string, action?: string): Record<string, FlagKind> {
|
||||
const resolved = resolveCommandMetadata(area);
|
||||
const flags = { ...resolved?.metadata.flags };
|
||||
const canonical = resolveCommandAction(area, action);
|
||||
// Most commands retain -c as the global corp selector. A few actions declare
|
||||
// a local meaning (bill code, node code, batch concurrency or bound rule codes).
|
||||
const localC = resolved?.area === "update"
|
||||
|| (["bill", "flow"].includes(resolved?.area || "") && ["list", "link"].includes(canonical || "list"))
|
||||
|| (resolved?.area === "workflow" && canonical === "node")
|
||||
|| (resolved?.area === "platform" && canonical === "record")
|
||||
|| (resolved?.area === "aipro" && canonical === "bind");
|
||||
if (!localC) delete flags.c;
|
||||
if (resolved?.area === "workflow" && canonical === "create") flags.f = "value";
|
||||
// --run historically accepts a session ID and, for decide, an apply boolean.
|
||||
if (resolved?.area === "aipro" && canonical === "decide") flags.run = "boolean-or-value";
|
||||
return flags;
|
||||
}
|
||||
|
||||
export function commandFlags(area?: string, action?: string): Record<string, FlagKind> {
|
||||
return { ...GLOBAL_FLAGS, ...localCommandFlags(area, action) };
|
||||
}
|
||||
+7
-15
@@ -1,24 +1,16 @@
|
||||
import { spawn } from "child_process";
|
||||
import { join } from "path";
|
||||
import { usageError } from "../errors.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions } from "../types.js";
|
||||
|
||||
export async function handleMcpCommand(
|
||||
parsed: CliParsedArgs,
|
||||
options: CliRunOptions
|
||||
): Promise<CliResult> {
|
||||
const appRoot = options.appRoot || process.cwd();
|
||||
const serverPath = join(appRoot, "src", "server.ts");
|
||||
|
||||
console.error("启动 MCP Server on stdio...");
|
||||
const child = spawn("bun", ["run", serverPath], {
|
||||
stdio: "inherit",
|
||||
cwd: appRoot,
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
child.on("exit", () => resolve());
|
||||
});
|
||||
if (parsed.action && parsed.action !== "serve") {
|
||||
throw usageError(`未知 mcp 子命令: ${parsed.action}。用法: hose-use mcp [serve]`);
|
||||
}
|
||||
// Lazy loading avoids a runner -> registry -> server -> runner startup cycle.
|
||||
const { startServer } = await import("../../server.js");
|
||||
await startServer(options);
|
||||
|
||||
return { stdout: "", stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -99,7 +99,7 @@ export async function handleSkillCommand(
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 hose-use skill install 进行全局安装\n`,
|
||||
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 hose-use skill install --yes 进行全局安装\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
detectArch,
|
||||
detectPlatform,
|
||||
downloadFile,
|
||||
downloadVerifiedReleaseAsset,
|
||||
extractTarGz,
|
||||
extractZip,
|
||||
fetchGitHubRelease,
|
||||
@@ -447,14 +448,13 @@ export async function handleUpdateCommand(
|
||||
mkdirSync(tmpDir, { recursive: true });
|
||||
|
||||
try {
|
||||
const downloadedFile = join(tmpDir, asset.name);
|
||||
await downloadFile(asset.downloadUrl, downloadedFile, release.tagName, asset.name, repo, options.sourcePreference);
|
||||
const downloadedFile = await downloadVerifiedReleaseAsset(release, asset, tmpDir, repo, options.sourcePreference);
|
||||
|
||||
let newBinaryPath = downloadedFile;
|
||||
if (asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz")) {
|
||||
newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform);
|
||||
newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform, arch);
|
||||
} else if (asset.name.endsWith(".zip")) {
|
||||
newBinaryPath = extractZip(downloadedFile, tmpDir, platform);
|
||||
newBinaryPath = extractZip(downloadedFile, tmpDir, platform, arch);
|
||||
}
|
||||
|
||||
chmodSync(newBinaryPath, 0o755);
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { downloadVerifiedReleaseAsset, extractTarGz, extractZip, fetchGitHubRelease, verifyAssetChecksum, type GitHubRelease } from "./releases.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
const temp = () => { const root = mkdtempSync(join(tmpdir(), "hose-update-test-")); roots.push(root); return root; };
|
||||
const payload = Buffer.alloc(2048, 42);
|
||||
const assetName = "hose-use-linux-x64.tar.gz";
|
||||
const digest = createHash("sha256").update(payload).digest("hex");
|
||||
const asset = { name: assetName, downloadUrl: `https://github.com/test/repo/releases/download/v9.9.9/${assetName}`, size: payload.length };
|
||||
const release: GitHubRelease = { version: "9.9.9", tagName: "v9.9.9", notes: "", htmlUrl: "", assets: [asset, { name: "checksums.txt", downloadUrl: "https://github.com/test/repo/releases/download/v9.9.9/checksums.txt", size: 100 }] };
|
||||
|
||||
describe("verified self-update assets", () => {
|
||||
test("rejects missing, duplicate and mismatched checksums", () => {
|
||||
const file = join(temp(), "asset"); writeFileSync(file, payload);
|
||||
expect(() => verifyAssetChecksum(file, assetName, `${digest} ${assetName}\n`)).not.toThrow();
|
||||
expect(() => verifyAssetChecksum(file, assetName, `${digest} *${assetName}\r\n`)).not.toThrow();
|
||||
for (const manifest of ["", `${digest} unrelated\n`, `${digest} ${assetName}\n${digest} ${assetName}\n`, `${digest} ${assetName}\ninvalid ${assetName}\n`, `${"0".repeat(64)} ${assetName}\n`]) {
|
||||
expect(() => verifyAssetChecksum(file, assetName, manifest)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test("pins manifest and binary to the release tag and never sends GitHub credentials to proxies", async () => {
|
||||
const fetchBefore = globalThis.fetch;
|
||||
const tokenBefore = process.env.GITHUB_TOKEN;
|
||||
process.env.GITHUB_TOKEN = "fixture-token";
|
||||
const requests: Array<{ url: string; authorization?: string }> = [];
|
||||
globalThis.fetch = (async (input: string | URL | Request, options?: RequestInit) => {
|
||||
const url = String(input);
|
||||
requests.push({ url, authorization: new Headers(options?.headers).get("Authorization") || undefined });
|
||||
return new Response(url.endsWith("checksums.txt") ? `${digest} ${assetName}\n` : payload);
|
||||
}) as typeof fetch;
|
||||
try {
|
||||
const path = await downloadVerifiedReleaseAsset(release, asset, temp(), "test/repo", "github");
|
||||
expect(readFileSync(path)).toEqual(payload);
|
||||
expect(requests).toHaveLength(2);
|
||||
for (const request of requests) {
|
||||
expect(request.url).toContain("/download/v9.9.9/");
|
||||
if (new URL(request.url).hostname !== "github.com") expect(request.authorization).toBeUndefined();
|
||||
}
|
||||
} finally {
|
||||
globalThis.fetch = fetchBefore;
|
||||
if (tokenBefore === undefined) delete process.env.GITHUB_TOKEN; else process.env.GITHUB_TOKEN = tokenBefore;
|
||||
}
|
||||
});
|
||||
|
||||
test("does not start downloading a release without a checksum manifest", async () => {
|
||||
const fetchBefore = globalThis.fetch;
|
||||
let requests = 0;
|
||||
globalThis.fetch = (async () => { requests++; throw new Error("must not fetch"); }) as unknown as typeof fetch;
|
||||
try {
|
||||
await expect(downloadVerifiedReleaseAsset({ ...release, assets: [asset] }, asset, temp())).rejects.toThrow("checksums.txt");
|
||||
expect(requests).toBe(0);
|
||||
} finally { globalThis.fetch = fetchBefore; }
|
||||
});
|
||||
|
||||
test("GitHub API credentials are also excluded from mirror metadata requests", async () => {
|
||||
const fetchBefore = globalThis.fetch;
|
||||
const tokenBefore = process.env.GITHUB_TOKEN;
|
||||
process.env.GITHUB_TOKEN = "fixture-token";
|
||||
let authorization: string | null = "not-called";
|
||||
globalThis.fetch = (async (_input: string | URL | Request, options?: RequestInit) => {
|
||||
authorization = new Headers(options?.headers).get("Authorization");
|
||||
return Response.json({ tag_name: "v9.9.9", assets: [{ name: "checksums.txt", browser_download_url: "https://example.test/checksums.txt" }] });
|
||||
}) as typeof fetch;
|
||||
try {
|
||||
expect((await fetchGitHubRelease("yunyingk/hose-use", "9.9.9", "gitea"))?.tagName).toBe("v9.9.9");
|
||||
expect(authorization).toBeNull();
|
||||
} finally {
|
||||
globalThis.fetch = fetchBefore;
|
||||
if (tokenBefore === undefined) delete process.env.GITHUB_TOKEN; else process.env.GITHUB_TOKEN = tokenBefore;
|
||||
}
|
||||
});
|
||||
|
||||
test("extracts only a known binary and rejects archives containing no expected member", () => {
|
||||
const root = temp(), source = join(root, "source"), target = join(root, "target");
|
||||
mkdirSync(source); mkdirSync(target);
|
||||
const platform = process.platform === "darwin" ? "darwin" : "linux";
|
||||
const name = `hose-use-${platform}-${process.arch === "arm64" ? "arm64" : "x64"}`;
|
||||
writeFileSync(join(source, name), payload);
|
||||
writeFileSync(join(source, "unrelated.txt"), "not a binary");
|
||||
const archive = join(target, "release.tar.gz");
|
||||
expect(spawnSync("tar", ["-czf", archive, "-C", source, name, "unrelated.txt"]).status).toBe(0);
|
||||
const extracted = extractTarGz(archive, target, platform);
|
||||
expect(readFileSync(extracted)).toEqual(payload);
|
||||
expect(existsSync(join(target, "unrelated.txt"))).toBe(false);
|
||||
expect(spawnSync("tar", ["-czf", archive, "-C", source, "unrelated.txt"]).status).toBe(0);
|
||||
expect(() => extractTarGz(archive, target, platform)).toThrow("目标平台二进制");
|
||||
});
|
||||
|
||||
test("extracts the selected Windows ZIP binary without materializing wrappers or extra files", () => {
|
||||
const root = temp(), source = join(root, "source"), target = join(root, "target");
|
||||
mkdirSync(source); mkdirSync(target);
|
||||
const name = "hose-use-windows-x64.exe";
|
||||
writeFileSync(join(source, name), payload);
|
||||
writeFileSync(join(source, "hose-aipro.cmd"), "fixture wrapper");
|
||||
const archive = join(target, "release.zip");
|
||||
expect(spawnSync("zip", ["-q", archive, name, "hose-aipro.cmd"], { cwd: source }).status).toBe(0);
|
||||
const extracted = extractZip(archive, target, "windows", "x64");
|
||||
expect(readFileSync(extracted)).toEqual(payload);
|
||||
expect(existsSync(join(target, "hose-aipro.cmd"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,6 @@
|
||||
import { unlinkSync, writeFileSync } from "node:fs";
|
||||
import { closeSync, mkdtempSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
import { basename, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { VERSION } from "../../../version.js";
|
||||
|
||||
@@ -79,7 +81,7 @@ export async function fetchGitHubReleases(
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
|
||||
const res = await fetch(url, { headers: scopedHeaders(headers, url), signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) continue;
|
||||
const json = (await res.json()) as Array<{
|
||||
tag_name?: string;
|
||||
@@ -168,7 +170,7 @@ export async function fetchGitHubRelease(
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
|
||||
const res = await fetch(url, { headers: scopedHeaders(headers, url), signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) continue;
|
||||
const json = (await res.json()) as {
|
||||
tag_name?: string;
|
||||
@@ -181,6 +183,7 @@ export async function fetchGitHubRelease(
|
||||
};
|
||||
|
||||
const tagName = json.tag_name ?? "";
|
||||
if (tag && tagName !== tag) continue;
|
||||
const version = tagName.replace(/^v/, "");
|
||||
if (!version) continue;
|
||||
|
||||
@@ -269,13 +272,22 @@ function logProgress(msg: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Credentials for GitHub must never be forwarded to a CDN or the Gitea mirror. */
|
||||
function scopedHeaders(headers: Record<string, string>, url: string): Record<string, string> {
|
||||
const hostname = new URL(url).hostname;
|
||||
if (hostname === "github.com" || hostname === "api.github.com") return headers;
|
||||
const { Authorization: _authorization, ...publicHeaders } = headers;
|
||||
return publicHeaders;
|
||||
}
|
||||
|
||||
export async function downloadFile(
|
||||
url: string,
|
||||
destPath: string,
|
||||
tagName?: string,
|
||||
assetName?: string,
|
||||
repo: string = DEFAULT_GITHUB_REPO,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
sourcePreference: UpdateSourcePreference = "auto",
|
||||
minimumBytes = 1000
|
||||
) {
|
||||
const candidates: string[] = [];
|
||||
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
|
||||
@@ -326,7 +338,7 @@ export async function downloadFile(
|
||||
"User-Agent": `hose-use/${VERSION}`,
|
||||
};
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
if (token && candidate.includes("github.com")) {
|
||||
if (token && ["github.com", "api.github.com"].includes(new URL(candidate).hostname)) {
|
||||
reqHeaders["Authorization"] = `Bearer ${token}`;
|
||||
}
|
||||
const res = await fetch(candidate, {
|
||||
@@ -341,7 +353,7 @@ export async function downloadFile(
|
||||
const reader = res.body?.getReader();
|
||||
if (!reader) {
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
if (buffer.length < 1000) {
|
||||
if (buffer.length < minimumBytes) {
|
||||
throw new Error(`下载文件异常(大小仅 ${buffer.length} 字节)`);
|
||||
}
|
||||
writeFileSync(destPath, buffer);
|
||||
@@ -381,7 +393,7 @@ export async function downloadFile(
|
||||
}
|
||||
|
||||
const completeBuffer = Buffer.concat(chunks);
|
||||
if (completeBuffer.length < 1000) {
|
||||
if (completeBuffer.length < minimumBytes) {
|
||||
throw new Error(`下载文件异常(大小仅 ${completeBuffer.length} 字节)`);
|
||||
}
|
||||
writeFileSync(destPath, completeBuffer);
|
||||
@@ -396,56 +408,63 @@ export async function downloadFile(
|
||||
throw new Error(`所有下载镜像均失败: ${lastError?.message}`);
|
||||
}
|
||||
|
||||
export function extractTarGz(archivePath: string, targetDir: string, platform: string): string {
|
||||
const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`解压 tar 归档失败: ${result.stderr.toString()}`);
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
|
||||
// Exact match for hose-use or hose-use.exe
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
|
||||
// Next match for hose-use-darwin-arm64 etc., excluding hose-aipro
|
||||
const platformBinary = files.find((f) => {
|
||||
const base = f.split("/").pop() || "";
|
||||
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
|
||||
export function verifyAssetChecksum(assetPath: string, assetName: string, manifest: string): void {
|
||||
const matches = manifest.split(/\r?\n/).flatMap(line => {
|
||||
const match = line.match(/^(\S+)\s+\*?(.+)$/);
|
||||
return match?.[2] === assetName ? [match[1].toLowerCase()] : [];
|
||||
});
|
||||
if (platformBinary) return platformBinary;
|
||||
|
||||
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
|
||||
if (matches.length !== 1 || !/^[a-f0-9]{64}$/.test(matches[0])) throw new Error(`checksums.txt 缺少、重复或错误列出 ${assetName},拒绝未经校验的更新`);
|
||||
const actual = createHash("sha256").update(readFileSync(assetPath)).digest("hex");
|
||||
if (actual !== matches[0]) throw new Error(`SHA-256 校验失败: ${assetName};现有安装未替换`);
|
||||
}
|
||||
|
||||
export function extractZip(archivePath: string, targetDir: string, platform: string): string {
|
||||
const result = spawnSync("unzip", ["-q", "-o", archivePath, "-d", targetDir], { stdio: "pipe" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`解压 zip 归档失败: ${result.stderr.toString()}`);
|
||||
export async function downloadVerifiedReleaseAsset(
|
||||
release: GitHubRelease,
|
||||
asset: GitHubAsset,
|
||||
targetDir: string,
|
||||
repo = DEFAULT_GITHUB_REPO,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
): Promise<string> {
|
||||
if (basename(asset.name) !== asset.name || /[\\/]/.test(asset.name)) throw new Error("非法 Release 资产文件名");
|
||||
if (!/^v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(release.tagName)) throw new Error("非法 Release tag");
|
||||
const manifest = release.assets.find(item => item.name === "checksums.txt");
|
||||
if (!manifest) throw new Error(`Release ${release.tagName} 缺少 checksums.txt,拒绝未经校验的更新`);
|
||||
const manifestPath = join(targetDir, "checksums.txt");
|
||||
await downloadFile(manifest.downloadUrl, manifestPath, release.tagName, manifest.name, repo, sourcePreference, 1);
|
||||
const assetPath = join(targetDir, asset.name);
|
||||
await downloadFile(asset.downloadUrl, assetPath, release.tagName, asset.name, repo, sourcePreference);
|
||||
verifyAssetChecksum(assetPath, asset.name, readFileSync(manifestPath, "utf8"));
|
||||
return assetPath;
|
||||
}
|
||||
|
||||
/** Extract only a known binary member; never materialize archive paths or aliases. */
|
||||
function extractReleaseBinary(archivePath: string, targetDir: string, platform: string, arch: string, format: "tar" | "zip"): string {
|
||||
const listing = spawnSync(format === "tar" ? "tar" : "unzip", format === "tar" ? ["-tzf", archivePath] : ["-Z1", archivePath], { encoding: "utf8" });
|
||||
if (listing.status !== 0) throw new Error(`无法读取 Release 归档: ${listing.stderr}`);
|
||||
const names = listing.stdout.split(/\r?\n/);
|
||||
const suffix = platform === "windows" ? ".exe" : "";
|
||||
const expected = [`hose-use-${platform}-${arch}${suffix}`, `hose-use${suffix}`];
|
||||
const member = expected.flatMap(name => [name, `./${name}`]).find(name => names.filter(item => item === name).length === 1);
|
||||
if (!member) throw new Error("Release 归档中没有唯一的目标平台二进制");
|
||||
const output = join(mkdtempSync(join(targetDir, ".extract-")), `hose-use${suffix}`);
|
||||
const fd = openSync(output, "wx", 0o700);
|
||||
try {
|
||||
const extraction = spawnSync(format === "tar" ? "tar" : "unzip", format === "tar" ? ["-xOzf", archivePath, member] : ["-p", archivePath, member], { stdio: ["ignore", fd, "pipe"] });
|
||||
if (extraction.status !== 0) throw new Error(`解压 Release 二进制失败: ${extraction.stderr}`);
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
if (!statSync(output).size) throw new Error("Release 二进制为空");
|
||||
unlinkSync(archivePath);
|
||||
return output;
|
||||
}
|
||||
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
export function extractTarGz(archivePath: string, targetDir: string, platform: string, arch = detectArch()): string {
|
||||
return extractReleaseBinary(archivePath, targetDir, platform, arch, "tar");
|
||||
}
|
||||
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
|
||||
const platformBinary = files.find((f) => {
|
||||
const base = f.split("/").pop() || "";
|
||||
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
|
||||
});
|
||||
if (platformBinary) return platformBinary;
|
||||
|
||||
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
|
||||
export function extractZip(archivePath: string, targetDir: string, platform: string, arch = detectArch()): string {
|
||||
return extractReleaseBinary(archivePath, targetDir, platform, arch, "zip");
|
||||
}
|
||||
|
||||
export function compareSemVer(v1: string, v2: string): number {
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
analyzeWorkflow,
|
||||
extractWorkflowSpecificationIds,
|
||||
type WorkflowFormSpecLike,
|
||||
} from "../../../domains/platform/analysis.js";
|
||||
} from "../../../domains/platform/workflow/analysis/index.js";
|
||||
import { getFormSpecification } from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { listAllWorkflows, listWorkflowLogs } from "../../../domains/platform/services.js";
|
||||
import { WorkflowAlertStore } from "../../../domains/platform/workflow-alert-store.js";
|
||||
import { WorkflowAlertStore } from "../../../domains/platform/workflow/alert/index.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
createWorkflowDraft,
|
||||
failWorkflowSave,
|
||||
hasWorkflowVersionConflict,
|
||||
} from "../../../domains/platform/workflow-state.js";
|
||||
} from "../../../domains/platform/workflow/state/index.js";
|
||||
import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
|
||||
@@ -367,7 +367,7 @@ export async function handleWorkflowEvalScript(
|
||||
}
|
||||
|
||||
function formatEvalCliResult(
|
||||
evalResult: import("../../../domains/platform/workflow-script.js").ScriptEvalResult,
|
||||
evalResult: import("../../../domains/platform/workflow/script/index.js").ScriptEvalResult,
|
||||
targetDesc: string
|
||||
): CliResult {
|
||||
const lines: string[] = [];
|
||||
|
||||
+10
-70
@@ -1,80 +1,20 @@
|
||||
export interface HelpTopic {
|
||||
summary: string;
|
||||
usage: string;
|
||||
commands: Record<string, string>;
|
||||
options?: string[];
|
||||
}
|
||||
|
||||
export const HELP_REGISTRY: Record<string, HelpTopic> = {
|
||||
context: { summary: "全局运行上下文与身份诊断", usage: "hose-use context [--json]", commands: { context: "输出当前企业、账号、运行模式与认证状态" } },
|
||||
auth: {
|
||||
summary: "认证与凭证管理(支持主账号登录与企业级 OpenAPI 持久化)",
|
||||
usage: "hose-use auth <子命令>",
|
||||
commands: {
|
||||
login: "登录并保存企业凭证",
|
||||
status: "查看当前认证状态",
|
||||
refresh: "刷新账号或企业 AccessToken",
|
||||
link: "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从协助链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
elevate: "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
accounts: "列出已保存账号",
|
||||
"switch-account": "切换默认账号",
|
||||
},
|
||||
},
|
||||
corps: {
|
||||
summary: "多企业租户管理",
|
||||
usage: "hose-use corps <子命令>",
|
||||
commands: {
|
||||
list: "列出本地企业配置",
|
||||
search: "搜索企业与员工",
|
||||
switch: "切换当前工作企业",
|
||||
current: "查看当前企业",
|
||||
link: "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
elevate: "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
},
|
||||
},
|
||||
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
|
||||
workflow: { summary: "工作流查询、草稿、运行排障与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流(含禁用/SKIP/联动覆盖检查)", job: "查看单次运行实例树、报错节点与MVEL日志", diff: "对比两个工作流快照的结构与脚本差异", "diff-job": "对比两次执行的节点分支与报错发散点", test: "端到端一键调试单据(替代前端手工调测)", node: "声明式节点编排与增删改 (list|get|add|edit|rm)", tail: "实时监听任务派发与节点执行日志流 (watch|follow)", create: "从零新建工作流草稿", copy: "复制克隆工作流", delete: "删除工作流", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--flow=<单号> 指定测试单据", "--file=<workflow.json> 指定工作流快照", "--failed 只看失败节点", "--parent=<executionId> 展开循环/分支子节点", "--logs=<executionId> 查看节点执行日志", "--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
|
||||
bill: { summary: "单据检索、表单规格诊断与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", spec: "查看单据模板字段配置与联动覆盖规则", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
|
||||
platform: { summary: "自建应用、业务对象、全量记录安全更新与台账体检", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录(支持 --all / --ndjson 流式 / --stats 画像)", record: "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)", audit: "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)", permissions: "查看权限", imports: "查看导入任务" }, options: ["--all 自动翻页拉取全量记录", "--ndjson 流式逐行下发 JSON Lines ($O(1)内存)", "--flat 剥离底层实体动态字段前缀并提取引用", "--stats 输出总数/启停/重名/编码规则聚类画像", "--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作", "--raw 跳过安全合并直接发送原始补丁"] },
|
||||
feetype: { summary: "费用类型全生命周期管理与模板规格查询", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", spec: "查看单据/申请模板字段与联动规则", create: "新建费用类型", update: "修改属性", disable: "停用", enable: "启用", move: "移动层级", fields: "查看字段配置" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
|
||||
rule: { summary: "本地审批规约管理", usage: "hose-use rule <子命令> [参数]", commands: { scopes: "列出适用场景", scope: "查看场景明细", list: "列出规则", get: "查看规则详情", add: "新增规则", delete: "删除规则" }, options: ["--dry-run 只预览增删", "--yes/--confirm 确认增删"] },
|
||||
approval: { summary: "确定性审批网关与要点仲裁", usage: "hose-use approval audit <子命令> [单号]", commands: { points: "查看审核要点", checklist: "查看核验清单", review: "核验事实", decide: "生成或执行仲裁决定" }, options: ["--apply --yes 执行真实审批流转"] },
|
||||
message: { summary: "消息中心与通知管理", usage: "hose-use message <子命令>", commands: { list: "查询消息", count: "查看未读数", read: "标记消息已读", "read-all": "全部标记已读" } },
|
||||
task: { summary: "待办中心与审批任务", usage: "hose-use task <子命令>", commands: { todo: "待我审批", approved: "我已审批", submitted: "我发起的", records: "审批记录", cc: "抄送任务" } },
|
||||
contact: { summary: "企业通讯录与人员检索", usage: "hose-use contact <子命令>", commands: { list: "列出员工", search: "搜索员工", get: "查看员工详情" } },
|
||||
dimension: { summary: "系统与自定义档案维度", usage: "hose-use dimension <子命令>", commands: { list: "列出维度", items: "列出维度项" } },
|
||||
role: { summary: "企业角色定义与成员", usage: "hose-use role <子命令>", commands: { list: "列出角色", groups: "列出角色组", members: "查看角色成员" } },
|
||||
permission: { summary: "权限模型快照", usage: "hose-use permission get", commands: { get: "查看角色权限开关" } },
|
||||
app: { summary: "桌面端工作台应用管理", usage: "hose-use app <子命令>", commands: { list: "列出应用", get: "查看应用详情" } },
|
||||
menu: { summary: "桌面端主导航菜单树", usage: "hose-use menu list", commands: { list: "查看主导航", apps: "查看应用入口" } },
|
||||
openapi: { summary: "OpenAPI 规范导出与路径查询", usage: "hose-use openapi [paths|info|--raw|keys]", commands: { paths: "列出路径概要", info: "查看规范元数据", keys: "查看企业接入密钥" } },
|
||||
keys: { summary: "企业 OpenAPI 接入凭证", usage: "hose-use keys [--json] [--reveal] [--save]", commands: { keys: "读取当前企业密钥(默认脱敏)" }, options: ["--reveal 仅在明确授权后查看明文", "--save --yes 提取并持久化保存到本地企业配置"] },
|
||||
store: { summary: "已购应用与应用商店探查", usage: "hose-use store <list|search|get>", commands: { list: "列出已购应用", search: "搜索应用商店", get: "查看应用详情" } },
|
||||
update: { summary: "版本自更新与发布记录", usage: "hose-use update [check|--changelog]", commands: { update: "检查并升级版本", check: "只检查可用版本", changelog: "查看发布记录" } },
|
||||
skill: { summary: "Agent Skill 管理", usage: "hose-use skill <install|status|dump>", commands: { install: "安装内嵌 Skill", status: "查看安装状态", dump: "导出 Skill 文件" } },
|
||||
service: { summary: "常驻守护进程管理", usage: "hose-use service <start|stop|restart|status|logs|poll>", commands: { start: "启动服务", stop: "停止服务", restart: "重启服务", status: "查看服务状态", logs: "查看服务日志", poll: "轮询事件" } },
|
||||
probe: { summary: "企业连通性诊断", usage: "hose-use probe [corpId]", commands: { probe: "检查认证与 API 连通性" } },
|
||||
http: { summary: "轻量 HTTP Server 与交互文档", usage: "hose-use http [--port=<port>]", commands: { http: "启动 HTTP 服务" } },
|
||||
mcp: { summary: "MCP Server", usage: "hose-use mcp serve", commands: { serve: "启动 MCP 服务" } },
|
||||
aipro: { summary: "AI PRO 确定性审批仲裁", usage: "hose-use aipro <子命令>", commands: { status: "查看网关状态", bind: "绑定单据", review: "核验要点", decide: "执行仲裁" } },
|
||||
};
|
||||
import { COMMAND_METADATA, commandFlags, resolveCommandAction, resolveCommandMetadata } from "./command-metadata.js";
|
||||
import { usageError } from "./errors.js";
|
||||
export type { HelpTopic } from "./command-metadata.js";
|
||||
export const HELP_REGISTRY = COMMAND_METADATA;
|
||||
|
||||
export function renderScopedHelp(target: string[]): string {
|
||||
const area = target[0]?.toLowerCase();
|
||||
const topic = area ? HELP_REGISTRY[area] : undefined;
|
||||
if (!topic) return `未找到命令域帮助: ${target.join(" ") || "<empty>"}\n运行 hose-use --help 查看全部命令域。`;
|
||||
const resolved = resolveCommandMetadata(target[0]);
|
||||
if (!resolved) throw usageError(`未找到命令域帮助: ${target.join(" ") || "<empty>"}。运行 hose-use --help 查看全部命令域。`);
|
||||
const { area, metadata: topic } = resolved;
|
||||
|
||||
const action = target[1]?.toLowerCase();
|
||||
const action = resolveCommandAction(area, target[1]);
|
||||
if (action && !Object.hasOwn(topic.commands, action)) throw usageError(`未找到子命令帮助: ${area} ${target[1]}`);
|
||||
const lines = [`${area} - ${topic.summary}`, "", `用法: ${topic.usage}`, "", "子命令:"];
|
||||
if (action && topic.commands[action]) lines.push(` ${action.padEnd(14)} ${topic.commands[action]}`);
|
||||
else for (const [name, description] of Object.entries(topic.commands)) lines.push(` ${name.padEnd(14)} ${description}`);
|
||||
if (topic.options?.length) lines.push("", "常用选项:", ...topic.options.map((option) => ` ${option}`));
|
||||
lines.push("", "支持选项:", ...Object.entries(commandFlags(area, action)).map(([key, kind]) => ` --${key}${kind === "value" ? "=<值>" : kind === "boolean-or-value" ? "[=<值>]" : ""}`));
|
||||
lines.push("", "提示: 追加 --json 获取机器可解析结果;写操作先用 --dry-run,再用 --yes 或 --confirm 执行。", "更多: hose-use --help");
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { join, relative } from "node:path";
|
||||
import ts from "typescript";
|
||||
import { commandFlags, COMMAND_METADATA } from "./command-metadata.js";
|
||||
import { parseArgs } from "./parser.js";
|
||||
import { runCli } from "./runner.js";
|
||||
import { CLI_COMMAND_REGISTRY, findCommandByArea } from "./registry.js";
|
||||
import { runAiProCli } from "../aipro-cli.js";
|
||||
|
||||
describe("strict command options", () => {
|
||||
test("rejects misspellings and missing values instead of silently dropping filters", async () => {
|
||||
const typo = await runCli(["bill", "list", "--limitt", "5", "--json"]);
|
||||
expect(typo.exitCode).toBe(2);
|
||||
expect(JSON.parse(typo.stdout).message).toContain("--limit");
|
||||
expect(typo.stderr).toBe("");
|
||||
for (const args of [["bill", "list", "--limit"], ["bill", "get", "-o"], ["--corp"], ["workflow", "get", "--file="], ["bill", "list", "--limit", "--json"]]) {
|
||||
expect((await runCli(args)).exitCode).toBe(2);
|
||||
}
|
||||
expect((await runCli(["mcp", "serve", "--unknwon"])).exitCode).toBe(2);
|
||||
});
|
||||
|
||||
test("uses command-specific boolean and value options without swallowing IDs", () => {
|
||||
expect(parseArgs(["bill", "list", "--fields", "name,code"]).options.fields).toBe("name,code");
|
||||
expect(parseArgs(["feetype", "get", "--fields", "FT001"]).args).toEqual(["FT001"]);
|
||||
expect(parseArgs(["wf", "job", "--verbose", "JOB_123"]).args).toEqual(["JOB_123"]);
|
||||
expect(parseArgs(["workflow", "create", "-f", "template.json"]).options.f).toBe("template.json");
|
||||
expect(parseArgs(["workflow", "tail", "-f", "PIPE_123"]).args).toEqual(["PIPE_123"]);
|
||||
expect(parseArgs(["auth", "import", "--raw", "curl https://example.test"]).options.raw).toBe("curl https://example.test");
|
||||
expect(parseArgs(["update", "--version", "0.9.0"]).options.version).toBe("0.9.0");
|
||||
expect(parseArgs(["http", "-h", "127.0.0.1"]).options.h).toBe("127.0.0.1");
|
||||
expect(parseArgs(["-c", "corp-test", "bill", "list"]).options.corp).toBe("corp-test");
|
||||
expect(parseArgs(["workflow", "get", "ID", "-c", "corp-test"]).options.corp).toBe("corp-test");
|
||||
expect(parseArgs(["status", "-c", "corp-test"], "aipro").options.corp).toBe("corp-test");
|
||||
expect(parseArgs(["platform", "records", "App", "Entity", "-c", "corp-test"]).options.corp).toBe("corp-test");
|
||||
expect(parseArgs(["bind", "R1", "-c", "[1]"], "aipro").options.corp).toBeUndefined();
|
||||
expect(parseArgs(["bill", "list", "-c", "BILL001"]).options.corp).toBeUndefined();
|
||||
expect(parseArgs(["-h", "http"]).options.help).toBe(true);
|
||||
expect(parseArgs(["feetype", "get", "--fields", "1"]).args).toEqual(["1"]);
|
||||
});
|
||||
|
||||
test("preserves explicit booleans, aliases, negative values, and -- boundaries", () => {
|
||||
const parsed = parseArgs(["--json", "--corp", "corp-test", "bill", "list", "--limit=-5", "--mine=false", "--", "--literal"]);
|
||||
expect(parsed.options).toMatchObject({ json: true, corp: "corp-test", limit: "-5", mine: false });
|
||||
expect(parsed.args).toEqual(["--literal"]);
|
||||
expect(parseArgs(["bill", "list", "--limit", "-5"]).options.limit).toBe("-5");
|
||||
expect(parseArgs(["platform", "record", "toggle", "--active=0", "REC_1"]).args).toEqual(["toggle", "REC_1"]);
|
||||
expect(parseArgs(["bill", "get", "ID", "-o", "/tmp/output.json"]).options.outputFile).toBe("/tmp/output.json");
|
||||
expect(() => parseArgs(["bill", "get", "ID", "--json=garbage"])).toThrow("布尔值");
|
||||
});
|
||||
|
||||
test("AI PRO returns structured parse failures before opening its repository", async () => {
|
||||
const result = await runAiProCli(["review", "--findngs", "[]", "--json"]);
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(JSON.parse(result.stdout).message).toContain("--findings");
|
||||
expect(parseArgs(["review", "--run", "R1"], "aipro").options.run).toBe("R1");
|
||||
expect(parseArgs(["decide", "approve", "R1", "--run", "--yes"], "aipro").options.run).toBe(true);
|
||||
const help = await runAiProCli(["review", "--help", "--json"]);
|
||||
expect(help.exitCode).toBe(0);
|
||||
expect(JSON.parse(help.stdout).help).toContain("核验要点");
|
||||
});
|
||||
|
||||
test("all command domains, aliases and declared flags have usable help", async () => {
|
||||
expect(CLI_COMMAND_REGISTRY.map(command => command.area)).toEqual(Object.keys(COMMAND_METADATA));
|
||||
const names = CLI_COMMAND_REGISTRY.flatMap(command => [command.area, ...command.aliases]);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
for (const [area, metadata] of Object.entries(COMMAND_METADATA)) {
|
||||
for (const name of [area, ...metadata.aliases]) {
|
||||
expect(findCommandByArea(name)?.area).toBe(area);
|
||||
const result = await runCli(["help", name]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain(`${area} -`);
|
||||
if (name === area) {
|
||||
const documentedFlags = result.stdout.split("支持选项:\n")[1].split("\n\n提示:")[0].trim().split("\n").map(line => line.trim().match(/^--([^=[\s]+)/)?.[1]);
|
||||
expect(documentedFlags).toEqual(Object.keys(commandFlags(area)));
|
||||
}
|
||||
}
|
||||
}
|
||||
const workflow = await runCli(["wf", "--help"]);
|
||||
for (const action of ["enum", "lint-script", "eval-script"]) expect(workflow.stdout).toContain(action);
|
||||
expect((await runCli(["help", "workflow", "not-real"])).exitCode).toBe(2);
|
||||
expect((await runCli(["help", "workflow", "constructor"])).exitCode).toBe(2);
|
||||
expect((await runCli(["help", "not-real"])).exitCode).toBe(2);
|
||||
expect((await runCli(["workflow", "help", "enum"])).stdout).toContain("枚举");
|
||||
});
|
||||
|
||||
test("handler option declarations cannot drift outside the shared flag vocabulary", () => {
|
||||
const root = join(import.meta.dir, "commands");
|
||||
function files(dir: string): string[] {
|
||||
return readdirSync(dir, { withFileTypes: true }).flatMap(e => e.isDirectory() ? files(join(dir, e.name)) : e.name.endsWith(".ts") && !e.name.endsWith(".test.ts") ? [join(dir, e.name)] : []);
|
||||
}
|
||||
const missing: string[] = [];
|
||||
for (const path of files(root)) {
|
||||
const area = relative(root, path).split("/")[0].replace(/\.ts$/, "");
|
||||
const source = ts.createSourceFile(path, readFileSync(path, "utf8"), ts.ScriptTarget.Latest, true);
|
||||
function visit(node: ts.Node) {
|
||||
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && /^(booleanOption|stringOption|numberOption|listOption)$/.test(node.expression.text)) {
|
||||
const keys = node.arguments[node.expression.text === "listOption" ? 0 : 1];
|
||||
if (keys && ts.isArrayLiteralExpression(keys)) {
|
||||
for (const key of keys.elements) if (ts.isStringLiteral(key) && !commandFlags(area)[key.text]) missing.push(`${relative(root, path)}: --${key.text}`);
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
visit(source);
|
||||
}
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
});
|
||||
+95
-185
@@ -1,202 +1,112 @@
|
||||
import type { CliParsedArgs, OutputOptions } from "./types.js";
|
||||
|
||||
const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"raw",
|
||||
"json",
|
||||
"j",
|
||||
"help",
|
||||
"h",
|
||||
"version",
|
||||
"v",
|
||||
"V",
|
||||
"force",
|
||||
"f",
|
||||
"stateless",
|
||||
"stateful",
|
||||
"check",
|
||||
"check-only",
|
||||
"changelog",
|
||||
"log",
|
||||
"l",
|
||||
"local",
|
||||
"workspace",
|
||||
"external",
|
||||
"full",
|
||||
"allow-full",
|
||||
"allowFull",
|
||||
"summary",
|
||||
"yes",
|
||||
"y",
|
||||
"confirm",
|
||||
"force-write",
|
||||
"forceWrite",
|
||||
"dry-run",
|
||||
"dryRun",
|
||||
"dryrun",
|
||||
"all",
|
||||
"a",
|
||||
"include-disabled",
|
||||
"flat",
|
||||
"flatten",
|
||||
"table",
|
||||
"specs",
|
||||
"spec",
|
||||
"fields",
|
||||
"recursive",
|
||||
"in-place",
|
||||
"inPlace",
|
||||
"value-json",
|
||||
"valueJson",
|
||||
"has-error",
|
||||
"hasError",
|
||||
"errors",
|
||||
"failed",
|
||||
"fail",
|
||||
"fail-on-alert",
|
||||
"failOnAlert",
|
||||
"includeDetail",
|
||||
"detail",
|
||||
"apply",
|
||||
"execute",
|
||||
"do",
|
||||
"refresh",
|
||||
"overwrite",
|
||||
"elevate",
|
||||
"elevate-hose",
|
||||
"as-hose",
|
||||
"no-elevate",
|
||||
"reveal",
|
||||
"plain",
|
||||
"save",
|
||||
"persist",
|
||||
"verify",
|
||||
"workbench",
|
||||
"w",
|
||||
"active-only",
|
||||
"activeOnly",
|
||||
"active",
|
||||
"read",
|
||||
"unread",
|
||||
"clear",
|
||||
"sms",
|
||||
"sync",
|
||||
"interactive",
|
||||
"i",
|
||||
"reminder",
|
||||
"remind",
|
||||
"keep-it-secret",
|
||||
"secret",
|
||||
"private",
|
||||
"mine",
|
||||
"my",
|
||||
"self",
|
||||
"distinct",
|
||||
"risk",
|
||||
"with-risk",
|
||||
"audit",
|
||||
"github",
|
||||
"gh",
|
||||
"gitea",
|
||||
"yingqing",
|
||||
"mirror",
|
||||
]);
|
||||
import { commandFlags, GLOBAL_FLAGS, localCommandFlags, type FlagKind } from "./command-metadata.js";
|
||||
import { usageError } from "./errors.js";
|
||||
|
||||
function isExplicitBooleanLiteral(val: string | undefined): boolean {
|
||||
if (!val) return false;
|
||||
const lower = val.toLowerCase();
|
||||
return lower === "true" || lower === "false";
|
||||
function explicitBoolean(value: string | undefined): boolean | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
if (value.toLowerCase() === "true" || value === "1") return true;
|
||||
if (value.toLowerCase() === "false" || value === "0") return false;
|
||||
}
|
||||
|
||||
export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
// Space-separated numeric tokens may be positional IDs. Numeric booleans use =0/=1.
|
||||
function separatedBoolean(value: string | undefined): boolean | undefined {
|
||||
return value && /^(true|false)$/i.test(value) ? explicitBoolean(value) : undefined;
|
||||
}
|
||||
|
||||
function findContext(raw: string[], areaOverride?: string): { area?: string; action?: string } {
|
||||
let area = areaOverride;
|
||||
let action: string | undefined;
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const arg = raw[i];
|
||||
if (arg === "--") break;
|
||||
if (arg.startsWith("-") && arg !== "-") {
|
||||
const key = arg.replace(/^-+/, "").split("=")[0];
|
||||
const flags = commandFlags(area, action);
|
||||
const kind = flags[key] || flags[Object.keys(flags).find(k => k.toLowerCase() === key.toLowerCase()) || ""];
|
||||
if (!arg.includes("=") && ((kind === "value" && raw[i + 1] && !raw[i + 1].startsWith("-")) || (kind !== "value" && separatedBoolean(raw[i + 1]) !== undefined))) i++;
|
||||
continue;
|
||||
}
|
||||
if (!area) area = arg.toLowerCase();
|
||||
else { action = arg.toLowerCase(); break; }
|
||||
}
|
||||
return { area, action };
|
||||
}
|
||||
|
||||
function distance(left: string, right: string): number {
|
||||
let previous = Array.from({ length: right.length + 1 }, (_, i) => i);
|
||||
for (let i = 0; i < left.length; i++) {
|
||||
const row = [i + 1];
|
||||
for (let j = 0; j < right.length; j++) row.push(Math.min(row[j] + 1, previous[j + 1] + 1, previous[j] + Number(left[i] !== right[j])));
|
||||
previous = row;
|
||||
}
|
||||
return previous[right.length];
|
||||
}
|
||||
|
||||
/** Read just the global JSON switch, even when strict parsing will fail. */
|
||||
export function isJsonRequested(raw: string[]): boolean {
|
||||
let enabled = false;
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const arg = raw[i];
|
||||
if (arg === "--") break;
|
||||
if (/^--(?:json|j)(?:=|$)/i.test(arg) || /^-j$/i.test(arg)) {
|
||||
const inline = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : undefined;
|
||||
enabled = (inline !== undefined ? explicitBoolean(inline) : separatedBoolean(raw[i + 1])) ?? true;
|
||||
}
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
|
||||
export function parseArgs(rawArgs: string[], areaOverride?: string): CliParsedArgs {
|
||||
const options: Record<string, string | boolean | number> = {};
|
||||
const positional: string[] = [];
|
||||
const context = findContext(rawArgs, areaOverride);
|
||||
const flags = commandFlags(context.area, context.action);
|
||||
const localFlags = localCommandFlags(context.area, context.action);
|
||||
|
||||
for (let i = 0; i < rawArgs.length; i++) {
|
||||
const arg = rawArgs[i];
|
||||
if (arg === "--") { positional.push(...rawArgs.slice(i + 1)); break; }
|
||||
if (!arg.startsWith("-") || arg === "-") { positional.push(arg); continue; }
|
||||
|
||||
if (arg === "--") {
|
||||
positional.push(...rawArgs.slice(i + 1));
|
||||
break;
|
||||
const body = arg.replace(/^-+/, "");
|
||||
const eqIdx = body.indexOf("=");
|
||||
const inputKey = eqIdx === -1 ? body : body.slice(0, eqIdx);
|
||||
const key = Object.hasOwn(flags, inputKey) ? inputKey : Object.keys(flags).find(k => k.toLowerCase() === inputKey.toLowerCase());
|
||||
if (!key) {
|
||||
const nearest = Object.keys(flags).sort((a, b) => distance(inputKey, a) - distance(inputKey, b))[0];
|
||||
const suggestion = nearest && distance(inputKey, nearest) <= Math.max(1, Math.floor(inputKey.length / 3)) ? `。是否想用 --${nearest}?` : "";
|
||||
throw usageError(`未知选项: ${arg.split("=")[0]}${suggestion}`);
|
||||
}
|
||||
const globalPrefix = positional.length === 0 && Object.hasOwn(GLOBAL_FLAGS, key);
|
||||
const kind: FlagKind = globalPrefix ? GLOBAL_FLAGS[key] : flags[key];
|
||||
const inline = eqIdx === -1 ? undefined : body.slice(eqIdx + 1);
|
||||
const next = rawArgs[i + 1];
|
||||
let value: string | boolean;
|
||||
if (kind === "boolean") {
|
||||
if (inline !== undefined) {
|
||||
const parsed = explicitBoolean(inline);
|
||||
if (parsed === undefined) throw usageError(`选项 --${key} 需要布尔值 true/false 或 1/0`);
|
||||
value = parsed;
|
||||
} else if (separatedBoolean(next) !== undefined) {
|
||||
value = separatedBoolean(next)!;
|
||||
i++;
|
||||
} else value = true;
|
||||
} else if (inline !== undefined) {
|
||||
if (!inline.length) throw usageError(`选项 --${key} 缺少值`);
|
||||
value = kind === "boolean-or-value" ? explicitBoolean(inline) ?? inline : inline;
|
||||
} else if (next !== undefined && next !== "--" && (!next.startsWith("-") || /^-\d+(?:\.\d+)?$/.test(next))) {
|
||||
value = kind === "boolean-or-value" ? separatedBoolean(next) ?? next : next;
|
||||
i++;
|
||||
} else if (kind === "boolean-or-value") value = true;
|
||||
else throw usageError(`选项 --${key} 缺少值`);
|
||||
|
||||
if (arg.startsWith("--")) {
|
||||
const eqIdx = arg.indexOf("=");
|
||||
if (eqIdx !== -1) {
|
||||
const key = arg.slice(2, eqIdx);
|
||||
const val = arg.slice(eqIdx + 1);
|
||||
options[key] = val;
|
||||
} else {
|
||||
const key = arg.slice(2);
|
||||
const keyLower = key.toLowerCase();
|
||||
const next = rawArgs[i + 1];
|
||||
if (KNOWN_BOOLEAN_FLAGS.has(key) || KNOWN_BOOLEAN_FLAGS.has(keyLower)) {
|
||||
if (isExplicitBooleanLiteral(next)) {
|
||||
const boolVal = next!.toLowerCase() === "true";
|
||||
options[key] = boolVal;
|
||||
if (key !== keyLower) options[keyLower] = boolVal;
|
||||
i++;
|
||||
} else {
|
||||
options[key] = true;
|
||||
if (key !== keyLower) options[keyLower] = true;
|
||||
}
|
||||
} else {
|
||||
if (next && !next.startsWith("-")) {
|
||||
options[key] = next;
|
||||
i++;
|
||||
} else {
|
||||
options[key] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg.startsWith("-") && arg.length > 1) {
|
||||
const flag = arg.slice(1);
|
||||
const flagLower = flag.toLowerCase();
|
||||
if (flagLower === "h" || flag === "?") {
|
||||
options.help = true;
|
||||
} else if (flagLower === "j") {
|
||||
options.json = true;
|
||||
} else if (flagLower === "v") {
|
||||
options.version = true;
|
||||
} else if (flag === "o") {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
options.outputFile = next;
|
||||
i++;
|
||||
} else {
|
||||
options.o = true;
|
||||
}
|
||||
} else if (flag === "c") {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
options.c = next;
|
||||
i++;
|
||||
} else {
|
||||
options.c = true;
|
||||
}
|
||||
} else {
|
||||
options[flag] = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
positional.push(arg);
|
||||
options[key] = value;
|
||||
// Preserve command-specific short names; global short names also get their semantic key.
|
||||
const globalNames: Record<string, string> = { h: "help", "?": "help", j: "json", v: "version", V: "version", c: "corp", o: "outputFile" };
|
||||
if (globalNames[key] && (globalPrefix || !Object.hasOwn(localFlags, key) || key === "j" || key === "o" || key === "V")) options[globalNames[key]] = value;
|
||||
}
|
||||
|
||||
const area = positional[0]?.toLowerCase();
|
||||
const action = positional[1]?.toLowerCase();
|
||||
const args = positional.slice(2);
|
||||
|
||||
return {
|
||||
area,
|
||||
action,
|
||||
args,
|
||||
positional,
|
||||
options,
|
||||
raw: rawArgs,
|
||||
};
|
||||
return { area: positional[0]?.toLowerCase(), action: positional[1]?.toLowerCase(), args: positional.slice(2), positional, options, raw: rawArgs };
|
||||
}
|
||||
|
||||
export function stringOption(
|
||||
|
||||
+3
-31
@@ -2,7 +2,7 @@ import { writeFileSync } from "node:fs";
|
||||
import { formatVersionLabel } from "../version.js";
|
||||
import type { OutputOptions } from "./types.js";
|
||||
import { PayloadTooLargeError } from "./errors.js";
|
||||
import { renderScopedHelp } from "./help.js";
|
||||
import { renderScopedHelp, HELP_REGISTRY } from "./help.js";
|
||||
|
||||
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
|
||||
|
||||
@@ -186,35 +186,7 @@ export function printHelp(target: string[] = []): string {
|
||||
hose-use <命令域> <子命令> [参数] [选项]
|
||||
|
||||
核心命令域:
|
||||
context 查看全局运行上下文与身份诊断 (context, status, whoami, env)
|
||||
auth 认证与凭证管理 (login, status, refresh, import, accounts, switch-account)
|
||||
corps 多企业租户管理 (list, search <关键词>, switch, current, add-link)
|
||||
aipro 合思 AI PRO 确定性审批仲裁网关入口 (status, scopes, bind, checklist, review, decide, logs)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, analyze, node, tail, job, create, copy, delete, toggle, publish, patch, save, history, logs, check)
|
||||
bill 单据检索、模板规格与审批动作 (list, get <单号|ID> [--risk], spec <模板ID>, approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
|
||||
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
|
||||
task 待办中心与审批任务 (todo, approved, records, submitted, cc)
|
||||
message 消息中心与通知管理 (list, count, read, read-all)
|
||||
app 应用管理 (桌面端工作台业务应用: list [--keyword], get <应用ID|名称>)
|
||||
menu 桌面端主导航菜单树与模块 (list, tree, apps)
|
||||
platform 自建应用与数据模型 (list, get, entities, schema, records [--all], record get|create|edit|batch-edit, audit, permissions, imports)
|
||||
datalink platform 的同义入口,面向 DataLink 业务对象查询
|
||||
dimension 系统/自定义档案维度 (list, items <维度>)
|
||||
feetype 费用类型管理与字段规格配置 (list, get, spec <模板ID>, create, update, disable, enable, move, fields)
|
||||
role 角色定义与成员 (list, groups, members <角色>)
|
||||
permission 权限模型快照 (get)
|
||||
rule 本地 AI 审批规约管理 (scopes, scope <索引号|场景>, list, get, add, delete)
|
||||
approval 确定性审批网关与要点仲裁 (audit points <单号>, checklist <单号>, review <单号>, decide <单号>)
|
||||
skill Agent Skill 管理 (install, status, dump)
|
||||
probe 连通性诊断 (probe [corpId])
|
||||
update 版本自更新与发布记录 (update, update check, update --changelog, --github, --gitea, --repo=<owner/repo>)
|
||||
openapi OpenAPI 3.1.0 规范导出与凭证查看 (openapi, openapi --raw, openapi paths, openapi info, openapi keys)
|
||||
keys 企业 OpenAPI 接入凭证一键获取 (keys [--reveal|-r])
|
||||
store 应用中心已购应用与应用商店探查 (list, search <关键词>, get <ID>)
|
||||
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
|
||||
service 常驻守护进程管理 (service start|stop|restart|status|logs|poll)
|
||||
mcp MCP Server 运行 (serve)
|
||||
${Object.entries(HELP_REGISTRY).map(([area, topic]) => ` ${area.padEnd(12)}${topic.summary} (${Object.keys(topic.commands).join(", ")})`).join("\n")}
|
||||
version 查看版本信息
|
||||
|
||||
全局选项:
|
||||
@@ -295,7 +267,7 @@ export function printHelp(target: string[] = []): string {
|
||||
hose-use service status # 查看守护进程运行状态与接口地址
|
||||
hose-use service poll --corp=<id> # 轮询待办/消息并持久化去重事件
|
||||
hose-use probe # 诊断当前企业鉴权连通性
|
||||
hose-use skill install # 安装 Agent 技能到用户目录
|
||||
hose-use skill install --yes # 安装 Agent 技能到用户目录
|
||||
hose-use update # 自动检查并升级到最新版本
|
||||
hose-use update --github # 强制走官方 GitHub 源升级
|
||||
hose-use update --changelog # 查看版本发布历史
|
||||
|
||||
+31
-31
@@ -26,6 +26,7 @@ import { handleContextCommand } from "./commands/context.js";
|
||||
import { handleKeysCommand } from "./commands/keys.js";
|
||||
import { handleStoreCommand } from "./commands/store.js";
|
||||
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
||||
import { COMMAND_METADATA, type CliCommandMetadata } from "./command-metadata.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
||||
|
||||
export type CliCommandHandler = (
|
||||
@@ -34,9 +35,8 @@ export type CliCommandHandler = (
|
||||
options: CliRunOptions
|
||||
) => Promise<CliResult>;
|
||||
|
||||
export interface CliCommandDefinition {
|
||||
export interface CliCommandDefinition extends CliCommandMetadata {
|
||||
area: string;
|
||||
aliases: string[];
|
||||
standing?: boolean | ((args: string[]) => boolean);
|
||||
handler: CliCommandHandler;
|
||||
}
|
||||
@@ -44,12 +44,12 @@ export interface CliCommandDefinition {
|
||||
export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
{
|
||||
area: "context",
|
||||
aliases: ["status", "whoami", "env"],
|
||||
...COMMAND_METADATA.context,
|
||||
handler: (parsed, runtime) => handleContextCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "aipro",
|
||||
aliases: [],
|
||||
...COMMAND_METADATA.aipro,
|
||||
handler: async (parsed) => {
|
||||
const { runAiProCli } = await import("../aipro-cli.js");
|
||||
const aiproIdx = parsed.raw.findIndex((a) => a.toLowerCase() === "aipro");
|
||||
@@ -59,139 +59,139 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
},
|
||||
{
|
||||
area: "auth",
|
||||
aliases: ["login"],
|
||||
...COMMAND_METADATA.auth,
|
||||
handler: (parsed, runtime) => handleAuthCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "corps",
|
||||
aliases: ["corp"],
|
||||
...COMMAND_METADATA.corps,
|
||||
handler: (parsed, runtime) => handleCorpsCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "config",
|
||||
aliases: ["mode"],
|
||||
...COMMAND_METADATA.config,
|
||||
handler: (parsed, runtime) => handleConfigCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "workflow",
|
||||
aliases: ["workflows", "wf"],
|
||||
...COMMAND_METADATA.workflow,
|
||||
handler: (parsed, runtime) => handleWorkflowCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "bill",
|
||||
aliases: ["bills", "fee", "fees", "invoice", "invoices"],
|
||||
...COMMAND_METADATA.bill,
|
||||
handler: (parsed, runtime) => handleBillCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "flow",
|
||||
aliases: ["flows", "trace"],
|
||||
...COMMAND_METADATA.flow,
|
||||
handler: (parsed, runtime) => handleFlowCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "contact",
|
||||
aliases: ["contacts", "staff", "staffs"],
|
||||
...COMMAND_METADATA.contact,
|
||||
handler: (parsed, runtime) => handleContactCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "task",
|
||||
aliases: ["tasks", "todo"],
|
||||
...COMMAND_METADATA.task,
|
||||
handler: (parsed, runtime) => handleTaskCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "dimension",
|
||||
aliases: ["dimensions", "archive", "archives"],
|
||||
...COMMAND_METADATA.dimension,
|
||||
handler: (parsed, runtime) => handleDimensionCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "feetype",
|
||||
aliases: ["feetypes", "fee-type", "fee-types", "expense-type", "expense-types", "costtype"],
|
||||
...COMMAND_METADATA.feetype,
|
||||
handler: (parsed, runtime) => handleFeeTypeCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "role",
|
||||
aliases: ["roles"],
|
||||
...COMMAND_METADATA.role,
|
||||
handler: (parsed, runtime) => handleRoleCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "permission",
|
||||
aliases: ["permissions"],
|
||||
...COMMAND_METADATA.permission,
|
||||
handler: (parsed, runtime) => handlePermissionCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "rule",
|
||||
aliases: ["rules"],
|
||||
...COMMAND_METADATA.rule,
|
||||
handler: (parsed, runtime) => handleRuleCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "approval",
|
||||
aliases: ["approvals", "audit"],
|
||||
...COMMAND_METADATA.approval,
|
||||
handler: (parsed, runtime) => handleApprovalCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "message",
|
||||
aliases: ["messages", "notify", "notifications"],
|
||||
...COMMAND_METADATA.message,
|
||||
handler: (parsed, runtime) => handleMessageCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "platform",
|
||||
aliases: ["platforms", "datalink", "data-link"],
|
||||
...COMMAND_METADATA.platform,
|
||||
handler: (parsed, runtime) => handlePlatformCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "app",
|
||||
aliases: ["apps", "workbench"],
|
||||
...COMMAND_METADATA.app,
|
||||
handler: (parsed, runtime) => handleAppCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "menu",
|
||||
aliases: ["menus"],
|
||||
...COMMAND_METADATA.menu,
|
||||
handler: (parsed, runtime) => handleMenuCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "skill",
|
||||
aliases: ["skills"],
|
||||
...COMMAND_METADATA.skill,
|
||||
handler: (parsed, runtime) => handleSkillCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "probe",
|
||||
aliases: ["diagnose"],
|
||||
...COMMAND_METADATA.probe,
|
||||
handler: (parsed, runtime) => handleProbeCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "update",
|
||||
aliases: ["upgrade", "self-update", "changelog"],
|
||||
...COMMAND_METADATA.update,
|
||||
handler: (parsed, runtime, options) => handleUpdateCommand(parsed, runtime, options),
|
||||
},
|
||||
{
|
||||
area: "openapi",
|
||||
aliases: ["schema", "spec"],
|
||||
...COMMAND_METADATA.openapi,
|
||||
handler: (parsed, runtime) => handleOpenApiCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "keys",
|
||||
aliases: ["key", "secret", "secrets"],
|
||||
...COMMAND_METADATA.keys,
|
||||
handler: (parsed, runtime) => handleKeysCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "store",
|
||||
aliases: ["market"],
|
||||
...COMMAND_METADATA.store,
|
||||
handler: (parsed, runtime) => handleStoreCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "http",
|
||||
aliases: ["server", "web"],
|
||||
...COMMAND_METADATA.http,
|
||||
standing: true,
|
||||
handler: (parsed, runtime) => handleHttpCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "service",
|
||||
aliases: ["daemon"],
|
||||
...COMMAND_METADATA.service,
|
||||
standing: (args) => args[1]?.toLowerCase() === "run",
|
||||
handler: (parsed, runtime) => handleServiceCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "mcp",
|
||||
aliases: [],
|
||||
...COMMAND_METADATA.mcp,
|
||||
standing: true,
|
||||
handler: (parsed, _runtime, options) => handleMcpCommand(parsed, options),
|
||||
},
|
||||
|
||||
+29
-25
@@ -1,6 +1,7 @@
|
||||
import { VERSION_INFO, formatVersionLabel } from "../version.js";
|
||||
import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js";
|
||||
import { parseArgs, stringOption, booleanOption, outputOptions, isJsonRequested } from "./parser.js";
|
||||
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
|
||||
import { resolveCommandMetadata } from "./command-metadata.js";
|
||||
import { classifyCliError } from "./errors.js";
|
||||
import { initCorpRuntime } from "./helpers.js";
|
||||
import { findCommandByArea, isStandingCommand } from "./registry.js";
|
||||
@@ -29,7 +30,7 @@ async function runCliOnce(
|
||||
): Promise<CliResult> {
|
||||
const stdoutChunks: string[] = [];
|
||||
const stderrChunks: string[] = [];
|
||||
const machineJson = booleanOption(parseArgs(rawArgs).options, ["json", "j"]);
|
||||
const machineJson = isJsonRequested(rawArgs);
|
||||
const originalLog = console.log;
|
||||
const originalError = console.error;
|
||||
|
||||
@@ -62,7 +63,7 @@ async function runCliOnce(
|
||||
|
||||
function isHelpRequested(parsed: CliParsedArgs): boolean {
|
||||
const normArea = (parsed.area || "").replace(/^-+/, "").toLowerCase();
|
||||
if (normArea === "help" || normArea === "h" || normArea === "?") return true;
|
||||
if (normArea === "help" || normArea === "h" || normArea === "?" || parsed.action === "help") return true;
|
||||
|
||||
for (const [key, val] of Object.entries(parsed.options)) {
|
||||
const normKey = key.replace(/^-+/, "").toLowerCase();
|
||||
@@ -79,6 +80,9 @@ function isVersionRequested(parsed: CliParsedArgs): boolean {
|
||||
|
||||
for (const [key, val] of Object.entries(parsed.options)) {
|
||||
const normKey = key.replace(/^-+/, "").toLowerCase();
|
||||
const localFlags = resolveCommandMetadata(parsed.area)?.metadata.flags;
|
||||
if (key === "v" && localFlags?.v) continue;
|
||||
if (key === "version" && localFlags?.version === "value" && typeof val !== "boolean") continue;
|
||||
if (normKey === "version" || normKey === "v") {
|
||||
if (val === true || val === "true" || val === "") return true;
|
||||
}
|
||||
@@ -90,10 +94,28 @@ function resolveHelpTarget(parsed: CliParsedArgs): string[] {
|
||||
if (["help", "h", "?"].includes((parsed.area || "").toLowerCase())) {
|
||||
return [parsed.action, parsed.args[0]].filter((value): value is string => Boolean(value));
|
||||
}
|
||||
return [parsed.area, parsed.action].filter((value): value is string => Boolean(value));
|
||||
return [parsed.area, parsed.action === "help" ? parsed.args[0] : parsed.action].filter((value): value is string => Boolean(value));
|
||||
}
|
||||
|
||||
async function dispatchCli(
|
||||
async function dispatchCli(rawArgs: string[], options: CliRunOptions = {}): Promise<CliResult> {
|
||||
try {
|
||||
return await dispatchParsedCli(rawArgs, options);
|
||||
} catch (error) {
|
||||
return cliErrorResult(error, isJsonRequested(rawArgs));
|
||||
}
|
||||
}
|
||||
|
||||
export function cliErrorResult(error: unknown, jsonMode: boolean): CliResult {
|
||||
const message = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||
const classification = classifyCliError(error);
|
||||
return {
|
||||
stdout: jsonMode ? JSON.stringify({ error: true, message, exitCode: classification.exitCode, ...(classification.nextAction ? { nextAction: classification.nextAction } : {}) }, null, 2) : "",
|
||||
stderr: jsonMode ? "" : `[ERROR] ${message}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`,
|
||||
exitCode: classification.exitCode,
|
||||
};
|
||||
}
|
||||
|
||||
async function dispatchParsedCli(
|
||||
rawArgs: string[],
|
||||
options: CliRunOptions = {}
|
||||
): Promise<CliResult> {
|
||||
@@ -117,7 +139,7 @@ async function dispatchCli(
|
||||
};
|
||||
}
|
||||
|
||||
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
|
||||
const corpIdOption = stringOption(parsed.options, ["corp"]);
|
||||
const statelessOption = booleanOption(parsed.options, ["stateless"]);
|
||||
const statefulOption = booleanOption(parsed.options, ["stateful"]);
|
||||
const outputOpts = outputOptions(parsed.options);
|
||||
@@ -152,24 +174,6 @@ async function dispatchCli(
|
||||
}
|
||||
return await commandDef.handler(parsed, runtime, options);
|
||||
} catch (error) {
|
||||
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||
const classification = classifyCliError(error);
|
||||
if (jsonMode) {
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
error: true,
|
||||
message: errorMsg,
|
||||
exitCode: classification.exitCode,
|
||||
...(classification.nextAction ? { nextAction: classification.nextAction } : {}),
|
||||
}, null, 2),
|
||||
stderr: "",
|
||||
exitCode: classification.exitCode,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] ${errorMsg}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`,
|
||||
exitCode: classification.exitCode,
|
||||
};
|
||||
return cliErrorResult(error, jsonMode);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
| 域 | 内部形态 | 说明 | 详细文档 |
|
||||
|---|---|---|---|
|
||||
| `platform/` | `api / tools / services / analysis / workflow-state / workflow-alert-store / types` | 自建应用(DataLink Platform)与工作流(EASO/Piper)、静态分析、草稿乐观锁状态机与错误指纹告警 | [README.platform.md](./platform/README.platform.md) |
|
||||
| `platform/` | `api / tools / services / workflow/{analysis,branch,nodes,script,state,watch,alert} / types` | 自建应用(DataLink Platform)与工作流(EASO/Piper)、静态分析、草稿乐观锁状态机与错误指纹告警 | [README.platform.md](./platform/README.platform.md) |
|
||||
| `datalink/` | `api / tools / services / types` | 自建应用下的业务对象、字段、记录检索、安全合并编辑(Read-Modify-Write)、台账体检与导入状态 | [README.datalink.md](./datalink/README.datalink.md) |
|
||||
| `bill/` | `api / tools / translator / types` | 费控单据、报销单、发票、审批流时间线、风控扫描与 Markdown 智能转译器 | [README.bill.md](./bill/README.bill.md) |
|
||||
| `approval/` | `index / gateway / parser / repository / service / db / types` | AI PRO 智能审批引擎(DSL 规则解析、确定性安全网关、要点核验与 `core/db` 会话持久化) | [README.approval.md](./approval/README.approval.md) |
|
||||
|
||||
@@ -22,73 +22,18 @@ src/domains/platform/
|
||||
└── tools.ts # MCP tool 注册
|
||||
```
|
||||
|
||||
## CLI 常用命令
|
||||
## 工作流使用与诊断
|
||||
|
||||
```bash
|
||||
hose-use workflow list [--platform-id=<id>|--app-id=<id>]
|
||||
hose-use workflow get <pipelineId>
|
||||
hose-use workflow enum [thirdId] [--third-id=<id>] [--json]
|
||||
hose-use workflow analyze <pipelineId> [--json]
|
||||
hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
|
||||
hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose]
|
||||
hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]
|
||||
hose-use workflow diff-job <jobId1> <jobId2> [--json]
|
||||
hose-use workflow test <pipelineId> [--flow=<单号>] [--record=<ID>] [--body='{...}'] [--dry-run|--yes]
|
||||
hose-use workflow debug <pipelineId> --flow=<单号> --yes
|
||||
hose-use workflow create [--name=<名称>] [--trigger=webhook|clock|datalink|flowform] [--file=<JSON模板>] [--dry-run|--yes]
|
||||
hose-use workflow copy <pipelineId> [--name=<名称>] [--platform-id=<应用ID>] [--dry-run|--yes]
|
||||
hose-use workflow delete <pipelineId> [--dry-run|--yes]
|
||||
hose-use workflow node list <pipelineId>
|
||||
hose-use workflow node get <pipelineId> <节点name或#序号>
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="清洗" --code="..." [--after=<节点>] [--parent=<容器>] [--dry-run|--yes]
|
||||
hose-use workflow node edit <pipelineId> <节点name或#序号> --label="新标题" [--code="..."] [--dry-run|--yes]
|
||||
hose-use workflow node rm <pipelineId> <节点name或#序号> [--dry-run|--yes]
|
||||
hose-use workflow tail <pipelineId> [--job=<jobId>] [--once] [--failed-only] [--interval=2] [--json]
|
||||
hose-use workflow lint-script <pipelineId> [节点标识] [--json]
|
||||
hose-use workflow lint-script --code="<code>" [--type=code-js2|code]
|
||||
hose-use workflow eval-script <pipelineId> <节点标识> [--input='{...}'] [--sample=1] [--timeout=3000]
|
||||
hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
```
|
||||
CLI 命令、触发器分类、生产调试风险、节点与脚本校验、实时监听以及诊断结果契约,统一见 [Workflow 说明](./workflow/README.workflow.md)。
|
||||
|
||||
## 触发器分类与调测路径分支 (Path Branching)
|
||||
## 模块边界
|
||||
|
||||
合思 EASO/Piper 调度引擎下不同首节点(Trigger)底层的调试协议存在显著差异,`hose-use workflow test` 会自动自适应路由:
|
||||
|
||||
| 触发器分类 (`category`) | 常见触发器类型 (`type`) | 调测协议与入参 | CLI 命令与交互行为 |
|
||||
|---|---|---|---|
|
||||
| **`SCHEDULE`** (定时调度) | `clock` | 服务端无 `debugSource`,`inputs: { id: "" }` | **自动模拟触发**:无需 `--flow`,直接秒级派发并抓取执行树 |
|
||||
| **`WEBHOOK`** (外部集成) | `webhook`, `hab-trigger-task`, `xrxs-trigger`, `fxiaoke-trigger` | 服务端维护最近 3 条 Sample 样本 (`/sampleData`),`inputs: { data: { ... } }` | **样本复用与 Payload 注入**:展示参数定义映射 (Key->Label),支持 `--sample=<1\|2\|3>` 直接使用历史真实样本,或 `--body='{...}'` / `--empty` |
|
||||
| **`DATALINK`** (业务对象台账) | `ekuaibao-datalink-*-trigger` | 服务端返回 `fields` 动态列定义与台账记录 | **动态列展示**:按实体结构动态打表,支持 `--record=<ID>` 或 `--flow=<编码>` |
|
||||
| **`FLOW_FORM`** (单据流转) | `ekuaibao-flowform-trigger`, `ekuaibao-ebot-trigger` | 服务端返回单据列表与表单定义 | **单据列表与筛选**:支持 `--flow=<单号>`,未提供时拉取候选单据表供挑选 |
|
||||
|
||||
|
||||
## 生产环境调试缺陷与安全防线(合思平台缺陷记录)
|
||||
|
||||
> [!WARNING] **合思后端架构缺陷:前端置灰防御,后端裸奔无防**
|
||||
> 1. **前端置灰表象**:合思 Web 控制台在工作流处于【启用中】(`state = 1`)时,会将【调试】与【保存更新】按钮置灰(disabled),给人以“生产启用态无法调试”的假象;
|
||||
> 2. **后端无状态鉴权**:合思 EASO/Piper 调度引擎后端 `POST /api/easo/jobs` 接口**完全未对工作流启用状态进行校验**,只要调用 API 即可在生产环境直接派发调试任务;
|
||||
> 3. **隐蔽快照自增污染**:每次调用 `POST /api/easo/jobs` 调试,服务端均会隐式创建一个新的 Pipeline Snapshot,并将版本号自增(如 `v26.10.10` ➔ `v26.10.13`),无声息地污染发布历史;
|
||||
> 4. **真实破坏性副作用风险**:合思后端**不具备调试沙箱(Sandbox)隔离**,调试是以真实操作员身份在生产环境真实运行。若下游包含单据自动审批、外部 HTTP 请求、修改业务对象台账或短信通知节点,一旦条件命中,将产生**不可逆的真实生产变更**!
|
||||
|
||||
### `hose-use` 生产环境调试特性与全方位风险提示
|
||||
|
||||
在合思 Web 控制台中,已发布启用的工作流【调试】按钮被置灰,人工无法直接发起测试;
|
||||
`hose-use` **保留了穿透前端限制的直达调测能力**(为线上排障与即时验证多保留了一条宝贵的高级通道),但同时提供**充分的安全提示与风险告知**:
|
||||
- **候选单据提示**:在拉取调试候选数据源时,高亮提示当前工作流处于【🟢 生产启用中】;
|
||||
- **调试执行提示**:在发起端到端调试时,置顶打印醒目的【生产启用态调试安全提醒】,提醒操作者合思无沙箱、写节点会真实生效以及快照版本会自增,确保线上调测“有路径、知风险、审慎用”。
|
||||
- `workflow/{analysis,branch,nodes,script,state,watch,alert}/index.ts` 是各能力的目录出口;内部引用直接指向所属目录,不再保留根目录的一行转发文件。
|
||||
- 单元测试与对应实现放在同一目录;分层测试检查已移除路径,保留正常的模块出口文件。
|
||||
- MVEL 校验先识别字符串、转义及行/块注释,再检查有效代码中的括号、return 和节点引用;这属于轻量静态检查,不是完整的 MVEL 编译器。JavaScript 校验仍检查函数体语法,不执行脚本。
|
||||
|
||||
## 详细文档
|
||||
|
||||
完整接口说明、认证链路、MCP tool 列表见:
|
||||
|
||||
[docs/modules/platform.md](../../../docs/modules/platform.md)
|
||||
|
||||
## 调试与诊断结果契约
|
||||
|
||||
- 调试属于写操作:`--dry-run` 仅展示目标、发布选项和风险,不创建客户端或发起 Job;实际执行需要 `--yes` / `--confirm`。启用中的工作流仍可在确认后直接调试。
|
||||
- JSON 和预览均包含风险信息。执行结果提供 `productionEnabled`(状态未知时为 `null`)和 `warnings`。
|
||||
- `outcome` 为 `completed`、`failed`、`timed_out` 或 `incomplete`;只有完整成功才返回退出码 `0`。超时不取消已经发起的 Job,保留 `jobId` 以供 `workflow job` 续查。
|
||||
- `timedOut`、`diagnosticsComplete`、`diagnosticsErrors` 区分执行超时、读取失败与没有失败节点;权限错误不再被当成空的成功结果。
|
||||
- 条件解释支持已声明的比较操作符、嵌套 AND/OR 和循环上下文;缺少证据、不支持的值类型或执行尚未结束时,`evaluation` / `matched` 为 `null`,不据此声称分支判定为 False。
|
||||
- `diff-job` 按父任务路径、循环路径及重复次数配对实例;JSON 节点包含 `instanceKey` / `currentLoopPath`,输出变化也计入差异。
|
||||
- `execution-context.ts` 是条件解释和 Job diff 共用的纯执行实例索引,不负责请求或 CLI 输出。
|
||||
@@ -1 +0,0 @@
|
||||
export * from "./workflow/analysis/index.js";
|
||||
@@ -2,7 +2,7 @@ import { KyInstance } from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import * as api from "./api.js";
|
||||
import { ValidationError } from "../../core/errors.js";
|
||||
import { explainConditionBranches } from "./workflow-branch.js";
|
||||
import { explainConditionBranches } from "./workflow/branch/index.js";
|
||||
import { indexExecutionContexts } from "./execution-context.js";
|
||||
import {
|
||||
Platform,
|
||||
@@ -923,7 +923,7 @@ export {
|
||||
explainConditionBranches,
|
||||
type ConditionBranchExplanation,
|
||||
type ConditionRuleExplanation,
|
||||
} from "./workflow-branch.js";
|
||||
} from "./workflow/branch/index.js";
|
||||
|
||||
export {
|
||||
classifyWorkflowTrigger,
|
||||
|
||||
@@ -645,7 +645,7 @@ export interface WorkflowTestReport {
|
||||
triggerLabel?: string;
|
||||
executionTree: WorkflowTaskExecution[];
|
||||
failedExecutions: WorkflowTaskExecution[];
|
||||
conditionDiagnoses: import("./workflow-branch.js").ConditionBranchExplanation[];
|
||||
conditionDiagnoses: import("./workflow/branch/index.js").ConditionBranchExplanation[];
|
||||
}
|
||||
|
||||
// ── 触发器元类型分类与智能路径路由 ───────────────────────────────────────────────
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export * from "./workflow/alert/index.js";
|
||||
@@ -1 +0,0 @@
|
||||
export * from "./workflow/branch/index.js";
|
||||
@@ -1 +0,0 @@
|
||||
export * from "./workflow/nodes/index.js";
|
||||
@@ -1 +0,0 @@
|
||||
export * from "./workflow/script/index.js";
|
||||
@@ -1 +0,0 @@
|
||||
export * from "./workflow/state/index.js";
|
||||
@@ -1 +0,0 @@
|
||||
export * from "./workflow/watch/index.js";
|
||||
@@ -0,0 +1,74 @@
|
||||
# Workflow 工作流模块
|
||||
|
||||
Platform 域下工作流能力的命令、协议与诊断契约。总体边界见 [Platform 概览](../README.platform.md)。
|
||||
|
||||
## CLI 常用命令
|
||||
|
||||
```bash
|
||||
hose-use workflow list [--platform-id=<id>|--app-id=<id>]
|
||||
hose-use workflow get <pipelineId>
|
||||
hose-use workflow enum [thirdId] [--third-id=<id>] [--json]
|
||||
hose-use workflow analyze <pipelineId> [--json]
|
||||
hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
|
||||
hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose]
|
||||
hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]
|
||||
hose-use workflow diff-job <jobId1> <jobId2> [--json]
|
||||
hose-use workflow test <pipelineId> [--flow=<单号>] [--record=<ID>] [--body='{...}'] [--dry-run|--yes]
|
||||
hose-use workflow debug <pipelineId> --flow=<单号> --yes
|
||||
hose-use workflow create [--name=<名称>] [--trigger=webhook|clock|datalink|flowform] [--file=<JSON模板>] [--dry-run|--yes]
|
||||
hose-use workflow copy <pipelineId> [--name=<名称>] [--platform-id=<应用ID>] [--dry-run|--yes]
|
||||
hose-use workflow delete <pipelineId> [--dry-run|--yes]
|
||||
hose-use workflow node list <pipelineId>
|
||||
hose-use workflow node get <pipelineId> <节点name或#序号>
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="清洗" --code="..." [--after=<节点>] [--parent=<容器>] [--dry-run|--yes]
|
||||
hose-use workflow node edit <pipelineId> <节点name或#序号> --label="新标题" [--code="..."] [--dry-run|--yes]
|
||||
hose-use workflow node rm <pipelineId> <节点name或#序号> [--dry-run|--yes]
|
||||
hose-use workflow tail <pipelineId> [--job=<jobId>] [--once] [--failed-only] [--interval=2] [--json]
|
||||
hose-use workflow lint-script <pipelineId> [节点标识] [--json]
|
||||
hose-use workflow lint-script --code="<code>" [--type=code-js2|code]
|
||||
hose-use workflow eval-script <pipelineId> <节点标识> [--input='{...}'] [--sample=1] [--timeout=3000]
|
||||
hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
```
|
||||
|
||||
## 触发器分类与调测路径分支 (Path Branching)
|
||||
|
||||
合思 EASO/Piper 调度引擎下不同首节点(Trigger)底层的调试协议存在显著差异,`hose-use workflow test` 会自动自适应路由:
|
||||
|
||||
| 触发器分类 (`category`) | 常见触发器类型 (`type`) | 调测协议与入参 | CLI 命令与交互行为 |
|
||||
|---|---|---|---|
|
||||
| **`SCHEDULE`** (定时调度) | `clock` | 服务端无 `debugSource`,`inputs: { id: "" }` | **自动模拟触发**:无需 `--flow`,直接秒级派发并抓取执行树 |
|
||||
| **`WEBHOOK`** (外部集成) | `webhook`, `hab-trigger-task`, `xrxs-trigger`, `fxiaoke-trigger` | 服务端维护最近 3 条 Sample 样本 (`/sampleData`),`inputs: { data: { ... } }` | **样本复用与 Payload 注入**:展示参数定义映射 (Key->Label),支持 `--sample=<1\|2\|3>` 直接使用历史真实样本,或 `--body='{...}'` / `--empty` |
|
||||
| **`DATALINK`** (业务对象台账) | `ekuaibao-datalink-*-trigger` | 服务端返回 `fields` 动态列定义与台账记录 | **动态列展示**:按实体结构动态打表,支持 `--record=<ID>` 或 `--flow=<编码>` |
|
||||
| **`FLOW_FORM`** (单据流转) | `ekuaibao-flowform-trigger`, `ekuaibao-ebot-trigger` | 服务端返回单据列表与表单定义 | **单据列表与筛选**:支持 `--flow=<单号>`,未提供时拉取候选单据表供挑选 |
|
||||
|
||||
|
||||
## 生产环境调试缺陷与安全防线(合思平台缺陷记录)
|
||||
|
||||
> [!WARNING] **合思后端架构缺陷:前端置灰防御,后端裸奔无防**
|
||||
> 1. **前端置灰表象**:合思 Web 控制台在工作流处于【启用中】(`state = 1`)时,会将【调试】与【保存更新】按钮置灰(disabled),给人以“生产启用态无法调试”的假象;
|
||||
> 2. **后端无状态鉴权**:合思 EASO/Piper 调度引擎后端 `POST /api/easo/jobs` 接口**完全未对工作流启用状态进行校验**,只要调用 API 即可在生产环境直接派发调试任务;
|
||||
> 3. **隐蔽快照自增污染**:每次调用 `POST /api/easo/jobs` 调试,服务端均会隐式创建一个新的 Pipeline Snapshot,并将版本号自增(如 `v26.10.10` ➔ `v26.10.13`),无声息地污染发布历史;
|
||||
> 4. **真实破坏性副作用风险**:合思后端**不具备调试沙箱(Sandbox)隔离**,调试是以真实操作员身份在生产环境真实运行。若下游包含单据自动审批、外部 HTTP 请求、修改业务对象台账或短信通知节点,一旦条件命中,将产生**不可逆的真实生产变更**!
|
||||
|
||||
### `hose-use` 生产环境调试特性与全方位风险提示
|
||||
|
||||
在合思 Web 控制台中,已发布启用的工作流【调试】按钮被置灰,人工无法直接发起测试;
|
||||
`hose-use` **保留了穿透前端限制的直达调测能力**(为线上排障与即时验证多保留了一条宝贵的高级通道),但同时提供**充分的安全提示与风险告知**:
|
||||
- **候选单据提示**:在拉取调试候选数据源时,高亮提示当前工作流处于【🟢 生产启用中】;
|
||||
- **调试执行提示**:在发起端到端调试时,置顶打印醒目的【生产启用态调试安全提醒】,提醒操作者合思无沙箱、写节点会真实生效以及快照版本会自增,确保线上调测“有路径、知风险、审慎用”。
|
||||
|
||||
## 详细文档
|
||||
|
||||
完整接口说明、认证链路、MCP tool 列表见:
|
||||
|
||||
[docs/modules/platform.md](../../../../docs/modules/platform.md)
|
||||
|
||||
## 调试与诊断结果契约
|
||||
|
||||
- 调试属于写操作:`--dry-run` 仅展示目标、发布选项和风险,不创建客户端或发起 Job;实际执行需要 `--yes` / `--confirm`。启用中的工作流仍可在确认后直接调试。
|
||||
- JSON 和预览均包含风险信息。执行结果提供 `productionEnabled`(状态未知时为 `null`)和 `warnings`。
|
||||
- `outcome` 为 `completed`、`failed`、`timed_out` 或 `incomplete`;只有完整成功才返回退出码 `0`。超时不取消已经发起的 Job,保留 `jobId` 以供 `workflow job` 续查。
|
||||
- `timedOut`、`diagnosticsComplete`、`diagnosticsErrors` 区分执行超时、读取失败与没有失败节点;权限错误不再被当成空的成功结果。
|
||||
- 条件解释支持已声明的比较操作符、嵌套 AND/OR 和循环上下文;缺少证据、不支持的值类型或执行尚未结束时,`evaluation` / `matched` 为 `null`,不据此声称分支判定为 False。
|
||||
- `diff-job` 按父任务路径、循环路径及重复次数配对实例;JSON 节点包含 `instanceKey` / `currentLoopPath`,输出变化也计入差异。
|
||||
- `execution-context.ts` 是条件解释和 Job diff 共用的纯执行实例索引,不负责请求或 CLI 输出。
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { analyzeWorkflow } from "./analysis.js";
|
||||
import { PlatformSchema } from "./types.js";
|
||||
import { analyzeWorkflow } from "./index.js";
|
||||
import { PlatformSchema } from "../../types.js";
|
||||
|
||||
describe("Workflow static analysis", () => {
|
||||
it("accepts nullable app center metadata", () => {
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { explainConditionBranches } from "./workflow-branch.js";
|
||||
import type { WorkflowTaskExecution } from "./types.js";
|
||||
import { explainConditionBranches } from "./index.js";
|
||||
import type { WorkflowTaskExecution } from "../../types.js";
|
||||
|
||||
describe("Workflow Condition Branch Diagnosis", () => {
|
||||
const choose = (property = "value") => `@{choose('${JSON.stringify({ key: "source", properties: [{ key: property }] })}')}`;
|
||||
+2
-2
@@ -8,8 +8,8 @@ import {
|
||||
removeWorkflowTask,
|
||||
buildWorkflowTask,
|
||||
summarizeTask,
|
||||
} from "./workflow-nodes.js";
|
||||
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
||||
} from "./index.js";
|
||||
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
|
||||
|
||||
const mockWorkflow: WorkflowDetail = {
|
||||
id: "wf_test_100",
|
||||
+39
-2
@@ -5,8 +5,8 @@ import {
|
||||
lintMvelCode,
|
||||
lintWorkflowScripts,
|
||||
executeJavaScriptSandbox,
|
||||
} from "./workflow-script.js";
|
||||
import type { WorkflowDetail } from "./types.js";
|
||||
} from "./index.js";
|
||||
import type { WorkflowDetail } from "../../types.js";
|
||||
|
||||
describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () => {
|
||||
describe("hasReturnStatement", () => {
|
||||
@@ -187,3 +187,40 @@ describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () =
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("MVEL lexical boundaries", () => {
|
||||
for (const code of [
|
||||
'return "{";',
|
||||
'return wrap("https://example.test/path");',
|
||||
'/* { action_missing */\nreturn 1;',
|
||||
'return "action_missing";',
|
||||
"return 'escaped \\' { action_missing';",
|
||||
'/* comment with "quotes" and // */\r\nreturn [1, 2]; // { action_missing',
|
||||
]) {
|
||||
it(`ignores literals and comments in ${JSON.stringify(code)}`, () => {
|
||||
const result = lintMvelCode(code, new Set());
|
||||
expect(result.issues).toEqual([]);
|
||||
expect(result.referencedNodes).toEqual([]);
|
||||
expect(result.hasReturn).toBe(true);
|
||||
});
|
||||
}
|
||||
|
||||
it("does not count quoted or commented return as executable code", () => {
|
||||
const result = lintMvelCode('value = "return"; /* return 1; */ // return 2;');
|
||||
expect(result.hasReturn).toBe(false);
|
||||
expect(result.issues.map(i => i.rule)).toEqual(["missing-return"]);
|
||||
});
|
||||
|
||||
it("keeps real references and error coordinates while diagnosing unfinished literals", () => {
|
||||
const result = lintMvelCode('// ]\nreturn action_missing;]', new Set());
|
||||
expect(result.issues.find(i => i.rule === "unmatched-brackets")).toMatchObject({ line: 2, column: 23 });
|
||||
expect(result.issues.find(i => i.rule === "dangling-node-reference")?.level).toBe("error");
|
||||
expect(lintMvelCode('return "unfinished').issues.some(i => i.rule === "unterminated-string")).toBe(true);
|
||||
expect(lintMvelCode('return 1;\n /* unfinished').issues.find(i => i.rule === "unterminated-comment")).toMatchObject({ line: 2, column: 3 });
|
||||
});
|
||||
|
||||
it("does not invalidate an entire workflow for literal-only node names", () => {
|
||||
const result = lintWorkflowScripts({ id: "lexical", tasks: [{ name: "action_code", type: "code", code: 'return "action_missing {";' }] } as unknown as WorkflowDetail);
|
||||
expect(result.allValid).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,62 @@
|
||||
import type { WorkflowTask } from "../../types.js";
|
||||
import type { ScriptIssue } from "./types.js";
|
||||
import { hasReturnStatement } from "./lint-js.js";
|
||||
|
||||
/** Mask literals/comments without moving offsets used by diagnostics. */
|
||||
function scanMvelCode(code: string, issues: ScriptIssue[]): string {
|
||||
const masked = code.split("");
|
||||
let mode: "code" | "line" | "block" | "'" | '"' = "code";
|
||||
let start = { line: 1, column: 1 };
|
||||
let line = 1;
|
||||
let column = 1;
|
||||
let escaped = false;
|
||||
|
||||
for (let i = 0; i < code.length; i++) {
|
||||
const ch = code[i];
|
||||
const next = code[i + 1];
|
||||
if (mode === "code") {
|
||||
if (ch === "'" || ch === '"') {
|
||||
mode = ch;
|
||||
start = { line, column };
|
||||
masked[i] = " ";
|
||||
} else if (ch === "/" && (next === "/" || next === "*")) {
|
||||
mode = next === "/" ? "line" : "block";
|
||||
start = { line, column };
|
||||
masked[i] = masked[i + 1] = " ";
|
||||
i++;
|
||||
column++;
|
||||
}
|
||||
} else {
|
||||
if (ch !== "\n" && ch !== "\r") masked[i] = " ";
|
||||
if (mode === "line") {
|
||||
if (ch === "\n" || ch === "\r") mode = "code";
|
||||
} else if (mode === "block") {
|
||||
if (ch === "*" && next === "/") {
|
||||
masked[++i] = " ";
|
||||
column++;
|
||||
mode = "code";
|
||||
}
|
||||
} else if (escaped) {
|
||||
escaped = false;
|
||||
} else if (ch === "\\") {
|
||||
escaped = true;
|
||||
} else if (ch === mode) {
|
||||
mode = "code";
|
||||
}
|
||||
}
|
||||
if (ch === "\n") { line++; column = 1; }
|
||||
else column++;
|
||||
}
|
||||
|
||||
if (mode === "block" || mode === "'" || mode === '"') {
|
||||
issues.push({
|
||||
level: "error",
|
||||
...start,
|
||||
rule: mode === "block" ? "unterminated-comment" : "unterminated-string",
|
||||
message: mode === "block" ? "未闭合的块注释" : `未闭合的字符串: ${mode}`,
|
||||
});
|
||||
}
|
||||
return masked.join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* 静态检查 MVEL (code) 括号闭合与上游节点引用有效性
|
||||
@@ -26,7 +82,8 @@ export function lintMvelCode(
|
||||
return { issues, referencedNodes, hasReturn: false };
|
||||
}
|
||||
|
||||
const hasRet = hasReturnStatement(code);
|
||||
const executableCode = scanMvelCode(code, issues);
|
||||
const hasRet = /\breturn\b/.test(executableCode);
|
||||
if (!hasRet) {
|
||||
issues.push({
|
||||
level: "warning",
|
||||
@@ -37,12 +94,12 @@ export function lintMvelCode(
|
||||
|
||||
// 1. 括号与引号对称性平衡检查
|
||||
const stack: Array<{ char: string; line: number }> = [];
|
||||
const lines = code.split(/\r?\n/);
|
||||
const lines = executableCode.split(/\r?\n/);
|
||||
|
||||
for (let l = 0; l < lines.length; l++) {
|
||||
const lineText = lines[l];
|
||||
// 忽略单行注释
|
||||
const cleanLine = lineText.replace(/\/\/.*$/, "");
|
||||
// 忽略单行注释,以及扫描器已屏蔽的字符串与块注释。
|
||||
const cleanLine = lineText;
|
||||
|
||||
for (let c = 0; c < cleanLine.length; c++) {
|
||||
const ch = cleanLine[c];
|
||||
@@ -80,7 +137,7 @@ export function lintMvelCode(
|
||||
const foundRefs = new Set<string>();
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = nodeRefRegex.exec(code)) !== null) {
|
||||
while ((match = nodeRefRegex.exec(executableCode)) !== null) {
|
||||
foundRefs.add(match[1]);
|
||||
}
|
||||
|
||||
|
||||
+7
-7
@@ -7,9 +7,9 @@ import {
|
||||
failWorkflowSave,
|
||||
hasWorkflowVersionConflict,
|
||||
patchWorkflowDraft,
|
||||
} from "./workflow-state.js";
|
||||
import { WorkflowDetailSchema } from "./types.js";
|
||||
import type { WorkflowDetail } from "./types.js";
|
||||
} from "./index.js";
|
||||
import { WorkflowDetailSchema } from "../../types.js";
|
||||
import type { WorkflowDetail } from "../../types.js";
|
||||
import {
|
||||
getExecutionLogs,
|
||||
getJob,
|
||||
@@ -21,15 +21,15 @@ import {
|
||||
listWorkflowLogs,
|
||||
toggleWorkflow,
|
||||
updateWorkflow,
|
||||
} from "./api.js";
|
||||
} from "../../api.js";
|
||||
import {
|
||||
extractFailureExecutions,
|
||||
findExecutionNode,
|
||||
flattenExecutionTree,
|
||||
isTaskExecutionFailed,
|
||||
} from "./services.js";
|
||||
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
|
||||
import { WorkflowAlertStore } from "./workflow-alert-store.js";
|
||||
} from "../../services.js";
|
||||
import { AuthenticationError, EkbApiError } from "../../../../core/errors.js";
|
||||
import { WorkflowAlertStore } from "../alert/index.js";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
+2
-2
@@ -8,8 +8,8 @@ import {
|
||||
watchSingleJob,
|
||||
watchWorkflowPipeline,
|
||||
type WorkflowWatchEvent,
|
||||
} from "./workflow-watch.js";
|
||||
import type { WorkflowTaskExecution } from "./types.js";
|
||||
} from "./index.js";
|
||||
import type { WorkflowTaskExecution } from "../../types.js";
|
||||
|
||||
describe("workflow-watch - 实时监控与日志流跟踪引擎", () => {
|
||||
describe("TaskExecutionTracker", () => {
|
||||
@@ -5,10 +5,31 @@
|
||||
## 文件职责
|
||||
|
||||
- `embedded-openapi.ts`:内嵌 `specs/openapi.json`(包装层)与 `specs/openapi.raw.json`(原生下游)两份 OpenAPI 规范,供 `hose-use openapi` 命令与 HTTP 文档页读取;产物由 `scripts/bundle-openapi.ts` / `scripts/generate-raw-openapi.ts` 生成。
|
||||
- `embedded-skill.ts`:内嵌 `skills/hose-use/` 全量 Skill 文件(`EMBEDDED_SKILL_FILES`),支持 `hose-use skill install` 一键安装到全局目录,并在编译二进制运行时自动同步(`syncGlobalSkillIfPresent`)。
|
||||
- `embedded-skill.ts`:内嵌 `skills/hose-use/` 全量 Skill 文件(`EMBEDDED_SKILL_FILES`),支持 `hose-use skill install --yes` 一键安装到全局目录,并在编译二进制运行时自动同步(`syncGlobalSkillIfPresent`)。
|
||||
- `runtime.ts`:二进制运行态自省——`isCompiledBinary` 判定编译态、`resolveAppRoot` 解析应用根目录、`resolveDefaultLauncher` 解析启动配置。
|
||||
|
||||
## 依赖约束
|
||||
|
||||
- 仅可被入口层与 `cli/` 导入;不得反向依赖 `domains/`。
|
||||
- 内嵌产物必须随 git 提交(`specs/*.json`),保证编译二进制无需构建步骤即可携带完整规范。
|
||||
|
||||
## 安装与自更新完整性
|
||||
|
||||
Release 同时发布平台二进制、归档和 `checksums.txt`。安装脚本与 `hose-use update` 固定一次解析得到的 tag,核对所选资产的 SHA-256,再进行解包或替换;校验条目缺失、重复或不匹配时失败。下载代理和 Gitea 不接收 GitHub 认证头。
|
||||
|
||||
安装脚本支持 `HOSE_USE_VERSION=0.8.14` 固定版本,`HOSE_USE_MIRROR=auto|github|gitea` 选择镜像策略,`HOSE_USE_INSTALL_DIR=/path/to/bin` 指定安装目录。这些变量只作用于脚本;CLI 自更新继续使用其已有的源选择参数。默认仍优先选择可写的常见 bin 目录。
|
||||
|
||||
归档保留 `hose-use-<平台>-<架构>` 文件名。安装端只将精确匹配的成员流式写入临时文件,随后安装为 `hose-use` 并创建 `hose-aipro` 别名;归档中的目录、其他文件和别名不会直接解到 bin。安装脚本在目标文件系统暂存并重命名,自更新也在可执行文件目录暂存,以保留替换的原子性。
|
||||
|
||||
Skill 初始化明确执行 `skill install --yes`;失败会报告二进制已安装和恢复命令,不再假报成功。旧 Release 没有校验清单时,这套安装/更新流程会明确拒绝;应与包含清单的新 Release 一起交付,不静默跳过验证或修改旧资产。
|
||||
|
||||
## 构建与发布验证
|
||||
|
||||
- PR/main CI:冻结依赖安装、版本一致性、类型检查、全套测试、独立二进制和插件 bundle 的构建及 MCP 协议验证。
|
||||
- 独立二进制:`bun run build:binary`;`bun run scripts/verify-binary.ts dist/bin/hose-use` 在空工作目录和没有 Bun 的 PATH 下验证版本、单工具发现、真实调用与错误返回。
|
||||
- 插件 bundle:`bun run build:plugin`;`.mcp.json` 指定 Bun 1.3.14+,与共享 CLI 的 `bun:sqlite` 依赖一致;`bun run scripts/verify-binary.ts dist/mcp/server.js --plugin` 验证实际产物。
|
||||
- Release:构建前检查 tag 版本、实际 HEAD 和 main 祖先关系;手动触发也必须输入 tag。正式构建显式使用 `--release`,两个发布源都上传校验清单,后台镜像上传失败会使任务失败。
|
||||
|
||||
版本准备使用 `codex/release-vX.Y.Z` 或 `release/vX.Y.Z` 分支及干净工作区。`bun run bump <版本|patch|minor|major>` 在写入前校验分支、递增版本和重复 tag,再同步仓库版本及生成物;全局开发版同步通过单独的 `bun run dev:override` 执行。预检失败不写版本文件;后续生成步骤若失败,会保留可复查的仓库修改以便修复。
|
||||
|
||||
完成本地验证后,提交发布分支、开 PR、等待 CI 和审查、合入并同步 main;然后创建带说明的 tag,依次推送 `home`、`origin`,最后检查两个源的 Release 产物。GitHub 是否能把 CI 设置为强制合并条件取决于仓库规则与套餐,workflow 本身只负责执行检查。
|
||||
+7
-4
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { runCli } from "./cli/runner.js";
|
||||
import { redactSensitiveText, writeStdoutChunk } from "./cli/printer.js";
|
||||
import { VERSION } from "./version.js";
|
||||
import type { CliResult } from "./cli/types.js";
|
||||
import type { CliResult, CliRunOptions } from "./cli/types.js";
|
||||
|
||||
export const HOSE_CLI_TOOL_NAME = "hose_cli";
|
||||
export const HOSE_MCP_MODE_ENV = "HOSE_MCP_MODE";
|
||||
@@ -118,7 +118,7 @@ export function cliResult(result: CliResult): {
|
||||
};
|
||||
}
|
||||
|
||||
export function createServer(options: { mode?: string; enabled?: boolean } = {}) {
|
||||
export function createServer(options: { mode?: string; enabled?: boolean; runtime?: CliRunOptions } = {}) {
|
||||
const enabled = options.enabled ?? resolveMcpEnabled();
|
||||
|
||||
const server = new Server(
|
||||
@@ -203,6 +203,9 @@ export function createServer(options: { mode?: string; enabled?: boolean } = {})
|
||||
const result = await runCli(cliArgs, {
|
||||
appRoot,
|
||||
entryFile: serverEntryFile,
|
||||
...options.runtime,
|
||||
// MCP output belongs to the protocol transport, never a terminal stream.
|
||||
writeStdout: undefined,
|
||||
});
|
||||
return cliResult(result);
|
||||
} catch (error) {
|
||||
@@ -217,8 +220,8 @@ export function createServer(options: { mode?: string; enabled?: boolean } = {})
|
||||
return server;
|
||||
}
|
||||
|
||||
export async function startServer() {
|
||||
const server = createServer();
|
||||
export async function startServer(runtime?: CliRunOptions) {
|
||||
const server = createServer({ runtime });
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
console.error(`hose-use MCP Server (v${VERSION}) running on stdio [mode: ${resolveMcpMode()}]`);
|
||||
|
||||
Reference in new issue
Block a user