Add built-in read-only Langfuse trace domain
This commit is contained in:
1 parent
e2410e6923
commit
45011c8333
31 files changed
+2823
-47
No files matched your search
@@ -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
|
||||
@@ -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`.
|
||||
|
||||
@@ -109,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
|
||||
|
||||
+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,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
|
||||
} : {})
|
||||
};
|
||||
|
||||
@@ -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`。
|
||||
@@ -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>;
|
||||
}
|
||||
+105
@@ -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);
|
||||
}
|
||||
+24
-24
@@ -26,11 +26,11 @@ 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", "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",
|
||||
"r", "recode", "refresh", "refresh-if-missing", "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",
|
||||
@@ -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",
|
||||
@@ -99,31 +99,31 @@ export const KNOWN_FLAGS = new Set([
|
||||
"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",
|
||||
"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",
|
||||
"selector", "session-id", "sign-key", "signKey", "silent", "silent-save", "simulation",
|
||||
"simulationBatchId", "since", "skip-expense-extraction", "skip-invoice-generation", "skipExpenseExtraction", "skipInvoiceGeneration",
|
||||
"sn", "sn-prefix", "sn-suffix", "snPrefix", "snSuffix", "snippet-only",
|
||||
"snippetOnly", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
|
||||
@@ -134,7 +134,7 @@ 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",
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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,79 @@
|
||||
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 密钥是否仍然有效");
|
||||
}
|
||||
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;
|
||||
};
|
||||
@@ -891,6 +891,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 +908,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}` }
|
||||
: {})
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user