dsh-tiddlywiki 0.33.2 → 0.33.4

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.
Files changed (54) hide show
  1. package/docs/CHANGELOG.md +172 -199
  2. package/docs/development.md +1 -1
  3. package/lib/client.js +6 -6
  4. package/lib/index.js +474 -189
  5. package/lib/index.js.map +1 -1
  6. package/package.json +2 -2
  7. package/src/client/i18n-frame.ts +4 -2
  8. package/src/client/i18n.ts +9 -2
  9. package/src/client/knowledge-fab.ts +7 -4
  10. package/src/client/note-widget-save.ts +4 -1
  11. package/src/client/note-widget-scope.ts +16 -1
  12. package/src/client/note-widget-tags.ts +15 -12
  13. package/src/client/note-widget.ts +1 -1
  14. package/src/client/settings-page-catalog.ts +7 -2
  15. package/src/client/settings-page-runtime.ts +7 -6
  16. package/src/client/settings-page-wikis.ts +3 -4
  17. package/src/client/sidebar-entry.ts +4 -0
  18. package/src/client/status-cache.ts +4 -1
  19. package/src/client/tid-parse.ts +88 -3
  20. package/src/client/tid-preview.ts +18 -7
  21. package/src/client/tool-views-shell.ts +4 -4
  22. package/src/client/tw-frame-api.ts +11 -4
  23. package/src/client/tw-frame-hash.ts +7 -1
  24. package/src/client/tw-frame.ts +11 -4
  25. package/src/host/admin-routes-info.ts +62 -16
  26. package/src/host/admin-routes-seeds.ts +22 -12
  27. package/src/host/admin-routes.ts +29 -13
  28. package/src/host/clip-bridge-limits.ts +12 -3
  29. package/src/host/clip-bridge-payload.ts +15 -4
  30. package/src/host/clip-bridge.ts +20 -3
  31. package/src/host/command-note.ts +6 -3
  32. package/src/host/config.ts +7 -2
  33. package/src/host/git.ts +6 -2
  34. package/src/host/mutation-lock.ts +22 -4
  35. package/src/host/routes-session-agent.ts +5 -1
  36. package/src/host/routes-session-summary.ts +23 -3
  37. package/src/host/routes-tw-proxy.ts +5 -0
  38. package/src/host/routes.ts +15 -3
  39. package/src/host/session-summary-scan.ts +12 -3
  40. package/src/host/tools-attach.ts +24 -4
  41. package/src/host/tools-git.ts +1 -1
  42. package/src/host/tools-notes-lifecycle.ts +53 -22
  43. package/src/host/tools-notes-structure.ts +11 -6
  44. package/src/host/tools-notes-write.ts +18 -7
  45. package/src/host/tools-support.ts +61 -12
  46. package/src/host/tools.ts +6 -3
  47. package/src/host/tw-api.ts +5 -1
  48. package/src/host/wechat-publish.ts +6 -2
  49. package/src/host/wiki-farm.ts +9 -3
  50. package/src/host/wiki-instance.ts +14 -0
  51. package/src/host/wiki.ts +8 -0
  52. package/src/index-routes.ts +52 -7
  53. package/src/index-wikis.ts +2 -2
  54. package/src/index.ts +23 -2
package/lib/index.js CHANGED
@@ -1203,7 +1203,7 @@ var TiddlyWebClient = class TiddlyWebClient {
1203
1203
  return true;
1204
1204
  });
1205
1205
  filtered.sort((a, b) => modifiedAt(b) - modifiedAt(a));
1206
- return filtered.slice(0, Math.max(1, Math.min(limit, 200)));
1206
+ return filtered.slice(0, clampLimit(limit, 15));
1207
1207
  }
1208
1208
  /** Full tag vocabulary + its size, so callers that cap can still report the
1209
1209
  * total ("showing 200 of N") — one listing request either way. */
@@ -1799,10 +1799,12 @@ var WechatPublishRunner = class {
1799
1799
  windowsVerbatimArguments: invocation.windowsVerbatimArguments
1800
1800
  });
1801
1801
  } catch (err) {
1802
- this.fail(record, `无法启动 ${command}:${err instanceof Error ? err.message : String(err)}`);
1802
+ const message = `无法启动 ${command}:${err instanceof Error ? err.message : String(err)}`;
1803
+ this.jobs.delete(id);
1803
1804
  return {
1804
- ok: true,
1805
- job: snapshot(record.view)
1805
+ ok: false,
1806
+ busy: false,
1807
+ error: message
1806
1808
  };
1807
1809
  }
1808
1810
  record.child = child;
@@ -2364,6 +2366,75 @@ function assertNoConflict(title, existing, expected) {
2364
2366
  throw new WriteConflictError(`写入冲突:tiddler「${title}」在你读取之后已被改动(不匹配的令牌:${failed};当前 revision=${currentRevision ?? "?"} modified=${toIsoDateString(existing.modified) ?? "?"};期望 revision=${expected.expectedRevision ?? "?"} modified=${expected.expectedModified ?? "?"})。${revisionHint}请重新读取最新内容后重试;确认要用你的版本覆盖时可传 force: true。`);
2365
2367
  }
2366
2368
  //#endregion
2369
+ //#region src/host/proxy-guard.ts
2370
+ /**
2371
+ * The secret-namespace guard, shared by every surface that turns a
2372
+ * caller-supplied title (or title reference) into TW output.
2373
+ *
2374
+ * Titles the browser-facing TW surfaces must never serve (v0.19.3 / v0.20.0).
2375
+ *
2376
+ * `$:/plugins/dsh-tiddlywiki/config` holds the shared tokens and the git
2377
+ * remote (possibly with a PAT); `/tw` and `/api` forward ANY path to the
2378
+ * loopback TW child, whose TiddlyWeb REST answers for `$:/…` titles — a
2379
+ * route-level guard on `/get` was therefore trivially bypassed by
2380
+ * `GET /dsh-tiddlywiki/tw/recipes/default/tiddlers/%24%3A%2Fplugins%2F…`
2381
+ * (verified). The whole plugin namespace is blocked: nothing under it is
2382
+ * needed by the TW frontend, and the host itself talks to TW directly.
2383
+ *
2384
+ * v0.20.0: the SAME predicate also guards `POST /render`, which had been
2385
+ * left open — TW's `/render` route renders ANY tiddler by title, so
2386
+ * `{"title":"$:/plugins/dsh-tiddlywiki/config"}` returned the raw config
2387
+ * (tokens + PAT in plain text inside `<pre><code>`, where the fragment
2388
+ * sanitizer keeps it). Verified end-to-end against a scratch wiki before the
2389
+ * fix. Every route that turns a caller-supplied title into TW output must use
2390
+ * `isBlockedProxyTitle`.
2391
+ *
2392
+ * v0.29.0: extracted from `routes-tw-proxy.ts` into this module because the
2393
+ * AGENT TOOL layer needs it too (`tiddlywiki_get` reached `$:/plugins/
2394
+ * dsh-tiddlywiki/config` directly, so the model could read the tokens the
2395
+ * routes are careful to hide). The tool layer must not depend on a route
2396
+ * module for a security primitive — hence one shared home, imported by both.
2397
+ *
2398
+ * @module dsh-tiddlywiki/host/proxy-guard
2399
+ */
2400
+ const BLOCKED_PROXY_TITLE_PREFIXES = ["$:/plugins/dsh-tiddlywiki/"];
2401
+ /** True when a caller-supplied tiddler title addresses the secret namespace. */
2402
+ const isBlockedProxyTitle = (title) => BLOCKED_PROXY_TITLE_PREFIXES.some((prefix) => title.startsWith(prefix));
2403
+ /**
2404
+ * True when a proxied pathname addresses a blocked (secret-bearing) tiddler.
2405
+ *
2406
+ * Decodes the WHOLE path rather than looking for a literal `/tiddlers/` marker
2407
+ * (v0.23.5). TW core's `get-tiddler-html.js` route is a SINGLE segment
2408
+ * (`path = /^\/([^\/]+)$/`) decoded with `decodeURIComponentSafe`, so
2409
+ * `GET /tw/%24%3A%2Fplugins%2Fdsh-tiddlywiki%2Fconfig` reached the config
2410
+ * tiddler while the old marker check saw no `/tiddlers/` at all (verified
2411
+ * before the fix: 200, 715 bytes of config JSON on both `/tw` and `/api`).
2412
+ * Raw, once- and twice-decoded forms are all checked so double-encoding cannot
2413
+ * slip through either.
2414
+ */
2415
+ const isBlockedProxyPath = (pathname) => {
2416
+ let candidate = pathname;
2417
+ for (let i = 0; i < 3; i += 1) {
2418
+ if (BLOCKED_PROXY_TITLE_PREFIXES.some((prefix) => candidate.includes(prefix))) return true;
2419
+ let next = candidate;
2420
+ try {
2421
+ next = decodeURIComponent(candidate);
2422
+ } catch {}
2423
+ if (next === candidate) break;
2424
+ candidate = next;
2425
+ }
2426
+ return BLOCKED_PROXY_TITLE_PREFIXES.some((prefix) => candidate.includes(prefix));
2427
+ };
2428
+ /**
2429
+ * Does caller-supplied CONTENT reference the protected namespace? (v0.23.5)
2430
+ * TW's `/render` resolves `{{…}}` transclusions server-side, so the `text`
2431
+ * branch was a second way to print the config tiddler: verified before the fix,
2432
+ * `POST /render {"text":"{{$:/plugins/dsh-tiddlywiki/config}}"}` returned 200
2433
+ * with the config JSON inside `<pre><code>` — the fragment sanitizer only strips
2434
+ * tags, it cannot know the text is a secret.
2435
+ */
2436
+ const referencesBlockedTitle = (value) => value !== void 0 && BLOCKED_PROXY_TITLE_PREFIXES.some((prefix) => value.includes(prefix));
2437
+ //#endregion
2367
2438
  //#region src/host/workspace.ts
