Add Hose assist URL command

This commit is contained in:
gitea committed 2026-06-09 17:00:46 +08:00
1 parent e21006ec5f
commit ed21f97e55
8 files changed
+251 -12

No files matched your search

+13 -1
View File
@@ -226,6 +226,15 @@ async function main() {
return;
}
if (area === "approval-runs" && action === "url") {
await runTool("seal_approval_run_url_get", client, corp, {
recordId: maybeName,
sourceDocumentSN: stringOption(args.options.sourceDocumentSN),
sourceDocumentId: stringOption(args.options.sourceDocumentId)
});
return;
}
if (area === "simulation" && action === "batch-records") {
const batchId = maybeName ?? stringOption(args.options.batchId);
if (!batchId) throw new Error("Usage: seal-home simulation batch-records <batchId>");
@@ -566,7 +575,7 @@ async function diagnoseAuth(corp: CorpConfig) {
token,
public: {
uid,
hasProvisionalUrl: true
enterpriseUrl: redactSensitiveText(url)
}
};
})
@@ -957,6 +966,9 @@ Usage:
seal-home approval-runs search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true]
seal-home approval-runs pick <documentSN-or-query> [--limit 20]
seal-home approval-runs get <recordId>
seal-home approval-runs url
seal-home approval-runs url <recordId>
seal-home approval-runs url --sourceDocumentSN B26022501
seal-home approval-runs bridge [--sourceDocumentSN B26001887]
seal-home simulation batch-records <batchId>
`);
+19 -6
View File
@@ -158,18 +158,19 @@ async function fetchHoseCloseApiToken(
return {
token: closeapiToken,
url,
expiresAt: Date.now() + 7200 * 1000
};
}
async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<string> {
async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<TokenEntry> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
}
const cache = getHoseAuthCache(corp.id);
if (isFresh(cache.closeapi)) {
return cache.closeapi.token;
if (isFresh(cache.closeapi) && cache.closeapi.url) {
return cache.closeapi;
}
const openapiToken = await ensureHoseOpenapiToken(corp);
@@ -178,7 +179,19 @@ async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<string> {
...getHoseAuthCache(corp.id),
closeapi
});
return closeapi.token;
return closeapi;
}
export async function getHoseEnterpriseUrl(corp: CorpConfig): Promise<string> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
}
const url = (await ensureHoseCloseApiToken(corp)).url;
if (!url) {
throw new Error("Hose provisional auth URL was not available");
}
return url;
}
export async function getHoseSealSession(corp: CorpConfig): Promise<SealSession> {
@@ -186,13 +199,13 @@ export async function getHoseSealSession(corp: CorpConfig): Promise<SealSession>
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
}
const hoseAccessToken = await ensureHoseCloseApiToken(corp);
const hoseAccess = await ensureHoseCloseApiToken(corp);
const sealUrl = defaultSealUrl(corp, corp.source);
const sealResponse = await ky
.get(`${normalizeBaseUrl(sealUrl)}/api/auth/oauth2/session/oem-hosecloud`, {
searchParams: {
token: hoseAccessToken,
token: hoseAccess.token,
returnToken: "1"
},
timeout: 30000
+2 -1
View File
@@ -2,7 +2,8 @@ import { z } from "zod";
export const TokenEntrySchema = z.object({
token: z.string(),
expiresAt: z.number()
expiresAt: z.number(),
url: z.string().url().optional()
});
export const SealEnterpriseConfigSchema = z.object({
+140 -4
View File
@@ -1,14 +1,33 @@
import { describe, expect, test } from "bun:test";
import { afterEach, describe, expect, test } from "bun:test";
import { KyInstance } from "ky";
import { z } from "zod";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { CorpConfig } from "../../core/config/types.js";
import { findSealMcpTool, findSealTool, sealMcpTools, sealTools } from "./tools.js";
type ToolHandler = (
client: KyInstance,
params: Record<string, unknown>,
context: ReturnType<typeof fakeContext>
context: { corp: CorpConfig }
) => Promise<unknown>;
const ORIGINAL_TOKEN_STORE = process.env.SEAL_HOME_TOKEN_STORE;
const tempDirs: string[] = [];
afterEach(() => {
if (ORIGINAL_TOKEN_STORE === undefined) {
delete process.env.SEAL_HOME_TOKEN_STORE;
} else {
process.env.SEAL_HOME_TOKEN_STORE = ORIGINAL_TOKEN_STORE;
}
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("sealTools", () => {
test("exposes concrete JSON schemas for parameterized tools", () => {
const createRule = sealTools.find((tool) => tool.name === "seal_approval_rule_create");
@@ -171,6 +190,78 @@ describe("sealTools", () => {
});
});
test("approval run url returns Hose enterprise and document links by recordId", async () => {
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
expect(tool).toBeDefined();
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
const handler = tool!.handler as ToolHandler;
const result = await handler(
fakeApprovalRunsClient(),
{ recordId: "run-1" },
fakeHoseContext()
) as {
enterpriseAssistUrl?: string;
enterpriseUrl?: string;
hoseDomain?: string;
documentUrl?: string;
recordId?: string;
sourceDocumentSN?: string;
};
expect(result).toMatchObject({
enterpriseAssistUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
enterpriseUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
hoseDomain: "https://app.ekuaibao.com",
documentUrl: "https://app.ekuaibao.com/web/thirdparty.html",
recordId: "run-1",
sourceDocumentSN: "B26001965"
});
});
test("approval run url returns enterprise assist link without a document lookup", async () => {
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
expect(tool).toBeDefined();
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
const requests: string[] = [];
const handler = tool!.handler as ToolHandler;
const result = await handler(
fakeApprovalRunsClient(requests),
{},
fakeHoseContext()
) as {
enterpriseAssistUrl?: string;
enterpriseUrl?: string;
documentUrl?: string;
};
expect(requests).toEqual([]);
expect(result).toMatchObject({
enterpriseAssistUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
enterpriseUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token"
});
expect(result.documentUrl).toBeUndefined();
});
test("approval run url can resolve by sourceDocumentSN", async () => {
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
expect(tool).toBeDefined();
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
const requests: string[] = [];
const handler = tool!.handler as ToolHandler;
const result = await handler(
fakeApprovalRunsClient(requests),
{ sourceDocumentSN: "B26001965" },
fakeHoseContext()
) as { documentUrl?: string };
expect(requests[0]).toContain("sourceDocumentSN=B26001965");
expect(requests[1]).toBe("api/v1/approvals/run-1");
expect(result.documentUrl).toBe("https://app.ekuaibao.com/web/thirdparty.html");
});
test("approval run summary filters by local date and returns compact aggregates", async () => {
const tool = sealTools.find((item) => item.name === "seal_approval_runs_summary");
expect(tool).toBeDefined();
@@ -272,7 +363,7 @@ function fakeApprovalRunsClient(requests: string[] = []): KyInstance {
} as unknown as KyInstance;
}
function fakeContext() {
function fakeContext(): { corp: CorpConfig } {
return {
corp: {
id: "corp-a",
@@ -285,7 +376,9 @@ function fakeContext() {
source: {
type: "direct",
token: "token",
sealUrl: "https://seal.test"
sealUrl: "https://seal.test",
expiresIn: 3600,
staffId: "direct"
},
auth: {
refreshTtl: 300
@@ -293,3 +386,46 @@ function fakeContext() {
}
};
}
function fakeHoseContext(): { corp: CorpConfig } {
return {
corp: {
id: "corp-a",
name: "Corp A",
seal: {
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "hose",
domain: "https://app.ekuaibao.com/",
appKey: "app-key",
appSecurity: "app-secret",
staffId: "staff-a",
corpId: "hose-corp-a"
},
auth: {
refreshTtl: 300
}
}
};
}
function primeHoseEnterpriseUrl(corpId: string, url: string) {
const dir = mkdtempSync(join(tmpdir(), "seal-home-tools-"));
tempDirs.push(dir);
const storePath = join(dir, "tokens.json");
process.env.SEAL_HOME_TOKEN_STORE = storePath;
writeFileSync(storePath, JSON.stringify({
[corpId]: {
hose: {
closeapi: {
token: "close-token",
url,
expiresAt: Date.now() + 3600 * 1000
}
}
}
}));
}
+70
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { KyInstance } from "ky";
import * as api from "./api.js";
import { getHoseEnterpriseUrl } from "../../core/auth/hose.js";
import { CorpConfig } from "../../core/config/types.js";
import { searchApprovalContent } from "./search.js";
import type { ApprovalRun, RuleSetVersion } from "./types.js";
@@ -448,6 +449,41 @@ export const sealTools = [
};
}
},
{
name: "seal_approval_run_url_get",
description: "获取合思企业协助链接,按需附带单据链接;支持只取企业协助链接,或按 Seal recordId/合思 sourceDocumentSN 查询单据链接",
parameters: z.object({
recordId: z.string().optional().describe("Seal approval run record ID"),
sourceDocumentSN: z.string().optional().describe("合思/易快报单号"),
sourceDocumentId: z.string().optional().describe("合思/易快报源单据 ID")
}),
handler: async (
client: KyInstance,
params: { recordId?: string; sourceDocumentSN?: string; sourceDocumentId?: string },
context: ToolContext
) => {
const hasDocumentLookup = Boolean(params.recordId || params.sourceDocumentSN || params.sourceDocumentId);
const record = hasDocumentLookup ? await resolveApprovalRunForUrl(client, params) : undefined;
const source = context.corp.source;
const enterpriseAssistUrl = source.type === "hose" ? await getHoseEnterpriseUrl(context.corp) : undefined;
const documentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
return {
enterpriseAssistUrl,
enterpriseUrl: enterpriseAssistUrl,
hoseDomain: source.type === "hose" ? normalizeUrl(source.domain) : undefined,
documentUrl,
recordId: record?.id,
sourceDocumentSN: record?.sourceDocumentSN,
sourceDocumentId: record?.sourceDocumentId,
sourceSystem: record?.sourceSystem,
missing: {
enterpriseAssistUrl: enterpriseAssistUrl ? undefined : "Current enterprise source is not Hose, so no Hose enterprise assist URL is configured.",
documentUrl: hasDocumentLookup && !documentUrl ? "sourceExtendData.hosecloudViewUrl is absent from the approval run detail." : undefined
}
};
}
},
{
name: "seal_approval_run_pick",
description: "按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",
@@ -600,6 +636,7 @@ const sealActionNames = [
"seal_approval_style_preferences_update",
"seal_approval_runs_summary",
"seal_approval_run_get",
"seal_approval_run_url_get",
"seal_approval_run_pick",
"seal_simulation_batch_records_get",
"seal_approval_run_langfuse_bridge_get"
@@ -622,6 +659,7 @@ const sealActionAliases: Record<string, (typeof sealActionNames)[number]> = {
"style.update": "seal_approval_style_preferences_update",
"runs.summary": "seal_approval_runs_summary",
"runs.get": "seal_approval_run_get",
"runs.url": "seal_approval_run_url_get",
"runs.pick": "seal_approval_run_pick",
"batch.records.get": "seal_simulation_batch_records_get",
"langfuse.bridge.get": "seal_approval_run_langfuse_bridge_get"
@@ -842,6 +880,38 @@ function summarizeRuleVersion(version: RuleSetVersion) {
};
}
async function resolveApprovalRunForUrl(
client: KyInstance,
params: { recordId?: string; sourceDocumentSN?: string; sourceDocumentId?: string }
): Promise<ApprovalRun> {
if (params.recordId) {
return api.getApprovalRun(client, params.recordId);
}
const data = await api.listApprovalRuns(client, {
limit: 1,
sourceDocumentSN: params.sourceDocumentSN,
sourceDocumentId: params.sourceDocumentId
});
const record = data.records[0];
if (!record) {
const lookup = params.sourceDocumentSN
? `sourceDocumentSN ${params.sourceDocumentSN}`
: `sourceDocumentId ${params.sourceDocumentId}`;
throw new Error(`Approval run not found for ${lookup}`);
}
return api.getApprovalRun(client, record.id);
}
function normalizeUrl(value: string): string {
return value.replace(/\/+$/, "");
}
function stringFromUnknown(value: unknown): string | undefined {
return typeof value === "string" && value.trim() ? value : undefined;
}
async function pickApprovalRuns(
client: KyInstance,
params: { query: string; limit: number; maxScan: number }