server.ts 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447
  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. persistBookSession,
  19. appendBookSessionMessage,
  20. createAndPersistBookSession,
  21. renameBookSession,
  22. updateSessionTitle,
  23. deleteBookSession,
  24. migrateBookSession,
  25. SessionAlreadyMigratedError,
  26. runAgentSession,
  27. buildAgentSystemPrompt,
  28. resolveServicePreset,
  29. resolveServiceProviderFamily,
  30. resolveServiceModelsBaseUrl,
  31. resolveServiceModel,
  32. loadSecrets,
  33. saveSecrets,
  34. getServiceApiKey,
  35. listModelsForService,
  36. chatCompletion,
  37. buildExportArtifact,
  38. GLOBAL_ENV_PATH,
  39. type ResolvedModel,
  40. type PipelineConfig,
  41. type ProjectConfig,
  42. type LogSink,
  43. type LogEntry,
  44. } from "@actalk/inkos-core";
  45. import { access, readFile, readdir, writeFile } from "node:fs/promises";
  46. import { join } from "node:path";
  47. import { isSafeBookId } from "./safety.js";
  48. import { ApiError } from "./errors.js";
  49. import { buildStudioBookConfig } from "./book-create.js";
  50. // -- Pipeline stage definitions per agent type --
  51. const PIPELINE_STAGES: Record<string, string[]> = {
  52. writer: [
  53. "准备章节输入", "撰写章节草稿", "落盘最终章节",
  54. "生成最终真相文件", "校验真相文件变更", "同步记忆索引",
  55. "更新章节索引与快照",
  56. ],
  57. architect: [
  58. "生成基础设定", "保存书籍配置", "写入基础设定文件",
  59. "初始化控制文档", "创建初始快照",
  60. ],
  61. reviser: [
  62. "加载修订上下文", "修订章节", "落盘修订结果",
  63. "更新索引与快照",
  64. ],
  65. auditor: ["审计章节"],
  66. };
  67. const AGENT_LABELS: Record<string, string> = {
  68. architect: "建书", writer: "写作", auditor: "审计",
  69. reviser: "修订", exporter: "导出",
  70. };
  71. const TOOL_LABELS: Record<string, string> = {
  72. read: "读取文件", edit: "编辑文件", grep: "搜索", ls: "列目录",
  73. };
  74. function resolveToolLabel(tool: string, agent?: string): string {
  75. if (tool === "sub_agent" && agent) return AGENT_LABELS[agent] ?? agent;
  76. return TOOL_LABELS[tool] ?? tool;
  77. }
  78. function summarizeResult(result: unknown): string {
  79. if (typeof result === "string") return result.slice(0, 200);
  80. if (result && typeof result === "object") {
  81. const r = result as Record<string, unknown>;
  82. if (typeof r.content === "string") return r.content.slice(0, 200);
  83. if (typeof r.text === "string") return r.text.slice(0, 200);
  84. }
  85. return String(result).slice(0, 200);
  86. }
  87. function extractToolError(result: unknown): string {
  88. if (typeof result === "string") return result.slice(0, 500);
  89. if (result && typeof result === "object") {
  90. const r = result as Record<string, unknown>;
  91. if (typeof r.content === "string") return r.content.slice(0, 500);
  92. if (r.content && Array.isArray(r.content)) {
  93. const textPart = r.content.find((c: any) => c.type === "text");
  94. if (textPart) return (textPart as any).text?.slice(0, 500) ?? "";
  95. }
  96. }
  97. return String(result).slice(0, 500);
  98. }
  99. function normalizeGeneratedSessionTitle(raw: string): string | null {
  100. const compact = raw
  101. .replace(/[\r\n]+/g, " ")
  102. .replace(/[“”"「」]/g, "")
  103. .trim()
  104. .slice(0, 20);
  105. return compact.length > 0 ? compact : null;
  106. }
  107. interface CollectedToolExec {
  108. id: string;
  109. tool: string;
  110. agent?: string;
  111. label: string;
  112. status: "running" | "completed" | "error";
  113. args?: Record<string, unknown>;
  114. result?: string;
  115. error?: string;
  116. stages?: Array<{ label: string; status: "pending" | "completed" }>;
  117. startedAt: number;
  118. completedAt?: number;
  119. }
  120. // --- Event bus for SSE ---
  121. type EventHandler = (event: string, data: unknown) => void;
  122. const subscribers = new Set<EventHandler>();
  123. const bookCreateStatus = new Map<string, { status: "creating" | "error"; error?: string }>();
  124. interface ServiceConfigEntry {
  125. service: string;
  126. name?: string;
  127. baseUrl?: string;
  128. temperature?: number;
  129. maxTokens?: number;
  130. apiFormat?: "chat" | "responses";
  131. stream?: boolean;
  132. }
  133. type LLMConfigSource = "env" | "studio";
  134. interface EnvConfigSummary {
  135. detected: boolean;
  136. provider: string | null;
  137. baseUrl: string | null;
  138. model: string | null;
  139. hasApiKey: boolean;
  140. }
  141. interface EnvConfigStatus {
  142. project: EnvConfigSummary;
  143. global: EnvConfigSummary;
  144. effectiveSource: "project" | "global" | null;
  145. }
  146. interface ServiceProbeResult {
  147. ok: boolean;
  148. models: Array<{ id: string; name: string }>;
  149. selectedModel?: string;
  150. apiFormat?: "chat" | "responses";
  151. stream?: boolean;
  152. baseUrl?: string;
  153. modelsSource?: "api" | "fallback";
  154. error?: string;
  155. }
  156. function broadcast(event: string, data: unknown): void {
  157. for (const handler of subscribers) {
  158. handler(event, data);
  159. }
  160. }
  161. function isCustomServiceId(serviceId: string): boolean {
  162. return serviceId === "custom" || serviceId.startsWith("custom:");
  163. }
  164. function serviceConfigKey(entry: ServiceConfigEntry): string {
  165. return entry.service === "custom" ? `custom:${entry.name ?? "Custom"}` : entry.service;
  166. }
  167. function normalizeServiceEntry(serviceId: string, value: Record<string, unknown>): ServiceConfigEntry {
  168. if (serviceId.startsWith("custom:")) {
  169. return {
  170. service: "custom",
  171. name: decodeURIComponent(serviceId.slice("custom:".length)),
  172. ...(typeof value.baseUrl === "string" && value.baseUrl.length > 0 ? { baseUrl: value.baseUrl } : {}),
  173. ...(typeof value.temperature === "number" ? { temperature: value.temperature } : {}),
  174. ...(typeof value.maxTokens === "number" ? { maxTokens: value.maxTokens } : {}),
  175. ...(value.apiFormat === "chat" || value.apiFormat === "responses" ? { apiFormat: value.apiFormat } : {}),
  176. ...(typeof value.stream === "boolean" ? { stream: value.stream } : {}),
  177. };
  178. }
  179. if (serviceId === "custom") {
  180. return {
  181. service: "custom",
  182. ...(typeof value.name === "string" && value.name.length > 0 ? { name: value.name } : {}),
  183. ...(typeof value.baseUrl === "string" && value.baseUrl.length > 0 ? { baseUrl: value.baseUrl } : {}),
  184. ...(typeof value.temperature === "number" ? { temperature: value.temperature } : {}),
  185. ...(typeof value.maxTokens === "number" ? { maxTokens: value.maxTokens } : {}),
  186. ...(value.apiFormat === "chat" || value.apiFormat === "responses" ? { apiFormat: value.apiFormat } : {}),
  187. ...(typeof value.stream === "boolean" ? { stream: value.stream } : {}),
  188. };
  189. }
  190. return {
  191. service: serviceId,
  192. ...(typeof value.temperature === "number" ? { temperature: value.temperature } : {}),
  193. ...(typeof value.maxTokens === "number" ? { maxTokens: value.maxTokens } : {}),
  194. ...(value.apiFormat === "chat" || value.apiFormat === "responses" ? { apiFormat: value.apiFormat } : {}),
  195. ...(typeof value.stream === "boolean" ? { stream: value.stream } : {}),
  196. };
  197. }
  198. function normalizeConfigSource(value: unknown): LLMConfigSource {
  199. return value === "studio" ? "studio" : "env";
  200. }
  201. function normalizeServiceConfig(raw: unknown): ServiceConfigEntry[] {
  202. if (Array.isArray(raw)) {
  203. return raw
  204. .filter((entry): entry is Record<string, unknown> => Boolean(entry) && typeof entry === "object")
  205. .map((entry) => ({
  206. service: typeof entry.service === "string" && entry.service.length > 0 ? entry.service : "custom",
  207. ...(typeof entry.name === "string" && entry.name.length > 0 ? { name: entry.name } : {}),
  208. ...(typeof entry.baseUrl === "string" && entry.baseUrl.length > 0 ? { baseUrl: entry.baseUrl } : {}),
  209. ...(typeof entry.temperature === "number" ? { temperature: entry.temperature } : {}),
  210. ...(typeof entry.maxTokens === "number" ? { maxTokens: entry.maxTokens } : {}),
  211. ...(entry.apiFormat === "chat" || entry.apiFormat === "responses" ? { apiFormat: entry.apiFormat } : {}),
  212. ...(typeof entry.stream === "boolean" ? { stream: entry.stream } : {}),
  213. }));
  214. }
  215. if (raw && typeof raw === "object") {
  216. return Object.entries(raw as Record<string, unknown>)
  217. .filter(([, value]) => value && typeof value === "object")
  218. .map(([serviceId, value]) => normalizeServiceEntry(serviceId, value as Record<string, unknown>));
  219. }
  220. return [];
  221. }
  222. function mergeServiceConfig(existing: ServiceConfigEntry[], updates: ServiceConfigEntry[]): ServiceConfigEntry[] {
  223. const merged = new Map(existing.map((entry) => [serviceConfigKey(entry), entry]));
  224. for (const update of updates) {
  225. merged.set(serviceConfigKey(update), update);
  226. }
  227. return [...merged.values()];
  228. }
  229. async function loadRawConfig(root: string): Promise<Record<string, unknown>> {
  230. const configPath = join(root, "inkos.json");
  231. const raw = await readFile(configPath, "utf-8");
  232. return JSON.parse(raw) as Record<string, unknown>;
  233. }
  234. async function saveRawConfig(root: string, config: Record<string, unknown>): Promise<void> {
  235. await writeFile(join(root, "inkos.json"), JSON.stringify(config, null, 2), "utf-8");
  236. }
  237. async function readEnvConfigSummary(path: string): Promise<EnvConfigSummary> {
  238. try {
  239. const raw = await readFile(path, "utf-8");
  240. const values = new Map<string, string>();
  241. for (const line of raw.split(/\r?\n/)) {
  242. const trimmed = line.trim();
  243. if (!trimmed || trimmed.startsWith("#")) continue;
  244. const match = trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
  245. if (!match) continue;
  246. const [, key, value] = match;
  247. values.set(key, value.trim());
  248. }
  249. const provider = values.get("INKOS_LLM_PROVIDER") ?? null;
  250. const baseUrl = values.get("INKOS_LLM_BASE_URL") ?? null;
  251. const model = values.get("INKOS_LLM_MODEL") ?? null;
  252. const apiKey = values.get("INKOS_LLM_API_KEY") ?? "";
  253. const detected = Boolean(provider || baseUrl || model || apiKey);
  254. return {
  255. detected,
  256. provider,
  257. baseUrl,
  258. model,
  259. hasApiKey: apiKey.length > 0,
  260. };
  261. } catch {
  262. return {
  263. detected: false,
  264. provider: null,
  265. baseUrl: null,
  266. model: null,
  267. hasApiKey: false,
  268. };
  269. }
  270. }
  271. async function readEnvConfigStatus(root: string): Promise<EnvConfigStatus> {
  272. const project = await readEnvConfigSummary(join(root, ".env"));
  273. const global = await readEnvConfigSummary(GLOBAL_ENV_PATH);
  274. return {
  275. project,
  276. global,
  277. effectiveSource: project.detected ? "project" : global.detected ? "global" : null,
  278. };
  279. }
  280. async function resolveConfiguredServiceBaseUrl(root: string, serviceId: string, inlineBaseUrl?: string): Promise<string | undefined> {
  281. if (inlineBaseUrl?.trim()) return inlineBaseUrl.trim();
  282. if (!isCustomServiceId(serviceId)) {
  283. return resolveServicePreset(serviceId)?.baseUrl;
  284. }
  285. try {
  286. const config = await loadRawConfig(root);
  287. const services = normalizeServiceConfig((config.llm as Record<string, unknown> | undefined)?.services);
  288. const matched = services.find((entry) => serviceConfigKey(entry) === serviceId);
  289. return matched?.baseUrl;
  290. } catch {
  291. return undefined;
  292. }
  293. }
  294. async function resolveConfiguredServiceEntry(root: string, serviceId: string): Promise<ServiceConfigEntry | undefined> {
  295. try {
  296. const config = await loadRawConfig(root);
  297. const services = normalizeServiceConfig((config.llm as Record<string, unknown> | undefined)?.services);
  298. return services.find((entry) => serviceConfigKey(entry) === serviceId);
  299. } catch {
  300. return undefined;
  301. }
  302. }
  303. function buildProbePlans(
  304. preferredApiFormat: "chat" | "responses" | undefined,
  305. preferredStream: boolean | undefined,
  306. ): Array<{ apiFormat: "chat" | "responses"; stream: boolean }> {
  307. const candidates: Array<{ apiFormat: "chat" | "responses"; stream: boolean }> = [];
  308. const seen = new Set<string>();
  309. const push = (apiFormat: "chat" | "responses", stream: boolean) => {
  310. const key = `${apiFormat}:${stream ? "1" : "0"}`;
  311. if (seen.has(key)) return;
  312. seen.add(key);
  313. candidates.push({ apiFormat, stream });
  314. };
  315. if (preferredApiFormat) {
  316. push(preferredApiFormat, preferredStream ?? false);
  317. push(preferredApiFormat, !(preferredStream ?? false));
  318. }
  319. const alternate = preferredApiFormat === "responses" ? "chat" : "responses";
  320. push(alternate, false);
  321. push(alternate, true);
  322. push("chat", false);
  323. push("chat", true);
  324. push("responses", false);
  325. push("responses", true);
  326. return candidates;
  327. }
  328. function buildModelCandidates(args: {
  329. preferredModel?: string;
  330. configModel?: string;
  331. envModel?: string | null;
  332. discoveredModels: Array<{ id: string; name: string }>;
  333. }): string[] {
  334. const seen = new Set<string>();
  335. const candidates: string[] = [];
  336. const push = (value: string | null | undefined) => {
  337. if (!value || value.trim().length === 0) return;
  338. const id = value.trim();
  339. if (seen.has(id)) return;
  340. seen.add(id);
  341. candidates.push(id);
  342. };
  343. push(args.preferredModel);
  344. push(args.configModel);
  345. push(args.envModel ?? undefined);
  346. for (const model of args.discoveredModels) push(model.id);
  347. push("gpt-5.4");
  348. push("gpt-4o");
  349. push("claude-sonnet-4-6");
  350. push("MiniMax-M2.7");
  351. push("kimi-k2.5");
  352. return candidates;
  353. }
  354. async function fetchModelsFromServiceBaseUrl(
  355. serviceId: string,
  356. baseUrl: string,
  357. apiKey: string,
  358. ): Promise<{ models: Array<{ id: string; name: string }>; error?: string; authFailed?: boolean }> {
  359. const modelsBaseUrl = isCustomServiceId(serviceId)
  360. ? baseUrl
  361. : resolveServiceModelsBaseUrl(serviceId) ?? baseUrl;
  362. const modelsUrl = modelsBaseUrl.replace(/\/$/, "") + "/models";
  363. try {
  364. const res = await fetch(modelsUrl, {
  365. headers: { Authorization: `Bearer ${apiKey}` },
  366. signal: AbortSignal.timeout(10_000),
  367. });
  368. if (!res.ok) {
  369. const body = await res.text().catch(() => "");
  370. return {
  371. models: [],
  372. error: `服务商返回 ${res.status}: ${body.slice(0, 200)}`,
  373. authFailed: res.status === 401 || res.status === 403,
  374. };
  375. }
  376. const json = await res.json() as { data?: Array<{ id: string }> };
  377. return {
  378. models: (json.data ?? []).map((m) => ({ id: m.id, name: m.id })),
  379. };
  380. } catch (error) {
  381. return {
  382. models: [],
  383. error: error instanceof Error ? error.message : String(error),
  384. };
  385. }
  386. }
  387. async function probeServiceCapabilities(args: {
  388. root: string;
  389. service: string;
  390. apiKey: string;
  391. baseUrl: string;
  392. preferredApiFormat?: "chat" | "responses";
  393. preferredStream?: boolean;
  394. preferredModel?: string;
  395. }): Promise<ServiceProbeResult> {
  396. const rawConfig = await loadRawConfig(args.root).catch(() => ({} as Record<string, unknown>));
  397. const llm = (rawConfig.llm as Record<string, unknown> | undefined) ?? {};
  398. const envConfig = await readEnvConfigStatus(args.root);
  399. const envModel = envConfig.effectiveSource === "project"
  400. ? envConfig.project.model
  401. : envConfig.effectiveSource === "global"
  402. ? envConfig.global.model
  403. : null;
  404. const baseService = isCustomServiceId(args.service) ? "custom" : args.service;
  405. const modelsResponse = await fetchModelsFromServiceBaseUrl(baseService, args.baseUrl, args.apiKey);
  406. if (modelsResponse.authFailed) {
  407. return {
  408. ok: false,
  409. models: [],
  410. error: modelsResponse.error ?? "API Key 无效或无权访问模型列表。",
  411. };
  412. }
  413. const discoveredModels = modelsResponse.models;
  414. // For services with knownModels, use their first model as top candidate — not the global default
  415. const preset = resolveServicePreset(baseService);
  416. const serviceFirstModel = preset?.knownModels?.[0];
  417. const modelCandidates = buildModelCandidates({
  418. preferredModel: args.preferredModel ?? serviceFirstModel,
  419. configModel: typeof llm.defaultModel === "string" ? llm.defaultModel : typeof llm.model === "string" ? llm.model : undefined,
  420. envModel,
  421. discoveredModels,
  422. });
  423. if (modelCandidates.length === 0) {
  424. return {
  425. ok: false,
  426. models: [],
  427. error: "无法自动确定模型,请先填写可用模型或提供支持 /models 的服务端点。",
  428. };
  429. }
  430. let lastError = modelsResponse.error ?? "自动探测失败";
  431. for (const model of modelCandidates) {
  432. for (const plan of buildProbePlans(args.preferredApiFormat, args.preferredStream)) {
  433. const client = createLLMClient({
  434. provider: resolveServiceProviderFamily(baseService) ?? "openai",
  435. service: baseService,
  436. configSource: "studio",
  437. baseUrl: args.baseUrl,
  438. apiKey: args.apiKey.trim(),
  439. model,
  440. temperature: 0.7,
  441. maxTokens: 2048,
  442. thinkingBudget: 0,
  443. apiFormat: plan.apiFormat,
  444. stream: plan.stream,
  445. } as ProjectConfig["llm"]);
  446. try {
  447. await chatCompletion(client, model, [{ role: "user", content: "ping" }], { maxTokens: 2048 });
  448. const models = discoveredModels.length > 0
  449. ? discoveredModels
  450. : preset?.knownModels?.map((id) => ({ id, name: id })) ?? [{ id: model, name: model }];
  451. return {
  452. ok: true,
  453. models,
  454. selectedModel: model,
  455. apiFormat: plan.apiFormat,
  456. stream: plan.stream,
  457. baseUrl: args.baseUrl,
  458. modelsSource: discoveredModels.length > 0 ? "api" : "fallback",
  459. };
  460. } catch (error) {
  461. lastError = error instanceof Error ? error.message : String(error);
  462. }
  463. }
  464. }
  465. return {
  466. ok: false,
  467. models: discoveredModels,
  468. error: lastError,
  469. };
  470. }
  471. // --- Server factory ---
  472. export function createStudioServer(initialConfig: ProjectConfig, root: string) {
  473. const app = new Hono();
  474. const state = new StateManager(root);
  475. let cachedConfig = initialConfig;
  476. app.use("/*", cors());
  477. // Structured error handler — ApiError returns typed JSON, others return 500
  478. app.onError((error, c) => {
  479. if (error instanceof ApiError) {
  480. return c.json({ error: { code: error.code, message: error.message } }, error.status as 400);
  481. }
  482. return c.json(
  483. { error: { code: "INTERNAL_ERROR", message: "Unexpected server error." } },
  484. 500,
  485. );
  486. });
  487. // BookId validation middleware — blocks path traversal on all book routes
  488. app.use("/api/v1/books/:id/*", async (c, next) => {
  489. const bookId = c.req.param("id");
  490. if (!isSafeBookId(bookId)) {
  491. throw new ApiError(400, "INVALID_BOOK_ID", `Invalid book ID: "${bookId}"`);
  492. }
  493. await next();
  494. });
  495. app.use("/api/v1/books/:id", async (c, next) => {
  496. const bookId = c.req.param("id");
  497. if (!isSafeBookId(bookId)) {
  498. throw new ApiError(400, "INVALID_BOOK_ID", `Invalid book ID: "${bookId}"`);
  499. }
  500. await next();
  501. });
  502. // Logger sink that broadcasts to SSE
  503. const sseSink: LogSink = {
  504. write(entry: LogEntry): void {
  505. broadcast("log", { level: entry.level, tag: entry.tag, message: entry.message });
  506. },
  507. };
  508. // Logger sink that prints to server terminal
  509. const consoleSink: LogSink = {
  510. write(entry: LogEntry): void {
  511. const prefix = `[${entry.tag}]`;
  512. if (entry.level === "warn") console.warn(prefix, entry.message);
  513. else if (entry.level === "error") console.error(prefix, entry.message);
  514. else console.log(prefix, entry.message);
  515. },
  516. };
  517. async function loadCurrentProjectConfig(
  518. options?: { readonly requireApiKey?: boolean },
  519. ): Promise<ProjectConfig> {
  520. const freshConfig = await loadProjectConfig(root, options);
  521. cachedConfig = freshConfig;
  522. return freshConfig;
  523. }
  524. async function buildPipelineConfig(
  525. overrides?: Partial<Pick<PipelineConfig, "externalContext" | "client" | "model">> & {
  526. readonly currentConfig?: ProjectConfig;
  527. readonly sessionIdForSSE?: string;
  528. },
  529. ): Promise<PipelineConfig> {
  530. const currentConfig = overrides?.currentConfig ?? await loadCurrentProjectConfig();
  531. const scopedSseSink: LogSink = overrides?.sessionIdForSSE
  532. ? {
  533. write(entry) {
  534. broadcast("log", {
  535. sessionId: overrides.sessionIdForSSE,
  536. level: entry.level,
  537. tag: entry.tag,
  538. message: entry.message,
  539. });
  540. },
  541. }
  542. : sseSink;
  543. const logger = createLogger({ tag: "studio", sinks: [scopedSseSink, consoleSink] });
  544. return {
  545. client: overrides?.client ?? createLLMClient(currentConfig.llm),
  546. model: overrides?.model ?? currentConfig.llm.model,
  547. projectRoot: root,
  548. defaultLLMConfig: currentConfig.llm,
  549. modelOverrides: currentConfig.modelOverrides,
  550. notifyChannels: currentConfig.notify,
  551. logger,
  552. onStreamProgress: (progress) => {
  553. broadcast("llm:progress", {
  554. ...(overrides?.sessionIdForSSE ? { sessionId: overrides.sessionIdForSSE } : {}),
  555. status: progress.status,
  556. elapsedMs: progress.elapsedMs,
  557. totalChars: progress.totalChars,
  558. chineseChars: progress.chineseChars,
  559. });
  560. },
  561. externalContext: overrides?.externalContext,
  562. };
  563. }
  564. // --- Books ---
  565. app.get("/api/v1/books", async (c) => {
  566. const bookIds = await state.listBooks();
  567. const books = await Promise.all(
  568. bookIds.map(async (id) => {
  569. const book = await state.loadBookConfig(id);
  570. const nextChapter = await state.getNextChapterNumber(id);
  571. return { ...book, chaptersWritten: nextChapter - 1 };
  572. }),
  573. );
  574. return c.json({ books });
  575. });
  576. app.get("/api/v1/books/:id", async (c) => {
  577. const id = c.req.param("id");
  578. try {
  579. const book = await state.loadBookConfig(id);
  580. const chapters = await state.loadChapterIndex(id);
  581. const nextChapter = await state.getNextChapterNumber(id);
  582. return c.json({ book, chapters, nextChapter });
  583. } catch {
  584. return c.json({ error: `Book "${id}" not found` }, 404);
  585. }
  586. });
  587. // --- Genres ---
  588. app.get("/api/v1/genres", async (c) => {
  589. const { listAvailableGenres, readGenreProfile } = await import("@actalk/inkos-core");
  590. const rawGenres = await listAvailableGenres(root);
  591. const genres = await Promise.all(
  592. rawGenres.map(async (g) => {
  593. try {
  594. const { profile } = await readGenreProfile(root, g.id);
  595. return { ...g, language: profile.language ?? "zh" };
  596. } catch {
  597. return { ...g, language: "zh" };
  598. }
  599. }),
  600. );
  601. return c.json({ genres });
  602. });
  603. // --- Book Create ---
  604. app.post("/api/v1/books/create", async (c) => {
  605. const body = await c.req.json<{
  606. title: string;
  607. genre: string;
  608. language?: string;
  609. platform?: string;
  610. chapterWordCount?: number;
  611. targetChapters?: number;
  612. }>();
  613. const now = new Date().toISOString();
  614. const bookConfig = buildStudioBookConfig(body, now);
  615. const bookId = bookConfig.id;
  616. const bookDir = state.bookDir(bookId);
  617. try {
  618. await access(join(bookDir, "book.json"));
  619. await access(join(bookDir, "story", "story_bible.md"));
  620. return c.json({ error: `Book "${bookId}" already exists` }, 409);
  621. } catch {
  622. // The target book is not fully initialized yet, so creation can continue.
  623. }
  624. broadcast("book:creating", { bookId, title: body.title });
  625. bookCreateStatus.set(bookId, { status: "creating" });
  626. const pipeline = new PipelineRunner(await buildPipelineConfig());
  627. const tools = createInteractionToolsFromDeps(pipeline, state);
  628. processProjectInteractionRequest({
  629. projectRoot: root,
  630. request: {
  631. intent: "create_book",
  632. title: body.title,
  633. genre: body.genre,
  634. language: body.language === "en" ? "en" : body.language === "zh" ? "zh" : undefined,
  635. platform: body.platform,
  636. chapterWordCount: body.chapterWordCount,
  637. targetChapters: body.targetChapters,
  638. },
  639. tools,
  640. }).then(
  641. (result: {
  642. readonly session: { readonly activeBookId?: string };
  643. readonly details?: Readonly<Record<string, unknown>>;
  644. }) => {
  645. const createdBookId = (result.details?.bookId as string | undefined) ?? result.session.activeBookId ?? bookId;
  646. bookCreateStatus.delete(createdBookId);
  647. broadcast("book:created", { bookId: createdBookId });
  648. },
  649. (e: unknown) => {
  650. const error = e instanceof Error ? e.message : String(e);
  651. bookCreateStatus.set(bookId, { status: "error", error });
  652. broadcast("book:error", { bookId, error });
  653. },
  654. );
  655. return c.json({ status: "creating", bookId });
  656. });
  657. app.get("/api/v1/books/:id/create-status", async (c) => {
  658. const id = c.req.param("id");
  659. const status = bookCreateStatus.get(id);
  660. if (!status) {
  661. return c.json({ status: "missing" }, 404);
  662. }
  663. return c.json(status);
  664. });
  665. // --- Chapters ---
  666. app.get("/api/v1/books/:id/chapters/:num", async (c) => {
  667. const id = c.req.param("id");
  668. const num = parseInt(c.req.param("num"), 10);
  669. const bookDir = state.bookDir(id);
  670. const chaptersDir = join(bookDir, "chapters");
  671. try {
  672. const files = await readdir(chaptersDir);
  673. const paddedNum = String(num).padStart(4, "0");
  674. const match = files.find((f) => f.startsWith(paddedNum) && f.endsWith(".md"));
  675. if (!match) return c.json({ error: "Chapter not found" }, 404);
  676. const content = await readFile(join(chaptersDir, match), "utf-8");
  677. return c.json({ chapterNumber: num, filename: match, content });
  678. } catch {
  679. return c.json({ error: "Chapter not found" }, 404);
  680. }
  681. });
  682. // --- Chapter Save ---
  683. app.put("/api/v1/books/:id/chapters/:num", async (c) => {
  684. const id = c.req.param("id");
  685. const num = parseInt(c.req.param("num"), 10);
  686. const bookDir = state.bookDir(id);
  687. const chaptersDir = join(bookDir, "chapters");
  688. const { content } = await c.req.json<{ content: string }>();
  689. try {
  690. const files = await readdir(chaptersDir);
  691. const paddedNum = String(num).padStart(4, "0");
  692. const match = files.find((f) => f.startsWith(paddedNum) && f.endsWith(".md"));
  693. if (!match) return c.json({ error: "Chapter not found" }, 404);
  694. const { writeFile: writeFileFs } = await import("node:fs/promises");
  695. await writeFileFs(join(chaptersDir, match), content, "utf-8");
  696. return c.json({ ok: true, chapterNumber: num });
  697. } catch (e) {
  698. return c.json({ error: String(e) }, 500);
  699. }
  700. });
  701. // --- Truth files ---
  702. const TRUTH_FILES = [
  703. "author_intent.md", "current_focus.md",
  704. "story_bible.md", "volume_outline.md", "current_state.md",
  705. "particle_ledger.md", "pending_hooks.md", "chapter_summaries.md",
  706. "subplot_board.md", "emotional_arcs.md", "character_matrix.md",
  707. "style_guide.md", "parent_canon.md", "fanfic_canon.md", "book_rules.md",
  708. ];
  709. app.get("/api/v1/books/:id/truth/:file", async (c) => {
  710. const id = c.req.param("id");
  711. const file = c.req.param("file");
  712. if (!TRUTH_FILES.includes(file)) {
  713. return c.json({ error: "Invalid truth file" }, 400);
  714. }
  715. const bookDir = state.bookDir(id);
  716. try {
  717. const content = await readFile(join(bookDir, "story", file), "utf-8");
  718. return c.json({ file, content });
  719. } catch {
  720. return c.json({ file, content: null });
  721. }
  722. });
  723. // --- Analytics ---
  724. app.get("/api/v1/books/:id/analytics", async (c) => {
  725. const id = c.req.param("id");
  726. try {
  727. const chapters = await state.loadChapterIndex(id);
  728. return c.json(computeAnalytics(id, chapters));
  729. } catch {
  730. return c.json({ error: `Book "${id}" not found` }, 404);
  731. }
  732. });
  733. // --- Actions ---
  734. app.post("/api/v1/books/:id/write-next", async (c) => {
  735. const id = c.req.param("id");
  736. const body = await c.req.json<{ wordCount?: number }>().catch(() => ({ wordCount: undefined }));
  737. broadcast("write:start", { bookId: id });
  738. // Fire and forget — progress/completion/errors pushed via SSE
  739. const pipeline = new PipelineRunner(await buildPipelineConfig());
  740. pipeline.writeNextChapter(id, body.wordCount).then(
  741. (result) => {
  742. broadcast("write:complete", { bookId: id, chapterNumber: result.chapterNumber, status: result.status, title: result.title, wordCount: result.wordCount });
  743. },
  744. (e) => {
  745. broadcast("write:error", { bookId: id, error: e instanceof Error ? e.message : String(e) });
  746. },
  747. );
  748. return c.json({ status: "writing", bookId: id });
  749. });
  750. app.post("/api/v1/books/:id/draft", async (c) => {
  751. const id = c.req.param("id");
  752. const body = await c.req.json<{ wordCount?: number; context?: string }>().catch(() => ({ wordCount: undefined, context: undefined }));
  753. broadcast("draft:start", { bookId: id });
  754. const pipeline = new PipelineRunner(await buildPipelineConfig());
  755. pipeline.writeDraft(id, body.context, body.wordCount).then(
  756. (result) => {
  757. broadcast("draft:complete", { bookId: id, chapterNumber: result.chapterNumber, title: result.title, wordCount: result.wordCount });
  758. },
  759. (e) => {
  760. broadcast("draft:error", { bookId: id, error: e instanceof Error ? e.message : String(e) });
  761. },
  762. );
  763. return c.json({ status: "drafting", bookId: id });
  764. });
  765. app.post("/api/v1/books/:id/chapters/:num/approve", async (c) => {
  766. const id = c.req.param("id");
  767. const num = parseInt(c.req.param("num"), 10);
  768. try {
  769. const index = await state.loadChapterIndex(id);
  770. const updated = index.map((ch) =>
  771. ch.number === num ? { ...ch, status: "approved" as const } : ch,
  772. );
  773. await state.saveChapterIndex(id, updated);
  774. return c.json({ ok: true, chapterNumber: num, status: "approved" });
  775. } catch (e) {
  776. return c.json({ error: String(e) }, 500);
  777. }
  778. });
  779. app.post("/api/v1/books/:id/chapters/:num/reject", async (c) => {
  780. const id = c.req.param("id");
  781. const num = parseInt(c.req.param("num"), 10);
  782. try {
  783. const index = await state.loadChapterIndex(id);
  784. const target = index.find((ch) => ch.number === num);
  785. if (!target) {
  786. return c.json({ error: `Chapter ${num} not found` }, 404);
  787. }
  788. const rollbackTarget = num - 1;
  789. const discarded = await state.rollbackToChapter(id, rollbackTarget);
  790. return c.json({
  791. ok: true,
  792. chapterNumber: num,
  793. status: "rejected",
  794. rolledBackTo: rollbackTarget,
  795. discarded,
  796. });
  797. } catch (e) {
  798. return c.json({ error: String(e) }, 500);
  799. }
  800. });
  801. // --- SSE ---
  802. app.get("/api/v1/events", (c) => {
  803. return streamSSE(c, async (stream) => {
  804. const handler: EventHandler = (event, data) => {
  805. stream.writeSSE({ event, data: JSON.stringify(data) });
  806. };
  807. subscribers.add(handler);
  808. // Keep alive
  809. const keepAlive = setInterval(() => {
  810. stream.writeSSE({ event: "ping", data: "" });
  811. }, 30000);
  812. stream.onAbort(() => {
  813. subscribers.delete(handler);
  814. clearInterval(keepAlive);
  815. });
  816. // Block until aborted
  817. await new Promise(() => {});
  818. });
  819. });
  820. // --- Model discovery ---
  821. app.get("/api/v1/services", async (c) => {
  822. const secrets = await loadSecrets(root);
  823. const SERVICE_KEYS = [
  824. "openai", "anthropic", "deepseek", "moonshot", "minimax",
  825. "bailian", "zhipu", "siliconflow", "ppio", "openrouter", "ollama",
  826. ];
  827. // Fast: only check connection status from secrets, no external API calls
  828. const services = SERVICE_KEYS.map((key) => {
  829. const preset = resolveServicePreset(key);
  830. return {
  831. service: key,
  832. label: preset?.label ?? key,
  833. connected: Boolean(secrets.services[key]?.apiKey),
  834. };
  835. });
  836. // Add custom services from inkos.json
  837. try {
  838. const config = await loadRawConfig(root);
  839. for (const svc of normalizeServiceConfig((config.llm as Record<string, unknown> | undefined)?.services)) {
  840. if (svc.service === "custom") {
  841. const secretKey = `custom:${svc.name}`;
  842. services.push({
  843. service: secretKey,
  844. label: svc.name ?? "Custom",
  845. connected: Boolean(secrets.services[secretKey]?.apiKey),
  846. });
  847. }
  848. }
  849. } catch { /* no config file */ }
  850. return c.json({ services });
  851. });
  852. app.get("/api/v1/services/config", async (c) => {
  853. const config = await loadRawConfig(root);
  854. const llm = (config.llm as Record<string, unknown> | undefined) ?? {};
  855. const services = normalizeServiceConfig(llm.services);
  856. const envConfig = await readEnvConfigStatus(root);
  857. return c.json({
  858. services,
  859. defaultModel: llm.defaultModel ?? null,
  860. configSource: normalizeConfigSource(llm.configSource),
  861. envConfig,
  862. });
  863. });
  864. app.put("/api/v1/services/config", async (c) => {
  865. const body = await c.req.json<{ services?: unknown; defaultModel?: string; configSource?: LLMConfigSource; service?: string }>();
  866. const config = await loadRawConfig(root);
  867. config.llm = config.llm ?? {};
  868. const llm = config.llm as Record<string, unknown>;
  869. if (body.services !== undefined) {
  870. const existingServices = normalizeServiceConfig(llm.services);
  871. const incomingServices = normalizeServiceConfig(body.services);
  872. llm.services = mergeServiceConfig(existingServices, incomingServices);
  873. }
  874. if (body.defaultModel !== undefined) {
  875. llm.defaultModel = body.defaultModel;
  876. }
  877. if (body.configSource !== undefined) {
  878. llm.configSource = normalizeConfigSource(body.configSource);
  879. }
  880. if (body.service !== undefined) {
  881. llm.service = body.service;
  882. }
  883. await saveRawConfig(root, config);
  884. return c.json({ ok: true });
  885. });
  886. app.post("/api/v1/services/:service/test", async (c) => {
  887. const service = c.req.param("service");
  888. const { apiKey, baseUrl, apiFormat, stream } = await c.req.json<{
  889. apiKey: string;
  890. baseUrl?: string;
  891. apiFormat?: "chat" | "responses";
  892. stream?: boolean;
  893. }>();
  894. if (!apiKey?.trim()) {
  895. return c.json({ ok: false, error: "API Key 不能为空" }, 400);
  896. }
  897. const resolvedBaseUrl = await resolveConfiguredServiceBaseUrl(root, service, baseUrl);
  898. if (!resolvedBaseUrl) {
  899. return c.json({ ok: false, error: `未知服务商: ${service}` }, 400);
  900. }
  901. const probe = await probeServiceCapabilities({
  902. root,
  903. service,
  904. apiKey: apiKey.trim(),
  905. baseUrl: resolvedBaseUrl,
  906. preferredApiFormat: apiFormat,
  907. preferredStream: stream,
  908. });
  909. if (!probe.ok) {
  910. return c.json({ ok: false, error: probe.error ?? "连接失败" }, 400);
  911. }
  912. return c.json({
  913. ok: true,
  914. modelCount: probe.models.length,
  915. models: probe.models,
  916. selectedModel: probe.selectedModel,
  917. detected: {
  918. apiFormat: probe.apiFormat,
  919. stream: probe.stream,
  920. baseUrl: probe.baseUrl,
  921. modelsSource: probe.modelsSource,
  922. },
  923. });
  924. });
  925. app.put("/api/v1/services/:service/secret", async (c) => {
  926. const service = c.req.param("service");
  927. const { apiKey } = await c.req.json<{ apiKey: string }>();
  928. const secrets = await loadSecrets(root);
  929. if (apiKey?.trim()) {
  930. secrets.services[service] = { apiKey: apiKey.trim() };
  931. } else {
  932. delete secrets.services[service];
  933. }
  934. await saveSecrets(root, secrets);
  935. return c.json({ ok: true });
  936. });
  937. app.get("/api/v1/services/:service/secret", async (c) => {
  938. const service = c.req.param("service");
  939. const secrets = await loadSecrets(root);
  940. return c.json({
  941. apiKey: secrets.services[service]?.apiKey ?? "",
  942. });
  943. });
  944. app.get("/api/v1/services/:service/models", async (c) => {
  945. const service = c.req.param("service");
  946. const apiKey = c.req.query("apiKey") || await getServiceApiKey(root, service);
  947. // No key = no models
  948. if (!apiKey) return c.json({ models: [] });
  949. // Fast path: services with knownModels return immediately
  950. const preset = resolveServicePreset(isCustomServiceId(service) ? "custom" : service);
  951. if (preset?.knownModels && preset.knownModels.length > 0) {
  952. return c.json({
  953. models: preset.knownModels.map((id) => ({ id, name: id })),
  954. });
  955. }
  956. // Simple /models API call + fallback to pi-ai built-in list (no slow probe)
  957. const resolvedBaseUrl = await resolveConfiguredServiceBaseUrl(root, service);
  958. if (!resolvedBaseUrl) return c.json({ models: [] });
  959. const modelsBase = preset?.modelsBaseUrl ?? resolvedBaseUrl;
  960. let models: Array<{ id: string; name: string }> = [];
  961. try {
  962. const modelsUrl = modelsBase.replace(/\/$/, "") + "/models";
  963. const res = await fetch(modelsUrl, {
  964. headers: { Authorization: `Bearer ${apiKey}` },
  965. signal: AbortSignal.timeout(10_000),
  966. });
  967. if (res.ok) {
  968. const json = await res.json() as { data?: Array<{ id: string }> };
  969. models = (json.data ?? []).map((m) => ({ id: m.id, name: m.id }));
  970. }
  971. } catch { /* timeout or network error */ }
  972. if (models.length === 0) {
  973. const builtIn = await listModelsForService(service, apiKey);
  974. models = builtIn.map((m) => ({ id: m.id, name: m.name }));
  975. }
  976. return c.json({ models });
  977. });
  978. // --- Project info ---
  979. app.get("/api/v1/project", async (c) => {
  980. const currentConfig = await loadCurrentProjectConfig({ requireApiKey: false });
  981. // Check if language was explicitly set in inkos.json (not just the schema default)
  982. const raw = JSON.parse(await readFile(join(root, "inkos.json"), "utf-8"));
  983. const languageExplicit = "language" in raw && raw.language !== "";
  984. return c.json({
  985. name: currentConfig.name,
  986. language: currentConfig.language,
  987. languageExplicit,
  988. model: currentConfig.llm.model,
  989. provider: currentConfig.llm.provider,
  990. baseUrl: currentConfig.llm.baseUrl,
  991. stream: currentConfig.llm.stream,
  992. temperature: currentConfig.llm.temperature,
  993. maxTokens: currentConfig.llm.maxTokens,
  994. });
  995. });
  996. // --- Config editing ---
  997. app.put("/api/v1/project", async (c) => {
  998. const updates = await c.req.json<Record<string, unknown>>();
  999. const configPath = join(root, "inkos.json");
  1000. try {
  1001. const raw = await readFile(configPath, "utf-8");
  1002. const existing = JSON.parse(raw);
  1003. // Merge LLM settings
  1004. if (updates.temperature !== undefined) {
  1005. existing.llm.temperature = updates.temperature;
  1006. }
  1007. if (updates.maxTokens !== undefined) {
  1008. existing.llm.maxTokens = updates.maxTokens;
  1009. }
  1010. if (updates.stream !== undefined) {
  1011. existing.llm.stream = updates.stream;
  1012. }
  1013. if (updates.language === "zh" || updates.language === "en") {
  1014. existing.language = updates.language;
  1015. }
  1016. const { writeFile: writeFileFs } = await import("node:fs/promises");
  1017. await writeFileFs(configPath, JSON.stringify(existing, null, 2), "utf-8");
  1018. return c.json({ ok: true });
  1019. } catch (e) {
  1020. return c.json({ error: String(e) }, 500);
  1021. }
  1022. });
  1023. // --- Truth files browser ---
  1024. app.get("/api/v1/books/:id/truth", async (c) => {
  1025. const id = c.req.param("id");
  1026. const bookDir = state.bookDir(id);
  1027. const storyDir = join(bookDir, "story");
  1028. try {
  1029. const files = await readdir(storyDir);
  1030. const mdFiles = files.filter((f) => f.endsWith(".md") || f.endsWith(".json"));
  1031. const result = await Promise.all(
  1032. mdFiles.map(async (f) => {
  1033. const content = await readFile(join(storyDir, f), "utf-8");
  1034. return { name: f, size: content.length, preview: content.slice(0, 200) };
  1035. }),
  1036. );
  1037. return c.json({ files: result });
  1038. } catch {
  1039. return c.json({ files: [] });
  1040. }
  1041. });
  1042. // --- Daemon control ---
  1043. let schedulerInstance: import("@actalk/inkos-core").Scheduler | null = null;
  1044. app.get("/api/v1/daemon", (c) => {
  1045. return c.json({
  1046. running: schedulerInstance?.isRunning ?? false,
  1047. });
  1048. });
  1049. app.post("/api/v1/daemon/start", async (c) => {
  1050. if (schedulerInstance?.isRunning) {
  1051. return c.json({ error: "Daemon already running" }, 400);
  1052. }
  1053. try {
  1054. const { Scheduler } = await import("@actalk/inkos-core");
  1055. const currentConfig = await loadCurrentProjectConfig();
  1056. const scheduler = new Scheduler({
  1057. ...(await buildPipelineConfig()),
  1058. radarCron: currentConfig.daemon.schedule.radarCron,
  1059. writeCron: currentConfig.daemon.schedule.writeCron,
  1060. maxConcurrentBooks: currentConfig.daemon.maxConcurrentBooks,
  1061. chaptersPerCycle: currentConfig.daemon.chaptersPerCycle,
  1062. retryDelayMs: currentConfig.daemon.retryDelayMs,
  1063. cooldownAfterChapterMs: currentConfig.daemon.cooldownAfterChapterMs,
  1064. maxChaptersPerDay: currentConfig.daemon.maxChaptersPerDay,
  1065. onChapterComplete: (bookId, chapter, status) => {
  1066. broadcast("daemon:chapter", { bookId, chapter, status });
  1067. },
  1068. onError: (bookId, error) => {
  1069. broadcast("daemon:error", { bookId, error: error.message });
  1070. },
  1071. });
  1072. schedulerInstance = scheduler;
  1073. broadcast("daemon:started", {});
  1074. void scheduler.start().catch((e) => {
  1075. const error = e instanceof Error ? e : new Error(String(e));
  1076. if (schedulerInstance === scheduler) {
  1077. scheduler.stop();
  1078. schedulerInstance = null;
  1079. broadcast("daemon:stopped", {});
  1080. }
  1081. broadcast("daemon:error", { bookId: "scheduler", error: error.message });
  1082. });
  1083. return c.json({ ok: true, running: true });
  1084. } catch (e) {
  1085. return c.json({ error: String(e) }, 500);
  1086. }
  1087. });
  1088. app.post("/api/v1/daemon/stop", (c) => {
  1089. if (!schedulerInstance?.isRunning) {
  1090. return c.json({ error: "Daemon not running" }, 400);
  1091. }
  1092. schedulerInstance.stop();
  1093. schedulerInstance = null;
  1094. broadcast("daemon:stopped", {});
  1095. return c.json({ ok: true, running: false });
  1096. });
  1097. // --- Logs ---
  1098. app.get("/api/v1/logs", async (c) => {
  1099. const logPath = join(root, "inkos.log");
  1100. try {
  1101. const content = await readFile(logPath, "utf-8");
  1102. const lines = content.trim().split("\n").slice(-100);
  1103. const entries = lines.map((line) => {
  1104. try { return JSON.parse(line); } catch { return { message: line }; }
  1105. });
  1106. return c.json({ entries });
  1107. } catch {
  1108. return c.json({ entries: [] });
  1109. }
  1110. });
  1111. // --- Agent chat ---
  1112. app.get("/api/v1/interaction/session", async (c) => {
  1113. const session = await loadProjectSession(root);
  1114. const activeBookId = await resolveSessionActiveBook(root, session);
  1115. return c.json({
  1116. session: activeBookId && session.activeBookId !== activeBookId
  1117. ? { ...session, activeBookId }
  1118. : session,
  1119. activeBookId,
  1120. });
  1121. });
  1122. // -- Per-book session endpoints --
  1123. app.get("/api/v1/sessions", async (c) => {
  1124. const bookId = c.req.query("bookId");
  1125. const sessions = await listBookSessions(root, bookId === undefined ? null : bookId === "null" ? null : bookId);
  1126. return c.json({ sessions });
  1127. });
  1128. app.get("/api/v1/sessions/:sessionId", async (c) => {
  1129. const session = await loadBookSession(root, c.req.param("sessionId"));
  1130. if (!session) return c.json({ error: "Session not found" }, 404);
  1131. return c.json({ session });
  1132. });
  1133. app.post("/api/v1/sessions", async (c) => {
  1134. const body = await c.req.json<{ bookId?: string | null }>().catch(() => ({}));
  1135. const bookId = (body as { bookId?: string | null }).bookId ?? null;
  1136. const session = await createAndPersistBookSession(root, bookId);
  1137. return c.json({ session });
  1138. });
  1139. app.put("/api/v1/sessions/:sessionId", async (c) => {
  1140. const sessionId = c.req.param("sessionId");
  1141. const body = await c.req.json<{ title?: string }>().catch(() => ({}) as { title?: string });
  1142. const title = body.title?.trim();
  1143. if (!title) {
  1144. throw new ApiError(400, "INVALID_SESSION_TITLE", "Session title is required");
  1145. }
  1146. const session = await renameBookSession(root, sessionId, title);
  1147. if (!session) {
  1148. return c.json({ error: "Session not found" }, 404);
  1149. }
  1150. return c.json({ session });
  1151. });
  1152. app.delete("/api/v1/sessions/:sessionId", async (c) => {
  1153. await deleteBookSession(root, c.req.param("sessionId"));
  1154. return c.json({ ok: true });
  1155. });
  1156. app.post("/api/v1/agent", async (c) => {
  1157. const { instruction, activeBookId, sessionId: reqSessionId, model: reqModel, service: reqService } = await c.req.json<{
  1158. instruction: string;
  1159. activeBookId?: string;
  1160. sessionId?: string;
  1161. model?: string;
  1162. service?: string;
  1163. }>();
  1164. const sessionId = reqSessionId;
  1165. if (!instruction?.trim()) {
  1166. return c.json({ error: "No instruction provided" }, 400);
  1167. }
  1168. if (!sessionId?.trim()) {
  1169. throw new ApiError(400, "SESSION_ID_REQUIRED", "sessionId is required");
  1170. }
  1171. broadcast("agent:start", { instruction, activeBookId, sessionId });
  1172. try {
  1173. // Load config + create LLM client (pipeline created after model resolution)
  1174. const config = await loadCurrentProjectConfig({ requireApiKey: false });
  1175. const client = createLLMClient(config.llm);
  1176. const loadedBookSession = await loadBookSession(root, sessionId);
  1177. if (!loadedBookSession) {
  1178. throw new ApiError(404, "SESSION_NOT_FOUND", `Session not found: ${sessionId}`);
  1179. }
  1180. let bookSession = loadedBookSession;
  1181. const streamSessionId = loadedBookSession.sessionId;
  1182. const scheduleSessionTitleGeneration = (resolvedSessionId: string) => {
  1183. void (async () => {
  1184. try {
  1185. const freshSession = await loadBookSession(root, resolvedSessionId);
  1186. if (!freshSession || freshSession.title !== null) return;
  1187. const firstUserMessage = freshSession.messages.find((message) => message.role === "user");
  1188. const firstAssistantMessage = freshSession.messages.find((message) => message.role === "assistant");
  1189. if (!firstUserMessage || !firstAssistantMessage) return;
  1190. const freshConfig = await loadCurrentProjectConfig({ requireApiKey: false });
  1191. const titleClient = createLLMClient(freshConfig.llm);
  1192. const titleResult = await chatCompletion(
  1193. titleClient,
  1194. freshConfig.llm.defaultModel ?? freshConfig.llm.model,
  1195. [
  1196. {
  1197. role: "user",
  1198. content:
  1199. "用 6 个中文字以内概括这段对话的主题,只返回标题文本。\n\n"
  1200. + `用户: ${firstUserMessage.content.slice(0, 200)}\n`
  1201. + `助手: ${firstAssistantMessage.content.slice(0, 200)}`,
  1202. },
  1203. ],
  1204. { maxTokens: 32 },
  1205. );
  1206. const title = normalizeGeneratedSessionTitle(titleResult.content ?? "");
  1207. if (!title) return;
  1208. const updated = await updateSessionTitle(root, resolvedSessionId, title);
  1209. if (!updated || updated.title !== title) return;
  1210. broadcast("session:title", { sessionId: resolvedSessionId, title });
  1211. } catch {
  1212. // ignore title generation errors and try again after the next exchange
  1213. }
  1214. })();
  1215. };
  1216. // Build initial message context from persisted session
  1217. const initialMessages = bookSession.messages
  1218. .filter((m) => m.role === "user" || m.role === "assistant")
  1219. .map((m) => ({ role: m.role as "user" | "assistant", content: m.content }));
  1220. // Resolve model — multi-service resolution
  1221. let resolvedModel: ResolvedModel["model"] | undefined;
  1222. let resolvedApiKey: string | undefined;
  1223. if (reqService && reqModel) {
  1224. // 1. Frontend explicitly selected a service+model — fail loudly if no key
  1225. try {
  1226. const configuredEntry = await resolveConfiguredServiceEntry(root, reqService);
  1227. const resolved = await resolveServiceModel(
  1228. reqService,
  1229. reqModel,
  1230. root,
  1231. await resolveConfiguredServiceBaseUrl(root, reqService),
  1232. configuredEntry?.apiFormat,
  1233. );
  1234. resolvedModel = resolved.model;
  1235. resolvedApiKey = resolved.apiKey;
  1236. } catch (e: any) {
  1237. const msg = e?.message ?? String(e);
  1238. if (/API key/i.test(msg)) {
  1239. return c.json({
  1240. error: `请先为 ${reqService} 配置 API Key`,
  1241. response: `请先在模型配置中为 ${reqService} 填写 API Key,然后再试。`,
  1242. }, 400);
  1243. }
  1244. throw e;
  1245. }
  1246. }
  1247. if (!resolvedModel) {
  1248. // 2. Try defaultModel from new config format
  1249. const rawConfig = config.llm as unknown as Record<string, unknown>;
  1250. const defaultModel = rawConfig.defaultModel as string | undefined;
  1251. const servicesArr = normalizeServiceConfig(rawConfig.services);
  1252. const firstService = servicesArr[0];
  1253. if (firstService?.service && defaultModel) {
  1254. try {
  1255. const resolved = await resolveServiceModel(
  1256. serviceConfigKey(firstService),
  1257. defaultModel,
  1258. root,
  1259. firstService.baseUrl,
  1260. firstService.apiFormat,
  1261. );
  1262. resolvedModel = resolved.model;
  1263. resolvedApiKey = resolved.apiKey;
  1264. } catch { /* fall through */ }
  1265. }
  1266. }
  1267. if (!resolvedModel) {
  1268. // 3. Try first connected service from secrets
  1269. const secrets = await loadSecrets(root);
  1270. for (const [svcName, svcData] of Object.entries(secrets.services)) {
  1271. if (svcData?.apiKey) {
  1272. try {
  1273. const models = await listModelsForService(svcName, svcData.apiKey);
  1274. if (models.length > 0) {
  1275. const configuredEntry = await resolveConfiguredServiceEntry(root, svcName);
  1276. const resolved = await resolveServiceModel(
  1277. svcName,
  1278. models[0].id,
  1279. root,
  1280. await resolveConfiguredServiceBaseUrl(root, svcName),
  1281. configuredEntry?.apiFormat,
  1282. );
  1283. resolvedModel = resolved.model;
  1284. resolvedApiKey = resolved.apiKey;
  1285. break;
  1286. }
  1287. } catch { /* try next */ }
  1288. }
  1289. }
  1290. }
  1291. if (!resolvedModel) {
  1292. // 4. Legacy fallback: use createLLMClient
  1293. resolvedModel = client._piModel
  1294. ? client._piModel
  1295. : { provider: config.llm.provider ?? "anthropic", modelId: config.llm.model } as any;
  1296. resolvedApiKey = client._apiKey;
  1297. }
  1298. const model = resolvedModel!;
  1299. const agentApiKey = resolvedApiKey;
  1300. const configuredEntry = reqService ? await resolveConfiguredServiceEntry(root, reqService) : undefined;
  1301. // Create pipeline with resolved model (so sub_agent tools use the frontend-selected model)
  1302. // Don't spread config.llm — its baseUrl/provider belong to the old service.
  1303. // Let createLLMClient resolve baseUrl from the service preset.
  1304. const pipelineClient = (reqService && reqModel && resolvedApiKey)
  1305. ? createLLMClient({
  1306. ...config.llm,
  1307. service: configuredEntry?.service ?? reqService,
  1308. model: reqModel,
  1309. apiKey: resolvedApiKey,
  1310. ...(configuredEntry?.apiFormat ? { apiFormat: configuredEntry.apiFormat } : {}),
  1311. ...(configuredEntry?.stream !== undefined ? { stream: configuredEntry.stream } : {}),
  1312. baseUrl: configuredEntry?.baseUrl ?? "",
  1313. } as any)
  1314. : client;
  1315. const pipeline = new PipelineRunner(await buildPipelineConfig({
  1316. client: pipelineClient,
  1317. model: reqModel ?? config.llm.model,
  1318. currentConfig: config,
  1319. sessionIdForSSE: bookSession.sessionId,
  1320. }));
  1321. // Run pi-agent session
  1322. const collectedToolExecs: CollectedToolExec[] = [];
  1323. const result = await runAgentSession(
  1324. {
  1325. model,
  1326. apiKey: agentApiKey,
  1327. pipeline,
  1328. projectRoot: root,
  1329. bookId: activeBookId ?? null,
  1330. sessionId: bookSession.sessionId,
  1331. language: config.language ?? "zh",
  1332. onEvent: (event) => {
  1333. if (event.type === "message_update") {
  1334. const ame = event.assistantMessageEvent;
  1335. if (ame.type === "text_delta") {
  1336. broadcast("draft:delta", { sessionId: streamSessionId, text: ame.delta });
  1337. } else if (ame.type === "thinking_delta") {
  1338. broadcast("thinking:delta", { sessionId: streamSessionId, text: (ame as any).delta });
  1339. } else if (ame.type === "thinking_start") {
  1340. broadcast("thinking:start", { sessionId: streamSessionId });
  1341. } else if (ame.type === "thinking_end") {
  1342. broadcast("thinking:end", { sessionId: streamSessionId });
  1343. }
  1344. }
  1345. if (event.type === "tool_execution_start") {
  1346. const args = event.args as Record<string, unknown> | undefined;
  1347. const agent = event.toolName === "sub_agent" ? (args?.agent as string | undefined) : undefined;
  1348. const stages = agent ? (PIPELINE_STAGES[agent] ?? []) : [];
  1349. collectedToolExecs.push({
  1350. id: event.toolCallId,
  1351. tool: event.toolName,
  1352. agent,
  1353. label: resolveToolLabel(event.toolName, agent),
  1354. status: "running",
  1355. args,
  1356. stages: stages.length > 0
  1357. ? stages.map(l => ({ label: l, status: "pending" as const }))
  1358. : undefined,
  1359. startedAt: Date.now(),
  1360. });
  1361. broadcast("tool:start", {
  1362. sessionId: streamSessionId,
  1363. id: event.toolCallId,
  1364. tool: event.toolName,
  1365. args,
  1366. stages,
  1367. });
  1368. }
  1369. if (event.type === "tool_execution_update") {
  1370. broadcast("tool:update", {
  1371. sessionId: streamSessionId,
  1372. tool: event.toolName,
  1373. partialResult: event.partialResult,
  1374. });
  1375. }
  1376. if (event.type === "tool_execution_end") {
  1377. const exec = collectedToolExecs.find(t => t.id === event.toolCallId);
  1378. if (exec) {
  1379. exec.status = event.isError ? "error" : "completed";
  1380. exec.completedAt = Date.now();
  1381. exec.stages = exec.stages?.map(s => ({ ...s, status: "completed" as const }));
  1382. if (event.isError) exec.error = extractToolError(event.result);
  1383. else exec.result = summarizeResult(event.result);
  1384. }
  1385. broadcast("tool:end", {
  1386. sessionId: streamSessionId,
  1387. id: event.toolCallId,
  1388. tool: event.toolName,
  1389. result: event.result,
  1390. isError: event.isError,
  1391. });
  1392. }
  1393. },
  1394. },
  1395. instruction,
  1396. initialMessages,
  1397. );
  1398. // Persist user + assistant messages to BookSession
  1399. bookSession = appendBookSessionMessage(bookSession, {
  1400. role: "user",
  1401. content: instruction,
  1402. timestamp: Date.now(),
  1403. });
  1404. if (result.responseText) {
  1405. const lastAssistant = result.messages?.filter((m: any) => m.role === "assistant").pop();
  1406. const thinking = lastAssistant?.thinking;
  1407. bookSession = appendBookSessionMessage(bookSession, {
  1408. role: "assistant",
  1409. content: result.responseText,
  1410. ...(thinking ? { thinking } : {}),
  1411. ...(collectedToolExecs.length > 0 ? { toolExecutions: collectedToolExecs } : {}),
  1412. timestamp: Date.now() + 1,
  1413. });
  1414. }
  1415. if (!result.responseText) {
  1416. try {
  1417. const fallbackClient = createLLMClient({
  1418. ...config.llm,
  1419. service: configuredEntry?.service ?? reqService ?? config.llm.service,
  1420. model: reqModel ?? config.llm.model,
  1421. apiKey: agentApiKey ?? config.llm.apiKey,
  1422. baseUrl: configuredEntry?.baseUrl ?? "",
  1423. ...(configuredEntry?.apiFormat ? { apiFormat: configuredEntry.apiFormat } : {}),
  1424. ...(configuredEntry?.stream !== undefined ? { stream: configuredEntry.stream } : {}),
  1425. } as ProjectConfig["llm"]);
  1426. const fallback = await chatCompletion(
  1427. fallbackClient,
  1428. reqModel ?? config.llm.model,
  1429. [
  1430. { role: "system", content: buildAgentSystemPrompt(activeBookId ?? null, config.language ?? "zh") },
  1431. { role: "user", content: instruction },
  1432. ],
  1433. { maxTokens: 256 },
  1434. );
  1435. if (fallback.content?.trim()) {
  1436. bookSession = appendBookSessionMessage(bookSession, {
  1437. role: "assistant",
  1438. content: fallback.content,
  1439. timestamp: Date.now() + 1,
  1440. });
  1441. await persistBookSession(root, bookSession);
  1442. scheduleSessionTitleGeneration(bookSession.sessionId);
  1443. return c.json({
  1444. response: fallback.content,
  1445. session: { sessionId: bookSession.sessionId },
  1446. });
  1447. }
  1448. } catch {
  1449. // fall through to probe-based diagnosis below
  1450. }
  1451. try {
  1452. const probeClient = createLLMClient({
  1453. ...config.llm,
  1454. service: configuredEntry?.service ?? reqService ?? config.llm.service,
  1455. model: reqModel ?? config.llm.model,
  1456. apiKey: agentApiKey ?? config.llm.apiKey,
  1457. baseUrl: configuredEntry?.baseUrl ?? "",
  1458. ...(configuredEntry?.apiFormat ? { apiFormat: configuredEntry.apiFormat } : {}),
  1459. ...(configuredEntry?.stream !== undefined ? { stream: configuredEntry.stream } : {}),
  1460. } as ProjectConfig["llm"]);
  1461. await chatCompletion(
  1462. probeClient,
  1463. reqModel ?? config.llm.model,
  1464. [{ role: "user", content: "ping" }],
  1465. { maxTokens: 5 },
  1466. );
  1467. } catch (probeError) {
  1468. const probeMessage = probeError instanceof Error ? probeError.message : String(probeError);
  1469. return c.json({
  1470. error: { code: "AGENT_EMPTY_RESPONSE", message: probeMessage },
  1471. response: probeMessage,
  1472. }, 502);
  1473. }
  1474. const emptyMessage = "模型未返回文本内容。请检查协议类型(chat/responses)、流式开关或上游服务兼容性。";
  1475. return c.json({
  1476. error: { code: "AGENT_EMPTY_RESPONSE", message: emptyMessage },
  1477. response: emptyMessage,
  1478. }, 502);
  1479. }
  1480. await persistBookSession(root, bookSession);
  1481. broadcast("agent:complete", { instruction, activeBookId, sessionId: bookSession.sessionId });
  1482. scheduleSessionTitleGeneration(bookSession.sessionId);
  1483. // If a sub_agent created a new book during this session, broadcast book:created
  1484. // so the sidebar refreshes.
  1485. if (!activeBookId && collectedToolExecs.some((t) => t.agent === "architect" && t.status === "completed")) {
  1486. const books = await state.listBooks();
  1487. const latestBook = books.at(-1);
  1488. if (latestBook) {
  1489. try {
  1490. const migratedSession = await migrateBookSession(root, bookSession.sessionId, latestBook);
  1491. if (migratedSession) {
  1492. bookSession = migratedSession;
  1493. }
  1494. } catch (e) {
  1495. if (!(e instanceof SessionAlreadyMigratedError)) {
  1496. throw e;
  1497. }
  1498. }
  1499. broadcast("book:created", { bookId: latestBook, sessionId: bookSession.sessionId });
  1500. }
  1501. }
  1502. return c.json({
  1503. response: result.responseText,
  1504. session: {
  1505. sessionId: bookSession.sessionId,
  1506. ...(bookSession.bookId ? { activeBookId: bookSession.bookId } : {}),
  1507. },
  1508. });
  1509. } catch (e) {
  1510. if (e instanceof ApiError) {
  1511. throw e;
  1512. }
  1513. if (e instanceof SessionAlreadyMigratedError) {
  1514. const migratedMessage = e instanceof Error ? e.message : String(e);
  1515. throw new ApiError(409, "SESSION_ALREADY_MIGRATED", migratedMessage);
  1516. }
  1517. const msg = e instanceof Error ? e.message : String(e);
  1518. broadcast("agent:error", { instruction, activeBookId, sessionId, error: msg });
  1519. // Agent busy — return 429 with user-friendly message
  1520. if (/already processing|prompt.*queue/i.test(msg)) {
  1521. return c.json({
  1522. error: { code: "AGENT_BUSY", message: "正在处理中,请等待当前操作完成" },
  1523. response: "正在处理中,请等待当前操作完成后再发送。",
  1524. }, 429);
  1525. }
  1526. return c.json(
  1527. { error: { code: "AGENT_ERROR", message: msg } },
  1528. 500,
  1529. );
  1530. }
  1531. });
  1532. // --- Language setup ---
  1533. app.post("/api/v1/project/language", async (c) => {
  1534. const { language } = await c.req.json<{ language: "zh" | "en" }>();
  1535. const configPath = join(root, "inkos.json");
  1536. try {
  1537. const raw = await readFile(configPath, "utf-8");
  1538. const existing = JSON.parse(raw);
  1539. existing.language = language;
  1540. const { writeFile: writeFileFs } = await import("node:fs/promises");
  1541. await writeFileFs(configPath, JSON.stringify(existing, null, 2), "utf-8");
  1542. return c.json({ ok: true, language });
  1543. } catch (e) {
  1544. return c.json({ error: String(e) }, 500);
  1545. }
  1546. });
  1547. // --- Audit ---
  1548. app.post("/api/v1/books/:id/audit/:chapter", async (c) => {
  1549. const id = c.req.param("id");
  1550. const chapterNum = parseInt(c.req.param("chapter"), 10);
  1551. const bookDir = state.bookDir(id);
  1552. broadcast("audit:start", { bookId: id, chapter: chapterNum });
  1553. try {
  1554. const book = await state.loadBookConfig(id);
  1555. const chaptersDir = join(bookDir, "chapters");
  1556. const files = await readdir(chaptersDir);
  1557. const paddedNum = String(chapterNum).padStart(4, "0");
  1558. const match = files.find((f) => f.startsWith(paddedNum) && f.endsWith(".md"));
  1559. if (!match) return c.json({ error: "Chapter not found" }, 404);
  1560. const content = await readFile(join(chaptersDir, match), "utf-8");
  1561. const currentConfig = await loadCurrentProjectConfig();
  1562. const { ContinuityAuditor } = await import("@actalk/inkos-core");
  1563. const auditor = new ContinuityAuditor({
  1564. client: createLLMClient(currentConfig.llm),
  1565. model: currentConfig.llm.model,
  1566. projectRoot: root,
  1567. bookId: id,
  1568. });
  1569. const result = await auditor.auditChapter(bookDir, content, chapterNum, book.genre);
  1570. broadcast("audit:complete", { bookId: id, chapter: chapterNum, passed: result.passed });
  1571. return c.json(result);
  1572. } catch (e) {
  1573. broadcast("audit:error", { bookId: id, error: String(e) });
  1574. return c.json({ error: String(e) }, 500);
  1575. }
  1576. });
  1577. // --- Revise ---
  1578. app.post("/api/v1/books/:id/revise/:chapter", async (c) => {
  1579. const id = c.req.param("id");
  1580. const chapterNum = parseInt(c.req.param("chapter"), 10);
  1581. const bookDir = state.bookDir(id);
  1582. const body = await c.req
  1583. .json<{ mode?: string; brief?: string }>()
  1584. .catch(() => ({ mode: "spot-fix", brief: undefined }));
  1585. broadcast("revise:start", { bookId: id, chapter: chapterNum });
  1586. try {
  1587. const book = await state.loadBookConfig(id);
  1588. const chaptersDir = join(bookDir, "chapters");
  1589. const files = await readdir(chaptersDir);
  1590. const paddedNum = String(chapterNum).padStart(4, "0");
  1591. const match = files.find((f) => f.startsWith(paddedNum) && f.endsWith(".md"));
  1592. if (!match) return c.json({ error: "Chapter not found" }, 404);
  1593. const pipeline = new PipelineRunner(await buildPipelineConfig({
  1594. externalContext: body.brief,
  1595. }));
  1596. const normalizedMode = body.mode ?? "spot-fix";
  1597. const result = await pipeline.reviseDraft(
  1598. id,
  1599. chapterNum,
  1600. normalizedMode as "polish" | "rewrite" | "rework" | "spot-fix" | "anti-detect",
  1601. );
  1602. broadcast("revise:complete", { bookId: id, chapter: chapterNum });
  1603. return c.json(result);
  1604. } catch (e) {
  1605. broadcast("revise:error", { bookId: id, error: String(e) });
  1606. return c.json({ error: String(e) }, 500);
  1607. }
  1608. });
  1609. // --- Export ---
  1610. app.get("/api/v1/books/:id/export", async (c) => {
  1611. const id = c.req.param("id");
  1612. const format = (c.req.query("format") ?? "txt") as string;
  1613. const approvedOnly = c.req.query("approvedOnly") === "true";
  1614. try {
  1615. const artifact = await buildExportArtifact(state, id, {
  1616. format: format as "txt" | "md" | "epub",
  1617. approvedOnly,
  1618. });
  1619. const responseBody = typeof artifact.payload === "string"
  1620. ? artifact.payload
  1621. : new Uint8Array(artifact.payload);
  1622. return new Response(responseBody, {
  1623. headers: {
  1624. "Content-Type": artifact.contentType,
  1625. "Content-Disposition": `attachment; filename="${artifact.fileName}"`,
  1626. },
  1627. });
  1628. } catch {
  1629. return c.json({ error: "Export failed" }, 500);
  1630. }
  1631. });
  1632. // --- Export to file (save to project dir) ---
  1633. app.post("/api/v1/books/:id/export-save", async (c) => {
  1634. const id = c.req.param("id");
  1635. const { format, approvedOnly } = await c.req.json<{ format?: string; approvedOnly?: boolean }>().catch(() => ({ format: "txt", approvedOnly: false }));
  1636. const fmt = format ?? "txt";
  1637. try {
  1638. const pipeline = new PipelineRunner(await buildPipelineConfig());
  1639. const tools = createInteractionToolsFromDeps(pipeline, state);
  1640. const bookDir = state.bookDir(id);
  1641. const outputPath = join(bookDir, `${id}.${fmt === "epub" ? "epub" : fmt}`);
  1642. const result = await processProjectInteractionRequest({
  1643. projectRoot: root,
  1644. request: {
  1645. intent: "export_book",
  1646. bookId: id,
  1647. format: fmt as "txt" | "md" | "epub",
  1648. approvedOnly,
  1649. outputPath,
  1650. },
  1651. tools,
  1652. activeBookId: id,
  1653. });
  1654. return c.json({
  1655. ok: true,
  1656. path: (result.details?.outputPath as string | undefined) ?? outputPath,
  1657. format: fmt,
  1658. chapters: (result.details?.chaptersExported as number | undefined) ?? 0,
  1659. });
  1660. } catch (e) {
  1661. return c.json({ error: String(e) }, 500);
  1662. }
  1663. });
  1664. // --- Genre detail + copy ---
  1665. app.get("/api/v1/genres/:id", async (c) => {
  1666. const genreId = c.req.param("id");
  1667. try {
  1668. const { readGenreProfile } = await import("@actalk/inkos-core");
  1669. const { profile, body } = await readGenreProfile(root, genreId);
  1670. return c.json({ profile, body });
  1671. } catch (e) {
  1672. return c.json({ error: String(e) }, 404);
  1673. }
  1674. });
  1675. app.post("/api/v1/genres/:id/copy", async (c) => {
  1676. const genreId = c.req.param("id");
  1677. if (/[/\\\0]/.test(genreId) || genreId.includes("..")) {
  1678. throw new ApiError(400, "INVALID_GENRE_ID", `Invalid genre ID: "${genreId}"`);
  1679. }
  1680. try {
  1681. const { getBuiltinGenresDir } = await import("@actalk/inkos-core");
  1682. const { mkdir: mkdirFs, copyFile } = await import("node:fs/promises");
  1683. const builtinDir = getBuiltinGenresDir();
  1684. const projectGenresDir = join(root, "genres");
  1685. await mkdirFs(projectGenresDir, { recursive: true });
  1686. await copyFile(join(builtinDir, `${genreId}.md`), join(projectGenresDir, `${genreId}.md`));
  1687. return c.json({ ok: true, path: `genres/${genreId}.md` });
  1688. } catch (e) {
  1689. return c.json({ error: String(e) }, 500);
  1690. }
  1691. });
  1692. // --- Model overrides ---
  1693. app.get("/api/v1/project/model-overrides", async (c) => {
  1694. const raw = JSON.parse(await readFile(join(root, "inkos.json"), "utf-8"));
  1695. return c.json({ overrides: raw.modelOverrides ?? {} });
  1696. });
  1697. app.put("/api/v1/project/model-overrides", async (c) => {
  1698. const { overrides } = await c.req.json<{ overrides: Record<string, unknown> }>();
  1699. const configPath = join(root, "inkos.json");
  1700. const raw = JSON.parse(await readFile(configPath, "utf-8"));
  1701. raw.modelOverrides = overrides;
  1702. const { writeFile: writeFileFs } = await import("node:fs/promises");
  1703. await writeFileFs(configPath, JSON.stringify(raw, null, 2), "utf-8");
  1704. return c.json({ ok: true });
  1705. });
  1706. // --- Notify channels ---
  1707. app.get("/api/v1/project/notify", async (c) => {
  1708. const raw = JSON.parse(await readFile(join(root, "inkos.json"), "utf-8"));
  1709. return c.json({ channels: raw.notify ?? [] });
  1710. });
  1711. app.put("/api/v1/project/notify", async (c) => {
  1712. const { channels } = await c.req.json<{ channels: unknown[] }>();
  1713. const configPath = join(root, "inkos.json");
  1714. const raw = JSON.parse(await readFile(configPath, "utf-8"));
  1715. raw.notify = channels;
  1716. const { writeFile: writeFileFs } = await import("node:fs/promises");
  1717. await writeFileFs(configPath, JSON.stringify(raw, null, 2), "utf-8");
  1718. return c.json({ ok: true });
  1719. });
  1720. // --- AIGC Detection ---
  1721. app.post("/api/v1/books/:id/detect/:chapter", async (c) => {
  1722. const id = c.req.param("id");
  1723. const chapterNum = parseInt(c.req.param("chapter"), 10);
  1724. const bookDir = state.bookDir(id);
  1725. try {
  1726. const chaptersDir = join(bookDir, "chapters");
  1727. const files = await readdir(chaptersDir);
  1728. const paddedNum = String(chapterNum).padStart(4, "0");
  1729. const match = files.find((f) => f.startsWith(paddedNum) && f.endsWith(".md"));
  1730. if (!match) return c.json({ error: "Chapter not found" }, 404);
  1731. const content = await readFile(join(chaptersDir, match), "utf-8");
  1732. const { analyzeAITells } = await import("@actalk/inkos-core");
  1733. const result = analyzeAITells(content);
  1734. return c.json({ chapterNumber: chapterNum, ...result });
  1735. } catch (e) {
  1736. return c.json({ error: String(e) }, 500);
  1737. }
  1738. });
  1739. // --- Truth file edit ---
  1740. app.put("/api/v1/books/:id/truth/:file", async (c) => {
  1741. const id = c.req.param("id");
  1742. const file = c.req.param("file");
  1743. if (!TRUTH_FILES.includes(file)) {
  1744. return c.json({ error: "Invalid truth file" }, 400);
  1745. }
  1746. const { content } = await c.req.json<{ content: string }>();
  1747. const bookDir = state.bookDir(id);
  1748. const { writeFile: writeFileFs, mkdir: mkdirFs } = await import("node:fs/promises");
  1749. await mkdirFs(join(bookDir, "story"), { recursive: true });
  1750. await writeFileFs(join(bookDir, "story", file), content, "utf-8");
  1751. return c.json({ ok: true });
  1752. });
  1753. // =============================================
  1754. // NEW ENDPOINTS — CLI parity
  1755. // =============================================
  1756. // --- Book Delete ---
  1757. app.delete("/api/v1/books/:id", async (c) => {
  1758. const id = c.req.param("id");
  1759. const bookDir = state.bookDir(id);
  1760. try {
  1761. const { rm } = await import("node:fs/promises");
  1762. await rm(bookDir, { recursive: true, force: true });
  1763. broadcast("book:deleted", { bookId: id });
  1764. return c.json({ ok: true, bookId: id });
  1765. } catch (e) {
  1766. return c.json({ error: String(e) }, 500);
  1767. }
  1768. });
  1769. // --- Book Update ---
  1770. app.put("/api/v1/books/:id", async (c) => {
  1771. const id = c.req.param("id");
  1772. const updates = await c.req.json<{
  1773. chapterWordCount?: number;
  1774. targetChapters?: number;
  1775. status?: string;
  1776. language?: string;
  1777. }>();
  1778. try {
  1779. const book = await state.loadBookConfig(id);
  1780. const updated = {
  1781. ...book,
  1782. ...(updates.chapterWordCount !== undefined ? { chapterWordCount: Number(updates.chapterWordCount) } : {}),
  1783. ...(updates.targetChapters !== undefined ? { targetChapters: Number(updates.targetChapters) } : {}),
  1784. ...(updates.status !== undefined ? { status: updates.status as typeof book.status } : {}),
  1785. ...(updates.language !== undefined ? { language: updates.language as "zh" | "en" } : {}),
  1786. updatedAt: new Date().toISOString(),
  1787. };
  1788. await state.saveBookConfig(id, updated);
  1789. return c.json({ ok: true, book: updated });
  1790. } catch (e) {
  1791. return c.json({ error: String(e) }, 500);
  1792. }
  1793. });
  1794. // --- Write Rewrite (specific chapter) ---
  1795. app.post("/api/v1/books/:id/rewrite/:chapter", async (c) => {
  1796. const id = c.req.param("id");
  1797. const chapterNum = parseInt(c.req.param("chapter"), 10);
  1798. const body: { brief?: string } = await c.req
  1799. .json<{ brief?: string }>()
  1800. .catch(() => ({}));
  1801. broadcast("rewrite:start", { bookId: id, chapter: chapterNum });
  1802. try {
  1803. const rollbackTarget = chapterNum - 1;
  1804. const discarded = await state.rollbackToChapter(id, rollbackTarget);
  1805. const pipeline = new PipelineRunner(await buildPipelineConfig({
  1806. externalContext: body.brief,
  1807. }));
  1808. pipeline.writeNextChapter(id).then(
  1809. (result) => broadcast("rewrite:complete", { bookId: id, chapterNumber: result.chapterNumber, title: result.title, wordCount: result.wordCount }),
  1810. (e) => broadcast("rewrite:error", { bookId: id, error: e instanceof Error ? e.message : String(e) }),
  1811. );
  1812. return c.json({ status: "rewriting", bookId: id, chapter: chapterNum, rolledBackTo: rollbackTarget, discarded });
  1813. } catch (e) {
  1814. broadcast("rewrite:error", { bookId: id, error: String(e) });
  1815. return c.json({ error: String(e) }, 500);
  1816. }
  1817. });
  1818. app.post("/api/v1/books/:id/resync/:chapter", async (c) => {
  1819. const id = c.req.param("id");
  1820. const chapterNum = parseInt(c.req.param("chapter"), 10);
  1821. const body: { brief?: string } = await c.req
  1822. .json<{ brief?: string }>()
  1823. .catch(() => ({}));
  1824. try {
  1825. const pipeline = new PipelineRunner(await buildPipelineConfig({
  1826. externalContext: body.brief,
  1827. }));
  1828. const result = await pipeline.resyncChapterArtifacts(id, chapterNum);
  1829. return c.json(result);
  1830. } catch (e) {
  1831. return c.json({ error: String(e) }, 500);
  1832. }
  1833. });
  1834. // --- Detect All chapters ---
  1835. app.post("/api/v1/books/:id/detect-all", async (c) => {
  1836. const id = c.req.param("id");
  1837. const bookDir = state.bookDir(id);
  1838. try {
  1839. const chaptersDir = join(bookDir, "chapters");
  1840. const files = await readdir(chaptersDir);
  1841. const mdFiles = files.filter((f) => f.endsWith(".md") && /^\d{4}/.test(f)).sort();
  1842. const { analyzeAITells } = await import("@actalk/inkos-core");
  1843. const results = await Promise.all(
  1844. mdFiles.map(async (f) => {
  1845. const num = parseInt(f.slice(0, 4), 10);
  1846. const content = await readFile(join(chaptersDir, f), "utf-8");
  1847. const result = analyzeAITells(content);
  1848. return { chapterNumber: num, filename: f, ...result };
  1849. }),
  1850. );
  1851. return c.json({ bookId: id, results });
  1852. } catch (e) {
  1853. return c.json({ error: String(e) }, 500);
  1854. }
  1855. });
  1856. // --- Detect Stats ---
  1857. app.get("/api/v1/books/:id/detect/stats", async (c) => {
  1858. const id = c.req.param("id");
  1859. try {
  1860. const { loadDetectionHistory, analyzeDetectionInsights } = await import("@actalk/inkos-core");
  1861. const bookDir = state.bookDir(id);
  1862. const history = await loadDetectionHistory(bookDir);
  1863. const insights = analyzeDetectionInsights(history);
  1864. return c.json(insights);
  1865. } catch (e) {
  1866. return c.json({ error: String(e) }, 500);
  1867. }
  1868. });
  1869. // --- Genre Create ---
  1870. app.post("/api/v1/genres/create", async (c) => {
  1871. const body = await c.req.json<{
  1872. id: string; name: string; language?: string;
  1873. chapterTypes?: string[]; fatigueWords?: string[];
  1874. numericalSystem?: boolean; powerScaling?: boolean; eraResearch?: boolean;
  1875. pacingRule?: string; satisfactionTypes?: string[]; auditDimensions?: number[];
  1876. body?: string;
  1877. }>();
  1878. if (!body.id || !body.name) {
  1879. return c.json({ error: "id and name are required" }, 400);
  1880. }
  1881. if (/[/\\\0]/.test(body.id) || body.id.includes("..")) {
  1882. throw new ApiError(400, "INVALID_GENRE_ID", `Invalid genre ID: "${body.id}"`);
  1883. }
  1884. const { writeFile: writeFileFs, mkdir: mkdirFs } = await import("node:fs/promises");
  1885. const genresDir = join(root, "genres");
  1886. await mkdirFs(genresDir, { recursive: true });
  1887. const frontmatter = [
  1888. "---",
  1889. `name: ${body.name}`,
  1890. `id: ${body.id}`,
  1891. `language: ${body.language ?? "zh"}`,
  1892. `chapterTypes: ${JSON.stringify(body.chapterTypes ?? [])}`,
  1893. `fatigueWords: ${JSON.stringify(body.fatigueWords ?? [])}`,
  1894. `numericalSystem: ${body.numericalSystem ?? false}`,
  1895. `powerScaling: ${body.powerScaling ?? false}`,
  1896. `eraResearch: ${body.eraResearch ?? false}`,
  1897. `pacingRule: "${body.pacingRule ?? ""}"`,
  1898. `satisfactionTypes: ${JSON.stringify(body.satisfactionTypes ?? [])}`,
  1899. `auditDimensions: ${JSON.stringify(body.auditDimensions ?? [])}`,
  1900. "---",
  1901. "",
  1902. body.body ?? "",
  1903. ].join("\n");
  1904. await writeFileFs(join(genresDir, `${body.id}.md`), frontmatter, "utf-8");
  1905. return c.json({ ok: true, id: body.id });
  1906. });
  1907. // --- Genre Edit ---
  1908. app.put("/api/v1/genres/:id", async (c) => {
  1909. const genreId = c.req.param("id");
  1910. if (/[/\\\0]/.test(genreId) || genreId.includes("..")) {
  1911. throw new ApiError(400, "INVALID_GENRE_ID", `Invalid genre ID: "${genreId}"`);
  1912. }
  1913. const body = await c.req.json<{ profile: Record<string, unknown>; body: string }>();
  1914. const { writeFile: writeFileFs, mkdir: mkdirFs } = await import("node:fs/promises");
  1915. const genresDir = join(root, "genres");
  1916. await mkdirFs(genresDir, { recursive: true });
  1917. const p = body.profile;
  1918. const frontmatter = [
  1919. "---",
  1920. `name: ${p.name ?? genreId}`,
  1921. `id: ${p.id ?? genreId}`,
  1922. `language: ${p.language ?? "zh"}`,
  1923. `chapterTypes: ${JSON.stringify(p.chapterTypes ?? [])}`,
  1924. `fatigueWords: ${JSON.stringify(p.fatigueWords ?? [])}`,
  1925. `numericalSystem: ${p.numericalSystem ?? false}`,
  1926. `powerScaling: ${p.powerScaling ?? false}`,
  1927. `eraResearch: ${p.eraResearch ?? false}`,
  1928. `pacingRule: "${p.pacingRule ?? ""}"`,
  1929. `satisfactionTypes: ${JSON.stringify(p.satisfactionTypes ?? [])}`,
  1930. `auditDimensions: ${JSON.stringify(p.auditDimensions ?? [])}`,
  1931. "---",
  1932. "",
  1933. body.body ?? "",
  1934. ].join("\n");
  1935. await writeFileFs(join(genresDir, `${genreId}.md`), frontmatter, "utf-8");
  1936. return c.json({ ok: true, id: genreId });
  1937. });
  1938. // --- Genre Delete (project-level only) ---
  1939. app.delete("/api/v1/genres/:id", async (c) => {
  1940. const genreId = c.req.param("id");
  1941. if (/[/\\\0]/.test(genreId) || genreId.includes("..")) {
  1942. throw new ApiError(400, "INVALID_GENRE_ID", `Invalid genre ID: "${genreId}"`);
  1943. }
  1944. const filePath = join(root, "genres", `${genreId}.md`);
  1945. try {
  1946. const { rm } = await import("node:fs/promises");
  1947. await rm(filePath);
  1948. return c.json({ ok: true, id: genreId });
  1949. } catch (e) {
  1950. return c.json({ error: `Genre "${genreId}" not found in project` }, 404);
  1951. }
  1952. });
  1953. // --- Style Analyze ---
  1954. app.post("/api/v1/style/analyze", async (c) => {
  1955. const { text, sourceName } = await c.req.json<{ text: string; sourceName: string }>();
  1956. if (!text?.trim()) return c.json({ error: "text is required" }, 400);
  1957. try {
  1958. const { analyzeStyle } = await import("@actalk/inkos-core");
  1959. const profile = analyzeStyle(text, sourceName ?? "unknown");
  1960. return c.json(profile);
  1961. } catch (e) {
  1962. return c.json({ error: String(e) }, 500);
  1963. }
  1964. });
  1965. // --- Style Import to Book ---
  1966. app.post("/api/v1/books/:id/style/import", async (c) => {
  1967. const id = c.req.param("id");
  1968. const { text, sourceName } = await c.req.json<{ text: string; sourceName: string }>();
  1969. broadcast("style:start", { bookId: id });
  1970. try {
  1971. const pipeline = new PipelineRunner(await buildPipelineConfig());
  1972. const result = await pipeline.generateStyleGuide(id, text, sourceName ?? "unknown");
  1973. broadcast("style:complete", { bookId: id });
  1974. return c.json({ ok: true, result });
  1975. } catch (e) {
  1976. broadcast("style:error", { bookId: id, error: String(e) });
  1977. return c.json({ error: String(e) }, 500);
  1978. }
  1979. });
  1980. // --- Import Chapters ---
  1981. app.post("/api/v1/books/:id/import/chapters", async (c) => {
  1982. const id = c.req.param("id");
  1983. const { text, splitRegex } = await c.req.json<{ text: string; splitRegex?: string }>();
  1984. if (!text?.trim()) return c.json({ error: "text is required" }, 400);
  1985. broadcast("import:start", { bookId: id, type: "chapters" });
  1986. try {
  1987. const { splitChapters } = await import("@actalk/inkos-core");
  1988. const chapters = [...splitChapters(text, splitRegex)];
  1989. const pipeline = new PipelineRunner(await buildPipelineConfig());
  1990. const result = await pipeline.importChapters({ bookId: id, chapters });
  1991. broadcast("import:complete", { bookId: id, type: "chapters", count: result.importedCount });
  1992. return c.json(result);
  1993. } catch (e) {
  1994. broadcast("import:error", { bookId: id, error: String(e) });
  1995. return c.json({ error: String(e) }, 500);
  1996. }
  1997. });
  1998. // --- Import Canon ---
  1999. app.post("/api/v1/books/:id/import/canon", async (c) => {
  2000. const id = c.req.param("id");
  2001. const { fromBookId } = await c.req.json<{ fromBookId: string }>();
  2002. if (!fromBookId) return c.json({ error: "fromBookId is required" }, 400);
  2003. broadcast("import:start", { bookId: id, type: "canon" });
  2004. try {
  2005. const pipeline = new PipelineRunner(await buildPipelineConfig());
  2006. await pipeline.importCanon(id, fromBookId);
  2007. broadcast("import:complete", { bookId: id, type: "canon" });
  2008. return c.json({ ok: true });
  2009. } catch (e) {
  2010. broadcast("import:error", { bookId: id, error: String(e) });
  2011. return c.json({ error: String(e) }, 500);
  2012. }
  2013. });
  2014. // --- Fanfic Init ---
  2015. app.post("/api/v1/fanfic/init", async (c) => {
  2016. const body = await c.req.json<{
  2017. title: string; sourceText: string; sourceName?: string;
  2018. mode?: string; genre?: string; platform?: string;
  2019. targetChapters?: number; chapterWordCount?: number; language?: string;
  2020. }>();
  2021. if (!body.title || !body.sourceText) {
  2022. return c.json({ error: "title and sourceText are required" }, 400);
  2023. }
  2024. const now = new Date().toISOString();
  2025. const bookId = body.title.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]/g, "-").replace(/-+/g, "-").slice(0, 30);
  2026. const bookConfig = {
  2027. id: bookId,
  2028. title: body.title,
  2029. platform: (body.platform ?? "other") as "other",
  2030. genre: (body.genre ?? "other") as "xuanhuan",
  2031. status: "outlining" as const,
  2032. targetChapters: body.targetChapters ?? 100,
  2033. chapterWordCount: body.chapterWordCount ?? 3000,
  2034. fanficMode: (body.mode ?? "canon") as "canon",
  2035. ...(body.language ? { language: body.language as "zh" | "en" } : {}),
  2036. createdAt: now,
  2037. updatedAt: now,
  2038. };
  2039. broadcast("fanfic:start", { bookId, title: body.title });
  2040. try {
  2041. const pipeline = new PipelineRunner(await buildPipelineConfig());
  2042. await pipeline.initFanficBook(bookConfig, body.sourceText, body.sourceName ?? "source", (body.mode ?? "canon") as "canon");
  2043. broadcast("fanfic:complete", { bookId });
  2044. return c.json({ ok: true, bookId });
  2045. } catch (e) {
  2046. broadcast("fanfic:error", { bookId, error: String(e) });
  2047. return c.json({ error: String(e) }, 500);
  2048. }
  2049. });
  2050. // --- Fanfic Show (read canon) ---
  2051. app.get("/api/v1/books/:id/fanfic", async (c) => {
  2052. const id = c.req.param("id");
  2053. const bookDir = state.bookDir(id);
  2054. try {
  2055. const content = await readFile(join(bookDir, "story", "fanfic_canon.md"), "utf-8");
  2056. return c.json({ bookId: id, content });
  2057. } catch {
  2058. return c.json({ bookId: id, content: null });
  2059. }
  2060. });
  2061. // --- Fanfic Refresh ---
  2062. app.post("/api/v1/books/:id/fanfic/refresh", async (c) => {
  2063. const id = c.req.param("id");
  2064. const { sourceText, sourceName } = await c.req.json<{ sourceText: string; sourceName?: string }>();
  2065. if (!sourceText?.trim()) return c.json({ error: "sourceText is required" }, 400);
  2066. broadcast("fanfic:refresh:start", { bookId: id });
  2067. try {
  2068. const book = await state.loadBookConfig(id);
  2069. const pipeline = new PipelineRunner(await buildPipelineConfig());
  2070. await pipeline.importFanficCanon(id, sourceText, sourceName ?? "source", (book.fanficMode ?? "canon") as "canon");
  2071. broadcast("fanfic:refresh:complete", { bookId: id });
  2072. return c.json({ ok: true });
  2073. } catch (e) {
  2074. broadcast("fanfic:refresh:error", { bookId: id, error: String(e) });
  2075. return c.json({ error: String(e) }, 500);
  2076. }
  2077. });
  2078. // --- Radar Scan ---
  2079. app.post("/api/v1/radar/scan", async (c) => {
  2080. broadcast("radar:start", {});
  2081. try {
  2082. const pipeline = new PipelineRunner(await buildPipelineConfig());
  2083. const result = await pipeline.runRadar();
  2084. broadcast("radar:complete", { result });
  2085. return c.json(result);
  2086. } catch (e) {
  2087. broadcast("radar:error", { error: String(e) });
  2088. return c.json({ error: String(e) }, 500);
  2089. }
  2090. });
  2091. // --- Doctor (environment health check) ---
  2092. app.get("/api/v1/doctor", async (c) => {
  2093. const { existsSync } = await import("node:fs");
  2094. const { GLOBAL_ENV_PATH } = await import("@actalk/inkos-core");
  2095. const checks = {
  2096. inkosJson: existsSync(join(root, "inkos.json")),
  2097. projectEnv: existsSync(join(root, ".env")),
  2098. globalEnv: existsSync(GLOBAL_ENV_PATH),
  2099. booksDir: existsSync(join(root, "books")),
  2100. llmConnected: false,
  2101. bookCount: 0,
  2102. };
  2103. try {
  2104. const books = await state.listBooks();
  2105. checks.bookCount = books.length;
  2106. } catch { /* ignore */ }
  2107. try {
  2108. const currentConfig = await loadCurrentProjectConfig({ requireApiKey: false });
  2109. const service = currentConfig.llm.service ?? currentConfig.llm.provider;
  2110. const probe = await probeServiceCapabilities({
  2111. root,
  2112. service,
  2113. apiKey: currentConfig.llm.apiKey,
  2114. baseUrl: currentConfig.llm.baseUrl,
  2115. preferredApiFormat: currentConfig.llm.apiFormat,
  2116. preferredStream: currentConfig.llm.stream,
  2117. preferredModel: currentConfig.llm.model,
  2118. });
  2119. checks.llmConnected = probe.ok;
  2120. } catch { /* ignore */ }
  2121. return c.json(checks);
  2122. });
  2123. return app;
  2124. }
  2125. // --- Standalone runner ---
  2126. export async function startStudioServer(
  2127. root: string,
  2128. port = 4567,
  2129. options?: { readonly staticDir?: string },
  2130. ): Promise<void> {
  2131. const config = await loadProjectConfig(root, { requireApiKey: false });
  2132. const app = createStudioServer(config, root);
  2133. // Serve frontend static files — single process for API + frontend
  2134. if (options?.staticDir) {
  2135. const { readFile: readFileFs } = await import("node:fs/promises");
  2136. const { join: joinPath } = await import("node:path");
  2137. const { existsSync } = await import("node:fs");
  2138. // Serve static assets (js, css, etc.)
  2139. app.get("/assets/*", async (c) => {
  2140. const filePath = joinPath(options.staticDir!, c.req.path);
  2141. try {
  2142. const content = await readFileFs(filePath);
  2143. const ext = filePath.split(".").pop() ?? "";
  2144. const contentTypes: Record<string, string> = {
  2145. js: "application/javascript",
  2146. css: "text/css",
  2147. svg: "image/svg+xml",
  2148. png: "image/png",
  2149. ico: "image/x-icon",
  2150. json: "application/json",
  2151. };
  2152. return new Response(content, {
  2153. headers: { "Content-Type": contentTypes[ext] ?? "application/octet-stream" },
  2154. });
  2155. } catch {
  2156. return c.notFound();
  2157. }
  2158. });
  2159. // SPA fallback — serve index.html for all non-API routes
  2160. const indexPath = joinPath(options.staticDir!, "index.html");
  2161. if (existsSync(indexPath)) {
  2162. const indexHtml = await readFileFs(indexPath, "utf-8");
  2163. app.get("*", (c) => {
  2164. if (c.req.path.startsWith("/api/v1/")) return c.notFound();
  2165. return c.html(indexHtml);
  2166. });
  2167. }
  2168. }
  2169. console.log(`InkOS Studio running on http://localhost:${port}`);
  2170. serve({ fetch: app.fetch, port });
  2171. }