From ed9fa979e0be8b07789b3e2e9247a8d82f3ab048 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 21 Oct 2026 10:33:27 +0800 Subject: [PATCH] feat(assist-platform): add assist platform automation and tenant onboarding - Add SSO QR status poller and assist platform HTTP client - Add assist-platform session store with 0600 secure permissions - Implement domains/assist-platform (api, services, types) for corporation search, detail, tickets, staff query and passwordless token generation - Implement cli/commands/assist-platform with aliases assist-center and ap - Support seamless --save --switch --elevate pipeline to import tenant and extract persistent OpenAPI credentials - Update embedded skill documentation, reference guide, and test suites --- skills/hose-use/SKILL.md | 1 + skills/hose-use/references/assist-platform.md | 114 +++++++++ src/cli/command-metadata.ts | 38 +++ src/cli/commands/assist-platform.test.ts | 130 ++++++++++ src/cli/commands/assist-platform/common.ts | 27 ++ src/cli/commands/assist-platform/detail.ts | 78 ++++++ src/cli/commands/assist-platform/enter.ts | 145 +++++++++++ src/cli/commands/assist-platform/index.ts | 96 +++++++ src/cli/commands/assist-platform/login.ts | 100 ++++++++ src/cli/commands/assist-platform/search.ts | 64 +++++ src/cli/commands/assist-platform/staff.ts | 67 +++++ src/cli/commands/assist-platform/tickets.ts | 63 +++++ src/cli/registry.ts | 6 + src/core/auth/assist-platform-store.ts | 73 ++++++ src/core/http/assist-platform-client.ts | 45 ++++ src/core/http/sso-client.ts | 69 ++++++ src/domains/README.domains.md | 4 +- .../assist-platform/README.assist-platform.md | 26 ++ src/domains/assist-platform/api.ts | 234 ++++++++++++++++++ .../assist-platform/assist-platform.test.ts | 193 +++++++++++++++ src/domains/assist-platform/index.ts | 2 + src/domains/assist-platform/services.ts | 155 ++++++++++++ src/domains/assist-platform/types.ts | 77 ++++++ src/packaging/embedded-skill.test.ts | 4 +- src/packaging/embedded-skill.ts | 2 + 25 files changed, 1811 insertions(+), 2 deletions(-) create mode 100644 skills/hose-use/references/assist-platform.md create mode 100644 src/cli/commands/assist-platform.test.ts create mode 100644 src/cli/commands/assist-platform/common.ts create mode 100644 src/cli/commands/assist-platform/detail.ts create mode 100644 src/cli/commands/assist-platform/enter.ts create mode 100644 src/cli/commands/assist-platform/index.ts create mode 100644 src/cli/commands/assist-platform/login.ts create mode 100644 src/cli/commands/assist-platform/search.ts create mode 100644 src/cli/commands/assist-platform/staff.ts create mode 100644 src/cli/commands/assist-platform/tickets.ts create mode 100644 src/core/auth/assist-platform-store.ts create mode 100644 src/core/http/assist-platform-client.ts create mode 100644 src/core/http/sso-client.ts create mode 100644 src/domains/assist-platform/README.assist-platform.md create mode 100644 src/domains/assist-platform/api.ts create mode 100644 src/domains/assist-platform/assist-platform.test.ts create mode 100644 src/domains/assist-platform/index.ts create mode 100644 src/domains/assist-platform/services.ts create mode 100644 src/domains/assist-platform/types.ts diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index 2b8515b..cef80fc 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -67,6 +67,7 @@ metadata: | 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](references/auth.md) | | 生成企业合思 Web 免密登录直达链接 (`thirdparty.html`) | `hose-use corps link [企业ID|名称]`, `hose-use auth hose-link` | [references/auth.md](references/auth.md) | | 第三方免密/协助链接一键导入(自动提取持久化密钥) | `hose-use corps add-link --yes`, `hose-use corps elevate [企业ID] --yes` | [references/auth.md](references/auth.md) | +| 合思协助平台(Unity 运营平台)扫码登录/租户全量库/工单/指定身份直通 | `hose-use assist-platform login/search/detail/tickets/staff/enter` | [references/assist-platform.md](references/assist-platform.md) | | OpenAPI 密钥持久化接入 / 从链接提取密钥 | `hose-use corps add-persistent`, `hose-use corps extract-keys ` | [references/auth.md](references/auth.md) | | 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](references/auth.md) | | 企业租户切换 / 查看当前企业 | `hose-use corps list`, `hose-use corps switch ` | [references/auth.md](references/auth.md) | diff --git a/skills/hose-use/references/assist-platform.md b/skills/hose-use/references/assist-platform.md new file mode 100644 index 0000000..2ac82c3 --- /dev/null +++ b/skills/hose-use/references/assist-platform.md @@ -0,0 +1,114 @@ +# 合思协助平台(Unity 运营中心) + +本专卷覆盖对接合思官方内部运营平台(Unity Assist Platform,`https://unity.ekuaibao.com/platform-charge/`)及其统一身份认证(SSO,`https://sso.hosecloud.com`)的自动化能力。 + +合思协助平台是面向实施、运维与服务团队的专属运营系统(管理 34 万+ 企业租户库),与终端企业 SaaS 门户(`app.ekuaibao.com`)互为独立站点。通过本模块,Agent 可完成从扫码登录、多租户全量库检索、协助工单提取、指定员工身份免密换票,到自动将目标企业一键持久化落盘至本地名录的全流程。 + +支持顶层命令:`hose-use assist-platform`(别名:`hose-use assist-center`, `hose-use ap`)。 + +--- + +## 1. 协助平台会话登录 (`login`) + +协助平台基于合思 SSO 进行钉钉扫码登录。本工具支持自动轮询二维码状态,也支持直接导入已有 Session Token。 + +```bash +# 检查当前协助平台的登录状态与有效性 +hose-use assist-platform login --status + +# 交互式二维码登录(输出终端二维码,并监听钉钉扫码与确认事件) +hose-use assist-platform login + +# 直接绑定已有 Token 会话并持久化 +hose-use assist-platform login --token + +# 退出协助平台登录态 +hose-use assist-platform login --logout +``` + +凭证安全落盘位置:`~/.config/hose-use/assist-platform.json`(权限 0600)。 + +--- + +## 2. 检索企业库 (`search` / `detail`) + +在拥有 34 万+ 企业的全量库中检索目标租户,获取企业 ID 与基本信息。 + +```bash +# 按关键词或企业 ID 检索企业 +hose-use assist-platform search "示例公司" +hose-use assist-platform search "Cxa3oOtQi2eS$g" --json + +# 查看企业详细画像(创建时间、版本、授权范围、联系人及备注) +hose-use assist-platform detail "Cxa3oOtQi2eS$g" +``` + +--- + +## 3. 协助工单探查 (`tickets`) + +协助平台进入客户租户必须依赖有效的协助工单。 + +```bash +# 查询指定企业当前所有协助工单 +hose-use assist-platform tickets <企业ID> + +# 查看历史全部工单(包含已结束/已撤回) +hose-use assist-platform tickets <企业ID> --all --limit 20 +``` + +工单信息包含:工单编号 (`ticketId`)、申请人、申请事由、起始时间与过期时间。 + +--- + +## 4. 员工名录检索 (`staff`) + +当需要以客户企业内特定员工身份(而非主管理员)代客进入时,可通过 `staff` 检索目标人员的 `staffId`。 + +```bash +# 按姓名精确或模糊搜索员工 +hose-use assist-platform staff <企业ID> --name "李志财" + +# 按手机号或工号过滤 +hose-use assist-platform staff <企业ID> --mobile "13800000000" +``` + +--- + +## 5. 免密代客进入与自动落盘 (`enter`) + +基于选定工单与身份(管理员或指定员工),向协助平台换取免密直通链接,并支持一键落盘到本地企业库和自动提权。 + +```bash +# 1. 仅获取免密直达 URL 与临时 Token(默认自动寻找最新有效工单) +hose-use assist-platform enter <企业ID> + +# 2. 以主管理员身份进入 +hose-use assist-platform enter <企业ID> --admin + +# 3. 指定员工姓名代客进入(内部自动匹配员工库 staffId) +hose-use assist-platform enter <企业ID> --name "李志财" + +# 4. 指定工单 ID 与 staffId 进入 +hose-use assist-platform enter <企业ID> --ticket --staff + +# 5. 【推荐一键流】获取免密链接后,自动落盘至本地企业名录并切换为当前上下文 +hose-use assist-platform enter <企业ID> --name "李志财" --save --switch + +# 6. 【高阶全自动】落盘并自动提权(换取永久 OpenAPI 密钥,避免 2 小时临时 Token 过期中断业务) +hose-use assist-platform enter <企业ID> --name "李志财" --save --switch --elevate +``` + +### 参数说明 + +| 参数 | 说明 | +|---|---| +| `` | 目标企业 ID(必填) | +| `--ticket ` | 指定协助工单 ID(缺省时自动采用最新有效工单) | +| `--admin` | 以企业主管理员身份进入 | +| `--staff ` | 指定代客员工的内部 ID (`staffId`) | +| `--name <姓名>` | 指定代客员工的真实姓名(自动检索匹配并转换) | +| `--save` | 换取成功后直接调用底层能力导入本地企业名录(`enterprises/.json`) | +| `--switch` | 导入后自动切换为当前活跃企业租户 | +| `--elevate` | 导入后自动探测并保存持久化 OpenAPI Key 与 Secret,实现长期免密接入 | +| `--json` | 输出结构化 JSON 结果 | diff --git a/src/cli/command-metadata.ts b/src/cli/command-metadata.ts index b275a9b..2e06b54 100644 --- a/src/cli/command-metadata.ts +++ b/src/cli/command-metadata.ts @@ -770,6 +770,44 @@ export const COMMAND_METADATA: Record = { "aliases": [], "commandAliases": {}, flags: { } + }, + "assist-platform": { + "summary": "合思协助/运营平台 (Assist Platform) 自动化运维", + "usage": "hose-use assist-platform <子命令> [参数] [选项]", + "commands": { + "login": "查看或保存协助平台凭证会话", + "search": "在协助中心 34 万家企业库中分页检索企业", + "detail": "查看企业详细业务配置与开通商品能力", + "tickets": "查询指定企业的协助工单与授权码", + "staff": "查询企业内部员工工号与角色", + "enter": "一键换取免密直通链接并落盘为本地工作企业", + "help": "查看帮助信息" + }, + "aliases": [ + "assist-center", + "ap" + ], + "commandAliases": { + "auth": "login", + "status": "login", + "find": "search", + "list": "search", + "ls": "search", + "info": "detail", + "config": "detail", + "ticket": "tickets", + "order": "tickets", + "orders": "tickets", + "user": "staff", + "users": "staff", + "import": "enter", + "token": "enter", + "get-token": "enter" + }, + flags: { + ...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff alias corp-name count limit n start offset state status corpid id keyword query q", "value"), + ...flagList("logout admin save import persist switch current overwrite", "boolean") + } } }; diff --git a/src/cli/commands/assist-platform.test.ts b/src/cli/commands/assist-platform.test.ts new file mode 100644 index 0000000..0ac21ca --- /dev/null +++ b/src/cli/commands/assist-platform.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it, beforeEach } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { handleAssistPlatformCommand } from "./assist-platform/index.js"; +import { + saveAssistPlatformSession, + clearAssistPlatformSession, +} from "../../core/auth/assist-platform-store.js"; +import type { CliParsedArgs, CliRuntime } from "../types.js"; + +function createMockRuntime(enterprisesDir: string): CliRuntime { + return { + jsonMode: false, + selectedCorp: null, + corpContext: { + enterprisesDir, + corps: new Map(), + stateful: true, + current: undefined, + defaultCorpId: undefined, + getCorp: () => undefined, + switchCorp: () => true, + listCorps: () => [], + getAllCorps: () => [], + } as any, + }; +} + +describe("CLI Commands - assist-platform (合思协助平台)", () => { + let tempDir: string; + + beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), "hose-assist-test-")); + process.env.HOSE_STATE_DIR = tempDir; + clearAssistPlatformSession(); + }); + + it("assist-platform help 输出完整使用指南与子命令", async () => { + const runtime = createMockRuntime(tempDir); + const parsed: CliParsedArgs = { + action: "help", + args: [], + options: {}, + raw: ["assist-platform", "help"], + }; + + const res = await handleAssistPlatformCommand(parsed, runtime); + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("合思协助平台"); + expect(res.stdout).toContain("login"); + expect(res.stdout).toContain("search"); + expect(res.stdout).toContain("tickets"); + expect(res.stdout).toContain("enter"); + expect(res.stdout).toContain("assist-center"); + }); + + it("assist-platform login 无凭证时给出指引", async () => { + const runtime = createMockRuntime(tempDir); + const parsed: CliParsedArgs = { + action: "login", + args: [], + options: {}, + raw: ["assist-platform", "login"], + }; + + const res = await handleAssistPlatformCommand(parsed, runtime); + expect(res.exitCode).toBe(1); + expect(res.stderr).toContain("未检测到协助平台登录凭证"); + }); + + it("assist-platform login --logout 能够注销凭证", async () => { + saveAssistPlatformSession({ + token: "mock-token", + userName: "测试人员", + baseUrl: "https://unity.ekuaibao.com/api", + updatedAt: Date.now(), + }); + + const runtime = createMockRuntime(tempDir); + const parsed: CliParsedArgs = { + action: "login", + args: [], + options: { logout: true }, + raw: ["assist-platform", "login", "--logout"], + }; + + const res = await handleAssistPlatformCommand(parsed, runtime); + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("已成功注销"); + }); + + it("未登录时运行 tickets 提示需要先登录", async () => { + const runtime = createMockRuntime(tempDir); + const parsed: CliParsedArgs = { + action: "tickets", + args: ["Cxa3oOtQi2eS$g"], + options: {}, + raw: ["assist-platform", "tickets", "Cxa3oOtQi2eS$g"], + }; + + try { + await handleAssistPlatformCommand(parsed, runtime); + expect(true).toBe(false); + } catch (err: any) { + expect(err.message).toContain("未检测到协助平台登录凭证"); + } + }); + + it("assist-platform enter --save --dry-run 能够输出变更预览", async () => { + saveAssistPlatformSession({ + token: "mock-token", + userName: "测试人员", + baseUrl: "https://unity.ekuaibao.com/api", + updatedAt: Date.now(), + }); + + const runtime = createMockRuntime(tempDir); + const parsed: CliParsedArgs = { + action: "enter", + args: ["Cxa3oOtQi2eS$g"], + options: { save: true, dryRun: true }, + raw: ["assist-platform", "enter", "Cxa3oOtQi2eS$g", "--save", "--dry-run"], + }; + + const res = await handleAssistPlatformCommand(parsed, runtime); + expect(res.stdout).toContain("[DRY-RUN]"); + expect(res.stdout).toContain("Cxa3oOtQi2eS$g"); + }); +}); diff --git a/src/cli/commands/assist-platform/common.ts b/src/cli/commands/assist-platform/common.ts new file mode 100644 index 0000000..cce7621 --- /dev/null +++ b/src/cli/commands/assist-platform/common.ts @@ -0,0 +1,27 @@ +import { loadAssistPlatformSession } from "../../../core/auth/assist-platform-store.js"; +import { createAssistPlatformClient } from "../../../core/http/assist-platform-client.js"; +import { stringOption } from "../../parser.js"; +import type { CliParsedArgs, CliRuntime } from "../../types.js"; +import { AuthenticationError } from "../../../core/errors.js"; +import type { KyInstance } from "ky"; + +export function resolveAssistClient( + parsed: CliParsedArgs, + _runtime: CliRuntime +): KyInstance { + const explicitToken = stringOption(parsed.options, ["token", "t"]); + const session = loadAssistPlatformSession(); + const token = explicitToken || session?.token; + + if (!token || !token.trim()) { + throw new AuthenticationError( + "未检测到协助平台登录凭证。请先运行: hose-use assist-platform login --token " + ); + } + + return createAssistPlatformClient({ + token: token.trim(), + hoseAccessToken: session?.hoseAccessToken, + baseUrl: session?.baseUrl, + }); +} diff --git a/src/cli/commands/assist-platform/detail.ts b/src/cli/commands/assist-platform/detail.ts new file mode 100644 index 0000000..4e44e18 --- /dev/null +++ b/src/cli/commands/assist-platform/detail.ts @@ -0,0 +1,78 @@ +import { getCorporationDetail } from "../../../domains/assist-platform/services.js"; +import { stringOption } from "../../parser.js"; +import { printJson, printKeyValue, printTable } from "../../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; +import { resolveAssistClient } from "./common.js"; + +export async function handleDetail( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const client = resolveAssistClient(parsed, runtime); + const corpId = + parsed.args[0] || + stringOption(parsed.options, ["corp", "corpid", "id"]) || + runtime.selectedCorp?.id; + + if (!corpId) { + return { + stdout: "", + stderr: "用法: hose-use assist-platform detail <企业ID>\n示例: hose-use assist-platform detail Cxa3oOtQi2eS$g\n", + exitCode: 1, + }; + } + + const detail = await getCorporationDetail(client, corpId); + + if (runtime.jsonMode) { + return { + stdout: printJson(detail, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + const corp = detail.corporation || {}; + const basic = detail.basic || {}; + + const summaryPairs: Record = { + 企业名称: String(corp.name || "-"), + 企业ID: String(corp.id || corpId), + 基础状态: String(basic.status || corp.state || "-"), + 付费模式: String(corp.payType || "-"), + 部署集群: String(corp.platformName || "app"), + 灰度版本: String(corp.grayver || "-"), + 数据库版本: String(corp.dbVersion || "-"), + 授权人数: String(basic.peopleCount || "-"), + 生效时间: basic.startTime ? new Date(Number(basic.startTime)).toLocaleDateString() : "-", + 到期时间: basic.endTime ? new Date(Number(basic.endTime)).toLocaleDateString() : "-", + }; + + const packageRows = detail.corporationPackageVos.map((p, i) => [ + String(i + 1), + p.name, + p.packageId, + p.enable ? "🟢 已启用" : "⚪ 未开通", + ]); + + const packageTable = printTable(["#", "套餐版本", "套餐 ID", "开通状态"], packageRows); + + const goodsRows = detail.otherGoodsList.slice(0, 30).map((g, i) => [ + String(i + 1), + String(g.name || "-"), + String(g.catName || "-"), + String(g.status || "-"), + String(g.model || "-"), + ]); + + const goodsTable = printTable(["#", "商品/功能名称", "业务类别", "状态", "类型"], goodsRows); + const moreNotice = detail.otherGoodsList.length > 30 + ? `\n(已显示前 30 项商品能力,全部 ${detail.otherGoodsList.length} 项可使用 --json 查看)\n` + : ""; + + return { + stdout: `====== 企业 [${corpId}] 协助中心全量业务配置 ======\n${printKeyValue(summaryPairs)}\n\n--- 原生套餐包规格 ---\n${packageTable}\n\n--- 已开通商品与扩展能力 ---\n${goodsTable}${moreNotice}\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/assist-platform/enter.ts b/src/cli/commands/assist-platform/enter.ts new file mode 100644 index 0000000..4be873b --- /dev/null +++ b/src/cli/commands/assist-platform/enter.ts @@ -0,0 +1,145 @@ +import { + generateAssistSession, + importAssistSessionToLocal, +} from "../../../domains/assist-platform/services.js"; +import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js"; +import { booleanOption, stringOption } from "../../parser.js"; +import { printJson, printKeyValue } from "../../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; +import { resolveAssistClient } from "./common.js"; + +export async function handleEnter( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const client = resolveAssistClient(parsed, runtime); + const corpId = + parsed.args[0] || + stringOption(parsed.options, ["corp", "corpid", "id"]) || + runtime.selectedCorp?.id; + + if (!corpId) { + return { + stdout: "", + stderr: "用法: hose-use assist-platform enter <企业ID> [--admin] [--staff <姓名>] [--save] [--switch]\n示例: hose-use assist-platform enter Cxa3oOtQi2eS$g --staff 李志财 --save --yes\n", + exitCode: 1, + }; + } + + const ticketId = stringOption(parsed.options, ["ticket", "ticket-id", "auth-code"]); + const staffName = stringOption(parsed.options, ["staff", "user", "name"]); + const forceAdmin = booleanOption(parsed.options, ["admin"]); + // 如果显式指定了 staffName 且未显式指定 --admin,则为用户模式;否则默认为管理员模式 + const isAdmin = forceAdmin || !staffName; + + const shouldSave = booleanOption(parsed.options, ["save", "import", "persist"]); + const shouldSwitch = booleanOption(parsed.options, ["switch", "current"]); + const overwrite = booleanOption(parsed.options, ["overwrite"]); + const saveName = stringOption(parsed.options, ["alias", "corp-name"]); + + // 1. 若不要求保存落盘,仅生成直通免密链接输出 + if (!shouldSave && !shouldSwitch) { + const sessionRes = await generateAssistSession(client, { + corpId, + ticketId, + isAdmin, + staffName, + }); + + if (runtime.jsonMode) { + return { + stdout: printJson(sessionRes, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + const pairs: Record = { + 企业ID: sessionRes.corporationId, + 授权模式: sessionRes.isAdmin ? "👑 企业管理员 (Admin)" : `👤 普通员工 (${sessionRes.staffName || "-"})`, + 授权工单: sessionRes.ticketId, + 会话Token: sessionRes.token, + 免密直通链接: sessionRes.loginUrl, + }; + + return { + stdout: `====== 协助平台免密会话生成成功 ======\n${printKeyValue(pairs)}\n\n操作提示:\n - 在浏览器中打开以上链接可直接进入协助调试工作台\n - 若要一键落盘到本地企业配置: hose-use assist-platform enter ${corpId} ${sessionRes.isAdmin ? "--admin" : `--staff "${sessionRes.staffName}"`} --save --yes\n`, + stderr: "", + exitCode: 0, + }; + } + + // 2. 要求持久化落盘 / 切换为工作企业 + if (isDryRun(parsed, runtime)) { + return mutationPreview( + parsed, + runtime, + "从协助平台换取免密凭证并落盘为本地企业配置", + saveName || `企业 [${corpId}]`, + { + corpId, + isAdmin, + staffName: staffName || null, + ticketId: ticketId || "自动选择最新有效工单", + switchCurrent: shouldSwitch, + overwrite, + } + ); + } + + const nextConfirmCmd = `hose-use assist-platform enter ${corpId} ${isAdmin ? "--admin" : `--staff "${staffName}"`} --save ${shouldSwitch ? "--switch " : ""}--yes`; + requireMutationConfirmation( + parsed, + runtime, + `从协助平台换取凭证并导入企业 [${corpId}]`, + nextConfirmCmd + ); + + const { sessionResult, corpConfig } = await importAssistSessionToLocal(client, { + corpId, + ticketId, + isAdmin, + staffName, + saveName, + overwrite: overwrite ?? true, + }); + + // 若指定了 --switch,切换当前激活企业 + if (shouldSwitch) { + runtime.corpContext.switchCorp(corpConfig.id, true); + } + + if (runtime.jsonMode) { + return { + stdout: printJson({ + success: true, + sessionResult, + enterprise: { + id: corpConfig.id, + name: corpConfig.name, + staffId: corpConfig.credentials.staffId, + hasOpenApi: Boolean(corpConfig.credentials.appKey), + switched: shouldSwitch, + }, + }, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + const successPairs: Record = { + 企业标识: corpConfig.id, + 企业名称: corpConfig.name, + 执行身份: sessionResult.isAdmin ? "👑 企业管理员" : `👤 ${sessionResult.staffName || "员工"} (${corpConfig.credentials.staffId})`, + 授权工单: sessionResult.ticketId, + 凭证状态: corpConfig.credentials.appKey ? `✅ 已提取 OpenAPI 持久化密钥 (${corpConfig.credentials.appKey})` : "⚪ 临时协助会话", + 配置文件: `enterprises/${corpConfig.id}.json`, + 激活状态: shouldSwitch ? "🎯 已设为当前激活工作企业" : "可随时运行 hose-use corps switch 进行切换", + }; + + return { + stdout: `[SUCCESS] 协助企业凭证获取并落盘成功!\n${printKeyValue(successPairs)}\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/assist-platform/index.ts b/src/cli/commands/assist-platform/index.ts new file mode 100644 index 0000000..98fbb9e --- /dev/null +++ b/src/cli/commands/assist-platform/index.ts @@ -0,0 +1,96 @@ +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; +import { handleLogin } from "./login.js"; +import { handleSearch } from "./search.js"; +import { handleDetail } from "./detail.js"; +import { handleTickets } from "./tickets.js"; +import { handleStaff } from "./staff.js"; +import { handleEnter } from "./enter.js"; + +export async function handleAssistPlatformCommand( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const action = (parsed.action || "help").toLowerCase(); + + switch (action) { + case "login": + case "auth": + case "status": + return handleLogin(parsed, runtime); + + case "search": + case "find": + case "list": + case "ls": + return handleSearch(parsed, runtime); + + case "detail": + case "info": + case "config": + return handleDetail(parsed, runtime); + + case "tickets": + case "ticket": + case "order": + case "orders": + return handleTickets(parsed, runtime); + + case "staff": + case "user": + case "users": + return handleStaff(parsed, runtime); + + case "enter": + case "import": + case "token": + case "get-token": + return handleEnter(parsed, runtime); + + case "help": + case "--help": + case "-h": + default: + return printHelp(); + } +} + +function printHelp(): CliResult { + const helpText = `用法: hose-use assist-platform <子命令> [参数] [选项] + +别名: assist-center, ap + +合思协助平台(https://unity.ekuaibao.com/platform-charge/)自动化运维交互命令。 +提供跨企业 34万+ 检索、协助工单状态查询、员工定位与免密直通链接一键换票持久化能力。 + +子命令列表: + login 查看当前协助平台会话,或传入 --token 进行登录保存 + search <关键词> 在协助中心 34 万家企业库中分页检索企业 + detail <企业ID> 查看企业全量业务配置(套餐规格、基础参数、已开通商品扩展能力) + tickets <企业ID> 查询指定企业的协助工单(申请人、授权码、剩余时长、工单状态) + staff <企业ID> <姓名> 查询企业内部指定员工的工号、账号、邮箱及 admin 属性 + enter <企业ID> 一键换取协助免密直通链接并进入(可选 --save 落盘为本地工作企业) + +常用选项: + --token, -t 显式指定当前操作使用的协助平台 Token + --admin 指定使用企业管理员模式换取免密链接(默认) + --staff <员工姓名> 指定使用特定员工身份换取免密链接 + --save 一键将换取的免密会话持久化落盘至本地企业列表(自动提取 OpenAPI 密钥) + --switch 配合 --save,导入后自动切换为当前激活工作企业 + --json 输出结构化 JSON 格式结果 + --dry-run 预览副作用操作,不真实落盘 + --yes, -y 跳过确认提示直接执行写操作 + +示例: + hose-use assist-platform login --token c31e9bb7-b0ed-4238-91bd-12ec14e05a5b + hose-use assist-platform search "CSM" + hose-use assist-platform tickets Cxa3oOtQi2eS$g + hose-use assist-platform staff Cxa3oOtQi2eS$g 李志财 + hose-use assist-platform enter Cxa3oOtQi2eS$g --staff 李志财 --save --switch --yes +`; + + return { + stdout: helpText, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/assist-platform/login.ts b/src/cli/commands/assist-platform/login.ts new file mode 100644 index 0000000..2be8c9f --- /dev/null +++ b/src/cli/commands/assist-platform/login.ts @@ -0,0 +1,100 @@ +import { + loadAssistPlatformSession, + saveAssistPlatformSession, + clearAssistPlatformSession, +} from "../../../core/auth/assist-platform-store.js"; +import { createAssistPlatformClient } from "../../../core/http/assist-platform-client.js"; +import { searchCorporations } from "../../../domains/assist-platform/services.js"; +import { booleanOption, stringOption } from "../../parser.js"; +import { printJson, printKeyValue } from "../../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; + +export async function handleLogin( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const logout = booleanOption(parsed.options, ["logout"]); + if (logout) { + clearAssistPlatformSession(); + return { + stdout: "[SUCCESS] 已成功注销并清理协助平台本地会话。\n", + stderr: "", + exitCode: 0, + }; + } + + const explicitToken = stringOption(parsed.options, ["token", "t"]); + const userName = stringOption(parsed.options, ["user", "name", "u"]); + const hoseAccessToken = stringOption(parsed.options, ["hose-token", "jwt"]); + + if (explicitToken) { + // 验证 Token 连通性 + const testClient = createAssistPlatformClient({ + token: explicitToken, + hoseAccessToken, + }); + try { + await searchCorporations(testClient, { limit: { start: 0, count: 1 } }); + } catch (err) { + return { + stdout: "", + stderr: `[ERROR] 协助平台 Token 校验失败: ${err instanceof Error ? err.message : String(err)}\n`, + exitCode: 1, + }; + } + + saveAssistPlatformSession({ + token: explicitToken, + hoseAccessToken, + userName: userName || "运营实施人员", + baseUrl: "https://unity.ekuaibao.com/api", + updatedAt: Date.now(), + }); + + if (runtime.jsonMode) { + return { + stdout: printJson({ success: true, token: explicitToken, userName }), + stderr: "", + exitCode: 0, + }; + } + + return { + stdout: `[SUCCESS] 协助平台登录凭证保存成功!\n操作人员: ${userName || "运营人员"}\n会话 Token: ${explicitToken}\n`, + stderr: "", + exitCode: 0, + }; + } + + // 查看当前协助平台会话状态 + const existing = loadAssistPlatformSession(); + if (!existing || !existing.token) { + return { + stdout: "", + stderr: `未检测到协助平台登录凭证。\n用法:\n hose-use assist-platform login --token [--user <姓名>]\n hose-use assist-platform login --logout (清理凭证)\n`, + exitCode: 1, + }; + } + + if (runtime.jsonMode) { + return { + stdout: printJson(existing), + stderr: "", + exitCode: 0, + }; + } + + const pairs: Record = { + 协助平台状态: "🟢 已登录", + 操作员工姓名: existing.userName || "运营实施人员", + 基础服务地址: existing.baseUrl || "https://unity.ekuaibao.com/api", + 当前会话凭证: existing.token.replace(/(.{4}).*(.{4})/, "$1****$2"), + 最后更新时间: new Date(existing.updatedAt).toLocaleString("zh-CN", { hour12: false }), + }; + + return { + stdout: `====== 合思协助平台当前会话 ======\n${printKeyValue(pairs)}\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/assist-platform/search.ts b/src/cli/commands/assist-platform/search.ts new file mode 100644 index 0000000..1b2c546 --- /dev/null +++ b/src/cli/commands/assist-platform/search.ts @@ -0,0 +1,64 @@ +import { searchCorporations } from "../../../domains/assist-platform/services.js"; +import { numberOption, stringOption } from "../../parser.js"; +import { printJson, printTable } from "../../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; +import { resolveAssistClient } from "./common.js"; + +export async function handleSearch( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const client = resolveAssistClient(parsed, runtime); + const keyword = + parsed.args[0] || + stringOption(parsed.options, ["keyword", "query", "q", "name", "id"]) || + ""; + + const count = numberOption(parsed.options, ["count", "limit", "n"]) || 20; + const start = numberOption(parsed.options, ["start", "offset"]) || 0; + const state = stringOption(parsed.options, ["state", "status"]); + + const res = await searchCorporations(client, { + keyword: keyword.trim() || undefined, + state: state?.trim() || undefined, + limit: { start, count }, + }); + + if (runtime.jsonMode) { + return { + stdout: printJson(res, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + if (res.items.length === 0) { + return { + stdout: `协助平台企业库中未找到匹配 "${keyword}" 的企业记录。\n`, + stderr: "", + exitCode: 0, + }; + } + + const rows = res.items.map((c, i) => [ + String(start + i + 1), + c.id, + c.name, + c.platformName || "app", + c.state || "-", + c.payType === "TRYOUT" ? "试用" : c.payType === "PAY" ? "付费" : c.payType || "-", + c.sumPeople !== null && c.sumPeople !== undefined ? String(c.sumPeople) : "-", + c.tel || "-", + ]); + + const table = printTable( + ["#", "企业 ID", "企业名称", "集群", "状态", "类型", "授权人数", "联系电话"], + rows + ); + + return { + stdout: `====== 合思协助平台企业搜索结果 (共匹配 ${res.count} 家,当前显示 ${res.items.length} 条) ======\n${table}\n\n提示: 可使用 hose-use assist-platform tickets <企业ID> 查询协助工单\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/assist-platform/staff.ts b/src/cli/commands/assist-platform/staff.ts new file mode 100644 index 0000000..4804574 --- /dev/null +++ b/src/cli/commands/assist-platform/staff.ts @@ -0,0 +1,67 @@ +import { findStaff } from "../../../domains/assist-platform/services.js"; +import { stringOption } from "../../parser.js"; +import { printJson, printTable } from "../../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; +import { resolveAssistClient } from "./common.js"; + +export async function handleStaff( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const client = resolveAssistClient(parsed, runtime); + const corpId = + parsed.args[0] || + stringOption(parsed.options, ["corp", "corpid", "id"]) || + runtime.selectedCorp?.id; + + const staffName = + parsed.args[1] || + stringOption(parsed.options, ["name", "user", "staff"]); + + if (!corpId || !staffName) { + return { + stdout: "", + stderr: "用法: hose-use assist-platform staff <企业ID> <员工姓名>\n示例: hose-use assist-platform staff Cxa3oOtQi2eS$g 李志财\n", + exitCode: 1, + }; + } + + const staffList = await findStaff(client, corpId, staffName); + + if (runtime.jsonMode) { + return { + stdout: printJson({ corporationId: corpId, queryName: staffName, items: staffList }, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + if (staffList.length === 0) { + return { + stdout: `企业 [${corpId}] 中未找到名为 "${staffName}" 的员工。\n`, + stderr: "", + exitCode: 0, + }; + } + + const rows = staffList.map((s, i) => [ + String(i + 1), + s.name, + s.code || "-", + s.admin ? "👑 是" : "否", + s.cellphone || "-", + s.email || "-", + s.id, + ]); + + const table = printTable( + ["#", "姓名", "工号", "管理员", "手机号码", "邮箱地址", "员工全局 ID (Staff ID)"], + rows + ); + + return { + stdout: `====== 企业 [${corpId}] 员工查询结果 ("${staffName}") ======\n${table}\n\n操作提示: 可使用 hose-use assist-platform enter ${corpId} --staff ${staffName} --save --yes 一键换票导入\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/assist-platform/tickets.ts b/src/cli/commands/assist-platform/tickets.ts new file mode 100644 index 0000000..478c006 --- /dev/null +++ b/src/cli/commands/assist-platform/tickets.ts @@ -0,0 +1,63 @@ +import { listAssistTickets } from "../../../domains/assist-platform/services.js"; +import { stringOption } from "../../parser.js"; +import { printJson, printTable } from "../../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; +import { resolveAssistClient } from "./common.js"; + +export async function handleTickets( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const client = resolveAssistClient(parsed, runtime); + const corpId = + parsed.args[0] || + stringOption(parsed.options, ["corp", "corpid", "id"]) || + runtime.selectedCorp?.id; + + if (!corpId) { + return { + stdout: "", + stderr: "用法: hose-use assist-platform tickets <企业ID>\n示例: hose-use assist-platform tickets Cxa3oOtQi2eS$g\n", + exitCode: 1, + }; + } + + const tickets = await listAssistTickets(client, corpId); + + if (runtime.jsonMode) { + return { + stdout: printJson({ corporationId: corpId, count: tickets.length, tickets }, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + if (tickets.length === 0) { + return { + stdout: `企业 [${corpId}] 协助中心未查询到任何协助工单记录。\n`, + stderr: "", + exitCode: 0, + }; + } + + const rows = tickets.map((t, i) => [ + String(i + 1), + t.ticketId, + t.applicant, + t.principal || "-", + t.state === "已提供" ? "🟢 已提供" : t.state === "待提供" ? "🟡 待提供" : t.state === "已过期" ? "⚪ 已过期" : t.state, + t.duration ? `${t.duration}h` : "-", + t.usePeriodDesc || (t.startTime && t.endTime ? `${new Date(t.startTime).toLocaleDateString()} - ${new Date(t.endTime).toLocaleDateString()}` : "-"), + ]); + + const table = printTable( + ["#", "授权码 (Ticket ID)", "申请人", "负责人", "工单状态", "时长", "有效期限"], + rows + ); + + return { + stdout: `====== 企业 [${corpId}] 协助工单列表 (共 ${tickets.length} 条) ======\n${table}\n\n操作提示:\n - 一键管理员直通调试: hose-use assist-platform enter ${corpId} --save --yes\n - 一键指定员工身份进入: hose-use assist-platform enter ${corpId} --staff <员工姓名> --save --yes\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/registry.ts b/src/cli/registry.ts index 3cfd4f9..4698cf1 100644 --- a/src/cli/registry.ts +++ b/src/cli/registry.ts @@ -26,6 +26,7 @@ import { handleContextCommand } from "./commands/context.js"; import { handleKeysCommand } from "./commands/keys.js"; import { handleStoreCommand } from "./commands/store.js"; import { handleFeeTypeCommand } from "./commands/feetype.js"; +import { handleAssistPlatformCommand } from "./commands/assist-platform/index.js"; import { COMMAND_METADATA, type CliCommandMetadata } from "./command-metadata.js"; import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js"; @@ -195,6 +196,11 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [ standing: true, handler: (parsed, _runtime, options) => handleMcpCommand(parsed, options), }, + { + area: "assist-platform", + ...COMMAND_METADATA["assist-platform"], + handler: (parsed, runtime) => handleAssistPlatformCommand(parsed, runtime), + }, ]; const COMMAND_LOOKUP = new Map(); diff --git a/src/core/auth/assist-platform-store.ts b/src/core/auth/assist-platform-store.ts new file mode 100644 index 0000000..6e8b3cf --- /dev/null +++ b/src/core/auth/assist-platform-store.ts @@ -0,0 +1,73 @@ +import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join, dirname } from "node:path"; +import { homedir } from "node:os"; +import { z } from "zod"; + +export const ASSIST_PLATFORM_STORE_PATH = join( + homedir(), + ".config", + "hose-use", + "assist-platform.json" +); + +export function resolveAssistPlatformStorePath(): string { + const envFile = process.env.HOSE_ASSIST_PLATFORM_FILE?.trim(); + if (envFile) return envFile; + const stateDir = process.env.HOSE_STATE_DIR?.trim(); + if (stateDir) return join(stateDir, "assist-platform.json"); + return ASSIST_PLATFORM_STORE_PATH; +} + +export const AssistPlatformSessionSchema = z.object({ + token: z.string().describe("协助平台 API 会话 Token"), + hoseAccessToken: z.string().optional().describe("统一认证 Access Token (JWT)"), + userName: z.string().optional().describe("登录运维/客服员工姓名"), + userId: z.string().optional().describe("登录用户 ID"), + baseUrl: z.string().default("https://unity.ekuaibao.com").describe("协助平台基础服务地址"), + updatedAt: z.number().default(() => Date.now()), +}); + +export type AssistPlatformSession = z.infer; + +function ensureDir(path: string): void { + const dir = dirname(path); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + } + try { + chmodSync(dir, 0o700); + } catch {} +} + +export function loadAssistPlatformSession(): AssistPlatformSession | null { + const filePath = resolveAssistPlatformStorePath(); + try { + if (!existsSync(filePath)) return null; + const content = readFileSync(filePath, "utf-8"); + const parsed = JSON.parse(content); + return AssistPlatformSessionSchema.parse(parsed); + } catch { + return null; + } +} + +export function saveAssistPlatformSession(session: AssistPlatformSession): void { + const filePath = resolveAssistPlatformStorePath(); + ensureDir(filePath); + writeFileSync(filePath, JSON.stringify(session, null, 2), { + encoding: "utf-8", + mode: 0o600, + }); + try { + chmodSync(filePath, 0o600); + } catch {} +} + +export function clearAssistPlatformSession(): void { + const filePath = resolveAssistPlatformStorePath(); + try { + if (existsSync(filePath)) { + writeFileSync(filePath, "{}", { encoding: "utf-8", mode: 0o600 }); + } + } catch {} +} diff --git a/src/core/http/assist-platform-client.ts b/src/core/http/assist-platform-client.ts new file mode 100644 index 0000000..93c73d7 --- /dev/null +++ b/src/core/http/assist-platform-client.ts @@ -0,0 +1,45 @@ +import ky, { type KyInstance } from "ky"; +import { AuthenticationError } from "../errors.js"; + +export const DEFAULT_ASSIST_PLATFORM_API_URL = "https://unity.ekuaibao.com/api"; + +export interface AssistPlatformClientOptions { + token: string; + baseUrl?: string; + hoseAccessToken?: string; + timeout?: number; +} + +export function createAssistPlatformClient(options: AssistPlatformClientOptions): KyInstance { + if (!options.token || !options.token.trim()) { + throw new AuthenticationError("缺少协助平台凭证 Token,请先登录协助平台"); + } + + const baseUrl = options.baseUrl || DEFAULT_ASSIST_PLATFORM_API_URL; + const cookieParts: string[] = []; + if (options.hoseAccessToken) { + cookieParts.push(`hose-access-token=${options.hoseAccessToken}`); + } + + return ky.create({ + prefix: baseUrl, + timeout: options.timeout ?? 30000, + headers: { + accept: "application/json", + "content-type": "application/json;charset=UTF-8", + token: options.token.trim(), + referer: "https://unity.ekuaibao.com/platform-charge/index.html", + ...(cookieParts.length > 0 ? { cookie: cookieParts.join("; ") } : {}), + }, + hooks: { + afterResponse: [ + async ({ response }) => { + if (response.status === 401 || response.status === 403) { + throw new AuthenticationError("协助平台凭证已过期或无效,请重新登录协助平台"); + } + return response; + }, + ], + }, + }); +} diff --git a/src/core/http/sso-client.ts b/src/core/http/sso-client.ts new file mode 100644 index 0000000..4c92625 --- /dev/null +++ b/src/core/http/sso-client.ts @@ -0,0 +1,69 @@ +import ky, { type KyInstance } from "ky"; +import { AuthenticationError } from "../errors.js"; + +export const DEFAULT_SSO_BASE_URL = "https://sso.hosecloud.com"; + +export interface SsoClientOptions { + baseUrl?: string; + timeout?: number; +} + +export function createSsoClient(options: SsoClientOptions = {}): KyInstance { + const baseUrl = options.baseUrl || DEFAULT_SSO_BASE_URL; + return ky.create({ + prefix: baseUrl, + timeout: options.timeout ?? 15000, + headers: { + accept: "application/json, text/plain, */*", + "user-agent": "hose-use/assist-platform-client", + referer: `${baseUrl}/`, + }, + }); +} + +export interface QrCodeStatusResponse { + code: number; + message: string; + data?: { + token?: string; + ticket?: string; + redirectUrl?: string; + [key: string]: unknown; + } | string; +} + +/** + * 轮询 HoseCloudSSO 钉钉扫码登录确认状态 + */ +export async function pollSsoQrCodeStatus( + client: KyInstance, + options: { + sessionId?: string; + cookie?: string; + signal?: AbortSignal; + } = {} +): Promise { + const headers: Record = {}; + if (options.cookie) { + headers.cookie = options.cookie; + } else if (options.sessionId) { + headers.cookie = `SSO_SESSION_ID=${options.sessionId}`; + } + + try { + return await client + .get("api/v1/user/login/qrcode/status", { + searchParams: { _t: Date.now() }, + headers, + signal: options.signal, + }) + .json(); + } catch (error) { + if (error instanceof Error && error.name === "AbortError") { + throw error; + } + throw new AuthenticationError( + `SSO 状态轮询异常: ${error instanceof Error ? error.message : String(error)}` + ); + } +} diff --git a/src/domains/README.domains.md b/src/domains/README.domains.md index cc8af6e..6487708 100644 --- a/src/domains/README.domains.md +++ b/src/domains/README.domains.md @@ -2,7 +2,7 @@ 本目录按业务域组织代码,每个域独立负责自己的传输层(`api.ts`)、业务编排层(`tools.ts` / `services.ts`)和模型层(`types.ts`)。 -## 当前域(共 14 个) +## 当前域(共 15 个) | 域 | 内部形态 | 说明 | 详细文档 | |---|---|---|---| @@ -10,6 +10,7 @@ | `datalink/` | `api / tools / services / types` | 自建应用下的业务对象、字段、记录检索、安全合并编辑(Read-Modify-Write)、台账体检与导入状态 | [README.datalink.md](./datalink/README.datalink.md) | | `bill/` | `api / tools / translator / types` | 费控单据、报销单、发票、审批流时间线、风控扫描与 Markdown 智能转译器 | [README.bill.md](./bill/README.bill.md) | | `approval/` | `index / gateway / parser / repository / service / db / types` | AI PRO 智能审批引擎(DSL 规则解析、确定性安全网关、要点核验与 `core/db` 会话持久化) | [README.approval.md](./approval/README.approval.md) | +| `assist-platform/` | `api / services / types` | 合思协助平台(Unity 运营中心)多租户检索、工单匹配、指定代客员工免密直通与落盘提权 | [README.assist-platform.md](./assist-platform/README.assist-platform.md) | | `store/` | `api / tools / types` | 企业应用中心/应用商店与 OpenAPI 密钥凭证探查 | [README.store.md](./store/README.store.md) | | `feetype/` | `api / tools / types` | 企业费用类型全生命周期管理与字段规格配置 | [README.feetype.md](./feetype/README.feetype.md) | | `contact/` | `api / tools / types` | 企业组织架构(部门树)与员工通讯录检索 | [README.contact.md](./contact/README.contact.md) | @@ -32,6 +33,7 @@ - `bill/`:独立拆分 `translator.ts` 负责复杂单据/审批流到结构化 Markdown 的纯函数转译 - `approval/`:采用 `parser.ts`(DSL 解析)+ `gateway.ts`(确定性仲裁门禁)+ `repository.ts`(基于 `core/db` 的数据访问)+ `service.ts`(业务编排) - `events/`:组合 `task/` 与 `message/` 域的 `tools.ts` 实现轮询(`poller.ts`),并通过 `store.ts` 落盘至 `core/db` + - `assist-platform/`:使用 `services.ts` 封装合思运营平台多租户检索、工单匹配、指定代客员工定位、免密直通换票及与租户存储的联动落盘提权 3. **边界与异常约束**(由 `src/cli/architecture-boundaries.test.ts` 强制校验): - 任何入口层(`src/cli/**`, `src/http/**`, `src/server.ts`, `src/cli.ts`, `src/aipro-cli.ts`)严禁直接导入 `domains/*/api.ts` - `domains/*` 严禁反向导入 `cli/`、`http/` 或顶层入口文件 diff --git a/src/domains/assist-platform/README.assist-platform.md b/src/domains/assist-platform/README.assist-platform.md new file mode 100644 index 0000000..5d9b44a --- /dev/null +++ b/src/domains/assist-platform/README.assist-platform.md @@ -0,0 +1,26 @@ +# Assist Platform (合思协助平台 / 运营平台) 域说明 + +本域负责对接合思官方内部运营平台(Unity Assist Platform,`https://unity.ekuaibao.com/platform-charge/`)及其 SSO 统一身份认证服务(`https://sso.hosecloud.com`)。 + +## 架构与分工 + +- **SSO 身份客户端 (`src/core/http/sso-client.ts`)**: + 负责与 `sso.hosecloud.com` 的登录二维码生成、扫码状态轮询以及凭证提取。 +- **协助平台网关客户端 (`src/core/http/assist-platform-client.ts`)**: + 负责与 `unity.ekuaibao.com/api` 网关通信,自动挂载 `token: ` 请求头与 Cookie。 +- **协助平台本地凭证安全存储 (`src/core/auth/assist-platform-store.ts`)**: + 将协助平台会话安全持久化在 `~/.config/hose-use/assist-platform.json`(权限 0600)。 +- **传输层 (`api.ts`)**: + 封装协助中心全部核心 REST API 并通过 Zod 进行响应强校验。 +- **业务编排层 (`services.ts`)**: + 纯函数式高阶编排,包括企业检索、协助工单提取、员工匹配定位、免密直通 Token 换取,以及无缝对接 `corps.importFromLink` 的一键落盘与 OpenAPI 自动提权。 +- **模型层 (`types.ts`)**: + 企业信息、工单列表、员工信息、直通链接及入参强类型定义。 + +## 关键 API + +- `searchCorporations`: 全量企业库检索(按关键词/企业 ID) +- `getCorporationDetail`: 查询企业详细画像与开通版本 +- `listAssistTickets`: 查询企业生效中的协助工单(包含 ticketId、原因、有效期、申请人) +- `searchStaffList`: 查询企业内部员工名单(用于指定代客身份时的 staffId 定位) +- `getAssistToken`: 换取免密代客登录链接与临时 JWT凭证 diff --git a/src/domains/assist-platform/api.ts b/src/domains/assist-platform/api.ts new file mode 100644 index 0000000..e131c2a --- /dev/null +++ b/src/domains/assist-platform/api.ts @@ -0,0 +1,234 @@ +import type { KyInstance } from "ky"; +import { EkbApiError, BusinessError, NotFoundError } from "../../core/errors.js"; +import type { + AssistPlatformCorporation, + AssistPlatformStaff, + AssistPlatformTicket, + CorporationDetail, +} from "./types.js"; + +export interface SearchCorporationsApiParams { + keyword?: string; + state?: string; + limit?: { + start: number; + count: number; + }; +} + +export interface SearchCorporationsApiResponse { + count: number; + items: AssistPlatformCorporation[]; +} + +export async function searchCorporationsApi( + client: KyInstance, + params: SearchCorporationsApiParams = {} +): Promise { + const requestBody: Record = { + limit: { + start: params.limit?.start ?? 0, + count: params.limit?.count ?? 20, + }, + }; + if (params.keyword?.trim()) { + requestBody.keyword = params.keyword.trim(); + } + if (params.state?.trim()) { + requestBody.state = params.state.trim(); + } + + try { + const res = await client + .post("corporation/search", { + json: requestBody, + }) + .json<{ count?: number; items?: AssistPlatformCorporation[] }>(); + + return { + count: res.count ?? (res.items?.length || 0), + items: res.items || [], + }; + } catch (error) { + if (error instanceof Error && error.name === "AuthenticationError") throw error; + throw new EkbApiError( + `查询协助企业列表失败: ${error instanceof Error ? error.message : String(error)}` + ); + } +} + +export async function getCorporationDetailApi( + client: KyInstance, + corpId: string +): Promise { + if (!corpId || !corpId.trim()) { + throw new BusinessError("必须指定企业 ID"); + } + + try { + const res = await client + .get(`corporation/${encodeURIComponent(corpId.trim())}/getCorporationDetail`) + .json<{ items?: CorporationDetail[] }>(); + + const detail = res.items?.[0]; + if (!detail) { + throw new NotFoundError(`未找到企业 [${corpId}] 的详细业务配置`); + } + return detail; + } catch (error) { + if (error instanceof Error && (error.name === "AuthenticationError" || error.name === "NotFoundError")) { + throw error; + } + throw new EkbApiError( + `获取企业 [${corpId}] 详情失败: ${error instanceof Error ? error.message : String(error)}` + ); + } +} + +export async function searchAssistTicketsApi( + client: KyInstance, + corpId: string +): Promise { + if (!corpId || !corpId.trim()) { + throw new BusinessError("必须指定企业 ID"); + } + + try { + const res = await client + .post(`assistPlatform/${encodeURIComponent(corpId.trim())}/search`, { + json: {}, + }) + .json<{ items?: Array> }>(); + + const rawItems = res.items || []; + return rawItems.map((item) => { + const startTime = typeof item.startTime === "number" ? item.startTime : undefined; + const endTime = typeof item.endTime === "number" ? item.endTime : undefined; + const usePeriodDesc = (startTime && endTime) + ? `${new Date(startTime).toLocaleString("zh-CN", { hour12: false })} 至 ${new Date(endTime).toLocaleString("zh-CN", { hour12: false })}` + : undefined; + + return { + id: String(item.id || item.ticketId || ""), + ticketId: String(item.ticketId || item.id || item.authCode || ""), + applicant: String(item.applicant || item.applyUserName || item.userName || "未知申请人"), + applicantId: item.applicantId ? String(item.applicantId) : undefined, + principal: item.principal ? String(item.principal) : (item.operationUserName ? String(item.operationUserName) : undefined), + principalId: item.principalId ? String(item.principalId) : undefined, + state: String(item.state || item.status || "未知状态"), + duration: typeof item.duration === "number" ? item.duration : (typeof item.hours === "number" ? item.hours : undefined), + startTime, + endTime, + usePeriodDesc, + matter: item.matter ? String(item.matter) : undefined, + createTime: typeof item.createTime === "number" ? item.createTime : undefined, + }; + }); + } catch (error) { + if (error instanceof Error && error.name === "AuthenticationError") throw error; + throw new EkbApiError( + `查询企业 [${corpId}] 协助工单失败: ${error instanceof Error ? error.message : String(error)}` + ); + } +} + +export async function getStaffApi( + client: KyInstance, + corpId: string, + name: string +): Promise { + if (!corpId || !corpId.trim()) throw new BusinessError("必须指定企业 ID"); + if (!name || !name.trim()) throw new BusinessError("必须指定要查询的用户姓名"); + + try { + const res = await client + .post("assistPlatform/getStaff", { + json: { + corporationId: corpId.trim(), + name: name.trim(), + }, + }) + .json<{ total?: number; items?: Array> }>(); + + const items = res.items || []; + return items.map((raw) => ({ + id: String(raw.id || ""), + code: raw.code ? String(raw.code) : undefined, + name: String(raw.name || name), + email: raw.email ? String(raw.email) : undefined, + cellphone: raw.cellphone ? String(raw.cellphone) : undefined, + admin: Boolean(raw.admin), + userId: raw.userId ? String(raw.userId) : undefined, + corporationId: String(raw.corporationId || corpId), + departments: Array.isArray(raw.departments) ? raw.departments.map(String) : [], + active: raw.active !== false, + })); + } catch (error) { + if (error instanceof Error && error.name === "AuthenticationError") throw error; + throw new EkbApiError( + `查询企业员工 [${name}] 失败: ${error instanceof Error ? error.message : String(error)}` + ); + } +} + +export interface GetAssistTokenApiParams { + ticketId: string; + corporationId: string; + isAdmin: boolean; + staffId?: string; +} + +export interface GetAssistTokenApiResponse { + token: string; + loginUrl: string; + baseUrl: string; +} + +export async function getAssistTokenApi( + client: KyInstance, + params: GetAssistTokenApiParams +): Promise { + const { ticketId, corporationId, isAdmin, staffId } = params; + if (!ticketId) throw new BusinessError("缺少协助授权码 ticketId"); + if (!corporationId) throw new BusinessError("缺少企业 ID corporationId"); + + const body: Record = { + ticketId, + corporationId, + isAdmin, + }; + if (!isAdmin && staffId) { + body.staffId = staffId; + } + + try { + const res = await client + .post("assistPlatform/getToken", { + json: body, + }) + .json<{ + value?: { + token?: string; + loginUrl?: string; + baseUrl?: string; + }; + }>(); + + if (!res.value?.token || !res.value?.loginUrl) { + throw new BusinessError("协助平台服务端未返回有效免密直通链接"); + } + + return { + token: res.value.token, + loginUrl: res.value.loginUrl, + baseUrl: res.value.baseUrl || "https://app.ekuaibao.com", + }; + } catch (error) { + if (error instanceof Error && (error.name === "AuthenticationError" || error.name === "BusinessError")) { + throw error; + } + throw new EkbApiError( + `换取协助免密链接失败: ${error instanceof Error ? error.message : String(error)}` + ); + } +} diff --git a/src/domains/assist-platform/assist-platform.test.ts b/src/domains/assist-platform/assist-platform.test.ts new file mode 100644 index 0000000..211b163 --- /dev/null +++ b/src/domains/assist-platform/assist-platform.test.ts @@ -0,0 +1,193 @@ +import { describe, expect, it } from "bun:test"; +import ky from "ky"; +import { + findStaff, + generateAssistSession, + getCorporationDetail, + listAssistTickets, + searchCorporations, +} from "./services.js"; + +function createMockClient(handler: (req: Request) => Response | Promise) { + return ky.create({ + prefix: "https://unity.ekuaibao.com/api", + fetch: async (input: string | Request | URL, init?: RequestInit) => { + const req = input instanceof Request ? input : new Request(input.toString(), init); + return handler(req); + }, + }); +} + +describe("domains/assist-platform - 协助平台业务编排", () => { + it("searchCorporations 能够正确分页并返回企业列表", async () => { + const client = createMockClient(async (req) => { + expect(req.url).toContain("corporation/search"); + const body = (await req.json()) as any; + expect(body.limit.count).toBe(10); + return Response.json({ + count: 1, + items: [ + { + id: "Cxa3oOtQi2eS$g", + name: "CSM", + platformName: "app", + state: "可用", + payType: "TRYOUT", + }, + ], + }); + }); + + const res = await searchCorporations(client, { + keyword: "CSM", + limit: { start: 0, count: 10 }, + }); + + expect(res.count).toBe(1); + expect(res.items[0].id).toBe("Cxa3oOtQi2eS$g"); + expect(res.items[0].name).toBe("CSM"); + }); + + it("getCorporationDetail 返回企业详细配置", async () => { + const client = createMockClient(async (req) => { + expect(req.url).toContain("corporation/Cxa3oOtQi2eS%24g/getCorporationDetail"); + return Response.json({ + items: [ + { + corporation: { id: "Cxa3oOtQi2eS$g", name: "CSM" }, + basic: { name: "基础功能", status: "可用" }, + corporationPackageVos: [{ packageId: "20210415003", name: "原生企业版", enable: true }], + otherGoodsList: [{ goodsId: "g1", name: "收款单据" }], + }, + ], + }); + }); + + const detail = await getCorporationDetail(client, "Cxa3oOtQi2eS$g"); + expect(detail.corporation?.name).toBe("CSM"); + expect(detail.corporationPackageVos.length).toBe(1); + }); + + it("listAssistTickets 正确映射工单时间、申请人与授权码", async () => { + const client = createMockClient(async (req) => { + expect(req.url).toContain("assistPlatform/Cxa3oOtQi2eS%24g/search"); + return Response.json({ + items: [ + { + ticketId: "ID01Xeh99QmgQn", + applicant: "李志财", + principal: "谢子豪", + state: "已提供", + duration: 24, + startTime: 1792547700000, + endTime: 1792634100000, + }, + ], + }); + }); + + const tickets = await listAssistTickets(client, "Cxa3oOtQi2eS$g"); + expect(tickets.length).toBe(1); + expect(tickets[0].ticketId).toBe("ID01Xeh99QmgQn"); + expect(tickets[0].applicant).toBe("李志财"); + expect(tickets[0].usePeriodDesc).toContain("至"); + }); + + it("findStaff 正确检索企业员工工号与角色", async () => { + const client = createMockClient(async (req) => { + expect(req.url).toContain("assistPlatform/getStaff"); + const body = (await req.json()) as any; + expect(body.name).toBe("李志财"); + return Response.json({ + total: 1, + items: [ + { + id: "Cxa3oOtQi2eS$g:2HQbkGx2DgnM00", + code: "777", + name: "李志财", + admin: true, + email: "lizhicai@hosecloud.com", + cellphone: "15727689231", + }, + ], + }); + }); + + const staffList = await findStaff(client, "Cxa3oOtQi2eS$g", "李志财"); + expect(staffList.length).toBe(1); + expect(staffList[0].name).toBe("李志财"); + expect(staffList[0].admin).toBe(true); + }); + + it("generateAssistSession 管理员模式一键换取免密登录直通链接", async () => { + const client = createMockClient(async (req) => { + const url = req.url; + if (url.includes("assistPlatform/Cxa3oOtQi2eS%24g/search")) { + return Response.json({ + items: [{ ticketId: "ID01Xeh99QmgQn", applicant: "李志财", state: "已提供" }], + }); + } + if (url.includes("assistPlatform/getToken")) { + const body = (await req.json()) as any; + expect(body.isAdmin).toBe(true); + expect(body.ticketId).toBe("ID01Xeh99QmgQn"); + return Response.json({ + value: { + token: "ID01XehbTTcihF", + loginUrl: "https://app.ekuaibao.com/api/engine/assistPlatform/login?corpId=Cxa3oOtQi2eS%24g&code=test1234", + baseUrl: "https://app.ekuaibao.com", + }, + }); + } + return new Response("Not found", { status: 404 }); + }); + + const result = await generateAssistSession(client, { + corpId: "Cxa3oOtQi2eS$g", + isAdmin: true, + }); + + expect(result.token).toBe("ID01XehbTTcihF"); + expect(result.loginUrl).toContain("assistPlatform/login"); + expect(result.isAdmin).toBe(true); + }); + + it("generateAssistSession 用户模式自动定位 staffId 换取免密链接", async () => { + const client = createMockClient(async (req) => { + const url = req.url; + if (url.includes("assistPlatform/Cxa3oOtQi2eS%24g/search")) { + return Response.json({ + items: [{ ticketId: "ID01Xeh99QmgQn", applicant: "李志财", state: "已提供" }], + }); + } + if (url.includes("assistPlatform/getStaff")) { + return Response.json({ + items: [{ id: "Cxa3oOtQi2eS$g:2HQbkGx2DgnM00", name: "李志财", admin: true }], + }); + } + if (url.includes("assistPlatform/getToken")) { + const body = (await req.json()) as any; + expect(body.isAdmin).toBe(false); + expect(body.staffId).toBe("Cxa3oOtQi2eS$g:2HQbkGx2DgnM00"); + return Response.json({ + value: { + token: "ID01Xeh9JK2Wlh", + loginUrl: "https://app.ekuaibao.com/api/engine/assistPlatform/login?corpId=Cxa3oOtQi2eS%24g&code=user5678", + baseUrl: "https://app.ekuaibao.com", + }, + }); + } + return new Response("Not found", { status: 404 }); + }); + + const result = await generateAssistSession(client, { + corpId: "Cxa3oOtQi2eS$g", + isAdmin: false, + staffName: "李志财", + }); + + expect(result.token).toBe("ID01Xeh9JK2Wlh"); + expect(result.isAdmin).toBe(false); + expect(result.staffId).toBe("Cxa3oOtQi2eS$g:2HQbkGx2DgnM00"); + }); +}); diff --git a/src/domains/assist-platform/index.ts b/src/domains/assist-platform/index.ts new file mode 100644 index 0000000..3ba379b --- /dev/null +++ b/src/domains/assist-platform/index.ts @@ -0,0 +1,2 @@ +export * from "./types.js"; +export * from "./services.js"; diff --git a/src/domains/assist-platform/services.ts b/src/domains/assist-platform/services.ts new file mode 100644 index 0000000..c0498ab --- /dev/null +++ b/src/domains/assist-platform/services.ts @@ -0,0 +1,155 @@ +import type { KyInstance } from "ky"; +import { BusinessError, NotFoundError } from "../../core/errors.js"; +import { importFromLink, type ImportFromLinkOptions } from "../../core/auth/link-import.js"; +import type { CorpConfig } from "../../core/config/types.js"; +import { + getAssistTokenApi, + getCorporationDetailApi, + getStaffApi, + searchAssistTicketsApi, + searchCorporationsApi, + type SearchCorporationsApiParams, + type SearchCorporationsApiResponse, +} from "./api.js"; +import type { + AssistPlatformCorporation, + AssistPlatformSessionResult, + AssistPlatformStaff, + AssistPlatformTicket, + CorporationDetail, +} from "./types.js"; + +export async function searchCorporations( + client: KyInstance, + params: SearchCorporationsApiParams = {} +): Promise { + return await searchCorporationsApi(client, params); +} + +export async function getCorporationDetail( + client: KyInstance, + corpId: string +): Promise { + return await getCorporationDetailApi(client, corpId); +} + +export async function listAssistTickets( + client: KyInstance, + corpId: string +): Promise { + return await searchAssistTicketsApi(client, corpId); +} + +export async function findStaff( + client: KyInstance, + corpId: string, + name: string +): Promise { + return await getStaffApi(client, corpId, name); +} + +export interface GenerateAssistSessionParams { + corpId: string; + ticketId?: string; + isAdmin?: boolean; + staffName?: string; + staffId?: string; +} + +/** + * 智能解析并换取协助平台的免密登录直通链接 + */ +export async function generateAssistSession( + client: KyInstance, + params: GenerateAssistSessionParams +): Promise { + const corpId = params.corpId.trim(); + let ticketId = params.ticketId?.trim(); + + // 若未手动指定授权码 ticketId,自动检索该企业名下首个有效状态工单 + if (!ticketId) { + const tickets = await searchAssistTicketsApi(client, corpId); + if (tickets.length === 0) { + throw new NotFoundError(`企业 [${corpId}] 协助中心未查询到任何协助工单`); + } + + const activeTicket = + tickets.find((t) => t.state === "已提供" || t.state === "待提供") ?? tickets[0]; + + if (!activeTicket || !activeTicket.ticketId) { + throw new NotFoundError(`企业 [${corpId}] 暂无可用状态的协助授权工单`); + } + ticketId = activeTicket.ticketId; + } + + const isAdmin = params.isAdmin !== false; + let resolvedStaffId = params.staffId?.trim(); + let resolvedStaffName = params.staffName?.trim(); + + // 若要求用户模式且指定了姓名,自动检索员工工号 + if (!isAdmin && resolvedStaffName && !resolvedStaffId) { + const staffList = await getStaffApi(client, corpId, resolvedStaffName); + if (staffList.length === 0) { + throw new NotFoundError( + `在企业 [${corpId}] 中未找到名为 "${resolvedStaffName}" 的员工` + ); + } + const targetStaff = staffList[0]; + resolvedStaffId = targetStaff.id; + resolvedStaffName = targetStaff.name; + } + + const tokenRes = await getAssistTokenApi(client, { + ticketId, + corporationId: corpId, + isAdmin, + staffId: resolvedStaffId, + }); + + return { + token: tokenRes.token, + loginUrl: tokenRes.loginUrl, + baseUrl: tokenRes.baseUrl, + ticketId, + corporationId: corpId, + isAdmin, + staffId: resolvedStaffId, + staffName: resolvedStaffName, + }; +} + +export interface ImportAssistSessionParams extends GenerateAssistSessionParams { + saveName?: string; + overwrite?: boolean; + enterprisesDir?: string; + ttl?: string | number; + elevate?: boolean; +} + +/** + * 自动化闭环:换取协助免密链接,并通过 importFromLink 一键落盘持久化至本地企业配置 + */ +export async function importAssistSessionToLocal( + client: KyInstance, + params: ImportAssistSessionParams +): Promise<{ + sessionResult: AssistPlatformSessionResult; + corpConfig: CorpConfig; +}> { + const sessionResult = await generateAssistSession(client, params); + + const importOptions: ImportFromLinkOptions = { + name: params.saveName, + overwrite: params.overwrite ?? true, + enterprisesDir: params.enterprisesDir, + ttl: params.ttl, + elevate: params.elevate ?? true, + }; + + const corpConfig = await importFromLink(sessionResult.loginUrl, importOptions); + + return { + sessionResult, + corpConfig, + }; +} diff --git a/src/domains/assist-platform/types.ts b/src/domains/assist-platform/types.ts new file mode 100644 index 0000000..ea9939e --- /dev/null +++ b/src/domains/assist-platform/types.ts @@ -0,0 +1,77 @@ +import { z } from "zod"; + +export const AssistPlatformCorporationSchema = z.object({ + id: z.string().describe("企业 ID"), + name: z.string().describe("企业名称"), + nameSpell: z.string().nullable().optional(), + platformName: z.string().nullable().optional().describe("部署集群/平台标识 (如 app, szcl-prod, 3in1, dd2)"), + state: z.string().nullable().optional().describe("企业状态 (如 可用, 未生效)"), + payType: z.string().nullable().optional().describe("付费模式 (TRYOUT 试用 / PAY 付费)"), + active: z.boolean().nullable().optional().describe("是否激活"), + sumPeople: z.number().nullable().optional().describe("授权人数上限"), + sourceChannel: z.string().nullable().optional().describe("来源渠道 (如 APP, FEISHU)"), + userId: z.string().nullable().optional().describe("创建者用户 ID"), + tel: z.string().nullable().optional().describe("绑定联系电话"), + createTime: z.number().nullable().optional(), + updateTime: z.number().nullable().optional(), +}); +export type AssistPlatformCorporation = z.infer; + +export const AssistPlatformTicketSchema = z.object({ + id: z.string().optional().describe("工单流水 ID"), + ticketId: z.string().describe("协助授权码 (用于换取免密调试会话)"), + applicant: z.string().describe("申请人姓名"), + applicantId: z.string().optional().describe("申请人工号/ID"), + principal: z.string().optional().describe("工单负责人姓名"), + principalId: z.string().optional().describe("工单负责人工号"), + state: z.string().describe("工单状态 (已提供 / 待提供 / 已过期)"), + duration: z.number().optional().describe("申请授权时长 (小时)"), + startTime: z.number().optional().describe("授权生效时间戳 (ms)"), + endTime: z.number().optional().describe("授权截止时间戳 (ms)"), + usePeriodDesc: z.string().optional().describe("使用日期范围文本 (如 2026-10-21 09:55 至 2026-10-22 09:54)"), + matter: z.string().optional().describe("申请事项描述"), + createTime: z.number().optional().describe("申请创建时间戳 (ms)"), +}); +export type AssistPlatformTicket = z.infer; + +export const AssistPlatformStaffSchema = z.object({ + id: z.string().describe("员工 ID (corpId:userId)"), + code: z.string().nullable().optional().describe("员工工号"), + name: z.string().describe("员工姓名"), + email: z.string().nullable().optional().describe("员工邮箱"), + cellphone: z.string().nullable().optional().describe("手机号码"), + admin: z.boolean().default(false).describe("是否具备管理员角色"), + userId: z.string().optional().describe("用户物理 ID"), + corporationId: z.string().describe("所属企业 ID"), + departments: z.array(z.string()).default([]).describe("所属部门 ID 列表"), + active: z.boolean().default(true), +}); +export type AssistPlatformStaff = z.infer; + +export const AssistPlatformSessionResultSchema = z.object({ + token: z.string().describe("临时协助会话 Token"), + loginUrl: z.string().url().describe("免密直通登录目标 URL"), + baseUrl: z.string().url().describe("基础服务域名"), + ticketId: z.string().describe("关联授权码"), + corporationId: z.string().describe("企业 ID"), + isAdmin: z.boolean().describe("是否为管理员模式"), + staffId: z.string().optional().describe("用户身份模式下的员工工号"), + staffName: z.string().optional().describe("用户姓名"), +}); +export type AssistPlatformSessionResult = z.infer; + +export const CorporationPackageVoSchema = z.object({ + packageId: z.string(), + name: z.string(), + enable: z.boolean(), + packageCatalogName: z.string().nullable().optional(), +}); +export type CorporationPackageVo = z.infer; + +export const CorporationDetailSchema = z.object({ + corporation: z.record(z.string(), z.any()).optional(), + basic: z.record(z.string(), z.any()).optional(), + corporationPackageVos: z.array(CorporationPackageVoSchema).default([]), + otherGoodsList: z.array(z.record(z.string(), z.any())).default([]), +}); +export type CorporationDetail = z.infer; diff --git a/src/packaging/embedded-skill.test.ts b/src/packaging/embedded-skill.test.ts index 4193dec..ddeb4c3 100644 --- a/src/packaging/embedded-skill.test.ts +++ b/src/packaging/embedded-skill.test.ts @@ -38,6 +38,8 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => { expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toContain("feetype"); expect(EMBEDDED_SKILL_FILES["references/store.md"]).toBeDefined(); expect(EMBEDDED_SKILL_FILES["references/store.md"]).toContain("hose-use keys"); + expect(EMBEDDED_SKILL_FILES["references/assist-platform.md"]).toBeDefined(); + expect(EMBEDDED_SKILL_FILES["references/assist-platform.md"]).toContain("assist-platform"); expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("--reveal -o "); expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("references/store.md"); @@ -54,7 +56,7 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => { try { const res = installSkillFiles(tmp); expect(res.targetDir).toBe(tmp); - expect(res.files.length).toBe(18); + expect(res.files.length).toBe(19); expect(existsSync(join(tmp, "SKILL.md"))).toBe(true); expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true); expect(existsSync(join(tmp, "references", "auth.md"))).toBe(true); diff --git a/src/packaging/embedded-skill.ts b/src/packaging/embedded-skill.ts index a60cf5e..8a3a4d8 100644 --- a/src/packaging/embedded-skill.ts +++ b/src/packaging/embedded-skill.ts @@ -16,6 +16,7 @@ import refRole from "../../skills/hose-use/references/role.md" with { type: "tex import refApproval from "../../skills/hose-use/references/approval.md" with { type: "text" }; import refFeeType from "../../skills/hose-use/references/feetype.md" with { type: "text" }; import refStore from "../../skills/hose-use/references/store.md" with { type: "text" }; +import refAssistPlatform from "../../skills/hose-use/references/assist-platform.md" with { type: "text" }; import multiMvel from "../../skills/hose-use/multi/ekuaibao-mvel/SKILL.md" with { type: "text" }; import multiMvelAgent from "../../skills/hose-use/multi/ekuaibao-mvel/agents/openai.yaml" with { type: "text" }; import multiNodes from "../../skills/hose-use/multi/ekuaibao-nodes/SKILL.md" with { type: "text" }; @@ -36,6 +37,7 @@ export const EMBEDDED_SKILL_FILES: Record = { "references/workflow.md": refWorkflow, "references/service.md": refService, "references/store.md": refStore, + "references/assist-platform.md": refAssistPlatform, "multi/ekuaibao-mvel/SKILL.md": multiMvel, "multi/ekuaibao-mvel/agents/openai.yaml": multiMvelAgent, "multi/ekuaibao-nodes/SKILL.md": multiNodes,