Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
75a0611f0e | ||
|
|
75740c4ec3 | ||
|
|
22215eb317 | ||
|
|
0c9eb27f85 | ||
|
|
ea5eb22c51 | ||
|
|
e588416a5f | ||
|
|
de88e218e7 | ||
|
|
020e4a2761 | ||
|
|
e7e856bbb0 | ||
|
|
bfbf6cf55f | ||
|
|
f3caebfd8a | ||
|
|
1eeb288143 | ||
|
|
4272dd8e60 | ||
|
|
7666db9f1d | ||
|
|
f9de8337b2 | ||
|
|
4beafe40cc | ||
|
|
3710f50ea4 | ||
|
|
55573de6a8 | ||
|
|
50362c2937 |
No files matched your search
@@ -10,7 +10,9 @@
|
||||
| [production-safety.md](./production-safety.md) | 操作真实企业前;确认只读/写入范围、预演、凭证脱敏要求 |
|
||||
| [tenant-and-credential.md](./tenant-and-credential.md) | 多租户身份、协助链接和凭证导入,以及个人单据查询 |
|
||||
| [testing-and-dev-hygiene.md](./testing-and-dev-hygiene.md) | 编写测试、隔离环境、处理非交互输入与提交验证 |
|
||||
| [troubleshooting-and-investigation.md](./troubleshooting-and-investigation.md) | 业务排障诊断、探针环境隔离,以及沉淀优先原则 |
|
||||
| [typescript-style.md](./typescript-style.md) | TypeScript、ESM 导入和运行时模型修改 |
|
||||
|
||||
| [windows-development.md](./windows-development.md) | 跨平台路径、分支命名、换行及文件名兼容 |
|
||||
|
||||
## 维护边界
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
description: "排障诊断、探针环境与正式环境隔离,以及沉淀优先原则"
|
||||
globs: "src/**/*.{ts,md}"
|
||||
trigger: "manual"
|
||||
---
|
||||
|
||||
# 业务排障与系统探查铁律(Troubleshooting & Investigation Rules)
|
||||
|
||||
本规则总结自多租户、工作流与审批流联动真实排障过程中的典型教训,面向所有在此仓库进行业务排查与功能迭代的 AI Agent。
|
||||
|
||||
---
|
||||
|
||||
## 1. 探针环境与业务目标企业严格隔离(Probe vs. Target Boundary)
|
||||
|
||||
在面对未知系统接口、未逆向的页面交互或存在破坏性风险的操作时,用户常会引导 Agent「先去测试企业(如沈玥妍测试企业)摸一下/探查一下」:
|
||||
|
||||
1. **明确行为性质是“探针(Probe)”而非“诊断结论”**:
|
||||
- 访问测试企业的**唯一目的**是:安全抓包、获取底层 API 路径、探明请求/响应 JSON Schema 或验证逆向结论。
|
||||
- **绝对禁止将探针环境的现状当作业务问题的根因**:例如测试企业的出站规则停用,绝不代表目标正式企业的单据卡住是因为规则停用。
|
||||
2. **探针完毕后必须立即主动切回业务企业**:
|
||||
- 一旦在测试企业摸清 API 契约与数据结构,必须**自动、毫不犹豫地切换回用户最初声明的问题主体(目标正式企业与员工身份)**执行只读验证;
|
||||
- 绝不能等用户反问“你在说什么、为什么不看某某所在的正式企业”才被动纠正。
|
||||
|
||||
---
|
||||
|
||||
## 2. 沉淀优先于临时脚本(Productization First)
|
||||
|
||||
在排障过程中,当发现需要调用尚未被 CLI 封装的系统内部接口(如系统出站消息规则 `GET api/outbound/v1/message`、投递日志 `POST api/outbound/v1/message/messageLog` 等)时:
|
||||
|
||||
1. **严禁随手编写 ad-hoc 一次性脚本(`scratch_*.ts`)解决眼前问题**:
|
||||
- 一次性脚本容易陷入路径引用、未导出函数、临时编译报错等低价值泥潭;
|
||||
- 一次性脚本无法给用户留下可复现、可交付的资产。
|
||||
2. **标准研发流:边排障边沉淀到工程体系**:
|
||||
- 按照分层架构规范,第一时间将接口接入:
|
||||
$$\text{transport/ (API 校验)} \rightarrow \text{services.ts (业务门面)} \rightarrow \text{cli/commands/ (用户命令)} \rightarrow \text{command-metadata.ts (参数契约)}$$
|
||||
- 补齐最小单元测试,保证 `bun test` 与 `bun run check` 通过;
|
||||
- **直接使用自身编译/运行的官方 CLI 命令(例如 `hose-use workflow outbound logs ...`)为用户输出排查结果**。
|
||||
3. **闭环 PR 与本地重载**:
|
||||
- 查完问题后,主动通过标准 PR 流程将能力合入主分支;
|
||||
- 执行 `bun run dev:override` 重新编译安装本地开发二进制与 Skill,保持环境资产最新。
|
||||
|
||||
---
|
||||
|
||||
## 3. 合思审批流与工作流联动排障心智模型(Mental Model)
|
||||
|
||||
当遇到“新提交的单据卡在工作流计算节点,且工作流运行日志没有任何记录”时,必须建立**全链路事件下发**的全局排查视角:
|
||||
|
||||
$$\text{单据提交审批} \xrightarrow{\text{审批流出站节点}} \text{系统出站规则 (Outbound)} \xrightarrow{\text{HTTP Webhook}} \text{工作流触发器 (Piper)} \xrightarrow{\text{OpenAPI}} \text{回写/推进节点}$$
|
||||
|
||||
排查漏斗四步法:
|
||||
1. **看出站规则列表(`workflow outbound list`)**:
|
||||
- 检查企业内是否存在类型为 `flow` 的出站规则;
|
||||
- 检查规则是否启用(`enable: true`),且其 `callbackUrl` 是否指向目标工作流的 Webhook 路径。
|
||||
2. **看出站投递日志(`workflow outbound logs <单号>`)**:
|
||||
- 若**完全无记录**:说明单据流转时未匹配上任何出站规则(常见原因:审批流中的出站节点未关联出站规则,或单据模板类型不在出站规则适用范围);
|
||||
- 若**有记录但状态为 FAILED**:查看日志中的 `request` 与目标服务器返回的 `response`(错误码、超时或 404 等)。
|
||||
3. **看工作流日志(`workflow logs <workflowId>`)**:
|
||||
- 若出站日志记录为 SUCCESS,但工作流日志为 0,排查 Webhook 载荷格式与工作流触发器入参映射是否脱节。
|
||||
4. **看单据类型契约(`formSpecification`)**:
|
||||
- 检查历史成功单据与卡住单据的表单规范(如「商机费用报销」vs「差旅费报销单」),核对工作流内代码节点或查询节点是否写死了特定单据模板 ID。
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
build-and-publish:
|
||||
name: 🚀 Build & Publish Multi-Platform Binaries
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
timeout-minutes: 60
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
@@ -183,9 +183,9 @@ jobs:
|
||||
local file="$1" filename expected_hash attempt info existing remote_hash asset_id response delete_failed
|
||||
filename=$(basename "$file")
|
||||
expected_hash=$(sha256sum "$file" | awk '{ print $1 }')
|
||||
for attempt in 1 2 3; do
|
||||
for attempt in 1 2 3 4 5; do
|
||||
if [ "$attempt" -gt 1 ]; then sleep "${GITEA_RETRY_DELAY:-3}"; fi
|
||||
echo " [start] Uploading ${filename} to Gitea (attempt ${attempt}/3)..."
|
||||
echo " [start] Uploading ${filename} to Gitea (attempt ${attempt}/5)..."
|
||||
if ! info=$(curl -fsS --connect-timeout 15 --max-time 60 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}"); then
|
||||
continue
|
||||
fi
|
||||
@@ -212,24 +212,16 @@ jobs:
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
echo "::error::Failed to upload ${filename} after 3 attempts."
|
||||
echo "::error::Failed to upload ${filename} after 5 attempts."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Bound outbound traffic: large raw binaries must not compete with all archives.
|
||||
pids=()
|
||||
# 串行上传:Gitea 维护期并发推大文件容易把重试窗口耗光,宁可慢也不要丢资产。
|
||||
# 配合 job 超时 60 分钟与单资产 5 次重试,给服务端抖动留出余量。
|
||||
failed=0
|
||||
for file in dist/bin/hose-use-* dist/bin/checksums.txt; do
|
||||
upload_asset "$file" &
|
||||
pids+=($!)
|
||||
if [ "${#pids[@]}" -eq 2 ]; then
|
||||
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
|
||||
pids=()
|
||||
fi
|
||||
upload_asset "$file" || failed=1
|
||||
done
|
||||
if [ "${#pids[@]}" -gt 0 ]; then
|
||||
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
|
||||
fi
|
||||
if [ "$failed" -ne 0 ]; then
|
||||
echo "::error::One or more Gitea assets failed to upload."
|
||||
exit 1
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.9.3",
|
||||
"version": "0.9.6",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.9.3)
|
||||
# hose-use (v0.9.6)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
@@ -55,7 +55,7 @@ hose-use version
|
||||
| `HOSE_AIPRO_LICENSE_FILE` | AI PRO 凭证文件路径(默认 `~/.config/hose-use/aipro-license.token`,0600) |
|
||||
| `HOSE_AIPRO_LICENSE_PRIVATE_KEY` / `HOSE_AIPRO_LICENSE_PRIVATE_FILE` | 仅签发方使用,客户端运行不需要 |
|
||||
|
||||
AI PRO 常驻服务启动后,浏览器打开 `http://127.0.0.1:8889/report` 即为本地 Web 控制台(Vue 单页、资源全内嵌、不依赖 CDN)。前端源码在 `web/`,构建产物由 `bun run web:build` 生成并内嵌进二进制。
|
||||
AI PRO 常驻服务启动后,浏览器打开 `http://127.0.0.1:8889/report` 即为本地 Web 控制台(Vue 单页、资源全内嵌、不依赖 CDN)。前端源码在 `web/`,构建产物由 `bun run web:build` 生成并内嵌进二进制。`GET /docs` 的交互式 API 文档同样全离线——Scalar 运行时由 `GET /static/scalar.js` 本地提供,仅在升级版本时才需要 `bun run docs:fetch` 联网刷新。
|
||||
|
||||
---
|
||||
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.9.3",
|
||||
"version": "0.9.6",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
@@ -29,6 +29,7 @@
|
||||
"openapi:bundle": "bun run scripts/generate/bundle-openapi.ts",
|
||||
"openapi:generate-raw": "bun run scripts/generate/generate-raw-openapi.ts",
|
||||
"openapi:all": "bun run scripts/generate/generate-raw-openapi.ts && bun run scripts/generate/bundle-openapi.ts",
|
||||
"docs:fetch": "node scripts/build/build-docs.mjs",
|
||||
"web:dev": "bun --cwd web run dev",
|
||||
"web:build": "node scripts/build/build-webui.mjs",
|
||||
"build:binary": "node scripts/build/build-binary.mjs",
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# 构建脚本
|
||||
|
||||
| 脚本 | 职责 |
|
||||
|---|---|
|
||||
| `build-binary.mjs` | 用 `bun build --compile` 编译各平台单二进制,注入 `HOSE_BUILD_*` 版本元数据,并创建 `hose-aipro` multicall 软链 |
|
||||
| `build-plugin.mjs` | 打包 `dist/mcp/server.js`(MCP 单文件产物) |
|
||||
| `package-plugin.mjs` | 生成 `dist/bin/hose-use-plugin-v<版本>.tar.gz` 完整插件包 |
|
||||
| `build-webui.mjs` | 构建 `web/` 的 Vue 控制台,把 JS/CSS 内联成 `src/packaging/generated/webui.txt` 供二进制内嵌 |
|
||||
| `build-docs.mjs` | 拉取固定版本 Scalar standalone 并校验 SHA-256,生成 `src/packaging/generated/scalar-standalone.js.txt` |
|
||||
|
||||
`build-webui.mjs` 需要开发机先执行 `bun install --cwd web`;生成物随 git 提交,CI 与编译二进制不需要前端依赖。其余三个脚本只依赖根仓库的 `bun install`。
|
||||
|
||||
对应根命令:`build:binary`、`build:plugin`、`package:plugin`、`web:build`。
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 刷新 /docs 页面使用的 Scalar 浏览器运行时。
|
||||
*
|
||||
* 固定版本 + SHA-256 校验,产物写到 src/packaging/generated/ 并随 git 提交,
|
||||
* 因此运行时完全离线,编译二进制与 CI 都不需要访问 CDN。
|
||||
* 用法:bun run docs:fetch(仅在升级 Scalar 版本时需要)
|
||||
*/
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
|
||||
const SCALAR_VERSION = "1.25.101";
|
||||
const SOURCE = `https://cdn.jsdelivr.net/npm/@scalar/api-reference@${SCALAR_VERSION}/dist/browser/standalone.js`;
|
||||
const EXPECTED_SHA256 = "045c6a1ffa88167ea7f8adb8359cdfe2d2233faead3ebe1d2ec0b1e7975d3fdc";
|
||||
|
||||
const root = resolve(import.meta.dirname, "../..");
|
||||
const target = join(root, "src", "packaging", "generated", "scalar-standalone.js.txt");
|
||||
|
||||
console.log(`[build:docs] fetching @scalar/api-reference@${SCALAR_VERSION} ...`);
|
||||
const response = await fetch(SOURCE);
|
||||
if (!response.ok) {
|
||||
console.error(`[build:docs] 下载失败: HTTP ${response.status}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
const actual = createHash("sha256").update(bytes).digest("hex");
|
||||
if (actual !== EXPECTED_SHA256) {
|
||||
console.error(`[build:docs] SHA-256 不匹配,拒绝写入`);
|
||||
console.error(` expected=${EXPECTED_SHA256}`);
|
||||
console.error(` actual =${actual}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 后缀 .txt:Bun 对 .js 的 text import 可能被当成模块;内容仍是完整 JS。
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
writeFileSync(target, bytes);
|
||||
console.log(`[build:docs] ✓ ${target} (${(bytes.length / 1024 / 1024).toFixed(2)} MiB, sha256 ${actual.slice(0, 12)}…)`);
|
||||
@@ -162,7 +162,7 @@ for arg in "$@"; do
|
||||
done
|
||||
exit 22
|
||||
`, { mode: 0o755 });
|
||||
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 30_000 });
|
||||
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 40_000 });
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toContain("assets failed to upload");
|
||||
expect(result.stdout).not.toContain("Successfully published");
|
||||
@@ -173,7 +173,7 @@ exit 22
|
||||
const result = f.run();
|
||||
expect(result.status).toBe(0);
|
||||
for (const name of f.files) expect(readFileSync(join(f.root, `count-${name}`), "utf8")).toBe("2");
|
||||
expect(result.stdout).toContain("attempt 2/3");
|
||||
expect(result.stdout).toContain("attempt 2/5");
|
||||
}, 60_000);
|
||||
|
||||
test("correct mirror assets are verified and retained without uploading replacements", () => {
|
||||
@@ -189,7 +189,7 @@ exit 22
|
||||
expect(readFileSync(join(f.root, "gh.log"), "utf8")).toContain("release download v1.0.0");
|
||||
}, 60_000);
|
||||
|
||||
test("asset transfers never exceed two concurrent workers", () => {
|
||||
test("asset transfers are serialized to a single worker", () => {
|
||||
const f = mirrorFixture("concurrency");
|
||||
expect(f.run().status).toBe(0);
|
||||
let active = 0, peak = 0;
|
||||
@@ -198,6 +198,6 @@ exit 22
|
||||
peak = Math.max(peak, active);
|
||||
}
|
||||
expect(active).toBe(0);
|
||||
expect(peak).toBeLessThanOrEqual(2);
|
||||
expect(peak).toBe(1);
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-aipro
|
||||
description: "合思 AI PRO(EASO AI PRO)确定性审批仲裁网关 CLI 与技能套件:单据挂载绑定、事实证据核验与打标 (PASS/FAIL/SKIP)、审核要点/规则场景库检索、确定性审批仲裁(同意/驳回/转人工硬阻断)、审计轨迹日志查询与常驻服务管理。用于一切合思 AI PRO 确定性审批仲裁与要点核验请求。"
|
||||
metadata:
|
||||
version: 0.9.3
|
||||
version: 0.9.6
|
||||
short-description: 合思 AI PRO 确定性审批仲裁网关与审核要点核验 skill
|
||||
---
|
||||
|
||||
# hose-aipro (v0.9.3)
|
||||
# hose-aipro (v0.9.6)
|
||||
|
||||
合思 AI PRO 确定性审批仲裁网关是专门面向企业财务核算、单据审核与自动化合规风控的确定性仲裁命令行与 SDK。
|
||||
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.9.3
|
||||
version: 0.9.6
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.9.3)
|
||||
# hose-use (v0.9.6)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.9.3
|
||||
version: 0.9.6
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.9.3",
|
||||
"version": "0.9.6",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -40,6 +40,8 @@ async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; std
|
||||
corpId: stringOption(parsed.options, ["corp"]),
|
||||
jsonMode,
|
||||
});
|
||||
// multicall 二进制的 argv0 不进 parsed.raw,显式标注入口身份供命令层判断
|
||||
runtime.app = "hose-aipro";
|
||||
|
||||
const corp = runtime.selectedCorp;
|
||||
const previewPositional = parsed.positional || [];
|
||||
|
||||
@@ -277,8 +277,10 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"lint-script": "静态检查 JavaScript / MVEL 脚本",
|
||||
"eval-script": "在本地沙箱中模拟执行脚本",
|
||||
"webhook": "向工作流 Webhook 触发器发送测试数据 (别名: webhook-send)",
|
||||
"link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)"
|
||||
"link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)",
|
||||
"outbound": "查询合思系统出站消息规则与投递日志 (list|logs)"
|
||||
},
|
||||
|
||||
"options": [
|
||||
"--flow=<单号> 指定测试单据",
|
||||
"--file=<workflow.json> 指定工作流快照",
|
||||
@@ -333,9 +335,13 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"webhook-send": "webhook",
|
||||
"webhooks": "webhook",
|
||||
"url": "link",
|
||||
"web": "link"
|
||||
"web": "link",
|
||||
"outbounds": "outbound",
|
||||
"outbound-message": "outbound"
|
||||
},
|
||||
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail is-test json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
|
||||
|
||||
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail is-test json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
|
||||
|
||||
},
|
||||
"bill": {
|
||||
"summary": "单据检索、表单规格诊断与审批动作",
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# AI PRO 命令层
|
||||
|
||||
`hose-aipro` 专属命令的 handler,由 `src/cli/aipro-registry.ts` 注册,经 `src/aipro-cli.ts` 的统一凭证门禁后分发。只读自省命令(`status` / `version` / `help` 等)豁免门禁,其余一律要求有效离线凭证。
|
||||
|
||||
| 文件 | 职责 |
|
||||
|---|---|
|
||||
| `status.ts` | 网关运行上下文、企业信息与帮助页 |
|
||||
| `rules.ts` | 规约场景、审核要点、核验清单 |
|
||||
| `bind.ts` | 单据挂载与会话初始化 |
|
||||
| `review.ts` | 事实证据核验打标(PASS / FAIL / SKIP) |
|
||||
| `decide.ts` | 确定性仲裁与流转 |
|
||||
| `logs.ts` | 审计流水查询 |
|
||||
| `service.ts` | 常驻服务控制 |
|
||||
| `report.ts` | `report --json` 聚合数据源,供本地 Web 控制台一次拉取场景 / 规则 / 会话 / 要点 / 流水 / 授权状态 |
|
||||
|
||||
`types.ts` 定义 `AiProExecutionContext` 与命令结果类型;`index.ts` 汇总导出。新增命令照常注册即可自动受门禁管辖,不需要改授权代码。
|
||||
|
||||
**边界**:凭证只作用于 `hose-aipro`;`hose-use` 是免费功能,不受任何激活门禁约束。
|
||||
@@ -572,5 +572,85 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
expect(jsRes.stdout).toContain('const ENTITY_ID = "E_contract";');
|
||||
expect(jsRes.stdout).toContain('"合同名称": FIELD_PREFIX + "name"');
|
||||
});
|
||||
|
||||
it("platform records 支持仅传单参数业务对象名称,全局反查其所属应用", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
// 按应用名称查未找到
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||
// 列出所有平台
|
||||
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||
{ id: "platform-lease", name: "租赁摊销业务" } as any,
|
||||
{ id: "platform-other", name: "其他应用" } as any,
|
||||
]));
|
||||
// 模拟应用详情与对象列表
|
||||
spies.push(spyOn(servicesApplications, "getPlatform").mockResolvedValue({
|
||||
id: "platform-lease",
|
||||
name: "租赁摊销业务",
|
||||
} as any));
|
||||
spies.push(spyOn(services, "listPlatformEntities").mockImplementation(async (_, __, platformId) => {
|
||||
if (platformId === "platform-lease") {
|
||||
return [
|
||||
{ id: "ent-track", name: "付款发票跟踪", code: "TRACK", fields: [{ name: "name", label: "名称", type: "text" }] } as any,
|
||||
];
|
||||
}
|
||||
return [];
|
||||
}));
|
||||
spies.push(spyOn(api, "searchEntityRecords").mockResolvedValue({
|
||||
total: 1,
|
||||
data: [
|
||||
{
|
||||
id: "rec-1",
|
||||
dataLink: { id: "rec-1", name: "记录1", code: "R1", active: true, updateTime: "2026-10-22" },
|
||||
},
|
||||
],
|
||||
actions: [],
|
||||
components: [],
|
||||
path: null,
|
||||
template: null,
|
||||
}));
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["付款发票跟踪"], options: { count: 1 }, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("记录1");
|
||||
});
|
||||
|
||||
it("platform records 单参数业务对象在多个应用重名时抛出明确指导错误", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||
{ id: "app-1", name: "应用一" } as any,
|
||||
{ id: "app-2", name: "应用二" } as any,
|
||||
]));
|
||||
spies.push(spyOn(services, "listPlatformEntities").mockImplementation(async (_, __, platformId) => {
|
||||
return [{ id: `ent-${platformId}`, name: "重名对象", code: "DUP" } as any];
|
||||
}));
|
||||
|
||||
await expect(
|
||||
handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["重名对象"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
)
|
||||
).rejects.toThrow("在多个自建应用中找到同名业务对象 [重名对象],请显式指定应用名称");
|
||||
});
|
||||
|
||||
it("platform records 单参数既不是应用也不是业务对象时返回明确 NOT FOUND 错误", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||
{ id: "app-1", name: "应用一" } as any,
|
||||
]));
|
||||
spies.push(spyOn(services, "listPlatformEntities").mockResolvedValue([]));
|
||||
|
||||
await expect(
|
||||
handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["未知目标"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
)
|
||||
).rejects.toThrow("[NOT FOUND] 当前企业下未找到名为 [未知目标] 的自建应用或业务对象");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -243,8 +243,8 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const nameField = resolved.entity.fields?.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields?.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
|
||||
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record<string, unknown>) : item;
|
||||
const id = source.id ?? item.id;
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { resolveEntity } from "../../../domains/platform/datalink/services.js";
|
||||
import { resolvePlatform } from "../../../domains/platform/applications/services.js";
|
||||
import type { KyInstance } from "ky";
|
||||
import { listPlatformEntities, resolveEntity } from "../../../domains/platform/datalink/services.js";
|
||||
import { getPlatform, listPlatforms, resolvePlatform } from "../../../domains/platform/applications/services.js";
|
||||
import type { DatalinkEntity } from "../../../domains/platform/datalink/types.js";
|
||||
import type { DatalinkPlatformDetail } from "../../../domains/platform/applications/types.js";
|
||||
import { createClientsForCorp } from "../../helpers.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
@@ -19,16 +22,81 @@ export function cell(value: unknown): string {
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在企业全量自建应用中智能反查指定业务对象,避免强制用户/Agent 手动查询并记忆 platformId
|
||||
*/
|
||||
async function resolveEntityGlobally(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<{ platform: DatalinkPlatformDetail; entity: DatalinkEntity } | undefined> {
|
||||
const platforms = await listPlatforms(client, corpId);
|
||||
const matches: Array<{ platform: any; entity: DatalinkEntity }> = [];
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
platforms.map(async (p) => {
|
||||
const entities = await listPlatformEntities(client, corpId, p.id);
|
||||
const found = entities.find((e) =>
|
||||
[e.id, e.name, e.code].some((val) => typeof val === "string" && val.toLowerCase() === target.toLowerCase())
|
||||
);
|
||||
if (found) {
|
||||
return { platform: p, entity: found };
|
||||
}
|
||||
return null;
|
||||
})
|
||||
);
|
||||
|
||||
for (const r of results) {
|
||||
if (r.status === "fulfilled" && r.value) {
|
||||
matches.push(r.value);
|
||||
}
|
||||
}
|
||||
|
||||
if (matches.length === 1) {
|
||||
const fullPlatform = await getPlatform(client, corpId, matches[0].platform.id);
|
||||
return { platform: fullPlatform || matches[0].platform, entity: matches[0].entity };
|
||||
}
|
||||
|
||||
if (matches.length > 1) {
|
||||
const names = matches.map((m) => `[${m.platform.name}] (${m.platform.id})`).join(", ");
|
||||
throw new Error(`在多个自建应用中找到同名业务对象 [${target}],请显式指定应用名称: ${names}`);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
|
||||
const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>");
|
||||
const targetA = parsed.args[appIndex]?.trim();
|
||||
const targetB = parsed.args[entityIndex]?.trim();
|
||||
|
||||
if (!targetA) {
|
||||
throw new Error("请提供自建应用或业务对象参数: hose-use platform <子命令> [应用] <业务对象>");
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, appTarget);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${appTarget}`);
|
||||
|
||||
const entityTarget = parsed.args[entityIndex]?.trim();
|
||||
if (!entityTarget) return { clients, corpId, platform, entity: undefined };
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
// 1. 若提供了两个位置参数,严格按「应用 ➔ 对象」标准两级解析
|
||||
if (targetB) {
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, targetA);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${targetA}`);
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, targetB);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${targetB}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
}
|
||||
|
||||
// 2. 若仅提供了一个位置参数:优先尝试按「应用」解析(兼容查看应用级信息,如 entities/audit 等)
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, targetA);
|
||||
if (platform) {
|
||||
return { clients, corpId, platform, entity: undefined };
|
||||
}
|
||||
|
||||
// 3. 若按应用未找到,自动降维为「业务对象」在企业全量自建应用中智能反查 (Zero-Config Search)
|
||||
const globalMatch = await resolveEntityGlobally(clients.ekbClient, corpId, targetA);
|
||||
if (globalMatch) {
|
||||
return { clients, corpId, platform: globalMatch.platform, entity: globalMatch.entity };
|
||||
}
|
||||
|
||||
throw new Error(`[NOT FOUND] 当前企业下未找到名为 [${targetA}] 的自建应用或业务对象`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { handleSkillCommand } from "./skill.js";
|
||||
import { getAiProSkillContent, getSkillContent } from "../../packaging/embedded-skill.js";
|
||||
|
||||
const parsed = {
|
||||
area: "skill",
|
||||
action: "dump",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["skill", "dump"],
|
||||
};
|
||||
|
||||
const baseRuntime = {
|
||||
selectedCorp: null,
|
||||
corpContext: {},
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
describe("skill dump 的 multicall 入口识别", () => {
|
||||
test("hose-aipro 入口返回 AI PRO Skill(不依赖 argv0 猜测)", async () => {
|
||||
const result = await handleSkillCommand(parsed as never,{ ...baseRuntime, app: "hose-aipro" } as never);
|
||||
expect(result.stdout).toBe(`${getAiProSkillContent()}\n`);
|
||||
expect(result.stdout).toContain("hose-aipro (v");
|
||||
});
|
||||
|
||||
test("hose-use 入口返回平台 Skill", async () => {
|
||||
const result = await handleSkillCommand(parsed as never,{ ...baseRuntime, app: "hose-use" } as never);
|
||||
expect(result.stdout).toBe(`${getSkillContent()}\n`);
|
||||
expect(result.stdout).toContain("hose-use (v");
|
||||
});
|
||||
|
||||
test("兼容历史:未标注 app 时仍按 parsed.raw 里的 aipro 标记识别", async () => {
|
||||
const legacyParsed = { ...parsed, raw: ["skill", "dump", "aipro"] };
|
||||
const result = await handleSkillCommand(legacyParsed as never, baseRuntime as never);
|
||||
expect(result.stdout).toBe(`${getAiProSkillContent()}\n`);
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,7 @@ export async function handleSkillCommand(
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action || "status";
|
||||
const isAiProCaller =
|
||||
runtime.app === "hose-aipro" ||
|
||||
parsed.area === "hose-aipro" ||
|
||||
parsed.raw.some((arg) => arg.includes("hose-aipro") || arg === "aipro");
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/workflow/services.js";
|
||||
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots, searchWorkflowJobByFlowCode } from "../../../domains/platform/workflow/services.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
@@ -28,8 +28,52 @@ export async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
|
||||
export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--flow=<单号>] [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
|
||||
// 优先支持按单号精准定位 Job(本地 SQLite 缓存秒级直达 + 流式熔断探查)
|
||||
const flowFilter = stringOption(parsed.options, ["flow", "flowCode", "code"]);
|
||||
if (flowFilter) {
|
||||
const corpId = runtime.selectedCorp?.credentials.corpId || "";
|
||||
const searchResult = await searchWorkflowJobByFlowCode(client, corpId, pipelineId, flowFilter, {
|
||||
maxScanPages: numberOption(parsed.options, ["max-pages", "maxPages", "page-limit"]) ?? 10,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(searchResult, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: searchResult.found ? 0 : 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (!searchResult.found) {
|
||||
return {
|
||||
stdout: `未找到单号 [${flowFilter}] 对应的工作流执行记录 (已探查 ${searchResult.totalScanned || 0} 笔 Job)\n`,
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const job = searchResult.job!;
|
||||
const hitInfo = searchResult.source === "cache" ? "⚡ 本地 SQLite 缓存秒级命中" : "🔍 远端流式探查并自动建立本地缓存";
|
||||
const out = [
|
||||
`====== 工作流单据定位成功 [${pipelineId}] ======`,
|
||||
printKeyValue({
|
||||
"定位来源": hitInfo,
|
||||
"触发单号": searchResult.flowCode || "-",
|
||||
"实例 ID (jobId)": job.id,
|
||||
"运行状态 (status)": job.status || "-",
|
||||
"提交人": job.inputs?.userInfo?.name || "-",
|
||||
"创建时间": job.createTime ? new Date(job.createTime).toLocaleString() : "-",
|
||||
}),
|
||||
"",
|
||||
`提示: 可执行 hose-use workflow job ${job.id} 查看该单据的完整节点执行树与代码运算日志。`,
|
||||
].join("\n");
|
||||
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rawResult = await listWorkflowLogs(client, pipelineId, {
|
||||
state: stringOption(parsed.options, ["state"]),
|
||||
page: numberOption(parsed.options, ["page"]),
|
||||
|
||||
@@ -17,6 +17,8 @@ import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js"
|
||||
import { handleWorkflowEnum } from "./enum.js";
|
||||
import { handleWebhookCommand } from "./webhook.js";
|
||||
import { handleWorkflowLink } from "./link.js";
|
||||
import { handleOutboundCommand } from "./outbound.js";
|
||||
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -126,11 +128,16 @@ export async function handleWorkflowCommand(
|
||||
case "url":
|
||||
case "web":
|
||||
return handleWorkflowLink(parsed, runtime);
|
||||
case "outbound":
|
||||
case "outbounds":
|
||||
case "outbound-message":
|
||||
return handleOutboundCommand(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook, link\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook, link, outbound\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { handleOutboundCommand } from "./outbound.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
describe("handleOutboundCommand", () => {
|
||||
it("rejects when no corp selected", async () => {
|
||||
const result = await handleOutboundCommand(
|
||||
{ args: ["list"], options: {}, raw: [] },
|
||||
{ selectedCorp: null, jsonMode: false } as unknown as CliRuntime
|
||||
);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("未选中企业");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { stringOption, numberOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createSessionClient } from "../../../core/http/session-client.js";
|
||||
import { getOutboundMessages, queryOutboundMessageLogs } from "../../../domains/platform/workflow/services.js";
|
||||
|
||||
function formatTime(timestamp: number | undefined): string {
|
||||
if (!timestamp) return "-";
|
||||
const date = new Date(timestamp);
|
||||
return date.toLocaleString("zh-CN", { hour12: false });
|
||||
}
|
||||
|
||||
export async function handleOutboundCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const sub = parsed.args[0] || "list";
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const client = await createSessionClient(corp);
|
||||
|
||||
if (sub === "list" || sub === "rules") {
|
||||
const rules = await getOutboundMessages(client, corpId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ corpId, total: rules.length, items: rules }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "规则名称", "类型", "状态", "目标回调 URL", "监听事件"];
|
||||
const rows = rules.map((r, i) => [
|
||||
String(i + 1),
|
||||
r.messageName || "-",
|
||||
r.messageType || "-",
|
||||
r.enable ? "🟢 启用" : "⚪ 停用",
|
||||
r.callbackUrl || "-",
|
||||
r.actionEvent && r.actionEvent.length ? r.actionEvent.join(", ") : "全部/默认",
|
||||
]);
|
||||
|
||||
const title = `====== [${corp.name}] 出站消息规则列表 (共 ${rules.length} 条) ======\n`;
|
||||
return {
|
||||
stdout: title + (rules.length ? printTable(headers, rows) : " (暂无配置)\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (sub === "logs" || sub === "log") {
|
||||
const code = stringOption(parsed.options, ["code", "sn", "flow", "bill"]) || (parsed.args[1] && !parsed.args[1].startsWith("-") ? parsed.args[1] : undefined);
|
||||
const messageType = stringOption(parsed.options, ["type", "message-type"]) || "flow";
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0) ?? 0;
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20) ?? 20;
|
||||
|
||||
const result = await queryOutboundMessageLogs(client, corpId, {
|
||||
messageType,
|
||||
code,
|
||||
start,
|
||||
count,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ corpId, code, total: result.count, items: result.items }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "单号", "规则名", "动作/阶段", "状态", "投递时间", "目标 URL / 响应详情"];
|
||||
const rows = result.items.map((item, i) => {
|
||||
const sn = item.flowId?.form?.code || item.request?.code || "-";
|
||||
const statusIcon = item.state === "SUCCESS" ? "✅ 成功" : item.state === "FAILED" ? "❌ 失败" : item.state;
|
||||
const respPreview = typeof item.response === "object" && item.response !== null
|
||||
? JSON.stringify(item.response).slice(0, 60)
|
||||
: String(item.response ?? "-").slice(0, 60);
|
||||
|
||||
return [
|
||||
String(i + 1),
|
||||
sn,
|
||||
item.name || "-",
|
||||
`${item.type} (${item.nodeName || "-"})`,
|
||||
statusIcon,
|
||||
formatTime(item.createTime),
|
||||
respPreview,
|
||||
];
|
||||
});
|
||||
|
||||
const filterDesc = code ? ` | 单号筛选: ${code}` : "";
|
||||
const title = `====== [${corp.name}] 出站消息投递日志 (类型: ${messageType}${filterDesc} | 匹配: ${result.count} | 返回: ${result.items.length}) ======\n`;
|
||||
return {
|
||||
stdout: title + (result.items.length ? printTable(headers, rows) : " (暂无匹配日志)\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 outbound 子命令: ${sub}。支持: list (别名: rules), logs [单号] [--type=flow|message]\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -162,6 +162,7 @@ async function dispatchParsedCli(
|
||||
launcher: options.launcher,
|
||||
});
|
||||
runtime.writeStdout = options.writeStdout;
|
||||
runtime.app = "hose-use";
|
||||
|
||||
try {
|
||||
if (!parsed.area) {
|
||||
|
||||
@@ -44,6 +44,8 @@ export interface CliRuntime {
|
||||
outputOptions?: OutputOptions;
|
||||
appRoot?: string;
|
||||
entryFile?: string;
|
||||
/** 入口身份,由 runCli / runAiProCli 显式标注,供命令层区分 multicall 调用方。 */
|
||||
app?: "hose-use" | "hose-aipro";
|
||||
launcher?: {
|
||||
command: string;
|
||||
args?: string[];
|
||||
|
||||
@@ -28,8 +28,9 @@ src/core/
|
||||
│ ├── multi-level.ts # 多级联动门面与 in-flight 并发防击穿包装器
|
||||
│ └── types.ts
|
||||
├── db/ # 统一 SQLite 数据库与结构化版本迁移
|
||||
│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护
|
||||
│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations)
|
||||
│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护
|
||||
│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations)
|
||||
│ ├── workflow-job-cache.ts # 工作流 Job 索引缓存与单据触发单号秒级检索
|
||||
│ └── types.ts
|
||||
├── config/ # 企业配置管理
|
||||
│ ├── loader.ts # 全局与多企业配置读写(强制 0o600 权限与字段归一化)
|
||||
|
||||
@@ -39,6 +39,7 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
|
||||
expect(tableNames.has("cache_entries")).toBe(true);
|
||||
expect(tableNames.has("observed_events")).toBe(true);
|
||||
expect(tableNames.has("workflow_error_alerts")).toBe(true);
|
||||
expect(tableNames.has("workflow_job_index")).toBe(true);
|
||||
|
||||
// 检查加固索引:UPPER(short_id)、findings(rule_id)
|
||||
const indices = db
|
||||
@@ -55,6 +56,8 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
|
||||
expect(indexNames.has("idx_cache_expires_at")).toBe(true);
|
||||
expect(indexNames.has("idx_observed_events_scope")).toBe(true);
|
||||
expect(indexNames.has("idx_workflow_alerts_scope")).toBe(true);
|
||||
expect(indexNames.has("idx_wf_jobs_corp_pipeline_code")).toBe(true);
|
||||
expect(indexNames.has("idx_wf_jobs_code_upper")).toBe(true);
|
||||
});
|
||||
|
||||
test("cache_entries 具备复合主键 (namespace, key) 约束", () => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./types.js";
|
||||
export * from "./connection.js";
|
||||
export * from "./migrations.js";
|
||||
export * from "./workflow-job-cache.js";
|
||||
@@ -242,6 +242,30 @@ export const migrations: DatabaseMigration[] = [
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
version: 5,
|
||||
name: "005_workflow_job_cache",
|
||||
up(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS workflow_job_index (
|
||||
corp_id TEXT NOT NULL,
|
||||
pipeline_id TEXT NOT NULL,
|
||||
job_id TEXT NOT NULL,
|
||||
flow_code TEXT,
|
||||
flow_id TEXT,
|
||||
execute_time INTEGER,
|
||||
status TEXT,
|
||||
user_name TEXT,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (corp_id, pipeline_id, job_id)
|
||||
);
|
||||
`);
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_code ON workflow_job_index(corp_id, flow_code);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_pipeline ON workflow_job_index(corp_id, pipeline_id);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_corp_pipeline_code ON workflow_job_index(corp_id, pipeline_id, flow_code);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_code_upper ON workflow_job_index(corp_id, pipeline_id, UPPER(flow_code));");
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function seedDefaultPreference(db: Database): void {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { closeDatabase, getDatabase } from "./connection.js";
|
||||
import {
|
||||
getCachedWorkflowJobByCode,
|
||||
upsertWorkflowJobIndex,
|
||||
type WorkflowJobCacheRecord,
|
||||
} from "./workflow-job-cache.js";
|
||||
|
||||
describe("Core DB - Workflow Job 本地缓存与索引检索 (workflow_job_index)", () => {
|
||||
let db: Database;
|
||||
|
||||
beforeEach(() => {
|
||||
db = getDatabase(":memory:");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeDatabase();
|
||||
});
|
||||
|
||||
test("批量插入 Job 缓存并支持单号精准与大小写不敏感检索", () => {
|
||||
const records: WorkflowJobCacheRecord[] = [
|
||||
{
|
||||
corpId: "corp_winner",
|
||||
pipelineId: "pipe_101",
|
||||
jobId: "job_001",
|
||||
flowCode: "XZ2610474",
|
||||
flowId: "flow_abc",
|
||||
executeTime: 1700000000000,
|
||||
status: "COMPLETED",
|
||||
userName: "欧阳亚玲",
|
||||
},
|
||||
{
|
||||
corpId: "corp_winner",
|
||||
pipelineId: "pipe_101",
|
||||
jobId: "job_002",
|
||||
flowCode: "XZ2610475",
|
||||
status: "RUNNING",
|
||||
},
|
||||
];
|
||||
|
||||
upsertWorkflowJobIndex(records, ":memory:");
|
||||
|
||||
// 精确匹配
|
||||
const hitExact = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "XZ2610474", ":memory:");
|
||||
expect(hitExact).not.toBeNull();
|
||||
expect(hitExact?.jobId).toBe("job_001");
|
||||
expect(hitExact?.userName).toBe("欧阳亚玲");
|
||||
expect(hitExact?.status).toBe("COMPLETED");
|
||||
|
||||
// 小写模糊匹配
|
||||
const hitLower = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "xz2610474", ":memory:");
|
||||
expect(hitLower).not.toBeNull();
|
||||
expect(hitLower?.jobId).toBe("job_001");
|
||||
|
||||
// 不存在的单号或不同企业/工作流应返回 null
|
||||
expect(getCachedWorkflowJobByCode("corp_winner", "pipe_101", "NON_EXISTENT", ":memory:")).toBeNull();
|
||||
expect(getCachedWorkflowJobByCode("other_corp", "pipe_101", "XZ2610474", ":memory:")).toBeNull();
|
||||
expect(getCachedWorkflowJobByCode("corp_winner", "other_pipe", "XZ2610474", ":memory:")).toBeNull();
|
||||
});
|
||||
|
||||
test("同单号存在多笔记录时,按 execute_time DESC 优先返回最新执行的一笔", () => {
|
||||
const records: WorkflowJobCacheRecord[] = [
|
||||
{
|
||||
corpId: "corp_winner",
|
||||
pipelineId: "pipe_101",
|
||||
jobId: "job_old",
|
||||
flowCode: "XZ2610474",
|
||||
executeTime: 1000,
|
||||
status: "FAILED",
|
||||
},
|
||||
{
|
||||
corpId: "corp_winner",
|
||||
pipelineId: "pipe_101",
|
||||
jobId: "job_new",
|
||||
flowCode: "XZ2610474",
|
||||
executeTime: 2000,
|
||||
status: "COMPLETED",
|
||||
},
|
||||
];
|
||||
|
||||
upsertWorkflowJobIndex(records, ":memory:");
|
||||
|
||||
const hit = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "XZ2610474", ":memory:");
|
||||
expect(hit).not.toBeNull();
|
||||
expect(hit?.jobId).toBe("job_new");
|
||||
expect(hit?.status).toBe("COMPLETED");
|
||||
});
|
||||
|
||||
test("相同主键冲突时,执行增量更新并保持已有非空字段 (COALESCE)", () => {
|
||||
upsertWorkflowJobIndex(
|
||||
[
|
||||
{
|
||||
corpId: "corp_winner",
|
||||
pipelineId: "pipe_101",
|
||||
jobId: "job_001",
|
||||
flowCode: "XZ2610474",
|
||||
userName: "欧阳亚玲",
|
||||
status: "RUNNING",
|
||||
executeTime: 1000,
|
||||
},
|
||||
],
|
||||
":memory:"
|
||||
);
|
||||
|
||||
// 再次写入,只更新 status,未传 userName
|
||||
upsertWorkflowJobIndex(
|
||||
[
|
||||
{
|
||||
corpId: "corp_winner",
|
||||
pipelineId: "pipe_101",
|
||||
jobId: "job_001",
|
||||
status: "COMPLETED",
|
||||
},
|
||||
],
|
||||
":memory:"
|
||||
);
|
||||
|
||||
const hit = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "XZ2610474", ":memory:");
|
||||
expect(hit).not.toBeNull();
|
||||
expect(hit?.jobId).toBe("job_001");
|
||||
expect(hit?.status).toBe("COMPLETED");
|
||||
// userName 依然保留
|
||||
expect(hit?.userName).toBe("欧阳亚玲");
|
||||
});
|
||||
|
||||
test("空数组调用 upsert 不抛异常", () => {
|
||||
expect(() => upsertWorkflowJobIndex([], ":memory:")).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { getDatabase } from "./connection.js";
|
||||
|
||||
export interface WorkflowJobCacheRecord {
|
||||
corpId: string;
|
||||
pipelineId: string;
|
||||
jobId: string;
|
||||
flowCode?: string;
|
||||
flowId?: string;
|
||||
executeTime?: number;
|
||||
status?: string;
|
||||
userName?: string;
|
||||
updatedAt?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按企业 + 工作流 + 单号快速从本地 SQLite 缓存中检索匹配的 Job 记录
|
||||
*/
|
||||
export function getCachedWorkflowJobByCode(
|
||||
corpId: string,
|
||||
pipelineId: string,
|
||||
flowCode: string,
|
||||
dbPath?: string
|
||||
): WorkflowJobCacheRecord | null {
|
||||
const db = getDatabase(dbPath);
|
||||
const normalizedCode = flowCode.trim();
|
||||
const row = db
|
||||
.query(
|
||||
`SELECT corp_id AS corpId, pipeline_id AS pipelineId, job_id AS jobId,
|
||||
flow_code AS flowCode, flow_id AS flowId, execute_time AS executeTime,
|
||||
status, user_name AS userName, updated_at AS updatedAt
|
||||
FROM workflow_job_index
|
||||
WHERE corp_id = ? AND pipeline_id = ? AND (flow_code = ? OR UPPER(flow_code) = UPPER(?))
|
||||
ORDER BY execute_time DESC, updated_at DESC
|
||||
LIMIT 1`
|
||||
)
|
||||
.get(corpId, pipelineId, normalizedCode, normalizedCode) as WorkflowJobCacheRecord | null;
|
||||
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入或更新 Job 缓存索引
|
||||
*/
|
||||
export function upsertWorkflowJobIndex(
|
||||
records: WorkflowJobCacheRecord[],
|
||||
dbPath?: string
|
||||
): void {
|
||||
if (!records.length) return;
|
||||
const db = getDatabase(dbPath);
|
||||
const now = Date.now();
|
||||
|
||||
const insertStmt = db.prepare(`
|
||||
INSERT INTO workflow_job_index (
|
||||
corp_id, pipeline_id, job_id, flow_code, flow_id, execute_time, status, user_name, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(corp_id, pipeline_id, job_id) DO UPDATE SET
|
||||
flow_code = COALESCE(excluded.flow_code, workflow_job_index.flow_code),
|
||||
flow_id = COALESCE(excluded.flow_id, workflow_job_index.flow_id),
|
||||
execute_time = COALESCE(excluded.execute_time, workflow_job_index.execute_time),
|
||||
status = COALESCE(excluded.status, workflow_job_index.status),
|
||||
user_name = COALESCE(excluded.user_name, workflow_job_index.user_name),
|
||||
updated_at = excluded.updated_at
|
||||
`);
|
||||
|
||||
db.transaction(() => {
|
||||
for (const r of records) {
|
||||
insertStmt.run(
|
||||
r.corpId,
|
||||
r.pipelineId,
|
||||
r.jobId,
|
||||
r.flowCode || null,
|
||||
r.flowId || null,
|
||||
r.executeTime || null,
|
||||
r.status || null,
|
||||
r.userName || null,
|
||||
now
|
||||
);
|
||||
}
|
||||
})();
|
||||
}
|
||||
@@ -33,7 +33,7 @@ hose-use platform list
|
||||
hose-use platform get <应用 ID|名称>
|
||||
hose-use platform entities <应用 ID|名称>
|
||||
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--page <页码>] [--count <每页条数>] [--all] [--keyword <关键词>] [--search-fields <字段列表>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats]
|
||||
hose-use platform records [应用 ID|名称] <对象 ID|名称> [--page <页码>] [--count <每页条数>] [--all] [--keyword <关键词>] [--search-fields <字段列表>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats]
|
||||
hose-use platform record get [<应用> <业务对象>] <记录ID>
|
||||
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> [--set="字段=值" | --data='{"field": "val"}'] [--raw] [--dry-run|--yes]
|
||||
@@ -47,6 +47,8 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
- `records <业务对象>`(单参数免应用查询):当企业自建应用较多时,无需事先查询 platformId。直接输入业务对象名称或编码,CLI 自动遍历企业全量自建应用进行智能反查与寻址;若跨应用重名则抛出精准候选项提示,避免人工心智负担。
|
||||
|
||||
- `records --ndjson`(或 `--stream`):针对万级~十万级海量记录,采用 AsyncGenerator 分页流式生成,逐行向 `stdout` 发射 NDJSON。内存恒定为 $O(\text{pageSize})$,严防大报文撑爆内存或终端,无缝对接下游 `jq`、Python 处理流水线。
|
||||
- 终端入口提供显式输出回调并等待写入完成以响应背压;`--ndjson -o <path>` 写入真正的 NDJSON 文件,返回文件路径、字节数和记录数摘要。
|
||||
- MCP / HTTP 默认不提供终端输出通道;未指定文件时拒绝直接流式输出,避免污染协议 stdout 或返回空的成功响应。输出逐行执行统一脱敏。
|
||||
|
||||
@@ -19,7 +19,7 @@ hose-use workflow list [--platform-id=<id>|--app-id=<id>] [-q|--keyword=<关键
|
||||
hose-use workflow get <pipelineId>
|
||||
hose-use workflow enum [thirdId] [--third-id=<id>] [--json]
|
||||
hose-use workflow analyze <pipelineId> [--json]
|
||||
hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
|
||||
hose-use workflow logs <pipelineId> [--flow=<单号>] [--has-error] [--state=FAILED]
|
||||
hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose]
|
||||
hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]
|
||||
hose-use workflow diff-job <jobId1> <jobId2> [--json]
|
||||
@@ -44,6 +44,7 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
```
|
||||
|
||||
- `workflow list [-q|--keyword=<关键词>] [--full]`:工作流列表。默认采用**轻量化紧凑模式**,自动剥离每个流程内部包含的庞大 `tasks` 节点树与 MVEL/JS 脚本代码(仅保留 `nodeCount` 统计与核心元数据),将输出报文体积削减 97%(从数兆降至几十 KB),彻底解决上下文截断。传入 `--full` 或 `--with-tasks` 时恢复输出完整节点树。支持 `-q / --keyword` 模糊匹配工作流名称、ID 与应用名称。
|
||||
- `workflow logs <pipelineId> --flow=<单号>`:按业务单号(如报销单/销账单号)秒级定位对应的 Job 实例。由于外部 Piper API 原生无单号索引,CLI 引入「本地 SQLite 缓存 + 流式探查早停熔断」机制:首次探查边扫描边建立本地单号索引,后续命中直接 0ms 返回,避免全表盲目拉取。
|
||||
|
||||
## 触发器分类与调测路径分支 (Path Branching)
|
||||
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { closeDatabase, getDatabase } from "../../../../core/db/connection.js";
|
||||
import {
|
||||
extractJobFlowCode,
|
||||
searchWorkflowJobByFlowCode,
|
||||
} from "./search-by-flow.js";
|
||||
|
||||
describe("Workflow - 按单号查找运行实例 (searchWorkflowJobByFlowCode)", () => {
|
||||
const originalDbEnv = process.env.HOSE_APPROVAL_DB;
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
getDatabase(":memory:");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeDatabase();
|
||||
if (originalDbEnv !== undefined) {
|
||||
process.env.HOSE_APPROVAL_DB = originalDbEnv;
|
||||
} else {
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
}
|
||||
});
|
||||
|
||||
test("extractJobFlowCode 能准确从各类 inputs 结构或顶层字段解析出单号", () => {
|
||||
expect(extractJobFlowCode(null)).toBeUndefined();
|
||||
expect(extractJobFlowCode({})).toBeUndefined();
|
||||
expect(extractJobFlowCode({ inputs: { code: " XZ2610474 " } })).toBe("XZ2610474");
|
||||
expect(extractJobFlowCode({ inputs: { flowCode: "BX20261101" } })).toBe("BX20261101");
|
||||
expect(extractJobFlowCode({ code: "JK20260901" })).toBe("JK20260901");
|
||||
});
|
||||
|
||||
test("空单号直接返回未找到", async () => {
|
||||
const dummyClient = {} as any;
|
||||
const res = await searchWorkflowJobByFlowCode(dummyClient, "corp1", "pipe1", " ");
|
||||
expect(res.found).toBe(false);
|
||||
});
|
||||
|
||||
test("流式翻页探查:命中目标单号并自动写入本地 SQLite 缓存,后续查询秒级命中缓存", async () => {
|
||||
const mockJobsDetail: Record<string, any> = {
|
||||
job_001: {
|
||||
id: "job_001",
|
||||
status: "COMPLETED",
|
||||
inputs: {
|
||||
code: "XZ2610474",
|
||||
flowId: "flow_xz_01",
|
||||
userInfo: { name: "欧阳亚玲" },
|
||||
},
|
||||
},
|
||||
job_002: {
|
||||
id: "job_002",
|
||||
status: "RUNNING",
|
||||
inputs: {
|
||||
code: "OTHER_999",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
let logCalls = 0;
|
||||
let jobCalls = 0;
|
||||
|
||||
const mockClient = {
|
||||
get: async (path: string, options?: any) => {
|
||||
if (path.includes("/log")) {
|
||||
logCalls++;
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
totalCount: 2,
|
||||
totalPages: 1,
|
||||
jobList: [
|
||||
{ jobId: "job_002", status: "RUNNING", executeTime: 1700000000000 },
|
||||
{ jobId: "job_001", status: "COMPLETED", executeTime: 1700000050000 },
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
if (path.includes("/jobs/")) {
|
||||
jobCalls++;
|
||||
const jobId = path.split("/jobs/")[1]?.split("?")[0];
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: mockJobsDetail[jobId] || { id: jobId },
|
||||
})
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify({ code: 404 }));
|
||||
},
|
||||
} as any;
|
||||
|
||||
// 第一次调用:缓存未命中,执行流式远端嗅探
|
||||
const res1 = await searchWorkflowJobByFlowCode(
|
||||
mockClient,
|
||||
"corp_winner",
|
||||
"pipe_win",
|
||||
"XZ2610474",
|
||||
{ maxScanPages: 5 }
|
||||
);
|
||||
|
||||
expect(res1.found).toBe(true);
|
||||
expect(res1.source).toBe("scan");
|
||||
expect(res1.jobId).toBe("job_001");
|
||||
expect(res1.job?.id).toBe("job_001");
|
||||
expect(logCalls).toBe(1);
|
||||
expect(jobCalls).toBe(2);
|
||||
|
||||
// 第二次调用:应当直接命中本地 SQLite 缓存,不调 /log 接口
|
||||
const prevLogCalls = logCalls;
|
||||
const prevJobCalls = jobCalls;
|
||||
|
||||
const res2 = await searchWorkflowJobByFlowCode(
|
||||
mockClient,
|
||||
"corp_winner",
|
||||
"pipe_win",
|
||||
"xz2610474" // 测试大小写模糊命中
|
||||
);
|
||||
|
||||
expect(res2.found).toBe(true);
|
||||
expect(res2.source).toBe("cache");
|
||||
expect(res2.jobId).toBe("job_001");
|
||||
// 不应再请求 /log
|
||||
expect(logCalls).toBe(prevLogCalls);
|
||||
// 仅通过 getJob 校验最新状态
|
||||
expect(jobCalls).toBe(prevJobCalls + 1);
|
||||
});
|
||||
|
||||
test("扫描达最大页数仍未找到时安全熔断并返回未找到", async () => {
|
||||
const mockClient = {
|
||||
get: async (path: string) => {
|
||||
if (path.includes("/log")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
totalCount: 10,
|
||||
totalPages: 10,
|
||||
jobList: [
|
||||
{ jobId: "job_x", status: "COMPLETED" },
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
if (path.includes("/jobs/")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: { id: "job_x", inputs: { code: "NO_MATCH" } },
|
||||
})
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify({ code: 404 }));
|
||||
},
|
||||
} as any;
|
||||
|
||||
const res = await searchWorkflowJobByFlowCode(
|
||||
mockClient,
|
||||
"corp1",
|
||||
"pipe1",
|
||||
"WANT_THIS",
|
||||
{ maxScanPages: 2 }
|
||||
);
|
||||
|
||||
expect(res.found).toBe(false);
|
||||
expect(res.scannedPages).toBe(2);
|
||||
expect(res.totalScanned).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { getCachedWorkflowJobByCode, upsertWorkflowJobIndex, type WorkflowJobCacheRecord } from "../../../../core/db/index.js";
|
||||
import { getJob } from "./queries.js";
|
||||
import { listWorkflowLogs } from "../transport/pipeline/api.js";
|
||||
import type { WorkflowJobDetail } from "../types.js";
|
||||
|
||||
export interface SearchJobByFlowOptions {
|
||||
maxScanPages?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface SearchJobByFlowResult {
|
||||
found: boolean;
|
||||
source?: "cache" | "scan";
|
||||
job?: WorkflowJobDetail;
|
||||
jobId?: string;
|
||||
flowCode?: string;
|
||||
scannedPages?: number;
|
||||
totalScanned?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取工作流 Job 内部携带的触发单号
|
||||
*/
|
||||
export function extractJobFlowCode(job: any): string | undefined {
|
||||
if (!job) return undefined;
|
||||
const inputs = job.inputs || {};
|
||||
if (inputs.code && typeof inputs.code === "string") return inputs.code.trim();
|
||||
if (inputs.flowCode && typeof inputs.flowCode === "string") return inputs.flowCode.trim();
|
||||
if (job.code && typeof job.code === "string") return job.code.trim();
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据单据编号 (flowCode) 高效查找对应的工作流运行实例 (Job)
|
||||
* 采用【本地 SQLite 缓存命中 ➔ 未命中流式翻页探查并写入缓存】的双层机制
|
||||
*/
|
||||
export async function searchWorkflowJobByFlowCode(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
pipelineId: string,
|
||||
flowCode: string,
|
||||
options: SearchJobByFlowOptions = {}
|
||||
): Promise<SearchJobByFlowResult> {
|
||||
const targetCode = flowCode.trim();
|
||||
if (!targetCode) {
|
||||
return { found: false, flowCode: targetCode };
|
||||
}
|
||||
|
||||
// 1. 本地 SQLite 缓存优先探查 (0ms 命中)
|
||||
try {
|
||||
const cached = getCachedWorkflowJobByCode(corpId, pipelineId, targetCode);
|
||||
if (cached?.jobId) {
|
||||
try {
|
||||
const fullJob = await getJob(client, cached.jobId);
|
||||
if (fullJob) {
|
||||
return {
|
||||
found: true,
|
||||
source: "cache",
|
||||
job: fullJob,
|
||||
jobId: cached.jobId,
|
||||
flowCode: targetCode,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// 若远程已清理或失效,平滑回退至实时扫描
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
// 2. 本地未命中,启动流式嗅探拉取(带本地边拉边存与早停熔断)
|
||||
const maxPages = options.maxScanPages ?? 10;
|
||||
const pageSize = options.pageSize ?? 20;
|
||||
let totalScanned = 0;
|
||||
|
||||
for (let page = 1; page <= maxPages; page++) {
|
||||
const logPage = await listWorkflowLogs(client, pipelineId, {
|
||||
page,
|
||||
pageSize,
|
||||
});
|
||||
|
||||
const jobs = logPage.jobList || [];
|
||||
if (!jobs.length) {
|
||||
break;
|
||||
}
|
||||
|
||||
// 并发提取当前页所有 Job 详情以解析其单号
|
||||
const batchDetails = await Promise.allSettled(
|
||||
jobs.map(async (j) => {
|
||||
try {
|
||||
const detail = await getJob(client, j.jobId);
|
||||
return { summary: j, detail };
|
||||
} catch {
|
||||
return { summary: j, detail: null };
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
const cacheBatch: WorkflowJobCacheRecord[] = [];
|
||||
let matchedJob: WorkflowJobDetail | null = null;
|
||||
|
||||
for (const item of batchDetails) {
|
||||
if (item.status !== "fulfilled") continue;
|
||||
const { summary, detail } = item.value;
|
||||
totalScanned++;
|
||||
|
||||
const parsedCode = detail ? extractJobFlowCode(detail) : undefined;
|
||||
const parsedFlowId = detail?.inputs?.flowId || undefined;
|
||||
const userName = detail?.inputs?.userInfo?.name || undefined;
|
||||
|
||||
let recordTime: number | undefined;
|
||||
if (summary.executeTime) {
|
||||
const t = typeof summary.executeTime === "number" ? summary.executeTime : new Date(summary.executeTime).getTime();
|
||||
recordTime = Number.isNaN(t) ? undefined : t;
|
||||
} else if (detail?.startTime) {
|
||||
const t = typeof detail.startTime === "number" ? detail.startTime : new Date(detail.startTime).getTime();
|
||||
recordTime = Number.isNaN(t) ? undefined : t;
|
||||
}
|
||||
|
||||
cacheBatch.push({
|
||||
corpId,
|
||||
pipelineId,
|
||||
jobId: summary.jobId,
|
||||
flowCode: parsedCode,
|
||||
flowId: parsedFlowId,
|
||||
executeTime: recordTime,
|
||||
status: summary.status || detail?.status,
|
||||
userName,
|
||||
});
|
||||
|
||||
if (
|
||||
parsedCode &&
|
||||
(parsedCode === targetCode || parsedCode.toUpperCase() === targetCode.toUpperCase())
|
||||
) {
|
||||
matchedJob = detail;
|
||||
}
|
||||
}
|
||||
|
||||
// 将拉取到的索引批量落盘至本地 SQLite 缓存
|
||||
try {
|
||||
upsertWorkflowJobIndex(cacheBatch);
|
||||
} catch {}
|
||||
|
||||
// 一旦命中立即短路熔断,返回目标单据的完整 Job 记录
|
||||
if (matchedJob) {
|
||||
return {
|
||||
found: true,
|
||||
source: "scan",
|
||||
job: matchedJob,
|
||||
jobId: matchedJob.id,
|
||||
flowCode: targetCode,
|
||||
scannedPages: page,
|
||||
totalScanned,
|
||||
};
|
||||
}
|
||||
|
||||
if (page >= (logPage.totalPages || 0)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
found: false,
|
||||
flowCode: targetCode,
|
||||
scannedPages: maxPages,
|
||||
totalScanned,
|
||||
};
|
||||
}
|
||||
@@ -18,6 +18,12 @@ export {
|
||||
getJobExecutionLevel,
|
||||
getExecutionLogs,
|
||||
} from "./execution/queries.js";
|
||||
export {
|
||||
searchWorkflowJobByFlowCode,
|
||||
extractJobFlowCode,
|
||||
type SearchJobByFlowOptions,
|
||||
type SearchJobByFlowResult,
|
||||
} from "./execution/search-by-flow.js";
|
||||
export type {
|
||||
WorkflowClients,
|
||||
ListAllWorkflowsOptions,
|
||||
@@ -82,3 +88,11 @@ export {
|
||||
|
||||
export * from "./index.js";
|
||||
export { webhookTriggerUrl } from "./triggers/index.js";
|
||||
export {
|
||||
getOutboundMessages,
|
||||
queryOutboundMessageLogs,
|
||||
type OutboundMessageConfig,
|
||||
type OutboundMessageLogItem,
|
||||
type OutboundLogQueryOptions,
|
||||
} from "./transport/outbound/index.js";
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { OutboundMessageConfig, OutboundMessageLogItem, OutboundLogQueryOptions } from "./types.js";
|
||||
|
||||
/**
|
||||
* 传输层:查询指定企业配置的出站消息列表
|
||||
* 对应合思底层接口:GET api/outbound/v1/message
|
||||
*/
|
||||
export async function getOutboundMessages(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<OutboundMessageConfig[]> {
|
||||
const response = await client.get("api/outbound/v1/message", {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return (json.items ?? []) as OutboundMessageConfig[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 传输层:分页查询出站消息投递执行日志
|
||||
* 对应合思底层接口:POST api/outbound/v1/message/messageLog
|
||||
*/
|
||||
export async function queryOutboundMessageLogs(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: OutboundLogQueryOptions = {}
|
||||
): Promise<{ count: number; items: OutboundMessageLogItem[] }> {
|
||||
const messageType = options.messageType ?? "flow";
|
||||
const start = options.start ?? 0;
|
||||
const count = options.count ?? 20;
|
||||
|
||||
const body: Record<string, unknown> = {
|
||||
limit: { start, count },
|
||||
orderBy: [{ value: "createTime", order: "DESC" }],
|
||||
select: "id,name,flowId(id, form(code)),nodeName,type,request,response,state,type,createTime,messageType",
|
||||
};
|
||||
|
||||
if (options.filterBy) {
|
||||
body.filterBy = options.filterBy;
|
||||
} else if (options.code) {
|
||||
body.filterBy = `(flowId.form.code==("${options.code.replace(/"/g, '\\"')}"))`;
|
||||
}
|
||||
|
||||
const response = await client.post("api/outbound/v1/message/messageLog", {
|
||||
searchParams: {
|
||||
messageType,
|
||||
corpId,
|
||||
},
|
||||
json: body,
|
||||
});
|
||||
|
||||
const json = (await response.json()) as { count?: number; items?: OutboundMessageLogItem[] };
|
||||
return {
|
||||
count: json.count ?? json.items?.length ?? 0,
|
||||
items: json.items ?? [],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./api.js";
|
||||
export * from "./types.js";
|
||||
@@ -0,0 +1,60 @@
|
||||
export interface OutboundMessageConfig {
|
||||
id: string;
|
||||
messageName?: string;
|
||||
messageType?: "flow" | "message" | "InternalMessage" | "dataLink" | string;
|
||||
enable?: boolean;
|
||||
callbackUrl?: string;
|
||||
signKey?: string;
|
||||
actionEvent?: string[] | null;
|
||||
formFields?: string[];
|
||||
conditions?: Array<{
|
||||
left?: string;
|
||||
operator?: string;
|
||||
right?: { type?: string; value?: unknown };
|
||||
}> | null;
|
||||
remark?: string | null;
|
||||
corporationId?: string;
|
||||
createTime?: number;
|
||||
updateTime?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface OutboundMessageLogItem {
|
||||
id: string;
|
||||
name: string;
|
||||
type: "INVOKING" | "CALLBACK" | string;
|
||||
state: "SUCCESS" | "FAILED" | string;
|
||||
flowId?: {
|
||||
id?: string;
|
||||
form?: {
|
||||
code?: string;
|
||||
};
|
||||
};
|
||||
nodeName?: string;
|
||||
createTime: number;
|
||||
messageType?: string;
|
||||
request?: {
|
||||
code?: string;
|
||||
flowId?: string;
|
||||
nodeId?: string;
|
||||
messageId?: string;
|
||||
corporationId?: string;
|
||||
action?: string;
|
||||
comment?: string;
|
||||
signKey?: string;
|
||||
formSpecification?: {
|
||||
specificationId?: string;
|
||||
specificationName?: string;
|
||||
};
|
||||
[key: string]: unknown;
|
||||
};
|
||||
response?: unknown;
|
||||
}
|
||||
|
||||
export interface OutboundLogQueryOptions {
|
||||
messageType?: string;
|
||||
code?: string;
|
||||
filterBy?: string;
|
||||
start?: number;
|
||||
count?: number;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderDocsHtml } from "./docs.js";
|
||||
import { handleHttpRequest } from "./routes.js";
|
||||
import { getScalarStandaloneJs } from "../packaging/embedded-docs.js";
|
||||
|
||||
describe("离线 API 文档", () => {
|
||||
test("HTML 不引用任何 CDN,指向本地路由", () => {
|
||||
const html = renderDocsHtml();
|
||||
expect(html).toContain('src="/static/scalar.js"');
|
||||
expect(html).toContain('data-url="/openapi.json"');
|
||||
expect(html).toContain('id="api-reference"');
|
||||
expect(html).not.toContain("cdn.jsdelivr.net");
|
||||
expect(html).not.toMatch(/src="https?:\/\//);
|
||||
expect(html).toContain("connect-src 'self'");
|
||||
expect(html).toContain("Content-Security-Policy");
|
||||
});
|
||||
|
||||
test("内嵌运行时是完整的 Scalar standalone", () => {
|
||||
const js = getScalarStandaloneJs();
|
||||
expect(js.length).toBeGreaterThan(1_000_000);
|
||||
expect(js).toContain("Scalar");
|
||||
expect(js).not.toContain("</script>");
|
||||
});
|
||||
|
||||
test("GET /static/scalar.js 返回 JS 且与内嵌产物一致", async () => {
|
||||
let status = 0;
|
||||
let headers: Record<string, string> = {};
|
||||
let body = "";
|
||||
const res = {
|
||||
setHeader: (key: string, value: unknown) => { headers[key] = String(value); },
|
||||
writeHead: (code: number, next: Record<string, string>) => {
|
||||
status = code;
|
||||
headers = { ...headers, ...next };
|
||||
},
|
||||
end: (value?: string) => { body = value ?? ""; },
|
||||
headersSent: false,
|
||||
};
|
||||
|
||||
await handleHttpRequest(
|
||||
{ method: "GET", url: "/static/scalar.js", headers: { host: "localhost" } } as never,
|
||||
res as never,
|
||||
{ app: "hose-use" }
|
||||
);
|
||||
|
||||
expect(status).toBe(200);
|
||||
expect(headers["Content-Type"]).toContain("application/javascript");
|
||||
expect(body).toBe(getScalarStandaloneJs());
|
||||
});
|
||||
});
|
||||
+3
-1
@@ -6,6 +6,8 @@ export function renderDocsHtml(): string {
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
|
||||
<!-- 运行时全部资源来自本地:即使 Scalar 内置的"示例规范"分支被触发也发不出外网请求 -->
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: blob:; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; worker-src 'self' blob:;" />
|
||||
<title>hose-use API Reference (v${VERSION})</title>
|
||||
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>" />
|
||||
<style>
|
||||
@@ -22,7 +24,7 @@ export function renderDocsHtml(): string {
|
||||
id="api-reference"
|
||||
data-url="/openapi.json"
|
||||
data-configuration='{"theme":"purple","layout":"modern","showSidebar":true}'
|
||||
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
|
||||
src="/static/scalar.js"
|
||||
></script>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
@@ -5,6 +5,7 @@ import { runAiProCli } from "../aipro-cli.js";
|
||||
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
|
||||
import { getOpenApiSchema } from "../packaging/embedded-openapi.js";
|
||||
import { getAiProWebUiHtml } from "../packaging/embedded-webui.js";
|
||||
import { getScalarStandaloneJs } from "../packaging/embedded-docs.js";
|
||||
import { tokenizeCommand, normalizeCliArgs } from "../server.js";
|
||||
import { VERSION } from "../version.js";
|
||||
import { renderDocsHtml } from "./docs.js";
|
||||
@@ -125,6 +126,12 @@ export async function handleHttpRequest(
|
||||
return;
|
||||
}
|
||||
|
||||
// /docs 的 Scalar 运行时由本地提供,彻底去掉 CDN 依赖
|
||||
if (method === "GET" && pathname === "/static/scalar.js") {
|
||||
sendJavascript(res, 200, getScalarStandaloneJs());
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && pathname === "/docs") {
|
||||
sendHtml(res, 200, renderDocsHtml());
|
||||
return;
|
||||
@@ -235,6 +242,16 @@ function sendHtml(res: ServerResponse, status: number, html: string): void {
|
||||
res.end(html);
|
||||
}
|
||||
|
||||
function sendJavascript(res: ServerResponse, status: number, source: string): void {
|
||||
if (res.headersSent) return;
|
||||
res.writeHead(status, {
|
||||
"Content-Type": "application/javascript; charset=utf-8",
|
||||
"Content-Length": Buffer.byteLength(source, "utf-8"),
|
||||
"Cache-Control": "public, max-age=86400",
|
||||
});
|
||||
res.end(source);
|
||||
}
|
||||
|
||||
function sendError(res: ServerResponse, status: number, message: string): void {
|
||||
sendJson(res, status, { error: true, message });
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
- `embedded-openapi.ts`:内嵌 `specs/openapi.json`(包装层)与 `specs/openapi.raw.json`(原生下游)两份 OpenAPI 规范,供 `hose-use openapi` 命令与 HTTP 文档页读取;产物由 `scripts/generate/bundle-openapi.ts` / `scripts/generate/generate-raw-openapi.ts` 生成。
|
||||
- `embedded-skill.ts`:内嵌 `skills/hose-use/` 全量 Skill 文件(`EMBEDDED_SKILL_FILES`),支持 `hose-use skill install --yes` 一键安装到全局目录,并在编译二进制运行时自动同步(`syncGlobalSkillIfPresent`)。
|
||||
- `embedded-webui.ts`:内嵌 AI PRO 本地 Web 控制台的单文件 HTML,供 `GET /report` 返回。
|
||||
- `embedded-docs.ts`:内嵌 `/docs` 交互式文档使用的 Scalar 浏览器运行时,供 `GET /static/scalar.js` 返回。
|
||||
- `runtime.ts`:二进制运行态自省——`isCompiledBinary` 判定编译态、`resolveAppRoot` 解析应用根目录、`resolveDefaultLauncher` 解析启动配置。
|
||||
|
||||
## Web 控制台内嵌产物
|
||||
@@ -22,6 +23,19 @@ bun run web:build # 生成 src/packaging/generated/webui.txt
|
||||
- 该生成物**必须随 git 提交**,与 `specs/*.json` 同理——编译二进制与 CI 不需要安装前端依赖。
|
||||
- `.webui-dist/` 是 Vite 中间产物,已被 `.gitignore` 忽略。
|
||||
|
||||
## 离线 API 文档运行时
|
||||
|
||||
`GET /docs` 的 Scalar 交互式文档不再引用 CDN。`scripts/build/build-docs.mjs` 固定 `@scalar/api-reference@1.25.101`,下载后按 SHA-256 校验,生成 `src/packaging/generated/scalar-standalone.js.txt`:
|
||||
|
||||
```bash
|
||||
bun run docs:fetch # 仅升级 Scalar 版本时需要联网
|
||||
```
|
||||
|
||||
- 生成物随 git 提交;daemon 的 `GET /static/scalar.js` 返回它,`/docs` 用相对路径加载,运行时完全离线。
|
||||
- 后缀用 `.txt` 与 webui 同理,避开 Bun 对 `.js` / `.html` 的非字符串类型推断。
|
||||
- `renderDocsHtml()` 里加了 CSP(`connect-src 'self'`):Scalar 内置一个"加载示例规范"分支会 `fetch` jsdelivr 的 galaxy.yaml,我们的页面用 `data-url="/openapi.json"` 不走该分支,CSP 再兜一层,保证任何情况下都发不出外网请求。
|
||||
- 生成物约 2.7 MiB,二进制体积因此增加约 2.9 MB。
|
||||
|
||||
## 依赖约束
|
||||
|
||||
- 仅可被入口层与 `cli/` 导入;不得反向依赖 `domains/`。
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* /docs 交互式 API 文档的 Scalar 浏览器运行时(固定版本,随源码提交)。
|
||||
*
|
||||
* 由 scripts/build/build-docs.mjs 从 jsdelivr 拉取并校验 SHA-256 后生成,
|
||||
* 运行时由本地 daemon 的 GET /static/scalar.js 提供,不访问任何 CDN。
|
||||
*/
|
||||
import scalarStandaloneJs from "./generated/scalar-standalone.js.txt" with { type: "text" };
|
||||
|
||||
export function getScalarStandaloneJs(): string {
|
||||
return scalarStandaloneJs;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,13 @@
|
||||
# AI PRO Web 控制台(前端子工程)
|
||||
|
||||
Vue 3.5 + Vite 6 + TypeScript + vue-router + Tailwind 3,配置对齐 `~/Code/影视飓风/twc-approval-go-bridge/web`。页面由 `hose-aipro` 常驻服务在 `http://127.0.0.1:8889/report` 提供,只监听回环地址。
|
||||
|
||||
```bash
|
||||
bun install --cwd web # 仅开发机需要
|
||||
bun run web:dev # Vite dev server :3000,/api /v1 代理到 8889
|
||||
bun run web:build # 生成 ../src/packaging/generated/webui.txt
|
||||
```
|
||||
|
||||
`scripts/build/build-webui.mjs` 会把 Vite 产物的 JS/CSS 内联成单个 HTML,再由 `src/packaging/embedded-webui.ts` 内嵌进二进制。**生成物随 git 提交**,所以 CI 与编译二进制不需要安装前端依赖;`.webui-dist/` 是忽略的中间产物。
|
||||
|
||||
前端统一经 `POST /api/cli` 调用现有 CLI 命令,不新增鉴权路径;`report --json` 是聚合数据源。设置 `HOSE_HTTP_TOKEN` 时浏览器请求需带 Bearer Token。
|
||||
@@ -0,0 +1,13 @@
|
||||
# 前端源码结构
|
||||
|
||||
| 路径 | 职责 |
|
||||
|---|---|
|
||||
| `main.ts` | 创建 Vue 实例、挂载路由与全局样式 |
|
||||
| `App.vue` | 侧边导航、网关健康状态 |
|
||||
| `router/index.ts` | hash 路由(适配 `/report` 挂载点) |
|
||||
| `api/client.ts` | 统一 CLI 网关取数与错误处理 |
|
||||
| `views/` | 总览、审批会话、规则与要点、审计流水、命令终端 |
|
||||
| `styles/main.css` | Tailwind 入口与共享组件类 |
|
||||
| `env.d.ts` | Vite 与 `.vue` 单文件组件类型声明 |
|
||||
|
||||
写操作(`bind` / `review` / `decide --apply`)在页面上保留二次确认,与 CLI 的 `--yes` 约定一致。
|
||||
Reference in new issue
Block a user