server.ts 102 KB

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