"use strict";(()=>{var a={};a.id=788,a.ids=[788],a.modules={261:a=>{a.exports=require("next/dist/shared/lib/router/utils/app-paths")},3295:a=>{a.exports=require("next/dist/server/app-render/after-task-async-storage.external.js")},10846:a=>{a.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},19771:a=>{a.exports=require("process")},21820:a=>{a.exports=require("os")},28354:a=>{a.exports=require("util")},29021:a=>{a.exports=require("fs")},29294:a=>{a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},33873:a=>{a.exports=require("path")},42007:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.r(b),c.d(b,{POST:()=>j,dynamic:()=>l});var e=c(23211),f=c(97990),g=c(29021),h=c(33873),i=a([f]);f=(i.then?(await i)():i)[0];let l="force-dynamic";async function j(a){try{let{action:b,cwd:d,args:i={}}=await a.json();if(!d)return e.NextResponse.json({error:"创作工作区目录 (cwd) 不能为空"},{status:400});if(!(0,g.existsSync)(d))if("init"!==b)return e.NextResponse.json({error:`创作工作区目录不存在: ${d}`},{status:400});else try{(0,g.mkdirSync)(d,{recursive:!0})}catch(a){return e.NextResponse.json({error:`无法创建创作工作区目录: ${a.message||a}`},{status:500})}let j=[],l=null,m=[];switch(b){case"init":j=["init"],i.name&&j.push(i.name);break;case"book-create":if(!i.title)return e.NextResponse.json({error:"书籍标题不能为空"},{status:400});j=["book","create","--title",i.title],i.genre&&j.push("--genre",i.genre);let n=i.brief||"";try{let a=c(29021),b=[d,(0,h.join)(d,"Temp"),(0,h.join)(d,"temp")],e=["novel_framework_v2.md","novel_framework.md","novel-framework.md","架构.md","构架.md"],f=["character_profiles.md","character-profiles.md","character.md","人设.md"],g="",j="";for(let c of b)if(a.existsSync(c)){for(let b of e){let e=(0,h.join)(c,b);if(a.existsSync(e)&&a.statSync(e).isFile()){g=a.readFileSync(e,"utf8"),m.push((0,h.join)(c===d?"":c.endsWith("Temp")?"Temp":"temp",b).replace(/\\/g,"/"));break}}if(g)break}for(let c of b)if(a.existsSync(c)){for(let b of f){let e=(0,h.join)(c,b);if(a.existsSync(e)&&a.statSync(e).isFile()){j=a.readFileSync(e,"utf8"),m.push((0,h.join)(c===d?"":c.endsWith("Temp")?"Temp":"temp",b).replace(/\\/g,"/"));break}}if(j)break}if(g||j){let a=[];g&&a.push(`# 导入的构架设定

${g}`),j&&a.push(`# 导入的角色人设

${j}`),i.brief&&a.push(`# 用户补充创意

${i.brief}`),n=a.join("\n\n---\n\n"),console.log(`[API/inkos] Book create using files: ${m.join(", ")}`)}}catch(a){console.error("[API/inkos] Failed to scan local framework/character files:",a)}if(n)try{let a=c(29021);l=(0,h.join)(d,"radar",`temp_brief_${Date.now()}.md`),a.writeFileSync(l,n,"utf8"),j.push("--brief",l)}catch(a){return e.NextResponse.json({error:`无法写入创意简报临时文件: ${a.message}`},{status:500})}i.chapterWords&&j.push("--chapter-words",String(i.chapterWords));break;case"fanfic-init":if(!i.title)return e.NextResponse.json({error:"同人书籍标题不能为空"},{status:400});if(!i.from)return e.NextResponse.json({error:"同人原作素材绝对路径不能为空"},{status:400});j=["fanfic","init","--title",i.title,"--from",i.from],i.mode&&j.push("--mode",i.mode),i.genre&&j.push("--genre",i.genre),i.platform&&j.push("--platform",i.platform),i.targetChapters&&j.push("--target-chapters",String(i.targetChapters)),i.chapterWords&&j.push("--chapter-words",String(i.chapterWords)),i.json&&j.push("--json");break;case"fanfic-refresh":if(!i.from)return e.NextResponse.json({error:"同人原作素材绝对路径不能为空"},{status:400});j=["fanfic","refresh"],i.bookId&&j.push(i.bookId),j.push("--from",i.from),i.json&&j.push("--json");break;case"write-next":{j=["write","next"],i.bookId&&j.push(i.bookId),i.count&&j.push("--count",String(i.count)),i.words&&j.push("--words",String(i.words)),i.json&&j.push("--json");let a=i.bookId,b=i.activeChapter;if(a&&"number"==typeof b){let j=(0,h.join)(d,"books",a,"chapters"),l=(0,h.join)(j,"index.json");if((0,g.existsSync)(j))try{let g,n=c(29021),o=n.readdirSync(j),p=o.map(a=>{let b=a.match(/^(\d+)/);return b?parseInt(b[1],10):null}).filter(a=>null!==a).sort((a,b)=>a-b),q=p.length>0?Math.max(...p):0,r=String(b).padStart(4,"0"),s=o.find(a=>a.startsWith(r)&&a.endsWith(".md")),t=!1;if(s){let a=n.readFileSync((0,h.join)(j,s),"utf8").trim();(0===a.length||a.includes("章节占位")||a.includes("占位草稿")||a.length<300)&&(t=!0)}g=t?b:b+1;let u=String(g).padStart(4,"0"),v=o.find(a=>a.startsWith(u)&&a.endsWith(".md")),w=!1;if(v){let a=n.readFileSync((0,h.join)(j,v),"utf8").trim();a.length>0&&!a.includes("章节占位")&&!a.includes("占位草稿")&&a.length>=300&&(w=!0)}let x=[];if(n.existsSync(l))try{let a=n.readFileSync(l,"utf8"),b=JSON.parse(a);Array.isArray(b)&&(x=b.map(a=>a?.number).filter(a=>"number"==typeof a&&a>0).sort((a,b)=>a-b))}catch(a){}let y=x.filter(a=>!p.includes(a));if(w){let b=p.filter(a=>a>=g);if(b.length>0)if(!i.forceRewrite)return e.NextResponse.json({success:!1,conflict:!0,nextChapterToCreate:g,chaptersToDiscard:b,message:`检测到您的书库中已存在后续的第 ${b.join(", ")} 章。在第 ${g-1} 章后重新续写，将自动覆盖并废弃后续所有章节。`},{status:409});else{console.log(`[write-next auto-healing] Confirmed force rewrite. Rolling back state to chapter ${g-1}`);try{let b=["write","rewrite",a,String(g),"--force"];await (0,f.IV)(b,{cwd:d}),console.log("[write-next auto-healing] Rollback command completed successfully.")}catch(a){console.error("[write-next auto-healing] Rollback failed:",a)}}}else{if(console.log(`[write-next auto-healing] Target chapter ${g} is missing or a placeholder. Filling the gap.`),v&&(console.log(`[write-next auto-healing] Deleting placeholder file ${v} to let CLI calculate contiguous progress correctly.`),n.unlinkSync((0,h.join)(j,v))),n.existsSync(l))try{let a=n.readFileSync(l,"utf8"),b=JSON.parse(a);if(Array.isArray(b)){let a=b.filter(a=>a?.number!==g);n.writeFileSync(l,JSON.stringify(a,null,2),"utf8"),console.log(`[write-next auto-healing] Removed Chapter ${g} from index.json to allow rebuilding.`)}}catch(a){console.error("[write-next auto-healing] Failed to clean up targetChapter from index.json:",a)}if(b>=q&&y.length>0){for(let a of y.filter(a=>a<g)){let b=String(a).padStart(4,"0"),c=(0,h.join)(j,`${b}_章节占位.md`);n.writeFileSync(c,`# 第 ${a} 章 占位草稿

（此章节文件曾被手动删除，系统已自动创建占位文件以维持故事连贯性。请在此处重新补充内容。）
`,"utf8"),console.log(`[write-next auto-healing] Created placeholder for Chapter ${a} at ${c}`)}m.push(`books/${a}/chapters/index.json`)}}console.log(`[write-next auto-healing] Restoring state to snapshot of chapter ${g-1}`),await k(d,a,g-1)}catch(a){console.error("[write-next auto-healing] Failed to execute check:",a)}}break}case"draft":{j=["draft"],i.bookId&&j.push(i.bookId),i.words&&j.push("--words",String(i.words)),i.context&&j.push("--context",i.context),i.json&&j.push("--json");let a=i.bookId,b=i.activeChapter;if(a&&"number"==typeof b){let j=(0,h.join)(d,"books",a,"chapters"),l=(0,h.join)(j,"index.json");if((0,g.existsSync)(j))try{let g,n=c(29021),o=n.readdirSync(j),p=o.map(a=>{let b=a.match(/^(\d+)/);return b?parseInt(b[1],10):null}).filter(a=>null!==a).sort((a,b)=>a-b),q=p.length>0?Math.max(...p):0,r=String(b).padStart(4,"0"),s=o.find(a=>a.startsWith(r)&&a.endsWith(".md")),t=!1;if(s){let a=n.readFileSync((0,h.join)(j,s),"utf8").trim();(0===a.length||a.includes("章节占位")||a.includes("占位草稿")||a.length<300)&&(t=!0)}g=t?b:b+1;let u=String(g).padStart(4,"0"),v=o.find(a=>a.startsWith(u)&&a.endsWith(".md")),w=!1;if(v){let a=n.readFileSync((0,h.join)(j,v),"utf8").trim();a.length>0&&!a.includes("章节占位")&&!a.includes("占位草稿")&&a.length>=300&&(w=!0)}let x=[];if(n.existsSync(l))try{let a=n.readFileSync(l,"utf8"),b=JSON.parse(a);Array.isArray(b)&&(x=b.map(a=>a?.number).filter(a=>"number"==typeof a&&a>0).sort((a,b)=>a-b))}catch(a){}let y=x.filter(a=>!p.includes(a));if(w){let b=p.filter(a=>a>=g);if(b.length>0)if(!i.forceRewrite)return e.NextResponse.json({success:!1,conflict:!0,nextChapterToCreate:g,chaptersToDiscard:b,message:`检测到您的书库中已存在后续的第 ${b.join(", ")} 章。在第 ${g-1} 章后重新起草，将自动覆盖并废弃后续所有章节。`},{status:409});else{console.log(`[draft auto-healing] Confirmed force rewrite. Rolling back state to chapter ${g-1}`);try{let b=["write","rewrite",a,String(g),"--force"];await (0,f.IV)(b,{cwd:d}),console.log("[draft auto-healing] Rollback command completed successfully.")}catch(a){console.error("[draft auto-healing] Rollback failed:",a)}}}else{if(console.log(`[draft auto-healing] Target chapter ${g} is missing or a placeholder. Filling the gap.`),v&&(console.log(`[draft auto-healing] Deleting placeholder file ${v} to let CLI calculate contiguous progress correctly.`),n.unlinkSync((0,h.join)(j,v))),n.existsSync(l))try{let a=n.readFileSync(l,"utf8"),b=JSON.parse(a);if(Array.isArray(b)){let a=b.filter(a=>a?.number!==g);n.writeFileSync(l,JSON.stringify(a,null,2),"utf8"),console.log(`[draft auto-healing] Removed Chapter ${g} from index.json to allow rebuilding.`)}}catch(a){console.error("[draft auto-healing] Failed to clean up targetChapter from index.json:",a)}if(b>=q&&y.length>0){for(let a of y.filter(a=>a<g)){let b=String(a).padStart(4,"0"),c=(0,h.join)(j,`${b}_章节占位.md`);n.writeFileSync(c,`# 第 ${a} 章 占位草稿

（此章节文件曾被手动删除，系统已自动创建占位文件以维持故事连贯性。请在此处重新补充内容。）
`,"utf8"),console.log(`[draft auto-healing] Created placeholder for Chapter ${a} at ${c}`)}m.push(`books/${a}/chapters/index.json`)}}console.log(`[draft auto-healing] Restoring state to snapshot of chapter ${g-1}`),await k(d,a,g-1)}catch(a){console.error("[draft auto-healing] Failed to execute check:",a)}}break}case"consolidate":j=["consolidate"],i.bookId&&j.push(i.bookId),i.json&&j.push("--json");break;case"audit":if(!i.chapter)return e.NextResponse.json({error:"审计的目标章节文件不能为空"},{status:400});j=["audit"];let o=i.bookId,p=i.chapter;if(i.chapter.includes("/")||i.chapter.includes("\\")){let a=i.chapter.replace(/\\/g,"/").split("/");"books"===a[0]&&a[1]&&(o=a[1]);let b=a[a.length-1].match(/^(\d+)/);b&&(p=String(parseInt(b[1],10)))}o&&j.push(o),j.push(p),i.json&&j.push("--json");break;case"plan":j=["plan","chapter"],i.bookId&&j.push(i.bookId),i.context&&j.push("--context",i.context);break;case"compose":j=["compose","chapter"],i.bookId&&j.push(i.bookId);break;case"revise":j=["revise"],i.bookId&&j.push(i.bookId),i.chapter&&j.push(String(i.chapter)),i.mode&&j.push("--mode",i.mode),i.brief&&j.push("--brief",i.brief),i.json&&j.push("--json");break;case"write-sync":j=["write","sync"],i.bookId&&j.push(i.bookId),i.chapter&&j.push(String(i.chapter)),i.brief&&j.push("--brief",i.brief),i.json&&j.push("--json");break;case"status":j=["status"],i.bookId&&j.push(i.bookId),i.json&&j.push("--json");break;case"export":j=["export"],i.bookId&&j.push(i.bookId),i.format&&j.push("--format",i.format),i.approvedOnly&&j.push("--approved-only"),i.output&&j.push("--output",i.output),i.json&&j.push("--json");break;case"review-approve":if(!i.chapter)return e.NextResponse.json({error:"审核章节号不能为空"},{status:400});j=["review","approve"],i.bookId&&j.push(i.bookId),j.push(String(i.chapter)),i.json&&j.push("--json");break;case"review-reject":if(!i.chapter)return e.NextResponse.json({error:"驳回章节号不能为空"},{status:400});j=["review","reject"],i.bookId&&j.push(i.bookId),j.push(String(i.chapter)),i.reason&&j.push("--reason",i.reason),i.keepSubsequent&&j.push("--keep-subsequent"),i.json&&j.push("--json");break;case"import-chapters":if(!i.from)return e.NextResponse.json({error:"导入源路径不能为空"},{status:400});j=["import","chapters"],i.bookId&&j.push(i.bookId),j.push("--from",i.from),i.split&&j.push("--split",i.split),i.resumeFrom&&j.push("--resume-from",String(i.resumeFrom)),i.series&&j.push("--series"),i.json&&j.push("--json");break;case"import-canon":if(!i.from)return e.NextResponse.json({error:"原著/前作 Book ID 不能为空"},{status:400});j=["import","canon"],i.bookId&&j.push(i.bookId),j.push("--from",i.from),i.json&&j.push("--json");break;case"style-import":{let a=i.from;if(i.content)try{let b=c(29021),e=(0,h.join)(d,"Temp");b.existsSync(e)||b.mkdirSync(e,{recursive:!0}),a=(0,h.join)(e,`style_sample_${Date.now()}.txt`),b.writeFileSync(a,i.content,"utf8"),l=a}catch(a){return e.NextResponse.json({error:`无法创建临时样文本文件: ${a.message||a}`},{status:500})}if(!a)return e.NextResponse.json({error:"样文文件路径或内容不能为空"},{status:400});j=["style","import",a],i.bookId&&j.push(i.bookId),i.name&&j.push("--name",i.name),i.statsOnly&&j.push("--stats-only"),i.json&&j.push("--json");break}case"style-list":{let a=c(29021),b=i.bookId;if(!b)return e.NextResponse.json({error:"书籍ID不能为空"},{status:400});let f=(0,h.join)(d,"books",b,"story"),g=(0,h.join)(f,"styles"),j=(0,h.join)(f,"style_guide.md");a.existsSync(g)||a.mkdirSync(g,{recursive:!0});let k="default";if(a.existsSync(j)){let b=a.readFileSync(j,"utf8"),c=b.match(/>\s*Profile:\s*\*\*([^*]+)\*\*/i);c&&(k=c[1].trim());let d=a.readdirSync(g).filter(a=>a.endsWith(".md"));0===d.length&&a.writeFileSync((0,h.join)(g,`${k}.md`),b,"utf8")}let l=a.readdirSync(g).filter(a=>a.endsWith(".md")).map(a=>a.substring(0,a.length-3)),m=null;if(a.existsSync(j)){let b=a.readFileSync(j,"utf8").match(/>\s*Profile:\s*\*\*([^*]+)\*\*/i);m=b?b[1].trim():"default"}return e.NextResponse.json({styles:l,activeStyle:m})}case"style-switch":{let a=c(29021),b=i.bookId,f=i.styleName;if(!b||!f)return e.NextResponse.json({error:"书籍ID和文风名称不能为空"},{status:400});let g=(0,h.join)(d,"books",b,"story"),j=(0,h.join)(g,"styles"),k=(0,h.join)(j,`${f}.md`),l=(0,h.join)(g,"style_guide.md");if(!a.existsSync(k))return e.NextResponse.json({error:`未找到文风配置: ${f}`},{status:404});let m=a.readFileSync(k,"utf8");return a.writeFileSync(l,m,"utf8"),e.NextResponse.json({success:!0,activeStyle:f})}case"radar-scan":j=["radar","scan"],i.json&&j.push("--json");break;case"aigc-detect":j=["detect"],i.bookId&&j.push(i.bookId),i.chapter&&j.push(String(i.chapter)),i.all&&j.push("--all"),i.stats&&j.push("--stats"),i.provider&&j.push("--provider",i.provider),i.json&&j.push("--json");break;case"short-run":if(!i.direction)return e.NextResponse.json({error:"短篇小说创作方向 (direction) 不能为空"},{status:400});j=["short","run","--direction",i.direction],i.chapters&&j.push("--chapters",String(i.chapters)),i.chars&&j.push("--chars",String(i.chars)),i.stage&&j.push("--stage",i.stage),i.storyId&&j.push("--story-id",i.storyId),i.noCover&&j.push("--no-cover"),i.model&&j.push("--model",i.model),i.json&&j.push("--json");break;case"custom":if(!i.command||!Array.isArray(i.command))return e.NextResponse.json({error:"自定义指令 args.command 必须是字符串数组"},{status:400});j=i.command;break;default:return e.NextResponse.json({error:`未知的命令行为: ${b}`},{status:400})}console.log(`[API/inkos] Spawning streaming local CLI in CWD "${d}": node packages/cli/dist/index.js ${j.join(" ")}`);let q=(0,f.WZ)(j,{cwd:d}),r=new ReadableStream({start(a){let e=b=>{try{a.enqueue(new TextEncoder().encode(JSON.stringify(b)+"\n"))}catch(a){}},f="",g="",j=!1,k=setTimeout(()=>{console.warn("[API/inkos] Process timed out after 1800s, killing child."),j=!0,q.kill("SIGTERM"),e({type:"stderr",data:"\n⚠️ 任务超时（超过 1800 秒），已自动终止。\n"})},18e5);q.stdout?.on("data",a=>{let b=a.toString();f+=b,e({type:"stdout",data:b})}),q.stderr?.on("data",a=>{let b=a.toString();g+=b,e({type:"stderr",data:b})}),q.on("close",n=>{if(clearTimeout(k),0===n&&!j&&"style-import"===b)try{let a=c(29021),b=i.bookId,e=i.name||"default";if(b){let c=(0,h.join)(d,"books",b,"story"),f=(0,h.join)(c,"style_guide.md"),g=(0,h.join)(c,"styles");if(a.existsSync(f)){a.existsSync(g)||a.mkdirSync(g,{recursive:!0});let b=a.readFileSync(f,"utf8");a.writeFileSync((0,h.join)(g,`${e}.md`),b,"utf8"),console.log(`[API/inkos] Successfully copied newly imported style to styles/${e}.md`)}}}catch(a){console.error("[API/inkos] Failed to copy style guide to styles dir after import:",a)}if(l)try{let a=c(29021);a.existsSync(l)&&a.unlinkSync(l)}catch(a){console.error("[API/inkos] Failed to delete temp brief file:",a)}e({type:"result",success:0===n&&!j,error:j?"任务运行超时（超过 1800 秒），已自动终止。":void 0,stdout:f,stderr:g,code:n,localFilesUsed:m.length>0?m:void 0}),a.close()}),q.on("error",b=>{if(clearTimeout(k),l)try{let a=c(29021);a.existsSync(l)&&a.unlinkSync(l)}catch(a){}e({type:"result",success:!1,error:j?"任务运行超时（超过 1800 秒），已自动终止。":b.message,stdout:f,stderr:g,localFilesUsed:m.length>0?m:void 0}),a.close()})},cancel(){try{q.kill("SIGTERM")}catch(a){}}});return new Response(r,{headers:{"Content-Type":"application/x-ndjson","Cache-Control":"no-cache",Connection:"keep-alive"}})}catch(a){return console.error("[API/inkos] Execution failed:",a),e.NextResponse.json({success:!1,error:a.message||String(a),stdout:a.stdout||"",stderr:a.stderr||""},{status:500})}}async function k(a,b,d){let e=c(29021),f=(0,h.join)(a,"books",b,"story"),g=(0,h.join)(f,"snapshots",String(d));if(!e.existsSync(g))return void console.warn(`[write-next auto-healing] Snapshot directory ${g} does not exist. Skipping state restore.`);let i=["current_state.md","pending_hooks.md"];for(let a of i){let b=(0,h.join)(g,a),c=(0,h.join)(f,a);e.existsSync(b)&&(e.writeFileSync(c,e.readFileSync(b)),console.log(`[write-next auto-healing] Restored required state file: ${a}`))}for(let a of["current_state.md","particle_ledger.md","pending_hooks.md","chapter_summaries.md","subplot_board.md","emotional_arcs.md","character_matrix.md"].filter(a=>!i.includes(a))){let b=(0,h.join)(g,a),c=(0,h.join)(f,a);e.existsSync(b)?(e.writeFileSync(c,e.readFileSync(b)),console.log(`[write-next auto-healing] Restored optional state file: ${a}`)):e.existsSync(c)&&e.unlinkSync(c)}let j=(0,h.join)(f,"state"),k=(0,h.join)(g,"state");if(e.existsSync(k)){for(let a of(e.existsSync(j)||e.mkdirSync(j,{recursive:!0}),e.readdirSync(k)))e.writeFileSync((0,h.join)(j,a),e.readFileSync((0,h.join)(k,a)));console.log("[write-next auto-healing] Restored structured state files from snapshot.")}else if(e.existsSync(j))for(let a of e.readdirSync(j))e.unlinkSync((0,h.join)(j,a))}d()}catch(a){d(a)}})},44870:a=>{a.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},63033:a=>{a.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},73978:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.r(b),c.d(b,{handler:()=>y,patchFetch:()=>x,routeModule:()=>z,serverHooks:()=>C,workAsyncStorage:()=>A,workUnitAsyncStorage:()=>B});var e=c(19225),f=c(84006),g=c(8317),h=c(99373),i=c(34775),j=c(24235),k=c(261),l=c(54365),m=c(90771),n=c(73461),o=c(67798),p=c(92280),q=c(62018),r=c(45696),s=c(47929),t=c(86439),u=c(37527),v=c(42007),w=a([v]);v=(w.then?(await w)():w)[0];let z=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/inkos/route",pathname:"/api/inkos",filename:"route",bundlePath:"app/api/inkos/route"},distDir:".next",relativeProjectDir:"",resolvedPagePath:"E:\\ink-xY\\app\\api\\inkos\\route.ts",nextConfigOutput:"",userland:v}),{workAsyncStorage:A,workUnitAsyncStorage:B,serverHooks:C}=z;function x(){return(0,g.patchFetch)({workAsyncStorage:A,workUnitAsyncStorage:B})}async function y(a,b,c){c.requestMeta&&(0,h.setRequestMeta)(a,c.requestMeta),z.isDev&&(0,h.addRequestMeta)(a,"devRequestTimingInternalsEnd",process.hrtime.bigint());let d="/api/inkos/route";"/index"===d&&(d="/");let e=await z.prepare(a,b,{srcPage:d,multiZoneDraftMode:!1});if(!e)return b.statusCode=400,b.end("Bad Request"),null==c.waitUntil||c.waitUntil.call(c,Promise.resolve()),null;let{buildId:g,params:v,nextConfig:w,parsedUrl:x,isDraftMode:y,prerenderManifest:A,routerServerContext:B,isOnDemandRevalidate:C,revalidateOnlyGenerated:D,resolvedPathname:E,clientReferenceManifest:F,serverActionsManifest:G}=e,H=(0,k.normalizeAppPath)(d),I=!!(A.dynamicRoutes[H]||A.routes[E]),J=async()=>((null==B?void 0:B.render404)?await B.render404(a,b,x,!1):b.end("This page could not be found"),null);if(I&&!y){let a=!!A.routes[E],b=A.dynamicRoutes[H];if(b&&!1===b.fallback&&!a){if(w.adapterPath)return await J();throw new t.NoFallbackError}}let K=null;!I||z.isDev||y||(K=E,K="/index"===K?"/":K);let L=!0===z.isDev||!I,M=I&&!L;G&&F&&(0,j.setManifestsSingleton)({page:d,clientReferenceManifest:F,serverActionsManifest:G});let N=a.method||"GET",O=(0,i.getTracer)(),P=O.getActiveScopeSpan(),Q=!!(null==B?void 0:B.isWrappedByNextServer),R=!!(0,h.getRequestMeta)(a,"minimalMode"),S=(0,h.getRequestMeta)(a,"incrementalCache")||await z.getIncrementalCache(a,w,A,R);null==S||S.resetRequestCache(),globalThis.__incrementalCache=S;let T={params:v,previewProps:A.preview,renderOpts:{experimental:{authInterrupts:!!w.experimental.authInterrupts},cacheComponents:!!w.cacheComponents,supportsDynamicResponse:L,incrementalCache:S,cacheLifeProfiles:w.cacheLife,waitUntil:c.waitUntil,onClose:a=>{b.on("close",a)},onAfterTaskError:void 0,onInstrumentationRequestError:(b,c,d,e)=>z.onRequestError(a,b,d,e,B)},sharedContext:{buildId:g}},U=new l.NodeNextRequest(a),V=new l.NodeNextResponse(b),W=m.NextRequestAdapter.fromNodeNextRequest(U,(0,m.signalFromNodeResponse)(b));try{let e,g=async a=>z.handle(W,T).finally(()=>{if(!a)return;a.setAttributes({"http.status_code":b.statusCode,"next.rsc":!1});let c=O.getRootSpanAttributes();if(!c)return;if(c.get("next.span_type")!==n.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${c.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let f=c.get("next.route");if(f){let b=`${N} ${f}`;a.setAttributes({"next.route":f,"http.route":f,"next.span_name":b}),a.updateName(b),e&&e!==a&&(e.setAttribute("http.route",f),e.updateName(b))}else a.updateName(`${N} ${d}`)}),h=async e=>{var h,i;let j=async({previousCacheEntry:f})=>{try{if(!R&&C&&D&&!f)return b.statusCode=404,b.setHeader("x-nextjs-cache","REVALIDATED"),b.end("This page could not be found"),null;let d=await g(e);a.fetchMetrics=T.renderOpts.fetchMetrics;let h=T.renderOpts.pendingWaitUntil;h&&c.waitUntil&&(c.waitUntil(h),h=void 0);let i=T.renderOpts.collectedTags;if(!I)return await (0,p.I)(U,V,d,T.renderOpts.pendingWaitUntil),null;{let a=await d.blob(),b=(0,q.toNodeOutgoingHttpHeaders)(d.headers);i&&(b[s.NEXT_CACHE_TAGS_HEADER]=i),!b["content-type"]&&a.type&&(b["content-type"]=a.type);let c=void 0!==T.renderOpts.collectedRevalidate&&!(T.renderOpts.collectedRevalidate>=s.INFINITE_CACHE)&&T.renderOpts.collectedRevalidate,e=void 0===T.renderOpts.collectedExpire||T.renderOpts.collectedExpire>=s.INFINITE_CACHE?void 0:T.renderOpts.collectedExpire;return{value:{kind:u.CachedRouteKind.APP_ROUTE,status:d.status,body:Buffer.from(await a.arrayBuffer()),headers:b},cacheControl:{revalidate:c,expire:e}}}}catch(b){throw(null==f?void 0:f.isStale)&&await z.onRequestError(a,b,{routerKind:"App Router",routePath:d,routeType:"route",revalidateReason:(0,o.c)({isStaticGeneration:M,isOnDemandRevalidate:C})},!1,B),b}},k=await z.handleResponse({req:a,nextConfig:w,cacheKey:K,routeKind:f.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:A,isRoutePPREnabled:!1,isOnDemandRevalidate:C,revalidateOnlyGenerated:D,responseGenerator:j,waitUntil:c.waitUntil,isMinimalMode:R});if(!I)return null;if((null==k||null==(h=k.value)?void 0:h.kind)!==u.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==k||null==(i=k.value)?void 0:i.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});R||b.setHeader("x-nextjs-cache",C?"REVALIDATED":k.isMiss?"MISS":k.isStale?"STALE":"HIT"),y&&b.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let l=(0,q.fromNodeOutgoingHttpHeaders)(k.value.headers);return R&&I||l.delete(s.NEXT_CACHE_TAGS_HEADER),!k.cacheControl||b.getHeader("Cache-Control")||l.get("Cache-Control")||l.set("Cache-Control",(0,r.getCacheControlHeader)(k.cacheControl)),await (0,p.I)(U,V,new Response(k.value.body,{headers:l,status:k.value.status||200})),null};Q&&P?await h(P):(e=O.getActiveScopeSpan(),await O.withPropagatedContext(a.headers,()=>O.trace(n.BaseServerSpan.handleRequest,{spanName:`${N} ${d}`,kind:i.SpanKind.SERVER,attributes:{"http.method":N,"http.target":a.url}},h),void 0,!Q))}catch(b){if(b instanceof t.NoFallbackError||await z.onRequestError(a,b,{routerKind:"App Router",routePath:H,routeType:"route",revalidateReason:(0,o.c)({isStaticGeneration:M,isOnDemandRevalidate:C})},!1,B),I)throw b;return await (0,p.I)(U,V,new Response(null,{status:500})),null}}d()}catch(a){d(a)}})},75430:a=>{a.exports=import("@earendil-works/pi-coding-agent")},79646:a=>{a.exports=require("child_process")},86439:a=>{a.exports=require("next/dist/shared/lib/no-fallback-error.external")}};var b=require("../../../webpack-runtime.js");b.C(a);var c=b.X(0,[741,813,162],()=>b(b.s=73978));module.exports=c})();