@goodpeanuts/dsh-sui 0.1.1 → 0.1.2-fix.1

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 CHANGED
@@ -45,6 +45,8 @@ npx --yes --package=@goodpeanuts/dsh-sui feidee sync recent --book '上一步返
45
45
 
46
46
  ### 会话草稿与待入账
47
47
 
48
+ 会话输入框上方的“账本授权”用于选择当前会话可访问的账本,即使还没有草稿也会显示。点击后选择账本并“确认授权”;可勾选设为默认,供尚未授权的会话自动使用。再次打开可切换当前会话账本或清除默认账本;清除默认不影响已经授权的会话。切换前须先处理当前草稿,防止旧草稿失去授权。没有可选账本时,先打开账本页面登录并同步。
49
+
48
50
  模型通过受限 finance 工具读取账本、维护当前会话的一份流水草稿。用户和 Agent 共同编辑同一份字段;缺项由必填字段和校验结果派生,未知信息通过宿主提问,不写入草稿问题状态。
49
51
 
50
52
  非空草稿在输入框上方显示单个图标,点击打开工作台,关闭后保留编辑。完整条目可加入“待入账”,原批次冻结为只读存档;部分加入时剩余条目继续使用原入口,整批加入后入口收起,后续记账另开批次。其他会话的 open 草稿不共享,已加入同一账本的待入账记录可读。
@@ -61,7 +61,7 @@ var FinanceDatabase = class {
61
61
  assertTimestamp(input.now, "now");
62
62
  return this.db.transaction(() => {
63
63
  const current = this.getActiveGrant(input.subjectId);
64
- if (input.expectedRevision !== void 0 && current?.revision !== input.expectedRevision) throw new Error("finance_grant_revision_conflict");
64
+ if (input.expectedRevision !== void 0 && (current?.revision ?? 0) !== input.expectedRevision) throw new Error("finance_grant_revision_conflict");
65
65
  if (current?.bookId === input.bookId) return current;
66
66
  const revision = (current?.revision ?? 0) + 1;
67
67
  if (current) this.db.prepare("UPDATE book_read_grants SET replaced_at=? WHERE id=? AND replaced_at IS NULL").run(input.now, current.id);
@@ -11184,6 +11184,243 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11184
11184
  };
11185
11185
  }));
11186
11186
  //#endregion
