Merge pull request #77 from yunyingk/fix/sqlite-cache-migration-and-bill-mine
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled

fix: sqlite cache migration, bill timeout protection with --mine, and add-link overwrite UX (v0.8.7)
This commit is contained in:
yunyingk authored and GitHub committed 2026-09-17 10:06:30 +08:00
commit dd647b65a6
15 files changed
+658 -439

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.8.6",
"version": "0.8.7",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
+1 -1
View File
@@ -1,4 +1,4 @@
# hose-use (v0.8.6)
# hose-use (v0.8.7)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
+495 -417
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.8.6",
"version": "0.8.7",
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.8.6
version: 0.8.7
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.8.6",
"version": "0.8.7",
"module": "src/server.ts",
"type": "module",
"bin": {
+2 -2
View File
@@ -2,11 +2,11 @@
name: hose-use
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
metadata:
version: 0.8.6
version: 0.8.7
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
---
# hose-use (v0.8.6)
# hose-use (v0.8.7)
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
+14 -1
View File
@@ -44,7 +44,7 @@ export async function handleBillCommand(
const actionTarget = () => parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
const requireWriteConfirmation = async () => {
if (isDryRun(parsed, runtime) || booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
if (!process.stdin.isTTY || !process.stdout.isTTY) {
if (!process.stdin.isTTY || !process.stdout.isTTY || Boolean(process.env.CI) || process.env.NODE_ENV === "test") {
requireMutationConfirmation(
parsed,
runtime,
@@ -149,6 +149,19 @@ export async function handleBillCommand(
case "list":
case "search":
case undefined: {
const mine = booleanOption(parsed.options, ["mine", "my", "self"]);
if (mine) {
const { handleTaskCommand } = await import("./task.js");
return handleTaskCommand(
{
...parsed,
area: "task",
action: "submitted",
},
runtime
);
}
const code = stringOption(parsed.options, ["code", "c"]);
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
const stage = stringOption(parsed.options, ["stage"]);
+35 -8
View File
@@ -1,3 +1,4 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
import { importFromLink } from "../../core/auth/login.js";
import { resolveWritableEnterprisesDir } from "../../core/config/loader.js";
@@ -358,7 +359,7 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
const ttl = stringOption(parsed.options, ["ttl"]);
const expires = stringOption(parsed.options, ["expires", "days"]);
if (!linkUrl && process.stdin.isTTY) {
if (!linkUrl && process.stdin.isTTY && !process.env.CI && process.env.NODE_ENV !== "test") {
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
}
@@ -370,15 +371,41 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
};
}
let targetCorpId = "";
try {
const parsedUrl = new URL(linkUrl);
targetCorpId = parsedUrl.searchParams.get("ekbCorpId") || "";
} catch {}
const targetDir = resolveWritableEnterprisesDir();
const existsAlready = Boolean(targetCorpId && existsSync(join(targetDir, `${targetCorpId}.json`)));
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "从协助链接导入企业凭证", name || "待解析企业", {
source: "assistance-link",
overwrite,
ttl: ttl || null,
expires: expires || null,
});
return mutationPreview(
parsed,
runtime,
"从协助链接导入企业凭证",
name || (targetCorpId ? `企业 [${targetCorpId}]` : "待解析企业"),
{
source: "assistance-link",
overwrite,
alreadyExists: existsAlready,
ttl: ttl || null,
expires: expires || null,
note: existsAlready && !overwrite ? "检测到本地已存在该企业配置,导入执行时请带上 --overwrite 参数" : undefined,
}
);
}
requireMutationConfirmation(parsed, runtime, "从协助链接导入企业凭证", `hose-use corps add-link <url> --yes`);
const nextConfirmCmd = existsAlready && !overwrite
? `hose-use corps add-link <url> --overwrite --yes`
: `hose-use corps add-link <url> --yes`;
const confirmOp = existsAlready && !overwrite
? `从协助链接导入企业凭证(检测到目标企业 [${targetCorpId}] 已存在,需覆盖更新)`
: "从协助链接导入企业凭证";
requireMutationConfirmation(parsed, runtime, confirmOp, nextConfirmCmd);
try {
const corp = await importFromLink(linkUrl, {
+3 -1
View File
@@ -80,7 +80,9 @@ export class SqliteCache implements ICache {
[namespace, key, serialized, expiresAt, now]
);
} catch (err) {
console.error(`[cache] SqliteCache.set error for ${namespace}:${key}:`, err);
if (process.env.DEBUG || process.env.NODE_ENV === "development") {
console.error(`[cache] SqliteCache.set error for ${namespace}:${key}:`, err);
}
}
}
+39
View File
@@ -66,6 +66,45 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
expect(countRow.c).toBe(2);
});
test("migration 2 可以平滑升级遗留的单列主键 cache_entries 表", () => {
const legacyDb = new Database(":memory:");
legacyDb.run(`
CREATE TABLE cache_entries (
key TEXT PRIMARY KEY,
namespace TEXT NOT NULL,
value TEXT NOT NULL,
expires_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`);
legacyDb.run(
"INSERT INTO cache_entries (key, namespace, value, expires_at, updated_at) VALUES ('k1', 'n1', 'v1', 9999, 1000)"
);
// 运行全量迁移
runMigrations(legacyDb);
// 验证升级后支持相同 key 不同 namespace
expect(() => {
legacyDb.run(
"INSERT INTO cache_entries (key, namespace, value, expires_at, updated_at) VALUES ('k1', 'n2', 'v2', 9999, 1000)"
);
}).not.toThrow();
// 验证 ON CONFLICT(namespace, key) 正常工作
expect(() => {
legacyDb.run(`
INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at)
VALUES ('n1', 'k1', 'v1_updated', 9999, 2000)
ON CONFLICT(namespace, key) DO UPDATE SET value = excluded.value
`);
}).not.toThrow();
const row = legacyDb.query("SELECT value FROM cache_entries WHERE namespace = 'n1' AND key = 'k1'").get() as { value: string };
expect(row.value).toBe("v1_updated");
legacyDb.close();
});
test("再次执行 runMigrations 保证幂等且不抛错", () => {
expect(() => runMigrations(db)).not.toThrow();
});
+40
View File
@@ -144,6 +144,46 @@ export const migrations: DatabaseMigration[] = [
seedDefaultPreference(db);
},
},
{
version: 2,
name: "002_cache_entries_composite_primary_key",
up(db: Database): void {
// 检查 cache_entries 的主键约束
// 兼容历史遗留的 key PRIMARY KEY 单列主键库,平滑升级为复合主键 (namespace, key)
const tableInfo = db.query("PRAGMA table_info(cache_entries)").all() as Array<{
name: string;
pk: number;
}>;
const pkColumns = tableInfo.filter((col) => col.pk > 0);
const isCompositePk =
pkColumns.length === 2 &&
pkColumns.some((c) => c.name === "namespace") &&
pkColumns.some((c) => c.name === "key");
if (!isCompositePk) {
db.run(`
CREATE TABLE IF NOT EXISTS cache_entries_v2 (
namespace TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
expires_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (namespace, key)
);
`);
try {
db.run(`
INSERT OR IGNORE INTO cache_entries_v2 (namespace, key, value, expires_at, updated_at)
SELECT namespace, key, value, expires_at, updated_at FROM cache_entries;
`);
} catch {}
db.run("DROP TABLE IF EXISTS cache_entries;");
db.run("ALTER TABLE cache_entries_v2 RENAME TO cache_entries;");
db.run("CREATE INDEX IF NOT EXISTS idx_cache_namespace ON cache_entries(namespace);");
db.run("CREATE INDEX IF NOT EXISTS idx_cache_expires_at ON cache_entries(expires_at);");
}
},
},
];
function seedDefaultPreference(db: Database): void {
+4
View File
@@ -3,6 +3,7 @@ import ky, { KyInstance } from "ky";
export interface CreateClientOptions {
prefixUrl: string;
headers?: Record<string, string>;
timeout?: number | false;
}
export interface CreateAuthClientOptions {
@@ -11,18 +12,21 @@ export interface CreateAuthClientOptions {
onUnauthorized?: () => Promise<void> | void;
onAuthFailure?: (response: Response) => Error;
retryUnauthorized?: boolean;
timeout?: number | false;
}
export function createClient(options: CreateClientOptions): KyInstance {
return ky.create({
prefix: options.prefixUrl,
headers: options.headers,
timeout: options.timeout ?? 30000,
});
}
export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
return ky.create({
prefix: options.prefixUrl,
timeout: options.timeout ?? 30000,
retry: {
limit: options.retryUnauthorized === false ? 0 : 1,
methods: ["get", "post", "put", "delete", "patch"],
+2 -1
View File
@@ -313,10 +313,11 @@ export async function getRawBillRisk(
export async function searchRawBills(
client: KyInstance,
corpId: string,
options: { start?: number; count?: number } = {}
options: { start?: number; count?: number; timeout?: number | false } = {}
): Promise<RawBillSearchResponse> {
const response = await client.post("api/v2/invoice/search", {
searchParams: { corporationId: corpId, corpId },
timeout: options.timeout ?? 30000,
json: {
limit: {
start: options.start ?? 0,
+19 -4
View File
@@ -32,6 +32,7 @@ import {
} from "./translator.js";
import {
type RawBillItem,
type RawBillSearchResponse,
type FormattedBill,
type BillPageResult,
type EntityMeta,
@@ -1145,10 +1146,24 @@ export async function searchAndFormatBills(
params: BillQueryParams = {}
): Promise<BillPageResult> {
const { dictionary } = await getFieldDictionary(client, corpId);
const searchRes = await searchRawBills(client, corpId, {
start: params.start ?? 0,
count: params.count ?? 50,
});
let searchRes: RawBillSearchResponse;
try {
searchRes = await searchRawBills(client, corpId, {
start: params.start ?? 0,
count: params.count ?? 50,
});
} catch (err) {
if (String(err).includes("timed out") || (err as any)?.name === "TimeoutError") {
throw new Error(
`全局单据台账检索超时。在大企业或海量单据租户中,全量检索较为耗时。\n` +
`建议:\n` +
` - 查看当前员工发起的单据:hose-use task submitted 或 hose-use bill list --mine\n` +
` - 查看待我审批单据:hose-use task todo\n` +
` - 按单号精确查询:hose-use bill get <单号>`
);
}
throw err;
}
let filtered = searchRes.items;