2368
2439
  /**
2369
2440
  * Workspace / project marking for agent-created notes (v0.24.0).
@@ -2696,12 +2767,20 @@ async function readTrashIndex(wiki) {
2696
2767
  return {
2697
2768
  readOk: false,
2698
2769
  corrupted: false,
2770
+ exists: false,
2699
2771
  entries: []
2700
2772
  };
2701
2773
  }
2702
- if (tiddler === void 0 || typeof tiddler.text !== "string" || tiddler.text.trim().length === 0) return {
2774
+ if (tiddler === void 0) return {
2703
2775
  readOk: true,
2704
2776
  corrupted: false,
2777
+ exists: false,
2778
+ entries: []
2779
+ };
2780
+ if (typeof tiddler.text !== "string" || tiddler.text.trim().length === 0) return {
2781
+ readOk: true,
2782
+ corrupted: false,
2783
+ exists: true,
2705
2784
  entries: []
2706
2785
  };
2707
2786
  try {
@@ -2709,11 +2788,13 @@ async function readTrashIndex(wiki) {
2709
2788
  if (!Array.isArray(parsed)) return {
2710
2789
  readOk: true,
2711
2790
  corrupted: true,
2791
+ exists: true,
2712
2792
  entries: []
2713
2793
  };
2714
2794
  return {
2715
2795
  readOk: true,
2716
2796
  corrupted: false,
2797
+ exists: true,
2717
2798
  entries: parsed.filter((entry) => {
2718
2799
  if (typeof entry !== "object" || entry === null) return false;
2719
2800
  const e = entry;
@@ -2728,6 +2809,7 @@ async function readTrashIndex(wiki) {
2728
2809
  return {
2729
2810
  readOk: true,
2730
2811
  corrupted: true,
2812
+ exists: true,
2731
2813
  entries: []
2732
2814
  };
2733
2815
  }
@@ -2805,7 +2887,17 @@ async function listTrashbin(wiki, renderFilter) {
2805
2887
  for (let i = 0; i < titles.length; i += CONCURRENCY) {
2806
2888
  const slice = titles.slice(i, i + CONCURRENCY);
2807
2889
  const rows = await Promise.all(slice.map(async (trash) => {
2808
- const t = await wiki.get(trash);
2890
+ const fallback = {
2891
+ trash,
2892
+ of: trash.slice(12),
2893
+ at: "(条目字段读取失败,时间未知)"
2894
+ };
2895
+ let t;
2896
+ try {
2897
+ t = await wiki.get(trash);
2898
+ } catch {
2899
+ return fallback;
2900
+ }
2809
2901
  const of = typeof t?.fields?.["trash-of"] === "string" ? t.fields[TRASHBIN_OF_FIELD] : trash.slice(12);
2810
2902
  const iso = typeof t?.fields?.["trash-iso"] === "string" ? t.fields[TRASHBIN_AT_FIELD] : "";
2811
2903
  const legacy = typeof t?.fields?.["trash-at"] === "string" ? t.fields[TRASHBIN_LEGACY_AT_FIELD] : "";
@@ -2997,11 +3089,29 @@ function insertIntoSection(base, heading, addition) {
2997
3089
  matched: true
2998
3090
  };
2999
3091
  }
3092
+ /**
3093
+ * Refuse a WRITE into the plugin's own secret namespace (v0.33.4).
3094
+ *
3095
+ * `tiddlywiki_get` and `tiddlywiki_export` have always refused
3096
+ * `$:/plugins/dsh-tiddlywiki/…`, and the clip bridge refuses `$:/` outright —
3097
+ * but the write tools had no such check, so the model (or any instruction
3098
+ * injected into a page) could `tiddlywiki_put` the config tiddler and rewrite
3099
+ * `wechat.command` (spawned as a CLI), `git.remote` (used by the next sync) or
3100
+ * the bridge token, or break its JSON and reproduce the「插件读不出自己的配置」
3101
+ * accident. Same predicate, same boundary, one place: read AND write.
3102
+ *
3103
+ * Deliberately NARROW: ordinary `$:/…` writes stay allowed (the tools are
3104
+ * documented to write system tiddlers without agent-written/markdown defaults).
3105
+ */
3106
+ function assertWritableTitle(title) {
3107
+ if (!isBlockedProxyTitle(title)) return;
3108
+ throw new Error(`不允许通过工具改写「${title}」:它属于本插件自己的配置/密钥命名空间(与 tiddlywiki_get / tiddlywiki_export 同一条边界)。改插件设置请用 DSH 设置页,否则会直接改坏运行配置(可能被当成命令执行或用于下一次 git 推送)。`);
3109
+ }
3000
3110
  /** Every read/write tool needs a live TW client — shared guard for the 8
3001
3111
  * wiki-facing tools (git tools operate on the repo path instead). */
3002
3112
  function requireWiki(deps, sessionId) {
3003
3113
  const scope = deps.scope(sessionId);
3004
- if (scope.client === void 0) throw new Error(scope.reason ?? "TiddlyWiki 服务未运行(tiddlywiki_status 可查)");
3114
+ if (scope.client === void 0) throw new Error(scope.reason ?? "知识库服务当前没有运行:请确认 TiddlyWiki 子进程已启动(可在 DSH 设置页的知识库分区查看运行状态)");
3005
3115
  return scope.client;
3006
3116
  }
3007
3117
  //#endregion
@@ -3782,81 +3892,12 @@ function lintTool(env) {
3782
3892
  });
3783
3893
  }
3784
3894
  //#endregion
3785
- //#region src/host/proxy-guard.ts
3786
- /**
3787
- * The secret-namespace guard, shared by every surface that turns a
3788
- * caller-supplied title (or title reference) into TW output.
3789
- *
3790
- * Titles the browser-facing TW surfaces must never serve (v0.19.3 / v0.20.0).
3791
- *
3792
- * `$:/plugins/dsh-tiddlywiki/config` holds the shared tokens and the git
3793
- * remote (possibly with a PAT); `/tw` and `/api` forward ANY path to the
3794
- * loopback TW child, whose TiddlyWeb REST answers for `$:/…` titles — a
3795
- * route-level guard on `/get` was therefore trivially bypassed by
3796
- * `GET /dsh-tiddlywiki/tw/recipes/default/tiddlers/%24%3A%2Fplugins%2F…`
3797
- * (verified). The whole plugin namespace is blocked: nothing under it is
3798
- * needed by the TW frontend, and the host itself talks to TW directly.
3799
- *
3800
- * v0.20.0: the SAME predicate also guards `POST /render`, which had been
3801
- * left open — TW's `/render` route renders ANY tiddler by title, so
3802
- * `{"title":"$:/plugins/dsh-tiddlywiki/config"}` returned the raw config
3803
- * (tokens + PAT in plain text inside `<pre><code>`, where the fragment
3804
- * sanitizer keeps it). Verified end-to-end against a scratch wiki before the
3805
- * fix. Every route that turns a caller-supplied title into TW output must use
3806
- * `isBlockedProxyTitle`.
3807
- *
3808
- * v0.29.0: extracted from `routes-tw-proxy.ts` into this module because the
3809
- * AGENT TOOL layer needs it too (`tiddlywiki_get` reached `$:/plugins/
3810
- * dsh-tiddlywiki/config` directly, so the model could read the tokens the
3811
- * routes are careful to hide). The tool layer must not depend on a route
3812
- * module for a security primitive — hence one shared home, imported by both.
3813
- *
3814
- * @module dsh-tiddlywiki/host/proxy-guard
3815
- */
3816
- const BLOCKED_PROXY_TITLE_PREFIXES = ["$:/plugins/dsh-tiddlywiki/"];
3817
- /** True when a caller-supplied tiddler title addresses the secret namespace. */
3818
- const isBlockedProxyTitle = (title) => BLOCKED_PROXY_TITLE_PREFIXES.some((prefix) => title.startsWith(prefix));
3819
- /**
3820
- * True when a proxied pathname addresses a blocked (secret-bearing) tiddler.
3821
- *
3822
- * Decodes the WHOLE path rather than looking for a literal `/tiddlers/` marker
3823
- * (v0.23.5). TW core's `get-tiddler-html.js` route is a SINGLE segment
3824
- * (`path = /^\/([^\/]+)$/`) decoded with `decodeURIComponentSafe`, so
3825
- * `GET /tw/%24%3A%2Fplugins%2Fdsh-tiddlywiki%2Fconfig` reached the config
3826
- * tiddler while the old marker check saw no `/tiddlers/` at all (verified
3827
- * before the fix: 200, 715 bytes of config JSON on both `/tw` and `/api`).
3828
- * Raw, once- and twice-decoded forms are all checked so double-encoding cannot
3829
- * slip through either.
3830
- */
3831
- const isBlockedProxyPath = (pathname) => {
3832
- let candidate = pathname;
3833
- for (let i = 0; i < 3; i += 1) {
3834
- if (BLOCKED_PROXY_TITLE_PREFIXES.some((prefix) => candidate.includes(prefix))) return true;
3835
- let next = candidate;
3836
- try {
3837
- next = decodeURIComponent(candidate);
3838
- } catch {}
3839
- if (next === candidate) break;
3840
- candidate = next;
3841
- }
3842
- return BLOCKED_PROXY_TITLE_PREFIXES.some((prefix) => candidate.includes(prefix));
3843
- };
3844
- /**
3845
- * Does caller-supplied CONTENT reference the protected namespace? (v0.23.5)
3846
- * TW's `/render` resolves `{{…}}` transclusions server-side, so the `text`
3847
- * branch was a second way to print the config tiddler: verified before the fix,
3848
- * `POST /render {"text":"{{$:/plugins/dsh-tiddlywiki/config}}"}` returned 200
3849
- * with the config JSON inside `<pre><code>` — the fragment sanitizer only strips
3850
- * tags, it cannot know the text is a secret.
3851
- */
3852
- const referencesBlockedTitle = (value) => value !== void 0 && BLOCKED_PROXY_TITLE_PREFIXES.some((prefix) => value.includes(prefix));
3853
- //#endregion
3854
3895
  //#region src/host/tools-notes-write.ts
3855
3896
  /**
3856
3897
  * Note WRITE tools: `get` / `put` / `batch_put`.
3857
3898
  *
3858
- * v0.30.7:从 ools-notes.ts **纯搬迁**拆出(职责分组),函数体一字未改。
3859
- * 原来的文件变成 barrel, ools.ts 的注册顺序与导入路径都没变。
3899
+ * v0.30.7:从 tools-notes.ts **纯搬迁**拆出(职责分组),函数体一字未改。
3900
+ * 原来的文件变成 barrel,tools.ts 的注册顺序与导入路径都没变。
3860
3901
  *
3861
3902
  * @module dsh-tiddlywiki/host/tools-notes-write
3862
3903
  */
