Add Seal approval run Langfuse bridge tools
This commit is contained in:
1 parent
d6a33de3d7
commit
0cc1f591dc
8 files changed
+392
-2
No files matched your search
@@ -56,3 +56,25 @@ For an already-authenticated Seal source, copy `enterprises/example.direct.json`
|
||||
- `seal_approval_rule_versions_list`, `seal_approval_rule_version_publish`: read and publish rule versions.
|
||||
- `seal_approval_documents_list`, `seal_approval_document_get`, `seal_approval_document_create`, `seal_approval_document_update`: maintain approval documents.
|
||||
- `seal_approval_style_preferences_get`, `seal_approval_style_preferences_update`: read and update approval style preferences.
|
||||
- `seal_approval_runs_search`: search the approval run history from `api/v1/approvals`. This is the broad record table for historical runs and returns compact bridge fields for locating Langfuse context.
|
||||
- `seal_simulation_batch_records_get`: read records from one simulation batch via `api/v1/simulation/batch/{batchId}/records`.
|
||||
- `seal_approval_run_langfuse_bridge_get`: resolve approval run records to Langfuse lookup hints. It prefers `sourceExtendData._langfuseTraceId`; if that is missing, it returns `hosecloud-{sourceDocumentSN}` as the session fallback.
|
||||
|
||||
## Approval Run To Langfuse Bridge
|
||||
|
||||
Seal approval runs and simulation batch records are treated as two views over the same run data:
|
||||
|
||||
- `api/v1/approvals` is the total approval run list. Use it for history search by time, status, task mode, source document SN, or source document ID.
|
||||
- `api/v1/simulation/batch/{batchId}/records` is the detail list for one simulation batch. Use it when the user is already looking at a simulation batch.
|
||||
|
||||
The useful join fields for Langfuse work are:
|
||||
|
||||
- `sourceDocumentSN`
|
||||
- `sourceDocumentId`
|
||||
- `tenantId`
|
||||
- `agentId`
|
||||
- approval run `id`
|
||||
- `sourceExtendData._langfuseTraceId`
|
||||
- `sourceExtendData.simulation_batch_id`
|
||||
|
||||
When `_langfuseTraceId` exists, downstream tools should fetch the trace directly. When it is absent, use `hosecloud-{sourceDocumentSN}` as the Langfuse session fallback.
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { CorpConfig } from "./types.js";
|
||||
import { CorpContext } from "./manager.js";
|
||||
|
||||
function corp(id: string, name = id): CorpConfig {
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
seal: {
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
||||
}
|
||||
},
|
||||
source: {
|
||||
type: "direct",
|
||||
token: `${id}-token`,
|
||||
sealUrl: `https://${id}.seal.test`,
|
||||
expiresIn: 3600,
|
||||
staffId: "direct"
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe("CorpContext", () => {
|
||||
test("refresh adds newly loaded corps", () => {
|
||||
const context = new CorpContext([corp("corp-a")]);
|
||||
|
||||
context.refresh([corp("corp-a"), corp("corp-b")]);
|
||||
|
||||
expect(context.listCorps().map((item) => item.id)).toEqual(["corp-a", "corp-b"]);
|
||||
});
|
||||
|
||||
test("refresh keeps the selected corp when it still exists", () => {
|
||||
const context = new CorpContext([corp("corp-a"), corp("corp-b")]);
|
||||
expect(context.switchCorp("corp-b")).toBe(true);
|
||||
|
||||
context.refresh([corp("corp-a"), corp("corp-b", "Corp B updated")]);
|
||||
|
||||
expect(context.getCurrent()?.id).toBe("corp-b");
|
||||
expect(context.getCurrent()?.name).toBe("Corp B updated");
|
||||
});
|
||||
|
||||
test("refresh falls back when the selected corp disappears", () => {
|
||||
const context = new CorpContext([corp("corp-a"), corp("corp-b")]);
|
||||
expect(context.switchCorp("corp-b")).toBe(true);
|
||||
|
||||
context.refresh([corp("corp-c")]);
|
||||
|
||||
expect(context.getCurrent()?.id).toBe("corp-c");
|
||||
});
|
||||
});
|
||||
@@ -2,13 +2,25 @@ import { CorpConfig } from "./types.js";
|
||||
|
||||
export class CorpContext {
|
||||
private current: CorpConfig | null = null;
|
||||
private readonly corps = new Map<string, CorpConfig>();
|
||||
private corps = new Map<string, CorpConfig>();
|
||||
|
||||
constructor(corps: CorpConfig[]) {
|
||||
this.replaceCorps(corps);
|
||||
this.current = corps[0] ?? null;
|
||||
}
|
||||
|
||||
refresh(corps: CorpConfig[]): void {
|
||||
const currentId = this.current?.id ?? null;
|
||||
this.replaceCorps(corps);
|
||||
this.current = currentId ? this.corps.get(currentId) ?? null : null;
|
||||
this.current ??= corps[0] ?? null;
|
||||
}
|
||||
|
||||
private replaceCorps(corps: CorpConfig[]): void {
|
||||
this.corps = new Map();
|
||||
for (const corp of corps) {
|
||||
this.corps.set(corp.id, corp);
|
||||
}
|
||||
this.current = corps[0] ?? null;
|
||||
}
|
||||
|
||||
getCurrent(): CorpConfig | null {
|
||||
|
||||
@@ -4,6 +4,10 @@ import {
|
||||
ApprovalDocumentListData,
|
||||
ApprovalDocumentListDataSchema,
|
||||
ApprovalDocumentSchema,
|
||||
ApprovalRun,
|
||||
ApprovalRunListData,
|
||||
ApprovalRunListDataSchema,
|
||||
ApprovalRunSchema,
|
||||
ApprovalRulesData,
|
||||
ApprovalRulesDataSchema,
|
||||
ApprovalRule,
|
||||
@@ -213,3 +217,56 @@ export async function getApprovalContext(
|
||||
stylePreferences
|
||||
};
|
||||
}
|
||||
|
||||
export async function listApprovalRuns(
|
||||
client: KyInstance,
|
||||
params: {
|
||||
offset?: number;
|
||||
limit?: number;
|
||||
fromTimestamp?: string;
|
||||
toTimestamp?: string;
|
||||
status?: string;
|
||||
taskMode?: string;
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
} = {}
|
||||
): Promise<ApprovalRunListData> {
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set("offset", String(params.offset ?? 0));
|
||||
searchParams.set("limit", String(params.limit ?? 50));
|
||||
|
||||
setOptional(searchParams, "fromTimestamp", params.fromTimestamp);
|
||||
setOptional(searchParams, "toTimestamp", params.toTimestamp);
|
||||
setOptional(searchParams, "status", params.status);
|
||||
setOptional(searchParams, "taskMode", params.taskMode);
|
||||
setOptional(searchParams, "sourceDocumentSN", params.sourceDocumentSN);
|
||||
setOptional(searchParams, "sourceDocumentId", params.sourceDocumentId);
|
||||
|
||||
return unwrap(
|
||||
await client.get("api/v1/approvals", { searchParams }),
|
||||
ApprovalRunListDataSchema
|
||||
);
|
||||
}
|
||||
|
||||
export async function listSimulationBatchRecords(
|
||||
client: KyInstance,
|
||||
batchId: string
|
||||
): Promise<ApprovalRun[]> {
|
||||
const json = (await client
|
||||
.get(`api/v1/simulation/batch/${batchId}/records`)
|
||||
.json()) as { data?: unknown };
|
||||
const data = json.data ?? json;
|
||||
|
||||
if (Array.isArray(data)) {
|
||||
return z.array(ApprovalRunSchema).parse(data);
|
||||
}
|
||||
|
||||
const parsed = ApprovalRunListDataSchema.parse(data);
|
||||
return parsed.records;
|
||||
}
|
||||
|
||||
function setOptional(searchParams: URLSearchParams, key: string, value?: string) {
|
||||
if (value) {
|
||||
searchParams.set(key, value);
|
||||
}
|
||||
}
|
||||
@@ -34,4 +34,10 @@ describe("sealTools", () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_search");
|
||||
expect(tool).toBeDefined();
|
||||
});
|
||||
|
||||
test("includes approval run Langfuse bridge tools", () => {
|
||||
expect(sealTools.find((item) => item.name === "seal_approval_runs_search")).toBeDefined();
|
||||
expect(sealTools.find((item) => item.name === "seal_simulation_batch_records_get")).toBeDefined();
|
||||
expect(sealTools.find((item) => item.name === "seal_approval_run_langfuse_bridge_get")).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { KyInstance } from "ky";
|
||||
import * as api from "./api.js";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { searchApprovalContent } from "./search.js";
|
||||
import type { ApprovalRun } from "./types.js";
|
||||
|
||||
type ToolContext = {
|
||||
corp: CorpConfig;
|
||||
@@ -242,7 +243,204 @@ export const sealTools = [
|
||||
params,
|
||||
context.corp.seal.endpoints.approvalStylePreferences
|
||||
)
|
||||
},
|
||||
{
|
||||
name: "seal_approval_runs_search",
|
||||
description: "查询 Seal 审批/审核运行记录总表,并整理合思单据到 Langfuse trace/session 的桥接字段",
|
||||
parameters: z.object({
|
||||
offset: z.number().int().nonnegative().optional(),
|
||||
limit: z.number().int().positive().max(100).optional(),
|
||||
fromTimestamp: z.string().optional(),
|
||||
toTimestamp: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
taskMode: z.string().optional(),
|
||||
sourceDocumentSN: z.string().optional(),
|
||||
sourceDocumentId: z.string().optional(),
|
||||
query: z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
offset?: number;
|
||||
limit?: number;
|
||||
fromTimestamp?: string;
|
||||
toTimestamp?: string;
|
||||
status?: string;
|
||||
taskMode?: string;
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
query?: string;
|
||||
}
|
||||
) => {
|
||||
const data = await api.listApprovalRuns(client, params);
|
||||
const records = filterRuns(data.records, params.query);
|
||||
|
||||
return {
|
||||
...data,
|
||||
records: records.map(summarizeApprovalRun),
|
||||
bridge: summarizeRunBridge(records)
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_simulation_batch_records_get",
|
||||
description: "获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",
|
||||
parameters: z.object({
|
||||
batchId: z.string().describe("simulation batch ID"),
|
||||
query: z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { batchId: string; query?: string }
|
||||
) => {
|
||||
const records = filterRuns(
|
||||
await api.listSimulationBatchRecords(client, params.batchId),
|
||||
params.query
|
||||
);
|
||||
|
||||
return {
|
||||
batchId: params.batchId,
|
||||
count: records.length,
|
||||
records: records.map(summarizeApprovalRun),
|
||||
bridge: summarizeRunBridge(records)
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_run_langfuse_bridge_get",
|
||||
description: "从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退",
|
||||
parameters: z.object({
|
||||
recordId: z.string().optional(),
|
||||
sourceDocumentSN: z.string().optional(),
|
||||
sourceDocumentId: z.string().optional(),
|
||||
simulationBatchId: z.string().optional(),
|
||||
limit: z.number().int().positive().max(100).optional()
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
recordId?: string;
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
simulationBatchId?: string;
|
||||
limit?: number;
|
||||
}
|
||||
) => {
|
||||
const records = params.simulationBatchId
|
||||
? await api.listSimulationBatchRecords(client, params.simulationBatchId)
|
||||
: (await api.listApprovalRuns(client, {
|
||||
limit: params.limit ?? 50,
|
||||
sourceDocumentSN: params.sourceDocumentSN,
|
||||
sourceDocumentId: params.sourceDocumentId
|
||||
})).records;
|
||||
|
||||
const filtered = records.filter((record) =>
|
||||
matchesRunLookup(record, {
|
||||
recordId: params.recordId,
|
||||
sourceDocumentSN: params.sourceDocumentSN,
|
||||
sourceDocumentId: params.sourceDocumentId
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
count: filtered.length,
|
||||
records: filtered.map(summarizeApprovalRun),
|
||||
bridge: summarizeRunBridge(filtered)
|
||||
};
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
export type SealTool = (typeof sealTools)[number];
|
||||
|
||||
type ApprovalRunSummary = {
|
||||
id: string;
|
||||
tenantId?: string;
|
||||
agentId?: string;
|
||||
status?: string;
|
||||
taskMode?: string;
|
||||
finalExecutionMode?: string;
|
||||
sourceSystem?: string;
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
documentId?: string;
|
||||
simulationBatchId?: string;
|
||||
langfuseTraceId?: string;
|
||||
langfuseSessionFallback?: string;
|
||||
createdAt?: string | number;
|
||||
updatedAt?: string | number;
|
||||
};
|
||||
|
||||
function summarizeApprovalRun(record: ApprovalRun): ApprovalRunSummary {
|
||||
const sourceDocumentSN = record.sourceDocumentSN;
|
||||
|
||||
return {
|
||||
id: record.id,
|
||||
tenantId: record.tenantId,
|
||||
agentId: record.agentId,
|
||||
status: record.status,
|
||||
taskMode: record.taskMode,
|
||||
finalExecutionMode: record.finalExecutionMode,
|
||||
sourceSystem: record.sourceSystem,
|
||||
sourceDocumentSN,
|
||||
sourceDocumentId: record.sourceDocumentId,
|
||||
documentId: record.documentId,
|
||||
simulationBatchId: record.sourceExtendData?.simulation_batch_id,
|
||||
langfuseTraceId: record.sourceExtendData?._langfuseTraceId,
|
||||
langfuseSessionFallback: sourceDocumentSN ? `hosecloud-${sourceDocumentSN}` : undefined,
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt
|
||||
};
|
||||
}
|
||||
|
||||
function summarizeRunBridge(records: ApprovalRun[]) {
|
||||
return records.map((record) => {
|
||||
const summary = summarizeApprovalRun(record);
|
||||
return {
|
||||
recordId: summary.id,
|
||||
tenantId: summary.tenantId,
|
||||
agentId: summary.agentId,
|
||||
sourceDocumentSN: summary.sourceDocumentSN,
|
||||
sourceDocumentId: summary.sourceDocumentId,
|
||||
simulationBatchId: summary.simulationBatchId,
|
||||
langfuseTraceId: summary.langfuseTraceId,
|
||||
langfuseSessionFallback: summary.langfuseSessionFallback,
|
||||
resolution:
|
||||
summary.langfuseTraceId
|
||||
? "trace"
|
||||
: summary.langfuseSessionFallback
|
||||
? "session-fallback"
|
||||
: "unresolved"
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function filterRuns(records: ApprovalRun[], query?: string): ApprovalRun[] {
|
||||
const normalized = query?.trim().toLowerCase();
|
||||
if (!normalized) return records;
|
||||
|
||||
return records.filter((record) =>
|
||||
[
|
||||
record.id,
|
||||
record.sourceDocumentSN,
|
||||
record.sourceDocumentId,
|
||||
record.documentId,
|
||||
record.sourceExtendData?._langfuseTraceId,
|
||||
record.sourceExtendData?.simulation_batch_id
|
||||
].some((value) => value?.toLowerCase().includes(normalized))
|
||||
);
|
||||
}
|
||||
|
||||
function matchesRunLookup(
|
||||
record: ApprovalRun,
|
||||
lookup: {
|
||||
recordId?: string;
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
}
|
||||
): boolean {
|
||||
if (lookup.recordId && record.id !== lookup.recordId) return false;
|
||||
if (lookup.sourceDocumentSN && record.sourceDocumentSN !== lookup.sourceDocumentSN) return false;
|
||||
if (lookup.sourceDocumentId && record.sourceDocumentId !== lookup.sourceDocumentId) return false;
|
||||
return true;
|
||||
}
|
||||
@@ -175,6 +175,44 @@ export const ApprovalStylePreferencesSchema = z.object({
|
||||
integrations: z.array(ApprovalIntegrationSchema).default([])
|
||||
}).passthrough();
|
||||
|
||||
export const ApprovalRunDocumentSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
sn: z.string().optional(),
|
||||
title: z.string().optional(),
|
||||
name: z.string().optional()
|
||||
}).passthrough();
|
||||
|
||||
export const ApprovalRunSourceExtendDataSchema = z.object({
|
||||
_langfuseTraceId: z.string().optional(),
|
||||
simulation_batch_id: z.string().optional()
|
||||
}).passthrough();
|
||||
|
||||
export const ApprovalRunSchema = z.object({
|
||||
id: z.string(),
|
||||
tenantId: z.string().optional(),
|
||||
agentId: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
taskMode: z.string().optional(),
|
||||
finalExecutionMode: z.string().optional(),
|
||||
sourceSystem: z.string().optional(),
|
||||
sourceDocumentSN: z.string().optional(),
|
||||
sourceDocumentId: z.string().optional(),
|
||||
documentId: z.string().optional(),
|
||||
document: ApprovalRunDocumentSchema.optional(),
|
||||
result: z.unknown().optional(),
|
||||
pipelineData: z.unknown().optional(),
|
||||
sourceExtendData: ApprovalRunSourceExtendDataSchema.optional(),
|
||||
createdAt: z.union([z.string(), z.number()]).optional(),
|
||||
updatedAt: z.union([z.string(), z.number()]).optional()
|
||||
}).passthrough();
|
||||
|
||||
export const ApprovalRunListDataSchema = z.object({
|
||||
records: z.array(ApprovalRunSchema).default([]),
|
||||
total: z.number().optional(),
|
||||
page: z.number().optional(),
|
||||
pageSize: z.number().optional()
|
||||
}).passthrough();
|
||||
|
||||
export type MeData = z.infer<typeof MeDataSchema>;
|
||||
export type SealSessionData = z.infer<typeof SealSessionDataSchema>;
|
||||
export type ApprovalRule = z.infer<typeof ApprovalRuleSchema>;
|
||||
@@ -185,3 +223,5 @@ export type ApprovalDocumentListData = z.infer<typeof ApprovalDocumentListDataSc
|
||||
export type DecisionPreferences = z.infer<typeof DecisionPreferencesSchema>;
|
||||
export type ApprovalIntegration = z.infer<typeof ApprovalIntegrationSchema>;
|
||||
export type ApprovalStylePreferences = z.infer<typeof ApprovalStylePreferencesSchema>;
|
||||
export type ApprovalRun = z.infer<typeof ApprovalRunSchema>;
|
||||
export type ApprovalRunListData = z.infer<typeof ApprovalRunListDataSchema>;
|
||||
@@ -60,6 +60,7 @@ async function main() {
|
||||
|
||||
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||
const { name, arguments: args } = request.params;
|
||||
corpContext.refresh(loadCorpConfigs());
|
||||
|
||||
if (name === "seal_corps_list") {
|
||||
return textResult(corpContext.listCorps());
|
||||
|
||||
Reference in new issue
Block a user