"use strict";(()=>{var a={};a.id=8665,a.ids=[8665],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")},3421:(a,b,c)=>{Object.defineProperty(b,"I",{enumerable:!0,get:function(){return g}});let d=c(71237),e=c(55088),f=c(17679);async function g(a,b,c,g){if((0,d.isNodeNextResponse)(b)){var h;b.statusCode=c.status,b.statusMessage=c.statusText;let d=["set-cookie","www-authenticate","proxy-authenticate","vary"];null==(h=c.headers)||h.forEach((a,c)=>{if("x-middleware-set-cookie"!==c.toLowerCase())if("set-cookie"===c.toLowerCase())for(let d of(0,f.splitCookiesString)(a))b.appendHeader(c,d);else{let e=void 0!==b.getHeader(c);(d.includes(c.toLowerCase())||!e)&&b.appendHeader(c,a)}});let{originalResponse:i}=b;c.body&&"HEAD"!==a.method?await (0,e.pipeToNodeResponse)(c.body,i,g):i.end()}}},6753:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.r(b),c.d(b,{POST:()=>y,dynamic:()=>A,runtime:()=>z});var e=c(1511),f=c(19151),g=c(65451),h=c(511),i=c(1623),j=c(91648),k=c(65072),l=c(72326),m=c(60105),n=c(41264),o=c(37437),p=c(63289),q=c(85728),r=a([e,f,g,h,i,j,k,l,m]);[e,f,g,h,i,j,k,l,m]=r.then?(await r)():r;let z="nodejs",A="force-dynamic";function s(a){if(!a||a.length<280)return!1;let b=/^#{1,3}\s+\S/m.test(a),c=a.split(/\s+/).filter(Boolean).length;return b||c>350}function t(a){let b=a.match(/^#{1,3}\s+(.+)$/m);if(b)return b[1].trim().replace(/[*_`#]/g,"").slice(0,80);let c=a.split("\n").map(a=>a.trim()).find(a=>a&&!/^[\-*\d>]/.test(a));return c&&c.length<80?c.replace(/^#+\s*/,"").replace(/[*_`]/g,""):"Response"}function u(a){let b=[];for(let c of[...a.matchAll(/```(?:html|HTML)\s*(<![\s\S]*?<\/html>)\s*```/gi)])b.push({html:c[1].trim(),full:c[0]});if(!b.length){let c=a.match(/(<!doctype\s+html[\s\S]*?<\/html>)/i);c&&b.push({html:c[1].trim(),full:c[1]})}return b}async function v(a,{emit:b,context:c={}}={}){let d,e=[],f=/```madarx-action\s*([\s\S]*?)```/gi;for(;null!==(d=f.exec(a));){let a,f;try{a=JSON.parse(d[1].trim())}catch{continue}let{tool:g,input:i}=a;if(!g||!i)continue;b&&b("tool_start",{name:g,input:i});let j=!1;try{f=await (0,h.o8)(g,i,c)}catch(a){f={error:a.message},j=!0}b&&b("tool_result",{name:g,output:f,isError:j}),e.push({tool:g,result:f})}return e}function w(a){return a.replace(/```madarx-action[\s\S]*?```/gi,"").trim()}function x(a,{sessionArtifactId:b,projectId:c=null}={}){let d=a?a.trim():"";if(!d||!s(d))return null;if(b)try{return{artifact_id:(0,m.eP)(b,{content:a}).artifact_id,created:!1}}catch{}try{return{artifact_id:(0,m.Dg)({title:t(a)||"Response",kind:"markdown",content:a,project_id:c}).artifact_id,created:!0}}catch{return null}}async function y(a){let b,c;try{b=await (0,e.OC)(a)}catch(a){if(a&&"object"==typeof a&&a.status)return Response.json({error:a.error||"unauthorized"},{status:a.status});throw a}try{c=await a.json()}catch{return new Response("Invalid JSON",{status:400})}c={...c,user_id:b.user_id};let d=Array.isArray(c.messages)?c.messages:[];if(!d.length)return new Response("messages required",{status:400});let r=await (0,i.zr)(),y=(c.model&&r.find(a=>a.id===c.model)?c.model:null)??(0,i.E1)(),z=r.find(a=>a.id===y),A=z?.engine||"anthropic",B="string"==typeof c.session_id?c.session_id:null;B&&!(0,m.fk)(B)&&(B=null),B||(B=(0,m.fB)({model:y}).id);let C="string"==typeof c.session_artifact_id?c.session_artifact_id:null,D="string"==typeof c.project_id&&c.project_id.trim()?c.project_id.trim():"personal",E={project_id:D,user_id:b.user_id,org_id:b.org_id},F=Array.isArray(c.pending_approvals)?c.pending_approvals.filter(a=>a&&"string"==typeof a.approval_id&&"string"==typeof a.tool_name).map(a=>({approval_id:String(a.approval_id),tool_name:String(a.tool_name),used:!1})):[],G=new Set(["spec_invalid","spec_required","slug_required","slug_in_use","version_bump_required","not_found","insufficient_role"]),H=(0,q.PT)(function(a){for(let b=a.length-1;b>=0;b--){let c=a[b];if("user"===c.role&&Array.isArray(c.attachments)&&c.attachments.length)return c.attachments}return[]}(d)),I=(0,q.zr)(H),J=function(a){for(let b=a.length-1;b>=0;b--){let c=a[b];if("user"===c.role&&"string"==typeof c.content)return c.content}return""}(d);if(J)try{(0,m.UA)(B,{role:"user",content:J,model:y})}catch{}let K="claude-code"===A||"codex"===A,L=C?`

Active artifact for this conversation: artifact_id="${C}". Use update_artifact with this ID instead of create_artifact when refining, extending, or following up on the existing result.`:"",M=C?`

ACTIVE ARTIFACT IN VIEW: There is already a designed HTML artifact open on the canvas from a previous turn. If the user is asking to refine, edit, restyle, extend, or change anything about it, output the FULL UPDATED HTML page in your \`\`\`html ... \`\`\` fence — madarX will replace the existing artifact in place. Do NOT start from scratch unless the user explicitly asks for a brand-new page.`:"",N=K?"":`

Active model: ${z?.label||y} (id: ${y}). If the user asks which model you are, answer with this exact name. Do not guess from training-data priors.`,O=K?function(){let a=(0,j.nX)();return`${(0,i.uB)()}

You are the madarX Main Agent — local-first AI orchestrator. You report to the owner as a chief of staff reports to a chairman: bring back the actual answer, not a list of places they could go to find it.

madarX is a VISUAL workspace, not a chatbot. The chat bubble exists only for short conversational exchanges. Anything that would make the reader scroll, scan, or compare belongs in a designed HTML artifact rendered on the canvas — never as a long markdown blob in chat.

What you CAN do:
- Search the web and fetch live data — use madarx-action blocks with web_search or web_fetch. Results come back automatically so you can synthesize a direct answer.
- Generate HTML pages, landing pages, dashboards, news feeds, reports, decks, and UI — output a complete self-contained HTML file in a \`\`\`html code fence. This is the PRIMARY output channel for any structured response.
- Write short conversational replies (≤ 2 sentences, no lists) — reply in plain text.
- Create agents for recurring/scheduled work only — output a madarx-action block.

ARTIFACT TEMPLATES (always emit a complete HTML page in a \`\`\`html fence — never paste structured data as markdown in chat):
- news → "news feed" layout: stacked story cards with headline, source label, timestamp, 2-3 sentence dek, and a "Read source" link per card. Publication-style typography.
- report → "executive report" layout: cover header (title/date), key findings callout, sectioned body, optional metric tiles, sources footer.
- document / brief / memo → serif body, generous margins, clear heading hierarchy, pull quotes for emphasis.
- presentation / pitch / deck → vertically stacked full-bleed slides, one idea per slide, large titles, slide counter.
- landing page → hero (headline + subhead + CTA), feature grid, social proof, footer.
- dashboard → KPI tiles + charts/lists, dense but legible.
- comparison (2+ options: flights, hotels, products, plans) → side-by-side comparison table or feature-matrix cards.
- timeline / roadmap / itinerary → vertical timeline with date markers and event cards.
- gallery / product list / portfolio → responsive card grid.
- leaderboard / ranking → ordered list with rank chip, name, score.

DECISION RULE (non-negotiable):
- 1 short factual answer (≤ 2 sentences, no list, no comparison) → reply in chat directly.
- Anything else (any list of 3+ items, any comparison, any news/report/document/page/dashboard, any response > 2 sentences) → emit a \`\`\`html ... \`\`\` artifact FIRST, then a 1-2 sentence chat summary describing what you built.
- Never paste a markdown response with bullet links into the chat. If you find yourself writing "## Sources" or a bulleted list outside an HTML artifact, stop and move it into the artifact.

LIVE DATA WORKFLOW (non-negotiable for flights, hotels, prices, addresses, schedules, any factual lookup):
  1) web_search to identify the 2-4 most authoritative sources (operator/booking sites, official pages, named publications).
  2) web_fetch each chosen source to extract concrete values — prices, dates, times, addresses, ratings, names, distances.
  3) Present the result as a comparison TABLE or structured list with real values in cells. Cite sources at the bottom as a short "Sources" list.

NEVER deliver a response that is just "Results for X" sections of search titles and snippets. That is not an answer. If a value cannot be extracted after fetching, put "Not listed" in the cell and continue — do not pad with snippets.

Web search:
\`\`\`madarx-action
{"tool":"web_search","input":{"query":"<search query>","count":5}}
\`\`\`

Fetch a specific URL:
\`\`\`madarx-action
{"tool":"web_fetch","input":{"url":"<url>"}}
\`\`\`

You can emit multiple action blocks in one response. Combine them: search broadly first, then fetch the strongest URLs that came back.

Example — user asks "find flights DXB to London May 18-25 and hotels in Kensington":
Turn 1 — discovery searches:
\`\`\`madarx-action
{"tool":"web_search","input":{"query":"Emirates DXB to LHR May 18 2026 return May 25 economy fare","count":5}}
\`\`\`
\`\`\`madarx-action
{"tool":"web_search","input":{"query":"4 star hotels South Kensington London 7 nights May 18 2026 price","count":5}}
\`\`\`
Turn 2 — after seeing results, fetch the actual booking/operator pages:
\`\`\`madarx-action
{"tool":"web_fetch","input":{"url":"https://www.emirates.com/.../dxb-to-lhr"}}
\`\`\`
\`\`\`madarx-action
{"tool":"web_fetch","input":{"url":"https://www.tripadvisor.com/Hotels-South-Kensington-London"}}
\`\`\`
Turn 3 — produce the final answer as a structured artifact:

# Trip plan: Dubai → London, 18–25 May 2026

## Flight options
| Airline | Route | Outbound | Return | Cabin | Price (AED) | Notes |
|---|---|---|---|---|---|---|
| Emirates | DXB → LHR | 18 May 02:40 | 25 May 14:25 | Economy Flex | 4,250 | Direct, 7h 50m |
| British Airways | DXB → LHR | 18 May 09:15 | 25 May 21:30 | Economy | 3,890 | Direct, 7h 55m |
| Etihad | AUH → LHR | 18 May 02:25 | 25 May 14:10 | Economy | 3,520 | 1h transfer at AUH |

## Hotel shortlist (South Kensington, 7 nights)
| Hotel | Stars | Nightly (\xa3) | 7-night total (\xa3) | Walk to Tube | Source |
|---|---|---|---|---|---|
| The Milestone | 5 | 612 | 4,284 | 3 min (High St Ken) | Booking.com |
| Number Sixteen | 5 | 478 | 3,346 | 4 min (South Ken) | Hotel site |
| The Cranley | 4 | 295 | 2,065 | 2 min (Gloucester Rd) | Tripadvisor |

## Sources
1. Emirates fare search (link)
2. British Airways fare search (link)
3. Tripadvisor South Kensington (link)

AGENT CREATION — only for recurring or scheduled tasks (daily monitoring, weekly reports):
\`\`\`madarx-action
{"tool":"create_agent","input":{"name":"Agent Name","mission":"...","engine":"anthropic","schedule":"daily 08:00","tools":["web-search","browser"]}}
\`\`\`

RUN AN EXISTING AGENT NOW — when the owner says "run X", "trigger X", "do today's run of X", "run the X agent":
\`\`\`madarx-action
{"tool":"run_agent","input":{"agent_name":"<the words the owner used>","wake_reason":"owner requested via chat"}}
\`\`\`
\`agent_name\` is a fuzzy, case-insensitive substring match against existing agents — pass the words the owner said (e.g. "ai brief", "uae tracker"). The sub-agent runs synchronously and produces its OWN artifact on the canvas. To dispatch an ad-hoc task for this one run, add \`"instruction":"<what to do right now>"\`. After emitting the block, write one short line confirming you started the run — do not narrate further.

CRITICAL — you are the ORCHESTRATOR, not the doer. NEVER use Bash, file editors, Read/Write/Edit, or any native developer tool to perform a madarX task. To run an agent, create an agent, search, or build a page, emit the matching \`madarx-action\` block (or an \`\`\`html\`\`\` artifact) and let madarX execute it. Do not try to do the sub-agent's job yourself.

IN-ARTIFACT CONFIRM/ACTION BUTTONS — when your artifact proposes an action that the user might want to confirm (e.g. "create this agent", "schedule this report", "run this now"), include a clickable button in the HTML that sends a confirmation prompt back into the chat on the user's behalf. Mark it with the data-madarx-action contract:

\`\`\`html
<button data-madarx-action="prompt" data-prompt="yes, create the daily AI news agent at 07:30">Create agent</button>
\`\`\`

The bridge in the iframe will catch the click and re-enter the chat as if the user typed the data-prompt text. Use a clear, unambiguous confirmation sentence in data-prompt so the next turn knows exactly what to do — for an agent proposal, include the name, schedule, and key tools. Style the button to look like a primary CTA inside the artifact; never use emojis.

Rules:
- ZERO EMOJIS in any output.
- Never tell the user to go to another page to see results.
- Always present extracted data in a comparison table when comparing 2+ options.
- A response made of search-engine titles + snippets is a failed answer — keep fetching until you have real values.${a?`

${a}`:""}`}()+M:(0,i.sR)()+(0,k.q)(J)+L+N,P=new TextEncoder,Q={closed:!1},R=new ReadableStream({async start(a){function b(b,c){if(Q.closed)return;let d="string"==typeof c?c:JSON.stringify(c);!function(b){if(!Q.closed)try{a.enqueue(P.encode(b))}catch(a){if(a?.code==="ERR_INVALID_STATE"){Q.closed=!0;return}throw a}}(`event: ${b}
data: ${d}

`)}try{b("session",{id:B});let a=J||d.map(a=>"string"==typeof a.content?a.content:JSON.stringify(a.content)).join("\n"),c=a+I,e=(d.length>1?d.map(a=>{let b="assistant"===a.role?"Assistant":"User",c="string"==typeof a.content?a.content:JSON.stringify(a.content);return`${b}: ${c}`}).join("\n\n"):a)+I;if("ollama"===A){let a=await (0,l.bD)({model:y,systemPrompt:O,userMessage:c,maxTokens:2048});if((0,p.S)(a)){let a="This local model has no tool access, so it fabricated a tool-call transcript with made-up results — nothing actually ran. Switch to the Anthropic API or Claude Code engine (Settings > Model) for tasks that need live data or real tools.";b("text",{delta:a}),b("usage",{model:y,input:0,output:0,cache_read:0,cache_creation:0,context:0});try{(0,m.UA)(B,{role:"assistant",content:a,model:y})}catch{}b("done",{ok:!1,engine:"ollama"});return}if(b("text",{delta:a}),s(a))try{let c=(0,m.Dg)({title:t(a),kind:"markdown",content:a,project_id:D});b("artifacts",{created:[{title:c.title,artifact_id:c.artifact_id}]})}catch{}b("usage",{model:y,input:0,output:0,cache_read:0,cache_creation:0,context:0});try{(0,m.UA)(B,{role:"assistant",content:a,model:y})}catch{}b("done",{ok:!0,engine:"ollama"});return}if("claude-code"===A||"codex"===A){let a,d="claude-code"===A?"claude_code_cli":"codex_cli";b("tool_start",{name:d,input:{mode:"subprocess"}});let h="",q=a=>{let c=(h+=a).replace(/```madarx-action[\s\S]*?```/gi,"").trim();c&&b("cli_stream",{text:c})},s=a=>{let c=a.replace(/```madarx-action[\s\S]*?```/gi,"").trim();c&&b("cli_stream",{text:c})},t=({name:a,input:c})=>{b("tool_start",{name:a,input:c})},z=({name:a,isError:c})=>{b("tool_result",{name:a,output:{ok:!c},isError:!!c})},F=a=>"claude-code"===A?(0,l.M2)({systemPrompt:O,userMessage:a,allowedTools:[],maxTurns:5,timeoutMs:Number(process.env.CLAUDE_CODE_CHAT_TIMEOUT_MS||6e5),onAssistantText:s,onToolStart:t,onToolResult:z}):(0,l.Iu)({systemPrompt:O,userMessage:a,onChunk:q});try{a=await F(e),b("tool_result",{name:d,output:{ok:!0},isError:!1})}catch(c){b("tool_result",{name:d,output:{error:c.message},isError:!0});let a=c.message?.includes("max turns")?"This task requires madarX tool access (agent creation, scheduling, state reads). Switch to the Anthropic engine in Settings > Model.":`CLI error: ${c.message}`;b("text",{delta:a}),b("done",{ok:!1,engine:A});return}let G=await v(a,{emit:b,context:E}),H=u(a).length>0,I=(0,p.S)(a);if(0===G.length&&!H&&(o.L.test(w(a))||I)){let c=`${e}

[SYSTEM] Your previous reply said you would do that, but you did NOT emit a \`\`\`madarx-action\`\`\` block, so nothing actually ran and the user is waiting.${I?" You SIMULATED a tool run by writing <tool_call>/<tool_response> text with made-up results — that is fiction, nothing actually ran. Do NOT simulate or narrate tool output. To run another agent, emit a real run_agent madarx-action block with the target agent id; madarX will execute it and return the real artifact.":""} If this task needs a tool (run_agent, create_agent, generate_ui, create_artifact, web_search, start_hermes_job, etc.), emit the madarx-action block NOW in this turn. Do not reply with another promise or a simulated transcript — emit the action.`;b("cli_stream",{text:"No action ran on the first pass — retrying…"});let d=null;try{d=await F(c)}catch(a){process.env.MADARX_DEBUG&&console.error("[madarx] intent-nudge retry failed:",a.message)}if(d){let c=await v(d,{emit:b,context:E});(c.length>0||u(d).length>0)&&(a=d,G=c,H=u(d).length>0)}}let M=G.length>0&&G.every(a=>"create_agent"===a.tool),N=w(a).trim(),P=0===G.length&&!H&&(0,p.S)(a),Q=N.length>=40&&!P,R=!!(0,g.resolveAnthropicApiKey)(),S=0===G.length&&!H||M;if(S&&R&&!Q&&!K){process.env.MADARX_DEBUG&&console.error("[madarx] CLI produced no actions/HTML or only create_agent — falling back to Anthropic agentic loop");let a=r.find(a=>a.id===f.A),b=`

Active model: ${a?.label||f.A} (id: ${f.A}). If the user asks which model you are, answer with this exact name. Do not guess from training-data priors.`;O=(0,i.sR)()+(0,k.q)(J)+L+b}else if(S&&P){let a="The CLI engine simulated a tool run instead of dispatching it — it wrote a tool-call transcript with made-up results, so the action did not actually run and no real result was produced. Try again, or switch this conversation to the Anthropic API engine (Settings > Model) so madarX runs the tools for real.";b("text",{delta:a}),b("usage",{model:y,input:0,output:0,cache_read:0,cache_creation:0,context:0});try{(0,m.UA)(B,{role:"assistant",content:a,model:y})}catch{}b("done",{ok:!1,engine:A});return}else if(S){let a=N||"No response.";if(b("text",{delta:a}),!H){let c=x(a,{sessionArtifactId:C,projectId:D});c&&(c.created?b("artifacts",{created:[{artifact_id:c.artifact_id}]}):b("artifact_updated",{artifact_id:c.artifact_id}),b("session_artifact",{artifact_id:c.artifact_id}))}b("usage",{model:y,input:0,output:0,cache_read:0,cache_creation:0,context:0});try{(0,m.UA)(B,{role:"assistant",content:a,model:y})}catch{}b("done",{ok:!0,engine:A});return}else{let d=new Set(["web_search","web_fetch","web_extract"]),e=G.filter(({tool:a,result:b})=>d.has(a)&&b&&!b.error);if(e.length>0){b("cli_stream",{text:"Composing answer from search results…"}),b("tool_start",{name:"synthesize_answer",input:{sources:e.map(a=>a.tool)}});let d=!1,g=!1,h=null,k=e.map(({tool:a,result:b})=>{let c="string"==typeof b?b:JSON.stringify(b,null,2);return`### ${a}
${c.slice(0,6e3)}`}).join("\n\n"),m=e.filter(a=>"web_fetch"===a.tool||"web_extract"===a.tool).length,n=`${(0,i.uB)()}

You are the madarX synthesis pass. You are reporting to the owner like a chief of staff to a chairman — bring back the actual answer, not a list of links to it.

OUTPUT FORMAT: Emit a complete self-contained HTML page inside a single \`\`\`html ... \`\`\` code fence. madarX will lift the HTML into a designed artifact rendered on the canvas. Outside the fence, write only a 1-2 sentence chat summary of what you built (no lists, no markdown headings, no links).

Pick the layout that fits the data:
- News stories → stacked news-card feed (headline, source, timestamp, 2-3 sentence dek, "Read source" link).
- Comparable options (flights, hotels, products, plans) → comparison table or feature-matrix cards with real values per cell.
- Reports / analyses → executive-report layout (cover header, key-findings callout, sectioned body, sources footer).
- Itinerary / schedule → vertical timeline with date markers and event cards.
- Dashboard / metrics → KPI tiles + supporting lists.
Use a clean publication-style typography hierarchy (serif or modern sans), generous whitespace, no emojis, no inline-style aggression. Always include a "Sources" section at the end of the HTML with 2-4 cited links.

Rules (non-negotiable):
- NEVER produce "Results for X" sections with raw search titles and snippets. That is a failed answer.
- Extract concrete values from the data below: prices, dates, times, addresses, names, numbers, ratings.
- Use "Not listed" where a value is genuinely missing — do NOT pad with snippets.
- ZERO emojis. No "click here", "see link", "visit the website" language.
- The HTML must be a full document (\`<!doctype html>\` ... \`</html>\`) with embedded \`<style>\`. No external scripts.${0===m?'\n- Important: only search-snippet data is available below. If concrete values cannot be extracted, build the HTML page with a short "What we know / What needs fetching" section — do NOT pad with raw search snippets.':""}${(0,j.nX)()?`

${(0,j.nX)()}`:""}`,o=`User question:
${c}

Live tool results:

${k}

Produce the final answer now as a complete HTML page in a \`\`\`html ... \`\`\` fence, with real values (not titles) and a Sources block at the bottom of the page. Then add a 1-2 sentence chat summary after the fence describing what you built.`;try{let b="";(b="claude-code"===A?(await (0,l.M2)({systemPrompt:n,userMessage:o,allowedTools:[],maxTurns:1,timeoutMs:Number(process.env.CLAUDE_CODE_CHAT_TIMEOUT_MS||6e5)}))?.trim()||"":"codex"===A?(await (0,l.Iu)({systemPrompt:n,userMessage:o}))?.trim()||"":((await (0,f.chatWithClaude)([{role:"user",content:c},{role:"assistant",content:"[Searching…]"},{role:"user",content:`Live search results:

${k}

Produce the final answer as a complete HTML page in a single \`\`\`html ... \`\`\` fence. Pick the best layout (news feed, comparison table, executive report, timeline, dashboard). Embed CSS, no external scripts. Real values in cells, no titles or snippets. Include a Sources section at the bottom of the page. After the fence, add a 1-2 sentence chat summary. No emojis.`}],n,[],{model:f.A})).content??[]).filter(a=>"text"===a.type).map(a=>a.text).join("\n").trim())&&(a=b,d=!0)}catch(a){h=a.message||String(a),process.env.MADARX_DEBUG&&console.error("[madarx] synthesis failed:",h)}if(!d){let b=function(a,b){let c=[];c.push("# Could not produce a complete answer"),b&&c.push(`_Synthesis step failed: ${b}._`),c.push("I gathered search results but could not extract concrete values (prices, times, addresses). The most relevant sources I found are below — please retry, or ask me to fetch a specific one for full details."),c.push(""),c.push("## Sources");let d=0;for(let{tool:b,result:e}of a){if(d>=8)break;if(e){if("web_search"===b)for(let a of(Array.isArray(e.results)?e.results:[]).slice(0,3)){if(d>=8)break;let b=(a.title||a.url||"Untitled").slice(0,110),e=a.url||"";e&&(c.push(`- [${b}](${e})`),d++)}else if("web_fetch"===b){let a=e.url||"";a&&(c.push(`- Fetched: ${a}`),d++)}}}return 0===d&&c.push("_No sources returned._"),c.join("\n").trim()}(e,h);b&&(a=b,g=!0)}b("tool_result",{name:"synthesize_answer",output:d?{ok:!0}:g?{ok:!0,fallback:!0,reason:h}:{error:h||"no output"},isError:!d&&!g})}let g=G.length?w(a):a,{text:h,artifacts:k,updated:o}=function(a,{sessionArtifactId:b,projectId:c=null}={}){let d=u(a);if(!d.length)return{text:a,artifacts:[],updated:[]};let e=[],f=[],g=a,h=b;for(let a of d){let b=function(a){let b=a.match(/<title[^>]*>([^<]+)<\/title>/i);return b?b[1].trim():"Generated page"}(a.html);if(h)try{let c=(0,m.eP)(h,{title:b,content:a.html});f.push({title:b,artifact_id:c.artifact_id}),g=g.replace(a.full,`
[Artifact updated: "${b}"]
`),h=null;continue}catch{}try{let d=(0,m.Dg)({title:b,kind:"html",content:a.html,project_id:c});e.push({title:b,artifact_id:d.artifact_id}),g=g.replace(a.full,`
[Artifact created: "${b}"]
`)}catch{}}return{text:g.trim(),artifacts:e,updated:f}}(g,{sessionArtifactId:C,projectId:D});if(b("text",{delta:h}),o.length){for(let a of o)b("artifact_updated",{artifact_id:a.artifact_id,title:a.title});b("session_artifact",{artifact_id:o[0].artifact_id})}k.length&&(b("artifacts",{created:k}),b("session_artifact",{artifact_id:k[0].artifact_id}));let p=G.filter(a=>"create_agent"===a.tool&&a.result?.agent).map(a=>({agent:a.result.agent,files:a.result.files??[]}));for(let{agent:a,files:c}of p)try{let d=(0,n.t)(a,c),e=(0,m.Dg)({title:`${a.name} — Agent created`,kind:"html",content:d,project_id:D});b("artifacts",{created:[{title:a.name,artifact_id:e.artifact_id}]}),b("session_artifact",{artifact_id:e.artifact_id})}catch{}let q=G.filter(a=>"run_agent"===a.tool&&a.result?.ok).map(a=>a.result),r=[];for(let a of q){let c=a.artifact_id||a.artifact?.artifact_id||a.artifact?.id||null;c&&(b("artifacts",{created:[{title:a.title||a.agent_name,artifact_id:c}]}),b("session_artifact",{artifact_id:c}));let d=(a.preview||"").trim();r.push(`Ran **${a.agent_name}** — ${a.status||"complete"}.${a.title?` Output: "${a.title}".`:""}${d?`

${d}`:""}`)}let s=G.filter(a=>"run_agent"===a.tool&&a.result&&!1===a.result.ok).map(a=>`Could not run agent: ${a.result.error||"unknown error"}.`);if(!k.length&&!o.length&&0===p.length&&0===q.length){let a=x(h,{sessionArtifactId:C,projectId:D});a&&(a.created?b("artifacts",{created:[{artifact_id:a.artifact_id}]}):b("artifact_updated",{artifact_id:a.artifact_id}),b("session_artifact",{artifact_id:a.artifact_id}))}for(let{agent:a,files:c}of p)b("agent_created",{agent:a,files:c});let t=[...r,...s].join("\n\n");t&&!h.trim()&&b("text",{delta:t});let v=h.trim()||t||"";b("usage",{model:y,input:0,output:0,cache_read:0,cache_creation:0,context:0});try{(0,m.UA)(B,{role:"assistant",content:v,model:y})}catch{}b("done",{ok:!0,engine:A});return}}if(!(0,g.resolveAnthropicApiKey)()){b("text",{delta:K?"Configured engine answered without tool calls. To enable Anthropic-powered tools (web search, artifact generation) add ANTHROPIC_API_KEY to the secrets vault (Settings → Secrets) or set it in .env.local and restart the dev server.":"ANTHROPIC_API_KEY is not configured. Add it to the secrets vault (Settings → Secrets) or to .env.local and restart the dev server, or switch to a CLI engine (Claude Code / Codex) in Settings."}),b("done",{ok:!1,engine:A});return}let z=K?f.A:y,M=d.map(a=>({role:a.role,content:a.content}));if(H.length){let a=(0,q.NJ)(H);for(let b=M.length-1;b>=0;b--){if("user"!==M[b].role)continue;let c=M[b].content,d="string"==typeof c?c?[{type:"text",text:c}]:[]:Array.isArray(c)?c:[];M[b]={role:"user",content:[...d,...a]};break}}for(;M.length&&"assistant"===M[0].role;)M.shift();let N=0,P=!1,Q="",R=0,S=0,T=0,U=0,V=0;for(;N<8;){N++;let a=await (0,f.x)(M,O,(0,h.Y)(),z),c="",d=[],e=null,g="",i=null,j=0,k=0,l=0,o=0;for await(let f of a)if("message_start"===f.type){let a=f.message?.usage||{};j=a.input_tokens??0,l=a.cache_read_input_tokens??0,o=a.cache_creation_input_tokens??0}else if("content_block_start"===f.type)"tool_use"===f.content_block.type&&(e={id:f.content_block.id,name:f.content_block.name,input:{}},g="");else if("content_block_delta"===f.type)"text_delta"===f.delta.type?(c+=f.delta.text,b("text",{delta:f.delta.text})):"input_json_delta"===f.delta.type&&(g+=f.delta.partial_json);else if("content_block_stop"===f.type){if(e){try{e.input=JSON.parse(g||"{}")}catch{e.input={}}d.push(e),e=null,g=""}}else"message_delta"===f.type&&(f.delta.stop_reason&&(i=f.delta.stop_reason),f.usage?.output_tokens&&(k=f.usage.output_tokens));R+=j,S+=k,T+=l,U+=o,V=j+l+o,b("usage",{model:y,input:R,output:S,cache_read:T,cache_creation:U,context:V});let p=[];for(let a of(c&&p.push({type:"text",text:c}),d))p.push({type:"tool_use",id:a.id,name:a.name,input:a.input});M=[...M,{role:"assistant",content:p}];try{(0,m.UA)(B,{role:"assistant",content:c,tool_calls:d.length?d.map(a=>({id:a.id,name:a.name,input:a.input})):null,model:y,input_tokens:j,output_tokens:k,cache_read_tokens:l,cache_creation_tokens:o})}catch{}if(Q+=c,"tool_use"!==i||0===d.length)break;let q=[];for(let a of d){let c;b("tool_start",{name:a.name,input:a.input});let d=!1,e=null;try{let b=function(a,b){let c=F.find(b=>b.tool_name===a&&!b.used)||null;return c?{input:{...b||{},approval_id:c.approval_id},entry:c}:{input:b,entry:null}}(a.name,a.input);e=b.entry,c=await (0,h.o8)(a.name,b.input,E)}catch(a){c={error:a.message},d=!0}if(e&&((d||c?.status==="error"||c?.ok===!1)&&G.has(c?.error)||(e.used=!0)),!d&&c?.artifact_id&&("create_artifact"===a.name||"generate_ui"===a.name||"send_to_hermes"===a.name||"start_hermes_job"===a.name)&&(P=!0),!d&&"create_agent"===a.name&&c?.agent)try{let a=(0,n.t)(c.agent,c.files??[]),d=(0,m.Dg)({title:`${c.agent.name} — Agent created`,kind:"html",content:a,project_id:D});b("artifacts",{created:[{title:c.agent.name,artifact_id:d.artifact_id}]}),b("session_artifact",{artifact_id:d.artifact_id}),b("agent_created",{agent:c.agent,files:c.files??[]}),P=!0}catch{}b("tool_result",{name:a.name,output:c,isError:d}),q.push({type:"tool_result",tool_use_id:a.id,content:JSON.stringify(c),is_error:d})}M=[...M,{role:"user",content:q}]}if(!P){let a=x(Q,{sessionArtifactId:C,projectId:D});a&&(a.created?b("artifacts",{created:[{artifact_id:a.artifact_id}]}):b("artifact_updated",{artifact_id:a.artifact_id}),b("session_artifact",{artifact_id:a.artifact_id}))}let W=F.filter(a=>!a.used).map(a=>({approval_id:a.approval_id,tool_name:a.tool_name}));W.length&&b("pending_approvals",{approvals:W}),b("done",{ok:!0})}catch(a){b("error",{message:a.message})}finally{if(!Q.closed){Q.closed=!0;try{a.close()}catch{}}}},cancel(){Q.closed=!0}});return new Response(R,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}d()}catch(a){d(a)}})},10846:a=>{a.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},19121:a=>{a.exports=require("next/dist/server/app-render/action-async-storage.external.js")},26848:a=>{a.exports=require("node:readline/promises")},29294:a=>{a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},31421:a=>{a.exports=require("node:child_process")},37437:(a,b,c)=>{c.d(b,{L:()=>d});let d=/\b(let me|i['’]ll|i will|i'm going to|i am going to|on it|started|starting|kicking off|kicked off|launching|launched|running it|running now|generating it|generating one|generating now|creating it|creating one|creating now|building it|building one|building now|fetching it|fetching now|hold on|one moment|one sec|standby|stand by|coming up|right away|right now|in a sec|give me a sec|working on it|will land|lands on canvas|land on canvas)\b/i},41264:(a,b,c)=>{function d(a){return String(a??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function e(a,b=[]){let c=d(a?.name||"madarX Custom Agent"),f=d(a?.mission||""),g=d(a?.schedule||"on demand"),h=d(a?.engine||"anthropic"),i=d(a?.model||""),j=d(a?.approval||"human-in-loop"),k=Array.isArray(a?.tools)?a.tools:[],l=Array.isArray(b)?b:[],m=`Run the ${a?.name||"new"} agent now`,n=k.length?k.map(a=>`<li class="chip">${d(a)}</li>`).join(""):'<li class="chip chip-muted">no tools assigned</li>',o=l.length?l.map(a=>`
        <li class="file">
          <span class="file-name">${d(function(a){let b=String(a||"").split(/[\\/]/).filter(Boolean);return b[b.length-1]||a||""}(a))}</span>
          <span class="file-path">${d(a)}</span>
        </li>`).join(""):'<li class="file file-empty">No workspace files written.</li>';return`<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>${c} — Agent created</title>
  <style>
    *, *::before, *::after { box-sizing: border-box; }
    html, body { margin: 0; padding: 0; }
    body {
      background: #0F0F11;
      color: #E8E8E5;
      font-family: 'Inter', system-ui, -apple-system, sans-serif;
      font-feature-settings: 'ss01', 'ss02';
      -webkit-font-smoothing: antialiased;
      padding: 40px clamp(20px, 4vw, 56px) 56px;
      min-height: 100vh;
    }
    .stage {
      max-width: 720px;
      margin: 0 auto;
      display: grid;
      gap: 32px;
    }
    .eyebrow {
      display: inline-flex;
      align-items: center;
      gap: 10px;
      font-family: 'IBM Plex Mono', ui-monospace, monospace;
      font-size: 11px;
      letter-spacing: 0.18em;
      text-transform: uppercase;
      color: #C2452A;
    }
    .eyebrow::before {
      content: "";
      width: 6px; height: 6px; border-radius: 50%;
      background: #C2452A;
      box-shadow: 0 0 0 4px rgba(194, 69, 42, 0.18);
    }
    h1 {
      font-size: clamp(34px, 5vw, 52px);
      font-weight: 600;
      letter-spacing: -0.02em;
      line-height: 1.05;
      margin: 14px 0 0;
      color: #E8E8E5;
    }
    .mission {
      max-width: 620px;
      font-size: 16px;
      line-height: 1.6;
      color: #DCDCD8;
      margin: 14px 0 0;
    }
    .meta {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
      gap: 1px;
      background: #1A1A1D;
      border: 1px solid #1A1A1D;
      border-radius: 14px;
      overflow: hidden;
    }
    .meta-cell {
      background: #131316;
      padding: 18px 20px;
      display: grid;
      gap: 6px;
    }
    .meta-label {
      font-family: 'IBM Plex Mono', ui-monospace, monospace;
      font-size: 10px;
      letter-spacing: 0.18em;
      text-transform: uppercase;
      color: #6F6F73;
    }
    .meta-value {
      font-size: 14px;
      color: #E8E8E5;
      font-weight: 500;
    }
    .section h2 {
      font-family: 'IBM Plex Mono', ui-monospace, monospace;
      font-size: 11px;
      letter-spacing: 0.22em;
      text-transform: uppercase;
      color: #6F6F73;
      margin: 0 0 14px;
      font-weight: 500;
    }
    .chips {
      list-style: none;
      padding: 0;
      margin: 0;
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
    .chip {
      padding: 7px 13px;
      border-radius: 999px;
      background: #18181B;
      border: 1px solid #25252A;
      color: #DCDCD8;
      font-size: 12.5px;
      font-family: 'IBM Plex Mono', ui-monospace, monospace;
      letter-spacing: 0.02em;
    }
    .chip-muted {
      color: #6F6F73;
      font-style: italic;
    }
    .files {
      list-style: none;
      padding: 0;
      margin: 0;
      display: grid;
      gap: 1px;
      background: #1A1A1D;
      border: 1px solid #1A1A1D;
      border-radius: 12px;
      overflow: hidden;
    }
    .file {
      background: #131316;
      padding: 14px 18px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 16px;
      font-size: 13px;
    }
    .file-empty {
      color: #6F6F73;
      font-style: italic;
      justify-content: flex-start;
    }
    .file-name {
      color: #E8E8E5;
      font-weight: 500;
    }
    .file-path {
      font-family: 'IBM Plex Mono', ui-monospace, monospace;
      font-size: 11px;
      color: #6F6F73;
      letter-spacing: 0.01em;
      text-align: right;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 60%;
    }
    .actions {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
      margin-top: 4px;
    }
    button {
      font-family: inherit;
      font-size: 13.5px;
      font-weight: 500;
      letter-spacing: 0.01em;
      padding: 12px 22px;
      border-radius: 10px;
      cursor: pointer;
      transition: transform 0.12s ease, background 0.12s ease, border-color 0.12s ease;
    }
    .btn-primary {
      background: #C2452A;
      color: #FAFAF8;
      border: 1px solid #C2452A;
    }
    .btn-primary:hover {
      background: #D14F33;
      border-color: #D14F33;
      transform: translateY(-1px);
    }
    .btn-ghost {
      background: transparent;
      color: #DCDCD8;
      border: 1px solid #2A2A2F;
    }
    .btn-ghost:hover {
      border-color: #4A4A4D;
      color: #E8E8E5;
    }
    .rule {
      height: 1px;
      background: linear-gradient(to right, #1A1A1D, #25252A 25%, #25252A 75%, #1A1A1D);
      border: none;
      margin: 0;
    }
    .footnote {
      font-size: 12px;
      color: #6F6F73;
      font-family: 'IBM Plex Mono', ui-monospace, monospace;
      letter-spacing: 0.02em;
    }
  </style>
</head>
<body>
  <main class="stage">
    <header>
      <span class="eyebrow">Agent created</span>
      <h1>${c}</h1>
      ${f?`<p class="mission">${f}</p>`:""}
    </header>

    <section class="meta">
      <div class="meta-cell">
        <span class="meta-label">Schedule</span>
        <span class="meta-value">${g}</span>
      </div>
      <div class="meta-cell">
        <span class="meta-label">Engine</span>
        <span class="meta-value">${h}${i?` <span style="color:#6F6F73">\xb7 ${i}</span>`:""}</span>
      </div>
      <div class="meta-cell">
        <span class="meta-label">Approval</span>
        <span class="meta-value">${j}</span>
      </div>
    </section>

    <section class="section">
      <h2>Allowed tools</h2>
      <ul class="chips">${n}</ul>
    </section>

    <hr class="rule">

    <section class="section">
      <h2>Workspace files</h2>
      <ul class="files">${o}</ul>
    </section>

    <section class="actions">
      <button class="btn-primary" data-madarx-action="prompt" data-prompt="${d(m)}">Run now</button>
      <button class="btn-ghost" data-madarx-action="prompt" data-prompt="Show me the skills for ${c}">Review skills</button>
    </section>

    <p class="footnote">Owner-in-loop \xb7 external sends, posts, and deployments require approval before execution.</p>
  </main>
</body>
</html>`}c.d(b,{t:()=>e})},44870:a=>{a.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},48161:a=>{a.exports=require("node:os")},50832:a=>{a.exports=import("@anthropic-ai/sdk")},63033:a=>{a.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},65072:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{q:()=>g});var e=c(60105),f=a([e]);function g(a){let b=String(a||"").toLowerCase();if(!b)return"";let c=(0,e.vc)().filter(a=>{let c=String(a.name||"").toLowerCase(),d=String(a.id||"").toLowerCase();return c&&b.includes(c)||d&&b.includes(d)}).slice(0,3).map(a=>{let b=Array.isArray(a.memory)?a.memory.slice(-10):[];return b.length?`<agent_memory name="${a.name}" id="${a.id}">
${b.map((a,b)=>`${b+1}. ${a}`).join("\n")}
</agent_memory>`:""}).filter(Boolean);return c.length?`

Referenced agent memory for this turn:
${c.join("\n\n")}`:""}e=(f.then?(await f)():f)[0],d()}catch(a){d(a)}})},71553:a=>{a.exports=require("node:dns/promises")},73024:a=>{a.exports=require("node:fs")},73136:a=>{a.exports=require("node:url")},76760:a=>{a.exports=require("node:path")},77030:a=>{a.exports=require("node:net")},77598:a=>{a.exports=require("node:crypto")},78608:a=>{a.exports=require("exceljs")},80099:a=>{a.exports=require("node:sqlite")},83237:a=>{a.exports=import("playwright")},85728:(a,b,c)=>{c.d(b,{NJ:()=>r,PT:()=>q,fz:()=>p,hR:()=>i,kW:()=>o,qQ:()=>j,zr:()=>s});var d=c(73024),e=c(76760),f=c(77598),g=c(9381);let h=e.join(g.nJ,"uploads"),i=0x1400000,j=8,k=new Set(["image/png","image/jpeg","image/gif","image/webp"]),l=new Set([".txt",".md",".markdown",".csv",".tsv",".json",".jsonl",".log",".yaml",".yml",".xml",".html",".htm",".css",".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".cs",".php",".sh",".bash",".zsh",".sql",".toml",".ini",".env",".conf",".tex",".rst"]),m=/^[0-9a-f]{32}$/;function n(a,b){let c=(a||"").toLowerCase(),d=e.extname(b||"").toLowerCase();return k.has(c)?"image":"application/pdf"===c||".pdf"===d?"pdf":c.startsWith("text/")||"application/json"===c||l.has(d)?"text":"other"}function o(a,b){return"other"!==n(a,b)}function p({buffer:a,name:b,mime:c}){if(!Buffer.isBuffer(a))throw Error("buffer required");if(0===a.length)throw Error("empty file");if(a.length>i)throw Error("file too large");let g=e.basename(String(b||"file")).replace(/[^\w.\- ]+/g,"_").trim().slice(0,160)||"file";if(!o(c,g))throw Error("unsupported file type");d.mkdirSync(h,{recursive:!0});let j=f.randomBytes(16).toString("hex"),k=n(c,g),l={id:j,name:g,mime:String(c||"application/octet-stream"),size:a.length,kind:k};return d.writeFileSync(e.join(h,j),a),d.writeFileSync(e.join(h,`${j}.json`),JSON.stringify(l)),l}function q(a){if(!Array.isArray(a))return[];let b=[];for(let c of a.slice(0,j)){let a=function(a){if("string"!=typeof a||!m.test(a))return null;let b=e.join(h,a),c=e.join(h,`${a}.json`);try{let a=JSON.parse(d.readFileSync(c,"utf8")),e=d.readFileSync(b);return{...a,buffer:e}}catch{return null}}(c&&"object"==typeof c?c.id:c);a&&b.push(a)}return b}function r(a){let b=[];for(let c of a)if("image"===c.kind)b.push({type:"image",source:{type:"base64",media_type:c.mime,data:c.buffer.toString("base64")}});else if("pdf"===c.kind)b.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:c.buffer.toString("base64")}});else if("text"===c.kind){let a=c.buffer.toString("utf8").slice(0,6e4),d=c.buffer.length>6e4?"\n…(truncated)":"";b.push({type:"text",text:`Attached file "${c.name}":

\`\`\`
${a}${d}
\`\`\``})}else b.push({type:"text",text:`Attached file "${c.name}" (${c.mime}, ${c.size} bytes) — binary, contents not shown.`});return b}function s(a){if(!a.length)return"";let b=["","--- Attachments ---"];for(let c of a)if("text"===c.kind){let a=c.buffer.toString("utf8").slice(0,6e4),d=c.buffer.length>6e4?"\n…(truncated)":"";b.push(`
File "${c.name}":
\`\`\`
${a}${d}
\`\`\``)}else"image"===c.kind?b.push(`
[Image attached: "${c.name}". This engine cannot view images — switch to an Anthropic model to analyze it.]`):"pdf"===c.kind?b.push(`
[PDF attached: "${c.name}". This engine cannot read PDFs — switch to an Anthropic model to analyze it.]`):b.push(`
[Attached "${c.name}" (${c.mime}) — binary, not shown.]`);return b.join("\n")}},86439:a=>{a.exports=require("next/dist/shared/lib/no-fallback-error.external")},95736:(a,b,c)=>{a.exports=c(44870)},95763:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.r(b),c.d(b,{handler:()=>x,patchFetch:()=>w,routeModule:()=>y,serverHooks:()=>B,workAsyncStorage:()=>z,workUnitAsyncStorage:()=>A});var e=c(95736),f=c(9117),g=c(4044),h=c(39326),i=c(32324),j=c(261),k=c(54290),l=c(85328),m=c(38928),n=c(46595),o=c(3421),p=c(17679),q=c(41681),r=c(63446),s=c(86439),t=c(51356),u=c(6753),v=a([u]);u=(v.then?(await v)():v)[0];let y=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/orchestrator/stream/route",pathname:"/api/orchestrator/stream",filename:"route",bundlePath:"app/api/orchestrator/stream/route"},distDir:".next",relativeProjectDir:"",resolvedPagePath:"/home/runner/work/madarx-os/madarx-os/app/api/orchestrator/stream/route.js",nextConfigOutput:"standalone",userland:u}),{workAsyncStorage:z,workUnitAsyncStorage:A,serverHooks:B}=y;function w(){return(0,g.patchFetch)({workAsyncStorage:z,workUnitAsyncStorage:A})}async function x(a,b,c){var d;let e="/api/orchestrator/stream/route";"/index"===e&&(e="/");let g=await y.prepare(a,b,{srcPage:e,multiZoneDraftMode:!1});if(!g)return b.statusCode=400,b.end("Bad Request"),null==c.waitUntil||c.waitUntil.call(c,Promise.resolve()),null;let{buildId:u,params:v,nextConfig:w,isDraftMode:x,prerenderManifest:z,routerServerContext:A,isOnDemandRevalidate:B,revalidateOnlyGenerated:C,resolvedPathname:D}=g,E=(0,j.normalizeAppPath)(e),F=!!(z.dynamicRoutes[E]||z.routes[D]);if(F&&!x){let a=!!z.routes[D],b=z.dynamicRoutes[E];if(b&&!1===b.fallback&&!a)throw new s.NoFallbackError}let G=null;!F||y.isDev||x||(G=D,G="/index"===G?"/":G);let H=!0===y.isDev||!F,I=F&&!H,J=a.method||"GET",K=(0,i.getTracer)(),L=K.getActiveScopeSpan(),M={params:v,prerenderManifest:z,renderOpts:{experimental:{cacheComponents:!!w.experimental.cacheComponents,authInterrupts:!!w.experimental.authInterrupts},supportsDynamicResponse:H,incrementalCache:(0,h.getRequestMeta)(a,"incrementalCache"),cacheLifeProfiles:null==(d=w.experimental)?void 0:d.cacheLife,isRevalidate:I,waitUntil:c.waitUntil,onClose:a=>{b.on("close",a)},onAfterTaskError:void 0,onInstrumentationRequestError:(b,c,d)=>y.onRequestError(a,b,d,A)},sharedContext:{buildId:u}},N=new k.NodeNextRequest(a),O=new k.NodeNextResponse(b),P=l.NextRequestAdapter.fromNodeNextRequest(N,(0,l.signalFromNodeResponse)(b));try{let d=async c=>y.handle(P,M).finally(()=>{if(!c)return;c.setAttributes({"http.status_code":b.statusCode,"next.rsc":!1});let d=K.getRootSpanAttributes();if(!d)return;if(d.get("next.span_type")!==m.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${d.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let e=d.get("next.route");if(e){let a=`${J} ${e}`;c.setAttributes({"next.route":e,"http.route":e,"next.span_name":a}),c.updateName(a)}else c.updateName(`${J} ${a.url}`)}),g=async g=>{var i,j;let k=async({previousCacheEntry:f})=>{try{if(!(0,h.getRequestMeta)(a,"minimalMode")&&B&&C&&!f)return b.statusCode=404,b.setHeader("x-nextjs-cache","REVALIDATED"),b.end("This page could not be found"),null;let e=await d(g);a.fetchMetrics=M.renderOpts.fetchMetrics;let i=M.renderOpts.pendingWaitUntil;i&&c.waitUntil&&(c.waitUntil(i),i=void 0);let j=M.renderOpts.collectedTags;if(!F)return await (0,o.I)(N,O,e,M.renderOpts.pendingWaitUntil),null;{let a=await e.blob(),b=(0,p.toNodeOutgoingHttpHeaders)(e.headers);j&&(b[r.NEXT_CACHE_TAGS_HEADER]=j),!b["content-type"]&&a.type&&(b["content-type"]=a.type);let c=void 0!==M.renderOpts.collectedRevalidate&&!(M.renderOpts.collectedRevalidate>=r.INFINITE_CACHE)&&M.renderOpts.collectedRevalidate,d=void 0===M.renderOpts.collectedExpire||M.renderOpts.collectedExpire>=r.INFINITE_CACHE?void 0:M.renderOpts.collectedExpire;return{value:{kind:t.CachedRouteKind.APP_ROUTE,status:e.status,body:Buffer.from(await a.arrayBuffer()),headers:b},cacheControl:{revalidate:c,expire:d}}}}catch(b){throw(null==f?void 0:f.isStale)&&await y.onRequestError(a,b,{routerKind:"App Router",routePath:e,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:I,isOnDemandRevalidate:B})},A),b}},l=await y.handleResponse({req:a,nextConfig:w,cacheKey:G,routeKind:f.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:z,isRoutePPREnabled:!1,isOnDemandRevalidate:B,revalidateOnlyGenerated:C,responseGenerator:k,waitUntil:c.waitUntil});if(!F)return null;if((null==l||null==(i=l.value)?void 0:i.kind)!==t.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==l||null==(j=l.value)?void 0:j.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});(0,h.getRequestMeta)(a,"minimalMode")||b.setHeader("x-nextjs-cache",B?"REVALIDATED":l.isMiss?"MISS":l.isStale?"STALE":"HIT"),x&&b.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let m=(0,p.fromNodeOutgoingHttpHeaders)(l.value.headers);return(0,h.getRequestMeta)(a,"minimalMode")&&F||m.delete(r.NEXT_CACHE_TAGS_HEADER),!l.cacheControl||b.getHeader("Cache-Control")||m.get("Cache-Control")||m.set("Cache-Control",(0,q.getCacheControlHeader)(l.cacheControl)),await (0,o.I)(N,O,new Response(l.value.body,{headers:m,status:l.value.status||200})),null};L?await g(L):await K.withPropagatedContext(a.headers,()=>K.trace(m.BaseServerSpan.handleRequest,{spanName:`${J} ${a.url}`,kind:i.SpanKind.SERVER,attributes:{"http.method":J,"http.target":a.url}},g))}catch(b){if(b instanceof s.NoFallbackError||await y.onRequestError(a,b,{routerKind:"App Router",routePath:E,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:I,isOnDemandRevalidate:B})}),F)throw b;return await (0,o.I)(N,O,new Response(null,{status:500})),null}}d()}catch(a){d(a)}})}};var b=require("../../../../webpack-runtime.js");b.C(a);var c=b.X(0,[5873,3940,1699,3230,3332,511],()=>b(b.s=95763));module.exports=c})();