@@ -4044,6 +4085,7 @@ function putTool(env) {
4044
4085
  execute: async (args, exec) => {
4045
4086
  const wiki = requireWiki(sessionIdOf(exec));
4046
4087
  if (args.title.trim().length === 0) throw new Error("tiddlywiki_put: title 不能为空");
4088
+ assertWritableTitle(args.title);
4047
4089
  const existing = await wiki.get(args.title);
4048
4090
  assertNoConflict(args.title, existing, {
4049
4091
  expectedModified: args.expectedModified,
@@ -4065,7 +4107,7 @@ function putTool(env) {
4065
4107
  fields: marked.fields
4066
4108
  });
4067
4109
  await wiki.put(tiddler);
4068
- deps.autoCommit();
4110
+ deps.autoCommit(sessionIdOf(exec));
4069
4111
  return {
4070
4112
  ok: true,
4071
4113
  title: args.title,
@@ -4073,7 +4115,7 @@ function putTool(env) {
4073
4115
  type: typeof tiddler.type === "string" ? tiddler.type : null,
4074
4116
  ...typeDefaulted ? { typeDefaulted: true } : {},
4075
4117
  ...typeChangeOf(existing, tiddler),
4076
- fields: marked.fields ?? null,
4118
+ fields: pickFields(tiddler),
4077
4119
  ...marked.workspace !== void 0 ? { workspace: marked.workspace } : {}
4078
4120
  };
4079
4121
  }
@@ -4160,6 +4202,7 @@ function batchPutTool(env) {
4160
4202
  try {
4161
4203
  if (title.length === 0) throw new Error("缺少非空 title");
4162
4204
  if (typeof item.text !== "string") throw new Error("缺少 text");
4205
+ assertWritableTitle(title);
4163
4206
  const existing = await wiki.get(title);
4164
4207
  if (!overwrite && existing !== void 0) {
4165
4208
  skipped++;
@@ -4210,7 +4253,7 @@ function batchPutTool(env) {
4210
4253
  await writeOne(list[index], index);
4211
4254
  }
4212
4255
  }));
4213
- deps.autoCommit();
4256
+ deps.autoCommit(sessionIdOf(exec));
4214
4257
  return {
4215
4258
  ok: failed === 0,
4216
4259
  written,
@@ -4226,8 +4269,8 @@ function batchPutTool(env) {
4226
4269
  /**
4227
4270
  * Note STRUCTURE tools: `rename` / `append`.
4228
4271
  *
4229
- * v0.30.7:从 ools-notes.ts **纯搬迁**拆出(职责分组),函数体一字未改。
4230
- * 原来的文件变成 barrel, ools.ts 的注册顺序与导入路径都没变。
4272
+ * v0.30.7:从 tools-notes.ts **纯搬迁**拆出(职责分组),函数体一字未改。
4273
+ * 原来的文件变成 barrel,tools.ts 的注册顺序与导入路径都没变。
4231
4274
  *
4232
4275
  * @module dsh-tiddlywiki/host/tools-notes-structure
4233
4276
  */
@@ -4290,6 +4333,8 @@ function renameTool(env) {
4290
4333
  refsUpdated: 0,
4291
4334
  refsTiddlers: 0
4292
4335
  };
4336
+ assertWritableTitle(oldTitle);
4337
+ assertWritableTitle(newTitle);
4293
4338
  const existing = await wiki.get(oldTitle);
4294
4339
  if (existing === void 0) throw new Error(`tiddler「${oldTitle}」不存在`);
4295
4340
  assertNoConflict(oldTitle, existing, {
@@ -4344,7 +4389,7 @@ function renameTool(env) {
4344
4389
  const partial = `新标题「${newTitle}」已写入,但旧标题「${oldTitle}」删除失败(${deleteFailed}):现在两个标题都存在同一份内容,请手动删除旧标题。`;
4345
4390
  warning = warning === void 0 ? partial : `${warning} ${partial}`;
4346
4391
  }
4347
- deps.autoCommit();
4392
+ deps.autoCommit(sessionIdOf(exec));
4348
4393
  return {
4349
4394
  ok: true,
4350
4395
  from: oldTitle,
@@ -4431,6 +4476,7 @@ function appendTool(env) {
4431
4476
  const wiki = requireWiki(sessionIdOf(exec));
4432
4477
  const title = args.title.trim();
4433
4478
  if (title.length === 0) throw new Error("tiddlywiki_append: title 不能为空");
4479
+ assertWritableTitle(title);
4434
4480
  const existing = await wiki.get(title);
4435
4481
  assertNoConflict(title, existing, {
4436
4482
  expectedModified: args.expectedModified,
@@ -4459,7 +4505,7 @@ function appendTool(env) {
4459
4505
  fields: appendMarked.fields
4460
4506
  });
4461
4507
  await wiki.put(tiddler);
4462
- deps.autoCommit();
4508
+ deps.autoCommit(sessionIdOf(exec));
4463
4509
  return {
4464
4510
  ok: true,
4465
4511
  title,
@@ -4533,6 +4579,7 @@ function replaceTool(env) {
4533
4579
  const title = args.title.trim();
4534
4580
  if (title.length === 0) throw new Error("tiddlywiki_replace: title 不能为空");
4535
4581
  if (typeof args.old !== "string" || args.old.length === 0) throw new Error("tiddlywiki_replace: old 不能为空");
4582
+ assertWritableTitle(title);
4536
4583
  const existing = await wiki.get(title);
4537
4584
  assertNoConflict(title, existing, {
4538
4585
  expectedModified: args.expectedModified,
@@ -4555,7 +4602,7 @@ function replaceTool(env) {
4555
4602
  const replaced = args.all === true ? base.split(args.old).length - 1 : 1;
4556
4603
  const { tiddler } = buildWriteTiddler(title, next, { existing });
4557
4604
  await wiki.put(tiddler);
4558
- deps.autoCommit();
4605
+ deps.autoCommit(sessionIdOf(exec));
4559
4606
  return {
4560
4607
  ok: true,
4561
4608
  title,
@@ -4572,8 +4619,8 @@ function replaceTool(env) {
4572
4619
  /**
4573
4620
  * Note LIFECYCLE tools: `delete` / `trash` (soft delete).
4574
4621
  *
4575
- * v0.30.7:从 ools-notes.ts **纯搬迁**拆出(职责分组),函数体一字未改。
4576
- * 原来的文件变成 barrel, ools.ts 的注册顺序与导入路径都没变。
4622
+ * v0.30.7:从 tools-notes.ts **纯搬迁**拆出(职责分组),函数体一字未改。
4623
+ * 原来的文件变成 barrel,tools.ts 的注册顺序与导入路径都没变。
4577
4624
  *
4578
4625
  * @module dsh-tiddlywiki/host/tools-notes-lifecycle
4579
4626
  */
@@ -4614,6 +4661,7 @@ function deleteTool(env) {
4614
4661
  },
4615
4662
  execute: async (args, exec) => {
4616
4663
  const wiki = requireWiki(sessionIdOf(exec));
4664
+ assertWritableTitle(args.title);
4617
4665
  const existing = await wiki.get(args.title);
4618
4666
  assertNoConflict(args.title, existing, {
4619
4667
  expectedModified: args.expectedModified,
@@ -4621,10 +4669,10 @@ function deleteTool(env) {
4621
4669
  force: args.force
4622
4670
  });
4623
4671
  const canTrash = existing !== void 0 && args.permanent !== true && !args.title.startsWith("$:/dsh-tiddlywiki/trash/") && !args.title.startsWith("$:/trashbin/") && !args.title.startsWith("$:/");
4624
- if (args.title === "$:/dsh-tiddlywiki/trash-index" && existing !== void 0) throw new Error(`tiddlywiki_delete: 「${TRASH_INDEX_TITLE}」是回收站索引,删掉它会让回收站里的条目全部变成不可恢复的孤儿(列不出、恢复不了、也清不掉)。要清空回收站请用 tiddlywiki_trash action=empty;确实要丢弃索引请显式传 permanent: true。`);
4672
+ if (args.title === "$:/dsh-tiddlywiki/trash-index" && existing !== void 0 && args.permanent !== true) throw new Error(`tiddlywiki_delete: 「${TRASH_INDEX_TITLE}」是回收站索引,删掉它会让回收站里的条目全部变成不可恢复的孤儿(列不出、恢复不了、也清不掉)。要清空回收站请用 tiddlywiki_trash action=empty;确实要丢弃索引请显式传 permanent: true。`);
4625
4673
  if (!canTrash) {
4626
4674
  await wiki.delete(args.title);
4627
- deps.autoCommit();
4675
+ deps.autoCommit(sessionIdOf(exec));
4628
4676
  return {
4629
4677
  ok: true,
4630
4678
  title: args.title,
@@ -4636,14 +4684,14 @@ function deleteTool(env) {
4636
4684
  const trashTitle = trashbinTitleFor(args.title);
4637
4685
  if (await wiki.get(trashTitle) !== void 0) throw new Error(`tiddlywiki_delete: 回收站里已经有「${trashTitle}」了(同名笔记被删过两次?)。请先在 TW 回收站侧边栏里清理它,或直接用 permanent: true 删除本条。`);
4638
4686
  const { tiddler: copy } = buildWriteTiddler(trashTitle, existing.text ?? "", { existing });
4639
- copy.tags = [TRASHBIN_TAG];
4687
+ copy.tags = [TRASHBIN_TAG, ...Array.isArray(existing.tags) ? existing.tags.filter((tag) => tag !== TRASHBIN_TAG) : []];
4640
4688
  copy.created = existing.created ?? copy.created;
4641
4689
  copy.modified = existing.modified ?? copy.modified;
4642
4690
  copy[TRASHBIN_OF_FIELD] = args.title;
4643
4691
  copy[TRASHBIN_AT_FIELD] = at;
4644
4692
  await wiki.put(copy);
4645
4693
  await wiki.delete(args.title);
4646
- deps.autoCommit();
4694
+ deps.autoCommit(sessionIdOf(exec));
4647
4695
  return {
4648
4696
  ok: true,
4649
4697
  title: args.title,
@@ -4669,7 +4717,7 @@ function deleteTool(env) {
4669
4717
  at
4670
4718
  });
4671
4719
  await writeTrashIndex(wiki, index.entries);
4672
- deps.autoCommit();
4720
+ deps.autoCommit(sessionIdOf(exec));
4673
4721
  return {
4674
4722
  ok: true,
4675
4723
  title: args.title,
@@ -4732,10 +4780,15 @@ function trashTool(env) {
4732
4780
  })), ...legacyEntries];
4733
4781
  if (args.action === "list") {
4734
4782
  const limit = Math.max(1, Math.min(args.limit ?? 30, 200));
4783
+ const ordered = indexed.map((entry, index) => ({
4784
+ entry,
4785
+ index,
4786
+ at: parseTiddlerDate(entry.at) ?? 0
4787
+ })).sort((a, b) => b.at - a.at || a.index - b.index).map((row) => row.entry);
4735
4788
  return {
4736
4789
  action: "list",
4737
- message: `共 ${indexed.length} 条`,
4738
- items: indexed.slice(-limit).reverse().map((entry) => ({
4790
+ message: `共 ${ordered.length} 条`,
4791
+ items: ordered.slice(0, limit).map((entry) => ({
4739
4792
  title: entry.trash,
4740
4793
  at: entry.at,
4741
4794
  of: entry.of
@@ -4744,8 +4797,8 @@ function trashTool(env) {
4744
4797
  }
4745
4798
  if (args.action === "empty") {
4746
4799
  for (const entry of indexed) await wiki.delete(entry.trash);
4747
- if (legacyEntries.length > 0 || trashbin === void 0) await writeTrashIndex(wiki, []);
4748
- deps.autoCommit();
4800
+ if (index.exists) await writeTrashIndex(wiki, []);
4801
+ deps.autoCommit(sessionIdOf(exec));
4749
4802
  return {
4750
4803
  action: "empty",
4751
4804
  message: `已清空 ${indexed.length} 条`
@@ -4768,11 +4821,18 @@ function trashTool(env) {
4768
4821
  delete restored[TRASHBIN_OF_FIELD];
4769
4822
  delete restored[TRASHBIN_AT_FIELD];
4770
4823
  delete restored[TRASHBIN_LEGACY_AT_FIELD];
4771
- if ((Array.isArray(stored.tags) ? stored.tags : []).includes("$:/tags/trashbin")) restored.tags = (Array.isArray(stored.fields?.tags) ? stored.fields.tags : []).filter((tag) => tag !== TRASHBIN_TAG);
4824
+ const copyTags = Array.isArray(stored.tags) ? stored.tags : [];
4825
+ if (copyTags.includes("$:/tags/trashbin")) {
4826
+ const legacyField = Array.isArray(stored.fields?.tags) ? stored.fields.tags : [];
4827
+ const fromCopy = copyTags.filter((tag) => tag !== TRASHBIN_TAG);
4828
+ const recovered = fromCopy.length > 0 ? fromCopy : legacyField.filter((tag) => tag !== TRASHBIN_TAG);
4829
+ if (recovered.length > 0) restored.tags = recovered;
4830
+ else delete restored.tags;
4831
+ }
4772
4832
  await wiki.put(restored);
4773
4833
  await wiki.delete(match.trash);
4774
4834
  if (fromIndex) await writeTrashIndex(wiki, legacyEntries.filter((entry) => entry.trash !== match.trash));
4775
- deps.autoCommit();
4835
+ deps.autoCommit(sessionIdOf(exec));
4776
4836
  return {
4777
4837
  action: "restore",
4778
4838
  message: `已恢复「${match.of}」`,
@@ -4998,10 +5058,19 @@ function absoluteHostBase(hostHeader, proxyPath) {
4998
5058
  *
4999
5059
  * @module dsh-tiddlywiki/host/clip-bridge-limits
5000
5060
  */
5001
- /** Cap on the clipped text (characters) — plenty for a page selection. */
5002
- const MAX_CLIP_TEXT_LENGTH = 2e5;
5003
- /** Cap on a single /clip request body (bytes). */
5061
+ /**
5062
+ * Cap on a single /clip request body (bytes).
5063
+ *
5064
+ * The text cap below is derived from THIS number, not chosen independently
5065
+ * (v0.33.4): the old pair (200 000 characters vs 256 KiB) was self-contradictory
5066
+ * — CJK text is 3 bytes per character in UTF-8, so ~600 KB was "allowed" by the
5067
+ * character cap and killed by the body cap with「请求体不是合法的 JSON(或过大)」.
5068
+ * 60 000 characters stays under 256 KiB even if every character is 3 bytes
5069
+ * (180 KB) plus JSON escaping and the url/title/tag fields.
5070
+ */
5004
5071
  const MAX_CLIP_BODY_BYTES = 256 * 1024;
5072
+ /** Cap on the clipped text (characters) — plenty for a page selection. */
5073
+ const MAX_CLIP_TEXT_LENGTH = 6e4;
5005
5074
  //#endregion
5006
5075
  //#region src/host/clip-bridge-ssrf.ts
5007
5076
  /**
@@ -5335,9 +5404,15 @@ async function resolveClipTitle(exists, base, now = Date.now) {
5335
5404
  if (!await exists(candidate)) return candidate;
5336
5405
  }
5337
5406
  const stamp = new Date(now()).toISOString().slice(0, 23).replace(/[T:]/g, "-");
5338
- let candidate = `${base}(${stamp})`;
5339
- for (let i = 0; i < 100 && await exists(candidate); i++) candidate = `${base}(${stamp}-${i})`;
5340
- return candidate;
5407
+ for (let i = 0; i < 100; i++) {
5408
+ const candidate = i === 0 ? `${base}(${stamp})` : `${base}(${stamp}-${i})`;
5409
+ if (!await exists(candidate)) return candidate;
5410
+ }
5411
+ for (let attempt = 0; attempt < 100; attempt++) {
5412
+ const candidate = `${base}(${stamp}-${Math.random().toString(36).slice(2, 8)})`;
5413
+ if (!await exists(candidate)) return candidate;
5414
+ }
5415
+ throw new Error("剪藏标题生成失败:同一毫秒内连续 200 次撞名,请稍后重试");
5341
5416
  }
5342
5417
  /** Build the markdown tiddler for ONE TEXT-ONLY clip (no images). */
5343
5418
  function buildClipTiddler(opts) {
@@ -5686,12 +5761,23 @@ var ClipBridge = class {
5686
5761
  }
5687
5762
  }
5688
5763
  let body;
5764
+ let rawBody;
5689
5765
  try {
5690
- body = JSON.parse(await readBody(req, MAX_CLIP_BODY_BYTES));
5766
+ rawBody = await readBody(req, MAX_CLIP_BODY_BYTES);
5767
+ } catch (err) {
5768
+ const tooLarge = err instanceof Error && /body too large/.test(err.message);
5769
+ this.respond(res, {
5770
+ ok: false,
5771
+ error: tooLarge ? `请求体超过 ${Math.floor(MAX_CLIP_BODY_BYTES / 1024)}KB 上限(正文最多 ${MAX_CLIP_TEXT_LENGTH} 字符);请减少选中内容后重试` : "请求体读取失败,请重试"
5772
+ }, tooLarge ? 413 : 400);
5773
+ return;
5774
+ }
5775
+ try {
5776
+ body = JSON.parse(rawBody);
5691
5777
  } catch {
5692
5778
  this.respond(res, {
5693
5779
  ok: false,
5694
- error: "请求体不是合法的 JSON(或过大)"
5780
+ error: "请求体不是合法的 JSON"
5695
5781
  }, 400);
5696
5782
  return;
5697
5783
  }
@@ -5909,6 +5995,8 @@ function attachTool(env) {
5909
5995
  const wiki = requireWiki(sessionIdOf(exec));
5910
5996
  const title = args.title.trim();
5911
5997
  if (title.length === 0) throw new Error("tiddlywiki_attach: title 不能为空");
5998
+ assertWritableTitle(title);
5999
+ if (typeof args.noteTitle === "string" && args.noteTitle.trim().length > 0) assertWritableTitle(args.noteTitle.trim());
5912
6000
  const hasPath = typeof args.path === "string" && args.path.trim().length > 0;
5913
6001
  if (hasPath === (typeof args.url === "string" && args.url.trim().length > 0)) throw new Error("tiddlywiki_attach: path 与 url 必须且只能提供一个");
5914
6002
  let buffer;
@@ -5941,14 +6029,14 @@ function attachTool(env) {
5941
6029
  force: args.force
5942
6030
  });
5943
6031
  if (existing !== void 0 && args.force !== true) throw new Error(`tiddlywiki_attach: 标题「${title}」已存在(type=${typeof existing.type === "string" ? existing.type : "?"})。为避免静默覆盖既有笔记,请换一个附件标题;确认要覆盖时传 force: true(tags 与自定义字段仍会保留)。`);
5944
- const explicitTags = Array.isArray(args.tags) ? args.tags.filter((t) => typeof t === "string" && t.trim().length > 0) : void 0;
6032
+ const explicitTags = Array.isArray(args.tags) ? args.tags.filter((t) => typeof t === "string" && t.trim().length > 0).map((t) => t.trim()) : void 0;
5945
6033
  const decoded = buffer.toString("utf8");
5946
6034
  const asText = isTextMime(mime) && Buffer.from(decoded, "utf8").equals(buffer);
5947
6035
  const encoding = asText ? "text" : "base64";
5948
6036
  const body = asText ? decoded : buffer.toString("base64");
5949
6037
  const { tiddler } = buildWriteTiddler(title, body, {
5950
6038
  existing,
5951
- ...explicitTags !== void 0 && explicitTags.length > 0 ? { tags: explicitTags } : {},
6039
+ ...explicitTags !== void 0 ? { tags: explicitTags } : {},
5952
6040
  fields: {
5953
6041
  type: mime,
5954
6042
  "attach-source": source,
@@ -5965,9 +6053,10 @@ function attachTool(env) {
5965
6053
  const embed = mime.startsWith("image/") ? `[img[${safeTitle}]]` : `[[${safeTitle}]]`;
5966
6054
  const text = note === void 0 ? embed : `${(note.text ?? "").replace(/\s+$/, "")}\n\n${embed}`;
5967
6055
  const { tiddler: noteTiddler } = buildWriteTiddler(embedInto, text, { existing: note });
6056
+ if (((await wiki.get(embedInto))?.modified ?? "") !== (note?.modified ?? "")) throw new Error(`tiddlywiki_attach: 笔记「${embedInto}」在你读取之后被改动过(可能是 TW 编辑器里的修改),为避免覆盖掉那次修改,本次没有写入嵌入链接。请稍后用新的 noteTitle 重试(附件本身已保存)。`);
5968
6057
  await wiki.put(noteTiddler);
5969
6058
  }
5970
- deps.autoCommit();
6059
+ deps.autoCommit(sessionIdOf(exec));
5971
6060
  return {
5972
6061
  ok: true,
5973
6062
  title,
@@ -8214,11 +8303,7 @@ var ConfigStore = class {
8214
8303
  * is recorded for the UI — see ConfigUnreadableError.
8215
8304
  */
8216
8305
  async load(client) {
8217
- if (client === void 0) {
8218
- this.overrides = {};
8219
- this.lastParseError = void 0;
8220
- return;
8221
- }
8306
+ if (client === void 0) return;
8222
8307
  let tiddler;
8223
8308
  try {
8224
8309
  tiddler = await client.get(CONFIG_TIDDLER);
@@ -8612,6 +8697,7 @@ var WikiServer = class {
8612
8697
  } else args.push(`anon-username=${ANON_USERNAME}`);
8613
8698
  if (this.stopping) {
8614
8699
  this.log("start aborted: stop() was requested while resolving the port");
8700
+ this.health = "stopped";
8615
8701
  return this.status();
8616
8702
  }
8617
8703
  const node = resolveNodeExecutable();
@@ -9825,7 +9911,7 @@ function gitResolveTool(env) {
9825
9911
  };
9826
9912
  throw err;
9827
9913
  }
9828
- deps.autoCommit();
9914
+ deps.autoCommit(sessionIdOf(exec));
9829
9915
  const status = await deps.git.status(dir);
9830
9916
  return {
9831
9917
  ok: true,
@@ -10877,7 +10963,8 @@ var WikiFarm = class {
10877
10963
  affectedBy(repoRoot, changedFiles) {
10878
10964
  if (changedFiles === void 0) {
10879
10965
  const all = [];
10880
- for (const runtime of this.runtimes.values()) if (isInsidePath(repoRoot, runtime.path)) all.push(runtime);
10966
+ const key = pathComparisonKey(repoRoot);
10967
+ for (const runtime of this.runtimes.values()) if (isInsidePath(repoRoot, runtime.path) || pathComparisonKey(runtime.path) === key) all.push(runtime);
10881
10968
  return all;
10882
10969
  }
10883
10970
  if (changedFiles.length === 0) return [];
@@ -11404,7 +11491,7 @@ function createWikiViews(deps) {
11404
11491
  /** Source of the CURRENT location, for the settings page. */
11405
11492
  const locationSource = async () => {
11406
11493
  const state = await readLocationState(locationStateFile());
11407
- if (state.active !== void 0 && locationPath(state.active) === defaultPath()) return "state";
11494
+ if (state.active !== void 0 && pathComparisonKey(locationPath(state.active)) === pathComparisonKey(defaultPath())) return "state";
11408
11495
  const raw = deps.rawConfig();
11409
11496
  return typeof raw.wikiRoot === "string" && raw.wikiRoot.trim().length > 0 ? "config" : "default";
11410
11497
  };
@@ -11580,7 +11667,7 @@ function createWikiViews(deps) {
11580
11667
  */
11581
11668
  const resetWikiLocation = async () => {
11582
11669
  if (farm()?.registry.mode === "multi") return repointDefault(defaultLocation());
11583
- if (locationPath(defaultLocation()) === defaultPath()) {
11670
+ if (pathComparisonKey(locationPath(defaultLocation())) === pathComparisonKey(defaultPath())) {
11584
11671
  await clearLocationState(locationStateFile());
11585
11672
  return {
11586
11673
  ok: true,
@@ -11808,7 +11895,8 @@ function createMutationLock() {
11808
11895
  inFlight = label;
11809
11896
  return true;
11810
11897
  },
11811
- end: () => {
11898
+ end: (label) => {
11899
+ if (label !== void 0 && inFlight !== label) return;
11812
11900
  inFlight = void 0;
11813
11901
  },
11814
11902
  current: () => inFlight
@@ -12384,7 +12472,7 @@ function createAgentHandlers(deps) {
12384
12472
  return;
12385
12473
  }
12386
12474
  const requestId = `tw-send-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
12387
- const accepted = await sc.prompt({
12475
+ if ((await sc.prompt({
12388
12476
  requestId,
12389
12477
  sessionId,
12390
12478
  mode: "queue",
@@ -12392,8 +12480,7 @@ function createAgentHandlers(deps) {
12392
12480
  type: "text",
12393
12481
  text
12394
12482
  }]
12395
- }, AbortSignal.timeout(2e4));
12396
- if (accepted !== void 0 && accepted.accepted === false) {
12483
+ }, AbortSignal.timeout(2e4)))?.accepted !== true) {
12397
12484
  json(res, {
12398
12485
  ok: false,
12399
12486
  error: "会话未接受该消息(可能已结束或正忙)",
@@ -12564,6 +12651,7 @@ const NOTE_TOOL_NAMES = /* @__PURE__ */ new Set([
12564
12651
  "tiddlywiki_put",
12565
12652
  "tiddlywiki_batch_put",
12566
12653
  "tiddlywiki_append",
12654
+ "tiddlywiki_replace",
12567
12655
  "tiddlywiki_attach",
12568
12656
  "tiddlywiki_rename",
12569
12657
  "tiddlywiki_get",
@@ -12593,7 +12681,7 @@ function isPlausibleTitle(title) {
12593
12681
  if (title.length === 0 || title.length > 300) return false;
12594
12682
  if (title.trim().length === 0) return false;
12595
12683
  if (/[\u0000-\u001f\u007f]/.test(title)) return false;
12596
- if (/[\]|`#]/.test(title)) return false;
12684
+ if (/[\]|[`#]/.test(title)) return false;
12597
12685
  if (title.startsWith("…") || title === "标题") return false;
12598
12686
  return true;
12599
12687
  }
@@ -12629,9 +12717,9 @@ function trimTrailingClosers(raw) {
12629
12717
  s = s.slice(0, -1);
12630
12718
  }
12631
12719
  }
12632
- /** 扫助手回复文本里的 `/dsh-tiddlywiki/tw/#标题` 引用链接 → 读取。 */
12720
+ /** 扫助手回复文本里的 `/dsh-tiddlywiki/tw/[<库 id>/]#标题` 引用链接 → 读取。 */
12633
12721
  function scanRefs(text, time, subagent, collected) {
12634
- const re = /\/dsh-tiddlywiki\/tw\/#([^#\s]+)/g;
12722
+ const re = /\/dsh-tiddlywiki\/tw\/(?:[a-z0-9][a-z0-9._-]{0,63}\/)?#([^#\s]+)/g;
12635
12723
  let m;
12636
12724
  while ((m = re.exec(text)) !== null) {
12637
12725
  const raw = trimTrailingClosers(m[1] ?? "");
@@ -13070,6 +13158,25 @@ function createSessionSummaryHandler(deps) {
13070
13158
  const SUMMARY_REUSE_MS = 3e3;
13071
13159
  const summaryInFlight = /* @__PURE__ */ new Map();
13072
13160
  /**
13161
+ * Identity of the TW client a cached run was started for (v0.33.4).
13162
+ *
13163
+ * `session` alone is NOT a valid cache key: `client` is the TARGETED wiki's
13164
+ * client, so within the 3s reuse window a request scoped to another wiki (the
13165
+ * session's scope changed, or `?wiki=` differs) reused the previous wiki's
13166
+ * summary — titles, tags and wikitext of the wrong knowledge base. A WeakMap
13167
+ * gives each client instance a stable number without touching its API.
13168
+ */
13169
+ const clientIds = /* @__PURE__ */ new WeakMap();
13170
+ let nextClientId = 1;
13171
+ const clientIdOf = (client) => {
13172
+ const known = clientIds.get(client);
13173
+ if (known !== void 0) return known;
13174
+ const id = nextClientId;
13175
+ nextClientId += 1;
13176
+ clientIds.set(client, id);
13177
+ return id;
13178
+ };
13179
+ /**
13073
13180
  * POST /dsh-tiddlywiki/session/summary — 生成当前会话的 wiki 汇总页(「知识库」
13074
13181
  * Tab 的后端)。body `{ session: <会话ID> }`;后端用 sessionQuery 读本会话(含
13075
13182
  * 后代 subagent)的完整事件日志,按「产生/读取/检索」收集 tiddlywiki_* 笔记,
@@ -13114,17 +13221,18 @@ function createSessionSummaryHandler(deps) {
13114
13221
  }, 503);
13115
13222
  return;
13116
13223
  }
13117
- const cachedSummary = summaryInFlight.get(session);
13224
+ const cacheKey = `${session}|${clientIdOf(client)}`;
13225
+ const cachedSummary = summaryInFlight.get(cacheKey);
13118
13226
  let pendingSummary;
13119
13227
  if (cachedSummary !== void 0 && Date.now() - cachedSummary.at < SUMMARY_REUSE_MS) pendingSummary = cachedSummary.value;
13120
13228
  else {
13121
13229
  pendingSummary = writeSessionSummary(client, sq, session);
13122
- summaryInFlight.set(session, {
13230
+ summaryInFlight.set(cacheKey, {
13123
13231
  at: Date.now(),
13124
13232
  value: pendingSummary
13125
13233
  });
13126
13234
  pendingSummary.catch(() => {
13127
- if (summaryInFlight.get(session)?.value === pendingSummary) summaryInFlight.delete(session);
13235
+ if (summaryInFlight.get(cacheKey)?.value === pendingSummary) summaryInFlight.delete(cacheKey);
13128
13236
  });
13129
13237
  }
13130
13238
  const result = await pendingSummary;
@@ -13712,6 +13820,7 @@ function createTwProxyRoutes(deps) {
13712
13820
  signal: AbortSignal.timeout(15e3)
13713
13821
  };
13714
13822
  if (method === "PUT" || method === "POST") init.body = await readBody(req, MAX_PROXY_BODY_BYTES);
13823
+ else if (req.readableEnded === false && (req.headers["content-length"] !== void 0 || req.headers["transfer-encoding"] !== void 0)) req.resume();
13715
13824
  const upstream = await fetch(`${server.url}${rest}${url.search}`, init);
13716
13825
  const data = await upstream.text();
13717
13826
  res.writeHead(upstream.status, {
@@ -14473,7 +14582,7 @@ function registerRoutes(ctx, deps) {
14473
14582
  */
14474
14583
  const mutationLock = deps.mutationLock ?? createMutationLock();
14475
14584
  const beginMutation = (label) => mutationLock.begin(label);
14476
- const endMutation = () => mutationLock.end();
14585
+ const endMutation = (label) => mutationLock.end(label);
14477
14586
  /**
14478
14587
  * Absolute twin of `twProxy` for embedders whose own document is not on
14479
14588
  * http(s) — the DSH desktop app's `dsh-app:` renderer (v0.26.7). See
@@ -14626,6 +14735,13 @@ function registerRoutes(ctx, deps) {
14626
14735
  try {
14627
14736
  if (rejectCrossSiteWrite(req, res, ["POST"])) return;
14628
14737
  if (refuseStoppedTarget(req, res)) return;
14738
+ if (deps.server(req) === void 0) {
14739
+ json(res, {
14740
+ ok: false,
14741
+ error: notRunning(req)
14742
+ }, 503);
14743
+ return;
14744
+ }
14629
14745
  if (!beginMutation("restart")) {
14630
14746
  json(res, {
14631
14747
  ok: false,
@@ -14644,7 +14760,7 @@ function registerRoutes(ctx, deps) {
14644
14760
  log: (message) => console.warn("[dsh-tiddlywiki]", message)
14645
14761
  });
14646
14762
  } finally {
14647
- endMutation();
14763
+ endMutation("restart");
14648
14764
  }
14649
14765
  json(res, {
14650
14766
  ok: true,
@@ -14745,7 +14861,7 @@ function registerRoutes(ctx, deps) {
14745
14861
  error: err instanceof Error ? err.message : String(err)
14746
14862
  }, errorStatus(err));
14747
14863
  } finally {
14748
- endMutation();
14864
+ endMutation("sync");
14749
14865
  }
14750
14866
  };
14751
14867
  /**
@@ -15514,7 +15630,7 @@ function createAdminSeedRoutes(deps, helpers) {
15514
15630
  }
15515
15631
  json(res, {
15516
15632
  ok: true,
15517
- items: await deps.seeds.checkAll(client)
15633
+ items: await deps.seeds.checkAll(client, req)
15518
15634
  });
15519
15635
  } catch (err) {
15520
15636
  json(res, {
@@ -15543,34 +15659,42 @@ function createAdminSeedRoutes(deps, helpers) {
15543
15659
  return;
15544
15660
  }
15545
15661
  const seedStartedAt = Date.now();
15546
- const results = await deps.seeds.run(client, id, force);
15662
+ const results = await deps.seeds.run(client, id, force, req);
15547
15663
  let restarted = false;
15548
15664
  let restartError;
15549
15665
  const seedLock = deps.mutationLock;
15550
- if (needsRestartAfterSeeds(results) && seedLock !== void 0 && !seedLock.begin("admin-seeds")) {
15551
- json(res, {
15552
- ok: false,
15553
- error: `另一个重启/同步正在进行中(${seedLock.current() ?? "?"}),请稍候`
15554
- }, 429);
15555
- return;
15666
+ const needsRestart = needsRestartAfterSeeds(results);
15667
+ let lockTaken = false;
15668
+ if (needsRestart && seedLock !== void 0) {
15669
+ if (!seedLock.begin("admin-seeds")) {
15670
+ json(res, {
15671
+ ok: false,
15672
+ error: `另一个重启/同步正在进行中(${seedLock.current() ?? "?"}),请稍候`
15673
+ }, 429);
15674
+ return;
15675
+ }
15676
+ lockTaken = true;
15556
15677
  }
15557
- if (needsRestartAfterSeeds(results)) try {
15558
- if (!await waitForFileWrite(join(deps.getWikiPath(req), "tiddlers", "$__plugins_dsh_render.json"), 8e3, 150, seedStartedAt)) console.warn("[dsh-tiddlywiki] seeded render plugin file not seen on disk before restart");
15559
- if (!await drainThenStop({
15560
- client,
15561
- tiddlersDir: join(deps.getWikiPath(req), "tiddlers"),
15562
- stop: async () => {
15563
- await deps.server(req)?.restart();
15564
- },
15565
- log: (message) => console.warn("[dsh-tiddlywiki]", message)
15566
- })) console.warn("[dsh-tiddlywiki] seed writes may not have been flushed before restart");
15567
- restarted = true;
15678
+ try {
15679
+ if (needsRestart) {
15680
+ if (!await waitForFileWrite(join(deps.getWikiPath(req), "tiddlers", "$__plugins_dsh_render.json"), 8e3, 150, seedStartedAt)) console.warn("[dsh-tiddlywiki] seeded render plugin file not seen on disk before restart");
15681
+ if (!await drainThenStop({
15682
+ client,
15683
+ tiddlersDir: join(deps.getWikiPath(req), "tiddlers"),
15684
+ stop: async () => {
15685
+ await deps.server(req)?.restart();
15686
+ },
15687
+ log: (message) => console.warn("[dsh-tiddlywiki]", message)
15688
+ })) console.warn("[dsh-tiddlywiki] seed writes may not have been flushed before restart");
15689
+ restarted = true;
15690
+ }
15568
15691
  } catch (err) {
15569
15692
  restartError = err instanceof Error ? err.message : String(err);
15570
15693
  console.warn("[dsh-tiddlywiki] restart after seeding failed:", restartError);
15694
+ } finally {
15695
+ if (lockTaken) seedLock?.end("admin-seeds");
15571
15696
  }
15572
15697
  const ok = results.every((r) => r.ok);
15573
- seedLock?.end();
15574
15698
  json(res, {
15575
15699
  ok,
15576
15700
  results,
@@ -15603,7 +15727,7 @@ function createAdminSeedRoutes(deps, helpers) {
15603
15727
  }, 503);
15604
15728
  return;
15605
15729
  }
15606
- const results = await deps.seeds.remove(client, id);
15730
+ const results = await deps.seeds.remove(client, id, req);
15607
15731
  const ok = results.every((r) => r.ok);
15608
15732
  json(res, {
15609
15733
  ok,
@@ -15857,28 +15981,44 @@ function createAdminInfoRoutes(deps, helpers) {
15857
15981
  return;
15858
15982
  }
15859
15983
  const changed = JSON.stringify(info) !== beforeInfo;
15860
- if (changed) {
15861
- await writeWikiInfo(wikiPath, info);
15862
- await drainThenStop({
15863
- client: deps.getClient(req),
15864
- tiddlersDir: join(deps.getWikiPath(req), "tiddlers"),
15865
- stop: async () => {
15866
- await deps.server(req)?.restart();
15867
- },
15868
- log: (message) => console.warn("[dsh-tiddlywiki]", message)
15869
- });
15984
+ const lock = deps.mutationLock;
15985
+ let lockTaken = false;
15986
+ if (changed && lock !== void 0) {
15987
+ if (!lock.begin("admin-info")) {
15988
+ json(res, {
15989
+ ok: false,
15990
+ error: `另一个重启/同步正在进行中(${lock.current() ?? "?"}),请稍候`
15991
+ }, 429);
15992
+ return;
15993
+ }
15994
+ lockTaken = true;
15995
+ }
15996
+ try {
15997
+ if (changed) {
15998
+ await writeWikiInfo(wikiPath, info);
15999
+ await drainThenStop({
16000
+ client: deps.getClient(req),
16001
+ tiddlersDir: join(deps.getWikiPath(req), "tiddlers"),
16002
+ stop: async () => {
16003
+ await deps.server(req)?.restart();
16004
+ },
16005
+ log: (message) => console.warn("[dsh-tiddlywiki]", message)
16006
+ });
16007
+ }
16008
+ } finally {
16009
+ if (lockTaken) lock?.end("admin-info");
15870
16010
  }
15871
16011
  if (Array.isArray(body.themes) && activatedTheme !== void 0) {
15872
16012
  const client = deps.getClient(req);
15873
- if (client !== void 0) await client.put({
15874
- title: "$:/theme",
15875
- text: `$:/themes/${activatedTheme}`,
15876
- type: "text/vnd.tiddlywiki",
15877
- tags: []
15878
- }).catch((err) => {
15879
- console.warn("[dsh-tiddlywiki] activating theme failed:", err);
15880
- });
16013
+ if (client !== void 0) {
16014
+ const existingTheme = await client.get("$:/theme");
16015
+ const { tiddler: themeTiddler } = buildWriteTiddler("$:/theme", `$:/themes/${activatedTheme}`, { existing: existingTheme });
16016
+ await client.put(themeTiddler).catch((err) => {
16017
+ console.warn("[dsh-tiddlywiki] activating theme failed:", err);
16018
+ });
16019
+ }
15881
16020
  }
16021
+ let languageHintError;
15882
16022
  if (Array.isArray(body.languages)) {
15883
16023
  const client = deps.getClient(req);
15884
16024
  if (client !== void 0) {
@@ -15888,7 +16028,12 @@ function createAdminInfoRoutes(deps, helpers) {
15888
16028
  else console.warn("[dsh-tiddlywiki] pinning $:/language failed:", err);
15889
16029
  });
15890
16030
  const hint = langs.length > 0 ? langs[0] : "";
15891
- if ((deps.config(req).get().uiLanguage ?? "") !== hint) await deps.config(req).set(client, { uiLanguage: hint }).catch(() => void 0);
16031
+ if ((deps.config(req).get().uiLanguage ?? "") !== hint) try {
16032
+ await deps.config(req).set(client, { uiLanguage: hint });
16033
+ } catch (err) {
16034
+ languageHintError = `语言提示没写进配置(下次 dsh web 启动可能又启用「${hint === "" ? "默认语言" : hint}」):${err instanceof Error ? err.message : String(err)}`;
16035
+ console.warn("[dsh-tiddlywiki]", languageHintError);
16036
+ }
15892
16037
  }
15893
16038
  }
15894
16039
  json(res, {
@@ -15898,7 +16043,8 @@ function createAdminInfoRoutes(deps, helpers) {
15898
16043
  plugins: info.plugins,
15899
16044
  themes: info.themes,
15900
16045
  languages: info.languages ?? []
15901
- }
16046
+ },
16047
+ ...languageHintError === void 0 ? {} : { warning: languageHintError }
15902
16048
  });
15903
16049
  } catch (err) {
15904
16050
  json(res, {
@@ -16085,6 +16231,13 @@ function registerAdminRoutes(ctx, deps) {
16085
16231
  try {
16086
16232
  if (rejectCrossSiteWrite(req, res, ["POST"])) return;
16087
16233
  if (refuseStoppedTarget(req, res)) return;
16234
+ if (deps.server(req) === void 0) {
16235
+ json(res, {
16236
+ ok: false,
16237
+ error: notRunning(req)
16238
+ }, 503);
16239
+ return;
16240
+ }
16088
16241
  const lock = deps.mutationLock;
16089
16242
  if (lock !== void 0 && !lock.begin("admin-restart")) {
16090
16243
  json(res, {
@@ -16108,7 +16261,7 @@ function registerAdminRoutes(ctx, deps) {
16108
16261
  drained
16109
16262
  });
16110
16263
  } finally {
16111
- lock?.end();
16264
+ lock?.end("admin-restart");
16112
16265
  }
16113
16266
  } catch (err) {
16114
16267
  json(res, {
@@ -16491,6 +16644,19 @@ var WikiInstance = class WikiInstance {
16491
16644
  this.server.setReadyTimeout(this.eff().startup?.readyTimeoutMs);
16492
16645
  }
16493
16646
  /**
16647
+ * This wiki's same-origin proxy base (`/dsh-tiddlywiki/tw/` or
16648
+ * `/dsh-tiddlywiki/tw/<id>/`).
16649
+ *
16650
+ * v0.33.4: exposed so routes that RE-RUN seeds (the settings page's
16651
+ * 「重新初始化」) pass the same value the startup path does. Without it the
16652
+ * `tw-web-host` seed wrote the bare legacy base in a multi-wiki install, and
16653
+ * that wiki's embedded editor then proxied every API call to the DEFAULT wiki
16654
+ * (one wiki's UI over another wiki's data).
16655
+ */
16656
+ proxyBasePath() {
16657
+ return this.options.proxyBase?.() ?? TW_PROXY_PATH;
16658
+ }
16659
+ /**
16494
16660
  * Debounced auto-commit touch for this wiki's folder. Routed to the
16495
16661
  * REPOSITORY's committer (several wikis may share one repository).
16496
16662
  */
@@ -16691,7 +16857,7 @@ function createRouteStage(deps) {
16691
16857
  const disposeRoutes = registerRoutes({ webServer: ws }, {
16692
16858
  mutationLock: deps.mutationLock,
16693
16859
  server: (req) => target(req)?.server,
16694
- wikiSummaries: (req) => {
16860
+ wikiSummaries: (_req) => {
16695
16861
  const registry = deps.getFarm()?.registry;
16696
16862
  return {
16697
16863
  mode: registry?.mode ?? "single",
@@ -16784,7 +16950,32 @@ function createRouteStage(deps) {
16784
16950
  twRoot: resolveTwRoot,
16785
16951
  config: (req) => target(req)?.config ?? idleConfig,
16786
16952
  onConfigChanged: deps.onConfigChanged,
16787
- getPrompt: (draft, req) => describePrompt(draft ?? deps.effectivePromptFor(req), tiddlywikiToolSummary()),
16953
+ getPrompt: (draft, req) => {
16954
+ const savedCfg = target(req)?.config.get() ?? deps.baseShape;
16955
+ const cfg = draft ?? savedCfg.prompt ?? {};
16956
+ const farm = deps.getFarm();
16957
+ const runtime = target(req);
16958
+ const registry = farm?.registry;
16959
+ const ambiguous = (registry?.wikis ?? []).filter((entry) => entry.agentVisible).length > 1;
16960
+ const entry = runtime === void 0 ? void 0 : registry?.wikis.find((item) => farm?.runtime(item.id) === runtime);
16961
+ const scopeId = entry?.id;
16962
+ const linkBase = ambiguous && typeof scopeId === "string" && scopeId.length > 0 ? `${TW_LINK_BASE}${scopeId}/` : TW_LINK_BASE;
16963
+ const built = describePrompt({
16964
+ ...cfg,
16965
+ wechat: savedCfg.wechat?.enabled === true,
16966
+ linkBase
16967
+ }, tiddlywikiToolSummary());
16968
+ return {
16969
+ ...built,
16970
+ text: withScopeBanner(built.text, {
16971
+ ...scopeId === void 0 ? {} : {
16972
+ id: scopeId,
16973
+ label: entry?.label
16974
+ },
16975
+ ambiguous
16976
+ })
16977
+ };
16978
+ },
16788
16979
  wiki: {
16789
16980
  info: locationInfo,
16790
16981
  switch: switchWikiLocation,
@@ -16872,15 +17063,23 @@ function createRouteStage(deps) {
16872
17063
  }
16873
17064
  },
16874
17065
  seeds: {
16875
- checkAll: async (c) => checkAllSeeds({
17066
+ checkAll: async (c, req) => checkAllSeeds({
16876
17067
  client: c,
16877
- tools: tiddlywikiToolSummary()
17068
+ tools: tiddlywikiToolSummary(),
17069
+ ...req === void 0 ? {} : {
17070
+ proxyBase: target(req)?.proxyBasePath(),
17071
+ wechat: target(req)?.wechatEnabled() ?? false
17072
+ }
16878
17073
  }),
16879
- run: async (c, id, force) => runSeedById({
17074
+ run: async (c, id, force, req) => runSeedById({
16880
17075
  client: c,
16881
- tools: tiddlywikiToolSummary()
17076
+ tools: tiddlywikiToolSummary(),
17077
+ ...req === void 0 ? {} : {
17078
+ proxyBase: target(req)?.proxyBasePath(),
17079
+ wechat: target(req)?.wechatEnabled() ?? false
17080
+ }
16882
17081
  }, id, force),
16883
- remove: async (c, id) => removeSeedById({ client: c }, id)
17082
+ remove: async (c, id, req) => removeSeedById({ client: c }, id)
16884
17083
  }
16885
17084
  };
16886
17085
  const disposeAdmin = registerAdminRoutes({ webServer: ws }, adminDeps);
@@ -17236,7 +17435,7 @@ function registerNoteCommand(commands, deps) {
17236
17435
  kind: "error",
17237
17436
  text: `「${parsed.title}」已经存在(${scope.label ?? "当前知识库"})。要改请用编辑器,或让 Agent 用 tiddlywiki_get + tiddlywiki_put 按并发令牌更新;换标题再加一次也可以。`
17238
17437
  };
17239
- const mark = deps.workspaceMarkEnabled?.() === true && sessionId !== void 0 ? workspaceMarkFromCwd(deps.workspaceName?.(sessionId)) : void 0;
17438
+ const mark = deps.workspaceMarkEnabled?.() !== false && sessionId !== void 0 ? workspaceMarkFromCwd(deps.workspaceName?.(sessionId)) : void 0;
17240
17439
  const fields = {};
17241
17440
  const tags = ["inbox"];
17242
17441
  if (mark !== void 0) {
@@ -17249,7 +17448,7 @@ function registerNoteCommand(commands, deps) {
17249
17448
  agentTag: false
17250
17449
  });
17251
17450
  await scope.client.put(tiddler);
17252
- deps.autoCommit();
17451
+ deps.autoCommit(sessionId);
17253
17452
  const where = scope.label !== void 0 ? `(${scope.label})` : "";
17254
17453
  return {
17255
17454
  kind: "success",
@@ -17483,6 +17682,83 @@ const TID_EXTENSIONS = ["tid", "tiddler"];
17483
17682
  /** 正文要注入的 keyed 子槽(宿主约定,见 docs/development.md)。 */
17484
17683
  const TID_PREVIEW_SLOT = "sidebar.right.tab.document";
17485
17684
  /**
17685
+ * 内部/机械性字段:对「人看这个文件」没有信息量,摘要里折到一行小字里。
17686
+ *
17687
+ * `ws/*` 与 `agent-written` 其实是**标签值里的标记**,不是字段名 —— 见 `summarizeTid`。
17688
+ */
17689
+ const INTERNAL_FIELD_KEYS = [
17690
+ "revision",
17691
+ "workspace",
17692
+ "human-edited",
17693
+ "agent-written",
17694
+ "bag",
17695
+ "list"
17696
+ ];
17697
+ /** 摘要里单列出来的字段(其余进「另外 N 个字段」那一行)。 */
17698
+ const SUMMARY_FIELD_KEYS = [
17699
+ "created",
17700
+ "modified",
17701
+ "creator",
17702
+ "modifier",
17703
+ "type"
17704
+ ];
17705
+ /**
17706
+ * 把 TiddlyWiki 的 17 位时间戳(`YYYYMMDDHHmmssSSS`,UTC)变成 `YYYY-MM-DD HH:mm`。
17707
+ *
17708
+ * 不是 17 位数字就原样返回 —— 宁可显示原文,也不要把一个看不懂的值装作看懂了。
17709
+ */
17710
+ function formatTidStamp(value) {
17711
+ const raw = value.trim();
17712
+ if (!/^\d{17}$/.test(raw)) return raw;
17713
+ const [y, mo, d, h, mi] = [
17714
+ raw.slice(0, 4),
17715
+ raw.slice(4, 6),
17716
+ raw.slice(6, 8),
17717
+ raw.slice(8, 10),
17718
+ raw.slice(10, 12)
17719
+ ];
17720
+ return `${y}-${mo}-${d} ${h}:${mi}`;
17721
+ }
17722
+ /**
17723
+ * 把解析结果压成**给人看**的摘要。
17724
+ *
17725
+ * 规则(作者 2026-10-26 要求):只单列 `title` / `tags` / 时间,其余(`revision`、`workspace`、
17726
+ * `human-edited`、`ws/*` 这类机械字段)折进一行小字 —— 预览器的第一眼应该看到**内容**,
17727
+ * 不是一堆元数据。
17728
+ */
17729
+ function summarizeTid(parsed) {
17730
+ const known = [];
17731
+ const other = [];
17732
+ let tags = [];
17733
+ let created;
17734
+ let modified;
17735
+ for (const [key, value] of parsed.fields) {
17736
+ if (key === "tags") {
17737
+ tags = value.split(/[\s,]+/).filter((tag) => tag.length > 0);
17738
+ continue;
17739
+ }
17740
+ if (key === "created") created = value;
17741
+ if (key === "modified") modified = value;
17742
+ if (SUMMARY_FIELD_KEYS.includes(key)) {
17743
+ known.push([key, key === "created" || key === "modified" ? formatTidStamp(value) : value]);
17744
+ continue;
17745
+ }
17746
+ other.push([key, key === "created" || key === "modified" ? formatTidStamp(value) : value]);
17747
+ }
17748
+ const visibleTags = tags.filter((tag) => !tag.startsWith("ws/") && tag !== "agent-written");
17749
+ const hiddenTags = tags.filter((tag) => !visibleTags.includes(tag));
17750
+ if (hiddenTags.length > 0) other.push(["tags(hidden)", hiddenTags.join(" ")]);
17751
+ const stamp = modified ?? created;
17752
+ const time = stamp === void 0 ? void 0 : formatTidStamp(stamp);
17753
+ return {
17754
+ ...parsed.title !== void 0 && parsed.title.length > 0 ? { title: parsed.title } : {},
17755
+ tags: visibleTags,
17756
+ ...time !== void 0 ? { time } : {},
17757
+ known: known.filter(([key]) => key !== "created" && key !== "modified"),
17758
+ other
17759
+ };
17760
+ }
17761
+ /**
17486
17762
  * 把一份 `.tid` 文件拆成「字段 + 正文」。
17487
17763
  *
17488
17764
  * `.tid` 格式:若干 `key: value` 行 → **一个空行** → 正文。没有空行时整份都当字段
@@ -17490,7 +17766,7 @@ const TID_PREVIEW_SLOT = "sidebar.right.tab.document";
17490
17766
  * 就丢内容 —— 预览器丢内容比显示得难看严重得多。
17491
17767
  */
17492
17768
  function parseTidText(raw) {
17493
- const normalised = String(raw ?? "").replace(/\r\n/g, "\n");
17769
+ const normalised = String(raw ?? "").replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
17494
17770
  const splitAt = normalised.indexOf("\n\n");
17495
17771
  const head = splitAt < 0 ? normalised : normalised.slice(0, splitAt);
17496
17772
  const body = splitAt < 0 ? "" : normalised.slice(splitAt + 2);
@@ -17510,7 +17786,11 @@ function parseTidText(raw) {
17510
17786
  if (key === "title") title = value;
17511
17787
  else fields.push([key, value]);
17512
17788
  }
17513
- if (splitAt < 0 && (!allLinesAreFields || title === void 0 && fields.length === 0)) return {
17789
+ if (fields.length === 0 && title === void 0) return {
17790
+ fields: [],
17791
+ text: normalised
17792
+ };
17793
+ if (splitAt < 0 && !allLinesAreFields) return {
17514
17794
  fields: [],
17515
17795
  text: normalised
17516
17796
  };
@@ -18487,7 +18767,8 @@ const CHUNKS = [
18487
18767
  "frame.statusUnreachable": "无法访问 /dsh-tiddlywiki/status",
18488
18768
  "frame.noEditorUrl": "服务未返回编辑器地址",
18489
18769
  "frame.statusError": "服务状态:{status}",
18490
- "frame.tidPreviewTitle": ".tid 文件预览",
18770
+ "frame.tidPreviewTitle": "真 TiddlyWiki 渲染",
18771
+ "frame.tidMoreFields": "另外 {n} 个字段",
18491
18772
  "frame.tidPreviewWaiting": "等待文件内容…",
18492
18773
  "frame.tidPreviewNoBody": "这个 .tid 只有字段、没有正文。",
18493
18774
  "frame.tidPreviewFallback": "渲染失败,下面是原文:"
@@ -18517,7 +18798,8 @@ const CHUNKS = [
18517
18798
  "frame.statusUnreachable": "Cannot reach /dsh-tiddlywiki/status",
18518
18799
  "frame.noEditorUrl": "The service returned no editor address",
18519
18800
  "frame.statusError": "Service status: {status}",
18520
- "frame.tidPreviewTitle": ".tid file preview",
18801
+ "frame.tidPreviewTitle": "Rendered TiddlyWiki",
18802
+ "frame.tidMoreFields": "{n} more fields",
18521
18803
  "frame.tidPreviewWaiting": "Waiting for file content…",
18522
18804
  "frame.tidPreviewNoBody": "This .tid has fields but no body text.",
18523
18805
  "frame.tidPreviewFallback": "Rendering failed; showing the raw text:"
@@ -18747,7 +19029,10 @@ function apply(ctx, rawConfig = {}) {
18747
19029
  scope: toolScope,
18748
19030
  git,
18749
19031
  gitTargets: () => gitTargets(),
18750
- autoCommit: () => defaultInstance()?.touchAutoCommit(),
19032
+ autoCommit: (sessionId) => {
19033
+ const scoped = sessionId === void 0 ? void 0 : toolScope(sessionId);
19034
+ ((scoped?.id !== void 0 ? farm?.runtime(scoped.id) : void 0) ?? defaultInstance())?.touchAutoCommit();
19035
+ },
18751
19036
  restartAffected: async (dir, changedFiles) => restartAffectedWikis({
18752
19037
  farm: () => farm,
18753
19038
  repoRootOf: (d) => repos.repoRootOf(d)
@@ -18906,6 +19191,6 @@ function apply(ctx, rawConfig = {}) {
18906
19191
  }, "dsh-tiddlywiki: host teardown");
18907
19192
  }
18908
19193
  //#endregion
18909
- export { AGENT_WRITTEN_TAG, ALL_ARTICLES_MARKER_TITLE, ALL_ARTICLES_TEXT, ALL_ARTICLES_TITLE, ANON_USERNAME, AutoCommitter, CLIP_BRIDGE_BOOKMARKLET, CLIP_BRIDGE_DEFAULT_PORT, CLIP_BRIDGE_DOC_TEXT, CLIP_BRIDGE_DOC_TITLE, CLIP_BRIDGE_DRAG_HREF, CLIP_BRIDGE_MARKER_TITLE, ClipBridge, ConfigPatchError, ConfigStore, ConfigUnreadableError, DEFAULT_NOTE_TYPE, DEFAULT_PROMPT_MODE, DEFAULT_WECHAT_ADAPTER, DEFAULT_WECHAT_COMMAND, DEFAULT_WIKI_ID, DEFAULT_WIKI_MODE, DOC_NOTE_TAG, DOC_NOTE_TEXT, DOC_NOTE_TITLE, DSH_DOCS_TAG, GitConflictStateError, GitFace, HOME_DEFAULT_TIDDLERS, HOME_INDEX_ITEMS, HOME_INDEX_MARKER_TITLE, HUMAN_EDITED_TAG, LOCALE_NAMESPACE, LOCATION_STATE_VERSION, MARKDOWN_PLUGIN, MASKED_SECRET, MENUBAR_THEME_MARKER_TITLE, MENUBAR_THEME_TEXT, MENUBAR_THEME_TIDDLER, MISSING_TYPE_FILTER, NOTE_COMMAND_NAME, PATH_PREFIX, PROMPT_GOVERNANCE_BLOCKS, PROMPT_MODES, PROMPT_SECTION_NAME, PROMPT_SECTION_ORDER, READY_HARD_FACTOR, READY_POLL_MS, READY_SLOW_POLL_MS, READY_TIMEOUT_DEFAULT_MS, READY_TIMEOUT_MAX_MS, READY_TIMEOUT_MIN_MS, RENDER_BUNDLE_TEXT, RENDER_MARKER_TITLE, RENDER_PLUGIN_FILE, RENDER_PLUGIN_TITLE, RESERVED_WIKI_IDS, RepoCommitters, SEED_DEFS, SEED_MARKER_VERSION, SEND_TO_AGENT_BUNDLE_TEXT, SEND_TO_AGENT_MARKER_TITLE, SEND_TO_AGENT_PLUGIN_TITLE, SESSION_SCOPE_MAX_AGE_MS, SESSION_SCOPE_VERSION, SESSION_SUMMARY_PREFIX, SKILL_FILE_NAME, SPLIT_SKILL_DIR, SPLIT_SKILL_MARKER, STARTER_DOCS_ITEMS, STARTER_DOCS_MARKER_TITLE, TEXT_LIST_FILTER, TID_EXTENSIONS, TID_PREVIEW_ID, TID_PREVIEW_SLOT, TRASH_INDEX_TITLE, TRASH_PREFIX, TW_PROXY_PATH, TW_PROXY_PREFIX, TW_WEB_HOST_DEFAULT, TW_WEB_HOST_TIDDLER, TiddlyWebClient, TrashIndexUnavailableError, UI_STYLES_MARKER_TITLE, UI_STYLE_ITEMS, WECHAT_ADAPTERS, WECHAT_ADAPTER_FILES, WECHAT_ADAPTER_MARKER, WECHAT_DOCS_MARKER_TITLE, WECHAT_DOCS_TEXT, WECHAT_DOCS_TITLE, WECHAT_PUBLISH_BUNDLE_TEXT, WECHAT_PUBLISH_MARKER_TITLE, WECHAT_PUBLISH_PLUGIN_TITLE, WIKI_ICON_NAMES, WIKI_MODES, WIKI_REGISTRY_VERSION, WORKSPACE_FIELD, WORKSPACE_TAG_PREFIX, WechatPublishRunner, WikiFarm, WikiInstance, WikiServer, WriteConflictError, apply, applyWikiAction, assertNoConflict, assertPublicImageUrl, awaitReady, buildBinaryTiddler, buildClipTiddler, buildImageNoteTiddler, buildPromptText, buildPublishInvocation, buildVersionInvocation, buildWriteTiddler, bundledCatalog, capOutput, checkAllSeeds, checkWechatReady, cleanTiddler, clearLocationState, createGitLayer, createMutationLock, deepMerge, defaultAdaptersDir, defaultEntry, defaultLocationStateFile, defaultRegistryFile, defaultSessionScopeFile, defaultSkillRoot, defaultWechatJobDir, defineTool, deriveWikiId, describeConflict, describePrompt, describeUnreadableConfig, docNoteText, downloadClipImage, drainThenStop, dshHomePath, ensureLanguage, ensurePlugin, ensureTiddlerTimestamps, entryLocation, entryPath, escapeInline, escapePromptBraces, expandEnvPath, findEntry, findPathConflicts, flattenTiddlerFields, flushPendingWrites, formatTiddlerDate, hasHostTranslator, hashText, hostAllowed, imageExtensionForMime, inject, insertIntoSection, installSplitSkill, interpretPublishOutcome, isBinaryType, isInsidePath, isJunkTag, isPrivateAddress, isSafeCliValue, isSafeDsn, isSafeSessionId, isSafeUrl, listWikiCandidates, locationPath, maskConfigSecrets, name, needsRestartAfterSeeds, normalizeConfigPatch, normalizeEntry, normalizeFieldsArg, normalizeLocation, normalizePromptMode, normalizePromptPreview, normalizeReadyTimeoutMs, normalizeThemes, normalizeWechatConfig, normalizeWikiIcon, normalizeWikiId, normalizeWorkspaceName, openInTwEditor, parseClipPayload, parseNoteInput, parseSeedMarker, parseSkillText, parseTidText, parseTiddlerDate, pathComparisonKey, pickImageMime, pinLanguageTiddler, proxyBaseFor, pruneScopes, readActiveThemeName, readBundledSkillText, readLocationState, readRegistry, readSeedMarker, readSessionScopes, readWikiInfo, readyHardTimeoutMs, registerAdminRoutes, registerLocaleWithHost, registerNoteCommand, registerRoutes, registerSplitSkill, registerTiddlywikiTools, removeSeedById, removeWiki, resolveAgentScope, resolveClipTitle, resolveNodeExecutable, resolveTwRoot, resolveWikiRoot, runAllSeeds, runSeedById, sanitizeTwFragment, scanAdapterDir, scopeBanner, seedAllArticles, seedClipBridge, seedDocNote, seedHomeIndex, seedMenubarTheme, seedRenderRoute, seedSendToAgent, seedStarterDocs, seedUiStyles, seedWechatDocs, seedWechatPublish, setSessionScope, singleEntryRegistry, stoppedWikiFromRequest, stoppedWikiMessage, stripMaskedSecrets, switchWiki, tailOf, targetRuntimeFor, tiddlywikiToolSummary, toIsoDateString, toolSignatureLines, translate, unseedClipBridge, unseedWechatDocs, unseedWechatPublish, upsertWiki, validateRegistry, waitForFileWrite, wikiIdFromRequest, withScopeBanner, workspaceMarkFromCwd, workspaceNameFromCwd, workspaceTagName, writeLocationState, writeRegistry, writeSeedMarker, writeSessionScopes, writeSessionSummary, writeWikiInfo };
19194
+ export { AGENT_WRITTEN_TAG, ALL_ARTICLES_MARKER_TITLE, ALL_ARTICLES_TEXT, ALL_ARTICLES_TITLE, ANON_USERNAME, AutoCommitter, CLIP_BRIDGE_BOOKMARKLET, CLIP_BRIDGE_DEFAULT_PORT, CLIP_BRIDGE_DOC_TEXT, CLIP_BRIDGE_DOC_TITLE, CLIP_BRIDGE_DRAG_HREF, CLIP_BRIDGE_MARKER_TITLE, ClipBridge, ConfigPatchError, ConfigStore, ConfigUnreadableError, DEFAULT_NOTE_TYPE, DEFAULT_PROMPT_MODE, DEFAULT_WECHAT_ADAPTER, DEFAULT_WECHAT_COMMAND, DEFAULT_WIKI_ID, DEFAULT_WIKI_MODE, DOC_NOTE_TAG, DOC_NOTE_TEXT, DOC_NOTE_TITLE, DSH_DOCS_TAG, GitConflictStateError, GitFace, HOME_DEFAULT_TIDDLERS, HOME_INDEX_ITEMS, HOME_INDEX_MARKER_TITLE, HUMAN_EDITED_TAG, INTERNAL_FIELD_KEYS, LOCALE_NAMESPACE, LOCATION_STATE_VERSION, MARKDOWN_PLUGIN, MASKED_SECRET, MENUBAR_THEME_MARKER_TITLE, MENUBAR_THEME_TEXT, MENUBAR_THEME_TIDDLER, MISSING_TYPE_FILTER, NOTE_COMMAND_NAME, PATH_PREFIX, PROMPT_GOVERNANCE_BLOCKS, PROMPT_MODES, PROMPT_SECTION_NAME, PROMPT_SECTION_ORDER, READY_HARD_FACTOR, READY_POLL_MS, READY_SLOW_POLL_MS, READY_TIMEOUT_DEFAULT_MS, READY_TIMEOUT_MAX_MS, READY_TIMEOUT_MIN_MS, RENDER_BUNDLE_TEXT, RENDER_MARKER_TITLE, RENDER_PLUGIN_FILE, RENDER_PLUGIN_TITLE, RESERVED_WIKI_IDS, RepoCommitters, SEED_DEFS, SEED_MARKER_VERSION, SEND_TO_AGENT_BUNDLE_TEXT, SEND_TO_AGENT_MARKER_TITLE, SEND_TO_AGENT_PLUGIN_TITLE, SESSION_SCOPE_MAX_AGE_MS, SESSION_SCOPE_VERSION, SESSION_SUMMARY_PREFIX, SKILL_FILE_NAME, SPLIT_SKILL_DIR, SPLIT_SKILL_MARKER, STARTER_DOCS_ITEMS, STARTER_DOCS_MARKER_TITLE, SUMMARY_FIELD_KEYS, TEXT_LIST_FILTER, TID_EXTENSIONS, TID_PREVIEW_ID, TID_PREVIEW_SLOT, TRASH_INDEX_TITLE, TRASH_PREFIX, TW_PROXY_PATH, TW_PROXY_PREFIX, TW_WEB_HOST_DEFAULT, TW_WEB_HOST_TIDDLER, TiddlyWebClient, TrashIndexUnavailableError, UI_STYLES_MARKER_TITLE, UI_STYLE_ITEMS, WECHAT_ADAPTERS, WECHAT_ADAPTER_FILES, WECHAT_ADAPTER_MARKER, WECHAT_DOCS_MARKER_TITLE, WECHAT_DOCS_TEXT, WECHAT_DOCS_TITLE, WECHAT_PUBLISH_BUNDLE_TEXT, WECHAT_PUBLISH_MARKER_TITLE, WECHAT_PUBLISH_PLUGIN_TITLE, WIKI_ICON_NAMES, WIKI_MODES, WIKI_REGISTRY_VERSION, WORKSPACE_FIELD, WORKSPACE_TAG_PREFIX, WechatPublishRunner, WikiFarm, WikiInstance, WikiServer, WriteConflictError, apply, applyWikiAction, assertNoConflict, assertPublicImageUrl, awaitReady, buildBinaryTiddler, buildClipTiddler, buildImageNoteTiddler, buildPromptText, buildPublishInvocation, buildVersionInvocation, buildWriteTiddler, bundledCatalog, capOutput, checkAllSeeds, checkWechatReady, cleanTiddler, clearLocationState, createGitLayer, createMutationLock, deepMerge, defaultAdaptersDir, defaultEntry, defaultLocationStateFile, defaultRegistryFile, defaultSessionScopeFile, defaultSkillRoot, defaultWechatJobDir, defineTool, deriveWikiId, describeConflict, describePrompt, describeUnreadableConfig, docNoteText, downloadClipImage, drainThenStop, dshHomePath, ensureLanguage, ensurePlugin, ensureTiddlerTimestamps, entryLocation, entryPath, escapeInline, escapePromptBraces, expandEnvPath, findEntry, findPathConflicts, flattenTiddlerFields, flushPendingWrites, formatTidStamp, formatTiddlerDate, hasHostTranslator, hashText, hostAllowed, imageExtensionForMime, inject, insertIntoSection, installSplitSkill, interpretPublishOutcome, isBinaryType, isInsidePath, isJunkTag, isPrivateAddress, isSafeCliValue, isSafeDsn, isSafeSessionId, isSafeUrl, listWikiCandidates, locationPath, maskConfigSecrets, name, needsRestartAfterSeeds, normalizeConfigPatch, normalizeEntry, normalizeFieldsArg, normalizeLocation, normalizePromptMode, normalizePromptPreview, normalizeReadyTimeoutMs, normalizeThemes, normalizeWechatConfig, normalizeWikiIcon, normalizeWikiId, normalizeWorkspaceName, openInTwEditor, parseClipPayload, parseNoteInput, parseSeedMarker, parseSkillText, parseTidText, parseTiddlerDate, pathComparisonKey, pickImageMime, pinLanguageTiddler, proxyBaseFor, pruneScopes, readActiveThemeName, readBundledSkillText, readLocationState, readRegistry, readSeedMarker, readSessionScopes, readWikiInfo, readyHardTimeoutMs, registerAdminRoutes, registerLocaleWithHost, registerNoteCommand, registerRoutes, registerSplitSkill, registerTiddlywikiTools, removeSeedById, removeWiki, resolveAgentScope, resolveClipTitle, resolveNodeExecutable, resolveTwRoot, resolveWikiRoot, runAllSeeds, runSeedById, sanitizeTwFragment, scanAdapterDir, scopeBanner, seedAllArticles, seedClipBridge, seedDocNote, seedHomeIndex, seedMenubarTheme, seedRenderRoute, seedSendToAgent, seedStarterDocs, seedUiStyles, seedWechatDocs, seedWechatPublish, setSessionScope, singleEntryRegistry, stoppedWikiFromRequest, stoppedWikiMessage, stripMaskedSecrets, summarizeTid, switchWiki, tailOf, targetRuntimeFor, tiddlywikiToolSummary, toIsoDateString, toolSignatureLines, translate, unseedClipBridge, unseedWechatDocs, unseedWechatPublish, upsertWiki, validateRegistry, waitForFileWrite, wikiIdFromRequest, withScopeBanner, workspaceMarkFromCwd, workspaceNameFromCwd, workspaceTagName, writeLocationState, writeRegistry, writeSeedMarker, writeSessionScopes, writeSessionSummary, writeWikiInfo };
18910
19195
 
18911
19196
  //# sourceMappingURL=index.js.map