@fangcuntai/fangcuntai-mcp 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,182 @@
1
+ # @fangcuntai/fangcuntai-mcp
2
+
3
+ 方寸台桌面助手 MCP 服务,供有道龙虾 / OpenClaw / Claude Desktop / Cursor 等客户端连接。
4
+
5
+ 用自然语言完成:**切换家庭/账本 → 查账 →(解锁并确认后)记一笔/删一笔**;删除进回收站可恢复;**整理记事两层文件夹**(浏览本层、建文件夹、移动记事)。
6
+
7
+ > **事情提醒已下线**:不再提供 `list_reminders` / `create_reminder_draft` / `mark_reminder_done`。
8
+
9
+ ## 前置条件
10
+
11
+ 1. 在方寸台 App:**我的 → 设置 → 连接桌面助手**
12
+ 2. 选择**默认家庭**,勾选权限后生成令牌(查询账单 / 查看统计 / 创建草稿 / 记一笔·删除;已有令牌不能改权限);可一键复制完整 MCP 配置
13
+ 3. 按页面内「如何安装到桌面 AI」把配置粘贴到龙虾 / Claude Desktop / Cursor
14
+ 4. 确保主 API 可访问(App 生产:`https://api-service.fangcuntai.com`;本地默认 `http://127.0.0.1:9080`)
15
+
16
+ ## 环境变量
17
+
18
+ | 变量 | 必填 | 说明 |
19
+ |------|------|------|
20
+ | `FANGCUNTAI_TOKEN` | 是 | App 生成的助手令牌(`hm_at_...`) |
21
+ | `FANGCUNTAI_API` | 否 | API 根地址,默认 `http://127.0.0.1:9080` |
22
+
23
+ > 兼容旧变量名:`HOME_MAN_TOKEN` / `HOME_MAN_API`(仍可使用,优先读 `FANGCUNTAI_*`)。
24
+
25
+ ## 安全模型(v1.5)
26
+
27
+ 防的是:**AI 误调写接口改正式数据**(MCP 不直连数据库)。
28
+
29
+ | 层 | 机制 |
30
+ |----|------|
31
+ | **确认锁(前门)** | 默认上锁。入账/删除记账或记事/清空回收站/确认草稿(含批量)/删除文件夹/移动记事所属:`unlock_writes` → `prepare_*` → 展示摘要 → `confirm_*` |
32
+ | **结构写(轻门)** | 新建/改名/移动文件夹:须 `unlock_writes` 后直接调用(非空文件夹不可删,服务端兜底) |
33
+ | **令牌权限** | App 生成时勾选查询/统计/草稿/记一笔;缺权限时工具拒绝并提示重新生成。已有令牌不能改权限 |
34
+ | **来源标记(追溯)** | 入账 `source=desktop_mcp`,App 可区分桌面助手写入 |
35
+ | **回收站(后门)** | 删除软删;`list_ledger_trash` / `restore_ledger_entry`、`list_notes_trash` / `restore_note` 可恢复。清空回收站为永久删除,须确认锁 |
36
+
37
+ 查账、列账本、列文件夹、建草稿、丢弃草稿、恢复回收站:**不需解锁**。
38
+
39
+ > 亦可先 `create_ledger_draft` / `create_note_draft`,再确认草稿入账。当前账号开启个人 `auto_confirm_ai_drafts`(App「设置 → 草稿自动保存」)后,创建草稿会自动确认;失败则仍为 `pending`,可在 App「我的 → AI 草稿箱」批量保存。家长打开开关不会替家人自动保存。
40
+
41
+ ## 有道龙虾 / OpenClaw 配置示例
42
+
43
+ ```json
44
+ {
45
+ "command": "npx",
46
+ "args": ["-y", "@fangcuntai/fangcuntai-mcp"],
47
+ "env": {
48
+ "FANGCUNTAI_API": "https://api-service.fangcuntai.com",
49
+ "FANGCUNTAI_TOKEN": "hm_at_你的令牌"
50
+ }
51
+ }
52
+ ```
53
+
54
+ ## 推荐用法
55
+
56
+ ### 查账(无需解锁)
57
+
58
+ `list_my_families` → `select_family` → `list_ledger_books` → `select_ledger_book` → `get_ledger_summary` / `list_ledger_entries`
59
+
60
+ ### 记一笔(须确认)
61
+
62
+ 1. 征得用户同意 → `unlock_writes`(`user_acknowledged=true`)
63
+ 2. `prepare_create_ledger_entry` → 向用户展示 summary
64
+ 3. 用户说确认 → `confirm_create_ledger_entry(confirm_token)`
65
+
66
+ ### 删一笔(进回收站)
67
+
68
+ `unlock_writes` → `prepare_delete_ledger_entry` → 确认 → `confirm_delete_ledger_entry`
69
+ 误删:`list_ledger_trash` → `restore_ledger_entry`
70
+ 清空:`prepare_empty_ledger_trash` → 确认 → `confirm_empty_ledger_trash`(永久删除)
71
+
72
+ ### 删一篇记事(进回收站)
73
+
74
+ `unlock_writes` → `prepare_delete_note` → 确认 → `confirm_delete_note`
75
+ 误删:`list_notes_trash` → `restore_note`
76
+ 清空:`prepare_empty_notes_trash` → 确认 → `confirm_empty_notes_trash`(永久删除)
77
+
78
+ ## 工具列表(v1.5)
79
+
80
+ ### 安全锁
81
+
82
+ | Tool | 说明 |
83
+ |------|------|
84
+ | `get_write_lock_status` | 是否解锁、剩余秒数 |
85
+ | `unlock_writes` | 解锁(须 `user_acknowledged=true`) |
86
+ | `lock_writes` | 立即上锁 |
87
+
88
+ ### 上下文 / 工作区
89
+
90
+ | Tool | 说明 |
91
+ |------|------|
92
+ | `get_assistant_context` | 令牌默认家庭 / 公开 scopes + workspace |
93
+ | `get_active_workspace` | 当前会话家庭与账本 |
94
+ | `list_my_families` / `select_family` | 家庭列表与切换 |
95
+ | `get_bound_family` / `get_family_entitlements` / `list_family_members` | 家庭信息与权限 |
96
+
97
+ ### 记账
98
+
99
+ | Tool | 说明 |
100
+ |------|------|
101
+ | `list_ledger_books` / `select_ledger_book` | 账本 |
102
+ | `get_ledger_summary` / `list_ledger_entries` / `get_ledger_trends` | 查账;`list_ledger_entries` 可按 `external_order_id` 精确查找 |
103
+ | `list_ledger_categories` | 分类 |
104
+ | `prepare_create_ledger_entry` / `confirm_create_ledger_entry` | 确认后入账;可传 `external_order_id`,已存在则 `already_exists` |
105
+ | `prepare_delete_ledger_entry` / `confirm_delete_ledger_entry` | 确认后进回收站 |
106
+ | `list_ledger_trash` / `restore_ledger_entry` | 回收站 |
107
+ | `prepare_empty_ledger_trash` / `confirm_empty_ledger_trash` | 清空回收站(永久删除) |
108
+ | `create_ledger_draft` | 仅草稿 |
109
+
110
+ ### 记事 / 文件夹 / 草稿
111
+
112
+ | Tool | 说明 |
113
+ |------|------|
114
+ | `list_note_folders` | 文件夹扁平列表(最多两层;按 `parent_id` 组树) |
115
+ | `create_note_folder` / `rename_note_folder` / `move_note_folder` | 建/改名/移动文件夹(须 `unlock_writes`) |
116
+ | `prepare_delete_note_folder` / `confirm_delete_note_folder` | 删空文件夹(须解锁 + confirm_token;非空拒绝) |
117
+ | `list_notes` / `search_notes` | 记事;`list_notes` 可传 `folder_id`(`0`=未分类;有关键词时忽略) |
118
+ | `create_note_draft` | 记事草稿;可传 `folder_id` |
119
+ | `prepare_move_note` / `confirm_move_note` | 已有记事改所属文件夹(须解锁 + confirm_token) |
120
+ | `prepare_delete_note` / `confirm_delete_note` | 确认后进回收站 |
121
+ | `list_notes_trash` / `restore_note` | 记事回收站 |
122
+ | `prepare_empty_notes_trash` / `confirm_empty_notes_trash` | 清空记事回收站(永久删除) |
123
+ | `list_ai_drafts` | 待确认列表(**仅当前账号自己创建的**;家长也不能看全家);可传 `session_id=mcp` |
124
+ | `get_ai_draft` | 单条详情(仅创建者;他人 404) |
125
+ | `prepare_confirm_ai_draft` / `confirm_ai_draft` | 单条确认(须解锁 + confirm_token;仅创建者) |
126
+ | `discard_ai_draft` | 单条丢弃(仅创建者) |
127
+ | `prepare_batch_confirm_ai_drafts` / `batch_confirm_ai_drafts` | 批量确认自己的草稿(须解锁 + confirm_token) |
128
+ | `batch_discard_ai_drafts` | 批量丢弃自己的草稿(不改正式数据,无需解锁) |
129
+
130
+ > App 侧也可在 **我的 → AI 草稿箱** 勾选后批量保存。文件夹规则与 App 一致:全家共用、最多两层、非空不可删。
131
+
132
+ ### 推荐:整理记事文件夹
133
+
134
+ 1. `list_note_folders` → 了解树
135
+ 2. 征得同意 → `unlock_writes`
136
+ 3. `create_note_folder` / `rename_note_folder` / `move_note_folder`
137
+ 4. `list_notes(folder_id=…)` 浏览本层;`create_note_draft(folder_id=…)` 写入
138
+ 5. 移动已有记事:`prepare_move_note` → 确认 → `confirm_move_note`
139
+ 6. 删空文件夹:`prepare_delete_note_folder` → 确认 → `confirm_delete_note_folder`
140
+
141
+ ### 账号只读
142
+
143
+ | Tool | 说明 |
144
+ |------|------|
145
+ | `get_subscription_info` | 订阅状态 |
146
+ | `get_credit_balance` | AI 积分余额 |
147
+
148
+ ## 安全说明
149
+
150
+ - 令牌生成时**绑定默认家庭**;MCP 会话可切换到**你已加入**的其他家庭,不能访问无关家庭
151
+ - 助手令牌仅开放白名单 API;写操作前检查家庭 `entitlements`
152
+ - App 内可随时撤销令牌
153
+ - 请求带 `X-App-ID: 60000` 与 `X-MCP-Tool`
154
+
155
+ ## 本地开发
156
+
157
+ ```bash
158
+ cd fangcuntai-mcp
159
+ npm install
160
+ npm test
161
+ npm run build
162
+ FANGCUNTAI_TOKEN=hm_at_xxx FANGCUNTAI_API=http://127.0.0.1:9080 node dist/index.js
163
+ ```
164
+
165
+ ### 本地功能测试数据
166
+
167
+ 先确保本地 PostgreSQL(`127.0.0.1:5433`)和 Redis(`127.0.0.1:6379`)可用,再执行:
168
+
169
+ ```bash
170
+ cd ../home-admin
171
+ go run cmd/seed-mcp-test-data/main.go -config config/config.yaml
172
+ ```
173
+
174
+ 命令仅允许写本机开发库,可重复执行且不会重复插入。它会创建 2 个家庭、2 个账本、
175
+ 近 3 个月账单、回收站条目、两层记事文件夹、不同可见范围的记事、MCP / 小家师草稿、
176
+ 积分和固定测试令牌。输出中的 `FANGCUNTAI_TOKEN` 可直接用于本地 MCP 配置。
177
+
178
+ ## 发布
179
+
180
+ ```bash
181
+ npm publish --access public
182
+ ```
@@ -0,0 +1,27 @@
1
+ export type ApiEnvelope<T = Record<string, unknown>> = {
2
+ code: number;
3
+ message: string;
4
+ data?: T;
5
+ };
6
+ /**
7
+ * 主 API 的产品契约使用 code=0;当前 HTTP 控制器仍返回 200/201。
8
+ * MCP 同时兼容两种信封,错误码继续按非 2xx 业务码映射。
9
+ */
10
+ export declare function isSuccessEnvelopeCode(code: number, httpStatus: number): boolean;
11
+ export declare class FangcuntaiApiClient {
12
+ private readonly apiBase;
13
+ private readonly token;
14
+ private lastToolName;
15
+ constructor(apiBase: string, token: string);
16
+ /** 设置当前 MCP Tool 名,写入 X-MCP-Tool 供后端审计。 */
17
+ setToolName(name: string): void;
18
+ private headers;
19
+ get<T = Record<string, unknown>>(path: string, query?: Record<string, string | number | boolean | undefined>): Promise<T>;
20
+ post<T = Record<string, unknown>>(path: string, body?: unknown): Promise<T>;
21
+ patch<T = Record<string, unknown>>(path: string, body?: unknown): Promise<T>;
22
+ put<T = Record<string, unknown>>(path: string, body?: unknown): Promise<T>;
23
+ delete<T = Record<string, unknown>>(path: string, query?: Record<string, string | number | boolean | undefined>): Promise<T>;
24
+ private parse;
25
+ }
26
+ /** @deprecated 使用 FangcuntaiApiClient */
27
+ export { FangcuntaiApiClient as HomeManApiClient };
@@ -0,0 +1,102 @@
1
+ import { mapApiError } from "../errors/user-messages.js";
2
+ const APP_ID_DESKTOP = "60000";
3
+ /**
4
+ * 主 API 的产品契约使用 code=0;当前 HTTP 控制器仍返回 200/201。
5
+ * MCP 同时兼容两种信封,错误码继续按非 2xx 业务码映射。
6
+ */
7
+ export function isSuccessEnvelopeCode(code, httpStatus) {
8
+ if (code === 0)
9
+ return true;
10
+ return httpStatus >= 200 && httpStatus < 300 && code >= 200 && code < 300;
11
+ }
12
+ export class FangcuntaiApiClient {
13
+ apiBase;
14
+ token;
15
+ lastToolName = "";
16
+ constructor(apiBase, token) {
17
+ this.apiBase = apiBase;
18
+ this.token = token;
19
+ }
20
+ /** 设置当前 MCP Tool 名,写入 X-MCP-Tool 供后端审计。 */
21
+ setToolName(name) {
22
+ this.lastToolName = name;
23
+ }
24
+ headers() {
25
+ const headers = {
26
+ Authorization: `Bearer ${this.token}`,
27
+ "Content-Type": "application/json",
28
+ Accept: "application/json",
29
+ "Accept-Language": "zh-Hans",
30
+ "X-App-ID": APP_ID_DESKTOP,
31
+ };
32
+ if (this.lastToolName) {
33
+ headers["X-MCP-Tool"] = this.lastToolName;
34
+ }
35
+ return headers;
36
+ }
37
+ async get(path, query) {
38
+ const url = new URL(`${this.apiBase}${path}`);
39
+ if (query) {
40
+ for (const [k, v] of Object.entries(query)) {
41
+ if (v !== undefined && v !== "")
42
+ url.searchParams.set(k, String(v));
43
+ }
44
+ }
45
+ const res = await fetch(url, { method: "GET", headers: this.headers() });
46
+ return this.parse(res);
47
+ }
48
+ async post(path, body) {
49
+ const res = await fetch(`${this.apiBase}${path}`, {
50
+ method: "POST",
51
+ headers: this.headers(),
52
+ body: body === undefined ? undefined : JSON.stringify(body),
53
+ });
54
+ return this.parse(res);
55
+ }
56
+ async patch(path, body) {
57
+ const res = await fetch(`${this.apiBase}${path}`, {
58
+ method: "PATCH",
59
+ headers: this.headers(),
60
+ body: body === undefined ? undefined : JSON.stringify(body),
61
+ });
62
+ return this.parse(res);
63
+ }
64
+ async put(path, body) {
65
+ const res = await fetch(`${this.apiBase}${path}`, {
66
+ method: "PUT",
67
+ headers: this.headers(),
68
+ body: body === undefined ? undefined : JSON.stringify(body),
69
+ });
70
+ return this.parse(res);
71
+ }
72
+ async delete(path, query) {
73
+ const url = new URL(`${this.apiBase}${path}`);
74
+ if (query) {
75
+ for (const [k, v] of Object.entries(query)) {
76
+ if (v !== undefined && v !== "")
77
+ url.searchParams.set(k, String(v));
78
+ }
79
+ }
80
+ const res = await fetch(url, { method: "DELETE", headers: this.headers() });
81
+ return this.parse(res);
82
+ }
83
+ async parse(res) {
84
+ const text = await res.text();
85
+ let json;
86
+ try {
87
+ json = JSON.parse(text);
88
+ }
89
+ catch {
90
+ throw new Error(`API 响应解析失败 (HTTP ${res.status})`);
91
+ }
92
+ if (typeof json.code !== "number") {
93
+ throw new Error(`API 响应格式异常 (HTTP ${res.status})`);
94
+ }
95
+ if (!isSuccessEnvelopeCode(json.code, res.status)) {
96
+ throw new Error(mapApiError(json.code, json.message));
97
+ }
98
+ return (json.data ?? {});
99
+ }
100
+ }
101
+ /** @deprecated 使用 FangcuntaiApiClient */
102
+ export { FangcuntaiApiClient as HomeManApiClient };
@@ -0,0 +1,9 @@
1
+ export type AppConfig = {
2
+ apiBase: string;
3
+ token: string;
4
+ };
5
+ /**
6
+ * 读取 MCP 配置。
7
+ * 优先使用 FANGCUNTAI_*,兼容旧版 HOME_MAN_*。
8
+ */
9
+ export declare function loadConfig(env?: NodeJS.ProcessEnv): AppConfig;
package/dist/config.js ADDED
@@ -0,0 +1,20 @@
1
+ function firstEnv(env, ...keys) {
2
+ for (const key of keys) {
3
+ const value = (env[key] ?? "").trim();
4
+ if (value)
5
+ return value;
6
+ }
7
+ return "";
8
+ }
9
+ /**
10
+ * 读取 MCP 配置。
11
+ * 优先使用 FANGCUNTAI_*,兼容旧版 HOME_MAN_*。
12
+ */
13
+ export function loadConfig(env = process.env) {
14
+ const apiBase = firstEnv(env, "FANGCUNTAI_API", "HOME_MAN_API") || "http://127.0.0.1:9080";
15
+ const token = firstEnv(env, "FANGCUNTAI_TOKEN", "HOME_MAN_TOKEN");
16
+ if (!token) {
17
+ throw new Error("缺少 FANGCUNTAI_TOKEN:请在方寸台 App「设置 → 连接桌面助手」生成令牌,并配置到 MCP env(兼容旧变量 HOME_MAN_TOKEN)。");
18
+ }
19
+ return { apiBase: apiBase.replace(/\/$/, ""), token };
20
+ }
@@ -0,0 +1,55 @@
1
+ import type { FangcuntaiApiClient } from "../client/api-client.js";
2
+ export declare const TOKEN_SCOPE_READ_LEDGER = "read:ledger";
3
+ export declare const TOKEN_SCOPE_READ_STATS = "read:stats";
4
+ export declare const TOKEN_SCOPE_WRITE_DRAFT = "write:draft";
5
+ export declare const TOKEN_SCOPE_WRITE_LEDGER = "write:ledger";
6
+ export declare const TOKEN_SCOPE_DENIED = "\u5F53\u524D\u4EE4\u724C\u672A\u52FE\u9009\u6B64\u9879\u6743\u9650\u3002\u8BF7\u5728\u65B9\u5BF8\u53F0 App\u300C\u8FDE\u63A5\u684C\u9762\u52A9\u624B\u300D\u751F\u6210\u65B0\u4EE4\u724C\u5E76\u52FE\u9009\u5BF9\u5E94\u6743\u9650\uFF1B\u5DF2\u6709\u4EE4\u724C\u4E0D\u80FD\u6539\u6743\u9650\u3002";
7
+ export type AssistantContext = {
8
+ user_id: number;
9
+ family_id: number;
10
+ bound_family_id?: number;
11
+ can_switch_family?: boolean;
12
+ scopes?: string[] | string;
13
+ };
14
+ export type WorkspaceContext = {
15
+ bound_family_id: number;
16
+ active_family_id: number;
17
+ active_ledger_book_id: number | null;
18
+ using_default_ledger_book: boolean;
19
+ };
20
+ export declare function setBoundFamilyId(id: number): void;
21
+ /** @deprecated 使用 setBoundFamilyId */
22
+ export declare function setCachedFamilyId(id: number): void;
23
+ export declare function clearWorkspaceSelection(): void;
24
+ /** @deprecated 使用 clearWorkspaceSelection */
25
+ export declare function clearCachedFamilyId(): void;
26
+ export declare function familyPath(familyId: number, suffix: string): string;
27
+ /** 通过助手上下文接口解析令牌默认家庭。 */
28
+ export declare function discoverBoundFamilyId(client: FangcuntaiApiClient): Promise<number>;
29
+ /** 当前会话使用的家庭 ID(已选中或令牌默认)。 */
30
+ export declare function ensureFamilyId(client: FangcuntaiApiClient): Promise<number>;
31
+ export declare function getAssistantContext(client: FangcuntaiApiClient): Promise<AssistantContext>;
32
+ /** 当前工作区:活跃家庭 + 账本选择。 */
33
+ export declare function getWorkspaceContext(client: FangcuntaiApiClient): Promise<WorkspaceContext>;
34
+ /**
35
+ * 切换会话家庭。须为用户已加入的家庭;切换后清空账本选择(回到新家庭默认账本)。
36
+ */
37
+ export declare function selectFamily(client: FangcuntaiApiClient, familyId: number): Promise<WorkspaceContext>;
38
+ /**
39
+ * 选择账本。ledger_book_id=0 表示回到当前家庭默认账本。
40
+ * 会先校验账本存在于当前家庭列表中。
41
+ */
42
+ export declare function selectLedgerBook(client: FangcuntaiApiClient, ledgerBookId: number): Promise<WorkspaceContext>;
43
+ /** 供 API query 使用的 ledger_book_id(未选中时不传,后端用默认账本)。 */
44
+ export declare function ledgerBookQuery(override?: number): Record<string, number | undefined>;
45
+ export declare function currentLedgerBookId(override?: number): number;
46
+ export type FamilyEntitlements = Record<string, unknown> & {
47
+ can_use_ledger?: boolean;
48
+ can_view_notes?: boolean;
49
+ };
50
+ export declare function fetchEntitlements(client: FangcuntaiApiClient, familyId: number): Promise<FamilyEntitlements>;
51
+ /** 写操作前检查能力位;失败时抛出中文错误。 */
52
+ export declare function requireEntitlement(client: FangcuntaiApiClient, familyId: number, key: keyof FamilyEntitlements, denyMessage: string): Promise<void>;
53
+ export declare function parseAssistantScopes(raw: unknown): string[];
54
+ /** 令牌未勾选对应权限时拒绝;尚未拉到 scopes 时交给后端 40305。 */
55
+ export declare function requireTokenScope(client: FangcuntaiApiClient, anyOf: string[], denyMessage?: string): Promise<void>;
@@ -0,0 +1,183 @@
1
+ /** 令牌绑定的默认家庭(assistant-context.family_id) */
2
+ let boundFamilyId = null;
3
+ /** 当前会话选中的家庭;未选则用绑定默认家庭 */
4
+ let activeFamilyId = null;
5
+ /** 当前会话选中的账本;null/0 表示使用该家庭默认账本 */
6
+ let activeLedgerBookId = null;
7
+ /** 助手令牌勾选的公开 scope;null 表示尚未拉取 */
8
+ let cachedTokenScopes = null;
9
+ export const TOKEN_SCOPE_READ_LEDGER = "read:ledger";
10
+ export const TOKEN_SCOPE_READ_STATS = "read:stats";
11
+ export const TOKEN_SCOPE_WRITE_DRAFT = "write:draft";
12
+ export const TOKEN_SCOPE_WRITE_LEDGER = "write:ledger";
13
+ export const TOKEN_SCOPE_DENIED = "当前令牌未勾选此项权限。请在方寸台 App「连接桌面助手」生成新令牌并勾选对应权限;已有令牌不能改权限。";
14
+ export function setBoundFamilyId(id) {
15
+ if (id > 0)
16
+ boundFamilyId = id;
17
+ }
18
+ /** @deprecated 使用 setBoundFamilyId */
19
+ export function setCachedFamilyId(id) {
20
+ setBoundFamilyId(id);
21
+ }
22
+ export function clearWorkspaceSelection() {
23
+ boundFamilyId = null;
24
+ activeFamilyId = null;
25
+ activeLedgerBookId = null;
26
+ cachedTokenScopes = null;
27
+ }
28
+ /** @deprecated 使用 clearWorkspaceSelection */
29
+ export function clearCachedFamilyId() {
30
+ clearWorkspaceSelection();
31
+ }
32
+ export function familyPath(familyId, suffix) {
33
+ return `/api/families/${familyId}${suffix}`;
34
+ }
35
+ /** 通过助手上下文接口解析令牌默认家庭。 */
36
+ export async function discoverBoundFamilyId(client) {
37
+ if (boundFamilyId && boundFamilyId > 0) {
38
+ if (!activeFamilyId)
39
+ activeFamilyId = boundFamilyId;
40
+ return boundFamilyId;
41
+ }
42
+ const ctx = await client.get("/api/users/me/assistant-context");
43
+ cacheTokenScopes(ctx.scopes);
44
+ const familyId = Number(ctx.bound_family_id ?? ctx.family_id);
45
+ if (!familyId || familyId <= 0) {
46
+ throw new Error("无法解析绑定家庭,请确认助手令牌有效且已绑定家庭");
47
+ }
48
+ boundFamilyId = familyId;
49
+ if (!activeFamilyId)
50
+ activeFamilyId = familyId;
51
+ return familyId;
52
+ }
53
+ /** 当前会话使用的家庭 ID(已选中或令牌默认)。 */
54
+ export async function ensureFamilyId(client) {
55
+ if (activeFamilyId && activeFamilyId > 0)
56
+ return activeFamilyId;
57
+ const bound = await discoverBoundFamilyId(client);
58
+ activeFamilyId = bound;
59
+ return bound;
60
+ }
61
+ export async function getAssistantContext(client) {
62
+ const ctx = await client.get("/api/users/me/assistant-context");
63
+ cacheTokenScopes(ctx.scopes);
64
+ const familyId = Number(ctx.bound_family_id ?? ctx.family_id);
65
+ if (familyId) {
66
+ setBoundFamilyId(familyId);
67
+ if (!activeFamilyId)
68
+ activeFamilyId = familyId;
69
+ }
70
+ return ctx;
71
+ }
72
+ /** 当前工作区:活跃家庭 + 账本选择。 */
73
+ export async function getWorkspaceContext(client) {
74
+ const bound = await discoverBoundFamilyId(client);
75
+ const active = await ensureFamilyId(client);
76
+ const bookId = activeLedgerBookId && activeLedgerBookId > 0 ? activeLedgerBookId : null;
77
+ return {
78
+ bound_family_id: bound,
79
+ active_family_id: active,
80
+ active_ledger_book_id: bookId,
81
+ using_default_ledger_book: bookId === null,
82
+ };
83
+ }
84
+ /**
85
+ * 切换会话家庭。须为用户已加入的家庭;切换后清空账本选择(回到新家庭默认账本)。
86
+ */
87
+ export async function selectFamily(client, familyId) {
88
+ if (!familyId || familyId <= 0) {
89
+ throw new Error("family_id 无效");
90
+ }
91
+ await discoverBoundFamilyId(client);
92
+ // 成员校验:非成员会 403/404
93
+ await client.get(familyPath(familyId, ""));
94
+ activeFamilyId = familyId;
95
+ activeLedgerBookId = null;
96
+ return getWorkspaceContext(client);
97
+ }
98
+ /**
99
+ * 选择账本。ledger_book_id=0 表示回到当前家庭默认账本。
100
+ * 会先校验账本存在于当前家庭列表中。
101
+ */
102
+ export async function selectLedgerBook(client, ledgerBookId) {
103
+ const familyId = await ensureFamilyId(client);
104
+ if (!ledgerBookId || ledgerBookId <= 0) {
105
+ activeLedgerBookId = null;
106
+ return getWorkspaceContext(client);
107
+ }
108
+ const books = await client.get(familyPath(familyId, "/ledger-books"));
109
+ const items = normalizeListItems(books);
110
+ const found = items.some((b) => Number(b.id) === ledgerBookId);
111
+ if (!found) {
112
+ throw new Error(`账本 ${ledgerBookId} 不在当前家庭,请先 list_ledger_books`);
113
+ }
114
+ activeLedgerBookId = ledgerBookId;
115
+ return getWorkspaceContext(client);
116
+ }
117
+ /** 供 API query 使用的 ledger_book_id(未选中时不传,后端用默认账本)。 */
118
+ export function ledgerBookQuery(override) {
119
+ const id = override !== undefined && override > 0
120
+ ? override
121
+ : activeLedgerBookId && activeLedgerBookId > 0
122
+ ? activeLedgerBookId
123
+ : undefined;
124
+ return id ? { ledger_book_id: id } : {};
125
+ }
126
+ export function currentLedgerBookId(override) {
127
+ if (override !== undefined && override > 0)
128
+ return override;
129
+ return activeLedgerBookId && activeLedgerBookId > 0 ? activeLedgerBookId : 0;
130
+ }
131
+ function normalizeListItems(data) {
132
+ if (Array.isArray(data))
133
+ return data;
134
+ if (data && typeof data === "object" && Array.isArray(data.items)) {
135
+ return data.items;
136
+ }
137
+ return [];
138
+ }
139
+ export async function fetchEntitlements(client, familyId) {
140
+ return client.get(familyPath(familyId, "/entitlements"));
141
+ }
142
+ /** 写操作前检查能力位;失败时抛出中文错误。 */
143
+ export async function requireEntitlement(client, familyId, key, denyMessage) {
144
+ const ent = await fetchEntitlements(client, familyId);
145
+ if (ent[key] === false) {
146
+ throw new Error(denyMessage);
147
+ }
148
+ }
149
+ export function parseAssistantScopes(raw) {
150
+ if (Array.isArray(raw)) {
151
+ return raw.map((item) => String(item).trim()).filter((item) => item.length > 0);
152
+ }
153
+ if (typeof raw === "string") {
154
+ return raw
155
+ .split(",")
156
+ .map((item) => item.trim())
157
+ .filter((item) => item.length > 0);
158
+ }
159
+ return [];
160
+ }
161
+ function cacheTokenScopes(raw) {
162
+ cachedTokenScopes = parseAssistantScopes(raw);
163
+ }
164
+ async function ensureTokenScopes(client) {
165
+ if (cachedTokenScopes !== null)
166
+ return cachedTokenScopes;
167
+ try {
168
+ await getAssistantContext(client);
169
+ }
170
+ catch {
171
+ cachedTokenScopes = [];
172
+ }
173
+ return cachedTokenScopes ?? [];
174
+ }
175
+ /** 令牌未勾选对应权限时拒绝;尚未拉到 scopes 时交给后端 40305。 */
176
+ export async function requireTokenScope(client, anyOf, denyMessage = TOKEN_SCOPE_DENIED) {
177
+ const scopes = await ensureTokenScopes(client);
178
+ if (scopes.length === 0)
179
+ return;
180
+ if (anyOf.some((scope) => scopes.includes(scope)))
181
+ return;
182
+ throw new Error(denyMessage);
183
+ }
@@ -0,0 +1,31 @@
1
+ export type PendingKind = "create_ledger" | "delete_ledger" | "empty_ledger_trash" | "confirm_draft" | "batch_confirm_draft" | "delete_note" | "empty_notes_trash" | "delete_note_folder" | "move_note";
2
+ export type PendingWrite = {
3
+ kind: PendingKind;
4
+ token: string;
5
+ expiresAt: number;
6
+ familyId: number;
7
+ summary: Record<string, unknown>;
8
+ /** 执行确认时所需的上下文 */
9
+ exec: Record<string, unknown>;
10
+ };
11
+ export declare function clearWriteLockState(): void;
12
+ export declare function isWritesUnlocked(): boolean;
13
+ export declare function unlockWrites(ttlMs?: number): {
14
+ unlocked: true;
15
+ expires_in_seconds: number;
16
+ hint: string;
17
+ };
18
+ export declare function lockWrites(): {
19
+ unlocked: false;
20
+ hint: string;
21
+ };
22
+ export declare function getWriteLockStatus(): {
23
+ unlocked: boolean;
24
+ expires_in_seconds: number;
25
+ pending_count: number;
26
+ };
27
+ /** 写操作前门:未解锁则抛错。 */
28
+ export declare function requireWritesUnlocked(): void;
29
+ export declare function createPending(kind: PendingKind, familyId: number, summary: Record<string, unknown>, exec: Record<string, unknown>): PendingWrite;
30
+ export declare function takePending(token: string, expectedKind?: PendingKind): PendingWrite;
31
+ export declare function pendingPublicView(item: PendingWrite): Record<string, unknown>;