@waterwx/dsh-novel-forge 1.7.3 → 1.9.0

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 (44) hide show
  1. package/lib/client.js +3627 -447
  2. package/lib/client.js.map +1 -1
  3. package/lib/index.js +1127 -141
  4. package/lib/index.js.map +1 -1
  5. package/lib/types/author-assets.d.ts +25 -0
  6. package/lib/types/client/api.d.ts +31 -1
  7. package/lib/types/client/locales.d.ts +16 -0
  8. package/lib/types/client/panel/AdaptModeView.d.ts +4 -0
  9. package/lib/types/client/panel/AuthorAssetsView.d.ts +4 -0
  10. package/lib/types/client/panel/AuthorHome.d.ts +30 -0
  11. package/lib/types/client/panel/ModelManager.d.ts +14 -0
  12. package/lib/types/client/panel/ModelPicker.d.ts +11 -0
  13. package/lib/types/client/panel/ProgressConsole.d.ts +17 -0
  14. package/lib/types/client/panel/ProgressHomeView.d.ts +5 -0
  15. package/lib/types/client/panel/ReasoningSection.d.ts +10 -0
  16. package/lib/types/client/panel/SettingsView.d.ts +14 -0
  17. package/lib/types/client/text.d.ts +9 -0
  18. package/lib/types/engine.d.ts +39 -1
  19. package/lib/types/index.d.ts +8 -0
  20. package/lib/types/protocol.d.ts +339 -0
  21. package/package.json +1 -1
  22. package/src/author-assets.ts +166 -0
  23. package/src/client/api.ts +82 -0
  24. package/src/client/locales.ts +32 -0
  25. package/src/client/mount.tsx._new +97 -0
  26. package/src/client/mount.tsx._nf +97 -0
  27. package/src/client/mount.tsx._tmp +97 -0
  28. package/src/client/panel/AdaptModeView.tsx +202 -0
  29. package/src/client/panel/AuthorAssetsView.tsx +206 -0
  30. package/src/client/panel/AuthorHome.tsx +107 -0
  31. package/src/client/panel/ImportModal.tsx +2 -1
  32. package/src/client/panel/ModelManager.tsx +205 -0
  33. package/src/client/panel/NovelPanel.tsx +73 -79
  34. package/src/client/panel/ProgressConsole.tsx +64 -0
  35. package/src/client/panel/ProgressHomeView.tsx +87 -0
  36. package/src/client/panel/ReasoningSection.tsx +31 -0
  37. package/src/client/panel/SettingsView.tsx +292 -0
  38. package/src/client/panel/panel.module.css +325 -0
  39. package/src/client/sidebar-entry.ts +1 -1
  40. package/src/client/text.ts +28 -0
  41. package/src/engine.ts +442 -0
  42. package/src/index.ts +20 -0
  43. package/src/protocol.ts +356 -0
  44. package/src/routes.ts +323 -0
