dsh-plugin-zotero 0.9.2 → 0.9.5

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.
@@ -0,0 +1,46 @@
1
+ /**
2
+ * 破坏性写操作的对话框审批(Host 半)。
3
+ *
4
+ * 为什么不用插件面板自己弹确认框:删除是**模型发起的工具调用**,用户唯一在意的
5
+ * 地方是对话流本身。宿主 `@deepseek-ai/dsh-user-approval` 已提供 `ctx.approval`
6
+ * 服务,执行前暂停、在对话框输入区上方弹卡片(允许一次 / 拒绝 / 始终允许),
7
+ * 拒绝就不执行;无需本插件造 UI,也不用注入新的 client 组件。
8
+ *
9
+ * 这里的接口都是最小结构面:审批服务由宿主装配,不在本包的类型面内。
10
+ * 设计上 **fail closed** —— 拿不到审批服务 / 没有 agent / 任何非 allowed-once
11
+ * 的结果一律中止写操作,绝不「审批失败就照删」。
12
+ */
13
+ import type { Context } from '@deepseek-ai/cordis';
14
+ /** 宿主 ApprovalRequest 里本插件用得到的字段。 */
15
+ export interface ApprovalRequestLike {
16
+ agent: unknown;
17
+ toolName: string;
18
+ callId?: unknown;
19
+ reason?: string;
20
+ displayReason?: Record<string, string>;
21
+ signal?: AbortSignal;
22
+ }
23
+ /** 宿主审批服务的最小结构面。 */
24
+ export interface ApprovalServiceLike {
25
+ request(req: ApprovalRequestLike): Promise<unknown>;
26
+ }
27
+ /** 工具执行上下文(宿主 ToolRunContext)里本插件用得到的字段。 */
28
+ export interface ApprovalExec {
29
+ /** 发起调用的 agent;审批服务靠它定位会话与 turn。 */
30
+ agent?: unknown;
31
+ /** 关联已流式呈现的工具调用,审批卡片据此显示参数详情。 */
32
+ callId?: unknown;
33
+ signal?: AbortSignal;
34
+ }
35
+ /** 本地化确认文案。宿主的 displayReason 要求 en 键必填。 */
36
+ export interface ApprovalText {
37
+ en: string;
38
+ zh: string;
39
+ }
40
+ /**
41
+ * 请求一次对话框审批;只有拿到 `allowed-once` 才返回,否则抛错让工具调用失败。
42
+ *
43
+ * `reason` 写进审计日志(纯文本),`displayReason` 给审批卡片做本地化展示。
44
+ * `signal` 透传工具调用的取消信号:用户中途取消这次工具调用,审批一并作废。
45
+ */
46
+ export declare function requireApproval(ctx: Context, exec: ApprovalExec, toolName: string, text: ApprovalText): Promise<void>;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 破坏性写操作的对话框审批(Host 半)。
3
+ *
4
+ * 为什么不用插件面板自己弹确认框:删除是**模型发起的工具调用**,用户唯一在意的
5
+ * 地方是对话流本身。宿主 `@deepseek-ai/dsh-user-approval` 已提供 `ctx.approval`
6
+ * 服务,执行前暂停、在对话框输入区上方弹卡片(允许一次 / 拒绝 / 始终允许),
7
+ * 拒绝就不执行;无需本插件造 UI,也不用注入新的 client 组件。
8
+ *
9
+ * 这里的接口都是最小结构面:审批服务由宿主装配,不在本包的类型面内。
10
+ * 设计上 **fail closed** —— 拿不到审批服务 / 没有 agent / 任何非 allowed-once
11
+ * 的结果一律中止写操作,绝不「审批失败就照删」。
12
+ */
13
+ /** 宿主四种 outcome 里,只有这一种放行。 */
14
+ const ALLOWED = 'allowed-once';
15
+ function refusalText(outcome) {
16
+ switch (outcome) {
17
+ case 'rejected': return '用户拒绝了本次操作,未改动 Zotero。';
18
+ case 'cancelled': return '审批已取消,未改动 Zotero。';
19
+ case 'unavailable': return '当前没有可用的审批应答器,为安全起见未执行操作,Zotero 未被改动。';
20
+ default: return `审批未通过(${String(outcome)}),未改动 Zotero。`;
21
+ }
22
+ }
23
+ /**
24
+ * 请求一次对话框审批;只有拿到 `allowed-once` 才返回,否则抛错让工具调用失败。
25
+ *
26
+ * `reason` 写进审计日志(纯文本),`displayReason` 给审批卡片做本地化展示。
27
+ * `signal` 透传工具调用的取消信号:用户中途取消这次工具调用,审批一并作废。
28
+ */
29
+ export async function requireApproval(ctx, exec, toolName, text) {
30
+ const approval = ctx.approval;
31
+ if (approval === undefined) {
32
+ throw new Error('宿主未提供审批服务,无法安全地执行此操作,已中止(Zotero 未被改动)。');
33
+ }
34
+ if (exec.agent === undefined) {
35
+ throw new Error('这次工具调用没有携带 agent,无法请求审批,已中止(Zotero 未被改动)。');
36
+ }
37
+ const req = {
38
+ agent: exec.agent,
39
+ toolName,
40
+ reason: text.zh,
41
+ displayReason: { en: text.en, zh: text.zh },
42
+ };
43
+ if (exec.callId !== undefined)
44
+ req.callId = exec.callId;
45
+ if (exec.signal !== undefined)
46
+ req.signal = exec.signal;
47
+ let outcome;
48
+ try {
49
+ outcome = await approval.request(req);
50
+ }
51
+ catch (error) {
52
+ throw new Error(`审批请求失败,已中止:${error instanceof Error ? error.message : String(error)}`);
53
+ }
54
+ if (outcome !== ALLOWED)
55
+ throw new Error(refusalText(outcome));
56
+ }
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import { callMcpTool, listMcpTools } from '../zotero/client.js';
13
13
  import { getSettings } from '../zotero/config.js';