11187
+ //#region ../../packages/finance-ui/src/book-grant.css
11188
+ var init_book_grant$1 = __esmMin((() => {}));
11189
+ //#endregion
11190
+ //#region ../../packages/finance-ui/src/book-grant.tsx
11191
+ /** Available before the first draft exists: authorization must not depend on authorized work. */
11192
+ function BookGrantControl({ subjectId, client, onOpenLedger }) {
11193
+ const [opened, setOpened] = (0, react.useState)(false);
11194
+ const [bound, setBound] = (0, react.useState)(false);
11195
+ (0, react.useEffect)(() => {
11196
+ let active = true;
11197
+ const refresh = () => {
11198
+ client.getSubjectGrant(subjectId).then((grant) => {
11199
+ if (active) setBound(Boolean(grant));
11200
+ }).catch(() => {});
11201
+ };
11202
+ refresh();
11203
+ window.addEventListener("sui-ledger:finance-updated", refresh);
11204
+ return () => {
11205
+ active = false;
11206
+ window.removeEventListener("sui-ledger:finance-updated", refresh);
11207
+ };
11208
+ }, [client, subjectId]);
11209
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
11210
+ className: "sui-ledger-draft-ui book-grant-control",
11211
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
11212
+ type: "button",
11213
+ className: "book-grant-trigger",
11214
+ "aria-haspopup": "dialog",
11215
+ "aria-expanded": opened,
11216
+ title: bound ? "查看或切换会话账本" : "选择当前会话可访问的账本",
11217
+ onClick: () => setOpened(true),
11218
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Icon, { name: "book" }), "账本授权"]
11219
+ }), opened && (0, react_dom.createPortal)(/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
11220
+ className: "sui-ledger-draft-ui",
11221
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BookGrantDialog, {
11222
+ subjectId,
11223
+ client,
11224
+ onClose: () => setOpened(false),
11225
+ onOpenLedger
11226
+ })
11227
+ }), document.body)]
11228
+ });
11229
+ }
11230
+ function BookGrantDialog({ subjectId, client, onClose, onOpenLedger }) {
11231
+ const dialog = (0, react.useRef)(null);
11232
+ const alive = (0, react.useRef)(true);
11233
+ const running = (0, react.useRef)(false);
11234
+ const [data, setData] = (0, react.useState)(null);
11235
+ const [selected, setSelected] = (0, react.useState)("");
11236
+ const [makeDefault, setMakeDefault] = (0, react.useState)(false);
11237
+ const [busy, setBusy] = (0, react.useState)(false);
11238
+ const [error, setError] = (0, react.useState)("");
11239
+ const load = (0, react.useCallback)(async () => {
11240
+ if (running.current) return;
11241
+ running.current = true;
11242
+ setBusy(true);
11243
+ setError("");
11244
+ setData(null);
11245
+ setMakeDefault(false);
11246
+ try {
11247
+ if (!client.requestBookGrantSelection) throw new Error("请更新插件后重试。");
11248
+ const next = await client.requestBookGrantSelection(subjectId);
11249
+ if (!alive.current) return;
11250
+ setData(next);
11251
+ const preferred = next.grant?.bookId ?? next.defaultBookId;
11252
+ setSelected(next.books.find((book) => book.id === preferred)?.id ?? next.books[0]?.id ?? "");
11253
+ } catch {
11254
+ if (alive.current) setError("无法读取账本授权,请重试。");
11255
+ } finally {
11256
+ running.current = false;
11257
+ if (alive.current) setBusy(false);
11258
+ }
11259
+ }, [client, subjectId]);
11260
+ (0, react.useEffect)(() => {
11261
+ alive.current = true;
11262
+ const element = dialog.current;
11263
+ element.showModal();
11264
+ load();
11265
+ return () => {
11266
+ alive.current = false;
11267
+ element.close();
11268
+ };
11269
+ }, [load]);
11270
+ const finish = async (decision) => {
11271
+ if (running.current) return;
11272
+ if (!data || !client.respondBookGrantSelection) {
11273
+ onClose();
11274
+ return;
11275
+ }
11276
+ running.current = true;
11277
+ setBusy(true);
11278
+ setError("");
11279
+ try {
11280
+ await client.respondBookGrantSelection(subjectId, data.request.id, {
11281
+ decision,
11282
+ ...decision === "confirm" ? {
11283
+ bookId: selected,
11284
+ makeDefault
11285
+ } : {}
11286
+ });
11287
+ window.dispatchEvent(new Event("sui-ledger:finance-updated"));
11288
+ if (alive.current) onClose();
11289
+ } catch (cause) {
11290
+ if (!alive.current) return;
11291
+ if (decision === "cancel") onClose();
11292
+ else if (cause instanceof Error && cause.message === "finance_draft_book_change_blocked") setError("当前会话仍有流水草稿,请先将其加入待入账或移除全部条目,再切换账本。");
11293
+ else setError("授权未完成,账本可能已在其他页面更改。请重新读取后确认。");
11294
+ } finally {
11295
+ running.current = false;
11296
+ if (alive.current) setBusy(false);
11297
+ }
11298
+ };
11299
+ const clearDefault = async () => {
11300
+ if (running.current || !client.setDefaultBook) return;
11301
+ running.current = true;
11302
+ setBusy(true);
11303
+ setError("");
11304
+ try {
11305
+ await client.setDefaultBook(null);
11306
+ if (alive.current) {
11307
+ setData((current) => current && {
11308
+ ...current,
11309
+ defaultBookId: null
11310
+ });
11311
+ setMakeDefault(false);
11312
+ }
11313
+ } catch {
11314
+ if (alive.current) setError("清除默认账本失败,请重试。");
11315
+ } finally {
11316
+ running.current = false;
11317
+ if (alive.current) setBusy(false);
11318
+ }
11319
+ };
11320
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("dialog", {
11321
+ ref: dialog,
11322
+ className: "book-grant-dialog",
11323
+ "aria-labelledby": "book-grant-title",
11324
+ onCancel: (event) => {
11325
+ event.preventDefault();
11326
+ finish("cancel");
11327
+ },
11328
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("form", {
11329
+ onSubmit: (event) => {
11330
+ event.preventDefault();
11331
+ if (selected && !busy) finish("confirm");
11332
+ },
11333
+ children: [
11334
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("header", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h2", {
11335
+ id: "book-grant-title",
11336
+ children: "选择会话账本"
11337
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
11338
+ type: "button",
11339
+ tone: "ghost",
11340
+ disabled: busy,
11341
+ "aria-label": "关闭账本授权",
11342
+ onClick: () => void finish("cancel"),
11343
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Icon, { name: "close" })
11344
+ })] }),
11345
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: "授权后,当前会话可读取所选账本并维护草稿;实际入账仍需单独人工确认。" }),
11346
+ data && data.books.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
11347
+ className: "workset-field",
11348
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "授权账本" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("select", {
11349
+ value: selected,
11350
+ disabled: busy,
11351
+ onChange: (event) => setSelected(event.currentTarget.value),
11352
+ children: data.books.map((book) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
11353
+ value: book.id,
11354
+ children: book.name || book.id
11355
+ }, book.id))
11356
+ })]
11357
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
11358
+ className: "book-grant-default",
11359
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
11360
+ type: "checkbox",
11361
+ checked: makeDefault,
11362
+ disabled: busy,
11363
+ onChange: (event) => setMakeDefault(event.currentTarget.checked)
11364
+ }), "设为默认账本,供尚未授权的会话自动使用"]
11365
+ })] }),
11366
+ data && data.books.length === 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
11367
+ role: "status",
11368
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: "尚无可用账本,请先在账本页面登录并同步。" }), onOpenLedger && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
11369
+ type: "button",
11370
+ disabled: busy,
11371
+ onClick: () => {
11372
+ finish("cancel").then(onOpenLedger);
11373
+ },
11374
+ children: "打开账本"
11375
+ })]
11376
+ }),
11377
+ data?.defaultBookId && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
11378
+ className: "book-grant-current-default",
11379
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: ["默认账本:", data.books.find((book) => book.id === data.defaultBookId)?.name ?? data.defaultBookId] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
11380
+ type: "button",
11381
+ tone: "ghost",
11382
+ disabled: busy,
11383
+ onClick: () => void clearDefault(),
11384
+ children: "清除默认账本"
11385
+ })]
11386
+ }),
11387
+ error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
11388
+ role: "alert",
11389
+ children: error
11390
+ }),
11391
+ busy && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
11392
+ role: "status",
11393
+ children: "正在处理…"
11394
+ }),
11395
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("footer", { children: [
11396
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
11397
+ type: "button",
11398
+ disabled: busy,
11399
+ onClick: () => void finish("cancel"),
11400
+ children: "取消"
11401
+ }),
11402
+ error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
11403
+ type: "button",
11404
+ disabled: busy,
11405
+ onClick: () => void load(),
11406
+ children: "重新读取"
11407
+ }),
11408
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
11409
+ type: "submit",
11410
+ tone: "primary",
11411
+ disabled: busy || !data?.books.length || !selected,
11412
+ children: "确认授权"
11413
+ })
11414
+ ] })
11415
+ ]
11416
+ })
11417
+ });
11418
+ }
11419
+ var init_book_grant = __esmMin((() => {
11420
+ init_src$2();
11421
+ init_book_grant$1();
11422
+ }));
11423
+ //#endregion
11187
11424
  //#region ../../packages/finance-ui/src/ledger-route-page.tsx
