dsh-palace 1.3.0 → 1.3.2

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/lib/index.js CHANGED
@@ -1,7 +1,7 @@
1
- // src/host/index.ts
1
+ // src/host/harness/index.ts
2
2
  import { existsSync as existsSync5 } from "node:fs";
3
- import { homedir as homedir3 } from "node:os";
4
- import { join as join6, resolve } from "node:path";
3
+ import { homedir as homedir4 } from "node:os";
4
+ import { join as join8, resolve } from "node:path";
5
5
 
6
6
  // src/core/memory.ts
7
7
  import { appendFileSync, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
@@ -72,9 +72,14 @@ function periodOf(item) {
72
72
  function monthOf(iso) {
73
73
  return /^\d{4}-\d{2}-\d{2}$/.test(iso) ? iso.slice(0, 7) : today(new Date(iso)).slice(0, 7);
74
74
  }
75
+ function weReadPosition(item) {
76
+ const { position } = item;
77
+ return item.source === null && position && (position.loc === "" || position.loc.startsWith("weread:")) ? position : void 0;
78
+ }
75
79
  function percentOf(item, done, total) {
76
80
  if (item.finishedAt !== void 0) return 1;
77
- if (item.source?.type === "epub" && item.position !== void 0) return item.position.percent;
81
+ const position = item.source?.type === "epub" ? item.position : weReadPosition(item);
82
+ if (position) return position.percent;
78
83
  return total > 0 ? done / total : void 0;
79
84
  }
80
85
  function findSection(item, sectionId) {
@@ -381,6 +386,12 @@ var SUMMARY_LIMIT = 40;
381
386
  var WHY_LIMIT = 40;
382
387
  var TOPIC_LIMIT = 5;
383
388
  var charCount = (s) => [...s].length;
389
+ function linkWhy(value) {
390
+ if (typeof value !== "string" || value.trim() === "") throw new ShelfError("\u8981\u5199\u4E00\u53E5\u7406\u7531");
391
+ const why = value.trim().replace(/\n/g, " ");
392
+ if (charCount(why) > WHY_LIMIT) throw new ShelfError(`\u7406\u7531\u6700\u591A ${WHY_LIMIT} \u5B57`);
393
+ return why;
394
+ }
384
395
  var pairKey = (a, b) => a < b ? `${a}|${b}` : `${b}|${a}`;
385
396
  function recordsOf(item) {
386
397
  const out = /* @__PURE__ */ new Map();
@@ -496,19 +507,20 @@ var Memory = class {
496
507
  if (line.trim() === "") continue;
497
508
  try {
498
509
  const r = JSON.parse(line);
499
- if ((r.type === "link" || r.type === "cut") && typeof r.from === "string" && typeof r.to === "string") records.push(r);
510
+ if ((r.type === "link" || r.type === "cut" || r.type === "retitle" && typeof r.why === "string") && typeof r.from === "string" && typeof r.to === "string") records.push(r);
500
511
  } catch {
501
512
  }
502
513
  }
503
514
  this.cache = { stamp: stamp2, records };
504
515
  return records;
505
516
  }
506
- append(record) {
517
+ append(records) {
518
+ if (records.length === 0) return;
507
519
  this.store.assertWritable();
508
520
  this.store.snapshotBeforeWrite();
509
521
  const size = existsSync2(this.linksFile) ? statSync2(this.linksFile).size : 0;
510
522
  const broken = size > 0 && readFileSync2(this.linksFile, "utf8").at(-1) !== "\n";
511
- appendFileSync(this.linksFile, (broken ? "\n" : "") + JSON.stringify(record) + "\n", "utf8");
523
+ appendFileSync(this.linksFile, (broken ? "\n" : "") + records.map((record) => JSON.stringify(record)).join("\n") + "\n", "utf8");
512
524
  this.store.rev += 1;
513
525
  }
514
526
  cellOf(id, allowGroup) {
@@ -527,9 +539,7 @@ var Memory = class {
527
539
  const from = this.cellOf(args.from, false);
528
540
  const to = this.cellOf(args.to, false);
529
541
  if (from.id === to.id) throw new ShelfError("\u4E0D\u80FD\u8FDE\u5230\u81EA\u5DF1");
530
- if (typeof args.why !== "string" || args.why.trim() === "") throw new ShelfError("\u8981\u5199\u4E00\u53E5\u7406\u7531");
531
- const why = args.why.trim().replace(/\n/g, " ");
532
- if (charCount(why) > WHY_LIMIT) throw new ShelfError(`\u7406\u7531\u6700\u591A ${WHY_LIMIT} \u5B57`);
542
+ const why = linkWhy(args.why);
533
543
  if (!Array.isArray(args.evidence)) throw new ShelfError("evidence \u5E94\u4E3A\u5361\u7247 / \u7075\u611F id \u7684\u6570\u7EC4");
534
544
  const evidence = [...new Set(args.evidence.filter((e) => typeof e === "string"))];
535
545
  const a = recordsOf(this.store.getItem(from.id));
@@ -541,14 +551,43 @@ var Memory = class {
541
551
  const used = new Set(this.validLinks().filter((l) => pairKey(l.from, l.to) === pairKey(from.id, to.id)).flatMap((l) => l.evidence));
542
552
  if (evidence.every((e) => used.has(e))) throw new ShelfError("\u8FD9\u4E9B\u8BC1\u636E\u5DF2\u7ECF\u8FDE\u8FC7\u4E86\uFF1B\u6709\u65B0\u7684\u5361\u7247\u6216\u7075\u611F\u518D\u8FDE");
543
553
  const record = { type: "link", id: newId("l"), from: from.id, to: to.id, why, evidence, ...args.sessionId ? { sessionId: args.sessionId } : {}, createdAt: nowIso() };
544
- this.append(record);
554
+ this.append([record]);
545
555
  return record;
546
556
  }
557
+ /** 导入双链按来源键去重。用户剪过的格子对继续保留断开状态。 */
558
+ previewImportedLinks(links) {
559
+ const records = this.records();
560
+ const cuts = new Set(records.filter((r) => r.type === "cut").map((r) => pairKey(r.from, r.to)));
561
+ const known = new Set(records.flatMap((r) => r.type === "link" && r.sourceKey ? [r.sourceKey] : []));
562
+ const active = this.validLinks();
563
+ const activeKeys = new Set(active.map((r) => r.sourceKey));
564
+ const activePairs = new Set(active.map((r) => pairKey(r.from, r.to)));
565
+ const eligible = links.filter((link) => !cuts.has(pairKey(link.from, link.to)));
566
+ const added = eligible.filter((link) => !activeKeys.has(link.sourceKey));
567
+ return {
568
+ pending: eligible.filter((link) => !known.has(link.sourceKey)),
569
+ arcs: new Set(added.map((link) => pairKey(link.from, link.to)).filter((pair) => !activePairs.has(pair))).size,
570
+ strands: added.length
571
+ };
572
+ }
573
+ addImportedLinks(links) {
574
+ if (links.length === 0) return;
575
+ const { pending } = this.previewImportedLinks(links);
576
+ this.append(pending.map((link) => ({ ...link, type: "link", id: newId("l"), why: linkWhy(link.why), createdAt: nowIso() })));
577
+ }
578
+ retitleLink(args) {
579
+ const from = this.cellOf(args.from, false).id;
580
+ const to = this.cellOf(args.to, false).id;
581
+ const why = linkWhy(args.why);
582
+ const arc = this.arcs().find((arc2) => pairKey(arc2.from, arc2.to) === pairKey(from, to));
583
+ if (!arc) throw new ShelfError("\u8FD9\u4E24\u683C\u4E4B\u95F4\u6CA1\u6709\u6709\u6548\u7535\u5F27");
584
+ if (arc.why !== why) this.append([{ type: "retitle", from, to, why }]);
585
+ }
547
586
  /** 用户剪断两格之间的电弧(追加记录,不删历史)。 */
548
587
  cut(args) {
549
588
  const from = this.cellOf(args.from, true);
550
589
  const to = this.cellOf(args.to, true);
551
- this.append({ type: "cut", from: from.id, to: to.id, createdAt: nowIso() });
590
+ this.append([{ type: "cut", from: from.id, to: to.id, createdAt: nowIso() }]);
552
591
  }
553
592
  /** 还有效的联想:两端格子都在、在最近一次剪断之后、两端各至少还剩一条证据。 */
554
593
  validLinks() {
@@ -562,12 +601,15 @@ var Memory = class {
562
601
  }
563
602
  return r;
564
603
  };
604
+ const records = this.records();
565
605
  const cuts = /* @__PURE__ */ new Map();
566
- for (const r of this.records()) if (r.type === "cut") {
567
- const k = pairKey(r.from, r.to);
568
- if (r.createdAt > (cuts.get(k) ?? "")) cuts.set(k, r.createdAt);
606
+ for (const r of records) {
607
+ if (r.type === "cut") {
608
+ const key = pairKey(r.from, r.to);
609
+ if (r.createdAt > (cuts.get(key) ?? "")) cuts.set(key, r.createdAt);
610
+ }
569
611
  }
570
- return this.records().filter((r) => {
612
+ return records.filter((r) => {
571
613
  if (r.type !== "link" || !cells.has(r.from) || !cells.has(r.to)) return false;
572
614
  if (r.createdAt <= (cuts.get(pairKey(r.from, r.to)) ?? "")) return false;
573
615
  const ev = Array.isArray(r.evidence) ? r.evidence : [];
@@ -576,14 +618,21 @@ var Memory = class {
576
618
  }
577
619
  /** 电弧:按格子对聚合有效联想。 */
578
620
  arcs() {
621
+ const titles = /* @__PURE__ */ new Map();
622
+ for (const r of this.records()) {
623
+ if (r.type === "cut") titles.delete(pairKey(r.from, r.to));
624
+ if (r.type === "retitle") titles.set(pairKey(r.from, r.to), r.why);
625
+ }
579
626
  const byPair = /* @__PURE__ */ new Map();
580
627
  for (const l of this.validLinks()) {
581
628
  const k = pairKey(l.from, l.to);
582
- byPair.set(k, [...byPair.get(k) ?? [], l]);
629
+ const links = byPair.get(k);
630
+ if (links) links.push(l);
631
+ else byPair.set(k, [l]);
583
632
  }
584
633
  return [...byPair.values()].map((links) => {
585
634
  const latest = links.reduce((x, y) => y.createdAt >= x.createdAt ? y : x);
586
- return { from: latest.from, to: latest.to, strands: links.length, why: latest.why, lastAt: latest.createdAt, links };
635
+ return { from: latest.from, to: latest.to, strands: links.length, why: titles.get(pairKey(latest.from, latest.to)) ?? latest.why, lastAt: latest.createdAt, links };
587
636
  }).sort((x, y) => y.strands - x.strands || (y.lastAt > x.lastAt ? 1 : -1));
588
637
  }
589
638
  // ---------- 对话背景 ----------
@@ -1052,8 +1101,8 @@ async function deleteInspiration(store, args) {
1052
1101
  // src/host/routes.ts
1053
1102
  import { execFile as execFile2, spawn } from "node:child_process";
1054
1103
  import { createReadStream, existsSync as existsSync4, statSync as statSync4 } from "node:fs";
1055
- import { homedir as homedir2 } from "node:os";
1056
- import { basename as basename2, extname as extname2, join as join5, normalize, sep as sep2 } from "node:path";
1104
+ import { homedir as homedir3 } from "node:os";
1105
+ import { basename as basename3, extname as extname2, join as join6, normalize, sep as sep3 } from "node:path";
1057
1106
  import { Readable } from "node:stream";
1058
1107
  import { fileURLToPath } from "node:url";
1059
1108
 
@@ -1176,7 +1225,7 @@ async function readPdfInfo(file) {
1176
1225
  try {
1177
1226
  let items = await doc.getOutline() ?? [];
1178
1227
  while (items.length === 1 && items[0].items.length > 0) items = items[0].items;
1179
- const outline = [];
1228
+ const outline2 = [];
1180
1229
  for (const item of items) {
1181
1230
  const sections = [];
1182
1231
  for (const child of item.items) {
@@ -1184,7 +1233,7 @@ async function readPdfInfo(file) {
1184
1233
  if (title3 !== "") sections.push({ title: title3, page: await pageOf(doc, child.dest) });
1185
1234
  }
1186
1235
  const title2 = clean(item.title);
1187
- if (title2 !== "") outline.push({ title: title2, page: await pageOf(doc, item.dest), sections });
1236
+ if (title2 !== "") outline2.push({ title: title2, page: await pageOf(doc, item.dest), sections });
1188
1237
  }
1189
1238
  let title;
1190
1239
  try {
@@ -1193,7 +1242,7 @@ async function readPdfInfo(file) {
1193
1242
  if (typeof info?.Title === "string" && info.Title.trim() !== "") title = info.Title.trim();
1194
1243
  } catch {
1195
1244
  }
1196
- return { pageCount: doc.numPages, title, outline };
1245
+ return { pageCount: doc.numPages, title, outline: outline2 };
1197
1246
  } finally {
1198
1247
  await close();
1199
1248
  }
@@ -1232,7 +1281,7 @@ async function addBook(store, args, signal, { readVideo = true } = {}) {
1232
1281
  };
1233
1282
  let source;
1234
1283
  let title;
1235
- let outline = [];
1284
+ let outline2 = [];
1236
1285
  let outlineSource;
1237
1286
  if (typeof args.url === "string" && args.url.trim() !== "") {
1238
1287
  const url = args.url.trim();
@@ -1248,7 +1297,7 @@ async function addBook(store, args, signal, { readVideo = true } = {}) {
1248
1297
  });
1249
1298
  source = { type: "video", url: course.url };
1250
1299
  title = course.title;
1251
- outline = course.chapters.map((c) => ({ title: c.title, sections: c.episodes.map((e) => ({ title: e.title, loc: e.url })) }));
1300
+ outline2 = course.chapters.map((c) => ({ title: c.title, sections: c.episodes.map((e) => ({ title: e.title, loc: e.url })) }));
1252
1301
  outlineSource = "video";
1253
1302
  } else if (typeof args.file === "string" && args.file.trim() !== "") {
1254
1303
  const file = expandHome(args.file.trim().replace(/^['"]|['"]$/g, ""));
@@ -1269,7 +1318,7 @@ async function addBook(store, args, signal, { readVideo = true } = {}) {
1269
1318
  });
1270
1319
  source = { type: "pdf", path: file, pageCount: info.pageCount };
1271
1320
  title = basename(file, extname(file));
1272
- outline = info.outline.map((c) => ({
1321
+ outline2 = info.outline.map((c) => ({
1273
1322
  title: c.title,
1274
1323
  ...c.page !== void 0 ? { loc: String(c.page) } : {},
1275
1324
  sections: c.sections.map((s) => ({ title: s.title, ...s.page !== void 0 ? { loc: String(s.page) } : {} }))
@@ -1280,7 +1329,7 @@ async function addBook(store, args, signal, { readVideo = true } = {}) {
1280
1329
  }
1281
1330
  if (typeof args.title === "string" && args.title.trim() !== "") title = args.title.trim();
1282
1331
  cancelled();
1283
- return addCell(store, { kind: "book", title, subtitle: args.subtitle, source, parentId: args.parentId, targetDate: args.targetDate, outline, outlineSource });
1332
+ return addCell(store, { kind: "book", title, subtitle: args.subtitle, source, parentId: args.parentId, targetDate: args.targetDate, outline: outline2, outlineSource });
1284
1333
  }
1285
1334
  function isZip(file) {
1286
1335
  const fd = openSync(file, "r");
@@ -1315,6 +1364,225 @@ function saveImage(store, ref) {
1315
1364
  return name2;
1316
1365
  }
1317
1366
 
1367
+ // src/host/weread.ts
1368
+ import { randomUUID } from "node:crypto";
1369
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync3, realpathSync, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
1370
+ import { homedir as homedir2 } from "node:os";
1371
+ import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute2, join as join5, relative, sep as sep2 } from "node:path";
1372
+ import { setTimeout as delay } from "node:timers/promises";
1373
+ var GATEWAY = "https://i.weread.qq.com/api/agent/gateway";
1374
+ var SKILL_VERSION = "1.0.6";
1375
+ var validKey = (key) => typeof key === "string" && /^wrk-[A-Za-z0-9_-]+$/.test(key);
1376
+ var keyFile = join5(homedir2(), ".dsh-palace", "weread.json");
1377
+ function readKey(file = keyFile) {
1378
+ try {
1379
+ const { key } = JSON.parse(readFileSync3(file, "utf8"));
1380
+ if (validKey(key)) return key;
1381
+ } catch (error) {
1382
+ if (error.code === "ENOENT") return void 0;
1383
+ }
1384
+ throw new ShelfError("\u65E0\u6CD5\u8BFB\u53D6\u5FAE\u4FE1\u8BFB\u4E66 Key\uFF0C\u8BF7\u5728\u5BAB\u6BBF\u91CD\u65B0\u4FDD\u5B58");
1385
+ }
1386
+ function wereadKey(key, file = keyFile, dataDir) {
1387
+ if (key === void 0) return readKey(file) !== void 0;
1388
+ if (key !== null && !validKey(key)) throw new ShelfError("\u8BF7\u8F93\u5165\u6709\u6548\u7684\u5FAE\u4FE1\u8BFB\u4E66 API Key");
1389
+ const stage = file + "." + randomUUID();
1390
+ try {
1391
+ if (key === null) {
1392
+ rmSync2(file, { force: true });
1393
+ return false;
1394
+ }
1395
+ mkdirSync4(dirname2(file), { recursive: true, mode: 448 });
1396
+ if (dataDir !== void 0) {
1397
+ const location = relative(realpathSync(dataDir), join5(realpathSync(dirname2(file)), basename2(file)));
1398
+ if (!isAbsolute2(location) && location !== ".." && !location.startsWith(".." + sep2)) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66 Key \u5FC5\u987B\u4FDD\u5B58\u5728\u5BAB\u6BBF\u6570\u636E\u76EE\u5F55\u5916");
1399
+ }
1400
+ writeFileSync3(stage, JSON.stringify({ key }), { mode: 384, flag: "wx" });
1401
+ renameSync3(stage, file);
1402
+ return true;
1403
+ } catch (error) {
1404
+ if (error instanceof ShelfError) throw error;
1405
+ throw new ShelfError("\u65E0\u6CD5\u4FDD\u5B58\u6216\u5220\u9664\u5FAE\u4FE1\u8BFB\u4E66 Key");
1406
+ } finally {
1407
+ try {
1408
+ rmSync2(stage, { force: true });
1409
+ } catch {
1410
+ }
1411
+ }
1412
+ }
1413
+ var positionKey = ({ chapterUid, range }) => chapterUid != null && range?.trim() ? JSON.stringify([String(chapterUid), range]) : void 0;
1414
+ var responseList = {
1415
+ "/shelf/sync": "books",
1416
+ "/user/notebooks": "books",
1417
+ "/review/list/mine": "reviews",
1418
+ "/book/chapterinfo": "chapters",
1419
+ "/book/bookmarklist": "updated",
1420
+ "/book/getprogress": "book"
1421
+ };
1422
+ function outline(chapters, cards, chapterUid) {
1423
+ const result = [];
1424
+ for (const chapter of chapters) {
1425
+ const title = chapter.title?.trim();
1426
+ if (!title) continue;
1427
+ const level = chapter.level ?? 1;
1428
+ const row = { title, loc: String(chapter.chapterUid), sections: [] };
1429
+ if (level === 1 || level === 2 && !result.length) result.push(row);
1430
+ else if (level === 2) result.at(-1).sections.push({ title: row.title, loc: row.loc });
1431
+ }
1432
+ const marked = /* @__PURE__ */ new Set([chapterUid, ...cards.map((card) => card.sectionKey)]);
1433
+ for (const row of result) {
1434
+ if (row.sections?.length && row.loc && marked.has(row.loc)) row.sections.unshift({ title: row.title, loc: row.loc });
1435
+ }
1436
+ return result;
1437
+ }
1438
+ function createWeRead(fetcher = fetch, keyReader = readKey) {
1439
+ const inFlight = /* @__PURE__ */ new Set();
1440
+ async function request(key, api_name, params, signal, retried = false) {
1441
+ async function send() {
1442
+ const deadline = AbortSignal.timeout(12e3);
1443
+ const requestSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
1444
+ const response = await fetcher(GATEWAY, {
1445
+ method: "POST",
1446
+ redirect: "error",
1447
+ signal: requestSignal,
1448
+ headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
1449
+ body: JSON.stringify({ api_name, skill_version: SKILL_VERSION, ...params })
1450
+ });
1451
+ return { response, data: response.ok ? await response.json() : {} };
1452
+ }
1453
+ try {
1454
+ while (inFlight.size >= 3) {
1455
+ signal?.throwIfAborted();
1456
+ await Promise.race(inFlight).catch(() => void 0);
1457
+ }
1458
+ signal?.throwIfAborted();
1459
+ const task = send();
1460
+ inFlight.add(task);
1461
+ const { response, data } = await task.finally(() => inFlight.delete(task));
1462
+ const code = Number(data?.errcode || response.status);
1463
+ if (code === 429) {
1464
+ const seconds = Number(response.headers.get("retry-after") ?? 1);
1465
+ if (seconds >= 0 && seconds <= 3 && !retried) {
1466
+ await delay(seconds * 1e3, void 0, { signal });
1467
+ return request(key, api_name, params, signal, true);
1468
+ }
1469
+ throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
1470
+ }
1471
+ if (code === 401 || code === 403) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u9274\u6743\u5931\u8D25\uFF0C\u8BF7\u66F4\u6362 API Key");
1472
+ if (!response.ok || !data || Number(data.errcode ?? 0) !== 0) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u63A5\u53E3\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
1473
+ const value = data[responseList[api_name]];
1474
+ if (api_name === "/book/getprogress" ? !value || typeof value !== "object" || Array.isArray(value) : !Array.isArray(value)) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u56DE\u5305\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u91CD\u8BD5");
1475
+ return data;
1476
+ } catch (error) {
1477
+ if (error instanceof ShelfError) throw error;
1478
+ if (signal?.aborted) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u5BFC\u5165\u5DF2\u53D6\u6D88");
1479
+ throw new ShelfError("\u8FDE\u63A5\u5FAE\u4FE1\u8BFB\u4E66\u5931\u8D25\u6216\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5");
1480
+ }
1481
+ }
1482
+ function currentKey() {
1483
+ const key = keyReader();
1484
+ if (!key) throw new ShelfError("\u8BF7\u5148\u5728\u5BAB\u6BBF\u300C\u4ECE\u5FAE\u4FE1\u8BFB\u4E66\u5BFC\u5165\u300D\u91CC\u4FDD\u5B58 API Key");
1485
+ return key;
1486
+ }
1487
+ async function shelf(key, signal) {
1488
+ const main = await request(key, "/shelf/sync", {}, signal);
1489
+ const books = new Map(main.books.map((book) => [book.bookId, { ...book, hasNotes: false }]));
1490
+ let lastSort;
1491
+ while (true) {
1492
+ const page = await request(key, "/user/notebooks", { count: 100, lastSort }, signal);
1493
+ for (const entry of page.books) {
1494
+ const book = books.get(entry.bookId) ?? entry.book;
1495
+ if (book) books.set(entry.bookId, { ...book, bookId: entry.bookId, hasNotes: Boolean(entry.noteCount || entry.reviewCount) });
1496
+ }
1497
+ if (!page.hasMore) break;
1498
+ const next = page.books.at(-1)?.sort;
1499
+ if (next === void 0 || next === lastSort) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u7B14\u8BB0\u5217\u8868\u5206\u9875\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5");
1500
+ lastSort = next;
1501
+ }
1502
+ return { books, total: main.books.length + (main.albums?.length ?? 0) + Number(Object.keys(main.mp ?? {}).length > 0) };
1503
+ }
1504
+ let listing;
1505
+ let prepared;
1506
+ return {
1507
+ async scan(signal, imported = (_id) => false) {
1508
+ const key = currentKey();
1509
+ listing = { key, data: await shelf(key, signal) };
1510
+ prepared = void 0;
1511
+ const { books, total } = listing.data;
1512
+ return { total, withNotes: [...books.values()].filter((book) => book.hasNotes).length, books: [...books.values()].map(
1513
+ ({ bookId, title, author, category, finishReading, readUpdateTime, publishTime, hasNotes }) => ({ bookId, title, author, category, finished: finishReading === 1, readUpdateTime, publishTime, hasNotes, imported: imported(bookId) })
1514
+ ) };
1515
+ },
1516
+ async prepare(plan, confirming, signal, imported) {
1517
+ if (plan !== void 0 && (!Array.isArray(plan) || plan.length === 0 || plan.some((id) => typeof id !== "string" || !id))) throw new ShelfError("\u8BF7\u63D0\u4F9B\u8981\u5BFC\u5165\u7684 bookId \u5217\u8868");
1518
+ const key = currentKey(), explicit = plan === void 0 ? void 0 : [...new Set(plan)];
1519
+ const fingerprint = JSON.stringify(explicit ?? null);
1520
+ if (confirming && prepared?.key === key && prepared.plan === fingerprint) return prepared.batch;
1521
+ if (confirming) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u5BFC\u5165\u9884\u89C8\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u9884\u89C8\u5E76\u786E\u8BA4");
1522
+ const { books } = listing?.key === key ? listing.data : await shelf(key, signal);
1523
+ listing = void 0;
1524
+ const ids = explicit ?? [...books.keys()].filter(imported);
1525
+ if (!ids.length) throw new ShelfError("\u6CA1\u6709\u53EF\u540C\u6B65\u7684\u4E66\uFF0C\u8BF7\u5148\u9009\u4E66\u5BFC\u5165");
1526
+ const groups = [];
1527
+ for (const id of ids) {
1528
+ const book = books.get(id);
1529
+ if (!book) throw new ShelfError("\u9009\u4E2D\u7684\u4E66\u4E0D\u5728\u4E66\u67B6\u6216\u7B14\u8BB0\u672C\u91CC\uFF0C\u8BF7\u91CD\u65B0\u626B\u63CF");
1530
+ const href = [book.readerLink, book.deepLink].find((link) => typeof link === "string" && /^https?:\/\//.test(link));
1531
+ const group = { key: id, kind: "book", title: book.title, href, cards: [] };
1532
+ groups.push(group);
1533
+ const { book: { progress, finishTime, chapterUid } } = await request(key, "/book/getprogress", { bookId: id }, signal);
1534
+ if (typeof progress === "number" && Number.isInteger(progress) && progress >= 0 && progress <= 100) {
1535
+ const finish = progress === 100 && typeof finishTime === "number" && finishTime > 0 ? new Date(finishTime * 1e3) : void 0;
1536
+ group.progress = { percent: progress / 100, chapterUid: chapterUid?.toString(), finishedAt: finish && Number.isFinite(finish.getTime()) ? today(finish) : void 0 };
1537
+ }
1538
+ if (!book.hasNotes) continue;
1539
+ const reviews = async () => {
1540
+ const rows = [];
1541
+ let synckey = 0;
1542
+ while (true) {
1543
+ const page = await request(key, "/review/list/mine", { bookid: id, synckey, count: 100 }, signal);
1544
+ rows.push(...page.reviews);
1545
+ if (!page.hasMore) return rows;
1546
+ if (!page.synckey || page.synckey === synckey) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u60F3\u6CD5\u5217\u8868\u5206\u9875\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5");
1547
+ synckey = page.synckey;
1548
+ }
1549
+ };
1550
+ const [toc, marks, notes] = await Promise.all([
1551
+ request(key, "/book/chapterinfo", { bookId: id }, signal),
1552
+ request(key, "/book/bookmarklist", { bookId: id }, signal),
1553
+ reviews()
1554
+ ]);
1555
+ const cards = /* @__PURE__ */ new Map();
1556
+ const highlights = /* @__PURE__ */ new Map();
1557
+ for (const row of marks.updated) if (row.markText?.trim()) {
1558
+ const key2 = JSON.stringify([id, "bookmark", row.bookmarkId]);
1559
+ const card = { key: key2, type: "excerpt", quote: row.markText, sectionKey: row.chapterUid?.toString() };
1560
+ cards.set(key2, card);
1561
+ const position = positionKey(row);
1562
+ if (position !== void 0) highlights.set(position, card);
1563
+ }
1564
+ const reviewsById = new Map(notes.map(({ review }) => [review.reviewId, review]));
1565
+ for (const row of reviewsById.values()) if (row.abstract?.trim() || row.content?.trim()) {
1566
+ const position = positionKey(row);
1567
+ const highlight = position === void 0 ? void 0 : highlights.get(position);
1568
+ if (highlight) {
1569
+ if (row.content?.trim()) highlight.note = highlight.note ? highlight.note + "\n\n" + row.content : row.content;
1570
+ continue;
1571
+ }
1572
+ const key2 = JSON.stringify([id, "review", row.reviewId]);
1573
+ cards.set(key2, { key: key2, type: row.abstract?.trim() ? "excerpt" : "thought", quote: row.abstract || void 0, note: row.content, sectionKey: row.chapterUid?.toString() });
1574
+ }
1575
+ group.cards = [...cards.values()];
1576
+ group.chapters = outline(toc.chapters, group.cards, group.progress?.chapterUid);
1577
+ }
1578
+ const batch = { source: "weread", groups, links: [] };
1579
+ prepared = { key, plan: fingerprint, batch };
1580
+ return batch;
1581
+ }
1582
+ };
1583
+ }
1584
+ var weread = createWeRead();
1585
+
1318
1586
  // src/host/dictionary.ts
1319
1587
  import { execFile } from "node:child_process";
1320
1588
  var SCRIPT = `ObjC.import('CoreServices')
@@ -1390,8 +1658,8 @@ function streamFile(file, type) {
1390
1658
  return new Response(body, { headers: { "content-type": type, "content-length": String(size), "cache-control": "no-store" } });
1391
1659
  }
1392
1660
  function displayPath(path) {
1393
- const home = homedir2();
1394
- return path === home || path.startsWith(home + sep2) ? "~" + path.slice(home.length) : path;
1661
+ const home = homedir3();
1662
+ return path === home || path.startsWith(home + sep3) ? "~" + path.slice(home.length) : path;
1395
1663
  }
1396
1664
  function openExternal(target) {
1397
1665
  const child = process.platform === "darwin" ? spawn("open", [target], { detached: true, stdio: "ignore" }) : process.platform === "win32" ? spawn("cmd", ["/c", "start", "", target], { detached: true, stdio: "ignore", windowsHide: true }) : spawn("xdg-open", [target], { detached: true, stdio: "ignore" });
@@ -1452,6 +1720,7 @@ function createRoutes(store, active, memory = new Memory(store)) {
1452
1720
  }
1453
1721
  });
1454
1722
  return [
1723
+ route("POST", "weread-key", ({ body }) => json({ ok: true, saved: wereadKey(body.key, void 0, store.dir) })),
1455
1724
  route("GET", "palace", () => json({
1456
1725
  ok: true,
1457
1726
  rev: store.rev,
@@ -1501,8 +1770,8 @@ function createRoutes(store, active, memory = new Memory(store)) {
1501
1770
  return json({ ok: true, pages: texts, scanned });
1502
1771
  }),
1503
1772
  route("GET", "image", ({ url }) => {
1504
- const name2 = basename2(url.searchParams.get("name") ?? "");
1505
- const file = join5(store.imagesDir, name2);
1773
+ const name2 = basename3(url.searchParams.get("name") ?? "");
1774
+ const file = join6(store.imagesDir, name2);
1506
1775
  const type = IMAGE_TYPES[extname2(name2).toLowerCase()];
1507
1776
  if (name2 === "" || type === void 0 || !existsSync4(file)) return new Response("not found", { status: 404 });
1508
1777
  return streamFile(file, type);
@@ -1513,13 +1782,13 @@ function createRoutes(store, active, memory = new Memory(store)) {
1513
1782
  if (rel.startsWith("reader/")) {
1514
1783
  const name2 = rel.slice("reader/".length);
1515
1784
  if (!READER_SCRIPTS.includes(name2)) return new Response("not found", { status: 404 });
1516
- const response2 = streamFile(join5(vendorDir(), name2), "text/javascript; charset=utf-8");
1785
+ const response2 = streamFile(join6(vendorDir(), name2), "text/javascript; charset=utf-8");
1517
1786
  response2.headers.set("cache-control", "public, max-age=86400");
1518
1787
  return response2;
1519
1788
  }
1520
- const theme = /^themes\/[a-z][a-z0-9-]{0,30}\/(?:[a-z]+\/)?[A-Za-z0-9][A-Za-z0-9-]{0,60}\.(webp|png|svg|ttf|woff2)$/.exec(rel.split(sep2).join("/"));
1789
+ const theme = /^themes\/[a-z][a-z0-9-]{0,30}\/(?:[a-z]+\/)?[A-Za-z0-9][A-Za-z0-9-]{0,60}\.(webp|png|svg|ttf|woff2)$/.exec(rel.split(sep3).join("/"));
1521
1790
  if (theme !== null) {
1522
- const file2 = join5(vendorDir(), rel);
1791
+ const file2 = join6(vendorDir(), rel);
1523
1792
  if (!existsSync4(file2)) return new Response("not found", { status: 404 });
1524
1793
  const response2 = streamFile(file2, THEME_TYPES[theme[1]]);
1525
1794
  response2.headers.set("cache-control", "public, max-age=86400");
@@ -1527,15 +1796,15 @@ function createRoutes(store, active, memory = new Memory(store)) {
1527
1796
  }
1528
1797
  const font = /^fonts\/([a-z0-9][a-z0-9-]{0,60})\.woff2$/.exec(rel)?.[1];
1529
1798
  if (font !== void 0) {
1530
- const file2 = join5(vendorDir(), "fonts", `${font}.woff2`);
1799
+ const file2 = join6(vendorDir(), "fonts", `${font}.woff2`);
1531
1800
  if (!existsSync4(file2)) return new Response("not found", { status: 404 });
1532
1801
  const response2 = streamFile(file2, "font/woff2");
1533
1802
  response2.headers.set("cache-control", "public, max-age=31536000, immutable");
1534
1803
  return response2;
1535
1804
  }
1536
1805
  const allowed = ["cmaps", "standard_fonts", "wasm", "iccs"];
1537
- if (!allowed.some((dir) => rel.startsWith(dir + sep2)) || rel.includes("..")) return new Response("not found", { status: 404 });
1538
- const file = join5(pdfjsDistDir(), rel);
1806
+ if (!allowed.some((dir) => rel.startsWith(dir + sep3)) || rel.includes("..")) return new Response("not found", { status: 404 });
1807
+ const file = join6(pdfjsDistDir(), rel);
1539
1808
  if (!existsSync4(file)) return new Response("not found", { status: 404 });
1540
1809
  const response = streamFile(file, file.endsWith(".wasm") ? "application/wasm" : "application/octet-stream");
1541
1810
  response.headers.set("cache-control", "public, max-age=31536000, immutable");
@@ -1580,9 +1849,129 @@ function createRoutes(store, active, memory = new Memory(store)) {
1580
1849
  ];
1581
1850
  }
1582
1851
 
1583
- // src/host/tools.ts
1852
+ // src/host/harness/tools.ts
1584
1853
  import { defineTool } from "@deepseek-ai/dsh-tools";
1585
1854
 
1855
+ // src/core/import.ts
1856
+ import { createHash } from "node:crypto";
1857
+ var digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
1858
+ var stableId = (prefix, ...key) => `${prefix}_${digest(key).slice(0, 10)}`;
1859
+ async function importBatch(store, memory, batch, confirmation) {
1860
+ const palace = store.getPalace();
1861
+ const cells = new Map(palace.cells.map((cell) => [cell.id, cell]));
1862
+ const placed = /* @__PURE__ */ new Map();
1863
+ for (const cell of palace.cells) {
1864
+ if (cell.kind === "group") continue;
1865
+ for (const card of store.getItem(cell.id).cards) {
1866
+ if (card.importSource?.source === batch.source) placed.set(card.importSource.key, { cell, card });
1867
+ }
1868
+ }
1869
+ const newCells = /* @__PURE__ */ new Map();
1870
+ const outlines = /* @__PURE__ */ new Map();
1871
+ const progress = [];
1872
+ const progressWrites = /* @__PURE__ */ new Map();
1873
+ const selected = /* @__PURE__ */ new Map();
1874
+ const at = nowIso();
1875
+ for (const group of batch.groups) {
1876
+ const id = group.itemId ?? stableId("c", batch.source, group.key);
1877
+ let target = cells.get(id) ?? newCells.get(id);
1878
+ if (group.itemId !== void 0 && (target === void 0 || target.kind === "group")) throw new ShelfError("\u5BFC\u5165\u76EE\u6807\u5FC5\u987B\u662F\u5DF2\u6709\u7684\u4E66\u6216\u7B14\u8BB0\u683C\u5B50");
1879
+ if (target === void 0 && (group.kind === "book" || group.cards.some((card) => !placed.has(card.key)))) {
1880
+ target = { id, kind: group.kind ?? "note", title: group.title, href: group.href, parentId: null, col: 0, row: 0, createdAt: at };
1881
+ newCells.set(id, target);
1882
+ }
1883
+ if (target && group.chapters?.length && (newCells.has(id) || store.getItem(id).chapters.length === 0)) outlines.set(id, buildChapters(group.chapters));
1884
+ if (target?.kind === "book" && group.progress) {
1885
+ const { percent, finishedAt, chapterUid } = group.progress;
1886
+ const item = newCells.has(id) ? void 0 : store.getItem(id);
1887
+ const sections = (outlines.get(id) ?? item?.chapters ?? []).flatMap((chapter) => chapter.sections);
1888
+ const current = chapterUid === void 0 ? -1 : sections.findIndex((section) => section.loc === chapterUid);
1889
+ const mark = sections.slice(0, Math.max(0, current)).flatMap((section, index) => section.done ? [] : [index]);
1890
+ const loc = current < 0 ? "" : "weread:" + chapterUid;
1891
+ progress.push({ bookId: group.key, title: target.title, percent: Math.round(percent * 100), finished: (finishedAt ?? item?.finishedAt) !== void 0, markRead: mark.length });
1892
+ if (mark.length || item?.position?.loc !== loc || item.position.percent !== percent || finishedAt !== void 0 && item.finishedAt !== finishedAt) {
1893
+ progressWrites.set(id, { percent, finishedAt, loc, mark });
1894
+ }
1895
+ }
1896
+ for (const input of group.cards) {
1897
+ if (selected.has(input.key)) throw new ShelfError(`\u65B9\u6848\u91CC\u91CD\u590D\u51FA\u73B0\uFF1A${input.key}`);
1898
+ const previous = placed.get(input.key);
1899
+ if (previous && group.itemId !== void 0 && previous.cell.id !== group.itemId) throw new ShelfError(`\u5DF2\u5BFC\u5165\u7684\u7B14\u8BB0\u7559\u5728\u539F\u683C\u5B50\uFF1A${input.key}`);
1900
+ const content = digest(input.type === void 0 ? [input.note, input.frontmatter] : [input.type, input.note, input.quote, input.sectionKey]);
1901
+ const card = {
1902
+ ...previous?.card ?? { id: stableId("k", batch.source, input.key), type: "thought", createdAt: at },
1903
+ ...input.type !== void 0 ? { type: input.type, quote: input.quote } : {},
1904
+ note: previous?.card.importSource?.digest === content ? previous.card.note : input.note,
1905
+ importSource: { source: batch.source, key: input.key, digest: content, frontmatter: input.frontmatter }
1906
+ };
1907
+ selected.set(input.key, { cell: previous?.cell ?? target, card, previous: previous?.card, sectionKey: input.sectionKey });
1908
+ }
1909
+ }
1910
+ const links = [];
1911
+ const occurrences = /* @__PURE__ */ new Map();
1912
+ for (const link of batch.links) {
1913
+ const from = selected.get(link.from);
1914
+ const to = selected.get(link.to) ?? placed.get(link.to);
1915
+ if (!from || !to || from.cell.id === to.cell.id) continue;
1916
+ const pair = JSON.stringify([link.from, link.to]);
1917
+ const occurrence = (occurrences.get(pair) ?? 0) + 1;
1918
+ occurrences.set(pair, occurrence);
1919
+ const sourceKey = digest([batch.source, pair, occurrence, from.cell.id, to.cell.id]);
1920
+ links.push({ sourceKey, from: from.cell.id, to: to.cell.id, why: link.why, evidence: [from.card.id, to.card.id], fromPath: link.from, toPath: link.to });
1921
+ }
1922
+ const changed = [...selected.values()].filter(({ previous, card }) => previous?.importSource?.digest !== card.importSource?.digest);
1923
+ const { pending, arcs, strands } = memory.previewImportedLinks(
1924
+ links.map(({ sourceKey, from, to, why, evidence }) => ({ sourceKey, from, to, why, evidence }))
1925
+ );
1926
+ const summary = {
1927
+ cells: newCells.size,
1928
+ cards: changed.filter((x) => !x.previous).length,
1929
+ updatedCards: changed.filter((x) => x.previous).length,
1930
+ arcs,
1931
+ strands,
1932
+ ...progress.length ? { progress } : {}
1933
+ };
1934
+ const token = digest([batch, [...selected].map(([key, x]) => [key, x.cell.id, x.previous?.id]), links, pending, [...outlines.keys()], [...progressWrites], summary]);
1935
+ if (confirmation === void 0) return { preview: true, ...summary, token };
1936
+ if (confirmation !== token) throw new ShelfError("\u7B14\u8BB0\u3001\u65B9\u6848\u6216\u5BAB\u6BBF\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u9884\u89C8\u5E76\u786E\u8BA4");
1937
+ if (changed.length || newCells.size || outlines.size || progressWrites.size) {
1938
+ await store.mutate((tx) => {
1939
+ for (const cell of newCells.values()) {
1940
+ Object.assign(cell, firstEmptySlot(tx.palace, null));
1941
+ tx.palace.cells.push(cell);
1942
+ tx.createItem(emptyItem(cell.id, null));
1943
+ }
1944
+ for (const [id, chapters] of outlines) tx.item(id).chapters = chapters;
1945
+ for (const [id, { percent, finishedAt, loc, mark }] of progressWrites) {
1946
+ const item = tx.item(id);
1947
+ item.position = { loc, percent };
1948
+ if (finishedAt !== void 0) item.finishedAt = finishedAt;
1949
+ const sections = item.chapters.flatMap((chapter) => chapter.sections);
1950
+ for (const index of mark) {
1951
+ const section = sections[index];
1952
+ if (section && !section.done) Object.assign(section, { done: true, doneAt: at });
1953
+ }
1954
+ }
1955
+ for (const { cell, card, previous, sectionKey } of changed) {
1956
+ const item = tx.item(cell.id);
1957
+ if (sectionKey !== void 0) card.sectionId = item.chapters.flatMap((chapter) => chapter.sections).find((section) => section.loc === sectionKey)?.id;
1958
+ const { cards } = item;
1959
+ const index = previous === void 0 ? -1 : cards.findIndex((value) => value.id === previous.id);
1960
+ if (index === -1) cards.push(card);
1961
+ else cards[index] = card;
1962
+ }
1963
+ });
1964
+ }
1965
+ memory.addImportedLinks(pending);
1966
+ const active = new Set(memory.validLinks().map((link) => link.sourceKey));
1967
+ const pairs = /* @__PURE__ */ new Map();
1968
+ for (const { sourceKey, from, to, fromPath, toPath, evidence } of links) {
1969
+ if (active.has(sourceKey)) pairs.set([from, to].sort().join(":"), { from, to, fromPath, toPath, evidence });
1970
+ if (pairs.size === 20) break;
1971
+ }
1972
+ return { preview: false, ...summary, links: [...pairs.values()] };
1973
+ }
1974
+
1586
1975
  // src/core/tools.ts
1587
1976
  var KIND_LABEL = { book: "\u4E66", note: "\u7B14\u8BB0", group: "\u5206\u7EC4" };
1588
1977
  var CARD_LABEL = { excerpt: "\u6458\u5F55", thought: "\u60F3\u6CD5", mistake: "\u9519\u9898" };
@@ -1594,11 +1983,15 @@ function cellLine(store, c, active) {
1594
1983
  const pace = paceOf(item);
1595
1984
  const todo = item.cards.filter((k) => k.type === "mistake" && k.status === "todo").length;
1596
1985
  if (item.source !== null) line += ` \u539F\u6587 ${item.source.type}${item.source.type === "pdf" ? ` ${item.source.pageCount} \u9875` : ""}`;
1597
- if (p.total > 0) line += ` \u8FDB\u5EA6 ${p.done}/${p.total} \u8282`;
1986
+ const external = weReadPosition(item);
1987
+ if (external) {
1988
+ const chapter = item.chapters.findIndex((chapter2) => chapter2.sections.some((section) => "weread:" + section.loc === external.loc)) + 1;
1989
+ line += ` \u5DF2\u8BFB ${Math.round(external.percent * 100)}%${chapter ? `\uFF0C\u8BFB\u5230\u7B2C ${chapter} \u7AE0` : ""}\uFF08\u6765\u81EA\u5FAE\u4FE1\u8BFB\u4E66\uFF09`;
1990
+ } else if (p.total > 0) line += ` \u8FDB\u5EA6 ${p.done}/${p.total} \u8282`;
1598
1991
  else if (item.source?.type === "pdf") line += "\uFF08\u8FD8\u6CA1\u6709\u76EE\u5F55\uFF09";
1599
1992
  if (item.targetDate) line += ` \u76EE\u6807\u65E5\u671F ${item.targetDate}`;
1600
1993
  if (pace?.perDay !== void 0 && pace.remaining > 0) line += ` \u6BCF\u5929\u7EA6 ${pace.perDay} \u8282`;
1601
- if (p.current) line += ` \u5F53\u524D\uFF1A${p.current.chapter.title} \u203A ${p.current.section.title}`;
1994
+ if (!external && p.current) line += ` \u5F53\u524D\uFF1A${p.current.chapter.title} \u203A ${p.current.section.title}`;
1602
1995
  if (item.cards.length > 0) line += ` \u5361\u7247 ${item.cards.length} \u5F20${todo > 0 ? `\uFF08\u5F85\u91CD\u505A\u9519\u9898 ${todo}\uFF09` : ""}`;
1603
1996
  if (item.inspirations.length > 0) line += ` \u7075\u611F ${item.inspirations.length} \u6761`;
1604
1997
  }
@@ -1619,12 +2012,12 @@ function itemDetail(store, id) {
1619
2012
  const cell = store.getPalace().cells.find((c) => c.id === id);
1620
2013
  if (cell === void 0 || cell.kind === "group") throw new ShelfError("\u683C\u5B50\u4E0D\u5B58\u5728");
1621
2014
  const item = store.getItem(id);
1622
- const outline = item.chapters.length === 0 ? "\uFF08\u8FD8\u6CA1\u6709\u76EE\u5F55\uFF09" : item.chapters.map((c, i) => `${i + 1}. ${c.title}
2015
+ const outline2 = item.chapters.length === 0 ? "\uFF08\u8FD8\u6CA1\u6709\u76EE\u5F55\uFF09" : item.chapters.map((c, i) => `${i + 1}. ${c.title}
1623
2016
  ${c.sections.map((s) => ` - ${s.done ? "[x]" : "[ ]"} ${s.title} (section_id=${s.id})`).join("\n")}`).join("\n");
1624
2017
  const cards = item.cards.slice(-20).map((k) => `- ${CARD_LABEL[k.type]} ${k.id}\uFF1A${(k.quote ?? k.note ?? "").slice(0, 60)}`).join("\n");
1625
2018
  const insps = item.inspirations.slice(-10).map((i) => `- ${i.id} ${i.createdAt.slice(0, 10)} ${i.title}`).join("\n");
1626
2019
  return `\u300A${cell.title}\u300B\u76EE\u5F55\uFF1A
1627
- ${outline}` + (cards ? `
2020
+ ${outline2}` + (cards ? `
1628
2021
 
1629
2022
  \u6700\u8FD1\u7684\u5361\u7247\uFF1A
1630
2023
  ${cards}` : "") + (insps ? `
@@ -1644,10 +2037,10 @@ async function guard(run) {
1644
2037
  throw error;
1645
2038
  }
1646
2039
  }
1647
- function createOverviewTool(store) {
2040
+ function createOverviewTool(store, currentItem) {
1648
2041
  return {
1649
2042
  name: "palace_overview",
1650
- description: "\u67E5\u770B\u7528\u6237\u7684 Memory Palace\uFF08\u8BB0\u5FC6\u5BAB\u6BBF\uFF09\uFF1A\u6240\u6709\u5206\u7EC4\u3001\u4E66\u3001\u7B14\u8BB0\u7684 id\u3001\u8FDB\u5EA6\u3001\u5361\u7247\u6570\uFF0C\u4EE5\u53CA\u7528\u6237\u5F53\u524D\u6253\u5F00\u7684\u662F\u54EA\u4E2A\u683C\u5B50\u3002\u6D89\u53CA\u5BAB\u6BBF\u7684\u4EFB\u4F55\u64CD\u4F5C\u524D\u5148\u8C03\u7528\u5B83\u62FF\u5230 id\u3002\u4F20 item_id \u53EF\u67E5\u770B\u8FD9\u4E2A\u683C\u5B50\u7684\u5B8C\u6574\u76EE\u5F55\uFF08\u542B section_id\uFF09\u3001\u6700\u8FD1\u7684\u5361\u7247\u548C\u7075\u611F\u3002",
2043
+ description: "\u67E5\u770B\u7528\u6237\u7684 Memory Palace\uFF08\u8BB0\u5FC6\u5BAB\u6BBF\uFF09\uFF1A\u6240\u6709\u5206\u7EC4\u3001\u4E66\u3001\u7B14\u8BB0\u7684 id\u3001\u8FDB\u5EA6\u3001\u5361\u7247\u6570" + (currentItem ? "\uFF0C\u4EE5\u53CA\u7528\u6237\u5F53\u524D\u6253\u5F00\u7684\u662F\u54EA\u4E2A\u683C\u5B50" : "") + "\u3002\u6D89\u53CA\u5BAB\u6BBF\u7684\u4EFB\u4F55\u64CD\u4F5C\u524D\u5148\u8C03\u7528\u5B83\u62FF\u5230 id\u3002\u4F20 item_id \u53EF\u67E5\u770B\u8FD9\u4E2A\u683C\u5B50\u7684\u5B8C\u6574\u76EE\u5F55\uFF08\u542B section_id\uFF09\u3001\u6700\u8FD1\u7684\u5361\u7247\u548C\u7075\u611F\u3002",
1651
2044
  parameters: {
1652
2045
  item_id: { type: "string", description: "\u53EF\u9009\uFF1A\u67E5\u770B\u8FD9\u4E2A\u683C\u5B50\u7684\u8BE6\u60C5" }
1653
2046
  },
@@ -1657,11 +2050,12 @@ function createOverviewTool(store) {
1657
2050
  };
1658
2051
  }
1659
2052
  function createPalaceTools(store, memory, sources) {
2053
+ const itemId = sources.currentItem ? { type: "string" } : { type: "string", minLength: 1, required: true, description: "\u76EE\u6807\u683C\u5B50 id" };
1660
2054
  return [
1661
- createOverviewTool(store),
2055
+ createOverviewTool(store, sources.currentItem),
1662
2056
  {
1663
2057
  name: "palace_add",
1664
- description: "\u5F80\u5BAB\u6BBF\u91CC\u653E\u4E1C\u897F\u3002kind=group \u65B0\u5EFA\u5206\u7EC4\uFF08title\uFF09\uFF1Bkind=note \u65B0\u5EFA\u7B14\u8BB0\u683C\u5B50\uFF08title\uFF0C\u7528\u4E8E\u6CA1\u6709\u539F\u6587\u7684\u4E1C\u897F\uFF1A\u65E5\u8BB0\u3001\u5FC3\u60C5\u3001\u8FFD\u5267\uFF09\uFF1Bkind=book \u6DFB\u52A0 PDF / EPUB\uFF08path \u4E3A\u7EDD\u5BF9\u8DEF\u5F84\uFF09\u6216\u89C6\u9891\uFF08url\uFF0C\u5267\u3001\u7EFC\u827A\u3001\u8BFE\u90FD\u7B97\uFF09\uFF0C\u53EF\u9009 title\u3001subtitle\uFF08\u5907\u6CE8\uFF1A\u683C\u5B50\u4E0A\u6807\u9898\u4E0A\u65B9\u7684\u4E00\u884C\u5C0F\u5B57\uFF0C\u7528\u6237\u60F3\u586B\u4EC0\u4E48\u90FD\u884C\uFF0C\u5E38\u89C1\u662F\u4F5C\u8005\u6216\u53E6\u4E00\u79CD\u8BED\u8A00\u7684\u4E66\u540D\uFF09\u3002title \u7528\u4E66\u7684\u539F\u540D\uFF0C\u5927\u5C0F\u5199\u7167\u539F\u4E66\uFF08\u5982 Invention of Nature\uFF09\uFF0C\u4E0D\u5E26\u6587\u4EF6\u540D\u91CC\u7684 - _ \u300A\u300B \u7B49\u7B26\u53F7\uFF1B\u5916\u6587\u4E66\u53EF\u628A\u4E2D\u6587\u8BD1\u540D\u653E subtitle\u3001target_date\uFF08YYYY-MM-DD\uFF09\u3002parent_id \u586B\u5206\u7EC4 id \u53EF\u4EE5\u76F4\u63A5\u653E\u8FDB\u5206\u7EC4\uFF08\u5206\u7EC4\u91CC\u4E0D\u80FD\u518D\u653E\u5206\u7EC4\uFF09\u3002\u89C6\u9891\u94FE\u63A5\u6309\u5E73\u53F0\u5904\u7406\uFF1AB \u7AD9\uFF08\u5E26 BV \u53F7\u6216 b23.tv \u77ED\u94FE\uFF09\u76F4\u63A5\u4F20 url\uFF0C\u4F1A\u81EA\u52A8\u8BFB\u51FA\u5206 P / \u5408\u96C6\u548C\u6BCF\u4E00\u96C6\u7684\u94FE\u63A5\uFF0Ctitle \u53EF\u4E0D\u586B\uFF1BYouTube\uFF1A\u4F20 url \u548C\u89C6\u9891\u6216\u64AD\u653E\u5217\u8868\u7684\u6807\u9898\uFF1B\u5176\u4ED6\u5E73\u53F0\uFF08Netflix\u3001\u7231\u5947\u827A\u3001\u8292\u679C TV\u3001\u817E\u8BAF\u89C6\u9891\u3001\u8BFE\u7A0B\u7F51\u7AD9\u2026\u2026\uFF09\uFF1A\u4ECE\u94FE\u63A5\u548C\u7528\u6237\u7684\u8BDD\u8BA4\u51FA\u4F5C\u54C1\uFF0Ctitle \u7528\u4F5C\u54C1\u7684\u6B63\u5F0F\u540D\uFF0C\u4F20 url\u3002\u8FD9\u4E24\u7C7B\u5EFA\u597D\u540E\u5148\u505C\u4E0B\uFF1A\u544A\u8BC9\u7528\u6237\u5DF2\u7ECF\u653E\u8FDB\u6765\u4E86\uFF0C\u95EE\u8981\u4E0D\u8981\u4E0A\u7F51\u67E5\u5206\u96C6\u548C\u6BCF\u4E00\u96C6\u7684\u94FE\u63A5\uFF08\u8981\u82B1\u4E00\u4E24\u5206\u949F\uFF09\uFF1B\u7528\u6237\u5728\u539F\u8BDD\u91CC\u5DF2\u7ECF\u8981\u4E86\u76EE\u5F55\u5C31\u76F4\u63A5\u67E5\u3002\u67E5\u7684\u65F6\u5019\u5206\u5B63\u5C31\u4E00\u5B63\u4E00\u7AE0\uFF0C\u7528 palace_set_outline \u5199\u5165\uFF08\u6BCF\u96C6\u5C3D\u91CF\u5E26 url\uFF09\uFF1B\u8FDE\u8F7D\u4E2D\u7684\u53EA\u5199\u5DF2\u7ECF\u67E5\u5B9E\u7684\u96C6\u6570\uFF0C\u67E5\u4E0D\u5230\u94FE\u63A5\u5C31\u53EA\u5199\u6807\u9898\u3002\u540C\u6837\u7684\u89C4\u77E9\u9002\u7528\u4E8E\u4EFB\u4F55\u8981\u82B1\u65F6\u95F4\u7684\u8865\u5168\uFF08\u4E0A\u7F51\u67E5\u76EE\u5F55\u3001\u8BFB\u5F88\u591A\u9875\u2026\u2026\uFF09\uFF1A\u5148\u5EFA\u683C\u5B50\uFF0C\u518D\u95EE\u7528\u6237\uFF1B\u51E0\u79D2\u5185\u5C31\u80FD\u5B8C\u6210\u7684\uFF08B \u7AD9\u63A5\u53E3\u3001PDF \u4E66\u7B7E\u3001EPUB \u76EE\u5F55\uFF09\u7167\u65E7\u81EA\u52A8\u505A\u3002\u6CA1\u6709\u539F\u6587\u3001\u4E5F\u4E0D\u9700\u8981\u6309\u96C6\u6253\u52FE\u7684\uFF08\u6BD4\u5982\u53EA\u662F\u60F3\u804A\u4E00\u90E8\u5267\uFF09\uFF0C\u7528 kind=note\u3002",
2058
+ description: "\u5F80\u5BAB\u6BBF\u91CC\u653E\u4E1C\u897F\u3002kind=group \u65B0\u5EFA\u5206\u7EC4\uFF08title\uFF09\uFF1Bkind=note \u65B0\u5EFA\u7B14\u8BB0\u683C\u5B50\uFF08title\uFF0C\u7528\u4E8E\u6CA1\u6709\u539F\u6587\u7684\u4E1C\u897F\uFF1A\u65E5\u8BB0\u3001\u5FC3\u60C5\u3001\u8FFD\u5267\uFF09\uFF1Bkind=book \u6DFB\u52A0 PDF / EPUB\uFF08path \u4E3A\u7EDD\u5BF9\u8DEF\u5F84\uFF09\u6216\u89C6\u9891\uFF08url\uFF0C\u5267\u3001\u7EFC\u827A\u3001\u8BFE\u90FD\u7B97\uFF09\uFF0C\u53EF\u9009 title\u3001subtitle\uFF08\u5907\u6CE8\uFF1A\u683C\u5B50\u4E0A\u6807\u9898\u4E0A\u65B9\u7684\u4E00\u884C\u5C0F\u5B57\uFF0C\u7528\u6237\u60F3\u586B\u4EC0\u4E48\u90FD\u884C\uFF0C\u5E38\u89C1\u662F\u4F5C\u8005\u6216\u53E6\u4E00\u79CD\u8BED\u8A00\u7684\u4E66\u540D\uFF09\u3002title \u7528\u4E66\u7684\u539F\u540D\uFF0C\u5927\u5C0F\u5199\u7167\u539F\u4E66\uFF08\u5982 Invention of Nature\uFF09\uFF0C\u4E0D\u5E26\u6587\u4EF6\u540D\u91CC\u7684 - _ \u300A\u300B \u7B49\u7B26\u53F7\uFF1B\u5916\u6587\u4E66\u53EF\u628A\u4E2D\u6587\u8BD1\u540D\u653E subtitle\u3001target_date\uFF08YYYY-MM-DD\uFF09\u3002parent_id \u586B\u5206\u7EC4 id \u53EF\u4EE5\u76F4\u63A5\u653E\u8FDB\u5206\u7EC4\uFF08\u5206\u7EC4\u91CC\u4E0D\u80FD\u518D\u653E\u5206\u7EC4\uFF09\u3002" + sources.videoHelp,
1665
2059
  parameters: {
1666
2060
  kind: { type: "string", enum: ["group", "note", "book"], required: true },
1667
2061
  title: { type: "string" },
@@ -1723,7 +2117,7 @@ ${t.text || "\uFF08\u65E0\u6587\u5B57\uFF09"}`).join("\n\n");
1723
2117
  if (scanned.length > 0) {
1724
2118
  out += `
1725
2119
 
1726
- \u6CE8\u610F\uFF1A\u7B2C ${scanned.join("\u3001")} \u9875\u6CA1\u6709\u6587\u5B57\u5C42\uFF08\u53EF\u80FD\u662F\u626B\u63CF\u4EF6\uFF09\u3002\u5982\u679C\u5BF9\u8BDD\u91CC\u9644\u6709\u8FD9\u4E9B\u9875\u7684\u56FE\u7247\uFF0C\u8BF7\u76F4\u63A5\u770B\u56FE\u8BC6\u522B\uFF1B\u5426\u5219\u8BF7\u7528\u6237\u5728\u53F3\u4FA7\u7B14\u8BB0\u672C\u91CC\u91CD\u65B0\u52FE\u9009\u8FD9\u4E9B\u9875\uFF08\u4F1A\u628A\u9875\u9762\u56FE\u7247\u53D1\u5230\u5BF9\u8BDD\uFF09\u3002`;
2120
+ \u6CE8\u610F\uFF1A\u7B2C ${scanned.join("\u3001")} \u9875\u6CA1\u6709\u6587\u5B57\u5C42\uFF08\u53EF\u80FD\u662F\u626B\u63CF\u4EF6\uFF09\u3002\u5982\u679C\u5BF9\u8BDD\u91CC\u9644\u6709\u8FD9\u4E9B\u9875\u7684\u56FE\u7247\uFF0C\u8BF7\u76F4\u63A5\u770B\u56FE\u8BC6\u522B\uFF1B` + sources.scannedPageHelp;
1727
2121
  }
1728
2122
  return out;
1729
2123
  });
@@ -1808,14 +2202,14 @@ ${lines.join("\n")}`;
1808
2202
  },
1809
2203
  {
1810
2204
  name: "palace_add_card",
1811
- description: "\u8BB0\u4E00\u5F20\u5361\u7247\u3002type=mistake \u9519\u9898\uFF1A\u7528\u6237\u53D1\u6765\u9519\u9898\u622A\u56FE\u5E76\u8BF4\u300C\u8BB0\u9519\u9898\u300D\u65F6\u8C03\u7528\uFF0C\u5148\u770B\u56FE\u628A\u9898\u76EE\u5B8C\u6574\u8F6C\u6210\u6587\u5B57\u5199\u8FDB quote\uFF08\u542B\u9009\u9879\uFF09\uFF0C\u80FD\u5224\u65AD\u7684\u8BDD\u628A\u7B54\u6848\u548C\u89E3\u6790\u5199\u8FDB answer\uFF1Btype=excerpt \u6458\u5F55\uFF1Aquote \u662F\u539F\u6587\uFF0Cnote \u662F\u7528\u6237\u7684\u60F3\u6CD5\uFF1Btype=thought \u60F3\u6CD5\uFF1A\u53EA\u6709 note\u3002image \u586B\u5BF9\u8BDD\u91CC\u56FE\u7247\u7684\u672C\u5730\u53EA\u8BFB\u8DEF\u5F84\uFF08\u56FE\u7247\u8BF4\u660E\u4E2D\u7684 read-only path\uFF09\uFF0C\u6CA1\u6709\u8DEF\u5F84\u5C31\u586B\u9644\u4EF6 id\uFF08sha256:...\uFF09\u3002item_id \u4E0D\u586B\u65F6\u8BB0\u5230\u7528\u6237\u5F53\u524D\u6253\u5F00\u7684\u683C\u5B50\uFF1Bsection_id \u4E0D\u586B\u65F6\uFF0C\u6458\u5F55\u548C\u9519\u9898\u9ED8\u8BA4\u6302\u5230\u5F53\u524D\u5728\u5B66\u7684\u90A3\u4E00\u8282\u3002",
2205
+ description: "\u8BB0\u4E00\u5F20\u5361\u7247\u3002type=mistake \u9519\u9898\uFF1A\u7528\u6237\u53D1\u6765\u9519\u9898\u622A\u56FE\u5E76\u8BF4\u300C\u8BB0\u9519\u9898\u300D\u65F6\u8C03\u7528\uFF0C\u5148\u770B\u56FE\u628A\u9898\u76EE\u5B8C\u6574\u8F6C\u6210\u6587\u5B57\u5199\u8FDB quote\uFF08\u542B\u9009\u9879\uFF09\uFF0C\u80FD\u5224\u65AD\u7684\u8BDD\u628A\u7B54\u6848\u548C\u89E3\u6790\u5199\u8FDB answer\uFF1Btype=excerpt \u6458\u5F55\uFF1Aquote \u662F\u539F\u6587\uFF0Cnote \u662F\u7528\u6237\u7684\u60F3\u6CD5\uFF1Btype=thought \u60F3\u6CD5\uFF1A\u53EA\u6709 note\u3002" + sources.imageHelp + (sources.currentItem ? "item_id \u4E0D\u586B\u65F6\u8BB0\u5230\u7528\u6237\u5F53\u524D\u6253\u5F00\u7684\u683C\u5B50\uFF1B" : "item_id \u586B\u76EE\u6807\u683C\u5B50 id\uFF1B") + "section_id \u4E0D\u586B\u65F6\uFF0C\u6458\u5F55\u548C\u9519\u9898\u9ED8\u8BA4\u6302\u5230\u5F53\u524D\u5728\u5B66\u7684\u90A3\u4E00\u8282\u3002",
1812
2206
  parameters: {
1813
2207
  type: { type: "string", enum: ["mistake", "excerpt", "thought"], required: true },
1814
2208
  quote: { type: "string", description: "\u539F\u6587\u6216\u9898\u76EE" },
1815
2209
  note: { type: "string", description: "\u60F3\u6CD5\u3001\u6279\u6CE8\u6216\u9519\u56E0\uFF08\u7528\u6237\u8BF4\u4E86\u624D\u586B\uFF09" },
1816
2210
  answer: { type: "string", description: "\u9519\u9898\u7684\u7B54\u6848\u4E0E\u89E3\u6790" },
1817
- image: { type: "string", description: "\u622A\u56FE\u7684\u672C\u5730\u8DEF\u5F84\u6216\u9644\u4EF6 id" },
1818
- item_id: { type: "string" },
2211
+ image: { type: "string", description: sources.imageDescription },
2212
+ item_id: itemId,
1819
2213
  section_id: { type: "string" }
1820
2214
  },
1821
2215
  async execute(args, options) {
@@ -1832,11 +2226,11 @@ ${lines.join("\n")}`;
1832
2226
  },
1833
2227
  {
1834
2228
  name: "palace_add_inspiration",
1835
- description: "\u628A\u8FD9\u6B21\u5BF9\u8BDD\u5B58\u6210\u4E00\u6761\u300C\u7075\u611F\u300D\uFF1A\u7528\u6237\u8BF4\u300C\u5B58\u6210\u7075\u611F\u300D\u300C\u8BB0\u4E0B\u6765\u300D\u4E4B\u7C7B\u65F6\u8C03\u7528\u3002\u7528\u7528\u6237\u7684\u53E3\u543B\u3001\u7B80\u6D01\u5730\u603B\u7ED3\u8FD9\u6B21\u5BF9\u8BDD\u91CC\u7528\u6237\u7684\u60F3\u6CD5\u548C\u5F97\u51FA\u7684\u7ED3\u8BBA\uFF08\u4E0D\u662F\u590D\u8FF0 AI \u8BF4\u4E86\u4EC0\u4E48\uFF09\uFF0Cbody \u7528 Markdown\uFF0C\u51E0\u6BB5\u5373\u53EF\uFF1Btitle \u4E00\u53E5\u8BDD\u70B9\u9898\u3002item_id \u4E0D\u586B\u65F6\u5B58\u5230\u7528\u6237\u5F53\u524D\u6253\u5F00\u7684\u683C\u5B50\u3002",
2229
+ description: "\u628A\u8FD9\u6B21\u5BF9\u8BDD\u5B58\u6210\u4E00\u6761\u300C\u7075\u611F\u300D\uFF1A\u7528\u6237\u8BF4\u300C\u5B58\u6210\u7075\u611F\u300D\u300C\u8BB0\u4E0B\u6765\u300D\u4E4B\u7C7B\u65F6\u8C03\u7528\u3002\u7528\u7528\u6237\u7684\u53E3\u543B\u3001\u7B80\u6D01\u5730\u603B\u7ED3\u8FD9\u6B21\u5BF9\u8BDD\u91CC\u7528\u6237\u7684\u60F3\u6CD5\u548C\u5F97\u51FA\u7684\u7ED3\u8BBA\uFF08\u4E0D\u662F\u590D\u8FF0 AI \u8BF4\u4E86\u4EC0\u4E48\uFF09\uFF0Cbody \u7528 Markdown\uFF0C\u51E0\u6BB5\u5373\u53EF\uFF1Btitle \u4E00\u53E5\u8BDD\u70B9\u9898\u3002" + (sources.currentItem ? "item_id \u4E0D\u586B\u65F6\u5B58\u5230\u7528\u6237\u5F53\u524D\u6253\u5F00\u7684\u683C\u5B50\u3002" : "item_id \u5FC5\u987B\u586B\u76EE\u6807\u683C\u5B50 id\u3002"),
1836
2230
  parameters: {
1837
2231
  title: { type: "string", required: true },
1838
2232
  body: { type: "string", required: true },
1839
- item_id: { type: "string" },
2233
+ item_id: itemId,
1840
2234
  card_ids: { type: "array", items: { type: "string" }, description: "\u53EF\u9009\uFF1A\u8FD9\u6B21\u5BF9\u8BDD\u6D89\u53CA\u7684\u5361\u7247" }
1841
2235
  },
1842
2236
  async execute(args, options) {
@@ -1850,7 +2244,7 @@ ${lines.join("\n")}`;
1850
2244
  },
1851
2245
  {
1852
2246
  name: "palace_wiki_read",
1853
- description: "\u8BFB\u4E00\u9875\u8BB0\u5FC6\uFF1Atarget \u586B\u683C\u5B50 id \u8BFB\u8FD9\u4E00\u683C\u7684 wiki\uFF08\u4E00\u53E5\u8BDD\u3001\u4E3B\u9898\u8BCD\u3001\u6B63\u6587\uFF09\uFF0C\u586B me \u8BFB\u300C\u5173\u4E8E\u7528\u6237\u300D\u3002\u5F53\u524D\u683C\u5B50\u548C me \u5DF2\u7ECF\u5728\u5BF9\u8BDD\u80CC\u666F\u91CC\uFF0C\u8BFB\u522B\u7684\u683C\u5B50\u65F6\u624D\u9700\u8981\u8C03\u7528\u3002",
2247
+ description: "\u8BFB\u4E00\u9875\u8BB0\u5FC6\uFF1Atarget \u586B\u683C\u5B50 id \u8BFB\u8FD9\u4E00\u683C\u7684 wiki\uFF08\u4E00\u53E5\u8BDD\u3001\u4E3B\u9898\u8BCD\u3001\u6B63\u6587\uFF09\uFF0C\u586B me \u8BFB\u300C\u5173\u4E8E\u7528\u6237\u300D\u3002" + sources.wikiReadHelp,
1854
2248
  parameters: {
1855
2249
  target: { type: "string", required: true, description: "\u683C\u5B50 id \u6216 me" }
1856
2250
  },
@@ -1895,16 +2289,21 @@ ${page.body}`;
1895
2289
  },
1896
2290
  {
1897
2291
  name: "palace_link",
1898
- description: "\u5728\u4E24\u683C\u4E4B\u95F4\u8FDE\u4E00\u6761\u7535\u5F27\uFF08\u8054\u60F3\uFF09\uFF1A\u7528\u6237\u7684\u67D0\u4E2A\u60F3\u6CD5\u3001\u4E3B\u9898\u6216\u7591\u95EE\u628A\u8FD9\u4E24\u683C\u8FDE\u5728\u4E00\u8D77\u65F6\u8C03\u7528\u3002\u4E0D\u9700\u8981\u4E24\u672C\u4E66\u4E92\u76F8\u63D0\u53CA\uFF0C\u8FDE\u7684\u662F\u7528\u6237\u7684\u5FF5\u5934\u3002why \u4E00\u53E5\u8BDD\u8BF4\u6E05\u8FDE\u5728\u54EA\uFF08\u226440 \u5B57\uFF0C\u4F8B\u5982\u300C\u90FD\u5728\u5199\u7B49\u5F85\uFF1A\u76D6\u8328\u6BD4\u7B49\u7EFF\u706F\uFF0C\u4F60\u5728\u7B49 offer\u300D\uFF09\uFF1Bevidence \u586B\u4E24\u7AEF\u5404\u81F3\u5C11\u4E00\u5F20\u5361\u7247\u6216\u4E00\u6761\u7075\u611F\u7684 id\u3002\u540C\u6837\u7684\u8BC1\u636E\u4E0D\u80FD\u91CD\u590D\u8FDE\uFF1B\u6709\u65B0\u8BC1\u636E\u5C31\u518D\u8FDE\u4E00\u6761\uFF0C\u7535\u5F27\u4F1A\u53D8\u7C97\u3002\u7528\u6237\u526A\u65AD\u8FC7\u7684\u4E24\u683C\uFF0C\u9664\u975E\u7528\u6237\u660E\u786E\u8981\u6C42\uFF0C\u5426\u5219\u4E0D\u8981\u518D\u8FDE\u3002",
2292
+ description: "\u5728\u4E24\u683C\u4E4B\u95F4\u8FDE\u4E00\u6761\u7535\u5F27\uFF08\u8054\u60F3\uFF09\uFF1A\u7528\u6237\u7684\u67D0\u4E2A\u60F3\u6CD5\u3001\u4E3B\u9898\u6216\u7591\u95EE\u628A\u8FD9\u4E24\u683C\u8FDE\u5728\u4E00\u8D77\u65F6\u8C03\u7528\u3002\u4E0D\u9700\u8981\u4E24\u672C\u4E66\u4E92\u76F8\u63D0\u53CA\uFF0C\u8FDE\u7684\u662F\u7528\u6237\u7684\u5FF5\u5934\u3002why \u4E00\u53E5\u8BDD\u8BF4\u6E05\u8FDE\u5728\u54EA\uFF08\u226440 \u5B57\uFF0C\u4F8B\u5982\u300C\u90FD\u5728\u5199\u7B49\u5F85\uFF1A\u76D6\u8328\u6BD4\u7B49\u7EFF\u706F\uFF0C\u4F60\u5728\u7B49 offer\u300D\uFF09\uFF1Bevidence \u586B\u4E24\u7AEF\u5404\u81F3\u5C11\u4E00\u5F20\u5361\u7247\u6216\u4E00\u6761\u7075\u611F\u7684 id\u3002\u540C\u6837\u7684\u8BC1\u636E\u4E0D\u80FD\u91CD\u590D\u8FDE\uFF1B\u6709\u65B0\u8BC1\u636E\u5C31\u518D\u8FDE\u4E00\u6761\uFF0C\u7535\u5F27\u4F1A\u53D8\u7C97\u3002\u7528\u6237\u526A\u65AD\u8FC7\u7684\u4E24\u683C\uFF0C\u9664\u975E\u7528\u6237\u660E\u786E\u8981\u6C42\uFF0C\u5426\u5219\u4E0D\u8981\u518D\u8FDE\u3002\u53EA\u6539\u5DF2\u6709\u7535\u5F27\u7684\u9898\u8BCD\u65F6\u586B update_why=true\uFF0Cwhy \u4ECE\u4E24\u7AEF\u539F\u6587\u6458\u53D6\uFF0C\u7701\u7565 evidence\u3002",
1899
2293
  parameters: {
1900
2294
  from: { type: "string", required: true, description: "\u683C\u5B50 id" },
1901
2295
  to: { type: "string", required: true, description: "\u683C\u5B50 id" },
1902
2296
  why: { type: "string", required: true },
1903
- evidence: { type: "array", items: { type: "string" }, required: true, description: "\u5361\u7247 / \u7075\u611F id" },
2297
+ evidence: { type: "array", items: { type: "string" }, description: "\u8FDE\u7EBF\u5FC5\u586B\uFF1A\u5361\u7247 / \u7075\u611F id" },
2298
+ update_why: { type: "boolean", description: "\u53EA\u66F4\u65B0\u73B0\u6709\u7535\u5F27\u7684\u9898\u8BCD" },
1904
2299
  user_asked: { type: "boolean", description: "\u7528\u6237\u660E\u786E\u8981\u6C42\u8FDE\uFF08\u526A\u65AD\u8FC7\u7684\u4E5F\u80FD\u91CD\u8FDE\uFF09" }
1905
2300
  },
1906
2301
  async execute(args, options) {
1907
2302
  return guard(async () => {
2303
+ if (args.update_why === true) {
2304
+ memory.retitleLink({ from: args.from, to: args.to, why: args.why });
2305
+ return "\u5DF2\u66F4\u65B0\u7535\u5F27\u9898\u8BCD\u3002";
2306
+ }
1908
2307
  const link = memory.addLink({ from: args.from, to: args.to, why: args.why, evidence: args.evidence, ...options.attribution, userAsked: args.user_asked === true });
1909
2308
  const cells = store.getPalace().cells;
1910
2309
  const arc = memory.arcs().find((a) => a.links.some((l) => l.id === link.id));
@@ -1928,8 +2327,246 @@ ${page.body}`;
1928
2327
  }
1929
2328
  ];
1930
2329
  }
2330
+ function createObsidianTools(store, memory, source) {
2331
+ const path = { type: "string", required: true, description: "\u7528\u6237\u63D0\u4F9B\u7684\u7B14\u8BB0\u5E93\u6587\u4EF6\u5939\u7EDD\u5BF9\u8DEF\u5F84" };
2332
+ return [
2333
+ {
2334
+ name: "palace_scan_obsidian",
2335
+ description: "\u53EA\u8BFB\u626B\u63CF Obsidian \u7B14\u8BB0\u5E93\u3002\u5411\u7528\u6237\u8BE2\u95EE\u8DEF\u5F84\u540E\u8C03\u7528\uFF0C\u6309\u6587\u4EF6\u5939\u7EDF\u8BA1\u7BC7\u6570\u3001\u6807\u7B7E\u548C\u53EF\u89E3\u6790\u53CC\u94FE\uFF0C\u6BCF\u9875\u5217\u51FA\u6700\u591A 100 \u7BC7\u3002\u548C\u7528\u6237\u5546\u91CF\u5206\u683C\u65B9\u6848\u540E\u518D\u9884\u89C8\u3002",
2336
+ parameters: { path, offset: { type: "integer", description: "\u4E0B\u4E00\u9875\u8D77\u70B9\uFF0C\u4F7F\u7528\u4E0A\u6B21\u8FD4\u56DE\u7684 nextOffset" } },
2337
+ async execute(args, options) {
2338
+ return guard(async () => JSON.stringify(await source.scan(args.path, args.offset, options.signal)));
2339
+ }
2340
+ },
2341
+ {
2342
+ name: "palace_import_obsidian",
2343
+ description: "\u5BFC\u5165 Obsidian \u7B14\u8BB0\u3002plan \u7701\u7565\u65F6\u6309\u6587\u4EF6\u5939\u5EFA\u683C\uFF1B\u6241\u5E73\u7B14\u8BB0\u5E93\u6309\u6807\u7B7E\u548C\u53CC\u94FE\u5546\u91CF\u5206\u683C\u3002plan \u6BCF\u4E2A\u76EE\u6807\u7528 paths \u6216 tags \u9009\u7B14\u8BB0\uFF0C\u4E8C\u9009\u4E00\uFF0C\u518D\u6307\u5B9A\u65B0\u683C\u5B50\u6807\u9898\u6216\u5DF2\u6709\u683C\u5B50 id\u3002\u5148\u7701\u7565 confirmation \u83B7\u53D6\u65B0\u589E\u683C\u5B50\u3001\u5361\u7247\u548C\u7535\u5F27\u7684\u9884\u89C8\uFF0C\u5411\u7528\u6237\u590D\u8FF0\u5E76\u7B49\u786E\u8BA4\uFF0C\u518D\u7528\u76F8\u540C\u65B9\u6848\u548C\u9884\u89C8\u7684 token \u8C03\u7528\u3002\u53CC\u94FE\u81EA\u52A8\u8FDE\u7EBF\u3002\u5BFC\u5165\u540E\u6309\u7ED3\u679C\u91CC\u7684\u4E24\u7AEF\u7B14\u8BB0\u8DEF\u5F84\u8BFB\u539F\u6587\uFF0C\u5FC5\u8981\u65F6\u7528 palace_link \u7684 update_why \u6539\u987A\u9898\u8BCD\u3002",
2344
+ parameters: {
2345
+ path,
2346
+ plan: {
2347
+ type: "array",
2348
+ items: { type: "object", additionalProperties: false, properties: {
2349
+ title: { type: "string", description: "\u65B0\u7B14\u8BB0\u683C\u5B50\u6807\u9898" },
2350
+ item_id: { type: "string", description: "\u5DF2\u6709\u4E66\u6216\u7B14\u8BB0\u683C\u5B50 id" },
2351
+ paths: { type: "array", items: { type: "string" }, description: "\u626B\u63CF\u8FD4\u56DE\u7684\u7B14\u8BB0\u76F8\u5BF9\u8DEF\u5F84" },
2352
+ tags: { type: "array", items: { type: "string" }, description: "\u626B\u63CF\u8FD4\u56DE\u7684\u6807\u7B7E\uFF0C\u5339\u914D\u5176\u4E2D\u4EFB\u610F\u4E00\u4E2A\u5C31\u9009\u5165" }
2353
+ } }
2354
+ },
2355
+ confirmation: { type: "string", description: "\u4EC5\u5728\u7528\u6237\u786E\u8BA4\u540E\u4F20\u5165\u9884\u89C8\u8FD4\u56DE\u7684 token" }
2356
+ },
2357
+ async execute(args, options) {
2358
+ return guard(async () => {
2359
+ if (args.confirmation !== void 0 && typeof args.confirmation !== "string") throw new ShelfError("\u786E\u8BA4\u503C\u5FC5\u987B\u662F\u9884\u89C8\u8FD4\u56DE\u7684 token");
2360
+ const batch = await source.prepare(args.path, args.plan, options.signal);
2361
+ options.signal?.throwIfAborted();
2362
+ return JSON.stringify(await importBatch(store, memory, batch, args.confirmation));
2363
+ });
2364
+ }
2365
+ }
2366
+ ];
2367
+ }
2368
+ function createWeReadTools(store, memory, source) {
2369
+ const importedBooks = () => {
2370
+ const ids = new Set(store.getPalace().cells.filter((cell) => cell.kind === "book").map((cell) => cell.id));
2371
+ return (bookId) => ids.has(stableId("c", "weread", bookId));
2372
+ };
2373
+ return [
2374
+ {
2375
+ name: "palace_scan_weread",
2376
+ description: "\u67E5\u770B\u5FAE\u4FE1\u8BFB\u4E66\u4E66\u67B6\u53CA\u7B14\u8BB0\u3002\u540C\u6B65\u6216\u518D\u6B21\u4ECE\u5165\u53E3\u5BFC\u5165\u65F6\uFF0C\u9ED8\u8BA4\u9884\u89C8\u5DF2\u5BFC\u5165\u7684\u4E66\uFF1B\u6709\u7B14\u8BB0\u4F46\u672A\u5BFC\u5165\u7684\u4E66\u53EA\u63D0\u793A\uFF0C\u7528\u6237\u660E\u786E\u9009\u4E2D\u624D\u5BFC\u5165\u3002",
2377
+ parameters: {},
2378
+ async execute(_args, { signal }) {
2379
+ return guard(async () => JSON.stringify(await source.scan(signal, importedBooks())));
2380
+ }
2381
+ },
2382
+ {
2383
+ name: "palace_import_weread",
2384
+ description: "\u5BFC\u5165\u6216\u540C\u6B65\u5FAE\u4FE1\u8BFB\u4E66\u3002\u540C\u6B65\u5148\u626B\u63CF\uFF0C\u7701\u7565 plan \u9ED8\u8BA4\u540C\u6B65\u5DF2\u5BFC\u5165\u7684\u4E66\uFF1B\u660E\u786E\u9009\u4E66\u624D\u4F20 bookId \u5217\u8868\u3002\u5148\u7701\u7565 confirmation\uFF0C\u5411\u7528\u6237\u8BF4\u660E\u65B0\u589E\u3001\u66F4\u65B0\u7684\u5361\u7247\u6570\u3001\u9605\u8BFB\u767E\u5206\u6BD4\u548C\u5C06\u6807\u8BB0\u4E3A\u5DF2\u8BFB\u7684\u8282\u6570\uFF08markRead\uFF09\uFF1B\u7528\u6237\u786E\u8BA4\u540E\u7528\u540C\u4E00\u65B9\u6848\u548C\u9884\u89C8 token \u5199\u5165\u3002",
2385
+ parameters: {
2386
+ plan: { type: "array", items: { type: "string" } },
2387
+ confirmation: { type: "string" }
2388
+ },
2389
+ async execute({ plan, confirmation }, { signal }) {
2390
+ return guard(async () => {
2391
+ if (confirmation !== void 0 && typeof confirmation !== "string") throw new ShelfError("\u8BF7\u4F7F\u7528\u9884\u89C8\u8FD4\u56DE\u7684 token");
2392
+ const batch = await source.prepare(plan, confirmation !== void 0, signal, importedBooks());
2393
+ if (signal?.aborted) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u5BFC\u5165\u5DF2\u53D6\u6D88");
2394
+ return JSON.stringify(await importBatch(store, memory, batch, confirmation));
2395
+ });
2396
+ }
2397
+ }
2398
+ ];
2399
+ }
1931
2400
 
1932
- // src/host/tools.ts
2401
+ // src/host/obsidian.ts
2402
+ import { createHash as createHash2 } from "node:crypto";
2403
+ import { constants } from "node:fs";
2404
+ import { open as open2, readdir, realpath, stat } from "node:fs/promises";
2405
+ import { isAbsolute as isAbsolute3, join as join7, posix } from "node:path";
2406
+ function withTitle(note, filename, raw) {
2407
+ const opening = note.replace(/^(?:\uFEFF)?(?:[ \t]*\r?\n)*/, "");
2408
+ if (/^ {0,3}#{1,6}(?:[ \t]|\r?\n|$)/.test(opening) || /^ {0,3}\S[^\r\n]*\r?\n {0,3}(?:=+|-+)[ \t]*(?:\r?\n|$)/.test(opening)) return note;
2409
+ const title = posix.basename(filename).replace(/\.md$/i, "").replace(/[\r\n]+/g, " ");
2410
+ const newline = raw.match(/\r?\n/)?.[0] ?? "\n";
2411
+ return `# ${title}${newline}${newline}${note}`;
2412
+ }
2413
+ async function readVault(path, signal) {
2414
+ if (typeof path !== "string" || !isAbsolute3(expandHome(path))) throw new ShelfError("\u8BF7\u63D0\u4F9B Obsidian \u7B14\u8BB0\u5E93\u7684\u7EDD\u5BF9\u8DEF\u5F84");
2415
+ const notes = [];
2416
+ const references = [];
2417
+ let root;
2418
+ try {
2419
+ root = await realpath(expandHome(path));
2420
+ if (!(await stat(root)).isDirectory()) throw new ShelfError("\u8BF7\u9009\u62E9 Obsidian \u7B14\u8BB0\u5E93\u6587\u4EF6\u5939");
2421
+ async function walk(folder) {
2422
+ signal?.throwIfAborted();
2423
+ const entries = await readdir(join7(root, folder), { withFileTypes: true });
2424
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
2425
+ signal?.throwIfAborted();
2426
+ if (entry.name.startsWith(".")) continue;
2427
+ const key = posix.join(folder, entry.name);
2428
+ if (entry.isDirectory()) {
2429
+ await walk(key);
2430
+ continue;
2431
+ }
2432
+ if (!entry.isFile() || !/\.md$/i.test(entry.name)) continue;
2433
+ const file = await open2(join7(root, key), constants.O_RDONLY | constants.O_NOFOLLOW);
2434
+ let raw;
2435
+ try {
2436
+ raw = await file.readFile({ encoding: "utf8", signal });
2437
+ } finally {
2438
+ await file.close();
2439
+ }
2440
+ const header = /^(?:\uFEFF)?---[ \t]*\r?\n[\s\S]*?^---[ \t]*(?:\r?\n|$)/m.exec(raw);
2441
+ const frontmatter = header?.index === 0 ? header[0] : void 0;
2442
+ const note = raw.slice(frontmatter?.length ?? 0);
2443
+ const metadataTags = /^tags:[ \t]*(.*)((?:\r?\n[ \t]*-[ \t]+[^\r\n]*)*)/m.exec(frontmatter ?? "");
2444
+ const tagValues = metadataTags ? metadataTags[1] + metadataTags[2].replace(/^[ \t]*-[ \t]+/gm, " ") : "";
2445
+ const tags = new Set(tagValues.match(/[\p{L}\p{N}_/-]+/gu) ?? []);
2446
+ const markup = note.replace(/<!--[^]*?(?:-->|$)|%%[^]*?(?:%%|$)/g, (comment) => comment.replace(/[^\r\n]/g, " "));
2447
+ let fence;
2448
+ for (const line of markup.split(/\r?\n/)) {
2449
+ const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
2450
+ if (marker && !fence) {
2451
+ fence = marker;
2452
+ continue;
2453
+ }
2454
+ if (fence) {
2455
+ if (marker?.startsWith(fence) && line.trim() === marker) fence = void 0;
2456
+ continue;
2457
+ }
2458
+ const text2 = line.replace(/(`+)[^`]*\1/g, (code) => " ".repeat(code.length));
2459
+ for (const match of text2.matchAll(/(?:^|[\s((,。!?、;:])#([\p{L}\p{N}_/-]+)/gu)) tags.add(match[1]);
2460
+ for (const match of text2.matchAll(/(!|\\)?\[\[([^\]\n]+)\]\]/g)) {
2461
+ if (match[1]) continue;
2462
+ const target = match[2].split(/[|#]/, 1)[0].trim();
2463
+ if (!target) continue;
2464
+ const start = match.index;
2465
+ const end = start + match[0].length;
2466
+ const before = line.slice(0, start).split(/[。!?!?]/).at(-1) ?? "";
2467
+ const after = line.slice(end).split(/[。!?!?]/, 1)[0];
2468
+ const sentence = [...(before + match[0] + after).trim()];
2469
+ const why = sentence.length <= 40 ? sentence.join("") : [...before.trimEnd()].slice(-8).concat([...match[0] + after]).slice(0, 40).join("").trim();
2470
+ references.push({ from: key, to: target, why });
2471
+ }
2472
+ }
2473
+ notes.push({ key, note: withTitle(note, key, raw), frontmatter, tags: [...tags].sort() });
2474
+ }
2475
+ }
2476
+ await walk("");
2477
+ } catch (error) {
2478
+ if (signal?.aborted || error instanceof ShelfError) throw error;
2479
+ throw new ShelfError("\u65E0\u6CD5\u8BFB\u53D6\u8FD9\u4E2A Obsidian \u7B14\u8BB0\u5E93\uFF0C\u8BF7\u786E\u8BA4\u8DEF\u5F84\u548C\u8BFB\u53D6\u6743\u9650");
2480
+ }
2481
+ const paths = new Set(notes.map((note) => note.key));
2482
+ const byName = /* @__PURE__ */ new Map();
2483
+ for (const { key } of notes) {
2484
+ const name2 = posix.basename(key).replace(/\.md$/i, "");
2485
+ const matches = byName.get(name2);
2486
+ if (matches) matches.push(key);
2487
+ else byName.set(name2, [key]);
2488
+ }
2489
+ const links = references.flatMap((link) => {
2490
+ const target = /\.md$/i.test(link.to) ? link.to : link.to + ".md";
2491
+ const relative2 = posix.normalize(posix.join(posix.dirname(link.from), target));
2492
+ const matches = byName.get(link.to.replace(/\.md$/i, ""));
2493
+ const to = target.startsWith(".") ? paths.has(relative2) ? relative2 : void 0 : target.includes("/") ? paths.has(target) ? target : paths.has(relative2) ? relative2 : void 0 : paths.has(relative2) ? relative2 : matches?.length === 1 ? matches[0] : void 0;
2494
+ return to && to !== link.from ? [{ ...link, to }] : [];
2495
+ });
2496
+ return { root, notes, links, unresolved: references.length - links.length };
2497
+ }
2498
+ var obsidian = {
2499
+ async scan(path, offset, signal) {
2500
+ if (offset !== void 0 && (typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0)) throw new ShelfError("offset \u5E94\u4E3A\u975E\u8D1F\u6574\u6570");
2501
+ const { notes, links, unresolved } = await readVault(path, signal);
2502
+ const start = Number(offset ?? 0);
2503
+ const folders = /* @__PURE__ */ new Map();
2504
+ const targets = /* @__PURE__ */ new Map();
2505
+ for (const link of links) {
2506
+ const ids = targets.get(link.from);
2507
+ if (ids) ids.push(link.to);
2508
+ else targets.set(link.from, [link.to]);
2509
+ }
2510
+ const listing = notes.map(({ key, tags }) => {
2511
+ const path2 = posix.dirname(key);
2512
+ const folder = folders.get(path2) ?? { path: path2, count: 0, tags: /* @__PURE__ */ new Set(), links: 0 };
2513
+ folders.set(path2, folder);
2514
+ const linked = targets.get(key) ?? [];
2515
+ folder.count += 1;
2516
+ for (const tag of tags) folder.tags.add(tag);
2517
+ folder.links += linked.length;
2518
+ return { path: key, tags, links: linked };
2519
+ });
2520
+ return {
2521
+ count: notes.length,
2522
+ links: links.length,
2523
+ unresolved,
2524
+ folders: [...folders.values()].map((folder) => ({ ...folder, tags: [...folder.tags].sort() })),
2525
+ notes: listing.slice(start, start + 100),
2526
+ nextOffset: start + 100 < listing.length ? start + 100 : void 0
2527
+ };
2528
+ },
2529
+ async prepare(path, plan, signal) {
2530
+ const { root, notes, links } = await readVault(path, signal);
2531
+ if (notes.length === 0) throw new ShelfError("\u8FD9\u4E2A\u6587\u4EF6\u5939\u6CA1\u6709 Markdown \u7B14\u8BB0");
2532
+ const source = "obsidian:" + createHash2("sha256").update(root).digest("hex");
2533
+ const groups = [];
2534
+ if (plan === void 0) {
2535
+ const folders = /* @__PURE__ */ new Map();
2536
+ for (const note of notes) {
2537
+ const folder = posix.dirname(note.key);
2538
+ const group = folders.get(folder) ?? { key: "folder:" + folder, title: posix.basename(folder === "." ? root : folder) || "Obsidian", cards: [] };
2539
+ folders.set(folder, group);
2540
+ group.cards.push(note);
2541
+ }
2542
+ groups.push(...folders.values());
2543
+ } else {
2544
+ if (!Array.isArray(plan) || plan.length === 0) throw new ShelfError("\u5206\u683C\u65B9\u6848\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u76EE\u6807");
2545
+ const byPath = new Map(notes.map((note) => [note.key, note]));
2546
+ for (const group of plan) {
2547
+ if (!group || typeof group !== "object") throw new ShelfError("\u5206\u683C\u65B9\u6848\u65E0\u6548");
2548
+ const { title, item_id: itemId, paths, tags } = group;
2549
+ if (paths === void 0 === (tags === void 0)) throw new ShelfError("\u6BCF\u4E2A\u76EE\u6807\u8BF7\u5728 paths \u548C tags \u4E2D\u9009\u4E00\u9879");
2550
+ const selection = paths ?? tags;
2551
+ if (!Array.isArray(selection) || selection.length === 0 || selection.some((value) => typeof value !== "string" || !value.trim())) {
2552
+ throw new ShelfError("paths \u6216 tags \u5FC5\u987B\u662F\u975E\u7A7A\u7684\u6587\u5B57\u5217\u8868");
2553
+ }
2554
+ const cards = paths === void 0 ? notes.filter((note) => note.tags.some((tag) => selection.includes(tag))) : selection.map((key) => {
2555
+ const note = byPath.get(key);
2556
+ if (!note) throw new ShelfError(`\u65B9\u6848\u4E2D\u7684\u7B14\u8BB0\u4E0D\u5B58\u5728\uFF1A${key}`);
2557
+ return note;
2558
+ });
2559
+ if (cards.length === 0) throw new ShelfError("\u6240\u9009\u6807\u7B7E\u6CA1\u6709\u5339\u914D\u7684\u7B14\u8BB0");
2560
+ if (typeof itemId === "string" && itemId) groups.push({ key: itemId, itemId, title: "", cards });
2561
+ else if (itemId === void 0 && typeof title === "string" && title.trim()) groups.push({ key: "title:" + title.trim(), title: title.trim(), cards });
2562
+ else throw new ShelfError("\u6BCF\u4E2A\u76EE\u6807\u8BF7\u586B\u5DF2\u6709\u683C\u5B50 item_id \u6216\u65B0\u683C\u5B50 title");
2563
+ }
2564
+ }
2565
+ return { source, groups, links };
2566
+ }
2567
+ };
2568
+
2569
+ // src/host/harness/tools.ts
1933
2570
  var stringOut = {
1934
2571
  schema: { type: "string" },
1935
2572
  render: (_args, value) => [{ type: "text", text: value }]
@@ -1950,12 +2587,19 @@ function createTools(store, active, memory = new Memory(store)) {
1950
2587
  return "\n\uFF08\u63D0\u793A\uFF1A\u5982\u679C\u8FD9\u6761\u548C\u5BAB\u6BBF\u91CC\u522B\u7684\u683C\u5B50\u6709\u5173\u2014\u2014\u540C\u4E00\u4E2A\u5FF5\u5934\u3001\u4E3B\u9898\u6216\u7591\u95EE\u2014\u2014\u53EF\u4EE5\u7528 palace_link \u8FDE\u4E00\u6761\u7535\u5F27\u3002\uFF09";
1951
2588
  };
1952
2589
  const activeOf = (exec) => exec.agent ? active.get(exec.agent.id) : void 0;
1953
- return createPalaceTools(store, memory, {
2590
+ const shared = createPalaceTools(store, memory, {
1954
2591
  addBook: (args, signal) => addBook(store, args, signal),
1955
2592
  readPageTexts,
1956
2593
  scannedThreshold: SCANNED_THRESHOLD,
2594
+ scannedPageHelp: "\u5426\u5219\u8BF7\u7528\u6237\u5728\u53F3\u4FA7\u7B14\u8BB0\u672C\u91CC\u91CD\u65B0\u52FE\u9009\u8FD9\u4E9B\u9875\uFF08\u4F1A\u628A\u9875\u9762\u56FE\u7247\u53D1\u5230\u5BF9\u8BDD\uFF09\u3002",
2595
+ videoHelp: "\u89C6\u9891\u94FE\u63A5\u6309\u5E73\u53F0\u5904\u7406\uFF1AB \u7AD9\uFF08\u5E26 BV \u53F7\u6216 b23.tv \u77ED\u94FE\uFF09\u76F4\u63A5\u4F20 url\uFF0C\u4F1A\u81EA\u52A8\u8BFB\u51FA\u5206 P / \u5408\u96C6\u548C\u6BCF\u4E00\u96C6\u7684\u94FE\u63A5\uFF0Ctitle \u53EF\u4E0D\u586B\uFF1BYouTube\uFF1A\u4F20 url \u548C\u89C6\u9891\u6216\u64AD\u653E\u5217\u8868\u7684\u6807\u9898\uFF1B\u5176\u4ED6\u5E73\u53F0\uFF08Netflix\u3001\u7231\u5947\u827A\u3001\u8292\u679C TV\u3001\u817E\u8BAF\u89C6\u9891\u3001\u8BFE\u7A0B\u7F51\u7AD9\u2026\u2026\uFF09\uFF1A\u4ECE\u94FE\u63A5\u548C\u7528\u6237\u7684\u8BDD\u8BA4\u51FA\u4F5C\u54C1\uFF0Ctitle \u7528\u4F5C\u54C1\u7684\u6B63\u5F0F\u540D\uFF0C\u4F20 url\u3002\u8FD9\u4E24\u7C7B\u5EFA\u597D\u540E\u5148\u505C\u4E0B\uFF1A\u544A\u8BC9\u7528\u6237\u5DF2\u7ECF\u653E\u8FDB\u6765\u4E86\uFF0C\u95EE\u8981\u4E0D\u8981\u4E0A\u7F51\u67E5\u5206\u96C6\u548C\u6BCF\u4E00\u96C6\u7684\u94FE\u63A5\uFF08\u8981\u82B1\u4E00\u4E24\u5206\u949F\uFF09\uFF1B\u7528\u6237\u5728\u539F\u8BDD\u91CC\u5DF2\u7ECF\u8981\u4E86\u76EE\u5F55\u5C31\u76F4\u63A5\u67E5\u3002\u67E5\u7684\u65F6\u5019\u5206\u5B63\u5C31\u4E00\u5B63\u4E00\u7AE0\uFF0C\u7528 palace_set_outline \u5199\u5165\uFF08\u6BCF\u96C6\u5C3D\u91CF\u5E26 url\uFF09\uFF1B\u8FDE\u8F7D\u4E2D\u7684\u53EA\u5199\u5DF2\u7ECF\u67E5\u5B9E\u7684\u96C6\u6570\uFF0C\u67E5\u4E0D\u5230\u94FE\u63A5\u5C31\u53EA\u5199\u6807\u9898\u3002\u540C\u6837\u7684\u89C4\u77E9\u9002\u7528\u4E8E\u4EFB\u4F55\u8981\u82B1\u65F6\u95F4\u7684\u8865\u5168\uFF08\u4E0A\u7F51\u67E5\u76EE\u5F55\u3001\u8BFB\u5F88\u591A\u9875\u2026\u2026\uFF09\uFF1A\u5148\u5EFA\u683C\u5B50\uFF0C\u518D\u95EE\u7528\u6237\uFF1B\u51E0\u79D2\u5185\u5C31\u80FD\u5B8C\u6210\u7684\uFF08B \u7AD9\u63A5\u53E3\u3001PDF \u4E66\u7B7E\u3001EPUB \u76EE\u5F55\uFF09\u7167\u65E7\u81EA\u52A8\u505A\u3002\u6CA1\u6709\u539F\u6587\u3001\u4E5F\u4E0D\u9700\u8981\u6309\u96C6\u6253\u52FE\u7684\uFF08\u6BD4\u5982\u53EA\u662F\u60F3\u804A\u4E00\u90E8\u5267\uFF09\uFF0C\u7528 kind=note\u3002",
2596
+ imageHelp: "image \u586B\u5BF9\u8BDD\u91CC\u56FE\u7247\u7684\u672C\u5730\u53EA\u8BFB\u8DEF\u5F84\uFF08\u56FE\u7247\u8BF4\u660E\u4E2D\u7684 read-only path\uFF09\uFF0C\u6CA1\u6709\u8DEF\u5F84\u5C31\u586B\u9644\u4EF6 id\uFF08sha256:...\uFF09\u3002",
2597
+ imageDescription: "\u622A\u56FE\u7684\u672C\u5730\u8DEF\u5F84\u6216\u9644\u4EF6 id",
2598
+ currentItem: true,
2599
+ wikiReadHelp: "\u5F53\u524D\u683C\u5B50\u548C me \u5DF2\u7ECF\u5728\u5BF9\u8BDD\u80CC\u666F\u91CC\uFF0C\u8BFB\u522B\u7684\u683C\u5B50\u65F6\u624D\u9700\u8981\u8C03\u7528\u3002",
1957
2600
  saveImage: (ref) => saveImage(store, ref)
1958
- }).map(({ execute, ...definition }) => defineTool({
2601
+ });
2602
+ return [...shared, ...createObsidianTools(store, memory, obsidian), ...createWeReadTools(store, memory, weread)].map(({ execute, ...definition }) => defineTool({
1959
2603
  ...definition,
1960
2604
  output: stringOut,
1961
2605
  async execute(args, exec) {
@@ -1975,12 +2619,12 @@ function createTools(store, active, memory = new Memory(store)) {
1975
2619
  }));
1976
2620
  }
1977
2621
 
1978
- // src/host/index.ts
2622
+ // src/host/harness/index.ts
1979
2623
  var name = "dsh-palace";
1980
- var defaultDataDir = () => join6(homedir3(), "Documents", "dsh-palace-data");
2624
+ var defaultDataDir = () => join8(homedir4(), "Documents", "dsh-palace-data");
1981
2625
  function apply(ctx, config = {}) {
1982
2626
  const dir = config.dataDir ?? defaultDataDir();
1983
- const firstRun = !existsSync5(join6(dir, "palace.json"));
2627
+ const firstRun = !existsSync5(join8(dir, "palace.json"));
1984
2628
  const store = new PalaceStore(dir);
1985
2629
  if (firstRun) void seedWelcome(store).catch((error) => console.warn("[dsh-palace] \u653E\u5165\u4ECB\u7ECD\u683C\u5B50\u5931\u8D25", error));
1986
2630
  const active = /* @__PURE__ */ new Map();