import { writeFileSync } from "node:fs"; import { formatVersionLabel } from "../version.js"; import type { OutputOptions } from "./types.js"; import { PayloadTooLargeError } from "./errors.js"; import { renderScopedHelp } from "./help.js"; export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000; /** Await the write callback so a slow terminal or pipe applies backpressure. */ export function writeStdoutChunk(chunk: string): Promise { return new Promise((resolve, reject) => { process.stdout.write(chunk, error => error ? reject(error) : resolve()); }); } export function redactSensitiveText(value: string): string { return value .replace(/([?&](?:accessToken|token|returnToken|security-token|x-amz-security-token|signature|x-amz-signature|ossaccesskeyid|x-amz-credential)=)[^&\s"']+/gi, "$1") .replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1") .replace(/((?:password|passwd|secret|appSecurity)["']?\s*[:=]\s*["']?)[^"',\s}]+/gi, "$1"); } export function protectLargeOutput(result: unknown, options: OutputOptions = {}) { if (options.allowFull || options.outputFile) return; const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8"); if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) { throw new PayloadTooLargeError( `输出体积过大 (${bodyBytes} 字节,超过安全阈值 ${DEFAULT_OUTPUT_BYTES_LIMIT} 字节)。请使用 --output-file <路径> (或 -o <路径>) 转储到本地文件;若确需完整大报文请附加 --full 参数。`, "hose-use --json --output-file " ); } } export function printJson(data: unknown, options: OutputOptions = {}): string { protectLargeOutput(data, options); const json = JSON.stringify(data, null, 2); if (options.outputFile) { writeFileSync(options.outputFile, json, "utf-8"); return JSON.stringify( { outputFile: options.outputFile, bytes: Buffer.byteLength(json, "utf-8"), }, null, 2 ); } return json; } export function formatSourceLabel(source?: string, persistentOpenApi?: boolean): string { if (persistentOpenApi || source === "openapi") { return "企业开放接口 (OpenAPI 密钥)"; } switch (source) { case "account": return "个人账号凭证 (手机号)"; case "assist": case "link": return "合思协助平台授权链接 (协助链接)"; case "browser": case "curl": case "f12": return "网页临时抓包凭证 (Cookie)"; case "manual": return "手动配置"; default: return source ? `其他 (${source})` : "未知来源"; } } export function formatExpiresAt( expiresAt?: number | null, persistent?: boolean, source?: string ): string { if (!expiresAt || expiresAt <= 0) { if (source === "openapi") { return "长期有效 (OpenAPI 密钥)"; } return "长期有效 / 服务端未显式限制"; } const diffMs = expiresAt - Date.now(); const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false }); if (diffMs <= 0) { if (persistent) { if (source === "account") { return `${dateStr} (🔄 随主账号自动换票)`; } if (source === "openapi") { return `${dateStr} (🔄 OpenAPI 密钥自动续期)`; } return `${dateStr} (🔄 自动续期)`; } if (source === "link" || source === "assist") { return `${dateStr} (⚠️ 协助授权已失效)`; } if (source === "curl" || source === "browser" || source === "f12") { return `${dateStr} (⚠️ Cookie 已失效)`; } return `${dateStr} (⚠️ 已过期)`; } const diffMins = Math.floor(diffMs / 60000); if (diffMins < 60) { const renewSuffix = persistent ? source === "account" ? ",支持主账号自动换票" : source === "openapi" ? ",支持 OpenAPI 密钥自动续期" : ",支持自动续期" : ""; return `${dateStr} (约剩余 ${diffMins} 分钟${renewSuffix})`; } const diffHours = (diffMs / 3600000).toFixed(1); if (Number(diffHours) < 24) { const renewSuffix = persistent ? source === "account" ? ",支持主账号自动换票" : source === "openapi" ? ",支持 OpenAPI 密钥自动续期" : ",支持自动续期" : ""; return `${dateStr} (约剩余 ${diffHours} 小时${renewSuffix})`; } const diffDays = Math.floor(diffMs / 86400000); const renewSuffix = persistent ? source === "account" ? ",支持主账号自动换票" : source === "openapi" ? ",支持 OpenAPI 密钥自动续期" : "" : ""; return `${dateStr} (约剩余 ${diffDays} 天${renewSuffix})`; } export function printKeyValue(pairs: Record): string { const lines: string[] = []; const maxKeyLen = Math.max(...Object.keys(pairs).map((k) => k.length), 0); for (const [key, val] of Object.entries(pairs)) { const formattedVal = typeof val === "object" ? JSON.stringify(val) : String(val ?? ""); lines.push(` ${key.padEnd(maxKeyLen + 2)}: ${formattedVal}`); } return lines.join("\n"); } export function printTable( headers: string[], rows: Array> ): string { if (rows.length === 0) return " (暂无数据)\n"; const strRows = rows.map((r) => r.map((c) => String(c ?? ""))); const colWidths = headers.map((h, colIdx) => { const maxRowWidth = Math.max(...strRows.map((r) => (r[colIdx] || "").length), 0); return Math.max(h.length, maxRowWidth); }); const headerLine = headers.map((h, i) => h.padEnd(colWidths[i])).join(" "); const separatorLine = colWidths.map((w) => "-".repeat(w)).join(" "); const dataLines = strRows.map((r) => r.map((c, i) => c.padEnd(colWidths[i])).join(" ") ); return [headerLine, separatorLine, ...dataLines].map((l) => ` ${l}`).join("\n"); } export function printHelp(target: string[] = []): string { if (target.length) return renderScopedHelp(target); return ` 合思/易快报企业级 CLI 工具 (${formatVersionLabel("hose-use")}) 用法: hose-use <命令域> <子命令> [参数] [选项] 核心命令域: context 查看全局运行上下文与身份诊断 (context, status, whoami, env) auth 认证与凭证管理 (login, status, refresh, import, accounts, switch-account) corps 多企业租户管理 (list, search <关键词>, switch, current, add-link) aipro 合思 AI PRO 确定性审批仲裁网关入口 (status, scopes, bind, checklist, review, decide, logs) config 全局运行模式与路径诊断 (show, paths, mode , set) workflow 工作流管理 (list, get, find, analyze, job, toggle, publish, patch, save, history, logs, check) bill 单据检索、模板规格与审批动作 (list, get <单号|ID> [--risk], spec <模板ID>, approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link) contact 企业通讯录与人员检索 (list, search <关键词>, get ) task 待办中心与审批任务 (todo, approved, records, submitted, cc) message 消息中心与通知管理 (list, count, read, read-all) app 应用管理 (桌面端工作台业务应用: list [--keyword], get <应用ID|名称>) menu 桌面端主导航菜单树与模块 (list, tree, apps) platform 自建应用与数据模型 (list, get, entities, schema, records [--all], record get|create|edit|batch-edit, audit, permissions, imports) datalink platform 的同义入口,面向 DataLink 业务对象查询 dimension 系统/自定义档案维度 (list, items <维度>) feetype 费用类型管理与字段规格配置 (list, get, spec <模板ID>, create, update, disable, enable, move, fields) role 角色定义与成员 (list, groups, members <角色>) permission 权限模型快照 (get) rule 本地 AI 审批规约管理 (scopes, scope <索引号|场景>, list, get, add, delete) approval 确定性审批网关与要点仲裁 (audit points <单号>, checklist <单号>, review <单号>, decide <单号>) skill Agent Skill 管理 (install, status, dump) probe 连通性诊断 (probe [corpId]) update 版本自更新与发布记录 (update, update check, update --changelog, --github, --gitea, --repo=) openapi OpenAPI 3.1.0 规范导出与凭证查看 (openapi, openapi --raw, openapi paths, openapi info, openapi keys) keys 企业 OpenAPI 接入凭证一键获取 (keys [--reveal|-r]) store 应用中心已购应用与应用商店探查 (list, search <关键词>, get ) http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1]) service 常驻守护进程管理 (service start|stop|restart|status|logs|poll) mcp MCP Server 运行 (serve) version 查看版本信息 全局选项: --corp= 临时指定操作的企业/身份 ID (覆盖默认企业) --json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成) --output-file, -o 将大体积结果直接转储至本地文件并输出精简摘要 --full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截) --stateless 单次强制以无状态模式执行 --stateful 单次强制以有状态模式执行 --dry-run 只预览写操作,不发起写请求或落盘 --yes, -y 确认执行会改变数据的写操作 --confirm --yes 的可读别名;写操作必须显式确认 --help, -h 查看帮助信息 常用示例: hose-use context # 一键查看全局运行上下文与身份诊断 (免读源码) hose-use aipro status # 查看 AI PRO 审批网关状态与当前连接企业 hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录 hose-use auth status # 查看当前登录状态与活跃企业 hose-use config paths # 查看多级企业配置目录链 hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作) hose-use corps list # 列出名下所有企业 hose-use corps search 某企业 # 模糊搜索已保存的企业与员工信息 hose-use corps switch ID01MCcOgJl1td # 切换工作企业 hose-use contact search 张三 # 模糊搜索员工工号、邮箱与电话 hose-use contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护) hose-use task todo --json # 查看当前待我审批任务 hose-use task approved # 查看我已审批任务 hose-use task submitted # 查看我发起的单据 hose-use task cc --unread # 查看未读抄送 hose-use message list --unread # 查看未读消息 hose-use message list --all # 合并查看已读和未读消息 hose-use message count # 查看未读消息数 hose-use workflow list # 汇总查看全部工作流 hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流 hose-use app list # 查看应用管理列表(桌面端工作台开通的业务应用) hose-use app get 用车补贴 # 查看指定应用管理的详情与元数据配置 hose-use menu list # 查看桌面端主框架一级导航树与功能模块 hose-use platform list # 列出企业可见的自建应用平台 hose-use platform entities <应用> # 查看应用下的业务对象 hose-use platform schema <应用> <对象> # 查看对象字段(--keyword 可筛选字段) hose-use platform records <应用> <对象> --keyword 关键词 --fields 名称,编码 --json # 查询记录并只输出指定字段 hose-use platform permissions <应用> [对象] # 查看应用/对象权限快照 hose-use bill list # 查看当前企业单据与报销列表 hose-use bill list --keyword=打车 --search-fields=name,form # 跨字段复合检索单据 hose-use bill flow S26000001 # 查看单据审批历史与后续节点 hose-use bill risk S26000001 # 查看风控预警、预算与发票风险 hose-use bill refs S26000001 # 二级解析提交人、部门、法人实体与费用类型引用 hose-use bill relations S26000001 # 追溯冲借款、事前申请和合同关联 hose-use bill budget S26000001 # 查看单据预算超限和预算接口状态 hose-use bill attachments S26000001 # 查看单据附件和发票原件标准列表 hose-use bill download S26000001 --output-dir ./downloads # 下载单据附件到本地目录 hose-use dimension list # 查看系统与自定义档案维度 hose-use dimension items 项目 # 查看项目档案项 hose-use feetype list # 查看费用类型树与层级关系 hose-use feetype get 交通费 --specs # 查看费用类型详情与报账/申请字段 hose-use feetype create --name="打车费" --parent="交通费" # 在指定父级下创建费用类型 hose-use feetype update 打车费 --desc="滴滴打车" # 修改费用类型属性 hose-use feetype disable 打车费 # 停用费用类型 hose-use feetype enable 打车费 # 重新启用费用类型 hose-use feetype move 打车费 --parent="差旅费用" # 移动费用类型到新的父级 hose-use role list # 查看企业角色定义 hose-use role groups # 查看角色组及其角色 hose-use role members 财务主管 # 查看指定角色成员 hose-use permission get # 查看角色权限开关 hose-use bill link CL20260901001 # 获取单据 Web 详情直达免密跳转链接 hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆 hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情 hose-use bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照 hose-use bill approve S26000001 --yes # 同意待审批单据 hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并填写原因 hose-use bill transfer S26000001 --approver-id <员工ID> --yes # 转交审批 hose-use bill add-node S26000001 --approver-id <员工ID> --mode pre --yes # 前加签 hose-use bill comment S26000001 --comment "请补充发票" --yes # 添加单据评论 hose-use http --port=8888 # 启动本地 HTTP 服务与可视化交互文档 hose-use service start # 后台启动常驻守护进程服务 hose-use service status # 查看守护进程运行状态与接口地址 hose-use service poll --corp= # 轮询待办/消息并持久化去重事件 hose-use probe # 诊断当前企业鉴权连通性 hose-use skill install # 安装 Agent 技能到用户目录 hose-use update # 自动检查并升级到最新版本 hose-use update --github # 强制走官方 GitHub 源升级 hose-use update --changelog # 查看版本发布历史 hose-use openapi paths # 查看所有 API 路径与概要一览 hose-use openapi --raw # 导出原生下游全量 OpenAPI 规范 `.trim(); }