Add built-in read-only Langfuse trace domain

This commit is contained in:
gitea committed 2026-10-10 09:57:20 +08:00
1 parent e2410e6923
commit 45011c8333
31 files changed
+2823 -47

No files matched your search

+171
View File
@@ -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
View File
@@ -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",
+34
View File
@@ -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
View File
@@ -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",
+5
View File
@@ -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"],
[]
]) {
+13
View File
@@ -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: [""]
+9
View File
@@ -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;