dsh-palace 1.2.1-walker.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,6 +1,7 @@
1
- // src/host/index.ts
2
- import { homedir as homedir3 } from "node:os";
3
- import { join as join6, resolve } from "node:path";
1
+ // src/host/harness/index.ts
2
+ import { existsSync as existsSync5 } from "node:fs";
3
+ import { homedir as homedir4 } from "node:os";
4
+ import { join as join8, resolve } from "node:path";
4
5
 
5
6
  // src/core/memory.ts
6
7
  import { appendFileSync, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
@@ -8,7 +9,7 @@ import { join as join2 } from "node:path";
8
9
 
9
10
  // src/core/store.ts
10
11
  import { randomBytes } from "node:crypto";
11
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
12
+ import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
12
13
  import { join } from "node:path";
13
14
 
14
15
  // src/shared/palace.ts
@@ -113,8 +114,10 @@ var KINDS = /* @__PURE__ */ new Set(["book", "note", "group"]);
113
114
  function assertCellId(id) {
114
115
  if (typeof id !== "string" || !CELL_ID.test(id)) throw new ShelfError("\u683C\u5B50 id \u65E0\u6548");
115
116
  }
116
- function parsePalace(raw) {
117
- const data = JSON.parse(raw);
117
+ function schemaOf(data) {
118
+ return typeof data?.schema === "number" && data.schema > SCHEMA ? data.schema : SCHEMA;
119
+ }
120
+ function parsePalace(data) {
118
121
  if (data === null || typeof data !== "object" || !Array.isArray(data.cells)) throw new Error("\u7F3A\u5C11 cells \u6570\u7EC4");
119
122
  for (const c of data.cells) {
120
123
  if (typeof c?.id !== "string" || !KINDS.has(c.kind) || !Number.isSafeInteger(c.col) || !Number.isSafeInteger(c.row) || typeof c.title !== "string") {
@@ -122,10 +125,9 @@ function parsePalace(raw) {
122
125
  }
123
126
  if (c.parentId === void 0) c.parentId = null;
124
127
  }
125
- return { ...data, schema: SCHEMA, cells: data.cells };
128
+ return { ...data, schema: schemaOf(data), cells: data.cells };
126
129
  }
127
- function parseItem(raw, id) {
128
- const data = JSON.parse(raw);
130
+ function parseItem(data, id) {
129
131
  if (data === null || typeof data !== "object") throw new Error("\u4E0D\u662F JSON \u5BF9\u8C61");
130
132
  for (const key of ["chapters", "cards", "inspirations"]) {
131
133
  if (data[key] !== void 0 && !Array.isArray(data[key])) throw new Error(`${key} \u5E94\u4E3A\u6570\u7EC4`);
@@ -140,7 +142,7 @@ function parseItem(raw, id) {
140
142
  return {
141
143
  ...emptyItem(id),
142
144
  ...data,
143
- schema: SCHEMA,
145
+ schema: schemaOf(data),
144
146
  id,
145
147
  chapters: data.chapters ?? [],
146
148
  cards: data.cards ?? [],
@@ -166,14 +168,17 @@ var PalaceStore = class {
166
168
  items = /* @__PURE__ */ new Map();
167
169
  /** 每次写入 +1,前端轮询它判断是否需要刷新。 */
168
170
  rev = 1;
169
- constructor(dir) {
171
+ constructor(dir, { create = true } = {}) {
170
172
  this.dir = dir;
171
173
  this.itemsDir = join(dir, "items");
172
174
  this.imagesDir = join(dir, "images");
173
175
  this.palaceFile = join(dir, "palace.json");
174
- mkdirSync(this.itemsDir, { recursive: true });
175
- mkdirSync(this.imagesDir, { recursive: true });
176
- this.refreshPalace();
176
+ if (create) {
177
+ mkdirSync(this.itemsDir, { recursive: true });
178
+ mkdirSync(this.imagesDir, { recursive: true });
179
+ }
180
+ const state = this.refreshPalace();
181
+ if (!create && (state.stamp === "" || state.broken)) throw new ShelfError(`\u65E0\u6CD5\u8BFB\u53D6 ${this.palaceFile}`);
177
182
  }
178
183
  // ---------- 读 ----------
179
184
  refreshPalace() {
@@ -186,11 +191,14 @@ var PalaceStore = class {
186
191
  }
187
192
  const mtime = stamp(this.palaceFile);
188
193
  if (mtime === this.palace.stamp) return this.palace;
194
+ let schema = this.palace.schema;
189
195
  try {
190
- this.palace = { value: parsePalace(readFileSync(this.palaceFile, "utf8")), stamp: mtime, broken: false };
196
+ const data = JSON.parse(readFileSync(this.palaceFile, "utf8"));
197
+ schema = schemaOf(data);
198
+ this.palace = { value: parsePalace(data), stamp: mtime, broken: false, schema };
191
199
  } catch (error) {
192
200
  console.warn("[dsh-palace] palace.json \u89E3\u6790\u5931\u8D25\uFF0C\u7EE7\u7EED\u4F7F\u7528\u5185\u5B58\u4E2D\u7684\u6570\u636E", error);
193
- this.palace = { ...this.palace, stamp: mtime, broken: true };
201
+ this.palace = { ...this.palace, stamp: mtime, broken: true, schema };
194
202
  }
195
203
  this.rev += 1;
196
204
  return this.palace;
@@ -209,11 +217,14 @@ var PalaceStore = class {
209
217
  const mtime = stamp(file);
210
218
  if (cached !== void 0 && cached.stamp === mtime) return cached;
211
219
  let next;
220
+ let schema = cached?.schema;
212
221
  try {
213
- next = { value: parseItem(readFileSync(file, "utf8"), id), stamp: mtime, broken: false };
222
+ const data = JSON.parse(readFileSync(file, "utf8"));
223
+ schema = schemaOf(data);
224
+ next = { value: parseItem(data, id), stamp: mtime, broken: false, schema };
214
225
  } catch (error) {
215
226
  console.warn(`[dsh-palace] items/${id}.json \u89E3\u6790\u5931\u8D25`, error);
216
- next = { value: cached?.value ?? emptyItem(id), stamp: mtime, broken: true };
227
+ next = { value: cached?.value ?? emptyItem(id), stamp: mtime, broken: true, schema };
217
228
  }
218
229
  if (cached !== void 0) this.rev += 1;
219
230
  this.items.set(id, next);
@@ -240,6 +251,41 @@ var PalaceStore = class {
240
251
  return out;
241
252
  }
242
253
  // ---------- 写 ----------
254
+ snapshotBeforeWrite() {
255
+ const name2 = ".snapshots";
256
+ const root = join(this.dir, name2), target = join(root, today());
257
+ try {
258
+ const state = lstatSync(root, { throwIfNoEntry: false });
259
+ if (state && !state.isDirectory()) throw new Error("\u5FEB\u7167\u8DEF\u5F84\u4E0D\u662F\u666E\u901A\u76EE\u5F55");
260
+ if (existsSync(target)) return;
261
+ mkdirSync(root, { recursive: true });
262
+ const temp = mkdtempSync(join(root, ".partial-"));
263
+ try {
264
+ for (const file of readdirSync(this.dir)) {
265
+ if (file !== name2) cpSync(join(this.dir, file), join(temp, file), { recursive: true, verbatimSymlinks: true });
266
+ }
267
+ if (!existsSync(target)) renameSync(temp, target);
268
+ } finally {
269
+ rmSync(temp, { recursive: true, force: true });
270
+ }
271
+ const days = readdirSync(root, { withFileTypes: true }).filter((entry) => entry.isDirectory() && /^\d{4}-\d{2}-\d{2}$/.test(entry.name)).map((entry) => entry.name);
272
+ for (const old of days.sort().slice(0, -3)) rmSync(join(root, old), { recursive: true, force: true });
273
+ } catch (error) {
274
+ console.warn("[dsh-palace] \u6BCF\u65E5\u5FEB\u7167\u5931\u8D25\uFF0C\u7EE7\u7EED\u5199\u5165", error);
275
+ }
276
+ }
277
+ /** 格子、记忆和图片共用同一条只读边界。 */
278
+ assertWritable() {
279
+ const palace = this.refreshPalace();
280
+ this.assertSupportedSchema(palace, "palace.json");
281
+ for (const cell of palace.value.cells) {
282
+ if (cell.kind === "group" || !CELL_ID.test(cell.id)) continue;
283
+ this.assertSupportedSchema(this.refreshItem(cell.id), `items/${cell.id}.json`);
284
+ }
285
+ }
286
+ assertSupportedSchema(state, file) {
287
+ if ((state.schema ?? SCHEMA) > SCHEMA) throw new ShelfError(`${file} \u7684\u6570\u636E\u7248\u672C\u8F83\u65B0\uFF0C\u8BF7\u5347\u7EA7\u63D2\u4EF6`);
288
+ }
243
289
  /**
244
290
  * 执行一次修改。fn 抛错则不落盘。
245
291
  *
@@ -256,7 +302,8 @@ var PalaceStore = class {
256
302
  }
257
303
  }
258
304
  commit(fn) {
259
- const palaceState = this.refreshPalace();
305
+ this.assertWritable();
306
+ const palaceState = this.palace;
260
307
  if (palaceState.broken) throw new ShelfError("palace.json \u683C\u5F0F\u6709\u8BEF\uFF1A\u8BF7\u5148\u4FEE\u597D\u6216\u5220\u6389\u8FD9\u4E2A\u6587\u4EF6\uFF0C\u518D\u7EE7\u7EED\u64CD\u4F5C");
261
308
  const palace = structuredClone(palaceState.value);
262
309
  const touched = /* @__PURE__ */ new Map();
@@ -270,17 +317,18 @@ var PalaceStore = class {
270
317
  return hit.item;
271
318
  }
272
319
  const state = this.refreshItem(id);
320
+ this.assertSupportedSchema(state, `items/${id}.json`);
273
321
  if (state.broken) throw new ShelfError(`items/${id}.json \u683C\u5F0F\u6709\u8BEF\uFF1A\u8BF7\u5148\u4FEE\u597D\u6216\u5220\u6389\u8FD9\u4E2A\u6587\u4EF6`);
274
322
  const item = structuredClone(state.value);
275
323
  touched.set(id, { item, before: JSON.stringify(state.value), stamp: state.stamp });
276
324
  return item;
277
325
  },
278
326
  createItem: (item) => {
279
- assertCellId(item.id);
327
+ this.assertSupportedSchema(this.refreshItem(item.id), `items/${item.id}.json`);
280
328
  touched.set(item.id, { item, before: "", stamp: "" });
281
329
  },
282
330
  deleteItem: (id) => {
283
- assertCellId(id);
331
+ this.assertSupportedSchema(this.refreshItem(id), `items/${id}.json`);
284
332
  touched.set(id, { item: null, before: "", stamp: "" });
285
333
  },
286
334
  deleteImage: (name2) => {
@@ -289,14 +337,17 @@ var PalaceStore = class {
289
337
  };
290
338
  const result = fn(tx);
291
339
  if (result instanceof Promise) throw new Error("mutate \u7684\u56DE\u8C03\u5FC5\u987B\u662F\u540C\u6B65\u7684");
292
- const changed = (file, was) => (existsSync(file) ? stamp(file) : "") !== was;
293
340
  const palaceChanged = JSON.stringify(palace) !== JSON.stringify(palaceState.value);
294
- if (palaceChanged && changed(this.palaceFile, palaceState.stamp)) throw new ShelfError("palace.json \u521A\u88AB\u5176\u4ED6\u7A0B\u5E8F\u4FEE\u6539\u8FC7\uFF0C\u8BF7\u91CD\u8BD5");
341
+ const writes = [...touched].filter(([, { item, before }]) => item === null || JSON.stringify(item) !== before);
342
+ if (palaceChanged || writes.length > 0 || images.length > 0) this.snapshotBeforeWrite();
343
+ const changed = (file, was) => (existsSync(file) ? stamp(file) : "") !== was;
344
+ if (changed(this.palaceFile, palaceState.stamp)) throw new ShelfError("palace.json \u521A\u88AB\u5176\u4ED6\u7A0B\u5E8F\u4FEE\u6539\u8FC7\uFF0C\u8BF7\u91CD\u8BD5");
295
345
  for (const [id, t] of touched) {
296
346
  if (t.before !== "" && changed(join(this.itemsDir, `${id}.json`), t.stamp)) throw new ShelfError(`items/${id}.json \u521A\u88AB\u5176\u4ED6\u7A0B\u5E8F\u4FEE\u6539\u8FC7\uFF0C\u8BF7\u91CD\u8BD5`);
297
347
  }
298
- for (const [id, { item, before }] of touched) {
299
- if (item === null || JSON.stringify(item) === before) continue;
348
+ for (const [id, { item }] of writes) {
349
+ if (item === null) continue;
350
+ if (!existsSync(this.itemsDir)) mkdirSync(this.itemsDir, { recursive: true });
300
351
  const st = writeAtomic(join(this.itemsDir, `${id}.json`), item);
301
352
  this.items.set(id, { value: item, stamp: st, broken: false });
302
353
  }
@@ -330,6 +381,12 @@ var SUMMARY_LIMIT = 40;
330
381
  var WHY_LIMIT = 40;
331
382
  var TOPIC_LIMIT = 5;
332
383
  var charCount = (s) => [...s].length;
384
+ function linkWhy(value) {
385
+ if (typeof value !== "string" || value.trim() === "") throw new ShelfError("\u8981\u5199\u4E00\u53E5\u7406\u7531");
386
+ const why = value.trim().replace(/\n/g, " ");
387
+ if (charCount(why) > WHY_LIMIT) throw new ShelfError(`\u7406\u7531\u6700\u591A ${WHY_LIMIT} \u5B57`);
388
+ return why;
389
+ }
333
390
  var pairKey = (a, b) => a < b ? `${a}|${b}` : `${b}|${a}`;
334
391
  function recordsOf(item) {
335
392
  const out = /* @__PURE__ */ new Map();
@@ -399,6 +456,7 @@ var Memory = class {
399
456
  }
400
457
  /** 整页覆写。target 是 'me' 或书 / 笔记格子的 id。 */
401
458
  writePage(target, input) {
459
+ this.store.assertWritable();
402
460
  if (target !== "me") this.cellOf(target, false);
403
461
  if (typeof input.body !== "string" || input.body.trim() === "") throw new ShelfError("\u6B63\u6587\u4E0D\u80FD\u4E3A\u7A7A");
404
462
  const body = input.body.trim();
@@ -419,6 +477,7 @@ var Memory = class {
419
477
  writtenAt: nowIso()
420
478
  };
421
479
  const file = this.pageFile(target);
480
+ this.store.snapshotBeforeWrite();
422
481
  mkdirSync2(this.cellsDir, { recursive: true });
423
482
  const tmp = `${file}.${process.pid}.tmp`;
424
483
  writeFileSync2(tmp, renderPage(page), "utf8");
@@ -443,17 +502,20 @@ var Memory = class {
443
502
  if (line.trim() === "") continue;
444
503
  try {
445
504
  const r = JSON.parse(line);
446
- if ((r.type === "link" || r.type === "cut") && typeof r.from === "string" && typeof r.to === "string") records.push(r);
505
+ 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);
447
506
  } catch {
448
507
  }
449
508
  }
450
509
  this.cache = { stamp: stamp2, records };
451
510
  return records;
452
511
  }
453
- append(record) {
512
+ append(records) {
513
+ if (records.length === 0) return;
514
+ this.store.assertWritable();
515
+ this.store.snapshotBeforeWrite();
454
516
  const size = existsSync2(this.linksFile) ? statSync2(this.linksFile).size : 0;
455
517
  const broken = size > 0 && readFileSync2(this.linksFile, "utf8").at(-1) !== "\n";
456
- appendFileSync(this.linksFile, (broken ? "\n" : "") + JSON.stringify(record) + "\n", "utf8");
518
+ appendFileSync(this.linksFile, (broken ? "\n" : "") + records.map((record) => JSON.stringify(record)).join("\n") + "\n", "utf8");
457
519
  this.store.rev += 1;
458
520
  }
459
521
  cellOf(id, allowGroup) {
@@ -472,9 +534,7 @@ var Memory = class {
472
534
  const from = this.cellOf(args.from, false);
473
535
  const to = this.cellOf(args.to, false);
474
536
  if (from.id === to.id) throw new ShelfError("\u4E0D\u80FD\u8FDE\u5230\u81EA\u5DF1");
475
- if (typeof args.why !== "string" || args.why.trim() === "") throw new ShelfError("\u8981\u5199\u4E00\u53E5\u7406\u7531");
476
- const why = args.why.trim().replace(/\n/g, " ");
477
- if (charCount(why) > WHY_LIMIT) throw new ShelfError(`\u7406\u7531\u6700\u591A ${WHY_LIMIT} \u5B57`);
537
+ const why = linkWhy(args.why);
478
538
  if (!Array.isArray(args.evidence)) throw new ShelfError("evidence \u5E94\u4E3A\u5361\u7247 / \u7075\u611F id \u7684\u6570\u7EC4");
479
539
  const evidence = [...new Set(args.evidence.filter((e) => typeof e === "string"))];
480
540
  const a = recordsOf(this.store.getItem(from.id));
@@ -486,14 +546,43 @@ var Memory = class {
486
546
  const used = new Set(this.validLinks().filter((l) => pairKey(l.from, l.to) === pairKey(from.id, to.id)).flatMap((l) => l.evidence));
487
547
  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");
488
548
  const record = { type: "link", id: newId("l"), from: from.id, to: to.id, why, evidence, ...args.sessionId ? { sessionId: args.sessionId } : {}, createdAt: nowIso() };
489
- this.append(record);
549
+ this.append([record]);
490
550
  return record;
491
551
  }
552
+ /** 导入双链按来源键去重。用户剪过的格子对继续保留断开状态。 */
553
+ previewImportedLinks(links) {
554
+ const records = this.records();
555
+ const cuts = new Set(records.filter((r) => r.type === "cut").map((r) => pairKey(r.from, r.to)));
556
+ const known = new Set(records.flatMap((r) => r.type === "link" && r.sourceKey ? [r.sourceKey] : []));
557
+ const active = this.validLinks();
558
+ const activeKeys = new Set(active.map((r) => r.sourceKey));
559
+ const activePairs = new Set(active.map((r) => pairKey(r.from, r.to)));
560
+ const eligible = links.filter((link) => !cuts.has(pairKey(link.from, link.to)));
561
+ const added = eligible.filter((link) => !activeKeys.has(link.sourceKey));
562
+ return {
563
+ pending: eligible.filter((link) => !known.has(link.sourceKey)),
564
+ arcs: new Set(added.map((link) => pairKey(link.from, link.to)).filter((pair) => !activePairs.has(pair))).size,
565
+ strands: added.length
566
+ };
567
+ }
568
+ addImportedLinks(links) {
569
+ if (links.length === 0) return;
570
+ const { pending } = this.previewImportedLinks(links);
571
+ this.append(pending.map((link) => ({ ...link, type: "link", id: newId("l"), why: linkWhy(link.why), createdAt: nowIso() })));
572
+ }
573
+ retitleLink(args) {
574
+ const from = this.cellOf(args.from, false).id;
575
+ const to = this.cellOf(args.to, false).id;
576
+ const why = linkWhy(args.why);
577
+ const arc = this.arcs().find((arc2) => pairKey(arc2.from, arc2.to) === pairKey(from, to));
578
+ if (!arc) throw new ShelfError("\u8FD9\u4E24\u683C\u4E4B\u95F4\u6CA1\u6709\u6709\u6548\u7535\u5F27");
579
+ if (arc.why !== why) this.append([{ type: "retitle", from, to, why }]);
580
+ }
492
581
  /** 用户剪断两格之间的电弧(追加记录,不删历史)。 */
493
582
  cut(args) {
494
583
  const from = this.cellOf(args.from, true);
495
584
  const to = this.cellOf(args.to, true);
496
- this.append({ type: "cut", from: from.id, to: to.id, createdAt: nowIso() });
585
+ this.append([{ type: "cut", from: from.id, to: to.id, createdAt: nowIso() }]);
497
586
  }
498
587
  /** 还有效的联想:两端格子都在、在最近一次剪断之后、两端各至少还剩一条证据。 */
499
588
  validLinks() {
@@ -507,12 +596,15 @@ var Memory = class {
507
596
  }
508
597
  return r;
509
598
  };
599
+ const records = this.records();
510
600
  const cuts = /* @__PURE__ */ new Map();
511
- for (const r of this.records()) if (r.type === "cut") {
512
- const k = pairKey(r.from, r.to);
513
- if (r.createdAt > (cuts.get(k) ?? "")) cuts.set(k, r.createdAt);
601
+ for (const r of records) {
602
+ if (r.type === "cut") {
603
+ const key = pairKey(r.from, r.to);
604
+ if (r.createdAt > (cuts.get(key) ?? "")) cuts.set(key, r.createdAt);
605
+ }
514
606
  }
515
- return this.records().filter((r) => {
607
+ return records.filter((r) => {
516
608
  if (r.type !== "link" || !cells.has(r.from) || !cells.has(r.to)) return false;
517
609
  if (r.createdAt <= (cuts.get(pairKey(r.from, r.to)) ?? "")) return false;
518
610
  const ev = Array.isArray(r.evidence) ? r.evidence : [];
@@ -521,14 +613,21 @@ var Memory = class {
521
613
  }
522
614
  /** 电弧:按格子对聚合有效联想。 */
523
615
  arcs() {
616
+ const titles = /* @__PURE__ */ new Map();
617
+ for (const r of this.records()) {
618
+ if (r.type === "cut") titles.delete(pairKey(r.from, r.to));
619
+ if (r.type === "retitle") titles.set(pairKey(r.from, r.to), r.why);
620
+ }
524
621
  const byPair = /* @__PURE__ */ new Map();
525
622
  for (const l of this.validLinks()) {
526
623
  const k = pairKey(l.from, l.to);
527
- byPair.set(k, [...byPair.get(k) ?? [], l]);
624
+ const links = byPair.get(k);
625
+ if (links) links.push(l);
626
+ else byPair.set(k, [l]);
528
627
  }
529
628
  return [...byPair.values()].map((links) => {
530
629
  const latest = links.reduce((x, y) => y.createdAt >= x.createdAt ? y : x);
531
- return { from: latest.from, to: latest.to, strands: links.length, why: latest.why, lastAt: latest.createdAt, links };
630
+ return { from: latest.from, to: latest.to, strands: links.length, why: titles.get(pairKey(latest.from, latest.to)) ?? latest.why, lastAt: latest.createdAt, links };
532
631
  }).sort((x, y) => y.strands - x.strands || (y.lastAt > x.lastAt ? 1 : -1));
533
632
  }
534
633
  // ---------- 对话背景 ----------
@@ -612,14 +711,6 @@ ${mine.map((a) => `- \u2194 ${title(a.from === current.id ? a.to : a.from)}\uFF0
612
711
  }
613
712
  };
614
713
 
615
- // src/host/routes.ts
616
- import { execFile as execFile2, spawn } from "node:child_process";
617
- import { createReadStream, existsSync as existsSync4, statSync as statSync4 } from "node:fs";
618
- import { homedir as homedir2 } from "node:os";
619
- import { basename as basename2, extname as extname2, join as join5, normalize, sep as sep2 } from "node:path";
620
- import { Readable } from "node:stream";
621
- import { fileURLToPath } from "node:url";
622
-
623
714
  // src/core/ops.ts
624
715
  function text(value, what) {
625
716
  if (typeof value !== "string" || value.trim() === "") throw new ShelfError(`${what}\u4E0D\u80FD\u4E3A\u7A7A`);
@@ -690,6 +781,15 @@ function pruneGroup(palace, groupId) {
690
781
  if (groupId === null || palace.cells.some((c) => c.parentId === groupId)) return;
691
782
  palace.cells = palace.cells.filter((c) => c.id !== groupId);
692
783
  }
784
+ var WELCOME_URL = "https://dsh-palace.pages.dev";
785
+ async function seedWelcome(store) {
786
+ return store.mutate((tx) => {
787
+ const cell = { id: newId("c"), kind: "note", parentId: null, ...firstEmptySlot(tx.palace, null), title: "Memory Palace \u2197", subtitle: "\u4EC0\u4E48\u662F", icon: "open-book", href: WELCOME_URL, createdAt: nowIso() };
788
+ tx.palace.cells.push(cell);
789
+ tx.createItem(emptyItem(cell.id, null));
790
+ return cell;
791
+ });
792
+ }
693
793
  async function addCell(store, args) {
694
794
  const kind = args.kind;
695
795
  if (kind !== "book" && kind !== "note" && kind !== "group") throw new ShelfError("\u683C\u5B50\u7C7B\u578B\u5E94\u4E3A book / note / group");
@@ -993,8 +1093,16 @@ async function deleteInspiration(store, args) {
993
1093
  });
994
1094
  }
995
1095
 
1096
+ // src/host/routes.ts
1097
+ import { execFile as execFile2, spawn } from "node:child_process";
1098
+ import { createReadStream, existsSync as existsSync4, statSync as statSync4 } from "node:fs";
1099
+ import { homedir as homedir3 } from "node:os";
1100
+ import { basename as basename3, extname as extname2, join as join6, normalize, sep as sep3 } from "node:path";
1101
+ import { Readable } from "node:stream";
1102
+ import { fileURLToPath } from "node:url";
1103
+
996
1104
  // src/host/books.ts
997
- import { closeSync, copyFileSync, existsSync as existsSync3, openSync, readdirSync, readSync, statSync as statSync3 } from "node:fs";
1105
+ import { closeSync, copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync3, openSync, readdirSync as readdirSync2, readSync, statSync as statSync3 } from "node:fs";
998
1106
  import { homedir } from "node:os";
999
1107
  import { basename, extname, isAbsolute, join as join4 } from "node:path";
1000
1108
 
@@ -1112,7 +1220,7 @@ async function readPdfInfo(file) {
1112
1220
  try {
1113
1221
  let items = await doc.getOutline() ?? [];
1114
1222
  while (items.length === 1 && items[0].items.length > 0) items = items[0].items;
1115
- const outline = [];
1223
+ const outline2 = [];
1116
1224
  for (const item of items) {
1117
1225
  const sections = [];
1118
1226
  for (const child of item.items) {
@@ -1120,7 +1228,7 @@ async function readPdfInfo(file) {
1120
1228
  if (title3 !== "") sections.push({ title: title3, page: await pageOf(doc, child.dest) });
1121
1229
  }
1122
1230
  const title2 = clean(item.title);
1123
- if (title2 !== "") outline.push({ title: title2, page: await pageOf(doc, item.dest), sections });
1231
+ if (title2 !== "") outline2.push({ title: title2, page: await pageOf(doc, item.dest), sections });
1124
1232
  }
1125
1233
  let title;
1126
1234
  try {
@@ -1129,7 +1237,7 @@ async function readPdfInfo(file) {
1129
1237
  if (typeof info?.Title === "string" && info.Title.trim() !== "") title = info.Title.trim();
1130
1238
  } catch {
1131
1239
  }
1132
- return { pageCount: doc.numPages, title, outline };
1240
+ return { pageCount: doc.numPages, title, outline: outline2 };
1133
1241
  } finally {
1134
1242
  await close();
1135
1243
  }
@@ -1162,19 +1270,19 @@ var SCANNED_THRESHOLD = 20;
1162
1270
  function expandHome(path) {
1163
1271
  return path.startsWith("~/") ? join4(homedir(), path.slice(2)) : path;
1164
1272
  }
1165
- async function addBook(store, args, signal) {
1273
+ async function addBook(store, args, signal, { readVideo = true } = {}) {
1166
1274
  const cancelled = () => {
1167
1275
  if (signal?.aborted) throw new ShelfError("\u5DF2\u53D6\u6D88");
1168
1276
  };
1169
1277
  let source;
1170
1278
  let title;
1171
- let outline = [];
1279
+ let outline2 = [];
1172
1280
  let outlineSource;
1173
1281
  if (typeof args.url === "string" && args.url.trim() !== "") {
1174
1282
  const url = args.url.trim();
1175
- if (!isBilibili(url)) {
1283
+ if (!readVideo || !isBilibili(url)) {
1176
1284
  if (!/^https?:\/\/\S+$/.test(url)) throw new ShelfError("\u89C6\u9891\u94FE\u63A5\u8981\u4EE5 http:// \u6216 https:// \u5F00\u5934");
1177
- if (typeof args.title !== "string" || args.title.trim() === "") throw new ShelfError("\u4E0D\u662F B \u7AD9\u94FE\u63A5\u65F6\u8981\u586B\u4F5C\u54C1\u540D");
1285
+ if (typeof args.title !== "string" || args.title.trim() === "") throw new ShelfError(readVideo ? "\u4E0D\u662F B \u7AD9\u94FE\u63A5\u65F6\u8981\u586B\u4F5C\u54C1\u540D" : "\u89C6\u9891\u94FE\u63A5\u8981\u586B\u4F5C\u54C1\u540D");
1178
1286
  cancelled();
1179
1287
  return addCell(store, { kind: "book", title: args.title.trim(), subtitle: args.subtitle, source: { type: "video", url }, parentId: args.parentId, targetDate: args.targetDate });
1180
1288
  }
@@ -1184,7 +1292,7 @@ async function addBook(store, args, signal) {
1184
1292
  });
1185
1293
  source = { type: "video", url: course.url };
1186
1294
  title = course.title;
1187
- outline = course.chapters.map((c) => ({ title: c.title, sections: c.episodes.map((e) => ({ title: e.title, loc: e.url })) }));
1295
+ outline2 = course.chapters.map((c) => ({ title: c.title, sections: c.episodes.map((e) => ({ title: e.title, loc: e.url })) }));
1188
1296
  outlineSource = "video";
1189
1297
  } else if (typeof args.file === "string" && args.file.trim() !== "") {
1190
1298
  const file = expandHome(args.file.trim().replace(/^['"]|['"]$/g, ""));
@@ -1205,7 +1313,7 @@ async function addBook(store, args, signal) {
1205
1313
  });
1206
1314
  source = { type: "pdf", path: file, pageCount: info.pageCount };
1207
1315
  title = basename(file, extname(file));
1208
- outline = info.outline.map((c) => ({
1316
+ outline2 = info.outline.map((c) => ({
1209
1317
  title: c.title,
1210
1318
  ...c.page !== void 0 ? { loc: String(c.page) } : {},
1211
1319
  sections: c.sections.map((s) => ({ title: s.title, ...s.page !== void 0 ? { loc: String(s.page) } : {} }))
@@ -1216,7 +1324,7 @@ async function addBook(store, args, signal) {
1216
1324
  }
1217
1325
  if (typeof args.title === "string" && args.title.trim() !== "") title = args.title.trim();
1218
1326
  cancelled();
1219
- return addCell(store, { kind: "book", title, subtitle: args.subtitle, source, parentId: args.parentId, targetDate: args.targetDate, outline, outlineSource });
1327
+ return addCell(store, { kind: "book", title, subtitle: args.subtitle, source, parentId: args.parentId, targetDate: args.targetDate, outline: outline2, outlineSource });
1220
1328
  }
1221
1329
  function isZip(file) {
1222
1330
  const fd = openSync(file, "r");
@@ -1233,7 +1341,7 @@ function findAttachment(ref) {
1233
1341
  const home = process.env.DSH_HOME ?? join4(homedir(), ".dsh");
1234
1342
  const dir = join4(home, "attachments", "v1", "objects", hex.slice(0, 2));
1235
1343
  if (!existsSync3(dir)) return void 0;
1236
- const name2 = readdirSync(dir).find((f) => f.startsWith(hex));
1344
+ const name2 = readdirSync2(dir).find((f) => f.startsWith(hex));
1237
1345
  return name2 === void 0 ? void 0 : join4(dir, name2);
1238
1346
  }
1239
1347
  var IMAGE_EXTS = /* @__PURE__ */ new Set([".png", ".jpg", ".jpeg", ".webp", ".gif"]);
@@ -1244,10 +1352,221 @@ function saveImage(store, ref) {
1244
1352
  if (source === void 0) return void 0;
1245
1353
  const ext = IMAGE_EXTS.has(extname(source).toLowerCase()) ? extname(source).toLowerCase() : ".png";
1246
1354
  const name2 = `${newId("img")}${ext}`;
1355
+ store.assertWritable();
1356
+ store.snapshotBeforeWrite();
1357
+ mkdirSync3(store.imagesDir, { recursive: true });
1247
1358
  copyFileSync(source, join4(store.imagesDir, name2));
1248
1359
  return name2;
1249
1360
  }
1250
1361
 
1362
+ // src/host/weread.ts
1363
+ import { randomUUID } from "node:crypto";
1364
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync3, realpathSync, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
1365
+ import { homedir as homedir2 } from "node:os";
1366
+ import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute2, join as join5, relative, sep as sep2 } from "node:path";
1367
+ import { setTimeout as delay } from "node:timers/promises";
1368
+ var GATEWAY = "https://i.weread.qq.com/api/agent/gateway";
1369
+ var SKILL_VERSION = "1.0.6";
1370
+ var validKey = (key) => typeof key === "string" && /^wrk-[A-Za-z0-9_-]+$/.test(key);
1371
+ var keyFile = join5(homedir2(), ".dsh-palace", "weread.json");
1372
+ function readKey(file = keyFile) {
1373
+ try {
1374
+ const { key } = JSON.parse(readFileSync3(file, "utf8"));
1375
+ if (validKey(key)) return key;
1376
+ } catch (error) {
1377
+ if (error.code === "ENOENT") return void 0;
1378
+ }
1379
+ throw new ShelfError("\u65E0\u6CD5\u8BFB\u53D6\u5FAE\u4FE1\u8BFB\u4E66 Key\uFF0C\u8BF7\u5728\u5BAB\u6BBF\u91CD\u65B0\u4FDD\u5B58");
1380
+ }
1381
+ function wereadKey(key, file = keyFile, dataDir) {
1382
+ if (key === void 0) return readKey(file) !== void 0;
1383
+ if (key !== null && !validKey(key)) throw new ShelfError("\u8BF7\u8F93\u5165\u6709\u6548\u7684\u5FAE\u4FE1\u8BFB\u4E66 API Key");
1384
+ const stage = file + "." + randomUUID();
1385
+ try {
1386
+ if (key === null) {
1387
+ rmSync2(file, { force: true });
1388
+ return false;
1389
+ }
1390
+ mkdirSync4(dirname2(file), { recursive: true, mode: 448 });
1391
+ if (dataDir !== void 0) {
1392
+ const location = relative(realpathSync(dataDir), join5(realpathSync(dirname2(file)), basename2(file)));
1393
+ 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");
1394
+ }
1395
+ writeFileSync3(stage, JSON.stringify({ key }), { mode: 384, flag: "wx" });
1396
+ renameSync3(stage, file);
1397
+ return true;
1398
+ } catch (error) {
1399
+ if (error instanceof ShelfError) throw error;
1400
+ throw new ShelfError("\u65E0\u6CD5\u4FDD\u5B58\u6216\u5220\u9664\u5FAE\u4FE1\u8BFB\u4E66 Key");
1401
+ } finally {
1402
+ try {
1403
+ rmSync2(stage, { force: true });
1404
+ } catch {
1405
+ }
1406
+ }
1407
+ }
1408
+ var positionKey = ({ chapterUid, range }) => chapterUid != null && range?.trim() ? JSON.stringify([String(chapterUid), range]) : void 0;
1409
+ var responseList = {
1410
+ "/shelf/sync": "books",
1411
+ "/user/notebooks": "books",
1412
+ "/review/list/mine": "reviews",
1413
+ "/book/chapterinfo": "chapters",
1414
+ "/book/bookmarklist": "updated"
1415
+ };
1416
+ function outline(chapters, cards) {
1417
+ const result = [];
1418
+ for (const chapter of chapters) {
1419
+ const title = chapter.title?.trim();
1420
+ if (!title) continue;
1421
+ const level = chapter.level ?? 1;
1422
+ const row = { title, loc: String(chapter.chapterUid), sections: [] };
1423
+ if (level === 1 || level === 2 && !result.length) result.push(row);
1424
+ else if (level === 2) result.at(-1).sections.push({ title: row.title, loc: row.loc });
1425
+ }
1426
+ const marked = new Set(cards.map((card) => card.sectionKey));
1427
+ for (const row of result) {
1428
+ if (row.sections?.length && row.loc && marked.has(row.loc)) row.sections.unshift({ title: row.title, loc: row.loc });
1429
+ }
1430
+ return result;
1431
+ }
1432
+ function createWeRead(fetcher = fetch, keyReader = readKey) {
1433
+ const inFlight = /* @__PURE__ */ new Set();
1434
+ async function request(key, api_name, params, signal, retried = false) {
1435
+ async function send() {
1436
+ const deadline = AbortSignal.timeout(12e3);
1437
+ const requestSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
1438
+ const response = await fetcher(GATEWAY, {
1439
+ method: "POST",
1440
+ redirect: "error",
1441
+ signal: requestSignal,
1442
+ headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
1443
+ body: JSON.stringify({ api_name, skill_version: SKILL_VERSION, ...params })
1444
+ });
1445
+ return { response, data: response.ok ? await response.json() : {} };
1446
+ }
1447
+ try {
1448
+ while (inFlight.size >= 3) {
1449
+ signal?.throwIfAborted();
1450
+ await Promise.race(inFlight).catch(() => void 0);
1451
+ }
1452
+ signal?.throwIfAborted();
1453
+ const task = send();
1454
+ inFlight.add(task);
1455
+ const { response, data } = await task.finally(() => inFlight.delete(task));
1456
+ const code = Number(data?.errcode || response.status);
1457
+ if (code === 429) {
1458
+ const seconds = Number(response.headers.get("retry-after") ?? 1);
1459
+ if (seconds >= 0 && seconds <= 3 && !retried) {
1460
+ await delay(seconds * 1e3, void 0, { signal });
1461
+ return request(key, api_name, params, signal, true);
1462
+ }
1463
+ throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
1464
+ }
1465
+ if (code === 401 || code === 403) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u9274\u6743\u5931\u8D25\uFF0C\u8BF7\u66F4\u6362 API Key");
1466
+ 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");
1467
+ if (!Array.isArray(data[responseList[api_name]])) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u56DE\u5305\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u91CD\u8BD5");
1468
+ return data;
1469
+ } catch (error) {
1470
+ if (error instanceof ShelfError) throw error;
1471
+ if (signal?.aborted) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u5BFC\u5165\u5DF2\u53D6\u6D88");
1472
+ throw new ShelfError("\u8FDE\u63A5\u5FAE\u4FE1\u8BFB\u4E66\u5931\u8D25\u6216\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5");
1473
+ }
1474
+ }
1475
+ function currentKey() {
1476
+ const key = keyReader();
1477
+ if (!key) throw new ShelfError("\u8BF7\u5148\u5728\u5BAB\u6BBF\u300C\u4ECE\u5FAE\u4FE1\u8BFB\u4E66\u5BFC\u5165\u300D\u91CC\u4FDD\u5B58 API Key");
1478
+ return key;
1479
+ }
1480
+ async function shelf(key, signal) {
1481
+ const main = await request(key, "/shelf/sync", {}, signal);
1482
+ const books = new Map(main.books.map((book) => [book.bookId, { ...book, hasNotes: false }]));
1483
+ let lastSort;
1484
+ while (true) {
1485
+ const page = await request(key, "/user/notebooks", { count: 100, lastSort }, signal);
1486
+ for (const entry of page.books) {
1487
+ const book = books.get(entry.bookId) ?? entry.book;
1488
+ if (book) books.set(entry.bookId, { ...book, bookId: entry.bookId, hasNotes: Boolean(entry.noteCount || entry.reviewCount) });
1489
+ }
1490
+ if (!page.hasMore) break;
1491
+ const next = page.books.at(-1)?.sort;
1492
+ 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");
1493
+ lastSort = next;
1494
+ }
1495
+ return { books, total: main.books.length + (main.albums?.length ?? 0) + Number(Object.keys(main.mp ?? {}).length > 0) };
1496
+ }
1497
+ let listing;
1498
+ let prepared;
1499
+ return {
1500
+ async scan(signal) {
1501
+ const key = currentKey();
1502
+ listing = { key, data: await shelf(key, signal) };
1503
+ prepared = void 0;
1504
+ const { books, total } = listing.data;
1505
+ return { total, withNotes: [...books.values()].filter((book) => book.hasNotes).length, books: [...books.values()].map(
1506
+ ({ bookId, title, author, category, finishReading, readUpdateTime, publishTime, hasNotes }) => ({ bookId, title, author, category, finished: finishReading === 1, readUpdateTime, publishTime, hasNotes })
1507
+ ) };
1508
+ },
1509
+ async prepare(plan, confirming, signal) {
1510
+ if (!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");
1511
+ const key = currentKey(), ids = [...new Set(plan)], fingerprint = JSON.stringify(ids);
1512
+ if (confirming && prepared?.key === key && prepared.plan === fingerprint) return prepared.batch;
1513
+ 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");
1514
+ const { books } = listing?.key === key ? listing.data : await shelf(key, signal);
1515
+ const groups = [];
1516
+ for (const id of ids) {
1517
+ const book = books.get(id);
1518
+ if (!book) throw new ShelfError("\u9009\u4E2D\u7684\u4E66\u4E0D\u5728\u4E66\u67B6\u6216\u7B14\u8BB0\u672C\u91CC\uFF0C\u8BF7\u91CD\u65B0\u626B\u63CF");
1519
+ const href = [book.readerLink, book.deepLink].find((link) => typeof link === "string" && /^https?:\/\//.test(link));
1520
+ const group = { key: id, kind: "book", title: book.title, href, cards: [] };
1521
+ groups.push(group);
1522
+ if (!book.hasNotes) continue;
1523
+ const reviews = async () => {
1524
+ const rows = [];
1525
+ let synckey = 0;
1526
+ while (true) {
1527
+ const page = await request(key, "/review/list/mine", { bookid: id, synckey, count: 100 }, signal);
1528
+ rows.push(...page.reviews);
1529
+ if (!page.hasMore) return rows;
1530
+ 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");
1531
+ synckey = page.synckey;
1532
+ }
1533
+ };
1534
+ const [toc, marks, notes] = await Promise.all([
1535
+ request(key, "/book/chapterinfo", { bookId: id }, signal),
1536
+ request(key, "/book/bookmarklist", { bookId: id }, signal),
1537
+ reviews()
1538
+ ]);
1539
+ const cards = /* @__PURE__ */ new Map();
1540
+ const highlights = /* @__PURE__ */ new Map();
1541
+ for (const row of marks.updated) if (row.markText?.trim()) {
1542
+ const key2 = JSON.stringify([id, "bookmark", row.bookmarkId]);
1543
+ const card = { key: key2, type: "excerpt", quote: row.markText, sectionKey: row.chapterUid?.toString() };
1544
+ cards.set(key2, card);
1545
+ const position = positionKey(row);
1546
+ if (position !== void 0) highlights.set(position, card);
1547
+ }
1548
+ const reviewsById = new Map(notes.map(({ review }) => [review.reviewId, review]));
1549
+ for (const row of reviewsById.values()) if (row.abstract?.trim() || row.content?.trim()) {
1550
+ const position = positionKey(row);
1551
+ const highlight = position === void 0 ? void 0 : highlights.get(position);
1552
+ if (highlight) {
1553
+ if (row.content?.trim()) highlight.note = highlight.note ? highlight.note + "\n\n" + row.content : row.content;
1554
+ continue;
1555
+ }
1556
+ const key2 = JSON.stringify([id, "review", row.reviewId]);
1557
+ cards.set(key2, { key: key2, type: row.abstract?.trim() ? "excerpt" : "thought", quote: row.abstract || void 0, note: row.content, sectionKey: row.chapterUid?.toString() });
1558
+ }
1559
+ group.cards = [...cards.values()];
1560
+ group.chapters = outline(toc.chapters, group.cards);
1561
+ }
1562
+ const batch = { source: "weread", groups, links: [] };
1563
+ prepared = { key, plan: fingerprint, batch };
1564
+ return batch;
1565
+ }
1566
+ };
1567
+ }
1568
+ var weread = createWeRead();
1569
+
1251
1570
  // src/host/dictionary.ts
1252
1571
  import { execFile } from "node:child_process";
1253
1572
  var SCRIPT = `ObjC.import('CoreServices')
@@ -1323,8 +1642,8 @@ function streamFile(file, type) {
1323
1642
  return new Response(body, { headers: { "content-type": type, "content-length": String(size), "cache-control": "no-store" } });
1324
1643
  }
1325
1644
  function displayPath(path) {
1326
- const home = homedir2();
1327
- return path === home || path.startsWith(home + sep2) ? "~" + path.slice(home.length) : path;
1645
+ const home = homedir3();
1646
+ return path === home || path.startsWith(home + sep3) ? "~" + path.slice(home.length) : path;
1328
1647
  }
1329
1648
  function openExternal(target) {
1330
1649
  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" });
@@ -1385,6 +1704,7 @@ function createRoutes(store, active, memory = new Memory(store)) {
1385
1704
  }
1386
1705
  });
1387
1706
  return [
1707
+ route("POST", "weread-key", ({ body }) => json({ ok: true, saved: wereadKey(body.key, void 0, store.dir) })),
1388
1708
  route("GET", "palace", () => json({
1389
1709
  ok: true,
1390
1710
  rev: store.rev,
@@ -1434,8 +1754,8 @@ function createRoutes(store, active, memory = new Memory(store)) {
1434
1754
  return json({ ok: true, pages: texts, scanned });
1435
1755
  }),
1436
1756
  route("GET", "image", ({ url }) => {
1437
- const name2 = basename2(url.searchParams.get("name") ?? "");
1438
- const file = join5(store.imagesDir, name2);
1757
+ const name2 = basename3(url.searchParams.get("name") ?? "");
1758
+ const file = join6(store.imagesDir, name2);
1439
1759
  const type = IMAGE_TYPES[extname2(name2).toLowerCase()];
1440
1760
  if (name2 === "" || type === void 0 || !existsSync4(file)) return new Response("not found", { status: 404 });
1441
1761
  return streamFile(file, type);
@@ -1446,13 +1766,13 @@ function createRoutes(store, active, memory = new Memory(store)) {
1446
1766
  if (rel.startsWith("reader/")) {
1447
1767
  const name2 = rel.slice("reader/".length);
1448
1768
  if (!READER_SCRIPTS.includes(name2)) return new Response("not found", { status: 404 });
1449
- const response2 = streamFile(join5(vendorDir(), name2), "text/javascript; charset=utf-8");
1769
+ const response2 = streamFile(join6(vendorDir(), name2), "text/javascript; charset=utf-8");
1450
1770
  response2.headers.set("cache-control", "public, max-age=86400");
1451
1771
  return response2;
1452
1772
  }
1453
- 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("/"));
1773
+ 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("/"));
1454
1774
  if (theme !== null) {
1455
- const file2 = join5(vendorDir(), rel);
1775
+ const file2 = join6(vendorDir(), rel);
1456
1776
  if (!existsSync4(file2)) return new Response("not found", { status: 404 });
1457
1777
  const response2 = streamFile(file2, THEME_TYPES[theme[1]]);
1458
1778
  response2.headers.set("cache-control", "public, max-age=86400");
@@ -1460,15 +1780,15 @@ function createRoutes(store, active, memory = new Memory(store)) {
1460
1780
  }
1461
1781
  const font = /^fonts\/([a-z0-9][a-z0-9-]{0,60})\.woff2$/.exec(rel)?.[1];
1462
1782
  if (font !== void 0) {
1463
- const file2 = join5(vendorDir(), "fonts", `${font}.woff2`);
1783
+ const file2 = join6(vendorDir(), "fonts", `${font}.woff2`);
1464
1784
  if (!existsSync4(file2)) return new Response("not found", { status: 404 });
1465
1785
  const response2 = streamFile(file2, "font/woff2");
1466
1786
  response2.headers.set("cache-control", "public, max-age=31536000, immutable");
1467
1787
  return response2;
1468
1788
  }
1469
1789
  const allowed = ["cmaps", "standard_fonts", "wasm", "iccs"];
1470
- if (!allowed.some((dir) => rel.startsWith(dir + sep2)) || rel.includes("..")) return new Response("not found", { status: 404 });
1471
- const file = join5(pdfjsDistDir(), rel);
1790
+ if (!allowed.some((dir) => rel.startsWith(dir + sep3)) || rel.includes("..")) return new Response("not found", { status: 404 });
1791
+ const file = join6(pdfjsDistDir(), rel);
1472
1792
  if (!existsSync4(file)) return new Response("not found", { status: 404 });
1473
1793
  const response = streamFile(file, file.endsWith(".wasm") ? "application/wasm" : "application/octet-stream");
1474
1794
  response.headers.set("cache-control", "public, max-age=31536000, immutable");
@@ -1477,10 +1797,19 @@ function createRoutes(store, active, memory = new Memory(store)) {
1477
1797
  route("POST", "pick-file", async () => json({ ok: true, path: await pickBook() })),
1478
1798
  // 只打开格子里登记过的东西,不接受任意路径
1479
1799
  route("POST", "open", ({ body }) => {
1800
+ if (body.target === "welcome") {
1801
+ openExternal(WELCOME_URL);
1802
+ return json({ ok: true });
1803
+ }
1480
1804
  if (body.target === "dataDir") {
1481
1805
  openExternal(store.dir);
1482
1806
  return json({ ok: true });
1483
1807
  }
1808
+ const linked = store.getPalace().cells.find((c) => c.id === body.id)?.href;
1809
+ if (linked !== void 0 && /^https?:\/\//.test(linked)) {
1810
+ openExternal(linked);
1811
+ return json({ ok: true });
1812
+ }
1484
1813
  const item = itemOf2(store, body.id);
1485
1814
  const section = findSection(item, typeof body.sectionId === "string" ? body.sectionId : void 0)?.section;
1486
1815
  const source = item.source;
@@ -1504,12 +1833,104 @@ function createRoutes(store, active, memory = new Memory(store)) {
1504
1833
  ];
1505
1834
  }
1506
1835
 
1507
- // src/host/tools.ts
1836
+ // src/host/harness/tools.ts
1508
1837
  import { defineTool } from "@deepseek-ai/dsh-tools";
1509
- var stringOut = {
1510
- schema: { type: "string" },
1511
- render: (_args, value) => [{ type: "text", text: value }]
1512
- };
1838
+
1839
+ // src/core/import.ts
1840
+ import { createHash } from "node:crypto";
1841
+ var digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
1842
+ var stableId = (prefix, ...key) => `${prefix}_${digest(key).slice(0, 10)}`;
1843
+ async function importBatch(store, memory, batch, confirmation, onlyNew = false) {
1844
+ const palace = store.getPalace();
1845
+ const cells = new Map(palace.cells.map((cell) => [cell.id, cell]));
1846
+ const placed = /* @__PURE__ */ new Map();
1847
+ for (const cell of palace.cells) {
1848
+ if (cell.kind === "group") continue;
1849
+ for (const card of store.getItem(cell.id).cards) {
1850
+ if (card.importSource?.source === batch.source) placed.set(card.importSource.key, { cell, card });
1851
+ }
1852
+ }
1853
+ const newCells = /* @__PURE__ */ new Map();
1854
+ const outlines = /* @__PURE__ */ new Map();
1855
+ const selected = /* @__PURE__ */ new Map();
1856
+ const at = nowIso();
1857
+ for (const group of batch.groups) {
1858
+ const id = group.itemId ?? stableId("c", batch.source, group.key);
1859
+ let target = cells.get(id) ?? newCells.get(id);
1860
+ 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");
1861
+ if (target === void 0 && (group.kind === "book" || group.cards.some((card) => !placed.has(card.key)))) {
1862
+ target = { id, kind: group.kind ?? "note", title: group.title, href: group.href, parentId: null, col: 0, row: 0, createdAt: at };
1863
+ newCells.set(id, target);
1864
+ }
1865
+ if (target && group.chapters?.length && (newCells.has(id) || store.getItem(id).chapters.length === 0)) outlines.set(id, group.chapters);
1866
+ for (const input of group.cards) {
1867
+ if (selected.has(input.key)) throw new ShelfError(`\u65B9\u6848\u91CC\u91CD\u590D\u51FA\u73B0\uFF1A${input.key}`);
1868
+ const previous = placed.get(input.key);
1869
+ 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}`);
1870
+ const content = digest(input.type === void 0 ? [input.note, input.frontmatter] : [input.type, input.note, input.quote, input.sectionKey]);
1871
+ const card = {
1872
+ ...previous?.card ?? { id: stableId("k", batch.source, input.key), type: input.type ?? "thought", quote: input.quote, createdAt: at },
1873
+ note: previous?.card.importSource?.digest === content ? previous.card.note : input.note,
1874
+ importSource: { source: batch.source, key: input.key, digest: content, frontmatter: input.frontmatter }
1875
+ };
1876
+ selected.set(input.key, { cell: previous?.cell ?? target, card, previous: previous?.card, sectionKey: input.sectionKey });
1877
+ }
1878
+ }
1879
+ const links = [];
1880
+ const occurrences = /* @__PURE__ */ new Map();
1881
+ for (const link of batch.links) {
1882
+ const from = selected.get(link.from);
1883
+ const to = selected.get(link.to) ?? placed.get(link.to);
1884
+ if (!from || !to || from.cell.id === to.cell.id) continue;
1885
+ const pair = JSON.stringify([link.from, link.to]);
1886
+ const occurrence = (occurrences.get(pair) ?? 0) + 1;
1887
+ occurrences.set(pair, occurrence);
1888
+ const sourceKey = digest([batch.source, pair, occurrence, from.cell.id, to.cell.id]);
1889
+ 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 });
1890
+ }
1891
+ const changed = [...selected.values()].filter(({ previous, card }) => previous === void 0 || !onlyNew && previous.importSource?.digest !== card.importSource?.digest);
1892
+ const { pending, arcs, strands } = memory.previewImportedLinks(
1893
+ links.map(({ sourceKey, from, to, why, evidence }) => ({ sourceKey, from, to, why, evidence }))
1894
+ );
1895
+ const summary = {
1896
+ cells: newCells.size,
1897
+ cards: changed.filter((x) => !x.previous).length,
1898
+ updatedCards: changed.filter((x) => x.previous).length,
1899
+ arcs,
1900
+ strands
1901
+ };
1902
+ const token = digest([batch, [...selected].map(([key, x]) => [key, x.cell.id, x.previous?.id]), links, pending, [...outlines.keys()], summary]);
1903
+ if (confirmation === void 0) return { preview: true, ...summary, token };
1904
+ 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");
1905
+ if (changed.length || newCells.size || outlines.size) {
1906
+ await store.mutate((tx) => {
1907
+ for (const cell of newCells.values()) {
1908
+ Object.assign(cell, firstEmptySlot(tx.palace, null));
1909
+ tx.palace.cells.push(cell);
1910
+ tx.createItem(emptyItem(cell.id, null));
1911
+ }
1912
+ for (const [id, chapters] of outlines) tx.item(id).chapters = buildChapters(chapters);
1913
+ for (const { cell, card, previous, sectionKey } of changed) {
1914
+ const item = tx.item(cell.id);
1915
+ if (sectionKey !== void 0) card.sectionId = item.chapters.flatMap((chapter) => chapter.sections).find((section) => section.loc === sectionKey)?.id;
1916
+ const { cards } = item;
1917
+ const index = previous === void 0 ? -1 : cards.findIndex((value) => value.id === previous.id);
1918
+ if (index === -1) cards.push(card);
1919
+ else cards[index] = card;
1920
+ }
1921
+ });
1922
+ }
1923
+ memory.addImportedLinks(pending);
1924
+ const active = new Set(memory.validLinks().map((link) => link.sourceKey));
1925
+ const pairs = /* @__PURE__ */ new Map();
1926
+ for (const { sourceKey, from, to, fromPath, toPath, evidence } of links) {
1927
+ if (active.has(sourceKey)) pairs.set([from, to].sort().join(":"), { from, to, fromPath, toPath, evidence });
1928
+ if (pairs.size === 20) break;
1929
+ }
1930
+ return { preview: false, ...summary, links: [...pairs.values()] };
1931
+ }
1932
+
1933
+ // src/core/tools.ts
1513
1934
  var KIND_LABEL = { book: "\u4E66", note: "\u7B14\u8BB0", group: "\u5206\u7EC4" };
1514
1935
  var CARD_LABEL = { excerpt: "\u6458\u5F55", thought: "\u60F3\u6CD5", mistake: "\u9519\u9898" };
1515
1936
  function cellLine(store, c, active) {
@@ -1545,12 +1966,12 @@ function itemDetail(store, id) {
1545
1966
  const cell = store.getPalace().cells.find((c) => c.id === id);
1546
1967
  if (cell === void 0 || cell.kind === "group") throw new ShelfError("\u683C\u5B50\u4E0D\u5B58\u5728");
1547
1968
  const item = store.getItem(id);
1548
- const outline = item.chapters.length === 0 ? "\uFF08\u8FD8\u6CA1\u6709\u76EE\u5F55\uFF09" : item.chapters.map((c, i) => `${i + 1}. ${c.title}
1969
+ const outline2 = item.chapters.length === 0 ? "\uFF08\u8FD8\u6CA1\u6709\u76EE\u5F55\uFF09" : item.chapters.map((c, i) => `${i + 1}. ${c.title}
1549
1970
  ${c.sections.map((s) => ` - ${s.done ? "[x]" : "[ ]"} ${s.title} (section_id=${s.id})`).join("\n")}`).join("\n");
1550
1971
  const cards = item.cards.slice(-20).map((k) => `- ${CARD_LABEL[k.type]} ${k.id}\uFF1A${(k.quote ?? k.note ?? "").slice(0, 60)}`).join("\n");
1551
1972
  const insps = item.inspirations.slice(-10).map((i) => `- ${i.id} ${i.createdAt.slice(0, 10)} ${i.title}`).join("\n");
1552
1973
  return `\u300A${cell.title}\u300B\u76EE\u5F55\uFF1A
1553
- ${outline}` + (cards ? `
1974
+ ${outline2}` + (cards ? `
1554
1975
 
1555
1976
  \u6700\u8FD1\u7684\u5361\u7247\uFF1A
1556
1977
  ${cards}` : "") + (insps ? `
@@ -1570,42 +1991,25 @@ async function guard(run) {
1570
1991
  throw error;
1571
1992
  }
1572
1993
  }
1573
- function createTools(store, active, memory = new Memory(store)) {
1574
- const nudged = /* @__PURE__ */ new Set();
1575
- const nudge = (exec, id, kind) => {
1576
- const key = `${exec.agent?.id ?? ""}:${id}:${kind}`;
1577
- if (nudged.has(key)) return "";
1578
- if (kind === "wiki") {
1579
- const debt = memory.debt(id);
1580
- if (debt < 3) return "";
1581
- nudged.add(key);
1582
- return `
1583
- \uFF08\u63D0\u793A\uFF1A\u8FD9\u4E00\u683C\u7684 wiki \u4E4B\u540E\u65B0\u589E\u4E86 ${debt} \u6761\u5361\u7247 / \u7075\u611F\uFF0C\u804A\u5B8C\u65B9\u4FBF\u65F6\u7528 palace_wiki_write \u66F4\u65B0\uFF1B\u4E0D\u7528\u6253\u65AD\u7528\u6237\u3002\uFF09`;
1994
+ function createOverviewTool(store, currentItem) {
1995
+ return {
1996
+ name: "palace_overview",
1997
+ 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",
1998
+ parameters: {
1999
+ item_id: { type: "string", description: "\u53EF\u9009\uFF1A\u67E5\u770B\u8FD9\u4E2A\u683C\u5B50\u7684\u8BE6\u60C5" }
2000
+ },
2001
+ async execute(args, options) {
2002
+ return guard(async () => args.item_id === void 0 ? describe(store, options.highlightId) : itemDetail(store, args.item_id));
1584
2003
  }
1585
- nudged.add(key);
1586
- 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";
1587
- };
1588
- const activeOf = (exec) => exec.agent ? active.get(exec.agent.id) : void 0;
1589
- const targetOf = (given, exec) => {
1590
- const id = typeof given === "string" && given !== "" ? given : activeOf(exec);
1591
- if (id === void 0) throw new ShelfError("\u4E0D\u77E5\u9053\u8BB0\u5230\u54EA\u4E2A\u683C\u5B50\uFF1A\u7528\u6237\u6CA1\u6709\u6253\u5F00\u683C\u5B50\u3002\u8BF7\u5148\u7528 palace_overview \u67E5\u770B\u540E\u6307\u5B9A item_id\uFF0C\u6216\u8BF7\u7528\u6237\u5728\u53F3\u4FA7 Memory Palace \u6253\u5F00\u5BF9\u5E94\u7684\u4E66\u3002");
1592
- return id;
1593
2004
  };
2005
+ }
2006
+ function createPalaceTools(store, memory, sources) {
2007
+ const itemId = sources.currentItem ? { type: "string" } : { type: "string", minLength: 1, required: true, description: "\u76EE\u6807\u683C\u5B50 id" };
1594
2008
  return [
1595
- defineTool({
1596
- name: "palace_overview",
1597
- 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",
1598
- parameters: {
1599
- item_id: { type: "string", description: "\u53EF\u9009\uFF1A\u67E5\u770B\u8FD9\u4E2A\u683C\u5B50\u7684\u8BE6\u60C5" }
1600
- },
1601
- output: stringOut,
1602
- async execute(args, exec) {
1603
- return guard(async () => args.item_id === void 0 ? describe(store, activeOf(exec)) : itemDetail(store, args.item_id));
1604
- }
1605
- }),
1606
- defineTool({
2009
+ createOverviewTool(store, sources.currentItem),
2010
+ {
1607
2011
  name: "palace_add",
1608
- 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",
2012
+ 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,
1609
2013
  parameters: {
1610
2014
  kind: { type: "string", enum: ["group", "note", "book"], required: true },
1611
2015
  title: { type: "string" },
@@ -1615,14 +2019,13 @@ function createTools(store, active, memory = new Memory(store)) {
1615
2019
  url: { type: "string", description: "book\uFF1A\u89C6\u9891\u94FE\u63A5\uFF08http / https\uFF09" },
1616
2020
  target_date: { type: "string" }
1617
2021
  },
1618
- output: stringOut,
1619
- async execute(args, exec) {
2022
+ async execute(args, options) {
1620
2023
  return guard(async () => {
1621
2024
  if (args.kind !== "book") {
1622
2025
  const c2 = await addCell(store, { kind: args.kind, title: args.title, subtitle: args.subtitle, parentId: args.parent_id });
1623
2026
  return `\u5DF2\u65B0\u5EFA${KIND_LABEL[c2.kind]}\u300C${c2.title}\u300D id=${c2.id}`;
1624
2027
  }
1625
- const c = await addBook(store, { file: args.path, url: args.url, title: args.title, subtitle: args.subtitle, parentId: args.parent_id, targetDate: args.target_date }, exec.signal);
2028
+ const c = await sources.addBook({ file: args.path, url: args.url, title: args.title, subtitle: args.subtitle, parentId: args.parent_id, targetDate: args.target_date }, options.signal);
1626
2029
  const item = store.getItem(c.id);
1627
2030
  const total = progressOf(item).total;
1628
2031
  if (item.source?.type === "video") {
@@ -1632,14 +2035,13 @@ function createTools(store, active, memory = new Memory(store)) {
1632
2035
  return `\u5DF2\u6DFB\u52A0\u300A${c.title}\u300B id=${c.id}\uFF0C\u5171 ${item.source?.type === "pdf" ? item.source.pageCount : "?"} \u9875\u3002` + (total > 0 ? `\u5DF2\u4ECE PDF \u4E66\u7B7E\u8BFB\u51FA\u76EE\u5F55\uFF1A${item.chapters.length} \u7AE0 ${total} \u8282\u3002` : "\u8FD9\u672C PDF \u6CA1\u6709\u4E66\u7B7E\uFF0C\u9700\u8981\u751F\u6210\u76EE\u5F55\uFF1A\u8BF7\u7528\u6237\u5728\u53F3\u4FA7\u7B14\u8BB0\u672C\u7684\u300C\u8FDB\u5EA6\u300D\u91CC\u52FE\u9009\u76EE\u5F55\u9875\uFF0C\u6216\u544A\u8BC9\u4F60\u76EE\u5F55\u5728\u7B2C\u51E0\u9875\uFF0C\u7136\u540E\u7528 palace_read \u8BFB\u53D6\u3002");
1633
2036
  });
1634
2037
  }
1635
- }),
1636
- defineTool({
2038
+ },
2039
+ {
1637
2040
  name: "palace_remove",
1638
2041
  description: "\u4ECE\u5BAB\u6BBF\u91CC\u5220\u6389\u4E00\u4E2A\u683C\u5B50\uFF08\u4E66\u3001\u7B14\u8BB0\u6216\u7A7A\u5206\u7EC4\uFF09\uFF0C\u8FDE\u540C\u5B83\u7684\u8FDB\u5EA6\u3001\u5361\u7247\u548C\u7075\u611F\uFF0C\u4E0D\u5220\u7535\u8111\u4E0A\u7684\u539F\u6587\u4EF6\u3002\u5206\u7EC4\u91CC\u6700\u540E\u4E00\u683C\u5220\u6389\u6216\u79FB\u51FA\u540E\uFF0C\u5206\u7EC4\u4F1A\u81EA\u52A8\u6D88\u5931\uFF0C\u4E0D\u7528\u518D\u5220\u3002\u4E0D\u53EF\u64A4\u9500\uFF1A\u8C03\u7528\u524D\u5FC5\u987B\u5148\u8BF4\u6E05\u8981\u5220\u7684\u662F\u54EA\u4E00\u4E2A\u3001\u4F1A\u4E22\u6389\u591A\u5C11\u5361\u7247\u548C\u7075\u611F\uFF0C\u7B49\u7528\u6237\u660E\u786E\u540C\u610F\u540E\u518D\u8C03\u7528\u3002\u5206\u7EC4\u91CC\u8FD8\u6709\u4E1C\u897F\u65F6\u4E0D\u80FD\u5220\u3002",
1639
2042
  parameters: {
1640
2043
  item_id: { type: "string", required: true }
1641
2044
  },
1642
- output: stringOut,
1643
2045
  async execute(args) {
1644
2046
  return guard(async () => {
1645
2047
  const cell = store.getPalace().cells.find((c) => c.id === args.item_id);
@@ -1649,34 +2051,33 @@ function createTools(store, active, memory = new Memory(store)) {
1649
2051
  return `\u5DF2\u5220\u9664${KIND_LABEL[cell.kind]}\u300C${cell.title}\u300D` + (item ? `\uFF08\u5361\u7247 ${item.cards.length} \u5F20\u3001\u7075\u611F ${item.inspirations.length} \u6761\uFF09` : "");
1650
2052
  });
1651
2053
  }
1652
- }),
1653
- defineTool({
2054
+ },
2055
+ {
1654
2056
  name: "palace_read",
1655
2057
  description: "\u8BFB\u53D6\u67D0\u672C PDF \u6307\u5B9A\u9875\u7684\u6587\u5B57\uFF08\u9875\u7801\u4E3A PDF \u7684\u9875\u5E8F\u53F7\uFF0C\u4ECE 1 \u5F00\u59CB\uFF0C\u4E0D\u662F\u4E66\u4E0A\u5370\u7684\u9875\u7801\uFF09\u3002\u7528\u4E8E\u8BFB\u53D6\u76EE\u5F55\u9875\u6765\u751F\u6210\u7AE0\u8282\u7ED3\u6784\u3002\u6BCF\u6B21\u6700\u591A 30 \u9875\u3002",
1656
2058
  parameters: {
1657
2059
  item_id: { type: "string", required: true },
1658
2060
  pages: { type: "array", items: { type: "integer" }, required: true, description: "PDF \u9875\u5E8F\u53F7\u5217\u8868" }
1659
2061
  },
1660
- output: stringOut,
1661
2062
  async execute(args) {
1662
2063
  return guard(async () => {
1663
2064
  const source = store.getItem(args.item_id).source;
1664
2065
  if (source?.type !== "pdf") throw new ShelfError("\u8FD9\u4E2A\u683C\u5B50\u4E0D\u662F PDF");
1665
2066
  const pages = [...new Set(args.pages)].slice(0, 30);
1666
- const texts = await readPageTexts(source.path, pages);
1667
- const scanned = texts.filter((t) => t.text.length < SCANNED_THRESHOLD).map((t) => t.page);
2067
+ const texts = await sources.readPageTexts(source.path, pages);
2068
+ const scanned = texts.filter((t) => t.text.length < sources.scannedThreshold).map((t) => t.page);
1668
2069
  let out = texts.map((t) => `=== \u7B2C ${t.page} \u9875 ===
1669
2070
  ${t.text || "\uFF08\u65E0\u6587\u5B57\uFF09"}`).join("\n\n");
1670
2071
  if (scanned.length > 0) {
1671
2072
  out += `
1672
2073
 
1673
- \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`;
2074
+ \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;
1674
2075
  }
1675
2076
  return out;
1676
2077
  });
1677
2078
  }
1678
- }),
1679
- defineTool({
2079
+ },
2080
+ {
1680
2081
  name: "palace_set_outline",
1681
2082
  description: "\u5199\u5165\uFF08\u8986\u76D6\uFF09\u4E66\u7684\u76EE\u5F55\u7ED3\u6784\uFF0C\u53EA\u8981\u4E24\u7EA7\uFF1A\u7AE0 \u203A \u8282\u3002\u6CA1\u6709\u5206\u8282\u7684\u7AE0\uFF0Csections \u7559\u7A7A\u5373\u53EF\uFF08\u4F1A\u81EA\u52A8\u7B97\u4F5C\u4E00\u8282\uFF09\u3002\u6807\u9898\u4FDD\u6301\u539F\u4E66\u5199\u6CD5\uFF0C\u53BB\u6389\u9875\u7801\u548C\u7701\u7565\u53F7\u3002\u91CD\u65B0\u751F\u6210\u76EE\u5F55\u65F6\uFF0C\u6807\u9898\u4E0D\u53D8\u7684\u8282\u4F1A\u4FDD\u7559\u5B8C\u6210\u72B6\u6001\u3002\u9875\u7801 page \u53EF\u9009\uFF0C\u586B PDF \u9875\u5E8F\u53F7\uFF08\u4E66\u4E0A\u5370\u7684\u9875\u7801 + \u504F\u79FB\u91CF\uFF09\uFF1B\u4E0D\u786E\u5B9A\u5C31\u4E0D\u586B\u3002\u89C6\u9891\u7684\u6BCF\u4E00\u96C6\u53EF\u4EE5\u586B url\uFF08\u8FD9\u4E00\u96C6\u7684\u64AD\u653E\u94FE\u63A5\uFF0Chttp / https\uFF09\uFF0C\u7528\u6237\u70B9\u300C\u64AD\u653E\u300D\u76F4\u63A5\u6253\u5F00\uFF1B\u4E0D\u586B\u5C31\u6253\u5F00\u4F5C\u54C1\u94FE\u63A5\u3002",
1682
2083
  parameters: {
@@ -1705,7 +2106,6 @@ ${t.text || "\uFF08\u65E0\u6587\u5B57\uFF09"}`).join("\n\n");
1705
2106
  }
1706
2107
  }
1707
2108
  },
1708
- output: stringOut,
1709
2109
  async execute(args) {
1710
2110
  return guard(async () => {
1711
2111
  let video = false;
@@ -1722,8 +2122,8 @@ ${t.text || "\uFF08\u65E0\u6587\u5B57\uFF09"}`).join("\n\n");
1722
2122
  return `\u5DF2\u5199\u5165\u76EE\u5F55\uFF1A${item.chapters.length} \u7AE0 ${progressOf(item).total} \u8282\u3002\u7528\u6237\u53EF\u4EE5\u5728\u53F3\u4FA7\u7B14\u8BB0\u672C\u91CC\u67E5\u770B\u548C\u6253\u52FE\u3002`;
1723
2123
  });
1724
2124
  }
1725
- }),
1726
- defineTool({
2125
+ },
2126
+ {
1727
2127
  name: "palace_set_target_dates",
1728
2128
  description: "\u8BBE\u7F6E\u4E66\u7684\u76EE\u6807\u5B8C\u6210\u65E5\u671F\uFF08YYYY-MM-DD\uFF09\uFF0C\u7528\u4E8E\u89C4\u5212\u8FDB\u5EA6\u3002\u53EF\u4E00\u6B21\u8BBE\u7F6E\u591A\u672C\u3002\u89C4\u5212\u65F6\u53C2\u8003\u5404\u4E66\u7684\u8282\u6570\uFF0C\u5E76\u7ED9\u590D\u4E60\u7559\u51FA\u65F6\u95F4\u3002\u8BBE\u7F6E\u524D\u5148\u548C\u7528\u6237\u786E\u8BA4\u65B9\u6848\u3002",
1729
2129
  parameters: {
@@ -1740,7 +2140,6 @@ ${t.text || "\uFF08\u65E0\u6587\u5B57\uFF09"}`).join("\n\n");
1740
2140
  }
1741
2141
  }
1742
2142
  },
1743
- output: stringOut,
1744
2143
  async execute(args) {
1745
2144
  return guard(async () => {
1746
2145
  const lines = [];
@@ -1754,58 +2153,55 @@ ${t.text || "\uFF08\u65E0\u6587\u5B57\uFF09"}`).join("\n\n");
1754
2153
  ${lines.join("\n")}`;
1755
2154
  });
1756
2155
  }
1757
- }),
1758
- defineTool({
2156
+ },
2157
+ {
1759
2158
  name: "palace_add_card",
1760
- 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",
2159
+ 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",
1761
2160
  parameters: {
1762
2161
  type: { type: "string", enum: ["mistake", "excerpt", "thought"], required: true },
1763
2162
  quote: { type: "string", description: "\u539F\u6587\u6216\u9898\u76EE" },
1764
2163
  note: { type: "string", description: "\u60F3\u6CD5\u3001\u6279\u6CE8\u6216\u9519\u56E0\uFF08\u7528\u6237\u8BF4\u4E86\u624D\u586B\uFF09" },
1765
2164
  answer: { type: "string", description: "\u9519\u9898\u7684\u7B54\u6848\u4E0E\u89E3\u6790" },
1766
- image: { type: "string", description: "\u622A\u56FE\u7684\u672C\u5730\u8DEF\u5F84\u6216\u9644\u4EF6 id" },
1767
- item_id: { type: "string" },
2165
+ image: { type: "string", description: sources.imageDescription },
2166
+ item_id: itemId,
1768
2167
  section_id: { type: "string" }
1769
2168
  },
1770
- output: stringOut,
1771
- async execute(args, exec) {
2169
+ async execute(args, options) {
1772
2170
  return guard(async () => {
1773
- const id = targetOf(args.item_id, exec);
2171
+ const id = args.item_id;
1774
2172
  const item = store.getItem(id);
1775
2173
  const sectionId = args.section_id ?? (args.type === "thought" ? void 0 : progressOf(item).current?.section.id);
1776
- const image = saveImage(store, args.image);
2174
+ const image = sources.saveImage(args.image);
1777
2175
  const card = await addCard(store, { id, type: args.type, quote: args.quote, note: args.note, answer: args.answer, image, sectionId });
1778
2176
  const title = store.getPalace().cells.find((c) => c.id === id)?.title;
1779
- return `\u5DF2\u8BB0\u5165\u300A${title}\u300B${where(store.getItem(id), card)}\u7684${CARD_LABEL[card.type]}` + (args.image ? image ? "\uFF0C\u539F\u56FE\u5DF2\u4FDD\u5B58\u3002" : "\u3002\uFF08\u6CA1\u6709\u627E\u5230\u539F\u56FE\uFF09" : "\u3002") + nudge(exec, id, "wiki");
2177
+ return `\u5DF2\u8BB0\u5165\u300A${title}\u300B${where(store.getItem(id), card)}\u7684${CARD_LABEL[card.type]}` + (args.image ? image ? "\uFF0C\u539F\u56FE\u5DF2\u4FDD\u5B58\u3002" : "\u3002\uFF08\u6CA1\u6709\u627E\u5230\u539F\u56FE\uFF09" : "\u3002") + (options.nudge?.(id, "wiki") ?? "");
1780
2178
  });
1781
2179
  }
1782
- }),
1783
- defineTool({
2180
+ },
2181
+ {
1784
2182
  name: "palace_add_inspiration",
1785
- 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",
2183
+ 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"),
1786
2184
  parameters: {
1787
2185
  title: { type: "string", required: true },
1788
2186
  body: { type: "string", required: true },
1789
- item_id: { type: "string" },
2187
+ item_id: itemId,
1790
2188
  card_ids: { type: "array", items: { type: "string" }, description: "\u53EF\u9009\uFF1A\u8FD9\u6B21\u5BF9\u8BDD\u6D89\u53CA\u7684\u5361\u7247" }
1791
2189
  },
1792
- output: stringOut,
1793
- async execute(args, exec) {
2190
+ async execute(args, options) {
1794
2191
  return guard(async () => {
1795
- const id = targetOf(args.item_id, exec);
1796
- const insp = await addInspiration(store, { id, title: args.title, body: args.body, cardIds: args.card_ids, sessionId: exec.agent?.id });
2192
+ const id = args.item_id;
2193
+ const insp = await addInspiration(store, { id, title: args.title, body: args.body, cardIds: args.card_ids, ...options.attribution });
1797
2194
  const title = store.getPalace().cells.find((c) => c.id === id)?.title;
1798
- return `\u5DF2\u5B58\u5230\u300A${title}\u300B\u7684\u7075\u611F\uFF1A\u300C${insp.title}\u300D id=${insp.id}` + nudge(exec, id, "link") + nudge(exec, id, "wiki");
2195
+ return `\u5DF2\u5B58\u5230\u300A${title}\u300B\u7684\u7075\u611F\uFF1A\u300C${insp.title}\u300D id=${insp.id}` + (options.nudge?.(id, "link") ?? "") + (options.nudge?.(id, "wiki") ?? "");
1799
2196
  });
1800
2197
  }
1801
- }),
1802
- defineTool({
2198
+ },
2199
+ {
1803
2200
  name: "palace_wiki_read",
1804
- 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",
2201
+ 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,
1805
2202
  parameters: {
1806
2203
  target: { type: "string", required: true, description: "\u683C\u5B50 id \u6216 me" }
1807
2204
  },
1808
- output: stringOut,
1809
2205
  async execute(args) {
1810
2206
  return guard(async () => {
1811
2207
  const page = memory.readPage(args.target);
@@ -1826,8 +2222,8 @@ ${page.body}` + (debt > 0 ? `
1826
2222
  ${page.body}`;
1827
2223
  });
1828
2224
  }
1829
- }),
1830
- defineTool({
2225
+ },
2226
+ {
1831
2227
  name: "palace_wiki_write",
1832
2228
  description: `\u6574\u9875\u91CD\u5199\u4E00\u9875\u8BB0\u5FC6\uFF08\u4F1A\u8986\u76D6\u65E7\u5185\u5BB9\uFF0C\u5148\u5728\u65E7\u5185\u5BB9\u57FA\u7840\u4E0A\u6539\uFF09\u3002\u6B63\u6587\u6700\u591A ${PAGE_LIMIT} \u5B57\uFF0C\u8D85\u4E86\u4F1A\u88AB\u62D2\u7EDD\uFF1A\u5408\u5E76\u76F8\u8FD1\u7684\u3001\u5220\u6389\u8FC7\u65F6\u7684\u518D\u5199\u3002target=me\uFF1A\u5173\u4E8E\u7528\u6237\u7684\u957F\u671F\u8BB0\u5FC6\uFF0C\u5206\u300C\u957F\u671F\u300D\u300C\u6700\u8FD1\u300D\u4E24\u6BB5\uFF0C\u53EA\u8BB0\u7528\u6237\u8BF4\u8FC7\u6216\u505A\u8FC7\u7684\u4E8B\u5B9E\uFF08\u559C\u597D\u3001\u6B63\u5728\u7ECF\u5386\u7684\u4E8B\u3001\u6DF1\u5165\u804A\u8FC7\u7684\u8BDD\u9898\uFF09\uFF0C\u4E0D\u8D34\u6027\u683C\u6807\u7B7E\u3002target=\u683C\u5B50 id\uFF1A\u8FD9\u4E00\u683C\u7684 wiki\uFF0C\u53EA\u5199\u5361\u7247\u548C\u7075\u611F\u91CC\u6CA1\u6709\u7684\u4E1C\u897F\uFF08\u5BF9\u7528\u6237\u610F\u5473\u7740\u4EC0\u4E48\u3001\u5361\u5728\u54EA\u3001\u53CD\u590D\u51FA\u73B0\u7684\u4E3B\u9898\u3001\u6CA1\u89E3\u51B3\u7684\u7591\u95EE\uFF09\uFF0C\u53E5\u672B\u7528 [^\u5361\u7247\u6216\u7075\u611F id] \u6807\u51FA\u4F9D\u636E\uFF1Bsummary \u4E00\u53E5\u8BDD\uFF08\u226440 \u5B57\uFF09\uFF0Ctopics 3\u20135 \u4E2A\u4E3B\u9898\u8BCD\uFF08\u81EA\u7531\u586B\u5199\uFF0C\u8DE8\u683C\u5B50\u76F8\u901A\u7684\u8BCD\u66F4\u597D\uFF0C\u6BD4\u5982\u300C\u7B49\u5F85\u300D\u300C\u5B64\u72EC\u300D\uFF09\u3002`,
1833
2229
  parameters: {
@@ -1836,7 +2232,6 @@ ${page.body}`;
1836
2232
  summary: { type: "string" },
1837
2233
  topics: { type: "array", items: { type: "string" } }
1838
2234
  },
1839
- output: stringOut,
1840
2235
  async execute(args) {
1841
2236
  return guard(async () => {
1842
2237
  const page = memory.writePage(args.target, { body: args.body, summary: args.summary, topics: args.topics });
@@ -1845,51 +2240,343 @@ ${page.body}`;
1845
2240
  return `\u5DF2\u66F4\u65B0\u300A${title}\u300B\u7684 wiki` + (page.topics?.length ? `\uFF08\u4E3B\u9898\u8BCD\uFF1A${page.topics.join("\u3001")}\uFF09` : "") + "\u3002";
1846
2241
  });
1847
2242
  }
1848
- }),
1849
- defineTool({
2243
+ },
2244
+ {
1850
2245
  name: "palace_link",
1851
- 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",
2246
+ 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",
1852
2247
  parameters: {
1853
2248
  from: { type: "string", required: true, description: "\u683C\u5B50 id" },
1854
2249
  to: { type: "string", required: true, description: "\u683C\u5B50 id" },
1855
2250
  why: { type: "string", required: true },
1856
- evidence: { type: "array", items: { type: "string" }, required: true, description: "\u5361\u7247 / \u7075\u611F id" },
2251
+ evidence: { type: "array", items: { type: "string" }, description: "\u8FDE\u7EBF\u5FC5\u586B\uFF1A\u5361\u7247 / \u7075\u611F id" },
2252
+ update_why: { type: "boolean", description: "\u53EA\u66F4\u65B0\u73B0\u6709\u7535\u5F27\u7684\u9898\u8BCD" },
1857
2253
  user_asked: { type: "boolean", description: "\u7528\u6237\u660E\u786E\u8981\u6C42\u8FDE\uFF08\u526A\u65AD\u8FC7\u7684\u4E5F\u80FD\u91CD\u8FDE\uFF09" }
1858
2254
  },
1859
- output: stringOut,
1860
- async execute(args, exec) {
2255
+ async execute(args, options) {
1861
2256
  return guard(async () => {
1862
- const link = memory.addLink({ from: args.from, to: args.to, why: args.why, evidence: args.evidence, sessionId: exec.agent?.id, userAsked: args.user_asked === true });
2257
+ if (args.update_why === true) {
2258
+ memory.retitleLink({ from: args.from, to: args.to, why: args.why });
2259
+ return "\u5DF2\u66F4\u65B0\u7535\u5F27\u9898\u8BCD\u3002";
2260
+ }
2261
+ const link = memory.addLink({ from: args.from, to: args.to, why: args.why, evidence: args.evidence, ...options.attribution, userAsked: args.user_asked === true });
1863
2262
  const cells = store.getPalace().cells;
1864
2263
  const arc = memory.arcs().find((a) => a.links.some((l) => l.id === link.id));
1865
2264
  return `\u5DF2\u8FDE\u4E0A\u300A${cells.find((c) => c.id === link.from)?.title}\u300B\u2194\u300A${cells.find((c) => c.id === link.to)?.title}\u300B\uFF1A${link.why}\uFF08\u73B0\u5728 ${arc?.strands ?? 1} \u80A1\uFF09`;
1866
2265
  });
1867
2266
  }
1868
- }),
1869
- defineTool({
2267
+ },
2268
+ {
1870
2269
  name: "palace_unlink",
1871
2270
  description: "\u526A\u65AD\u4E24\u683C\u4E4B\u95F4\u7684\u7535\u5F27\uFF08\u7528\u6237\u8BF4\u8FD9\u4E24\u4E2A\u6CA1\u5173\u7CFB\u3001\u8FDE\u9519\u4E86\u65F6\u8C03\u7528\uFF09\u3002\u4E4B\u524D\u7684\u8054\u60F3\u90FD\u4E0D\u518D\u663E\u793A\uFF0C\u4EE5\u540E\u4E5F\u4E0D\u4F1A\u81EA\u52A8\u518D\u8FDE\u3002",
1872
2271
  parameters: {
1873
2272
  from: { type: "string", required: true },
1874
2273
  to: { type: "string", required: true }
1875
2274
  },
1876
- output: stringOut,
1877
2275
  async execute(args) {
1878
2276
  return guard(async () => {
1879
2277
  memory.cut({ from: args.from, to: args.to });
1880
2278
  return "\u5DF2\u526A\u65AD\u3002";
1881
2279
  });
1882
2280
  }
1883
- })
2281
+ }
1884
2282
  ];
1885
2283
  }
2284
+ function createObsidianTools(store, memory, source) {
2285
+ const path = { type: "string", required: true, description: "\u7528\u6237\u63D0\u4F9B\u7684\u7B14\u8BB0\u5E93\u6587\u4EF6\u5939\u7EDD\u5BF9\u8DEF\u5F84" };
2286
+ return [
2287
+ {
2288
+ name: "palace_scan_obsidian",
2289
+ 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",
2290
+ parameters: { path, offset: { type: "integer", description: "\u4E0B\u4E00\u9875\u8D77\u70B9\uFF0C\u4F7F\u7528\u4E0A\u6B21\u8FD4\u56DE\u7684 nextOffset" } },
2291
+ async execute(args, options) {
2292
+ return guard(async () => JSON.stringify(await source.scan(args.path, args.offset, options.signal)));
2293
+ }
2294
+ },
2295
+ {
2296
+ name: "palace_import_obsidian",
2297
+ 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",
2298
+ parameters: {
2299
+ path,
2300
+ plan: {
2301
+ type: "array",
2302
+ items: { type: "object", additionalProperties: false, properties: {
2303
+ title: { type: "string", description: "\u65B0\u7B14\u8BB0\u683C\u5B50\u6807\u9898" },
2304
+ item_id: { type: "string", description: "\u5DF2\u6709\u4E66\u6216\u7B14\u8BB0\u683C\u5B50 id" },
2305
+ paths: { type: "array", items: { type: "string" }, description: "\u626B\u63CF\u8FD4\u56DE\u7684\u7B14\u8BB0\u76F8\u5BF9\u8DEF\u5F84" },
2306
+ 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" }
2307
+ } }
2308
+ },
2309
+ confirmation: { type: "string", description: "\u4EC5\u5728\u7528\u6237\u786E\u8BA4\u540E\u4F20\u5165\u9884\u89C8\u8FD4\u56DE\u7684 token" }
2310
+ },
2311
+ async execute(args, options) {
2312
+ return guard(async () => {
2313
+ if (args.confirmation !== void 0 && typeof args.confirmation !== "string") throw new ShelfError("\u786E\u8BA4\u503C\u5FC5\u987B\u662F\u9884\u89C8\u8FD4\u56DE\u7684 token");
2314
+ const batch = await source.prepare(args.path, args.plan, options.signal);
2315
+ options.signal?.throwIfAborted();
2316
+ return JSON.stringify(await importBatch(store, memory, batch, args.confirmation));
2317
+ });
2318
+ }
2319
+ }
2320
+ ];
2321
+ }
2322
+ function createWeReadTools(store, memory, source) {
2323
+ return [
2324
+ {
2325
+ name: "palace_scan_weread",
2326
+ description: "\u9884\u89C8\u5FAE\u4FE1\u8BFB\u4E66\u4E66\u67B6\u548C\u6709\u5212\u7EBF\u6216\u60F3\u6CD5\u7684\u4E66\u3002\u7528\u6237\u63D0\u51FA\u5BFC\u5165\u65F6\uFF0C\u5148\u7528\u8FD9\u4E9B\u4FE1\u606F\u5546\u91CF\u8981\u5BFC\u5165\u54EA\u4E9B\u4E66\u3002",
2327
+ parameters: {},
2328
+ async execute(_args, { signal }) {
2329
+ return guard(async () => JSON.stringify(await source.scan(signal)));
2330
+ }
2331
+ },
2332
+ {
2333
+ name: "palace_import_weread",
2334
+ description: "\u628A\u9009\u4E2D\u7684\u5FAE\u4FE1\u8BFB\u4E66\u4E66\u548C\u7B14\u8BB0\u5BFC\u5165\u5BAB\u6BBF\u3002plan \u586B\u626B\u63CF\u5F97\u5230\u7684 bookId \u5217\u8868\u3002\u5148\u7701\u7565 confirmation \u8FDB\u884C\u9884\u89C8\uFF0C\u7B49\u7528\u6237\u786E\u8BA4\u540E\u7528\u540C\u4E00\u65B9\u6848\u548C\u9884\u89C8\u7684 token \u5199\u5165\u3002",
2335
+ parameters: {
2336
+ plan: { type: "array", required: true, items: { type: "string" } },
2337
+ confirmation: { type: "string" }
2338
+ },
2339
+ async execute({ plan, confirmation }, { signal }) {
2340
+ return guard(async () => {
2341
+ if (confirmation !== void 0 && typeof confirmation !== "string") throw new ShelfError("\u8BF7\u4F7F\u7528\u9884\u89C8\u8FD4\u56DE\u7684 token");
2342
+ const batch = await source.prepare(plan, confirmation !== void 0, signal);
2343
+ if (signal?.aborted) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u5BFC\u5165\u5DF2\u53D6\u6D88");
2344
+ return JSON.stringify(await importBatch(store, memory, batch, confirmation, true));
2345
+ });
2346
+ }
2347
+ }
2348
+ ];
2349
+ }
2350
+
2351
+ // src/host/obsidian.ts
2352
+ import { createHash as createHash2 } from "node:crypto";
2353
+ import { constants } from "node:fs";
2354
+ import { open as open2, readdir, realpath, stat } from "node:fs/promises";
2355
+ import { isAbsolute as isAbsolute3, join as join7, posix } from "node:path";
2356
+ function withTitle(note, filename, raw) {
2357
+ const opening = note.replace(/^(?:\uFEFF)?(?:[ \t]*\r?\n)*/, "");
2358
+ 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;
2359
+ const title = posix.basename(filename).replace(/\.md$/i, "").replace(/[\r\n]+/g, " ");
2360
+ const newline = raw.match(/\r?\n/)?.[0] ?? "\n";
2361
+ return `# ${title}${newline}${newline}${note}`;
2362
+ }
2363
+ async function readVault(path, signal) {
2364
+ if (typeof path !== "string" || !isAbsolute3(expandHome(path))) throw new ShelfError("\u8BF7\u63D0\u4F9B Obsidian \u7B14\u8BB0\u5E93\u7684\u7EDD\u5BF9\u8DEF\u5F84");
2365
+ const notes = [];
2366
+ const references = [];
2367
+ let root;
2368
+ try {
2369
+ root = await realpath(expandHome(path));
2370
+ if (!(await stat(root)).isDirectory()) throw new ShelfError("\u8BF7\u9009\u62E9 Obsidian \u7B14\u8BB0\u5E93\u6587\u4EF6\u5939");
2371
+ async function walk(folder) {
2372
+ signal?.throwIfAborted();
2373
+ const entries = await readdir(join7(root, folder), { withFileTypes: true });
2374
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
2375
+ signal?.throwIfAborted();
2376
+ if (entry.name.startsWith(".")) continue;
2377
+ const key = posix.join(folder, entry.name);
2378
+ if (entry.isDirectory()) {
2379
+ await walk(key);
2380
+ continue;
2381
+ }
2382
+ if (!entry.isFile() || !/\.md$/i.test(entry.name)) continue;
2383
+ const file = await open2(join7(root, key), constants.O_RDONLY | constants.O_NOFOLLOW);
2384
+ let raw;
2385
+ try {
2386
+ raw = await file.readFile({ encoding: "utf8", signal });
2387
+ } finally {
2388
+ await file.close();
2389
+ }
2390
+ const header = /^(?:\uFEFF)?---[ \t]*\r?\n[\s\S]*?^---[ \t]*(?:\r?\n|$)/m.exec(raw);
2391
+ const frontmatter = header?.index === 0 ? header[0] : void 0;
2392
+ const note = raw.slice(frontmatter?.length ?? 0);
2393
+ const metadataTags = /^tags:[ \t]*(.*)((?:\r?\n[ \t]*-[ \t]+[^\r\n]*)*)/m.exec(frontmatter ?? "");
2394
+ const tagValues = metadataTags ? metadataTags[1] + metadataTags[2].replace(/^[ \t]*-[ \t]+/gm, " ") : "";
2395
+ const tags = new Set(tagValues.match(/[\p{L}\p{N}_/-]+/gu) ?? []);
2396
+ const markup = note.replace(/<!--[^]*?(?:-->|$)|%%[^]*?(?:%%|$)/g, (comment) => comment.replace(/[^\r\n]/g, " "));
2397
+ let fence;
2398
+ for (const line of markup.split(/\r?\n/)) {
2399
+ const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
2400
+ if (marker && !fence) {
2401
+ fence = marker;
2402
+ continue;
2403
+ }
2404
+ if (fence) {
2405
+ if (marker?.startsWith(fence) && line.trim() === marker) fence = void 0;
2406
+ continue;
2407
+ }
2408
+ const text2 = line.replace(/(`+)[^`]*\1/g, (code) => " ".repeat(code.length));
2409
+ for (const match of text2.matchAll(/(?:^|[\s((,。!?、;:])#([\p{L}\p{N}_/-]+)/gu)) tags.add(match[1]);
2410
+ for (const match of text2.matchAll(/(!|\\)?\[\[([^\]\n]+)\]\]/g)) {
2411
+ if (match[1]) continue;
2412
+ const target = match[2].split(/[|#]/, 1)[0].trim();
2413
+ if (!target) continue;
2414
+ const start = match.index;
2415
+ const end = start + match[0].length;
2416
+ const before = line.slice(0, start).split(/[。!?!?]/).at(-1) ?? "";
2417
+ const after = line.slice(end).split(/[。!?!?]/, 1)[0];
2418
+ const sentence = [...(before + match[0] + after).trim()];
2419
+ const why = sentence.length <= 40 ? sentence.join("") : [...before.trimEnd()].slice(-8).concat([...match[0] + after]).slice(0, 40).join("").trim();
2420
+ references.push({ from: key, to: target, why });
2421
+ }
2422
+ }
2423
+ notes.push({ key, note: withTitle(note, key, raw), frontmatter, tags: [...tags].sort() });
2424
+ }
2425
+ }
2426
+ await walk("");
2427
+ } catch (error) {
2428
+ if (signal?.aborted || error instanceof ShelfError) throw error;
2429
+ throw new ShelfError("\u65E0\u6CD5\u8BFB\u53D6\u8FD9\u4E2A Obsidian \u7B14\u8BB0\u5E93\uFF0C\u8BF7\u786E\u8BA4\u8DEF\u5F84\u548C\u8BFB\u53D6\u6743\u9650");
2430
+ }
2431
+ const paths = new Set(notes.map((note) => note.key));
2432
+ const byName = /* @__PURE__ */ new Map();
2433
+ for (const { key } of notes) {
2434
+ const name2 = posix.basename(key).replace(/\.md$/i, "");
2435
+ const matches = byName.get(name2);
2436
+ if (matches) matches.push(key);
2437
+ else byName.set(name2, [key]);
2438
+ }
2439
+ const links = references.flatMap((link) => {
2440
+ const target = /\.md$/i.test(link.to) ? link.to : link.to + ".md";
2441
+ const relative2 = posix.normalize(posix.join(posix.dirname(link.from), target));
2442
+ const matches = byName.get(link.to.replace(/\.md$/i, ""));
2443
+ 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;
2444
+ return to && to !== link.from ? [{ ...link, to }] : [];
2445
+ });
2446
+ return { root, notes, links, unresolved: references.length - links.length };
2447
+ }
2448
+ var obsidian = {
2449
+ async scan(path, offset, signal) {
2450
+ if (offset !== void 0 && (typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0)) throw new ShelfError("offset \u5E94\u4E3A\u975E\u8D1F\u6574\u6570");
2451
+ const { notes, links, unresolved } = await readVault(path, signal);
2452
+ const start = Number(offset ?? 0);
2453
+ const folders = /* @__PURE__ */ new Map();
2454
+ const targets = /* @__PURE__ */ new Map();
2455
+ for (const link of links) {
2456
+ const ids = targets.get(link.from);
2457
+ if (ids) ids.push(link.to);
2458
+ else targets.set(link.from, [link.to]);
2459
+ }
2460
+ const listing = notes.map(({ key, tags }) => {
2461
+ const path2 = posix.dirname(key);
2462
+ const folder = folders.get(path2) ?? { path: path2, count: 0, tags: /* @__PURE__ */ new Set(), links: 0 };
2463
+ folders.set(path2, folder);
2464
+ const linked = targets.get(key) ?? [];
2465
+ folder.count += 1;
2466
+ for (const tag of tags) folder.tags.add(tag);
2467
+ folder.links += linked.length;
2468
+ return { path: key, tags, links: linked };
2469
+ });
2470
+ return {
2471
+ count: notes.length,
2472
+ links: links.length,
2473
+ unresolved,
2474
+ folders: [...folders.values()].map((folder) => ({ ...folder, tags: [...folder.tags].sort() })),
2475
+ notes: listing.slice(start, start + 100),
2476
+ nextOffset: start + 100 < listing.length ? start + 100 : void 0
2477
+ };
2478
+ },
2479
+ async prepare(path, plan, signal) {
2480
+ const { root, notes, links } = await readVault(path, signal);
2481
+ if (notes.length === 0) throw new ShelfError("\u8FD9\u4E2A\u6587\u4EF6\u5939\u6CA1\u6709 Markdown \u7B14\u8BB0");
2482
+ const source = "obsidian:" + createHash2("sha256").update(root).digest("hex");
2483
+ const groups = [];
2484
+ if (plan === void 0) {
2485
+ const folders = /* @__PURE__ */ new Map();
2486
+ for (const note of notes) {
2487
+ const folder = posix.dirname(note.key);
2488
+ const group = folders.get(folder) ?? { key: "folder:" + folder, title: posix.basename(folder === "." ? root : folder) || "Obsidian", cards: [] };
2489
+ folders.set(folder, group);
2490
+ group.cards.push(note);
2491
+ }
2492
+ groups.push(...folders.values());
2493
+ } else {
2494
+ if (!Array.isArray(plan) || plan.length === 0) throw new ShelfError("\u5206\u683C\u65B9\u6848\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u76EE\u6807");
2495
+ const byPath = new Map(notes.map((note) => [note.key, note]));
2496
+ for (const group of plan) {
2497
+ if (!group || typeof group !== "object") throw new ShelfError("\u5206\u683C\u65B9\u6848\u65E0\u6548");
2498
+ const { title, item_id: itemId, paths, tags } = group;
2499
+ if (paths === void 0 === (tags === void 0)) throw new ShelfError("\u6BCF\u4E2A\u76EE\u6807\u8BF7\u5728 paths \u548C tags \u4E2D\u9009\u4E00\u9879");
2500
+ const selection = paths ?? tags;
2501
+ if (!Array.isArray(selection) || selection.length === 0 || selection.some((value) => typeof value !== "string" || !value.trim())) {
2502
+ throw new ShelfError("paths \u6216 tags \u5FC5\u987B\u662F\u975E\u7A7A\u7684\u6587\u5B57\u5217\u8868");
2503
+ }
2504
+ const cards = paths === void 0 ? notes.filter((note) => note.tags.some((tag) => selection.includes(tag))) : selection.map((key) => {
2505
+ const note = byPath.get(key);
2506
+ if (!note) throw new ShelfError(`\u65B9\u6848\u4E2D\u7684\u7B14\u8BB0\u4E0D\u5B58\u5728\uFF1A${key}`);
2507
+ return note;
2508
+ });
2509
+ if (cards.length === 0) throw new ShelfError("\u6240\u9009\u6807\u7B7E\u6CA1\u6709\u5339\u914D\u7684\u7B14\u8BB0");
2510
+ if (typeof itemId === "string" && itemId) groups.push({ key: itemId, itemId, title: "", cards });
2511
+ else if (itemId === void 0 && typeof title === "string" && title.trim()) groups.push({ key: "title:" + title.trim(), title: title.trim(), cards });
2512
+ else throw new ShelfError("\u6BCF\u4E2A\u76EE\u6807\u8BF7\u586B\u5DF2\u6709\u683C\u5B50 item_id \u6216\u65B0\u683C\u5B50 title");
2513
+ }
2514
+ }
2515
+ return { source, groups, links };
2516
+ }
2517
+ };
2518
+
2519
+ // src/host/harness/tools.ts
2520
+ var stringOut = {
2521
+ schema: { type: "string" },
2522
+ render: (_args, value) => [{ type: "text", text: value }]
2523
+ };
2524
+ function createTools(store, active, memory = new Memory(store)) {
2525
+ const nudged = /* @__PURE__ */ new Set();
2526
+ const nudge = (exec, id, kind) => {
2527
+ const key = `${exec.agent?.id ?? ""}:${id}:${kind}`;
2528
+ if (nudged.has(key)) return "";
2529
+ if (kind === "wiki") {
2530
+ const debt = memory.debt(id);
2531
+ if (debt < 3) return "";
2532
+ nudged.add(key);
2533
+ return `
2534
+ \uFF08\u63D0\u793A\uFF1A\u8FD9\u4E00\u683C\u7684 wiki \u4E4B\u540E\u65B0\u589E\u4E86 ${debt} \u6761\u5361\u7247 / \u7075\u611F\uFF0C\u804A\u5B8C\u65B9\u4FBF\u65F6\u7528 palace_wiki_write \u66F4\u65B0\uFF1B\u4E0D\u7528\u6253\u65AD\u7528\u6237\u3002\uFF09`;
2535
+ }
2536
+ nudged.add(key);
2537
+ 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";
2538
+ };
2539
+ const activeOf = (exec) => exec.agent ? active.get(exec.agent.id) : void 0;
2540
+ const shared = createPalaceTools(store, memory, {
2541
+ addBook: (args, signal) => addBook(store, args, signal),
2542
+ readPageTexts,
2543
+ scannedThreshold: SCANNED_THRESHOLD,
2544
+ 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",
2545
+ 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",
2546
+ 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",
2547
+ imageDescription: "\u622A\u56FE\u7684\u672C\u5730\u8DEF\u5F84\u6216\u9644\u4EF6 id",
2548
+ currentItem: true,
2549
+ 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",
2550
+ saveImage: (ref) => saveImage(store, ref)
2551
+ });
2552
+ return [...shared, ...createObsidianTools(store, memory, obsidian), ...createWeReadTools(store, memory, weread)].map(({ execute, ...definition }) => defineTool({
2553
+ ...definition,
2554
+ output: stringOut,
2555
+ async execute(args, exec) {
2556
+ const highlightId = activeOf(exec);
2557
+ if (definition.name === "palace_add_card" || definition.name === "palace_add_inspiration") {
2558
+ const id = typeof args.item_id === "string" && args.item_id !== "" ? args.item_id : highlightId;
2559
+ if (id === void 0) return "\u64CD\u4F5C\u5931\u8D25\uFF1A\u4E0D\u77E5\u9053\u8BB0\u5230\u54EA\u4E2A\u683C\u5B50\uFF1A\u7528\u6237\u6CA1\u6709\u6253\u5F00\u683C\u5B50\u3002\u8BF7\u5148\u7528 palace_overview \u67E5\u770B\u540E\u6307\u5B9A item_id\uFF0C\u6216\u8BF7\u7528\u6237\u5728\u53F3\u4FA7 Memory Palace \u6253\u5F00\u5BF9\u5E94\u7684\u4E66\u3002";
2560
+ args = { ...args, item_id: id };
2561
+ }
2562
+ return execute(args, {
2563
+ signal: exec.signal,
2564
+ highlightId,
2565
+ attribution: { sessionId: exec.agent?.id },
2566
+ nudge: (id, kind) => nudge(exec, id, kind)
2567
+ });
2568
+ }
2569
+ }));
2570
+ }
1886
2571
 
1887
- // src/host/index.ts
2572
+ // src/host/harness/index.ts
1888
2573
  var name = "dsh-palace";
1889
- var defaultDataDir = () => join6(homedir3(), "Documents", "dsh-palace-data");
2574
+ var defaultDataDir = () => join8(homedir4(), "Documents", "dsh-palace-data");
1890
2575
  function apply(ctx, config = {}) {
1891
2576
  const dir = config.dataDir ?? defaultDataDir();
2577
+ const firstRun = !existsSync5(join8(dir, "palace.json"));
1892
2578
  const store = new PalaceStore(dir);
2579
+ if (firstRun) void seedWelcome(store).catch((error) => console.warn("[dsh-palace] \u653E\u5165\u4ECB\u7ECD\u683C\u5B50\u5931\u8D25", error));
1893
2580
  const active = /* @__PURE__ */ new Map();
1894
2581
  const memory = new Memory(store);
1895
2582
  ctx.inject(["tools"], (scope) => {