server.ts 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948
  1. import { Hono } from "hono";
  2. import { cors } from "hono/cors";
  3. import { streamSSE } from "hono/streaming";
  4. import { serve } from "@hono/node-server";
  5. import {
  6. StateManager,
  7. PipelineRunner,
  8. createLLMClient,
  9. createLogger,
  10. createInteractionToolsFromDeps,
  11. computeAnalytics,
  12. loadProjectConfig,
  13. loadProjectSession,
  14. processProjectInteractionRequest,
  15. resolveSessionActiveBook,
  16. listBookSessions,
  17. loadBookSession,
  18. appendManualSessionMessages,
  19. createAndPersistBookSession,
  20. renameBookSession,
  21. deleteBookSession,
  22. migrateBookSession,
  23. SessionAlreadyMigratedError,
  24. runAgentSession,
  25. buildAgentSystemPrompt,
  26. resolveServicePreset,
  27. resolveServiceProviderFamily,
  28. resolveServiceModelsBaseUrl,
  29. resolveServiceModel,
  30. loadSecrets,
  31. saveSecrets,
  32. listModelsForService,
  33. getAllEndpoints,
  34. probeModelsFromUpstream,
  35. fetchWithProxy,
  36. chatCompletion,
  37. buildExportArtifact,
  38. GLOBAL_ENV_PATH,
  39. type ResolvedModel,
  40. type PipelineConfig,
  41. type ProjectConfig,
  42. type LogSink,
  43. type LogEntry,
  44. } from "@actalk/inkos-core";
  45. import { access, readFile, readdir, writeFile } from "node:fs/promises";
  46. import { isAbsolute, join, relative, resolve } from "node:path";
  47. import { isSafeBookId } from "./safety.js";
  48. import { ApiError } from "./errors.js";
  49. import { buildStudioBookConfig } from "./book-create.js";
  50. // -- Pipeline stage definitions per agent type --
  51. const PIPELINE_STAGES: Record<string, string[]> = {
  52. writer: [
  53. "准备章节输入", "撰写章节草稿", "落盘最终章节",
  54. "生成最终真相文件", "校验真相文件变更", "同步记忆索引",
  55. "更新章节索引与快照",
  56. ],
  57. architect: [
  58. "生成基础设定", "保存书籍配置", "写入基础设定文件",
  59. "初始化控制文档", "创建初始快照",
  60. ],
  61. reviser: [
  62. "加载修订上下文", "修订章节", "落盘修订结果",
  63. "更新索引与快照",
  64. ],
  65. auditor: ["审计章节"],
  66. };
  67. const AGENT_LABELS: Record<string, string> = {
  68. architect: "建书", writer: "写作", auditor: "审计",
  69. reviser: "修订", exporter: "导出",
  70. };
  71. const TOOL_LABELS: Record<string, string> = {
  72. read: "读取文件", edit: "编辑文件", grep: "搜索", ls: "列目录",
  73. };
  74. function resolveToolLabel(tool: string, agent?: string): string {
  75. if (tool === "sub_agent" && agent) return AGENT_LABELS[agent] ?? agent;
  76. return TOOL_LABELS[tool] ?? tool;
  77. }
  78. function summarizeResult(result: unknown): string {
  79. if (typeof result === "string") return result.slice(0, 200);
  80. if (result && typeof result === "object") {
  81. const r = result as Record<string, unknown>;
  82. if (typeof r.content === "string") return r.content.slice(0, 200);
  83. if (typeof r.text === "string") return r.text.slice(0, 200);
  84. }
  85. return String(result).slice(0, 200);
  86. }
  87. const NON_TEXT_MODEL_ID_PARTS = [
  88. "image",
  89. "embedding",
  90. "embed",
  91. "rerank",
  92. "tts",
  93. "speech",
  94. "audio",
  95. "moderation",
  96. ] as const;
  97. function isTextChatModelId(modelId: string): boolean {
  98. const normalized = modelId.trim().toLowerCase();
  99. if (!normalized) return false;
  100. return !NON_TEXT_MODEL_ID_PARTS.some((part) => normalized.includes(part));
  101. }
  102. function filterTextChatModels<T extends { readonly id: string }>(models: ReadonlyArray<T>): T[] {
  103. return models.filter((model) => isTextChatModelId(model.id));
  104. }
  105. function normalizeApiBookId(value: unknown, fieldName: string): string | null {
  106. if (value === undefined || value === null) return null;
  107. if (typeof value !== "string") {
  108. throw new ApiError(400, "INVALID_BOOK_ID", `${fieldName} must be a string`);
  109. }
  110. const bookId = value.trim();
  111. if (!bookId) {
  112. throw new ApiError(400, "INVALID_BOOK_ID", `${fieldName} cannot be blank`);
  113. }
  114. if (!isSafeBookId(bookId)) {
  115. throw new ApiError(400, "INVALID_BOOK_ID", `Invalid ${fieldName}: "${bookId}"`);
  116. }
  117. return bookId;
  118. }
  119. function nonTextModelMessage(modelId: string): string {
  120. return `模型 ${modelId} 不适合文本聊天/写作。请在模型选择器中改用文本模型,例如 gemini-2.5-flash、gemini-2.5-pro 或对应服务的 chat 模型。`;
  121. }
  122. function extractToolError(result: unknown): string {
  123. if (typeof result === "string") return result.slice(0, 500);
  124. if (result && typeof result === "object") {
  125. const r = result as Record<string, unknown>;
  126. if (typeof r.content === "string") return r.content.slice(0, 500);
  127. if (r.content && Array.isArray(r.content)) {
  128. const textPart = r.content.find((c: any) => c.type === "text");
  129. if (textPart) return (textPart as any).text?.slice(0, 500) ?? "";
  130. }
  131. }
  132. return String(result).slice(0, 500);
  133. }
  134. function isLikelyFailedToolResult(exec: CollectedToolExec): boolean {
  135. if (exec.status === "error") return true;
  136. const text = `${exec.error ?? ""}\n${exec.result ?? ""}`.toLowerCase();
  137. return /\bfailed\b|\berror\b|失败|异常|出错/.test(text);
  138. }
  139. function hasSuccessfulSubAgentExec(
  140. execs: ReadonlyArray<CollectedToolExec>,
  141. agent: string,
  142. ): boolean {
  143. return execs.some((exec) =>
  144. exec.tool === "sub_agent"
  145. && exec.agent === agent
  146. && exec.status === "completed"
  147. && !isLikelyFailedToolResult(exec)
  148. );
  149. }
  150. function isWriteNextInstruction(instruction: string): boolean {
  151. const trimmed = instruction.trim();
  152. return /^(continue|继续|继续写|写下一章|write next|下一章|再来一章)$/i.test(trimmed)
  153. || /(继续写|写下一章|下一章|再来一章|write\s+next)/i.test(trimmed);
  154. }
  155. function looksLikeBookCreatedClaim(responseText: string): boolean {
  156. return /(?:已|已经|成功).{0,12}(?:创建|建书|初始化|保存).{0,12}(?:作品|书|书籍|文件夹)?/.test(responseText)
  157. || /\b(?:created|initiali[sz]ed|saved)\b.{0,40}\b(?:book|project|novel)\b/i.test(responseText);
  158. }
  159. function validateAgentActionExecution(args: {
  160. readonly instruction: string;
  161. readonly agentBookId: string | null | undefined;
  162. readonly responseText: string;
  163. readonly collectedToolExecs: ReadonlyArray<CollectedToolExec>;
  164. }): string | undefined {
  165. const failedExec = args.collectedToolExecs.find(isLikelyFailedToolResult);
  166. if (failedExec) {
  167. return `${failedExec.label} 执行失败:${failedExec.error ?? failedExec.result ?? "未知错误"}`;
  168. }
  169. if (
  170. args.agentBookId
  171. && isWriteNextInstruction(args.instruction)
  172. && !hasSuccessfulSubAgentExec(args.collectedToolExecs, "writer")
  173. ) {
  174. return "模型声称已完成下一章,但没有实际调用写作工具。请重试;如果仍失败,请检查模型是否支持工具调用。";
  175. }
  176. if (
  177. !args.agentBookId
  178. && looksLikeBookCreatedClaim(args.responseText)
  179. && !resolveCreatedBookIdFromToolExecs(args.collectedToolExecs)
  180. ) {
  181. return "模型声称已创建作品,但没有实际调用建书工具,也没有生成作品文件。请补充书名/题材后重试,或换用支持工具调用的模型。";
  182. }
  183. return undefined;
  184. }
  185. interface CollectedToolExec {
  186. id: string;
  187. tool: string;
  188. agent?: string;
  189. label: string;
  190. status: "running" | "completed" | "error";
  191. args?: Record<string, unknown>;
  192. result?: string;
  193. details?: unknown;
  194. error?: string;
  195. stages?: Array<{ label: string; status: "pending" | "completed" }>;
  196. startedAt: number;
  197. completedAt?: number;
  198. }
  199. interface StudioBookListSummary {
  200. readonly id: string;
  201. readonly title: string;
  202. readonly genre: string;
  203. readonly status: string;
  204. readonly chaptersWritten: number;
  205. readonly [key: string]: unknown;
  206. }
  207. // --- Event bus for SSE ---
  208. type EventHandler = (event: string, data: unknown) => void;
  209. const subscribers = new Set<EventHandler>();
  210. const bookCreateStatus = new Map<string, { status: "creating" | "error"; error?: string }>();
  211. // 内存缓存:service -> 模型列表 + 更新时间戳;避免每次 sidebar 挂载时都打真实 LLM /models
  212. const modelListCache = new Map<string, { models: Array<{ id: string; name: string }>; at: number }>();
  213. interface ServiceConfigEntry {
  214. service: string;
  215. name?: string;
  216. baseUrl?: string;
  217. temperature?: number;
  218. apiFormat?: "chat" | "responses";
  219. stream?: boolean;
  220. }
  221. type LLMConfigSource = "env" | "studio";
  222. interface EnvConfigSummary {
  223. detected: boolean;
  224. provider: string | null;
  225. baseUrl: string | null;
  226. model: string | null;
  227. hasApiKey: boolean;
  228. }
  229. interface EnvConfigStatus {
  230. project: EnvConfigSummary;
  231. global: EnvConfigSummary;
  232. effectiveSource: "project" | "global" | null;
  233. runtimeUsesEnv: false;
  234. }
  235. interface ServiceProbeResult {
  236. ok: boolean;
  237. models: Array<{ id: string; name: string }>;
  238. selectedModel?: string;
  239. apiFormat?: "chat" | "responses";
  240. stream?: boolean;
  241. baseUrl?: string;
  242. modelsSource?: "api" | "fallback";
  243. error?: string;
  244. }
  245. function broadcast(event: string, data: unknown): void {
  246. for (const handler of subscribers) {
  247. handler(event, data);
  248. }
  249. }
  250. function deriveBookIdFromTitle(title: string): string {
  251. return title
  252. .trim()
  253. .toLowerCase()
  254. .replace(/[^a-z0-9\u4e00-\u9fff]/g, "-")
  255. .replace(/-+/g, "-")
  256. .replace(/^-+|-+$/g, "")
  257. .slice(0, 30);
  258. }
  259. function resolveArchitectBookIdFromArgs(args?: Record<string, unknown>): string | null {
  260. if (!args || args.agent !== "architect" || args.revise === true) return null;
  261. if (typeof args.bookId === "string" && args.bookId.trim()) return args.bookId.trim();
  262. if (typeof args.title === "string" && args.title.trim()) {
  263. return deriveBookIdFromTitle(args.title) || null;
  264. }
  265. return null;
  266. }
  267. function resolveCreatedBookIdFromToolExecs(execs: ReadonlyArray<CollectedToolExec>): string | null {
  268. for (let i = execs.length - 1; i >= 0; i -= 1) {
  269. const exec = execs[i];
  270. if (exec.tool !== "sub_agent" || exec.agent !== "architect" || exec.status !== "completed") continue;
  271. const details = exec.details as { kind?: unknown; bookId?: unknown } | undefined;
  272. if (details?.kind === "book_created" && typeof details.bookId === "string" && details.bookId.trim()) {
  273. return details.bookId.trim();
  274. }
  275. const fromArgs = resolveArchitectBookIdFromArgs(exec.args);
  276. if (fromArgs) return fromArgs;
  277. }
  278. return null;
  279. }
  280. async function loadStudioBookListSummary(
  281. state: StateManager,
  282. bookId: string,
  283. ): Promise<StudioBookListSummary> {
  284. const book = await state.loadBookConfig(bookId);
  285. const nextChapter = await state.getNextChapterNumber(bookId);
  286. return { ...book, chaptersWritten: nextChapter - 1 };
  287. }
  288. function isCustomServiceId(serviceId: string): boolean {
  289. return serviceId === "custom" || serviceId.startsWith("custom:");
  290. }
  291. function serviceConfigKey(entry: ServiceConfigEntry): string {
  292. return entry.service === "custom" ? `custom:${entry.name ?? "Custom"}` : entry.service;
  293. }
  294. function normalizeServiceEntry(serviceId: string, value: Record<string, unknown>): ServiceConfigEntry {
  295. if (serviceId.startsWith("custom:")) {
  296. return {
  297. service: "custom",
  298. name: decodeURIComponent(serviceId.slice("custom:".length)),
  299. ...(typeof value.baseUrl === "string" && value.baseUrl.length > 0 ? { baseUrl: value.baseUrl } : {}),
  300. ...(typeof value.temperature === "number" ? { temperature: value.temperature } : {}),
  301. ...(value.apiFormat === "chat" || value.apiFormat === "responses" ? { apiFormat: value.apiFormat } : {}),
  302. ...(typeof value.stream === "boolean" ? { stream: value.stream } : {}),
  303. };
  304. }
  305. if (serviceId === "custom") {
  306. return {
  307. service: "custom",
  308. ...(typeof value.name === "string" && value.name.length > 0 ? { name: value.name } : {}),
  309. ...(typeof value.baseUrl === "string" && value.baseUrl.length > 0 ? { baseUrl: value.baseUrl } : {}),
  310. ...(typeof value.temperature === "number" ? { temperature: value.temperature } : {}),
  311. ...(value.apiFormat === "chat" || value.apiFormat === "responses" ? { apiFormat: value.apiFormat } : {}),
  312. ...(typeof value.stream === "boolean" ? { stream: value.stream } : {}),
  313. };
  314. }
  315. return {
  316. service: serviceId,
  317. ...(typeof value.temperature === "number" ? { temperature: value.temperature } : {}),
  318. ...(value.apiFormat === "chat" || value.apiFormat === "responses" ? { apiFormat: value.apiFormat } : {}),
  319. ...(typeof value.stream === "boolean" ? { stream: value.stream } : {}),
  320. };
  321. }
  322. function normalizeConfigSource(value: unknown): LLMConfigSource {
  323. return value === "studio" ? "studio" : "env";
  324. }
  325. function normalizeServiceConfig(raw: unknown): ServiceConfigEntry[] {
  326. if (Array.isArray(raw)) {
  327. return raw
  328. .filter((entry): entry is Record<string, unknown> => Boolean(entry) && typeof entry === "object")
  329. .map((entry) => ({
  330. service: typeof entry.service === "string" && entry.service.length > 0 ? entry.service : "custom",
  331. ...(typeof entry.name === "string" && entry.name.length > 0 ? { name: entry.name } : {}),
  332. ...(typeof entry.baseUrl === "string" && entry.baseUrl.length > 0 ? { baseUrl: entry.baseUrl } : {}),
  333. ...(typeof entry.temperature === "number" ? { temperature: entry.temperature } : {}),
  334. ...(entry.apiFormat === "chat" || entry.apiFormat === "responses" ? { apiFormat: entry.apiFormat } : {}),
  335. ...(typeof entry.stream === "boolean" ? { stream: entry.stream } : {}),
  336. }));
  337. }
  338. if (raw && typeof raw === "object") {
  339. return Object.entries(raw as Record<string, unknown>)
  340. .filter(([, value]) => value && typeof value === "object")
  341. .map(([serviceId, value]) => normalizeServiceEntry(serviceId, value as Record<string, unknown>));
  342. }
  343. return [];
  344. }
  345. function mergeServiceConfig(existing: ServiceConfigEntry[], updates: ServiceConfigEntry[]): ServiceConfigEntry[] {
  346. const merged = new Map(existing.map((entry) => [serviceConfigKey(entry), entry]));
  347. for (const update of updates) {
  348. merged.set(serviceConfigKey(update), update);
  349. }
  350. return [...merged.values()];
  351. }
  352. async function loadRawConfig(root: string): Promise<Record<string, unknown>> {
  353. const configPath = join(root, "inkos.json");
  354. const raw = await readFile(configPath, "utf-8");
  355. return JSON.parse(raw) as Record<string, unknown>;
  356. }
  357. async function saveRawConfig(root: string, config: Record<string, unknown>): Promise<void> {
  358. await writeFile(join(root, "inkos.json"), JSON.stringify(config, null, 2), "utf-8");
  359. }
  360. async function readEnvConfigSummary(path: string): Promise<EnvConfigSummary> {
  361. try {
  362. const raw = await readFile(path, "utf-8");
  363. const values = new Map<string, string>();
  364. for (const line of raw.split(/\r?\n/)) {
  365. const trimmed = line.trim();
  366. if (!trimmed || trimmed.startsWith("#")) continue;
  367. const match = trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
  368. if (!match) continue;
  369. const [, key, value] = match;
  370. values.set(key, value.trim());
  371. }
  372. const provider = values.get("INKOS_LLM_PROVIDER") ?? null;
  373. const baseUrl = values.get("INKOS_LLM_BASE_URL") ?? null;
  374. const model = values.get("INKOS_LLM_MODEL") ?? null;
  375. const apiKey = values.get("INKOS_LLM_API_KEY") ?? "";
  376. const detected = Boolean(provider || baseUrl || model || apiKey);
  377. return {
  378. detected,
  379. provider,
  380. baseUrl,
  381. model,
  382. hasApiKey: apiKey.length > 0,
  383. };
  384. } catch {
  385. return {
  386. detected: false,
  387. provider: null,
  388. baseUrl: null,
  389. model: null,
  390. hasApiKey: false,
  391. };
  392. }
  393. }
  394. async function readEnvConfigStatus(root: string): Promise<EnvConfigStatus> {
  395. const project = await readEnvConfigSummary(join(root, ".env"));
  396. const global = await readEnvConfigSummary(GLOBAL_ENV_PATH);
  397. return {
  398. project,
  399. global,
  400. effectiveSource: project.detected ? "project" : global.detected ? "global" : null,
  401. runtimeUsesEnv: false,
  402. };
  403. }
  404. async function resolveConfiguredServiceBaseUrl(root: string, serviceId: string, inlineBaseUrl?: string): Promise<string | undefined> {
  405. if (inlineBaseUrl?.trim()) return inlineBaseUrl.trim();
  406. if (!isCustomServiceId(serviceId)) {
  407. return resolveServicePreset(serviceId)?.baseUrl;
  408. }
  409. try {
  410. const config = await loadRawConfig(root);
  411. const services = normalizeServiceConfig((config.llm as Record<string, unknown> | undefined)?.services);
  412. const matched = services.find((entry) => serviceConfigKey(entry) === serviceId);
  413. return matched?.baseUrl;
  414. } catch {
  415. return undefined;
  416. }
  417. }
  418. async function resolveConfiguredServiceEntry(root: string, serviceId: string): Promise<ServiceConfigEntry | undefined> {
  419. try {
  420. const config = await loadRawConfig(root);
  421. const services = normalizeServiceConfig((config.llm as Record<string, unknown> | undefined)?.services);
  422. return services.find((entry) => serviceConfigKey(entry) === serviceId);
  423. } catch {
  424. return undefined;
  425. }
  426. }
  427. function buildProbePlans(
  428. preferredApiFormat: "chat" | "responses" | undefined,
  429. preferredStream: boolean | undefined,
  430. ): Array<{ apiFormat: "chat" | "responses"; stream: boolean }> {
  431. const candidates: Array<{ apiFormat: "chat" | "responses"; stream: boolean }> = [];
  432. const seen = new Set<string>();
  433. const push = (apiFormat: "chat" | "responses", stream: boolean) => {
  434. const key = `${apiFormat}:${stream ? "1" : "0"}`;
  435. if (seen.has(key)) return;
  436. seen.add(key);
  437. candidates.push({ apiFormat, stream });
  438. };
  439. if (preferredApiFormat) {
  440. push(preferredApiFormat, preferredStream ?? false);
  441. push(preferredApiFormat, !(preferredStream ?? false));
  442. }
  443. const alternate = preferredApiFormat === "responses" ? "chat" : "responses";
  444. push(alternate, false);
  445. push(alternate, true);
  446. push("chat", false);
  447. push("chat", true);
  448. push("responses", false);
  449. push("responses", true);
  450. return candidates;
  451. }
  452. function buildModelCandidates(args: {
  453. preferredModel?: string;
  454. configModel?: string;
  455. envModel?: string | null;
  456. discoveredModels: Array<{ id: string; name: string }>;
  457. includeGenericFallbacks?: boolean;
  458. }): string[] {
  459. const seen = new Set<string>();
  460. const candidates: string[] = [];
  461. const push = (value: string | null | undefined) => {
  462. if (!value || value.trim().length === 0) return;
  463. const id = value.trim();
  464. if (seen.has(id)) return;
  465. seen.add(id);
  466. candidates.push(id);
  467. };
  468. push(args.preferredModel);
  469. push(args.configModel);
  470. push(args.envModel ?? undefined);
  471. for (const model of args.discoveredModels) push(model.id);
  472. if (args.includeGenericFallbacks === false) return candidates;
  473. push("gpt-5.4");
  474. push("gpt-4o");
  475. push("claude-sonnet-4-6");
  476. push("MiniMax-M2.7");
  477. push("kimi-k2.5");
  478. return candidates;
  479. }
  480. function formatServiceProbeError(args: {
  481. readonly service: string;
  482. readonly label?: string;
  483. readonly baseUrl: string;
  484. readonly model?: string;
  485. readonly apiFormat?: "chat" | "responses";
  486. readonly stream?: boolean;
  487. readonly error: string;
  488. }): string {
  489. const rawDetail = args.error
  490. .replace(/\n\s*\(baseUrl:[\s\S]*?\)$/m, "")
  491. .trim();
  492. const upstreamDetail = rawDetail.includes("上游详情:")
  493. ? rawDetail
  494. : "";
  495. const context = [
  496. `服务商:${args.label ?? args.service}`,
  497. `测试模型:${args.model ?? "未确定"}`,
  498. `协议:${args.apiFormat === "responses" ? "Responses" : "Chat / Completions"}${typeof args.stream === "boolean" ? `,${args.stream ? "流式" : "非流式"}` : ""}`,
  499. `Base URL:${args.baseUrl}`,
  500. ].join("\n");
  501. if (args.service === "google") {
  502. return [
  503. "Google Gemini 测试连接失败。",
  504. context,
  505. "",
  506. "请优先检查:",
  507. "1. API Key 是否来自 Google AI Studio 的 Gemini API key,而不是 OAuth、Vertex AI 或其它 Google 服务凭据。",
  508. "2. 该 key 所属项目是否已启用 Gemini API,并且没有被限制到其它 API、来源或服务。",
  509. "3. 当前地区/账号是否允许访问 Gemini API。",
  510. "4. 如果 key 曾经泄露,请在 AI Studio 重新生成后再保存。",
  511. upstreamDetail ? `\n上游返回:${upstreamDetail}` : "",
  512. ].filter(Boolean).join("\n");
  513. }
  514. if (args.service === "moonshot" || args.service === "kimiCodingPlan") {
  515. return [
  516. `${args.label ?? args.service} 测试连接失败。`,
  517. context,
  518. "",
  519. "请优先检查模型是否可用,以及 kimi-k2.x 这类模型是否需要 temperature=1。",
  520. rawDetail ? `\n上游返回:${rawDetail}` : "",
  521. ].filter(Boolean).join("\n");
  522. }
  523. return [
  524. `${args.label ?? args.service} 测试连接失败。`,
  525. context,
  526. "",
  527. "请检查 API Key、模型可用性、账号额度,以及协议类型是否匹配该服务商。",
  528. rawDetail ? `\n上游返回:${rawDetail}` : "",
  529. ].filter(Boolean).join("\n");
  530. }
  531. async function fetchModelsFromServiceBaseUrl(
  532. serviceId: string,
  533. baseUrl: string,
  534. apiKey: string,
  535. proxyUrl?: string,
  536. ): Promise<{ models: Array<{ id: string; name: string }>; error?: string; authFailed?: boolean }> {
  537. const endpoint = isCustomServiceId(serviceId)
  538. ? undefined
  539. : getAllEndpoints().find((ep) => ep.id === serviceId);
  540. const modelsBaseUrl = isCustomServiceId(serviceId)
  541. ? baseUrl
  542. : endpoint?.modelsBaseUrl ?? (endpoint ? baseUrl : resolveServiceModelsBaseUrl(serviceId) ?? baseUrl);
  543. const modelsUrl = modelsBaseUrl.replace(/\/$/, "") + "/models";
  544. try {
  545. const res = await fetchWithProxy(modelsUrl, {
  546. headers: { Authorization: `Bearer ${apiKey}` },
  547. signal: AbortSignal.timeout(10_000),
  548. }, proxyUrl);
  549. if (!res.ok) {
  550. const body = await res.text().catch(() => "");
  551. return {
  552. models: [],
  553. error: `服务商返回 ${res.status}: ${body.slice(0, 200)}`,
  554. authFailed: res.status === 401 || res.status === 403,
  555. };
  556. }
  557. const json = await res.json() as { data?: Array<{ id: string }> };
  558. return {
  559. models: (json.data ?? []).map((m) => ({ id: m.id, name: m.id })),
  560. };
  561. } catch (error) {
  562. return {
  563. models: [],
  564. error: error instanceof Error ? error.message : String(error),
  565. };
  566. }
  567. }
  568. async function probeServiceCapabilities(args: {
  569. root: string;
  570. service: string;
  571. apiKey: string;
  572. baseUrl: string;
  573. preferredApiFormat?: "chat" | "responses";
  574. preferredStream?: boolean;
  575. preferredModel?: string;
  576. proxyUrl?: string;
  577. }): Promise<ServiceProbeResult> {
  578. const rawConfig = await loadRawConfig(args.root).catch(() => ({} as Record<string, unknown>));
  579. const llm = (rawConfig.llm as Record<string, unknown> | undefined) ?? {};
  580. const envConfig = await readEnvConfigStatus(args.root);
  581. const envModel = envConfig.effectiveSource === "project"
  582. ? envConfig.project.model
  583. : envConfig.effectiveSource === "global"
  584. ? envConfig.global.model
  585. : null;
  586. const baseService = isCustomServiceId(args.service) ? "custom" : args.service;
  587. const modelsResponse = await fetchModelsFromServiceBaseUrl(baseService, args.baseUrl, args.apiKey, args.proxyUrl);
  588. if (modelsResponse.authFailed) {
  589. return {
  590. ok: false,
  591. models: [],
  592. error: modelsResponse.error ?? "API Key 无效或无权访问模型列表。",
  593. };
  594. }
  595. const discoveredModels = modelsResponse.models;
  596. // For bank services, probe with the service's own check model first — not the global default.
  597. const endpoint = getAllEndpoints().find((ep) => ep.id === baseService);
  598. const preset = resolveServicePreset(baseService);
  599. const serviceFirstModel =
  600. endpoint?.checkModel
  601. ?? preset?.knownModels?.[0]
  602. ?? endpoint?.models.find((model) => model.enabled !== false)?.id;
  603. const useEndpointCheckModel = !isCustomServiceId(args.service) && Boolean(endpoint?.checkModel);
  604. const configService = typeof llm.service === "string" ? llm.service : undefined;
  605. const configModel = !useEndpointCheckModel && configService === args.service
  606. ? typeof llm.defaultModel === "string"
  607. ? llm.defaultModel
  608. : typeof llm.model === "string"
  609. ? llm.model
  610. : undefined
  611. : undefined;
  612. const useCustomFallbacks = isCustomServiceId(args.service);
  613. const modelCandidates = buildModelCandidates({
  614. preferredModel: args.preferredModel ?? serviceFirstModel,
  615. configModel,
  616. envModel: useCustomFallbacks ? envModel : undefined,
  617. discoveredModels: useEndpointCheckModel ? [] : discoveredModels,
  618. includeGenericFallbacks: useCustomFallbacks,
  619. });
  620. if (modelCandidates.length === 0) {
  621. return {
  622. ok: false,
  623. models: [],
  624. error: "无法自动确定模型,请先填写可用模型或提供支持 /models 的服务端点。",
  625. };
  626. }
  627. let lastError = modelsResponse.error ?? "自动探测失败";
  628. for (const model of modelCandidates) {
  629. for (const plan of buildProbePlans(args.preferredApiFormat, args.preferredStream)) {
  630. const client = createLLMClient({
  631. provider: resolveServiceProviderFamily(baseService) ?? "openai",
  632. service: baseService,
  633. configSource: "studio",
  634. baseUrl: args.baseUrl,
  635. apiKey: args.apiKey.trim(),
  636. model,
  637. temperature: 0.7,
  638. maxTokens: 2048,
  639. thinkingBudget: 0,
  640. proxyUrl: args.proxyUrl,
  641. apiFormat: plan.apiFormat,
  642. stream: plan.stream,
  643. } as ProjectConfig["llm"]);
  644. try {
  645. await chatCompletion(client, model, [{ role: "user", content: "ping" }], { maxTokens: 2048 });
  646. const models = discoveredModels.length > 0
  647. ? discoveredModels
  648. : endpoint?.models
  649. .filter((m) => m.enabled !== false)
  650. .filter((m) => isTextChatModelId(m.id))
  651. .map((m) => ({ id: m.id, name: m.id }))
  652. ?? preset?.knownModels?.map((id) => ({ id, name: id }))
  653. ?? [{ id: model, name: model }];
  654. return {
  655. ok: true,
  656. models,
  657. selectedModel: model,
  658. apiFormat: plan.apiFormat,
  659. stream: plan.stream,
  660. baseUrl: args.baseUrl,
  661. modelsSource: discoveredModels.length > 0 ? "api" : "fallback",
  662. };
  663. } catch (error) {
  664. lastError = formatServiceProbeError({
  665. service: baseService,
  666. label: endpoint?.label ?? preset?.label,
  667. baseUrl: args.baseUrl,
  668. model,
  669. apiFormat: plan.apiFormat,
  670. stream: plan.stream,
  671. error: error instanceof Error ? error.message : String(error),
  672. });
  673. }
  674. }
  675. }
  676. return {
  677. ok: false,
  678. models: discoveredModels,
  679. error: lastError,
  680. };
  681. }
  682. // --- Server factory ---
  683. export function createStudioServer(initialConfig: ProjectConfig, root: string) {
  684. const app = new Hono();
  685. const state = new StateManager(root);
  686. let cachedConfig = initialConfig;
  687. app.use("/*", cors());
  688. // Structured error handler — ApiError returns typed JSON, others return 500
  689. app.onError((error, c) => {
  690. if (error instanceof ApiError) {
  691. return c.json({ error: { code: error.code, message: error.message } }, error.status as 400);
  692. }
  693. return c.json(
  694. { error: { code: "INTERNAL_ERROR", message: "Unexpected server error." } },
  695. 500,
  696. );
  697. });
  698. // BookId validation middleware — blocks path traversal on all book routes
  699. app.use("/api/v1/books/:id/*", async (c, next) => {
  700. const bookId = c.req.param("id");
  701. if (!isSafeBookId(bookId)) {
  702. throw new ApiError(400, "INVALID_BOOK_ID", `Invalid book ID: "${bookId}"`);
  703. }
  704. await next();
  705. });
  706. app.use("/api/v1/books/:id", async (c, next) => {
  707. const bookId = c.req.param("id");
  708. if (!isSafeBookId(bookId)) {
  709. throw new ApiError(400, "INVALID_BOOK_ID", `Invalid book ID: "${bookId}"`);
  710. }
  711. await next();
  712. });
  713. // Logger sink that broadcasts to SSE
  714. const sseSink: LogSink = {
  715. write(entry: LogEntry): void {
  716. broadcast("log", { level: entry.level, tag: entry.tag, message: entry.message });
  717. },
  718. };
  719. // Logger sink that prints to server terminal
  720. const consoleSink: LogSink = {
  721. write(entry: LogEntry): void {
  722. const prefix = `[${entry.tag}]`;
  723. if (entry.level === "warn") console.warn(prefix, entry.message);
  724. else if (entry.level === "error") console.error(prefix, entry.message);
  725. else console.log(prefix, entry.message);
  726. },
  727. };
  728. async function loadCurrentProjectConfig(
  729. options?: { readonly requireApiKey?: boolean },
  730. ): Promise<ProjectConfig> {
  731. const freshConfig = await loadProjectConfig(root, { ...options, consumer: "studio" });
  732. cachedConfig = freshConfig;
  733. return freshConfig;
  734. }
  735. async function buildPipelineConfig(
  736. overrides?: Partial<Pick<PipelineConfig, "externalContext" | "client" | "model">> & {
  737. readonly currentConfig?: ProjectConfig;
  738. readonly sessionIdForSSE?: string;
  739. },
  740. ): Promise<PipelineConfig> {
  741. const currentConfig = overrides?.currentConfig ?? await loadCurrentProjectConfig();
  742. const scopedSseSink: LogSink = overrides?.sessionIdForSSE
  743. ? {
  744. write(entry) {
  745. broadcast("log", {
  746. sessionId: overrides.sessionIdForSSE,
  747. level: entry.level,
  748. tag: entry.tag,
  749. message: entry.message,
  750. });
  751. },
  752. }
  753. : sseSink;
  754. const logger = createLogger({ tag: "studio", sinks: [scopedSseSink, consoleSink] });
  755. return {
  756. client: overrides?.client ?? createLLMClient(currentConfig.llm),
  757. model: overrides?.model ?? currentConfig.llm.model,
  758. projectRoot: root,
  759. defaultLLMConfig: currentConfig.llm,
  760. foundationReviewRetries: currentConfig.foundation?.reviewRetries ?? 2,
  761. modelOverrides: currentConfig.modelOverrides,
  762. notifyChannels: currentConfig.notify,
  763. logger,
  764. onStreamProgress: (progress) => {
  765. broadcast("llm:progress", {
  766. ...(overrides?.sessionIdForSSE ? { sessionId: overrides.sessionIdForSSE } : {}),
  767. status: progress.status,
  768. elapsedMs: progress.elapsedMs,
  769. totalChars: progress.totalChars,
  770. chineseChars: progress.chineseChars,
  771. });
  772. },
  773. externalContext: overrides?.externalContext,
  774. };
  775. }
  776. // --- Books ---
  777. app.get("/api/v1/books", async (c) => {
  778. const bookIds = await state.listBooks();
  779. const books = await Promise.all(bookIds.map((id) => loadStudioBookListSummary(state, id)));
  780. return c.json({ books });
  781. });
  782. app.get("/api/v1/books/:id", async (c) => {
  783. const id = c.req.param("id");
  784. try {
  785. const book = await state.loadBookConfig(id);
  786. const chapters = await state.loadChapterIndex(id);
  787. const nextChapter = await state.getNextChapterNumber(id);
  788. return c.json({ book, chapters, nextChapter });
  789. } catch {
  790. return c.json({ error: `Book "${id}" not found` }, 404);
  791. }
  792. });
  793. // --- Genres ---
  794. app.get("/api/v1/genres", async (c) => {
  795. const { listAvailableGenres, readGenreProfile } = await import("@actalk/inkos-core");
  796. const rawGenres = await listAvailableGenres(root);
  797. const genres = await Promise.all(
  798. rawGenres.map(async (g) => {
  799. try {
  800. const { profile } = await readGenreProfile(root, g.id);
  801. return { ...g, language: profile.language ?? "zh" };
  802. } catch {
  803. return { ...g, language: "zh" };
  804. }
  805. }),
  806. );
  807. return c.json({ genres });
  808. });
  809. // --- Book Create ---
  810. app.post("/api/v1/books/create", async (c) => {
  811. const body = await c.req.json<{
  812. title: string;
  813. genre: string;
  814. language?: string;
  815. platform?: string;
  816. chapterWordCount?: number;
  817. targetChapters?: number;
  818. }>();
  819. const now = new Date().toISOString();
  820. const bookConfig = buildStudioBookConfig(body, now);
  821. const bookId = bookConfig.id;
  822. const bookDir = state.bookDir(bookId);
  823. try {
  824. await access(join(bookDir, "book.json"));
  825. await access(join(bookDir, "story", "story_bible.md"));
  826. return c.json({ error: `Book "${bookId}" already exists` }, 409);
  827. } catch {
  828. // The target book is not fully initialized yet, so creation can continue.
  829. }
  830. broadcast("book:creating", { bookId, title: body.title });
  831. bookCreateStatus.set(bookId, { status: "creating" });
  832. const pipeline = new PipelineRunner(await buildPipelineConfig());
  833. const tools = createInteractionToolsFromDeps(pipeline, state);
  834. processProjectInteractionRequest({
  835. projectRoot: root,
  836. request: {
  837. intent: "create_book",
  838. title: body.title,
  839. genre: body.genre,
  840. language: body.language === "en" ? "en" : body.language === "zh" ? "zh" : undefined,
  841. platform: body.platform,
  842. chapterWordCount: body.chapterWordCount,
  843. targetChapters: body.targetChapters,
  844. },
  845. tools,
  846. }).then(
  847. async (result: {
  848. readonly session: { readonly activeBookId?: string };
  849. readonly details?: Readonly<Record<string, unknown>>;
  850. }) => {
  851. const createdBookId = (result.details?.bookId as string | undefined) ?? result.session.activeBookId ?? bookId;
  852. const book = await loadStudioBookListSummary(state, createdBookId).catch(() => undefined);
  853. bookCreateStatus.delete(createdBookId);
  854. broadcast("book:created", { bookId: createdBookId, ...(book ? { book } : {}) });
  855. },
  856. (e: unknown) => {
  857. const error = e instanceof Error ? e.message : String(e);
  858. bookCreateStatus.set(bookId, { status: "error", error });
  859. broadcast("book:error", { bookId, error });
  860. },
  861. );
  862. return c.json({ status: "creating", bookId });
  863. });
  864. app.get("/api/v1/books/:id/create-status", async (c) => {
  865. const id = c.req.param("id");
  866. const status = bookCreateStatus.get(id);
  867. if (!status) {
  868. return c.json({ status: "missing" }, 404);
  869. }
  870. return c.json(status);
  871. });
  872. // --- Chapters ---
  873. app.get("/api/v1/books/:id/chapters/:num", async (c) => {
  874. const id = c.req.param("id");
  875. const num = parseInt(c.req.param("num"), 10);
  876. const bookDir = state.bookDir(id);
  877. const chaptersDir = join(bookDir, "chapters");
  878. try {
  879. const files = await readdir(chaptersDir);
  880. const paddedNum = String(num).padStart(4, "0");
  881. const match = files.find((f) => f.startsWith(paddedNum) && f.endsWith(".md"));
  882. if (!match) return c.json({ error: "Chapter not found" }, 404);
  883. const content = await readFile(join(chaptersDir, match), "utf-8");
  884. return c.json({ chapterNumber: num, filename: match, content });
  885. } catch {
  886. return c.json({ error: "Chapter not found" }, 404);
  887. }
  888. });
  889. // --- Chapter Save ---
  890. app.put("/api/v1/books/:id/chapters/:num", async (c) => {
  891. const id = c.req.param("id");
  892. const num = parseInt(c.req.param("num"), 10);
  893. const bookDir = state.bookDir(id);
  894. const chaptersDir = join(bookDir, "chapters");
  895. const { content } = await c.req.json<{ content: string }>();
  896. try {
  897. const files = await readdir(chaptersDir);
  898. const paddedNum = String(num).padStart(4, "0");
  899. const match = files.find((f) => f.startsWith(paddedNum) && f.endsWith(".md"));
  900. if (!match) return c.json({ error: "Chapter not found" }, 404);
  901. const { writeFile: writeFileFs } = await import("node:fs/promises");
  902. await writeFileFs(join(chaptersDir, match), content, "utf-8");
  903. return c.json({ ok: true, chapterNumber: num });
  904. } catch (e) {
  905. return c.json({ error: String(e) }, 500);
  906. }
  907. });
  908. // --- Truth files ---
  909. // Flat-file whitelist — the pre-Phase-5 story root files plus dev's legacy
  910. // editor targets (author_intent / current_focus / volume_outline).
  911. //
  912. // Phase 5 cleanup #3 moved the authoritative YAML frontmatter + outline prose
  913. // into story/outline/ and character sheets into story/roles/. `story_bible.md`
  914. // and `book_rules.md` now exist only as compat pointer shims — we still allow
  915. // reading them so legacy books keep rendering, but the server-side writer
  916. // (write_truth_file) no longer accepts them as edit targets.
  917. const TRUTH_FLAT_FILES = [
  918. "author_intent.md", "current_focus.md",
  919. "story_bible.md", "book_rules.md", "volume_outline.md", "current_state.md",
  920. "particle_ledger.md", "pending_hooks.md", "chapter_summaries.md",
  921. "subplot_board.md", "emotional_arcs.md", "character_matrix.md",
  922. "style_guide.md", "parent_canon.md", "fanfic_canon.md",
  923. ];
  924. // Authoritative Phase 5 paths — prose outline + role sheets live under
  925. // dedicated subdirectories of story/. The full path (relative to story/) is
  926. // matched literally here. `节奏原则.md` / `rhythm_principles.md` is optional
  927. // after Phase 5 consolidation (rhythm lives in volume_map's closing paragraph);
  928. // the entries stay whitelisted for legacy books and manual overrides.
  929. const TRUTH_OUTLINE_FILES = [
  930. "outline/story_frame.md",
  931. "outline/volume_map.md",
  932. "outline/节奏原则.md",
  933. "outline/rhythm_principles.md",
  934. ];
  935. // Pointer shims that the runtime no longer treats as authoritative. The
  936. // GET handler tags them with `legacy: true` so the UI can surface that the
  937. // edits won't land where the user expects.
  938. const LEGACY_SHIM_FILES = new Set(["story_bible.md", "book_rules.md"]);
  939. /**
  940. * Validate a requested truth-file path:
  941. * 1. Must be one of the declared flat files, an outline/* allow-listed
  942. * entry, or a roles/**\/*.md file under 主要角色/ | 次要角色/.
  943. * 2. Must resolve to a path inside bookDir/story/ (no `..`, no absolute
  944. * paths, no traversal via the tier-name segment).
  945. */
  946. function resolveTruthFilePath(bookDir: string, file: string): string | null {
  947. // Reject absolute paths, traversal, null bytes outright.
  948. if (!file || file.includes("\0") || isAbsolute(file) || file.includes("..")) {
  949. return null;
  950. }
  951. // Phase hotfix 3: accept both Chinese and English locale role dirs so
  952. // English-layout books (roles/major, roles/minor) are reachable through
  953. // Studio. The runtime reader (utils/outline-paths.ts:75) already scans
  954. // both — Studio used to drop English books to read-only.
  955. const allowed =
  956. TRUTH_FLAT_FILES.includes(file)
  957. || TRUTH_OUTLINE_FILES.includes(file)
  958. || /^roles\/(主要角色|次要角色|major|minor)\/[^/]+\.md$/.test(file);
  959. if (!allowed) return null;
  960. const storyDir = resolve(bookDir, "story");
  961. const resolved = resolve(storyDir, file);
  962. const relativePath = relative(storyDir, resolved);
  963. if (relativePath === "" || relativePath.startsWith("..") || isAbsolute(relativePath)) {
  964. return null;
  965. }
  966. return resolved;
  967. }
  968. async function fileExists(path: string): Promise<boolean> {
  969. try {
  970. await access(path);
  971. return true;
  972. } catch {
  973. return false;
  974. }
  975. }
  976. // Use `:file{.+}` wildcard so nested paths (outline/..., roles/.../...) match.
  977. app.get("/api/v1/books/:id/truth/:file{.+}", async (c) => {
  978. const file = c.req.param("file");
  979. const id = c.req.param("id");
  980. const bookDir = state.bookDir(id);
  981. const resolved = resolveTruthFilePath(bookDir, file);
  982. if (!resolved) {
  983. return c.json({ error: "Invalid truth file" }, 400);
  984. }
  985. // Phase 5: new-layout books keep the authoritative prose under outline/.
  986. // A legacy book may only have story_bible.md / book_rules.md on disk —
  987. // we still serve those for read-only display, but flag them so the UI
  988. // can warn users their edits won't reach the runtime.
  989. // Hotfix: only tag as legacy when the book actually HAS the new layout.
  990. // Pre-Phase-5 books use story_bible/book_rules as the authoritative source.
  991. const { isNewLayoutBook } = await import("@actalk/inkos-core");
  992. const legacy = LEGACY_SHIM_FILES.has(file) && await isNewLayoutBook(bookDir);
  993. try {
  994. const content = await readFile(resolved, "utf-8");
  995. return c.json({ file, content, ...(legacy ? { legacy: true } : {}) });
  996. } catch {
  997. return c.json({ file, content: null, ...(legacy ? { legacy: true } : {}) });
  998. }
  999. });
  1000. // --- Analytics ---
  1001. app.get("/api/v1/books/:id/analytics", async (c) => {
  1002. const id = c.req.param("id");
  1003. try {
  1004. const chapters = await state.loadChapterIndex(id);
  1005. return c.json(computeAnalytics(id, chapters));
  1006. } catch {
  1007. return c.json({ error: `Book "${id}" not found` }, 404);
  1008. }
  1009. });
  1010. // --- Actions ---
  1011. app.post("/api/v1/books/:id/write-next", async (c) => {
  1012. const id = c.req.param("id");
  1013. const body = await c.req.json<{ wordCount?: number }>().catch(() => ({ wordCount: undefined }));
  1014. broadcast("write:start", { bookId: id });
  1015. // Fire and forget — progress/completion/errors pushed via SSE
  1016. const pipeline = new PipelineRunner(await buildPipelineConfig());
  1017. pipeline.writeNextChapter(id, body.wordCount).then(
  1018. (result) => {
  1019. broadcast("write:complete", { bookId: id, chapterNumber: result.chapterNumber, status: result.status, title: result.title, wordCount: result.wordCount });
  1020. },
  1021. (e) => {
  1022. broadcast("write:error", { bookId: id, error: e instanceof Error ? e.message : String(e) });
  1023. },
  1024. );
  1025. return c.json({ status: "writing", bookId: id });
  1026. });
  1027. app.post("/api/v1/books/:id/draft", async (c) => {
  1028. const id = c.req.param("id");
  1029. const body = await c.req.json<{ wordCount?: number; context?: string }>().catch(() => ({ wordCount: undefined, context: undefined }));
  1030. broadcast("draft:start", { bookId: id });
  1031. const pipeline = new PipelineRunner(await buildPipelineConfig());
  1032. pipeline.writeDraft(id, body.context, body.wordCount).then(
  1033. (result) => {
  1034. broadcast("draft:complete", { bookId: id, chapterNumber: result.chapterNumber, title: result.title, wordCount: result.wordCount });
  1035. },
  1036. (e) => {
  1037. broadcast("draft:error", { bookId: id, error: e instanceof Error ? e.message : String(e) });
  1038. },
  1039. );
  1040. return c.json({ status: "drafting", bookId: id });
  1041. });
  1042. app.post("/api/v1/books/:id/chapters/:num/approve", async (c) => {
  1043. const id = c.req.param("id");
  1044. const num = parseInt(c.req.param("num"), 10);
  1045. try {
  1046. const index = await state.loadChapterIndex(id);
  1047. const updated = index.map((ch) =>
  1048. ch.number === num ? { ...ch, status: "approved" as const } : ch,
  1049. );
  1050. await state.saveChapterIndex(id, updated);
  1051. return c.json({ ok: true, chapterNumber: num, status: "approved" });
  1052. } catch (e) {
  1053. return c.json({ error: String(e) }, 500);
  1054. }
  1055. });
  1056. app.post("/api/v1/books/:id/chapters/:num/reject", async (c) => {
  1057. const id = c.req.param("id");
  1058. const num = parseInt(c.req.param("num"), 10);
  1059. try {
  1060. const index = await state.loadChapterIndex(id);
  1061. const target = index.find((ch) => ch.number === num);
  1062. if (!target) {
  1063. return c.json({ error: `Chapter ${num} not found` }, 404);
  1064. }
  1065. const rollbackTarget = num - 1;
  1066. const discarded = await state.rollbackToChapter(id, rollbackTarget);
  1067. return c.json({
  1068. ok: true,
  1069. chapterNumber: num,
  1070. status: "rejected",
  1071. rolledBackTo: rollbackTarget,
  1072. discarded,
  1073. });
  1074. } catch (e) {
  1075. return c.json({ error: String(e) }, 500);
  1076. }
  1077. });
  1078. // --- SSE ---
  1079. app.get("/api/v1/events", (c) => {
  1080. return streamSSE(c, async (stream) => {
  1081. const handler: EventHandler = (event, data) => {
  1082. stream.writeSSE({ event, data: JSON.stringify(data) });
  1083. };
  1084. subscribers.add(handler);
  1085. await stream.writeSSE({ event: "ping", data: "" });
  1086. // Keep alive
  1087. const keepAlive = setInterval(() => {
  1088. stream.writeSSE({ event: "ping", data: "" });
  1089. }, 30000);
  1090. stream.onAbort(() => {
  1091. subscribers.delete(handler);
  1092. clearInterval(keepAlive);
  1093. });
  1094. // Block until aborted
  1095. await new Promise(() => {});
  1096. });
  1097. });
  1098. // --- Model discovery ---
  1099. app.get("/api/v1/services", async (c) => {
  1100. const secrets = await loadSecrets(root);
  1101. const endpoints = getAllEndpoints().filter((ep) => ep.id !== "custom");
  1102. // Fast: only check connection status from secrets, no external API calls.
  1103. const services = endpoints.map((ep) => ({
  1104. service: ep.id,
  1105. label: ep.label,
  1106. group: ep.group,
  1107. connected: Boolean(secrets.services[ep.id]?.apiKey),
  1108. }));
  1109. // Add custom services from inkos.json
  1110. try {
  1111. const config = await loadRawConfig(root);
  1112. for (const svc of normalizeServiceConfig((config.llm as Record<string, unknown> | undefined)?.services)) {
  1113. if (svc.service === "custom") {
  1114. const secretKey = `custom:${svc.name}`;
  1115. services.push({
  1116. service: secretKey,
  1117. label: svc.name ?? "Custom",
  1118. group: undefined,
  1119. connected: Boolean(secrets.services[secretKey]?.apiKey),
  1120. });
  1121. }
  1122. }
  1123. } catch { /* no config file */ }
  1124. return c.json({ services });
  1125. });
  1126. app.get("/api/v1/services/config", async (c) => {
  1127. const config = await loadRawConfig(root);
  1128. const llm = (config.llm as Record<string, unknown> | undefined) ?? {};
  1129. const services = normalizeServiceConfig(llm.services);
  1130. const envConfig = await readEnvConfigStatus(root);
  1131. return c.json({
  1132. services,
  1133. defaultModel: llm.defaultModel ?? null,
  1134. configSource: "studio" satisfies LLMConfigSource,
  1135. storedConfigSource: normalizeConfigSource(llm.configSource),
  1136. envConfig,
  1137. });
  1138. });
  1139. app.put("/api/v1/services/config", async (c) => {
  1140. const body = await c.req.json<{ services?: unknown; defaultModel?: string; configSource?: LLMConfigSource; service?: string }>();
  1141. const config = await loadRawConfig(root);
  1142. config.llm = config.llm ?? {};
  1143. const llm = config.llm as Record<string, unknown>;
  1144. if (body.services !== undefined) {
  1145. const existingServices = normalizeServiceConfig(llm.services);
  1146. const incomingServices = normalizeServiceConfig(body.services);
  1147. llm.services = mergeServiceConfig(existingServices, incomingServices);
  1148. }
  1149. if (body.defaultModel !== undefined) {
  1150. llm.defaultModel = body.defaultModel;
  1151. }
  1152. if (body.configSource === "env") {
  1153. return c.json({
  1154. error: "Studio 运行时不支持切换到 env;env 只在 CLI/daemon/部署运行时作为覆盖层使用。",
  1155. }, 400);
  1156. }
  1157. if (body.configSource !== undefined) {
  1158. llm.configSource = normalizeConfigSource(body.configSource);
  1159. }
  1160. if (body.service !== undefined) {
  1161. llm.service = body.service;
  1162. }
  1163. await saveRawConfig(root, config);
  1164. return c.json({ ok: true });
  1165. });
  1166. app.post("/api/v1/services/:service/test", async (c) => {
  1167. const service = c.req.param("service");
  1168. const { apiKey, baseUrl, apiFormat, stream } = await c.req.json<{
  1169. apiKey: string;
  1170. baseUrl?: string;
  1171. apiFormat?: "chat" | "responses";
  1172. stream?: boolean;
  1173. }>();
  1174. if (!apiKey?.trim()) {
  1175. return c.json({ ok: false, error: "API Key 不能为空" }, 400);
  1176. }
  1177. const resolvedBaseUrl = await resolveConfiguredServiceBaseUrl(root, service, baseUrl);
  1178. if (!resolvedBaseUrl) {
  1179. return c.json({ ok: false, error: `未知服务商: ${service}` }, 400);
  1180. }
  1181. const rawConfig = await loadRawConfig(root).catch(() => ({} as Record<string, unknown>));
  1182. const llm = (rawConfig.llm as Record<string, unknown> | undefined) ?? {};
  1183. const probe = await probeServiceCapabilities({
  1184. root,
  1185. service,
  1186. apiKey: apiKey.trim(),
  1187. baseUrl: resolvedBaseUrl,
  1188. preferredApiFormat: apiFormat,
  1189. preferredStream: stream,
  1190. proxyUrl: typeof llm.proxyUrl === "string" ? llm.proxyUrl : undefined,
  1191. });
  1192. // B12: 升级响应 shape 为 { probe, chat, ... },同时保留老字段供 UI 过渡期兼容
  1193. const probeStatus = {
  1194. ok: probe.ok,
  1195. models: probe.models?.length ?? 0,
  1196. ...(probe.ok ? {} : { error: probe.error ?? "连接失败" }),
  1197. };
  1198. if (!probe.ok) {
  1199. return c.json({
  1200. ok: false,
  1201. error: probe.error ?? "连接失败",
  1202. probe: probeStatus,
  1203. chat: null,
  1204. }, 400);
  1205. }
  1206. return c.json({
  1207. ok: true,
  1208. modelCount: probe.models.length,
  1209. models: probe.models,
  1210. selectedModel: probe.selectedModel,
  1211. detected: {
  1212. apiFormat: probe.apiFormat,
  1213. stream: probe.stream,
  1214. baseUrl: probe.baseUrl,
  1215. modelsSource: probe.modelsSource,
  1216. },
  1217. // B12 新字段:两步验证状态
  1218. probe: probeStatus,
  1219. chat: null, // probeServiceCapabilities 本身只做 probe,chat hello 在 Studio 的 follow-up 调用里单独触发
  1220. });
  1221. });
  1222. app.put("/api/v1/services/:service/secret", async (c) => {
  1223. const service = c.req.param("service");
  1224. const { apiKey } = await c.req.json<{ apiKey: string }>();
  1225. const secrets = await loadSecrets(root);
  1226. if (apiKey?.trim()) {
  1227. secrets.services[service] = { apiKey: apiKey.trim() };
  1228. } else {
  1229. delete secrets.services[service];
  1230. }
  1231. await saveSecrets(root, secrets);
  1232. return c.json({ ok: true });
  1233. });
  1234. app.get("/api/v1/services/:service/secret", async (c) => {
  1235. const service = c.req.param("service");
  1236. const secrets = await loadSecrets(root);
  1237. return c.json({
  1238. apiKey: secrets.services[service]?.apiKey ?? "",
  1239. });
  1240. });
  1241. app.get("/api/v1/services/models", async (c) => {
  1242. const secrets = await loadSecrets(root);
  1243. const endpoints = getAllEndpoints()
  1244. .filter((ep) => ep.id !== "custom" && Boolean(secrets.services[ep.id]?.apiKey));
  1245. const groups = endpoints.map((ep) => ({
  1246. service: ep.id,
  1247. label: ep.label,
  1248. models: ep.models
  1249. .filter((m) => m.enabled !== false)
  1250. .filter((m) => isTextChatModelId(m.id))
  1251. .map((m) => ({
  1252. id: m.id,
  1253. name: m.id,
  1254. ...(typeof m.maxOutput === "number" ? { maxOutput: m.maxOutput } : {}),
  1255. ...(m.contextWindowTokens > 0 ? { contextWindow: m.contextWindowTokens } : {}),
  1256. })),
  1257. }));
  1258. return c.json({ groups });
  1259. });
  1260. app.get("/api/v1/services/models/custom", async (c) => {
  1261. const secrets = await loadSecrets(root);
  1262. let config: Record<string, unknown> = {};
  1263. try {
  1264. config = await loadRawConfig(root);
  1265. } catch {
  1266. // no config file
  1267. }
  1268. const customs = normalizeServiceConfig((config.llm as Record<string, unknown> | undefined)?.services)
  1269. .filter((s) => s.service === "custom")
  1270. .map((s) => ({
  1271. id: `custom:${s.name ?? "Custom"}`,
  1272. baseUrl: s.baseUrl ?? "",
  1273. label: s.name ?? "Custom",
  1274. }))
  1275. .filter((s) => s.baseUrl && Boolean(secrets.services[s.id]?.apiKey));
  1276. const groups = await Promise.all(customs.map(async (s) => ({
  1277. service: s.id,
  1278. label: s.label,
  1279. models: filterTextChatModels(
  1280. await probeModelsFromUpstream(s.baseUrl, secrets.services[s.id].apiKey, 10_000),
  1281. ),
  1282. })));
  1283. return c.json({ groups });
  1284. });
  1285. app.get("/api/v1/services/:service/models", async (c) => {
  1286. const service = c.req.param("service");
  1287. const refresh = c.req.query("refresh") === "1";
  1288. const secrets = await loadSecrets(root);
  1289. const apiKey = c.req.query("apiKey") || secrets.services[service]?.apiKey || "";
  1290. // No key = no models
  1291. if (!apiKey) return c.json({ models: [] });
  1292. const resolvedBaseUrl = await resolveConfiguredServiceBaseUrl(root, service);
  1293. // Cache by service + resolved baseUrl + apiKey fingerprint; valid for 10 min unless ?refresh=1
  1294. const cacheKey = `${service}::${resolvedBaseUrl ?? ""}::${apiKey.slice(-8)}`;
  1295. if (!refresh) {
  1296. const cached = modelListCache.get(cacheKey);
  1297. if (cached && Date.now() - cached.at < 10 * 60 * 1000) {
  1298. return c.json({ models: cached.models });
  1299. }
  1300. }
  1301. // B13: 走 listModelsForService 走 live probe + bank 交叉,返回带元数据的 models
  1302. const enriched = await listModelsForService(
  1303. isCustomServiceId(service) ? "custom" : service,
  1304. apiKey,
  1305. isCustomServiceId(service) ? resolvedBaseUrl ?? undefined : undefined,
  1306. );
  1307. const models = filterTextChatModels(enriched).map((m) => ({
  1308. id: m.id,
  1309. name: m.name,
  1310. ...(m.maxOutput !== undefined ? { maxOutput: m.maxOutput } : {}),
  1311. ...(m.contextWindow > 0 ? { contextWindow: m.contextWindow } : {}),
  1312. }));
  1313. modelListCache.set(cacheKey, { models, at: Date.now() });
  1314. return c.json({ models });
  1315. });
  1316. // --- Project info ---
  1317. app.get("/api/v1/project", async (c) => {
  1318. const currentConfig = await loadCurrentProjectConfig({ requireApiKey: false });
  1319. // Check if language was explicitly set in inkos.json (not just the schema default)
  1320. const raw = JSON.parse(await readFile(join(root, "inkos.json"), "utf-8"));
  1321. const languageExplicit = "language" in raw && raw.language !== "";
  1322. return c.json({
  1323. name: currentConfig.name,
  1324. language: currentConfig.language,
  1325. languageExplicit,
  1326. model: currentConfig.llm.model,
  1327. provider: currentConfig.llm.provider,
  1328. baseUrl: currentConfig.llm.baseUrl,
  1329. stream: currentConfig.llm.stream,
  1330. temperature: currentConfig.llm.temperature,
  1331. });
  1332. });
  1333. // --- Config editing ---
  1334. app.put("/api/v1/project", async (c) => {
  1335. const updates = await c.req.json<Record<string, unknown>>();
  1336. const configPath = join(root, "inkos.json");
  1337. try {
  1338. const raw = await readFile(configPath, "utf-8");
  1339. const existing = JSON.parse(raw);
  1340. // Merge LLM settings
  1341. if (updates.temperature !== undefined) {
  1342. existing.llm.temperature = updates.temperature;
  1343. }
  1344. if (updates.stream !== undefined) {
  1345. existing.llm.stream = updates.stream;
  1346. }
  1347. if (updates.language === "zh" || updates.language === "en") {
  1348. existing.language = updates.language;
  1349. }
  1350. const { writeFile: writeFileFs } = await import("node:fs/promises");
  1351. await writeFileFs(configPath, JSON.stringify(existing, null, 2), "utf-8");
  1352. return c.json({ ok: true });
  1353. } catch (e) {
  1354. return c.json({ error: String(e) }, 500);
  1355. }
  1356. });
  1357. // --- Truth files browser ---
  1358. app.get("/api/v1/books/:id/truth", async (c) => {
  1359. const id = c.req.param("id");
  1360. const bookDir = state.bookDir(id);
  1361. const storyDir = join(bookDir, "story");
  1362. async function listDir(subdir: string): Promise<string[]> {
  1363. try {
  1364. const entries = await readdir(join(storyDir, subdir));
  1365. return entries.filter((f) => f.endsWith(".md") || f.endsWith(".json"));
  1366. } catch {
  1367. return [];
  1368. }
  1369. }
  1370. // Hotfix: only tag shim files as legacy when the book has the new layout.
  1371. const { isNewLayoutBook } = await import("@actalk/inkos-core");
  1372. const newLayout = await isNewLayoutBook(bookDir);
  1373. async function describe(relPath: string): Promise<{ readonly name: string; readonly size: number; readonly preview: string; readonly legacy?: true } | null> {
  1374. try {
  1375. const content = await readFile(join(storyDir, relPath), "utf-8");
  1376. const isShim = LEGACY_SHIM_FILES.has(relPath) && newLayout;
  1377. const entry: { readonly name: string; readonly size: number; readonly preview: string; readonly legacy?: true } =
  1378. isShim
  1379. ? { name: relPath, size: content.length, preview: content.slice(0, 200), legacy: true }
  1380. : { name: relPath, size: content.length, preview: content.slice(0, 200) };
  1381. return entry;
  1382. } catch {
  1383. return null;
  1384. }
  1385. }
  1386. try {
  1387. // Flat story/ files (legacy + runtime logs)
  1388. const flatFiles = (await listDir(".")).filter((f) => !f.startsWith("outline") && !f.startsWith("roles"));
  1389. // Phase 5 outline/ files
  1390. const outlineFiles = (await listDir("outline")).map((f) => `outline/${f}`);
  1391. // Phase 5 roles/主要角色 + roles/次要角色, plus Phase hotfix 3
  1392. // English-locale equivalents so en-language books are visible.
  1393. const majorRolesZh = (await listDir("roles/主要角色")).map((f) => `roles/主要角色/${f}`);
  1394. const minorRolesZh = (await listDir("roles/次要角色")).map((f) => `roles/次要角色/${f}`);
  1395. const majorRolesEn = (await listDir("roles/major")).map((f) => `roles/major/${f}`);
  1396. const minorRolesEn = (await listDir("roles/minor")).map((f) => `roles/minor/${f}`);
  1397. const all = [
  1398. ...flatFiles,
  1399. ...outlineFiles,
  1400. ...majorRolesZh,
  1401. ...minorRolesZh,
  1402. ...majorRolesEn,
  1403. ...minorRolesEn,
  1404. ];
  1405. const described = await Promise.all(all.map(describe));
  1406. const result = described.filter((x): x is NonNullable<typeof x> => x !== null);
  1407. return c.json({ files: result });
  1408. } catch {
  1409. return c.json({ files: [] });
  1410. }
  1411. });
  1412. // --- Daemon control ---
  1413. let schedulerInstance: import("@actalk/inkos-core").Scheduler | null = null;
  1414. app.get("/api/v1/daemon", (c) => {
  1415. return c.json({
  1416. running: schedulerInstance?.isRunning ?? false,
  1417. });
  1418. });
  1419. app.post("/api/v1/daemon/start", async (c) => {
  1420. if (schedulerInstance?.isRunning) {
  1421. return c.json({ error: "Daemon already running" }, 400);
  1422. }
  1423. try {
  1424. const { Scheduler } = await import("@actalk/inkos-core");
  1425. const currentConfig = await loadCurrentProjectConfig();
  1426. const scheduler = new Scheduler({
  1427. ...(await buildPipelineConfig()),
  1428. radarCron: currentConfig.daemon.schedule.radarCron,
  1429. writeCron: currentConfig.daemon.schedule.writeCron,
  1430. maxConcurrentBooks: currentConfig.daemon.maxConcurrentBooks,
  1431. chaptersPerCycle: currentConfig.daemon.chaptersPerCycle,
  1432. retryDelayMs: currentConfig.daemon.retryDelayMs,
  1433. cooldownAfterChapterMs: currentConfig.daemon.cooldownAfterChapterMs,
  1434. maxChaptersPerDay: currentConfig.daemon.maxChaptersPerDay,
  1435. onChapterComplete: (bookId, chapter, status) => {
  1436. broadcast("daemon:chapter", { bookId, chapter, status });
  1437. },
  1438. onError: (bookId, error) => {
  1439. broadcast("daemon:error", { bookId, error: error.message });
  1440. },
  1441. });
  1442. schedulerInstance = scheduler;
  1443. broadcast("daemon:started", {});
  1444. void scheduler.start().catch((e) => {
  1445. const error = e instanceof Error ? e : new Error(String(e));
  1446. if (schedulerInstance === scheduler) {
  1447. scheduler.stop();
  1448. schedulerInstance = null;
  1449. broadcast("daemon:stopped", {});
  1450. }
  1451. broadcast("daemon:error", { bookId: "scheduler", error: error.message });
  1452. });
  1453. return c.json({ ok: true, running: true });
  1454. } catch (e) {
  1455. return c.json({ error: String(e) }, 500);
  1456. }
  1457. });
  1458. app.post("/api/v1/daemon/stop", (c) => {
  1459. if (!schedulerInstance?.isRunning) {
  1460. return c.json({ error: "Daemon not running" }, 400);
  1461. }
  1462. schedulerInstance.stop();
  1463. schedulerInstance = null;
  1464. broadcast("daemon:stopped", {});
  1465. return c.json({ ok: true, running: false });
  1466. });
  1467. // --- Logs ---
  1468. app.get("/api/v1/logs", async (c) => {
  1469. const logPath = join(root, "inkos.log");
  1470. try {
  1471. const content = await readFile(logPath, "utf-8");
  1472. const lines = content.trim().split("\n").slice(-100);
  1473. const entries = lines.map((line) => {
  1474. try { return JSON.parse(line); } catch { return { message: line }; }
  1475. });
  1476. return c.json({ entries });
  1477. } catch {
  1478. return c.json({ entries: [] });
  1479. }
  1480. });
  1481. // --- Agent chat ---
  1482. app.get("/api/v1/interaction/session", async (c) => {
  1483. const session = await loadProjectSession(root);
  1484. const activeBookId = await resolveSessionActiveBook(root, session);
  1485. return c.json({
  1486. session: activeBookId && session.activeBookId !== activeBookId
  1487. ? { ...session, activeBookId }
  1488. : session,
  1489. activeBookId,
  1490. });
  1491. });
  1492. // -- Per-book session endpoints --
  1493. app.get("/api/v1/sessions", async (c) => {
  1494. const bookId = c.req.query("bookId");
  1495. const sessions = await listBookSessions(root, bookId === undefined ? null : bookId === "null" ? null : bookId);
  1496. return c.json({ sessions });
  1497. });
  1498. app.get("/api/v1/sessions/:sessionId", async (c) => {
  1499. const session = await loadBookSession(root, c.req.param("sessionId"));
  1500. if (!session) return c.json({ error: "Session not found" }, 404);
  1501. return c.json({ session });
  1502. });
  1503. app.post("/api/v1/sessions", async (c) => {
  1504. const body = await c.req.json<{ bookId?: string | null; sessionId?: string }>().catch(() => ({}));
  1505. const bookId = normalizeApiBookId((body as { bookId?: unknown }).bookId, "bookId");
  1506. const sessionId = (body as { sessionId?: string }).sessionId;
  1507. // sessionId 只允许 timestamp-random 格式;防止注入任意文件名
  1508. const safeSessionId = sessionId && /^[0-9]+-[a-z0-9]+$/.test(sessionId) ? sessionId : undefined;
  1509. const session = await createAndPersistBookSession(root, bookId, safeSessionId);
  1510. return c.json({ session });
  1511. });
  1512. app.put("/api/v1/sessions/:sessionId", async (c) => {
  1513. const sessionId = c.req.param("sessionId");
  1514. const body = await c.req.json<{ title?: string }>().catch(() => ({}) as { title?: string });
  1515. const title = body.title?.trim();
  1516. if (!title) {
  1517. throw new ApiError(400, "INVALID_SESSION_TITLE", "Session title is required");
  1518. }
  1519. const session = await renameBookSession(root, sessionId, title);
  1520. if (!session) {
  1521. return c.json({ error: "Session not found" }, 404);
  1522. }
  1523. return c.json({ session });
  1524. });
  1525. app.delete("/api/v1/sessions/:sessionId", async (c) => {
  1526. await deleteBookSession(root, c.req.param("sessionId"));
  1527. return c.json({ ok: true });
  1528. });
  1529. app.post("/api/v1/agent", async (c) => {
  1530. const { instruction, activeBookId, sessionId: reqSessionId, model: reqModel, service: reqService } = await c.req.json<{
  1531. instruction: string;
  1532. activeBookId?: string;
  1533. sessionId?: string;
  1534. model?: string;
  1535. service?: string;
  1536. }>();
  1537. const sessionId = reqSessionId;
  1538. if (!instruction?.trim()) {
  1539. return c.json({ error: "No instruction provided" }, 400);
  1540. }
  1541. if (!sessionId?.trim()) {
  1542. throw new ApiError(400, "SESSION_ID_REQUIRED", "sessionId is required");
  1543. }
  1544. if (reqModel && !isTextChatModelId(reqModel)) {
  1545. const message = nonTextModelMessage(reqModel);
  1546. return c.json({ error: message, response: message }, 400);
  1547. }
  1548. broadcast("agent:start", { instruction, activeBookId, sessionId });
  1549. try {
  1550. // Load config + create LLM client (pipeline created after model resolution)
  1551. const config = await loadCurrentProjectConfig({ requireApiKey: false });
  1552. const client = createLLMClient(config.llm);
  1553. const loadedBookSession = await loadBookSession(root, sessionId);
  1554. if (!loadedBookSession) {
  1555. throw new ApiError(404, "SESSION_NOT_FOUND", `Session not found: ${sessionId}`);
  1556. }
  1557. let bookSession = loadedBookSession;
  1558. const requestedActiveBookId = normalizeApiBookId(activeBookId, "activeBookId");
  1559. const persistedBookId = normalizeApiBookId(bookSession.bookId, "session.bookId");
  1560. if (
  1561. requestedActiveBookId
  1562. && persistedBookId
  1563. && persistedBookId !== requestedActiveBookId
  1564. ) {
  1565. throw new ApiError(
  1566. 409,
  1567. "SESSION_BOOK_MISMATCH",
  1568. `Session ${bookSession.sessionId} is bound to ${persistedBookId}, not ${requestedActiveBookId}`,
  1569. );
  1570. }
  1571. const agentBookId = requestedActiveBookId ?? persistedBookId;
  1572. if (agentBookId) {
  1573. try {
  1574. await state.loadBookConfig(agentBookId);
  1575. } catch {
  1576. throw new ApiError(404, "BOOK_NOT_FOUND", `Book not found: ${agentBookId}`);
  1577. }
  1578. }
  1579. const streamSessionId = loadedBookSession.sessionId;
  1580. const titleBeforeRun = bookSession.title;
  1581. let sessionTitleBroadcasted = false;
  1582. const refreshBookSessionFromTranscript = async (): Promise<void> => {
  1583. const refreshed = await loadBookSession(root, bookSession.sessionId);
  1584. if (refreshed) {
  1585. bookSession = refreshed;
  1586. }
  1587. if (!sessionTitleBroadcasted && titleBeforeRun === null && bookSession.title) {
  1588. broadcast("session:title", { sessionId: bookSession.sessionId, title: bookSession.title });
  1589. sessionTitleBroadcasted = true;
  1590. }
  1591. };
  1592. // Resolve model — multi-service resolution
  1593. let resolvedModel: ResolvedModel["model"] | undefined;
  1594. let resolvedApiKey: string | undefined;
  1595. if (reqService && reqModel) {
  1596. // 1. Frontend explicitly selected a service+model — fail loudly if no key
  1597. try {
  1598. const configuredEntry = await resolveConfiguredServiceEntry(root, reqService);
  1599. const resolved = await resolveServiceModel(
  1600. reqService,
  1601. reqModel,
  1602. root,
  1603. await resolveConfiguredServiceBaseUrl(root, reqService),
  1604. configuredEntry?.apiFormat,
  1605. );
  1606. resolvedModel = resolved.model;
  1607. resolvedApiKey = resolved.apiKey;
  1608. } catch (e: any) {
  1609. const msg = e?.message ?? String(e);
  1610. if (/API key/i.test(msg)) {
  1611. return c.json({
  1612. error: `请先为 ${reqService} 配置 API Key`,
  1613. response: `请先在模型配置中为 ${reqService} 填写 API Key,然后再试。`,
  1614. }, 400);
  1615. }
  1616. throw e;
  1617. }
  1618. }
  1619. if (!resolvedModel) {
  1620. // 2. Try defaultModel from new config format
  1621. const rawConfig = config.llm as unknown as Record<string, unknown>;
  1622. const defaultModel = rawConfig.defaultModel as string | undefined;
  1623. const servicesArr = normalizeServiceConfig(rawConfig.services);
  1624. const firstService = servicesArr[0];
  1625. if (firstService?.service && defaultModel && isTextChatModelId(defaultModel)) {
  1626. try {
  1627. const resolved = await resolveServiceModel(
  1628. serviceConfigKey(firstService),
  1629. defaultModel,
  1630. root,
  1631. firstService.baseUrl,
  1632. firstService.apiFormat,
  1633. );
  1634. resolvedModel = resolved.model;
  1635. resolvedApiKey = resolved.apiKey;
  1636. } catch { /* fall through */ }
  1637. }
  1638. }
  1639. if (!resolvedModel) {
  1640. // 3. Try first connected service from secrets
  1641. const secrets = await loadSecrets(root);
  1642. for (const [svcName, svcData] of Object.entries(secrets.services)) {
  1643. if (svcData?.apiKey) {
  1644. try {
  1645. const models = await listModelsForService(svcName, svcData.apiKey);
  1646. const textModels = filterTextChatModels(models);
  1647. if (textModels.length > 0) {
  1648. const configuredEntry = await resolveConfiguredServiceEntry(root, svcName);
  1649. const resolved = await resolveServiceModel(
  1650. svcName,
  1651. textModels[0].id,
  1652. root,
  1653. await resolveConfiguredServiceBaseUrl(root, svcName),
  1654. configuredEntry?.apiFormat,
  1655. );
  1656. resolvedModel = resolved.model;
  1657. resolvedApiKey = resolved.apiKey;
  1658. break;
  1659. }
  1660. } catch { /* try next */ }
  1661. }
  1662. }
  1663. }
  1664. if (!resolvedModel) {
  1665. // 4. Legacy fallback: use createLLMClient
  1666. resolvedModel = client._piModel
  1667. ? client._piModel
  1668. : { provider: config.llm.provider ?? "anthropic", modelId: config.llm.model } as any;
  1669. resolvedApiKey = client._apiKey;
  1670. }
  1671. const model = resolvedModel!;
  1672. const agentApiKey = resolvedApiKey;
  1673. const configuredEntry = reqService ? await resolveConfiguredServiceEntry(root, reqService) : undefined;
  1674. // Create pipeline with resolved model (so sub_agent tools use the frontend-selected model)
  1675. // Don't spread config.llm — its baseUrl/provider belong to the old service.
  1676. // Let createLLMClient resolve baseUrl from the service preset.
  1677. const pipelineClient = (reqService && reqModel && resolvedApiKey)
  1678. ? createLLMClient({
  1679. ...config.llm,
  1680. service: configuredEntry?.service ?? reqService,
  1681. model: reqModel,
  1682. apiKey: resolvedApiKey,
  1683. ...(configuredEntry?.apiFormat ? { apiFormat: configuredEntry.apiFormat } : {}),
  1684. ...(configuredEntry?.stream !== undefined ? { stream: configuredEntry.stream } : {}),
  1685. baseUrl: configuredEntry?.baseUrl ?? "",
  1686. } as any)
  1687. : client;
  1688. const pipeline = new PipelineRunner(await buildPipelineConfig({
  1689. client: pipelineClient,
  1690. model: reqModel ?? config.llm.model,
  1691. currentConfig: config,
  1692. sessionIdForSSE: bookSession.sessionId,
  1693. }));
  1694. // Run pi-agent session
  1695. const collectedToolExecs: CollectedToolExec[] = [];
  1696. const result = await runAgentSession(
  1697. {
  1698. model,
  1699. apiKey: agentApiKey,
  1700. pipeline,
  1701. projectRoot: root,
  1702. bookId: agentBookId,
  1703. sessionId: bookSession.sessionId,
  1704. language: config.language ?? "zh",
  1705. onEvent: (event) => {
  1706. if (event.type === "message_update") {
  1707. const ame = event.assistantMessageEvent;
  1708. if (ame.type === "text_delta") {
  1709. broadcast("draft:delta", { sessionId: streamSessionId, text: ame.delta });
  1710. } else if (ame.type === "thinking_delta") {
  1711. broadcast("thinking:delta", { sessionId: streamSessionId, text: (ame as any).delta });
  1712. } else if (ame.type === "thinking_start") {
  1713. broadcast("thinking:start", { sessionId: streamSessionId });
  1714. } else if (ame.type === "thinking_end") {
  1715. broadcast("thinking:end", { sessionId: streamSessionId });
  1716. }
  1717. }
  1718. if (event.type === "tool_execution_start") {
  1719. const args = event.args as Record<string, unknown> | undefined;
  1720. const agent = event.toolName === "sub_agent" ? (args?.agent as string | undefined) : undefined;
  1721. const stages = agent ? (PIPELINE_STAGES[agent] ?? []) : [];
  1722. collectedToolExecs.push({
  1723. id: event.toolCallId,
  1724. tool: event.toolName,
  1725. agent,
  1726. label: resolveToolLabel(event.toolName, agent),
  1727. status: "running",
  1728. args,
  1729. stages: stages.length > 0
  1730. ? stages.map(l => ({ label: l, status: "pending" as const }))
  1731. : undefined,
  1732. startedAt: Date.now(),
  1733. });
  1734. if (!agentBookId && event.toolName === "sub_agent" && agent === "architect") {
  1735. const bookId = resolveArchitectBookIdFromArgs(args);
  1736. if (bookId) {
  1737. const title = typeof args?.title === "string" && args.title.trim()
  1738. ? args.title.trim()
  1739. : bookId;
  1740. bookCreateStatus.set(bookId, { status: "creating" });
  1741. broadcast("book:creating", { bookId, title, sessionId: streamSessionId });
  1742. }
  1743. }
  1744. broadcast("tool:start", {
  1745. sessionId: streamSessionId,
  1746. id: event.toolCallId,
  1747. tool: event.toolName,
  1748. args,
  1749. stages,
  1750. });
  1751. }
  1752. if (event.type === "tool_execution_update") {
  1753. broadcast("tool:update", {
  1754. sessionId: streamSessionId,
  1755. tool: event.toolName,
  1756. partialResult: event.partialResult,
  1757. });
  1758. }
  1759. if (event.type === "tool_execution_end") {
  1760. const exec = collectedToolExecs.find(t => t.id === event.toolCallId);
  1761. if (exec) {
  1762. exec.status = event.isError ? "error" : "completed";
  1763. exec.completedAt = Date.now();
  1764. exec.stages = exec.stages?.map(s => ({ ...s, status: "completed" as const }));
  1765. if (event.isError) exec.error = extractToolError(event.result);
  1766. else exec.result = summarizeResult(event.result);
  1767. exec.details = (event.result as { details?: unknown } | undefined)?.details;
  1768. if (
  1769. event.isError &&
  1770. !agentBookId &&
  1771. exec.tool === "sub_agent" &&
  1772. exec.agent === "architect"
  1773. ) {
  1774. const bookId = resolveArchitectBookIdFromArgs(exec.args);
  1775. if (bookId) {
  1776. const error = exec.error ?? "Book creation failed";
  1777. bookCreateStatus.set(bookId, { status: "error", error });
  1778. broadcast("book:error", { bookId, sessionId: streamSessionId, error });
  1779. }
  1780. }
  1781. }
  1782. broadcast("tool:end", {
  1783. sessionId: streamSessionId,
  1784. id: event.toolCallId,
  1785. tool: event.toolName,
  1786. result: event.result,
  1787. isError: event.isError,
  1788. });
  1789. }
  1790. },
  1791. },
  1792. instruction,
  1793. );
  1794. if (result.responseText) {
  1795. const actionExecutionError = validateAgentActionExecution({
  1796. instruction,
  1797. agentBookId,
  1798. responseText: result.responseText,
  1799. collectedToolExecs,
  1800. });
  1801. if (actionExecutionError) {
  1802. return c.json({
  1803. error: { code: "AGENT_ACTION_NOT_EXECUTED", message: actionExecutionError },
  1804. response: actionExecutionError,
  1805. }, 502);
  1806. }
  1807. }
  1808. let broadcastedCreatedBookId: string | null = null;
  1809. const finalizeCreatedBook = async (): Promise<string | null> => {
  1810. if (agentBookId) return null;
  1811. const createdBookId = resolveCreatedBookIdFromToolExecs(collectedToolExecs);
  1812. if (!createdBookId) return null;
  1813. if (broadcastedCreatedBookId === createdBookId) return createdBookId;
  1814. try {
  1815. const migratedSession = await migrateBookSession(root, bookSession.sessionId, createdBookId);
  1816. if (migratedSession) {
  1817. bookSession = migratedSession;
  1818. }
  1819. } catch (e) {
  1820. if (!(e instanceof SessionAlreadyMigratedError)) {
  1821. throw e;
  1822. }
  1823. }
  1824. const book = await loadStudioBookListSummary(state, createdBookId).catch(() => undefined);
  1825. bookCreateStatus.delete(createdBookId);
  1826. broadcast("book:created", {
  1827. bookId: createdBookId,
  1828. sessionId: bookSession.sessionId,
  1829. ...(book ? { book } : {}),
  1830. });
  1831. broadcastedCreatedBookId = createdBookId;
  1832. return createdBookId;
  1833. };
  1834. if (!result.responseText) {
  1835. if (result.errorMessage) {
  1836. if (resolveCreatedBookIdFromToolExecs(collectedToolExecs)) {
  1837. await finalizeCreatedBook();
  1838. }
  1839. return c.json({
  1840. error: { code: "AGENT_LLM_ERROR", message: result.errorMessage },
  1841. response: result.errorMessage,
  1842. }, 502);
  1843. }
  1844. try {
  1845. const fallbackClient = createLLMClient({
  1846. ...config.llm,
  1847. service: configuredEntry?.service ?? reqService ?? config.llm.service,
  1848. model: reqModel ?? config.llm.model,
  1849. apiKey: agentApiKey ?? config.llm.apiKey,
  1850. baseUrl: configuredEntry?.baseUrl ?? "",
  1851. ...(configuredEntry?.apiFormat ? { apiFormat: configuredEntry.apiFormat } : {}),
  1852. ...(configuredEntry?.stream !== undefined ? { stream: configuredEntry.stream } : {}),
  1853. } as ProjectConfig["llm"]);
  1854. const fallback = await chatCompletion(
  1855. fallbackClient,
  1856. reqModel ?? config.llm.model,
  1857. [
  1858. { role: "system", content: buildAgentSystemPrompt(agentBookId, config.language ?? "zh") },
  1859. { role: "user", content: instruction },
  1860. ],
  1861. { maxTokens: 256 },
  1862. );
  1863. if (fallback.content?.trim()) {
  1864. const actionExecutionError = validateAgentActionExecution({
  1865. instruction,
  1866. agentBookId,
  1867. responseText: fallback.content,
  1868. collectedToolExecs,
  1869. });
  1870. if (actionExecutionError) {
  1871. return c.json({
  1872. error: { code: "AGENT_ACTION_NOT_EXECUTED", message: actionExecutionError },
  1873. response: actionExecutionError,
  1874. }, 502);
  1875. }
  1876. await appendManualSessionMessages(root, bookSession.sessionId, [{
  1877. role: "assistant",
  1878. content: [{ type: "text", text: fallback.content }],
  1879. api: "anthropic-messages",
  1880. provider: configuredEntry?.service ?? reqService ?? config.llm.provider,
  1881. model: reqModel ?? config.llm.model,
  1882. usage: {
  1883. input: 0,
  1884. output: 0,
  1885. cacheRead: 0,
  1886. cacheWrite: 0,
  1887. totalTokens: 0,
  1888. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  1889. },
  1890. stopReason: "stop",
  1891. timestamp: Date.now(),
  1892. }], instruction);
  1893. await refreshBookSessionFromTranscript();
  1894. const createdBookId = await finalizeCreatedBook();
  1895. return c.json({
  1896. response: fallback.content,
  1897. session: {
  1898. sessionId: bookSession.sessionId,
  1899. ...(createdBookId ? { activeBookId: createdBookId } : {}),
  1900. },
  1901. });
  1902. }
  1903. } catch {
  1904. // fall through to probe-based diagnosis below
  1905. }
  1906. try {
  1907. const probeClient = createLLMClient({
  1908. ...config.llm,
  1909. service: configuredEntry?.service ?? reqService ?? config.llm.service,
  1910. model: reqModel ?? config.llm.model,
  1911. apiKey: agentApiKey ?? config.llm.apiKey,
  1912. baseUrl: configuredEntry?.baseUrl ?? "",
  1913. ...(configuredEntry?.apiFormat ? { apiFormat: configuredEntry.apiFormat } : {}),
  1914. ...(configuredEntry?.stream !== undefined ? { stream: configuredEntry.stream } : {}),
  1915. } as ProjectConfig["llm"]);
  1916. await chatCompletion(
  1917. probeClient,
  1918. reqModel ?? config.llm.model,
  1919. [{ role: "user", content: "ping" }],
  1920. { maxTokens: 5 },
  1921. );
  1922. } catch (probeError) {
  1923. const probeMessage = probeError instanceof Error ? probeError.message : String(probeError);
  1924. if (resolveCreatedBookIdFromToolExecs(collectedToolExecs)) {
  1925. await finalizeCreatedBook();
  1926. }
  1927. return c.json({
  1928. error: { code: "AGENT_EMPTY_RESPONSE", message: probeMessage },
  1929. response: probeMessage,
  1930. }, 502);
  1931. }
  1932. const emptyMessage = "模型未返回文本内容。请检查协议类型(chat/responses)、流式开关或上游服务兼容性。";
  1933. if (resolveCreatedBookIdFromToolExecs(collectedToolExecs)) {
  1934. await finalizeCreatedBook();
  1935. }
  1936. return c.json({
  1937. error: { code: "AGENT_EMPTY_RESPONSE", message: emptyMessage },
  1938. response: emptyMessage,
  1939. }, 502);
  1940. }
  1941. await refreshBookSessionFromTranscript();
  1942. await finalizeCreatedBook();
  1943. broadcast("agent:complete", { instruction, activeBookId, sessionId: bookSession.sessionId });
  1944. return c.json({
  1945. response: result.responseText,
  1946. session: {
  1947. sessionId: bookSession.sessionId,
  1948. ...(bookSession.bookId ? { activeBookId: bookSession.bookId } : {}),
  1949. },
  1950. });
  1951. } catch (e) {
  1952. if (e instanceof ApiError) {
  1953. throw e;
  1954. }
  1955. if (e instanceof SessionAlreadyMigratedError) {
  1956. const migratedMessage = e instanceof Error ? e.message : String(e);
  1957. throw new ApiError(409, "SESSION_ALREADY_MIGRATED", migratedMessage);
  1958. }
  1959. const msg = e instanceof Error ? e.message : String(e);
  1960. broadcast("agent:error", { instruction, activeBookId, sessionId, error: msg });
  1961. // Agent busy — return 429 with user-friendly message
  1962. if (/already processing|prompt.*queue/i.test(msg)) {
  1963. return c.json({
  1964. error: { code: "AGENT_BUSY", message: "正在处理中,请等待当前操作完成" },
  1965. response: "正在处理中,请等待当前操作完成后再发送。",
  1966. }, 429);
  1967. }
  1968. return c.json(
  1969. { error: { code: "AGENT_ERROR", message: msg } },
  1970. 500,
  1971. );
  1972. }
  1973. });
  1974. // --- Language setup ---
  1975. app.post("/api/v1/project/language", async (c) => {
  1976. const { language } = await c.req.json<{ language: "zh" | "en" }>();
  1977. const configPath = join(root, "inkos.json");
  1978. try {
  1979. const raw = await readFile(configPath, "utf-8");
  1980. const existing = JSON.parse(raw);
  1981. existing.language = language;
  1982. const { writeFile: writeFileFs } = await import("node:fs/promises");
  1983. await writeFileFs(configPath, JSON.stringify(existing, null, 2), "utf-8");
  1984. return c.json({ ok: true, language });
  1985. } catch (e) {
  1986. return c.json({ error: String(e) }, 500);
  1987. }
  1988. });
  1989. // --- Audit ---
  1990. app.post("/api/v1/books/:id/audit/:chapter", async (c) => {
  1991. const id = c.req.param("id");
  1992. const chapterNum = parseInt(c.req.param("chapter"), 10);
  1993. const bookDir = state.bookDir(id);
  1994. broadcast("audit:start", { bookId: id, chapter: chapterNum });
  1995. try {
  1996. const book = await state.loadBookConfig(id);
  1997. const chaptersDir = join(bookDir, "chapters");
  1998. const files = await readdir(chaptersDir);
  1999. const paddedNum = String(chapterNum).padStart(4, "0");
  2000. const match = files.find((f) => f.startsWith(paddedNum) && f.endsWith(".md"));
  2001. if (!match) return c.json({ error: "Chapter not found" }, 404);
  2002. const content = await readFile(join(chaptersDir, match), "utf-8");
  2003. const currentConfig = await loadCurrentProjectConfig();
  2004. const { ContinuityAuditor } = await import("@actalk/inkos-core");
  2005. const auditor = new ContinuityAuditor({
  2006. client: createLLMClient(currentConfig.llm),
  2007. model: currentConfig.llm.model,
  2008. projectRoot: root,
  2009. bookId: id,
  2010. });
  2011. const result = await auditor.auditChapter(bookDir, content, chapterNum, book.genre);
  2012. broadcast("audit:complete", { bookId: id, chapter: chapterNum, passed: result.passed });
  2013. return c.json(result);
  2014. } catch (e) {
  2015. broadcast("audit:error", { bookId: id, error: String(e) });
  2016. return c.json({ error: String(e) }, 500);
  2017. }
  2018. });
  2019. // --- Revise ---
  2020. app.post("/api/v1/books/:id/revise/:chapter", async (c) => {
  2021. const id = c.req.param("id");
  2022. const chapterNum = parseInt(c.req.param("chapter"), 10);
  2023. const bookDir = state.bookDir(id);
  2024. const body = await c.req
  2025. .json<{ mode?: string; brief?: string }>()
  2026. .catch(() => ({ mode: "spot-fix", brief: undefined }));
  2027. broadcast("revise:start", { bookId: id, chapter: chapterNum });
  2028. try {
  2029. const book = await state.loadBookConfig(id);
  2030. const chaptersDir = join(bookDir, "chapters");
  2031. const files = await readdir(chaptersDir);
  2032. const paddedNum = String(chapterNum).padStart(4, "0");
  2033. const match = files.find((f) => f.startsWith(paddedNum) && f.endsWith(".md"));
  2034. if (!match) return c.json({ error: "Chapter not found" }, 404);
  2035. const pipeline = new PipelineRunner(await buildPipelineConfig({
  2036. externalContext: body.brief,
  2037. }));
  2038. const normalizedMode = body.mode ?? "spot-fix";
  2039. const result = await pipeline.reviseDraft(
  2040. id,
  2041. chapterNum,
  2042. normalizedMode as "polish" | "rewrite" | "rework" | "spot-fix" | "anti-detect",
  2043. );
  2044. broadcast("revise:complete", { bookId: id, chapter: chapterNum });
  2045. return c.json(result);
  2046. } catch (e) {
  2047. broadcast("revise:error", { bookId: id, error: String(e) });
  2048. return c.json({ error: String(e) }, 500);
  2049. }
  2050. });
  2051. // --- Export ---
  2052. app.get("/api/v1/books/:id/export", async (c) => {
  2053. const id = c.req.param("id");
  2054. const format = (c.req.query("format") ?? "txt") as string;
  2055. const approvedOnly = c.req.query("approvedOnly") === "true";
  2056. try {
  2057. const artifact = await buildExportArtifact(state, id, {
  2058. format: format as "txt" | "md" | "epub",
  2059. approvedOnly,
  2060. });
  2061. const responseBody = typeof artifact.payload === "string"
  2062. ? artifact.payload
  2063. : new Uint8Array(artifact.payload);
  2064. return new Response(responseBody, {
  2065. headers: {
  2066. "Content-Type": artifact.contentType,
  2067. "Content-Disposition": `attachment; filename="${artifact.fileName}"`,
  2068. },
  2069. });
  2070. } catch {
  2071. return c.json({ error: "Export failed" }, 500);
  2072. }
  2073. });
  2074. // --- Export to file (save to project dir) ---
  2075. app.post("/api/v1/books/:id/export-save", async (c) => {
  2076. const id = c.req.param("id");
  2077. const { format, approvedOnly } = await c.req.json<{ format?: string; approvedOnly?: boolean }>().catch(() => ({ format: "txt", approvedOnly: false }));
  2078. const fmt = format ?? "txt";
  2079. try {
  2080. const pipeline = new PipelineRunner(await buildPipelineConfig());
  2081. const tools = createInteractionToolsFromDeps(pipeline, state);
  2082. const bookDir = state.bookDir(id);
  2083. const outputPath = join(bookDir, `${id}.${fmt === "epub" ? "epub" : fmt}`);
  2084. const result = await processProjectInteractionRequest({
  2085. projectRoot: root,
  2086. request: {
  2087. intent: "export_book",
  2088. bookId: id,
  2089. format: fmt as "txt" | "md" | "epub",
  2090. approvedOnly,
  2091. outputPath,
  2092. },
  2093. tools,
  2094. activeBookId: id,
  2095. });
  2096. return c.json({
  2097. ok: true,
  2098. path: (result.details?.outputPath as string | undefined) ?? outputPath,
  2099. format: fmt,
  2100. chapters: (result.details?.chaptersExported as number | undefined) ?? 0,
  2101. });
  2102. } catch (e) {
  2103. return c.json({ error: String(e) }, 500);
  2104. }
  2105. });
  2106. // --- Genre detail + copy ---
  2107. app.get("/api/v1/genres/:id", async (c) => {
  2108. const genreId = c.req.param("id");
  2109. try {
  2110. const { readGenreProfile } = await import("@actalk/inkos-core");
  2111. const { profile, body } = await readGenreProfile(root, genreId);
  2112. return c.json({ profile, body });
  2113. } catch (e) {
  2114. return c.json({ error: String(e) }, 404);
  2115. }
  2116. });
  2117. app.post("/api/v1/genres/:id/copy", async (c) => {
  2118. const genreId = c.req.param("id");
  2119. if (/[/\\\0]/.test(genreId) || genreId.includes("..")) {
  2120. throw new ApiError(400, "INVALID_GENRE_ID", `Invalid genre ID: "${genreId}"`);
  2121. }
  2122. try {
  2123. const { getBuiltinGenresDir } = await import("@actalk/inkos-core");
  2124. const { mkdir: mkdirFs, copyFile } = await import("node:fs/promises");
  2125. const builtinDir = getBuiltinGenresDir();
  2126. const projectGenresDir = join(root, "genres");
  2127. await mkdirFs(projectGenresDir, { recursive: true });
  2128. await copyFile(join(builtinDir, `${genreId}.md`), join(projectGenresDir, `${genreId}.md`));
  2129. return c.json({ ok: true, path: `genres/${genreId}.md` });
  2130. } catch (e) {
  2131. return c.json({ error: String(e) }, 500);
  2132. }
  2133. });
  2134. // --- Model overrides ---
  2135. app.get("/api/v1/project/model-overrides", async (c) => {
  2136. const raw = JSON.parse(await readFile(join(root, "inkos.json"), "utf-8"));
  2137. return c.json({ overrides: raw.modelOverrides ?? {} });
  2138. });
  2139. app.put("/api/v1/project/model-overrides", async (c) => {
  2140. const { overrides } = await c.req.json<{ overrides: Record<string, unknown> }>();
  2141. const configPath = join(root, "inkos.json");
  2142. const raw = JSON.parse(await readFile(configPath, "utf-8"));
  2143. raw.modelOverrides = overrides;
  2144. const { writeFile: writeFileFs } = await import("node:fs/promises");
  2145. await writeFileFs(configPath, JSON.stringify(raw, null, 2), "utf-8");
  2146. return c.json({ ok: true });
  2147. });
  2148. // --- Notify channels ---
  2149. app.get("/api/v1/project/notify", async (c) => {
  2150. const raw = JSON.parse(await readFile(join(root, "inkos.json"), "utf-8"));
  2151. return c.json({ channels: raw.notify ?? [] });
  2152. });
  2153. app.put("/api/v1/project/notify", async (c) => {
  2154. const { channels } = await c.req.json<{ channels: unknown[] }>();
  2155. const configPath = join(root, "inkos.json");
  2156. const raw = JSON.parse(await readFile(configPath, "utf-8"));
  2157. raw.notify = channels;
  2158. const { writeFile: writeFileFs } = await import("node:fs/promises");
  2159. await writeFileFs(configPath, JSON.stringify(raw, null, 2), "utf-8");
  2160. return c.json({ ok: true });
  2161. });
  2162. // --- AIGC Detection ---
  2163. app.post("/api/v1/books/:id/detect/:chapter", async (c) => {
  2164. const id = c.req.param("id");
  2165. const chapterNum = parseInt(c.req.param("chapter"), 10);
  2166. const bookDir = state.bookDir(id);
  2167. try {
  2168. const chaptersDir = join(bookDir, "chapters");
  2169. const files = await readdir(chaptersDir);
  2170. const paddedNum = String(chapterNum).padStart(4, "0");
  2171. const match = files.find((f) => f.startsWith(paddedNum) && f.endsWith(".md"));
  2172. if (!match) return c.json({ error: "Chapter not found" }, 404);
  2173. const content = await readFile(join(chaptersDir, match), "utf-8");
  2174. const { analyzeAITells } = await import("@actalk/inkos-core");
  2175. const result = analyzeAITells(content);
  2176. return c.json({ chapterNumber: chapterNum, ...result });
  2177. } catch (e) {
  2178. return c.json({ error: String(e) }, 500);
  2179. }
  2180. });
  2181. // --- Truth file edit ---
  2182. app.put("/api/v1/books/:id/truth/:file{.+}", async (c) => {
  2183. const id = c.req.param("id");
  2184. const file = c.req.param("file");
  2185. const bookDir = state.bookDir(id);
  2186. const resolved = resolveTruthFilePath(bookDir, file);
  2187. if (!resolved) {
  2188. return c.json({ error: "Invalid truth file" }, 400);
  2189. }
  2190. // Legacy pointer shims are read-only in new-layout books: writing
  2191. // story_bible.md or book_rules.md does nothing at runtime (the pipeline
  2192. // reads outline/ instead). For pre-Phase-5 books these ARE authoritative.
  2193. if (LEGACY_SHIM_FILES.has(file)) {
  2194. const { isNewLayoutBook } = await import("@actalk/inkos-core");
  2195. if (await isNewLayoutBook(bookDir)) {
  2196. return c.json(
  2197. { error: "Legacy compat shim; edit outline/story_frame.md instead" },
  2198. 400,
  2199. );
  2200. }
  2201. }
  2202. const { content } = await c.req.json<{ content: string }>();
  2203. const { writeFile: writeFileFs, mkdir: mkdirFs } = await import("node:fs/promises");
  2204. const { dirname: dirnameFs } = await import("node:path");
  2205. await mkdirFs(dirnameFs(resolved), { recursive: true });
  2206. await writeFileFs(resolved, content, "utf-8");
  2207. return c.json({ ok: true });
  2208. });
  2209. // =============================================
  2210. // NEW ENDPOINTS — CLI parity
  2211. // =============================================
  2212. // --- Book Delete ---
  2213. app.delete("/api/v1/books/:id", async (c) => {
  2214. const id = c.req.param("id");
  2215. const bookDir = state.bookDir(id);
  2216. try {
  2217. const { rm } = await import("node:fs/promises");
  2218. await rm(bookDir, { recursive: true, force: true });
  2219. broadcast("book:deleted", { bookId: id });
  2220. return c.json({ ok: true, bookId: id });
  2221. } catch (e) {
  2222. return c.json({ error: String(e) }, 500);
  2223. }
  2224. });
  2225. // --- Book Update ---
  2226. app.put("/api/v1/books/:id", async (c) => {
  2227. const id = c.req.param("id");
  2228. const updates = await c.req.json<{
  2229. chapterWordCount?: number;
  2230. targetChapters?: number;
  2231. status?: string;
  2232. language?: string;
  2233. }>();
  2234. try {
  2235. const book = await state.loadBookConfig(id);
  2236. const updated = {
  2237. ...book,
  2238. ...(updates.chapterWordCount !== undefined ? { chapterWordCount: Number(updates.chapterWordCount) } : {}),
  2239. ...(updates.targetChapters !== undefined ? { targetChapters: Number(updates.targetChapters) } : {}),
  2240. ...(updates.status !== undefined ? { status: updates.status as typeof book.status } : {}),
  2241. ...(updates.language !== undefined ? { language: updates.language as "zh" | "en" } : {}),
  2242. updatedAt: new Date().toISOString(),
  2243. };
  2244. await state.saveBookConfig(id, updated);
  2245. return c.json({ ok: true, book: updated });
  2246. } catch (e) {
  2247. return c.json({ error: String(e) }, 500);
  2248. }
  2249. });
  2250. // --- Write Rewrite (specific chapter) ---
  2251. app.post("/api/v1/books/:id/rewrite/:chapter", async (c) => {
  2252. const id = c.req.param("id");
  2253. const chapterNum = parseInt(c.req.param("chapter"), 10);
  2254. const body: { brief?: string } = await c.req
  2255. .json<{ brief?: string }>()
  2256. .catch(() => ({}));
  2257. broadcast("rewrite:start", { bookId: id, chapter: chapterNum });
  2258. try {
  2259. const rollbackTarget = chapterNum - 1;
  2260. const discarded = await state.rollbackToChapter(id, rollbackTarget);
  2261. const pipeline = new PipelineRunner(await buildPipelineConfig({
  2262. externalContext: body.brief,
  2263. }));
  2264. pipeline.writeNextChapter(id).then(
  2265. (result) => broadcast("rewrite:complete", { bookId: id, chapterNumber: result.chapterNumber, title: result.title, wordCount: result.wordCount }),
  2266. (e) => broadcast("rewrite:error", { bookId: id, error: e instanceof Error ? e.message : String(e) }),
  2267. );
  2268. return c.json({ status: "rewriting", bookId: id, chapter: chapterNum, rolledBackTo: rollbackTarget, discarded });
  2269. } catch (e) {
  2270. broadcast("rewrite:error", { bookId: id, error: String(e) });
  2271. return c.json({ error: String(e) }, 500);
  2272. }
  2273. });
  2274. app.post("/api/v1/books/:id/resync/:chapter", async (c) => {
  2275. const id = c.req.param("id");
  2276. const chapterNum = parseInt(c.req.param("chapter"), 10);
  2277. const body: { brief?: string } = await c.req
  2278. .json<{ brief?: string }>()
  2279. .catch(() => ({}));
  2280. try {
  2281. const pipeline = new PipelineRunner(await buildPipelineConfig({
  2282. externalContext: body.brief,
  2283. }));
  2284. const result = await pipeline.resyncChapterArtifacts(id, chapterNum);
  2285. return c.json(result);
  2286. } catch (e) {
  2287. return c.json({ error: String(e) }, 500);
  2288. }
  2289. });
  2290. // --- Detect All chapters ---
  2291. app.post("/api/v1/books/:id/detect-all", async (c) => {
  2292. const id = c.req.param("id");
  2293. const bookDir = state.bookDir(id);
  2294. try {
  2295. const chaptersDir = join(bookDir, "chapters");
  2296. const files = await readdir(chaptersDir);
  2297. const mdFiles = files.filter((f) => f.endsWith(".md") && /^\d{4}/.test(f)).sort();
  2298. const { analyzeAITells } = await import("@actalk/inkos-core");
  2299. const results = await Promise.all(
  2300. mdFiles.map(async (f) => {
  2301. const num = parseInt(f.slice(0, 4), 10);
  2302. const content = await readFile(join(chaptersDir, f), "utf-8");
  2303. const result = analyzeAITells(content);
  2304. return { chapterNumber: num, filename: f, ...result };
  2305. }),
  2306. );
  2307. return c.json({ bookId: id, results });
  2308. } catch (e) {
  2309. return c.json({ error: String(e) }, 500);
  2310. }
  2311. });
  2312. // --- Detect Stats ---
  2313. app.get("/api/v1/books/:id/detect/stats", async (c) => {
  2314. const id = c.req.param("id");
  2315. try {
  2316. const { loadDetectionHistory, analyzeDetectionInsights } = await import("@actalk/inkos-core");
  2317. const bookDir = state.bookDir(id);
  2318. const history = await loadDetectionHistory(bookDir);
  2319. const insights = analyzeDetectionInsights(history);
  2320. return c.json(insights);
  2321. } catch (e) {
  2322. return c.json({ error: String(e) }, 500);
  2323. }
  2324. });
  2325. // --- Genre Create ---
  2326. app.post("/api/v1/genres/create", async (c) => {
  2327. const body = await c.req.json<{
  2328. id: string; name: string; language?: string;
  2329. chapterTypes?: string[]; fatigueWords?: string[];
  2330. numericalSystem?: boolean; powerScaling?: boolean; eraResearch?: boolean;
  2331. pacingRule?: string; satisfactionTypes?: string[]; auditDimensions?: number[];
  2332. body?: string;
  2333. }>();
  2334. if (!body.id || !body.name) {
  2335. return c.json({ error: "id and name are required" }, 400);
  2336. }
  2337. if (/[/\\\0]/.test(body.id) || body.id.includes("..")) {
  2338. throw new ApiError(400, "INVALID_GENRE_ID", `Invalid genre ID: "${body.id}"`);
  2339. }
  2340. const { writeFile: writeFileFs, mkdir: mkdirFs } = await import("node:fs/promises");
  2341. const genresDir = join(root, "genres");
  2342. await mkdirFs(genresDir, { recursive: true });
  2343. const frontmatter = [
  2344. "---",
  2345. `name: ${body.name}`,
  2346. `id: ${body.id}`,
  2347. `language: ${body.language ?? "zh"}`,
  2348. `chapterTypes: ${JSON.stringify(body.chapterTypes ?? [])}`,
  2349. `fatigueWords: ${JSON.stringify(body.fatigueWords ?? [])}`,
  2350. `numericalSystem: ${body.numericalSystem ?? false}`,
  2351. `powerScaling: ${body.powerScaling ?? false}`,
  2352. `eraResearch: ${body.eraResearch ?? false}`,
  2353. `pacingRule: "${body.pacingRule ?? ""}"`,
  2354. `satisfactionTypes: ${JSON.stringify(body.satisfactionTypes ?? [])}`,
  2355. `auditDimensions: ${JSON.stringify(body.auditDimensions ?? [])}`,
  2356. "---",
  2357. "",
  2358. body.body ?? "",
  2359. ].join("\n");
  2360. await writeFileFs(join(genresDir, `${body.id}.md`), frontmatter, "utf-8");
  2361. return c.json({ ok: true, id: body.id });
  2362. });
  2363. // --- Genre Edit ---
  2364. app.put("/api/v1/genres/:id", async (c) => {
  2365. const genreId = c.req.param("id");
  2366. if (/[/\\\0]/.test(genreId) || genreId.includes("..")) {
  2367. throw new ApiError(400, "INVALID_GENRE_ID", `Invalid genre ID: "${genreId}"`);
  2368. }
  2369. const body = await c.req.json<{ profile: Record<string, unknown>; body: string }>();
  2370. const { writeFile: writeFileFs, mkdir: mkdirFs } = await import("node:fs/promises");
  2371. const genresDir = join(root, "genres");
  2372. await mkdirFs(genresDir, { recursive: true });
  2373. const p = body.profile;
  2374. const frontmatter = [
  2375. "---",
  2376. `name: ${p.name ?? genreId}`,
  2377. `id: ${p.id ?? genreId}`,
  2378. `language: ${p.language ?? "zh"}`,
  2379. `chapterTypes: ${JSON.stringify(p.chapterTypes ?? [])}`,
  2380. `fatigueWords: ${JSON.stringify(p.fatigueWords ?? [])}`,
  2381. `numericalSystem: ${p.numericalSystem ?? false}`,
  2382. `powerScaling: ${p.powerScaling ?? false}`,
  2383. `eraResearch: ${p.eraResearch ?? false}`,
  2384. `pacingRule: "${p.pacingRule ?? ""}"`,
  2385. `satisfactionTypes: ${JSON.stringify(p.satisfactionTypes ?? [])}`,
  2386. `auditDimensions: ${JSON.stringify(p.auditDimensions ?? [])}`,
  2387. "---",
  2388. "",
  2389. body.body ?? "",
  2390. ].join("\n");
  2391. await writeFileFs(join(genresDir, `${genreId}.md`), frontmatter, "utf-8");
  2392. return c.json({ ok: true, id: genreId });
  2393. });
  2394. // --- Genre Delete (project-level only) ---
  2395. app.delete("/api/v1/genres/:id", async (c) => {
  2396. const genreId = c.req.param("id");
  2397. if (/[/\\\0]/.test(genreId) || genreId.includes("..")) {
  2398. throw new ApiError(400, "INVALID_GENRE_ID", `Invalid genre ID: "${genreId}"`);
  2399. }
  2400. const filePath = join(root, "genres", `${genreId}.md`);
  2401. try {
  2402. const { rm } = await import("node:fs/promises");
  2403. await rm(filePath);
  2404. return c.json({ ok: true, id: genreId });
  2405. } catch (e) {
  2406. return c.json({ error: `Genre "${genreId}" not found in project` }, 404);
  2407. }
  2408. });
  2409. // --- Style Analyze ---
  2410. app.post("/api/v1/style/analyze", async (c) => {
  2411. const { text, sourceName } = await c.req.json<{ text: string; sourceName: string }>();
  2412. if (!text?.trim()) return c.json({ error: "text is required" }, 400);
  2413. try {
  2414. const { analyzeStyle } = await import("@actalk/inkos-core");
  2415. const profile = analyzeStyle(text, sourceName ?? "unknown");
  2416. return c.json(profile);
  2417. } catch (e) {
  2418. return c.json({ error: String(e) }, 500);
  2419. }
  2420. });
  2421. // --- Style Import to Book ---
  2422. app.post("/api/v1/books/:id/style/import", async (c) => {
  2423. const id = c.req.param("id");
  2424. const { text, sourceName } = await c.req.json<{ text: string; sourceName: string }>();
  2425. if (!text?.trim()) return c.json({ error: "text is required" }, 400);
  2426. broadcast("style:start", { bookId: id });
  2427. try {
  2428. const pipeline = new PipelineRunner(await buildPipelineConfig());
  2429. const result = await pipeline.generateStyleGuide(id, text, sourceName ?? "unknown");
  2430. broadcast("style:complete", { bookId: id });
  2431. return c.json({ ok: true, result });
  2432. } catch (e) {
  2433. broadcast("style:error", { bookId: id, error: String(e) });
  2434. return c.json({ error: String(e) }, 500);
  2435. }
  2436. });
  2437. // --- Import Chapters ---
  2438. app.post("/api/v1/books/:id/import/chapters", async (c) => {
  2439. const id = c.req.param("id");
  2440. const { text, splitRegex } = await c.req.json<{ text: string; splitRegex?: string }>();
  2441. if (!text?.trim()) return c.json({ error: "text is required" }, 400);
  2442. broadcast("import:start", { bookId: id, type: "chapters" });
  2443. try {
  2444. const { splitChapters } = await import("@actalk/inkos-core");
  2445. const chapters = [...splitChapters(text, splitRegex)];
  2446. const pipeline = new PipelineRunner(await buildPipelineConfig());
  2447. const result = await pipeline.importChapters({ bookId: id, chapters });
  2448. broadcast("import:complete", { bookId: id, type: "chapters", count: result.importedCount });
  2449. return c.json(result);
  2450. } catch (e) {
  2451. broadcast("import:error", { bookId: id, error: String(e) });
  2452. return c.json({ error: String(e) }, 500);
  2453. }
  2454. });
  2455. // --- Import Canon ---
  2456. app.post("/api/v1/books/:id/import/canon", async (c) => {
  2457. const id = c.req.param("id");
  2458. const { fromBookId } = await c.req.json<{ fromBookId: string }>();
  2459. if (!fromBookId) return c.json({ error: "fromBookId is required" }, 400);
  2460. broadcast("import:start", { bookId: id, type: "canon" });
  2461. try {
  2462. const pipeline = new PipelineRunner(await buildPipelineConfig());
  2463. await pipeline.importCanon(id, fromBookId);
  2464. broadcast("import:complete", { bookId: id, type: "canon" });
  2465. return c.json({ ok: true });
  2466. } catch (e) {
  2467. broadcast("import:error", { bookId: id, error: String(e) });
  2468. return c.json({ error: String(e) }, 500);
  2469. }
  2470. });
  2471. // --- Fanfic Init ---
  2472. app.post("/api/v1/fanfic/init", async (c) => {
  2473. const body = await c.req.json<{
  2474. title: string; sourceText: string; sourceName?: string;
  2475. mode?: string; genre?: string; platform?: string;
  2476. targetChapters?: number; chapterWordCount?: number; language?: string;
  2477. }>();
  2478. if (!body.title || !body.sourceText) {
  2479. return c.json({ error: "title and sourceText are required" }, 400);
  2480. }
  2481. const now = new Date().toISOString();
  2482. const bookId = body.title.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]/g, "-").replace(/-+/g, "-").slice(0, 30);
  2483. const bookConfig = {
  2484. id: bookId,
  2485. title: body.title,
  2486. platform: (body.platform ?? "other") as "other",
  2487. genre: (body.genre ?? "other") as "xuanhuan",
  2488. status: "outlining" as const,
  2489. targetChapters: body.targetChapters ?? 100,
  2490. chapterWordCount: body.chapterWordCount ?? 3000,
  2491. fanficMode: (body.mode ?? "canon") as "canon",
  2492. ...(body.language ? { language: body.language as "zh" | "en" } : {}),
  2493. createdAt: now,
  2494. updatedAt: now,
  2495. };
  2496. broadcast("fanfic:start", { bookId, title: body.title });
  2497. try {
  2498. const pipeline = new PipelineRunner(await buildPipelineConfig());
  2499. await pipeline.initFanficBook(bookConfig, body.sourceText, body.sourceName ?? "source", (body.mode ?? "canon") as "canon");
  2500. broadcast("fanfic:complete", { bookId });
  2501. return c.json({ ok: true, bookId });
  2502. } catch (e) {
  2503. broadcast("fanfic:error", { bookId, error: String(e) });
  2504. return c.json({ error: String(e) }, 500);
  2505. }
  2506. });
  2507. // --- Fanfic Show (read canon) ---
  2508. app.get("/api/v1/books/:id/fanfic", async (c) => {
  2509. const id = c.req.param("id");
  2510. const bookDir = state.bookDir(id);
  2511. try {
  2512. const content = await readFile(join(bookDir, "story", "fanfic_canon.md"), "utf-8");
  2513. return c.json({ bookId: id, content });
  2514. } catch {
  2515. return c.json({ bookId: id, content: null });
  2516. }
  2517. });
  2518. // --- Fanfic Refresh ---
  2519. app.post("/api/v1/books/:id/fanfic/refresh", async (c) => {
  2520. const id = c.req.param("id");
  2521. const { sourceText, sourceName } = await c.req.json<{ sourceText: string; sourceName?: string }>();
  2522. if (!sourceText?.trim()) return c.json({ error: "sourceText is required" }, 400);
  2523. broadcast("fanfic:refresh:start", { bookId: id });
  2524. try {
  2525. const book = await state.loadBookConfig(id);
  2526. const pipeline = new PipelineRunner(await buildPipelineConfig());
  2527. await pipeline.importFanficCanon(id, sourceText, sourceName ?? "source", (book.fanficMode ?? "canon") as "canon");
  2528. broadcast("fanfic:refresh:complete", { bookId: id });
  2529. return c.json({ ok: true });
  2530. } catch (e) {
  2531. broadcast("fanfic:refresh:error", { bookId: id, error: String(e) });
  2532. return c.json({ error: String(e) }, 500);
  2533. }
  2534. });
  2535. // --- Radar Scan ---
  2536. app.post("/api/v1/radar/scan", async (c) => {
  2537. broadcast("radar:start", {});
  2538. try {
  2539. const pipeline = new PipelineRunner(await buildPipelineConfig());
  2540. const result = await pipeline.runRadar();
  2541. broadcast("radar:complete", { result });
  2542. return c.json(result);
  2543. } catch (e) {
  2544. broadcast("radar:error", { error: String(e) });
  2545. return c.json({ error: String(e) }, 500);
  2546. }
  2547. });
  2548. // --- Doctor (environment health check) ---
  2549. app.get("/api/v1/doctor", async (c) => {
  2550. const { existsSync } = await import("node:fs");
  2551. const { GLOBAL_ENV_PATH } = await import("@actalk/inkos-core");
  2552. const checks = {
  2553. inkosJson: existsSync(join(root, "inkos.json")),
  2554. projectEnv: existsSync(join(root, ".env")),
  2555. globalEnv: existsSync(GLOBAL_ENV_PATH),
  2556. booksDir: existsSync(join(root, "books")),
  2557. llmConnected: false,
  2558. bookCount: 0,
  2559. };
  2560. try {
  2561. const books = await state.listBooks();
  2562. checks.bookCount = books.length;
  2563. } catch { /* ignore */ }
  2564. try {
  2565. const currentConfig = await loadCurrentProjectConfig({ requireApiKey: false });
  2566. const service = currentConfig.llm.service ?? currentConfig.llm.provider;
  2567. const probe = await probeServiceCapabilities({
  2568. root,
  2569. service,
  2570. apiKey: currentConfig.llm.apiKey,
  2571. baseUrl: currentConfig.llm.baseUrl,
  2572. preferredApiFormat: currentConfig.llm.apiFormat,
  2573. preferredStream: currentConfig.llm.stream,
  2574. preferredModel: currentConfig.llm.model,
  2575. proxyUrl: currentConfig.llm.proxyUrl,
  2576. });
  2577. checks.llmConnected = probe.ok;
  2578. } catch { /* ignore */ }
  2579. return c.json(checks);
  2580. });
  2581. return app;
  2582. }
  2583. // --- Standalone runner ---
  2584. export async function startStudioServer(
  2585. root: string,
  2586. port = 4567,
  2587. options?: { readonly staticDir?: string },
  2588. ): Promise<void> {
  2589. const config = await loadProjectConfig(root, { consumer: "studio", requireApiKey: false });
  2590. const app = createStudioServer(config, root);
  2591. // Serve frontend static files — single process for API + frontend
  2592. if (options?.staticDir) {
  2593. const { readFile: readFileFs } = await import("node:fs/promises");
  2594. const { join: joinPath } = await import("node:path");
  2595. const { existsSync } = await import("node:fs");
  2596. // Serve static assets (js, css, etc.)
  2597. app.get("/assets/*", async (c) => {
  2598. const filePath = joinPath(options.staticDir!, c.req.path);
  2599. try {
  2600. const content = await readFileFs(filePath);
  2601. const ext = filePath.split(".").pop() ?? "";
  2602. const contentTypes: Record<string, string> = {
  2603. js: "application/javascript",
  2604. css: "text/css",
  2605. svg: "image/svg+xml",
  2606. png: "image/png",
  2607. ico: "image/x-icon",
  2608. json: "application/json",
  2609. };
  2610. return new Response(content, {
  2611. headers: { "Content-Type": contentTypes[ext] ?? "application/octet-stream" },
  2612. });
  2613. } catch {
  2614. return c.notFound();
  2615. }
  2616. });
  2617. // SPA fallback — serve index.html for all non-API routes
  2618. const indexPath = joinPath(options.staticDir!, "index.html");
  2619. if (existsSync(indexPath)) {
  2620. const indexHtml = await readFileFs(indexPath, "utf-8");
  2621. app.get("*", (c) => {
  2622. if (c.req.path.startsWith("/api/v1/")) return c.notFound();
  2623. return c.html(indexHtml);
  2624. });
  2625. }
  2626. }
  2627. console.log(`InkOS Studio running on http://localhost:${port}`);
  2628. serve({ fetch: app.fetch, port });
  2629. }