@zaip-ai/cli 3.4.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/services/adapters.d.ts +1 -1
- package/dist/services/adapters.js +1 -1
- package/package.json +1 -1
- package/templates/.agents/config/agents/discovery.json +1 -1
- package/templates/.agents/dashboard/.zaip-managed.json +54 -38
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{ProjectSettingsPage-B9GWkEyN.css → ProjectSettingsPage-CQMhvzvJ.css} +1 -1
- package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-D46WWIKr.js +3 -0
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{TraceabilityWorkspace-CqK3Psfy.js → TraceabilityWorkspace-BKBpJyLh.js} +1 -1
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{index-Cl5EWx8R.js → index-Bas2TVju.js} +2 -2
- package/templates/.agents/dashboard/apps/frontend/dist/assets/index-CxrG_wRI.css +1 -0
- package/templates/.agents/dashboard/apps/frontend/dist/index.html +2 -2
- package/templates/.agents/dashboard/apps/frontend/package.json +1 -1
- package/templates/.agents/dashboard/apps/frontend/src/ProjectSettingsCard.tsx +5 -0
- package/templates/.agents/dashboard/apps/frontend/src/ProjectSettingsField.tsx +21 -0
- package/templates/.agents/dashboard/apps/frontend/src/ProjectSettingsPage.dom.test.ts +12 -1
- package/templates/.agents/dashboard/apps/frontend/src/ProjectSettingsPage.tsx +16 -28
- package/templates/.agents/dashboard/apps/frontend/src/ProjectStackEditor.tsx +25 -4
- package/templates/.agents/dashboard/apps/frontend/src/WorkspaceStatus.test.tsx +26 -8
- package/templates/.agents/dashboard/apps/frontend/src/WorkspaceStatus.tsx +9 -28
- package/templates/.agents/dashboard/apps/frontend/src/project-settings-copy.ts +13 -4
- package/templates/.agents/dashboard/apps/frontend/src/project-settings-model.ts +25 -1
- package/templates/.agents/dashboard/apps/frontend/src/project-settings-workspace.css +28 -0
- package/templates/.agents/dashboard/apps/frontend/src/project-settings.test.ts +39 -0
- package/templates/.agents/dashboard/apps/frontend/src/workspace-status.css +1 -14
- package/templates/.agents/dashboard/modules/cost-monitor/package.json +1 -1
- package/templates/.agents/dashboard/modules/operations/package.json +1 -1
- package/templates/.agents/dashboard/modules/traceability/package.json +1 -1
- package/templates/.agents/dashboard/packages/branding/package.json +1 -1
- package/templates/.agents/dashboard/packages/contracts/package.json +1 -1
- package/templates/.agents/dashboard/packages/data-export/package.json +1 -1
- package/templates/.agents/dashboard/packages/local-runtime/dist/server.cjs +2 -2
- package/templates/.agents/dashboard/packages/local-runtime/dist/sqlite-read-model.cjs +73 -73
- package/templates/.agents/dashboard/packages/local-runtime/package.json +1 -1
- package/templates/.agents/dashboard/packages/local-runtime/scripts/validate-sqlite-read-model.mjs +38 -6
- package/templates/.agents/dashboard/packages/local-runtime/server.mjs +2 -2
- package/templates/.agents/dashboard/packages/local-runtime/src/project-settings.test.ts +2 -3
- package/templates/.agents/dashboard/packages/local-runtime/src/project-settings.ts +1 -1
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-pricing-provenance.test.ts +39 -0
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-canonical.ts +2 -2
- package/templates/.agents/dashboard/packages/ui/package.json +1 -1
- package/templates/.agents/dashboard/tests/e2e/package.json +1 -1
- package/templates/.agents/design/.zaip-managed.json +78 -50
- package/templates/.agents/design/apps/catalog/dist/assets/index-D1JaPXfV.css +1 -0
- package/templates/.agents/design/apps/catalog/dist/assets/index-D2miO4-O.js +72 -0
- package/templates/.agents/design/apps/catalog/dist/assets/index-mvD5mwcC.js +72 -0
- package/templates/.agents/design/apps/catalog/dist/index.html +2 -2
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{CatalogShell-CvaciY0C.js → CatalogShell-BJ8b4xZr.js} +1 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{Color-6AOWCN3U-DwBV1A1Y.js → Color-6AOWCN3U-CQLHzznn.js} +1 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/Components.stories-kxWwSKin.js +146 -0
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/DashboardFilters.stories-Chm_dXV7.js +9 -0
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/DashboardFiltersSpecimen-9CaCbGIZ.js +1 -0
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{DesignSystem.stories-2OCgtT0I.js → DesignSystem.stories-ED52wFjY.js} +1 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{DocsRenderer-JROSPFPF-CODg0rSl.js → DocsRenderer-JROSPFPF-BcLgM80v.js} +4 -4
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{Primitives-BmeKjJW4.js → Primitives-DV6Bpudf.js} +1 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{WithTooltip-7X4HQR7L-C5MI-3uZ.js → WithTooltip-7X4HQR7L-BKNiAz_E.js} +1 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{WorkspaceStatus.stories-Tb_iQqVK.js → WorkspaceStatus.stories-BL19HGOo.js} +2 -2
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/WorkspaceStatusSpecimen-DQnSS6s9.js +1 -0
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{chunk-DRQKCCAG-KSn75jcy.js → chunk-DRQKCCAG-DZBcXL-p.js} +1 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{chunk-W22LQPXL-C4LS1Thf.js → chunk-W22LQPXL-CF3y2mfo.js} +1 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{components-DV1BRgMY.js → components-BVjxMRGq.js} +5 -5
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/formatter-L2YTDE3Q-Do9sjqiW.js +1 -0
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{iframe-CBbPFx5G.js → iframe-CTWGZcEe.js} +4 -4
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{react-18-C9IPGXtb.js → react-18-B9_a4mHb.js} +1 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/react-NrUxok8K.js +1 -0
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{syntaxhighlighter-YFXUGROL-ZgDQjyWI.js → syntaxhighlighter-YFXUGROL-F_p8E2xc.js} +1 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/{theming-Cx9-gH6l.js → theming-fbSD9ZLF.js} +1 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/iframe.html +1 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/index.json +1 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/sb-addons/a11y-2/manager-bundle.js +3 -3
- package/templates/.agents/design/apps/catalog/dist/storybook/sb-addons/docs-1/manager-bundle.js +4 -4
- package/templates/.agents/design/apps/catalog/dist/storybook/sb-addons/storybook-core-server-presets-0/common-manager-bundle.js +60 -60
- package/templates/.agents/design/apps/catalog/package.json +1 -1
- package/templates/.agents/design/apps/catalog/src/components/StackVersionFieldSpecimen.tsx +70 -0
- package/templates/.agents/design/apps/catalog/src/components/WorkspaceStatusSpecimen.tsx +23 -7
- package/templates/.agents/design/apps/catalog/src/pages/ComponentsPage.tsx +20 -6
- package/templates/.agents/design/apps/catalog/src/stories/Components.stories.tsx +14 -0
- package/templates/.agents/design/apps/catalog/src/stories/WorkspaceStatus.stories.tsx +5 -2
- package/templates/.agents/design/apps/catalog/src/styles/components.css +1 -1
- package/templates/.agents/design/apps/catalog/src/styles/stack-version-field.css +17 -0
- package/templates/.agents/design/packages/local-runtime/package.json +1 -1
- package/templates/.agents/requirements/autonomous-assurance.md +1 -1
- package/templates/.agents/requirements/cloud-hostinger-autonomy.md +1 -1
- package/templates/.agents/requirements/comparative-audit.md +1 -1
- package/templates/.agents/requirements/context-engine.md +1 -1
- package/templates/.agents/requirements/cost-observability.md +1 -1
- package/templates/.agents/requirements/dashboard-launch.md +1 -1
- package/templates/.agents/requirements/data-export.md +1 -1
- package/templates/.agents/requirements/design-system.md +1 -1
- package/templates/.agents/requirements/execution-engine.md +1 -1
- package/templates/.agents/requirements/kanban-dashboard.md +1 -1
- package/templates/.agents/requirements/model-orchestration.md +1 -1
- package/templates/.agents/requirements/public-distribution.md +1 -1
- package/templates/.agents/requirements/software-architecture.md +1 -1
- package/templates/.agents/requirements/strategic-improvements.md +1 -1
- package/templates/.agents/requirements/work-lifecycle.md +1 -1
- package/templates/.agents/requirements/zaip-strategic-95.md +1 -1
- package/templates/.agents/rules/workflow.md +1 -1
- package/templates/.agents/runtime/VERSION +1 -1
- package/templates/.agents/runtime/bin/zaip.mjs +9 -9
- package/templates/.agents/runtime/checksums.sha256 +5 -5
- package/templates/.agents/runtime/manifest.json +1 -1
- package/templates/.agents/runtime/provenance.json +4 -4
- package/templates/.agents/runtime/sbom.cdx.json +1 -1
- package/templates/.agents/skills/zaip-skill-github-deploy/SKILL.md +5 -4
- package/templates/.agents/skills/zaip-skill-github-deploy/agents/openai.yaml +1 -1
- package/templates/.agents/skills/zaip-skill-github-deploy/references/deployment-workflow.md +7 -7
- package/templates/.agents/skills/zaip-skill-github-deploy/scripts/consumer-release-preparation.mjs +1 -2
- package/templates/.agents/skills/zaip-skill-github-deploy/scripts/consumer-release-preparation.test.mjs +9 -1
- package/templates/.agents/skills/zaip-skill-github-deploy/scripts/github-deploy-contract.test.mjs +23 -0
- package/templates/.agents/skills/zaip-skill-github-deploy/scripts/preflight.mjs +2 -6
- package/templates/.agents/skills/zaip-skill-github-deploy/scripts/preflight.test.mjs +15 -1
- package/templates/.agents/zaip-aios/VERSION +1 -1
- package/templates/template-manifest.json +169 -125
- package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-DVCPPV75.js +0 -3
- package/templates/.agents/dashboard/apps/frontend/dist/assets/index-Cwylbh_N.css +0 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/Components.stories-3dqK5g3e.js +0 -142
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/WorkspaceStatusSpecimen-CD54pw0-.js +0 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/formatter-L2YTDE3Q-BU_68im1.js +0 -1
- package/templates/.agents/design/apps/catalog/dist/storybook/assets/react-CEv2qkJT.js +0 -1
|
@@ -342,7 +342,7 @@ ${i.join(`\r
|
|
|
342
342
|
\r
|
|
343
343
|
`)},gL=e=>{let t=e.socket.encrypted?"https":"http",n=new URL(e.url??"/",`${t}://${e.headers.host??"localhost"}`),i=new Headers;for(let r in e.headers){let o=e.headers[r];o&&i.append(r,Array.isArray(o)?o[0]:o)}return new Request(n,{headers:i})},hL=e=>{let{server:t,fetchCallback:n,wss:i}=e,r=new Map;i.on("connection",(s,l)=>{let c=r.get(l);c&&(c.resolve(s),r.delete(l))});let o=s=>{let l=r.get(s);l&&(r.delete(s),l.reject(new Error("WebSocket handshake aborted")))},a=(s,l)=>new Promise((c,u)=>{r.set(s,{resolve:c,reject:u,connectionSymbol:l})});t.on("upgrade",async(s,l,c)=>{if(s.headers.upgrade?.toLowerCase()!=="websocket")return;let u={incoming:s,outgoing:void 0,wss:i,[Ib]:a},d=400,_;try{let g=await n(gL(s),u);g instanceof Response&&(d=g.status,_=g.headers)}catch{t.listenerCount("upgrade")===1&&yb(l,500);return}let p=r.get(s);if(!p||p.connectionSymbol!==u[Cb]){o(s),t.listenerCount("upgrade")===1&&yb(l,d,_);return}let f=g=>{Nb(g,_)},m=()=>o(s);l.once("close",m),i.on("headers",f);try{i.handleUpgrade(s,l,c,g=>{l.off("close",m),i.emit("connection",g,s)})}finally{i.off("headers",f)}}),t.on("close",()=>{i.close()})},l5=db(async(e,t,n)=>{if(e.req.header("upgrade")?.toLowerCase()!=="websocket")return;let i=e.env,r=i[Ib];if(!r||!i.incoming)return new Response(null,{status:500});let o=mL();return i[Cb]=o,(async()=>{let a;try{a=await r(i.incoming,o)}catch{return}let s=[],l=(d,_)=>{s.push([d,_])};a.on("message",l);let c={binaryType:"arraybuffer",close(d,_){a.close(d,_)},protocol:a.protocol,raw:a,get readyState(){return a.readyState},send(d,_){a.send(d,{compress:_?.compress})},url:new URL(e.req.url)};try{t?.onOpen?.(new Event("open"),c)}catch(d){(n?.onError??console.error)(d)}let u=(d,_)=>{let p=Array.isArray(d)?d:[d];for(let f of p)try{t?.onMessage?.(new MessageEvent("message",{data:_?f instanceof ArrayBuffer?f:f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength):typeof f=="string"?f:Buffer.from(f).toString("utf-8")}),c)}catch(m){(n?.onError??console.error)(m)}};a.off("message",l);for(let d of s)u(...d);a.on("message",(d,_)=>{u(d,_)}),a.on("close",(d,_)=>{try{t?.onClose?.(new _L("close",{code:d,reason:_.toString()}),c)}catch(p){(n?.onError??console.error)(p)}}),a.on("error",d=>{try{t?.onError?.(new pL("error",{error:d}),c)}catch(_){(n?.onError??console.error)(_)}})})(),new Response}),yL=e=>{let t=e.fetch,n=dL(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),i=(e.createServer||nl.createServer)(e.serverOptions||{},n);if(e.websocket&&e.websocket.server){if(e.websocket.server.options.noServer!==!0)throw new Error("WebSocket server must be created with { noServer: true } option");hL({server:i,fetchCallback:t,wss:e.websocket.server})}return i},$b=(e,t)=>{let n=yL(e);return n.listen(e?.port??3e3,e.hostname,()=>{let i=n.address();t&&t(i)}),n};var Pb=require("node:stream"),Lb=require("node:process"),vL=()=>{let[e,t]=Lb.versions.node.split(".").map(n=>parseInt(n));return e>=23||e===22&&t>=7||e===20&&t>=18},bL=vL(),im=(e,t=bL)=>{if(t)return Pb.Readable.toWeb(e);let n,i=!1,r=()=>{e.off("data",a),e.off("error",s),e.off("end",l),e.off("close",l)},o=c=>{i||(i=!0,r(),c?.())},a=c=>{i||!n||(n.enqueue(c),(n.desiredSize??0)<=0&&e.pause())},s=c=>{o(()=>{n?.error(c)})},l=()=>{o(()=>{n?.close()})};return new ReadableStream({start(c){n=c,e.on("data",a),e.on("error",s),e.on("end",l),e.on("close",l),e.pause()},pull(){i||e.resume()},cancel(){o();let c=()=>{};e.on("error",c),e.once("close",()=>e.off("error",c)),e.destroy()}})};var Mb=(e,t=kL)=>{let n=/\.([a-zA-Z0-9]+?)$/,i=e.match(n);if(i)return t[i[1].toLowerCase()]};var SL={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css; charset=utf-8",csv:"text/csv; charset=utf-8",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html; charset=utf-8",html:"text/html; charset=utf-8",ico:"image/x-icon",ics:"text/calendar; charset=utf-8",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript; charset=utf-8",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript; charset=utf-8",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml; charset=utf-8",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain; charset=utf-8",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml; charset=utf-8",xml:"application/xml; charset=utf-8",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},kL=SL;var eo=require("node:fs"),am=require("node:path"),EL=/^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,sm={br:".br",zstd:".zst",gzip:".gz"},wL=Object.keys(sm),om=e=>{let t;try{t=(0,eo.statSync)(e)}catch{}return t},AL=/^(?:bytes=)?(?!-$)(\d*)-(\d*)$/,TL=e=>{let t=e.match(AL);if(!t)return;let[,n,i]=t;return n===""?{type:"suffix",length:Number(i)}:i===""?{type:"open-ended",start:Number(n)}:{type:"bounded",start:Number(n),end:Number(i)}},xL=(e,t)=>{if(t===0)return;if(e.type==="suffix")return e.length===0?void 0:{start:Math.max(t-e.length,0),end:t-1};let n=e.type==="bounded"?Math.min(e.end,t-1):t-1;if(!(e.start>=t||e.start>n))return{start:e.start,end:n}},OL=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},RL=e=>OL(e,decodeURI),rl=(e={root:""})=>{let t=e.root||"",n=e.path;return t!==""&&!(0,eo.existsSync)(t)&&console.error(`serveStatic: root path '${t}' is not found, are you sure it's correct?`),async(i,r)=>{if(i.finalized)return r();let o;if(n)o=n;else try{if(o=RL(i.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(o))throw new Error}catch{return await e.onNotFound?.(i.req.path,i),r()}let a=(0,am.join)(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(o,i):o),s=om(a);if(s&&s.isDirectory()){let _=e.index??"index.html";a=(0,am.join)(a,_),s=om(a)}if(!s)return await e.onNotFound?.(a,i),r();let l=Mb(a);if(i.header("Content-Type",l||"application/octet-stream"),e.precompressed&&(!l||l==="application/octet-stream"||EL.test(l))){let _=new Set(i.req.header("Accept-Encoding")?.split(",").map(p=>p.trim()));for(let p of wL){if(!_.has(p))continue;let f=om(a+sm[p]);if(f){i.header("Content-Encoding",p),i.header("Vary","Accept-Encoding",{append:!0}),s=f,a=a+sm[p];break}}}let c,u=s.size,d=i.req.header("range")||"";if(i.header("Last-Modified",s.mtime.toUTCString()),i.req.method=="HEAD"||i.req.method=="OPTIONS")i.header("Content-Length",u.toString()),i.status(200),c=i.body(null);else if(!d)i.header("Content-Length",u.toString()),c=i.body(im((0,eo.createReadStream)(a)),200);else{i.header("Accept-Ranges","bytes");let _=xL(TL(d)??{type:"open-ended",start:0},u);if(!_)i.header("Content-Range",`bytes */${u}`),c=i.body(null,416);else{let{start:p,end:f}=_,m=f-p+1,g=(0,eo.createReadStream)(a,{start:p,end:f});i.header("Content-Length",m.toString()),i.header("Content-Range",`bytes ${p}-${f}/${u}`),c=i.body(im(g),206)}}return await e.onFound?.(a,i),c}};We();Wr();var dh=(e,t,n)=>(i,r)=>{let o=-1;return a(0);async function a(s){if(s<=o)throw new Error("next() called multiple times");o=s;let l,c=!1,u;if(e[s]?(u=e[s][0][0],i.req.routeIndex=s):u=s===e.length&&r||void 0,u)try{l=await u(i,()=>a(s+1))}catch(d){if(d instanceof Error&&t)i.error=d,l=await t(d,i),c=!0;else throw d}else i.finalized===!1&&n&&(l=await n(i));return l&&(i.finalized===!1||c)&&(i.res=l),i}};var aO=Symbol();var sO=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,i=>i.toLowerCase())}}).formData();var cO=32,MG=1e4,Kd=e=>"headers"in e,dO=async(e,t=Object.create(null))=>{let{all:n=!1,dot:i=!1}=t,a=(Kd(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return a==="multipart/form-data"||a==="application/x-www-form-urlencoded"?DG(e,{all:n,dot:i}):{}};async function DG(e,t){if(!Kd(e)&&e.bodyCache.formData)return lO(await e.bodyCache.formData,t);let n=Kd(e)?e.headers:e.raw.headers,i=await e.arrayBuffer(),r=sO(i,n.get("Content-Type")||"");Kd(e)||(e.bodyCache.formData=r);let o=await r;return o?lO(o,t):{}}function lO(e,t){let n=Object.create(null),i={count:0};return e.forEach((r,o)=>{t.all||o.endsWith("[]")?jG(n,o,r):n[o]=r}),t.dot&&Object.entries(n).forEach(([r,o])=>{r.includes(".")&&(UG(n,r,o,i),delete n[r])}),n}var jG=(e,t,n)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]:t.endsWith("[]")?e[t]=[n]:e[t]=n},UG=(e,t,n,i)=>{if(/(?:^|\.)__proto__\./.test(t))return;let r=e,o=t.split(".",cO+2);o.length>cO+1&&uO(),o.forEach((a,s)=>{s===o.length-1?r[a]=n:((!r[a]||typeof r[a]!="object"||Array.isArray(r[a])||r[a]instanceof File)&&(i.count++>=MG&&uO(),r[a]=Object.create(null)),r=r[a])})},uO=()=>{throw new Error("Nesting limit exceeded")};var ph=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},_O=e=>{let{groups:t,path:n}=FG(e),i=ph(n);return zG(i,t)},FG=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,i)=>{let r=`@${i}`;return t.push([r,n]),r}),{groups:t,path:e}},zG=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[i]=t[n];for(let r=e.length-1;r>=0;r--)if(e[r].includes(i)){e[r]=e[r].replace(i,t[n][1]);break}}return e},Xd={},pO=(e,t)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let i=`${e}#${t}`;return Xd[i]||(n[2]?Xd[i]=t&&t[0]!==":"&&t[0]!=="*"?[i,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)]:Xd[i]=[e,n[1],!0]),Xd[i]}return null},mO=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},qG=e=>mO(e,decodeURI),mh=e=>{let t=e.url,n=t.indexOf("/",t.indexOf(":")+4),i=n;for(;i<t.length;i++){let r=t.charCodeAt(i);if(r===37){let o=t.indexOf("?",i),a=t.indexOf("#",i),s=o===-1?a===-1?void 0:a:a===-1?o:Math.min(o,a),l=t.slice(n,s);return qG(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(r===63||r===35)break}return t.slice(n,i)};var fO=e=>{let t=mh(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},Ui=(e,t,...n)=>(n.length&&(t=Ui(t,...n)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),Yd=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),n=[],i="";return t.forEach(r=>{if(r!==""&&!/\:/.test(r))i+="/"+r;else if(/\:/.test(r))if(r.charCodeAt(r.length-1)===63){n.length===0&&i===""?n.push("/"):n.push(i);let o=r.slice(0,-1);i+="/"+o,n.push(i)}else i+="/"+r}),n.filter((r,o,a)=>a.indexOf(r)===o)},ya=e=>e.indexOf("%")!==-1?mO(e,VG):e,_h=e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),ya(e)),gO=(e,t,n)=>{let i=e.indexOf("#",8);i!==-1&&(e=e.slice(0,i));let r;if(!n&&t&&t.indexOf("%")===-1&&t.indexOf("+")===-1){let s=e.indexOf("?",8);if(s===-1)return;for(e.startsWith(t,s+1)||(s=e.indexOf(`&${t}`,s+1));s!==-1;){let l=e.charCodeAt(s+t.length+1);if(l===61){let c=s+t.length+2,u=e.indexOf("&",c);return _h(e.slice(c,u===-1?void 0:u))}else if(l==38||isNaN(l))return"";s=e.indexOf(`&${t}`,s+1)}if(r=/[%+]/.test(e),!r)return}let o=Object.create(null);r??=/[%+]/.test(e);let a=e.indexOf("?",8);for(;a!==-1;){let s=e.indexOf("&",a+1),l=e.indexOf("=",a);l>s&&s!==-1&&(l=-1);let c=e.slice(a+1,l===-1?s===-1?void 0:s:l);if(r&&(c=_h(c)),a=s,c==="")continue;let u;l===-1?u="":(u=e.slice(l+1,s===-1?void 0:s),r&&(u=_h(u))),n?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(u)):o[c]??=u}return t?o[t]:o},hO=gO,yO=(e,t)=>gO(e,t,!0),VG=decodeURIComponent;var vO=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",n=[[]]){this.raw=e,this.path=t,this.#t=n}param(e){return e?this.#n(e):this.#o()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#r(t);return n&&ya(n)}#o(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let i=this.#r(this.#t[0][this.routeIndex][1][n]);i!==void 0&&(e[n]=ya(i))}return e}#r(e){return this.#t[1]?this.#t[1][e]:e}query(e){return hO(this.url,e)}queries(e){return yO(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((n,i)=>{t[i]=n}),t}async parseBody(e){return dO(this,e)}#i=e=>{let{bodyCache:t,raw:n}=this,i=t[e];if(i)return i;for(let r in t)return t[r].then(o=>(r==="json"&&(o=JSON.stringify(o)),new Response(o)[e]()));return t[e]=n[e]()};json(){return this.#i("text").then(e=>JSON.parse(e))}text(){return this.#i("text")}arrayBuffer(){return this.#i("arrayBuffer")}bytes(){return this.#i("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#i("blob")}formData(){return this.#i("formData")}addValidatedData(e,t){(this.#e??={})[e]=t}valid(e){return this.#e?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[aO](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};var Qd={Stringify:1,BeforeStream:2,Stream:3},WG=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n};var Ks=async(e,t,n,i,r)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let o=e.callbacks;if(!o?.length)return Promise.resolve(e);r?r[0]+=e:r=[e];let a=Promise.all(o.map(s=>s({phase:t,buffer:r,context:i}))).then(s=>Promise.all(s.filter(Boolean).map(l=>Ks(l,t,!1,i,r))).then(()=>r[0]));return n?WG(await a,o):a};var bO="text/plain; charset=UTF-8",fh=(e,t)=>({"Content-Type":e,...t}),Xs=(e,t)=>new Response(e,t),gh=class{#e;#t;env={};#n;finalized=!1;error;#o;#r;#i;#u;#c;#l;#s;#d;#_;constructor(e,t){this.#e=e,t&&(this.#r=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#_=t.path,this.#d=t.matchResult)}get req(){return this.#t??=new vO(this.#e,this.#_,this.#d),this.#t}get event(){if(this.#r&&"respondWith"in this.#r)return this.#r;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#r)return this.#r;throw Error("This context has no ExecutionContext")}get res(){return this.#i||=Xs(null,{headers:this.#s??=new Headers})}set res(e){if(this.#i&&e){e=Xs(e.body,e);for(let[t,n]of this.#i.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let i=this.#i.headers.getSetCookie();e.headers.delete("set-cookie");for(let r of i)e.headers.append("set-cookie",r)}else e.headers.set(t,n)}this.#i=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,n)=>{this.finalized&&(this.#i=Xs(this.#i.body,this.#i));let i=this.#i?this.#i.headers:this.#s??=new Headers;t===void 0?i.delete(e):n?.append?i.append(e,t):i.set(e,t)};status=e=>{this.#o=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#a(e,t,n){let i=this.#i?new Headers(this.#i.headers):this.#s;if(typeof t=="object"&&t.headers){i??=new Headers;for(let[o,a]of new Headers(t.headers))o==="set-cookie"?i.append(o,a):i.set(o,a)}if(n){if(!i){let o=0;for(let a in n)if(++o>1||typeof n[a]!="string"){i=new Headers;break}}if(i)for(let o in n){let a=n[o];if(typeof a=="string")i.set(o,a);else{i.delete(o);for(let s of a)i.append(o,s)}}}let r=typeof t=="number"?t:t?.status??this.#o;return Xs(e,{status:r,headers:i??n})}newResponse=(...e)=>this.#a(...e);body=(e,t,n)=>this.#a(e,t,n);text=(e,t,n)=>!this.#s&&!this.#o&&!t&&!n&&!this.finalized?new Response(e):this.#a(e,t,fh(bO,n));json=(e,t,n)=>this.#a(JSON.stringify(e),t,fh("application/json",n));html=(e,t,n)=>{let i=r=>this.#a(r,t,fh("text/html; charset=UTF-8",n));return typeof e=="object"?Ks(e,Qd.Stringify,!1,{}).then(i):i(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>Xs(),this.#l(this))};var Mt="ALL",SO="all",kO=["get","post","put","delete","options","patch","query"],e_="Can not add a route since the matcher is already built.",t_=class extends Error{};var EO="__COMPOSED_HANDLER";var ZG=e=>e.text("404 Not Found",404),wO=(e,t)=>{if("getResponse"in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text("Internal Server Error",500)},AO=class TO{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...kO,SO].forEach(o=>{this[o]=(a,...s)=>(typeof a=="string"?this.#e=a:this.#o(o,this.#e,a),s.forEach(l=>{this.#o(o,this.#e,l)}),this)}),this.on=(o,a,...s)=>{for(let l of[a].flat()){this.#e=l;for(let c of[o].flat())s.map(u=>{this.#o(c.toUpperCase(),this.#e,u)})}return this},this.use=(o,...a)=>(typeof o=="string"?this.#e=o:(this.#e="*",a.unshift(o)),a.forEach(s=>{this.#o(Mt,this.#e,s)}),this);let{strict:i,...r}=t;Object.assign(this,r),this.getPath=i??!0?t.getPath??mh:fO}#t(){let t=new TO({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=ZG;errorHandler=wO;route(t,n){let i=this.basePath(t);return n.routes.map(r=>{let o;n.errorHandler===wO?o=r.handler:(o=async(a,s)=>(await dh([],n.errorHandler)(a,()=>r.handler(a,s))).res,o[EO]=r.handler),i.#o(r.method,r.path,o,r.basePath)}),this}basePath(t){let n=this.#t();return n._basePath=Ui(this._basePath,t),n}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#n=t,this);mount(t,n,i){let r,o;i&&(typeof i=="function"?o=i:(o=i.optionHandler,i.replaceRequest===!1?r=l=>l:r=i.replaceRequest));let a=o?l=>{let c=o(l);return Array.isArray(c)?c:[c]}:l=>{let c;try{c=l.executionCtx}catch{}return[l.env,c]};r||=(()=>{let l=Ui(this._basePath,t),c=l==="/"?0:l.length;return u=>{let d=new URL(u.url);return d.pathname=this.getPath(u).slice(c)||"/",new Request(d,u)}})();let s=async(l,c)=>{let u=await n(r(l.req.raw),...a(l));if(u)return u;await c()};return this.#o(Mt,Ui(t,"*"),s),this}#o(t,n,i,r){t=t.toUpperCase(),n=Ui(this._basePath,n);let o={basePath:r!==void 0?Ui(this._basePath,r):this._basePath,path:n,method:t,handler:i};this.router.add(t,n,[i,o]),this.routes.push(o)}#r(t,n){if(t instanceof Error)return this.errorHandler(t,n);throw t}#i(t,n,i,r){if(r==="HEAD")return(async()=>new Response(null,await this.#i(t,n,i,"GET")))();let o=this.getPath(t,{env:i}),a=this.router.match(r,o),s=new gh(t,{path:o,matchResult:a,env:i,executionCtx:n,notFoundHandler:this.#n});if(a[0].length===1){let c;try{c=a[0][0][0][0](s,async()=>{s.res=await this.#n(s)})}catch(u){return this.#r(u,s)}return c instanceof Promise?c.then(u=>u||(s.finalized?s.res:this.#n(s))).catch(u=>this.#r(u,s)):c??this.#n(s)}let l=dh(a[0],this.errorHandler,this.#n);return(async()=>{try{let c=await l(s);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#r(c,s)}})()}fetch=(t,...n)=>this.#i(t,n[1],n[0],t.method);request=(t,n,i,r)=>t instanceof Request?this.fetch(n?new Request(t,n):t,i,r):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Ui("/",t)}`,n),i,r));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#i(t.request,t,void 0,t.request.method))})}};var Nt=()=>Object.create(null);var n_=[];function hh(e,t){let n=this.buildAllMatchers(),i=((r,o)=>{let a=n[r]||n[Mt],s=a[2][o];if(s)return s;let l=o.match(a[0]);if(!l)return[[],n_];let c=l.indexOf("",1);return[a[1][c],l]});return this.match=i,i(e,t)}var va="[^/]+",zi=".*",_i="(?:|/.*)",Fi=Symbol(),xO=new Set(".\\+*[^]$()");function BG(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===zi||e===_i?t===_i?-1:1:t===zi||t===_i?-1:e===va?1:t===va?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var OO=class yh{#e;#t;#n=Nt();insert(t,n,i,r,o){let a=this;for(let s=0,l=t.length;s<l;s++){let c=t[s],u=c.length===1?c==="*"?s===l-1?["","",zi]:["","",va]:null:c==="/*"?["","",_i]:c.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let _=u[1],p=u[2]||va;if(_&&u[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))||p.length===1&&xO.has(p)))throw Fi;if(d=a.#n[p],!d){if(p!==zi&&p!==_i){for(let f in a.#n)if((p.length>1||f.length>1)&&f!==zi&&f!==_i)throw Fi}d=a.#n[p]=new yh}_!==""&&(d.#t??=r.varIndex++,i.push([_,d.#t]))}else if(d=a.#n[c],!d){for(let _ in a.#n)if(_.length>1&&_!==zi&&_!==_i)throw Fi;d=a.#n[c]=new yh}a=d}if(a.#e!==void 0)throw Fi;a.#e=o?-1:n}buildRegExpStr(){let n=Object.keys(this.#n).sort(BG).map(i=>{let r=this.#n[i],o=r.buildRegExpStr();return o===""?"":(typeof r.#t=="number"?`(${i})@${r.#t}`:xO.has(i)?`\\${i}`:i)+o}).filter(Boolean);return typeof this.#e=="number"&&this.#e!==-1&&n.unshift(`#${this.#e}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};var vh=class{#e={varIndex:0};#t=new OO;#n=0;paths=Nt();insert(e,t){if(t){this.#t.insert(e.split(""),0,[],this.#e,!0);return}let n=[],i=[],r=e;for(let a=0;;){let s=!1;if(r=r.replace(/\{[^}]+\}/g,l=>{let c=`@\\${a}`;return i[a]=[c,l],a++,s=!0,c}),!s)break}let o=r.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=i.length-1;a>=0;a--){let[s]=i[a];for(let l=o.length-1;l>=0;l--)if(o[l].indexOf(s)!==-1){o[l]=o[l].replace(s,i[a][1]);break}}this.#t.insert(o,this.#n,n,this.#e,!1),this.paths[e]=[this.#n++,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,n=[],i=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(r,o,a)=>o!==void 0?(n[++t]=Number(o),"$()"):(a!==void 0&&(i[Number(a)]=++t),"")),[new RegExp(`^${e}`),n,i]}};var RO=Nt();function CO(e){return RO[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,n)=>n?`\\${n}`:t==="/*"?_i:t==="*"?zi:`/:${va}`)}$`)}function r_(e,t){for(let n of Object.keys(e).sort((i,r)=>r.length-i.length))if(CO(n).test(t))return[...e[n]]}var i_=class{name="RegExpRouter";#e;#t;#n;constructor(){this.#e={[Mt]:Nt()},this.#t={[Mt]:Nt()},this.#n={[Mt]:new vh}}#o(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(n){throw n===Fi?new t_(t):n}}add(e,t,n){let i=this.#e,r=this.#t;if(!i)throw new Error(e_);if(!i[e]){this.#n[e]=new vh;for(let s of[i,r]){s[e]=Nt();for(let l in s[Mt])s[e][l]=[...s[Mt][l]],this.#o(e,l)}}t==="/*"&&(t="*");let o=e===Mt?Object.keys(i):[e];if(/\*$/.test(t)){let s=CO(t);for(let l of o)i[l][t]||(this.#o(l,t),i[l][t]=r_(i[l],t)||r_(i[Mt],t)||[]);for(let l of[i,r])for(let c of o)for(let u in l[c])s.test(u)&&l[c][u].push([n,t]);return}let a=Yd(t)||[t];for(let s of a)for(let l of o)r[l][s]||(this.#o(l,s),r[l][s]=r_(i[l],s)||r_(i[Mt],s)||[]),r[l][s].push([n,s])}match=hh;buildAllMatchers(){let e=Nt();for(let t of Object.keys(this.#t))e[t]=this.#r(t);return this.#e=this.#t=this.#n=void 0,RO=Nt(),e}#r(e){let t=this.#e[e],n=this.#t[e],i=this.#n[e],r=Nt(),o=[],[a,s,l]=i.buildRegExp();for(let c of[t,n])for(let u in c){let d=c[u],_=i.paths[u];if(!_){r[u]=[d.map(([p])=>[p,Nt()]),n_];continue}o[_[0]]=d.map(([p,f])=>[p,i.paths[f][1].reduceRight((m,[g],v)=>(m[g]=l[_[1][v][1]],m),Nt())])}return[a,s.map(c=>o[c]),r]}};var bh=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw new Error(e_);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw new Error("Fatal error");let n=this.#e,i=this.#t,r=n.length,o=0,a;for(;o<r;o++){let s=n[o];try{for(let l=0,c=i.length;l<c;l++)s.add(...i[l]);a=s.match(e,t)}catch(l){if(l instanceof t_)continue;throw l}this.match=s.match.bind(s),this.#e=[s],this.#t=void 0;break}if(o===r)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,a}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};var Sh=Nt(),HG=0,IO=class NO{#e=[];#t=Nt();#n=[];#o;#r=Sh;insert(t,n,i){let r=this,o=_O(n),a=new Set,s=0;for(let l of o){let c=o[++s],u=pO(l,c)||(c===void 0&&l&&l.indexOf("*")===l.length-1?l:null),d=Array.isArray(u),_=d?u[0]:u||l,p=r.#t[_]||=new NO;u&&!p.#o&&(p.#o=u,r.#n.push(p)),r=p,d&&a.add(u[1])}r.#e.push({[t]:{handler:i,possibleKeys:[...a],score:++HG}})}#i(t,n,i,r,o){for(let a=0,s=n.#e.length;a<s;a++){let l=n.#e[a],c=l[i]||l[Mt];if(c){c.params=Nt(),t.push(c);for(let u=0,d=c.possibleKeys.length;u<d;u++){let _=c.possibleKeys[u];c.params[_]=o?.[_]&&!u?o[_]:r[_]??o?.[_]}}}}search(t,n){let i=[];this.#r=Sh;let o=[this],a=ph(n),s=[],l=a.length,c=null;for(let u=0;u<l;u++){let d=a[u],_=u===l-1,p=[];for(let m=0,g=o.length;m<g;m++){let v=o[m],S=v.#t[d];S&&(S.#r=v.#r,_?(S.#t["*"]&&this.#i(i,S.#t["*"],t,v.#r),this.#i(i,S,t,v.#r)):p.push(S));for(let b of v.#n){let y=b.#o,k=v.#r===Sh?{}:{...v.#r};if(typeof y=="string"){(y==="*"||d.startsWith(y.slice(0,-1)))&&(this.#i(i,b,t,v.#r),y==="*"&&(b.#r=k,p.push(b)));continue}let[,M,j]=y;if(!(!d&&j===!0)){if(j!==!0){if(!c){c=[];let N=n[0]==="/"?1:0;for(let O=0;O<l;O++)c[O]=N,N+=a[O].length+1}let $=n.slice(c[u]),B=j.exec($);if(B){k[M]=B[0],this.#i(i,b,t,v.#r,k),B[0].length===$.length&&b.#t["*"]&&this.#i(i,b.#t["*"],t,v.#r,k);for(let N in b.#t){b.#r=k;let O=B[0].match(/\//g)?.length??0;(s[O]||=[]).push(b);break}continue}}(j===!0||j.test(d))&&(k[M]=d,_?(this.#i(i,b,t,k,v.#r),b.#t["*"]&&this.#i(i,b.#t["*"],t,k,v.#r)):(b.#r=k,p.push(b)))}}}let f=s.shift();o=f?p.concat(f):p}return i[1]&&i.sort((u,d)=>u.score-d.score),[i.map(({handler:u,params:d})=>[u,d])]}};var kh=class{name="TrieRouter";#e=new IO;add(e,t,n){for(let i of Yd(t)||[t])this.#e.insert(e,i,n)}match(e,t){return this.#e.search(e,t)}};var Eh=class extends AO{constructor(e={}){super(e),this.router=e.router??new bh({routers:[new i_,new kh]})}};var JG=/^[\w!#$%&'*.^`|~+-]+$/,GG=/^[!#-:<>-[\]-~]+$/,KG=/^[ !#-:<-[\]-~]*$/,$O=e=>{let t=0,n=e.length;for(;t<n;){let i=e.charCodeAt(t);if(i!==32&&i!==9)break;t++}for(;n>t;){let i=e.charCodeAt(n-1);if(i!==32&&i!==9)break;n--}return t===0&&n===e.length?e:e.slice(t,n)},wh=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.split(";"),i=Object.create(null);for(let r of n){let o=r.indexOf("=");if(o===-1)continue;let a=$O(r.substring(0,o));if(t&&t!==a||!GG.test(a)||a in i)continue;let s=$O(r.substring(o+1));if(s.startsWith('"')&&s.endsWith('"')&&(s=s.slice(1,-1)),KG.test(s)&&(i[a]=ya(s),t))break}return i};var XG=(e,t,n={})=>{if(!JG.test(e))throw new Error("Invalid cookie name");let i=`${e}=${t}`;if(e.startsWith("__Secure-")&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(e.startsWith("__Host-")){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}for(let r of["domain","path","sameSite","priority"])if(n[r]&&/[;\r\n]/.test(n[r]))throw new Error(`${r} must not contain ";", "\\r", or "\\n"`);if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");i+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!=="host"&&(i+=`; Domain=${n.domain}`),n.path&&(i+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");i+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(i+="; HttpOnly"),n.secure&&(i+="; Secure"),n.sameSite&&(i+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(i+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");i+="; Partitioned"}return i},o_=(e,t,n)=>(t=encodeURIComponent(t),XG(e,t,n));var PO=(e,t,n)=>{let i=e.req.raw.headers.get("Cookie");if(typeof t=="string"){if(!i)return;let o=t;return n==="secure"?o="__Secure-"+t:n==="host"&&(o="__Host-"+t),wh(i,o)[o]}return i?wh(i):{}};var YG=(e,t,n)=>{let i;return n?.prefix==="secure"?i=o_("__Secure-"+e,t,{path:"/",...n,secure:!0}):n?.prefix==="host"?i=o_("__Host-"+e,t,{...n,path:"/",secure:!0,domain:void 0}):i=o_(e,t,{path:"/",...n}),i},LO=(e,t,n,i)=>{let r=YG(t,n,i);e.header("Set-Cookie",r,{append:!0})};var DO=require("node:child_process"),jO=require("node:path"),UO=require("node:util");We();var pi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),MO=e=>typeof e=="string"&&Number.isFinite(Date.parse(e));async function Ys(e){let t=".agents/records/lifecycle",[n,i]=await Promise.all([e.exists(`${t}/manifest.json`),e.exists(`${t}/summary.json`)]);if(!n&&!i)return"missing";if(!n||!i)return"invalid";try{let[r,o]=await Promise.all([e.readText(`${t}/manifest.json`).then(a=>JSON.parse(a)),e.readText(`${t}/summary.json`).then(a=>JSON.parse(a))]);return!pi(r)||r.schema_version!==1||!MO(r.updated_at)||!pi(r.offsets)||!Object.values(r.offsets).every(a=>Number.isSafeInteger(a)&&Number(a)>=0)||!pi(o)||o.schema_version!==1||!MO(o.updated_at)||!pi(o.counts)||!Number.isSafeInteger(o.counts.total)||Number(o.counts.total)<0||!pi(o.counts.by_kind)||!pi(o.counts.by_status)||!pi(o.freshness)||!pi(o.usage)||!pi(o.periods)?"invalid":"initialized"}catch{return"invalid"}}var QG=(0,UO.promisify)(DO.execFile);async function FO(e){let t=await Ys(new Vr(e));if(t!=="initialized")return{captured_runs:0,captured_segments:0,manifest_state:t,skipped_reason:t==="missing"?"manifest_uninitialized":"manifest_invalid",last_capture_at:new Date().toISOString()};let n=(0,jO.resolve)(e,".agents","runtime","bin","zaip.mjs");try{let i=await QG(process.execPath,[n,"run","usage","--active","--limit","1","--disable-codex-raw","--json"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:55e3,maxBuffer:1048576}),r=eK(i.stdout),o=tK(r),a=o.filter(s=>s.captured).length;return{captured_runs:a,captured_segments:a===0?0:null,manifest_state:"initialized",skipped_reason:o.length===0?"no_active_runs":a===0?"no_new_segments":null,last_capture_at:new Date().toISOString()}}catch(i){if(nK(i))return{captured_runs:0,captured_segments:0,manifest_state:"missing",skipped_reason:"manifest_uninitialized",last_capture_at:new Date().toISOString()};throw i}}function eK(e){if(!e.trim())throw new Error("Active telemetry capture returned no JSON result");try{return JSON.parse(e.trim())}catch{throw new Error("Active telemetry capture returned invalid JSON")}}function tK(e){if(typeof e!="object"||e===null)throw new Error("Invalid capture payload");let t=e.telemetry;if(typeof t!="object"||t===null)throw new Error("Invalid capture telemetry");let n=t.captured;if(!Array.isArray(n))throw new Error("Invalid capture entries");return n.map(i=>{if(typeof i!="object"||i===null||typeof i.captured!="boolean")throw new Error("Invalid capture entry");return{captured:i.captured}})}function nK(e){return(e instanceof Error?`${e.message}
|
|
344
344
|
${"stdout"in e?String(e.stdout??""):""}
|
|
345
|
-
${"stderr"in e?String(e.stderr??""):""}`:String(e)).includes("Lifecycle manifest is not initialized")}var qO=require("node:child_process"),VO=require("node:path"),WO=require("node:util"),zO=(0,WO.promisify)(qO.execFile);async function ZO(e){let t=(0,VO.resolve)(e,".agents","runtime","bin","zaip.mjs"),n={cwd:e,encoding:"utf8",windowsHide:!0,timeout:12e4,maxBuffer:10*1024*1024};await zO(process.execPath,[t,"adapters","build","--json"],n);let{stdout:i}=await zO(process.execPath,[t,"adapters","check","--json"],n),r=JSON.parse(i);return{valid:r.valid===!0,drifted:Array.isArray(r.drifted)?r.drifted.filter(o=>typeof o=="string"):[]}}var Th=require("node:util");We();var a_=".agents/config/agents/catalog.yaml",xh=["agent-orchestrator","agent-builder","agent-task-executor","agent-analyst","agent-finalizer","agent-reviewer","agent-integrator","agent-auditor","agent-text-summarizer","agent-data-analyst","agent-refactoring-specialist","agent-frontend","agent-backend","agent-website-developer","agent-designer","agent-cloud-engineer","agent-security-auditor","agent-marketing-analyst","agent-brand-strategist","agent-growth-strategist","agent-sales-specialist","agent-general-operations","agent-governance-compliance"],rK=new Set(xh),Jt=class extends Error{constructor(n,i){super(n);this.status=i}status;name="AgentCatalogUpdateError"};async function JO(e){let t=await KO(e);return{catalog:await sK(e),framework_agent_ids:xh,...t,sync:{required:!0,valid:null,drifted:[]}}}async function GO(e,t,n){let i=await e.readText(a_),r=Ai(Ct(i)),o=await KO(e),a=iK(r,t,o);await e.writeTextAtomic(a_,li(a));try{let s=await n();if(!s.valid||s.drifted.length>0)throw new Error(`Adapter parity failed; drifted: ${s.drifted.join(", ")||"unknown"}`);return{catalog:a,framework_agent_ids:xh,...o,sync:{required:!0,valid:!0,drifted:[]}}}catch(s){await e.writeTextAtomic(a_,i);try{await n()}catch{}throw new Jt(`Agent catalog was not saved because adapter synchronization failed: ${s instanceof Error?s.message:String(s)}`,500)}}function iK(e,t,n){if(!Ah(t)||!Array.isArray(t.agents))throw new Jt("Request body must contain an agents array",400);if(Object.keys(t).some(o=>o!=="agents"))throw new Jt("Only the agents collection may be updated",400);let i;try{let o=t.agents.map(a=>oK(a));i=Ai({schema_version:e.schema_version,agents:o,squads:e.squads})}catch(o){throw new Jt(o instanceof Error?o.message:String(o),400)}cK(e,i),uK(e,i),lK(e,i),n!==void 0&&aK(i,n);let r=Vm(i);if(r.length>0)throw new Jt(r.map(o=>`${o.rule}: ${o.message}`).join("; "),409);return i}function oK(e){if(!Ah(e)||!Ah(e.persona))return e;let t=e.persona.nome,n=e.persona.cargo;if(typeof t!="string"||typeof n!="string")return e;let i=`${t}_${n}_zaip_agent`;return{...e,codex_task_name:i,nickname_candidates:[i]}}async function KO(e){let n=ui(Ct(await e.readText(".agents/config/project.yaml"))).model_orchestration;return n?.mode==="auto"?{default_model:n.default_model,default_reasoning_effort:n.default_effort,allowed_models:n.allowed_models,allowed_reasoning_efforts:n.allowed_efforts}:{default_model:n?.default_model??null,default_reasoning_effort:n?.default_effort??null,allowed_models:[],allowed_reasoning_efforts:[]}}function aK(e,t){for(let n of e.agents){let i=n.model.preferred.find(r=>r!=="policy-selected"&&!t.allowed_models.includes(r));if(t.allowed_models.length>0&&i!==void 0)throw new Jt(`Agent ${n.id} uses a model outside project.allowed_models: ${i}`,400);if(n.model.reasoning_effort!==void 0&&t.allowed_reasoning_efforts.length>0&&!t.allowed_reasoning_efforts.includes(n.model.reasoning_effort))throw new Jt(`Agent ${n.id} uses reasoning effort outside project.allowed_efforts: ${n.model.reasoning_effort}`,400)}}async function sK(e){return Ai(Ct(await e.readText(a_)))}function cK(e,t){for(let n of rK){let i=e.agents.find(o=>o.id===n),r=t.agents.find(o=>o.id===n);if(i===void 0||r===void 0)throw new Jt(`Framework agent cannot be removed: ${n}`,409);if(!(0,Th.isDeepStrictEqual)(BO(i),BO(r)))throw new Jt(`Framework agent ${n} only allows persona name and role changes`,409)}}function BO(e){let{persona:t,codex_task_name:n,nickname_candidates:i,...r}=e;return{...r,persona:{nome:"protected",cargo:"protected"},codex_task_name:"protected_protected_zaip_agent",nickname_candidates:["protected_protected_zaip_agent"],model:{...e.model,preferred:[],reasoning_effort:void 0}}}function lK(e,t){for(let n of e.agents){let i=t.agents.find(r=>r.id===n.id);if(i!==void 0&&!(0,Th.isDeepStrictEqual)(HO(n),HO(i)))throw new Jt(`Existing agent ${n.id} only allows persona name and role changes`,409)}}function HO(e){let{persona:t,codex_task_name:n,nickname_candidates:i,...r}=e;return{...r,persona:{...t,nome:"protected",cargo:"protected"}}}function uK(e,t){for(let n of e.agents){let i=t.agents.find(r=>r.id===n.id);if(i!==void 0&&n.codex_name!==i.codex_name)throw new Jt(`Technical identity is stable and cannot be changed: ${n.id}`,409)}}function Ah(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var nR=require("node:child_process"),rR=require("node:path"),iR=require("node:util");We();var ba=["Node.js","TypeScript","Vite","Astro","Redis","BullMQ","Hono","React","Git","Terraform"],Qs=["software_architecture","design_system","brandbook","marketing_strategy","sales_playbook","growth_strategy"],s_=ba.length+Qs.length;function YO(e){let t=e.stack.overrides.installation_profile;return t==="full"||t==="dev-lite"||t==="lite"?t:"custom"}async function QO(e,t){try{return(await e.readText(t)).trim().length>0}catch(n){return n.code==="ENOENT"?!1:null}}function Oh(e,t,n,i="unknown"){let r={state:i,scope:"settings_runtime"};if(e==="custom"){let _={applicable:null,missing:null,unknown:null,not_applicable:null,percent:null,state:"unknown"};return{installation_profile:e,health:r,dependencies:{..._,installed:null},documentation:{..._,available:null}}}let o=e==="full"?ba:e==="dev-lite"?ba.filter(_=>_!=="Terraform"):["Node.js","Git"],a=0,s=0,l=0;for(let _ of o){let p=t.filter(m=>m.name===_),f=p.length===1?p[0]:void 0;f&&eR(f)&&f.probe!=="unknown"?a++:f?.probe==="missing"?s++:l++}let c=0,u=0,d=0;for(let _ of Qs){let p=n.filter(m=>m.id===_),f=p.length===1?p[0]?.available:null;f===!0?c++:f===!1?u++:d++}return{installation_profile:e,health:r,dependencies:{...XO(o.length,a,s,l,ba.length-o.length),installed:a},documentation:{...XO(Qs.length,c,u,d,0),available:c}}}function XO(e,t,n,i,r){return{applicable:e,missing:n,unknown:i,not_applicable:r,percent:e>0&&i===0?t/e*100:null,state:e===0?"not_applicable":i>0?"unknown":n>0?"incomplete":"complete"}}function Rh(e,t){let n=ba.filter(i=>e.some(r=>r.name===i&&eR(r))).length+Qs.filter(i=>t.some(r=>r.id===i&&r.available===!0)).length;return{completed:n,total:s_,percent:n/s_*100,state:n===s_?"complete":"incomplete"}}function eR(e){return e.verification==="exact"&&e.version!==null&&(e.installation==="runtime"||e.installation==="installed")}var dK=".agents/config/agents/catalog.yaml",_K=".codex/config.toml",pK=".agents/config/framework.lock.yaml",mK=".agents/dashboard/stack-dependencies.json",fK=(0,iR.promisify)(nR.execFile),oR=".agents/architecture/software-architecture.md",gK=[{id:"software_architecture",label:"Arquitetura de Software",artifact:oR},{id:"design_system",label:"Design system",artifact:".agents/design/DESIGN.md"},{id:"brandbook",label:"Brandbook",artifact:".agents/branding/brandbook.md"},{id:"marketing_strategy",label:"Estrat\xE9gia de Marketing",artifact:".agents/marketing/strategy.md"},{id:"sales_playbook",label:"Playbook de Sales",artifact:".agents/sales/playbook.md"},{id:"growth_strategy",label:"Estrat\xE9gia de Growth",artifact:".agents/growth/strategy.md"}];async function tc(e){return ui(Ct(await e.readText($n)))}async function aR(e){let[t,n,i,r,o]=await Promise.all([e.readText(dK).then(Ct).then(Ai),hK(e),yK(e),vK(e,".agents/rules"),bK(e)]),[a,s,l]=await Promise.all([tc(e),SK(e),Promise.all(gK.map(async d=>({...d,available:await QO(e,d.artifact)})))]),c=Rh(s,l),u=Oh(YO(a),s,l,"healthy");return{framework_version:n,installation:c,...u,metrics:[{id:"agents",label:"Agentes",value:t.agents.length},{id:"squads",label:"Squads",value:t.squads.length},{id:"skills",label:"Skills",value:i},{id:"rules",label:"Rules",value:r},{id:"hooks",label:"Hooks",value:o}],stack_components:s,areas:l}}async function hK(e){try{let t=Tt(Ct(await e.readText(pK))),n=Tt(t.framework).version;return typeof n=="string"&&n.trim()?n.trim():null}catch{return null}}async function yK(e){let t=await e.listDirectories(".agents/skills");return(await Promise.all(t.map(i=>e.exists(`${i}/SKILL.md`)))).filter(Boolean).length}async function vK(e,t){let n=`${t}/`;return(await e.listFiles(t,".md")).filter(r=>!r.slice(n.length).includes("/")).length}async function bK(e){try{let t=await e.readText(_K);return new Set([...t.matchAll(/^\s*\[\[hooks\.([A-Za-z0-9_-]+)\]\]\s*$/gm)].map(i=>i[1])).size}catch{return 0}}async function SK(e){let[t,n,i,r,o,a]=await Promise.all([tc(e),EK(e),TK(e,".agents/dashboard/packages/local-runtime/server.mjs"),AK(e),tR(e,"Git",["--version"],"git",u=>/^git version (.+)$/m.exec(u.trim())?.[1]??null),tR(e,"Terraform",["version","-json"],"terraform",u=>{try{let d=JSON.parse(u).terraform_version;return typeof d=="string"?d:null}catch{return null}})]),s=wK(t,n),l=await Promise.all(["typescript","vite","astro","redis","bullmq","hono","react"].map(u=>kK(e,u))),c=new Map(l.map(u=>[u.name,u]));return[xK("Node.js",process.versions.node,s.get("node")),vo("TypeScript","typescript",s.get("typescript"),c),vo("Vite","vite",s.get("vite"),c),vo("Astro","astro",s.get("astro"),c),vo("Redis","redis",s.get("redis"),c),vo("BullMQ","bullmq",s.get("bullmq"),c),vo("Hono","hono",s.get("hono"),c,i),vo("React","react",s.get("react"),c,r),o,a]}async function kK(e,t){let n=!1,i=["node_modules"];t==="hono"&&i.push(".agents/dashboard/packages/local-runtime/node_modules"),t==="react"&&i.push(".agents/dashboard/apps/frontend/node_modules");for(let r of i)try{let o=`${r}/${t}/package.json`,a=Tt(JSON.parse(await e.readText(o))),s=bo(a.version),l=OK(a);if(a.name!==t||s===null||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(s)||l===null){n=!0;continue}return await e.readText(`${r}/${t}/${l}`),{name:t,version:s,source:o,probe:"verified"}}catch(o){o.code!=="ENOENT"&&(n=!0)}return{name:t,version:null,source:null,probe:n?"unknown":"missing"}}async function EK(e){try{let t=Tt(JSON.parse(await e.readText(mK))),n=new Map;for(let i of Array.isArray(t.packages)?t.packages:[]){let r=Tt(i),o=bo(r.name),a=bo(r.version);o!==null&&a!==null&&n.set(o,a)}return{node:bo(t.node),packages:n}}catch{return{node:null,packages:new Map}}}function wK(e,t){let n=Tt(Tt(e.stack.overrides).components),i=new Map(t.packages);t.node!==null&&i.set("node",t.node);for(let[r,o]of Object.entries({backend_runtime:"node",primary_language:"typescript",web_language:"typescript",web_build:"vite",site_framework:"astro",cache_messaging:"redis",async_queue:"bullmq",backend_api:"hono",web_framework:"react"})){let a=bo(Tt(n[r]).version);a!==null&&i.set(o,a)}return i}async function AK(e){try{return(await e.listFiles(".agents/dashboard/apps/frontend/dist",".js")).length>0}catch{return!1}}async function TK(e,t){try{return(await e.readText(t)).trim().length>0}catch{return!1}}async function tR(e,t,n,i,r){let o=await tc(e),a=Tt(Tt(o.stack.overrides).components),s=i==="git"?"latest":bo(Tt(a.backend_infrastructure).version)??"1.16.1",l=/^\d+\.\d+\.\d+$/.test(s)?s:"1.16.1",c=i==="git"?".local/git/cmd/git.exe":`.local/terraform/v${l}-${process.platform}-${process.arch}/${process.platform==="win32"?"terraform.exe":"terraform"}`,u=(0,rR.join)(e.root,c),d=await e.exists(c)?u:i;try{let _=r((await fK(d,n,{timeout:1e4,windowsHide:!0})).stdout);if(_===null)throw new Error("unsupported version output");return{name:t,version:_,configured_version:s,source:d===i?`Comando do workspace: ${i}`:c,verification:"exact",installation:d===i?"runtime":"installed",probe:"verified"}}catch{return{name:t,version:null,configured_version:s,source:null,verification:"unavailable",installation:"missing",probe:"unknown"}}}function xK(e,t,n){return{name:e,version:t,configured_version:n??null,source:`Runtime do Dashboard: ${process.execPath}`,verification:"exact",installation:"runtime",probe:"verified"}}function vo(e,t,n,i,r=!1){let o=i.get(t)?.version??null;return o!==null?{name:e,version:o,configured_version:n??null,source:i.get(t)?.source??null,verification:"exact",installation:"installed",probe:"verified"}:r?{name:e,version:null,configured_version:n??null,source:t==="hono"?".agents/dashboard/packages/local-runtime/server.mjs":".agents/dashboard/apps/frontend/dist",verification:"unavailable",installation:"bundled",probe:"unknown"}:{name:e,version:null,configured_version:n??null,source:null,verification:"unavailable",installation:"missing",probe:i.get(t)?.probe??"missing"}}function bo(e){return typeof e=="string"&&e.trim()?e.trim():null}function OK(e){if(typeof e.bin=="string")return e.bin;let t=Object.values(Tt(e.bin)).find(n=>typeof n=="string");return typeof t=="string"?t:bo(e.main)}async function sR(e,t){let n=await e.readText($n),i=ui(Ct(n)),r=ui(t);if(r.tracking.storage_mode!=="tracked_sanitized")throw new TypeError("This project requires Git-native tracked_sanitized storage.");let o=Tt(i.stack.overrides.components),a=Tt(r.stack.overrides.components),s=ui({...r,clients:i.clients,tracking:i.tracking,model_orchestration:i.model_orchestration,stack:{...r.stack,overrides:{...i.stack.overrides,...r.stack.overrides,...Object.keys(o).length>0||Object.keys(a).length>0?{components:{...o,...a}}:{}}}});await e.writeTextAtomic($n,li(s));try{await e.writeTextAtomic(oR,IK(s))}catch(l){throw await e.writeTextAtomic($n,n),new Error("Project settings were rolled back because the software architecture summary could not be updated.",{cause:l})}return s}var RK={primary_language:"Linguagem principal",backend_runtime:"Runtime backend",backend_api:"Framework backend / API",query_builder:"Query builder",database:"Banco de dados",auth_storage:"Autentica\xE7\xE3o e Storage",cache_messaging:"Cache e mensageria",async_queue:"Filas e processamento ass\xEDncrono",backend_infrastructure:"Infraestrutura backend",backend_hosting:"Hospedagem do backend",web_framework:"Framework do Web App",web_language:"Linguagem do Web App",web_build:"Build do Web App",frontend_hosting:"Hospedagem do frontend",site_framework:"Framework do site",site_language:"Linguagem do site",site_islands:"Componentes interativos",site_build:"Build do site",site_hosting:"Hospedagem do site",prometheus:"Coleta de m\xE9tricas",grafana:"Dashboards",uptime_kuma:"Monitoramento de disponibilidade",cadvisor:"M\xE9tricas de containers",node_exporter:"M\xE9tricas de host",redis_exporter:"M\xE9tricas do Redis",k6:"Teste de carga",autocannon:"Teste HTTP de carga"},CK={backend_data_and_managed_services:"Dados e servi\xE7os gerenciados",backend_api_and_business_rules:"APIs e regras de neg\xF3cio",backend_async_processing:"Filas e processamento ass\xEDncrono",backend_infrastructure:"Infraestrutura backend",backend_hosting:"Hospedagem do backend"};function IK(e){let t=na(e.autonomy),n=Tt(e.stack.overrides),i=Tt(n.components),r=Tt(n.languages),o=Tt(n.architecture),a=Object.entries(RK).map(([_,p])=>{let f=Tt(i[_]);return`| ${p} | ${$t(f.name,"N\xE3o definido")} | ${$t(f.version,"N\xE3o fixada")} | ${$t(f.reference,"\u2014")} |`}),s=Object.entries(e.stack.layout??{}).map(([_,p])=>`| ${$t(_)} | ${$t(p)} |`),l=Object.entries(e.stack.commands??{}).map(([_,p])=>`| ${$t(_)} | \`${NK(p)}\` |`),c=Object.entries(o).flatMap(([_,p])=>[`### ${CK[_]??$K(_)}`,"",...ec(c_(p)),""]),u=e.execution&&e.execution.runtime!=="manual"?[`- **Runtime:** ${e.execution.runtime}`,`- **Provider:** ${$t(e.execution.autonomous.provider)}`,`- **Modelo-base:** ${$t(e.execution.autonomous.model)}`,`- **Paralelismo m\xE1ximo:** ${e.execution.autonomous.max_parallelism}`,`- **Lease configurado:** ${e.execution.autonomous.lease_ms} ms`,`- **Limite total de invoca\xE7\xF5es:** ${e.autonomy?"Por Task; sem teto agregado de SPEC/PRD":e.execution.autonomous.max_total_invocations??"N\xE3o definido"}`]:[`- **Runtime:** ${e.execution?.runtime??"manual (padr\xE3o impl\xEDcito)"}`],d=e.assurance===void 0?["- N\xE3o configurada."]:[`- **Vers\xE3o:** ${e.assurance.version}`,`- **Profundidade padr\xE3o:** ${$t(e.assurance.standard_depth)}`,`- **Exigir commit final:** ${e.assurance.require_final_commit?"Sim":"N\xE3o"}`];return["---","schema_version: 1","kind: software-architecture",`generated_from: ${$n}`,"---","","# Arquitetura de Software","",`> Proje\xE7\xE3o gerada automaticamente pela p\xE1gina de configura\xE7\xF5es a partir de \`${$n}\`. N\xE3o edite este arquivo manualmente.`,"","## Projeto","",`- **Nome:** ${$t(e.project.name)}`,`- **ID:** ${$t(e.project.id)}`,`- **Timezone:** ${$t(e.project.timezone)}`,"","## Perfil t\xE9cnico","",`- **Stack profile:** ${$t(e.stack.id)}`,`- **Linguagem:** ${$t(e.stack.language,"N\xE3o definida")}`,`- **API:** ${$t(e.stack.api,"N\xE3o definida")}`,`- **Query builder:** ${$t(e.stack.query_builder,"N\xE3o definido")}`,"","## Execu\xE7\xE3o","",...u,...e.autonomy?["","### Autonomia","",`- **Perfil:** ${t.label}`,`- **Execu\xE7\xF5es por Task:** ${t.attempts??"Ilimitadas"}`,`- **Replanejamentos por Task:** ${t.replans??"Ilimitados"}`,"- Sem abandono por tempo. Tasks iniciadas preservam o perfil e os contadores.","- Subagentes podem ter modelo/esfor\xE7o diferentes do principal, com aviso expl\xEDcito."]:[],"","## Assurance","",...d,"","## Componentes e vers\xF5es","","| Responsabilidade | Tecnologia | Vers\xE3o exata | Pacote / imagem / servi\xE7o |","| --- | --- | --- | --- |",...a,"","## Superf\xEDcies","","### Web App \u2014 Frontend","",...ec(c_(r.frontend)),"","### Backend","",...ec(c_(r.backend)),"","### Site e Landing Pages","",...ec(c_(r.site)),"","## Decis\xF5es de arquitetura","",...c.length>0?c:["- Nenhuma decis\xE3o adicional registrada.",""],"## Layout do c\xF3digo","","| Papel | Caminho |","| --- | --- |",...s.length>0?s:["| N\xE3o definido | \u2014 |"],"","## Invariantes","",...ec(e.stack.invariants??[]),"","## Comandos de valida\xE7\xE3o","","| Comando | Execu\xE7\xE3o |","| --- | --- |",...l.length>0?l:["| N\xE3o definido | \u2014 |"],""].join(`
|
|
345
|
+
${"stderr"in e?String(e.stderr??""):""}`:String(e)).includes("Lifecycle manifest is not initialized")}var qO=require("node:child_process"),VO=require("node:path"),WO=require("node:util"),zO=(0,WO.promisify)(qO.execFile);async function ZO(e){let t=(0,VO.resolve)(e,".agents","runtime","bin","zaip.mjs"),n={cwd:e,encoding:"utf8",windowsHide:!0,timeout:12e4,maxBuffer:10*1024*1024};await zO(process.execPath,[t,"adapters","build","--json"],n);let{stdout:i}=await zO(process.execPath,[t,"adapters","check","--json"],n),r=JSON.parse(i);return{valid:r.valid===!0,drifted:Array.isArray(r.drifted)?r.drifted.filter(o=>typeof o=="string"):[]}}var Th=require("node:util");We();var a_=".agents/config/agents/catalog.yaml",xh=["agent-orchestrator","agent-builder","agent-task-executor","agent-analyst","agent-finalizer","agent-reviewer","agent-integrator","agent-auditor","agent-text-summarizer","agent-data-analyst","agent-refactoring-specialist","agent-frontend","agent-backend","agent-website-developer","agent-designer","agent-cloud-engineer","agent-security-auditor","agent-marketing-analyst","agent-brand-strategist","agent-growth-strategist","agent-sales-specialist","agent-general-operations","agent-governance-compliance"],rK=new Set(xh),Jt=class extends Error{constructor(n,i){super(n);this.status=i}status;name="AgentCatalogUpdateError"};async function JO(e){let t=await KO(e);return{catalog:await sK(e),framework_agent_ids:xh,...t,sync:{required:!0,valid:null,drifted:[]}}}async function GO(e,t,n){let i=await e.readText(a_),r=Ai(Ct(i)),o=await KO(e),a=iK(r,t,o);await e.writeTextAtomic(a_,li(a));try{let s=await n();if(!s.valid||s.drifted.length>0)throw new Error(`Adapter parity failed; drifted: ${s.drifted.join(", ")||"unknown"}`);return{catalog:a,framework_agent_ids:xh,...o,sync:{required:!0,valid:!0,drifted:[]}}}catch(s){await e.writeTextAtomic(a_,i);try{await n()}catch{}throw new Jt(`Agent catalog was not saved because adapter synchronization failed: ${s instanceof Error?s.message:String(s)}`,500)}}function iK(e,t,n){if(!Ah(t)||!Array.isArray(t.agents))throw new Jt("Request body must contain an agents array",400);if(Object.keys(t).some(o=>o!=="agents"))throw new Jt("Only the agents collection may be updated",400);let i;try{let o=t.agents.map(a=>oK(a));i=Ai({schema_version:e.schema_version,agents:o,squads:e.squads})}catch(o){throw new Jt(o instanceof Error?o.message:String(o),400)}cK(e,i),uK(e,i),lK(e,i),n!==void 0&&aK(i,n);let r=Vm(i);if(r.length>0)throw new Jt(r.map(o=>`${o.rule}: ${o.message}`).join("; "),409);return i}function oK(e){if(!Ah(e)||!Ah(e.persona))return e;let t=e.persona.nome,n=e.persona.cargo;if(typeof t!="string"||typeof n!="string")return e;let i=`${t}_${n}_zaip_agent`;return{...e,codex_task_name:i,nickname_candidates:[i]}}async function KO(e){let n=ui(Ct(await e.readText(".agents/config/project.yaml"))).model_orchestration;return n?.mode==="auto"?{default_model:n.default_model,default_reasoning_effort:n.default_effort,allowed_models:n.allowed_models,allowed_reasoning_efforts:n.allowed_efforts}:{default_model:n?.default_model??null,default_reasoning_effort:n?.default_effort??null,allowed_models:[],allowed_reasoning_efforts:[]}}function aK(e,t){for(let n of e.agents){let i=n.model.preferred.find(r=>r!=="policy-selected"&&!t.allowed_models.includes(r));if(t.allowed_models.length>0&&i!==void 0)throw new Jt(`Agent ${n.id} uses a model outside project.allowed_models: ${i}`,400);if(n.model.reasoning_effort!==void 0&&t.allowed_reasoning_efforts.length>0&&!t.allowed_reasoning_efforts.includes(n.model.reasoning_effort))throw new Jt(`Agent ${n.id} uses reasoning effort outside project.allowed_efforts: ${n.model.reasoning_effort}`,400)}}async function sK(e){return Ai(Ct(await e.readText(a_)))}function cK(e,t){for(let n of rK){let i=e.agents.find(o=>o.id===n),r=t.agents.find(o=>o.id===n);if(i===void 0||r===void 0)throw new Jt(`Framework agent cannot be removed: ${n}`,409);if(!(0,Th.isDeepStrictEqual)(BO(i),BO(r)))throw new Jt(`Framework agent ${n} only allows persona name and role changes`,409)}}function BO(e){let{persona:t,codex_task_name:n,nickname_candidates:i,...r}=e;return{...r,persona:{nome:"protected",cargo:"protected"},codex_task_name:"protected_protected_zaip_agent",nickname_candidates:["protected_protected_zaip_agent"],model:{...e.model,preferred:[],reasoning_effort:void 0}}}function lK(e,t){for(let n of e.agents){let i=t.agents.find(r=>r.id===n.id);if(i!==void 0&&!(0,Th.isDeepStrictEqual)(HO(n),HO(i)))throw new Jt(`Existing agent ${n.id} only allows persona name and role changes`,409)}}function HO(e){let{persona:t,codex_task_name:n,nickname_candidates:i,...r}=e;return{...r,persona:{...t,nome:"protected",cargo:"protected"}}}function uK(e,t){for(let n of e.agents){let i=t.agents.find(r=>r.id===n.id);if(i!==void 0&&n.codex_name!==i.codex_name)throw new Jt(`Technical identity is stable and cannot be changed: ${n.id}`,409)}}function Ah(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var nR=require("node:child_process"),rR=require("node:path"),iR=require("node:util");We();var ba=["Node.js","TypeScript","Vite","Astro","Redis","BullMQ","Hono","React","Git","Terraform"],Qs=["software_architecture","design_system","brandbook","marketing_strategy","sales_playbook","growth_strategy"],s_=ba.length+Qs.length;function YO(e){let t=e.stack.overrides.installation_profile;return t==="full"||t==="dev-lite"||t==="lite"?t:"custom"}async function QO(e,t){try{return(await e.readText(t)).trim().length>0}catch(n){return n.code==="ENOENT"?!1:null}}function Oh(e,t,n,i="unknown"){let r={state:i,scope:"settings_runtime"};if(e==="custom"){let _={applicable:null,missing:null,unknown:null,not_applicable:null,percent:null,state:"unknown"};return{installation_profile:e,health:r,dependencies:{..._,installed:null},documentation:{..._,available:null}}}let o=e==="full"?ba:e==="dev-lite"?ba.filter(_=>_!=="Terraform"):["Node.js","Git"],a=0,s=0,l=0;for(let _ of o){let p=t.filter(m=>m.name===_),f=p.length===1?p[0]:void 0;f&&eR(f)&&f.probe!=="unknown"?a++:f?.probe==="missing"?s++:l++}let c=0,u=0,d=0;for(let _ of Qs){let p=n.filter(m=>m.id===_),f=p.length===1?p[0]?.available:null;f===!0?c++:f===!1?u++:d++}return{installation_profile:e,health:r,dependencies:{...XO(o.length,a,s,l,ba.length-o.length),installed:a},documentation:{...XO(Qs.length,c,u,d,0),available:c}}}function XO(e,t,n,i,r){return{applicable:e,missing:n,unknown:i,not_applicable:r,percent:e>0&&i===0?t/e*100:null,state:e===0?"not_applicable":i>0?"unknown":n>0?"incomplete":"complete"}}function Rh(e,t){let n=ba.filter(i=>e.some(r=>r.name===i&&eR(r))).length+Qs.filter(i=>t.some(r=>r.id===i&&r.available===!0)).length;return{completed:n,total:s_,percent:n/s_*100,state:n===s_?"complete":"incomplete"}}function eR(e){return e.verification==="exact"&&e.version!==null&&(e.installation==="runtime"||e.installation==="installed")}var dK=".agents/config/agents/catalog.yaml",_K=".codex/config.toml",pK=".agents/config/framework.lock.yaml",mK=".agents/dashboard/stack-dependencies.json",fK=(0,iR.promisify)(nR.execFile),oR=".agents/architecture/software-architecture.md",gK=[{id:"software_architecture",label:"Arquitetura de Software",artifact:oR},{id:"design_system",label:"Design system",artifact:".agents/design/DESIGN.md"},{id:"brandbook",label:"Brandbook",artifact:".agents/branding/brandbook.md"},{id:"marketing_strategy",label:"Estrat\xE9gia de Marketing",artifact:".agents/marketing/strategy.md"},{id:"sales_playbook",label:"Playbook de Sales",artifact:".agents/sales/playbook.md"},{id:"growth_strategy",label:"Estrat\xE9gia de Growth",artifact:".agents/growth/strategy.md"}];async function tc(e){return ui(Ct(await e.readText($n)))}async function aR(e){let[t,n,i,r,o]=await Promise.all([e.readText(dK).then(Ct).then(Ai),hK(e),yK(e),vK(e,".agents/rules"),bK(e)]),[a,s,l]=await Promise.all([tc(e),SK(e),Promise.all(gK.map(async d=>({...d,available:await QO(e,d.artifact)})))]),c=Rh(s,l),u=Oh(YO(a),s,l,"healthy");return{framework_version:n,installation:c,...u,metrics:[{id:"agents",label:"Agentes",value:t.agents.length},{id:"squads",label:"Squads",value:t.squads.length},{id:"skills",label:"Skills",value:i},{id:"rules",label:"Rules",value:r},{id:"hooks",label:"Hooks",value:o}],stack_components:s,areas:l}}async function hK(e){try{let t=Tt(Ct(await e.readText(pK))),n=Tt(t.framework).version;return typeof n=="string"&&n.trim()?n.trim():null}catch{return null}}async function yK(e){let t=await e.listDirectories(".agents/skills");return(await Promise.all(t.map(i=>e.exists(`${i}/SKILL.md`)))).filter(Boolean).length}async function vK(e,t){let n=`${t}/`;return(await e.listFiles(t,".md")).filter(r=>!r.slice(n.length).includes("/")).length}async function bK(e){try{let t=await e.readText(_K);return new Set([...t.matchAll(/^\s*\[\[hooks\.([A-Za-z0-9_-]+)\]\]\s*$/gm)].map(i=>i[1])).size}catch{return 0}}async function SK(e){let[t,n,i,r,o,a]=await Promise.all([tc(e),EK(e),TK(e,".agents/dashboard/packages/local-runtime/server.mjs"),AK(e),tR(e,"Git",["--version"],"git",u=>/^git version (.+)$/m.exec(u.trim())?.[1]??null),tR(e,"Terraform",["version","-json"],"terraform",u=>{try{let d=JSON.parse(u).terraform_version;return typeof d=="string"?d:null}catch{return null}})]),s=wK(t,n),l=await Promise.all(["typescript","vite","astro","redis","bullmq","hono","react"].map(u=>kK(e,u))),c=new Map(l.map(u=>[u.name,u]));return[xK("Node.js",process.versions.node,s.get("node")),vo("TypeScript","typescript",s.get("typescript"),c),vo("Vite","vite",s.get("vite"),c),vo("Astro","astro",s.get("astro"),c),vo("Redis","redis",s.get("redis"),c),vo("BullMQ","bullmq",s.get("bullmq"),c),vo("Hono","hono",s.get("hono"),c,i),vo("React","react",s.get("react"),c,r),o,a]}async function kK(e,t){let n=!1,i=["node_modules"];t==="hono"&&i.push(".agents/dashboard/packages/local-runtime/node_modules"),t==="react"&&i.push(".agents/dashboard/apps/frontend/node_modules");for(let r of i)try{let o=`${r}/${t}/package.json`,a=Tt(JSON.parse(await e.readText(o))),s=bo(a.version),l=OK(a);if(a.name!==t||s===null||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(s)||l===null){n=!0;continue}return await e.readText(`${r}/${t}/${l}`),{name:t,version:s,source:o,probe:"verified"}}catch(o){o.code!=="ENOENT"&&(n=!0)}return{name:t,version:null,source:null,probe:n?"unknown":"missing"}}async function EK(e){try{let t=Tt(JSON.parse(await e.readText(mK))),n=new Map;for(let i of Array.isArray(t.packages)?t.packages:[]){let r=Tt(i),o=bo(r.name),a=bo(r.version);o!==null&&a!==null&&n.set(o,a)}return{node:bo(t.node),packages:n}}catch{return{node:null,packages:new Map}}}function wK(e,t){let n=Tt(Tt(e.stack.overrides).components),i=new Map(t.packages);t.node!==null&&i.set("node",t.node);for(let[r,o]of Object.entries({backend_runtime:"node",primary_language:"typescript",web_language:"typescript",web_build:"vite",site_framework:"astro",cache_messaging:"redis",async_queue:"bullmq",backend_api:"hono",web_framework:"react"})){let a=bo(Tt(n[r]).version);a!==null&&i.set(o,a)}return i}async function AK(e){try{return(await e.listFiles(".agents/dashboard/apps/frontend/dist",".js")).length>0}catch{return!1}}async function TK(e,t){try{return(await e.readText(t)).trim().length>0}catch{return!1}}async function tR(e,t,n,i,r){let o=await tc(e),a=Tt(Tt(o.stack.overrides).components),s=i==="git"?"latest":bo(Tt(a.backend_infrastructure).version)??"1.16.1",l=/^\d+\.\d+\.\d+$/.test(s)?s:"1.16.1",c=i==="git"?".local/git/cmd/git.exe":`.local/terraform/v${l}-${process.platform}-${process.arch}/${process.platform==="win32"?"terraform.exe":"terraform"}`,u=(0,rR.join)(e.root,c),d=await e.exists(c)?u:i;try{let _=r((await fK(d,n,{timeout:1e4,windowsHide:!0})).stdout);if(_===null)throw new Error("unsupported version output");return{name:t,version:_,configured_version:s,source:d===i?`Comando do workspace: ${i}`:c,verification:"exact",installation:d===i?"runtime":"installed",probe:"verified"}}catch{return{name:t,version:null,configured_version:s,source:null,verification:"unavailable",installation:"missing",probe:"unknown"}}}function xK(e,t,n){return{name:e,version:t,configured_version:n??null,source:`Runtime do Dashboard: ${process.execPath}`,verification:"exact",installation:"runtime",probe:"verified"}}function vo(e,t,n,i,r=!1){let o=i.get(t)?.version??null;return o!==null?{name:e,version:o,configured_version:n??null,source:i.get(t)?.source??null,verification:"exact",installation:"installed",probe:"verified"}:r?{name:e,version:null,configured_version:n??null,source:t==="hono"?".agents/dashboard/packages/local-runtime/server.mjs":".agents/dashboard/apps/frontend/dist",verification:"unavailable",installation:"bundled",probe:"unknown"}:{name:e,version:null,configured_version:n??null,source:null,verification:"unavailable",installation:"missing",probe:i.get(t)?.probe??"missing"}}function bo(e){return typeof e=="string"&&e.trim()?e.trim():null}function OK(e){if(typeof e.bin=="string")return e.bin;let t=Object.values(Tt(e.bin)).find(n=>typeof n=="string");return typeof t=="string"?t:bo(e.main)}async function sR(e,t){let n=await e.readText($n),i=ui(Ct(n)),r=ui(t);if(r.tracking.storage_mode!=="tracked_sanitized")throw new TypeError("This project requires Git-native tracked_sanitized storage.");let o=Tt(i.stack.overrides.components),a=Tt(r.stack.overrides.components),s=ui({...r,clients:i.clients,tracking:i.tracking,model_orchestration:i.model_orchestration,stack:{...r.stack,overrides:{...i.stack.overrides,...r.stack.overrides,...Object.keys(o).length>0||Object.keys(a).length>0?{components:{...o,...a}}:{}}}});await e.writeTextAtomic($n,li(s));try{await e.writeTextAtomic(oR,IK(s))}catch(l){throw await e.writeTextAtomic($n,n),new Error("Project settings were rolled back because the software architecture summary could not be updated.",{cause:l})}return s}var RK={primary_language:"Linguagem principal",backend_runtime:"Runtime backend",backend_api:"Framework backend / API",query_builder:"Query builder",database:"Banco de dados",auth_storage:"Autentica\xE7\xE3o e Storage",cache_messaging:"Cache e mensageria",async_queue:"Filas e processamento ass\xEDncrono",backend_infrastructure:"Infraestrutura backend",backend_hosting:"Hospedagem do backend",web_framework:"Framework do Web App",web_language:"Linguagem do Web App",web_build:"Build do Web App",frontend_hosting:"Hospedagem do frontend",site_framework:"Framework do site",site_language:"Linguagem do site",site_islands:"Componentes interativos",site_build:"Build do site",site_hosting:"Hospedagem do site",prometheus:"Coleta de m\xE9tricas",grafana:"Dashboards",uptime_kuma:"Monitoramento de disponibilidade",cadvisor:"M\xE9tricas de containers",node_exporter:"M\xE9tricas de host",redis_exporter:"M\xE9tricas do Redis",k6:"Teste de carga",autocannon:"Teste HTTP de carga"},CK={backend_data_and_managed_services:"Dados e servi\xE7os gerenciados",backend_api_and_business_rules:"APIs e regras de neg\xF3cio",backend_async_processing:"Filas e processamento ass\xEDncrono",backend_infrastructure:"Infraestrutura backend",backend_hosting:"Hospedagem do backend"};function IK(e){let t=na(e.autonomy),n=Tt(e.stack.overrides),i=Tt(n.components),r=Tt(n.languages),o=Tt(n.architecture),a=Object.entries(RK).map(([_,p])=>{let f=Tt(i[_]);return`| ${p} | ${$t(f.name,"N\xE3o definido")} | ${$t(f.version,"N\xE3o fixada")} | ${$t(f.reference,"\u2014")} |`}),s=Object.entries(e.stack.layout??{}).map(([_,p])=>`| ${$t(_)} | ${$t(p)} |`),l=Object.entries(e.stack.commands??{}).map(([_,p])=>`| ${$t(_)} | \`${NK(p)}\` |`),c=Object.entries(o).flatMap(([_,p])=>[`### ${CK[_]??$K(_)}`,"",...ec(c_(p)),""]),u=e.execution&&e.execution.runtime!=="manual"?[`- **Runtime:** ${e.execution.runtime}`,`- **Provider:** ${$t(e.execution.autonomous.provider)}`,`- **Modelo-base:** ${$t(e.execution.autonomous.model)}`,`- **Paralelismo m\xE1ximo:** ${e.execution.autonomous.max_parallelism}`,`- **Lease configurado:** ${e.execution.autonomous.lease_ms} ms`,`- **Limite total de invoca\xE7\xF5es:** ${e.autonomy?"Por Task; sem teto agregado de SPEC/PRD":e.execution.autonomous.max_total_invocations??"N\xE3o definido"}`]:[`- **Runtime:** ${e.execution?.runtime??"manual (padr\xE3o impl\xEDcito)"}`],d=e.assurance===void 0?["- N\xE3o configurada."]:[`- **Vers\xE3o:** ${e.assurance.version}`,`- **Profundidade padr\xE3o:** ${$t(e.assurance.standard_depth)}`,`- **Exigir commit final:** ${e.assurance.require_final_commit?"Sim":"N\xE3o"}`];return["---","schema_version: 1","kind: software-architecture",`generated_from: ${$n}`,"---","","# Arquitetura de Software","",`> Proje\xE7\xE3o gerada automaticamente pela p\xE1gina de configura\xE7\xF5es a partir de \`${$n}\`. N\xE3o edite este arquivo manualmente.`,"","## Projeto","",`- **Nome:** ${$t(e.project.name)}`,`- **ID:** ${$t(e.project.id)}`,`- **Timezone:** ${$t(e.project.timezone)}`,"","## Perfil t\xE9cnico","",`- **Stack profile:** ${$t(e.stack.id)}`,`- **Linguagem:** ${$t(e.stack.language,"N\xE3o definida")}`,`- **API:** ${$t(e.stack.api,"N\xE3o definida")}`,`- **Query builder:** ${$t(e.stack.query_builder,"N\xE3o definido")}`,"","## Execu\xE7\xE3o","",...u,...e.autonomy?["","### Autonomia","",`- **Perfil:** ${t.label}`,`- **Execu\xE7\xF5es por Task:** ${t.attempts??"Ilimitadas"}`,`- **Replanejamentos por Task:** ${t.replans??"Ilimitados"}`,"- Sem abandono por tempo. Tasks iniciadas preservam o perfil e os contadores.","- Subagentes podem ter modelo/esfor\xE7o diferentes do principal, com aviso expl\xEDcito."]:[],"","## Assurance","",...d,"","## Componentes e vers\xF5es","","| Responsabilidade | Tecnologia | Vers\xE3o atual / refer\xEAncia | Pacote / imagem / servi\xE7o |","| --- | --- | --- | --- |",...a,"","## Superf\xEDcies","","### Web App \u2014 Frontend","",...ec(c_(r.frontend)),"","### Backend","",...ec(c_(r.backend)),"","### Site e Landing Pages","",...ec(c_(r.site)),"","## Decis\xF5es de arquitetura","",...c.length>0?c:["- Nenhuma decis\xE3o adicional registrada.",""],"## Layout do c\xF3digo","","| Papel | Caminho |","| --- | --- |",...s.length>0?s:["| N\xE3o definido | \u2014 |"],"","## Invariantes","",...ec(e.stack.invariants??[]),"","## Comandos de valida\xE7\xE3o","","| Comando | Execu\xE7\xE3o |","| --- | --- |",...l.length>0?l:["| N\xE3o definido | \u2014 |"],""].join(`
|
|
346
346
|
`)}function Tt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function c_(e){return Array.isArray(e)?e.flatMap(t=>{if(typeof t=="string"&&t.length>0)return[t];let n=Object.entries(Tt(t));return n.length===1&&typeof n[0]?.[1]=="string"?[`${n[0][0]}: ${n[0][1]}`]:[]}):[]}function ec(e){return e.length>0?e.map(t=>`- ${$t(t)}`):["- N\xE3o definido."]}function $t(e,t="\u2014"){return typeof e!="string"||e.trim().length===0?t:e.trim().replaceAll("|","\\|").replaceAll(/\r?\n/g," ")}function NK(e){return $t(e).replaceAll("`","\\`")}function $K(e){let t=e.replaceAll("_"," ");return t.charAt(0).toUpperCase()+t.slice(1)}function cR(){let e=null;return{get failure(){return e},get healthStatus(){return e===null?"ok":"degraded"},clear:()=>{e=null},record:({trigger:t,error:n})=>{e={trigger:t,occurred_at:new Date().toISOString(),code:"projection_refresh_failed",cause:n instanceof Error&&n.name.length>0?n.name:"unknown_error"}}}}var lR={"agent-orchestrator":"1 - Dave - Product Owner.png","agent-builder":"2 - Rafa - Tech Lead.png","agent-task-executor":"3 - Leo - Software Engineer.png","agent-analyst":"4 - Bia - Product Manager.png","agent-finalizer":"5 - Gui - Quality Assurance Lead.png","agent-reviewer":"6 - Nanda - Principal Engineer.png","agent-integrator":"7 - Dani - Integration Engineer.png","agent-auditor":"8 - Ana - Quality Auditor.png","agent-text-summarizer":"9 - Lia - Technical Writer.png","agent-data-analyst":"10 - Gabi - Data Analyst.png","agent-refactoring-specialist":"11 - Tati - Refactoring Specialist.png","agent-frontend":"12 - Doug - Frontend Developer.png","agent-backend":"13 - Will - Backend Developer.png","agent-website-developer":"14 - Jonny - Website Developer.png","agent-designer":"15 - Manu - Product Designer.png","agent-cloud-engineer":"16 - Dan - Cloud Engineer.png","agent-security-auditor":"17 - Luis - Security Auditor.png","agent-marketing-analyst":"18 - Lucia - Marketing Analyst.png"};function uR(e){let t=new Set(["prd","spec","change","task","execution"]),n=new Set(["active","executing","verifying","running","paused"]);return e.filter(i=>t.has(i.kind)&&(n.has(i.status??"")||i.kind==="task"&&i.status==="planned")).map(i=>i.id).sort()}var Ch=class{writer;encoder;writable;abortSubscribers=[];responseReadable;aborted=!1;closed=!1;constructor(e,t){this.writable=e,this.writer=e.getWriter(),this.encoder=new TextEncoder;let n=t.getReader();this.abortSubscribers.push(async()=>{await n.cancel()}),this.responseReadable=new ReadableStream({async pull(i){let{done:r,value:o}=await n.read();r?i.close():i.enqueue(o)},cancel:()=>{this.closed||this.abort()}})}async write(e){try{typeof e=="string"&&(e=this.encoder.encode(e)),await this.writer.write(e)}catch{}return this}async writeln(e){return await this.write(e+`
|
|
347
347
|
`),this}sleep(e){return new Promise(t=>setTimeout(t,e))}async close(){this.closed=!0;try{await this.writer.close()}catch{}}async pipe(e){this.writer.releaseLock();try{await e.pipeTo(this.writable,{preventClose:!0,preventAbort:!0})}finally{this.writer=this.writable.getWriter()}}onAbort(e){this.abortSubscribers.push(e)}abort(){this.aborted||(this.aborted=!0,this.abortSubscribers.forEach(e=>{try{Promise.resolve(e()).catch(()=>{})}catch{}}))}};var l_=()=>{let e=typeof Bun<"u"?Bun.version:void 0;if(e===void 0)return!1;let t=e.startsWith("1.1")||e.startsWith("1.0")||e.startsWith("0.");return l_=()=>t,t};var dR=class extends Ch{constructor(e,t){super(e,t)}async writeSSE(e){let n=(await Ks(e.data,Qd.Stringify,!1,{})).split(/\r\n|\r|\n/).map(r=>`data: ${r}`).join(`
|
|
348
348
|
`);for(let r of["event","id"]){let o=e[r];if(o&&/[\r\n]/.test(o))throw new Error(`${r} must not contain "\\r" or "\\n"`)}let i=[e.event&&`event: ${e.event}`,n,e.id!==void 0&&`id: ${e.id}`,e.retry!==void 0&&`retry: ${e.retry}`].filter(Boolean).join(`
|
|
@@ -351,7 +351,7 @@ ${"stderr"in e?String(e.stderr??""):""}`:String(e)).includes("Lifecycle manifest
|
|
|
351
351
|
`;await this.write(i)}},PK=async(e,t,n)=>{try{await t(e)}catch(i){i instanceof Error&&n?(await n(i,e),await e.writeSSE({event:"error",data:i.message})):console.error(i)}finally{e.close()}},LK=new WeakMap,Ih=(e,t,n)=>{let{readable:i,writable:r}=new TransformStream,o=new dR(r,i);return l_()&&e.req.raw.signal.addEventListener("abort",()=>{o.closed||o.abort()}),LK.set(o.responseReadable,e),e.header("Transfer-Encoding","chunked"),e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),PK(o,t,n),e.newResponse(o.responseReadable)};function _R(e,t,n=!1){let i=new Set,r;n&&(r=setTimeout(()=>process.exit(0),12e3),r.unref());let o=a=>{i.delete(a)&&(!n||i.size!==0||(r!==void 0&&clearTimeout(r),r=setTimeout(()=>process.exit(0),12e3),r.unref()))};e.get(`${t}/browser-lease`,a=>{let s={};return r!==void 0&&clearTimeout(r),r=void 0,i.add(s),Ih(a,async l=>{let c,u;l.onAbort(()=>{c!==void 0&&clearTimeout(c),u?.(),o(s)});try{for(await l.writeSSE({event:"lease",data:"active"});!l.aborted;)await new Promise(d=>{u=d,c=setTimeout(d,1e4),c.unref()}),l.aborted||await l.write(`: keep-alive
|
|
352
352
|
|
|
353
353
|
`)}finally{c!==void 0&&clearTimeout(c),o(s)}})})}function d_(e,t){let n=e.length;return{tasks:u_(e.map(i=>i.task_count),n),specs:u_(e.map(i=>i.spec_count),n),prds:u_(e.map(i=>i.prd_count),n),durationMs:u_(e.map(i=>i.duration_ms),n),tokens:pR(e.map(i=>i.total_tokens)),cost:pR(e.map(i=>t==="BRL"?i.estimated_brl:i.estimated_usd))}}function pR(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)/t.length}function u_(e,t){return t===0||e.every(n=>n===null)?null:e.reduce((n,i)=>n+(i??0),0)/t}Wr();Sa();function fR(e,t){let n=new Map(e.map(i=>[i.key,i]));for(let i of t??[])n.has(i)||n.set(i,UK(i));return[...n.values()].sort((i,r)=>r.latest_started_at.localeCompare(i.latest_started_at)||i.label.localeCompare(r.label))}function UK(e){return{key:e,label:e,latest_started_at:"",run_count:0,task_count:0,prd_count:0,spec_count:0,evidence_count:0,test_count:0,event_count:0,total_tokens:0,estimated_usd:0,estimated_brl:0,duration_ms:0,duration:{known_sum:0,unknown:0,complete:!0,coverage_ratio:1},coverage:{events:0,tokens:0,usd:0,brl:0}}}function Nh(e){return e.length===0||e.some(t=>t===null)?null:e.reduce((t,n)=>t+(n??0),0)/e.length}function ka(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)}function nc(e,t="all_invocations"){let n=new Map;for(let a of e)n.has(a.run_id)||n.set(a.run_id,a);let i=[...n.values()];if(t==="all_invocations")return i;let r=new Set(i.map(a=>a.run_id));return t==="all_execution"?i.filter(a=>a.phase==="execution"):i.filter(a=>a.phase==="execution"&&(a.parent_run_id===null||!r.has(a.parent_run_id)))}function p_(e,t="all_invocations"){let n=nc(e,t),i=n.filter(o=>o.duration_ms!==null),r=n.length-i.length;return{known_sum:i.reduce((o,a)=>o+a.duration_ms,0),unknown:r,complete:r===0,coverage_ratio:n.length===0?1:i.length/n.length}}function m_(e){let t=e?.trim().toLowerCase();return!t||t==="unknown"||t==="codex"?"openai":t}var FK={events:0,tokens:0,usd:0,brl:0};function hR(e,t){let n=new Map;for(let l of t)l.task_id!==null&&n.set(l.task_id,[...n.get(l.task_id)??[],l]);let i=e.filter(l=>n.has(l.id)).map(l=>yR(l,n.get(l.id)??[])),r=new Set(e.map(l=>l.id)),o=[...n].filter(([l])=>!r.has(l)).map(([l,c])=>gR(l,c)),a=t.filter(l=>l.task_id===null),s=a.length===0?[]:[gR("Sem tarefa vinculada",a)];return[...i,...o,...s].sort((l,c)=>c.latest_started_at.localeCompare(l.latest_started_at))}function gR(e,t){return{...yR({id:e,title:e,created_at:t[0]?.started_at??"",test_count:0},t),label:`Tarefa hist\xF3rica: ${e}`,latest_started_at:t.reduce((n,i)=>i.started_at>n?i.started_at:n,"")}}function yR(e,t){let n=p_(t);return{key:e.id,label:e.title,latest_started_at:e.created_at,run_count:t.length,task_count:1,tasksCreated:1,tasksActive:1,prd_count:0,spec_count:0,evidence_count:0,test_count:e.test_count??0,event_count:t.reduce((i,r)=>i+(r.event_count??0),0),total_tokens:ka(t.map(i=>i.total_tokens)),estimated_usd:ka(t.map(i=>i.estimated_usd)),estimated_brl:ka(t.map(i=>i.estimated_brl)),duration_ms:n.known_sum,duration:n,coverage:t.reduce((i,r)=>({events:i.events+r.coverage.events,tokens:i.tokens+r.coverage.tokens,usd:i.usd+r.coverage.usd,brl:i.brl+r.coverage.brl}),FK),coverage_counts:{source:"run_rows",granularity:"event",events:t.reduce((i,r)=>i+r.coverage.events,0),tokens:null,usd:null,brl:null,metrics:{tokens:$h(t,i=>i.total_tokens),usd:$h(t,i=>i.estimated_usd),brl:$h(t,i=>i.estimated_brl)}}}}function $h(e,t){let n=e.filter(i=>t(i)!==null).length;return{eligible_runs:e.length,known_runs:n,unknown_runs:e.length-n}}function Ea(e,t,n=r=>r,i="all_invocations"){let r=[...new Set(e.map(t))],o=new Set(nc(e,i).map(a=>a.run_id));return r.map(a=>{let s=e.filter(c=>t(c)===a),l=p_(s.filter(c=>o.has(c.run_id)),i);return{key:a,label:n(a),latest_started_at:s.reduce((c,u)=>u.started_at>c?u.started_at:c,s[0]?.started_at??""),run_count:s.length,task_count:new Set(s.flatMap(c=>c.task_id===null?[]:[c.task_id])).size,tasksActive:new Set(s.flatMap(c=>c.task_id===null?[]:[c.task_id])).size,taskDaysActive:new Set(s.flatMap(c=>c.task_id===null?[]:[c.task_id])).size,prd_count:0,spec_count:0,evidence_count:0,test_count:0,event_count:s.reduce((c,u)=>c+(u.event_count??0),0),total_tokens:Ph(s.map(c=>c.total_tokens)),estimated_usd:Ph(s.map(c=>c.estimated_usd)),estimated_brl:Ph(s.map(c=>c.estimated_brl)),duration_ms:l.known_sum,duration:l,coverage:zK(s)}}).sort(qK)}function Ph(e){return ka(e)}function vR(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)/t.length}function zK(e){return e.reduce((t,n)=>({events:t.events+n.coverage.events,tokens:t.tokens+n.coverage.tokens,usd:t.usd+n.coverage.usd,brl:t.brl+n.coverage.brl}),{events:0,tokens:0,usd:0,brl:0})}function qK(e,t){return t.latest_started_at.localeCompare(e.latest_started_at)}function f_(e,t,n){if(e.schema_version!==2)throw new TypeError("Cost Monitor accepts only OperationsProjection V2");let i=t?.currency??"BRL",r=Br(n?.agentNames??[]),o=e.runs,a=new Map(e.runs.map(y=>[y.id,y])),s=o,l=s,c=new Map(e.tasks.map(y=>[y.id,y])),d=l.map(y=>{let k=y.task_id===null?void 0:c.get(y.task_id),M=a.get(y.id),j=M?.usage.total.cost??{usd:null,brl:null},$=(M?.pricing_segments??[]).map(ae=>ae.recorded_fx_rate??kR(ae.recorded_usd??null,ae.recorded_brl??null)).filter(ae=>ae!==null),B=y.usage.total,N=B.coverage.tokens>0,O=B.coverage.usd>0,L=B.coverage.brl>0,J=t?ZK(y,t):null,ie=N?AR(M?.usage.total.tokens??B.tokens):null,U=XK(y);return{run_id:y.id,execution_id:y.execution_id,conversation_id:y.conversation_id,task_id:y.task_id,task_title:k?.title??y.task_id??y.conversation_id,task_status:k?.status??y.status,priority:k?.priority??"none",risk:k?.risk??"none",spec_id:y.spec_id,prd_id:y.prd_id,change_id:y.change_id,parent_run_id:y.parent_run_id,run_role:y.run_role,run_kind:y.run_kind,run_purpose:y.run_purpose,requires_finalizer:y.requires_finalizer,client:y.client,agent:y.agent,agent_name:WK(y,n),provider:m_(y.provider),model:y.effective_model??y.model,requested_model:y.model,reasoning_effort:y.reasoning_effort??null,effective_reasoning_effort:y.effective_reasoning_effort,service_tier:y.service_tier??null,call_count:y.call_count,status:y.status,phase:VK(y),origin:y.entrypoint,work_type:y.work_type,started_at:y.started_at,finished_at:y.finished_at,...U,estimation_basis:null,source_started_at:y.source_started_at??null,source_finished_at:y.source_finished_at??null,capture_lag_ms:y.capture_lag_ms??null,event_count:B.events,input_tokens:B.tokens.input,cached_input_tokens:B.tokens.cached_input,output_tokens:B.tokens.output,reasoning_tokens:B.tokens.reasoning,total_tokens:ie,uncached_input_tokens:B.tokens.input===null?null:Math.max(B.tokens.input-(B.tokens.cached_input??0),0),visible_output_tokens:B.tokens.output===null?null:Math.max(B.tokens.output-(B.tokens.reasoning??0),0),input_rate_usd_per_million:J?.rates.input??null,cached_input_rate_usd_per_million:J?.rates.cached??null,output_rate_usd_per_million:J?.rates.output??null,reasoning_rate_usd_per_million:J?.rates.reasoning??null,context_input_multiplier:J?.context.input??null,context_output_multiplier:J?.context.output??null,speed_cost_multiplier:J?.speedMultiplier??null,standard_cost_usd:J?.standardUsd??null,speed_uplift_usd:J?.upliftUsd??null,input_cost_usd:J?.components.input??null,cached_input_cost_usd:J?.components.cached??null,output_cost_usd:J?.components.output??null,reasoning_cost_usd:J?.components.reasoning??null,fx_rate:i==="BRL"?t?.fxRate?.rate??null:null,estimated_usd:O?j.usd:null,estimated_brl:L?j.brl:null,recorded_usd:O?j.usd:null,recorded_brl:L?j.brl:null,recorded_fx_rate:KK($)??kR(j.usd,j.brl),coverage:B.coverage,artifact_path:y.artifact_path}}),_=(y,k,M)=>Ea(d,y,k,M),p=qi(s),f={conversation:qi(s.filter(y=>y.entrypoint==="conversation")),task:qi(s.filter(y=>y.entrypoint==="task")),spec:qi(s.filter(y=>y.entrypoint==="spec")),prd:qi(s.filter(y=>y.entrypoint==="prd"))},m=p.total,g=d.filter(y=>y.total_tokens!==null),v=g.reduce((y,k)=>y+(k.total_tokens??0),0),S=g.reduce((y,k)=>y+(k.event_count??0),0),b=[...g].sort((y,k)=>(k.total_tokens??0)-(y.total_tokens??0)).slice(0,10).reduce((y,k)=>y+(k.total_tokens??0),0);return{schema_version:2,layout_version:2,readonly:!0,legacy_effort_baseline:{cutoff:sn.cutoff,duration_ms:sn.durationMs},source:e.source,currency:i,pricing:{catalog_updated_at:t?.catalog.updated_at??null,fx_rate:i==="BRL"?t?.fxRate?.rate??null:null,conversion_applied:t!==void 0&&i==="BRL"&&t.fxRate!==null},filters:e.filters,overview:{task_count:new Set(d.flatMap(y=>y.task_id===null?[]:[y.task_id])).size,run_count:d.length,event_count:d.reduce((y,k)=>y+(k.event_count??0),0),total_tokens:m.tokens.total,estimated_usd:m.cost.usd,estimated_brl:m.cost.brl,recorded_usd:SR(s.map(y=>a.get(y.id)?.usage.total.cost.usd??null)),recorded_brl:SR(s.map(y=>a.get(y.id)?.usage.total.cost.brl??null)),average_run_cost_usd:Nh(d.map(y=>y.estimated_usd)),average_run_cost_brl:Nh(d.map(y=>y.estimated_brl)),average_run_duration_ms:vR(nc(d).map(y=>y.duration_ms)),known_tokens_per_cycle:S===0?null:v/S,top_10_token_share:v===0?null:b/v,coverage:m.coverage},filters_available:{providers:Br(d.map(y=>m_(y.provider))),agents:Br(d.map(y=>y.agent_name)),models:Br(d.map(y=>y.model)),statuses:Br(d.map(y=>y.task_status)),priorities:Br(d.map(y=>y.priority)),risks:Br(d.map(y=>y.risk)),phases:Br(d.map(y=>y.phase)),origins:Br(d.map(y=>y.origin)),work_types:Br(d.map(y=>y.work_type))},configured_agents:r,usage:p,origins:f,prds:ER(e.prds,s),specs:ER(e.specs,s),runs:[...d].sort((y,k)=>k.started_at.localeCompare(y.started_at)),groups:{conversations:Ea(d,y=>y.conversation_id,void 0,"all_invocations"),tasks:hR(e.tasks,d),providers:_(y=>m_(y.provider)),agents:fR(_(y=>y.agent_name),r),models:_(y=>y.model),daily:Lh(Ea(d,y=>{let k=y.finished_at??y.started_at;return Dt(k,"day")??k.slice(0,10)},void 0,"all_invocations"),e.tasks,"day"),monthly:Lh(Ea(d,y=>{let k=y.finished_at??y.started_at;return Dt(k,"month")??k.slice(0,7)},void 0,"all_invocations"),e.tasks,"month"),annual:Lh(Ea(d,y=>{let k=y.finished_at??y.started_at;return Dt(k,"year")??k.slice(0,4)},void 0,"all_invocations"),e.tasks,"year")}}}function Lh(e,t,n){let i=new Map(e.map(r=>[r.key,{...r,tasksActive:r.tasksActive??r.task_count,taskDaysActive:r.tasksActive??r.task_count,tasksCreated:0}]));for(let r of t){let o=Dt(r.created_at,n);if(o===null)continue;let a=i.get(o);a!==void 0&&(a.tasksCreated=(a.tasksCreated??0)+1)}return[...i.values()]}function VK(e){return e.entrypoint==="task"&&e.phase==="conversation"?"planning":e.phase}function WK(e,t){if(e.agent==="codex")return"codex";let n=t?.agentNamesById?.[e.agent];if(n!==void 0)return n;if(e.agent==="agent-orchestrator")return t?.agentNamesByRole?.orchestrator??"zaip-agent-orchestrator";if(e.agent_name.trim()===e.agent){let i=t?.agentNamesByRole?.[e.run_role];if(i!==void 0)return i}return e.agent_name!=="codex",e.agent_name}function ZK(e,t){let n=e.pricing_segments??[],i=n.length>0?n.map(m=>({provider:m.provider,model:m.model??e.effective_model??e.model,serviceTier:m.service_tier??e.service_tier??"default",usage:JK(m)})):[{provider:e.provider,model:e.effective_model??e.model,serviceTier:e.service_tier??"default",usage:GK(e.usage.total)}],r=i.map(m=>yo({provider:m.provider==="openai"||m.provider==="anthropic"?m.provider:null,model:m.model,serviceTier:m.serviceTier,usage:m.usage,catalog:t.catalog,fxRate:null})),o=i.map(m=>yo({provider:m.provider==="openai"||m.provider==="anthropic"?m.provider:null,model:m.model,serviceTier:"default",usage:m.usage,catalog:t.catalog,fxRate:null})),a=bR(r.map(m=>m.estimated_usd)),s=bR(o.map(m=>m.estimated_usd)),l=a,c=l===null&&s!==null,u=BK(i,t.catalog),d=HK(t.catalog,i.map(m=>m.model)),_=i.some(m=>m.serviceTier==="priority"||m.serviceTier==="fast"),p=(m,g)=>_&&!c?g:m,f=i.some(m=>d?.long_context_threshold_tokens!==null&&d?.long_context_threshold_tokens!==void 0&&(m.usage.input??0)>d.long_context_threshold_tokens);return{rates:{input:d?p(d.input_per_million_usd,d.priority_input_per_million_usd??null):null,cached:d?p(d.cached_input_per_million_usd,d.priority_cached_input_per_million_usd??null):null,output:d?p(d.output_per_million_usd,d.priority_output_per_million_usd??null):null,reasoning:d?p(d.reasoning_per_million_usd??d.output_per_million_usd,d.priority_reasoning_per_million_usd??d.priority_output_per_million_usd??null):null},context:{input:d?f?d.long_context_input_multiplier:1:null,output:d?f?d.long_context_output_multiplier:1:null},speedMultiplier:l!==null&&s!==null&&s>0?Math.round(l/s*1e3)/1e3:null,standardUsd:s,upliftUsd:l!==null&&s!==null?g_(l-s):null,components:{input:u?.input??null,cached:u?.cached??null,output:u?.output??null,reasoning:u?.reasoning??null}}}function BK(e,t){let n=0,i=0,r=0;for(let o of e){let a=wR(t,o.model);if(a===null||o.provider!==null&&o.provider!==a.provider||o.usage.input===null||o.usage.cached_input===null||o.usage.output===null)return null;let s=a.long_context_threshold_tokens!==null&&o.usage.input>a.long_context_threshold_tokens,l=o.serviceTier==="priority"||o.serviceTier==="fast",c=a.priority_input_per_million_usd,u=a.priority_output_per_million_usd,d=l&&!s&&c!==null&&c!==void 0&&u!==null&&u!==void 0,_=d&&c!==null&&c!==void 0?c:a.input_per_million_usd,p=d?a.priority_cached_input_per_million_usd??0:a.cached_input_per_million_usd??0,f=d&&u!==null&&u!==void 0?u:a.output_per_million_usd,m=s?a.long_context_input_multiplier:1,g=s?a.long_context_output_multiplier:1,v=Math.max(o.usage.input-o.usage.cached_input,0);n+=v/1e6*_*m,i+=o.usage.cached_input/1e6*p*m,r+=o.usage.output/1e6*f*g}return{input:n,cached:i,output:r,reasoning:0}}function wR(e,t){let n=t.toLowerCase();return e.models.find(i=>i.id.toLowerCase()===n||i.aliases.some(r=>r.toLowerCase()===n))??null}function HK(e,t){let n=t.map(r=>wR(e,r));if(n.some(r=>r===null))return null;let i=n[0];return!i||n.some(r=>r?.id!==i.id)?null:i}function JK(e){return{input:e.input_tokens,cached_input:e.cached_input_tokens,output:e.output_tokens,reasoning:e.reasoning_tokens,total:e.total_tokens,source:"provider_reported"}}function GK(e){return{input:e.tokens.input,cached_input:e.tokens.cached_input,output:e.tokens.output,reasoning:e.tokens.reasoning,total:e.tokens.total,source:"provider_reported"}}function bR(e){return e.length===0||e.some(t=>t===null)?null:g_(e.reduce((t,n)=>t+n,0))}function SR(e){let t=e.filter(n=>n!==null);return t.length===0?null:g_(t.reduce((n,i)=>n+i,0))}function g_(e){return Math.round(e*1e6)/1e6}function kR(e,t){return e!==null&&e>0&&t!==null?g_(t/e):null}function KK(e){if(e.length===0)return null;let t=e[0]??null;return e.every(n=>n===t)?t:null}function XK(e){return typeof e.source_duration_ms=="number"&&e.source_duration_ms>=0?{duration_ms:e.source_duration_ms,duration_provenance:"observed"}:typeof e.duration_ms=="number"&&e.duration_ms>=0&&(e.duration_provenance===void 0||e.duration_provenance==="observed"||e.duration_provenance==="reconciled"||e.duration_provenance==="legacy_inferred")?{duration_ms:e.duration_ms,duration_provenance:e.duration_provenance??"legacy_inferred"}:{duration_ms:null,duration_provenance:"unavailable"}}function qi(e){return Object.fromEntries(["conversation","planning","execution","total","new_work","rework"].map(n=>[n,YK(e.map(i=>i.usage[n]))]))}function YK(e){let t=n=>{let i=n.filter(r=>r!==null);return i.length===0?null:i.reduce((r,o)=>r+o,0)};return{events:e.reduce((n,i)=>n+i.events,0),duration_ms:t(e.map(n=>n.duration_ms??null)),tokens:{input:t(e.map(n=>n.tokens.input)),cached_input:t(e.map(n=>n.tokens.cached_input)),output:t(e.map(n=>n.tokens.output)),reasoning:t(e.map(n=>n.tokens.reasoning)),total:t(e.map(n=>AR(n.tokens)))},cost:{usd:t(e.map(n=>n.cost.usd)),brl:t(e.map(n=>n.cost.brl))},coverage:{events:e.reduce((n,i)=>n+i.coverage.events,0),tokens:e.reduce((n,i)=>n+i.coverage.tokens,0),usd:e.reduce((n,i)=>n+i.coverage.usd,0),brl:e.reduce((n,i)=>n+i.coverage.brl,0)}}}function AR(e){return e.input!==null&&e.output!==null?e.input+e.output:e.total}function ER(e,t){return e.map(n=>{let i=new Set(n.run_ids),r=t.filter(o=>i.has(o.id)||n.kind==="prd"&&o.prd_id===n.id||n.kind==="spec"&&o.spec_id===n.id);return{...n,usage:qi(r)}})}function Br(e){return[...new Set(e)].sort()}Sa();jo();function fp(e,t,n,i){let r=(e.run_metrics??[]).map(G9),o=r.filter(N=>{let O=Dt(N.finished_at??N.started_at,"day");return O!==null&&YN(O,t.filters.from,t.filters.to)}).map(J9),a=t.schema_version===2?f_({...t,tasks:t.tasks??[],runs:o},void 0):null,s=N=>N.filter(O=>{let L=O.key.trim().toLowerCase();return L.length>0&&!["mixed","unknown","unavailable"].includes(L)}),l=e.run_metrics!==void 0,c=e.cost_monitor_daily_duration!==void 0||e.canonical_daily_duration_ms!==void 0,u=new Map(Object.entries(K9(e)));for(let N of Object.keys(e.cost_monitor_daily_duration??{}))u.has(N)||u.set(N,vv());if(!l&&!c)for(let N of Object.keys(Zr))u.has(N)||u.set(N,vv());let d=[...u].filter(([N])=>YN(N,t.filters.from,t.filters.to)),_=Y9(r),p=e.cost_monitor_daily_duration,f=(N,O)=>{if(p!==void 0){let L=p[N];return L===void 0?gv():{value:{known_sum:L.known_sum,unknown:L.eligible_runs-L.known_runs,complete:L.eligible_runs===L.known_runs,coverage_ratio:L.eligible_runs===0?1:L.known_runs/L.eligible_runs},population:Kr(L.eligible_runs,L.known_runs)}}if(e.canonical_daily_duration_ms!==void 0){let L=e.canonical_daily_duration_ms[N];return L===void 0?gv():{value:{known_sum:L,unknown:0,complete:!0,coverage_ratio:1},population:Kr(O.runs,O.runs)}}return l?_.get(N)??gv():H9(N,O)},m=new Map((e.daily_rows??[]).map(N=>[N.key,N])),v=d.map(([N,O])=>X9(N,O,i,f(N,O),m.get(N))),S=v.reduce((N,O)=>N+O.run_count,0),b=v.reduce((N,O)=>N+O.event_count,0),y=!c&&o.every(N=>N.usage.total.tokens.total===null)?null:hv(v.map(N=>N.total_tokens)),k=!c&&o.every(N=>N.usage.total.cost.brl===null)?null:hv(v.map(N=>N.estimated_brl)),M=hv(v.map(N=>N.estimated_usd)),j=Q9(e.run_metrics??[]),$=t.summary.overview_metrics?.task_count??t.summary.task_count,B={events:S,tokens:v.reduce((N,O)=>N+O.coverage.tokens,0),usd:v.reduce((N,O)=>N+O.coverage.usd,0),brl:v.reduce((N,O)=>N+O.coverage.brl,0)};return{schema_version:2,layout_version:t.layout_version,readonly:!0,source:".agents/records",aggregate_only:!0,data_source:l||c?"run_records":"lifecycle_manifest_summary",legacy_effort_baseline:!l&&!c&&t.filters.from===null&&t.filters.to===null?{cutoff:sn.cutoff,duration_ms:sn.durationMs}:null,currency:n,pricing:{catalog_updated_at:null,fx_rate:i,conversion_applied:i!==null},filters:t.filters,overview:{task_count:$,run_count:S,event_count:b,total_tokens:y,estimated_usd:M,estimated_brl:k,recorded_usd:null,recorded_brl:null,average_run_cost_usd:S===0||M===null||B.usd!==S?null:M/S,average_run_cost_brl:S===0||k===null||B.brl!==S?null:k/S,average_run_duration_ms:j,known_tokens_per_cycle:S===0||y===null?null:y/S,top_10_token_share:null,coverage:B},filters_available:{providers:e.filters_available?.providers??a?.filters_available.providers??[],agents:e.filters_available?.agents??a?.filters_available.agents??[],models:e.filters_available?.models??a?.filters_available.models??[],statuses:e.filters_available?.statuses??a?.filters_available.statuses??[],priorities:e.filters_available?.priorities??a?.filters_available.priorities??[],risks:e.filters_available?.risks??a?.filters_available.risks??[],phases:e.filters_available?.phases??a?.filters_available.phases??[],origins:e.filters_available?.origins??a?.filters_available.origins??[],work_types:e.filters_available?.work_types??a?.filters_available.work_types??[]},configured_agents:a?.configured_agents??[],usage:e.aggregate_usage??a?.usage??qi(o),origins:e3(),prds:a?.prds??t.prds,specs:a?.specs??t.specs,runs:[],groups:{conversations:[],tasks:[],providers:s(a?.groups.providers??[]),agents:a?.groups.agents??[],models:s(e.model_groups??a?.groups.models??[]),daily:v,monthly:XN(v,7),annual:XN(v,4)}}}function H9(e,t){if((Zr[e]??0)>0)return Mo(e,t);if(t.duration!==void 0){let n=bv(t.runs,t.duration.unknown);return{value:t.duration,population:Kr(t.runs,n)}}return{value:{known_sum:0,unknown:t.runs,complete:t.runs===0,coverage_ratio:t.runs===0?1:0},population:Kr(t.runs,0)}}function vv(){let e={known_sum:0,unknown:0,complete:!0,coverage_ratio:1};return{prds:0,specs:0,tasks:0,validations:0,evidences:0,runs:0,usage:{total_tokens:e,cost:{...e,currency:"BRL"}}}}function J9(e){let t={events:0,duration_ms:null,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}},n={...t,events:e.events??0,duration_ms:e.source_duration_ms??null,tokens:{...t.tokens,input:e.input_tokens??null,cached_input:e.cached_input_tokens??null,output:e.output_tokens??null,reasoning:e.reasoning_tokens??null,total:e.total_tokens},cost:{usd:null,brl:e.currency==="BRL"?e.cost:null},coverage:{events:e.events??0,tokens:e.total_tokens===null?0:1,usd:0,brl:e.cost===null?0:1}},i=e.phase==="conversation"||e.phase==="planning"?e.phase:"execution";return{id:e.id,artifact_path:`.agents/records/runs/${e.id}`,status:e.status==="failed"||e.status==="cancelled"||e.status==="running"?e.status:"completed",phase:i,entrypoint:e.task_id===null?"conversation":"task",work_type:"new",run_role:e.run_kind==="subrun"?"subagent":"orchestrator",run_kind:e.run_kind??"run",run_purpose:"execution",requires_finalizer:!1,parent_run_id:e.parent_run_id,client:"unknown",agent:e.agent??"unknown",agent_name:e.agent_name??e.agent??"unknown",provider:e.provider??"unavailable",model:e.model??"unknown",reasoning_effort:null,effective_model:e.model??null,effective_reasoning_effort:null,effective_config_mixed:!1,call_count:null,terminal_call_count:null,failed_call_count:0,cancelled_call_count:0,conversation_id:e.conversation_id??e.id,execution_id:e.execution_id??null,task_id:e.task_id,spec_id:e.spec_id??null,prd_id:e.prd_id??null,change_id:e.change_id??null,started_at:e.started_at,finished_at:e.finished_at,duration_ms:e.duration_ms,source_duration_ms:e.source_duration_ms??null,...e.duration_provenance===void 0?{}:{duration_provenance:e.duration_provenance},...e.estimation_basis===void 0?{}:{estimation_basis:e.estimation_basis},usage:{conversation:i==="conversation"?n:t,planning:i==="planning"?n:t,execution:i==="execution"?n:t,total:n,new_work:n,rework:t}}}function G9(e){let t=e.source_duration_ms??e.duration_ms,n=e.source_duration_ms!==null&&e.source_duration_ms!==void 0?"observed":e.duration_provenance??"legacy_inferred";return typeof t=="number"&&t>=0&&(n==="observed"||n==="reconciled"||n==="legacy_inferred")?{...e,duration_ms:t,duration_provenance:n,estimation_basis:null}:{...e,duration_ms:null,duration_provenance:"unavailable",estimation_basis:null}}function K9(e){let t=[...new Map((e.run_metrics??[]).map(r=>[r.id,r])).values()];if(e.run_metrics===void 0)return e.periods.daily;let n=new Map;for(let r of t){let o=Dt(r.started_at,"day");o!==null&&n.set(o,[...n.get(o)??[],r])}let i=new Set([...Object.keys(e.periods.daily),...n.keys()]);return Object.fromEntries([...i].map(r=>{let o=e.periods.daily[r]??vv(),a=n.get(r)??[],s=mv(a.map(u=>u.total_tokens)),l=mv(a.map(u=>u.cost)),c=mv(a.map(u=>u.events));return[r,{...o,runs:a.length,usage:{total_tokens:s,cost:{...l,currency:a.find(u=>u.currency!==null)?.currency??o.usage.cost.currency}},events:c}]}))}function mv(e){let t=e.filter(i=>i!==null),n=e.length-t.length;return{known_sum:t.reduce((i,r)=>i+r,0),unknown:n,complete:n===0,coverage_ratio:e.length===0?1:t.length/e.length}}function X9(e,t,n,i,r){let o=t.usage.cost.known_sum===0&&t.usage.cost.unknown>0?null:t.usage.cost.known_sum,a=r===void 0?o:r.total_cost_brl,s=r===void 0?a!==null&&n!==null&&n>0?a/n:null:r.total_cost_usd,l=t.events?.known_sum??0,c=bv(t.runs,t.usage.total_tokens.unknown),u=bv(t.runs,t.usage.cost.unknown);return{key:e,label:e,latest_started_at:`${e}T23:59:59.999-03:00`,run_count:t.runs,task_count:t.tasks,tasksCreated:t.tasks,tasksActive:t.tasks,taskDaysActive:t.tasks,prd_count:t.prds,spec_count:t.specs,evidence_count:t.evidences,test_count:t.validations,event_count:l,total_tokens:t.usage.total_tokens.known_sum===0&&t.usage.total_tokens.unknown>0?null:t.usage.total_tokens.known_sum,estimated_usd:s,estimated_brl:a,duration_ms:i.population.known_runs>0?i.value.known_sum:null,duration:i.value,coverage:{events:t.runs,tokens:c,usd:u,brl:u},coverage_counts:{source:"period_summary",granularity:t.events===void 0?"unavailable":"event",events:t.events?.known_sum??null,tokens:null,usd:null,brl:null,metrics:{duration:i.population,tokens:Kr(t.runs,c),usd:Kr(t.runs,u),brl:Kr(t.runs,u)}}}}function XN(e,t){let n=new Map;for(let i of e){let r=i.key.slice(0,t);n.set(r,[...n.get(r)??[],i])}return[...n].map(([i,r])=>{let o=r[0],a=r.reduce((d,_)=>d+_.duration.known_sum,0),s=r.reduce((d,_)=>d+_.duration.unknown,0),l=r.reduce((d,_)=>d+(_.coverage_counts?.metrics?.duration?.eligible_runs??0),0),c=r.reduce((d,_)=>d+(_.coverage_counts?.metrics?.duration?.known_runs??0),0),u=r.reduce((d,_)=>d+_.run_count,0);return{...o,key:i,label:i,latest_started_at:r.map(d=>d.latest_started_at).sort().at(-1)??o.latest_started_at,run_count:u,task_count:r.reduce((d,_)=>d+(_.task_count??0),0),tasksCreated:r.reduce((d,_)=>d+(_.tasksCreated??0),0),tasksActive:r.reduce((d,_)=>d+(_.tasksActive??0),0),taskDaysActive:r.reduce((d,_)=>d+(_.taskDaysActive??0),0),prd_count:r.reduce((d,_)=>d+(_.prd_count??0),0),spec_count:r.reduce((d,_)=>d+(_.spec_count??0),0),evidence_count:r.reduce((d,_)=>d+(_.evidence_count??0),0),test_count:r.reduce((d,_)=>d+(_.test_count??0),0),event_count:r.reduce((d,_)=>d+_.event_count,0),total_tokens:yv(r.map(d=>d.total_tokens)),estimated_usd:yv(r.map(d=>d.estimated_usd)),estimated_brl:yv(r.map(d=>d.estimated_brl)),duration_ms:s===0?a:null,duration:{known_sum:a,unknown:s,complete:s===0,coverage_ratio:l===0?1:c/l},coverage:{events:r.reduce((d,_)=>d+_.coverage.events,0),tokens:r.reduce((d,_)=>d+_.coverage.tokens,0),usd:r.reduce((d,_)=>d+_.coverage.usd,0),brl:r.reduce((d,_)=>d+_.coverage.brl,0)},...o.coverage_counts===void 0?{}:{coverage_counts:{...o.coverage_counts,metrics:{duration:Kr(l,c),tokens:fv(r,"tokens"),usd:fv(r,"usd"),brl:fv(r,"brl")}}}}}).sort((i,r)=>r.key.localeCompare(i.key))}function fv(e,t){let n=e.map(i=>i.coverage_counts?.metrics?.[t]);return Kr(n.reduce((i,r)=>i+(r?.eligible_runs??0),0),n.reduce((i,r)=>i+(r?.known_runs??0),0))}function Y9(e){return Nc(e)}function Q9(e){let t=e.filter(n=>n.phase==="execution"&&n.parent_run_id==null&&__(n.duration_started_at??n.started_at)&&n.duration_ms!==null&&n.duration_ms>=0);return t.length===0?null:t.reduce((n,i)=>n+i.duration_ms,0)/t.length}function gv(){return{value:{known_sum:0,unknown:0,complete:!0,coverage_ratio:1},population:Kr(0,0)}}function YN(e,t,n){let i=a=>a===null?null:/^\d{4}-\d{2}-\d{2}$/.test(a)?a:Dt(a,"day"),r=i(t),o=i(n);return(r===null||e>=r)&&(o===null||e<=o)}function hv(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)}function yv(e){return e.some(t=>t===null)?null:e.reduce((t,n)=>t+(n??0),0)}function bv(e,t){return Math.max(0,e-t)}function Kr(e,t){return{eligible_runs:e,known_runs:t,unknown_runs:e-t}}function Ua(){return{events:0,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}}}function e3(){let e=()=>({conversation:Ua(),planning:Ua(),execution:Ua(),total:Ua(),new_work:Ua(),rework:Ua()});return{conversation:e(),task:e(),spec:e(),prd:e()}}Wr();var QN=require("node:crypto");We();var Ee="/api/v2",e0=".agents/dashboard/work-priority.json",Ut=class extends Error{name="V2WorkspaceRequiredError"};async function yi(e){let t=await xx(e);if(t.version===1)throw new Ut("Dashboard API requires a modern ZAIP-AIOS workspace");return t}function ve(e,t,n=200,i=!1){if(i){let r=`"${(0,QN.createHash)("sha256").update(JSON.stringify(t)).digest("base64url")}"`;if(e.header("ETag",r),e.header("Cache-Control","private, no-cache"),e.req.header("if-none-match")===r)return e.body(null,304)}return e.req.method==="HEAD"?e.body(null,n):e.json(t,n)}function Et(e){let t=e.req.query("from")??null,n=e.req.query("to")??null;return{from:t0(t,"start"),to:t0(n,"end")}}function t0(e,t){if(e===null||!/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let n=n0(e);if(t==="start")return new Date(n).toISOString();let[i,r,o]=e.split("-").map(Number),a=new Date(Date.UTC(i,r-1,o+1)).toISOString().slice(0,10);return new Date(n0(a)-1).toISOString()}function n0(e){let[t,n,i]=e.split("-").map(Number),r=Date.UTC(t,n-1,i),o=r-r0(r);return o=r-r0(o),o}function r0(e){let n=new Intl.DateTimeFormat("en-US",{timeZone:"America/Sao_Paulo",timeZoneName:"longOffset"}).formatToParts(new Date(e)).find(o=>o.type==="timeZoneName")?.value??"GMT",i=/^GMT([+-])(\d{2}):(\d{2})$/.exec(n);if(i===null)return 0;let r=Number(i[2])*60+Number(i[3]);return(i[1]==="+"?1:-1)*r*6e4}Wr();jo();function Dc(e,t){let n=new Map(e.map(i=>[i.id,i]));for(let i of t.map(r=>Sv(r,t))){let r=n.get(i.id);if(r===void 0){n.set(i.id,i);continue}n.set(i.id,{...i,...r,usage:t3(r.usage,i.usage),provider:r.provider??i.provider,model:r.model==="unknown"?i.model:r.model,reasoning_effort:r.reasoning_effort??i.reasoning_effort,service_tier:r.service_tier??i.service_tier??null,call_count:r.call_count??i.call_count,terminal_call_count:r.terminal_call_count??i.terminal_call_count,...(r.pricing_segments?.length??0)>0?{pricing_segments:r.pricing_segments}:i.pricing_segments===void 0?{}:{pricing_segments:i.pricing_segments},...r.duration_ms!==null&&(r.source_duration_ms===null||r.source_duration_ms===0)?{duration_ms:r.duration_ms,source_duration_ms:null,source_started_at:null,source_finished_at:null,capture_lag_ms:null}:n3(r)})}return[...n.values()]}function t3(e,t){let n=(i,r)=>({...r,...i,tokens:{...r.tokens,...i.tokens,input:i.tokens.input??r.tokens.input,cached_input:i.tokens.cached_input??r.tokens.cached_input,output:i.tokens.output??r.tokens.output,reasoning:i.tokens.reasoning??r.tokens.reasoning,total:i.tokens.total??r.tokens.total},cost:{...r.cost,...i.cost,usd:i.cost.usd??r.cost.usd,brl:i.cost.brl??r.cost.brl}});return{conversation:n(e.conversation,t.conversation),planning:n(e.planning,t.planning),execution:n(e.execution,t.execution),total:n(e.total,t.total),new_work:n(e.new_work,t.new_work),rework:n(e.rework,t.rework)}}function n3(e){return{duration_ms:e.duration_ms,...typeof e.source_duration_ms=="number"?{duration_provenance:"observed"}:e.duration_provenance===void 0?{}:{duration_provenance:e.duration_provenance},estimation_basis:typeof e.source_duration_ms=="number"?null:e.estimation_basis??null,source_duration_ms:e.source_duration_ms??null,source_started_at:e.source_started_at??null,source_finished_at:e.source_finished_at??null,capture_lag_ms:e.capture_lag_ms??null}}function Sv(e,t){let n=Array.isArray(e.usage_segments)?e.usage_segments:[],i=d=>n.length===0||n.some(_=>!i3(_.tokens?.[d]))?null:n.reduce((_,p)=>_+(p.tokens?.[d]??0),0),r=e.quantitative_metrics.tokens_total,o=e.quantitative_metrics.estimated_usd,a=e.quantitative_metrics.estimated_brl,s={events:e.source_event_count,tokens:{input:i("input"),cached_input:i("cached_input"),output:i("output"),reasoning:i("reasoning"),total:r.known_sum},cost:{usd:e.historical_cost?.estimated_usd??o.known_sum,brl:e.historical_cost?.estimated_brl??a.known_sum},coverage:{events:e.source_event_count,tokens:r.complete,usd:o.complete,brl:a.complete}},l={...s,events:0,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}},c=e.phase==="execution"?s:l,u=e.invocation_kind==="delegated";return{id:e.run_id,artifact_path:`.agents/records/runs/${e.run_id}`,status:e.status??"completed",phase:e.phase??"execution",entrypoint:e.task_id===null?"conversation":"task",work_type:"new",run_role:u?"subagent":"orchestrator",run_kind:u?"subrun":"run",run_purpose:r3(e.purpose,u),requires_finalizer:!1,parent_run_id:t.find(d=>d.agent_invocation_id===e.parent_agent_invocation_id)?.run_id??null,client:"codex",agent:e.zaip_agent??"unknown",agent_name:e.zaip_agent??"unknown",provider:n.find(d=>typeof d.provider=="string")?.provider??null,model:n.find(d=>typeof d.model=="string")?.model??"unknown",reasoning_effort:n.find(d=>typeof d.reasoning_effort=="string")?.reasoning_effort??null,effective_model:null,effective_reasoning_effort:null,effective_config_mixed:!1,service_tier:n.find(d=>typeof d.service_tier=="string")?.service_tier??null,call_count:e.llm_call_count,terminal_call_count:e.llm_call_count,failed_call_count:e.status==="failed"?e.llm_call_count:0,cancelled_call_count:e.status==="cancelled"?e.llm_call_count:0,conversation_id:e.agent_invocation_id,execution_id:e.execution_id,task_id:e.task_id,spec_id:e.spec_id,prd_id:e.prd_id,change_id:e.change_id,started_at:e.occurred_at,finished_at:e.status===null?null:e.occurred_at,duration_ms:e.time.duration_ms,source_duration_ms:e.time.duration_ms,source_started_at:null,source_finished_at:e.time.source_latest_at,pricing_segments:n.map(d=>({phase:"execution",provider:d.provider,model:d.model,service_tier:d.service_tier,input_tokens:d.tokens?.input??null,cached_input_tokens:d.tokens?.cached_input??null,output_tokens:d.tokens?.output??null,reasoning_tokens:d.tokens?.reasoning??null,total_tokens:d.tokens?.total??null})),usage:{conversation:l,planning:l,execution:c,total:s,new_work:s,rework:l}}}function r3(e,t){return e==="intake"||e==="orchestration"||e==="execution"||e==="review"||e==="audit"||e==="finalization"?e:t?"execution":"orchestration"}function i3(e){return typeof e=="number"&&Number.isFinite(e)}We();Wr();function jn(e){return e.req.query("currency")==="USD"?"USD":"BRL"}function Qe(e,t){let n=e.req.query(t);return n===void 0||n===""?[]:n.split(",").filter(Boolean)}async function kv(e,t){let n=new Map,i=new Map,r=1,o=!0;for(;o;){let a=await rO(e,{...t,cache:n,page:r,page_size:500});for(let s of a.summaries)o3(s)&&i.set(s.agent_invocation_id,s);o=a.has_more,r+=1}return[...i.values()]}function o3(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.agent_invocation_id=="string"&&typeof t.root_agent_invocation_id=="string"&&(t.parent_agent_invocation_id===null||typeof t.parent_agent_invocation_id=="string")&&(t.invocation_kind==="orchestrator"||t.invocation_kind==="delegated")&&typeof t.run_id=="string"&&typeof t.quantitative_metrics=="object"&&t.quantitative_metrics!==null&&typeof t.time=="object"&&t.time!==null&&Array.isArray(t.usage_segments)}async function i0(e){try{let t=Ai(Ct(await e.readText(".agents/config/agents/catalog.yaml"))).agents;return{agentNames:t.map(n=>n.codex_name),agentNamesById:Object.fromEntries(t.map(n=>[n.id,n.codex_name])),agentNamesByRole:Object.fromEntries(t.map(n=>[n.role,n.codex_name]))}}catch{return{agentNames:[],agentNamesById:{},agentNamesByRole:{}}}}var a3=".agents/dashboard/work-priority.json";async function za(e,t,n,i=!1,r=!1){let o=await Mc(e,t,n,{overviewOnly:i,includeOverviewChanges:r}),a=s3(o,await hp(e,yp(o)));if(i||n.from===null||n.to===null)return a;let s=await kv(e,{from:n.from,to:n.to});return s.length===0?a:lp({...a,runs:Gr(s0(a.runs,s))})}async function hp(e,t){try{let n=Ev(JSON.parse(await e.readText(a3)),!1);return t===void 0?n:{...n,item_ids:n.item_ids.filter(i=>t.has(i))}}catch{return{schema_version:1,item_ids:[],updated_at:null}}}function yp(e){return new Set([...e.prds.map(t=>t.id),...e.specs.map(t=>t.id),...e.tasks.map(t=>t.id)])}function Ev(e,t=!0){let n=typeof e=="object"&&e!==null?e:{};return{schema_version:1,item_ids:Array.isArray(n.item_ids)?[...new Set(n.item_ids.filter(r=>typeof r=="string"&&r.length>0))]:[],updated_at:typeof n.updated_at=="string"&&!t?n.updated_at:new Date().toISOString()}}function s3(e,t){let n=new Map(t.item_ids.map((r,o)=>[r,o])),i=r=>n.get(r)??null;return{...e,prds:e.prds.map(r=>({...r,manual_order:i(r.id)})),specs:e.specs.map(r=>({...r,manual_order:i(r.id)})),tasks:e.tasks.map(r=>({...r,manual_order:i(r.id)}))}}async function Fa(e,t,n){let i=new ji(e),[r,o]=await Promise.all([i.readCatalog(),n==="BRL"?i.readLatestFxRate():Promise.resolve(null)]),a=await i0(e);return f_(t,{catalog:r,fxRate:o,currency:n},a)}async function a0(e,t,n){let i=n.req.query("from")??null,r=n.req.query("to")??null;if(i===null||r===null)return Fa(e,t,jn(n));let o={providers:Qe(n,"provider"),models:Qe(n,"model"),zaip_agents:Qe(n,"agent"),phases:Qe(n,"phase"),statuses:Qe(n,"status")},a=await kv(e,{from:i,to:r,filters:o});if(a.length===0)return Fa(e,t,jn(n));let s=Gr(s0(t.runs,a));return Fa(e,{...t,runs:s},jn(n))}function s0(e,t){let n=new Set(e.map(i=>i.id));return Dc(e,t.filter(i=>n.has(i.run_id)))}async function c0(e,t,n,i,r,o){let a=await l3(e,i.from,i.to),{from:s,to:l}=a,c={providers:Qe(n,"provider"),models:Qe(n,"model"),zaip_agents:Qe(n,"agent"),phases:Qe(n,"phase"),statuses:Qe(n,"status")},u=c.providers.length>0||c.models.length>0||c.zaip_agents.length>0||c.statuses.length>0,[d,_,p]=await Promise.all([Promise.resolve().then(()=>(jo(),KN)).then(({buildQuickOperationsProjection:k})=>k(e,t,{from:s,to:l})),lh(e,{from:s,to:l,filters:c,offset:r,limit:o}),e.readText(".agents/records/lifecycle/summary.json").then(k=>JSON.parse(k))]),f=(p.run_metrics??[]).filter(k=>u3(k.finished_at??k.started_at,s,l)).sort((k,M)=>(M.finished_at??M.started_at).localeCompare(k.finished_at??k.started_at)||k.id.localeCompare(M.id)),m=c.phases.length===0?f:f.filter(k=>k.phase!==null&&c.phases.includes(k.phase)),g=new Set(_.summaries.map(k=>k.run_id)),v=u?m.filter(k=>g.has(k.id)).map(o0):m.slice(r,r+o).map(o0),S=c3(v,_.summaries),b=Gr(S),y=await Fa(e,{...d,runs:b},jn(n));return{...y,page_only:!0,overview:{...y.overview,run_count:0,event_count:0,total_tokens:null,estimated_usd:null,estimated_brl:null,recorded_usd:null,recorded_brl:null,average_run_cost_usd:null,average_run_cost_brl:null,average_run_duration_ms:null,known_tokens_per_cycle:null,top_10_token_share:null},groups:{conversations:[],tasks:[],providers:[],agents:[],models:[],daily:[],monthly:[],annual:[]},run_page:{offset:r,limit:o,total:u?null:m.length,has_more:u?_.has_more:r+o<m.length}}}function c3(e,t){let n=new Set(e.map(o=>o.id)),i=Dc(e,t.filter(o=>n.has(o.run_id))),r=new Map(i.map(o=>[o.id,o]));return e.map(o=>r.get(o.id)??o)}function o0(e){let t={events:0,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}},n={...t,events:e.events??0,tokens:{...t.tokens,total:e.total_tokens},cost:{usd:null,brl:e.currency==="BRL"?e.cost:null},coverage:{events:e.events??0,tokens:e.total_tokens===null?0:1,usd:0,brl:e.cost===null?0:1}};return{id:e.id,artifact_path:`.agents/records/runs/${e.id}`,status:e.status==="failed"||e.status==="cancelled"||e.status==="running"?e.status:"completed",phase:e.phase??"execution",entrypoint:e.task_id===null?"conversation":"task",work_type:"new",run_role:e.run_kind==="subrun"?"subagent":"orchestrator",run_kind:e.run_kind??"run",run_purpose:"execution",requires_finalizer:!1,parent_run_id:e.parent_run_id,client:"unknown",agent:e.agent??"unknown",agent_name:e.agent_name??e.agent??"unknown",provider:e.provider,model:e.model??"unknown",reasoning_effort:null,effective_model:e.model,effective_reasoning_effort:null,effective_config_mixed:!1,call_count:null,terminal_call_count:null,failed_call_count:0,cancelled_call_count:0,conversation_id:e.conversation_id??e.id,execution_id:e.execution_id,task_id:e.task_id,spec_id:e.spec_id,prd_id:e.prd_id,change_id:e.change_id,started_at:e.started_at,finished_at:e.finished_at,duration_ms:e.duration_ms,source_duration_ms:e.duration_ms,usage:{conversation:t,planning:t,execution:n,total:n,new_work:n,rework:t}}}async function l3(e,t,n){if(t!==null&&n!==null)return{from:t,to:n};let i=await e.readText(".agents/records/lifecycle/summary.json").then(l=>JSON.parse(l)),r=Object.keys(i.periods?.daily??{}).sort(),o=r.at(0),a=r.at(-1),s=new Date().toISOString().slice(0,10);return{from:gp(t??o??s,"start"),to:gp(n??a??s,"end")}}function u3(e,t,n){let i=Date.parse(e),r=Date.parse(gp(t,"start")),o=Date.parse(gp(n,"end"));return Number.isFinite(i)&&Number.isFinite(r)&&Number.isFinite(o)&&i>=r&&i<=o}function gp(e,t){return/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T${t==="start"?"00:00:00.000":"23:59:59.999"}Z`:e}async function vp(e){return new ji(e).readLatestFxRate()}function l0(e){return["provider","model","agent","phase","status"].every(t=>(e.req.queries(t)?.length??0)===0)}jo();Hr();function bp(e){return e.map(t=>({task_id:t.task_id,duration_ms:t.total_duration_ms,total_tokens:t.total_tokens,total_cost_usd:t.total_cost_usd,cost_brl:t.total_cost_brl,run_count:t.total_run_count}))}var jc=e=>typeof e=="number"&&Number.isFinite(e)?e:null,d3=(e,t)=>{let n=String(t);return n==="draft"?e==="prd"?"definition":"planning":n==="ready"||n==="planned"?"ready":n==="active"?"executing":n==="delivered"?"completed":["definition","planning","executing","verifying","completed","blocked","failed","cancelled"].includes(n)?n:"planning"};function wv(e,t){let n=_=>{let p=e.map(f=>f[_]).filter(f=>typeof f=="number"&&Number.isFinite(f));return p.length===0?null:p.reduce((f,m)=>f+m,0)},i=(_,p)=>jc(_[p])??0,r=n("total_duration"),o=n("total_tokens"),a=n("total_cost_usd"),s=n("total_cost_brl"),l={},c={empty:0,structured:0,rework:0};for(let _ of e){let p=d3(t,_.stage??_.status);l[p]=(l[p]??0)+1;let f=i(_,"rework_run_count")>0?"rework":i(_,"task_count")>0?"structured":"empty";c[f]=(c[f]??0)+1}let u=e.map(_=>({entity_id:String(_.id),title:String(_.title??_.id),duration_ms:jc(_.total_duration),total_tokens:jc(_.total_tokens),total_cost_usd:jc(_.total_cost_usd),cost_brl:jc(_.total_cost_brl),run_count:i(_,"invocation_count")})).toSorted((_,p)=>(p.duration_ms??-1)-(_.duration_ms??-1)||_.entity_id.localeCompare(p.entity_id)).slice(0,5).map(_=>({..._,duration_share:r===null||r===0||_.duration_ms===null?0:_.duration_ms/r})),d=e.flatMap(_=>typeof _.occurred_at=="string"?[_.occurred_at]:[]).toSorted().at(-1)??null;return{status_counts:l,classification_counts:c,entity_count:e.length,total_run_count:e.reduce((_,p)=>_+i(p,"invocation_count"),0),total_duration_ms:r,total_tokens:o,total_cost_usd:a,total_cost_brl:s,average_duration_ms:r===null||e.length===0?null:r/e.length,average_tokens:o===null||e.length===0?null:o/e.length,average_cost_usd:a===null||e.length===0?null:a/e.length,average_cost_brl:s===null||e.length===0?null:s/e.length,latest_created_at:d,top_entities:u}}var d0=require("node:child_process"),_0=require("node:crypto"),Av=require("node:path"),p0=require("node:util"),u0=".agents/dashboard/dashboard.config.json",m0=(0,p0.promisify)(d0.execFile);async function kp(e,t){let n=process.env.ZAIP_DASHBOARD_TITLE?.trim()||"Dashboard Zaip AIOS",i="auto";try{if(await e.exists(u0)){let r=JSON.parse(await e.readText(u0));typeof r.title=="string"&&r.title.trim()&&(n=r.title.trim()),typeof r.github_repository=="string"&&(i=r.github_repository.trim())}}catch{}if(i.toLowerCase()!=="auto")return{title:n,repository_name:Sp(i)??""};try{let{stdout:r}=await m0("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",windowsHide:!0});return{title:n,repository_name:Sp(r)??""}}catch{return{title:n,repository_name:""}}}function Sp(e){let t=e.trim(),n=t.match(/github\.com(?::|\/)([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i)??t.match(/^([^/:\s]+)\/([^/\s]+?)(?:\.git)?$/);return n?`${n[1]}/${n[2]}`:null}function Ep(e){return(0,_0.createHash)("sha256").update(`${(0,Av.resolve)(e)}:dashboard-sqlite`).digest("hex").slice(0,16)}var wp=17e4,Uo=class extends Error{constructor(){super(`Open-work reconciliation exceeded ${wp}ms. Canonical records may contain partial changes; the dashboard projection is being refreshed.`),this.name="ReconciliationCommandTimeoutError"}};async function f0(e,t,n={}){if(!await e.exists(".agents/runtime/bin/zaip.mjs"))throw new Error("ZAIP runtime is unavailable; open work could not be reconciled.");let i=(0,Av.resolve)(t,".agents","runtime","bin","zaip.mjs"),r;try{({stdout:r}=await m0(process.execPath,[i,"run","reconcile","--open","--json",...n.hostTerminalOnly?["--host-terminal-only"]:[]],{cwd:t,windowsHide:!0,maxBuffer:10*1024*1024,timeout:wp,killSignal:"SIGTERM"}))}catch(o){throw typeof o=="object"&&o!==null&&"killed"in o&&o.killed===!0?new Uo:o}return Tv(JSON.parse(r))}function Tv(e){let t=new Set,n=new Map,i=new Map,r=(f,m,g)=>{typeof m=="string"&&f.set(m,typeof g=="string"&&g.trim()?g:null)},o=typeof e=="object"&&e!==null?e:{},a=new Set(["completed","delivered","blocked","cancelled","failed"]),s=Array.isArray(o.reconciliations)?o.reconciliations:[];for(let f of s){if(typeof f!="object"||f===null)continue;let m=f,g=m.error,v=["tasks","changes","executions","specs","prds"].flatMap(S=>Array.isArray(m[S])?m[S]:[]);for(let S of v){if(typeof S!="object"||S===null)continue;let b=S;m.status==="closed"&&a.has(b.status)&&typeof b.id=="string"&&t.add(b.id),b.status==="blocked"?r(n,b.id,b.status_reason??g):m.status==="deferred"&&r(i,b.id,g)}}(Array.isArray(o.runs)?o.runs:[]).forEach(f=>{if(typeof f!="object"||f===null)return;let m=f.run?.run_id;typeof m=="string"&&t.add(m)}),(Array.isArray(o.orphaned_executions)?o.orphaned_executions:[]).forEach(f=>{r(n,f,"Execution orphaned after the reconciliation grace period.")}),(Array.isArray(o.orphaned_interaction_executions)?o.orphaned_interaction_executions:[]).forEach(f=>{r(n,f,"Interaction Execution orphaned after the reconciliation grace period.")});for(let f of["orphaned_owner_entities","orphaned_execution_entities"])for(let m of Array.isArray(o[f])?o[f]:[]){if(typeof m!="object"||m===null)continue;let g=m;typeof g.id!="string"||!a.has(g.status)||(t.add(g.id),g.status==="blocked"&&r(n,g.id,g.status_reason))}(Array.isArray(o.reconciliation_errors)?o.reconciliation_errors:[]).forEach(f=>{if(typeof f!="object"||f===null)return;let m=f;r(i,m.run_id,m.error)}),(Array.isArray(o.unresolved_running_run_ids)?o.unresolved_running_run_ids:[]).forEach(f=>{r(i,f,"Invocation is still running.")});let p=f=>[...f.entries()].map(([m,g])=>({id:m,reason:g})).sort((m,g)=>m.id.localeCompare(g.id));return{reconciled_ids:[...t].sort(),blocked:p(n),not_reconciled:p(i)}}function qa(e){return e.status==="completed"?"completed":e.status==="cancelled"?"cancelled":e.status==="failed"?"failed":e.status==="blocked"?"blocked":e.is_active===!0||e.status==="executing"?"executing":e.status==="verifying"?"verifying":(e.attempt_count??0)>0||e.started_at!=null||e.execution_started===!0?"executing":e.status==="draft"?null:e.status==="planned"?"ready":null}function Ap(e,t){if(e.lifecycle_status==="cancelled")return"cancelled";if(e.lifecycle_status==="failed")return"failed";if(e.lifecycle_status==="blocked")return"blocked";if(e.lifecycle_status==="delivered"||e.lifecycle_status==="completed")return"completed";if(e.lifecycle_status==="ready")return"ready";if(e.kind==="prd"&&e.lifecycle_status==="draft")return"definition";if(e.kind==="spec"&&e.lifecycle_status==="draft")return"planning";if(e.work_status==="cancelled")return"cancelled";if(e.work_status==="failed")return"failed";if(e.work_status==="blocked")return"blocked";if(e.work_status==="completed")return"completed";if(e.is_active||t.some(n=>e.task_ids.includes(n.id)&&n.is_active))return"executing";if(e.lifecycle_status==="verifying"||e.work_status==="verifying")return"verifying";if(e.work_status==="executing"){let n=t.filter(i=>e.task_ids.includes(i.id));return n.length>0&&n.every(i=>i.status==="verifying"||i.status==="completed")?"verifying":"executing"}return e.lifecycle_status==="active"?"executing":"planning"}We();function Tp(e){return/^\.agents\/(?:data|records)\/(?:executions\/.*\/execution\.md|changes\/.*\/change\.md|(?:changes|executions)\/.*\/decisions\/.*\.md)$/.test(e)}function xv(e){let t=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(e)?.[1];if(t===void 0)return null;try{let n=Ct(t);return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function Va(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function pt(e){return typeof e=="string"&&e.length>0?e:null}function Uc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function mn(e){let t=[...new Set(e.filter(n=>typeof n=="string"&&n.length>0&&n!=="unavailable"))];return t.length===0?null:t.length===1?t[0]:"mixed"}Wr();var _3=new Intl.DateTimeFormat("en",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"});function gt(e){let t=Object.fromEntries(_3.formatToParts(new Date(e)).filter(n=>n.type!=="literal").map(n=>[n.type,n.value]));return`${t.year}-${t.month}-${t.day}`}function xp(e){let t=new Set;for(let r of e){t.add(r.startMs),t.add(r.endMs);for(let o=r.startMs;o<r.endMs;){let a=Date.parse(`${gt(new Date(o).toISOString())}T03:00:00.000Z`)+864e5;if(a>=r.endMs)break;t.add(a),o=a}}let n=[...t].sort((r,o)=>r-o),i=new Map;for(let r=0;r<n.length-1;r+=1){let o=n[r],a=n[r+1],s=e.filter(u=>u.startMs<a&&u.endMs>o);if(s.length===0||a<=o)continue;let l=(a-o)/s.length,c=gt(new Date(o).toISOString());for(let u of s){let d=`${u.activityRowId}:${c}`,_=i.get(d);i.set(d,{activityRowId:u.activityRowId,day:c,value:(_?.value??0)+l})}}return[...i.values()]}var Ov=2*36e5;function g0(){let e=new Intl.DateTimeFormat("en-CA",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date),t=Object.fromEntries(e.map(i=>[i.type,i.value])),n=`${t.year}-${t.month}-${t.day}`;return{from:`${t.year}-${t.month}-01`,to:n}}function h0(e){let t=[],n=[],i=[];for(let r of e){if(!Tp(r.path))continue;let o=xv(r.content);if(o===null)continue;let a=pt(o.id),s=pt(o.created_at);if(!(a===null||s===null||Number.isNaN(Date.parse(s)))){if(/^\.agents\/(?:data|records)\/executions\/.*\/execution\.md$/.test(r.path)){let l=Va(o.origin),c=pt(l?.type),u=c==="interaction"?pt(l?.conversation_id):c==="task"?pt(l?.task_id):c==="spec"?pt(l?.spec_id):c==="prd"?pt(l?.prd_id):null;t.push({id:a,status:pt(o.status),kind:pt(o.kind),originType:c,originId:u,createdAt:s,finishedAt:pt(o.finished_at),sourcePath:r.path});continue}if(/^\.agents\/(?:data|records)\/changes\/.*\/change\.md$/.test(r.path)){let l=Va(o.source),c=pt(l?.type),u=c==="task"?pt(l?.task_id):c==="spec"?pt(l?.spec_id):c==="prd"?pt(l?.prd_id):null;if(c===null||u===null)continue;n.push({id:a,title:pt(o.title)??a,status:pt(o.status)??"unclassified",risk:pt(o.risk)??"unclassified",sourceType:c,sourceId:u,sourceSpecId:pt(l?.spec_id),sourcePrdId:pt(l?.prd_id),requirementIds:Uc(o.requirement_ids),acceptanceIds:Uc(o.acceptance_ids),taskIds:Uc(o.task_ids),result:pt(o.result),createdAt:s,sourcePath:r.path});continue}if(/^\.agents\/(?:data|records)\/(changes|executions)\/.*\/decisions\/.*\.md$/.test(r.path)){let l=o.origin,c=o.scope_type,u=pt(o.scope_id);if(l!=="human"&&l!=="agent"||c!=="change"&&c!=="execution"||u===null)continue;i.push({id:a,title:pt(o.title)??a,origin:l,scopeType:c,scopeId:u,createdAt:s,sourcePath:r.path})}}}return{executions:t,changes:n,decisions:i}}function Rv(e){let t=new Map;for(let n of e){let i=/^\.agents\/(?:data|records)\/(tasks|specs|prds|changes|executions|conversations)\//.exec(n.path);if(i===null)continue;let r=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(n.content)?.[1];if(r===void 0)continue;let o=l=>{let c=new RegExp(`^${l}:\\s*(.+?)\\s*$`,"m").exec(r)?.[1]?.trim();return c===void 0||c==="null"?null:c.replace(/^['"]|['"]$/g,"")},a=o("id");if(a===null)continue;let s=i[1]?.slice(0,-1);s!==void 0&&t.set(`${s}:${a}`,{kind:s,id:a,title:o("title"),status:o("status"),stage:s==="task"?qa({status:o("status"),spec_id:o("spec_id"),started_at:o("started_at"),attempt_count:Number(o("attempt_count")??0)}):o("stage"),risk:o("risk"),priority:o("priority"),specId:o("spec_id"),prdId:o("prd_id"),changeId:o("change_id"),occurredAt:o("created_at")??o("started_at")??o("recorded_at"),creationRunId:o("creation_run_id"),completedRunId:o("completed_run_id")})}return t}function y0(e,t){let n=new Map;for(let i of(e??"").split(/^ {2}- id: /m).slice(1)){let r=i.slice(0,i.indexOf(`
|
|
354
|
-
`)).trim(),o=/\bcodex_name:\s*([^\s#]+)/.exec(i)?.[1]??null;if(o===null)continue;let a=/persona:\s*\{\s*nome:\s*([^,}\s]+),\s*cargo:\s*([^,}\s]+)\s*\}/.exec(i),s=/\brole:\s*([^\s#]+)/.exec(i)?.[1]??null,l={catalogId:r,persona:a?.[1]??null,job:a?.[2]??null,role:s},c=new Set([o,r]);for(let u of i.matchAll(/^ {8}- kind:\s*(?:id|codex_name|codex_task_name)\s*\r?\n {10}value:\s*([^\s#]+)/gm)){let d=u[1];d!==void 0&&c.add(d)}for(let u of[...c])u.startsWith("agent-")&&c.add(`zaip-${u}`);for(let u of c)n.set(u,l)}return/^ {2}- id:\s*codex\s*$/m.test(t??"")&&n.set("codex",{catalogId:"client:codex",persona:"codex",job:"client_host",role:"host"}),n}function v0(e){return e.prd_id!==null&&e.execution_id===null||e.spec_id!==null&&e.execution_id===null||e.phase==="planning"||e.purpose==="planning"?"planning":e.execution_id!==null||e.task_id!==null||e.phase==="execution"||e.purpose==="implementation"?"development":"conversation"}function fn(e,t){let n=e.map(i=>i.tokens[t]).filter(i=>typeof i=="number");return n.length===0?null:n.reduce((i,r)=>i+r,0)}function Wa(e,t,n){return e==="openai"||e==="anthropic"?e:e==="unavailable"||t==="unavailable"||t===null?null:Jd(t,n,"")}function p3(e){return typeof e.duration_ms=="number"&&(e.duration_provenance==="observed"||e.duration_provenance==="reconciled"||e.duration_provenance==="legacy_inferred")}function m3(e){let t=e.flatMap(r=>{let o=r.source_started_at,a=r.source_finished_at,s=typeof o=="string"?Date.parse(o):Number.NaN,l=typeof a=="string"?Date.parse(a):Number.NaN;return typeof o=="string"&&typeof a=="string"&&Number.isFinite(s)&&Number.isFinite(l)&&l>s&&l-s<=Ov?[{start:o,end:a,startMs:s,endMs:l}]:[]});if(t.length===0)return null;let n=t.reduce((r,o)=>o.startMs<r.startMs?o:r),i=t.reduce((r,o)=>o.endMs>r.endMs?o:r);return i.endMs-n.startMs<=Ov?{start:n.start,end:i.end,duration:i.endMs-n.startMs}:null}function b0(e,t){let n=m3(e);if(n!==null)return{source:n.duration,effective:n.duration,provenance:"reconciled",sourceStartedAt:n.start,sourceFinishedAt:n.end};if(typeof t.finished?.duration_ms=="number"&&t.finished.duration_provenance!=="estimated"&&t.finished.duration_provenance!=="unavailable")return{source:t.finished.duration_ms,effective:t.finished.duration_ms,provenance:t.finished.duration_provenance??"observed",sourceStartedAt:null,sourceFinishedAt:null};let i=e.filter(p3);if(i.length>0){let a=i.reduce((l,c)=>l+(c.duration_ms??0),0),s=mn(i.map(l=>l.duration_provenance))??"observed";return{source:a,effective:a,provenance:s,sourceStartedAt:null,sourceFinishedAt:null}}let r=Date.parse(t.run.occurred_at),o=typeof t.finished?.occurred_at=="string"?Date.parse(t.finished.occurred_at):Number.NaN;return Number.isFinite(r)&&Number.isFinite(o)&&o>r&&o-r<=Ov?{source:null,effective:o-r,provenance:"reconciled",sourceStartedAt:null,sourceFinishedAt:null}:{source:null,effective:null,provenance:null,sourceStartedAt:null,sourceFinishedAt:null}}function S0(e){return e.flatMap(t=>{try{return[go.parse(JSON.parse(t.content))]}catch{return[]}}).sort((t,n)=>n.as_of.localeCompare(t.as_of))[0]??null}function Op(e,t,n,i){let r=0,o=0,a=!1,s=!1,l=!1,c=[],u=[];for(let _ of e){if(typeof _.cost.usd=="number"&&(r+=_.cost.usd,a=!0),typeof _.cost.brl=="number"&&(o+=_.cost.brl,s=!0),typeof _.cost.usd=="number"&&typeof _.cost.brl=="number"||_.tokens.total===null)continue;if(_.tokens.total===0){a=!0,s=!0;continue}let p=_.model??t.run.model;if(p===null||p==="unavailable")continue;let f=yo({provider:Wa(_.provider,p,t.run.client),model:p,usage:_.tokens,catalog:n,fxRate:i,serviceTier:_.runtime?.service_tier??null});typeof _.cost.usd!="number"&&f.estimated_usd!==null&&(r+=f.estimated_usd,a=!0,l=!0),typeof _.cost.brl!="number"&&f.estimated_brl!==null&&(o+=f.estimated_brl,s=!0,l=!0),f.pricing_model!==null&&c.push(f.pricing_model),f.pricing_source!==null&&u.push(f.pricing_source)}let d=fn(e,"total");return{usd:a?Math.round(r*1e6)/1e6:null,brl:s?Math.round(o*1e6)/1e6:null,method:d===0?"zero_no_llm_usage":l?"token_pricing_estimate":a||s?"canonical_recorded":null,pricingModel:mn(c),pricingSource:mn(u),fxRate:s?i?.rate??null:null}}function f3(e,t){if(t===null)return null;let n=t.toLowerCase(),i=r=>{let o=r.toLowerCase();if(n===o)return!0;let a=n.slice(o.length);return a.startsWith("@")||a.startsWith(":")||a.startsWith("/")||/^-\d{4}-\d{2}-\d{2}(?:$|[.:@/])/.test(a)};return e.models.find(r=>i(r.id)||r.aliases.some(o=>i(o)))??null}function k0(e,t,n,i){let r=e.model??t.run.model,o=Wa(e.provider,r,t.run.client),a=e.runtime?.service_tier??null,s=f3(n,r),l=r===null?null:yo({provider:o,model:r,usage:e.tokens,catalog:n,fxRate:i,serviceTier:a}),c=r===null?null:yo({provider:o,model:r,usage:e.tokens,catalog:n,fxRate:i,serviceTier:"default"}),u=s?.long_context_threshold_tokens!==null&&s?.long_context_threshold_tokens!==void 0&&(e.tokens.input??0)>s.long_context_threshold_tokens,d=a==="priority"||a==="fast",_=d&&!u,p=s?_?s.priority_input_per_million_usd??null:s.input_per_million_usd:null,f=s?_?s.priority_cached_input_per_million_usd??null:s.cached_input_per_million_usd:null,m=s?_?s.priority_output_per_million_usd??null:s.output_per_million_usd:null,g=s?_?s.priority_reasoning_per_million_usd??s.priority_output_per_million_usd??null:s.reasoning_per_million_usd??s.output_per_million_usd:null,v=l?.estimated_usd!==null&&l!==null?l:c,S=v?.estimated_usd??null,b=c?.estimated_usd??null,y=e.cost.usd,k=y??S,M=e.cost.brl??l?.estimated_brl??(k!==null&&i!==null?Math.round(k*i.rate*1e6)/1e6:null);return{provider:o,model:r,serviceTier:a,uncachedInputTokens:e.tokens.input===null?null:Math.max(e.tokens.input-(e.tokens.cached_input??0),0),visibleOutputTokens:e.tokens.output===null?null:Math.max(e.tokens.output-(e.tokens.reasoning??0),0),inputRate:p,cachedRate:f,outputRate:m,reasoningRate:g,contextInputMultiplier:s?u?s.long_context_input_multiplier:1:null,contextOutputMultiplier:s?u?s.long_context_output_multiplier:1:null,speedCostMultiplier:S!==null&&b!==null&&b>0?Math.round(S/b*1e3)/1e3:null,pricingScenario:d&&u?"standard_long_context_fallback":d?"priority":"standard",standardUsd:b,speedUpliftUsd:S!==null&&b!==null?Math.round((S-b)*1e6)/1e6:null,inputUsd:v?.input_usd??null,cachedInputUsd:v?.cached_input_usd??null,outputUsd:v?.output_usd??null,reasoningUsd:v?.reasoning_usd??null,calculatedUsd:S,recordedUsd:y,effectiveUsd:k,effectiveBrl:M,varianceUsd:y!==null&&S!==null?Math.round((y-S)*1e6)/1e6:null,pricingModel:v?.pricing_model??null,pricingSource:v?.pricing_source??null,fxRate:e.cost.fx_rate??i?.rate??null}}function ot(e){return e==null?null:/^\d{4}-\d{2}-\d{2}$/.test(e)?e:gt(e)}function Cv(e,t){let n=e.map(i=>i[t]).filter(i=>typeof i=="number"&&Number.isFinite(i));return n.length===0?null:n.reduce((i,r)=>i+r,0)}function E0(e,t){let n=e.includes("/artifacts/evidence/")?"evidence":e.includes("/artifacts/validations/")||e.includes("/artifacts/tests/")?"validation":null;if(n===null)return null;let i=/^---\r?\n([\s\S]*?)\r?\n---/.exec(t)?.[1]??"",r=a=>{let s=new RegExp(`^${a}:\\s*['"]?(.+?)['"]?\\s*$`,"m").exec(i)?.[1]?.trim();return s===void 0||s==="null"?null:s},o=r("observed_at")??r("executed_at")??r("created_at")??r("recorded_at");return o===null||Number.isNaN(Date.parse(o))?null:{kind:n,id:r("id")??e.slice(e.lastIndexOf("/")+1,-3),occurredAt:o,occurredDaySp:gt(o),taskId:r("task_id"),changeId:r("change_id"),runId:r("run_id")}}var Zv=require("node:sqlite");We();var g3=["prd_count","spec_count","task_count","test_count","evidence_count"],Rp=()=>({prd_count:0,spec_count:0,task_count:0,test_count:0,evidence_count:0});function h3(e,t){let n=["a.payload_type IS NULL","a.run_id IS NOT NULL","a.zaip_agent IS NOT NULL"],i=[];for(let p of["from","to"])t[p]&&(n.push(`a.occurred_day_sp ${p==="from"?">=":"<="} ?`),i.push(t[p].slice(0,10)));for(let p of["agent","phase","status"])t[p]&&(n.push(`a.${p==="agent"?"zaip_agent":p}=?`),i.push(t[p]));t.risk&&(n.push("EXISTS (SELECT 1 FROM zaip_aios_activities t WHERE t.payload_type='work_item' AND json_extract(t.payload_json,'$.entity_kind')='task' AND json_extract(t.payload_json,'$.id')=a.task_id AND json_extract(t.payload_json,'$.risk')=?)"),i.push(t.risk)),(t.priority||t.workType)&&n.push("0"),t.origin&&n.push(t.origin==="prd"?"a.prd_id IS NOT NULL":t.origin==="spec"?"a.prd_id IS NULL AND a.spec_id IS NOT NULL":t.origin==="task"?"a.prd_id IS NULL AND a.spec_id IS NULL AND a.task_id IS NOT NULL":"a.prd_id IS NULL AND a.spec_id IS NULL AND a.task_id IS NULL");let r=[];for(let p of["provider","model"])t[p]&&(r.push(`COALESCE(u.${p},'unavailable')=?`),i.push(t[p]));r.length&&n.push(`EXISTS (SELECT 1 FROM invocation_usage u WHERE u.agent_invocation_id=a.agent_invocation_id AND ${r.join(" AND ")})`),t.query&&(n.push("(a.zaip_agent LIKE ? OR a.zaip_agent_persona LIKE ? OR a.zaip_agent_job LIKE ?)"),i.push(...Array(3).fill(`%${t.query}%`)));let o=e.prepare(`SELECT a.run_id, MIN(a.zaip_agent) AS agent FROM zaip_aios_activities a WHERE ${n.join(" AND ")} GROUP BY a.run_id HAVING COUNT(DISTINCT a.zaip_agent)=1`).all(...i),a=new Map(o.map(p=>[p.run_id,p.agent])),s=new Map,l=new Set,c=t.from?.slice(0,10)??"0000-01-01",u=t.to?.slice(0,10)??"9999-12-31",d=e.prepare(`WITH files AS (
|
|
354
|
+
`)).trim(),o=/\bcodex_name:\s*([^\s#]+)/.exec(i)?.[1]??null;if(o===null)continue;let a=/persona:\s*\{\s*nome:\s*([^,}\s]+),\s*cargo:\s*([^,}\s]+)\s*\}/.exec(i),s=/\brole:\s*([^\s#]+)/.exec(i)?.[1]??null,l={catalogId:r,persona:a?.[1]??null,job:a?.[2]??null,role:s},c=new Set([o,r]);for(let u of i.matchAll(/^ {8}- kind:\s*(?:id|codex_name|codex_task_name)\s*\r?\n {10}value:\s*([^\s#]+)/gm)){let d=u[1];d!==void 0&&c.add(d)}for(let u of[...c])u.startsWith("agent-")&&c.add(`zaip-${u}`);for(let u of c)n.set(u,l)}return/^ {2}- id:\s*codex\s*$/m.test(t??"")&&n.set("codex",{catalogId:"client:codex",persona:"codex",job:"client_host",role:"host"}),n}function v0(e){return e.prd_id!==null&&e.execution_id===null||e.spec_id!==null&&e.execution_id===null||e.phase==="planning"||e.purpose==="planning"?"planning":e.execution_id!==null||e.task_id!==null||e.phase==="execution"||e.purpose==="implementation"?"development":"conversation"}function fn(e,t){let n=e.map(i=>i.tokens[t]).filter(i=>typeof i=="number");return n.length===0?null:n.reduce((i,r)=>i+r,0)}function Wa(e,t,n){return e==="openai"||e==="anthropic"?e:e==="unavailable"||t==="unavailable"||t===null?null:Jd(t,n,"")}function p3(e){return typeof e.duration_ms=="number"&&(e.duration_provenance==="observed"||e.duration_provenance==="reconciled"||e.duration_provenance==="legacy_inferred")}function m3(e){let t=e.flatMap(r=>{let o=r.source_started_at,a=r.source_finished_at,s=typeof o=="string"?Date.parse(o):Number.NaN,l=typeof a=="string"?Date.parse(a):Number.NaN;return typeof o=="string"&&typeof a=="string"&&Number.isFinite(s)&&Number.isFinite(l)&&l>s&&l-s<=Ov?[{start:o,end:a,startMs:s,endMs:l}]:[]});if(t.length===0)return null;let n=t.reduce((r,o)=>o.startMs<r.startMs?o:r),i=t.reduce((r,o)=>o.endMs>r.endMs?o:r);return i.endMs-n.startMs<=Ov?{start:n.start,end:i.end,duration:i.endMs-n.startMs}:null}function b0(e,t){let n=m3(e);if(n!==null)return{source:n.duration,effective:n.duration,provenance:"reconciled",sourceStartedAt:n.start,sourceFinishedAt:n.end};if(typeof t.finished?.duration_ms=="number"&&t.finished.duration_provenance!=="estimated"&&t.finished.duration_provenance!=="unavailable")return{source:t.finished.duration_ms,effective:t.finished.duration_ms,provenance:t.finished.duration_provenance??"observed",sourceStartedAt:null,sourceFinishedAt:null};let i=e.filter(p3);if(i.length>0){let a=i.reduce((l,c)=>l+(c.duration_ms??0),0),s=mn(i.map(l=>l.duration_provenance))??"observed";return{source:a,effective:a,provenance:s,sourceStartedAt:null,sourceFinishedAt:null}}let r=Date.parse(t.run.occurred_at),o=typeof t.finished?.occurred_at=="string"?Date.parse(t.finished.occurred_at):Number.NaN;return Number.isFinite(r)&&Number.isFinite(o)&&o>r&&o-r<=Ov?{source:null,effective:o-r,provenance:"reconciled",sourceStartedAt:null,sourceFinishedAt:null}:{source:null,effective:null,provenance:null,sourceStartedAt:null,sourceFinishedAt:null}}function S0(e){return e.flatMap(t=>{try{return[go.parse(JSON.parse(t.content))]}catch{return[]}}).sort((t,n)=>n.as_of.localeCompare(t.as_of))[0]??null}function Op(e,t,n,i){let r=0,o=0,a=!1,s=!1,l=!1,c=[],u=[];for(let _ of e){if(typeof _.cost.usd=="number"&&(r+=_.cost.usd,a=!0),typeof _.cost.brl=="number"&&(o+=_.cost.brl,s=!0),typeof _.cost.usd=="number"&&typeof _.cost.brl=="number"||_.tokens.total===null)continue;if(_.tokens.total===0){a=!0,s=!0;continue}let p=_.model??t.run.model;if(p===null||p==="unavailable")continue;let f=yo({provider:Wa(_.provider,p,t.run.client),model:p,usage:_.tokens,catalog:n,fxRate:i,serviceTier:_.runtime?.service_tier??null});typeof _.cost.usd!="number"&&f.estimated_usd!==null&&(r+=f.estimated_usd,a=!0,l=!0),typeof _.cost.brl!="number"&&f.estimated_brl!==null&&(o+=f.estimated_brl,s=!0,l=!0),f.pricing_model!==null&&c.push(f.pricing_model),f.pricing_source!==null&&u.push(f.pricing_source)}let d=fn(e,"total");return{usd:a?Math.round(r*1e6)/1e6:null,brl:s?Math.round(o*1e6)/1e6:null,method:d===0?"zero_no_llm_usage":l?"token_pricing_estimate":a||s?"canonical_recorded":null,pricingModel:mn(c),pricingSource:mn(u),fxRate:s?i?.rate??null:null}}function f3(e,t){if(t===null)return null;let n=t.toLowerCase(),i=r=>{let o=r.toLowerCase();if(n===o)return!0;let a=n.slice(o.length);return a.startsWith("@")||a.startsWith(":")||a.startsWith("/")||/^-\d{4}-\d{2}-\d{2}(?:$|[.:@/])/.test(a)};return e.models.find(r=>i(r.id)||r.aliases.some(o=>i(o)))??null}function k0(e,t,n,i){let r=e.model??t.run.model,o=Wa(e.provider,r,t.run.client),a=e.runtime?.service_tier??null,s=f3(n,r),l=r===null?null:yo({provider:o,model:r,usage:e.tokens,catalog:n,fxRate:i,serviceTier:a}),c=r===null?null:yo({provider:o,model:r,usage:e.tokens,catalog:n,fxRate:i,serviceTier:"default"}),u=s?.long_context_threshold_tokens!==null&&s?.long_context_threshold_tokens!==void 0&&(e.tokens.input??0)>s.long_context_threshold_tokens,d=a==="priority"||a==="fast",_=d&&!u,p=s?_?s.priority_input_per_million_usd??null:s.input_per_million_usd:null,f=s?_?s.priority_cached_input_per_million_usd??null:s.cached_input_per_million_usd:null,m=s?_?s.priority_output_per_million_usd??null:s.output_per_million_usd:null,g=s?_?s.priority_reasoning_per_million_usd??s.priority_output_per_million_usd??null:s.reasoning_per_million_usd??s.output_per_million_usd:null,v=l?.estimated_usd!==null&&l!==null?l:c,S=v?.estimated_usd??null,b=c?.estimated_usd??null,y=e.cost.usd,k=y??S,M=e.cost.brl??l?.estimated_brl??(k!==null&&i!==null?Math.round(k*i.rate*1e6)/1e6:null);return{provider:o,model:r,serviceTier:a,uncachedInputTokens:e.tokens.input===null?null:Math.max(e.tokens.input-(e.tokens.cached_input??0),0),visibleOutputTokens:e.tokens.output===null?null:Math.max(e.tokens.output-(e.tokens.reasoning??0),0),inputRate:p,cachedRate:f,outputRate:m,reasoningRate:g,contextInputMultiplier:s?u?s.long_context_input_multiplier:1:null,contextOutputMultiplier:s?u?s.long_context_output_multiplier:1:null,speedCostMultiplier:S!==null&&b!==null&&b>0?Math.round(S/b*1e3)/1e3:null,pricingScenario:d&&u?"standard_long_context_fallback":d?"priority":"standard",standardUsd:b,speedUpliftUsd:S!==null&&b!==null?Math.round((S-b)*1e6)/1e6:null,inputUsd:v?.input_usd??null,cachedInputUsd:v?.cached_input_usd??null,outputUsd:v?.output_usd??null,reasoningUsd:v?.reasoning_usd??null,calculatedUsd:S,recordedUsd:y,effectiveUsd:k,effectiveBrl:M,varianceUsd:y!==null&&S!==null?Math.round((y-S)*1e6)/1e6:null,pricingModel:v?.pricing_model??s?.id??null,pricingSource:v?.pricing_source??s?.source_label??null,fxRate:e.cost.fx_rate??i?.rate??null}}function ot(e){return e==null?null:/^\d{4}-\d{2}-\d{2}$/.test(e)?e:gt(e)}function Cv(e,t){let n=e.map(i=>i[t]).filter(i=>typeof i=="number"&&Number.isFinite(i));return n.length===0?null:n.reduce((i,r)=>i+r,0)}function E0(e,t){let n=e.includes("/artifacts/evidence/")?"evidence":e.includes("/artifacts/validations/")||e.includes("/artifacts/tests/")?"validation":null;if(n===null)return null;let i=/^---\r?\n([\s\S]*?)\r?\n---/.exec(t)?.[1]??"",r=a=>{let s=new RegExp(`^${a}:\\s*['"]?(.+?)['"]?\\s*$`,"m").exec(i)?.[1]?.trim();return s===void 0||s==="null"?null:s},o=r("observed_at")??r("executed_at")??r("created_at")??r("recorded_at");return o===null||Number.isNaN(Date.parse(o))?null:{kind:n,id:r("id")??e.slice(e.lastIndexOf("/")+1,-3),occurredAt:o,occurredDaySp:gt(o),taskId:r("task_id"),changeId:r("change_id"),runId:r("run_id")}}var Zv=require("node:sqlite");We();var g3=["prd_count","spec_count","task_count","test_count","evidence_count"],Rp=()=>({prd_count:0,spec_count:0,task_count:0,test_count:0,evidence_count:0});function h3(e,t){let n=["a.payload_type IS NULL","a.run_id IS NOT NULL","a.zaip_agent IS NOT NULL"],i=[];for(let p of["from","to"])t[p]&&(n.push(`a.occurred_day_sp ${p==="from"?">=":"<="} ?`),i.push(t[p].slice(0,10)));for(let p of["agent","phase","status"])t[p]&&(n.push(`a.${p==="agent"?"zaip_agent":p}=?`),i.push(t[p]));t.risk&&(n.push("EXISTS (SELECT 1 FROM zaip_aios_activities t WHERE t.payload_type='work_item' AND json_extract(t.payload_json,'$.entity_kind')='task' AND json_extract(t.payload_json,'$.id')=a.task_id AND json_extract(t.payload_json,'$.risk')=?)"),i.push(t.risk)),(t.priority||t.workType)&&n.push("0"),t.origin&&n.push(t.origin==="prd"?"a.prd_id IS NOT NULL":t.origin==="spec"?"a.prd_id IS NULL AND a.spec_id IS NOT NULL":t.origin==="task"?"a.prd_id IS NULL AND a.spec_id IS NULL AND a.task_id IS NOT NULL":"a.prd_id IS NULL AND a.spec_id IS NULL AND a.task_id IS NULL");let r=[];for(let p of["provider","model"])t[p]&&(r.push(`COALESCE(u.${p},'unavailable')=?`),i.push(t[p]));r.length&&n.push(`EXISTS (SELECT 1 FROM invocation_usage u WHERE u.agent_invocation_id=a.agent_invocation_id AND ${r.join(" AND ")})`),t.query&&(n.push("(a.zaip_agent LIKE ? OR a.zaip_agent_persona LIKE ? OR a.zaip_agent_job LIKE ?)"),i.push(...Array(3).fill(`%${t.query}%`)));let o=e.prepare(`SELECT a.run_id, MIN(a.zaip_agent) AS agent FROM zaip_aios_activities a WHERE ${n.join(" AND ")} GROUP BY a.run_id HAVING COUNT(DISTINCT a.zaip_agent)=1`).all(...i),a=new Map(o.map(p=>[p.run_id,p.agent])),s=new Map,l=new Set,c=t.from?.slice(0,10)??"0000-01-01",u=t.to?.slice(0,10)??"9999-12-31",d=e.prepare(`WITH files AS (
|
|
355
355
|
SELECT json_extract(payload_json,'$.path') path,
|
|
356
356
|
json_extract(payload_json,'$.artifact_kind') artifact_kind,
|
|
357
357
|
json_extract(payload_json,'$.artifact_id') artifact_id,
|