11188
11425
  var ledger_route_page_exports = /* @__PURE__ */ __exportAll({ createFinanceLedgerRoutePage: () => createFinanceLedgerRoutePage });
11189
11426
  function createFinanceLedgerRoutePage(financeClient, fetchImpl) {
@@ -11229,6 +11466,15 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11229
11466
  };
11230
11467
  const readStatus = (path) => request(path, { signal: AbortSignal.timeout(1e4) });
11231
11468
  return {
11469
+ async requestBookGrantSelection(subjectId) {
11470
+ return request(`/finance/subjects/${encodeURIComponent(subjectId)}/grant/selection`, jsonRequest("POST", {}));
11471
+ },
11472
+ async respondBookGrantSelection(subjectId, requestId, response) {
11473
+ return request(`/finance/subjects/${encodeURIComponent(subjectId)}/grant/selection/${encodeURIComponent(requestId)}`, jsonRequest("POST", response));
11474
+ },
11475
+ async setDefaultBook(bookId) {
11476
+ return (await request("/finance/default-book", jsonRequest("PUT", { bookId }))).bookId;
11477
+ },
11232
11478
  async getPreparation(worksetId) {
11233
11479
  return (await readStatus(`/finance/worksets/${encodeURIComponent(worksetId)}/preparation`)).operation;
11234
11480
  },
@@ -14397,6 +14643,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
14397
14643
  init_transaction_time();
14398
14644
  init_memo_policy();
14399
14645
  init_draft_card();
14646
+ init_book_grant();
14400
14647
  init_ledger_route();
14401
14648
  }));
