Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6cd2c68b0 | ||
|
|
38e1a45fc2 | ||
|
|
fa4113e828 | ||
|
|
793fcff5d5 | ||
|
|
11780f7fe4 | ||
|
|
4583dcc090 | ||
|
|
d069e7232e | ||
|
|
45011c8333 | ||
|
|
e2410e6923 | ||
|
|
fb8a48ea3c | ||
|
|
0a71674c64 | ||
|
|
3918e3de43 | ||
|
|
d4fb3828b7 | ||
|
|
2724ea5490 | ||
|
|
e542c0a5f2 | ||
|
|
8329b294e5 | ||
|
|
e72803ba3c | ||
|
|
e4b1eea5a9 | ||
|
|
482ebf57b5 |
No files matched your search
@@ -0,0 +1,32 @@
|
||||
---
|
||||
description: "本设备创建分支的命名规范(设备前缀)与 git hook 机械强制"
|
||||
trigger: "always"
|
||||
---
|
||||
|
||||
# 分支命名规范 (设备前缀 + 机械强制)
|
||||
|
||||
为了让"哪台设备/哪个 Agent 开的分支"一眼可辨,本仓库的分支命名按创建设备加前缀。规则文档随仓库走,前缀的值留在各设备本地。
|
||||
|
||||
## 1. 命名规则
|
||||
|
||||
- **格式**:`<设备键>/<小写连字符主题>`。本机(这台 Mac)的设备键是 `mac15`,例如:`mac15/improve-corp-search`。
|
||||
- **设备键声明**:每个克隆只声明一次,写入本地 git 配置(存于 `.git/config`,不提交、随设备走):
|
||||
```bash
|
||||
git config seal.branchPrefix mac15 # 这台 Mac;其他设备换自己的键,不设置则本规则休眠
|
||||
```
|
||||
- **Agent 行为要求**:任何 Agent(Codex/ZCode/Claude 等)创建分支前,先执行 `git config seal.branchPrefix`;有值则分支名必须以 `<值>/` 开头,没有值时用普通主题名即可。
|
||||
|
||||
## 2. 保留名(不受设备前缀约束)
|
||||
|
||||
- `main`:主分支。
|
||||
- `codex/release-vX.Y.Z`:发版自动化专用(`bun run release` 创建),沿用既有约定。
|
||||
|
||||
## 3. 机械强制(不依赖 Agent 自觉)
|
||||
|
||||
- 钩子:`.githooks/pre-commit` 与 `.githooks/pre-push` 通过 `.githooks/branch-guard.sh` 校验分支名,违规即拒绝并给出改名命令。`package.json` 的 `prepare` 脚本在 `bun install` 时自动设置 `core.hooksPath=.githooks`,新克隆无需手动接线。
|
||||
- **存量分支豁免**:已存在于 origin 的旧分支(如云端 Agent 创建的 `codex/*`)不拦,避免影响在途 PR。
|
||||
- **逃生门**:`git commit --no-verify` / `git push --no-verify` 可一次性绕过,仅用于特殊情况,不要养成习惯。
|
||||
|
||||
## 4. 相关规则
|
||||
|
||||
- 分支/工作树清理见 `.agents/rules/workspace-hygiene.md`;PR 工作流见 `.agents/rules/issue-pr-workflow.md`。
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/bin/bash
|
||||
# Shared branch-naming guard: .agents/rules/branch-naming.md
|
||||
# Devices opt in per clone: git config seal.branchPrefix <device-key> (e.g. mac15)
|
||||
# Sourced by pre-commit and pre-push.
|
||||
|
||||
# guard_branch_name <branch> — returns 1 with guidance when the name breaks the rule.
|
||||
guard_branch_name() {
|
||||
local branch="$1"
|
||||
[ -n "$branch" ] || return 0
|
||||
|
||||
# Reserved names: mainline branches and the release automation.
|
||||
case "$branch" in
|
||||
main|master|develop) return 0 ;;
|
||||
codex/release-*) return 0 ;;
|
||||
esac
|
||||
|
||||
# Enforcement is opt-in per device; without a configured prefix this guard is dormant.
|
||||
local prefix
|
||||
prefix="$(git config seal.branchPrefix 2>/dev/null || true)"
|
||||
[ -n "$prefix" ] || return 0
|
||||
|
||||
case "$branch" in
|
||||
"$prefix"/*) return 0 ;;
|
||||
esac
|
||||
|
||||
# Branches that already exist on origin (created elsewhere, e.g. cloud agents) stay usable.
|
||||
if git rev-parse -q --verify "refs/remotes/origin/$branch" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "" >&2
|
||||
echo "🛑 [branch-guard] Branch '$branch' violates the device branch-prefix rule (.agents/rules/branch-naming.md)." >&2
|
||||
echo " Branches created on this device must start with '${prefix}/'." >&2
|
||||
echo " 👉 Rename and retry: git branch -m '${prefix}/${branch##*/}'" >&2
|
||||
echo " (One-off bypass: git commit --no-verify / git push --no-verify)" >&2
|
||||
echo "" >&2
|
||||
return 1
|
||||
}
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
# Git pre-commit hook: enforce the device branch-prefix rule
|
||||
# (.agents/rules/branch-naming.md) via .githooks/branch-guard.sh
|
||||
source "$(dirname "$0")/branch-guard.sh"
|
||||
|
||||
guard_branch_name "$(git branch --show-current)"
|
||||
@@ -1,12 +1,24 @@
|
||||
#!/bin/bash
|
||||
# Git pre-push hook: Prevent accidental direct push to origin/main or GitHub/main
|
||||
# Enforces the PR workflow required by AGENTS.md & .agents/rules/issue-pr-workflow.md
|
||||
# Also enforces the device branch-prefix rule via .githooks/branch-guard.sh
|
||||
|
||||
source "$(dirname "$0")/branch-guard.sh"
|
||||
|
||||
remote="$1"
|
||||
url="$2"
|
||||
zero="0000000000000000000000000000000000000000"
|
||||
|
||||
while read local_ref local_oid remote_ref remote_oid; do
|
||||
# Device branch-prefix rule (.agents/rules/branch-naming.md); deletions are exempt
|
||||
case "$local_ref" in
|
||||
refs/heads/*)
|
||||
if [ "$local_oid" != "$zero" ]; then
|
||||
guard_branch_name "${local_ref#refs/heads/}" || exit 1
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
# If pushing the main branch (or pushing to remote main)
|
||||
if [ "$remote_ref" = "refs/heads/main" ] || [ "$local_ref" = "refs/heads/main" ]; then
|
||||
# When pushing to origin or GitHub (main repository)
|
||||
|
||||
@@ -72,6 +72,14 @@ jobs:
|
||||
run: bun test
|
||||
|
||||
- name: Compile multi-target binaries
|
||||
# Langfuse read-only credentials are injected at compile time from
|
||||
# repository secrets and inlined into the binaries; they never appear in
|
||||
# the repository or in the workflow logs.
|
||||
env:
|
||||
SEAL_BUILD_LANGFUSE_BASE_URL: ${{ secrets.LANGFUSE_BASE_URL }}
|
||||
SEAL_BUILD_LANGFUSE_PUBLIC_KEY: ${{ secrets.LANGFUSE_PUBLIC_KEY }}
|
||||
SEAL_BUILD_LANGFUSE_SECRET_KEY: ${{ secrets.LANGFUSE_SECRET_KEY }}
|
||||
SEAL_BUILD_LANGFUSE_PROJECT_ID: ${{ secrets.LANGFUSE_PROJECT_ID }}
|
||||
run: |
|
||||
mkdir -p dist/bin
|
||||
node scripts/build-binary.mjs --all
|
||||
|
||||
@@ -12,5 +12,11 @@ dist/bin/
|
||||
# Local runtime state (rule snapshots, bridge, reports) — never committed
|
||||
.local/
|
||||
|
||||
# Developer-only build-time credentials for compile-time injection — never committed
|
||||
.env.langfuse
|
||||
|
||||
# ZCode session plan artifacts (workspace-local, never committed)
|
||||
.zcode/plans/
|
||||
|
||||
# One-off export harnesses dropped in scripts/ while exporting
|
||||
scripts/export-*.ts
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.1",
|
||||
"version": "0.11.4",
|
||||
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Project Structure & Module Organization
|
||||
|
||||
This is a Bun + TypeScript toolkit for the `seal-use` CLI and a local stdio MCP server (`seal-use mcp`). Entry points are `src/cli.ts`, `src/server.ts`, and `src/probe.ts`. Shared config, auth, token, and HTTP code is under `src/core/`. Seal-specific API and logic is under `src/domains/seal/`; the capability registry under `src/domains/seal/capabilities/` holds the shared handlers dispatched by the CLI (`runCapability`) and allow-listed by the MCP gateways. Capability IDs are camelCase internal registry identifiers (for example `sealApprovalContextGet`) — the MCP surface only ever exposes the `seal_use` / `seal_use_write` gateway pair, never these names (see README "One registry, two doors").
|
||||
This is a Bun + TypeScript toolkit for the `seal-use` CLI and a local stdio MCP server (`seal-use mcp`). Entry points are `src/cli.ts`, `src/server.ts`, and `src/probe.ts`. Shared config, auth, token, and HTTP code is under `src/core/`. Seal-specific API and logic is under `src/domains/seal/`; the capability registry under `src/domains/seal/capabilities/` holds the shared handlers dispatched by the CLI (`runCapability`) and allow-listed by the MCP gateways. Capability IDs are camelCase internal registry identifiers (for example `sealApprovalContextGet`) — the MCP surface only ever exposes the `seal_use` / `seal_use_write` gateway pair, never these names (see README "One registry, two doors"). The built-in read-only Langfuse trace domain lives under `src/domains/langfuse/` with its own registry (`langfuseCapabilities`, dispatched by `runLangfuseCapability`); its client only issues `GET`, and its credentials are injected at compile time (`SEAL_BUILD_LANGFUSE_*`), never stored in the tree or in user config.
|
||||
|
||||
The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares a skills-only plugin manifest and the agent skill lives under `skills/seal-use/`. The plugin ships no MCP surface; the local MCP runs from the CLI (`seal-use mcp`, or the `mcp-config` snippet for Cursor/Claude Desktop). The in-repo `.agents/skills/seal-use` symlink has been dropped; workspace and Codex skill loading use the global `~/.agents/skills/seal-use` copy installed by `seal-use skill install`.
|
||||
|
||||
@@ -51,7 +51,8 @@ Use `bun:test` with `describe`, `test`, and `expect`. Place tests next to covere
|
||||
|
||||
## Commit & Pull Request Guidelines
|
||||
|
||||
Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`, such as `Add compact approval rule listing`. Keep subjects under roughly 72 characters. Specific workflows and domain guidelines are maintained in `.agents/rules/`:
|
||||
Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`, such as `Add compact approval rule listing`. Keep subjects under roughly 72 characters. Branches created on a workstation must carry that device's prefix from `git config seal.branchPrefix` (e.g. `mac15/improve-corp-search` on this Mac), enforced by the `.githooks` pre-commit/pre-push guards. Specific workflows and domain guidelines are maintained in `.agents/rules/`:
|
||||
- Branch naming (device-prefix rule & mechanical enforcement): `.agents/rules/branch-naming.md`
|
||||
- Issue triage & PR workflow (No premature release): `.agents/rules/issue-pr-workflow.md`
|
||||
- CLI stream & exit code protocol: `.agents/rules/cli-protocol.md`
|
||||
- Testing conventions & isolation: `.agents/rules/testing.md`
|
||||
@@ -108,6 +109,8 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
|
||||
|
||||
Never commit real enterprise credentials, Seal tokens, service logs, or local generated state. Enterprise configs live only in `~/.config/seal-use/enterprises` (with legacy fallback to `~/.config/seal-home/enterprises`); the project tree carries none. For auth or tenant changes, verify with `bun run probe` or `seal-use auth diagnose`.
|
||||
|
||||
Documented exception: the Langfuse read-only key pair for `seal-use langfuse` is injected at **compile time** (`SEAL_BUILD_LANGFUSE_*` — repository secrets in `release.yml` for releases; for developer builds, shell env vars or the repo-local gitignored `.env.langfuse`, never under `~/.config`, which is user config space) and is never written to the tree or to user config; `src/domains/langfuse/client.ts` is GET-only, which is what makes the embedded key safe to ship. See `SECURITY.md`.
|
||||
|
||||
Credential files are written `0600`; a config placed by hand keeps the `0o644` default, so run `seal-use doctor` and act on its `credential_permissions` check before sharing a machine or a backup. See `SECURITY.md` for the trust model (self-update, custom linters).
|
||||
|
||||
## Agent-Specific Instructions
|
||||
|
||||
@@ -7,6 +7,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.11.4] - 2026-10-10
|
||||
|
||||
### Added
|
||||
- Merge pull request #211 from yunyingk/mac15/diagnose-simulation-dx-improvements
|
||||
- Refine simulation DX, diagnose fields extraction, and rule mapping
|
||||
|
||||
|
||||
## [0.11.3] - 2026-10-10
|
||||
|
||||
### Added
|
||||
- Merge pull request #209 from yunyingk/mac15/langfuse-readonly-domain
|
||||
- Add built-in read-only Langfuse trace domain
|
||||
- Merge pull request #208 from yunyingk/mac15/corp-search-optimization
|
||||
- Break search relevance ties by recent usage
|
||||
- Split corp-search module and tune match scoring
|
||||
- Merge pull request #207 from yunyingk/mac15/rename-corp-search-dir
|
||||
- Rename core search module to corp-search
|
||||
|
||||
|
||||
## [0.11.2] - 2026-10-02
|
||||
|
||||
### Added
|
||||
- Merge pull request #205 from yunyingk/mac15/improve-corp-search
|
||||
- Add device branch-prefix rule with hook enforcement
|
||||
- Refactor fuzzy search engine into strategy functions
|
||||
- Improve Chinese enterprise search segmentation and ranking
|
||||
|
||||
|
||||
## [0.11.1] - 2026-09-30
|
||||
|
||||
### Added
|
||||
|
||||
+12
@@ -26,11 +26,23 @@ The tool writes these `0600`; a config placed by hand can keep the `0o644` defau
|
||||
`seal-use doctor` reports any credential file whose mode is wider than `0600`. Real enterprise
|
||||
configs are gitignored — never commit them.
|
||||
|
||||
The one credential that ships **inside the binary** is the Langfuse read-only key pair used by
|
||||
`seal-use langfuse`. It is injected at compile time (`SEAL_BUILD_LANGFUSE_*`: repository secrets in
|
||||
`release.yml` for releases; for developer builds, shell env vars or the repo-local gitignored
|
||||
`.env.langfuse` — deliberately outside `~/.config`, which is user config space) and never appears
|
||||
in the repository tree or in user config.
|
||||
|
||||
## Trust model and documented limitations
|
||||
|
||||
These are deliberate trade-offs, not unknown bugs. Report them anyway if you can make one worse
|
||||
than described here.
|
||||
|
||||
- **The embedded Langfuse key pair is not scope-limited upstream.** Langfuse project keys carry
|
||||
full API access, so "read-only" is guaranteed only by this client (it exposes `GET` only — see
|
||||
`src/domains/langfuse/client.ts`), and anyone with the binary can extract the key pair. The
|
||||
repository and its Releases are private, which is what bounds distribution. Treat Langfuse traces
|
||||
and `.cache/langfuse/` as sensitive (they can contain enterprise approval data); rotate the key
|
||||
pair in Langfuse and update the four `LANGFUSE_*` repository secrets to re-key.
|
||||
- **Self-update and the install script do not verify signatures.** `seal-use update` downloads a
|
||||
release binary and replaces the running executable; `scripts/install.sh` compares
|
||||
`checksums.txt` but only warns on a mismatch. Prefer the direct GitHub source
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.1",
|
||||
"version": "0.11.4",
|
||||
"private": true,
|
||||
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdirSync, readFileSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -6,6 +6,49 @@ import { fileURLToPath } from "node:url";
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const bun = process.env.BUN_BIN || "bun";
|
||||
|
||||
// Langfuse read-only credentials are injected at COMPILE time (never committed):
|
||||
// `bun build --env=SEAL_BUILD_*` inlines them into release binaries, so end
|
||||
// users need zero configuration. Resolution order per key: an explicit
|
||||
// `SEAL_BUILD_LANGFUSE_*` build var (CI secrets) > plain `LANGFUSE_*` shell var
|
||||
// > the repo-local gitignored `.env.langfuse` (developer workspace, override
|
||||
// path with SEAL_BUILD_LANGFUSE_ENV_FILE). Build sources deliberately do NOT
|
||||
// live under `~/.config` — that is user config space, not build state. Values
|
||||
// must never be printed or written into the repository.
|
||||
const LANGFUSE_KEYS = ["BASE_URL", "PUBLIC_KEY", "SECRET_KEY", "PROJECT_ID"];
|
||||
|
||||
function readLocalLangfuseEnvFile() {
|
||||
const path = process.env.SEAL_BUILD_LANGFUSE_ENV_FILE || resolve(root, ".env.langfuse");
|
||||
if (!existsSync(path)) return {};
|
||||
const values = {};
|
||||
for (const line of readFileSync(path, "utf8").split("\n")) {
|
||||
const match = line.match(/^\s*(LANGFUSE_[A-Z_]+)\s*=\s*(.*?)\s*$/);
|
||||
if (!match) continue;
|
||||
let value = match[2];
|
||||
if (value.startsWith('"') && value.endsWith('"')) {
|
||||
try {
|
||||
value = JSON.parse(value);
|
||||
} catch {
|
||||
// Keep the raw quoted value; the config writer quotes uniformly.
|
||||
}
|
||||
}
|
||||
values[match[1]] = value;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function resolveLangfuseBuildEnv() {
|
||||
const local = readLocalLangfuseEnvFile();
|
||||
const resolved = {};
|
||||
for (const key of LANGFUSE_KEYS) {
|
||||
const injected = process.env[`SEAL_BUILD_LANGFUSE_${key}`]?.trim();
|
||||
const shell = process.env[`LANGFUSE_${key}`]?.trim();
|
||||
const fromFile = local[`LANGFUSE_${key}`]?.trim();
|
||||
const value = injected || shell || fromFile;
|
||||
if (value) resolved[`SEAL_BUILD_LANGFUSE_${key}`] = value;
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
const TARGET_MAP = {
|
||||
"darwin-arm64": { bunTarget: "bun-darwin-arm64", outfile: "dist/bin/seal-use-darwin-arm64" },
|
||||
"darwin-x64": { bunTarget: "bun-darwin-x64", outfile: "dist/bin/seal-use-darwin-x64" },
|
||||
@@ -95,16 +138,22 @@ async function main() {
|
||||
const buildInfo = getBuildInfo(isRelease);
|
||||
console.log(`[build:binary] version: ${buildInfo.version} (${buildInfo.channel}, isRelease: ${buildInfo.isRelease})`);
|
||||
|
||||
const langfuseEnv = resolveLangfuseBuildEnv();
|
||||
console.log(
|
||||
`[build:binary] langfuse credentials: ${Object.keys(langfuseEnv).length}/${LANGFUSE_KEYS.length} injected (values never logged)`
|
||||
);
|
||||
|
||||
const buildEnv = {
|
||||
...process.env,
|
||||
SEAL_BUILD_VERSION: buildInfo.version,
|
||||
SEAL_BUILD_CHANNEL: buildInfo.channel,
|
||||
SEAL_BUILD_IS_RELEASE: String(buildInfo.isRelease),
|
||||
...langfuseEnv,
|
||||
...(buildInfo.git ? {
|
||||
SEAL_BUILD_GIT_BASE: buildInfo.git.baseVersion,
|
||||
SEAL_BUILD_GIT_COMMITS_AHEAD: String(buildInfo.git.commitsAhead),
|
||||
SEAL_BUILD_GIT_COMMIT: buildInfo.git.commit,
|
||||
SEAL_BUILD_GIT_DIRTY: String(buildInfo.git.dirty),
|
||||
SEAL_BUILD_GIT_DIRTY: buildInfo.git.dirty,
|
||||
SEAL_BUILD_GIT_DESCRIBE: buildInfo.git.describe
|
||||
} : {})
|
||||
};
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: seal-use
|
||||
description: "v0.11.1: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
description: "v0.11.4: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
metadata:
|
||||
version: 0.11.1
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.1)
|
||||
version: 0.11.4
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.4)
|
||||
---
|
||||
|
||||
# Seal Use
|
||||
@@ -96,6 +96,7 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
|
||||
| 规则数量、摘要列表、历史规则、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
|
||||
| 规则质量评分、lint、发布前质检 | `references/rule-lint.md` | 不要把 lint 问题直接当成客诉根因 |
|
||||
| 客诉、截图/通知、预期业务行为,并要求诊断或修改规则 | `references/customer-feedback-rule-remediation.md` | 只有该流程明确要求附件追踪或测试发布时,才追加对应 reference |
|
||||
| Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` |
|
||||
| 附件、发票、收据、OCR 或界面高亮结论争议 | `references/approval-attachment-trace.md` | 先完成追踪和归因后,才读 `approval-bad-cases.md` 做案例对照 |
|
||||
| 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 |
|
||||
| 月度审核准确率报告、月报生成、accuracy report | 本文「月度审核准确率报告」一节 | 需要结构校验或 PDF 渲染时,再读 `report-templates/README.md` |
|
||||
@@ -112,6 +113,19 @@ seal-use approval-runs diagnose --sn <单号> --corp <corpId>
|
||||
|
||||
一次返回单据摘要、AI 判定结果、引用规则、判定当时的规则版本快照(含被引规则的快照内容)与 Langfuse trace 指针;需要完整 result 原文加 `--full`,需要按 recordId 定位则直接传 `<recordId>`。只有诊断结果不够、需要更细颗粒时,再拆用 `pick` / `get --summary` / `cited-rules` / `rules version`。
|
||||
|
||||
## Langfuse trace 内置只读检索
|
||||
|
||||
Langfuse 后台信息内建在 CLI 里(`seal-use langfuse`,凭据编译期注入、零配置、只读、无需 `--corp` 和 `langfuse-home`):
|
||||
|
||||
```bash
|
||||
seal-use langfuse cache-refresh <traceId> # 先缓存(一次拉全)
|
||||
seal-use langfuse outline <traceId> --include-io-preview # 大纲:观测树/体量/用量/成本
|
||||
seal-use langfuse search <traceId> --query "关键词1,关键词2" # 单 trace 关键词检索(qrep)
|
||||
seal-use langfuse observation <traceId> <observationId> # 最后才取焦点 IO
|
||||
```
|
||||
|
||||
`approval-runs diagnose` / `bridge` 返回的 `bridge[].next` 就是下一步可执行命令。`seal-use langfuse check` 可自检内置密钥是否失效(失效 → exit 11/1 的结构化报错,绝不崩溃;已缓存 trace 仍可离线读取)。session、attachment-flow、rule-flow、缓存语义与失效兜底见 `references/langfuse-trace.md`。
|
||||
|
||||
## 月度审核准确率报告
|
||||
|
||||
月度报告一次调用生成,不要手搓 Markdown 表格或串行取数:
|
||||
|
||||
@@ -38,15 +38,15 @@ seal-use approval-runs get <recordId> --corp <corpId> > /tmp/seal-run.json
|
||||
seal-use approval-runs bridge --corp <corpId> --sourceDocumentSN <sourceDocumentSN>
|
||||
```
|
||||
|
||||
Refresh and inspect the Langfuse trace.
|
||||
Refresh and inspect the Langfuse trace (built-in read-only domain, no `langfuse-home` needed):
|
||||
|
||||
```bash
|
||||
langfuse-home call langfuse_trace_cache_refresh --json '{"traceId":"<traceId>"}'
|
||||
langfuse-home call langfuse_trace_url_get --json '{"traceId":"<traceId>"}'
|
||||
langfuse-home call langfuse_trace_outline_get --json '{"traceId":"<traceId>","includeInput":true,"includeOutput":true,"maxPreviewChars":800}'
|
||||
seal-use langfuse cache-refresh <traceId>
|
||||
seal-use langfuse url <traceId>
|
||||
seal-use langfuse outline <traceId> --include-io-preview --max-preview-chars 800
|
||||
```
|
||||
|
||||
If `langfuse_trace_qrep_search` does not find Chinese terms reliably, grep the cached JSON directly.
|
||||
If `seal-use langfuse search` does not find Chinese terms reliably, grep the cached JSON directly.
|
||||
|
||||
```bash
|
||||
rg -n "发票未上传至发票栏位|附件中存在定额发票|检查该附件(定额发票)|<file-name-or-fileId>" \
|
||||
@@ -56,7 +56,7 @@ rg -n "发票未上传至发票栏位|附件中存在定额发票|检查该附
|
||||
Read focused IO for the relevant observations.
|
||||
|
||||
```bash
|
||||
langfuse-home call langfuse_observation_io_get --json '{"traceId":"<traceId>","observationId":"<observationId>","maxChars":30000}'
|
||||
seal-use langfuse observation <traceId> <observationId> --max-chars 30000
|
||||
```
|
||||
|
||||
## Separate Object IDs Before Judging
|
||||
|
||||
@@ -65,6 +65,16 @@ seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]
|
||||
seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]
|
||||
seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]
|
||||
seal-use documents delete <documentId> --yes [--corp <corpId>]
|
||||
seal-use langfuse check
|
||||
seal-use langfuse cache-refresh <traceId>
|
||||
seal-use langfuse outline <traceId> [--include-io-preview] [--max-preview-chars <n>] [--full] [--refresh-if-missing]
|
||||
seal-use langfuse search <traceId> --query <term1,term2> [--fields <fields>] [--max-results <n>] [--context-chars <n>] [--observation-types <types>] [--metadata <json>] [--session-id <id>] [--refresh-if-missing]
|
||||
seal-use langfuse observation <traceId> <observationId> [--fields <fields>] [--max-chars <n>] [--json-path <path>] [--full] [--refresh-if-missing]
|
||||
seal-use langfuse session <sessionId> [--trace-limit <n>]
|
||||
seal-use langfuse observations <traceId> [--name-contains <text>] [--type <type>] [--metadata-key <key>] [--has-input] [--has-output] [--max-results <n>] [--refresh-if-missing]
|
||||
seal-use langfuse url <traceId>
|
||||
seal-use langfuse attachment-flow <traceId> [--file-id <id>] [--file-name <name>] [--content-hints <hints>] [--context-chars <n>] [--refresh-if-missing]
|
||||
seal-use langfuse rule-flow <traceId> --rule <text> [--rule-hints <hints>] [--context-chars <n>] [--refresh-if-missing]
|
||||
seal-use update [--check] [--force] [--version <v>]
|
||||
seal-use update check
|
||||
seal-use update changelog [--limit <n>]
|
||||
@@ -358,6 +368,16 @@ Approval runs, simulations, and Langfuse bridge:
|
||||
- `seal-use simulation templates --corp <corpId>`
|
||||
- `seal-use simulation integrations --corp <corpId>`
|
||||
|
||||
Langfuse trace inspection (built-in, read-only, credentials injected at compile time; no `--corp` and no user config required; all verbs are `seal_use` MCP-read-only):
|
||||
|
||||
- `seal-use langfuse check` verifies connectivity of the embedded read-only credentials (missing credentials → exit 11).
|
||||
- `seal-use langfuse cache-refresh <traceId>` fetches one full trace into `<cwd>/.cache/langfuse/traces/default/<traceId>.json` (shared format with langfuse-home); other cache-first verbs answer from it and point here (exit 13) when it is missing, unless `--refresh-if-missing`.
|
||||
- `seal-use langfuse outline <traceId> [--include-io-preview] [--max-preview-chars <n>] [--full]` returns the compact observation tree with sizes, usage, cost, and `warnings[]` for >20k-char fields.
|
||||
- `seal-use langfuse search <traceId> --query <term1,term2>` is the ranked single-trace keyword search (qrep): hierarchy paths, `observationId`, before/match/after context; `--metadata <json>` and `--observation-types` narrow it.
|
||||
- `seal-use langfuse observation <traceId> <observationId> [--max-chars <n>] [--json-path <path>]` reads focused IO last (middle-truncated to 8000 chars by default, 30000 max, 500000 with `--full`).
|
||||
- `seal-use langfuse session <sessionId>`, `seal-use langfuse observations <traceId>`, and `seal-use langfuse url <traceId>` give the session outline, filtered observation summaries, and a UI deep link.
|
||||
- `seal-use langfuse attachment-flow <traceId> --file-id/--file-name/--content-hints` and `seal-use langfuse rule-flow <traceId> --rule <text>` extract deterministic text evidence per pipeline stage (they do not prove model reasoning).
|
||||
|
||||
## Common Examples
|
||||
|
||||
Add and verify a Hose enterprise:
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
# Langfuse Trace 内置只读检索
|
||||
|
||||
`seal-use langfuse` 是内建的只读 Langfuse trace 检索域:凭据在编译期注入,最终用户**零配置**,无需 `langfuse-home` 或任何本地 `.env`。命令不需要 `--corp`,MCP `seal_use` 网关全部可达。
|
||||
|
||||
只读边界:client 只发 `GET`,本地只写 `.cache/langfuse/` 缓存。凭据缺失(源码直跑未注入)→ exit 11;Langfuse 401/403 → exit 11;其它上游失败 → exit 1;参数缺失/越界 → exit 13。
|
||||
|
||||
## IO-last 工作流
|
||||
|
||||
顺序不要颠倒:**cache → outline → search/observations → observation IO**。outline 和 search 只读本地缓存,避免 dump 原始 payload;只有最后一步才取焦点 IO。
|
||||
|
||||
### 1. 缓存单条 trace(必做第一步)
|
||||
|
||||
```bash
|
||||
seal-use langfuse cache-refresh <traceId>
|
||||
```
|
||||
|
||||
缓存写入 `<cwd>/.cache/langfuse/traces/default/<traceId>.json`(与 langfuse-home 同格式,可共享)。后续命令缺缓存时报 exit 13 并提示补缓存,或加 `--refresh-if-missing` 现场拉取。
|
||||
|
||||
### 2. 读大纲(不打印原始 IO)
|
||||
|
||||
```bash
|
||||
seal-use langfuse outline <traceId> # 观测树 + 体量 + 用量 + 成本
|
||||
seal-use langfuse outline <traceId> --include-io-preview --max-preview-chars 800
|
||||
```
|
||||
|
||||
`warnings[]` 标出超过 20k 字符的字段;`--full` 才请求完整 IO(可能触发 exit 12,配 `--output-file`)。
|
||||
|
||||
### 3. 关键词检索(qrep,确定性排序)
|
||||
|
||||
```bash
|
||||
seal-use langfuse search <traceId> --query "发票,驳回" --max-results 10 --context-chars 160
|
||||
seal-use langfuse search <traceId> --query "关键词" --fields input,output --observation-types GENERATION
|
||||
seal-use langfuse search <traceId> --query "关键词" --metadata '{"stage":"review"}'
|
||||
```
|
||||
|
||||
返回带 `path` 层级、`observationId`、`context{before,match,after}` 的排序片段。output 命中权重最高,`approval_review`/`审核` 观测加成。中文分词不理想时直接 grep 缓存:`rg -n "<原文>" .cache/langfuse/traces/default/<traceId>.json`。
|
||||
|
||||
### 4. 焦点 observation IO
|
||||
|
||||
只在 outline/search 给出 `observationId` 之后使用:
|
||||
|
||||
```bash
|
||||
seal-use langfuse observation <traceId> <observationId> --max-chars 8000
|
||||
seal-use langfuse observation <traceId> <observationId> --json-path "items[0].name"
|
||||
```
|
||||
|
||||
默认 input/output 各截断到 8000 字符(middle-truncation 保头尾);`--max-chars` 上限 30000,`--full` 上限 500000。
|
||||
|
||||
### 5. 辅助视图
|
||||
|
||||
```bash
|
||||
seal-use langfuse session <sessionId> --trace-limit 50 # session 摘要(不缓存整 session)
|
||||
seal-use langfuse observations <traceId> --name-contains review # 只列观测摘要,不载 IO
|
||||
seal-use langfuse url <traceId> # 后台直达链接
|
||||
seal-use langfuse check # 连通性自检
|
||||
```
|
||||
|
||||
### 6. 领域专用追踪
|
||||
|
||||
```bash
|
||||
seal-use langfuse attachment-flow <traceId> --file-id <fileId> --file-name <name>
|
||||
seal-use langfuse rule-flow <traceId> --rule "禁止差旅超标" --rule-hints "差旅,超标"
|
||||
```
|
||||
|
||||
- `attachment-flow`:按 attachment parsing / 图片理解 / pre_analysis / document_parsing / approval_review 阶段返回文本证据与来源分类(`filename-only`/`parsed-text`/`image-ocr`/`model-inferred`/`absent`…)。是确定性文本抽取,不证明模型语义理解。
|
||||
- `rule-flow`:按 rule matching / document parsing / final review 阶段返回规则文本证据、`extractedFields` 与 `relatedObservationIds`。同样不推断隐藏推理。
|
||||
|
||||
## 与审批诊断的衔接
|
||||
|
||||
`seal-use approval-runs diagnose` 和 `... bridge` 的 `bridge[].next` 直接给出可执行的下一步:
|
||||
|
||||
```bash
|
||||
seal-use approval-runs diagnose --sn <单号> --corp <corpId> # bridge[].next → langfuse outline ...
|
||||
seal-use langfuse outline <traceId> --include-io-preview
|
||||
```
|
||||
|
||||
trace 缺失时 `resolution: "session-fallback"`,`next` 指向 `seal-use langfuse session hosecloud-<SN>`。
|
||||
|
||||
## 内置密钥失效:兜底与不崩溃契约
|
||||
|
||||
内置 key 有失效的可能(轮换、上游清理、某个发行版注入了坏值)。约定如下:
|
||||
|
||||
- **自检**:`seal-use langfuse check` 是内置健康检查,一秒发现失效——密钥无效 → `Langfuse API 401/403` + exit 11(附"检查注入的密钥"下一步提示);凭据未注入 → exit 11 并说明注入方式;网络不通、代理返回非 JSON、上游 5xx → exit 1。全部是结构化报错 + 稳定退出码,**不会崩溃、不会栈溢出、不会挂住**。
|
||||
- **影响面隔离**:`langfuse` 域是懒加载的,失效只影响这 10 个动词本身;其它命令、MCP 网关完全不受影响(`version`/`corps` 等照常)。
|
||||
- **cache-first 自动降级**:outline / search / observation / observations / url / attachment-flow / rule-flow 只读本地缓存——**即使 key 当场失效,已缓存过的 trace 依然能离线读取**;只有 `check` / `cache-refresh` / `session` 这类必须联网的动词会失败。
|
||||
- **处置**:不要在本地补 key(用户配置不参与本域);拿新版 `seal-use update`(轮换密钥后会随新发行版注入),期间改用 Langfuse Web 后台。
|
||||
|
||||
## 安全
|
||||
|
||||
trace 的 input/output/metadata 可能包含企业审批数据,按敏感数据对待:不贴大段 prompt/输出,不跨受众分享缓存 JSON。凭据内嵌于二进制、只读由 client 保证,详见 `SECURITY.md`。
|
||||
@@ -349,6 +349,32 @@ describe("corps get and search", () => {
|
||||
expect(data.source.tokenMasked).toContain("...");
|
||||
});
|
||||
|
||||
test("corps search ranks a Chinese name typo above industry-only matches", async () => {
|
||||
const enterprises = setupConfigEnv();
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
for (const [id, name] of [
|
||||
["corp-yutai", "钰泰半导体股份有限公司"],
|
||||
["corp-other", "华芯半导体股份有限公司"]
|
||||
]) {
|
||||
writeFileSync(join(enterprises, `${id}.json`), JSON.stringify({
|
||||
id,
|
||||
name,
|
||||
seal: { url: `https://${id}.seal.test` },
|
||||
source: { type: "hose", appKey: "fixture-key", appSecurity: "fixture-secret", corpId: id, staffId: "fixture-staff" },
|
||||
auth: { refreshTtl: 300 }
|
||||
}));
|
||||
}
|
||||
|
||||
for (const query of ["瑞泰半导体", "瑞泰 半导体"]) {
|
||||
const result = await runCli(["corps", "search", query]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).map((corp: { id: string }) => corp.id)).toEqual(["corp-yutai"]);
|
||||
}
|
||||
const strict = await runCli(["corps", "search", "瑞泰半导体", "--strict"]);
|
||||
expect(strict.exitCode).toBe(0);
|
||||
expect(JSON.parse(strict.stdout)).toEqual([]);
|
||||
});
|
||||
|
||||
test("corps search filters across name, staffId, environment, and keywords", async () => {
|
||||
const enterprises = setupConfigEnv();
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
|
||||
@@ -78,11 +78,17 @@ export async function handleCorpBindings(
|
||||
}
|
||||
|
||||
if (prodCorp.testCorpId && prodCorp.testCorpId !== testCorp.id) {
|
||||
console.error(
|
||||
`⚠️ [bind-test] 检测到冲突:已强制解除生产企业「${prodCorp.name}」(${prodCorp.id}) 与原测试企业「${prodCorp.testCorpId}」的绑定关联。`
|
||||
);
|
||||
try {
|
||||
updateCorpConfig(prodCorp.testCorpId, { prodCorpId: undefined });
|
||||
} catch {}
|
||||
}
|
||||
if (testCorp.prodCorpId && testCorp.prodCorpId !== prodCorp.id) {
|
||||
console.error(
|
||||
`⚠️ [bind-test] 检测到冲突:已强制解除测试企业「${testCorp.name}」(${testCorp.id}) 与原生产企业「${testCorp.prodCorpId}」的绑定关联。`
|
||||
);
|
||||
try {
|
||||
updateCorpConfig(testCorp.prodCorpId, { testCorpId: undefined });
|
||||
} catch {}
|
||||
|
||||
@@ -5,8 +5,11 @@ import {
|
||||
saveGlobalConfig,
|
||||
updateCorpConfig
|
||||
} from "../../../core/config/loader.js";
|
||||
import { filterCorpsFuzzy } from "../../../core/search/fuzzy.js";
|
||||
import { sortCorpsByUsageAndRecency } from "../../../core/stats/usage-tracker.js";
|
||||
import { filterCorpsFuzzy } from "../../../core/corp-search/rank.js";
|
||||
import {
|
||||
getRecentCorpUsageScores,
|
||||
sortCorpsByUsageAndRecency
|
||||
} from "../../../core/stats/usage-tracker.js";
|
||||
import type { CorpEnvironment } from "../../../core/config/types.js";
|
||||
import { selectCorp } from "../../helpers.js";
|
||||
import { confirmationRequired, usageError } from "../../errors.js";
|
||||
@@ -48,7 +51,10 @@ export async function handleCorpOverview(
|
||||
filtered = filtered.filter((item) => (item.environment ?? "production").toLowerCase() === envFilter);
|
||||
}
|
||||
if (rawQuery) {
|
||||
filtered = filterCorpsFuzzy(filtered, rawQuery, { strict: isStrict });
|
||||
// Equal-relevance results are ordered by recent usage so frequent corps
|
||||
// surface on ties without ever beating a better match.
|
||||
const usageScores = getRecentCorpUsageScores(filtered.map((item) => item.id));
|
||||
filtered = filterCorpsFuzzy(filtered, rawQuery, { strict: isStrict }, usageScores);
|
||||
}
|
||||
|
||||
if (allCorps.length === 0) {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../dom
|
||||
import { selectCorp } from "../../helpers.js";
|
||||
import { CliError, confirmationRequired, usageError } from "../../errors.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import { outputOptions, printJson } from "../../printer.js";
|
||||
import type { ParsedArgs } from "../../types.js";
|
||||
|
||||
export { buildTestHosecloudOutboundName } from "../../../domains/seal/test-sync.js";
|
||||
@@ -50,7 +50,16 @@ export async function handleCorpSync(
|
||||
`seal-use corps sync-test ${prodCorp.id} --yes`
|
||||
);
|
||||
}
|
||||
printJson(await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: true }));
|
||||
const result = await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: true });
|
||||
const targetVersion = (result as { target?: { publishedVersion?: { versionNumber?: number; versionName?: string; rulesCount?: number } } })?.target?.publishedVersion;
|
||||
const rulesList = (result as { ruleMapping?: unknown[] })?.ruleMapping ?? [];
|
||||
console.error(
|
||||
`✅ 测试企业同步完成: 生产「${prodCorp.name}」(${prodCorp.id}) -> 测试「${testCorp.name}」(${testCorp.id})\n` +
|
||||
`📦 已发布测试版本: v${targetVersion?.versionNumber ?? "?"} (${targetVersion?.versionName ?? "最新"}) | 规则总数: ${targetVersion?.rulesCount ?? rulesList.length} 条\n` +
|
||||
`🔄 规则映射已归档: 共 ${rulesList.length} 条规则已与测试环境对齐\n` +
|
||||
`👉 下一步模拟测试建议: seal-use simulation create --document-sn <单号> --corp ${testCorp.id} --extract-expenses`
|
||||
);
|
||||
printJson(result, outputOptions(args.options));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { validationError } from "../../core/errors.js";
|
||||
import { booleanOption, numberOption, splitOption, stringOption } from "../parser.js";
|
||||
import { runLangfuseCapability } from "../helpers.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
/**
|
||||
* `seal-use langfuse <verb>` — read-only Langfuse trace inspection.
|
||||
*
|
||||
* The trace/session id is a positional argument (flag fallback accepted), all
|
||||
* tuning knobs are flags. JSON goes to stdout via `runLangfuseCapability`
|
||||
* (size-capped: `--full` / `--output-file` escape hatches); unknown verbs throw
|
||||
* so the runner assigns exit 2.
|
||||
*/
|
||||
export async function handleLangfuseCommand(
|
||||
action: string | undefined,
|
||||
maybeName: string | undefined,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
const options = args.options;
|
||||
const out = outputOptions(options);
|
||||
const traceId = () => maybeName ?? stringOption(options["trace-id"]);
|
||||
const refreshIfMissing = () => booleanOption(options["refresh-if-missing"]);
|
||||
|
||||
if (action === "check") {
|
||||
await runLangfuseCapability("sealLangfuseConnectionCheck", {}, out);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "cache-refresh") {
|
||||
await runLangfuseCapability("sealLangfuseTraceCacheRefresh", { traceId: traceId() }, out);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "url") {
|
||||
await runLangfuseCapability("sealLangfuseTraceUrlGet", { traceId: traceId() }, out);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "outline") {
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseTraceOutlineGet",
|
||||
{
|
||||
traceId: traceId(),
|
||||
includeIoPreview: booleanOption(options["include-io-preview"]),
|
||||
full: booleanOption(options.full),
|
||||
maxPreviewChars: numberOption(options["max-preview-chars"]),
|
||||
refreshIfMissing: refreshIfMissing()
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "search") {
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseTraceQrepSearch",
|
||||
{
|
||||
traceId: traceId(),
|
||||
query: splitOption(options.query),
|
||||
sessionId: stringOption(options["session-id"]),
|
||||
fields: splitOption(options.fields),
|
||||
observationTypes: splitOption(options["observation-types"]),
|
||||
metadata: parseMetadataOption(stringOption(options.metadata)),
|
||||
maxResults: numberOption(options["max-results"]),
|
||||
contextChars: numberOption(options["context-chars"]),
|
||||
refreshIfMissing: refreshIfMissing()
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "observation") {
|
||||
const observationId = args.command[3] ?? stringOption(options["observation-id"]);
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseObservationIoGet",
|
||||
{
|
||||
traceId: traceId(),
|
||||
observationId,
|
||||
fields: splitOption(options.fields),
|
||||
maxChars: numberOption(options["max-chars"]),
|
||||
full: booleanOption(options.full),
|
||||
jsonPath: stringOption(options["json-path"]) ?? stringOption(options.path),
|
||||
refreshIfMissing: refreshIfMissing()
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "session") {
|
||||
const sessionId = maybeName ?? stringOption(options["session-id"]);
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseSessionOutlineGet",
|
||||
{
|
||||
sessionId,
|
||||
traceLimit: numberOption(options["trace-limit"])
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "observations") {
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseObservationsFind",
|
||||
{
|
||||
traceId: traceId(),
|
||||
nameContains: stringOption(options["name-contains"]),
|
||||
type: stringOption(options.type),
|
||||
metadataKey: stringOption(options["metadata-key"]),
|
||||
hasInput: booleanOption(options["has-input"]),
|
||||
hasOutput: booleanOption(options["has-output"]),
|
||||
maxResults: numberOption(options["max-results"]),
|
||||
refreshIfMissing: refreshIfMissing()
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "attachment-flow") {
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseAttachmentFlowGet",
|
||||
{
|
||||
traceId: traceId(),
|
||||
fileId: stringOption(options["file-id"]),
|
||||
fileName: stringOption(options["file-name"]),
|
||||
contentHints: splitOption(options["content-hints"]),
|
||||
contextChars: numberOption(options["context-chars"]),
|
||||
refreshIfMissing: refreshIfMissing()
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "rule-flow") {
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseTraceRuleFlowGet",
|
||||
{
|
||||
traceId: traceId(),
|
||||
rule: stringOption(options.rule),
|
||||
ruleHints: splitOption(options["rule-hints"]),
|
||||
contextChars: numberOption(options["context-chars"]),
|
||||
refreshIfMissing: refreshIfMissing()
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Unknown langfuse command: ${action ?? ""}. Run 'seal-use help' for available commands.`
|
||||
);
|
||||
}
|
||||
|
||||
function parseMetadataOption(raw: string | undefined): Record<string, string | number | boolean> | undefined {
|
||||
if (raw === undefined) return undefined;
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
throw validationError(`无效的 --metadata:需要 JSON 对象,例如 '{"key":"value"}'`);
|
||||
}
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
||||
throw validationError("无效的 --metadata:需要 JSON 对象,例如 '{\"key\":\"value\"}'");
|
||||
}
|
||||
return parsed as Record<string, string | number | boolean>;
|
||||
}
|
||||
@@ -66,6 +66,26 @@ export async function handleSimulationCommand(
|
||||
const wait = booleanOption(args.options.wait) === true;
|
||||
const noWait = booleanOption(args.options.noWait) ?? booleanOption(args.options["no-wait"]) ?? (wait ? false : true);
|
||||
|
||||
const extractExpenses =
|
||||
booleanOption(args.options.extract) ??
|
||||
booleanOption(args.options["extract-expenses"]) ??
|
||||
booleanOption(args.options.extractExpenses) ??
|
||||
booleanOption(args.options["with-expense-extraction"]) ??
|
||||
booleanOption(args.options.withExpenseExtraction);
|
||||
const skipExpenseOption =
|
||||
booleanOption(args.options["skip-extract"]) ??
|
||||
booleanOption(args.options.skipExtract) ??
|
||||
booleanOption(args.options.skipExpenseExtraction) ??
|
||||
booleanOption(args.options["skip-expense-extraction"]);
|
||||
const skipExpenseExtraction =
|
||||
extractExpenses !== undefined ? !extractExpenses : skipExpenseOption;
|
||||
|
||||
if (extractExpenses === true) {
|
||||
console.error(
|
||||
"💡 [simulation] 已开启后台费用明细提取入库 (--extract)。此批次明细将写入费用库,供后续跨单防重报检索。"
|
||||
);
|
||||
}
|
||||
|
||||
const result = await runCapabilityResult(
|
||||
"sealSimulationBatchCreate",
|
||||
client,
|
||||
@@ -78,7 +98,7 @@ export async function handleSimulationCommand(
|
||||
rejectNodeName: stringOption(args.options.rejectNode) ?? stringOption(args.options["reject-node"]) ?? null,
|
||||
thinkingDepthOverride: stringOption(args.options.thinkingDepth) ?? stringOption(args.options["thinking-depth"]),
|
||||
skipInvoiceGeneration: booleanOption(args.options.skipInvoiceGeneration) ?? booleanOption(args.options["skip-invoice-generation"]),
|
||||
skipExpenseExtraction: booleanOption(args.options.skipExpenseExtraction) ?? booleanOption(args.options["skip-expense-extraction"]),
|
||||
skipExpenseExtraction,
|
||||
disableAttachmentCache: booleanOption(args.options.disableAttachmentCache) ?? booleanOption(args.options["disable-attachment-cache"]),
|
||||
signKey,
|
||||
packageIds,
|
||||
|
||||
+107
-2
@@ -654,9 +654,9 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "create",
|
||||
summary: "Trigger a simulation batch (reuses an identical batch within the reuse window)",
|
||||
summary: "Trigger a simulation batch (reuses an identical batch within the reuse window; defaults to skipping background expense DB extraction)",
|
||||
usage: [
|
||||
"seal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--force] [--reuse-window 5m] [--corp <corpId>]",
|
||||
"seal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-extract|--extract] [--skip-invoice-generation] [--no-wait] [--force] [--reuse-window 5m] [--corp <corpId>]",
|
||||
"seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]",
|
||||
"seal-use simulation create --source-system weaver --request-ids \"req-01,req-02\" [--corp <corpId>]"
|
||||
]
|
||||
@@ -1170,6 +1170,111 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "langfuse",
|
||||
title: "Langfuse trace inspection (read-only)",
|
||||
description:
|
||||
"Inspect Langfuse traces/sessions with the built-in read-only credentials: cache once, then outline → search → observation IO. No tenant or user config required.",
|
||||
commands: [
|
||||
{
|
||||
name: "check",
|
||||
summary: "Check connectivity of the built-in Langfuse read-only credentials",
|
||||
usage: ["seal-use langfuse check"]
|
||||
},
|
||||
{
|
||||
name: "cache-refresh",
|
||||
summary: "Fetch one full trace into the local cache for offline inspection",
|
||||
usage: ["seal-use langfuse cache-refresh <traceId> [--trace-id <traceId>]"],
|
||||
options: [{ flag: "--trace-id <id>", description: "Trace id when not given as a positional" }]
|
||||
},
|
||||
{
|
||||
name: "outline",
|
||||
summary: "Read a compact observation tree with sizes, usage, cost, and optional IO previews",
|
||||
usage: ["seal-use langfuse outline <traceId> [--include-io-preview] [--max-preview-chars <n>] [--full]"],
|
||||
options: [
|
||||
{ flag: "--include-io-preview", description: "Include short input/output previews on the trace and observations" },
|
||||
{ flag: "--max-preview-chars <n>", description: "Preview length per field, 20-5000 (default 160)" },
|
||||
{ flag: "--full", description: "Return full IO instead of previews (large output)" },
|
||||
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "search",
|
||||
summary: "Ranked keyword search inside one cached trace (qrep)",
|
||||
usage: ["seal-use langfuse search <traceId> --query <term1,term2> [--fields input,output] [--max-results <n>]"],
|
||||
options: [
|
||||
{ flag: "--query <terms>", description: "Comma-separated terms; earliest best match wins per field" },
|
||||
{ flag: "--fields <fields>", description: "Comma-separated fields: name,input,output,metadata,userId,sessionId" },
|
||||
{ flag: "--observation-types <types>", description: "Comma-separated observation type filter (e.g. GENERATION,SPAN)" },
|
||||
{ flag: "--metadata <json>", description: "Exact metadata filter as a JSON object" },
|
||||
{ flag: "--max-results <n>", description: "Maximum ranked results, 1-30 (default 10)" },
|
||||
{ flag: "--context-chars <n>", description: "Context around each match, 20-500 (default 120)" },
|
||||
{ flag: "--session-id <id>", description: "Only match when the trace belongs to this session" },
|
||||
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "observation",
|
||||
summary: "Read focused input/output/metadata of one observation",
|
||||
usage: ["seal-use langfuse observation <traceId> <observationId> [--fields input,output] [--max-chars <n>]"],
|
||||
options: [
|
||||
{ flag: "--fields <fields>", description: "Comma-separated fields to read: input,output,metadata (default input,output)" },
|
||||
{ flag: "--max-chars <n>", description: "Per-field character cap, 100-30000 (default 8000)" },
|
||||
{ flag: "--json-path <path>", description: "Read one nested value, e.g. items[0].name" },
|
||||
{ flag: "--full", description: "Raise the cap to 500000 chars (large output)" },
|
||||
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "session",
|
||||
summary: "Read a compact session outline with trace summaries",
|
||||
usage: ["seal-use langfuse session <sessionId> [--trace-limit <n>]"],
|
||||
options: [{ flag: "--trace-limit <n>", description: "Maximum traces to summarize, 1-200 (default 50)" }]
|
||||
},
|
||||
{
|
||||
name: "observations",
|
||||
summary: "Filter cached observations by name/type/metadata without loading IO",
|
||||
usage: ["seal-use langfuse observations <traceId> [--name-contains <text>] [--type <type>]"],
|
||||
options: [
|
||||
{ flag: "--name-contains <text>", description: "Substring match on observation name" },
|
||||
{ flag: "--type <type>", description: "Exact observation type filter" },
|
||||
{ flag: "--metadata-key <key>", description: "Only observations whose metadata has this key" },
|
||||
{ flag: "--has-input", description: "Only observations with non-empty input" },
|
||||
{ flag: "--has-output", description: "Only observations with non-empty output" },
|
||||
{ flag: "--max-results <n>", description: "Maximum summaries, 1-200 (default 50)" },
|
||||
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
summary: "Build the Langfuse UI deep link for one trace",
|
||||
usage: ["seal-use langfuse url <traceId>"]
|
||||
},
|
||||
{
|
||||
name: "attachment-flow",
|
||||
summary: "Trace text evidence of a file id/name through attachment and review stages",
|
||||
usage: ["seal-use langfuse attachment-flow <traceId> [--file-id <id>] [--file-name <name>]"],
|
||||
options: [
|
||||
{ flag: "--file-id <id>", description: "File id to look for (at least one hint required)" },
|
||||
{ flag: "--file-name <name>", description: "File name to look for (at least one hint required)" },
|
||||
{ flag: "--content-hints <hints>", description: "Comma-separated extra content hints" },
|
||||
{ flag: "--context-chars <n>", description: "Context around each match, 20-500 (default 120)" },
|
||||
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "rule-flow",
|
||||
summary: "Trace text evidence of one rule through matching, parsing, and review stages",
|
||||
usage: ["seal-use langfuse rule-flow <traceId> --rule <规则内容>"],
|
||||
options: [
|
||||
{ flag: "--rule <text>", description: "Rule text to trace (required)" },
|
||||
{ flag: "--rule-hints <hints>", description: "Comma-separated extra rule hints" },
|
||||
{ flag: "--context-chars <n>", description: "Context around each match, 20-500 (default 300)" },
|
||||
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "mcp",
|
||||
title: "Model Context Protocol (MCP) server",
|
||||
|
||||
@@ -3,6 +3,9 @@ import { resolveCorpConfig } from "../core/config/manager.js";
|
||||
import { recordCorpUsage } from "../core/stats/usage-tracker.js";
|
||||
import { createSealClient } from "../core/http/factory.js";
|
||||
import { sealCapabilities, parseCapabilityParams, type SealCapability } from "../domains/seal/capabilities.js";
|
||||
import { createLangfuseService, findLangfuseCapability } from "../domains/langfuse/capabilities.js";
|
||||
import type { LangfuseService } from "../domains/langfuse/service.js";
|
||||
import { validationError } from "../core/errors.js";
|
||||
import type { CorpConfig, GlobalConfig } from "../core/config/types.js";
|
||||
import { printJson } from "./printer.js";
|
||||
import type { OutputOptions } from "./types.js";
|
||||
@@ -67,3 +70,34 @@ export async function runCapabilityResult(
|
||||
const handler = tool.handler as SealCapability["handler"];
|
||||
return handler(client, compactParams as never, { corp });
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatches one read-only Langfuse capability and prints its JSON payload.
|
||||
*
|
||||
* Same contract as `runCapability` minus the tenant: no Seal client, no
|
||||
* corp — Langfuse access relies solely on the compile-time injected key pair.
|
||||
* Params are gated by the capability's Zod schema (missing/invalid → exit 13)
|
||||
* before the handler sees them.
|
||||
*/
|
||||
export async function runLangfuseCapability(
|
||||
name: string,
|
||||
params: Record<string, unknown>,
|
||||
options: OutputOptions = {}
|
||||
) {
|
||||
const tool = findLangfuseCapability(name);
|
||||
if (!tool) throw new Error(`Unknown Langfuse tool: ${name}`);
|
||||
|
||||
const compactParams = Object.fromEntries(
|
||||
Object.entries(params).filter(([, value]) => value !== undefined)
|
||||
);
|
||||
const parsed = tool.parameters.safeParse(compactParams);
|
||||
if (!parsed.success) {
|
||||
const detail = parsed.error.issues
|
||||
.map((issue) => `${issue.path.length ? issue.path.join(".") : "(root)"}: ${issue.message}`)
|
||||
.join("; ");
|
||||
throw validationError(`Invalid parameters for ${tool.name}: ${detail}`);
|
||||
}
|
||||
|
||||
const handler = tool.handler as (params: never, service: LangfuseService) => Promise<unknown>;
|
||||
printJson(await handler(compactParams as never, createLangfuseService()), options);
|
||||
}
|
||||
+30
-30
@@ -26,14 +26,14 @@ export const BOOLEAN_FLAGS = new Set([
|
||||
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
|
||||
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
|
||||
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
|
||||
"exclude-deleted", "fail-on-flips", "flow", "force", "full", "help",
|
||||
"hose", "hose-sso", "hoseSso", "include-deleted", "include-simulation", "include-unchanged",
|
||||
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "has-input", "has-output", "help",
|
||||
"hose", "hose-sso", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow",
|
||||
"no-wait", "noWait", "overwrite", "plain", "publish", "quiet",
|
||||
"r", "recode", "refresh", "reveal", "rotate-secret", "rotateSecret",
|
||||
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-invoice-generation",
|
||||
"skipExpenseExtraction", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
|
||||
"summary", "to-downloads", "toDownloads", "v", "wait", "with-flow",
|
||||
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
|
||||
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation",
|
||||
"skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
|
||||
"summary", "to-downloads", "toDownloads", "v", "wait", "with-expense-extraction", "withExpenseExtraction", "with-flow",
|
||||
"workspace", "yes"
|
||||
]);
|
||||
|
||||
@@ -41,22 +41,22 @@ export const BOOLEAN_FLAGS = new Set([
|
||||
export const VALUE_FLAGS = new Set([
|
||||
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
|
||||
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
|
||||
"code", "concurrency", "content", "content-file", "content-type", "contentFile",
|
||||
"contentType", "contextLines", "corp", "corp-id", "corpId", "date",
|
||||
"code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile",
|
||||
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "date",
|
||||
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
|
||||
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
|
||||
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
|
||||
"documentId", "documentLimit", "documentSn", "documentType", "domain", "enable",
|
||||
"end", "end-date", "end-time", "endDate", "endTime", "env",
|
||||
"environment", "expire", "expiresIn", "fields", "file", "flow-concurrency",
|
||||
"environment", "expire", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
|
||||
"flow-ids", "flow-status-list", "flowIds", "flowStatusList", "format", "from",
|
||||
"from-link", "host", "humanResult", "id", "input", "integration",
|
||||
"json", "key-id", "keyId", "keyword", "level", "limit",
|
||||
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
|
||||
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
|
||||
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
|
||||
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
||||
"max-runs",
|
||||
"month",
|
||||
"n", "name", "note", "o", "offset", "out",
|
||||
"n", "name", "name-contains", "note", "observation-id", "observation-types", "o", "offset", "out",
|
||||
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
|
||||
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
|
||||
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
|
||||
@@ -65,9 +65,9 @@ export const VALUE_FLAGS = new Set([
|
||||
"reviewed-by", "reviewedBy",
|
||||
"report-id",
|
||||
"repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window",
|
||||
"reuseWindow", "rule", "rule-id", "ruleId", "ruleVersion", "runtime-id",
|
||||
"reuseWindow", "rule", "rule-hints", "rule-id", "ruleId", "ruleVersion", "runtime-id",
|
||||
"runtimeId", "samples", "scenarios", "schema-config", "schemaConfig", "scope",
|
||||
"sealUrl", "search", "secret", "selector", "sign-key", "signKey",
|
||||
"sealUrl", "search", "secret", "selector", "session-id", "sign-key", "signKey",
|
||||
"simulationBatchId", "since", "sn", "sn-prefix", "sn-suffix", "snPrefix",
|
||||
"snSuffix", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
|
||||
"sourceDocumentSN", "sourceSystem", "staff-id", "staff-name", "staff-phone", "staffId",
|
||||
@@ -77,7 +77,7 @@ export const VALUE_FLAGS = new Set([
|
||||
"template",
|
||||
"taskMode", "template-id", "templateId", "test-corp", "thinking-depth", "thinkingDepth",
|
||||
"timeout", "timezone", "title", "to", "token", "tokenId",
|
||||
"template",
|
||||
"trace-id", "trace-limit",
|
||||
"type", "until", "url", "userId", "version-name", "versionName",
|
||||
"verdict",
|
||||
"webhook", "workflow-type-id", "workflowTypeId"
|
||||
@@ -90,7 +90,7 @@ export const KNOWN_FLAGS = new Set([
|
||||
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
|
||||
"bg-save", "business-codes", "businessCodes", "changelog", "check", "check-only",
|
||||
"code", "completed-only", "completedOnly", "concurrency", "confirm", "content",
|
||||
"content-file", "content-type", "contentFile", "contentType", "contextLines", "corp",
|
||||
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
|
||||
"corp-id", "corpId", "count", "date", "dedupe-by", "dedupeBy",
|
||||
"default", "departmentId", "dept", "desc", "description", "description-file",
|
||||
"descriptionFile", "dir", "disable-attachment-cache", "disableAttachmentCache", "doc-id-prefix", "doc-id-suffix",
|
||||
@@ -98,33 +98,33 @@ export const KNOWN_FLAGS = new Set([
|
||||
"documentId", "documentLimit", "documentSn", "documentType", "domain", "download",
|
||||
"downloads", "dry-run", "dryRun", "elevate-hose", "enable", "enabled",
|
||||
"end", "end-date", "end-time", "endDate", "endTime", "env",
|
||||
"environment", "exclude-deleted", "expire", "expiresIn", "f", "fail-on-flips",
|
||||
"fields", "file", "flow", "flow-concurrency", "flow-ids", "flow-status-list",
|
||||
"environment", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "expire", "expiresIn", "f", "fail-on-flips",
|
||||
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-ids", "flow-status-list",
|
||||
"flowIds", "flowStatusList", "force", "format", "from", "from-link",
|
||||
"full", "h", "help", "hose", "hose-sso", "hoseSso",
|
||||
"host", "humanResult", "id", "include-deleted", "include-simulation", "include-unchanged",
|
||||
"full", "h", "has-input", "has-output", "help", "hose", "hose-sso", "hoseSso",
|
||||
"host", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
|
||||
"key-id", "keyId", "keyword", "level", "limit", "lines",
|
||||
"json-path", "key-id", "keyId", "keyword", "level", "limit", "lines",
|
||||
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
|
||||
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
|
||||
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
||||
"max-runs",
|
||||
"month",
|
||||
"n", "name", "no-attachments", "no-flow", "no-wait", "noWait",
|
||||
"note", "o", "offset", "out", "out-dir", "outDir",
|
||||
"n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait",
|
||||
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir",
|
||||
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
|
||||
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
|
||||
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
|
||||
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
|
||||
"query", "quiet", "r", "recode", "record-id", "record-ids",
|
||||
"recordId", "recordIds", "refresh", "reject-node", "rejectNode", "repo",
|
||||
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "repo",
|
||||
"report-id",
|
||||
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
|
||||
"reviewed-by", "reviewedBy",
|
||||
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-id", "ruleId",
|
||||
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-hints", "rule-id", "ruleId",
|
||||
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
|
||||
"schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret",
|
||||
"selector", "sign-key", "signKey", "silent", "silent-save", "simulation",
|
||||
"simulationBatchId", "since", "skip-expense-extraction", "skip-invoice-generation", "skipExpenseExtraction", "skipInvoiceGeneration",
|
||||
"selector", "session-id", "sign-key", "signKey", "silent", "silent-save", "simulation",
|
||||
"simulationBatchId", "since", "skip-expense-extraction", "skip-extract", "skip-invoice-generation", "skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration",
|
||||
"sn", "sn-prefix", "sn-suffix", "snPrefix", "snSuffix", "snippet-only",
|
||||
"snippetOnly", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
|
||||
"sourceDocumentSN", "sourceSystem", "sso", "staff-id", "staff-name", "staff-phone",
|
||||
@@ -134,10 +134,10 @@ export const KNOWN_FLAGS = new Set([
|
||||
"template",
|
||||
"target-corp", "targetCorp", "task-mode", "taskMode", "template-id", "templateId",
|
||||
"test-corp", "thinking-depth", "thinkingDepth", "timeout", "timezone", "title",
|
||||
"to", "to-downloads", "toDownloads", "token", "tokenId", "type",
|
||||
"to", "to-downloads", "toDownloads", "token", "tokenId", "trace-id", "trace-limit", "type",
|
||||
"until", "url", "userId", "v", "version", "version-name",
|
||||
"verdict",
|
||||
"versionName", "wait", "webhook", "with-flow", "workflow-type-id", "workflowTypeId",
|
||||
"versionName", "wait", "webhook", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
|
||||
"workspace", "yes"
|
||||
]);
|
||||
|
||||
|
||||
@@ -61,6 +61,10 @@ describe("CLI read-only classification", () => {
|
||||
["deploy", "hosecloud", "status", "--corp", "corp-a"],
|
||||
["preferences", "get"],
|
||||
["doctor", "tenant", "--corp", "corp-a"],
|
||||
["langfuse", "check"],
|
||||
["langfuse", "outline", "trace-1", "--include-io-preview"],
|
||||
["langfuse", "search", "trace-1", "--query", "发票"],
|
||||
["langfuse", "observation", "trace-1", "obs-1"],
|
||||
["version"],
|
||||
["mcp-config"]
|
||||
]) {
|
||||
@@ -97,6 +101,7 @@ describe("CLI read-only classification", () => {
|
||||
["auth", "keys"],
|
||||
["analytics", "analyze", "record-1"],
|
||||
["tool", "sealApprovalRuleCreate", "--json", "{}"],
|
||||
["langfuse", "unknown-verb"],
|
||||
["totally-unknown", "list"],
|
||||
[]
|
||||
]) {
|
||||
|
||||
@@ -82,6 +82,19 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
source: ["config"],
|
||||
skill: ["dump", "status"],
|
||||
doctor: ["", "guide", "paths", "tenant", "auth"],
|
||||
// The whole Langfuse area is read-only: the embedded client issues GET only.
|
||||
langfuse: [
|
||||
"check",
|
||||
"cache-refresh",
|
||||
"outline",
|
||||
"search",
|
||||
"observation",
|
||||
"session",
|
||||
"url",
|
||||
"observations",
|
||||
"attachment-flow",
|
||||
"rule-flow"
|
||||
],
|
||||
// Bare form only; the optional trailing `<corpId>` selector is handled by
|
||||
// SELECTOR_POSITIONAL_AREAS below, since a bare entry matches no tokens.
|
||||
probe: [""]
|
||||
|
||||
@@ -64,6 +64,7 @@ export const KNOWN_AREAS = new Set([
|
||||
"skill",
|
||||
"probe",
|
||||
"doctor",
|
||||
"langfuse",
|
||||
"changelog",
|
||||
"test"
|
||||
]);
|
||||
@@ -223,6 +224,14 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Langfuse trace inspection needs no tenant: it authenticates with the
|
||||
// compile-time injected read-only key pair, so it dispatches before corp
|
||||
// selection (like probe/doctor) and never touches a Seal client.
|
||||
if (area === "langfuse") {
|
||||
await (await import("./commands/langfuse.js")).handleLangfuseCommand(action, maybeName, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "test") {
|
||||
await (await import("./commands/test.js")).handleTestCommand(action, maybeName, args);
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import { fuzzyMatchString } from "./engine.js";
|
||||
import { isSubsequence } from "./distance.js";
|
||||
import { matchTokenizedQuery } from "./tokens.js";
|
||||
import type { FuzzyMatchOptions, MatchReason, MatchScoreResult } from "./types.js";
|
||||
|
||||
interface CorpField {
|
||||
text: string | undefined;
|
||||
weight: number;
|
||||
}
|
||||
|
||||
function corpSearchFields(corp: CorpConfig): CorpField[] {
|
||||
return [
|
||||
{ text: corp.name, weight: 1.2 },
|
||||
{ text: corp.id, weight: 1.1 },
|
||||
{ text: corp.source.staffId, weight: 1.0 },
|
||||
{ text: (corp.source as any).domain, weight: 1.0 },
|
||||
{ text: (corp.source as any).corpId, weight: 1.0 },
|
||||
{ text: corp.seal.tenantSlug, weight: 1.0 },
|
||||
{ text: (corp.source as any).tenantSlug, weight: 1.0 },
|
||||
{ text: (corp.source as any).tenantName, weight: 1.1 },
|
||||
{ text: corp.testCorpId, weight: 1.0 },
|
||||
{ text: corp.prodCorpId, weight: 1.0 },
|
||||
{ text: corp.environment ?? "production", weight: 0.8 },
|
||||
{ text: corp.source.type, weight: 0.8 },
|
||||
{ text: (corp.source as any).provider, weight: 0.8 }
|
||||
];
|
||||
}
|
||||
|
||||
interface WeightedMatch {
|
||||
score: number;
|
||||
reason: MatchReason;
|
||||
}
|
||||
|
||||
/** Keeps the higher-scoring candidate; ties stay with the earlier match. */
|
||||
function strongerMatch(current: WeightedMatch, candidate: WeightedMatch): WeightedMatch {
|
||||
return candidate.score > current.score ? candidate : current;
|
||||
}
|
||||
|
||||
function matchCorpFields(
|
||||
fields: CorpField[],
|
||||
query: string,
|
||||
options: FuzzyMatchOptions
|
||||
): WeightedMatch {
|
||||
let best: WeightedMatch = { score: 0, reason: "none" };
|
||||
for (const field of fields) {
|
||||
if (!field.text) continue;
|
||||
const res = fuzzyMatchString(query, field.text, options);
|
||||
if (res.matched) {
|
||||
best = strongerMatch(best, { score: res.score * field.weight, reason: res.reason });
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* When a long Chinese query contains a compact enterprise name in order (for
|
||||
* example, "苏州园区测绘" contains the leading "园测" of "园测信息科技股份有限公司"),
|
||||
* retain that candidate as a lower-confidence abbreviation match. This is
|
||||
* deliberately below exact/substring/pinyin matches and disabled in strict mode.
|
||||
*/
|
||||
function matchCorpAbbreviation(fields: CorpField[], query: string): WeightedMatch {
|
||||
let best: WeightedMatch = { score: 0, reason: "none" };
|
||||
const queryChinese = query.trim().match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
|
||||
if (queryChinese.length < 3) return best;
|
||||
|
||||
for (const field of fields) {
|
||||
if (!field.text) continue;
|
||||
const targetChinese = field.text.match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
|
||||
const prefix = targetChinese.slice(0, 2);
|
||||
if (prefix.length < 2 || !isSubsequence(prefix, queryChinese)) continue;
|
||||
|
||||
best = strongerMatch(best, { score: 0.74 * field.weight, reason: "abbreviation" });
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function matchCorpTokens(fields: CorpField[], query: string): WeightedMatch {
|
||||
let best: WeightedMatch = { score: 0, reason: "none" };
|
||||
for (const field of fields) {
|
||||
if (!field.text) continue;
|
||||
const res = matchTokenizedQuery(query, field.text);
|
||||
if (res.matched) {
|
||||
best = strongerMatch(best, { score: res.score * field.weight, reason: res.reason });
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches an enterprise (`CorpConfig`) against a query across all its searchable fields,
|
||||
* returning the highest match score and reason.
|
||||
*/
|
||||
export function matchCorp(
|
||||
corp: CorpConfig,
|
||||
query: string,
|
||||
options: FuzzyMatchOptions = {}
|
||||
): MatchScoreResult {
|
||||
const fields = corpSearchFields(corp);
|
||||
|
||||
let best = matchCorpFields(fields, query, options);
|
||||
if (!options.strict) {
|
||||
best = strongerMatch(best, matchCorpAbbreviation(fields, query));
|
||||
best = strongerMatch(best, matchCorpTokens(fields, query));
|
||||
}
|
||||
|
||||
return {
|
||||
matched: best.score > 0,
|
||||
score: best.score,
|
||||
reason: best.reason
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { levenshteinDistance, minSubstringLevenshtein } from "./distance.js";
|
||||
|
||||
describe("distance primitives", () => {
|
||||
describe("levenshteinDistance", () => {
|
||||
test("calculates distance correctly", () => {
|
||||
expect(levenshteinDistance("", "")).toBe(0);
|
||||
expect(levenshteinDistance("abc", "abc")).toBe(0);
|
||||
expect(levenshteinDistance("abc", "ab")).toBe(1);
|
||||
expect(levenshteinDistance("abc", "abcd")).toBe(1);
|
||||
expect(levenshteinDistance("kitten", "sitting")).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("minSubstringLevenshtein", () => {
|
||||
test("detects exact substring with distance 0", () => {
|
||||
expect(minSubstringLevenshtein("abc", "xyzabcdef")).toBe(0);
|
||||
});
|
||||
|
||||
test("detects missing letter with distance 1", () => {
|
||||
expect(minSubstringLevenshtein("acm", "acme corp")).toBe(0); // acm is substring of acme
|
||||
expect(minSubstringLevenshtein("xiezihao", "xieziha")).toBe(1); // target missing 'o'
|
||||
expect(minSubstringLevenshtein("xiezhao", "xiezihao")).toBe(1); // query missing 'i'
|
||||
});
|
||||
|
||||
test("detects single substitution typo with distance 1", () => {
|
||||
expect(minSubstringLevenshtein("xiezhao", "xiezihao")).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Standard Levenshtein distance between two strings.
|
||||
*/
|
||||
export function levenshteinDistance(a: string, b: string): number {
|
||||
const m = a.length;
|
||||
const n = b.length;
|
||||
if (m === 0) return n;
|
||||
if (n === 0) return m;
|
||||
|
||||
let prevRow = Array.from({ length: n + 1 }, (_, j) => j);
|
||||
let currRow: number[] = Array.from({ length: n + 1 }, () => 0);
|
||||
|
||||
for (let i = 1; i <= m; i += 1) {
|
||||
currRow[0] = i;
|
||||
for (let j = 1; j <= n; j += 1) {
|
||||
if (a[i - 1] === b[j - 1]) {
|
||||
currRow[j] = prevRow[j - 1] ?? 0;
|
||||
} else {
|
||||
const sub = prevRow[j - 1] ?? 0;
|
||||
const ins = currRow[j - 1] ?? 0;
|
||||
const del = prevRow[j] ?? 0;
|
||||
currRow[j] = Math.min(sub, ins, del) + 1;
|
||||
}
|
||||
}
|
||||
const temp = prevRow;
|
||||
prevRow = currRow;
|
||||
currRow = temp;
|
||||
}
|
||||
return prevRow[n] ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the minimum Levenshtein distance between `query` and any sliding window substring in `target`.
|
||||
* Supports queries missing a letter, having an extra letter, or having an internal typo.
|
||||
*/
|
||||
export function minSubstringLevenshtein(query: string, target: string): number {
|
||||
if (!query || !target) return 999;
|
||||
if (target.includes(query)) return 0;
|
||||
|
||||
const qLen = query.length;
|
||||
if (target.length < qLen - 2) {
|
||||
return levenshteinDistance(query, target);
|
||||
}
|
||||
|
||||
let min = 999;
|
||||
const minWindow = Math.max(1, qLen - 2);
|
||||
const maxWindow = Math.min(target.length, qLen + 2);
|
||||
|
||||
for (let len = minWindow; len <= maxWindow; len += 1) {
|
||||
for (let i = 0; i <= target.length - len; i += 1) {
|
||||
const sub = target.slice(i, i + len);
|
||||
const dist = levenshteinDistance(query, sub);
|
||||
if (dist < min) min = dist;
|
||||
if (min === 0) return 0;
|
||||
}
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if all characters of `query` appear in order inside `target` (subsequence).
|
||||
*/
|
||||
export function isSubsequence(query: string, target: string): boolean {
|
||||
if (!query || !target) return false;
|
||||
let qIdx = 0;
|
||||
for (let tIdx = 0; tIdx < target.length && qIdx < query.length; tIdx += 1) {
|
||||
if (query[qIdx] === target[tIdx]) {
|
||||
qIdx += 1;
|
||||
}
|
||||
}
|
||||
return qIdx === query.length;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { fuzzyMatchString } from "./engine.js";
|
||||
|
||||
describe("fuzzyMatchString", () => {
|
||||
test("exact match", () => {
|
||||
const res = fuzzyMatchString("谢子豪", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("exact");
|
||||
expect(res.score).toBe(1.0);
|
||||
});
|
||||
|
||||
test("prefix substring keeps the 0.95 band", () => {
|
||||
const res = fuzzyMatchString("谢子", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("substring");
|
||||
expect(res.score).toBe(0.95);
|
||||
});
|
||||
|
||||
test("mid-string substring ranks below prefix hits", () => {
|
||||
const res = fuzzyMatchString("子豪", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("substring");
|
||||
expect(res.score).toBe(0.92);
|
||||
});
|
||||
|
||||
test("normalizes full-width characters (NFKC)", () => {
|
||||
const res = fuzzyMatchString("GB", "GB科技");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("substring");
|
||||
});
|
||||
|
||||
test("initials match (简拼)", () => {
|
||||
const res = fuzzyMatchString("xzh", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("initials");
|
||||
expect(res.score).toBe(0.9);
|
||||
});
|
||||
|
||||
test("pinyin match (全拼)", () => {
|
||||
const res = fuzzyMatchString("xiezihao", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("pinyin");
|
||||
});
|
||||
|
||||
test("homophones (同音字)", () => {
|
||||
const res1 = fuzzyMatchString("鞋子豪", "谢子豪");
|
||||
expect(res1.matched).toBe(true);
|
||||
expect(res1.reason).toBe("fuzzy_pinyin");
|
||||
|
||||
const res2 = fuzzyMatchString("渠到", "渠道AI演示环境");
|
||||
expect(res2.matched).toBe(true);
|
||||
expect(res2.reason).toBe("fuzzy_pinyin");
|
||||
});
|
||||
|
||||
test("front/back nasals & flat/retroflex (不区分前后鼻音和平翘舌)", () => {
|
||||
const res1 = fuzzyMatchString("詹三", "张三");
|
||||
expect(res1.matched).toBe(true);
|
||||
|
||||
const res2 = fuzzyMatchString("谢自豪", "谢子豪");
|
||||
expect(res2.matched).toBe(true);
|
||||
});
|
||||
|
||||
test("missing 1 letter or typo tolerance (缺失字母或轻微拼写错误)", () => {
|
||||
const res1 = fuzzyMatchString("xieziha", "谢子豪");
|
||||
expect(res1.matched).toBe(true);
|
||||
|
||||
const res2 = fuzzyMatchString("xiezhao", "谢子豪");
|
||||
expect(res2.matched).toBe(true);
|
||||
|
||||
const res3 = fuzzyMatchString("acme", "acm corp");
|
||||
expect(res3.matched).toBe(true);
|
||||
expect(res3.reason).toBe("levenshtein");
|
||||
});
|
||||
|
||||
test("strict mode rejects fuzzy / homophone / typo matches", () => {
|
||||
expect(fuzzyMatchString("鞋子豪", "谢子豪", { strict: true }).matched).toBe(false);
|
||||
expect(fuzzyMatchString("xzh", "谢子豪", { strict: true }).matched).toBe(false);
|
||||
expect(fuzzyMatchString("xieziha", "谢子豪", { strict: true }).matched).toBe(false);
|
||||
|
||||
// But exact substring is allowed in strict mode
|
||||
expect(fuzzyMatchString("谢子", "谢子豪", { strict: true }).matched).toBe(true);
|
||||
expect(fuzzyMatchString("谢子豪", "谢子豪", { strict: true }).matched).toBe(true);
|
||||
});
|
||||
|
||||
test("rejects completely unrelated terms", () => {
|
||||
expect(fuzzyMatchString("alibaba", "谢子豪").matched).toBe(false);
|
||||
expect(fuzzyMatchString("tencent", "ID01VAdCnJEdFd").matched).toBe(false);
|
||||
expect(fuzzyMatchString("xyz", "渠道环境").matched).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
import { pinyin, match as pinyinMatch } from "pinyin-pro";
|
||||
import { isSubsequence, minSubstringLevenshtein } from "./distance.js";
|
||||
import { normalizeFuzzyPinyin } from "./pinyin.js";
|
||||
import type { FuzzyMatchOptions, MatchScoreResult } from "./types.js";
|
||||
|
||||
/** Normalizes NFKC (full-width -> half-width), trims, and lowercases. */
|
||||
function normalizeText(value: string): string {
|
||||
return value.normalize("NFKC").trim().toLowerCase();
|
||||
}
|
||||
|
||||
function noMatch(): MatchScoreResult {
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
interface PinyinPair {
|
||||
query: string;
|
||||
target: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Precomputed per (query, target) pair so every strategy can share the work.
|
||||
*/
|
||||
interface MatchContext {
|
||||
targetHasChinese: boolean;
|
||||
queryHasChinese: boolean;
|
||||
/** Fuzzy pinyin of both sides, or null when neither side contains Chinese. */
|
||||
fuzzyPinyin: PinyinPair | null;
|
||||
maxDistance: number;
|
||||
}
|
||||
|
||||
function buildMatchContext(
|
||||
normQuery: string,
|
||||
normTarget: string,
|
||||
options: FuzzyMatchOptions
|
||||
): MatchContext {
|
||||
const targetHasChinese = /[\u4e00-\u9fa5]/.test(normTarget);
|
||||
const queryHasChinese = /[\u4e00-\u9fa5]/.test(normQuery);
|
||||
return {
|
||||
targetHasChinese,
|
||||
queryHasChinese,
|
||||
fuzzyPinyin:
|
||||
targetHasChinese || queryHasChinese
|
||||
? { target: normalizeFuzzyPinyin(normTarget), query: normalizeFuzzyPinyin(normQuery) }
|
||||
: null,
|
||||
// Allowed edit distance based on query length:
|
||||
// - <= 2: 0 (no fuzzy edits to prevent excessive false positives)
|
||||
// - 3..5: 1 (missing 1 letter or 1 typo)
|
||||
// - >= 6: 2 (missing 1-2 letters)
|
||||
maxDistance: options.maxDistance ?? (normQuery.length <= 2 ? 0 : normQuery.length <= 5 ? 1 : 2)
|
||||
};
|
||||
}
|
||||
|
||||
/** Initials / Acronym match (e.g. "xzh" matches "谢子豪", "sc" matches "生产"). */
|
||||
function matchByInitials(query: string, target: string, ctx: MatchContext): MatchScoreResult | null {
|
||||
if (!ctx.targetHasChinese || query.length < 2) return null;
|
||||
const targetInitials = pinyin(target, { pattern: "first", toneType: "none", type: "array" })
|
||||
.join("")
|
||||
.toLowerCase();
|
||||
if (targetInitials.includes(query)) {
|
||||
return { matched: true, score: 0.9, reason: "initials" };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Pinyin-pro built-in match (handles full/partial pinyin matching against Chinese targets). */
|
||||
function matchByPinyin(query: string, target: string, ctx: MatchContext): MatchScoreResult | null {
|
||||
if (!ctx.targetHasChinese) return null;
|
||||
try {
|
||||
const pm = pinyinMatch(target, query, { precision: "start" });
|
||||
if (pm && pm.length > 0) {
|
||||
return { matched: true, score: 0.88, reason: "pinyin" };
|
||||
}
|
||||
} catch {
|
||||
// ignore match errors if non-standard regex chars
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Fuzzy Pinyin & Homophones (同音字、前后鼻音、平翘舌音). */
|
||||
function matchByFuzzyPinyin(ctx: MatchContext): MatchScoreResult | null {
|
||||
const pair = ctx.fuzzyPinyin;
|
||||
if (!pair || pair.query.length < 2) return null;
|
||||
if (pair.target.includes(pair.query)) {
|
||||
return { matched: true, score: 0.85, reason: "fuzzy_pinyin" };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Missing letter / Typo tolerance (Levenshtein Distance), on raw strings then on fuzzy pinyin. */
|
||||
function matchByEditDistance(
|
||||
query: string,
|
||||
target: string,
|
||||
ctx: MatchContext
|
||||
): MatchScoreResult | null {
|
||||
if (ctx.maxDistance <= 0) return null;
|
||||
|
||||
// Check raw string distance
|
||||
const rawDist = minSubstringLevenshtein(query, target);
|
||||
if (rawDist <= ctx.maxDistance) {
|
||||
return { matched: true, score: Math.max(0.6, 0.8 - rawDist * 0.1), reason: "levenshtein" };
|
||||
}
|
||||
|
||||
// Check fuzzy pinyin distance (e.g. pinyin with 1 missing letter)
|
||||
const pair = ctx.fuzzyPinyin;
|
||||
if (pair && pair.query.length >= 3 && pair.target.length >= 3) {
|
||||
const pinyinDist = minSubstringLevenshtein(pair.query, pair.target);
|
||||
if (pinyinDist <= ctx.maxDistance) {
|
||||
return { matched: true, score: Math.max(0.6, 0.78 - pinyinDist * 0.1), reason: "levenshtein" };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Subsequence match (loose character order, min query length 3). */
|
||||
function matchBySubsequence(
|
||||
query: string,
|
||||
target: string,
|
||||
ctx: MatchContext
|
||||
): MatchScoreResult | null {
|
||||
if (query.length < 3) return null;
|
||||
if (isSubsequence(query, target)) {
|
||||
return { matched: true, score: 0.65, reason: "subsequence" };
|
||||
}
|
||||
const pair = ctx.fuzzyPinyin;
|
||||
if (pair && isSubsequence(pair.query, pair.target)) {
|
||||
return { matched: true, score: 0.65, reason: "subsequence" };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Core fuzzy string match engine:
|
||||
* Evaluates match across exact, substring (prefix hits outrank mid-string hits),
|
||||
* initials, pinyin, homophone/fuzzy pinyin, sliding-window edit distance
|
||||
* (missing/typo tolerance), and character subsequence.
|
||||
* Strategies run in priority order; the first hit wins.
|
||||
*/
|
||||
export function fuzzyMatchString(
|
||||
query: string,
|
||||
target: string,
|
||||
options: FuzzyMatchOptions = {}
|
||||
): MatchScoreResult {
|
||||
const normQuery = normalizeText(query);
|
||||
const normTarget = normalizeText(target);
|
||||
|
||||
if (!normQuery || !normTarget) {
|
||||
return noMatch();
|
||||
}
|
||||
|
||||
// Exact match
|
||||
if (normTarget === normQuery) {
|
||||
return { matched: true, score: 1.0, reason: "exact" };
|
||||
}
|
||||
|
||||
// Substring match: a query that opens the target is stronger evidence than a
|
||||
// mid-string hit, so it keeps the historical 0.95 band while mid-string drops to 0.92.
|
||||
if (normTarget.startsWith(normQuery)) {
|
||||
return { matched: true, score: 0.95, reason: "substring" };
|
||||
}
|
||||
if (normTarget.includes(normQuery)) {
|
||||
return { matched: true, score: 0.92, reason: "substring" };
|
||||
}
|
||||
|
||||
// If strict mode is requested, only exact or substring matches are accepted.
|
||||
if (options.strict) {
|
||||
return noMatch();
|
||||
}
|
||||
|
||||
const context = buildMatchContext(normQuery, normTarget, options);
|
||||
return (
|
||||
matchByInitials(normQuery, normTarget, context) ??
|
||||
matchByPinyin(normQuery, normTarget, context) ??
|
||||
matchByFuzzyPinyin(context) ??
|
||||
matchByEditDistance(normQuery, normTarget, context) ??
|
||||
matchBySubsequence(normQuery, normTarget, context) ??
|
||||
noMatch()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import type { FuzzyMatchOptions } from "./types.js";
|
||||
import { filterCorpsFuzzy } from "./rank.js";
|
||||
|
||||
// Golden evaluation set for corp search: real-shaped (query -> expected result)
|
||||
// pairs collected from usage regressions and CLI tests. Every tuning change to
|
||||
// scores/thresholds must keep this green; grow it with every real-world
|
||||
// mis-hit or miss instead of re-tuning against a single complaint.
|
||||
|
||||
function makeCorp(id: string, name: string, overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
environment: "production",
|
||||
seal: {
|
||||
tenantSlug: `${id}-slug`,
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
||||
}
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: `${id}-token`,
|
||||
sealUrl: `https://${id}.seal.test`,
|
||||
expiresIn: 3600,
|
||||
staffId: `staff-${id}`
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300
|
||||
},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
const HOSE_SOURCE = {
|
||||
type: "hose",
|
||||
corpId: "ID01VAdCnJEdFd",
|
||||
staffId: "staff-channel",
|
||||
domain: "https://app.ekuaibao.com"
|
||||
} as any;
|
||||
|
||||
const CORPUS: CorpConfig[] = [
|
||||
makeCorp("corp-xiezihao", "谢子豪"),
|
||||
makeCorp("corp-qudao", "渠道AI演示环境", { source: HOSE_SOURCE }),
|
||||
makeCorp("corp-acme", "Acme Global", { environment: "test" }),
|
||||
makeCorp("corp-yuance", "园测信息科技股份有限公司"),
|
||||
makeCorp("corp-yutai", "钰泰半导体股份有限公司"),
|
||||
makeCorp("corp-huaxin", "华芯半导体股份有限公司"),
|
||||
makeCorp("corp-nanjing", "南京测绘"),
|
||||
makeCorp("corp-pingan", "中国平安人寿保险股份有限公司"),
|
||||
makeCorp("corp-gb", "GB国际(集团)有限公司"),
|
||||
makeCorp("corp-shengchan", "生产正式企业", {
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "shengchan-token",
|
||||
sealUrl: "https://shengchan.seal.test",
|
||||
expiresIn: 3600,
|
||||
staffId: "admin-zhangsan"
|
||||
} as any
|
||||
})
|
||||
];
|
||||
|
||||
interface GoldenCase {
|
||||
query: string;
|
||||
/** The id that must rank first. */
|
||||
top?: string;
|
||||
/** Ids that must appear somewhere in the results. */
|
||||
includes?: string[];
|
||||
/** Ids that must not appear (noise suppression checks). */
|
||||
excludes?: string[];
|
||||
/** No corp may match at all. */
|
||||
empty?: boolean;
|
||||
options?: FuzzyMatchOptions;
|
||||
}
|
||||
|
||||
const GOLDEN: GoldenCase[] = [
|
||||
// Exact & substring bands
|
||||
{ query: "园测信息科技股份有限公司", top: "corp-yuance" },
|
||||
{ query: "园测信息", top: "corp-yuance" },
|
||||
{ query: "信息科技", top: "corp-yuance" },
|
||||
{ query: "平安", top: "corp-pingan" },
|
||||
{ query: "渠道", top: "corp-qudao" },
|
||||
// Initials / pinyin / homophones
|
||||
{ query: "xzh", top: "corp-xiezihao" },
|
||||
{ query: "xiezihao", top: "corp-xiezihao" },
|
||||
{ query: "鞋子豪", top: "corp-xiezihao" },
|
||||
{ query: "谢自豪", top: "corp-xiezihao" },
|
||||
{ query: "qudao", top: "corp-qudao" },
|
||||
{ query: "sc", top: "corp-shengchan" },
|
||||
{ query: "盛产", top: "corp-shengchan" },
|
||||
{ query: "yuan-ce", top: "corp-yuance" },
|
||||
// Typo tolerance
|
||||
{ query: "xieziha", top: "corp-xiezihao" },
|
||||
{ query: "zhangsa", top: "corp-shengchan" },
|
||||
// Tokenized Chinese queries with a contextual typo
|
||||
{ query: "瑞泰半导体", top: "corp-yutai", excludes: ["corp-huaxin"] },
|
||||
{ query: "瑞泰 半导体", top: "corp-yutai", excludes: ["corp-huaxin"] },
|
||||
{ query: "半导体 瑞泰", top: "corp-yutai", excludes: ["corp-huaxin"] },
|
||||
{ query: "钰泰 半导体", top: "corp-yutai" },
|
||||
// Compact name inside a long query (abbreviation + weak suppression)
|
||||
{ query: "苏州园区测绘", top: "corp-yuance", excludes: ["corp-nanjing"] },
|
||||
// Identifier fields
|
||||
{ query: "staff-channel", top: "corp-qudao" },
|
||||
{ query: "ID01VAdCnJEdFd", top: "corp-qudao" },
|
||||
{ query: "test", top: "corp-acme" },
|
||||
// Full-width / half-width (NFKC)
|
||||
{ query: "GB", top: "corp-gb" },
|
||||
{ query: "gb", top: "corp-gb" },
|
||||
// Strict mode
|
||||
{ query: "钰泰半导体", options: { strict: true }, top: "corp-yutai" },
|
||||
{ query: "瑞泰半导体", options: { strict: true }, empty: true },
|
||||
{ query: "苏州园区测绘", options: { strict: true }, empty: true },
|
||||
// Unrelated queries match nothing
|
||||
{ query: "alibaba", empty: true },
|
||||
{ query: "腾讯", empty: true }
|
||||
];
|
||||
|
||||
describe("corp search golden set", () => {
|
||||
for (const golden of GOLDEN) {
|
||||
const label = `golden: ${golden.query}${golden.options?.strict ? " --strict" : ""}`;
|
||||
test(label, () => {
|
||||
const results = filterCorpsFuzzy(CORPUS, golden.query, golden.options ?? {});
|
||||
const ids = results.map((corp) => corp.id);
|
||||
|
||||
if (golden.empty) {
|
||||
expect(ids).toEqual([]);
|
||||
}
|
||||
if (golden.top) {
|
||||
expect(ids[0]).toBe(golden.top);
|
||||
}
|
||||
for (const id of golden.includes ?? []) {
|
||||
expect(ids).toContain(id);
|
||||
}
|
||||
for (const id of golden.excludes ?? []) {
|
||||
expect(ids).not.toContain(id);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { normalizeFuzzyPinyin } from "./pinyin.js";
|
||||
|
||||
describe("normalizeFuzzyPinyin", () => {
|
||||
test("normalizes retroflex to flat consonants", () => {
|
||||
expect(normalizeFuzzyPinyin("张")).toBe(normalizeFuzzyPinyin("詹")); // zhang -> zhang/zhan -> zan
|
||||
expect(normalizeFuzzyPinyin("超")).toContain("cao");
|
||||
expect(normalizeFuzzyPinyin("沙")).toContain("sa");
|
||||
});
|
||||
|
||||
test("normalizes front and back nasals", () => {
|
||||
expect(normalizeFuzzyPinyin("陈")).toBe(normalizeFuzzyPinyin("程")); // chen / cheng -> cen
|
||||
expect(normalizeFuzzyPinyin("金")).toBe(normalizeFuzzyPinyin("京")); // jin / jing -> jin
|
||||
});
|
||||
|
||||
test("normalizes homophones to identical representations", () => {
|
||||
expect(normalizeFuzzyPinyin("谢子豪")).toBe(normalizeFuzzyPinyin("鞋子豪"));
|
||||
expect(normalizeFuzzyPinyin("渠道")).toBe(normalizeFuzzyPinyin("渠到"));
|
||||
});
|
||||
|
||||
test("memoizes repeated inputs", () => {
|
||||
expect(normalizeFuzzyPinyin("谢子豪")).toBe(normalizeFuzzyPinyin("谢子豪"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { pinyin } from "pinyin-pro";
|
||||
|
||||
// Query and target strings repeat across corps and fields within one search run
|
||||
// (one query × N corps × 13 fields), so memoize by raw input. Bounded: queries
|
||||
// per process are few, but clear instead of growing without limit.
|
||||
const fuzzyPinyinCache = new Map<string, string>();
|
||||
const PINYIN_CACHE_LIMIT = 128;
|
||||
|
||||
/**
|
||||
* Normalizes Chinese text to toneless pinyin with fuzzy sound rules:
|
||||
* - Retroflex vs flat consonants: zh -> z, ch -> c, sh -> s
|
||||
* - Front vs back nasal sounds: ang -> an, eng -> en, ing -> in, iang -> ian, uang -> uan
|
||||
* - Strips non-alphanumeric whitespace
|
||||
*/
|
||||
export function normalizeFuzzyPinyin(str: string): string {
|
||||
const cached = fuzzyPinyinCache.get(str);
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
let normalized = "";
|
||||
if (str) {
|
||||
const pyTokens = pinyin(str, { toneType: "none", type: "array" });
|
||||
normalized = pyTokens
|
||||
.map((token) =>
|
||||
token
|
||||
.toLowerCase()
|
||||
.replace(/zh/g, "z")
|
||||
.replace(/ch/g, "c")
|
||||
.replace(/sh/g, "s")
|
||||
.replace(/iang/g, "ian")
|
||||
.replace(/uang/g, "uan")
|
||||
.replace(/ang/g, "an")
|
||||
.replace(/eng/g, "en")
|
||||
.replace(/ing/g, "in")
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
|
||||
if (fuzzyPinyinCache.size >= PINYIN_CACHE_LIMIT) fuzzyPinyinCache.clear();
|
||||
fuzzyPinyinCache.set(str, normalized);
|
||||
return normalized;
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import { filterCorpsFuzzy } from "./rank.js";
|
||||
|
||||
function makeCorp(id: string, name: string, overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
environment: "production",
|
||||
seal: {
|
||||
tenantSlug: `${id}-slug`,
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
||||
}
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: `${id}-token`,
|
||||
sealUrl: `https://${id}.seal.test`,
|
||||
expiresIn: 3600,
|
||||
staffId: `staff-${id}`
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300
|
||||
},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe("filterCorpsFuzzy", () => {
|
||||
const corp1 = makeCorp("xiezihao", "谢子豪", {
|
||||
testCorpId: "test-xzh"
|
||||
});
|
||||
const corp2 = makeCorp("ID01VAdCnJEdFd", "渠道AI演示环境", {
|
||||
source: {
|
||||
type: "hose",
|
||||
corpId: "ID01VAdCnJEdFd",
|
||||
staffId: "staff-channel",
|
||||
domain: "https://app.ekuaibao.com"
|
||||
} as any
|
||||
});
|
||||
const corp3 = makeCorp("acme-corp", "Acme Global", {
|
||||
environment: "test"
|
||||
});
|
||||
|
||||
const corps = [corp1, corp2, corp3];
|
||||
|
||||
test("finds enterprise by homophone", () => {
|
||||
const results = filterCorpsFuzzy(corps, "鞋子豪");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("xiezihao");
|
||||
});
|
||||
|
||||
test("finds enterprise by initials", () => {
|
||||
const results = filterCorpsFuzzy(corps, "xzh");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("xiezihao");
|
||||
});
|
||||
|
||||
test("finds enterprise by missing letter query", () => {
|
||||
const results = filterCorpsFuzzy(corps, "xieziha");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("xiezihao");
|
||||
});
|
||||
|
||||
test("finds enterprise by pinyin of Chinese name", () => {
|
||||
const results = filterCorpsFuzzy(corps, "qudao");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("ID01VAdCnJEdFd");
|
||||
});
|
||||
|
||||
test("finds enterprise by hose corpId or staffId", () => {
|
||||
const results = filterCorpsFuzzy(corps, "ID01VAdCnJEdFd");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("ID01VAdCnJEdFd");
|
||||
|
||||
const staffResults = filterCorpsFuzzy(corps, "staff-channel");
|
||||
expect(staffResults.length).toBe(1);
|
||||
expect(staffResults[0]!.id).toBe("ID01VAdCnJEdFd");
|
||||
});
|
||||
|
||||
test("strict mode filtering excludes fuzzy homophone matches", () => {
|
||||
const fuzzyRes = filterCorpsFuzzy(corps, "鞋子豪", { strict: false });
|
||||
expect(fuzzyRes.length).toBe(1);
|
||||
|
||||
const strictRes = filterCorpsFuzzy(corps, "鞋子豪", { strict: true });
|
||||
expect(strictRes.length).toBe(0);
|
||||
|
||||
const strictExact = filterCorpsFuzzy(corps, "谢子豪", { strict: true });
|
||||
expect(strictExact.length).toBe(1);
|
||||
});
|
||||
|
||||
test("ranks exact match higher than fuzzy matches", () => {
|
||||
const cExact = makeCorp("test-qudao", "渠道");
|
||||
const cFuzzy = makeCorp("test-other", "渠到另外一家");
|
||||
const ranked = filterCorpsFuzzy([cFuzzy, cExact], "渠道");
|
||||
expect(ranked[0]!.id).toBe("test-qudao");
|
||||
});
|
||||
|
||||
test("finds a compact enterprise name inside a longer Chinese query", () => {
|
||||
const compactName = makeCorp("corp-yuan-ce", "园测信息科技股份有限公司");
|
||||
const unrelated = makeCorp("corp-other", "南京测绘");
|
||||
const results = filterCorpsFuzzy([unrelated, compactName], "苏州园区测绘");
|
||||
|
||||
expect(results[0]!.id).toBe("corp-yuan-ce");
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("keeps strict search limited to exact substrings", () => {
|
||||
const compactName = makeCorp("corp-yuan-ce", "园测信息科技股份有限公司");
|
||||
const results = filterCorpsFuzzy([compactName], "苏州园区测绘", { strict: true });
|
||||
|
||||
expect(results).toEqual([]);
|
||||
});
|
||||
|
||||
test("matches Chinese name and industry words despite a contextual name typo", () => {
|
||||
const target = makeCorp("corp-yutai", "钰泰半导体股份有限公司");
|
||||
const sameIndustry = makeCorp("corp-other", "华芯半导体股份有限公司");
|
||||
for (const query of ["瑞泰半导体", "瑞泰 半导体", "半导体 瑞泰", "钰泰 半导体"]) {
|
||||
expect(filterCorpsFuzzy([sameIndustry, target], query).map((corp) => corp.id))
|
||||
.toEqual([target.id]);
|
||||
}
|
||||
});
|
||||
|
||||
test("requires another matching word before tolerating a typo in a short Chinese name", () => {
|
||||
const target = makeCorp("corp-yutai", "钰泰半导体股份有限公司");
|
||||
expect(filterCorpsFuzzy([target], "瑞泰")).toEqual([]);
|
||||
expect(filterCorpsFuzzy([target], "瑞泰 半导体", { strict: true })).toEqual([]);
|
||||
expect(filterCorpsFuzzy([target], "钰泰半导体", { strict: true })).toEqual([target]);
|
||||
});
|
||||
|
||||
test("breaks relevance ties by recent usage", () => {
|
||||
const a = makeCorp("corp-a", "匹配企业甲");
|
||||
const b = makeCorp("corp-b", "匹配企业乙");
|
||||
// Both names prefix-match at the same score; higher usage wins even against
|
||||
// input order and zh-CN name collation (甲 < 乙 alphabetically).
|
||||
const usage = new Map([["corp-a", 1], ["corp-b", 5]]);
|
||||
const results = filterCorpsFuzzy([a, b], "匹配企业", {}, usage);
|
||||
expect(results.map((corp) => corp.id)).toEqual(["corp-b", "corp-a"]);
|
||||
});
|
||||
|
||||
test("usage never outranks a better match", () => {
|
||||
const weak = makeCorp("corp-weak", "匹配企业甲");
|
||||
const strong = makeCorp("corp-strong", "匹配企业");
|
||||
const usage = new Map([["corp-weak", 99]]);
|
||||
const results = filterCorpsFuzzy([weak, strong], "匹配企业", {}, usage);
|
||||
expect(results[0]!.id).toBe("corp-strong");
|
||||
});
|
||||
|
||||
test("falls back to name and id order when usage is absent", () => {
|
||||
const second = makeCorp("corp-b", "匹配企业乙");
|
||||
const first = makeCorp("corp-a", "匹配企业甲");
|
||||
const results = filterCorpsFuzzy([second, first], "匹配企业");
|
||||
expect(results.map((corp) => corp.id)).toEqual(["corp-a", "corp-b"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import { matchCorp } from "./corp.js";
|
||||
import type { FuzzyMatchOptions } from "./types.js";
|
||||
|
||||
/**
|
||||
* Once a strong candidate exists, suppress weak token-only suggestions. This
|
||||
* keeps a query such as "苏州园区测绘" focused on the compact-name match
|
||||
* instead of also returning every enterprise that merely contains "测绘".
|
||||
*/
|
||||
function suppressWeakMatches(scored: Array<{ corp: CorpConfig; score: number }>): CorpConfig[] {
|
||||
const strongMatches = scored.filter((item) => item.score >= 0.8);
|
||||
return (strongMatches.length > 0 ? strongMatches : scored).map((item) => item.corp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters a list of enterprises using soft fuzzy search (or strict search if requested),
|
||||
* and automatically sorts the matching results from highest relevance to lowest.
|
||||
*
|
||||
* `usageScores` (optional, from `getRecentCorpUsageScores`) only breaks ties among
|
||||
* equally-relevant results — recent usage can lift a corp within a score band but
|
||||
* never above a better match.
|
||||
*/
|
||||
export function filterCorpsFuzzy(
|
||||
corps: CorpConfig[],
|
||||
query: string,
|
||||
options: FuzzyMatchOptions = {},
|
||||
usageScores?: ReadonlyMap<string, number>
|
||||
): CorpConfig[] {
|
||||
const trimmed = query.trim();
|
||||
if (!trimmed) return corps;
|
||||
|
||||
const scored: Array<{ corp: CorpConfig; score: number }> = [];
|
||||
|
||||
for (const corp of corps) {
|
||||
const res = matchCorp(corp, trimmed, options);
|
||||
if (res.matched) {
|
||||
scored.push({ corp, score: res.score });
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by match score descending (highest confidence first); relevance ties
|
||||
// fall back to recent usage, then name, then id for stable ordering.
|
||||
scored.sort((a, b) => {
|
||||
if (a.score !== b.score) return b.score - a.score;
|
||||
const usageA = usageScores?.get(a.corp.id) ?? 0;
|
||||
const usageB = usageScores?.get(b.corp.id) ?? 0;
|
||||
if (usageA !== usageB) return usageB - usageA;
|
||||
const byName = (a.corp.name ?? a.corp.id).localeCompare(b.corp.name ?? b.corp.id, "zh-CN");
|
||||
if (byName !== 0) return byName;
|
||||
return a.corp.id.localeCompare(b.corp.id);
|
||||
});
|
||||
|
||||
return suppressWeakMatches(scored);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Chinese query segmentation: word-level via Intl.Segmenter (with adjacent
|
||||
// single-character run merging for uncommon enterprise names) and term-level
|
||||
// via overlapping two-character windows.
|
||||
|
||||
let wordSegmenter: Intl.Segmenter | undefined;
|
||||
|
||||
// The same query string is segmented once per corp × field without memoization;
|
||||
// cache by raw input (bounded like the pinyin cache).
|
||||
const wordsCache = new Map<string, string[]>();
|
||||
const termsCache = new Map<string, string[]>();
|
||||
const SEGMENT_CACHE_LIMIT = 64;
|
||||
|
||||
function cached(key: string, cache: Map<string, string[]>, compute: () => string[]): string[] {
|
||||
const hit = cache.get(key);
|
||||
if (hit !== undefined) return hit;
|
||||
const value = compute();
|
||||
if (cache.size >= SEGMENT_CACHE_LIMIT) cache.clear();
|
||||
cache.set(key, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function searchTerms(value: string): string[] {
|
||||
return cached(value, termsCache, () => {
|
||||
const normalized = value.normalize("NFKC").trim().toLowerCase();
|
||||
const chunks = normalized.match(/[\u4e00-\u9fa5]+|[a-z0-9]+/g) ?? [];
|
||||
return chunks.flatMap((chunk) => {
|
||||
if (!/[\u4e00-\u9fa5]/.test(chunk)) return [chunk];
|
||||
if (chunk.length <= 2) return [chunk];
|
||||
|
||||
const terms: string[] = [];
|
||||
for (let index = 0; index < chunk.length - 1; index += 1) {
|
||||
terms.push(chunk.slice(index, index + 2));
|
||||
}
|
||||
return terms;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function searchWords(value: string): string[] {
|
||||
return cached(value, wordsCache, () => {
|
||||
wordSegmenter ??= new Intl.Segmenter("zh", { granularity: "word" });
|
||||
const words: string[] = [];
|
||||
let nameChars = "";
|
||||
const flushName = () => {
|
||||
if (nameChars) words.push(nameChars);
|
||||
nameChars = "";
|
||||
};
|
||||
|
||||
for (const part of wordSegmenter.segment(value.normalize("NFKC").trim().toLowerCase())) {
|
||||
// Uncommon enterprise names are often segmented into individual characters.
|
||||
if (part.isWordLike && /^[\u4e00-\u9fa5]$/.test(part.segment)) {
|
||||
nameChars += part.segment;
|
||||
} else {
|
||||
flushName();
|
||||
if (part.isWordLike) words.push(part.segment);
|
||||
}
|
||||
}
|
||||
flushName();
|
||||
return words;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { minSubstringLevenshtein } from "./distance.js";
|
||||
import { fuzzyMatchString } from "./engine.js";
|
||||
import { searchTerms, searchWords } from "./segment.js";
|
||||
import type { MatchScoreResult } from "./types.js";
|
||||
|
||||
function noMatch(): MatchScoreResult {
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
/** Word-level pass: every segmented word matches the target (one typo tolerated via context). */
|
||||
function matchQueryWords(queryWords: string[], target: string): MatchScoreResult | null {
|
||||
if (queryWords.length < 2) return null;
|
||||
|
||||
const wordMatches = queryWords.map((word) => fuzzyMatchString(word, target).matched);
|
||||
if (wordMatches.filter(Boolean).length < queryWords.length - 1) return null;
|
||||
|
||||
const allWordsMatch = queryWords.every((word, index) => wordMatches[index] || (
|
||||
// A second matching word supplies context for a typo in a two-character
|
||||
// name, e.g. "瑞泰 半导体" -> "钰泰半导体". Single-word searches stay conservative.
|
||||
/^[\u4e00-\u9fa5]{2}$/.test(word) && minSubstringLevenshtein(word, target) <= 1
|
||||
));
|
||||
if (!allWordsMatch) return null;
|
||||
|
||||
return { matched: true, score: 0.76, reason: "tokens" };
|
||||
}
|
||||
|
||||
/** Term-coverage pass: overlapping two-character terms of the query hit the target. */
|
||||
function matchQueryTerms(
|
||||
query: string,
|
||||
queryWordCount: number,
|
||||
target: string
|
||||
): MatchScoreResult | null {
|
||||
const queryTerms = searchTerms(query);
|
||||
if (queryTerms.length < 2) return null;
|
||||
|
||||
const matchedTerms = queryTerms.filter((term) => fuzzyMatchString(term, target).matched);
|
||||
if (matchedTerms.length === 0) return null;
|
||||
|
||||
const coverage = matchedTerms.length / queryTerms.length;
|
||||
return {
|
||||
matched: true,
|
||||
score: queryWordCount >= 2 ? Math.min(0.64, 0.56 + coverage * 0.2) : 0.56 + coverage * 0.2,
|
||||
reason: "tokens"
|
||||
};
|
||||
}
|
||||
|
||||
export function matchTokenizedQuery(query: string, target: string): MatchScoreResult {
|
||||
if (!/[\u4e00-\u9fa5]/.test(query)) {
|
||||
return noMatch();
|
||||
}
|
||||
|
||||
const queryWords = searchWords(query);
|
||||
return matchQueryWords(queryWords, target) ?? matchQueryTerms(query, queryWords.length, target) ?? noMatch();
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
export interface FuzzyMatchOptions {
|
||||
/**
|
||||
* If true, disables fuzzy/soft matching and requires exact substring matching.
|
||||
* Defaults to false (soft search by default).
|
||||
*/
|
||||
strict?: boolean;
|
||||
|
||||
/**
|
||||
* Maximum edit distance allowed for typo / missing letter tolerance.
|
||||
* Defaults based on query length:
|
||||
* - length <= 2: 0 (no fuzzy edits)
|
||||
* - length 3..5: 1 (missing 1 letter or 1 typo)
|
||||
* - length >= 6: 2 (missing 1-2 letters)
|
||||
*/
|
||||
maxDistance?: number;
|
||||
}
|
||||
|
||||
export type MatchReason =
|
||||
| "exact"
|
||||
| "substring"
|
||||
| "initials"
|
||||
| "pinyin"
|
||||
| "fuzzy_pinyin"
|
||||
| "levenshtein"
|
||||
| "subsequence"
|
||||
| "tokens"
|
||||
| "abbreviation"
|
||||
| "none";
|
||||
|
||||
export interface MatchScoreResult {
|
||||
matched: boolean;
|
||||
score: number;
|
||||
reason: MatchReason;
|
||||
}
|
||||
@@ -18,10 +18,11 @@ import file14 from "../../skills/seal-use/references/first-time-user.md" with {
|
||||
import file15 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" };
|
||||
import file16 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" };
|
||||
import file17 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" };
|
||||
import file18 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
|
||||
import file19 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
|
||||
import file20 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
|
||||
import file21 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
|
||||
import file18 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" };
|
||||
import file19 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
|
||||
import file20 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
|
||||
import file21 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
|
||||
import file22 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
||||
"SKILL.md": file0,
|
||||
@@ -36,10 +37,11 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
||||
"references/hose-enterprise-auth.md": file15,
|
||||
"references/hose-enterprise-deploy.md": file16,
|
||||
"references/hose-enterprise-init.md": file17,
|
||||
"references/rule-lightweight.md": file18,
|
||||
"references/rule-lint.md": file19,
|
||||
"references/staging-simulation-workflow.md": file20,
|
||||
"references/webhook-resource-pack.md": file21,
|
||||
"references/langfuse-trace.md": file18,
|
||||
"references/rule-lightweight.md": file19,
|
||||
"references/rule-lint.md": file20,
|
||||
"references/staging-simulation-workflow.md": file21,
|
||||
"references/webhook-resource-pack.md": file22,
|
||||
};
|
||||
|
||||
export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {
|
||||
@@ -70,6 +72,7 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
|
||||
"references/hose-enterprise-auth.md",
|
||||
"references/hose-enterprise-deploy.md",
|
||||
"references/hose-enterprise-init.md",
|
||||
"references/langfuse-trace.md",
|
||||
"references/rule-lightweight.md",
|
||||
"references/rule-lint.md",
|
||||
"references/staging-simulation-workflow.md",
|
||||
|
||||
@@ -15,6 +15,7 @@ export function redactSensitiveText(value: string): string {
|
||||
return value
|
||||
.replace(/([?&](?:accessToken|token|returnToken|appSecurity|signKey|secret)=)[^&\s]+/gi, "$1<redacted>")
|
||||
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>")
|
||||
.replace(/(Basic\s+)[A-Za-z0-9+/=]+/gi, "$1<redacted>")
|
||||
.replace(
|
||||
/("(?:appSecurity|password|secret|signKey|closeToken|refreshToken|accessToken|authorization)"\s*:\s*")[^"]*(")/gi,
|
||||
"$1<redacted>$2"
|
||||
|
||||
@@ -1,242 +0,0 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import {
|
||||
filterCorpsFuzzy,
|
||||
fuzzyMatchString,
|
||||
levenshteinDistance,
|
||||
minSubstringLevenshtein,
|
||||
normalizeFuzzyPinyin
|
||||
} from "./fuzzy.js";
|
||||
|
||||
function makeCorp(id: string, name: string, overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
environment: "production",
|
||||
seal: {
|
||||
tenantSlug: `${id}-slug`,
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
||||
}
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: `${id}-token`,
|
||||
sealUrl: `https://${id}.seal.test`,
|
||||
expiresIn: 3600,
|
||||
staffId: `staff-${id}`
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300
|
||||
},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe("fuzzy search utilities", () => {
|
||||
describe("levenshteinDistance", () => {
|
||||
test("calculates distance correctly", () => {
|
||||
expect(levenshteinDistance("", "")).toBe(0);
|
||||
expect(levenshteinDistance("abc", "abc")).toBe(0);
|
||||
expect(levenshteinDistance("abc", "ab")).toBe(1);
|
||||
expect(levenshteinDistance("abc", "abcd")).toBe(1);
|
||||
expect(levenshteinDistance("kitten", "sitting")).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("minSubstringLevenshtein", () => {
|
||||
test("detects exact substring with distance 0", () => {
|
||||
expect(minSubstringLevenshtein("abc", "xyzabcdef")).toBe(0);
|
||||
});
|
||||
|
||||
test("detects missing letter with distance 1", () => {
|
||||
expect(minSubstringLevenshtein("acm", "acme corp")).toBe(0); // acm is substring of acme
|
||||
expect(minSubstringLevenshtein("xiezihao", "xieziha")).toBe(1); // target missing 'o'
|
||||
expect(minSubstringLevenshtein("xiezhao", "xiezihao")).toBe(1); // query missing 'i'
|
||||
});
|
||||
|
||||
test("detects single substitution typo with distance 1", () => {
|
||||
expect(minSubstringLevenshtein("xiezhao", "xiezihao")).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeFuzzyPinyin", () => {
|
||||
test("normalizes retroflex to flat consonants", () => {
|
||||
expect(normalizeFuzzyPinyin("张")).toBe(normalizeFuzzyPinyin("詹")); // zhang -> zhang/zhan -> zan
|
||||
expect(normalizeFuzzyPinyin("超")).toContain("cao");
|
||||
expect(normalizeFuzzyPinyin("沙")).toContain("sa");
|
||||
});
|
||||
|
||||
test("normalizes front and back nasals", () => {
|
||||
expect(normalizeFuzzyPinyin("陈")).toBe(normalizeFuzzyPinyin("程")); // chen / cheng -> cen
|
||||
expect(normalizeFuzzyPinyin("金")).toBe(normalizeFuzzyPinyin("京")); // jin / jing -> jin
|
||||
});
|
||||
|
||||
test("normalizes homophones to identical representations", () => {
|
||||
expect(normalizeFuzzyPinyin("谢子豪")).toBe(normalizeFuzzyPinyin("鞋子豪"));
|
||||
expect(normalizeFuzzyPinyin("渠道")).toBe(normalizeFuzzyPinyin("渠到"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("fuzzyMatchString", () => {
|
||||
test("exact match", () => {
|
||||
const res = fuzzyMatchString("谢子豪", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("exact");
|
||||
expect(res.score).toBe(1.0);
|
||||
});
|
||||
|
||||
test("substring match", () => {
|
||||
const res = fuzzyMatchString("谢子", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("substring");
|
||||
expect(res.score).toBe(0.95);
|
||||
});
|
||||
|
||||
test("initials match (简拼)", () => {
|
||||
const res = fuzzyMatchString("xzh", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("initials");
|
||||
expect(res.score).toBe(0.9);
|
||||
});
|
||||
|
||||
test("pinyin match (全拼)", () => {
|
||||
const res = fuzzyMatchString("xiezihao", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("pinyin");
|
||||
});
|
||||
|
||||
test("homophones (同音字)", () => {
|
||||
const res1 = fuzzyMatchString("鞋子豪", "谢子豪");
|
||||
expect(res1.matched).toBe(true);
|
||||
expect(res1.reason).toBe("fuzzy_pinyin");
|
||||
|
||||
const res2 = fuzzyMatchString("渠到", "渠道AI演示环境");
|
||||
expect(res2.matched).toBe(true);
|
||||
expect(res2.reason).toBe("fuzzy_pinyin");
|
||||
});
|
||||
|
||||
test("front/back nasals & flat/retroflex (不区分前后鼻音和平翘舌)", () => {
|
||||
const res1 = fuzzyMatchString("詹三", "张三");
|
||||
expect(res1.matched).toBe(true);
|
||||
|
||||
const res2 = fuzzyMatchString("谢自豪", "谢子豪");
|
||||
expect(res2.matched).toBe(true);
|
||||
});
|
||||
|
||||
test("missing 1 letter or typo tolerance (缺失字母或轻微拼写错误)", () => {
|
||||
const res1 = fuzzyMatchString("xieziha", "谢子豪");
|
||||
expect(res1.matched).toBe(true);
|
||||
|
||||
const res2 = fuzzyMatchString("xiezhao", "谢子豪");
|
||||
expect(res2.matched).toBe(true);
|
||||
|
||||
const res3 = fuzzyMatchString("acme", "acm corp");
|
||||
expect(res3.matched).toBe(true);
|
||||
expect(res3.reason).toBe("levenshtein");
|
||||
});
|
||||
|
||||
test("strict mode rejects fuzzy / homophone / typo matches", () => {
|
||||
expect(fuzzyMatchString("鞋子豪", "谢子豪", { strict: true }).matched).toBe(false);
|
||||
expect(fuzzyMatchString("xzh", "谢子豪", { strict: true }).matched).toBe(false);
|
||||
expect(fuzzyMatchString("xieziha", "谢子豪", { strict: true }).matched).toBe(false);
|
||||
|
||||
// But exact substring is allowed in strict mode
|
||||
expect(fuzzyMatchString("谢子", "谢子豪", { strict: true }).matched).toBe(true);
|
||||
expect(fuzzyMatchString("谢子豪", "谢子豪", { strict: true }).matched).toBe(true);
|
||||
});
|
||||
|
||||
test("rejects completely unrelated terms", () => {
|
||||
expect(fuzzyMatchString("alibaba", "谢子豪").matched).toBe(false);
|
||||
expect(fuzzyMatchString("tencent", "ID01VAdCnJEdFd").matched).toBe(false);
|
||||
expect(fuzzyMatchString("xyz", "渠道环境").matched).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterCorpsFuzzy", () => {
|
||||
const corp1 = makeCorp("xiezihao", "谢子豪", {
|
||||
testCorpId: "test-xzh"
|
||||
});
|
||||
const corp2 = makeCorp("ID01VAdCnJEdFd", "渠道AI演示环境", {
|
||||
source: {
|
||||
type: "hose",
|
||||
corpId: "ID01VAdCnJEdFd",
|
||||
staffId: "staff-channel",
|
||||
domain: "https://app.ekuaibao.com"
|
||||
} as any
|
||||
});
|
||||
const corp3 = makeCorp("acme-corp", "Acme Global", {
|
||||
environment: "test"
|
||||
});
|
||||
|
||||
const corps = [corp1, corp2, corp3];
|
||||
|
||||
test("finds enterprise by homophone", () => {
|
||||
const results = filterCorpsFuzzy(corps, "鞋子豪");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("xiezihao");
|
||||
});
|
||||
|
||||
test("finds enterprise by initials", () => {
|
||||
const results = filterCorpsFuzzy(corps, "xzh");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("xiezihao");
|
||||
});
|
||||
|
||||
test("finds enterprise by missing letter query", () => {
|
||||
const results = filterCorpsFuzzy(corps, "xieziha");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("xiezihao");
|
||||
});
|
||||
|
||||
test("finds enterprise by pinyin of Chinese name", () => {
|
||||
const results = filterCorpsFuzzy(corps, "qudao");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("ID01VAdCnJEdFd");
|
||||
});
|
||||
|
||||
test("finds enterprise by hose corpId or staffId", () => {
|
||||
const results = filterCorpsFuzzy(corps, "ID01VAdCnJEdFd");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("ID01VAdCnJEdFd");
|
||||
|
||||
const staffResults = filterCorpsFuzzy(corps, "staff-channel");
|
||||
expect(staffResults.length).toBe(1);
|
||||
expect(staffResults[0]!.id).toBe("ID01VAdCnJEdFd");
|
||||
});
|
||||
|
||||
test("strict mode filtering excludes fuzzy homophone matches", () => {
|
||||
const fuzzyRes = filterCorpsFuzzy(corps, "鞋子豪", { strict: false });
|
||||
expect(fuzzyRes.length).toBe(1);
|
||||
|
||||
const strictRes = filterCorpsFuzzy(corps, "鞋子豪", { strict: true });
|
||||
expect(strictRes.length).toBe(0);
|
||||
|
||||
const strictExact = filterCorpsFuzzy(corps, "谢子豪", { strict: true });
|
||||
expect(strictExact.length).toBe(1);
|
||||
});
|
||||
|
||||
test("ranks exact match higher than fuzzy matches", () => {
|
||||
const cExact = makeCorp("test-qudao", "渠道");
|
||||
const cFuzzy = makeCorp("test-other", "渠到另外一家");
|
||||
const ranked = filterCorpsFuzzy([cFuzzy, cExact], "渠道");
|
||||
expect(ranked[0]!.id).toBe("test-qudao");
|
||||
});
|
||||
|
||||
test("finds a compact enterprise name inside a longer Chinese query", () => {
|
||||
const compactName = makeCorp("corp-yuan-ce", "园测信息科技股份有限公司");
|
||||
const unrelated = makeCorp("corp-other", "南京测绘");
|
||||
const results = filterCorpsFuzzy([unrelated, compactName], "苏州园区测绘");
|
||||
|
||||
expect(results[0]!.id).toBe("corp-yuan-ce");
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("keeps strict search limited to exact substrings", () => {
|
||||
const compactName = makeCorp("corp-yuan-ce", "园测信息科技股份有限公司");
|
||||
const results = filterCorpsFuzzy([compactName], "苏州园区测绘", { strict: true });
|
||||
|
||||
expect(results).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,400 +0,0 @@
|
||||
import { pinyin, match as pinyinMatch } from "pinyin-pro";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
|
||||
export interface FuzzyMatchOptions {
|
||||
/**
|
||||
* If true, disables fuzzy/soft matching and requires exact substring matching.
|
||||
* Defaults to false (soft search by default).
|
||||
*/
|
||||
strict?: boolean;
|
||||
|
||||
/**
|
||||
* Maximum edit distance allowed for typo / missing letter tolerance.
|
||||
* Defaults based on query length:
|
||||
* - length <= 2: 0 (no fuzzy edits)
|
||||
* - length 3..5: 1 (missing 1 letter or 1 typo)
|
||||
* - length >= 6: 2 (missing 1-2 letters)
|
||||
*/
|
||||
maxDistance?: number;
|
||||
}
|
||||
|
||||
export type MatchReason =
|
||||
| "exact"
|
||||
| "substring"
|
||||
| "initials"
|
||||
| "pinyin"
|
||||
| "fuzzy_pinyin"
|
||||
| "levenshtein"
|
||||
| "subsequence"
|
||||
| "tokens"
|
||||
| "abbreviation"
|
||||
| "none";
|
||||
|
||||
export interface MatchScoreResult {
|
||||
matched: boolean;
|
||||
score: number;
|
||||
reason: MatchReason;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Levenshtein distance between two strings.
|
||||
*/
|
||||
export function levenshteinDistance(a: string, b: string): number {
|
||||
const m = a.length;
|
||||
const n = b.length;
|
||||
if (m === 0) return n;
|
||||
if (n === 0) return m;
|
||||
|
||||
let prevRow = Array.from({ length: n + 1 }, (_, j) => j);
|
||||
let currRow: number[] = Array.from({ length: n + 1 }, () => 0);
|
||||
|
||||
for (let i = 1; i <= m; i += 1) {
|
||||
currRow[0] = i;
|
||||
for (let j = 1; j <= n; j += 1) {
|
||||
if (a[i - 1] === b[j - 1]) {
|
||||
currRow[j] = prevRow[j - 1] ?? 0;
|
||||
} else {
|
||||
const sub = prevRow[j - 1] ?? 0;
|
||||
const ins = currRow[j - 1] ?? 0;
|
||||
const del = prevRow[j] ?? 0;
|
||||
currRow[j] = Math.min(sub, ins, del) + 1;
|
||||
}
|
||||
}
|
||||
const temp = prevRow;
|
||||
prevRow = currRow;
|
||||
currRow = temp;
|
||||
}
|
||||
return prevRow[n] ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the minimum Levenshtein distance between `query` and any sliding window substring in `target`.
|
||||
* Supports queries missing a letter, having an extra letter, or having an internal typo.
|
||||
*/
|
||||
export function minSubstringLevenshtein(query: string, target: string): number {
|
||||
if (!query || !target) return 999;
|
||||
if (target.includes(query)) return 0;
|
||||
|
||||
const qLen = query.length;
|
||||
if (target.length < qLen - 2) {
|
||||
return levenshteinDistance(query, target);
|
||||
}
|
||||
|
||||
let min = 999;
|
||||
const minWindow = Math.max(1, qLen - 2);
|
||||
const maxWindow = Math.min(target.length, qLen + 2);
|
||||
|
||||
for (let len = minWindow; len <= maxWindow; len += 1) {
|
||||
for (let i = 0; i <= target.length - len; i += 1) {
|
||||
const sub = target.slice(i, i + len);
|
||||
const dist = levenshteinDistance(query, sub);
|
||||
if (dist < min) min = dist;
|
||||
if (min === 0) return 0;
|
||||
}
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes Chinese text to toneless pinyin with fuzzy sound rules:
|
||||
* - Retroflex vs flat consonants: zh -> z, ch -> c, sh -> s
|
||||
* - Front vs back nasal sounds: ang -> an, eng -> en, ing -> in, iang -> ian, uang -> uan
|
||||
* - Strips non-alphanumeric whitespace
|
||||
*/
|
||||
export function normalizeFuzzyPinyin(str: string): string {
|
||||
if (!str) return "";
|
||||
const pyTokens = pinyin(str, { toneType: "none", type: "array" });
|
||||
return pyTokens
|
||||
.map((token) =>
|
||||
token
|
||||
.toLowerCase()
|
||||
.replace(/zh/g, "z")
|
||||
.replace(/ch/g, "c")
|
||||
.replace(/sh/g, "s")
|
||||
.replace(/iang/g, "ian")
|
||||
.replace(/uang/g, "uan")
|
||||
.replace(/ang/g, "an")
|
||||
.replace(/eng/g, "en")
|
||||
.replace(/ing/g, "in")
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if all characters of `query` appear in order inside `target` (subsequence).
|
||||
*/
|
||||
export function isSubsequence(query: string, target: string): boolean {
|
||||
if (!query || !target) return false;
|
||||
let qIdx = 0;
|
||||
for (let tIdx = 0; tIdx < target.length && qIdx < query.length; tIdx += 1) {
|
||||
if (query[qIdx] === target[tIdx]) {
|
||||
qIdx += 1;
|
||||
}
|
||||
}
|
||||
return qIdx === query.length;
|
||||
}
|
||||
|
||||
function searchTerms(value: string): string[] {
|
||||
const chunks = value.trim().toLowerCase().match(/[\u4e00-\u9fa5]+|[a-z0-9]+/g) ?? [];
|
||||
return chunks.flatMap((chunk) => {
|
||||
if (!/[\u4e00-\u9fa5]/.test(chunk)) return [chunk];
|
||||
if (chunk.length <= 2) return [chunk];
|
||||
|
||||
const terms: string[] = [];
|
||||
for (let index = 0; index < chunk.length - 1; index += 1) {
|
||||
terms.push(chunk.slice(index, index + 2));
|
||||
}
|
||||
return terms;
|
||||
});
|
||||
}
|
||||
|
||||
function matchTokenizedQuery(query: string, target: string): MatchScoreResult {
|
||||
if (!/[\u4e00-\u9fa5]/.test(query)) {
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
const queryTerms = searchTerms(query);
|
||||
if (queryTerms.length < 2) return { matched: false, score: 0, reason: "none" };
|
||||
|
||||
const matchedTerms = queryTerms.filter((term) => fuzzyMatchString(term, target).matched);
|
||||
if (matchedTerms.length > 0) {
|
||||
const coverage = matchedTerms.length / queryTerms.length;
|
||||
return {
|
||||
matched: true,
|
||||
score: 0.56 + coverage * 0.2,
|
||||
reason: "tokens"
|
||||
};
|
||||
}
|
||||
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Core fuzzy string match engine:
|
||||
* Evaluates match across exact, substring, initials, pinyin, homophone/fuzzy pinyin,
|
||||
* sliding-window edit distance (missing/typo tolerance), and character subsequence.
|
||||
*/
|
||||
export function fuzzyMatchString(
|
||||
query: string,
|
||||
target: string,
|
||||
options: FuzzyMatchOptions = {}
|
||||
): MatchScoreResult {
|
||||
const normQuery = query.trim().toLowerCase();
|
||||
const normTarget = target.trim().toLowerCase();
|
||||
|
||||
if (!normQuery || !normTarget) {
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
// 1. Exact match
|
||||
if (normTarget === normQuery) {
|
||||
return { matched: true, score: 1.0, reason: "exact" };
|
||||
}
|
||||
|
||||
// 2. Substring match
|
||||
if (normTarget.includes(normQuery)) {
|
||||
return { matched: true, score: 0.95, reason: "substring" };
|
||||
}
|
||||
|
||||
// If strict mode is requested, only exact or substring matches are accepted.
|
||||
if (options.strict) {
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
const targetHasChinese = /[\u4e00-\u9fa5]/.test(normTarget);
|
||||
const queryHasChinese = /[\u4e00-\u9fa5]/.test(normQuery);
|
||||
|
||||
// 3. Initials / Acronym match (e.g. "xzh" matches "谢子豪", "sc" matches "生产")
|
||||
if (targetHasChinese && normQuery.length >= 2) {
|
||||
const targetInitials = pinyin(normTarget, { pattern: "first", toneType: "none", type: "array" })
|
||||
.join("")
|
||||
.toLowerCase();
|
||||
if (targetInitials.includes(normQuery)) {
|
||||
return { matched: true, score: 0.9, reason: "initials" };
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Pinyin-pro built-in match (handles full/partial pinyin matching against Chinese targets)
|
||||
if (targetHasChinese) {
|
||||
try {
|
||||
const pm = pinyinMatch(normTarget, normQuery, { precision: "start" });
|
||||
if (pm && pm.length > 0) {
|
||||
return { matched: true, score: 0.88, reason: "pinyin" };
|
||||
}
|
||||
} catch {
|
||||
// ignore match errors if non-standard regex chars
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Fuzzy Pinyin & Homophones (同音字、前后鼻音、平翘舌音)
|
||||
let targetFuzzyPinyin = "";
|
||||
let queryFuzzyPinyin = "";
|
||||
if (targetHasChinese || queryHasChinese) {
|
||||
targetFuzzyPinyin = normalizeFuzzyPinyin(normTarget);
|
||||
queryFuzzyPinyin = normalizeFuzzyPinyin(normQuery);
|
||||
|
||||
if (queryFuzzyPinyin.length >= 2 && targetFuzzyPinyin.includes(queryFuzzyPinyin)) {
|
||||
return { matched: true, score: 0.85, reason: "fuzzy_pinyin" };
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Missing letter / Typo tolerance (Levenshtein Distance)
|
||||
// Determine allowed distance based on query length:
|
||||
// - <= 2: 0 (no fuzzy edits to prevent excessive false positives)
|
||||
// - 3..5: 1 (missing 1 letter or 1 typo)
|
||||
// - >= 6: 2 (missing 1-2 letters)
|
||||
const defaultMaxDist = normQuery.length <= 2 ? 0 : normQuery.length <= 5 ? 1 : 2;
|
||||
const maxAllowedDist = options.maxDistance ?? defaultMaxDist;
|
||||
|
||||
if (maxAllowedDist > 0) {
|
||||
// Check raw string distance
|
||||
const rawDist = minSubstringLevenshtein(normQuery, normTarget);
|
||||
if (rawDist <= maxAllowedDist) {
|
||||
return {
|
||||
matched: true,
|
||||
score: Math.max(0.6, 0.8 - rawDist * 0.1),
|
||||
reason: "levenshtein"
|
||||
};
|
||||
}
|
||||
|
||||
// Check fuzzy pinyin distance (e.g. pinyin with 1 missing letter)
|
||||
if (
|
||||
(targetHasChinese || queryHasChinese) &&
|
||||
queryFuzzyPinyin.length >= 3 &&
|
||||
targetFuzzyPinyin.length >= 3
|
||||
) {
|
||||
const pinyinDist = minSubstringLevenshtein(queryFuzzyPinyin, targetFuzzyPinyin);
|
||||
if (pinyinDist <= maxAllowedDist) {
|
||||
return {
|
||||
matched: true,
|
||||
score: Math.max(0.6, 0.78 - pinyinDist * 0.1),
|
||||
reason: "levenshtein"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Subsequence match (loose character order, min query length 3)
|
||||
if (normQuery.length >= 3) {
|
||||
if (
|
||||
isSubsequence(normQuery, normTarget) ||
|
||||
((targetHasChinese || queryHasChinese) && isSubsequence(queryFuzzyPinyin, targetFuzzyPinyin))
|
||||
) {
|
||||
return { matched: true, score: 0.65, reason: "subsequence" };
|
||||
}
|
||||
}
|
||||
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches an enterprise (`CorpConfig`) against a query across all its searchable fields,
|
||||
* returning the highest match score and reason.
|
||||
*/
|
||||
export function matchCorp(
|
||||
corp: CorpConfig,
|
||||
query: string,
|
||||
options: FuzzyMatchOptions = {}
|
||||
): MatchScoreResult {
|
||||
const fields: Array<{ text: string | undefined; weight: number }> = [
|
||||
{ text: corp.name, weight: 1.2 },
|
||||
{ text: corp.id, weight: 1.1 },
|
||||
{ text: corp.source.staffId, weight: 1.0 },
|
||||
{ text: (corp.source as any).domain, weight: 1.0 },
|
||||
{ text: (corp.source as any).corpId, weight: 1.0 },
|
||||
{ text: corp.seal.tenantSlug, weight: 1.0 },
|
||||
{ text: (corp.source as any).tenantSlug, weight: 1.0 },
|
||||
{ text: (corp.source as any).tenantName, weight: 1.1 },
|
||||
{ text: corp.testCorpId, weight: 1.0 },
|
||||
{ text: corp.prodCorpId, weight: 1.0 },
|
||||
{ text: corp.environment ?? "production", weight: 0.8 },
|
||||
{ text: corp.source.type, weight: 0.8 },
|
||||
{ text: (corp.source as any).provider, weight: 0.8 }
|
||||
];
|
||||
|
||||
let bestScore = 0;
|
||||
let bestReason: MatchReason = "none";
|
||||
|
||||
for (const field of fields) {
|
||||
if (!field.text) continue;
|
||||
const res = fuzzyMatchString(query, field.text, options);
|
||||
if (res.matched) {
|
||||
const weightedScore = res.score * field.weight;
|
||||
if (weightedScore > bestScore) {
|
||||
bestScore = weightedScore;
|
||||
bestReason = res.reason;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// When a long Chinese query contains a compact enterprise name in order (for
|
||||
// example, "苏州园区测绘" contains the leading "园测" of "园测信息科技股份有限公司"),
|
||||
// retain that candidate as a lower-confidence abbreviation match. This is
|
||||
// deliberately below exact/substring/pinyin matches and disabled in strict mode.
|
||||
if (!options.strict) {
|
||||
const queryChinese = query.trim().match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
|
||||
if (queryChinese.length >= 3) {
|
||||
for (const field of fields) {
|
||||
if (!field.text) continue;
|
||||
const targetChinese = field.text.match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
|
||||
const prefix = targetChinese.slice(0, 2);
|
||||
if (prefix.length < 2 || !isSubsequence(prefix, queryChinese)) continue;
|
||||
|
||||
const weightedScore = 0.74 * field.weight;
|
||||
if (weightedScore > bestScore) {
|
||||
bestScore = weightedScore;
|
||||
bestReason = "abbreviation";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const field of fields) {
|
||||
if (!field.text) continue;
|
||||
const res = matchTokenizedQuery(query, field.text);
|
||||
if (res.matched) {
|
||||
const weightedScore = res.score * field.weight;
|
||||
if (weightedScore > bestScore) {
|
||||
bestScore = weightedScore;
|
||||
bestReason = res.reason;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
matched: bestScore > 0,
|
||||
score: bestScore,
|
||||
reason: bestReason
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters a list of enterprises using soft fuzzy search (or strict search if requested),
|
||||
* and automatically sorts the matching results from highest relevance to lowest.
|
||||
*/
|
||||
export function filterCorpsFuzzy(
|
||||
corps: CorpConfig[],
|
||||
query: string,
|
||||
options: FuzzyMatchOptions = {}
|
||||
): CorpConfig[] {
|
||||
const trimmed = query.trim();
|
||||
if (!trimmed) return corps;
|
||||
|
||||
const scored: Array<{ corp: CorpConfig; score: number }> = [];
|
||||
|
||||
for (const corp of corps) {
|
||||
const res = matchCorp(corp, trimmed, options);
|
||||
if (res.matched) {
|
||||
scored.push({ corp, score: res.score });
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by match score descending (highest confidence first)
|
||||
scored.sort((a, b) => b.score - a.score);
|
||||
|
||||
// Once a strong candidate exists, suppress weak token-only suggestions. This
|
||||
// keeps a query such as "苏州园区测绘" focused on the compact-name match
|
||||
// instead of also returning every enterprise that merely contains "测绘".
|
||||
const strongMatches = scored.filter((item) => item.score >= 0.8);
|
||||
return (strongMatches.length > 0 ? strongMatches : scored).map((item) => item.corp);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { LangfuseClient } from "./client.js";
|
||||
import type { LangfuseProject, LangfuseSession, LangfuseTraceSummary } from "./types.js";
|
||||
|
||||
/**
|
||||
* Langfuse Public API surface used by this domain. Deliberately tiny: every
|
||||
* method maps to a single `GET`, mirroring the read-only client contract.
|
||||
*/
|
||||
export class LangfuseApi {
|
||||
constructor(private readonly client: LangfuseClient) {}
|
||||
|
||||
async getProject(): Promise<LangfuseProject[]> {
|
||||
const response = await this.client.getJson<{ data?: LangfuseProject[] }>(
|
||||
"/api/public/projects"
|
||||
);
|
||||
return response.data ?? [];
|
||||
}
|
||||
|
||||
async getTrace(traceId: string, params: { fields?: string } = {}): Promise<LangfuseTraceSummary> {
|
||||
return await this.client.getJson<LangfuseTraceSummary>(
|
||||
`/api/public/traces/${encodeURIComponent(traceId)}`,
|
||||
{ fields: params.fields }
|
||||
);
|
||||
}
|
||||
|
||||
async getSession(sessionId: string): Promise<LangfuseSession> {
|
||||
return await this.client.getJson<LangfuseSession>(
|
||||
`/api/public/sessions/${encodeURIComponent(sessionId)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import type { CachedTrace, LangfuseTraceSummary } from "./types.js";
|
||||
|
||||
const CACHE_VERSION = 1;
|
||||
const CACHE_ROOT = ".cache/langfuse/traces";
|
||||
// Single-project domain: the cache segment stays "default", which keeps this
|
||||
// cache byte-compatible with `langfuse-home` (same cwd-relative layout), so the
|
||||
// two tools share cached traces instead of re-fetching them.
|
||||
const PROJECT_SEGMENT = "default";
|
||||
|
||||
export type TraceCacheProject = {
|
||||
baseUrl: string;
|
||||
projectId?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Single-trace JSON cache keyed by traceId, written under `<cwd>/.cache`
|
||||
* (gitignored). Holds the FULL raw trace (including observation IO) so outline,
|
||||
* search, observation and flow tools can answer without touching the network.
|
||||
* No TTL: `cache-refresh` overwrites explicitly.
|
||||
*/
|
||||
export class TraceCache {
|
||||
constructor(private readonly project: TraceCacheProject) {}
|
||||
|
||||
path(traceId: string): string {
|
||||
return resolve(
|
||||
process.cwd(),
|
||||
CACHE_ROOT,
|
||||
PROJECT_SEGMENT,
|
||||
`${sanitizeSegment(traceId)}.json`
|
||||
);
|
||||
}
|
||||
|
||||
async exists(traceId: string): Promise<boolean> {
|
||||
try {
|
||||
await stat(this.path(traceId));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async read(traceId: string): Promise<CachedTrace | undefined> {
|
||||
try {
|
||||
const content = await readFile(this.path(traceId), "utf8");
|
||||
const parsed = JSON.parse(content) as CachedTrace;
|
||||
return parsed.cacheVersion === CACHE_VERSION ? parsed : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async write(traceId: string, trace: LangfuseTraceSummary): Promise<CachedTrace> {
|
||||
const cached: CachedTrace = {
|
||||
cacheVersion: CACHE_VERSION,
|
||||
cachedAt: new Date().toISOString(),
|
||||
project: {
|
||||
key: PROJECT_SEGMENT,
|
||||
projectId: trace.projectId ?? this.project.projectId ?? "",
|
||||
baseUrl: this.project.baseUrl
|
||||
},
|
||||
trace
|
||||
};
|
||||
|
||||
const path = this.path(traceId);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, `${JSON.stringify(cached, null, 2)}\n`, "utf8");
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeSegment(value: string): string {
|
||||
return value.replace(/[^a-zA-Z0-9._-]/g, "_");
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
LANGFUSE_READ_ONLY_CAPABILITIES,
|
||||
findLangfuseCapability,
|
||||
langfuseCapabilities
|
||||
} from "./capabilities.js";
|
||||
|
||||
describe("langfuse capability registry", () => {
|
||||
test("every capability is classified read-only, exhaustively and without overlap", () => {
|
||||
const names = langfuseCapabilities.map((capability) => capability.name);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
expect([...LANGFUSE_READ_ONLY_CAPABILITIES].sort()).toEqual(names.slice().sort());
|
||||
});
|
||||
|
||||
test("every capability carries a description and a parameter schema", () => {
|
||||
for (const capability of langfuseCapabilities) {
|
||||
expect({ name: capability.name, described: capability.description.length > 0 }).toEqual({
|
||||
name: capability.name,
|
||||
described: true
|
||||
});
|
||||
expect(typeof capability.handler).toBe("function");
|
||||
expect(capability.parameters.safeParse({}).success).toBeTypeOf("boolean");
|
||||
}
|
||||
});
|
||||
|
||||
test("unknown capability names resolve to undefined", () => {
|
||||
expect(findLangfuseCapability("sealLangfuseDoesNotExist")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("required params gate before any handler runs", () => {
|
||||
expect(findLangfuseCapability("sealLangfuseTraceCacheRefresh")!.parameters.safeParse({}).success).toBe(false);
|
||||
expect(
|
||||
findLangfuseCapability("sealLangfuseTraceCacheRefresh")!.parameters.safeParse({ traceId: "t-1" }).success
|
||||
).toBe(true);
|
||||
expect(findLangfuseCapability("sealLangfuseTraceRuleFlowGet")!.parameters.safeParse({ traceId: "t-1" }).success).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test("ranges and refinements reject out-of-contract values", () => {
|
||||
const outline = findLangfuseCapability("sealLangfuseTraceOutlineGet")!.parameters;
|
||||
expect(outline.safeParse({ traceId: "t-1", maxPreviewChars: 10 }).success).toBe(false);
|
||||
expect(outline.safeParse({ traceId: "t-1", maxPreviewChars: 100 }).success).toBe(true);
|
||||
expect(outline.safeParse({ traceId: "t-1", maxPreviewChars: 9_999 }).success).toBe(false);
|
||||
|
||||
const search = findLangfuseCapability("sealLangfuseTraceQrepSearch")!.parameters;
|
||||
expect(search.safeParse({ traceId: "t-1", query: "发票" }).success).toBe(true);
|
||||
expect(search.safeParse({ traceId: "t-1", maxResults: 0 }).success).toBe(false);
|
||||
expect(search.safeParse({ traceId: "t-1", query: ["a"], fields: ["bogus"] }).success).toBe(false);
|
||||
|
||||
const attachment = findLangfuseCapability("sealLangfuseAttachmentFlowGet")!.parameters;
|
||||
expect(attachment.safeParse({ traceId: "t-1" }).success).toBe(false);
|
||||
expect(attachment.safeParse({ traceId: "t-1", fileName: "a.pdf" }).success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,243 @@
|
||||
import { z } from "zod";
|
||||
import { resolveLangfuseConfig, type LangfuseConfig } from "./config.js";
|
||||
import { LangfuseService } from "./service.js";
|
||||
|
||||
/**
|
||||
* Registry of read-only Langfuse capabilities.
|
||||
*
|
||||
* Separate from `sealCapabilities` on purpose: these handlers need no Seal
|
||||
* tenant, no `CorpConfig` and no Seal HTTP client — they talk to Langfuse with
|
||||
* the compile-time injected key pair. They share the same shape (name /
|
||||
* description / Zod `parameters` / `handler`) so the CLI dispatch helper can
|
||||
* treat them uniformly.
|
||||
*
|
||||
* Naming keeps the `sealLangfuse*` prefix because these are internal registry
|
||||
* identifiers for dispatch and allow-lists; the MCP surface only ever exposes
|
||||
* the `seal_use` / `seal_use_write` gateway pair (see README "One registry,
|
||||
* two doors").
|
||||
*
|
||||
* Every entry is read-only by construction: the underlying `LangfuseClient`
|
||||
* issues `GET` requests only. `LANGFUSE_READ_ONLY_CAPABILITIES` lists the names
|
||||
* explicitly so a newly added capability fails `capabilities.test.ts` until it
|
||||
* is classified here.
|
||||
*/
|
||||
export const langfuseCapabilities = [
|
||||
{
|
||||
name: "sealLangfuseConnectionCheck",
|
||||
description: "检查内置 Langfuse 只读凭据的连通性,返回项目信息",
|
||||
parameters: z.object({}),
|
||||
handler: async (_params: Record<string, never>, service: LangfuseService) =>
|
||||
service.connectionCheck()
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseTraceCacheRefresh",
|
||||
description: "按 traceId 拉取完整 Langfuse trace 并写入本地缓存,供离线 outline/search 使用",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1)
|
||||
}),
|
||||
handler: async (params: { traceId: string }, service: LangfuseService) =>
|
||||
service.refreshTraceCache(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseTraceUrlGet",
|
||||
description: "构建单条 trace 的 Langfuse 后台直达链接(优先使用缓存中的 projectId)",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1)
|
||||
}),
|
||||
handler: async (params: { traceId: string }, service: LangfuseService) =>
|
||||
service.getTraceUrl(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseTraceOutlineGet",
|
||||
description: "读取缓存 trace 的紧凑大纲:观测树、体量、用量、成本与可选 IO 预览",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1),
|
||||
includeIoPreview: z.boolean().optional(),
|
||||
includeInput: z.boolean().optional(),
|
||||
includeOutput: z.boolean().optional(),
|
||||
full: z.boolean().optional(),
|
||||
maxPreviewChars: z.number().int().min(20).max(5_000).optional(),
|
||||
refreshIfMissing: z.boolean().optional()
|
||||
}),
|
||||
handler: async (
|
||||
params: {
|
||||
traceId: string;
|
||||
includeIoPreview?: boolean;
|
||||
includeInput?: boolean;
|
||||
includeOutput?: boolean;
|
||||
full?: boolean;
|
||||
maxPreviewChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
},
|
||||
service: LangfuseService
|
||||
) => service.getTraceOutline(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseTraceQrepSearch",
|
||||
description: "在单条缓存 trace 内做层级感知的关键词检索,返回带上下文的排序片段",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1),
|
||||
query: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]),
|
||||
sessionId: z.string().optional(),
|
||||
fields: z
|
||||
.array(z.enum(["name", "input", "output", "metadata", "userId", "sessionId"]))
|
||||
.optional(),
|
||||
observationTypes: z.array(z.string().min(1)).optional(),
|
||||
metadata: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional(),
|
||||
maxResults: z.number().int().min(1).max(30).optional(),
|
||||
contextChars: z.number().int().min(20).max(500).optional(),
|
||||
refreshIfMissing: z.boolean().optional()
|
||||
}),
|
||||
handler: async (
|
||||
params: {
|
||||
traceId: string;
|
||||
query: string | string[];
|
||||
sessionId?: string;
|
||||
fields?: Array<"name" | "input" | "output" | "metadata" | "userId" | "sessionId">;
|
||||
observationTypes?: string[];
|
||||
metadata?: Record<string, string | number | boolean>;
|
||||
maxResults?: number;
|
||||
contextChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
},
|
||||
service: LangfuseService
|
||||
) => service.searchTrace(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseObservationIoGet",
|
||||
description: "读取指定 observation 的聚焦 input/output/metadata,支持 jsonPath 定点取值",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1),
|
||||
observationId: z.string().min(1),
|
||||
fields: z.array(z.enum(["input", "output", "metadata"])).optional(),
|
||||
maxChars: z.number().int().min(100).max(500_000).optional(),
|
||||
full: z.boolean().optional(),
|
||||
jsonPath: z.string().optional(),
|
||||
path: z.string().optional(),
|
||||
refreshIfMissing: z.boolean().optional()
|
||||
}),
|
||||
handler: async (
|
||||
params: {
|
||||
traceId: string;
|
||||
observationId: string;
|
||||
fields?: Array<"input" | "output" | "metadata">;
|
||||
maxChars?: number;
|
||||
full?: boolean;
|
||||
jsonPath?: string;
|
||||
path?: string;
|
||||
refreshIfMissing?: boolean;
|
||||
},
|
||||
service: LangfuseService
|
||||
) => service.getObservationIo(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseSessionOutlineGet",
|
||||
description: "获取 Langfuse session 的紧凑 trace 摘要列表(不缓存整 session)",
|
||||
parameters: z.object({
|
||||
sessionId: z.string().min(1),
|
||||
traceLimit: z.number().int().min(1).max(200).optional()
|
||||
}),
|
||||
handler: async (params: { sessionId: string; traceLimit?: number }, service: LangfuseService) =>
|
||||
service.getSessionOutline(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseObservationsFind",
|
||||
description: "按名称/类型/metadata 键/是否含 IO 过滤缓存 trace 内的 observation,只返回摘要",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1),
|
||||
nameContains: z.string().optional(),
|
||||
type: z.string().optional(),
|
||||
metadataKey: z.string().optional(),
|
||||
hasInput: z.boolean().optional(),
|
||||
hasOutput: z.boolean().optional(),
|
||||
maxResults: z.number().int().min(1).max(200).optional(),
|
||||
refreshIfMissing: z.boolean().optional()
|
||||
}),
|
||||
handler: async (
|
||||
params: {
|
||||
traceId: string;
|
||||
nameContains?: string;
|
||||
type?: string;
|
||||
metadataKey?: string;
|
||||
hasInput?: boolean;
|
||||
hasOutput?: boolean;
|
||||
maxResults?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
},
|
||||
service: LangfuseService
|
||||
) => service.findObservations(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseAttachmentFlowGet",
|
||||
description: "在缓存 trace 中追踪附件文件 id/名称/提示词经解析与审核阶段的文本证据",
|
||||
parameters: z
|
||||
.object({
|
||||
traceId: z.string().min(1),
|
||||
fileId: z.string().optional(),
|
||||
fileName: z.string().optional(),
|
||||
contentHints: z.array(z.string().min(1)).optional(),
|
||||
contextChars: z.number().int().min(20).max(500).optional(),
|
||||
refreshIfMissing: z.boolean().optional()
|
||||
})
|
||||
.refine(
|
||||
(value) => Boolean(value.fileId || value.fileName || value.contentHints?.length),
|
||||
{ message: "Provide at least one of fileId, fileName, or contentHints" }
|
||||
),
|
||||
handler: async (
|
||||
params: {
|
||||
traceId: string;
|
||||
fileId?: string;
|
||||
fileName?: string;
|
||||
contentHints?: string[];
|
||||
contextChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
},
|
||||
service: LangfuseService
|
||||
) => service.getAttachmentFlow(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseTraceRuleFlowGet",
|
||||
description: "在缓存 trace 中追踪一条规则经规则匹配、文档解析、最终审核阶段的文本证据",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1),
|
||||
rule: z.string().min(1),
|
||||
ruleHints: z.array(z.string().min(1)).optional(),
|
||||
contextChars: z.number().int().min(20).max(500).optional(),
|
||||
refreshIfMissing: z.boolean().optional()
|
||||
}),
|
||||
handler: async (
|
||||
params: {
|
||||
traceId: string;
|
||||
rule: string;
|
||||
ruleHints?: string[];
|
||||
contextChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
},
|
||||
service: LangfuseService
|
||||
) => service.getTraceRuleFlow(params)
|
||||
}
|
||||
];
|
||||
|
||||
export type LangfuseCapability = (typeof langfuseCapabilities)[number];
|
||||
|
||||
export const LANGFUSE_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
|
||||
"sealLangfuseConnectionCheck",
|
||||
"sealLangfuseTraceCacheRefresh",
|
||||
"sealLangfuseTraceUrlGet",
|
||||
"sealLangfuseTraceOutlineGet",
|
||||
"sealLangfuseTraceQrepSearch",
|
||||
"sealLangfuseObservationIoGet",
|
||||
"sealLangfuseSessionOutlineGet",
|
||||
"sealLangfuseObservationsFind",
|
||||
"sealLangfuseAttachmentFlowGet",
|
||||
"sealLangfuseTraceRuleFlowGet"
|
||||
]);
|
||||
|
||||
export function findLangfuseCapability(name: string): LangfuseCapability | undefined {
|
||||
return langfuseCapabilities.find((capability) => capability.name === name);
|
||||
}
|
||||
|
||||
/** Built lazily per invocation so tests can swap env vars before first use. */
|
||||
export function createLangfuseService(config?: LangfuseConfig): LangfuseService {
|
||||
return new LangfuseService(config ?? resolveLangfuseConfig());
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { CliError } from "../../core/errors.js";
|
||||
import type { LangfuseConfig } from "./config.js";
|
||||
import { LangfuseClient } from "./client.js";
|
||||
|
||||
type ServedRequest = {
|
||||
method: string;
|
||||
authorization: string | undefined;
|
||||
url: string;
|
||||
};
|
||||
|
||||
async function withServer(
|
||||
respond: (request: ServedRequest) => Response,
|
||||
run: (client: LangfuseClient, requests: ServedRequest[]) => Promise<void>
|
||||
) {
|
||||
const requests: ServedRequest[] = [];
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const served: ServedRequest = {
|
||||
method: request.method,
|
||||
authorization: request.headers.get("authorization") ?? undefined,
|
||||
url: request.url
|
||||
};
|
||||
requests.push(served);
|
||||
return respond(served);
|
||||
}
|
||||
});
|
||||
|
||||
const config: LangfuseConfig = {
|
||||
baseUrl: `http://127.0.0.1:${server.port}`,
|
||||
publicKey: "pk-lf-test",
|
||||
secretKey: "sk-lf-test"
|
||||
};
|
||||
|
||||
try {
|
||||
await run(new LangfuseClient(config), requests);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
}
|
||||
|
||||
describe("LangfuseClient read-only contract", () => {
|
||||
test("issues GET with Basic auth and returns parsed JSON", async () => {
|
||||
await withServer(
|
||||
() => Response.json({ data: [{ id: "proj-1" }] }),
|
||||
async (client, requests) => {
|
||||
const result = await client.getJson<{ data: Array<{ id: string }> }>("/api/public/projects", {
|
||||
limit: 5,
|
||||
skipped: undefined
|
||||
});
|
||||
|
||||
expect(result.data[0]?.id).toBe("proj-1");
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0]?.method).toBe("GET");
|
||||
expect(requests[0]?.authorization).toBe(
|
||||
`Basic ${Buffer.from("pk-lf-test:sk-lf-test", "utf8").toString("base64")}`
|
||||
);
|
||||
const url = new URL(requests[0]!.url);
|
||||
expect(url.pathname).toBe("/api/public/projects");
|
||||
expect(url.searchParams.get("limit")).toBe("5");
|
||||
expect(url.searchParams.has("skipped")).toBe(false);
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("the class exposes no method that could mutate remote state", () => {
|
||||
const methods = Object.getOwnPropertyNames(LangfuseClient.prototype).sort();
|
||||
// Getters (`baseUrl`, `getProjectId`) are prototype properties too; anything
|
||||
// beyond this allow-list would need a read-only review before shipping.
|
||||
expect(methods).toEqual(["baseUrl", "constructor", "getJson", "getProjectId"]);
|
||||
});
|
||||
|
||||
test("401 maps to exit 11 and never echoes the secret", async () => {
|
||||
await withServer(
|
||||
() => new Response("token invalid", { status: 401, statusText: "Unauthorized" }),
|
||||
async (client) => {
|
||||
try {
|
||||
await client.getJson("/api/public/projects");
|
||||
expect.unreachable("401 should throw");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(CliError);
|
||||
expect((error as CliError).exitCode).toBe(11);
|
||||
expect((error as CliError).message).toContain("401");
|
||||
expect((error as CliError).message).not.toContain("sk-lf-test");
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("403 also maps to exit 11", async () => {
|
||||
await withServer(
|
||||
() => new Response("forbidden", { status: 403, statusText: "Forbidden" }),
|
||||
async (client) => {
|
||||
try {
|
||||
await client.getJson("/api/public/traces/x");
|
||||
expect.unreachable("403 should throw");
|
||||
} catch (error) {
|
||||
expect((error as CliError).exitCode).toBe(11);
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("other upstream failures map to exit 1", async () => {
|
||||
await withServer(
|
||||
() => new Response("boom", { status: 500, statusText: "Internal Server Error" }),
|
||||
async (client) => {
|
||||
try {
|
||||
await client.getJson("/api/public/traces/x");
|
||||
expect.unreachable("500 should throw");
|
||||
} catch (error) {
|
||||
expect((error as CliError).exitCode).toBe(1);
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("a 200 non-JSON body degrades to exit 1 instead of a parse crash", async () => {
|
||||
await withServer(
|
||||
() => new Response("<html>captive portal</html>", { status: 200, headers: { "content-type": "text/html" } }),
|
||||
async (client) => {
|
||||
try {
|
||||
await client.getJson("/api/public/projects");
|
||||
expect.unreachable("non-JSON body should throw");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(CliError);
|
||||
expect((error as CliError).exitCode).toBe(1);
|
||||
expect((error as CliError).message).toContain("non-JSON");
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("network errors map to exit 1 with a Basic-redacted message", async () => {
|
||||
const config: LangfuseConfig = {
|
||||
// Reserved port with nothing listening: connection refused, no DNS.
|
||||
baseUrl: "http://127.0.0.1:9",
|
||||
publicKey: "pk-lf-test",
|
||||
secretKey: "sk-lf-test"
|
||||
};
|
||||
const client = new LangfuseClient(config);
|
||||
try {
|
||||
await client.getJson("/api/public/projects");
|
||||
expect.unreachable("connection failure should throw");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(CliError);
|
||||
expect((error as CliError).exitCode).toBe(1);
|
||||
expect((error as CliError).message).toContain("unreachable");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { CliError } from "../../core/errors.js";
|
||||
import { redactSensitiveText } from "../../core/redact.js";
|
||||
import type { LangfuseConfig } from "./config.js";
|
||||
|
||||
export type HttpQuery = Record<string, string | number | boolean | undefined>;
|
||||
|
||||
/**
|
||||
* Read-only Langfuse Public API client.
|
||||
*
|
||||
* The embedded key pair is not scope-limited upstream (Langfuse project keys
|
||||
* carry full API access), so "read-only" is a guarantee of THIS client: it
|
||||
* exposes `getJson` only, issues `GET` exclusively, and has no method that can
|
||||
* mutate remote state. Keep it that way — adding a POST/PUT/DELETE helper here
|
||||
* breaks the documented trust boundary in SECURITY.md.
|
||||
*
|
||||
* Failures map to the CLI exit-code contract: 401/403 → 11 (authentication),
|
||||
* any other upstream failure → 1 (upstream API failure). Messages pass through
|
||||
* `redactSensitiveText` so the Basic credential can never leak via an error.
|
||||
*/
|
||||
export class LangfuseClient {
|
||||
constructor(private readonly config: LangfuseConfig) {}
|
||||
|
||||
get baseUrl(): string {
|
||||
return this.config.baseUrl;
|
||||
}
|
||||
|
||||
getProjectId(): string | undefined {
|
||||
return this.config.projectId;
|
||||
}
|
||||
|
||||
async getJson<T>(path: string, query: HttpQuery = {}): Promise<T> {
|
||||
const url = new URL(`${this.config.baseUrl}${path}`);
|
||||
for (const [key, value] of Object.entries(query)) {
|
||||
if (value !== undefined) url.searchParams.set(key, String(value));
|
||||
}
|
||||
|
||||
const credential = Buffer.from(
|
||||
`${this.config.publicKey}:${this.config.secretKey}`,
|
||||
"utf8"
|
||||
).toString("base64");
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Basic ${credential}`,
|
||||
Accept: "application/json"
|
||||
},
|
||||
signal: AbortSignal.timeout(30_000)
|
||||
});
|
||||
} catch (error) {
|
||||
const detail = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||
throw new CliError(`Langfuse API unreachable: ${detail}`, 1);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const body = redactSensitiveText(await response.text());
|
||||
const detail = `Langfuse API ${response.status} ${response.statusText}: ${body.slice(0, 500)}`;
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new CliError(detail, 11, "检查注入的 Langfuse 密钥是否仍然有效");
|
||||
}
|
||||
if (response.status === 404) {
|
||||
const isProjectMismatch = body.includes("authorized project") || body.includes("not found");
|
||||
const suggestion = isProjectMismatch
|
||||
? "当前使用内置生产 Langfuse 凭据。若单据来自测试或 Staging 环境(如 staging.sealai.cc),其 Trace 属于 Staging 项目,无法通过内置生产凭据查询。可设置 LANGFUSE_BASE_URL、LANGFUSE_PUBLIC_KEY、LANGFUSE_SECRET_KEY 环境变量临时覆盖凭据。"
|
||||
: "确认 Trace ID / Session ID 是否正确,或已过生命周期保留期";
|
||||
throw new CliError(detail, 1, suggestion);
|
||||
}
|
||||
throw new CliError(detail, 1);
|
||||
}
|
||||
|
||||
// A 200 that is not JSON (captive portal, HTML error page from a proxy)
|
||||
// must degrade like any other upstream failure — exit 1, never a raw
|
||||
// SyntaxError bubbling up as a misleading "invalid config" exit 13.
|
||||
try {
|
||||
return (await response.json()) as T;
|
||||
} catch {
|
||||
throw new CliError(
|
||||
"Langfuse API returned a non-JSON response (upstream or network proxy problem).",
|
||||
1,
|
||||
"用 seal-use langfuse check 复测连通性,或改用 Langfuse Web 后台"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { CliError } from "../../core/errors.js";
|
||||
import { hasLangfuseCredentials, resolveLangfuseConfig } from "./config.js";
|
||||
|
||||
const KEYS = [
|
||||
"SEAL_BUILD_LANGFUSE_BASE_URL",
|
||||
"SEAL_BUILD_LANGFUSE_PUBLIC_KEY",
|
||||
"SEAL_BUILD_LANGFUSE_SECRET_KEY",
|
||||
"SEAL_BUILD_LANGFUSE_PROJECT_ID",
|
||||
"LANGFUSE_BASE_URL",
|
||||
"LANGFUSE_PUBLIC_KEY",
|
||||
"LANGFUSE_SECRET_KEY",
|
||||
"LANGFUSE_PROJECT_ID"
|
||||
] as const;
|
||||
|
||||
const original = new Map<string, string | undefined>(KEYS.map((key) => [key, process.env[key]]));
|
||||
|
||||
afterEach(() => {
|
||||
for (const key of KEYS) {
|
||||
const value = original.get(key);
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
function clearAll() {
|
||||
for (const key of KEYS) delete process.env[key];
|
||||
}
|
||||
|
||||
describe("langfuse config resolution", () => {
|
||||
test("prefers compile-time injected vars and normalizes the base URL", () => {
|
||||
clearAll();
|
||||
process.env.SEAL_BUILD_LANGFUSE_BASE_URL = "https://cloud.langfuse.com/";
|
||||
process.env.SEAL_BUILD_LANGFUSE_PUBLIC_KEY = "pk-lf-build";
|
||||
process.env.SEAL_BUILD_LANGFUSE_SECRET_KEY = "sk-lf-build";
|
||||
process.env.LANGFUSE_BASE_URL = "https://dev.example";
|
||||
process.env.LANGFUSE_PUBLIC_KEY = "pk-lf-dev";
|
||||
|
||||
const config = resolveLangfuseConfig();
|
||||
expect(config).toEqual({
|
||||
baseUrl: "https://cloud.langfuse.com",
|
||||
publicKey: "pk-lf-build",
|
||||
secretKey: "sk-lf-build"
|
||||
});
|
||||
});
|
||||
|
||||
test("falls back to plain LANGFUSE_* shell vars for source runs", () => {
|
||||
clearAll();
|
||||
process.env.LANGFUSE_BASE_URL = "https://cloud.langfuse.com";
|
||||
process.env.LANGFUSE_PUBLIC_KEY = "pk-lf-dev";
|
||||
process.env.LANGFUSE_SECRET_KEY = "sk-lf-dev";
|
||||
process.env.LANGFUSE_PROJECT_ID = "proj-1";
|
||||
|
||||
expect(hasLangfuseCredentials()).toBe(true);
|
||||
expect(resolveLangfuseConfig()).toEqual({
|
||||
baseUrl: "https://cloud.langfuse.com",
|
||||
publicKey: "pk-lf-dev",
|
||||
secretKey: "sk-lf-dev",
|
||||
projectId: "proj-1"
|
||||
});
|
||||
});
|
||||
|
||||
test("throws exit 11 when no credentials exist in the build", () => {
|
||||
clearAll();
|
||||
expect(hasLangfuseCredentials()).toBe(false);
|
||||
try {
|
||||
resolveLangfuseConfig();
|
||||
expect.unreachable("resolveLangfuseConfig should throw without credentials");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(CliError);
|
||||
expect((error as CliError).exitCode).toBe(11);
|
||||
expect((error as CliError).message).toContain("SEAL_BUILD_LANGFUSE_BASE_URL");
|
||||
}
|
||||
});
|
||||
|
||||
test("incomplete credentials are treated as missing", () => {
|
||||
clearAll();
|
||||
process.env.SEAL_BUILD_LANGFUSE_BASE_URL = "https://cloud.langfuse.com";
|
||||
expect(hasLangfuseCredentials()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { CliError } from "../../core/errors.js";
|
||||
|
||||
/**
|
||||
* Langfuse connection settings resolved at runtime.
|
||||
*
|
||||
* Credentials are injected at COMPILE time, never stored in this repository or
|
||||
* in user config: `scripts/build-binary.mjs` copies them into the build
|
||||
* environment as `SEAL_BUILD_LANGFUSE_*`, and `bun build --env=SEAL_BUILD_*`
|
||||
* embeds them into release binaries. End users therefore need zero setup.
|
||||
*
|
||||
* Precedence: injected build vars → plain `LANGFUSE_*` shell vars (development
|
||||
* convenience when running from source) → nothing. Reading user config files is
|
||||
* deliberately absent: this domain must work without any local configuration.
|
||||
*/
|
||||
export type LangfuseConfig = {
|
||||
baseUrl: string;
|
||||
publicKey: string;
|
||||
secretKey: string;
|
||||
projectId?: string;
|
||||
};
|
||||
|
||||
function pick(...candidates: Array<string | undefined>): string | undefined {
|
||||
for (const candidate of candidates) {
|
||||
const trimmed = candidate?.trim();
|
||||
if (trimmed) return trimmed;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(baseUrl: string): string {
|
||||
return baseUrl.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
export function hasLangfuseCredentials(): boolean {
|
||||
const { baseUrl, publicKey, secretKey } = readLangfuseCredentials();
|
||||
return Boolean(baseUrl && publicKey && secretKey);
|
||||
}
|
||||
|
||||
/** Returns the credential set, or `undefined` parts when a build has none. */
|
||||
function readLangfuseCredentials(): {
|
||||
baseUrl?: string;
|
||||
publicKey?: string;
|
||||
secretKey?: string;
|
||||
projectId?: string;
|
||||
} {
|
||||
// Literal `process.env.X` accesses on purpose: `bun build --env=SEAL_BUILD_*`
|
||||
// inlines static property reads at compile time, while a computed key
|
||||
// (`process.env["SEAL_BUILD_" + name]`) stays a runtime lookup and comes back
|
||||
// empty from a release binary. Reads happen per call so tests and dev shells
|
||||
// can change the environment between invocations. The `LANGFUSE_*` fallbacks
|
||||
// are deliberately outside the SEAL_BUILD_ prefix: they are never inlined and
|
||||
// remain live shell-env vars for development runs from source.
|
||||
return {
|
||||
baseUrl: pick(process.env.SEAL_BUILD_LANGFUSE_BASE_URL, process.env.LANGFUSE_BASE_URL),
|
||||
publicKey: pick(process.env.SEAL_BUILD_LANGFUSE_PUBLIC_KEY, process.env.LANGFUSE_PUBLIC_KEY),
|
||||
secretKey: pick(process.env.SEAL_BUILD_LANGFUSE_SECRET_KEY, process.env.LANGFUSE_SECRET_KEY),
|
||||
projectId: pick(process.env.SEAL_BUILD_LANGFUSE_PROJECT_ID, process.env.LANGFUSE_PROJECT_ID)
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveLangfuseConfig(): LangfuseConfig {
|
||||
const { baseUrl, publicKey, secretKey, projectId } = readLangfuseCredentials();
|
||||
|
||||
if (!baseUrl || !publicKey || !secretKey) {
|
||||
throw new CliError(
|
||||
"Langfuse credentials are missing in this build: SEAL_BUILD_LANGFUSE_BASE_URL / SEAL_BUILD_LANGFUSE_PUBLIC_KEY / SEAL_BUILD_LANGFUSE_SECRET_KEY were not injected at compile time.",
|
||||
11,
|
||||
"使用官方发行版二进制(seal-use update),或在构建时注入 SEAL_BUILD_LANGFUSE_* 环境变量"
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
baseUrl: normalizeBaseUrl(baseUrl),
|
||||
publicKey,
|
||||
secretKey,
|
||||
...(projectId ? { projectId } : {})
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import type {
|
||||
LangfuseObservationSummary,
|
||||
LangfuseSearchResult,
|
||||
LangfuseTraceSummary,
|
||||
SearchField
|
||||
} from "./types.js";
|
||||
|
||||
const DEFAULT_FIELDS: SearchField[] = ["name", "input", "output", "metadata", "userId", "sessionId"];
|
||||
|
||||
/**
|
||||
* Deterministic ranked search inside ONE cached trace (the "qrep" engine).
|
||||
* Case-insensitive substring matching — no embeddings, no LLM. Matches are
|
||||
* scored (output > metadata > name; trace scope and review-stage observations
|
||||
* rank higher) and returned with a hierarchy path plus before/match/after
|
||||
* context so callers can decide which observation to open next.
|
||||
*/
|
||||
export function searchTrace(
|
||||
projectId: string,
|
||||
trace: LangfuseTraceSummary,
|
||||
query: string | string[],
|
||||
options: {
|
||||
maxResults: number;
|
||||
contextChars: number;
|
||||
fields?: SearchField[];
|
||||
observationTypes?: string[];
|
||||
metadata?: Record<string, string | number | boolean>;
|
||||
}
|
||||
): LangfuseSearchResult[] {
|
||||
const terms = normalizeTerms(query);
|
||||
if (terms.length === 0) return [];
|
||||
if (!metadataMatches(trace.metadata, options.metadata)) return [];
|
||||
|
||||
const fields = options.fields?.length ? options.fields : DEFAULT_FIELDS;
|
||||
const observations = trace.observations ?? [];
|
||||
const pathByObservationId = buildObservationPaths(trace, observations);
|
||||
const allowedTypes = new Set(options.observationTypes?.map((type) => type.toUpperCase()));
|
||||
const results: Array<LangfuseSearchResult & { score: number }> = [];
|
||||
|
||||
for (const field of searchableFields(trace, fields)) {
|
||||
const match = makeMatch(field.value, terms, options.contextChars);
|
||||
if (!match) continue;
|
||||
|
||||
results.push({
|
||||
score: scoreMatch("trace", field.name),
|
||||
projectId,
|
||||
sessionId: trace.sessionId,
|
||||
traceId: trace.id,
|
||||
traceName: trace.name,
|
||||
timestamp: trace.timestamp,
|
||||
path: buildTracePath(trace, field.name),
|
||||
field: field.name,
|
||||
snippet: formatSnippet(match),
|
||||
matchedField: field.name,
|
||||
matchedText: match.match,
|
||||
context: match,
|
||||
hierarchy: {
|
||||
session: trace.sessionId ? { id: trace.sessionId } : undefined,
|
||||
trace: { id: trace.id, name: trace.name, userId: trace.userId }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (const observation of observations) {
|
||||
if (allowedTypes.size > 0 && observation.type && !allowedTypes.has(observation.type.toUpperCase())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const field of searchableFields(observation, fields)) {
|
||||
const match = makeMatch(field.value, terms, options.contextChars);
|
||||
if (!match) continue;
|
||||
|
||||
results.push({
|
||||
score: scoreMatch("observation", field.name, observation.name),
|
||||
projectId,
|
||||
sessionId: trace.sessionId ?? observation.sessionId,
|
||||
traceId: trace.id,
|
||||
traceName: trace.name,
|
||||
timestamp: observation.startTime ?? trace.timestamp,
|
||||
path: [...(pathByObservationId.get(observation.id) ?? buildObservationPath(trace, observation)), field.name],
|
||||
observationId: observation.id,
|
||||
observationName: observation.name,
|
||||
observationType: observation.type,
|
||||
field: field.name,
|
||||
snippet: formatSnippet(match),
|
||||
matchedField: `observations.${observation.id}.${field.name}`,
|
||||
matchedText: match.match,
|
||||
context: match,
|
||||
hierarchy: {
|
||||
session: trace.sessionId ? { id: trace.sessionId } : undefined,
|
||||
trace: { id: trace.id, name: trace.name, userId: trace.userId },
|
||||
observation: {
|
||||
id: observation.id,
|
||||
type: observation.type,
|
||||
name: observation.name
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
.sort((left, right) => right.score - left.score)
|
||||
.slice(0, options.maxResults)
|
||||
.map(({ score: _score, ...result }) => result);
|
||||
}
|
||||
|
||||
function searchableFields(
|
||||
entity: Record<string, unknown>,
|
||||
fields: SearchField[]
|
||||
): Array<{ name: SearchField; value: string }> {
|
||||
return fields
|
||||
.map((field) => ({ name: field, value: stringifyValue(entity[field]) }))
|
||||
.filter((field) => field.value.length > 0);
|
||||
}
|
||||
|
||||
export function stringifyValue(value: unknown): string {
|
||||
if (value === undefined || value === null) return "";
|
||||
if (typeof value === "string") return value;
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTerms(query: string | string[]): string[] {
|
||||
const values = Array.isArray(query) ? query : [query];
|
||||
return values.map((value) => value.trim().toLowerCase()).filter(Boolean);
|
||||
}
|
||||
|
||||
function makeMatch(
|
||||
text: string,
|
||||
terms: string[],
|
||||
contextChars: number
|
||||
): { before: string; match: string; after: string } | undefined {
|
||||
const normalizedText = text.toLowerCase();
|
||||
let best: { term: string; index: number } | undefined;
|
||||
|
||||
for (const term of terms) {
|
||||
const index = normalizedText.indexOf(term);
|
||||
if (index < 0) continue;
|
||||
if (!best || index < best.index) best = { term, index };
|
||||
}
|
||||
|
||||
if (!best) return undefined;
|
||||
|
||||
const start = Math.max(0, best.index - contextChars);
|
||||
const end = Math.min(text.length, best.index + best.term.length + contextChars);
|
||||
|
||||
return {
|
||||
before: text.slice(start, best.index),
|
||||
match: text.slice(best.index, best.index + best.term.length),
|
||||
after: text.slice(best.index + best.term.length, end)
|
||||
};
|
||||
}
|
||||
|
||||
function formatSnippet(match: { before: string; match: string; after: string }): string {
|
||||
return `${match.before}${match.match}${match.after}`;
|
||||
}
|
||||
|
||||
function scoreMatch(scope: "trace" | "observation", fieldName: string, observationName?: string): number {
|
||||
const fieldWeight = fieldName === "output" ? 30 : fieldName === "metadata" ? 20 : fieldName === "name" ? 10 : 5;
|
||||
const scopeWeight = scope === "trace" ? 15 : 0;
|
||||
const finalReviewWeight =
|
||||
observationName?.includes("approval_review") || observationName?.includes("审核") ? 10 : 0;
|
||||
return fieldWeight + scopeWeight + finalReviewWeight;
|
||||
}
|
||||
|
||||
function buildTracePath(trace: LangfuseTraceSummary, fieldName: string): string[] {
|
||||
return [...(trace.sessionId ? [`session:${trace.sessionId}`] : []), `trace:${trace.name ?? trace.id}`, fieldName];
|
||||
}
|
||||
|
||||
function buildObservationPaths(
|
||||
trace: LangfuseTraceSummary,
|
||||
observations: LangfuseObservationSummary[]
|
||||
): Map<string, string[]> {
|
||||
const byId = new Map(observations.map((observation) => [observation.id, observation]));
|
||||
const paths = new Map<string, string[]>();
|
||||
|
||||
for (const observation of observations) {
|
||||
paths.set(observation.id, resolveObservationPath(trace, observation, byId, paths));
|
||||
}
|
||||
|
||||
return paths;
|
||||
}
|
||||
|
||||
function resolveObservationPath(
|
||||
trace: LangfuseTraceSummary,
|
||||
observation: LangfuseObservationSummary,
|
||||
byId: Map<string, LangfuseObservationSummary>,
|
||||
paths: Map<string, string[]>
|
||||
): string[] {
|
||||
const cached = paths.get(observation.id);
|
||||
if (cached) return cached;
|
||||
|
||||
const current = `${observation.type?.toLowerCase() ?? "observation"}:${observation.name ?? observation.id}`;
|
||||
const parent = observation.parentObservationId ? byId.get(observation.parentObservationId) : undefined;
|
||||
const path = parent
|
||||
? [...resolveObservationPath(trace, parent, byId, paths), current]
|
||||
: [...buildTracePath(trace, "observations").slice(0, -1), current];
|
||||
|
||||
paths.set(observation.id, path);
|
||||
return path;
|
||||
}
|
||||
|
||||
function buildObservationPath(trace: LangfuseTraceSummary, observation: LangfuseObservationSummary): string[] {
|
||||
return [
|
||||
...(trace.sessionId ? [`session:${trace.sessionId}`] : []),
|
||||
`trace:${trace.name ?? trace.id}`,
|
||||
`${observation.type?.toLowerCase() ?? "observation"}:${observation.name ?? observation.id}`
|
||||
];
|
||||
}
|
||||
|
||||
function metadataMatches(metadata: unknown, filters?: Record<string, string | number | boolean>): boolean {
|
||||
if (!filters || Object.keys(filters).length === 0) return true;
|
||||
if (!metadata || typeof metadata !== "object") return false;
|
||||
|
||||
const record = metadata as Record<string, unknown>;
|
||||
return Object.entries(filters).every(([key, expected]) => record[key] === expected);
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, realpathSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { CliError } from "../../core/errors.js";
|
||||
import { TraceCache } from "./cache.js";
|
||||
import type { LangfuseConfig } from "./config.js";
|
||||
import { LangfuseService } from "./service.js";
|
||||
import { searchTrace } from "./search.js";
|
||||
import type { LangfuseTraceSummary } from "./types.js";
|
||||
|
||||
const CONFIG: LangfuseConfig = {
|
||||
baseUrl: "https://langfuse.invalid",
|
||||
publicKey: "pk-lf-test",
|
||||
secretKey: "sk-lf-test",
|
||||
projectId: "proj-1"
|
||||
};
|
||||
|
||||
function sampleTrace(): LangfuseTraceSummary {
|
||||
return {
|
||||
id: "trace-1",
|
||||
name: "approval 驳回 run",
|
||||
projectId: "proj-1",
|
||||
sessionId: "sess-1",
|
||||
userId: "user-1",
|
||||
timestamp: "2026-10-01T00:00:00+08:00",
|
||||
input: "申请单 A",
|
||||
output: "已通过",
|
||||
observations: [
|
||||
{
|
||||
id: "obs-root",
|
||||
traceId: "trace-1",
|
||||
type: "SPAN",
|
||||
name: "document_parsing",
|
||||
input: { items: [{ name: "invoice.pdf" }] },
|
||||
output: "解析完成",
|
||||
metadata: { stage: "parsing" }
|
||||
},
|
||||
{
|
||||
id: "obs-review",
|
||||
traceId: "trace-1",
|
||||
parentObservationId: "obs-root",
|
||||
type: "GENERATION",
|
||||
name: "approval_review",
|
||||
input: "上下文",
|
||||
output: "驳回:材料不全",
|
||||
usageDetails: { input: 10 },
|
||||
totalCost: 0.01
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
let originalCwd: string;
|
||||
let workdir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
originalCwd = process.cwd();
|
||||
workdir = mkdtempSync(join(tmpdir(), "seal-langfuse-test-"));
|
||||
process.chdir(workdir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(originalCwd);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function seedCache(trace: LangfuseTraceSummary = sampleTrace()) {
|
||||
const cache = new TraceCache({ baseUrl: CONFIG.baseUrl, projectId: CONFIG.projectId });
|
||||
await cache.write(trace.id, trace);
|
||||
return cache;
|
||||
}
|
||||
|
||||
describe("trace cache", () => {
|
||||
test("writes the langfuse-home compatible path and round-trips", async () => {
|
||||
const cache = await seedCache();
|
||||
// process.cwd() resolves symlinks, so compare against the physical tmpdir
|
||||
// (macOS /var -> /private/var).
|
||||
const physicalWorkdir = realpathSync(workdir);
|
||||
expect(cache.path("trace-1")).toBe(
|
||||
join(physicalWorkdir, ".cache", "langfuse", "traces", "default", "trace-1.json")
|
||||
);
|
||||
|
||||
const read = await new TraceCache({ baseUrl: CONFIG.baseUrl }).read("trace-1");
|
||||
expect(read?.cacheVersion).toBe(1);
|
||||
expect(read?.trace.id).toBe("trace-1");
|
||||
expect(read?.project.baseUrl).toBe(CONFIG.baseUrl);
|
||||
});
|
||||
|
||||
test("returns undefined for a missing or version-mismatched entry", async () => {
|
||||
const cache = new TraceCache({ baseUrl: CONFIG.baseUrl });
|
||||
expect(await cache.read("missing")).toBeUndefined();
|
||||
await cache.write("trace-1", sampleTrace());
|
||||
expect(await cache.exists("trace-1")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("service outline and observation IO (offline, cache-first)", () => {
|
||||
test("builds the observation tree from the cached trace", async () => {
|
||||
await seedCache();
|
||||
const service = new LangfuseService(CONFIG);
|
||||
|
||||
const outline = await service.getTraceOutline({ traceId: "trace-1" });
|
||||
expect(outline.projectId).toBe("proj-1");
|
||||
expect(outline.flatObservationCount).toBe(2);
|
||||
expect(outline.observations).toHaveLength(1);
|
||||
expect(outline.observations[0]?.id).toBe("obs-root");
|
||||
expect(outline.observations[0]?.children[0]?.id).toBe("obs-review");
|
||||
// Size-before-content: lengths instead of bodies.
|
||||
expect(outline.observations[0]?.outputLength).toBe(4);
|
||||
expect(JSON.stringify(outline)).not.toContain("解析完成");
|
||||
});
|
||||
|
||||
test("reading a missing observation or an uncached trace fails with exit 13 guidance", async () => {
|
||||
await seedCache();
|
||||
const service = new LangfuseService(CONFIG);
|
||||
|
||||
try {
|
||||
await service.getObservationIo({ traceId: "trace-1", observationId: "nope" });
|
||||
expect.unreachable("missing observation should throw");
|
||||
} catch (error) {
|
||||
expect((error as CliError).exitCode).toBe(13);
|
||||
}
|
||||
|
||||
try {
|
||||
await service.getTraceOutline({ traceId: "trace-other" });
|
||||
expect.unreachable("uncached trace should throw");
|
||||
} catch (error) {
|
||||
expect((error as CliError).exitCode).toBe(13);
|
||||
expect((error as CliError).message).toContain("seal-use langfuse cache-refresh");
|
||||
}
|
||||
});
|
||||
|
||||
test("jsonPath selects one nested value and maxChars truncates with a warning", async () => {
|
||||
await seedCache();
|
||||
const service = new LangfuseService(CONFIG);
|
||||
|
||||
const picked = await service.getObservationIo({
|
||||
traceId: "trace-1",
|
||||
observationId: "obs-root",
|
||||
fields: ["input"],
|
||||
jsonPath: "items[0].name"
|
||||
});
|
||||
// `input`/`output`/`metadata` are dynamic keys filled per requested field.
|
||||
expect((picked as Record<string, unknown>).input).toBe("invoice.pdf");
|
||||
|
||||
const long = sampleTrace();
|
||||
long.observations![1]!.output = "驳回理由".repeat(500);
|
||||
await new TraceCache({ baseUrl: CONFIG.baseUrl }).write("trace-1", long);
|
||||
|
||||
const truncated = await service.getObservationIo({
|
||||
traceId: "trace-1",
|
||||
observationId: "obs-review",
|
||||
maxChars: 200
|
||||
});
|
||||
expect((truncated.warnings ?? []).join(" ")).toContain("truncated");
|
||||
expect(String((truncated as Record<string, unknown>).output).length).toBeLessThan(2_000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("qrep search", () => {
|
||||
test("ranks an observation output match above the trace-level name match", () => {
|
||||
const trace = sampleTrace();
|
||||
const results = searchTrace("proj-1", trace, ["驳回"], {
|
||||
maxResults: 10,
|
||||
contextChars: 50
|
||||
});
|
||||
|
||||
expect(results.length).toBeGreaterThanOrEqual(2);
|
||||
expect(results[0]?.observationId).toBe("obs-review");
|
||||
expect(results[0]?.field).toBe("output");
|
||||
expect(results[0]?.hierarchy.trace.id).toBe("trace-1");
|
||||
expect(results[0]?.context.match).toBe("驳回");
|
||||
expect(results.some((result) => result.observationId === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
test("filters by observation type and metadata", () => {
|
||||
const trace = sampleTrace();
|
||||
|
||||
const typed = searchTrace("proj-1", trace, "解析", {
|
||||
maxResults: 10,
|
||||
contextChars: 50,
|
||||
observationTypes: ["GENERATION"]
|
||||
});
|
||||
expect(typed.every((result) => result.observationType === "GENERATION" || result.observationId === undefined)).toBe(true);
|
||||
|
||||
const empty = searchTrace("proj-1", trace, "驳回", {
|
||||
maxResults: 10,
|
||||
contextChars: 50,
|
||||
metadata: { stage: "review" }
|
||||
});
|
||||
expect(empty).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,772 @@
|
||||
import { validationError } from "../../core/errors.js";
|
||||
import { LangfuseApi } from "./api.js";
|
||||
import { TraceCache } from "./cache.js";
|
||||
import type { LangfuseConfig } from "./config.js";
|
||||
import { LangfuseClient } from "./client.js";
|
||||
import { searchTrace, stringifyValue } from "./search.js";
|
||||
import type {
|
||||
AttachmentFlowInput,
|
||||
CachedTrace,
|
||||
LangfuseObservationSummary,
|
||||
LangfuseSearchResult,
|
||||
LangfuseTraceSummary,
|
||||
ObservationIoInput,
|
||||
ObservationsFindInput,
|
||||
ObservationOutlineNode,
|
||||
SearchInput,
|
||||
SessionOutlineInput,
|
||||
TraceCacheRefreshInput,
|
||||
TraceOutline,
|
||||
TraceOutlineInput,
|
||||
TraceRuleFlowInput,
|
||||
TraceUrlInput
|
||||
} from "./types.js";
|
||||
|
||||
const DEFAULT_MAX_RESULTS = 10;
|
||||
const DEFAULT_CONTEXT_CHARS = 120;
|
||||
const DEFAULT_IO_CHARS = 8_000;
|
||||
const DEFAULT_PREVIEW_CHARS = 160;
|
||||
const FULL_OUTPUT_WARNING_THRESHOLD = 30_000;
|
||||
const OUTLINE_FULL_FIELD_THRESHOLD = 20_000;
|
||||
const ATTACHMENT_STAGES = [
|
||||
"attachment parsing",
|
||||
"image/document understanding",
|
||||
"pre_analysis",
|
||||
"document_parsing",
|
||||
"approval_review"
|
||||
] as const;
|
||||
const RULE_FLOW_STAGES = ["rule matching", "document parsing", "final review"] as const;
|
||||
|
||||
/**
|
||||
* Read-only Langfuse trace service, ported from langfuse-home.
|
||||
*
|
||||
* The whole surface is cache-first by design (the "IO-last" workflow): fetch a
|
||||
* trace once via `refreshTraceCache`, then outline / search / observations /
|
||||
* flows read the local cache; `refreshIfMissing` opts into an on-demand fetch.
|
||||
* All output is size-before-content: summaries carry lengths, bytes, usage and
|
||||
* cost instead of bodies, previews middle-truncate, and oversized fields return
|
||||
* an actionable warning instead of a wall of text.
|
||||
*/
|
||||
export class LangfuseService {
|
||||
private readonly client: LangfuseClient;
|
||||
private readonly api: LangfuseApi;
|
||||
private readonly cache: TraceCache;
|
||||
|
||||
constructor(private readonly config: LangfuseConfig) {
|
||||
this.client = new LangfuseClient(config);
|
||||
this.api = new LangfuseApi(this.client);
|
||||
this.cache = new TraceCache({ baseUrl: config.baseUrl, projectId: config.projectId });
|
||||
}
|
||||
|
||||
async connectionCheck() {
|
||||
const projects = await this.api.getProject();
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
checkedPath: "/api/public/projects",
|
||||
projectId: this.config.projectId,
|
||||
baseUrl: this.config.baseUrl,
|
||||
projects
|
||||
};
|
||||
}
|
||||
|
||||
async refreshTraceCache(input: TraceCacheRefreshInput) {
|
||||
const trace = await this.api.getTrace(input.traceId);
|
||||
const cached = await this.cache.write(input.traceId, trace);
|
||||
|
||||
return {
|
||||
projectId: this.config.projectId,
|
||||
traceId: input.traceId,
|
||||
cache: {
|
||||
path: this.cache.path(input.traceId),
|
||||
exists: true,
|
||||
cachedAt: cached.cachedAt,
|
||||
refreshed: true
|
||||
},
|
||||
trace: summarizeTrace(trace),
|
||||
observationCount: trace.observations?.length ?? 0
|
||||
};
|
||||
}
|
||||
|
||||
async getTraceUrl(input: TraceUrlInput) {
|
||||
const cached = await this.cache.read(input.traceId);
|
||||
let source = "config";
|
||||
let traceProjectId = cached?.trace.projectId;
|
||||
let cachedAt = cached?.cachedAt;
|
||||
let refreshed = false;
|
||||
|
||||
if (traceProjectId) {
|
||||
source = "cache";
|
||||
} else {
|
||||
const trace = await this.api.getTrace(input.traceId, { fields: "core" });
|
||||
const refreshedCache = await this.cache.write(input.traceId, trace);
|
||||
traceProjectId = trace.projectId;
|
||||
cachedAt = refreshedCache.cachedAt;
|
||||
refreshed = true;
|
||||
source = traceProjectId ? "trace-api" : "config";
|
||||
}
|
||||
|
||||
const projectId = traceProjectId ?? this.config.projectId;
|
||||
if (!projectId) {
|
||||
throw validationError("Langfuse projectId is unknown: the trace carried none and no project was injected.");
|
||||
}
|
||||
|
||||
return {
|
||||
traceId: input.traceId,
|
||||
projectId,
|
||||
baseUrl: this.config.baseUrl,
|
||||
url: buildTraceUrl(this.config.baseUrl, projectId, input.traceId),
|
||||
source,
|
||||
cache: {
|
||||
path: this.cache.path(input.traceId),
|
||||
exists: Boolean(cached) || refreshed,
|
||||
cachedAt,
|
||||
refreshed
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async searchTrace(input: SearchInput): Promise<LangfuseSearchResult[]> {
|
||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||
const trace = cached.trace;
|
||||
|
||||
if (input.sessionId && trace.sessionId !== input.sessionId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return searchTrace(this.projectIdFor(trace), trace, input.query, {
|
||||
maxResults: clamp(input.maxResults ?? DEFAULT_MAX_RESULTS, 1, 30),
|
||||
contextChars: clamp(input.contextChars ?? DEFAULT_CONTEXT_CHARS, 20, 500),
|
||||
fields: input.fields,
|
||||
observationTypes: input.observationTypes,
|
||||
metadata: input.metadata
|
||||
});
|
||||
}
|
||||
|
||||
async getTraceOutline(input: TraceOutlineInput): Promise<TraceOutline> {
|
||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||
const trace = cached.trace;
|
||||
const maxPreviewChars = clamp(input.maxPreviewChars ?? DEFAULT_PREVIEW_CHARS, 20, 5_000);
|
||||
const includeInput = input.includeInput ?? input.includeIoPreview ?? false;
|
||||
const includeOutput = input.includeOutput ?? input.includeIoPreview ?? false;
|
||||
const warnings = buildOutlineWarnings(trace, includeInput, includeOutput, input.full ?? false);
|
||||
|
||||
return {
|
||||
projectId: this.projectIdFor(trace),
|
||||
trace: {
|
||||
id: trace.id,
|
||||
projectId: trace.projectId,
|
||||
name: trace.name,
|
||||
sessionId: trace.sessionId,
|
||||
userId: trace.userId,
|
||||
timestamp: trace.timestamp,
|
||||
environment: trace.environment,
|
||||
tags: trace.tags,
|
||||
inputPreview: includeInput
|
||||
? guardedPreview(trace.input, maxPreviewChars, input.full ?? false)
|
||||
: undefined,
|
||||
outputPreview: includeOutput
|
||||
? guardedPreview(trace.output, maxPreviewChars, input.full ?? false)
|
||||
: undefined,
|
||||
metadata: trace.metadata,
|
||||
latency: trace.latency,
|
||||
totalCost: trace.totalCost
|
||||
},
|
||||
observations: buildObservationTree(trace.observations ?? [], {
|
||||
includeInput,
|
||||
includeOutput,
|
||||
maxPreviewChars,
|
||||
full: input.full ?? false
|
||||
}),
|
||||
flatObservationCount: trace.observations?.length ?? 0,
|
||||
warnings: warnings.length ? warnings : undefined,
|
||||
cache: {
|
||||
path: this.cache.path(input.traceId),
|
||||
exists: true,
|
||||
cachedAt: cached.cachedAt
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async findObservations(input: ObservationsFindInput) {
|
||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||
const maxResults = clamp(input.maxResults ?? 50, 1, 200);
|
||||
const nameNeedle = input.nameContains?.toLowerCase();
|
||||
const typeNeedle = input.type?.toLowerCase();
|
||||
|
||||
const observations = (cached.trace.observations ?? []).filter((observation) => {
|
||||
if (nameNeedle && !observation.name?.toLowerCase().includes(nameNeedle)) return false;
|
||||
if (typeNeedle && observation.type?.toLowerCase() !== typeNeedle) return false;
|
||||
if (input.metadataKey && !objectKeys(observation.metadata).includes(input.metadataKey)) return false;
|
||||
if (input.hasInput !== undefined && hasValue(observation.input) !== input.hasInput) return false;
|
||||
if (input.hasOutput !== undefined && hasValue(observation.output) !== input.hasOutput) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
return {
|
||||
traceId: input.traceId,
|
||||
totalMatches: observations.length,
|
||||
observations: observations.slice(0, maxResults).map(summarizeObservation),
|
||||
truncated: observations.length > maxResults,
|
||||
cache: {
|
||||
cachedAt: cached.cachedAt
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async getSessionOutline(input: SessionOutlineInput) {
|
||||
const session = await this.api.getSession(input.sessionId);
|
||||
const traceLimit = clamp(input.traceLimit ?? 50, 1, 200);
|
||||
|
||||
return {
|
||||
projectId: session.projectId ?? this.config.projectId,
|
||||
session: {
|
||||
id: session.id,
|
||||
projectId: session.projectId,
|
||||
createdAt: session.createdAt
|
||||
},
|
||||
traces: (session.traces ?? []).slice(0, traceLimit).map(summarizeTrace),
|
||||
totalReturnedTraces: Math.min(session.traces?.length ?? 0, traceLimit),
|
||||
note: "Session outline uses the Langfuse session endpoint and returns compact trace summaries only."
|
||||
};
|
||||
}
|
||||
|
||||
async getObservationIo(input: ObservationIoInput) {
|
||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||
const observation = (cached.trace.observations ?? []).find(
|
||||
(candidate) => candidate.id === input.observationId
|
||||
);
|
||||
|
||||
if (!observation) {
|
||||
throw validationError(
|
||||
`Observation not found in cached trace: ${input.observationId}. Refresh the trace or check the observationId from outline/search.`
|
||||
);
|
||||
}
|
||||
|
||||
const maxChars = clamp(input.maxChars ?? DEFAULT_IO_CHARS, 100, input.full ? 500_000 : 30_000);
|
||||
const fields = input.fields?.length ? input.fields : (["input", "output"] as const);
|
||||
const path = input.jsonPath ?? input.path;
|
||||
const values: Record<string, unknown> = {};
|
||||
const warnings: string[] = [];
|
||||
|
||||
for (const field of fields) {
|
||||
const rawValue = observation[field];
|
||||
const selectedValue = path ? readPath(rawValue, path) : rawValue;
|
||||
const rendered = stringifyValue(selectedValue);
|
||||
const guarded = guardLargeText(rendered, maxChars, input.full ?? false);
|
||||
values[field] = guarded.value;
|
||||
if (guarded.warning) warnings.push(`${field}: ${guarded.warning}`);
|
||||
}
|
||||
|
||||
return {
|
||||
traceId: input.traceId,
|
||||
observationId: input.observationId,
|
||||
observation: summarizeObservation(observation),
|
||||
fields,
|
||||
path,
|
||||
...values,
|
||||
warnings: warnings.length ? warnings : undefined,
|
||||
cache: {
|
||||
cachedAt: cached.cachedAt
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async getAttachmentFlow(input: AttachmentFlowInput) {
|
||||
if (!input.fileId && !input.fileName && !input.contentHints?.length) {
|
||||
throw validationError("Provide at least one of fileId, fileName, or contentHints.");
|
||||
}
|
||||
|
||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||
const trace = cached.trace;
|
||||
const contextChars = clamp(input.contextChars ?? DEFAULT_CONTEXT_CHARS, 20, 500);
|
||||
const needles = [input.fileId, input.fileName, ...(input.contentHints ?? [])].filter(
|
||||
(value): value is string => Boolean(value?.trim())
|
||||
);
|
||||
const observations = trace.observations ?? [];
|
||||
const stages = ATTACHMENT_STAGES.map((stage) =>
|
||||
inspectAttachmentStage(stage, observations, needles, input.fileId, input.fileName, contextChars)
|
||||
);
|
||||
|
||||
return {
|
||||
traceId: input.traceId,
|
||||
fileId: input.fileId,
|
||||
fileName: input.fileName,
|
||||
contentHints: input.contentHints,
|
||||
stages,
|
||||
note:
|
||||
"Attachment flow is deterministic text evidence extraction from cached Langfuse fields. Source labels describe where the matched text appears to come from; they do not prove hidden model reasoning or semantic understanding.",
|
||||
cache: {
|
||||
cachedAt: cached.cachedAt
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async getTraceRuleFlow(input: TraceRuleFlowInput) {
|
||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||
const trace = cached.trace;
|
||||
const contextChars = clamp(input.contextChars ?? 300, 20, 500);
|
||||
const needles = uniqueStrings([input.rule, ...(input.ruleHints ?? [])]);
|
||||
const observations = trace.observations ?? [];
|
||||
const stageResults = RULE_FLOW_STAGES.map((stage) =>
|
||||
inspectRuleStage(stage, observations, needles, contextChars)
|
||||
);
|
||||
const allEvidence = stageResults.flatMap((stage) => stage.evidence);
|
||||
const relatedObservationIds = uniqueStrings(allEvidence.map((item) => item.observationId));
|
||||
|
||||
return {
|
||||
traceId: input.traceId,
|
||||
rule: input.rule,
|
||||
ruleHints: input.ruleHints,
|
||||
stages: {
|
||||
ruleMatching: stageResults[0],
|
||||
documentParsing: stageResults[1],
|
||||
finalReview: stageResults[2]
|
||||
},
|
||||
relatedObservationIds,
|
||||
evidenceCount: allEvidence.length,
|
||||
note:
|
||||
"Rule flow is deterministic text evidence extraction from cached Langfuse fields. It reports where the rule or hints appear; it does not infer hidden model reasoning or prove causality beyond the recorded trace text.",
|
||||
cache: {
|
||||
cachedAt: cached.cachedAt
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private projectIdFor(trace: LangfuseTraceSummary): string {
|
||||
return trace.projectId ?? this.config.projectId ?? "";
|
||||
}
|
||||
|
||||
private async getCachedTrace(traceId: string, refreshIfMissing: boolean): Promise<CachedTrace> {
|
||||
const cached = await this.cache.read(traceId);
|
||||
if (cached) return cached;
|
||||
|
||||
if (!refreshIfMissing) {
|
||||
throw validationError(
|
||||
`Trace cache missing for ${traceId}. Run "seal-use langfuse cache-refresh --traceId ${traceId}" first or pass --refresh-if-missing.`
|
||||
);
|
||||
}
|
||||
|
||||
const trace = await this.api.getTrace(traceId);
|
||||
return await this.cache.write(traceId, trace);
|
||||
}
|
||||
}
|
||||
|
||||
function buildObservationTree(
|
||||
observations: LangfuseObservationSummary[],
|
||||
options: {
|
||||
includeInput: boolean;
|
||||
includeOutput: boolean;
|
||||
maxPreviewChars: number;
|
||||
full: boolean;
|
||||
}
|
||||
): ObservationOutlineNode[] {
|
||||
const nodes = new Map<string, ObservationOutlineNode>();
|
||||
const roots: ObservationOutlineNode[] = [];
|
||||
|
||||
for (const observation of observations) {
|
||||
nodes.set(observation.id, {
|
||||
id: observation.id,
|
||||
parentObservationId: observation.parentObservationId,
|
||||
type: observation.type,
|
||||
name: observation.name,
|
||||
level: observation.level,
|
||||
startTime: observation.startTime,
|
||||
endTime: observation.endTime,
|
||||
latency: observation.latency,
|
||||
model: observation.providedModelName ?? observation.model,
|
||||
inputLength: stringifyValue(observation.input).length,
|
||||
outputLength: stringifyValue(observation.output).length,
|
||||
inputBytes: byteLength(stringifyValue(observation.input)),
|
||||
outputBytes: byteLength(stringifyValue(observation.output)),
|
||||
metadataKeys: objectKeys(observation.metadata),
|
||||
usageDetails: observation.usageDetails,
|
||||
costDetails: observation.costDetails,
|
||||
totalCost: observation.totalCost,
|
||||
inputPreview: options.includeInput
|
||||
? guardedPreview(observation.input, options.maxPreviewChars, options.full)
|
||||
: undefined,
|
||||
outputPreview: options.includeOutput
|
||||
? guardedPreview(observation.output, options.maxPreviewChars, options.full)
|
||||
: undefined,
|
||||
children: []
|
||||
});
|
||||
}
|
||||
|
||||
for (const observation of observations) {
|
||||
const node = nodes.get(observation.id);
|
||||
if (!node) continue;
|
||||
|
||||
const parent = observation.parentObservationId ? nodes.get(observation.parentObservationId) : undefined;
|
||||
if (parent) {
|
||||
parent.children.push(node);
|
||||
} else {
|
||||
roots.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
return roots;
|
||||
}
|
||||
|
||||
function buildOutlineWarnings(
|
||||
trace: LangfuseTraceSummary,
|
||||
includeInput: boolean,
|
||||
includeOutput: boolean,
|
||||
full: boolean
|
||||
): string[] {
|
||||
if (full) return [];
|
||||
const warnings: string[] = [];
|
||||
const check = (label: string, value: unknown) => {
|
||||
const length = stringifyValue(value).length;
|
||||
if (length > OUTLINE_FULL_FIELD_THRESHOLD) {
|
||||
warnings.push(
|
||||
`${label} is ${length} chars. Trace IO is large. Use --max-preview-chars, observationId, or search. Pass --full to request the full value.`
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
if (includeInput) check("trace.input", trace.input);
|
||||
if (includeOutput) check("trace.output", trace.output);
|
||||
|
||||
for (const observation of trace.observations ?? []) {
|
||||
if (includeInput) check(`observation.${observation.id}.input`, observation.input);
|
||||
if (includeOutput) check(`observation.${observation.id}.output`, observation.output);
|
||||
}
|
||||
|
||||
return warnings.slice(0, 20);
|
||||
}
|
||||
|
||||
function summarizeTrace(trace: LangfuseTraceSummary) {
|
||||
return {
|
||||
id: trace.id,
|
||||
name: trace.name,
|
||||
projectId: trace.projectId,
|
||||
sessionId: trace.sessionId,
|
||||
userId: trace.userId,
|
||||
timestamp: trace.timestamp,
|
||||
environment: trace.environment,
|
||||
tags: trace.tags,
|
||||
inputLength: stringifyValue(trace.input).length,
|
||||
outputLength: stringifyValue(trace.output).length,
|
||||
metadata: trace.metadata,
|
||||
latency: trace.latency,
|
||||
totalCost: trace.totalCost
|
||||
};
|
||||
}
|
||||
|
||||
function summarizeObservation(observation: LangfuseObservationSummary) {
|
||||
return {
|
||||
id: observation.id,
|
||||
traceId: observation.traceId,
|
||||
parentObservationId: observation.parentObservationId,
|
||||
type: observation.type,
|
||||
name: observation.name,
|
||||
startTime: observation.startTime,
|
||||
endTime: observation.endTime,
|
||||
model: observation.providedModelName ?? observation.model,
|
||||
inputLength: stringifyValue(observation.input).length,
|
||||
outputLength: stringifyValue(observation.output).length,
|
||||
inputBytes: byteLength(stringifyValue(observation.input)),
|
||||
outputBytes: byteLength(stringifyValue(observation.output)),
|
||||
metadataKeys: objectKeys(observation.metadata),
|
||||
usageDetails: observation.usageDetails,
|
||||
costDetails: observation.costDetails,
|
||||
totalCost: observation.totalCost
|
||||
};
|
||||
}
|
||||
|
||||
function buildTraceUrl(baseUrl: string, projectId: string, traceId: string): string {
|
||||
const url = new URL(
|
||||
`/project/${encodeURIComponent(projectId)}/traces/${encodeURIComponent(traceId)}`,
|
||||
baseUrl
|
||||
);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function guardedPreview(value: unknown, maxChars: number, full: boolean): string | undefined {
|
||||
const text = stringifyValue(value);
|
||||
if (!text) return undefined;
|
||||
if (!full && text.length > OUTLINE_FULL_FIELD_THRESHOLD && maxChars >= text.length) {
|
||||
return "Trace IO is large. Use maxPreviewChars, observationId, or search. Pass full=true to request the full value.";
|
||||
}
|
||||
return full ? text : truncateMiddle(text, maxChars);
|
||||
}
|
||||
|
||||
function guardLargeText(text: string, maxChars: number, full: boolean): { value: string; warning?: string } {
|
||||
if (!text) return { value: "" };
|
||||
if (!full && text.length > FULL_OUTPUT_WARNING_THRESHOLD && maxChars >= text.length) {
|
||||
return {
|
||||
value: truncateMiddle(text, DEFAULT_IO_CHARS),
|
||||
warning:
|
||||
"Trace IO is large. Use maxChars, observationId, fields, jsonPath/path, or search. Pass full=true to request more."
|
||||
};
|
||||
}
|
||||
if (!full && text.length > maxChars) {
|
||||
return {
|
||||
value: truncateMiddle(text, maxChars),
|
||||
warning: `Value truncated from ${text.length} chars to ${maxChars} chars. Pass full=true to request more.`
|
||||
};
|
||||
}
|
||||
return { value: text };
|
||||
}
|
||||
|
||||
function readPath(value: unknown, path: string): unknown {
|
||||
const segments = parsePath(path);
|
||||
let current = value;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (current === undefined || current === null) return undefined;
|
||||
if (typeof segment === "number") {
|
||||
current = Array.isArray(current) ? current[segment] : undefined;
|
||||
continue;
|
||||
}
|
||||
if (typeof current !== "object") return undefined;
|
||||
current = (current as Record<string, unknown>)[segment];
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
function parsePath(path: string): Array<string | number> {
|
||||
const normalized = path
|
||||
.trim()
|
||||
.replace(/^\$\.?/, "")
|
||||
.replace(/^(input|output|metadata)\.?/, "");
|
||||
if (!normalized) return [];
|
||||
|
||||
const segments: Array<string | number> = [];
|
||||
for (const part of normalized.split(".")) {
|
||||
const matches = part.matchAll(/([^[\]]+)|\[(\d+)\]/g);
|
||||
for (const match of matches) {
|
||||
if (match[1]) segments.push(match[1]);
|
||||
if (match[2]) segments.push(Number(match[2]));
|
||||
}
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
function inspectAttachmentStage(
|
||||
stage: (typeof ATTACHMENT_STAGES)[number],
|
||||
observations: LangfuseObservationSummary[],
|
||||
needles: string[],
|
||||
fileId: string | undefined,
|
||||
fileName: string | undefined,
|
||||
contextChars: number
|
||||
) {
|
||||
const stageTerms = stageSearchTerms(stage);
|
||||
const candidates = observations.filter((observation) => {
|
||||
const name = observation.name?.toLowerCase() ?? "";
|
||||
return stageTerms.some((term) => name.includes(term));
|
||||
});
|
||||
const evidence = candidates.flatMap((observation) =>
|
||||
collectAttachmentEvidence(observation, needles, contextChars)
|
||||
);
|
||||
const source = classifyAttachmentEvidence(evidence, fileId, fileName);
|
||||
|
||||
return {
|
||||
stage,
|
||||
source,
|
||||
status: source === "absent" ? "absent" : "seen",
|
||||
observations: candidates.map(summarizeObservation),
|
||||
evidence
|
||||
};
|
||||
}
|
||||
|
||||
function stageSearchTerms(stage: (typeof ATTACHMENT_STAGES)[number]): string[] {
|
||||
switch (stage) {
|
||||
case "attachment parsing":
|
||||
return ["attachment", "附件", "parse_attachment", "attachment_parsing"];
|
||||
case "image/document understanding":
|
||||
return ["understanding", "vision", "image", "document_understanding", "文档理解", "图片理解"];
|
||||
case "pre_analysis":
|
||||
return ["pre_analysis", "pre-analysis", "预分析"];
|
||||
case "document_parsing":
|
||||
return ["document_parsing", "document parsing", "文档解析"];
|
||||
case "approval_review":
|
||||
return ["approval_review", "approval review", "审核"];
|
||||
}
|
||||
}
|
||||
|
||||
function collectAttachmentEvidence(
|
||||
observation: LangfuseObservationSummary,
|
||||
needles: string[],
|
||||
contextChars: number
|
||||
): Array<{
|
||||
observationId: string;
|
||||
name?: string;
|
||||
field: "input" | "output" | "metadata";
|
||||
matched: string;
|
||||
snippet: string;
|
||||
}> {
|
||||
const fields = [
|
||||
["input", stringifyValue(observation.input)],
|
||||
["output", stringifyValue(observation.output)],
|
||||
["metadata", stringifyValue(observation.metadata)]
|
||||
] as const;
|
||||
const evidence: ReturnType<typeof collectAttachmentEvidence> = [];
|
||||
|
||||
for (const [field, text] of fields) {
|
||||
const normalized = text.toLowerCase();
|
||||
for (const needle of needles) {
|
||||
const index = normalized.indexOf(needle.toLowerCase());
|
||||
if (index < 0) continue;
|
||||
evidence.push({
|
||||
observationId: observation.id,
|
||||
name: observation.name,
|
||||
field,
|
||||
matched: text.slice(index, index + needle.length),
|
||||
snippet: text.slice(
|
||||
Math.max(0, index - contextChars),
|
||||
Math.min(text.length, index + needle.length + contextChars)
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return evidence.slice(0, 10);
|
||||
}
|
||||
|
||||
function classifyAttachmentEvidence(
|
||||
evidence: Array<{ matched: string; snippet: string; field?: string }>,
|
||||
fileId: string | undefined,
|
||||
fileName: string | undefined
|
||||
): "filename-only" | "file-id-only" | "parsed-text" | "image-ocr" | "model-inferred" | "absent" | "unknown" {
|
||||
if (evidence.length === 0) return "absent";
|
||||
const hasFileName = fileName ? evidence.some((item) => item.matched === fileName) : false;
|
||||
const hasFileId = fileId ? evidence.some((item) => item.matched === fileId) : false;
|
||||
const hasOtherHint = evidence.some((item) => item.matched !== fileId && item.matched !== fileName);
|
||||
if (hasOtherHint) {
|
||||
const joined = evidence
|
||||
.map((item) => item.snippet)
|
||||
.join("\n")
|
||||
.toLowerCase();
|
||||
if (/(ocr|图片|image|vision|视觉|识别)/i.test(joined)) return "image-ocr";
|
||||
if (/(infer|inferred|推断|模型认为|判断|审核结论)/i.test(joined)) return "model-inferred";
|
||||
return "parsed-text";
|
||||
}
|
||||
if (hasFileName && !hasOtherHint) return "filename-only";
|
||||
if (hasFileId && !hasOtherHint) return "file-id-only";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function inspectRuleStage(
|
||||
stage: (typeof RULE_FLOW_STAGES)[number],
|
||||
observations: LangfuseObservationSummary[],
|
||||
needles: string[],
|
||||
contextChars: number
|
||||
) {
|
||||
const stageTerms = ruleStageSearchTerms(stage);
|
||||
const candidates = observations.filter((observation) => {
|
||||
const name = observation.name?.toLowerCase() ?? "";
|
||||
return stageTerms.some((term) => name.includes(term));
|
||||
});
|
||||
const candidatePool = candidates.length ? candidates : observations;
|
||||
const evidence = candidatePool
|
||||
.flatMap((observation) => collectRuleEvidence(observation, needles, contextChars))
|
||||
.slice(0, 20);
|
||||
const matchedObservationIds = uniqueStrings(evidence.map((item) => item.observationId));
|
||||
|
||||
return {
|
||||
stage,
|
||||
matched: evidence.length > 0,
|
||||
matchedObservationIds,
|
||||
observations: candidates.map(summarizeObservation),
|
||||
extractedFields: summarizeEvidenceFields(evidence),
|
||||
evidence
|
||||
};
|
||||
}
|
||||
|
||||
function ruleStageSearchTerms(stage: (typeof RULE_FLOW_STAGES)[number]): string[] {
|
||||
switch (stage) {
|
||||
case "rule matching":
|
||||
return ["rule", "规则", "policy", "match", "matching", "命中"];
|
||||
case "document parsing":
|
||||
return ["document", "parse", "parsing", "attachment", "ocr", "文档", "解析", "附件", "提取"];
|
||||
case "final review":
|
||||
return ["approval_review", "approval review", "review", "审核", "结论", "final"];
|
||||
}
|
||||
}
|
||||
|
||||
function collectRuleEvidence(
|
||||
observation: LangfuseObservationSummary,
|
||||
needles: string[],
|
||||
contextChars: number
|
||||
): Array<{
|
||||
observationId: string;
|
||||
name?: string;
|
||||
type?: string;
|
||||
field: "input" | "output" | "metadata";
|
||||
matched: string;
|
||||
snippet: string;
|
||||
}> {
|
||||
const fields = [
|
||||
["input", stringifyValue(observation.input)],
|
||||
["output", stringifyValue(observation.output)],
|
||||
["metadata", stringifyValue(observation.metadata)]
|
||||
] as const;
|
||||
const evidence: ReturnType<typeof collectRuleEvidence> = [];
|
||||
|
||||
for (const [field, text] of fields) {
|
||||
const normalized = text.toLowerCase();
|
||||
for (const needle of needles) {
|
||||
const index = normalized.indexOf(needle.toLowerCase());
|
||||
if (index < 0) continue;
|
||||
evidence.push({
|
||||
observationId: observation.id,
|
||||
name: observation.name,
|
||||
type: observation.type,
|
||||
field,
|
||||
matched: text.slice(index, index + needle.length),
|
||||
snippet: text.slice(
|
||||
Math.max(0, index - contextChars),
|
||||
Math.min(text.length, index + needle.length + contextChars)
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return evidence;
|
||||
}
|
||||
|
||||
function summarizeEvidenceFields(
|
||||
evidence: Array<{ field: "input" | "output" | "metadata"; matched: string }>
|
||||
): Record<string, { count: number; matched: string[] }> {
|
||||
const summary: Record<string, { count: number; matched: string[] }> = {};
|
||||
for (const item of evidence) {
|
||||
const entry = summary[item.field];
|
||||
if (entry) {
|
||||
entry.count += 1;
|
||||
if (!entry.matched.includes(item.matched)) entry.matched.push(item.matched);
|
||||
} else {
|
||||
summary[item.field] = { count: 1, matched: [item.matched] };
|
||||
}
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
function uniqueStrings(values: Array<string | undefined>): string[] {
|
||||
return [...new Set(values.filter((value): value is string => Boolean(value?.trim())))];
|
||||
}
|
||||
|
||||
function hasValue(value: unknown): boolean {
|
||||
return stringifyValue(value).length > 0;
|
||||
}
|
||||
|
||||
function truncateMiddle(text: string, maxChars: number): string {
|
||||
if (text.length <= maxChars) return text;
|
||||
const head = Math.floor((maxChars - 20) / 2);
|
||||
const tail = Math.max(0, maxChars - 20 - head);
|
||||
return `${text.slice(0, head)}\n...<truncated>...\n${text.slice(text.length - tail)}`;
|
||||
}
|
||||
|
||||
function objectKeys(value: unknown): string[] {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value) : [];
|
||||
}
|
||||
|
||||
function byteLength(value: string): number {
|
||||
return Buffer.byteLength(value, "utf8");
|
||||
}
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
// Ported from langfuse-home (`src/domains/langfuse/types.ts`), adapted to the
|
||||
// single-project seal-use domain: per-input `projectKey`/`projectId` lookups are
|
||||
// gone (one injected project), and compat-only inputs were dropped.
|
||||
|
||||
export type SearchInput = {
|
||||
query: string | string[];
|
||||
traceId: string;
|
||||
sessionId?: string;
|
||||
fields?: SearchField[];
|
||||
observationTypes?: string[];
|
||||
metadata?: Record<string, string | number | boolean>;
|
||||
maxResults?: number;
|
||||
contextChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
};
|
||||
|
||||
export type TraceOutlineInput = {
|
||||
traceId: string;
|
||||
includeIoPreview?: boolean;
|
||||
includeInput?: boolean;
|
||||
includeOutput?: boolean;
|
||||
full?: boolean;
|
||||
maxPreviewChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
};
|
||||
|
||||
export type SessionOutlineInput = {
|
||||
sessionId: string;
|
||||
traceLimit?: number;
|
||||
};
|
||||
|
||||
export type ObservationIoInput = {
|
||||
traceId: string;
|
||||
observationId: string;
|
||||
fields?: ObservationIoField[];
|
||||
maxChars?: number;
|
||||
full?: boolean;
|
||||
jsonPath?: string;
|
||||
path?: string;
|
||||
refreshIfMissing?: boolean;
|
||||
};
|
||||
|
||||
export type ObservationIoField = "input" | "output" | "metadata";
|
||||
|
||||
export type ObservationsFindInput = {
|
||||
traceId: string;
|
||||
nameContains?: string;
|
||||
type?: string;
|
||||
metadataKey?: string;
|
||||
hasInput?: boolean;
|
||||
hasOutput?: boolean;
|
||||
maxResults?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
};
|
||||
|
||||
export type AttachmentFlowInput = {
|
||||
traceId: string;
|
||||
fileId?: string;
|
||||
fileName?: string;
|
||||
contentHints?: string[];
|
||||
contextChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
};
|
||||
|
||||
export type TraceRuleFlowInput = {
|
||||
traceId: string;
|
||||
rule: string;
|
||||
ruleHints?: string[];
|
||||
contextChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
};
|
||||
|
||||
export type TraceCacheRefreshInput = {
|
||||
traceId: string;
|
||||
};
|
||||
|
||||
export type TraceUrlInput = {
|
||||
traceId: string;
|
||||
};
|
||||
|
||||
export type SearchField = "name" | "input" | "output" | "metadata" | "userId" | "sessionId";
|
||||
|
||||
export type LangfuseSearchResult = {
|
||||
projectId: string;
|
||||
sessionId?: string;
|
||||
traceId: string;
|
||||
traceName?: string;
|
||||
timestamp?: string;
|
||||
path: string[];
|
||||
observationId?: string;
|
||||
observationName?: string;
|
||||
observationType?: string;
|
||||
field: SearchField;
|
||||
snippet: string;
|
||||
matchedField: string;
|
||||
matchedText: string;
|
||||
context: {
|
||||
before: string;
|
||||
match: string;
|
||||
after: string;
|
||||
};
|
||||
hierarchy: {
|
||||
session?: {
|
||||
id: string;
|
||||
};
|
||||
trace: {
|
||||
id: string;
|
||||
name?: string;
|
||||
userId?: string;
|
||||
};
|
||||
observation?: {
|
||||
id: string;
|
||||
type?: string;
|
||||
name?: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
export type LangfuseTraceSummary = {
|
||||
id: string;
|
||||
name?: string;
|
||||
projectId?: string;
|
||||
environment?: string;
|
||||
tags?: string[];
|
||||
sessionId?: string;
|
||||
userId?: string;
|
||||
timestamp?: string;
|
||||
input?: unknown;
|
||||
output?: unknown;
|
||||
metadata?: unknown;
|
||||
latency?: number;
|
||||
totalCost?: number;
|
||||
observations?: LangfuseObservationSummary[];
|
||||
scores?: unknown[];
|
||||
};
|
||||
|
||||
export type LangfuseObservationSummary = {
|
||||
id: string;
|
||||
traceId: string;
|
||||
parentObservationId?: string;
|
||||
type?: string;
|
||||
name?: string;
|
||||
level?: string;
|
||||
statusMessage?: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
input?: unknown;
|
||||
output?: unknown;
|
||||
metadata?: unknown;
|
||||
environment?: string;
|
||||
userId?: string;
|
||||
sessionId?: string;
|
||||
traceName?: string;
|
||||
providedModelName?: string;
|
||||
model?: string;
|
||||
modelParameters?: unknown;
|
||||
usageDetails?: Record<string, unknown>;
|
||||
costDetails?: Record<string, unknown>;
|
||||
totalCost?: number;
|
||||
latency?: number;
|
||||
timeToFirstToken?: number;
|
||||
promptId?: string;
|
||||
promptName?: string;
|
||||
promptVersion?: number;
|
||||
};
|
||||
|
||||
export type LangfuseProject = {
|
||||
id: string;
|
||||
name: string;
|
||||
organization: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
metadata?: Record<string, unknown>;
|
||||
retentionDays?: number | null;
|
||||
};
|
||||
|
||||
export type LangfuseSession = {
|
||||
id: string;
|
||||
projectId?: string;
|
||||
createdAt?: string;
|
||||
traces?: LangfuseTraceSummary[];
|
||||
};
|
||||
|
||||
export type ObservationOutlineNode = {
|
||||
id: string;
|
||||
parentObservationId?: string;
|
||||
type?: string;
|
||||
name?: string;
|
||||
level?: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
latency?: number;
|
||||
model?: string;
|
||||
inputLength: number;
|
||||
outputLength: number;
|
||||
inputBytes: number;
|
||||
outputBytes: number;
|
||||
metadataKeys: string[];
|
||||
usageDetails?: Record<string, unknown>;
|
||||
costDetails?: Record<string, unknown>;
|
||||
totalCost?: number;
|
||||
inputPreview?: string;
|
||||
outputPreview?: string;
|
||||
children: ObservationOutlineNode[];
|
||||
};
|
||||
|
||||
export type TraceOutline = {
|
||||
projectId: string;
|
||||
trace: {
|
||||
id: string;
|
||||
projectId?: string;
|
||||
name?: string;
|
||||
sessionId?: string;
|
||||
userId?: string;
|
||||
timestamp?: string;
|
||||
environment?: string;
|
||||
tags?: string[];
|
||||
inputPreview?: string;
|
||||
outputPreview?: string;
|
||||
metadata?: unknown;
|
||||
latency?: number;
|
||||
totalCost?: number;
|
||||
};
|
||||
observations: ObservationOutlineNode[];
|
||||
flatObservationCount: number;
|
||||
warnings?: string[];
|
||||
cache?: TraceCacheInfo;
|
||||
};
|
||||
|
||||
export type CachedTrace = {
|
||||
cacheVersion: 1;
|
||||
cachedAt: string;
|
||||
project: {
|
||||
key: string;
|
||||
projectId: string;
|
||||
baseUrl: string;
|
||||
};
|
||||
trace: LangfuseTraceSummary;
|
||||
};
|
||||
|
||||
export type TraceCacheInfo = {
|
||||
path: string;
|
||||
exists: boolean;
|
||||
cachedAt?: string;
|
||||
refreshed?: boolean;
|
||||
};
|
||||
@@ -735,6 +735,53 @@ describe("sealCapabilities", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("approval run cited rules attaches mappedProdCode when test snapshot exists", async () => {
|
||||
const mappingDir = mkdtempSync(join(tmpdir(), "seal-mapping-cited-"));
|
||||
process.env.SEAL_USE_MAPPINGS_DIR = mappingDir;
|
||||
try {
|
||||
saveRuleMappingSnapshot({
|
||||
syncedAt: "2026-10-10T10:00:00+08:00",
|
||||
source: { id: "corp-prod", name: "Prod Corp" },
|
||||
target: { id: "corp-test", name: "Test Corp", publishedVersionNumber: 16, rulesCount: 1 },
|
||||
versionMapping: {
|
||||
sourceProdVersionNumber: 22,
|
||||
sourceProdVersionName: "Prod v22",
|
||||
targetTestVersionNumber: 16,
|
||||
targetTestVersionName: "Test v16"
|
||||
},
|
||||
ruleMapping: [{
|
||||
index: 0,
|
||||
sourceRuleId: "prod-rule-17",
|
||||
sourceRuleCode: 17,
|
||||
targetRuleId: "test-rule-38",
|
||||
targetRuleCode: "0038",
|
||||
description: "Prod rule 17",
|
||||
scope: "travel",
|
||||
strictness: "MUST_FOLLOW"
|
||||
}]
|
||||
});
|
||||
|
||||
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunCitedRulesGet");
|
||||
expect(tool).toBeDefined();
|
||||
|
||||
const handler = tool!.handler as CapabilityHandler;
|
||||
const context = { corp: { ...fakeContext().corp, id: "corp-test", environment: "test" as const } };
|
||||
const result = await handler(
|
||||
fakeApprovalRunsClient(),
|
||||
{ recordId: "run-1" },
|
||||
context
|
||||
) as { count: number; rules: Array<Record<string, unknown>> };
|
||||
|
||||
expect(result.rules[0]).toMatchObject({
|
||||
code: "0038",
|
||||
mappedProdCode: "0017",
|
||||
mappedProdRuleId: "prod-rule-17"
|
||||
});
|
||||
} finally {
|
||||
delete process.env.SEAL_USE_MAPPINGS_DIR;
|
||||
}
|
||||
});
|
||||
|
||||
test("approval run document summary returns key fields without raw payload", async () => {
|
||||
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunDocumentSummaryGet");
|
||||
expect(tool).toBeDefined();
|
||||
|
||||
@@ -377,10 +377,11 @@ export const approvalRunsCapabilities = [
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { recordId: string }
|
||||
params: { recordId: string },
|
||||
context: CapabilityContext
|
||||
) => {
|
||||
const record = await api.getApprovalRun(client, params.recordId);
|
||||
return extractCitedRules(record);
|
||||
return extractCitedRules(record, context.corp);
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -654,7 +655,7 @@ export const approvalRunsCapabilities = [
|
||||
|
||||
const documentSummary = summarizeApprovalRunDocument(detail);
|
||||
const resultSummary = summarizeApprovalRunResult(detail);
|
||||
const citedRules = extractCitedRules(detail);
|
||||
const citedRules = extractCitedRules(detail, context.corp);
|
||||
|
||||
let ruleVersion: {
|
||||
version: ReturnType<typeof summarizeRuleVersion>;
|
||||
|
||||
@@ -635,10 +635,30 @@ export function summarizeApprovalRunResult(record: ApprovalRun) {
|
||||
};
|
||||
}
|
||||
|
||||
export function prioritizeKeyFields(fields: Array<Record<string, unknown>>, maxCount = 60) {
|
||||
const priorityKeywords = ["金额", "费用", "报销", "申请", "借款", "付款", "部门", "事由", "收款", "公司", "抬头", "税", "类别", "项目", "说明", "币种"];
|
||||
const prioritized: Array<Record<string, unknown>> = [];
|
||||
const others: Array<Record<string, unknown>> = [];
|
||||
|
||||
for (const field of fields) {
|
||||
const label = stringFromUnknown(field.label) ?? "";
|
||||
const path = stringFromUnknown(field.path) ?? "";
|
||||
const isPriority = priorityKeywords.some((k) => label.includes(k) || path.toLowerCase().includes(k.toLowerCase()));
|
||||
if (isPriority) {
|
||||
prioritized.push(field);
|
||||
} else {
|
||||
others.push(field);
|
||||
}
|
||||
}
|
||||
|
||||
return [...prioritized, ...others].slice(0, maxCount);
|
||||
}
|
||||
|
||||
export function summarizeApprovalRunDocument(record: ApprovalRun) {
|
||||
const document = asRecord(record.document);
|
||||
const fields = flattenDocumentFields(record.document);
|
||||
const fieldText = fields.map((field) => `${field.label ?? field.path ?? ""}:${field.value ?? ""}`).join("\n");
|
||||
const prioritizedFields = prioritizeKeyFields(fields, 60);
|
||||
return {
|
||||
recordId: record.id,
|
||||
sourceDocumentSN: record.sourceDocumentSN,
|
||||
@@ -648,11 +668,44 @@ export function summarizeApprovalRunDocument(record: ApprovalRun) {
|
||||
sn: document?.sn ?? document?.sourceDocumentSN ?? record.sourceDocumentSN,
|
||||
title: document?.title ?? document?.name,
|
||||
template: firstPath(document, ["template.name", "templateName", "form.name", "formName", "formTitle"]),
|
||||
amount: firstByLabel(fields, ["金额", "报销金额", "付款金额", "合计", "价税合计"]) ?? firstPath(document, ["amount", "totalAmount", "expenseAmount"]),
|
||||
expenseType: firstByLabel(fields, ["费用类型", "费用类别", "报销类型"]),
|
||||
amount:
|
||||
firstByLabel(fields, [
|
||||
"金额",
|
||||
"报销金额",
|
||||
"付款金额",
|
||||
"申请金额",
|
||||
"借款金额",
|
||||
"实报金额",
|
||||
"总金额",
|
||||
"费用金额",
|
||||
"单据金额",
|
||||
"合计",
|
||||
"价税合计",
|
||||
"明细合计",
|
||||
"总计"
|
||||
]) ??
|
||||
firstPath(document, ["amount", "totalAmount", "expenseAmount", "applyAmount", "paymentAmount"]) ??
|
||||
fields.find((f) => {
|
||||
const path = stringFromUnknown(f.path)?.toLowerCase() ?? "";
|
||||
return path.endsWith(".amount") || path.endsWith(".totalamount");
|
||||
})?.value,
|
||||
expenseType:
|
||||
firstByLabel(fields, [
|
||||
"费用类型",
|
||||
"费用类别",
|
||||
"报销类型",
|
||||
"报销类别",
|
||||
"支出类别",
|
||||
"费用科目",
|
||||
"单据类型",
|
||||
"业务类型"
|
||||
]) ??
|
||||
firstPath(document, ["expenseType", "expenseCategory", "categoryName", "businessType"]),
|
||||
costCompany: firstByLabel(fields, ["费用承担公司", "承担公司", "成本中心", "费用归属"]),
|
||||
payee: firstByLabel(fields, ["收款方", "收款账户", "收款信息", "开户名", "银行账号"]),
|
||||
keyFields: fields.slice(0, 30)
|
||||
keyFields: prioritizedFields,
|
||||
totalFieldsCount: fields.length,
|
||||
fieldsTruncated: fields.length > prioritizedFields.length
|
||||
}),
|
||||
invoices: collectInvoiceSummary(record),
|
||||
attachments: extractApprovalRunAttachments(record, { summary: true }).attachments,
|
||||
@@ -665,7 +718,7 @@ export function summarizeApprovalRunDocument(record: ApprovalRun) {
|
||||
};
|
||||
}
|
||||
|
||||
export function extractCitedRules(record: ApprovalRun) {
|
||||
export function extractCitedRules(record: ApprovalRun, corp?: CorpConfig | string) {
|
||||
const candidates: Array<[string, unknown]> = [
|
||||
["result.rulesResult", getPath(record, "result.rulesResult")],
|
||||
["result.hitRules", getPath(record, "result.hitRules")],
|
||||
@@ -740,6 +793,35 @@ export function extractCitedRules(record: ApprovalRun) {
|
||||
});
|
||||
}
|
||||
|
||||
const corpId = typeof corp === "string" ? corp : corp?.id;
|
||||
if (corpId) {
|
||||
try {
|
||||
const snapshot = loadRuleMappingSnapshot(corpId, record.ruleSetVersionNumber ?? "latest");
|
||||
if (snapshot && snapshot.ruleMapping) {
|
||||
for (const rule of rules) {
|
||||
const ruleCode = stringFromUnknown(rule.code);
|
||||
const runtimeRuleId = stringFromUnknown(rule.runtimeRuleId);
|
||||
const codeNum = parseRuleCodeNumber(ruleCode ?? runtimeRuleId);
|
||||
const matchedItem = snapshot.ruleMapping.find((m) => {
|
||||
if (ruleCode && (String(m.targetRuleCode) === ruleCode || m.targetRuleCode === ruleCode)) return true;
|
||||
if (runtimeRuleId && (m.targetRuleId === runtimeRuleId || `rule-${m.targetRuleCode}` === runtimeRuleId)) return true;
|
||||
if (codeNum !== undefined) {
|
||||
const targetNum = parseRuleCodeNumber(m.targetRuleCode);
|
||||
if (targetNum !== undefined && targetNum === codeNum) return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
if (matchedItem) {
|
||||
const mappedCodeNum = parseRuleCodeNumber(matchedItem.sourceRuleCode);
|
||||
rule.mappedProdCode = mappedCodeNum !== undefined ? formatRuleCode(mappedCodeNum) : String(matchedItem.sourceRuleCode);
|
||||
rule.mappedProdRuleId = matchedItem.sourceRuleId;
|
||||
rule.mappingNote = `测试规则 ${ruleCode ?? runtimeRuleId} 对应生产规则 ${rule.mappedProdCode}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
return {
|
||||
recordId: record.id,
|
||||
sourceDocumentSN: record.sourceDocumentSN,
|
||||
@@ -891,6 +973,11 @@ export function findKeywordLines(text: string, keywords: string[], limit: number
|
||||
export function summarizeRunBridge(records: ApprovalRun[]) {
|
||||
return records.map((record) => {
|
||||
const summary = summarizeApprovalRun(record);
|
||||
const resolution = summary.langfuseTraceId
|
||||
? "trace"
|
||||
: summary.langfuseSessionFallback
|
||||
? "session-fallback"
|
||||
: "unresolved";
|
||||
return {
|
||||
recordId: summary.id,
|
||||
tenantId: summary.tenantId,
|
||||
@@ -903,12 +990,13 @@ export function summarizeRunBridge(records: ApprovalRun[]) {
|
||||
ruleSetVersionNumber: summary.ruleSetVersionNumber,
|
||||
ruleSetPublishedAt: summary.ruleSetPublishedAt,
|
||||
ruleSetPublishedByName: summary.ruleSetPublishedByName,
|
||||
resolution:
|
||||
summary.langfuseTraceId
|
||||
? "trace"
|
||||
: summary.langfuseSessionFallback
|
||||
? "session-fallback"
|
||||
: "unresolved"
|
||||
resolution,
|
||||
// Ready-to-run handoff into the built-in read-only Langfuse domain.
|
||||
...(summary.langfuseTraceId
|
||||
? { next: `seal-use langfuse outline ${summary.langfuseTraceId} --include-io-preview` }
|
||||
: summary.langfuseSessionFallback
|
||||
? { next: `seal-use langfuse session ${summary.langfuseSessionFallback}` }
|
||||
: {})
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ export const simulationCapabilities = [
|
||||
rejectNodeName: z.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),
|
||||
thinkingDepthOverride: z.enum(["default", "medium", "high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),
|
||||
skipInvoiceGeneration: z.boolean().optional().describe("跳过发票生成, 默认 true"),
|
||||
skipExpenseExtraction: z.boolean().optional().describe("跳过费用提取, 默认 true"),
|
||||
skipExpenseExtraction: z.boolean().optional().describe("跳过后台历史费用明细库提取(防重报检索用), 默认 true"),
|
||||
disableAttachmentCache: z.boolean().optional().describe("不使用附件缓存, 默认 false"),
|
||||
signKey: z.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),
|
||||
packageIds: z.array(z.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),
|
||||
@@ -317,8 +317,30 @@ export const simulationCapabilities = [
|
||||
console.error(
|
||||
`⏳ [Simulation] 批次 ${params.batchId} 正在轮询等待结果(单据及附件解析预计耗时 1~3 分钟;若命令转入后台可等待完成通知,或随时执行 seal-use simulation status ${params.batchId} 查看进度)...`
|
||||
);
|
||||
let retryCount = 0;
|
||||
while (true) {
|
||||
const batch = await api.getSimulationBatch(client, params.batchId);
|
||||
let batch;
|
||||
try {
|
||||
batch = await api.getSimulationBatch(client, params.batchId);
|
||||
} catch (err: unknown) {
|
||||
const isInitialPhase = Date.now() - startedAt < 15000;
|
||||
const statusStr = String(
|
||||
(err && typeof err === "object" && "status" in err ? (err as { status: unknown }).status : "") ??
|
||||
(err instanceof Error ? err.message : "")
|
||||
);
|
||||
const isNotFoundOrForbidden =
|
||||
statusStr.includes("403") || statusStr.includes("404") || statusStr.toLowerCase().includes("not found");
|
||||
if (isInitialPhase && isNotFoundOrForbidden && retryCount < 4) {
|
||||
retryCount++;
|
||||
console.error(
|
||||
`⏳ [Simulation] 批次 ${params.batchId} 刚创建,等待服务端落库就绪 (重试 ${retryCount}/4)...`
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const status = (batch.status ?? "").toLowerCase();
|
||||
if (["completed", "failed", "cancelled", "canceled"].includes(status)) {
|
||||
return {
|
||||
@@ -332,7 +354,22 @@ export const simulationCapabilities = [
|
||||
};
|
||||
}
|
||||
if (Date.now() - startedAt >= timeoutMs) {
|
||||
throw new Error(`等待模拟批次 ${params.batchId} 超时(已等待 ${(Date.now() - startedAt) / 1000}s)。可稍后执行 seal-use simulation get ${params.batchId} 查看状态`);
|
||||
console.error(
|
||||
`⏳ [Simulation] 批次 ${params.batchId} 等待超时(已等待 ${(Date.now() - startedAt) / 1000}s)。批次仍在服务端执行中。`
|
||||
);
|
||||
return {
|
||||
batchId: params.batchId,
|
||||
completed: false,
|
||||
timedOut: true,
|
||||
status: status || "running",
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
message: `等待模拟批次 ${params.batchId} 超时(已等待 ${(Date.now() - startedAt) / 1000}s)。任务仍在后台执行。`,
|
||||
next: {
|
||||
status: `seal-use simulation status ${params.batchId}`,
|
||||
getRecords: `seal-use simulation batch-records ${params.batchId}`,
|
||||
wait: `seal-use simulation wait ${params.batchId}`
|
||||
}
|
||||
};
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user