Compare commits

...
17 Commits
Author SHA1 Message Date
yunyingk 0554f41d12 Merge pull request #73 from yunyingk/codex/release-v0.8.6
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): v0.8.6
2026-09-13 13:43:51 +08:00
gitea 8e4535a812 chore(release): bump version to v0.8.6 2026-09-13 13:42:56 +08:00
yunyingk 68c7541cf6 Merge pull request #72 from yunyingk/fix/dev-check-symlink-awareness
fix: recognize canonical Skill symlinks
2026-09-12 23:36:00 +08:00
gitea 134ebf0d2e fix: treat canonical skill symlinks as healthy 2026-09-12 23:34:50 +08:00
yunyingk 5d441d9e90 Merge pull request #71 from yunyingk/feat/dev-hygiene-check
feat: 增加开发环境卫生检查与安全清理
2026-09-12 23:29:20 +08:00
gitea 3db5907357 feat: add development hygiene checks and cleanup 2026-09-12 23:26:08 +08:00
yunyingk b6551497d7 Merge pull request #70 from yunyingk/fix/canonical-skill-install
fix: 统一 Agent Skill 全局安装目录
2026-09-12 23:13:02 +08:00
gitea 33db72f863 fix: install skill only in canonical global directory 2026-09-12 23:02:25 +08:00
gitea f26eae7b08 fix: make dry-run next steps executable 2026-09-11 17:41:58 +08:00
gitea 1571c524c1 feat: protect all CLI state mutations 2026-09-11 17:40:47 +08:00
gitea 3e072b490e feat: install development build globally 2026-09-11 17:35:29 +08:00
gitea 7cfb68e434 feat: migrate legacy hose configuration paths 2026-09-11 17:24:08 +08:00
gitea d15fa65517 feat: sync release version plugin and OpenAPI artifacts 2026-09-11 17:21:41 +08:00
gitea 34983e1c07 feat: add layered CLI help registry 2026-09-11 17:18:39 +08:00
gitea a5c0146c8d feat: add semantic CLI exit codes 2026-09-11 17:11:51 +08:00
gitea 45eb83a609 feat: unify CLI dry-run and write confirmation 2026-09-11 16:53:14 +08:00
gitea 639aaa9271 feat: embed keys and store skill guidance 2026-09-11 16:35:21 +08:00
48 changed files with 2712 additions and 620 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.8.4",
"version": "0.8.6",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
+19 -5
View File
@@ -1,4 +1,4 @@
# hose-use (v0.8.5)
# hose-use (v0.8.6)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -17,6 +17,19 @@ bun install
bun run cli <command>
```
### 方式三:将当前工作区安装为全局开发版
开发过程中需要让 PATH 中的 `hose-use` 立即使用当前源码时:
```bash
bun run dev:override
hose-use version
```
该命令会构建本机二进制、原子替换全局 `hose-use`,同步 `~/.agents/skills/hose-use`,并保留 `hose-aipro` 别名;后台服务若正在运行会自动重启。只预览动作可运行 `bun run dev:override -- --dry-run`。
> 开发版安装会覆盖当前 PATH 中的 `hose-use`,适合本机测试;发布环境请使用正式 Release 安装脚本。不要用 `npm install -g .` 代替,它会留下不会随源码更新的旧副本。
---
### CLI 常用命令速查 (`hose-use`)
@@ -46,13 +59,13 @@ hose-use menu list # 查看桌面端全站一级主
hose-use workflow list # 汇总查看全部工作流列表
hose-use workflow get <pipelineId> # 获取工作流详情与节点结构
hose-use workflow find --task=code-js2 # 搜索包含特定节点类型的工作流
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
hose-use workflow save <pipelineId> --file=workflow.json # 按完整快照保存草稿
hose-use workflow toggle <pipelineId> --state=1 --yes # 启用/停用工作流
hose-use workflow save <pipelineId> --file=workflow.json --yes # 按完整快照保存草稿
hose-use workflow patch <pipelineId> --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json
hose-use workflow history <pipelineId> # 查看服务端版本快照历史
hose-use workflow logs <pipelineId> --state=FAILED # 查看工作流运行错误日志
hose-use workflow check --json --fail-on-alert # 检查错误管道并按错误计数去重提醒
hose-use workflow publish <pipelineId> # 保存后的发布/启用
hose-use workflow publish <pipelineId> --yes # 保存后的发布/启用
hose-use platform list # 查看企业下所有启用的自建应用
# 5. 单据与费用明细管理 (DataLink 字典自动还原 & 200KB 防爆拦截)
@@ -94,7 +107,8 @@ hose-use mcp # 启动 MCP Server (默认暴露
### 模块化 Agent Skill 与 IDE 插件规范
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装并支持环境自愈;
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装到统一的 `~/.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`。
+868 -482
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.8.4",
"version": "0.8.6",
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.8.4
version: 0.8.6
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+8 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.8.5",
"version": "0.8.6",
"module": "src/server.ts",
"type": "module",
"bin": {
@@ -15,11 +15,18 @@
"typecheck": "tsc --noEmit",
"test": "bun test",
"bump": "bun run scripts/bump-version.ts",
"sync:release": "bun run scripts/bump-version.ts",
"check:version": "bun run scripts/check-version-sync.ts",
"openapi:bundle": "bun run scripts/bundle-openapi.ts",
"openapi:generate-raw": "bun run scripts/generate-raw-openapi.ts",
"openapi:all": "bun run scripts/generate-raw-openapi.ts && bun run scripts/bundle-openapi.ts",
"build:binary": "node scripts/build-binary.mjs",
"build:plugin": "node scripts/build-plugin.mjs",
"dev:override": "bun run scripts/dev-override.ts",
"dev:link": "bun run scripts/dev-override.ts",
"dev:status": "bun run scripts/dev-hygiene.ts status",
"dev:check": "bun run scripts/dev-hygiene.ts check",
"dev:clean": "bun run scripts/dev-hygiene.ts clean",
"dev": "bun run --watch src/server.ts",
"start": "bun run src/server.ts",
"export:workflow-schema": "bun run scripts/export-workflow-schema.ts"
+4 -3
View File
@@ -85,13 +85,14 @@ if (existsSync(globalSkillDir)) {
console.log("✓ Synchronized ~/.agents/skills/hose-use/");
}
// 7. Rebuild OpenAPI bundles
console.log("==> Rebuilding OpenAPI bundles...");
// 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" });
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 main --tags\n`);
console.log(` 4. git push origin <feature-branch>\n`);
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bun
import { readFileSync, existsSync } from "node:fs";
import { join } from "node:path";
const root = join(import.meta.dirname, "..");
const packageVersion = (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version: string }).version;
const expected: Array<[string, string | undefined]> = [
["package.json", packageVersion],
["src/version.ts", readFileSync(join(root, "src/version.ts"), "utf8").match(/VERSION\s*=\s*[\"']([^\"']+)/)?.[1]],
[".zcode-plugin/plugin.json", readJsonVersion(".zcode-plugin/plugin.json")],
["openapi/openapi.yaml", readFileSync(join(root, "openapi/openapi.yaml"), "utf8").match(/^\s+version:\s+([^\s]+)\s*$/m)?.[1]],
["dist/openapi.json", readJsonVersion("dist/openapi.json", ["info", "version"])],
];
const mismatches = expected.filter(([, value]) => value !== packageVersion);
if (mismatches.length) {
console.error(`Version drift detected; expected ${packageVersion}:`);
for (const [file, value] of mismatches) console.error(` ${file}: ${value ?? "missing"}`);
process.exit(1);
}
console.log(`Version synchronized: ${packageVersion}`);
function readJsonVersion(file: string, path: string[] = ["version"]): string | undefined {
const fullPath = join(root, file);
if (!existsSync(fullPath)) return undefined;
let value: unknown = JSON.parse(readFileSync(fullPath, "utf8"));
for (const key of path) {
if (!value || typeof value !== "object") return undefined;
value = (value as Record<string, unknown>)[key];
}
return typeof value === "string" ? value : undefined;
}
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, test } from "bun:test";
import { buildCleanupPlan, classifyExitCode, parseDevHygieneArgs, type Finding } from "./dev-hygiene.ts";
describe("dev hygiene tooling", () => {
test("only accepts development-scoped modes and confirmation flags", () => {
expect(parseDevHygieneArgs(["status"])).toEqual({ mode: "status", dryRun: false, yes: false, pruneUnreachable: false, help: false });
expect(parseDevHygieneArgs(["clean", "--dry-run"])).toEqual({ mode: "clean", dryRun: true, yes: false, pruneUnreachable: false, help: false });
expect(parseDevHygieneArgs(["clean", "--yes", "--prune-unreachable"])).toEqual({ mode: "clean", dryRun: false, yes: true, pruneUnreachable: true, help: false });
});
test("uses semantic exit codes for clean, warning, and blocked states", () => {
const finding = (level: Finding["level"]): Finding => ({ id: level, level, message: level });
expect(classifyExitCode([])).toBe(0);
expect(classifyExitCode([finding("info")])).toBe(0);
expect(classifyExitCode([finding("warning")])).toBe(2);
expect(classifyExitCode([finding("blocked")])).toBe(3);
});
test("only plans deletion for clean merged worktrees and local branches", () => {
const snapshot = {
repository: {} as any,
worktrees: [
{ path: "/tmp/merged", head: "a", branch: "feat/merged", current: false, exists: true, clean: true },
{ path: "/tmp/dirty", head: "b", branch: "feat/dirty", current: false, exists: true, clean: false },
],
branches: [
{ name: "main", sha: "m", merged: true, gone: false },
{ name: "feat/merged", sha: "a", merged: true, gone: false },
{ name: "feat/dirty", sha: "b", merged: true, gone: false },
{ name: "feat/live", sha: "c", merged: false, gone: false },
],
unreachableCommits: ["deadbeef"],
skill: {} as any,
binaries: [],
legacyConfig: {} as any,
};
const plan = buildCleanupPlan(snapshot, false);
expect(plan.map((action) => action.target)).toEqual(["/tmp/merged", "feat/merged"]);
expect(plan[1]?.kind).toBe("branch-delete");
expect(plan.some((action) => action.kind === "git-prune")).toBe(false);
});
});
+517
View File
@@ -0,0 +1,517 @@
#!/usr/bin/env bun
import { createHash } from "node:crypto";
import { execFileSync, spawnSync } from "node:child_process";
import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const PACKAGE = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as { version: string };
const CANONICAL_SKILL_DIR = join(homedir(), ".agents", "skills", "hose-use");
const NON_CANONICAL_SKILL_DIRS = [
join(homedir(), ".gemini", "antigravity", "skills", "hose-use"),
join(homedir(), ".codex", "skills", "hose-use"),
];
export type FindingLevel = "info" | "warning" | "blocked";
export type HygieneMode = "status" | "check" | "clean";
export interface Finding {
id: string;
level: FindingLevel;
message: string;
details?: Record<string, unknown>;
nextAction?: string;
}
export interface HygieneArgs {
mode: HygieneMode;
dryRun: boolean;
yes: boolean;
pruneUnreachable: boolean;
help: boolean;
}
export interface CleanupAction {
kind: "worktree-remove" | "worktree-prune" | "branch-delete" | "git-prune";
target: string;
command: string;
reason: string;
}
interface GitBranch {
name: string;
sha: string;
upstream?: string;
gone: boolean;
merged: boolean;
}
interface GitWorktree {
path: string;
head: string;
branch?: string;
current: boolean;
exists: boolean;
clean?: boolean;
}
interface HygieneSnapshot {
repository: {
root: string;
branch: string;
head: string;
upstream?: string;
ahead: number;
behind: number;
clean: boolean;
stagedChanges: number;
unstagedChanges: number;
untrackedFiles: number;
};
worktrees: GitWorktree[];
branches: GitBranch[];
unreachableCommits: string[];
skill: {
canonicalDir: string;
canonicalExists: boolean;
canonicalIsSymlink: boolean;
missingFiles: string[];
mismatchedFiles: string[];
nonCanonicalCopies: Array<{ dir: string; exists: boolean; isSymlink: boolean; pointsToCanonical: boolean }>;
};
binaries: Array<{
name: string;
path?: string;
version?: string;
expectedVersion: string;
matches: boolean;
error?: string;
}>;
legacyConfig: {
enterprisesDir: string;
configFile: string;
enterprisesDirExists: boolean;
configFileExists: boolean;
};
}
export interface HygieneReport {
schemaVersion: 1;
mode: HygieneMode;
generatedAt: string;
repository: string;
snapshot: HygieneSnapshot;
findings: Finding[];
counts: Record<FindingLevel, number>;
nextActions: string[];
exitCode: number;
}
export function parseDevHygieneArgs(argv: string[]): HygieneArgs {
const requestedMode = argv.find((arg) => !arg.startsWith("--")) || "check";
const mode: HygieneMode = requestedMode === "status" || requestedMode === "clean" ? requestedMode : "check";
return {
mode,
dryRun: argv.includes("--dry-run") || argv.includes("--dryRun"),
yes: argv.includes("--yes") || argv.includes("--confirm"),
pruneUnreachable: argv.includes("--prune-unreachable"),
help: argv.includes("--help") || argv.includes("-h"),
};
}
export function classifyExitCode(findings: Finding[]): number {
if (findings.some((finding) => finding.level === "blocked")) return 3;
if (findings.some((finding) => finding.level === "warning")) return 2;
return 0;
}
function git(args: string[], cwd = ROOT): string {
try {
return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
throw new Error(`git ${args.join(" ")} 失败: ${detail}`);
}
}
function gitMaybe(args: string[], cwd = ROOT): string | undefined {
try {
return git(args, cwd).trim() || undefined;
} catch {
return undefined;
}
}
function parseRepository(): HygieneSnapshot["repository"] {
const status = git(["status", "--porcelain=v1", "-b"]);
const lines = status.split("\n").filter(Boolean);
const branchLine = lines.shift() || "## HEAD";
const branch = branchLine.replace(/^##\s+/, "").split("...")[0] || "HEAD";
const changes = lines.filter((line) => !line.startsWith("##"));
const stagedChanges = changes.filter((line) => line !== "??" && line[0] !== " " && line[0] !== "?").length;
const unstagedChanges = changes.filter((line) => line !== "??" && line[1] !== " " && line.slice(0, 2) !== "??").length;
const untrackedFiles = changes.filter((line) => line.startsWith("??")).length;
const upstream = gitMaybe(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]);
const divergence = upstream ? gitMaybe(["rev-list", "--left-right", "--count", "HEAD...@{upstream}"]) : undefined;
const [ahead, behind] = (divergence || "0 0").split(/\s+/).map((value) => Number(value) || 0);
return {
root: ROOT,
branch,
head: git(["rev-parse", "--short", "HEAD"]).trim(),
...(upstream ? { upstream } : {}),
ahead,
behind,
clean: changes.length === 0,
stagedChanges,
unstagedChanges,
untrackedFiles,
};
}
function parseWorktrees(): GitWorktree[] {
const records: GitWorktree[] = [];
let current: Partial<GitWorktree> = {};
const flush = () => {
if (!current.path) return;
const path = resolve(current.path);
const exists = existsSync(path);
let clean: boolean | undefined;
if (exists) {
try {
clean = git(["status", "--porcelain=v1"], path).trim() === "";
} catch {
clean = undefined;
}
}
records.push({
path,
head: current.head || "",
...(current.branch ? { branch: current.branch } : {}),
current: path === ROOT,
exists,
...(clean === undefined ? {} : { clean }),
});
current = {};
};
for (const line of git(["worktree", "list", "--porcelain"]).split("\n")) {
if (!line) {
flush();
continue;
}
const [key, ...rest] = line.split(" ");
const value = rest.join(" ");
if (key === "worktree") current.path = value;
if (key === "HEAD") current.head = value;
if (key === "branch") current.branch = value.replace(/^refs\/heads\//, "");
}
flush();
return records;
}
function parseBranches(): GitBranch[] {
const merged = new Set(git(["branch", "--merged", "main", "--format=%(refname:short)"]).split("\n").filter(Boolean));
return git(["for-each-ref", "--format=%(refname:short)%09%(objectname:short)%09%(upstream:short)%09%(upstream:track)", "refs/heads"])
.split("\n")
.filter(Boolean)
.map((line) => {
const [name, sha, upstream, track] = line.split("\t");
return { name, sha, ...(upstream ? { upstream } : {}), gone: track === "[gone]", merged: merged.has(name) };
});
}
function parseUnreachableCommits(): string[] {
return git(["fsck", "--full", "--no-reflogs", "--unreachable"])
.split("\n")
.filter((line) => line.includes(" commit "))
.map((line) => line.trim().split(/\s+/)[2])
.filter(Boolean);
}
function listFiles(dir: string, base = dir): string[] {
if (!existsSync(dir)) return [];
const files: string[] = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const fullPath = join(dir, entry.name);
if (entry.isDirectory() && !entry.isSymbolicLink()) files.push(...listFiles(fullPath, base));
else files.push(relative(base, fullPath));
}
return files.sort();
}
function fileHash(path: string): string | undefined {
try {
return createHash("sha256").update(readFileSync(path)).digest("hex");
} catch {
return undefined;
}
}
function parseSkill(): HygieneSnapshot["skill"] {
const expectedFiles = git(["ls-files", "skills/hose-use"]).split("\n").filter(Boolean).map((path) => path.slice("skills/hose-use/".length));
const missingFiles = expectedFiles.filter((file) => !existsSync(join(CANONICAL_SKILL_DIR, file)));
const mismatchedFiles = expectedFiles.filter((file) => {
const sourceHash = fileHash(join(ROOT, "skills", "hose-use", file));
const targetHash = fileHash(join(CANONICAL_SKILL_DIR, file));
return sourceHash !== undefined && targetHash !== undefined && sourceHash !== targetHash;
});
return {
canonicalDir: CANONICAL_SKILL_DIR,
canonicalExists: existsSync(CANONICAL_SKILL_DIR),
canonicalIsSymlink: existsSync(CANONICAL_SKILL_DIR) && lstatSync(CANONICAL_SKILL_DIR).isSymbolicLink(),
missingFiles,
mismatchedFiles,
nonCanonicalCopies: NON_CANONICAL_SKILL_DIRS.map((dir) => ({
dir,
exists: existsSync(dir),
isSymlink: existsSync(dir) && lstatSync(dir).isSymbolicLink(),
pointsToCanonical: (() => {
try {
return lstatSync(dir).isSymbolicLink() && realpathSync(dir) === CANONICAL_SKILL_DIR;
} catch {
return false;
}
})(),
})),
};
}
function resolveCommand(name: string): string | undefined {
const result = spawnSync("which", [name], { encoding: "utf8" });
if (result.status === 0 && result.stdout?.trim()) return result.stdout.trim();
return undefined;
}
function inspectBinary(name: string): HygieneSnapshot["binaries"][number] {
const path = resolveCommand(name);
if (!path) return { name, expectedVersion: PACKAGE.version, matches: false, error: "PATH 中未找到" };
const result = spawnSync(path, ["version", "--json"], { cwd: ROOT, encoding: "utf8", timeout: 5000 });
if (result.status !== 0) {
return { name, path, expectedVersion: PACKAGE.version, matches: false, error: result.stderr?.trim() || `退出码 ${result.status ?? 1}` };
}
try {
const version = (JSON.parse(result.stdout) as { version?: string }).version;
return { name, path, version, expectedVersion: PACKAGE.version, matches: version === PACKAGE.version };
} catch {
return { name, path, expectedVersion: PACKAGE.version, matches: false, error: "版本输出不是 JSON" };
}
}
function parseLegacyConfig(): HygieneSnapshot["legacyConfig"] {
const home = homedir();
const enterprisesDir = join(home, ".cache", "ekb-mcp", "enterprises");
const configFile = join(home, ".cache", "ekb-mcp", "config.json");
return { enterprisesDir, configFile, enterprisesDirExists: existsSync(enterprisesDir), configFileExists: existsSync(configFile) };
}
function collectSnapshot(): HygieneSnapshot {
return {
repository: parseRepository(),
worktrees: parseWorktrees(),
branches: parseBranches(),
unreachableCommits: parseUnreachableCommits(),
skill: parseSkill(),
binaries: [inspectBinary("hose-use"), inspectBinary("hose-aipro")],
legacyConfig: parseLegacyConfig(),
};
}
function buildFindings(snapshot: HygieneSnapshot): Finding[] {
const findings: Finding[] = [];
const repo = snapshot.repository;
if (!repo.clean) {
findings.push({ id: "repo.dirty", level: "warning", message: "当前开发工作树存在未提交修改", details: { stagedChanges: repo.stagedChanges, unstagedChanges: repo.unstagedChanges, untrackedFiles: repo.untrackedFiles }, nextAction: "先确认这些修改属于当前工作,必要时提交或单独保存" });
}
if (repo.branch === "HEAD") findings.push({ id: "repo.detached", level: "blocked", message: "当前处于 detached HEAD", nextAction: "切换到明确的开发分支后再进行清理" });
if (repo.behind > 0) findings.push({ id: "repo.behind", level: "warning", message: "当前分支落后于上游分支", details: { upstream: repo.upstream, behind: repo.behind }, nextAction: "确认远程变化后再执行开发清理" });
for (const worktree of snapshot.worktrees) {
if (!worktree.exists) {
findings.push({ id: "worktree.missing", level: "blocked", message: "Git 记录了不存在的工作树路径", details: { path: worktree.path, branch: worktree.branch }, nextAction: "先用 git worktree prune 清理失效记录" });
} else if (!worktree.current && worktree.clean === false) {
findings.push({ id: "worktree.dirty", level: "warning", message: "额外工作树存在未提交修改", details: { path: worktree.path, branch: worktree.branch }, nextAction: "不要自动删除;先进入该工作树确认修改归属" });
} else if (!worktree.current) {
findings.push({ id: "worktree.extra", level: "info", message: "存在额外工作树,需人工确认是否仍有用途", details: { path: worktree.path, branch: worktree.branch } });
}
}
for (const branch of snapshot.branches) {
if (branch.name === snapshot.repository.branch) continue;
if (branch.name !== "main" && branch.merged) {
const linked = snapshot.worktrees.some((worktree) => worktree.branch === branch.name);
findings.push({ id: "branch.merged", level: linked ? "warning" : "info", message: linked ? "已合并分支仍被工作树占用" : "发现已合并的本地分支", details: { branch: branch.name, sha: branch.sha, linkedWorktree: linked } });
} else if (branch.gone) {
findings.push({ id: "branch.gone", level: "warning", message: "本地分支的上游远程分支已不存在", details: { branch: branch.name, upstream: branch.upstream }, nextAction: "确认本地分支不再需要后再删除" });
}
}
if (snapshot.unreachableCommits.length) {
findings.push({ id: "git.unreachable", level: "warning", message: "发现无分支或标签引用的 Git commit", details: { count: snapshot.unreachableCommits.length, commits: snapshot.unreachableCommits }, nextAction: "先检查内容,确认后使用 dev:clean --yes --prune-unreachable" });
}
const skill = snapshot.skill;
if (!skill.canonicalExists || skill.missingFiles.length || skill.mismatchedFiles.length) {
findings.push({ id: "skill.canonical-drift", level: "warning", message: "canonical Skill 缺失或与当前源码不一致", details: { dir: skill.canonicalDir, missingFiles: skill.missingFiles, mismatchedFiles: skill.mismatchedFiles }, nextAction: "运行 bun run dev:override 同步开发版 Skill" });
}
for (const copy of skill.nonCanonicalCopies.filter((item) => item.exists && !item.pointsToCanonical)) {
findings.push({ id: "skill.noncanonical-copy", level: "warning", message: "发现非 canonical Skill 副本;检查不会删除它", details: copy, nextAction: "确认外部工具不再使用后,再单独设计迁移或软链接" });
}
for (const binary of snapshot.binaries) {
if (!binary.path) {
findings.push({ id: "binary.missing", level: "info", message: `${binary.name} 未安装到 PATH`, details: binary, nextAction: "如需全局开发版,运行 bun run dev:override" });
} else if (!binary.matches) {
findings.push({ id: "binary.drift", level: "warning", message: `${binary.name} 全局版本与当前源码不一致`, details: binary, nextAction: "运行 bun run dev:override 同步全局开发版" });
}
}
const legacy = snapshot.legacyConfig;
if (legacy.enterprisesDirExists || legacy.configFileExists) {
findings.push({ id: "config.legacy", level: "warning", message: "发现旧版 ekb-mcp 配置路径;检查不会删除配置", details: legacy, nextAction: "先确认迁移结果,再按配置迁移策略清理" });
}
return findings;
}
export function buildCleanupPlan(snapshot: HygieneSnapshot, pruneUnreachable: boolean): CleanupAction[] {
const actions: CleanupAction[] = [];
if (snapshot.worktrees.some((worktree) => !worktree.exists)) {
actions.push({ kind: "worktree-prune", target: "stale-worktree-records", command: "git worktree prune", reason: "移除 Git 记录中已经不存在的工作树" });
}
const removableWorktreeBranches = new Set(
snapshot.worktrees
.filter((worktree) => !worktree.current && worktree.exists && worktree.clean && worktree.branch && snapshot.branches.some((branch) => branch.name === worktree.branch && branch.merged))
.map((worktree) => worktree.branch)
.filter((branch): branch is string => Boolean(branch))
);
const linkedPaths = new Set(
snapshot.worktrees
.filter((worktree) => !removableWorktreeBranches.has(worktree.branch || ""))
.map((worktree) => worktree.branch)
.filter((branch): branch is string => Boolean(branch))
);
for (const worktree of snapshot.worktrees) {
if (!worktree.current && worktree.exists && worktree.clean && worktree.branch && snapshot.branches.some((branch) => branch.name === worktree.branch && branch.merged)) {
actions.push({ kind: "worktree-remove", target: worktree.path, command: `git worktree remove ${JSON.stringify(worktree.path)}`, reason: `工作树干净且分支 ${worktree.branch} 已合并` });
}
}
for (const branch of snapshot.branches) {
if (branch.name !== "main" && branch.merged && !linkedPaths.has(branch.name)) {
actions.push({ kind: "branch-delete", target: branch.name, command: `git branch -d ${branch.name}`, reason: "本地分支已合并且没有关联工作树" });
}
}
if (pruneUnreachable && snapshot.unreachableCommits.length) {
actions.push({ kind: "git-prune", target: "unreachable-objects", command: "git reflog expire --expire=now --all && git gc --prune=now", reason: "明确启用 unreachable 对象清理" });
}
return actions;
}
function applyCleanup(actions: CleanupAction[]): Array<{ action: CleanupAction; ok: boolean; error?: string }> {
return actions.map((action) => {
try {
if (action.kind === "worktree-remove") git(["worktree", "remove", action.target]);
else if (action.kind === "worktree-prune") git(["worktree", "prune"]);
else if (action.kind === "branch-delete") git(["branch", "-d", action.target]);
else {
git(["reflog", "expire", "--expire=now", "--all"]);
git(["gc", "--prune=now"]);
}
return { action, ok: true };
} catch (error) {
return { action, ok: false, error: error instanceof Error ? error.message : String(error) };
}
});
}
function createReport(mode: HygieneMode): HygieneReport {
const snapshot = collectSnapshot();
const findings = buildFindings(snapshot);
const counts = {
info: findings.filter((finding) => finding.level === "info").length,
warning: findings.filter((finding) => finding.level === "warning").length,
blocked: findings.filter((finding) => finding.level === "blocked").length,
};
const exitCode = classifyExitCode(findings);
return {
schemaVersion: 1,
mode,
generatedAt: new Date().toISOString(),
repository: ROOT,
snapshot,
findings,
counts,
nextActions: findings.map((finding) => finding.nextAction).filter((action): action is string => Boolean(action)),
exitCode,
};
}
function emit(value: unknown): void {
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
}
function emitSummary(report: HygieneReport): void {
console.error(`[dev:${report.mode}] ${report.repository}`);
console.error(`发现 ${report.counts.info} 条提示、${report.counts.warning} 条警告、${report.counts.blocked} 条阻塞项;退出码 ${report.exitCode}`);
for (const finding of report.findings) console.error(`- [${finding.level}] ${finding.message}`);
}
function usage(): string {
return [
"开发环境检查(不会进入 hose-use 用户命令):",
" bun run dev:status 输出当前开发环境快照",
" bun run dev:check 只读检查并返回语义化退出码",
" bun run dev:clean --dry-run 预览安全清理动作",
" bun run dev:clean --yes 执行干净且已合并的本地清理",
" bun run dev:clean --yes --prune-unreachable 额外清理无引用 Git 对象",
"",
"stdout 始终为 JSON;人类提示和进度写入 stderr。远程分支和非 canonical Skill 目录不会被自动删除。",
].join("\n");
}
export async function main(argv = process.argv.slice(2)): Promise<number> {
const args = parseDevHygieneArgs(argv);
if (args.help) {
emit({ ok: true, usage: usage().split("\n") });
console.error(usage());
return 0;
}
try {
if (args.mode !== "clean") {
const report = createReport(args.mode);
emit(report);
emitSummary(report);
return args.mode === "status" ? 0 : report.exitCode;
}
const report = createReport("clean");
const plan = buildCleanupPlan(report.snapshot, args.pruneUnreachable);
if (args.dryRun || !args.yes) {
emit({ ...report, plan, dryRun: true, nextAction: "bun run dev:clean --yes" });
emitSummary(report);
console.error(plan.length ? "[dev:clean] 当前仅预览,追加 --yes 才会执行。" : "[dev:clean] 没有满足安全条件的本地清理动作。");
return report.exitCode;
}
if (report.snapshot.repository.branch === "HEAD") {
emit({ ...report, plan, applied: false, error: "detached HEAD 下拒绝清理" });
return 3;
}
const results = applyCleanup(plan);
const failed = results.filter((result) => !result.ok);
emit({ ...report, plan, applied: true, results, failed: failed.length });
console.error(`[dev:clean] 已执行 ${results.length - failed.length} 项,失败 ${failed.length} 项。`);
return failed.length ? 4 : 0;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
emit({ ok: false, error: message });
console.error(`[dev:hygiene] ${message}`);
return 4;
}
}
if (import.meta.main) {
main().then((exitCode) => {
process.exitCode = exitCode;
});
}
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, test } from "bun:test";
import { globalBinCandidates, parseDevOverrideArgs } from "./dev-override.js";
describe("dev:override", () => {
test("parses dry-run and explicit target path without touching the host", () => {
expect(parseDevOverrideArgs(["--dry-run", "--target-path=/tmp/hose-use-test"])).toEqual({
dryRun: true,
targetPath: "/tmp/hose-use-test",
});
});
test("uses stable global binary locations", () => {
const candidates = globalBinCandidates("hose-use-test");
expect(candidates.some((candidate) => candidate.endsWith("/hose-use-test"))).toBe(true);
expect(candidates).toHaveLength(4);
});
});
+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env bun
import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, rmSync, symlinkSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
export interface DevOverrideOptions {
dryRun: boolean;
targetPath?: string;
}
export function parseDevOverrideArgs(argv: string[]): DevOverrideOptions {
return {
dryRun: argv.includes("--dry-run") || argv.includes("--dryRun"),
targetPath: argv.find((arg) => arg.startsWith("--target-path="))?.slice("--target-path=".length),
};
}
export function globalBinCandidates(commandName = "hose-use"): string[] {
return [
"/opt/homebrew/bin",
"/usr/local/bin",
join(homedir(), ".local", "bin"),
join(homedir(), "bin"),
].map((dir) => join(dir, commandName));
}
export function resolveTargetBinaryPath(commandName = "hose-use"): string {
try {
const whichRes = spawnSync("which", [commandName], { encoding: "utf8" });
if (whichRes.status === 0 && whichRes.stdout) {
const path = whichRes.stdout.trim();
if (path && existsSync(path)) return path;
}
} catch {
// Fall back to conventional user-level locations.
}
for (const candidate of globalBinCandidates(commandName)) {
if (existsSync(dirname(candidate))) return candidate;
}
const defaultDir = join(homedir(), ".local", "bin");
mkdirSync(defaultDir, { recursive: true });
return join(defaultDir, commandName);
}
function runBuild(): string {
const result = spawnSync("node", ["scripts/build-binary.mjs"], {
cwd: ROOT,
stdio: ["ignore", "inherit", "inherit"],
});
if (result.error) throw result.error;
if (result.status !== 0) throw new Error(`构建开发版二进制失败,退出码: ${result.status ?? 1}`);
const localBinary = join(ROOT, "dist", "bin", "hose-use");
if (!existsSync(localBinary)) throw new Error(`未找到构建产物: ${localBinary}`);
return localBinary;
}
function stopRunningService(targetPath: string): boolean {
try {
const statusRes = spawnSync(targetPath, ["service", "status", "--json"], { encoding: "utf8" });
if (statusRes.status !== 0 || !statusRes.stdout) return false;
const status = JSON.parse(statusRes.stdout) as { running?: boolean };
if (!status.running) return false;
console.error("==> [dev:override] 停止正在运行的后台服务...");
const stopRes = spawnSync(targetPath, ["service", "stop"], { stdio: "ignore" });
if (stopRes.status !== 0) throw new Error("无法停止后台服务,已中止替换操作");
return true;
} catch (error) {
if (error instanceof Error && error.message.includes("无法停止")) throw error;
return false;
}
}
function installBinary(localBinary: string, targetPath: string): void {
const targetDir = dirname(targetPath);
mkdirSync(targetDir, { recursive: true });
const temporaryPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
try {
copyFileSync(localBinary, temporaryPath);
chmodSync(temporaryPath, 0o755);
if (process.platform === "darwin") {
spawnSync("/usr/bin/codesign", ["--remove-signature", temporaryPath], { stdio: "ignore" });
spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", temporaryPath], { stdio: "ignore" });
}
// copyFileSync follows an existing symlink, so a package-manager shim is not
// accidentally replaced by a regular file.
copyFileSync(temporaryPath, targetPath);
chmodSync(targetPath, 0o755);
} finally {
rmSync(temporaryPath, { force: true });
}
}
function syncAgentSkill(): string | undefined {
const source = join(ROOT, "skills", "hose-use");
const target = join(homedir(), ".agents", "skills", "hose-use");
if (!existsSync(source)) return undefined;
mkdirSync(dirname(target), { recursive: true });
cpSync(source, target, { recursive: true, force: true });
return target;
}
export async function main(argv = process.argv.slice(2)): Promise<number> {
const options = parseDevOverrideArgs(argv);
const targetPath = options.targetPath || resolveTargetBinaryPath();
console.error("==> [dev:override] 将当前工作区安装为全局开发版 hose-use");
console.error(` 工作区: ${ROOT}`);
console.error(` 目标: ${targetPath}`);
if (options.dryRun) {
console.error("[DRY-RUN] 将执行: 构建 dist/bin/hose-use、替换全局二进制、同步 ~/.agents/skills/hose-use");
return 0;
}
const builtBinary = runBuild();
const serviceWasRunning = stopRunningService(targetPath);
installBinary(builtBinary, targetPath);
const aiproPath = join(dirname(targetPath), "hose-aipro");
if (aiproPath !== targetPath) {
rmSync(aiproPath, { force: true });
symlinkSync(targetPath, aiproPath);
}
try {
const skillTarget = syncAgentSkill();
if (skillTarget) console.error(`✓ [dev:override] 已同步 Agent Skill: ${skillTarget}`);
} catch (error) {
console.error(`⚠️ [dev:override] Agent Skill 同步失败: ${error}`);
}
if (serviceWasRunning) {
console.error("==> [dev:override] 使用新二进制重启后台服务...");
const startRes = spawnSync(targetPath, ["service", "start"], { stdio: "ignore" });
if (startRes.status !== 0) console.error("⚠️ [dev:override] 后台服务重启失败,请手动运行 hose-use service start");
}
const versionRes = spawnSync(targetPath, ["version"], { encoding: "utf8" });
if (versionRes.status !== 0) throw new Error(versionRes.stderr || "开发版安装后校验失败");
console.error("✨ [dev:override] 全局开发版安装完成");
process.stdout.write(versionRes.stdout || "");
return 0;
}
if (import.meta.main) {
main().catch((error) => {
console.error(`❌ [dev:override] ${error instanceof Error ? error.message : String(error)}`);
process.exitCode = 1;
});
}
+33 -18
View File
@@ -1,12 +1,12 @@
---
name: hose-use
description: "v0.8.5: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
description: "v0.8.6: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
metadata:
version: 0.8.5
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.8.5)
version: 0.8.6
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.8.6)
---
# hose-use (v0.8.5)
# hose-use (v0.8.6)
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
@@ -22,7 +22,10 @@ metadata:
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 `--json -o <path>` 本地转储或使用 `--limit` 限制分页;
- 严禁盲目使用 `--full` 将上万行原始报文一次性塞入上下文;
- 永远解析 JSON stdout,不要从格式化表格的终端字符中正则刮取数据。
4. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
4. **密钥安全**:`keys` 默认在表格和 JSON 中脱敏 `appSecurity`;只有用户明确需要完整凭证时才使用 `--reveal`/`-r`。不要把明文密钥写入日志、共享文件、提示词或聊天回复;尤其不要组合 `--reveal -o <path>`。
5. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
6. **写操作两阶段确认**:所有 CLI 写操作先使用 `--dry-run` 查看目标和变更,再使用同一命令追加 `--yes` 或 `--confirm` 执行;未确认时不会发起写请求或写入本地状态。
7. **开发版全局安装**:需要让 PATH 中的命令立即跟随当前工作区时,运行 `bun run dev:override`;它会构建本机二进制、同步 Agent Skill,并更新全局 `hose-use` / `hose-aipro`。可先用 `bun run dev:override -- --dry-run` 查看计划;不要使用 `npm install -g .` 留下静态旧副本。
---
@@ -34,7 +37,7 @@ metadata:
| AI PRO 审批仲裁网关状态与当前连接企业 | `hose-aipro status [--json]`, `hose-use aipro status` | [references/approval.md](references/approval.md) |
| AI PRO 规则场景库与审核要点清单 | `hose-aipro scopes`, `hose-aipro points <索引>` | [references/approval.md](references/approval.md) |
| AI PRO 确定性审批仲裁全流程 (核验/仲裁) | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [references/approval.md](references/approval.md) |
| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add`, `hose-use rule list` | [references/approval.md](references/approval.md) |
| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/approval.md](references/approval.md) |
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](references/auth.md) |
| 第三方免密/协助链接一键秒级导入 | `hose-use corps add-link <url>`, `hose-use auth add-link <url>` | [references/auth.md](references/auth.md) |
| 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](references/auth.md) |
@@ -66,6 +69,8 @@ metadata:
| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、发布与开通切换 | `hose-use workflow get`, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) |
| 工作流节点树、代码依赖与静态诊断 | `hose-use workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [references/workflow.md](references/workflow.md) |
| 企业 OpenAPI 接入密钥(默认脱敏) | `hose-use keys [--json]`, `hose-use openapi keys`, `hose-use store keys` | [references/store.md](references/store.md) |
| 企业已购应用 / 应用商店探查 | `hose-use store list / search / get` | [references/store.md](references/store.md) |
| 常驻守护进程管理 / 后台运行 | `hose-use service start`, `hose-use service status` | [references/service.md](references/service.md) |
| 待办/消息事件轮询与去重 | `hose-use service poll --corp=<id>` | [references/service.md](references/service.md) |
| 启动本地 HTTP 服务 / 打开可视化交互文档 | `hose-use http --port=8888` (访问 `/docs`) | [references/service.md](references/service.md) |
@@ -117,11 +122,12 @@ hose-use dimension list # 查看系统与自定
hose-use dimension items 项目 # 查看项目、成本中心等档案项
hose-use feetype list # 树形层级查看企业费用类型
hose-use feetype get 交通费 --specs # 查看费用类型详情与报账/申请字段
hose-use feetype create --name="市内打车" --parent="交通费" # 在指定父级下新建费用类型
hose-use feetype update 市内打车 --desc="滴滴企业版" # 修改费用类型属性
hose-use feetype disable 市内打车 # 停用费用类型 (软删除)
hose-use feetype enable 市内打车 # 重新启用费用类型
hose-use feetype move 市内打车 --parent="差旅费用" # 移动费用类型到新父级
hose-use feetype create --name="市内打车" --parent="交通费" --dry-run # 先预览新建
hose-use feetype create --name="市内打车" --parent="交通费" --yes # 确认新建
hose-use feetype update 市内打车 --desc="滴滴企业版" --yes # 修改费用类型属性
hose-use feetype disable 市内打车 --yes # 停用费用类型 (软删除)
hose-use feetype enable 市内打车 --yes # 重新启用费用类型
hose-use feetype move 市内打车 --parent="差旅费用" --yes # 移动费用类型到新父级
hose-use role list # 查看企业角色定义
hose-use role groups # 查看角色组及其角色
hose-use role members 财务主管 # 查看指定角色成员
@@ -142,22 +148,29 @@ hose-use platform list # 列出企业可见的
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
hose-use platform records 新转转集团 合同 # 查看业务对象的底层数据记录
hose-use platform record get 新转转集团 合同 <记录ID> # 获取单条记录完整字段与属性详情
hose-use platform record toggle 新转转集团 合同 <记录ID> # 切换单条记录停启用状态
hose-use platform record edit 新转转集团 合同 <记录ID> --data='{"name":"新名称"}' # 编辑记录字段
hose-use platform record recompute 新转转集团 合同 <记录ID> # 重新计算记录关联的全部台账
hose-use platform record toggle 新转转集团 合同 <记录ID> --dry-run # 预览状态切换
hose-use platform record edit 新转转集团 合同 <记录ID> --data='{"name":"新名称"}' --yes # 编辑记录字段
hose-use platform record recompute 新转转集团 合同 <记录ID> --yes # 重新计算记录关联的全部台账
hose-use menu list # 查看桌面端主框架一级导航树
hose-use workflow list # 聚合扫描全部自建应用下的工作流
hose-use workflow find --task=code-js2 # 查找部署了代码节点的工作流
hose-use workflow get wf_01k83y... # 查看指定工作流节点拓扑
hose-use workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断
hose-use workflow save wf_01k83y... --file=workflow.json # 按完整快照保存草稿并做版本保护
hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json
hose-use workflow save wf_01k83y... --file=workflow.json --yes # 按完整快照保存草稿并做版本保护
hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json --yes
hose-use workflow history wf_01k83y... --json # 查看服务端版本快照历史
hose-use workflow logs wf_01k83y... --state=FAILED # 查看运行错误日志
hose-use workflow check --json --fail-on-alert # 扫描错误管道并只提醒新增错误计数
hose-use workflow publish wf_01k83y... # 将保存后的工作流发布/启用
hose-use workflow publish wf_01k83y... --yes # 将保存后的工作流发布/启用
# 6. 服务与守护进程
# 6. OpenAPI 密钥与应用中心
hose-use keys --json # 查询当前企业密钥,appSecurity 默认脱敏
hose-use keys --reveal # 仅在用户明确授权时查看完整 appSecurity
hose-use store list --all # 查看当前企业已购/已开通应用
hose-use store search "开放接口" # 搜索应用商店
hose-use store get <应用ID> # 查看应用详情(ID 可带或不带前导 $)
# 7. 服务与守护进程
hose-use http --port=8888 # 启动前台 HTTP 服务与交互式文档
hose-use service start # 后台启动常驻守护进程服务
hose-use service status # 查看常驻守护进程运行状态与端点
@@ -176,4 +189,6 @@ hose-use service stop # 停止后台常驻守
- `--full`:全量输出大报文(绕过 200KB 体积防爆拦截)
- `--stateless`:单次命令强制以无状态模式执行
- `--stateful`:单次命令强制以有状态模式执行
- `--dry-run`:预览写操作,不发起写请求或落盘
- `--yes`, `--confirm`:显式确认执行写操作
- `--help, -h`:查看命令帮助与参数说明
+1 -1
View File
@@ -5,7 +5,7 @@ auth:
type: "none"
tools:
- name: "hose_cli"
description: "执行合思/易快报 hose-use CLI 命令。详细命令语法请参考 hose-use skill 文档。"
description: "执行合思/易快报 hose-use CLI 命令,包括 keys 凭证查询与 store 应用探查。详细命令语法请参考 hose-use skill 文档。"
parameters:
type: "object"
properties:
+36
View File
@@ -0,0 +1,36 @@
# OpenAPI 密钥与应用中心
本专卷覆盖 v0.8.1 引入的企业 OpenAPI 接入密钥查询,以及企业已购应用和合思应用商店探查。执行前先确认目标企业;可用 `hose-use context --json` 或 `hose-use corps list`,跨企业任务优先显式传入 `--corp=<id>`。
## 密钥查询 (`keys`)
```bash
hose-use keys # 当前企业的密钥列表,appSecurity 默认脱敏
hose-use keys --json # 结构化结果,appSecurity 仍默认脱敏
hose-use openapi keys # 同一能力的 OpenAPI 别名
hose-use store keys # 同一能力的 store 别名
hose-use keys --reveal # 用户明确要求时才显示完整 appSecurity
```
`keys` 返回密钥备注、`appKey`、状态和创建时间。`appSecurity` 是接入密码:默认输出会遮罩;`--reveal`/`-r`/`--plain` 才请求完整值。
安全边界:
- 没有用户明确授权时,不要使用 `--reveal`,也不要从结果中推断或复述明文密钥。
- 不要把明文密钥放进聊天、日志、命令历史、提交内容或共享目录;不要使用 `--reveal -o <path>`。
- 只需判断密钥是否存在、状态或匹配某个 `appKey` 时,使用默认脱敏输出即可。
- 需要交给脚本处理时优先使用不带 `--reveal` 的 `--json`;若确实必须取得明文,先确认接收方和落盘位置,再尽量短暂使用并及时清理。
## 应用中心与应用商店 (`store`)
```bash
hose-use store list # 当前企业已购/已开通应用
hose-use store list --all # 请求完整已购应用列表
hose-use store list <关键词> # 按名称或简介筛选已购应用
hose-use store search <关键词> # 搜索应用商店商品
hose-use store get <应用ID> # 查看商品详情;ID 可带或不带前导 $
```
`store list` 展示应用 ID、名称、开通状态、有效期限、配置支持和绑定能力;`store search` 返回商店结果总数及当前结果;`store get` 用于查看指定应用的详情。上述命令均支持 `--json`,适合 Agent 解析。
若用户说“查 OpenAPI 密钥”,路由到 `keys`;若用户说“看企业买了什么应用/查应用市场”,路由到 `store list` 或 `store search`;若已有应用 ID,再用 `store get` 下钻。`openapi keys` 与 `store keys` 只作为 `keys` 的兼容别名。
+10
View File
@@ -25,6 +25,16 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
delete process.env.HOSE_APPROVAL_DB;
});
test("version/help --json only emit machine-readable stdout", async () => {
const version = await runAiProCli(["version", "--json"]);
const help = await runAiProCli(["help", "--json"]);
expect(JSON.parse(version.stdout)).toEqual({ name: "hose-aipro", version: expect.any(String) });
expect(JSON.parse(help.stdout).help).toContain("hose-aipro");
expect(version.stderr).toBe("");
expect(help.stderr).toBe("");
});
test("完整闭环:bind 挂载 ➔ review 证据核验 ➔ decide 网关阻拦与裁决 ➔ logs 审计追溯", async () => {
const db = getApprovalDatabase(":memory:");
const repo = new ApprovalRepository(db);
+22 -5
View File
@@ -53,6 +53,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
}
const command = (positional[0] || "help").toLowerCase();
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
const targetSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
const args = positional.slice(1);
const corpId = corp?.corpId || corp?.id;
@@ -73,6 +74,16 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
};
try {
if (command === "version" || command === "v" || booleanOption(parsed.options, ["version", "v"])) {
return {
stdout: jsonMode
? printJson({ name: "hose-aipro", version: VERSION }) + "\n"
: `hose-aipro v${VERSION}\n`,
stderr: "",
exitCode: 0,
};
}
switch (command) {
// ── 0. 运行时上下文与身份诊断 (status / whoami / context / info) ────────
case "status":
@@ -1136,7 +1147,11 @@ ${corpBanner}
7. 全流程监控日志流水查看:
hose-aipro logs [单号] # 追溯所有 AI PRO 操作流水
`;
return { stdout: helpText.trim() + "\n", stderr: "", exitCode: 0 };
return {
stdout: jsonMode ? printJson({ help: helpText.trim() }) + "\n" : helpText.trim() + "\n",
stderr: "",
exitCode: 0,
};
}
}
} catch (err: any) {
@@ -1151,8 +1166,8 @@ ${corpBanner}
summary: err.message.replace(/\n+/g, " "),
});
return {
stdout: "",
stderr: `\n${err.message}\n`,
stdout: jsonMode ? printJson({ error: true, message: err.message, exitCode: 1 }) + "\n" : "",
stderr: jsonMode ? "" : `\n${err.message}\n`,
exitCode: 1,
};
}
@@ -1167,8 +1182,10 @@ ${corpBanner}
});
return {
stdout: "",
stderr: `[AI PRO 错误] ${err?.message || err}\n`,
stdout: jsonMode
? printJson({ error: true, message: String(err?.message || err), exitCode: 1 }) + "\n"
: "",
stderr: jsonMode ? "" : `[AI PRO 错误] ${err?.message || err}\n`,
exitCode: 1,
};
}
+28
View File
@@ -18,6 +18,7 @@ import { createEkbClient } from "../../core/auth/ekb.js";
import { stringOption, booleanOption } from "../parser.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import { prompt } from "../helpers.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleAuthCommand(
@@ -68,6 +69,14 @@ async function handleLogin(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
const isSync = booleanOption(parsed.options, ["sync"]);
const isInteractive = booleanOption(parsed.options, ["interactive", "i"]) || (!phone && !password && !isSms && !isSync);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "登录并保存企业凭证", phone || (isSync ? "浏览器会话" : "交互式登录"), {
mode: isSync ? "browser-sync" : isSms ? "sms" : "password",
saveAll: true,
});
}
requireMutationConfirmation(parsed, runtime, "登录并保存企业凭证", `hose-use auth login${phone ? ` --phone=${phone}` : ""} --yes`);
// 1. 浏览器同步
if (isSync) {
const res = await fullBrowserSyncLogin({ saveAll: true });
@@ -230,6 +239,10 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
async function handleRefresh(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const accountId = stringOption(parsed.options, ["account", "a"]);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "刷新账号下企业凭证", accountId || "当前账号", { saveAll: true });
}
requireMutationConfirmation(parsed, runtime, "刷新账号下企业凭证", `hose-use auth refresh${accountId ? ` --account=${accountId}` : ""} --yes`);
const res = await refreshAccountCorporations(accountId, { saveAll: true });
if (runtime.jsonMode) {
@@ -253,6 +266,16 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
const ttl = stringOption(parsed.options, ["ttl"]);
const expires = stringOption(parsed.options, ["expires", "days"]);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "导入并保存企业凭证", corpId || "待解析企业", {
source: raw ? "captured-input" : "manual-input",
overwrite,
ttl: ttl || null,
expires: expires || null,
});
}
requireMutationConfirmation(parsed, runtime, "导入并保存企业凭证", `hose-use auth ${parsed.action || "import"} --yes`);
if (!raw && !accessToken && process.stdin.isTTY) {
raw = await prompt("请粘贴抓包文本 / cURL 命令行 / 协助免密 URL (直接回车则手动逐项输入): ");
}
@@ -370,6 +393,11 @@ async function handleSwitchAccount(parsed: CliParsedArgs, runtime: CliRuntime):
return { stdout: "", stderr: "用法: hose-use auth switch-account <accountId>\n", exitCode: 1 };
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换当前活跃账号", target, { activeAccountId: target });
}
requireMutationConfirmation(parsed, runtime, "切换当前活跃账号", `hose-use auth switch-account ${target} --yes`);
const success = setActiveAccount(target);
if (!success) {
return { stdout: "", stderr: `未找到账号: ${target}\n`, exitCode: 1 };
+41 -23
View File
@@ -20,6 +20,7 @@ import {
commentBill,
resolveBillStaffIds,
} from "../../domains/bill/tools.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
export async function handleBillCommand(
parsed: CliParsedArgs,
@@ -32,15 +33,24 @@ export async function handleBillCommand(
);
}
const client = await createEkbClient(corp);
const action = parsed.action?.toLowerCase();
const corpId = corp.corpId || corp.id;
let client: Awaited<ReturnType<typeof createEkbClient>> | undefined;
const getClient = async () => {
client ??= await createEkbClient(corp);
return client;
};
const actionTarget = () => parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
const requireWriteConfirmation = async () => {
if (booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
if (isDryRun(parsed, runtime) || booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
if (!process.stdin.isTTY || !process.stdout.isTTY) {
throw new Error("审批动作会改变单据状态。请显式添加 --yes(或 --confirm)后重试。");
requireMutationConfirmation(
parsed,
runtime,
"单据审批动作",
`hose-use bill ${action || "approve"} ${actionTarget() || "<单号|ID>"} --yes`
);
}
const { prompt } = await import("../helpers.js");
const answer = await prompt("该操作会改变单据状态,确认继续?输入 yes 继续: ");
@@ -68,7 +78,7 @@ export async function handleBillCommand(
});
const resolveApproverIds = async (values: string[] | undefined): Promise<string[]> => {
if (!values?.length) throw new Error("请通过 --approver-id、--staff 或 --to 指定员工 ID、工号或姓名");
return resolveBillStaffIds(client, corpId, values);
return resolveBillStaffIds(await getClient(), corpId, values);
};
switch (action) {
@@ -77,7 +87,8 @@ export async function handleBillCommand(
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill approve <单号|ID> --yes");
const result = await approveBill(client, corpId, target, actionOptions());
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "同意单据审批", target, actionOptions());
const result = await approveBill(await getClient(), corpId, target, actionOptions());
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `审批同意成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
}
@@ -89,7 +100,8 @@ export async function handleBillCommand(
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill reject <单号|ID> --comment <原因> --yes");
const options = actionOptions();
if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因");
const result = await rejectBill(client, corpId, target, options);
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "驳回单据审批", target, options);
const result = await rejectBill(await getClient(), corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `驳回成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
}
@@ -99,8 +111,10 @@ export async function handleBillCommand(
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill transfer <单号|ID> --approver-id <员工ID> --yes");
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
const result = await transferBill(client, corpId, target, options);
const rawOptions = actionOptions();
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "转交单据审批", target, rawOptions);
const options = { ...rawOptions, approverIds: await resolveApproverIds(rawOptions.approverIds) };
const result = await transferBill(await getClient(), corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `转交审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
}
@@ -112,8 +126,10 @@ export async function handleBillCommand(
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill add-node <单号|ID> --approver-id <员工ID> --yes");
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
const result = await addNodeBill(client, corpId, target, options);
const rawOptions = actionOptions();
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "单据加签", target, rawOptions);
const options = { ...rawOptions, approverIds: await resolveApproverIds(rawOptions.approverIds) };
const result = await addNodeBill(await getClient(), corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `加签审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
}
@@ -123,7 +139,9 @@ export async function handleBillCommand(
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供单号或单据 ID: hose-use bill comment <单号|ID> --comment <内容> --yes");
const result = await commentBill(client, corpId, target, actionOptions());
const options = actionOptions();
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "添加单据评论", target, options);
const result = await commentBill(await getClient(), corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `单据评论成功\n单号: ${result.billCode || target}\n流程 ID: ${result.flowId}\n`, stderr: "", exitCode: 0 };
}
@@ -137,7 +155,7 @@ export async function handleBillCommand(
const state = stringOption(parsed.options, ["state", "s"]);
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
const result = await searchAndFormatBills(client, corpId, {
const result = await searchAndFormatBills(await getClient(), corpId, {
code,
keyword,
stage,
@@ -192,7 +210,7 @@ export async function handleBillCommand(
throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");
}
const bills = await getBillByCodeOrId(client, corpId, target);
const bills = await getBillByCodeOrId(await getClient(), corpId, target);
if (bills.length === 0) {
if (runtime.jsonMode) {
@@ -211,7 +229,7 @@ export async function handleBillCommand(
const withRisk = booleanOption(parsed.options, ["risk", "with-risk", "audit"]);
const riskReports = withRisk
? await Promise.all(bills.map((bill) => getBillRisk(client, corpId, bill.billId || bill.billCode)))
? await Promise.all(bills.map(async (bill) => getBillRisk(await getClient(), corpId, bill.billId || bill.billCode)))
: [];
if (runtime.jsonMode) {
@@ -287,7 +305,7 @@ export async function handleBillCommand(
case "schema":
case "schemas":
case "entities": {
const { entities } = await getFieldDictionary(client, corpId, true);
const { entities } = await getFieldDictionary(await getClient(), corpId, true);
if (runtime.jsonMode) {
return {
@@ -328,7 +346,7 @@ export async function handleBillCommand(
case "timeline": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose-use bill flow <单号|ID>");
const flow = await getBillFlow(client, corpId, target);
const flow = await getBillFlow(await getClient(), corpId, target);
if (!flow) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据流程: ${target}\n`, exitCode: 1 };
@@ -370,7 +388,7 @@ export async function handleBillCommand(
case "warnings": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose-use bill risk <单号|ID>");
const report = await getBillRisk(client, corpId, target);
const report = await getBillRisk(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据风控结果: ${target}\n`, exitCode: 1 };
@@ -400,7 +418,7 @@ export async function handleBillCommand(
case "budgets": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose-use bill budget <单号|ID>");
const report = await getBillRisk(client, corpId, target);
const report = await getBillRisk(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据预算状态: ${target}\n`, exitCode: 1 };
@@ -426,7 +444,7 @@ export async function handleBillCommand(
case "resolve": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose-use bill refs <单号|ID>");
const report = await getBillReferences(client, corpId, target);
const report = await getBillReferences(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据引用: ${target}\n`, exitCode: 1 };
@@ -455,7 +473,7 @@ export async function handleBillCommand(
case "links": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose-use bill relations <单号|ID>");
const report = await getBillRelations(client, corpId, target);
const report = await getBillRelations(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据关联关系: ${target}\n`, exitCode: 1 };
@@ -488,7 +506,7 @@ export async function handleBillCommand(
case "files": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose-use bill attachments <单号|ID>");
const report = await getBillAttachments(client, corpId, target);
const report = await getBillAttachments(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据附件: ${target}\n`, exitCode: 1 };
@@ -511,7 +529,7 @@ export async function handleBillCommand(
if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose-use bill download <单号|ID>");
const outputDir = stringOption(parsed.options, ["output-dir", "dir"]) || `${process.cwd()}/downloads`;
const fileId = stringOption(parsed.options, ["file-id", "file"]);
const result = await downloadBillAttachments(client, corpId, target, outputDir, fileId);
const result = await downloadBillAttachments(await getClient(), corpId, target, outputDir, fileId);
const summary = {
corpId,
corpName: corp.name,
@@ -546,7 +564,7 @@ export async function handleBillCommand(
};
}
const items = await getBillByCodeOrId(client, corpId, target);
const items = await getBillByCodeOrId(await getClient(), corpId, target);
if (!items || items.length === 0) {
return {
stdout: "",
+17
View File
@@ -9,6 +9,7 @@ import {
} from "../../core/config/loader.js";
import { booleanOption } from "../parser.js";
import { printJson, printKeyValue } from "../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleConfigCommand(
@@ -94,6 +95,10 @@ async function handleMode(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
}
const isStateful = targetMode === "stateful";
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换全局运行模式", targetMode, { stateful: isStateful });
}
requireMutationConfirmation(parsed, runtime, "切换全局运行模式", `hose-use config mode ${targetMode} --yes`);
const updated = saveGlobalConfig({ stateful: isStateful });
if (runtime.jsonMode) {
@@ -112,6 +117,10 @@ async function handleTestDir(parsed: CliParsedArgs, runtime: CliRuntime): Promis
const globalConfig = loadGlobalConfig();
if (isClear) {
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "清除测试企业目录配置", globalConfig.testEnterprisesDir || "当前未设置", { testEnterprisesDir: null });
}
requireMutationConfirmation(parsed, runtime, "清除测试企业目录配置", "hose-use config test-dir --clear --yes");
const updated = saveGlobalConfig({ testEnterprisesDir: undefined });
if (runtime.jsonMode) {
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
@@ -144,6 +153,10 @@ async function handleTestDir(parsed: CliParsedArgs, runtime: CliRuntime): Promis
}
const resolved = resolve(dirArg);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "设置测试企业目录", resolved, { testEnterprisesDir: resolved });
}
requireMutationConfirmation(parsed, runtime, "设置测试企业目录", `hose-use config test-dir ${dirArg} --yes`);
const updated = saveGlobalConfig({ testEnterprisesDir: resolved });
if (runtime.jsonMode) {
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
@@ -209,6 +222,10 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
};
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "更新全局配置", resolvedKey, partial);
}
requireMutationConfirmation(parsed, runtime, "更新全局配置", `hose-use config set ${rawKey} ${val} --yes`);
const updated = saveGlobalConfig(partial);
if (runtime.jsonMode) {
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
+16
View File
@@ -4,6 +4,7 @@ import { resolveWritableEnterprisesDir } from "../../core/config/loader.js";
import { stringOption, booleanOption } from "../parser.js";
import { prompt } from "../helpers.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
const FIELD_LABEL_MAP: Record<string, string> = {
@@ -269,6 +270,11 @@ async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
return { stdout: "", stderr: "用法: hose-use corps switch <企业ID>\n", exitCode: 1 };
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换当前工作企业", corpId, { defaultCorpId: corpId });
}
requireMutationConfirmation(parsed, runtime, "切换当前工作企业", `hose-use corps switch ${corpId} --yes`);
const success = runtime.corpContext.switchCorp(corpId);
if (!success) {
return {
@@ -364,6 +370,16 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
};
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "从协助链接导入企业凭证", name || "待解析企业", {
source: "assistance-link",
overwrite,
ttl: ttl || null,
expires: expires || null,
});
}
requireMutationConfirmation(parsed, runtime, "从协助链接导入企业凭证", `hose-use corps add-link <url> --yes`);
try {
const corp = await importFromLink(linkUrl, {
name,
+30 -7
View File
@@ -229,8 +229,9 @@ describe("CLI - feetype 费用类型管理命令", () => {
options: {
name: "酒店住宿",
parent: "差旅费用",
yes: true,
},
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用"],
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用", "--yes"],
},
dummyRuntimeWithCorp
);
@@ -266,8 +267,8 @@ describe("CLI - feetype 费用类型管理命令", () => {
area: "feetype",
action: "update",
args: ["酒店住宿"],
options: { desc: "新说明" },
raw: ["feetype", "update", "酒店住宿", "--desc=新说明"],
options: { desc: "新说明", yes: true },
raw: ["feetype", "update", "酒店住宿", "--desc=新说明", "--yes"],
},
dummyRuntimeWithCorp
);
@@ -324,8 +325,8 @@ describe("CLI - feetype 费用类型管理命令", () => {
area: "feetype",
action: "enable",
args: ["酒店住宿"],
options: {},
raw: ["feetype", "enable", "酒店住宿"],
options: { yes: true },
raw: ["feetype", "enable", "酒店住宿", "--yes"],
},
dummyRuntimeWithCorp
);
@@ -355,8 +356,8 @@ describe("CLI - feetype 费用类型管理命令", () => {
area: "feetype",
action: "move",
args: ["酒店住宿"],
options: { parent: "办公费" },
raw: ["feetype", "move", "酒店住宿", "--parent=办公费"],
options: { parent: "办公费", yes: true },
raw: ["feetype", "move", "酒店住宿", "--parent=办公费", "--yes"],
},
dummyRuntimeWithCorp
);
@@ -368,6 +369,28 @@ describe("CLI - feetype 费用类型管理命令", () => {
spy.mockRestore();
});
it("feetype create --dry-run 不创建费用类型", async () => {
const spy = spyOn(feetypeTools, "createFeeType").mockResolvedValue({} as any);
const res = await handleFeeTypeCommand(
{
area: "feetype",
action: "create",
args: [],
options: { name: "酒店住宿", parent: "差旅费用", "dry-run": true },
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用", "--dry-run"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("DRY-RUN");
expect(res.stdout).toContain("新建费用类型");
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
it("feetype fields 打印报账与申请字段表格", async () => {
const spy = spyOn(feetypeTools, "getFeeTypeFieldsList").mockResolvedValue({
feeType: {
+88 -9
View File
@@ -16,6 +16,7 @@ import {
updateFeeTypeInfo,
} from "../../domains/feetype/tools.js";
import { FeeTypeNode } from "../../domains/feetype/types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
/**
* 递归渲染树形层级格式
@@ -65,9 +66,13 @@ export async function handleFeeTypeCommand(
);
}
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.id;
const action = (parsed.action?.toLowerCase() || "list").trim();
let client: Awaited<ReturnType<typeof createEkbClient>> | undefined;
const getClient = async () => {
client ??= await createEkbClient(corp);
return client;
};
// ── 1. 列表 / 树形展示 (list / tree) ──────────────────────────────────────────
if (["list", "tree", "all", "search"].includes(action)) {
@@ -80,7 +85,7 @@ export async function handleFeeTypeCommand(
const keyword =
stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
const result = await listFeeTypes(client, corpId, {
const result = await listFeeTypes(await getClient(), corpId, {
all: includeAll,
flat: isFlat,
keyword,
@@ -142,7 +147,7 @@ export async function handleFeeTypeCommand(
}
const includeSpecs = booleanOption(parsed.options, ["specs", "spec", "fields"]);
const detail = await getFeeTypeDetail(client, corpId, target, { includeSpecs });
const detail = await getFeeTypeDetail(await getClient(), corpId, target, { includeSpecs });
if (runtime.jsonMode) {
return {
@@ -215,7 +220,26 @@ export async function handleFeeTypeCommand(
const color = stringOption(parsed.options, ["color"]);
const icon = stringOption(parsed.options, ["icon"]);
const created = await createFeeType(client, corpId, {
requireMutationConfirmation(
parsed,
runtime,
"新建费用类型",
`hose-use feetype create --name="${name.trim()}" --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "新建费用类型", name.trim(), {
corpId,
name: name.trim(),
code: code || null,
parentId: parent || null,
enName: enName || null,
description: description || null,
color: color || null,
icon: icon || null,
});
}
const created = await createFeeType(await getClient(), corpId, {
name: name.trim(),
code,
parentId: parent,
@@ -283,7 +307,25 @@ export async function handleFeeTypeCommand(
throw new Error("请至少提供一个待更新的属性参数 (例如 --name, --code, --desc, --color)");
}
const updated = await updateFeeTypeInfo(client, corpId, target, {
requireMutationConfirmation(
parsed,
runtime,
"修改费用类型",
`hose-use feetype update ${target} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "修改费用类型", target, {
corpId,
name: name ?? null,
code: code ?? null,
enName: enName ?? null,
description: description ?? null,
color: color ?? null,
icon: icon ?? null,
});
}
const updated = await updateFeeTypeInfo(await getClient(), corpId, target, {
name,
code,
enName,
@@ -329,7 +371,17 @@ export async function handleFeeTypeCommand(
throw new Error("请指定待停用的费用类型: hose-use feetype disable <ID|编码|名称>");
}
const res = await disableFeeTypeItem(client, corpId, target);
requireMutationConfirmation(
parsed,
runtime,
"停用费用类型",
`hose-use feetype disable ${target} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "停用费用类型", target, { corpId, active: false });
}
const res = await disableFeeTypeItem(await getClient(), corpId, target);
if (runtime.jsonMode) {
return {
@@ -365,7 +417,21 @@ export async function handleFeeTypeCommand(
const recursive =
booleanOption(parsed.options, ["recursive", "r"]) !== false;
const res = await enableFeeTypeItem(client, corpId, target, { recursive });
requireMutationConfirmation(
parsed,
runtime,
"启用费用类型",
`hose-use feetype enable ${target} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "启用费用类型", target, {
corpId,
active: true,
recursive,
});
}
const res = await enableFeeTypeItem(await getClient(), corpId, target, { recursive });
if (runtime.jsonMode) {
return {
@@ -404,7 +470,20 @@ export async function handleFeeTypeCommand(
throw new Error("请指定目标父级: --parent=<目标父级ID|编码|名称> 或 --parent=root (移至顶级)");
}
const res = await moveFeeTypeItem(client, corpId, target, parentTarget);
requireMutationConfirmation(
parsed,
runtime,
"移动费用类型",
`hose-use feetype move ${target} --parent=${parentTarget} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "移动费用类型", target, {
corpId,
parent: parentTarget,
});
}
const res = await moveFeeTypeItem(await getClient(), corpId, target, parentTarget);
if (runtime.jsonMode) {
return {
@@ -443,7 +522,7 @@ export async function handleFeeTypeCommand(
throw new Error("请指定费用类型: hose-use feetype fields <ID|编码|名称>");
}
const res = await getFeeTypeFieldsList(client, corpId, target);
const res = await getFeeTypeFieldsList(await getClient(), corpId, target);
if (runtime.jsonMode) {
return {
+14 -1
View File
@@ -4,6 +4,7 @@ import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { createEkbClient } from "../../core/auth/ekb.js";
import { filterMessages, listMessages, mergeMessages, readMessage } from "../../domains/message/tools.js";
import type { MessageItem } from "../../domains/message/types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
function formatTime(value: number | undefined): string {
return value === undefined ? "-" : new Date(value).toISOString().replace("T", " ").slice(0, 16);
@@ -26,10 +27,10 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
const corp = runtime.selectedCorp;
if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose-use corps list 或指定 --corp=<id>");
const action = parsed.action || parsed.args[0] || "list";
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.id;
if (action === "count" || action === "unread") {
const client = await createEkbClient(corp);
const result = await listMessages(client, corpId, { start: 0, count: 1, read: false });
if (runtime.jsonMode) return { stdout: printJson({ corpId, unread: result.total }, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `未读消息: ${result.total}\n`, stderr: "", exitCode: 0 };
@@ -38,12 +39,22 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
if (action === "read" || action === "mark-read") {
const messageId = parsed.args[0] || stringOption(parsed.options, ["id", "message-id"]);
if (!messageId) return { stdout: "", stderr: "用法: hose-use message read <messageId>\n", exitCode: 1 };
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "标记消息为已读", messageId, { read: true });
}
requireMutationConfirmation(parsed, runtime, "标记消息为已读", `hose-use message read ${messageId} --yes`);
const client = await createEkbClient(corp);
await readMessage(client, corpId, messageId);
if (runtime.jsonMode) return { stdout: printJson({ corpId, id: messageId, read: true }, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `已标记消息为已读: ${messageId}\n`, stderr: "", exitCode: 0 };
}
if (action === "read-all" || action === "mark-all-read") {
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "批量标记未读消息为已读", `corp:${corpId}`, { read: true, allUnread: true });
}
requireMutationConfirmation(parsed, runtime, "批量标记未读消息为已读", "hose-use message read-all --yes");
const client = await createEkbClient(corp);
const ids: string[] = [];
let start = 0;
let total = 0;
@@ -63,6 +74,8 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
return { stdout: "", stderr: `未知消息子命令: ${action}。支持: list, count, read <messageId>, read-all\n`, exitCode: 1 };
}
const client = await createEkbClient(corp);
const read = booleanOption(parsed.options, ["read"]);
const unread = booleanOption(parsed.options, ["unread"]);
const all = booleanOption(parsed.options, ["all"]);
+4 -4
View File
@@ -140,7 +140,7 @@ describe("CLI - platform 命令与 record 动作", () => {
spies.push(toggleSpy);
const res = await handlePlatformCommand(
{ area: "platform", action: "record", args: ["toggle", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
{ area: "platform", action: "record", args: ["toggle", "platform-1", "entity-1", "r-1"], options: { yes: true }, raw: ["platform", "record", "toggle", "platform-1", "entity-1", "r-1", "--yes"] },
dummyRuntime
);
@@ -161,8 +161,8 @@ describe("CLI - platform 命令与 record 动作", () => {
area: "platform",
action: "record",
args: ["edit", "platform-1", "entity-1", "r-1"],
options: { data: '{"name":"更新后的名称"}' },
raw: [],
options: { data: '{"name":"更新后的名称"}', yes: true },
raw: ["platform", "record", "edit", "platform-1", "entity-1", "r-1", "--yes"],
},
dummyRuntime
);
@@ -188,7 +188,7 @@ describe("CLI - platform 命令与 record 动作", () => {
spies.push(recomputeSpy);
const res = await handlePlatformCommand(
{ area: "platform", action: "record", args: ["recompute", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
{ area: "platform", action: "record", args: ["recompute", "platform-1", "entity-1", "r-1"], options: { yes: true }, raw: ["platform", "record", "recompute", "platform-1", "entity-1", "r-1", "--yes"] },
dummyRuntime
);
+43
View File
@@ -4,6 +4,7 @@ import { createClientsForCorp } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
function requiredTarget(parsed: CliParsedArgs, index: number, usage: string): string {
const target = parsed.args[index]?.trim();
@@ -251,6 +252,20 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
: parsed.options.active !== undefined
? booleanOption(parsed.options, ["active"], true)
: undefined;
requireMutationConfirmation(
parsed,
runtime,
"切换业务对象记录状态",
`hose-use platform record toggle ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换业务对象记录状态", recordId, {
corpId: resolved.corpId,
platformId: resolved.platform.id,
entityId: resolved.entity.id,
active: explicitState ?? "toggle",
});
}
const res = await api.toggleRecordState(resolved.clients.ekbClient, resolved.corpId, recordId, explicitState);
if (runtime.jsonMode) {
return {
@@ -278,6 +293,21 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
}
}
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
const changes = {
dataLinkEntityId: resolved.entity.id,
dataLinkId: recordId,
form,
active: activeOpt ?? null,
};
requireMutationConfirmation(
parsed,
runtime,
"编辑业务对象记录",
`hose-use platform record edit ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, changes);
}
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, {
dataLinkEntityId: resolved.entity.id,
dataLinkId: recordId,
@@ -293,6 +323,19 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
}
case "recompute":
case "recalc": {
requireMutationConfirmation(
parsed,
runtime,
"触发业务对象记录台账重算",
`hose-use platform record recompute ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "触发业务对象记录台账重算", recordId, {
corpId: resolved.corpId,
platformId: resolved.platform.id,
entityId: resolved.entity.id,
});
}
const result = await api.recomputeRecordLedger(resolved.clients.ekbClient, resolved.corpId, recordId);
if (runtime.jsonMode) return { stdout: printJson({ success: true, recordId, result }, runtime.outputOptions), stderr: "", exitCode: 0 };
return {
+37 -1
View File
@@ -87,7 +87,8 @@ describe("CLI - hose-use rule 规则与场景索引命令", () => {
"add",
"办公采购",
"单笔采购大于1万,[必须附采购合同]{硬性};[建议由采购员集中办理]{建议}。",
"--json"
"--json",
"--yes"
]);
expect(addRes.exitCode).toBe(0);
const addData = JSON.parse(addRes.stdout);
@@ -102,6 +103,41 @@ describe("CLI - hose-use rule 规则与场景索引命令", () => {
expect(scopesData.scopes[2].scope).toBe("办公采购");
});
test("hose-use rule add --dry-run 只预览且不写入数据库", async () => {
const res = await runCli([
"rule",
"add",
"办公采购",
"单笔采购大于1万,[必须附采购合同]{硬性}。",
"--json",
"--dry-run",
]);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.dryRun).toBe(true);
expect(data.operation).toBe("新增审批规则");
expect(data.changes.scope).toBe("办公采购");
const scopes = await runCli(["rule", "scopes", "--json"]);
expect(JSON.parse(scopes.stdout).count).toBe(2);
});
test("hose-use rule add 未确认时拒绝写入并给出下一步", async () => {
const res = await runCli([
"rule",
"add",
"办公采购",
"单笔采购大于1万,[必须附采购合同]{硬性}。",
]);
expect(res.exitCode).not.toBe(0);
expect(res.stderr).toContain("--dry-run");
expect(res.stderr).toContain("--yes");
const scopes = await runCli(["rule", "scopes", "--json"]);
expect(JSON.parse(scopes.stdout).count).toBe(2);
});
test("hose-use rule add 语法错误拦截并阻止入库", async () => {
const failRes = await runCli([
"rule",
+30
View File
@@ -2,6 +2,7 @@ import { ApprovalRepository, parseRuleBody } from "../../domains/approval/index.
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
export async function handleRuleCommand(
parsed: CliParsedArgs,
@@ -205,6 +206,22 @@ export async function handleRuleCommand(
if (!scope) throw new Error("缺少适用场景/索引参数:请输入索引名称或使用 --scope 指定");
if (!body) throw new Error("缺少规约正文参数:请输入正文或使用 --body 指定,须包含 [动作句式]{硬性|弹性|建议|特殊}");
// 先做纯函数校验,让调用方在确认前就能修正格式错误。
parseRuleBody(body);
requireMutationConfirmation(
parsed,
runtime,
"新增审批规则",
`hose-use rule add --scope=${scope} --body='${body}' --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "新增审批规则", scope, {
scope,
body,
status: "active",
});
}
const rule = repo.createRule({
scope,
@@ -240,6 +257,19 @@ export async function handleRuleCommand(
ruleId = found.id;
}
requireMutationConfirmation(
parsed,
runtime,
"删除审批规则",
`hose-use rule delete ${ruleId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "删除审批规则", ruleId, {
id: ruleId,
irreversible: true,
});
}
const deleted = repo.deleteRule(ruleId);
if (runtime.jsonMode) {
return {
+11 -18
View File
@@ -1,13 +1,14 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
import {
EMBEDDED_SKILL_FILES,
getDefaultGlobalSkillDir,
getAgentSkillCandidates,
getSkillContent,
installSkillFiles,
} from "../../core/embedded-skill.js";
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printKeyValue } from "../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleSkillCommand(
@@ -41,19 +42,16 @@ export async function handleSkillCommand(
? join(process.cwd(), ".agents", "skills", "hose-use")
: getDefaultGlobalSkillDir();
const result = installSkillFiles(targetDir);
// 也同时尝试安装到其它检测到的候选目录
const candidates = getAgentSkillCandidates();
for (const dir of candidates) {
if (dir !== targetDir) {
try {
installSkillFiles(dir);
} catch {
// ignore
}
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "安装 Agent Skill 文件", targetDir, {
fileCount: Object.keys(EMBEDDED_SKILL_FILES).length,
local: isLocal,
targetPolicy: customDir ? "explicit" : isLocal ? "workspace" : "global-canonical",
});
}
requireMutationConfirmation(parsed, runtime, "安装 Agent Skill 文件", `hose-use skill install${customDir ? ` --dir=${customDir}` : ""} --yes`);
const result = installSkillFiles(targetDir);
if (runtime.jsonMode) {
return {
@@ -79,7 +77,6 @@ export async function handleSkillCommand(
case "get": {
const globalDir = getDefaultGlobalSkillDir();
const localDir = join(process.cwd(), ".agents", "skills", "hose-use");
const candidates = getAgentSkillCandidates();
const statusObj = {
global: {
@@ -90,10 +87,6 @@ export async function handleSkillCommand(
dir: localDir,
installed: existsSync(join(localDir, "SKILL.md")),
},
candidates: candidates.map((dir) => ({
dir,
installed: existsSync(join(dir, "SKILL.md")),
})),
};
if (runtime.jsonMode) {
+48 -1
View File
@@ -21,6 +21,7 @@ import {
applyWorkflowPathPatch,
} from "../../domains/platform/workflow-state.js";
import { WorkflowAlertStore } from "../../domains/platform/workflow-alert-store.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
const WORKFLOW_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
@@ -118,6 +119,20 @@ async function handlePatch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
}
const patched = applyWorkflowPathPatch(sourceWorkflow, path, value);
const target = inPlace ? file : output!;
requireMutationConfirmation(
parsed,
runtime,
"写入工作流草稿文件",
`hose-use workflow patch ${pipelineId} --file=${file} --path=${path} --value='${rawValue}' ${inPlace ? "--in-place" : `--output=${target}`} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "写入工作流草稿文件", target, {
pipelineId,
path,
value,
tasksVersion: patched.tasksVersion,
});
}
writeFileSync(target, `${JSON.stringify(patched, null, 2)}\n`, "utf8");
const result = { success: true, pipelineId, path, output: target, tasksVersion: patched.tasksVersion };
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
@@ -147,6 +162,21 @@ async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${parsedWorkflow.id}]`);
}
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
requireMutationConfirmation(
parsed,
runtime,
"保存工作流草稿到远端",
`hose-use workflow save ${pipelineId} --file=${file} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "保存工作流草稿到远端", pipelineId, {
file,
tasksVersion: parsedWorkflow.tasksVersion,
forceWrite,
});
}
const clients = await createClientsForCorp(runtime.selectedCorp!);
const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId);
const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, platformId);
@@ -159,7 +189,6 @@ async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
dirtyPaths: ["*"],
};
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
if (!forceWrite && hasWorkflowVersionConflict(state, remote)) {
throw new Error(
`工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 文件 tasksVersion=${parsedWorkflow.tasksVersion}。确认来源后使用 --force-write。`
@@ -300,6 +329,15 @@ async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
async function handlePublish(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow publish <pipelineId>\n", exitCode: 1 };
requireMutationConfirmation(
parsed,
runtime,
"发布并启用工作流",
`hose-use workflow publish ${pipelineId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "发布并启用工作流", pipelineId, { state: 1 });
}
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const result = await api.toggleWorkflow(client, pipelineId, 1);
const output = { success: result.success, pipelineId, published: result.success, state: 1 };
@@ -468,6 +506,15 @@ async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise
}
const state = (stateArg === "1" || stateArg === "true" ? 1 : 0) as 0 | 1;
requireMutationConfirmation(
parsed,
runtime,
"切换工作流状态",
`hose-use workflow toggle ${pipelineId} --state=${state} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换工作流状态", pipelineId, { state });
}
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const result = await api.toggleWorkflow(client, pipelineId, state);
+58
View File
@@ -0,0 +1,58 @@
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
export class CliError extends Error {
readonly exitCode: CliExitCode;
readonly nextAction?: string;
constructor(message: string, exitCode: CliExitCode, nextAction?: string) {
super(message);
this.name = "CliError";
this.exitCode = exitCode;
this.nextAction = nextAction;
}
}
export class PayloadTooLargeError extends CliError {
constructor(message: string, nextAction?: string) {
super(message, 12, nextAction);
this.name = "PayloadTooLargeError";
}
}
export function usageError(message: string, nextAction?: string): CliError {
return new CliError(message, 2, nextAction);
}
export function confirmationRequired(message: string, nextAction: string): CliError {
return new CliError(message, 10, nextAction);
}
export function classifyCliError(error: unknown): {
exitCode: CliExitCode;
nextAction?: string;
} {
if (error instanceof CliError) {
return { exitCode: error.exitCode, nextAction: error.nextAction };
}
const value = error instanceof Error ? error.message : String(error);
const status = responseStatus(error);
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
return { exitCode: 11, nextAction: "hose-use auth login" };
}
if (/^(?:Usage:|用法:|未知(?:命令|.*子命令)|缺少|请提供|请指定|Invalid|Missing|required)/i.test(value)) {
return { exitCode: 2 };
}
if (/without --(?:yes|confirm)|请显式添加 --yes|需要 --(?:yes|confirm)/i.test(value)) {
return { exitCode: 10 };
}
return { exitCode: 1 };
}
function responseStatus(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const response = (error as { response?: unknown }).response;
if (!response || typeof response !== "object") return undefined;
const status = (response as { status?: unknown }).status;
return typeof status === "number" ? status : undefined;
}
+51
View File
@@ -0,0 +1,51 @@
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: "认证与凭证管理", usage: "hose-use auth <子命令>", commands: { login: "登录并保存企业凭证", status: "查看当前认证状态", accounts: "列出已保存账号", "switch-account": "切换默认账号" } },
corps: { summary: "多企业租户管理", usage: "hose-use corps <子命令>", commands: { list: "列出本地企业配置", search: "搜索企业与员工", switch: "切换当前工作企业", current: "查看当前企业", "add-link": "从链接导入企业凭证" } },
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
workflow: { summary: "工作流查询、草稿与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作", "--file=<workflow.json> 指定工作流快照"] },
bill: { summary: "单据检索与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
platform: { summary: "自建应用、业务对象与底层记录", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录", record: "查看或修改单条记录", permissions: "查看权限", imports: "查看导入任务" }, options: ["--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作"] },
feetype: { summary: "费用类型全生命周期管理", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", 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]", commands: { keys: "读取当前企业密钥(默认脱敏)" }, options: ["--reveal 仅在明确授权后查看明文"] },
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: "执行仲裁" } },
};
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 action = target[1]?.toLowerCase();
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("", "提示: 追加 --json 获取机器可解析结果;写操作先用 --dry-run,再用 --yes 或 --confirm 执行。", "更多: hose-use --help");
return lines.join("\n");
}
+4
View File
@@ -13,6 +13,8 @@ export function initCorpRuntime(
stateless?: boolean;
stateful?: boolean;
jsonMode?: boolean;
dryRun?: boolean;
confirmed?: boolean;
outputOptions?: OutputOptions;
appRoot?: string;
entryFile?: string;
@@ -48,6 +50,8 @@ export function initCorpRuntime(
corpContext,
selectedCorp,
jsonMode: options.jsonMode ?? false,
dryRun: options.dryRun ?? false,
confirmed: options.confirmed ?? false,
outputOptions: options.outputOptions,
appRoot: options.appRoot,
entryFile: options.entryFile,
+45
View File
@@ -0,0 +1,45 @@
import { describe, expect, test } from "bun:test";
import { handleAuthCommand } from "./commands/auth.js";
import { handleConfigCommand } from "./commands/config.js";
import { handleCorpsCommand } from "./commands/corps.js";
import { handleMessageCommand } from "./commands/message.js";
import { handleSkillCommand } from "./commands/skill.js";
import type { CliRuntime } from "./types.js";
const runtime: CliRuntime = {
corpContext: {
listCorps: () => [],
getCurrent: () => null,
switchCorp: () => true,
resolve: () => null,
} as any,
selectedCorp: {
id: "corp-test",
name: "测试企业",
corpId: "corp-test",
credentials: { accessToken: "token", corpId: "corp-test", staffId: "staff-test" },
} as any,
jsonMode: true,
};
describe("CLI mutation boundaries", () => {
test("auth login dry-run does not prompt or call the login API", async () => {
const result = await handleAuthCommand({ area: "auth", action: "login", args: [], options: { "dry-run": true }, raw: ["auth", "login", "--dry-run"] }, runtime);
expect(result.exitCode).toBe(0);
expect(JSON.parse(result.stdout).dryRun).toBe(true);
});
test("corps/config state changes share the dry-run protocol", async () => {
const corp = await handleCorpsCommand({ area: "corps", action: "switch", args: ["corp-next"], options: { "dry-run": true }, raw: ["corps", "switch", "corp-next", "--dry-run"] }, runtime);
const config = await handleConfigCommand({ area: "config", action: "mode", args: ["stateless"], options: { "dry-run": true }, raw: ["config", "mode", "stateless", "--dry-run"] }, runtime);
expect(JSON.parse(corp.stdout).operation).toContain("工作企业");
expect(JSON.parse(config.stdout).changes.stateful).toBe(false);
});
test("skill installation and message read never write during dry-run", async () => {
const skill = await handleSkillCommand({ area: "skill", action: "install", args: [], options: { "dry-run": true }, raw: ["skill", "install", "--dry-run"] }, runtime);
const message = await handleMessageCommand({ area: "message", action: "read", args: ["message-1"], options: { "dry-run": true }, raw: ["message", "read", "message-1", "--dry-run"] }, runtime);
expect(JSON.parse(skill.stdout).dryRun).toBe(true);
expect(JSON.parse(message.stdout).changes.read).toBe(true);
});
});
+57
View File
@@ -0,0 +1,57 @@
import { describe, expect, test } from "bun:test";
import { handleBillCommand } from "./commands/bill.js";
import type { CliRuntime } from "./types.js";
const runtime: CliRuntime = {
corpContext: {} as any,
selectedCorp: {
id: "corp-test",
name: "测试企业",
source: "account",
baseUrl: "https://app.ekuaibao.com",
credentials: {
corpId: "corp-test",
staffId: "staff-test",
accessToken: "token-test",
},
},
jsonMode: true,
};
describe("CLI mutation protocol", () => {
test("bill --dry-run returns a preview without creating an API client", async () => {
const result = await handleBillCommand(
{
area: "bill",
action: "approve",
args: ["S26000001"],
options: { "dry-run": true },
raw: ["bill", "approve", "S26000001", "--dry-run"],
},
runtime
);
expect(result.exitCode).toBe(0);
const preview = JSON.parse(result.stdout);
expect(preview.dryRun).toBe(true);
expect(preview.operation).toBe("同意单据审批");
expect(preview.target).toBe("S26000001");
expect(preview.nextAction).not.toContain("--dry-run");
expect(preview.nextAction).toContain("--yes");
});
test("bill write without confirmation is rejected before the API call", async () => {
await expect(
handleBillCommand(
{
area: "bill",
action: "approve",
args: ["S26000001"],
options: {},
raw: ["bill", "approve", "S26000001"],
},
runtime
)
).rejects.toThrow("--yes");
});
});
+87
View File
@@ -0,0 +1,87 @@
import { booleanOption } from "./parser.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "./types.js";
import { CliError } from "./errors.js";
/**
* All mutating CLI commands use the same two-step contract:
* 1. --dry-run only describes the intended change;
* 2. --yes/--confirm is required before the real operation runs.
*
* The parsed-argument fallback keeps command handlers easy to unit-test without
* requiring every hand-built CliRuntime to include the newer fields.
*/
export class MutationConfirmationRequired extends CliError {
readonly operation: string;
constructor(operation: string, nextAction: string) {
super(
`拒绝执行${operation}:该操作会改变数据。请先使用 --dry-run 预览,确认后追加 --yes(或 --confirm)。`,
10,
nextAction
);
this.name = "MutationConfirmationRequired";
this.operation = operation;
}
}
export function isDryRun(parsed: CliParsedArgs, runtime: CliRuntime): boolean {
return runtime.dryRun === true || booleanOption(parsed.options, ["dry-run", "dryRun", "dryrun"]);
}
export function isConfirmed(parsed: CliParsedArgs, runtime: CliRuntime): boolean {
return (
runtime.confirmed === true ||
booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])
);
}
export function requireMutationConfirmation(
parsed: CliParsedArgs,
runtime: CliRuntime,
operation: string,
nextAction: string
): void {
if (isDryRun(parsed, runtime) || isConfirmed(parsed, runtime)) return;
throw new MutationConfirmationRequired(operation, nextAction);
}
export function mutationPreview(
parsed: CliParsedArgs,
runtime: CliRuntime,
operation: string,
target: string,
changes: Record<string, unknown>
): CliResult {
const confirmedArgs = parsed.raw.filter((arg) => !["--dry-run", "--dryRun", "--dryrun"].includes(arg));
const nextAction = `hose-use ${confirmedArgs.join(" ")} --yes`;
const payload = {
dryRun: true,
operation,
target,
changes,
nextAction,
};
if (runtime.jsonMode) {
return {
stdout: `${JSON.stringify(payload, null, 2)}\n`,
stderr: "",
exitCode: 0,
};
}
const lines = [
"[DRY-RUN] 未执行任何写操作。",
`操作: ${operation}`,
`目标: ${target}`,
"变更:",
...Object.entries(changes).map(([key, value]) => ` ${key}: ${formatPreviewValue(value)}`),
`下一步: ${nextAction}`,
];
return { stdout: `${lines.join("\n")}\n`, stderr: "", exitCode: 0 };
}
function formatPreviewValue(value: unknown): string {
if (typeof value === "string") return value;
return JSON.stringify(value);
}
+3
View File
@@ -27,6 +27,9 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
"yes",
"confirm",
"force-write",
"dry-run",
"dryRun",
"dryrun",
]);
export function parseArgs(rawArgs: string[]): CliParsedArgs {
+10 -4
View File
@@ -1,6 +1,8 @@
import { writeFileSync } from "node:fs";
import { VERSION } from "../version.js";
import type { OutputOptions } from "./types.js";
import { PayloadTooLargeError } from "./errors.js";
import { renderScopedHelp } from "./help.js";
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
@@ -15,8 +17,9 @@ export function protectLargeOutput(result: unknown, options: OutputOptions = {})
if (options.allowFull || options.outputFile) return;
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) {
throw new Error(
`输出体积过大 (${bodyBytes} 字节,超过安全阈值 ${DEFAULT_OUTPUT_BYTES_LIMIT} 字节)。请使用 --output-file <路径> (或 -o <路径>) 转储到本地文件;若确需完整大报文请附加 --full 参数。`
throw new PayloadTooLargeError(
`输出体积过大 (${bodyBytes} 字节,超过安全阈值 ${DEFAULT_OUTPUT_BYTES_LIMIT} 字节)。请使用 --output-file <路径> (或 -o <路径>) 转储到本地文件;若确需完整大报文请附加 --full 参数。`,
"hose-use <command> --json --output-file <path>"
);
}
}
@@ -109,7 +112,8 @@ export function printTable(
return [headerLine, separatorLine, ...dataLines].map((l) => ` ${l}`).join("\n");
}
export function printHelp(): string {
export function printHelp(target: string[] = []): string {
if (target.length) return renderScopedHelp(target);
return `
合思/易快报企业级 CLI 工具 (hose-use) v${VERSION}
@@ -155,7 +159,9 @@ export function printHelp(): string {
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
--stateless 单次强制以无状态模式执行
--stateful 单次强制以有状态模式执行
--yes, -y 确认执行会改变单据状态的审批动作
--dry-run 只预览写操作,不发起写请求或落盘
--yes, -y 确认执行会改变数据的写操作
--confirm --yes 的可读别名;写操作必须显式确认
--help, -h 查看帮助信息
常用示例:
+38
View File
@@ -60,4 +60,42 @@ describe("CLI runner - version and help aliases", () => {
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("未知命令域: unknown-command-xyz");
});
it("returns semantic confirmation exit code and nextAction", async () => {
const result = await runCli([
"rule",
"add",
"办公采购",
"采购时,[必须附采购合同]{硬性}。",
"--json",
]);
expect(result.exitCode).toBe(10);
const data = JSON.parse(result.stdout);
expect(data.exitCode).toBe(10);
expect(data.nextAction).toContain("--yes");
});
it("supports layered help by command domain and subcommand", async () => {
const domain = await runCli(["help", "workflow"]);
expect(domain.exitCode).toBe(0);
expect(domain.stdout).toContain("workflow -");
expect(domain.stdout).toContain("patch");
expect(domain.stdout).toContain("--dry-run");
const command = await runCli(["workflow", "publish", "--help"]);
expect(command.exitCode).toBe(0);
expect(command.stdout).toContain("publish");
expect(command.stdout).toContain("发布并启用工作流");
});
it("keeps help and version machine-readable when --json is requested", async () => {
const help = await runCli(["help", "workflow", "--json"]);
const version = await runCli(["version", "--json"]);
expect(JSON.parse(help.stdout).help).toContain("workflow -");
expect(JSON.parse(version.stdout)).toEqual({ name: "hose-use", version: VERSION });
expect(help.stderr).toBe("");
expect(version.stderr).toBe("");
});
});
+38 -9
View File
@@ -1,6 +1,7 @@
import { VERSION } from "../version.js";
import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js";
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
import { classifyCliError } from "./errors.js";
import { initCorpRuntime } from "./helpers.js";
import { handleAuthCommand } from "./commands/auth.js";
import { handleCorpsCommand } from "./commands/corps.js";
@@ -65,11 +66,13 @@ async function runCliOnce(
): Promise<CliResult> {
const stdoutChunks: string[] = [];
const stderrChunks: string[] = [];
const machineJson = booleanOption(parseArgs(rawArgs).options, ["json", "j"]);
const originalLog = console.log;
const originalError = console.error;
console.log = (...values: unknown[]) => {
stdoutChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
const line = values.map((v) => (typeof v === "string" ? v : String(v))).join(" ");
(machineJson ? stderrChunks : stdoutChunks).push(line);
};
console.error = (...values: unknown[]) => {
stderrChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
@@ -116,31 +119,51 @@ function isVersionRequested(parsed: CliParsedArgs): boolean {
return false;
}
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));
}
async function dispatchCli(
rawArgs: string[],
options: CliRunOptions = {}
): Promise<CliResult> {
const parsed = parseArgs(rawArgs);
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
if (isHelpRequested(parsed)) {
return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 };
const help = printHelp(resolveHelpTarget(parsed));
return {
stdout: jsonMode ? printJson({ help }) : `${help}\n`,
stderr: "",
exitCode: 0,
};
}
if (isVersionRequested(parsed)) {
return { stdout: `hose-use v${VERSION}\n`, stderr: "", exitCode: 0 };
return {
stdout: jsonMode ? printJson({ name: "hose-use", version: VERSION }) : `hose-use v${VERSION}\n`,
stderr: "",
exitCode: 0,
};
}
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
const statelessOption = booleanOption(parsed.options, ["stateless"]);
const statefulOption = booleanOption(parsed.options, ["stateful"]);
const outputOpts = outputOptions(parsed.options);
const dryRun = booleanOption(parsed.options, ["dry-run", "dryRun", "dryrun"]);
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"]);
const runtime = initCorpRuntime({
corpId: corpIdOption,
stateless: statelessOption,
stateful: statefulOption,
jsonMode,
dryRun,
confirmed,
outputOptions: outputOpts,
appRoot: options.appRoot,
entryFile: options.entryFile,
@@ -265,7 +288,7 @@ async function dispatchCli(
case "mcp":
return await handleMcpCommand(parsed, options);
case undefined:
return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 };
return { stdout: printHelp(resolveHelpTarget(parsed)) + "\n", stderr: "", exitCode: 0 };
default:
return {
stdout: "",
@@ -275,17 +298,23 @@ async function dispatchCli(
}
} catch (error) {
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
const classification = classifyCliError(error);
if (jsonMode) {
return {
stdout: printJson({ error: true, message: errorMsg }),
stdout: JSON.stringify({
error: true,
message: errorMsg,
exitCode: classification.exitCode,
...(classification.nextAction ? { nextAction: classification.nextAction } : {}),
}, null, 2),
stderr: "",
exitCode: 1,
exitCode: classification.exitCode,
};
}
return {
stdout: "",
stderr: `[ERROR] ${errorMsg}\n`,
exitCode: 1,
stderr: `[ERROR] ${errorMsg}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`,
exitCode: classification.exitCode,
};
}
}
+2
View File
@@ -34,6 +34,8 @@ export interface CliRuntime {
corpContext: CorpContext;
selectedCorp: CorpConfig | null;
jsonMode: boolean;
dryRun?: boolean;
confirmed?: boolean;
outputOptions?: OutputOptions;
appRoot?: string;
entryFile?: string;
+44 -1
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, utimesSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
@@ -11,6 +11,8 @@ import {
loadGlobalConfig,
saveGlobalConfig,
resolveGlobalConfigFile,
syncLegacyEnterprisesDir,
syncLegacyGlobalConfig,
} from "./loader.js";
import type { CorpConfig } from "./types.js";
@@ -170,4 +172,45 @@ describe("core/config/loader", () => {
expect(updated.stateful).toBe(false);
expect(updated.defaultCorpId).toBe("test-corp-123");
});
test("syncLegacyEnterprisesDir copies legacy credentials and removes stale legacy directory", () => {
const primary = join(tempDir, "primary");
const legacy = join(tempDir, "legacy");
mkdirSync(legacy, { recursive: true });
writeFileSync(join(legacy, "corp-old.json"), JSON.stringify(createMockCorp("corp-old", "旧企业")));
const old = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);
utimesSync(join(legacy, "corp-old.json"), old, old);
utimesSync(legacy, old, old);
const result = syncLegacyEnterprisesDir(primary, legacy);
expect(result.copied).toEqual(["corp-old.json"]);
expect(result.deletedLegacyDir).toBe(true);
expect(existsSync(join(primary, "corp-old.json"))).toBe(true);
expect(existsSync(legacy)).toBe(false);
});
test("syncLegacyEnterprisesDir preserves a recently modified legacy directory", () => {
const primary = join(tempDir, "primary-recent");
const legacy = join(tempDir, "legacy-recent");
mkdirSync(legacy, { recursive: true });
writeFileSync(join(legacy, "corp-recent.json"), JSON.stringify(createMockCorp("corp-recent", "近期企业")));
const result = syncLegacyEnterprisesDir(primary, legacy);
expect(result.deletedLegacyDir).toBe(false);
expect(existsSync(legacy)).toBe(true);
});
test("syncLegacyGlobalConfig migrates and removes a stale legacy config", () => {
const primary = join(tempDir, "config", "config.json");
const legacy = join(tempDir, "legacy-config.json");
writeFileSync(legacy, JSON.stringify({ stateful: false }));
const old = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);
utimesSync(legacy, old, old);
const result = syncLegacyGlobalConfig(primary, legacy);
expect(result.copied).toBe(true);
expect(result.deletedLegacyFile).toBe(true);
expect(JSON.parse(readFileSync(primary, "utf8")).stateful).toBe(false);
expect(existsSync(legacy)).toBe(false);
});
});
+70 -2
View File
@@ -1,4 +1,4 @@
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
@@ -14,6 +14,8 @@ export const USER_ENTERPRISES_DIR = PRIMARY_USER_ENTERPRISES_DIR;
export const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "hose-use", "config.json");
export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "config.json");
const LEGACY_CLEANUP_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
function ensureDir(dir: string): void {
mkdirSync(dir, { recursive: true });
}
@@ -27,7 +29,14 @@ export function resolveEnterprisesDirs(): string[] {
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
const userDirs = configuredUserDir
? (existsSync(configuredUserDir) ? [configuredUserDir] : [])
: [PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
: (() => {
try {
syncLegacyEnterprisesDir();
} catch {
// Legacy migration must never prevent normal CLI startup.
}
return [PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
})();
const globalConfig = loadGlobalConfig();
const testDir = globalConfig.testEnterprisesDir?.trim();
@@ -69,11 +78,70 @@ export function getEnterprisesDirCandidates(): string[] {
export function resolveGlobalConfigFile(): string {
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
if (configured) return configured;
try {
syncLegacyGlobalConfig();
} catch {
// Legacy migration must never prevent normal CLI startup.
}
if (existsSync(PRIMARY_GLOBAL_CONFIG_FILE)) return PRIMARY_GLOBAL_CONFIG_FILE;
if (existsSync(LEGACY_GLOBAL_CONFIG_FILE)) return LEGACY_GLOBAL_CONFIG_FILE;
return PRIMARY_GLOBAL_CONFIG_FILE;
}
export function syncLegacyEnterprisesDir(
primaryDir: string = PRIMARY_USER_ENTERPRISES_DIR,
legacyDir: string = LEGACY_USER_ENTERPRISES_DIR
): { copied: string[]; deletedLegacyDir: boolean } {
if (!existsSync(legacyDir)) return { copied: [], deletedLegacyDir: false };
mkdirSync(primaryDir, { recursive: true, mode: 0o700 });
const copied: string[] = [];
const files = readdirSync(legacyDir).filter((file) => file.endsWith(".json"));
for (const file of files) {
const legacyPath = join(legacyDir, file);
const primaryPath = join(primaryDir, file);
if (!existsSync(primaryPath) || statSync(legacyPath).mtimeMs > statSync(primaryPath).mtimeMs) {
copyFileSync(legacyPath, primaryPath);
copied.push(file);
}
}
const now = Date.now();
const hasRecentEntry = readdirSync(legacyDir).some((file) => now - statSync(join(legacyDir, file)).mtimeMs < LEGACY_CLEANUP_GRACE_MS);
const hasNewerLegacyFile = files.some((file) => {
const legacyPath = join(legacyDir, file);
const primaryPath = join(primaryDir, file);
return existsSync(primaryPath) && statSync(legacyPath).mtimeMs > statSync(primaryPath).mtimeMs;
});
const directoryIsRecent = now - statSync(legacyDir).mtimeMs < LEGACY_CLEANUP_GRACE_MS;
const deletedLegacyDir = !hasRecentEntry && !hasNewerLegacyFile && !directoryIsRecent;
if (deletedLegacyDir) rmSync(legacyDir, { recursive: true, force: true });
return { copied, deletedLegacyDir };
}
export function syncLegacyGlobalConfig(
primaryFile: string = PRIMARY_GLOBAL_CONFIG_FILE,
legacyFile: string = LEGACY_GLOBAL_CONFIG_FILE
): { copied: boolean; deletedLegacyFile: boolean } {
if (!existsSync(legacyFile)) return { copied: false, deletedLegacyFile: false };
mkdirSync(dirname(primaryFile), { recursive: true, mode: 0o700 });
let copied = false;
if (!existsSync(primaryFile) || statSync(legacyFile).mtimeMs > statSync(primaryFile).mtimeMs) {
copyFileSync(legacyFile, primaryFile);
copied = true;
}
const oldEnough = Date.now() - statSync(legacyFile).mtimeMs >= LEGACY_CLEANUP_GRACE_MS;
const safeToDelete = existsSync(primaryFile) && statSync(legacyFile).mtimeMs <= statSync(primaryFile).mtimeMs && oldEnough;
if (safeToDelete) {
rmSync(legacyFile, { force: true });
return { copied, deletedLegacyFile: true };
}
return { copied, deletedLegacyFile: false };
}
export function loadGlobalConfig(): GlobalConfig {
const file = resolveGlobalConfigFile();
try {
+12 -3
View File
@@ -1,10 +1,14 @@
import { describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import { EMBEDDED_SKILL_FILES, getSkillContent, installSkillFiles } from "./embedded-skill.js";
import { EMBEDDED_SKILL_FILES, getDefaultGlobalSkillDir, getSkillContent, installSkillFiles } from "./embedded-skill.js";
describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
test("全局 Skill 目录固定为 ~/.agents/skills/hose-use", () => {
expect(getDefaultGlobalSkillDir()).toBe(join(homedir(), ".agents", "skills", "hose-use"));
});
test("正确内嵌 SKILL.md、agents/openai.yaml 及各领域参考专卷", () => {
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("name: hose-use");
@@ -32,6 +36,10 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toContain("hose-aipro");
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toContain("feetype");
expect(EMBEDDED_SKILL_FILES["references/store.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["references/store.md"]).toContain("hose-use keys");
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("--reveal -o <path>");
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("references/store.md");
});
test("installSkillFiles 递归保留层级结构并落盘到目标目录", () => {
@@ -39,7 +47,7 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
try {
const res = installSkillFiles(tmp);
expect(res.targetDir).toBe(tmp);
expect(res.files.length).toBe(13);
expect(res.files.length).toBe(14);
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true);
expect(existsSync(join(tmp, "references", "auth.md"))).toBe(true);
@@ -50,6 +58,7 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
expect(existsSync(join(tmp, "references", "role.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "workflow.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "service.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "store.md"))).toBe(true);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
+2 -8
View File
@@ -15,6 +15,7 @@ import refDimension from "../../skills/hose-use/references/dimension.md" with {
import refRole from "../../skills/hose-use/references/role.md" with { type: "text" };
import refApproval from "../../skills/hose-use/references/approval.md" with { type: "text" };
import refFeeType from "../../skills/hose-use/references/feetype.md" with { type: "text" };
import refStore from "../../skills/hose-use/references/store.md" with { type: "text" };
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
"SKILL.md": skillMain,
@@ -30,6 +31,7 @@ export const EMBEDDED_SKILL_FILES: Record<string, string> = {
"references/role.md": refRole,
"references/workflow.md": refWorkflow,
"references/service.md": refService,
"references/store.md": refStore,
};
export function getSkillContent(): string {
@@ -40,14 +42,6 @@ export function getDefaultGlobalSkillDir(): string {
return join(homedir(), ".agents", "skills", "hose-use");
}
export function getAgentSkillCandidates(): string[] {
return [
join(homedir(), ".agents", "skills", "hose-use"),
join(homedir(), ".gemini", "antigravity", "skills", "hose-use"),
join(homedir(), ".codex", "skills", "hose-use"),
];
}
export function installSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): {
targetDir: string;
files: string[];
+3 -3
View File
@@ -32,9 +32,9 @@ hose-use platform entities <应用 ID|名称>
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--keyword <关键词>] [--filter <表达式>] [--fields <字段列表>]
hose-use platform record get <应用> <业务对象> <记录ID>
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false]
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}'
hose-use platform record recompute <应用> <业务对象> <记录ID>
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}' [--dry-run|--yes]
hose-use platform record recompute <应用> <业务对象> <记录ID> [--dry-run|--yes]
hose-use platform permissions <应用 ID|名称> [对象 ID|名称]
hose-use platform imports <应用 ID|名称> <对象 ID|名称>
```
+8 -7
View File
@@ -49,19 +49,20 @@ hose-use feetype get 交通费
hose-use feetype get 交通费 --specs
# 创建费用类型
hose-use feetype create --name="办公杂费"
hose-use feetype create --name="市内打车" --parent="交通费"
hose-use feetype create --name="办公杂费" --dry-run
hose-use feetype create --name="办公杂费" --yes
hose-use feetype create --name="市内打车" --parent="交通费" --yes
# 修改费用类型
hose-use feetype update 市内打车 --desc="滴滴企业版"
hose-use feetype update 市内打车 --desc="滴滴企业版" --yes
# 停用与启用
hose-use feetype disable 市内打车
hose-use feetype enable 市内打车
hose-use feetype disable 市内打车 --yes
hose-use feetype enable 市内打车 --yes
# 移动层级
hose-use feetype move 市内打车 --parent="差旅费用"
hose-use feetype move 市内打车 --parent=root
hose-use feetype move 市内打车 --parent="差旅费用" --yes
hose-use feetype move 市内打车 --parent=root --yes
# 查看表单字段配置
hose-use feetype fields 交通费
+1 -1
View File
@@ -1 +1 @@
export const VERSION = "0.8.5";
export const VERSION = "0.8.6";