"use strict";(()=>{var a={};a.id=1557,a.ids=[1557],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()}}},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")},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")},64077:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.r(b),c.d(b,{GET:()=>h,dynamic:()=>j,runtime:()=>i});var e=c(78224),f=a([e]);e=(f.then?(await f)():f)[0];let i="nodejs",j="force-dynamic";function g(a,b,c){a.enqueue(`event: ${b}
data: ${JSON.stringify(c)}

`)}async function h(a,{params:b}){let{id:c}=await b;if(!(0,e.qw)(c))return Response.json({error:"not found"},{status:404});let d=new TextEncoder,f=0,h=new ReadableStream({async start(a){let b={enqueue(b){a.enqueue(d.encode(b))}},h=setInterval(()=>{try{let d=(0,e.Zn)(c,500);for(let a of d.slice(f))g(b,a.type||"event",a);f=d.length;let i=(0,e.qw)(c);["complete","failed","cancelled","stale"].includes(i?.status)&&(g(b,"done",{status:i.status}),clearInterval(h),a.close())}catch(c){g(b,"error",{message:c.message}),clearInterval(h),a.close()}},1e3)}});return new Response(h,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}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")},78224:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Z2:()=>u,Zn:()=>t,_3:()=>y,o0:()=>x,qw:()=>s,rK:()=>z,vy:()=>r});var e=c(73024),f=c(76760),g=c(31421),h=c(34255),i=c(9381),j=c(73066),k=c(61423),l=c(60105),m=c(8727),n=a([h,j,k,l,m]);[h,j,k,l,m]=n.then?(await n)():n;let A=new Set(["complete","failed","cancelled","stale"]);function o(a){return a?{...a}:null}function p(a){return a?{...a,payload:function(a,b){if(!a)return null;try{return JSON.parse(a)}catch{return null}}(a.payload,null)}:null}function q(a,b){let c=f.resolve(i.Dl,a),d=e.realpathSync(i.un),g=e.existsSync(f.dirname(c))?e.realpathSync(f.dirname(c)):f.resolve(f.dirname(c)),h=f.join(g,f.basename(c));if(!(h===d||h.startsWith(`${d}${f.sep}`)))throw Error(`Refusing to write artifact outside workspace: ${a}`);e.mkdirSync(f.dirname(c),{recursive:!0}),e.writeFileSync(c,b,"utf8")}function r(a=20){return(0,h.getDb)().prepare("SELECT * FROM hermes_jobs ORDER BY updated_at DESC LIMIT ?").all(a).map(o)}function s(a){let b=(0,h.getDb)();return o(b.prepare("SELECT * FROM hermes_jobs WHERE id = ?").get(a))}function t(a,b=200){return(0,h.getDb)().prepare("SELECT * FROM hermes_job_events WHERE job_id = ? ORDER BY at ASC LIMIT ?").all(a,b).map(p)}function u(a){let b=s(a);return b?{...b,events:t(a,500)}:null}function v(a,b=[]){let c=a.status||"queued",d=[],e=[...b].reverse().find(a=>"final"===a.type),f=[...b].reverse().find(a=>"error"===a.type);e?.message?d.push(e.message,""):(a.error||f?.message)&&d.push("## Error","",a.error||f.message,"");let g=b.filter(a=>!["final"].includes(a.type));if(g.length){for(let a of(d.push("## Progress",""),g.slice(-80))){let b=a.at?a.at.replace("T"," ").replace(/\.\d+Z$/,"Z"):"",c=(function(a,b=6e3){let c=String(a||"");return c.length>b?`${c.slice(0,b)}

[truncated ${c.length-b} chars]`:c})(a.message||a.type,1200).replace(/\n/g,"\n  ");d.push(`- ${b} ${a.type}: ${c}`.trim())}d.push("")}return"running"===c?d.push("## Current state","","Hermes is still running. This artifact updates as new progress arrives.",""):"queued"===c&&d.push("## Current state","","Hermes is queued and will start shortly.",""),`${d.join("\n")}
`}function w(a,{type:b,message:c,payload:d}={}){let e=(0,h.getDb)(),f=(0,h.newId)("hermes-event"),g=(0,h.nowIso)();return e.prepare(`
    INSERT INTO hermes_job_events (id, job_id, type, message, payload, at)
    VALUES (?, ?, ?, ?, ?, ?)
  `).run(f,a,b||"status",c||null,d?JSON.stringify(d):null,g),e.prepare("UPDATE hermes_jobs SET updated_at = ? WHERE id = ?").run(g,a),!function(a){let b=s(a);if(!b?.artifact_id)return;let c=t(a,500),d=(0,m.vr)(v(b,c)),e=(0,m.j7)({title:b.title||"Hermes Job",markdown:d,meta:`Status: ${b.status||"queued"}`}),f=(0,h.getDb)(),g=f.prepare("SELECT * FROM artifacts WHERE id = ?").get(b.artifact_id);g&&(f.prepare("UPDATE artifacts SET content = ?, source_md = ?, kind = ? WHERE id = ?").run(e,d,"document",b.artifact_id),q(g.path,d),b.artifact_id)}(a),{id:f,job_id:a,type:b||"status",message:c,payload:d,at:g}}function x({prompt:a,title:b,cwd:c,session_id:d,model:g,timeout_ms:n,project_id:o}={}){if(!a||"string"!=typeof a)throw Error("prompt is required");(0,i.Jh)();let p=function(a){if(!a)return null;let b=f.resolve(String(a));if(!e.existsSync(b)||!e.statSync(b).isDirectory())throw Error(`Working directory not found: ${b}`);let c=e.realpathSync(b);if(!(function(){let a=String(process.env.HERMES_ALLOWED_ROOTS||"").split(f.delimiter).map(a=>a.trim()).filter(Boolean);return[i.Dl,i.un,f.dirname(i.Dl),...a].map(a=>{let b=f.resolve(a);return e.existsSync(b)?e.realpathSync(b):b})})().some(a=>c===a||c.startsWith(`${a}${f.sep}`)))throw Error(`Working directory is outside allowed roots: ${b}`);return b}(c),r=(0,h.newId)("hermes-job"),t=(0,h.nowIso)(),u=b||`Hermes job: ${a.slice(0,60)}`,y=o||k.Sk,z=(0,j.Kg)(y),A=f.join(z,`${String(u||"hermes-job").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"hermes-job"}-${Date.now().toString(36)}.md`),B=(0,i.z9)(A),C=(0,l.recordRun)({kind:"hermes-job",title:u,agent:"Hermes Agent",agent_id:"hermes",status:"running",artifact:B,preview:`Hermes job queued: ${a.slice(0,160)}`,triggered_by:"claude"}),D=(0,m.vr)(v({id:r,title:u,prompt:a,cwd:p,status:"queued",created_at:t,updated_at:t},[])),E=(0,m.j7)({title:u,markdown:D,meta:"Status: queued"});q(B,D);let F=(0,l.recordArtifact)({run_id:C.id,agent_id:"hermes",file_path:B,kind:"document",title:u,content:E,source_md:D,project_id:y});return(0,h.getDb)().prepare(`
    INSERT INTO hermes_jobs (
      id, artifact_id, run_id, status, title, prompt, cwd, hermes_session_id, model,
      timeout_ms, created_at, updated_at
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(r,F,C.id,"queued",u,a,p,d||null,g||null,n?Number(n):null,t,t),w(r,{type:"queued",message:"Hermes job queued."}),(0,l.appendAudit)({type:"hermes.job.create",summary:`Queued Hermes job: ${u}`,status:"queued",meta:{job_id:r,run_id:C.id,artifact_id:F}}),{...s(r),file_path:B}}function y(a){let b=f.join(i.QG,"scripts","hermes-job-runner.mjs"),c=(0,g.spawn)(process.execPath,[b,"--job-id",a],{cwd:(0,i.wn)(i.QG,i.un),env:process.env,stdio:"ignore",detached:!0});return c.unref(),w(a,{type:"status",message:`Background runner spawned with pid ${c.pid}.`}),{pid:c.pid}}function z({olderThanMs:a=18e5}={}){let b=(0,h.getDb)(),c=new Date(Date.now()-a).toISOString(),d=b.prepare(`
    SELECT id FROM hermes_jobs
    WHERE status IN ('queued', 'running') AND updated_at < ?
  `).all(c);for(let a of d)!function(a,{error:b,exit_code:c=null,status:d="failed"}={}){let e=A.has(d)?d:"failed",f=(0,h.getDb)(),g=(0,h.nowIso)();f.prepare(`
    UPDATE hermes_jobs
    SET status = ?, error = ?, exit_code = ?, completed_at = ?, updated_at = ?
    WHERE id = ?
  `).run(e,b||"Hermes job failed",c,g,g,a),w(a,{type:"error",message:b||"Hermes job failed."});let i=s(a);i?.run_id&&(0,l.PF)(i.run_id,{status:"cancelled"===e?"cancelled":"failed",preview:b||"Hermes job failed.",output:b||""}),(0,l.appendAudit)({type:"hermes.job.fail",summary:`Hermes job failed: ${i?.title||a}`,status:e,meta:{job_id:a,error:b}}),s(a)}(a.id,{status:"stale",error:"Hermes job became stale before completion."});return d.length}d()}catch(a){d(a)}})},78608:a=>{a.exports=require("exceljs")},80099:a=>{a.exports=require("node:sqlite")},83237:a=>{a.exports=import("playwright")},86439:a=>{a.exports=require("next/dist/shared/lib/no-fallback-error.external")},95736:(a,b,c)=>{a.exports=c(44870)},96231:(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(64077),v=a([u]);u=(v.then?(await v)():v)[0];let y=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/hermes/jobs/[id]/events/route",pathname:"/api/hermes/jobs/[id]/events",filename:"route",bundlePath:"app/api/hermes/jobs/[id]/events/route"},distDir:".next",relativeProjectDir:"",resolvedPagePath:"/home/runner/work/madarx-os/madarx-os/app/api/hermes/jobs/[id]/events/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/hermes/jobs/[id]/events/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],()=>b(b.s=96231));module.exports=c})();