14
+ import { requireApproval } from './approval.js';
14
15
  /** 服务器命名空间,与历史 `mcp__zotero__*` 工具名保持一致。 */
15
16
  const SERVER_NAME = 'zotero';
16
17
  /** 公开工具名:`mcp__zotero__<原始名>`。 */
@@ -37,8 +38,14 @@ export function blocksToText(content) {
37
38
  * (`write_item` / `create_collection` / `add_by_identifier` / `remove_items_from_collection` …)。
38
39
  */
39
40
  const WRITE_TOOL_RE = /^(write|add|create|update|delete|remove)_/i;
40
- /** 破坏性写工具:删除/移除类,需要额外的确认提示。 */
41
- const DESTRUCTIVE_TOOL_RE = /^(delete|remove)_/i;
41
+ /**
42
+ * 破坏性写工具:删除/移除/移入回收站类,需要对话框审批 + 额外提示。
43
+ *
44
+ * 实测集成 MCP 的这类工具有 `delete_collection` / `remove_items_from_collection`
45
+ * / `trash_item`,统一命中。注意 `add_*_to_collection`(移入分类)不是破坏性的,
46
+ * 不在此列。
47
+ */
48
+ const DESTRUCTIVE_TOOL_RE = /^(delete|remove|trash)_/i;
42
49
  /**
43
50
  * 注入到写工具描述前面的引导语。
44
51
  *
@@ -80,8 +87,34 @@ function descriptionFor(tool) {
80
87
  return base;
81
88
  return `${parts.join('\n\n')}\n\n${base}`;
82
89
  }
90
+ /**
91
+ * 给 MCP 破坏性工具生成审批文案:尽量把调用里的条目 / 分类 key 摆到卡片上。
92
+ *
93
+ * 这几类工具的 args 形状不统一(`trash_item` 是 `itemKeys`,`delete_collection` 是
94
+ * `collectionKey`,`remove_items_from_collection` 两者都有),所以宽松地收集几个
95
+ * 常见字段,拿不到就只显示工具名 —— 审批卡片本身还会挂 callId 展示完整参数。
96
+ */
97
+ function mcpApprovalText(tool, args) {
98
+ const record = args;
99
+ const keys = [];
100
+ if (typeof record === 'object' && record !== null) {
101
+ for (const field of ['itemKeys', 'itemKey', 'collectionKey', 'keys']) {
102
+ const value = record[field];
103
+ if (Array.isArray(value))
104
+ keys.push(...value.filter((k) => typeof k === 'string'));
105
+ else if (typeof value === 'string')
106
+ keys.push(value);
107
+ }
108
+ }
109
+ const target = keys.length === 0 ? '' : `:${keys.slice(0, 8).join('、')}${keys.length > 8 ? ` 等 ${keys.length} 个` : ''}`;
110
+ const action = tool.name === 'trash_item' ? '移入回收站(可在 Zotero 恢复)' : '删除';
111
+ return {
112
+ en: `Approve Zotero ${tool.name}: ${action}${target}.`,
113
+ zh: `即将对 Zotero 执行 ${action} ${tool.name}${target},请核对后确认。`,
114
+ };
115
+ }
83
116
  /** 由 MCP 工具造一条 dsh 工具定义(参数直接沿用上游 JSON Schema)。 */
84
- function definitionFor(tool) {
117
+ function definitionFor(tool, ctx) {
85
118
  return {
86
119
  name: publicName(tool.name),
87
120
  description: descriptionFor(tool),
@@ -98,6 +131,9 @@ function definitionFor(tool) {
98
131
  ],
99
132
  },
100
133
  async execute(args, exec) {
134
+ if (DESTRUCTIVE_TOOL_RE.test(tool.name)) {
135
+ await requireApproval(ctx, exec, publicName(tool.name), mcpApprovalText(tool, args));
136
+ }
101
137
  const result = await callMcpTool(tool.name, args, exec.signal);
102
138
  const text = blocksToText(result.content);
103
139
  if (result.isError)
@@ -132,7 +168,7 @@ export class McpToolBridge {
132
168
  for (const tool of tools) {
133
169
  if (disabled.has(tool.name))
134
170
  continue;
135
- next.push(toolsService.register(definitionFor(tool)));
171
+ next.push(toolsService.register(definitionFor(tool, this.ctx)));
136
172
  }
137
173
  }
138
174
  catch (error) {
@@ -365,16 +365,8 @@ async function handleAttachmentInfo(res, params) {
365
365
  };
366
366
  ok(res, data);
367
367
  }
368
- /** 用系统默认处理器打开 `zotero://` URL;参数数组传递,不经过 shell。 */
369
- function openExternal(url) {
370
- const command = process.platform === 'darwin'
371
- ? 'open'
372
- : process.platform === 'win32'
373
- ? 'rundll32'
374
- : 'xdg-open';
375
- const args = process.platform === 'win32'
376
- ? ['url.dll,FileProtocolHandler', url]
377
- : [url];
368
+ /** 分离进程启动外部命令;参数数组传递,不经过 shell。 */
369
+ function spawnDetached(command, args) {
378
370
  return new Promise((resolvePromise, reject) => {
379
371
  const child = spawn(command, args, { detached: true, stdio: 'ignore' });
380
372
  child.once('spawn', () => {
@@ -386,6 +378,29 @@ function openExternal(url) {
386
378
  });
387
379
  });
388
380
  }
381
+ /** 用系统默认处理器打开 `zotero://` URL。 */
382
+ function openExternal(url) {
383
+ const command = process.platform === 'darwin'
384
+ ? 'open'
385
+ : process.platform === 'win32'
386
+ ? 'rundll32'
387
+ : 'xdg-open';
388
+ const args = process.platform === 'win32'
389
+ ? ['url.dll,FileProtocolHandler', url]
390
+ : [url];
391
+ return spawnDetached(command, args);
392
+ }
393
+ /**
394
+ * 启动 / 激活 Zotero 主窗口:没有可定位的分类 key 时用(文库根、虚拟分类)。
395
+ * `zotero://select/library` 不是合法的 select URL,只能交给系统唤起应用。
396
+ */
397
+ function activateZotero() {
398
+ if (process.platform === 'darwin')
399
+ return spawnDetached('open', ['-a', 'Zotero']);
400
+ if (process.platform === 'win32')
401
+ return spawnDetached('cmd.exe', ['/c', 'start', '', 'zotero']);
402
+ return spawnDetached('zotero', []);
403
+ }
389
404
  /** 读取小请求体;超过上限直接拒绝,避免被大 body 拖住。 */
390
405
  async function readBody(req, limit) {
391
406
  const chunks = [];
@@ -402,9 +417,29 @@ async function readBody(req, limit) {
402
417
  async function handleOpenInZotero(req, res) {
403
418
  const record = await readJsonBody(req, 4096);
404
419
  const key = typeof record.key === 'string' ? record.key : '';
405
- const kind = record.kind === 'item' || record.kind === 'attachment' ? record.kind : null;
406
- if (!KEY_PATTERN.test(key) || kind === null) {
407
- fail(res, 400, 'bad_request', 'key 或 kind 不合法');
420
+ const kind = record.kind === 'item'
421
+ || record.kind === 'attachment'
422
+ || record.kind === 'collection'
423
+ || record.kind === 'library'
424
+ ? record.kind
425
+ : null;
426
+ if (kind === null) {
427
+ fail(res, 400, 'bad_request', 'kind 不合法');
428
+ return;
429
+ }
430
+ if (kind === 'library') {
431
+ await activateZotero();
432
+ ok(res, { opened: true });
433
+ return;
434
+ }
435
+ if (!KEY_PATTERN.test(key)) {
436
+ fail(res, 400, 'bad_request', 'key 格式不合法');
437
+ return;
438
+ }
439
+ if (kind === 'collection') {
440
+ // Zotero 主窗口选中该分类,右侧即为该分类的文献列表。
441
+ await openExternal(`zotero://select/library/collections/${key}`);
442
+ ok(res, { opened: true });
408
443
  return;
409
444
  }
410
445
  let url = `zotero://select/library/items/${key}`;
@@ -18,6 +18,7 @@ import { deleteAnnotation, patchAnnotation } from '../zotero/annotation-writes.j
18
18
  import { getAnnotationState, getNoteRaw, ZoteroError } from '../zotero/client.js';
19
19
  import { createNote, deleteNote, updateNote } from '../zotero/notes.js';
20
20
  import { getSettings } from '../zotero/config.js';
21
+ import { requireApproval } from './approval.js';
21
22
  import { blocksToText } from './mcp-bridge.js';
22
23
  import { requireKey } from './router.js';
23
24
  /** 每条写工具描述前面都挂的引导语:授权是一次点击,不是重试能解决的事。 */
@@ -28,6 +29,17 @@ const AUTH_HINT = '[写入 Zotero] 本工具经 Zotero 本地 API 改动用户
28
29
  const DESTRUCTIVE_HINT = '[破坏性写操作] 删除是**硬删**,不进 Zotero 回收站、撤销不了。执行前必须向用户点明要删的具体对象并得到确认。';
29
30
  /** Zotero 标注色板,直接写进描述,省得模型猜 hex。 */
30
31
  const COLOR_HINT = '颜色只能取 Zotero 色板:`#ffd400` 黄 / `#ff6666` 红 / `#5fb236` 绿 / `#2ea8e5` 蓝 / `#a28ae5` 紫 / `#e56eee` 粉 / `#f19837` 橙。';
32
+ /** 给删除工具用的审批文案:把被删的 key 摆到卡片上,让用户核对具体对象。 */
33
+ function deleteApprovalText(label, keyField, args) {
34
+ const record = args;
35
+ const key = typeof record === 'object' && record !== null && typeof record[keyField] === 'string'
36
+ ? record[keyField]
37
+ : '(未识别)';
38
+ return {
39
+ en: `Delete Zotero ${label} ${key}? Hard delete, cannot be undone.`,
40
+ zh: `即将删除 Zotero ${label} ${key} —— 硬删除,不进回收站、无法撤销。请核对后确认。`,
41
+ };
42
+ }
31
43
  /** 结果统一压成 MCP 那种内容块,渲染与序列化只有一份实现。 */
32
44
  function resultFor(text) {
33
45
  return { content: [{ type: 'text', text }] };
@@ -116,6 +128,7 @@ const TOOL_DEFINITIONS = [
116
128
  required: ['key'],
117
129
  additionalProperties: false,
118
130
  },
131
+ approval: (args) => deleteApprovalText('笔记', 'key', args),
119
132
  async execute(args) {
120
133
  const record = readArgs(args);
121
134
  assertKnown(record, ['key'], 'zotero_delete_note');
@@ -187,6 +200,7 @@ const TOOL_DEFINITIONS = [
187
200
  required: ['key'],
188
201
  additionalProperties: false,
189
202
  },
203
+ approval: (args) => deleteApprovalText('标注', 'key', args),
190
204
  async execute(args) {
191
205
  const record = readArgs(args);
192
206
  assertKnown(record, ['key'], 'zotero_delete_annotation');
@@ -222,7 +236,8 @@ export class ZoteroWriteToolBridge {
222
236
  this.enabled = enabled;
223
237
  if (!enabled)
224
238
  return;
225
- const toolsService = this.ctx.tools;
239
+ const ctx = this.ctx;
240
+ const toolsService = ctx.tools;
226
241
  const next = [];
227
242
  try {
228
243
  for (const tool of TOOL_DEFINITIONS) {
@@ -241,7 +256,10 @@ export class ZoteroWriteToolBridge {
241
256
  { type: 'text', text: blocksToText(value.content) },
242
257
  ],
243
258
  },
244
- async execute(args) {
259
+ async execute(args, exec) {
260
+ if (tool.approval) {
261
+ await requireApproval(ctx, exec, tool.name, tool.approval(args));
262
+ }
245
263
  return resultFor(await tool.execute(args));
246
264
  },
247
265
  }));
@@ -52,6 +52,8 @@ interface RawItemData {
52
52
  collections?: string[];
53
53
  contentType?: string;
54
54
  filename?: string;
55
+ /** 附件形态:`imported_file` / `linked_file` / `imported_url` / `linked_url`。 */
56
+ linkMode?: string;
55
57
  /**
56
58
  * 链接附件的路径,只有 `linkMode: linked_file` 才有。
57
59
  *
@@ -188,6 +190,8 @@ export interface ListTagUsageOptions {
188
190
  * 传多个 `collectionKeys` 时分目录扫描,并按条目 key 去重——同一篇条目可能
189
191
  * 同时挂在父分类与子分类里,不能重复计数。超过 `USAGE_SCAN_MAX` 条的大范围
190
192
  * 按前若干页截断,超大目录可能漏掉靠后的标签(本地 API 没有按分类列标签的端点)。
193
+ *
194
+ * 回收站走 `/items/trash/top`:不带 `/top` 会把子附件也扫进来,与列表口径不一致。
191
195
  */
192
196
  export declare function listTagUsage(options: ListTagUsageOptions): Promise<ZoteroTags>;
193
197
  export interface ListItemsOptions {
@@ -100,6 +100,37 @@ function toAttachment(raw) {
100
100
  size: raw.links?.enclosure?.length ?? 0,
101
101
  };
102
102
  }
103
+ /**
104
+ * 列表行子项的图标分类。
105
+ *
106
+ * 只认 Zotero 子条目 JSON 里现成的字段,不额外请求详情:
107
+ * - `note` 是子笔记(itemType 就是 note,不是附件);
108
+ * - PDF 看规范化后的 MIME,MIME 缺失时按文件名后缀兜底;
109
+ * - `linked_url` 是「链接到网页」,与 `imported_url` 存下来的网页快照分开画;
110
+ * - HTML / XHTML 一律按快照(Zotero 的 SingleFile 快照就是本地 HTML);
111
+ * - 其余附件(Word / 图片 / 音频 / EPUB …)统一用通用文件图标。
112
+ */
113
+ function childKind(raw) {
114
+ const data = raw.data ?? {};
115
+ if (data.itemType === 'note')
116
+ return 'note';
117
+ const filename = data.filename ?? '';
118
+ const mime = normalizeContentType(data.contentType ?? '', filename);
119
+ if (mime === 'application/pdf' || /\.pdf$/iu.test(filename))
120
+ return 'pdf';
121
+ if (data.linkMode === 'linked_url')
122
+ return 'webpage';
123
+ if (mime === 'text/html'
124
+ || mime === 'application/xhtml+xml'
125
+ || /\.x?html?$/iu.test(filename))
126
+ return 'snapshot';
127
+ return 'file';
128
+ }
129
+ /** 子项标题:笔记没有 title 字段,跟顶层摘要行一样取正文首段。 */
130
+ function childTitle(raw) {
131
+ const data = raw.data ?? {};
132
+ return data.itemType === 'note' ? noteTitle(data.note ?? '') : attachmentTitle(raw);
133
+ }
103
134
  // ---- 笔记正文清洗 ------------------------------------------------------------
104
135
  /**
105
136
  * 笔记正文清洗。
@@ -284,11 +315,12 @@ function toSummary(raw, child) {
284
315
  creators: raw.meta?.creatorSummary ?? '',
285
316
  year: yearOf(raw.meta, data),
286
317
  itemType,
287
- attachments: child.attachments,
318
+ kind: childKind(raw),
319
+ attachments: child.children,
288
320
  lastRead: child.lastRead,
289
321
  };
290
322
  }
291
- const NO_CHILD_STATE = { lastRead: null, attachments: [] };
323
+ const NO_CHILD_STATE = { lastRead: null, children: [] };
292
324
  /** 附件自己的 `lastRead` 就在它的 JSON 里,笔记没有,其余条目去问子附件。 */
293
325
  function childStateOf(raw) {
294
326
  const data = raw.data ?? {};
@@ -297,7 +329,7 @@ function childStateOf(raw) {
297
329
  // 顶层附件没有子附件可展开,但它自己的阅读时间仍要报。
298
330
  return Promise.resolve({
299
331
  lastRead: typeof value === 'number' && value > 0 ? value : null,
300
- attachments: [],
332
+ children: [],
301
333
  });
302
334
  }
303
335
  if (data.itemType === 'note')
@@ -512,6 +544,8 @@ const USAGE_SCAN_MAX = 3000;
512
544
  * 传多个 `collectionKeys` 时分目录扫描,并按条目 key 去重——同一篇条目可能
513
545
  * 同时挂在父分类与子分类里,不能重复计数。超过 `USAGE_SCAN_MAX` 条的大范围
514
546
  * 按前若干页截断,超大目录可能漏掉靠后的标签(本地 API 没有按分类列标签的端点)。
547
+ *
548
+ * 回收站走 `/items/trash/top`:不带 `/top` 会把子附件也扫进来,与列表口径不一致。
515
549
  */
516
550
  export async function listTagUsage(options) {
517
551
  // 「最近阅读」没有可按分类扫描的端点,也没有必要:面板在选它时不请求标签用量。
@@ -523,7 +557,7 @@ export async function listTagUsage(options) {
523
557
  const bases = options.scope === 'publications'
524
558
  ? [`${libraryBase()}/publications/items`]
525
559
  : options.scope === 'trash'
526
- ? [`${libraryBase()}/items/trash`]
560
+ ? [`${libraryBase()}/items/trash/top`]
527
561
  : (options.collectionKeys ?? []).length > 0
528
562
  ? options.collectionKeys.map((key) => `${libraryBase()}/collections/${encode(key)}/items/top`)
529
563
  : [`${libraryBase()}/items/top`];
@@ -576,30 +610,34 @@ const CHILD_STATE_TTL_MS = 60_000;
576
610
  const CHILD_STATE_CACHE_MAX = 5000;
577
611
  const childStateCache = new Map();
578
612
  /**
579
- * 父条目的子附件状态:最晚阅读时间 + 子附件清单。
613
+ * 父条目的子项状态:最晚阅读时间 + 附件与子笔记清单。
580
614
  *
581
- * 两样都来自同一次 `/children?itemType=attachment`:列表行要画已读标志,
582
- * 还要数附件、展开附件,没必要多打一份请求。已读状态只记在附件上,父条目
583
- * 要问它的子附件(原生 `getItemLastRead()` 同理)。按条目查而不是扫全库:
615
+ * 两样都来自同一次 `/children`:列表行要画已读标志、按形态计数、展开子项,
616
+ * 没必要多打一份请求。本机 API 不带 `itemType` 时不返回标注(标注要显式
617
+ * `itemType=annotation` 才给),这里再按 itemType 兜一层;已读时间只记在附件上,
618
+ * 父条目要问它的子附件(原生 `getItemLastRead()` 同理)。按条目查而不是扫全库:
584
619
  * 单条约 6ms,只查当前列表里的条目,大口库也不会卡。
585
- * 取不到按「无子附件、未读」处理——附加信息不能拖垮条目列表。
620
+ * 取不到按「无子项、未读」处理——附加信息不能拖垮条目列表。
586
621
  */
587
622
  async function itemChildState(key) {
588
623
  const cached = childStateCache.get(key);
589
624
  if (cached !== undefined && Date.now() - cached.at < CHILD_STATE_TTL_MS)
590
625
  return cached.state;
591
626
  try {
592
- const { body } = await requestJson(`${libraryBase()}/items/${encode(key)}/children?itemType=attachment`);
627
+ const { body } = await requestJson(`${libraryBase()}/items/${encode(key)}/children`);
593
628
  let lastRead = null;
594
- const attachments = [];
629
+ const children = [];
595
630
  for (const child of Array.isArray(body) ? body : []) {
631
+ const itemType = child.data?.itemType ?? '';
632
+ if (itemType !== 'attachment' && itemType !== 'note')
633
+ continue;
596
634
  const value = child.data?.lastRead;
597
635
  if (typeof value === 'number' && value > 0 && (lastRead === null || value > lastRead)) {
598
636
  lastRead = value;
599
637
  }
600
- attachments.push({ key: child.key, title: attachmentTitle(child) });
638
+ children.push({ key: child.key, title: childTitle(child), kind: childKind(child) });
601
639
  }
602
- const state = { lastRead, attachments };
640
+ const state = { lastRead, children };
603
641
  if (childStateCache.size >= CHILD_STATE_CACHE_MAX)
604
642
  childStateCache.clear();
605
643
  childStateCache.set(key, { at: Date.now(), state });
@@ -631,12 +669,18 @@ function appendItemSort(params, options) {
631
669
  params.set('sort', options.sort);
632
670
  params.set('direction', options.direction === 'desc' ? 'desc' : 'asc');
633
671
  }
634
- /** 范围内的顶层条目端点基址(条目列表与标签用量共用同一套范围规则)。 */
672
+ /**
673
+ * 范围内的顶层条目端点基址(条目列表与标签用量共用同一套范围规则)。
674
+ *
675
+ * 回收站必须用 `/items/trash/top`:Zotero 本地 API 的 `/items/trash` 会把
676
+ * 子附件一并列出,`Total-Results` 因此比客户端回收站的顶层条目数多(实测
677
+ * 126 = 94 顶层 + 32 子附件),列表里也会多出一批子附件行。
678
+ */
635
679
  function itemListBase(options) {
636
680
  return options.scope === 'publications'
637
681
  ? `${libraryBase()}/publications/items`
638
682
  : options.scope === 'trash'
639
- ? `${libraryBase()}/items/trash`
683
+ ? `${libraryBase()}/items/trash/top`
640
684
  : options.collectionKey
641
685
  ? `${libraryBase()}/collections/${encode(options.collectionKey)}/items/top`
642
686
  : `${libraryBase()}/items/top`;
@@ -787,7 +831,7 @@ export async function listRecentItems(positions, options) {
787
831
  const raw = itemByKey.get(key);
788
832
  if (raw === undefined)
789
833
  continue;
790
- const row = toSummary(raw, { lastRead: readAtByKey.get(key) ?? null, attachments: [] });
834
+ const row = toSummary(raw, { lastRead: readAtByKey.get(key) ?? null, children: [] });
791
835
  if (search !== ''
792
836
  && !row.title.toLowerCase().includes(search)
793
837
  && !row.creators.toLowerCase().includes(search))
@@ -813,7 +857,7 @@ export async function listRecentItems(positions, options) {
813
857
  return row;
814
858
  const child = await childStateOf(raw);
815
859
  // 阅读时间保持本插件记录的,别被 Zotero 的 lastRead 覆盖。
816
- return { ...row, attachments: child.attachments };
860
+ return { ...row, attachments: child.children };
817
861
  }));
818
862
  return { total: rows.length, items };
819
863
  }
@@ -22,10 +22,19 @@ export interface ZoteroCollection {
22
22
  /** 虚拟分类的范围;真实分类为空。 */
23
23
  scope?: ZoteroItemScope;
24
24
  }
25
- /** 列表展开行里的子附件(只够渲染一行)。 */
25
+ /**
26
+ * 条目列表里「附件形态」的判定结果。
27
+ *
28
+ * 同时用于展开行的子项和顶层裸附件条目(直接导进库的 PDF / 快照等)。
29
+ * Host 从 `itemType` / `contentType` / `linkMode` / 文件名判定,Client 只按它挑图标;
30
+ * 笔记也在内(`note`),虽然 Zotero 严格意义上不把它算作附件。
31
+ */
32
+ export type ZoteroChildKind = 'pdf' | 'snapshot' | 'webpage' | 'note' | 'file';
33
+ /** 列表展开行里的子项(附件与笔记,只够渲染一行)。 */
26
34
  export interface ZoteroChildAttachment {
27
35
  key: string;
28
36
  title: string;
37
+ kind: ZoteroChildKind;
29
38
  }
30
39
  /** 列表行用的条目摘要。 */
31
40
  export interface ZoteroItemSummary {
@@ -35,7 +44,9 @@ export interface ZoteroItemSummary {
35
44
  creators: string;
36
45
  year: string;
37
46
  itemType: string;
38
- /** 子附件;空数组表示没有附件,列表行不显示展开图标。 */
47
+ /** 条目自身的形态;`itemType === 'attachment'` 时据此画具体图标而非纸夹。 */
48
+ kind: ZoteroChildKind;
49
+ /** 子项(附件 + 子笔记);空数组表示没有可展开内容。 */
39
50
  attachments: ZoteroChildAttachment[];
40
51
  /**
41
52
  * 子附件里最晚的阅读时间(Unix **秒**),与 Zotero 原生 `getItemLastRead()` 一致;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-zotero",
3
- "version": "0.9.2",
3
+ "version": "0.9.5",
4
4
  "description": "Map your Zotero library into DSH: let AI operate Zotero for you and help you read papers. Browse collections and tags in the sidebar, read PDFs with highlights in place, and cite excerpts, annotations, notes or whole items into the chat. The model works from the source text for reviews, comparisons and data extraction, and can also search and organize the library, import papers and attach translations back to items; first use needs the Zotero MCP plugin and the local API enabled.",
5
5
  "keywords": [
6
6
  "dsh",