14402
14649
  //#endregion
@@ -23204,7 +23451,11 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
23204
23451
  init_src$2();
23205
23452
  /** DSH's session-scoped input dock stays mounted even while the icon is absent. */
23206
23453
  function DraftComposerDock(props) {
23207
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionDraftDock, { ...props }, props.sessionId);
23454
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(BookGrantControl, {
23455
+ subjectId: `dsh-session-${props.sessionId}`,
23456
+ client: props.financeClient,
23457
+ onOpenLedger: props.onOpenLedger
23458
+ }, `grant-${props.sessionId}`), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionDraftDock, { ...props }, props.sessionId)] });
23208
23459
  }
23209
23460
  function SessionDraftDock(props) {
23210
23461
  const timeline = props.useChat((snapshot) => snapshot.timeline);
@@ -23721,7 +23972,10 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
23721
23972
  id: "sui-ledger-draft",
23722
23973
  order: 15,
23723
23974
  locale: NS,
23724
- inject: () => ({ financeClient })
23975
+ inject: () => ({
23976
+ financeClient,
23977
+ onOpenLedger: () => ctx.layout.selectPanel(PANEL_ID)
23978
+ })
23725
23979
  }, DraftComposerDock));
23726
23980
  for (const { key, component } of TOOLVIEWS) ctx.slots.inject("tool.call.toolview", () => ctx.slots.register({
23727
23981
  name: "tool.call.toolview",
@@ -25,7 +25,7 @@ function registerFinanceStateContext(prompt, read) {
25
25
  }
26
26
  }
27
27
  function buildFinanceStateContext(snapshot) {
28
- if (snapshot.status === "unbound") return "【当前账务状态】\n当前会话尚无账本授权;未读取任何默认账本统计。用 finance_books_list 查看默认账本和授权,沿用现有账本授权流程。";
28
+ if (snapshot.status === "unbound") return "【当前账务状态】\n当前会话尚无账本授权;未读取任何默认账本统计。用 finance_books_list 查看默认账本和授权;没有默认账本时,请用户点击会话输入框上方的“账本授权”选择并确认。若没有可选账本,先打开账本页面登录并同步。";
29
29
  return [
30
30
  "【当前账务状态】",
31
31
  "以下是本次模型上下文组装时的轻量状态,覆盖之前的状态快照,不是已读取或已核对的凭据。fingerprint 仅为状态指纹,不能作为读取工具的分页版本;续读须使用各工具实际返回的 dataVersion。",
@@ -135,7 +135,7 @@ async function apply(ctx, config) {
135
135
  path: "/api/sui-ledger",
136
136
  handler: async (req, res) => {
137
137
  const url = new URL(req.url ?? "/", "http://localhost"), path = url.pathname.slice(15);
138
- if (path === "/maintenance" || path.startsWith("/maintenance/") || path === "/finance/services" || path.startsWith("/finance/services/") || path === "/finance/session" || path.startsWith("/finance/session/")) {
138
+ if (path === "/maintenance" || path.startsWith("/maintenance/") || path === "/finance/services" || path.startsWith("/finance/services/") || path === "/finance/session" || path.startsWith("/finance/session/") || path === "/finance/default-book" || /^\/finance\/subjects\/[^/]+\/grant(?:\/|$)/.test(path)) {
139
139
  const rejection = web.connection.requestRejection(req);
140
140
  if (rejection !== void 0) {
141
141
  res.statusCode = rejection;
@@ -90,7 +90,7 @@ function createFinanceTools(service, ledger, options = {}) {
90
90
  throw new FinancePublicError(JSON.stringify({
91
91
  code,
92
92
  activeGrant: books.activeGrant,
93
- message: code === "finance_grant_book_mismatch" ? "Use the active grant's bookId if the requested ID was mistyped. Selecting another book requires trusted user action." : "No active book grant. Request finance.book_grant.selection and wait for the trusted response."
93
+ message: code === "finance_grant_book_mismatch" ? "Use the active grant's bookId if the requested ID was mistyped. Selecting another book requires trusted user action." : "No active book grant. Ask the user to click 账本授权 (Book access) above the conversation input and confirm a book; if the list is empty, open the Ledger panel to log in and sync first."
94
94
  }));
95
95
  }
96
96
  if (code) throw new FinancePublicError(JSON.stringify({
@@ -61,7 +61,7 @@ var FinanceDatabase = class {
61
61
  assertTimestamp(input.now, "now");
62
62
  return this.db.transaction(() => {
63
63
  const current = this.getActiveGrant(input.subjectId);
64
- if (input.expectedRevision !== void 0 && current?.revision !== input.expectedRevision) throw new Error("finance_grant_revision_conflict");
64
+ if (input.expectedRevision !== void 0 && (current?.revision ?? 0) !== input.expectedRevision) throw new Error("finance_grant_revision_conflict");
65
65
  if (current?.bookId === input.bookId) return current;
66
66
  const revision = (current?.revision ?? 0) + 1;
67
67
  if (current) this.db.prepare("UPDATE book_read_grants SET replaced_at=? WHERE id=? AND replaced_at IS NULL").run(input.now, current.id);
@@ -18,6 +18,10 @@ function createFinanceInteractionTypes(service) {
18
18
  suggestedBookId: {
19
19
  type: "string",
20
20
  minLength: 1
21
+ },
22
+ expectedRevision: {
23
+ type: "integer",
24
+ minimum: 0
21
25
  }
22
26
  },
23
27
  additionalProperties: false
@@ -39,7 +43,7 @@ function createFinanceInteractionTypes(service) {
39
43
  },
40
44
  additionalProperties: false
41
45
  },
42
- handleResponse(ctx, _payload, response) {
46
+ handleResponse(ctx, payload, response) {
43
47
  if (ctx.request.context.scope.type !== "subject") return {
44
48
  ok: false,
45
49
  error: "Book selection requires a Conversation"
@@ -53,10 +57,11 @@ function createFinanceInteractionTypes(service) {
53
57
  ok: false,
54
58
  error: "A book must be selected"
55
59
  };
56
- const grant = service.bindSubjectGrant({
57
- subjectId: ctx.request.context.scope.subjectId,
60
+ const subjectId = ctx.request.context.scope.subjectId;
61
+ const grant = service.selectSubjectBook({
62
+ subjectId,
58
63
  bookId: response.bookId,
59
- ...response.expectedRevision !== void 0 ? { expectedRevision: response.expectedRevision } : {}
64
+ ...(payload.expectedRevision ?? response.expectedRevision) !== void 0 ? { expectedRevision: payload.expectedRevision ?? response.expectedRevision } : {}
60
65
  });
61
66
  if (response.makeDefault) service.setDefaultBook(grant.bookId);
62
67
  return {
@@ -175,15 +175,67 @@ function createFinanceTrustedControlRoute(finance, interaction, preferences) {
175
175
  return recoveryResponse(() => recovery[2] === "resume" ? finance.resumeCommit(recovery[1], hash, recoveryHash) : finance.endCommit(recovery[1], hash), "checking", recovery[2] === "resume" ? 202 : 200);
176
176
  }
177
177
  if (request.pathname === "/v1/finance/default-book" && request.method === "PUT") {
178
- const bookId = requiredIdentifier((await request.body()).bookId, "bookId");
178
+ const body = await request.body();
179
+ if (Object.keys(body).some((key) => key !== "bookId")) badRequest("Invalid default book request");
180
+ const bookId = body.bookId === null ? null : requiredIdentifier(body.bookId, "bookId");
179
181
  return json(200, { bookId: (await financeCall(() => finance.setDefaultBook(bookId))).bookId });
180
182
  }
183
+ const selection = request.pathname.match(/^\/v1\/finance\/subjects\/([A-Za-z0-9._-]+)\/grant\/selection(?:\/([A-Za-z0-9._-]+))?$/);
184
+ if (request.method === "POST" && selection) {
185
+ const subjectId = selection[1], requestId = selection[2];
186
+ const body = await request.body();
187
+ if (!requestId) {
188
+ if (Object.keys(body).length) badRequest("Book selection accepts an empty object");
189
+ const { books, defaultBookId } = finance.describeBooks({ subjectId });
190
+ const grant = finance.getGrant(subjectId) ?? null;
191
+ const revision = grant?.revision ?? 0;
192
+ const suggestedBookId = grant?.bookId ?? defaultBookId;
193
+ return json(200, {
194
+ request: publicInteraction(interaction.attention().flatMap((item) => item.kind === "interaction" ? [item.value] : []).find((item) => item.type === FinanceInteractionTypes.bookGrantSelection && item.context.scope.type === "subject" && item.context.scope.subjectId === subjectId && record(item.payload)?.expectedRevision === revision) ?? interaction.request({
195
+ type: FinanceInteractionTypes.bookGrantSelection,
196
+ context: {
197
+ scope: {
198
+ type: "subject",
199
+ subjectId
200
+ },
201
+ origin: { module: "finance" }
202
+ },
203
+ title: "选择会话账本",
204
+ summary: "确认当前会话可读取和编辑草稿的账本。",
205
+ payload: {
206
+ reason: "用户选择会话账本",
207
+ expectedRevision: revision,
208
+ ...suggestedBookId ? { suggestedBookId } : {}
209
+ }
210
+ })),
211
+ books,
212
+ grant,
213
+ defaultBookId
214
+ });
215
+ }
216
+ if (Object.keys(body).some((key) => ![
217
+ "decision",
218
+ "bookId",
219
+ "makeDefault"
220
+ ].includes(key))) badRequest("Invalid book selection response");
221
+ if (body.decision !== "confirm" && body.decision !== "cancel") badRequest("decision must be confirm or cancel");
222
+ if (body.decision === "confirm") requiredIdentifier(body.bookId, "bookId");
223
+ if (body.makeDefault !== void 0 && typeof body.makeDefault !== "boolean") badRequest("makeDefault must be a boolean");
224
+ if (!interaction.attention().flatMap((item) => item.kind === "interaction" ? [item.value] : []).find((item) => item.id === requestId && item.type === FinanceInteractionTypes.bookGrantSelection && item.context.scope.type === "subject" && item.context.scope.subjectId === subjectId)) throw new FinanceRouteError(409, "Book selection is no longer current; reopen Book access");
225
+ const result = await financeCall(() => interaction.respond(requestId, body));
226
+ return json(result.accepted ? 200 : 409, {
227
+ accepted: result.accepted,
228
+ ...result.error ? { error: result.error } : {},
229
+ grant: finance.getGrant(subjectId) ?? null,
230
+ defaultBookId: finance.getDefaultBook()
231
+ });
232
+ }
181
233
  const grant = request.pathname.match(/^\/v1\/finance\/subjects\/([A-Za-z0-9._-]+)\/grant$/);
182
234
  if (request.method === "PUT" && grant) {
183
235
  const body = await request.body();
184
236
  const bookId = requiredIdentifier(body.bookId, "bookId");
185
237
  const expectedRevision = body.expectedRevision === void 0 ? void 0 : requiredInteger(body.expectedRevision, "expectedRevision");
186
- return json(200, { grant: await financeCall(() => finance.bindSubjectGrant({
238
+ return json(200, { grant: await financeCall(() => finance.selectSubjectBook({
187
239
  subjectId: grant[1],
188
240
  bookId,
189
241
  ...expectedRevision !== void 0 ? { expectedRevision } : {}
@@ -386,6 +438,8 @@ async function financeCall(operation) {
386
438
  if (message === "checkpoint_not_found") throw new FinanceRouteError(404, "finance_checkpoint_not_found");
387
439
  if (message.includes("finance_workset_version_conflict") || message.includes("finance_workset_review_version_conflict") || message.includes("finance_entry_version_conflict") || message.includes("finance_draft_open_row_exists") || message.includes("finance_draft_book_mismatch") || message.includes("finance_draft_row_frozen") || message.includes("finance_grant_revision_conflict") || message.includes("finance_ledger_revision_conflict")) throw new FinanceRouteError(409, "Finance resource version changed; reload before continuing");
388
440
  if (message.includes("finance_workset_confirmation_pending")) throw new FinanceRouteError(409, "finance_workset_confirmation_pending");
441
+ if (message === "finance_draft_book_change_blocked") throw new FinanceRouteError(409, message);
442
+ if (message === "finance_book_not_found") throw new FinanceRouteError(404, message);
389
443
  if ([
390
444
  "finance_commit_operations_changed",
391
445
  "finance_commit_not_resumable",
@@ -20,7 +20,7 @@ import { createHash, randomUUID } from "node:crypto";
20
20
  //#region ../../packages/finance-module/src/service.ts
21
21
  const DEFAULT_BOOK_SETTING_KEY = "default_book_id";
22
22
  const FINANCE_REMOTE_WRITES_DISABLED_ERROR = "finance_remote_writes_disabled";
23
- const FINANCE_GRANT_MISSING_HINT = "finance_grant_missing: no active BookReadGrant for this subject. Call finance_books_list to inspect the books and the active grant, then create the finance.book_grant.selection interaction so the user can bind a book; do not retry other book tools.";
23
+ const FINANCE_GRANT_MISSING_HINT = "finance_grant_missing: no active BookReadGrant for this subject. Ask the user to click 账本授权 (Book access) above the conversation input and confirm a book. If no books are listed, open the Ledger panel to log in and sync first. Do not retry other book tools before authorization.";
24
24
  function knownBook(ledger, bookId) {
25
25
  const books = ledger.cachedBooks();
26
26
  return Array.isArray(books) && books.some((book) => book?.id === bookId);
@@ -89,6 +89,18 @@ var FinanceApplicationService = class {
89
89
  getGrant(subjectId) {
90
90
  return this.options.store.getActiveGrant(subjectId);
91
91
  }
92
+ /** User selection must not strand a note bound to the previous grant. */
93
+ selectSubjectBook(input) {
94
+ if (!knownBook(this.options.ledger, input.bookId)) throw new Error("finance_book_not_found");
95
+ return this.options.store.transaction(() => {
96
+ const current = this.getGrant(input.subjectId);
97
+ const draft = this.options.store.getOpenDraftRow(input.subjectId);
98
+ if (draft?.entries.length && (current?.bookId !== input.bookId || draft.grantId !== current.id)) throw new Error("finance_draft_book_change_blocked");
99
+ const grant = this.bindSubjectGrant(input);
100
+ if (draft && !draft.entries.length && draft.grantId !== grant.id) this.options.store.deleteDraftRow(draft.id);
101
+ return grant;
102
+ });
103
+ }
92
104
  /** Prompt assembly is a pure read: it must not auto-bind the default book. */
93
105
  getModelFinanceContext(subjectId) {
94
106
  const grant = this.options.store.getActiveGrant(subjectId);
@@ -130,7 +142,7 @@ var FinanceApplicationService = class {
130
142
  return typeof value === "string" && value.trim() ? value : null;
131
143
  }
132
144
  setDefaultBook(bookId) {
133
- if (!knownBook(this.options.ledger, bookId)) throw new Error("finance_book_not_found");
145
+ if (bookId !== null && !knownBook(this.options.ledger, bookId)) throw new Error("finance_book_not_found");
134
146
  this.options.store.setSetting(DEFAULT_BOOK_SETTING_KEY, bookId, this.now());
135
147
  return { bookId };
136
148
  }
@@ -1816,7 +1828,7 @@ var FinanceApplicationService = class {
1816
1828
  requireGrant(subjectId, bookId, grantId) {
1817
1829
  const grant = this.ensureDefaultBookGrant(subjectId);
1818
1830
  if (!grant) throw new Error(FINANCE_GRANT_MISSING_HINT);
1819
- if (grant.bookId !== bookId || grantId && grant.id !== grantId) throw new Error(`finance_grant_book_mismatch: the active BookReadGrant covers book ${grant.bookId}, not ${bookId}. Rebind the book via the finance.book_grant.selection interaction instead of retrying other book tools.`);
1831
+ if (grant.bookId !== bookId || grantId && grant.id !== grantId) throw new Error(`finance_grant_book_mismatch: the active BookReadGrant covers book ${grant.bookId}, not ${bookId}. Ask the user to click 账本授权 (Book access) above the conversation input to select another book instead of retrying other book tools.`);
1820
1832
  return grant;
1821
1833
  }
1822
1834
  draftMutationOnce(context, operation, input, mutate) {
@@ -1,3 +1,116 @@
1
+ .book-grant-control {
2
+ box-sizing: border-box;
3
+ width: calc(100% - 2 * var(--finance-composer-side-clearance, 16px));
4
+ max-width: var(--finance-composer-card-max-width, 712px);
5
+ margin-inline: auto;
6
+ padding: 0 0 6px;
7
+ }
8
+
9
+ .book-grant-trigger {
10
+ border: 1px solid var(--line);
11
+ background: var(--surface);
12
+ color: var(--ink);
13
+ cursor: pointer;
14
+ font: inherit;
15
+ border-radius: 8px;
16
+ align-items: center;
17
+ gap: 6px;
18
+ padding: 5px 10px;
19
+ font-size: 12px;
20
+ display: inline-flex;
21
+ }
22
+
23
+ .book-grant-trigger svg {
24
+ width: 16px;
25
+ height: 16px;
26
+ }
27
+
28
+ .book-grant-trigger:hover {
29
+ background: var(--surface-soft);
30
+ }
31
+
32
+ .book-grant-trigger:focus-visible {
33
+ outline: 2px solid var(--blue);
34
+ outline-offset: 2px;
35
+ }
36
+
37
+ .book-grant-dialog {
38
+ box-sizing: border-box;
39
+ border: 1px solid var(--line);
40
+ width: min(480px, 100vw - 32px);
41
+ max-height: calc(100dvh - 32px);
42
+ color: var(--ink);
43
+ background: var(--surface);
44
+ border-radius: 14px;
45
+ padding: 24px;
46
+ overflow: auto;
47
+ }
48
+
49
+ .book-grant-dialog::backdrop {
50
+ background: #00000059;
51
+ }
52
+
53
+ .book-grant-dialog form {
54
+ gap: 16px;
55
+ display: grid;
56
+ }
57
+
58
+ .book-grant-dialog header, .book-grant-dialog footer, .book-grant-current-default {
59
+ justify-content: space-between;
60
+ align-items: center;
61
+ gap: 12px;
62
+ display: flex;
63
+ }
64
+
65
+ .book-grant-dialog h2 {
66
+ margin: 0;
67
+ font-size: 18px;
68
+ }
69
+
70
+ .book-grant-dialog p {
71
+ margin: 0;
72
+ font-size: 13px;
73
+ line-height: 1.6;
74
+ }
75
+
76
+ .book-grant-dialog select {
77
+ box-sizing: border-box;
78
+ border: 1px solid var(--line);
79
+ background: var(--surface);
80
+ width: 100%;
81
+ min-width: 0;
82
+ min-height: 36px;
83
+ color: var(--ink);
84
+ font: inherit;
85
+ border-radius: 8px;
86
+ padding: 6px 10px;
87
+ }
88
+
89
+ .book-grant-default {
90
+ align-items: flex-start;
91
+ gap: 8px;
92
+ font-size: 13px;
93
+ line-height: 1.5;
94
+ display: flex;
95
+ }
96
+
97
+ .book-grant-default input {
98
+ flex: none;
99
+ }
100
+
101
+ .book-grant-current-default {
102
+ flex-wrap: wrap;
103
+ font-size: 13px;
104
+ }
105
+
106
+ .book-grant-dialog [role="alert"] {
107
+ color: var(--danger);
108
+ }
109
+
110
+ .book-grant-dialog footer {
111
+ flex-wrap: wrap;
112
+ justify-content: flex-end;
113
+ }
1
114
  .backup-recovery-page .page-head h1 {
2
115
  margin: 0 0 26px;
3
116
  font-size: 24px;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodpeanuts/dsh-sui",
3
- "version": "0.1.1",
3
+ "version": "0.1.2-fix.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Ledger (随手记/feidee) plugin for DeepSeek Harness — finance tools and ledger UI",