@@ -55,6 +55,18 @@ export declare const NOVEL_API: {
55
55
  readonly storyboardPrompts: "/api/dsh-novel-forge/storyboard/prompts";
56
56
  /** 生图接口连通性测试(设置页每个模型条目用)。 */
57
57
  readonly imageTest: "/api/dsh-novel-forge/image-test";
58
+ /** LLM 模型连通性测试:真实最小调用,验证 Key / 端点 / 模型可用。 */
59
+ readonly llmTest: "/api/dsh-novel-forge/llm-test";
60
+ /** 添加模型:厂商直填 key 或自定义路由,写进 DSH 凭据与 llm-pi-ai 路由。 */
61
+ readonly addModel: "/api/dsh-novel-forge/llm-add";
62
+ /** 运行时厂商目录(DSH pi-ai 可配置提供方 + 内置适配器)。 */
63
+ readonly llmVendors: "/api/dsh-novel-forge/llm-vendors";
64
+ /** 查询某个 provider 当前可用的模型(添加成功后可即时刷新)。 */
65
+ readonly llmModels: "/api/dsh-novel-forge/llm-models";
66
+ /** 已注册的提供方路由列表(提供方管理)。 */
67
+ readonly llmProviders: "/api/dsh-novel-forge/llm-providers";
68
+ /** 移除一个提供方。 */
69
+ readonly llmRemove: "/api/dsh-novel-forge/llm-remove";
58
70
  /** 重置项目(可选携带新大纲):清空设定/卷/章节/伏笔/资产/事实库。 */
59
71
  readonly reset: "/api/dsh-novel-forge/reset";
60
72
  /** 全书一致性质检:LLM 扫描已生成章节,输出矛盾问题清单。 */
@@ -104,6 +116,24 @@ export declare const NOVEL_API: {
104
116
  readonly runStatus: "/api/dsh-novel-forge/run/status";
105
117
  readonly config: "/api/dsh-novel-forge/config";
106
118
  readonly openFolder: "/api/dsh-novel-forge/open-folder";
119
+ /** 作者资产库/总数据:读取个人跨书资产(笔法/红线/套路/角色模板/世界观模板)。 */
120
+ readonly authorAssets: "/api/dsh-novel-forge/author-assets";
121
+ /** 作者资产库:新增/更新一条资产(upsert by id)。 */
122
+ readonly authorAssetsUpsert: "/api/dsh-novel-forge/author-assets/upsert";
123
+ /** 作者资产库:删除一条资产。 */
124
+ readonly authorAssetsRemove: "/api/dsh-novel-forge/author-assets/remove";
125
+ /** 作者资产库:导入默认(书架书的写作资产/角色 + 内置全局库)批量沉淀。 */
126
+ readonly authorAssetsImportDefault: "/api/dsh-novel-forge/author-assets/import-default";
127
+ /** 改编模式:上传全文 → 分析 → 原文设定卡片/可改范围矩阵。 */
128
+ readonly adaptAnalyze: "/api/dsh-novel-forge/adapt/analyze";
129
+ /** 改编模式:确认要改的维度 → 生成映射表/改编规则/联动影响清单。 */
130
+ readonly adaptPropose: "/api/dsh-novel-forge/adapt/propose";
131
+ /** 改编模式:执行术语替换(全局替换 + 命中统计 + 改编文本预览)。 */
132
+ readonly adaptExecute: "/api/dsh-novel-forge/adapt/execute";
133
+ /** 主题自定义背景:上传图片(POST,存盘并返回服务端 URL)。 */
134
+ readonly themeBackgroundUpload: "/api/dsh-novel-forge/theme/background";
135
+ /** 主题自定义背景:读取已上传文件(GET prefix,/theme/background/<name>)。 */
136
+ readonly themeBackgroundGet: "/api/dsh-novel-forge/theme/background";
107
137
  };
108
138
  /** 书架:一本书的条目。 */
109
139
  export interface BookEntry {
@@ -977,6 +1007,21 @@ export interface ImageTestResponse {
977
1007
  /** 模型 id 是否出现在接口的模型列表(探测成功时才有)。 */
978
1008
  modelFound?: boolean;
979
1009
  }
1010
+ /** POST /llm-test 请求:对选中的提供商/模型发一次最小真实调用。 */
1011
+ export interface LlmTestRequest {
1012
+ provider: string;
1013
+ model: string;
1014
+ }
1015
+ /** POST /llm-test 响应。 */
1016
+ export interface LlmTestResponse {
1017
+ ok: boolean;
1018
+ /** 连通延迟(毫秒)。 */
1019
+ ms?: number;
1020
+ /** 失败原因(已映射为人话)。 */
1021
+ message?: string;
1022
+ /** 稳定错误码(LlmError code),便于排查。 */
1023
+ code?: string;
1024
+ }
980
1025
  /** POST /roles 响应。 */
981
1026
  export interface RolesResponse {
982
1027
  roles: RoleRecord[];
@@ -1140,6 +1185,122 @@ export interface ImageModelConfig {
1140
1185
  enabled: boolean;
1141
1186
  }
1142
1187
  /** Runtime config surface exposed to the panel (subset of plugin Config). */
1188
+ /** 手动添加的模型库条目(只存插件内,不改 DSH 全局)。 */
1189
+ export interface SavedModel {
1190
+ /** 唯一 id(前端生成的短 id)。 */
1191
+ id: string;
1192
+ /** 展示名(可为空,回退到 model)。 */
1193
+ name: string;
1194
+ /** DSH 提供商路由(如 zai-coding-cn)。 */
1195
+ provider: string;
1196
+ /** 模型 id(如 glm-5.3-flash)。 */
1197
+ model: string;
1198
+ }
1199
+ /** DSH 模型添加:厂商预设(选择厂商,直接填 API Key)。 */
1200
+ export interface LlmVendor {
1201
+ id: string;
1202
+ name: string;
1203
+ /** 该厂商对应的 provider 路由。 */
1204
+ route: string;
1205
+ /** DSH 凭据引用名(写入 .credentials.yaml 的 refs)。 */
1206
+ apiKeyEnv: string;
1207
+ /** 默认模型 id。 */
1208
+ defaultModel: string;
1209
+ /** 建议可选模型 id 列表(下拉 data-list 用)。 */
1210
+ models: string[];
1211
+ /** 内置适配器(如 deepseek-official),无需注册 pi-ai 路由。 */
1212
+ builtin?: boolean;
1213
+ }
1214
+ /** 预置的常见厂商(id=provider 路由;添加模型下拉兜底用,其余厂商由运行时目录动态补充)。 */
1215
+ export declare const LLM_VENDORS: LlmVendor[];
1216
+ /** 运行时厂商目录的一项(添加到模型下拉;由 DSH 的 pi-ai 可配置提供方动态生成)。 */
1217
+ export interface LlmVendorOption {
1218
+ /** provider 路由 id(也是厂商下拉的值)。 */
1219
+ id: string;
1220
+ /** 展示名。 */
1221
+ name: string;
1222
+ /** 建议模型 id(可为空,用户手填)。 */
1223
+ models: string[];
1224
+ /** 已知 DSH 凭据引用名;为空时 host 生成 `PI_AI_<ID>_API_KEY`。 */
1225
+ apiKeyEnv?: string;
1226
+ /** 内置适配器(只写凭据,不注册 pi-ai 路由)。 */
1227
+ builtin?: boolean;
1228
+ }
1229
+ /** GET /llm-vendors 响应。 */
1230
+ export interface LlmVendorsResponse {
1231
+ vendors: LlmVendorOption[];
1232
+ }
1233
+ /** /llm-models 里的一条模型。 */
1234
+ export interface LlmModelOption {
1235
+ id: string;
1236
+ name: string;
1237
+ }
1238
+ /** GET /llm-models?provider=x 响应。 */
1239
+ export interface LlmModelsResponse {
1240
+ models: LlmModelOption[];
1241
+ }
1242
+ /** GET /llm-providers 响应:当前已注册的提供方路由。 */
1243
+ export interface LlmProvidersResponse {
1244
+ providers: {
1245
+ id: string;
1246
+ name: string;
1247
+ }[];
1248
+ }
1249
+ /** POST /llm-remove 请求:移除一个提供方(unset key + 移除 llm-pi-ai 路由)。 */
1250
+ export interface RemoveProviderRequest {
1251
+ provider: string;
1252
+ /** 该提供方对应的 DSH 凭据引用名(用于 unset)。 */
1253
+ apiKeyEnv?: string;
1254
+ }
1255
+ /** POST /llm-remove 响应。 */
1256
+ export interface RemoveProviderResponse {
1257
+ ok: boolean;
1258
+ message?: string;
1259
+ }
1260
+ /** GET /llm-providers 响应:当前已注册的提供方路由。 */
1261
+ export interface LlmProvidersResponse {
1262
+ providers: {
1263
+ id: string;
1264
+ name: string;
1265
+ }[];
1266
+ }
1267
+ /** POST /llm-remove 请求:移除一个提供方(unset key + 移除 llm-pi-ai 路由)。 */
1268
+ export interface RemoveProviderRequest {
1269
+ provider: string;
1270
+ /** 该提供方对应的 DSH 凭据引用名(用于 unset)。 */
1271
+ apiKeyEnv?: string;
1272
+ }
1273
+ /** POST /llm-remove 响应。 */
1274
+ export interface RemoveProviderResponse {
1275
+ ok: boolean;
1276
+ message?: string;
1277
+ }
1278
+ /** POST /llm-add 请求:添加一个模型(厂商直填 key,或自定义路由)。 */
1279
+ export interface AddModelRequest {
1280
+ mode: 'vendor' | 'custom';
1281
+ /** 厂商模式用:provider 路由 id(来自 /llm-vendors)。 */
1282
+ vendor?: string;
1283
+ /** 厂商已知的 DSH 凭据引用名(可选;为空时 host 生成)。 */
1284
+ apiKeyEnv?: string;
1285
+ /** 自定义模式用:provider 路由 id。 */
1286
+ provider?: string;
1287
+ /** 模型 id。 */
1288
+ model: string;
1289
+ /** API Key。 */
1290
+ apiKey: string;
1291
+ /** 展示名(可选)。 */
1292
+ name?: string;
1293
+ /** 自定义模式用:OpenAI 兼容 base URL。 */
1294
+ baseURL?: string;
1295
+ }
1296
+ /** POST /llm-add 响应。 */
1297
+ export interface AddModelResponse {
1298
+ ok: boolean;
1299
+ saved: SavedModel;
1300
+ provider: string;
1301
+ message?: string;
1302
+ }
1303
+ /** 手动添加的模型库条目(只存插件内,不改 DSH 全局)。 */
1143
1304
  export interface NovelConfig {
1144
1305
  /** Absolute path of the default docx outline to load. */
1145
1306
  outlinePath: string;
@@ -1175,6 +1336,16 @@ export interface NovelConfig {
1175
1336
  imageApiModel?: string;
1176
1337
  /** 是否启用生图(= 存在启用条目)。 */
1177
1338
  imageApiEnabled?: boolean;
1339
+ /** 自定义背景图(URL 或 dataURL 或服务端路径引用;空 = 使用主题默认背景)。 */
1340
+ themeBackground?: string;
1341
+ /** 自定义背景遮罩/模糊强度 0-80(0 = 不遮罩)。 */
1342
+ themeBackgroundBlur?: number;
1343
+ /** 玻璃透明度 0-100(100=当前原样,越小越透,新拟态/黏土可见背景图)。 */
1344
+ themeOpacity?: number;
1345
+ /** 是否启用改编模式(默认关闭;发布后开启)。 */
1346
+ enableAdaptMode?: boolean;
1347
+ /** 手动添加的模型库(「我的模型」条目;只存插件内)。 */
1348
+ savedModels?: SavedModel[];
1178
1349
  }
1179
1350
  /** GET /status response. */
1180
1351
  export interface StatusResponse {
@@ -1412,8 +1583,17 @@ export interface ConfigPatch {
1412
1583
  imageApiKey?: string;
1413
1584
  imageApiModel?: string;
1414
1585
  imageApiEnabled?: boolean;
1586
+ /** 自定义背景图(URL / dataURL / 服务端路径引用)。 */
1587
+ themeBackground?: string;
1588
+ /** 自定义背景遮罩/模糊强度 0-80。 */
1589
+ themeBackgroundBlur?: number;
1590
+ /** 玻璃透明度 0-100(100=当前原样)。 */
1591
+ themeOpacity?: number;
1592
+ enableAdaptMode?: boolean;
1415
1593
  /** 生图模型库(完整替换保存)。 */
1416
1594
  imageModels?: ImageModelConfig[];
1595
+ /** 手动添加的模型库(完整替换保存)。 */
1596
+ savedModels?: SavedModel[];
1417
1597
  }
1418
1598
  /** One assistant conversation message (persisted per project). */
1419
1599
  export interface AssistantMessage {
@@ -1573,3 +1753,162 @@ export interface StyleEngineRequest {
1573
1753
  /** 资产名(可选,默认「风格资产 N」)。 */
1574
1754
  name?: string;
1575
1755
  }
1756
+ /** 作者资产库中一条可跨书复用的资产(笔法/红线/套路/角色模板/世界观模板等)。 */
1757
+ export interface AuthorStyleAsset {
1758
+ /** 稳定 id(本地唯一)。 */
1759
+ id: string;
1760
+ /** 资产名(如「短句快节奏爽文风」「林越式痞坏角色」)。 */
1761
+ name: string;
1762
+ /** 资产类型。 */
1763
+ kind: 'style' | 'antiAi' | 'progression' | 'genre' | 'roleTemplate' | 'worldTemplate' | 'custom';
1764
+ /** 一句话摘要。 */
1765
+ summary: string;
1766
+ /** 资产正文内容(按 kind 约定解读的文本/JSON 描述)。 */
1767
+ content: string;
1768
+ /** 结构化载荷(角色模板/世界观模板等可结构化字段;缺省为 null)。 */
1769
+ structured?: Record<string, unknown>;
1770
+ /** 来源书名(哪本书提炼/收藏而来)。 */
1771
+ sourceBooks: string[];
1772
+ /** 标签。 */
1773
+ tags: string[];
1774
+ /** 来源样本文本(可选)。 */
1775
+ sourceText?: string;
1776
+ /** 创建时间。 */
1777
+ createdAt: string;
1778
+ /** 更新时间。 */
1779
+ updatedAt: string;
1780
+ }
1781
+ /** 作者资产库(跨书总数据):按作者维度聚合的可复用资产。 */
1782
+ export interface AuthorAssetLibrary {
1783
+ /** 货架版本,便于未来迁移。 */
1784
+ version: 1;
1785
+ items: AuthorStyleAsset[];
1786
+ }
1787
+ /** GET /author-assets 响应。 */
1788
+ export interface AuthorAssetsResponse {
1789
+ assets: AuthorAssetLibrary;
1790
+ }
1791
+ /** POST /author-assets/upsert 请求:新增或按 id 更新一条资产。 */
1792
+ export interface AuthorAssetUpsertRequest {
1793
+ asset: AuthorStyleAsset;
1794
+ }
1795
+ /** POST /author-assets/remove 请求:删除一条资产。 */
1796
+ export interface AuthorAssetRemoveRequest {
1797
+ id: string;
1798
+ }
1799
+ /** 改编可改范围的单个维度(矩阵的一行)。 */
1800
+ export interface AdaptationDimension {
1801
+ /** 维度 key(如 realm/name/goldenFinger…)。 */
1802
+ key: string;
1803
+ /** 维度名(如「大世界」「修为体系」「主角名」「金手指」)。 */
1804
+ title: string;
1805
+ /** 可改度:保留 / 可改影响大 / 可改影响小 / 可自由改 / 仅视觉包装。 */
1806
+ mutability: 'locked' | 'big' | 'small' | 'free' | 'visual';
1807
+ /** 原文当前值(从正文提炼,附证据)。 */
1808
+ current: string;
1809
+ /** 该值在正文中的出现证据(章节/频次,可空)。 */
1810
+ evidence?: string;
1811
+ /** AI 建议的候选新值(可空)。 */
1812
+ candidates?: string[];
1813
+ /** 联动影响说明(改了会影响哪些章节/角色/伏笔/术语)。 */
1814
+ impact: string;
1815
+ /** 风险评级。 */
1816
+ risk: 'high' | 'medium' | 'low';
1817
+ }
1818
+ /** POST /adapt/analyze 请求:上传全文做改编分析。 */
1819
+ export interface AdaptAnalyzeRequest {
1820
+ /** 全文文本(优先)。 */
1821
+ text: string;
1822
+ /** 或服务器端全文文件路径。 */
1823
+ filePath?: string;
1824
+ }
1825
+ /** POST /adapt/analyze 响应。 */
1826
+ export interface AdaptAnalyzeResponse {
1827
+ /** 识别书名(文件名推断或正文首行)。 */
1828
+ bookName: string;
1829
+ /** 拆出的章节数。 */
1830
+ chapters: number;
1831
+ /** 反推的初始大纲(可空)。 */
1832
+ outline?: string;
1833
+ /** 可改范围矩阵。 */
1834
+ dimensions: AdaptationDimension[];
1835
+ /** 分析消耗说明。 */
1836
+ note?: string;
1837
+ }
1838
+ /** 一条改编映射(原值 → 新值)。 */
1839
+ export interface AdaptationMapping {
1840
+ /** 原值(如「林尘」「练气」「青云宗」)。 */
1841
+ source: string;
1842
+ /** 新值(如「楚风」「凝元」「天渊阁」)。 */
1843
+ target: string;
1844
+ /** 适用范围。 */
1845
+ scope: 'name' | 'realm' | 'faction' | 'term' | 'other';
1846
+ /** 说明(可空)。 */
1847
+ note?: string;
1848
+ }
1849
+ /** 改编规则:哪些必须保留、哪些允许改、一致性约束。 */
1850
+ export interface AdaptationRules {
1851
+ /** 必须保留的要素(骨架/人物动机/伏笔逻辑/爽点结构…)。 */
1852
+ preserve: string[];
1853
+ /** 允许改变的要素。 */
1854
+ change: string[];
1855
+ /** 改编红线/一致性要求。 */
1856
+ constraints: string[];
1857
+ }
1858
+ /** 一组改编方案(映射表 + 规则 + 联动影响清单)。 */
1859
+ export interface AdaptationProposal {
1860
+ /** 映射表(原→新)。 */
1861
+ mappings: AdaptationMapping[];
1862
+ /** 改编规则。 */
1863
+ rules: AdaptationRules;
1864
+ /** 联动影响清单。 */
1865
+ impacts: Array<{
1866
+ item: string;
1867
+ detail: string;
1868
+ risk: 'high' | 'medium' | 'low';
1869
+ chapters?: number[];
1870
+ }>;
1871
+ }
1872
+ /** POST /adapt/propose 请求:由用户勾选的维度 + 新值生成改编方案。 */
1873
+ export interface AdaptProposeRequest {
1874
+ /** 原文全文(复用,便于 LLM 核对联动影响)。 */
1875
+ text: string;
1876
+ /** 用户确认要改的维度(含原值与新值)。 */
1877
+ selections: Array<{
1878
+ key: string;
1879
+ title: string;
1880
+ current: string;
1881
+ target: string;
1882
+ mutability: string;
1883
+ }>;
1884
+ /** 若已分析过,可携带完整矩阵作为上下文。 */
1885
+ dimensions?: AdaptationDimension[];
1886
+ }
1887
+ /** POST /adapt/propose 响应。 */
1888
+ export interface AdaptProposeResponse {
1889
+ proposal: AdaptationProposal;
1890
+ }
1891
+ /** POST /adapt/execute 请求:执行改编(首版为术语替换)。 */
1892
+ export interface AdaptExecuteRequest {
1893
+ /** 原文全文。 */
1894
+ text: string;
1895
+ /** 改编映射表。 */
1896
+ mappings: AdaptationMapping[];
1897
+ /** 改编规则(可选,后续逐章改写使用;替换模式暂不依赖)。 */
1898
+ rules?: AdaptationRules;
1899
+ /** 执行模式:首版仅 replace(术语替换)。 */
1900
+ mode?: 'replace' | 'rewrite';
1901
+ }
1902
+ /** POST /adapt/execute 响应。 */
1903
+ export interface AdaptExecuteResponse {
1904
+ /** 改编后的全文。 */
1905
+ adaptedText: string;
1906
+ /** 执行的映射数。 */
1907
+ mappings: number;
1908
+ /** 命中统计:每条映射的替换次数。 */
1909
+ hits: Array<{
1910
+ source: string;
1911
+ target: string;
1912
+ count: number;
1913
+ }>;
1914
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@waterwx/dsh-novel-forge",
3
3
  "description": "AI 编译小说工作台 for the dsh web GUI: import a novel outline (docx/text), plan chapters with LLM, generate chapter by chapter (3000-4000 chars each), and save every chapter as Markdown into your chosen output folder.",
4
- "version": "1.7.3",
4
+ "version": "1.9.0",
5
5
  "type": "module",
6
6
  "engines": {
7
7
  "node": "^22.19.0 || >=24.0.0"
@@ -0,0 +1,166 @@
1
+ /**
2
+ * 作者资产库/总数据(跨书)— 按作者维度聚合的可复用资产。
3
+ * 与书架同惯例持久化到 ~/.dsh/dsh-novel-forge-author-assets.json。
4
+ * 提供读取/持久化/新增或更新/删除,以及「导入默认」:把书架书的写作资产/角色 +
5
+ * 内置全局库(题材/反AI规则/风格模板/推进模式)批量沉淀成资产条目(默认库)。
6
+ */
7
+
8
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
9
+ import { homedir } from 'node:os'
10
+ import { join } from 'node:path'
11
+ import { randomBytes } from 'node:crypto'
12
+ import type { AuthorAssetLibrary, AuthorStyleAsset, GenreNode, AntiAiRule, StyleTemplate, ProgressionMode } from './protocol.ts'
13
+ import { BUILTIN_ANTI_AI_RULES, BUILTIN_GENRE_LIBRARY, BUILTIN_PROGRESSION_MODES, BUILTIN_STYLE_TEMPLATES } from './assets.ts'
14
+ import { loadBookshelf } from './bookshelf.ts'
15
+ import { loadProject } from './engine.ts'
16
+
17
+ /** 作者资产库配置文件路径。 */
18
+ export function authorAssetsFile(): string {
19
+ return join(homedir(), '.dsh', 'dsh-novel-forge-author-assets.json')
20
+ }
21
+
22
+ /** 默认空资产库。 */
23
+ function defaultLibrary(): AuthorAssetLibrary {
24
+ return { version: 1, items: [] }
25
+ }
26
+
27
+ /** 读取作者资产库(不存在/损坏则返回空库,不抛错)。 */
28
+ export function loadAuthorAssets(): AuthorAssetLibrary {
29
+ const file = authorAssetsFile()
30
+ if (!existsSync(file)) return defaultLibrary()
31
+ try {
32
+ let raw = readFileSync(file, 'utf8')
33
+ if (raw.charCodeAt(0) === 0xFEFF) raw = raw.slice(1)
34
+ const parsed = JSON.parse(raw) as Partial<AuthorAssetLibrary>
35
+ if (!Array.isArray(parsed.items)) return defaultLibrary()
36
+ return { version: 1, items: parsed.items }
37
+ } catch {
38
+ return defaultLibrary()
39
+ }
40
+ }
41
+
42
+ /** 持久化作者资产库。 */
43
+ export function saveAuthorAssets(library: AuthorAssetLibrary): void {
44
+ const file = authorAssetsFile()
45
+ mkdirSync(join(homedir(), '.dsh'), { recursive: true })
46
+ writeFileSync(file, JSON.stringify(library, null, 2), 'utf8')
47
+ }
48
+
49
+ /** 新建一条资产(自动生成 id 与时间戳)。 */
50
+ export function createAuthorAsset(input: Omit<AuthorStyleAsset, 'id' | 'createdAt' | 'updatedAt'>): AuthorStyleAsset {
51
+ const now = new Date().toISOString()
52
+ const asset: AuthorStyleAsset = {
53
+ ...input,
54
+ id: 'aa-' + Date.now().toString(36) + '-' + randomBytes(3).toString('hex'),
55
+ sourceBooks: input.sourceBooks ?? [],
56
+ tags: input.tags ?? [],
57
+ createdAt: now,
58
+ updatedAt: now,
59
+ }
60
+ const library = loadAuthorAssets()
61
+ library.items.push(asset)
62
+ saveAuthorAssets(library)
63
+ return asset
64
+ }
65
+
66
+ /** 按 id 更新一条资产;不存在则追加。 */
67
+ export function upsertAuthorAsset(input: AuthorStyleAsset): AuthorAssetLibrary {
68
+ const library = loadAuthorAssets()
69
+ const idx = library.items.findIndex(a => a.id === input.id)
70
+ const now = new Date().toISOString()
71
+ if (idx >= 0) {
72
+ const prev = library.items[idx]
73
+ if (prev !== undefined) {
74
+ library.items[idx] = {
75
+ ...prev,
76
+ ...input,
77
+ id: prev.id,
78
+ createdAt: prev.createdAt,
79
+ updatedAt: now,
80
+ }
81
+ }
82
+ } else {
83
+ library.items.push({ ...input, createdAt: input.createdAt !== '' ? input.createdAt : now, updatedAt: now })
84
+ }
85
+ saveAuthorAssets(library)
86
+ return library
87
+ }
88
+
89
+ /** 删除一条资产;返回更新后的资产库。 */
90
+ export function removeAuthorAsset(id: string): AuthorAssetLibrary {
91
+ const library = loadAuthorAssets()
92
+ library.items = library.items.filter(a => a.id !== id)
93
+ saveAuthorAssets(library)
94
+ return library
95
+ }
96
+
97
+ /**
98
+ * 导入默认:把书架所有书的写作资产/角色 + 内置全局库批量沉淀到作者资产库。
99
+ * 按 `kind:name` 去重(已存在则跳过),不覆盖用户已有条目。
100
+ * @returns 更新后的资产库。
101
+ */
102
+ export function importDefaultAuthorAssets(): AuthorAssetLibrary {
103
+ const library = loadAuthorAssets()
104
+ const seen = new Set(library.items.map(a => a.kind + ':' + a.name))
105
+ const now = new Date().toISOString()
106
+ const push = (kind: AuthorStyleAsset['kind'], name: string, summary: string, content: string, tags: string[], sourceBooks: string[], structured?: Record<string, unknown>): void => {
107
+ const key = kind + ':' + name.trim()
108
+ if (name.trim() === '' || seen.has(key)) return
109
+ seen.add(key)
110
+ library.items.push({
111
+ id: 'aa-' + Date.now().toString(36) + '-' + randomBytes(3).toString('hex'),
112
+ kind, name: name.trim(), summary: summary.trim(), content: content.trim(),
113
+ sourceBooks, tags, structured, createdAt: now, updatedAt: now,
114
+ });
115
+ };
116
+
117
+ // 1) 内置全局库
118
+ for (const g of flattenGenres(BUILTIN_GENRE_LIBRARY)) {
119
+ push('genre', g.name, g.description, g.description, ['内置', '题材'], [], { description: g.description, children: (g.children ?? []).map(c => c.name) });
120
+ }
121
+ for (const r of BUILTIN_ANTI_AI_RULES) {
122
+ push('antiAi', r.name, r.avoid, '避免:' + r.avoid + '\n修正:' + r.fix, ['内置', '反AI'], [], { avoid: r.avoid, fix: r.fix, detectPatterns: r.detectPatterns });
123
+ }
124
+ for (const t of BUILTIN_STYLE_TEMPLATES) {
125
+ push('style', t.name, t.description,
126
+ '分类:' + t.category + '\n适用:' + t.applicableGenres.join('、') + '\n叙述:' + t.proseRules.join(';') + '\n台词:' + t.dialogueRules.join(';') + '\n语言:' + t.languageRules.join(';') + '\n节奏:' + t.rhythmRules.join(';'),
127
+ ['内置', '风格模板'], [], { category: t.category, applicableGenres: t.applicableGenres });
128
+ }
129
+ for (const p of BUILTIN_PROGRESSION_MODES) {
130
+ push('progression', p.name, p.driver, '驱动:' + p.driver + '\n期待:' + p.readerExpectation + '\n兑现:' + p.payoffs.join(';') + '\n风险:' + p.risks.join(';'), ['内置', '推进'], [], { driver: p.driver, primary: p.primary });
131
+ }
132
+
133
+ // 2) 书架里的书:写作资产 + 角色模板
134
+ const shelf = loadBookshelf()
135
+ for (const book of shelf.books) {
136
+ const project = loadProject(book.outputDir)
137
+ if (project === undefined) continue
138
+ const src = [project.bookName]
139
+ const assets = project.assets
140
+ if (assets !== undefined) {
141
+ if (assets.genre !== undefined) push('genre', assets.genre.name, assets.genre.description, assets.genre.description, ['书', '题材'], src, { description: assets.genre.description });
142
+ if (assets.primaryProgression !== undefined) push('progression', assets.primaryProgression.name, assets.primaryProgression.driver, '驱动:' + assets.primaryProgression.driver + '\n期待:' + assets.primaryProgression.readerExpectation, src, [], { driver: assets.primaryProgression.driver, primary: true });
143
+ for (const p of assets.auxiliaryProgressions ?? []) push('progression', p.name, p.driver, '驱动:' + p.driver + '\n期待:' + p.readerExpectation, src, [], { driver: p.driver, primary: false });
144
+ for (const r of assets.antiAiRules ?? []) push('antiAi', r.name, r.avoid, '避免:' + r.avoid + '\n修正:' + r.fix, src, [], { avoid: r.avoid, fix: r.fix, detectPatterns: r.detectPatterns });
145
+ for (const s of assets.styleAssets ?? []) push('style', s.name, s.proseRules.join(';'),
146
+ '叙述:' + s.proseRules.join(';') + '\n台词:' + s.dialogueRules.join(';') + '\n描写:' + s.descriptionRules.join(';') + '\n边界:' + s.boundaries.join(';'), src, [], { sourceText: s.sourceText });
147
+ }
148
+ for (const role of project.roles ?? []) {
149
+ const persona = ('身份:' + role.identity + '\n性格:' + role.traits.join('、') + '\n目标:' + role.goals + '\n关系:' + role.relations.join('、') + '\n成长线:' + (role.arc.length > 0 ? role.arc.join(' > ') : '—') + '\n知情度:' + role.knowledge.join('、')).trim();
150
+ push('roleTemplate', role.name, role.identity, persona, src, [], { roleLabel: role.roleLabel, traits: role.traits, relations: role.relations, arc: role.arc, knowledge: role.knowledge });
151
+ }
152
+ }
153
+
154
+ saveAuthorAssets(library)
155
+ return library
156
+ }
157
+
158
+ /** 拍平题材库(含子题材,父级名称并入 tag)。 */
159
+ function flattenGenres(nodes: GenreNode[], parentName?: string): GenreNode[] {
160
+ const out: GenreNode[] = []
161
+ for (const n of nodes) {
162
+ out.push({ ...n, name: parentName !== undefined ? parentName + '/' + n.name : n.name });
163
+ if (n.children.length > 0) out.push(...flattenGenres(n.children, parentName !== undefined ? parentName + '/' + n.name : n.name));
164
+ }
165
+ return out
166
+ }
package/src/client/api.ts CHANGED
@@ -8,6 +8,13 @@ import {
8
8
  NOVEL_API,
9
9
  type AssetsPatch,
10
10
  type AssetsResponse,
11
+ type AddModelRequest,
12
+ type AddModelResponse,
13
+ type LlmModelsResponse,
14
+ type LlmProvidersResponse,
15
+ type LlmVendorsResponse,
16
+ type RemoveProviderRequest,
17
+ type RemoveProviderResponse,
11
18
  type BibleResponse,
12
19
  type ChapterResponse,
13
20
  type ConfigPatch,
@@ -16,6 +23,7 @@ import {
16
23
  type ForeshadowResponse,
17
24
  type JobFrame,
18
25
  type LoadOutlineResponse,
26
+ type LlmTestResponse,
19
27
  type NovelConfig,
20
28
  type PlanResponse,
21
29
  type ReviewReport,
@@ -232,6 +240,39 @@ export class NovelApi {
232
240
  return postJson<import('../protocol.ts').ImageTestResponse>(NOVEL_API.imageTest, req)
233
241
  }
234
242
 
243
+ /** 对选中的提供商/模型发一次最小真实调用,验证连通性。 */
244
+ async llmTest(provider: string, model: string): Promise<LlmTestResponse> {
245
+ return postJson<LlmTestResponse>(NOVEL_API.llmTest, { provider, model })
246
+ }
247
+
248
+ /** 添加模型:厂商直填 key,或自定义 OpenAI 兼容路由(写 DSH 凭据 + 注册路由)。 */
249
+ async addModel(req: AddModelRequest): Promise<AddModelResponse> {
250
+ return postJson<AddModelResponse>(NOVEL_API.addModel, req)
251
+ }
252
+
253
+ /** 运行时厂商目录(DSH pi-ai 可配置提供方 + 内置适配器)。 */
254
+ async llmVendors(): Promise<LlmVendorsResponse> {
255
+ const response = await fetch(NOVEL_API.llmVendors)
256
+ return readJson<LlmVendorsResponse>(response)
257
+ }
258
+
259
+ /** 查询某个 provider 当前可用的模型(添加成功后可即时刷新)。 */
260
+ async llmModels(provider: string): Promise<LlmModelsResponse> {
261
+ const response = await fetch(NOVEL_API.llmModels + '?provider=' + encodeURIComponent(provider))
262
+ return readJson<LlmModelsResponse>(response)
263
+ }
264
+
265
+ /** 已注册的提供方路由列表(提供方管理卡片)。 */
266
+ async llmProviders(): Promise<LlmProvidersResponse> {
267
+ const response = await fetch(NOVEL_API.llmProviders)
268
+ return readJson<LlmProvidersResponse>(response)
269
+ }
270
+
271
+ /** 移除一个提供方(unset key + 移除 llm-pi-ai 路由)。 */
272
+ async removeProvider(req: RemoveProviderRequest): Promise<RemoveProviderResponse> {
273
+ return postJson<RemoveProviderResponse>(NOVEL_API.llmRemove, req)
274
+ }
275
+
235
276
  async roles(req: import('../protocol.ts').RolesRequest): Promise<import('../protocol.ts').RolesResponse> {
236
277
  return postJson<import('../protocol.ts').RolesResponse>(NOVEL_API.roles, req)
237
278
  }
@@ -461,4 +502,45 @@ export class NovelApi {
461
502
  async assistantClear(): Promise<{ ok: boolean }> {
462
503
  return postJson<{ ok: boolean }>(NOVEL_API.assistantClear, {})
463
504
  }
505
+
506
+ /** 作者资产库/总数据:读取跨书可复用资产。 */
507
+ async authorAssets(): Promise<import('../protocol.ts').AuthorAssetsResponse> {
508
+ const response = await fetch(NOVEL_API.authorAssets)
509
+ return readJson<import('../protocol.ts').AuthorAssetsResponse>(response)
510
+ }
511
+
512
+ /** 作者资产库:新增/更新一条资产(upsert by id)。 */
513
+ async authorAssetsUpsert(asset: import('../protocol.ts').AuthorStyleAsset): Promise<import('../protocol.ts').AuthorAssetsResponse> {
514
+ return postJson<import('../protocol.ts').AuthorAssetsResponse>(NOVEL_API.authorAssetsUpsert, { asset })
515
+ }
516
+
517
+ /** 作者资产库:删除一条资产。 */
518
+ async authorAssetsRemove(id: string): Promise<import('../protocol.ts').AuthorAssetsResponse> {
519
+ return postJson<import('../protocol.ts').AuthorAssetsResponse>(NOVEL_API.authorAssetsRemove, { id })
520
+ }
521
+
522
+ /** 作者资产库:导入默认(书架书的写作资产/角色 + 内置全局库)批量沉淀。 */
523
+ async authorAssetsImportDefault(): Promise<import('../protocol.ts').AuthorAssetsResponse> {
524
+ return postJson<import('../protocol.ts').AuthorAssetsResponse>(NOVEL_API.authorAssetsImportDefault, {})
525
+ }
526
+
527
+ /** 改编模式 P0:上传全文 → 原文设定卡片 / 可改范围矩阵。 */
528
+ async adaptAnalyze(text: string, filePath?: string): Promise<import('../protocol.ts').AdaptAnalyzeResponse> {
529
+ return postJson<import('../protocol.ts').AdaptAnalyzeResponse>(NOVEL_API.adaptAnalyze, { text, filePath })
530
+ }
531
+
532
+ /** 改编模式 P1:确认要改的维度 → 生成映射表/改编规则/联动影响清单。 */
533
+ async adaptPropose(req: import('../protocol.ts').AdaptProposeRequest): Promise<import('../protocol.ts').AdaptProposeResponse> {
534
+ return postJson<import('../protocol.ts').AdaptProposeResponse>(NOVEL_API.adaptPropose, req)
535
+ }
536
+
537
+ /** 改编模式 P2:执行术语替换(全局替换 + 命中统计 + 改编文本预览)。 */
538
+ async adaptExecute(req: import('../protocol.ts').AdaptExecuteRequest): Promise<import('../protocol.ts').AdaptExecuteResponse> {
539
+ return postJson<import('../protocol.ts').AdaptExecuteResponse>(NOVEL_API.adaptExecute, req)
540
+ }
541
+
542
+ /** 主题自定义背景:上传图片,服务端存盘并返回可访问 URL。 */
543
+ async themeBackgroundUpload(dataUrl: string): Promise<{ url: string }> {
544
+ return postJson<{ url: string }>(NOVEL_API.themeBackgroundUpload, { dataUrl })
545
+ }
464
546
  }