@zaip-ai/cli 3.4.0 → 3.6.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.
Files changed (148) hide show
  1. package/dist/services/adapters.d.ts +1 -1
  2. package/dist/services/adapters.js +1 -1
  3. package/dist/services/stack-install.d.ts.map +1 -1
  4. package/dist/services/stack-install.js +19 -9
  5. package/dist/services/stack-install.js.map +1 -1
  6. package/dist/services/stack-node.d.ts.map +1 -1
  7. package/dist/services/stack-node.js +1 -1
  8. package/dist/services/stack-node.js.map +1 -1
  9. package/package.json +1 -1
  10. package/templates/.agents/config/agents/discovery.json +1 -1
  11. package/templates/.agents/dashboard/.zaip-managed.json +95 -51
  12. package/templates/.agents/dashboard/apps/frontend/dist/assets/DashboardHelpDialog-BDQR0U4a.js +2938 -0
  13. package/templates/.agents/dashboard/apps/frontend/dist/assets/DashboardHelpDialog-DRI_XwUf.css +1 -0
  14. package/templates/.agents/dashboard/apps/frontend/dist/assets/{ProjectSettingsPage-B9GWkEyN.css → ProjectSettingsPage-CQMhvzvJ.css} +1 -1
  15. package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-D46WWIKr.js +3 -0
  16. package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-OulA4CoX.js +3 -0
  17. package/templates/.agents/dashboard/apps/frontend/dist/assets/{TraceabilityWorkspace-CqK3Psfy.js → TraceabilityWorkspace-BKBpJyLh.js} +1 -1
  18. package/templates/.agents/dashboard/apps/frontend/dist/assets/TraceabilityWorkspace-Ckxk_izu.js +1 -0
  19. package/templates/.agents/dashboard/apps/frontend/dist/assets/{index-Cl5EWx8R.js → index-Bas2TVju.js} +2 -2
  20. package/templates/.agents/dashboard/apps/frontend/dist/assets/index-CqfSgtk9.js +2 -0
  21. package/templates/.agents/dashboard/apps/frontend/dist/assets/index-CxrG_wRI.css +1 -0
  22. package/templates/.agents/dashboard/apps/frontend/dist/assets/index-OBJXZOwe.css +1 -0
  23. package/templates/.agents/dashboard/apps/frontend/dist/index.html +2 -2
  24. package/templates/.agents/dashboard/apps/frontend/package.json +1 -1
  25. package/templates/.agents/dashboard/apps/frontend/src/AppDashboardContent.tsx +0 -2
  26. package/templates/.agents/dashboard/apps/frontend/src/DashboardGlobalSettings.tsx +7 -0
  27. package/templates/.agents/dashboard/apps/frontend/src/ProjectSettingsCard.tsx +18 -0
  28. package/templates/.agents/dashboard/apps/frontend/src/ProjectSettingsField.tsx +21 -0
  29. package/templates/.agents/dashboard/apps/frontend/src/ProjectSettingsPage.dom.test.ts +12 -1
  30. package/templates/.agents/dashboard/apps/frontend/src/ProjectSettingsPage.tsx +16 -28
  31. package/templates/.agents/dashboard/apps/frontend/src/ProjectStackEditor.tsx +25 -4
  32. package/templates/.agents/dashboard/apps/frontend/src/WorkspaceStatus.test.tsx +26 -8
  33. package/templates/.agents/dashboard/apps/frontend/src/WorkspaceStatus.tsx +9 -28
  34. package/templates/.agents/dashboard/apps/frontend/src/cost-calculation-guide.css +1 -1
  35. package/templates/.agents/dashboard/apps/frontend/src/dashboard-help-dialog.css +2 -2
  36. package/templates/.agents/dashboard/apps/frontend/src/operations-entity-page-projection.ts +4 -1
  37. package/templates/.agents/dashboard/apps/frontend/src/operations-period-contract.test.ts +20 -9
  38. package/templates/.agents/dashboard/apps/frontend/src/pricing-settings-dialog.css +5 -5
  39. package/templates/.agents/dashboard/apps/frontend/src/project-settings-copy.ts +13 -4
  40. package/templates/.agents/dashboard/apps/frontend/src/project-settings-model.ts +25 -1
  41. package/templates/.agents/dashboard/apps/frontend/src/project-settings-workspace.css +28 -0
  42. package/templates/.agents/dashboard/apps/frontend/src/project-settings.test.ts +39 -0
  43. package/templates/.agents/dashboard/apps/frontend/src/use-app-work-board.test.ts +1 -1
  44. package/templates/.agents/dashboard/apps/frontend/src/workspace-status.css +1 -14
  45. package/templates/.agents/dashboard/modules/cost-monitor/package.json +1 -1
  46. package/templates/.agents/dashboard/modules/operations/package.json +1 -1
  47. package/templates/.agents/dashboard/modules/operations/src/react/OperationsEntityFilters.tsx +1 -1
  48. package/templates/.agents/dashboard/modules/operations/src/react/PagedWorkList.tsx +2 -2
  49. package/templates/.agents/dashboard/modules/traceability/package.json +1 -1
  50. package/templates/.agents/dashboard/packages/branding/package.json +1 -1
  51. package/templates/.agents/dashboard/packages/contracts/package.json +1 -1
  52. package/templates/.agents/dashboard/packages/data-export/package.json +1 -1
  53. package/templates/.agents/dashboard/packages/local-runtime/dist/server.cjs +2 -2
  54. package/templates/.agents/dashboard/packages/local-runtime/dist/sqlite-read-model.cjs +73 -73
  55. package/templates/.agents/dashboard/packages/local-runtime/package.json +1 -1
  56. package/templates/.agents/dashboard/packages/local-runtime/scripts/validate-sqlite-read-model.mjs +38 -6
  57. package/templates/.agents/dashboard/packages/local-runtime/server.mjs +2 -2
  58. package/templates/.agents/dashboard/packages/local-runtime/src/project-settings.test.ts +3 -4
  59. package/templates/.agents/dashboard/packages/local-runtime/src/project-settings.ts +1 -1
  60. package/templates/.agents/dashboard/packages/local-runtime/src/server-snapshot-refresh.test.ts +2 -2
  61. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-cost-filter-matrix.test.ts +1 -1
  62. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-pricing-provenance.test.ts +75 -0
  63. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-canonical.ts +2 -2
  64. package/templates/.agents/dashboard/packages/ui/package.json +1 -1
  65. package/templates/.agents/dashboard/tests/e2e/package.json +1 -1
  66. package/templates/.agents/dashboard/tests/e2e/specs/dashboard.spec.ts +4 -6
  67. package/templates/.agents/dashboard/tests/e2e/specs/work-board-hydration.ts +38 -0
  68. package/templates/.agents/design/.zaip-managed.json +83 -51
  69. package/templates/.agents/design/apps/catalog/dist/assets/index-Cv4VfxTQ.js +72 -0
  70. package/templates/.agents/design/apps/catalog/dist/assets/index-D1JaPXfV.css +1 -0
  71. package/templates/.agents/design/apps/catalog/dist/assets/index-D2miO4-O.js +72 -0
  72. package/templates/.agents/design/apps/catalog/dist/assets/index-mvD5mwcC.js +72 -0
  73. package/templates/.agents/design/apps/catalog/dist/index.html +2 -2
  74. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{CatalogShell-CvaciY0C.js → CatalogShell-BJ8b4xZr.js} +1 -1
  75. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{Color-6AOWCN3U-DwBV1A1Y.js → Color-6AOWCN3U-CQLHzznn.js} +1 -1
  76. package/templates/.agents/design/apps/catalog/dist/storybook/assets/Components.stories-kxWwSKin.js +146 -0
  77. package/templates/.agents/design/apps/catalog/dist/storybook/assets/DashboardFilters.stories-Chm_dXV7.js +9 -0
  78. package/templates/.agents/design/apps/catalog/dist/storybook/assets/DashboardFiltersSpecimen-9CaCbGIZ.js +1 -0
  79. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{DesignSystem.stories-2OCgtT0I.js → DesignSystem.stories-ED52wFjY.js} +1 -1
  80. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{DocsRenderer-JROSPFPF-CODg0rSl.js → DocsRenderer-JROSPFPF-BcLgM80v.js} +4 -4
  81. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{Primitives-BmeKjJW4.js → Primitives-DV6Bpudf.js} +1 -1
  82. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{WithTooltip-7X4HQR7L-C5MI-3uZ.js → WithTooltip-7X4HQR7L-BKNiAz_E.js} +1 -1
  83. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{WorkspaceStatus.stories-Tb_iQqVK.js → WorkspaceStatus.stories-BL19HGOo.js} +2 -2
  84. package/templates/.agents/design/apps/catalog/dist/storybook/assets/WorkspaceStatusSpecimen-DQnSS6s9.js +1 -0
  85. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{chunk-DRQKCCAG-KSn75jcy.js → chunk-DRQKCCAG-DZBcXL-p.js} +1 -1
  86. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{chunk-W22LQPXL-C4LS1Thf.js → chunk-W22LQPXL-CF3y2mfo.js} +1 -1
  87. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{components-DV1BRgMY.js → components-BVjxMRGq.js} +5 -5
  88. package/templates/.agents/design/apps/catalog/dist/storybook/assets/formatter-L2YTDE3Q-Do9sjqiW.js +1 -0
  89. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{iframe-CBbPFx5G.js → iframe-CTWGZcEe.js} +4 -4
  90. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{react-18-C9IPGXtb.js → react-18-B9_a4mHb.js} +1 -1
  91. package/templates/.agents/design/apps/catalog/dist/storybook/assets/react-NrUxok8K.js +1 -0
  92. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{syntaxhighlighter-YFXUGROL-ZgDQjyWI.js → syntaxhighlighter-YFXUGROL-F_p8E2xc.js} +1 -1
  93. package/templates/.agents/design/apps/catalog/dist/storybook/assets/{theming-Cx9-gH6l.js → theming-fbSD9ZLF.js} +1 -1
  94. package/templates/.agents/design/apps/catalog/dist/storybook/iframe.html +1 -1
  95. package/templates/.agents/design/apps/catalog/dist/storybook/index.json +1 -1
  96. package/templates/.agents/design/apps/catalog/dist/storybook/sb-addons/a11y-2/manager-bundle.js +3 -3
  97. package/templates/.agents/design/apps/catalog/dist/storybook/sb-addons/docs-1/manager-bundle.js +4 -4
  98. package/templates/.agents/design/apps/catalog/dist/storybook/sb-addons/storybook-core-server-presets-0/common-manager-bundle.js +60 -60
  99. package/templates/.agents/design/apps/catalog/package.json +1 -1
  100. package/templates/.agents/design/apps/catalog/src/components/DashboardFiltersSpecimen.tsx +26 -21
  101. package/templates/.agents/design/apps/catalog/src/components/StackVersionFieldSpecimen.tsx +66 -0
  102. package/templates/.agents/design/apps/catalog/src/components/WorkspaceStatusSpecimen.tsx +23 -7
  103. package/templates/.agents/design/apps/catalog/src/pages/ComponentsPage.tsx +20 -6
  104. package/templates/.agents/design/apps/catalog/src/stories/Components.stories.tsx +14 -0
  105. package/templates/.agents/design/apps/catalog/src/stories/WorkspaceStatus.stories.tsx +5 -2
  106. package/templates/.agents/design/apps/catalog/src/styles/components.css +1 -1
  107. package/templates/.agents/design/apps/catalog/src/styles/stack-version-field.css +79 -0
  108. package/templates/.agents/design/packages/local-runtime/package.json +1 -1
  109. package/templates/.agents/requirements/autonomous-assurance.md +1 -1
  110. package/templates/.agents/requirements/cloud-hostinger-autonomy.md +1 -1
  111. package/templates/.agents/requirements/comparative-audit.md +1 -1
  112. package/templates/.agents/requirements/context-engine.md +1 -1
  113. package/templates/.agents/requirements/cost-observability.md +1 -1
  114. package/templates/.agents/requirements/dashboard-launch.md +1 -1
  115. package/templates/.agents/requirements/data-export.md +1 -1
  116. package/templates/.agents/requirements/design-system.md +1 -1
  117. package/templates/.agents/requirements/execution-engine.md +1 -1
  118. package/templates/.agents/requirements/kanban-dashboard.md +1 -1
  119. package/templates/.agents/requirements/model-orchestration.md +1 -1
  120. package/templates/.agents/requirements/public-distribution.md +1 -1
  121. package/templates/.agents/requirements/software-architecture.md +1 -1
  122. package/templates/.agents/requirements/strategic-improvements.md +1 -1
  123. package/templates/.agents/requirements/work-lifecycle.md +1 -1
  124. package/templates/.agents/requirements/zaip-strategic-95.md +1 -1
  125. package/templates/.agents/rules/workflow.md +1 -1
  126. package/templates/.agents/runtime/VERSION +1 -1
  127. package/templates/.agents/runtime/bin/zaip.mjs +46 -15
  128. package/templates/.agents/runtime/checksums.sha256 +5 -5
  129. package/templates/.agents/runtime/manifest.json +1 -1
  130. package/templates/.agents/runtime/provenance.json +4 -4
  131. package/templates/.agents/runtime/sbom.cdx.json +1 -1
  132. package/templates/.agents/skills/zaip-skill-execution/SKILL.md +1 -0
  133. package/templates/.agents/skills/zaip-skill-github-deploy/SKILL.md +5 -4
  134. package/templates/.agents/skills/zaip-skill-github-deploy/agents/openai.yaml +1 -1
  135. package/templates/.agents/skills/zaip-skill-github-deploy/references/deployment-workflow.md +7 -7
  136. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/consumer-release-preparation.mjs +1 -2
  137. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/consumer-release-preparation.test.mjs +9 -1
  138. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/github-deploy-contract.test.mjs +25 -0
  139. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/preflight.mjs +2 -6
  140. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/preflight.test.mjs +15 -1
  141. package/templates/.agents/zaip-aios/VERSION +1 -1
  142. package/templates/template-manifest.json +216 -140
  143. package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-DVCPPV75.js +0 -3
  144. package/templates/.agents/dashboard/apps/frontend/dist/assets/index-Cwylbh_N.css +0 -1
  145. package/templates/.agents/design/apps/catalog/dist/storybook/assets/Components.stories-3dqK5g3e.js +0 -142
  146. package/templates/.agents/design/apps/catalog/dist/storybook/assets/WorkspaceStatusSpecimen-CD54pw0-.js +0 -1
  147. package/templates/.agents/design/apps/catalog/dist/storybook/assets/formatter-L2YTDE3Q-BU_68im1.js +0 -1
  148. package/templates/.agents/design/apps/catalog/dist/storybook/assets/react-CEv2qkJT.js +0 -1
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaip-ai/dashboard-local-runtime",
3
- "version": "3.4.0",
3
+ "version": "3.6.0",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "scripts": {
@@ -64,6 +64,31 @@ try {
64
64
  SUM(total_tokens IS NULL) AS missing_tokens_count,
65
65
  SUM(cost_usd IS NULL OR cost_brl IS NULL) AS missing_effective_cost_count,
66
66
  SUM(calculated_cost_usd IS NULL) AS missing_calculated_cost_count,
67
+ SUM(
68
+ (cost_usd IS NULL OR cost_brl IS NULL)
69
+ AND total_tokens IS NOT NULL
70
+ AND calculated_cost_usd IS NULL
71
+ AND pricing_model IS NOT NULL
72
+ AND pricing_source IS NOT NULL
73
+ ) AS known_token_explicitly_unpriced_count,
74
+ SUM(
75
+ total_tokens IS NOT NULL
76
+ AND calculated_cost_usd IS NULL
77
+ AND cost_usd IS NOT NULL
78
+ AND cost_brl IS NOT NULL
79
+ ) AS recorded_cost_without_calculation_count,
80
+ SUM(
81
+ calculated_cost_usd IS NULL
82
+ AND (cost_usd IS NULL OR cost_brl IS NULL)
83
+ AND NOT (
84
+ total_tokens IS NULL
85
+ OR (
86
+ total_tokens IS NOT NULL
87
+ AND pricing_model IS NOT NULL
88
+ AND pricing_source IS NOT NULL
89
+ )
90
+ )
91
+ ) AS unexplained_unavailable_cost_count,
67
92
  SUM(ABS(
68
93
  COALESCE(input_cost_usd, 0) +
69
94
  COALESCE(cached_input_cost_usd, 0) +
@@ -87,8 +112,8 @@ try {
87
112
  );
88
113
  assert.equal(
89
114
  metrics.known_token_missing_cost_count,
90
- 0,
91
- "Token conhecido exige custo conhecido ou estimado",
115
+ invocationAudit.known_token_explicitly_unpriced_count,
116
+ "Token conhecido sem custo deve permanecer NULL e carregar proveniência explícita de tentativa de precificação",
92
117
  );
93
118
  assert.equal(
94
119
  excluded.count,
@@ -127,13 +152,20 @@ try {
127
152
  );
128
153
  assert.equal(
129
154
  invocationAudit.missing_effective_cost_count,
130
- metrics.unknown_agent_run_count,
131
- "Custo ausente só é permitido quando a cobertura de tokens é desconhecida",
155
+ metrics.unknown_agent_run_count + invocationAudit.known_token_explicitly_unpriced_count,
156
+ "Custo ausente só é permitido para telemetria de token desconhecida ou precificação explicitamente indisponível",
132
157
  );
133
158
  assert.equal(
134
159
  invocationAudit.missing_calculated_cost_count,
135
- metrics.unknown_agent_run_count,
136
- "Custo calculado ausente só é permitido quando a cobertura de tokens é desconhecida",
160
+ metrics.unknown_agent_run_count +
161
+ invocationAudit.known_token_explicitly_unpriced_count +
162
+ invocationAudit.recorded_cost_without_calculation_count,
163
+ "Cálculo ausente só é permitido para token desconhecido, precificação explicitamente indisponível ou custo canônico já registrado",
164
+ );
165
+ assert.equal(
166
+ invocationAudit.unexplained_unavailable_cost_count,
167
+ 0,
168
+ "Nenhum custo ausente pode escapar das categorias de indisponibilidade verificáveis",
137
169
  );
138
170
  assert.equal(
139
171
  invocationAudit.component_mismatch_count,
@@ -343,7 +343,7 @@ ${i.join(`\r
343
343
  \r
344
344
  `)},zP=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})},qP=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,[gb]:a},d=400,_;try{let g=await n(zP(s),u);g instanceof Response&&(d=g.status,_=g.headers)}catch{t.listenerCount("upgrade")===1&&rb(l,500);return}let p=r.get(s);if(!p||p.connectionSymbol!==u[fb]){o(s),t.listenerCount("upgrade")===1&&rb(l,d,_);return}let f=g=>{hb(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()})},M5=Gv(async(e,t,n)=>{if(e.req.header("upgrade")?.toLowerCase()!=="websocket")return;let i=e.env,r=i[gb];if(!r||!i.incoming)return new Response(null,{status:500});let o=UP();return i[fb]=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 DP("close",{code:d,reason:_.toString()}),c)}catch(p){(n?.onError??console.error)(p)}}),a.on("error",d=>{try{t?.onError?.(new jP("error",{error:d}),c)}catch(_){(n?.onError??console.error)(_)}})})(),new Response}),VP=e=>{let t=e.fetch,n=MP(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),i=(e.createServer||oP)(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");qP({server:i,fetchCallback:t,wss:e.websocket.server})}return i},yb=(e,t)=>{let n=VP(e);return n.listen(e?.port??3e3,e.hostname,()=>{let i=n.address();t&&t(i)}),n};import{Readable as WP}from"node:stream";import{versions as ZP}from"node:process";var BP=()=>{let[e,t]=ZP.node.split(".").map(n=>parseInt(n));return e>=23||e===22&&t>=7||e===20&&t>=18},HP=BP(),Kp=(e,t=HP)=>{if(t)return WP.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 vb=(e,t=GP)=>{let n=/\.([a-zA-Z0-9]+?)$/,i=e.match(n);if(i)return t[i[1].toLowerCase()]};var JP={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"},GP=JP;import{createReadStream as bb,existsSync as KP,statSync as XP}from"node:fs";import{join as Sb}from"node:path";var YP=/^\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,Yp={br:".br",zstd:".zst",gzip:".gz"},QP=Object.keys(Yp),Xp=e=>{let t;try{t=XP(e)}catch{}return t},eL=/^(?:bytes=)?(?!-$)(\d*)-(\d*)$/,tL=e=>{let t=e.match(eL);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)}},nL=(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}},rL=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},iL=e=>rL(e,decodeURI),Kc=(e={root:""})=>{let t=e.root||"",n=e.path;return t!==""&&!KP(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=iL(i.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(o))throw new Error}catch{return await e.onNotFound?.(i.req.path,i),r()}let a=Sb(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(o,i):o),s=Xp(a);if(s&&s.isDirectory()){let _=e.index??"index.html";a=Sb(a,_),s=Xp(a)}if(!s)return await e.onNotFound?.(a,i),r();let l=vb(a);if(i.header("Content-Type",l||"application/octet-stream"),e.precompressed&&(!l||l==="application/octet-stream"||YP.test(l))){let _=new Set(i.req.header("Accept-Encoding")?.split(",").map(p=>p.trim()));for(let p of QP){if(!_.has(p))continue;let f=Xp(a+Yp[p]);if(f){i.header("Content-Encoding",p),i.header("Vary","Accept-Encoding",{append:!0}),s=f,a=a+Yp[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(Kp(bb(a)),200);else{i.header("Accept-Ranges","bytes");let _=nL(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=bb(a,{start:p,end:f});i.header("Content-Length",m.toString()),i.header("Content-Range",`bytes ${p}-${f}/${u}`),c=i.body(Kp(g),206)}}return await e.onFound?.(a,i),c}};Ve();qr();var oh=(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 Bx=Symbol();var Hx=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,i=>i.toLowerCase())}}).formData();var Jx=32,kG=1e4,Zd=e=>"headers"in e,Xx=async(e,t=Object.create(null))=>{let{all:n=!1,dot:i=!1}=t,a=(Zd(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return a==="multipart/form-data"||a==="application/x-www-form-urlencoded"?EG(e,{all:n,dot:i}):{}};async function EG(e,t){if(!Zd(e)&&e.bodyCache.formData)return Gx(await e.bodyCache.formData,t);let n=Zd(e)?e.headers:e.raw.headers,i=await e.arrayBuffer(),r=Hx(i,n.get("Content-Type")||"");Zd(e)||(e.bodyCache.formData=r);let o=await r;return o?Gx(o,t):{}}function Gx(e,t){let n=Object.create(null),i={count:0};return e.forEach((r,o)=>{t.all||o.endsWith("[]")?wG(n,o,r):n[o]=r}),t.dot&&Object.entries(n).forEach(([r,o])=>{r.includes(".")&&(AG(n,r,o,i),delete n[r])}),n}var wG=(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},AG=(e,t,n,i)=>{if(/(?:^|\.)__proto__\./.test(t))return;let r=e,o=t.split(".",Jx+2);o.length>Jx+1&&Kx(),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++>=kG&&Kx(),r[a]=Object.create(null)),r=r[a])})},Kx=()=>{throw new Error("Nesting limit exceeded")};var sh=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Yx=e=>{let{groups:t,path:n}=TG(e),i=sh(n);return xG(i,t)},TG=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,i)=>{let r=`@${i}`;return t.push([r,n]),r}),{groups:t,path:e}},xG=(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},Bd={},Qx=(e,t)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let i=`${e}#${t}`;return Bd[i]||(n[2]?Bd[i]=t&&t[0]!==":"&&t[0]!=="*"?[i,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)]:Bd[i]=[e,n[1],!0]),Bd[i]}return null},eO=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},OG=e=>eO(e,decodeURI),ch=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 OG(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(r===63||r===35)break}return t.slice(n,i)};var tO=e=>{let t=ch(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},Mi=(e,t,...n)=>(n.length&&(t=Mi(t,...n)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),Hd=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)},pa=e=>e.indexOf("%")!==-1?eO(e,RG):e,ah=e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),pa(e)),nO=(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 ah(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=ah(c)),a=s,c==="")continue;let u;l===-1?u="":(u=e.slice(l+1,s===-1?void 0:s),r&&(u=ah(u))),n?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(u)):o[c]??=u}return t?o[t]:o},rO=nO,iO=(e,t)=>nO(e,t,!0),RG=decodeURIComponent;var oO=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&&pa(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]=pa(i))}return e}#r(e){return this.#t[1]?this.#t[1][e]:e}query(e){return rO(this.url,e)}queries(e){return iO(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 Xx(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[Bx](){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 Jd={Stringify:1,BeforeStream:2,Stream:3},CG=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n};var Ws=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=>Ws(l,t,!1,i,r))).then(()=>r[0]));return n?CG(await a,o):a};var aO="text/plain; charset=UTF-8",lh=(e,t)=>({"Content-Type":e,...t}),Zs=(e,t)=>new Response(e,t),uh=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 oO(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||=Zs(null,{headers:this.#s??=new Headers})}set res(e){if(this.#i&&e){e=Zs(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=Zs(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 Zs(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,lh(aO,n));json=(e,t,n)=>this.#a(JSON.stringify(e),t,lh("application/json",n));html=(e,t,n)=>{let i=r=>this.#a(r,t,lh("text/html; charset=UTF-8",n));return typeof e=="object"?Ws(e,Jd.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??=()=>Zs(),this.#l(this))};var Pt="ALL",sO="all",cO=["get","post","put","delete","options","patch","query"],Gd="Can not add a route since the matcher is already built.",Kd=class extends Error{};var lO="__COMPOSED_HANDLER";var IG=e=>e.text("404 Not Found",404),uO=(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)},dO=class _O{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...cO,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(Pt,this.#e,s)}),this);let{strict:i,...r}=t;Object.assign(this,r),this.getPath=i??!0?t.getPath??ch:tO}#t(){let t=new _O({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=IG;errorHandler=uO;route(t,n){let i=this.basePath(t);return n.routes.map(r=>{let o;n.errorHandler===uO?o=r.handler:(o=async(a,s)=>(await oh([],n.errorHandler)(a,()=>r.handler(a,s))).res,o[lO]=r.handler),i.#o(r.method,r.path,o,r.basePath)}),this}basePath(t){let n=this.#t();return n._basePath=Mi(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=Mi(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(Pt,Mi(t,"*"),s),this}#o(t,n,i,r){t=t.toUpperCase(),n=Mi(this._basePath,n);let o={basePath:r!==void 0?Mi(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 uh(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=oh(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${Mi("/",t)}`,n),i,r));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#i(t.request,t,void 0,t.request.method))})}};var Ct=()=>Object.create(null);var Xd=[];function dh(e,t){let n=this.buildAllMatchers(),i=((r,o)=>{let a=n[r]||n[Pt],s=a[2][o];if(s)return s;let l=o.match(a[0]);if(!l)return[[],Xd];let c=l.indexOf("",1);return[a[1][c],l]});return this.match=i,i(e,t)}var ma="[^/]+",ji=".*",li="(?:|/.*)",Di=Symbol(),pO=new Set(".\\+*[^]$()");function NG(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===ji||e===li?t===li?-1:1:t===ji||t===li?-1:e===ma?1:t===ma?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var mO=class _h{#e;#t;#n=Ct();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?["","",ji]:["","",ma]:null:c==="/*"?["","",li]:c.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let _=u[1],p=u[2]||ma;if(_&&u[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))||p.length===1&&pO.has(p)))throw Di;if(d=a.#n[p],!d){if(p!==ji&&p!==li){for(let f in a.#n)if((p.length>1||f.length>1)&&f!==ji&&f!==li)throw Di}d=a.#n[p]=new _h}_!==""&&(d.#t??=r.varIndex++,i.push([_,d.#t]))}else if(d=a.#n[c],!d){for(let _ in a.#n)if(_.length>1&&_!==ji&&_!==li)throw Di;d=a.#n[c]=new _h}a=d}if(a.#e!==void 0)throw Di;a.#e=o?-1:n}buildRegExpStr(){let n=Object.keys(this.#n).sort(NG).map(i=>{let r=this.#n[i],o=r.buildRegExpStr();return o===""?"":(typeof r.#t=="number"?`(${i})@${r.#t}`:pO.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 ph=class{#e={varIndex:0};#t=new mO;#n=0;paths=Ct();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 fO=Ct();function gO(e){return fO[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,n)=>n?`\\${n}`:t==="/*"?li:t==="*"?ji:`/:${ma}`)}$`)}function Yd(e,t){for(let n of Object.keys(e).sort((i,r)=>r.length-i.length))if(gO(n).test(t))return[...e[n]]}var Qd=class{name="RegExpRouter";#e;#t;#n;constructor(){this.#e={[Pt]:Ct()},this.#t={[Pt]:Ct()},this.#n={[Pt]:new ph}}#o(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(n){throw n===Di?new Kd(t):n}}add(e,t,n){let i=this.#e,r=this.#t;if(!i)throw new Error(Gd);if(!i[e]){this.#n[e]=new ph;for(let s of[i,r]){s[e]=Ct();for(let l in s[Pt])s[e][l]=[...s[Pt][l]],this.#o(e,l)}}t==="/*"&&(t="*");let o=e===Pt?Object.keys(i):[e];if(/\*$/.test(t)){let s=gO(t);for(let l of o)i[l][t]||(this.#o(l,t),i[l][t]=Yd(i[l],t)||Yd(i[Pt],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=Hd(t)||[t];for(let s of a)for(let l of o)r[l][s]||(this.#o(l,s),r[l][s]=Yd(i[l],s)||Yd(i[Pt],s)||[]),r[l][s].push([n,s])}match=dh;buildAllMatchers(){let e=Ct();for(let t of Object.keys(this.#t))e[t]=this.#r(t);return this.#e=this.#t=this.#n=void 0,fO=Ct(),e}#r(e){let t=this.#e[e],n=this.#t[e],i=this.#n[e],r=Ct(),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,Ct()]),Xd];continue}o[_[0]]=d.map(([p,f])=>[p,i.paths[f][1].reduceRight((m,[g],v)=>(m[g]=l[_[1][v][1]],m),Ct())])}return[a,s.map(c=>o[c]),r]}};var mh=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw new Error(Gd);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 Kd)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 fh=Ct(),$G=0,hO=class yO{#e=[];#t=Ct();#n=[];#o;#r=fh;insert(t,n,i){let r=this,o=Yx(n),a=new Set,s=0;for(let l of o){let c=o[++s],u=Qx(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 yO;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:++$G}})}#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[Pt];if(c){c.params=Ct(),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=fh;let o=[this],a=sh(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===fh?{}:{...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 gh=class{name="TrieRouter";#e=new hO;add(e,t,n){for(let i of Hd(t)||[t])this.#e.insert(e,i,n)}match(e,t){return this.#e.search(e,t)}};var hh=class extends dO{constructor(e={}){super(e),this.router=e.router??new mh({routers:[new Qd,new gh]})}};var PG=/^[\w!#$%&'*.^`|~+-]+$/,LG=/^[!#-:<>-[\]-~]+$/,MG=/^[ !#-:<-[\]-~]*$/,vO=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)},yh=(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=vO(r.substring(0,o));if(t&&t!==a||!LG.test(a)||a in i)continue;let s=vO(r.substring(o+1));if(s.startsWith('"')&&s.endsWith('"')&&(s=s.slice(1,-1)),MG.test(s)&&(i[a]=pa(s),t))break}return i};var DG=(e,t,n={})=>{if(!PG.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},e_=(e,t,n)=>(t=encodeURIComponent(t),DG(e,t,n));var bO=(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),yh(i,o)[o]}return i?yh(i):{}};var jG=(e,t,n)=>{let i;return n?.prefix==="secure"?i=e_("__Secure-"+e,t,{path:"/",...n,secure:!0}):n?.prefix==="host"?i=e_("__Host-"+e,t,{...n,path:"/",secure:!0,domain:void 0}):i=e_(e,t,{path:"/",...n}),i},SO=(e,t,n,i)=>{let r=jG(t,n,i);e.header("Set-Cookie",r,{append:!0})};Ve();import{execFile as UG}from"node:child_process";import{resolve as FG}from"node:path";import{promisify as zG}from"node:util";var ui=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kO=e=>typeof e=="string"&&Number.isFinite(Date.parse(e));async function Bs(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!ui(r)||r.schema_version!==1||!kO(r.updated_at)||!ui(r.offsets)||!Object.values(r.offsets).every(a=>Number.isSafeInteger(a)&&Number(a)>=0)||!ui(o)||o.schema_version!==1||!kO(o.updated_at)||!ui(o.counts)||!Number.isSafeInteger(o.counts.total)||Number(o.counts.total)<0||!ui(o.counts.by_kind)||!ui(o.counts.by_status)||!ui(o.freshness)||!ui(o.usage)||!ui(o.periods)?"invalid":"initialized"}catch{return"invalid"}}var qG=zG(UG);async function EO(e){let t=await Bs(new zr(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=FG(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=VG(i.stdout),o=WG(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(ZG(i))return{captured_runs:0,captured_segments:0,manifest_state:"missing",skipped_reason:"manifest_uninitialized",last_capture_at:new Date().toISOString()};throw i}}function VG(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 WG(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 ZG(e){return(e instanceof Error?`${e.message}
345
345
  ${"stdout"in e?String(e.stdout??""):""}
346
- ${"stderr"in e?String(e.stderr??""):""}`:String(e)).includes("Lifecycle manifest is not initialized")}import{execFile as BG}from"node:child_process";import{resolve as HG}from"node:path";import{promisify as JG}from"node:util";var wO=JG(BG);async function AO(e){let t=HG(e,".agents","runtime","bin","zaip.mjs"),n={cwd:e,encoding:"utf8",windowsHide:!0,timeout:12e4,maxBuffer:10*1024*1024};await wO(process.execPath,[t,"adapters","build","--json"],n);let{stdout:i}=await wO(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"):[]}}Ve();import{isDeepStrictEqual as OO}from"node:util";var t_=".agents/config/agents/catalog.yaml",bh=["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"],GG=new Set(bh),Bt=class extends Error{constructor(n,i){super(n);this.status=i}status;name="AgentCatalogUpdateError"};async function RO(e){let t=await IO(e);return{catalog:await QG(e),framework_agent_ids:bh,...t,sync:{required:!0,valid:null,drifted:[]}}}async function CO(e,t,n){let i=await e.readText(t_),r=ki(Ot(i)),o=await IO(e),a=KG(r,t,o);await e.writeTextAtomic(t_,ai(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:bh,...o,sync:{required:!0,valid:!0,drifted:[]}}}catch(s){await e.writeTextAtomic(t_,i);try{await n()}catch{}throw new Bt(`Agent catalog was not saved because adapter synchronization failed: ${s instanceof Error?s.message:String(s)}`,500)}}function KG(e,t,n){if(!vh(t)||!Array.isArray(t.agents))throw new Bt("Request body must contain an agents array",400);if(Object.keys(t).some(o=>o!=="agents"))throw new Bt("Only the agents collection may be updated",400);let i;try{let o=t.agents.map(a=>XG(a));i=ki({schema_version:e.schema_version,agents:o,squads:e.squads})}catch(o){throw new Bt(o instanceof Error?o.message:String(o),400)}eK(e,i),nK(e,i),tK(e,i),n!==void 0&&YG(i,n);let r=Pm(i);if(r.length>0)throw new Bt(r.map(o=>`${o.rule}: ${o.message}`).join("; "),409);return i}function XG(e){if(!vh(e)||!vh(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 IO(e){let n=si(Ot(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 YG(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 Bt(`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 Bt(`Agent ${n.id} uses reasoning effort outside project.allowed_efforts: ${n.model.reasoning_effort}`,400)}}async function QG(e){return ki(Ot(await e.readText(t_)))}function eK(e,t){for(let n of GG){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 Bt(`Framework agent cannot be removed: ${n}`,409);if(!OO(TO(i),TO(r)))throw new Bt(`Framework agent ${n} only allows persona name and role changes`,409)}}function TO(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 tK(e,t){for(let n of e.agents){let i=t.agents.find(r=>r.id===n.id);if(i!==void 0&&!OO(xO(n),xO(i)))throw new Bt(`Existing agent ${n.id} only allows persona name and role changes`,409)}}function xO(e){let{persona:t,codex_task_name:n,nickname_candidates:i,...r}=e;return{...r,persona:{...t,nome:"protected",cargo:"protected"}}}function nK(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 Bt(`Technical identity is stable and cannot be changed: ${n.id}`,409)}}function vh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}Ve();import{execFile as rK}from"node:child_process";import{join as iK}from"node:path";import{promisify as oK}from"node:util";var fa=["Node.js","TypeScript","Vite","Astro","Redis","BullMQ","Hono","React","Git","Terraform"],Hs=["software_architecture","design_system","brandbook","marketing_strategy","sales_playbook","growth_strategy"],n_=fa.length+Hs.length;function $O(e){let t=e.stack.overrides.installation_profile;return t==="full"||t==="dev-lite"||t==="lite"?t:"custom"}async function PO(e,t){try{return(await e.readText(t)).trim().length>0}catch(n){return n.code==="ENOENT"?!1:null}}function Sh(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"?fa:e==="dev-lite"?fa.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&&LO(f)&&f.probe!=="unknown"?a++:f?.probe==="missing"?s++:l++}let c=0,u=0,d=0;for(let _ of Hs){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:{...NO(o.length,a,s,l,fa.length-o.length),installed:a},documentation:{...NO(Hs.length,c,u,d,0),available:c}}}function NO(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 kh(e,t){let n=fa.filter(i=>e.some(r=>r.name===i&&LO(r))).length+Hs.filter(i=>t.some(r=>r.id===i&&r.available===!0)).length;return{completed:n,total:n_,percent:n/n_*100,state:n===n_?"complete":"incomplete"}}function LO(e){return e.verification==="exact"&&e.version!==null&&(e.installation==="runtime"||e.installation==="installed")}var aK=".agents/config/agents/catalog.yaml",sK=".codex/config.toml",cK=".agents/config/framework.lock.yaml",lK=".agents/dashboard/stack-dependencies.json",uK=oK(rK),DO=".agents/architecture/software-architecture.md",dK=[{id:"software_architecture",label:"Arquitetura de Software",artifact:DO},{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 Gs(e){return si(Ot(await e.readText(In)))}async function jO(e){let[t,n,i,r,o]=await Promise.all([e.readText(aK).then(Ot).then(ki),_K(e),pK(e),mK(e,".agents/rules"),fK(e)]),[a,s,l]=await Promise.all([Gs(e),gK(e),Promise.all(dK.map(async d=>({...d,available:await PO(e,d.artifact)})))]),c=kh(s,l),u=Sh($O(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 _K(e){try{let t=Et(Ot(await e.readText(cK))),n=Et(t.framework).version;return typeof n=="string"&&n.trim()?n.trim():null}catch{return null}}async function pK(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 mK(e,t){let n=`${t}/`;return(await e.listFiles(t,".md")).filter(r=>!r.slice(n.length).includes("/")).length}async function fK(e){try{let t=await e.readText(sK);return new Set([...t.matchAll(/^\s*\[\[hooks\.([A-Za-z0-9_-]+)\]\]\s*$/gm)].map(i=>i[1])).size}catch{return 0}}async function gK(e){let[t,n,i,r,o,a]=await Promise.all([Gs(e),yK(e),SK(e,".agents/dashboard/packages/local-runtime/server.mjs"),bK(e),MO(e,"Git",["--version"],"git",u=>/^git version (.+)$/m.exec(u.trim())?.[1]??null),MO(e,"Terraform",["version","-json"],"terraform",u=>{try{let d=JSON.parse(u).terraform_version;return typeof d=="string"?d:null}catch{return null}})]),s=vK(t,n),l=await Promise.all(["typescript","vite","astro","redis","bullmq","hono","react"].map(u=>hK(e,u))),c=new Map(l.map(u=>[u.name,u]));return[kK("Node.js",process.versions.node,s.get("node")),fo("TypeScript","typescript",s.get("typescript"),c),fo("Vite","vite",s.get("vite"),c),fo("Astro","astro",s.get("astro"),c),fo("Redis","redis",s.get("redis"),c),fo("BullMQ","bullmq",s.get("bullmq"),c),fo("Hono","hono",s.get("hono"),c,i),fo("React","react",s.get("react"),c,r),o,a]}async function hK(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=Et(JSON.parse(await e.readText(o))),s=go(a.version),l=EK(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 yK(e){try{let t=Et(JSON.parse(await e.readText(lK))),n=new Map;for(let i of Array.isArray(t.packages)?t.packages:[]){let r=Et(i),o=go(r.name),a=go(r.version);o!==null&&a!==null&&n.set(o,a)}return{node:go(t.node),packages:n}}catch{return{node:null,packages:new Map}}}function vK(e,t){let n=Et(Et(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=go(Et(n[r]).version);a!==null&&i.set(o,a)}return i}async function bK(e){try{return(await e.listFiles(".agents/dashboard/apps/frontend/dist",".js")).length>0}catch{return!1}}async function SK(e,t){try{return(await e.readText(t)).trim().length>0}catch{return!1}}async function MO(e,t,n,i,r){let o=await Gs(e),a=Et(Et(o.stack.overrides).components),s=i==="git"?"latest":go(Et(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=iK(e.root,c),d=await e.exists(c)?u:i;try{let _=r((await uK(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 kK(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 fo(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 go(e){return typeof e=="string"&&e.trim()?e.trim():null}function EK(e){if(typeof e.bin=="string")return e.bin;let t=Object.values(Et(e.bin)).find(n=>typeof n=="string");return typeof t=="string"?t:go(e.main)}async function UO(e,t){let n=await e.readText(In),i=si(Ot(n)),r=si(t);if(r.tracking.storage_mode!=="tracked_sanitized")throw new TypeError("This project requires Git-native tracked_sanitized storage.");let o=Et(i.stack.overrides.components),a=Et(r.stack.overrides.components),s=si({...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(In,ai(s));try{await e.writeTextAtomic(DO,TK(s))}catch(l){throw await e.writeTextAtomic(In,n),new Error("Project settings were rolled back because the software architecture summary could not be updated.",{cause:l})}return s}var wK={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"},AK={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 TK(e){let t=Ko(e.autonomy),n=Et(e.stack.overrides),i=Et(n.components),r=Et(n.languages),o=Et(n.architecture),a=Object.entries(wK).map(([_,p])=>{let f=Et(i[_]);return`| ${p} | ${It(f.name,"N\xE3o definido")} | ${It(f.version,"N\xE3o fixada")} | ${It(f.reference,"\u2014")} |`}),s=Object.entries(e.stack.layout??{}).map(([_,p])=>`| ${It(_)} | ${It(p)} |`),l=Object.entries(e.stack.commands??{}).map(([_,p])=>`| ${It(_)} | \`${xK(p)}\` |`),c=Object.entries(o).flatMap(([_,p])=>[`### ${AK[_]??OK(_)}`,"",...Js(r_(p)),""]),u=e.execution&&e.execution.runtime!=="manual"?[`- **Runtime:** ${e.execution.runtime}`,`- **Provider:** ${It(e.execution.autonomous.provider)}`,`- **Modelo-base:** ${It(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:** ${It(e.assurance.standard_depth)}`,`- **Exigir commit final:** ${e.assurance.require_final_commit?"Sim":"N\xE3o"}`];return["---","schema_version: 1","kind: software-architecture",`generated_from: ${In}`,"---","","# Arquitetura de Software","",`> Proje\xE7\xE3o gerada automaticamente pela p\xE1gina de configura\xE7\xF5es a partir de \`${In}\`. N\xE3o edite este arquivo manualmente.`,"","## Projeto","",`- **Nome:** ${It(e.project.name)}`,`- **ID:** ${It(e.project.id)}`,`- **Timezone:** ${It(e.project.timezone)}`,"","## Perfil t\xE9cnico","",`- **Stack profile:** ${It(e.stack.id)}`,`- **Linguagem:** ${It(e.stack.language,"N\xE3o definida")}`,`- **API:** ${It(e.stack.api,"N\xE3o definida")}`,`- **Query builder:** ${It(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","",...Js(r_(r.frontend)),"","### Backend","",...Js(r_(r.backend)),"","### Site e Landing Pages","",...Js(r_(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","",...Js(e.stack.invariants??[]),"","## Comandos de valida\xE7\xE3o","","| Comando | Execu\xE7\xE3o |","| --- | --- |",...l.length>0?l:["| N\xE3o definido | \u2014 |"],""].join(`
346
+ ${"stderr"in e?String(e.stderr??""):""}`:String(e)).includes("Lifecycle manifest is not initialized")}import{execFile as BG}from"node:child_process";import{resolve as HG}from"node:path";import{promisify as JG}from"node:util";var wO=JG(BG);async function AO(e){let t=HG(e,".agents","runtime","bin","zaip.mjs"),n={cwd:e,encoding:"utf8",windowsHide:!0,timeout:12e4,maxBuffer:10*1024*1024};await wO(process.execPath,[t,"adapters","build","--json"],n);let{stdout:i}=await wO(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"):[]}}Ve();import{isDeepStrictEqual as OO}from"node:util";var t_=".agents/config/agents/catalog.yaml",bh=["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"],GG=new Set(bh),Bt=class extends Error{constructor(n,i){super(n);this.status=i}status;name="AgentCatalogUpdateError"};async function RO(e){let t=await IO(e);return{catalog:await QG(e),framework_agent_ids:bh,...t,sync:{required:!0,valid:null,drifted:[]}}}async function CO(e,t,n){let i=await e.readText(t_),r=ki(Ot(i)),o=await IO(e),a=KG(r,t,o);await e.writeTextAtomic(t_,ai(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:bh,...o,sync:{required:!0,valid:!0,drifted:[]}}}catch(s){await e.writeTextAtomic(t_,i);try{await n()}catch{}throw new Bt(`Agent catalog was not saved because adapter synchronization failed: ${s instanceof Error?s.message:String(s)}`,500)}}function KG(e,t,n){if(!vh(t)||!Array.isArray(t.agents))throw new Bt("Request body must contain an agents array",400);if(Object.keys(t).some(o=>o!=="agents"))throw new Bt("Only the agents collection may be updated",400);let i;try{let o=t.agents.map(a=>XG(a));i=ki({schema_version:e.schema_version,agents:o,squads:e.squads})}catch(o){throw new Bt(o instanceof Error?o.message:String(o),400)}eK(e,i),nK(e,i),tK(e,i),n!==void 0&&YG(i,n);let r=Pm(i);if(r.length>0)throw new Bt(r.map(o=>`${o.rule}: ${o.message}`).join("; "),409);return i}function XG(e){if(!vh(e)||!vh(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 IO(e){let n=si(Ot(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 YG(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 Bt(`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 Bt(`Agent ${n.id} uses reasoning effort outside project.allowed_efforts: ${n.model.reasoning_effort}`,400)}}async function QG(e){return ki(Ot(await e.readText(t_)))}function eK(e,t){for(let n of GG){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 Bt(`Framework agent cannot be removed: ${n}`,409);if(!OO(TO(i),TO(r)))throw new Bt(`Framework agent ${n} only allows persona name and role changes`,409)}}function TO(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 tK(e,t){for(let n of e.agents){let i=t.agents.find(r=>r.id===n.id);if(i!==void 0&&!OO(xO(n),xO(i)))throw new Bt(`Existing agent ${n.id} only allows persona name and role changes`,409)}}function xO(e){let{persona:t,codex_task_name:n,nickname_candidates:i,...r}=e;return{...r,persona:{...t,nome:"protected",cargo:"protected"}}}function nK(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 Bt(`Technical identity is stable and cannot be changed: ${n.id}`,409)}}function vh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}Ve();import{execFile as rK}from"node:child_process";import{join as iK}from"node:path";import{promisify as oK}from"node:util";var fa=["Node.js","TypeScript","Vite","Astro","Redis","BullMQ","Hono","React","Git","Terraform"],Hs=["software_architecture","design_system","brandbook","marketing_strategy","sales_playbook","growth_strategy"],n_=fa.length+Hs.length;function $O(e){let t=e.stack.overrides.installation_profile;return t==="full"||t==="dev-lite"||t==="lite"?t:"custom"}async function PO(e,t){try{return(await e.readText(t)).trim().length>0}catch(n){return n.code==="ENOENT"?!1:null}}function Sh(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"?fa:e==="dev-lite"?fa.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&&LO(f)&&f.probe!=="unknown"?a++:f?.probe==="missing"?s++:l++}let c=0,u=0,d=0;for(let _ of Hs){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:{...NO(o.length,a,s,l,fa.length-o.length),installed:a},documentation:{...NO(Hs.length,c,u,d,0),available:c}}}function NO(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 kh(e,t){let n=fa.filter(i=>e.some(r=>r.name===i&&LO(r))).length+Hs.filter(i=>t.some(r=>r.id===i&&r.available===!0)).length;return{completed:n,total:n_,percent:n/n_*100,state:n===n_?"complete":"incomplete"}}function LO(e){return e.verification==="exact"&&e.version!==null&&(e.installation==="runtime"||e.installation==="installed")}var aK=".agents/config/agents/catalog.yaml",sK=".codex/config.toml",cK=".agents/config/framework.lock.yaml",lK=".agents/dashboard/stack-dependencies.json",uK=oK(rK),DO=".agents/architecture/software-architecture.md",dK=[{id:"software_architecture",label:"Arquitetura de Software",artifact:DO},{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 Gs(e){return si(Ot(await e.readText(In)))}async function jO(e){let[t,n,i,r,o]=await Promise.all([e.readText(aK).then(Ot).then(ki),_K(e),pK(e),mK(e,".agents/rules"),fK(e)]),[a,s,l]=await Promise.all([Gs(e),gK(e),Promise.all(dK.map(async d=>({...d,available:await PO(e,d.artifact)})))]),c=kh(s,l),u=Sh($O(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 _K(e){try{let t=Et(Ot(await e.readText(cK))),n=Et(t.framework).version;return typeof n=="string"&&n.trim()?n.trim():null}catch{return null}}async function pK(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 mK(e,t){let n=`${t}/`;return(await e.listFiles(t,".md")).filter(r=>!r.slice(n.length).includes("/")).length}async function fK(e){try{let t=await e.readText(sK);return new Set([...t.matchAll(/^\s*\[\[hooks\.([A-Za-z0-9_-]+)\]\]\s*$/gm)].map(i=>i[1])).size}catch{return 0}}async function gK(e){let[t,n,i,r,o,a]=await Promise.all([Gs(e),yK(e),SK(e,".agents/dashboard/packages/local-runtime/server.mjs"),bK(e),MO(e,"Git",["--version"],"git",u=>/^git version (.+)$/m.exec(u.trim())?.[1]??null),MO(e,"Terraform",["version","-json"],"terraform",u=>{try{let d=JSON.parse(u).terraform_version;return typeof d=="string"?d:null}catch{return null}})]),s=vK(t,n),l=await Promise.all(["typescript","vite","astro","redis","bullmq","hono","react"].map(u=>hK(e,u))),c=new Map(l.map(u=>[u.name,u]));return[kK("Node.js",process.versions.node,s.get("node")),fo("TypeScript","typescript",s.get("typescript"),c),fo("Vite","vite",s.get("vite"),c),fo("Astro","astro",s.get("astro"),c),fo("Redis","redis",s.get("redis"),c),fo("BullMQ","bullmq",s.get("bullmq"),c),fo("Hono","hono",s.get("hono"),c,i),fo("React","react",s.get("react"),c,r),o,a]}async function hK(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=Et(JSON.parse(await e.readText(o))),s=go(a.version),l=EK(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 yK(e){try{let t=Et(JSON.parse(await e.readText(lK))),n=new Map;for(let i of Array.isArray(t.packages)?t.packages:[]){let r=Et(i),o=go(r.name),a=go(r.version);o!==null&&a!==null&&n.set(o,a)}return{node:go(t.node),packages:n}}catch{return{node:null,packages:new Map}}}function vK(e,t){let n=Et(Et(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=go(Et(n[r]).version);a!==null&&i.set(o,a)}return i}async function bK(e){try{return(await e.listFiles(".agents/dashboard/apps/frontend/dist",".js")).length>0}catch{return!1}}async function SK(e,t){try{return(await e.readText(t)).trim().length>0}catch{return!1}}async function MO(e,t,n,i,r){let o=await Gs(e),a=Et(Et(o.stack.overrides).components),s=i==="git"?"latest":go(Et(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=iK(e.root,c),d=await e.exists(c)?u:i;try{let _=r((await uK(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 kK(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 fo(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 go(e){return typeof e=="string"&&e.trim()?e.trim():null}function EK(e){if(typeof e.bin=="string")return e.bin;let t=Object.values(Et(e.bin)).find(n=>typeof n=="string");return typeof t=="string"?t:go(e.main)}async function UO(e,t){let n=await e.readText(In),i=si(Ot(n)),r=si(t);if(r.tracking.storage_mode!=="tracked_sanitized")throw new TypeError("This project requires Git-native tracked_sanitized storage.");let o=Et(i.stack.overrides.components),a=Et(r.stack.overrides.components),s=si({...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(In,ai(s));try{await e.writeTextAtomic(DO,TK(s))}catch(l){throw await e.writeTextAtomic(In,n),new Error("Project settings were rolled back because the software architecture summary could not be updated.",{cause:l})}return s}var wK={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"},AK={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 TK(e){let t=Ko(e.autonomy),n=Et(e.stack.overrides),i=Et(n.components),r=Et(n.languages),o=Et(n.architecture),a=Object.entries(wK).map(([_,p])=>{let f=Et(i[_]);return`| ${p} | ${It(f.name,"N\xE3o definido")} | ${It(f.version,"N\xE3o fixada")} | ${It(f.reference,"\u2014")} |`}),s=Object.entries(e.stack.layout??{}).map(([_,p])=>`| ${It(_)} | ${It(p)} |`),l=Object.entries(e.stack.commands??{}).map(([_,p])=>`| ${It(_)} | \`${xK(p)}\` |`),c=Object.entries(o).flatMap(([_,p])=>[`### ${AK[_]??OK(_)}`,"",...Js(r_(p)),""]),u=e.execution&&e.execution.runtime!=="manual"?[`- **Runtime:** ${e.execution.runtime}`,`- **Provider:** ${It(e.execution.autonomous.provider)}`,`- **Modelo-base:** ${It(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:** ${It(e.assurance.standard_depth)}`,`- **Exigir commit final:** ${e.assurance.require_final_commit?"Sim":"N\xE3o"}`];return["---","schema_version: 1","kind: software-architecture",`generated_from: ${In}`,"---","","# Arquitetura de Software","",`> Proje\xE7\xE3o gerada automaticamente pela p\xE1gina de configura\xE7\xF5es a partir de \`${In}\`. N\xE3o edite este arquivo manualmente.`,"","## Projeto","",`- **Nome:** ${It(e.project.name)}`,`- **ID:** ${It(e.project.id)}`,`- **Timezone:** ${It(e.project.timezone)}`,"","## Perfil t\xE9cnico","",`- **Stack profile:** ${It(e.stack.id)}`,`- **Linguagem:** ${It(e.stack.language,"N\xE3o definida")}`,`- **API:** ${It(e.stack.api,"N\xE3o definida")}`,`- **Query builder:** ${It(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","",...Js(r_(r.frontend)),"","### Backend","",...Js(r_(r.backend)),"","### Site e Landing Pages","",...Js(r_(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","",...Js(e.stack.invariants??[]),"","## Comandos de valida\xE7\xE3o","","| Comando | Execu\xE7\xE3o |","| --- | --- |",...l.length>0?l:["| N\xE3o definido | \u2014 |"],""].join(`
347
347
  `)}function Et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function r_(e){return Array.isArray(e)?e.flatMap(t=>{if(typeof t=="string"&&t.length>0)return[t];let n=Object.entries(Et(t));return n.length===1&&typeof n[0]?.[1]=="string"?[`${n[0][0]}: ${n[0][1]}`]:[]}):[]}function Js(e){return e.length>0?e.map(t=>`- ${It(t)}`):["- N\xE3o definido."]}function It(e,t="\u2014"){return typeof e!="string"||e.trim().length===0?t:e.trim().replaceAll("|","\\|").replaceAll(/\r?\n/g," ")}function xK(e){return It(e).replaceAll("`","\\`")}function OK(e){let t=e.replaceAll("_"," ");return t.charAt(0).toUpperCase()+t.slice(1)}function FO(){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 zO={"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 RK(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 Eh=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+`
348
348
  `),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 i_=()=>{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 i_=()=>t,t};var qO=class extends Eh{constructor(e,t){super(e,t)}async writeSSE(e){let n=(await Ws(e.data,Jd.Stringify,!1,{})).split(/\r\n|\r|\n/).map(r=>`data: ${r}`).join(`
349
349
  `);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(`
@@ -352,7 +352,7 @@ ${"stderr"in e?String(e.stderr??""):""}`:String(e)).includes("Lifecycle manifest
352
352
  `;await this.write(i)}},CK=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()}},IK=new WeakMap,wh=(e,t,n)=>{let{readable:i,writable:r}=new TransformStream,o=new qO(r,i);return i_()&&e.req.raw.signal.addEventListener("abort",()=>{o.closed||o.abort()}),IK.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"),CK(o,t,n),e.newResponse(o.responseReadable)};function VO(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),wh(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
353
353
 
354
354
  `)}finally{c!==void 0&&clearTimeout(c),o(s)}})})}function a_(e,t){let n=e.length;return{tasks:o_(e.map(i=>i.task_count),n),specs:o_(e.map(i=>i.spec_count),n),prds:o_(e.map(i=>i.prd_count),n),durationMs:o_(e.map(i=>i.duration_ms),n),tokens:WO(e.map(i=>i.total_tokens)),cost:WO(e.map(i=>t==="BRL"?i.estimated_brl:i.estimated_usd))}}function WO(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)/t.length}function o_(e,t){return t===0||e.every(n=>n===null)?null:e.reduce((n,i)=>n+(i??0),0)/t}qr();ga();function BO(e,t){let n=new Map(e.map(i=>[i.key,i]));for(let i of t??[])n.has(i)||n.set(i,LK(i));return[...n.values()].sort((i,r)=>r.latest_started_at.localeCompare(i.latest_started_at)||i.label.localeCompare(r.label))}function LK(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 Ah(e){return e.length===0||e.some(t=>t===null)?null:e.reduce((t,n)=>t+(n??0),0)/e.length}function ha(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)}function Ks(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 c_(e,t="all_invocations"){let n=Ks(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 l_(e){let t=e?.trim().toLowerCase();return!t||t==="unknown"||t==="codex"?"openai":t}var MK={events:0,tokens:0,usd:0,brl:0};function JO(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=>GO(l,n.get(l.id)??[])),r=new Set(e.map(l=>l.id)),o=[...n].filter(([l])=>!r.has(l)).map(([l,c])=>HO(l,c)),a=t.filter(l=>l.task_id===null),s=a.length===0?[]:[HO("Sem tarefa vinculada",a)];return[...i,...o,...s].sort((l,c)=>c.latest_started_at.localeCompare(l.latest_started_at))}function HO(e,t){return{...GO({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 GO(e,t){let n=c_(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:ha(t.map(i=>i.total_tokens)),estimated_usd:ha(t.map(i=>i.estimated_usd)),estimated_brl:ha(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}),MK),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:Th(t,i=>i.total_tokens),usd:Th(t,i=>i.estimated_usd),brl:Th(t,i=>i.estimated_brl)}}}}function Th(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 ya(e,t,n=r=>r,i="all_invocations"){let r=[...new Set(e.map(t))],o=new Set(Ks(e,i).map(a=>a.run_id));return r.map(a=>{let s=e.filter(c=>t(c)===a),l=c_(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:xh(s.map(c=>c.total_tokens)),estimated_usd:xh(s.map(c=>c.estimated_usd)),estimated_brl:xh(s.map(c=>c.estimated_brl)),duration_ms:l.known_sum,duration:l,coverage:DK(s)}}).sort(jK)}function xh(e){return ha(e)}function KO(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)/t.length}function DK(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 jK(e,t){return t.latest_started_at.localeCompare(e.latest_started_at)}function u_(e,t,n){if(e.schema_version!==2)throw new TypeError("Cost Monitor accepts only OperationsProjection V2");let i=t?.currency??"BRL",r=Wr(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??QO(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?nR(M?.usage.total.tokens??B.tokens):null,U=HK(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:FK(y,n),provider:l_(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:UK(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:BK($)??QO(j.usd,j.brl),coverage:B.coverage,artifact_path:y.artifact_path}}),_=(y,k,M)=>ya(d,y,k,M),p=Ui(s),f={conversation:Ui(s.filter(y=>y.entrypoint==="conversation")),task:Ui(s.filter(y=>y.entrypoint==="task")),spec:Ui(s.filter(y=>y.entrypoint==="spec")),prd:Ui(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:on.cutoff,duration_ms:on.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:YO(s.map(y=>a.get(y.id)?.usage.total.cost.usd??null)),recorded_brl:YO(s.map(y=>a.get(y.id)?.usage.total.cost.brl??null)),average_run_cost_usd:Ah(d.map(y=>y.estimated_usd)),average_run_cost_brl:Ah(d.map(y=>y.estimated_brl)),average_run_duration_ms:KO(Ks(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:Wr(d.map(y=>l_(y.provider))),agents:Wr(d.map(y=>y.agent_name)),models:Wr(d.map(y=>y.model)),statuses:Wr(d.map(y=>y.task_status)),priorities:Wr(d.map(y=>y.priority)),risks:Wr(d.map(y=>y.risk)),phases:Wr(d.map(y=>y.phase)),origins:Wr(d.map(y=>y.origin)),work_types:Wr(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:ya(d,y=>y.conversation_id,void 0,"all_invocations"),tasks:JO(e.tasks,d),providers:_(y=>l_(y.provider)),agents:BO(_(y=>y.agent_name),r),models:_(y=>y.model),daily:Oh(ya(d,y=>{let k=y.finished_at??y.started_at;return Lt(k,"day")??k.slice(0,10)},void 0,"all_invocations"),e.tasks,"day"),monthly:Oh(ya(d,y=>{let k=y.finished_at??y.started_at;return Lt(k,"month")??k.slice(0,7)},void 0,"all_invocations"),e.tasks,"month"),annual:Oh(ya(d,y=>{let k=y.finished_at??y.started_at;return Lt(k,"year")??k.slice(0,4)},void 0,"all_invocations"),e.tasks,"year")}}}function Oh(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=Lt(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 UK(e){return e.entrypoint==="task"&&e.phase==="conversation"?"planning":e.phase}function FK(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:WK(m)})):[{provider:e.provider,model:e.effective_model??e.model,serviceTier:e.service_tier??"default",usage:ZK(e.usage.total)}],r=i.map(m=>mo({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=>mo({provider:m.provider==="openai"||m.provider==="anthropic"?m.provider:null,model:m.model,serviceTier:"default",usage:m.usage,catalog:t.catalog,fxRate:null})),a=XO(r.map(m=>m.estimated_usd)),s=XO(o.map(m=>m.estimated_usd)),l=a,c=l===null&&s!==null,u=qK(i,t.catalog),d=VK(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?d_(l-s):null,components:{input:u?.input??null,cached:u?.cached??null,output:u?.output??null,reasoning:u?.reasoning??null}}}function qK(e,t){let n=0,i=0,r=0;for(let o of e){let a=tR(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 tR(e,t){let n=t.toLowerCase();return e.models.find(i=>i.id.toLowerCase()===n||i.aliases.some(r=>r.toLowerCase()===n))??null}function VK(e,t){let n=t.map(r=>tR(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 WK(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 ZK(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 XO(e){return e.length===0||e.some(t=>t===null)?null:d_(e.reduce((t,n)=>t+n,0))}function YO(e){let t=e.filter(n=>n!==null);return t.length===0?null:d_(t.reduce((n,i)=>n+i,0))}function d_(e){return Math.round(e*1e6)/1e6}function QO(e,t){return e!==null&&e>0&&t!==null?d_(t/e):null}function BK(e){if(e.length===0)return null;let t=e[0]??null;return e.every(n=>n===t)?t:null}function HK(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 Ui(e){return Object.fromEntries(["conversation","planning","execution","total","new_work","rework"].map(n=>[n,JK(e.map(i=>i.usage[n]))]))}function JK(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=>nR(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 nR(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:Ui(r)}})}function Wr(e){return[...new Set(e)].sort()}ga();Po();function up(e,t,n,i){let r=(e.run_metrics??[]).map(J9),o=r.filter(N=>{let O=Lt(N.finished_at??N.started_at,"day");return O!==null&&xN(O,t.filters.from,t.filters.to)}).map(H9),a=t.schema_version===2?u_({...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(G9(e)));for(let N of Object.keys(e.cost_monitor_daily_duration??{}))u.has(N)||u.set(N,dv());if(!l&&!c)for(let N of Object.keys(Vr))u.has(N)||u.set(N,dv());let d=[...u].filter(([N])=>xN(N,t.filters.from,t.filters.to)),_=X9(r),p=e.cost_monitor_daily_duration,f=(N,O)=>{if(p!==void 0){let L=p[N];return L===void 0?cv():{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:Jr(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?cv():{value:{known_sum:L,unknown:0,complete:!0,coverage_ratio:1},population:Jr(O.runs,O.runs)}}return l?_.get(N)??cv():B9(N,O)},m=new Map((e.daily_rows??[]).map(N=>[N.key,N])),v=d.map(([N,O])=>K9(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:lv(v.map(N=>N.total_tokens)),k=!c&&o.every(N=>N.usage.total.cost.brl===null)?null:lv(v.map(N=>N.estimated_brl)),M=lv(v.map(N=>N.estimated_usd)),j=Y9(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:on.cutoff,duration_ms:on.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??Ui(o),origins:Q9(),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:TN(v,7),annual:TN(v,4)}}}function B9(e,t){if((Vr[e]??0)>0)return No(e,t);if(t.duration!==void 0){let n=_v(t.runs,t.duration.unknown);return{value:t.duration,population:Jr(t.runs,n)}}return{value:{known_sum:0,unknown:t.runs,complete:t.runs===0,coverage_ratio:t.runs===0?1:0},population:Jr(t.runs,0)}}function dv(){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 H9(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 J9(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 G9(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=Lt(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]??dv(),a=n.get(r)??[],s=av(a.map(u=>u.total_tokens)),l=av(a.map(u=>u.cost)),c=av(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 av(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 K9(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=_v(t.runs,t.usage.total_tokens.unknown),u=_v(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:Jr(t.runs,c),usd:Jr(t.runs,u),brl:Jr(t.runs,u)}}}}function TN(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:uv(r.map(d=>d.total_tokens)),estimated_usd:uv(r.map(d=>d.estimated_usd)),estimated_brl:uv(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:Jr(l,c),tokens:sv(r,"tokens"),usd:sv(r,"usd"),brl:sv(r,"brl")}}}}}).sort((i,r)=>r.key.localeCompare(i.key))}function sv(e,t){let n=e.map(i=>i.coverage_counts?.metrics?.[t]);return Jr(n.reduce((i,r)=>i+(r?.eligible_runs??0),0),n.reduce((i,r)=>i+(r?.known_runs??0),0))}function X9(e){return Tc(e)}function Y9(e){let t=e.filter(n=>n.phase==="execution"&&n.parent_run_id==null&&s_(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 cv(){return{value:{known_sum:0,unknown:0,complete:!0,coverage_ratio:1},population:Jr(0,0)}}function xN(e,t,n){let i=a=>a===null?null:/^\d{4}-\d{2}-\d{2}$/.test(a)?a:Lt(a,"day"),r=i(t),o=i(n);return(r===null||e>=r)&&(o===null||e<=o)}function lv(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)}function uv(e){return e.some(t=>t===null)?null:e.reduce((t,n)=>t+(n??0),0)}function _v(e,t){return Math.max(0,e-t)}function Jr(e,t){return{eligible_runs:e,known_runs:t,unknown_runs:e-t}}function Pa(){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 Q9(){let e=()=>({conversation:Pa(),planning:Pa(),execution:Pa(),total:Pa(),new_work:Pa(),rework:Pa()});return{conversation:e(),task:e(),spec:e(),prd:e()}}qr();Ve();import{createHash as e3}from"node:crypto";var Ee="/api/v2",ON=".agents/dashboard/work-priority.json",Dt=class extends Error{name="V2WorkspaceRequiredError"};async function fi(e){let t=await mx(e);if(t.version===1)throw new Dt("Dashboard API requires a modern ZAIP-AIOS workspace");return t}function ve(e,t,n=200,i=!1){if(i){let r=`"${e3("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 wt(e){let t=e.req.query("from")??null,n=e.req.query("to")??null;return{from:RN(t,"start"),to:RN(n,"end")}}function RN(e,t){if(e===null||!/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let n=CN(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(CN(a)-1).toISOString()}function CN(e){let[t,n,i]=e.split("-").map(Number),r=Date.UTC(t,n-1,i),o=r-IN(r);return o=r-IN(o),o}function IN(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}qr();Po();function dp(e,t){let n=new Map(e.map(i=>[i.id,i]));for(let i of t.map(r=>NN(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 NN(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)}Ve();qr();function Mn(e){return e.req.query("currency")==="USD"?"USD":"BRL"}function Ye(e,t){let n=e.req.query(t);return n===void 0||n===""?[]:n.split(",").filter(Boolean)}async function pv(e,t){let n=new Map,i=new Map,r=1,o=!0;for(;o;){let a=await Vx(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 $N(e){try{let t=ki(Ot(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 Ma(e,t,n,i=!1,r=!1){let o=await Cc(e,t,n,{overviewOnly:i,includeOverviewChanges:r}),a=s3(o,await pp(e,mp(o)));if(i||n.from===null||n.to===null)return a;let s=await pv(e,{from:n.from,to:n.to});return s.length===0?a:ip({...a,runs:Hr(MN(a.runs,s))})}async function pp(e,t){try{let n=mv(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 mp(e){return new Set([...e.prds.map(t=>t.id),...e.specs.map(t=>t.id),...e.tasks.map(t=>t.id)])}function mv(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 La(e,t,n){let i=new Li(e),[r,o]=await Promise.all([i.readCatalog(),n==="BRL"?i.readLatestFxRate():Promise.resolve(null)]),a=await $N(e);return u_(t,{catalog:r,fxRate:o,currency:n},a)}async function LN(e,t,n){let i=n.req.query("from")??null,r=n.req.query("to")??null;if(i===null||r===null)return La(e,t,Mn(n));let o={providers:Ye(n,"provider"),models:Ye(n,"model"),zaip_agents:Ye(n,"agent"),phases:Ye(n,"phase"),statuses:Ye(n,"status")},a=await pv(e,{from:i,to:r,filters:o});if(a.length===0)return La(e,t,Mn(n));let s=Hr(MN(t.runs,a));return La(e,{...t,runs:s},Mn(n))}function MN(e,t){let n=new Set(e.map(i=>i.id));return dp(e,t.filter(i=>n.has(i.run_id)))}async function DN(e,t,n,i,r,o){let a=await l3(e,i.from,i.to),{from:s,to:l}=a,c={providers:Ye(n,"provider"),models:Ye(n,"model"),zaip_agents:Ye(n,"agent"),phases:Ye(n,"phase"),statuses:Ye(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(()=>(Po(),AN)).then(({buildQuickOperationsProjection:k})=>k(e,t,{from:s,to:l})),rh(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(PN):m.slice(r,r+o).map(PN),S=c3(v,_.summaries),b=Hr(S),y=await La(e,{...d,runs:b},Mn(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=dp(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 PN(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:_p(t??o??s,"start"),to:_p(n??a??s,"end")}}function u3(e,t,n){let i=Date.parse(e),r=Date.parse(_p(t,"start")),o=Date.parse(_p(n,"end"));return Number.isFinite(i)&&Number.isFinite(r)&&Number.isFinite(o)&&i>=r&&i<=o}function _p(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 fp(e){return new Li(e).readLatestFxRate()}function jN(e){return["provider","model","agent","phase","status"].every(t=>(e.req.queries(t)?.length??0)===0)}Po();Zr();function fv(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 Ic=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 gv(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)=>Ic(_[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:Ic(_.total_duration),total_tokens:Ic(_.total_tokens),total_cost_usd:Ic(_.total_cost_usd),cost_brl:Ic(_.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}}import{execFile as _3}from"node:child_process";import{createHash as p3}from"node:crypto";import{resolve as FN}from"node:path";import{promisify as m3}from"node:util";var UN=".agents/dashboard/dashboard.config.json",zN=m3(_3);async function gp(e,t){let n=process.env.ZAIP_DASHBOARD_TITLE?.trim()||"Dashboard Zaip AIOS",i="auto";try{if(await e.exists(UN)){let r=JSON.parse(await e.readText(UN));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:hv(i)??""};try{let{stdout:r}=await zN("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",windowsHide:!0});return{title:n,repository_name:hv(r)??""}}catch{return{title:n,repository_name:""}}}function hv(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 yv(e){return p3("sha256").update(`${FN(e)}:dashboard-sqlite`).digest("hex").slice(0,16)}var hp=17e4,Lo=class extends Error{constructor(){super(`Open-work reconciliation exceeded ${hp}ms. Canonical records may contain partial changes; the dashboard projection is being refreshed.`),this.name="ReconciliationCommandTimeoutError"}};async function qN(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=FN(t,".agents","runtime","bin","zaip.mjs"),r;try{({stdout:r}=await zN(process.execPath,[i,"run","reconcile","--open","--json",...n.hostTerminalOnly?["--host-terminal-only"]:[]],{cwd:t,windowsHide:!0,maxBuffer:10*1024*1024,timeout:hp,killSignal:"SIGTERM"}))}catch(o){throw typeof o=="object"&&o!==null&&"killed"in o&&o.killed===!0?new Lo:o}return VN(JSON.parse(r))}function VN(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 Da(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 yp(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"}Ve();function vp(e){return/^\.agents\/(?:data|records)\/(?:executions\/.*\/execution\.md|changes\/.*\/change\.md|(?:changes|executions)\/.*\/decisions\/.*\.md)$/.test(e)}function vv(e){let t=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(e)?.[1];if(t===void 0)return null;try{let n=Ot(t);return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function ja(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function dt(e){return typeof e=="string"&&e.length>0?e:null}function Nc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function _n(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"}qr();var f3=new Intl.DateTimeFormat("en",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"});function mt(e){let t=Object.fromEntries(f3.formatToParts(new Date(e)).filter(n=>n.type!=="literal").map(n=>[n.type,n.value]));return`${t.year}-${t.month}-${t.day}`}function bp(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(`${mt(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=mt(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 bv=2*36e5;function WN(){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 ZN(e){let t=[],n=[],i=[];for(let r of e){if(!vp(r.path))continue;let o=vv(r.content);if(o===null)continue;let a=dt(o.id),s=dt(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=ja(o.origin),c=dt(l?.type),u=c==="interaction"?dt(l?.conversation_id):c==="task"?dt(l?.task_id):c==="spec"?dt(l?.spec_id):c==="prd"?dt(l?.prd_id):null;t.push({id:a,status:dt(o.status),kind:dt(o.kind),originType:c,originId:u,createdAt:s,finishedAt:dt(o.finished_at),sourcePath:r.path});continue}if(/^\.agents\/(?:data|records)\/changes\/.*\/change\.md$/.test(r.path)){let l=ja(o.source),c=dt(l?.type),u=c==="task"?dt(l?.task_id):c==="spec"?dt(l?.spec_id):c==="prd"?dt(l?.prd_id):null;if(c===null||u===null)continue;n.push({id:a,title:dt(o.title)??a,status:dt(o.status)??"unclassified",risk:dt(o.risk)??"unclassified",sourceType:c,sourceId:u,sourceSpecId:dt(l?.spec_id),sourcePrdId:dt(l?.prd_id),requirementIds:Nc(o.requirement_ids),acceptanceIds:Nc(o.acceptance_ids),taskIds:Nc(o.task_ids),result:dt(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=dt(o.scope_id);if(l!=="human"&&l!=="agent"||c!=="change"&&c!=="execution"||u===null)continue;i.push({id:a,title:dt(o.title)??a,origin:l,scopeType:c,scopeId:u,createdAt:s,sourcePath:r.path})}}}return{executions:t,changes:n,decisions:i}}function Sv(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"?Da({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 BN(e,t){let n=new Map;for(let i of(e??"").split(/^ {2}- id: /m).slice(1)){let r=i.slice(0,i.indexOf(`
355
- `)).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 HN(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 pn(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 Ua(e,t,n){return e==="openai"||e==="anthropic"?e:e==="unavailable"||t==="unavailable"||t===null?null:Vd(t,n,"")}function g3(e){return typeof e.duration_ms=="number"&&(e.duration_provenance==="observed"||e.duration_provenance==="reconciled"||e.duration_provenance==="legacy_inferred")}function h3(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<=bv?[{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<=bv?{start:n.start,end:i.end,duration:i.endMs-n.startMs}:null}function JN(e,t){let n=h3(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(g3);if(i.length>0){let a=i.reduce((l,c)=>l+(c.duration_ms??0),0),s=_n(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<=bv?{source:null,effective:o-r,provenance:"reconciled",sourceStartedAt:null,sourceFinishedAt:null}:{source:null,effective:null,provenance:null,sourceStartedAt:null,sourceFinishedAt:null}}function GN(e){return e.flatMap(t=>{try{return[_o.parse(JSON.parse(t.content))]}catch{return[]}}).sort((t,n)=>n.as_of.localeCompare(t.as_of))[0]??null}function Sp(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=mo({provider:Ua(_.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=pn(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:_n(c),pricingSource:_n(u),fxRate:s?i?.rate??null:null}}function y3(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 KN(e,t,n,i){let r=e.model??t.run.model,o=Ua(e.provider,r,t.run.client),a=e.runtime?.service_tier??null,s=y3(n,r),l=r===null?null:mo({provider:o,model:r,usage:e.tokens,catalog:n,fxRate:i,serviceTier:a}),c=r===null?null:mo({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 rt(e){return e==null?null:/^\d{4}-\d{2}-\d{2}$/.test(e)?e:mt(e)}function kv(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 XN(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:mt(o),taskId:r("task_id"),changeId:r("change_id"),runId:r("run_id")}}Ve();import{DatabaseSync as G0}from"node:sqlite";var v3=["prd_count","spec_count","task_count","test_count","evidence_count"],kp=()=>({prd_count:0,spec_count:0,task_count:0,test_count:0,evidence_count:0});function b3(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
+ `)).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 HN(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 pn(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 Ua(e,t,n){return e==="openai"||e==="anthropic"?e:e==="unavailable"||t==="unavailable"||t===null?null:Vd(t,n,"")}function g3(e){return typeof e.duration_ms=="number"&&(e.duration_provenance==="observed"||e.duration_provenance==="reconciled"||e.duration_provenance==="legacy_inferred")}function h3(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<=bv?[{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<=bv?{start:n.start,end:i.end,duration:i.endMs-n.startMs}:null}function JN(e,t){let n=h3(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(g3);if(i.length>0){let a=i.reduce((l,c)=>l+(c.duration_ms??0),0),s=_n(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<=bv?{source:null,effective:o-r,provenance:"reconciled",sourceStartedAt:null,sourceFinishedAt:null}:{source:null,effective:null,provenance:null,sourceStartedAt:null,sourceFinishedAt:null}}function GN(e){return e.flatMap(t=>{try{return[_o.parse(JSON.parse(t.content))]}catch{return[]}}).sort((t,n)=>n.as_of.localeCompare(t.as_of))[0]??null}function Sp(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=mo({provider:Ua(_.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=pn(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:_n(c),pricingSource:_n(u),fxRate:s?i?.rate??null:null}}function y3(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 KN(e,t,n,i){let r=e.model??t.run.model,o=Ua(e.provider,r,t.run.client),a=e.runtime?.service_tier??null,s=y3(n,r),l=r===null?null:mo({provider:o,model:r,usage:e.tokens,catalog:n,fxRate:i,serviceTier:a}),c=r===null?null:mo({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 rt(e){return e==null?null:/^\d{4}-\d{2}-\d{2}$/.test(e)?e:mt(e)}function kv(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 XN(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:mt(o),taskId:r("task_id"),changeId:r("change_id"),runId:r("run_id")}}Ve();import{DatabaseSync as G0}from"node:sqlite";var v3=["prd_count","spec_count","task_count","test_count","evidence_count"],kp=()=>({prd_count:0,spec_count:0,task_count:0,test_count:0,evidence_count:0});function b3(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 (
356
356
  SELECT json_extract(payload_json,'$.path') path,
357
357
  json_extract(payload_json,'$.artifact_kind') artifact_kind,
358
358
  json_extract(payload_json,'$.artifact_id') artifact_id,
@@ -230,11 +230,10 @@ describe("project settings persistence", () => {
230
230
  autocannon: { name: "autocannon", version: "" },
231
231
  future_tool: { enabled: true },
232
232
  });
233
- await expect(filesystem.readText(SOFTWARE_ARCHITECTURE_PATH)).resolves.toContain(
234
- "| Coleta de métricas | Prometheus | 3.6.0 | docker:prom/prometheus |",
235
- );
233
+ const architecture = await filesystem.readText(SOFTWARE_ARCHITECTURE_PATH);
234
+ expect(architecture).toContain("Prometheus | 3.6.0 | docker:prom/prometheus");
235
+ expect(architecture).toContain("Tecnologia | Versão atual / referência | Pacote");
236
236
  });
237
-
238
237
  it("rejects invalid settings before touching the project file", async () => {
239
238
  const { configPath, filesystem } = await fixtureProject();
240
239
  const original = await readFile(configPath, "utf8");
@@ -610,7 +610,7 @@ export function renderSoftwareArchitecture(config: ProjectConfig): string {
610
610
  "",
611
611
  "## Componentes e versões",
612
612
  "",
613
- "| Responsabilidade | Tecnologia | Versão exata | Pacote / imagem / serviço |",
613
+ "| Responsabilidade | Tecnologia | Versão atual / referência | Pacote / imagem / serviço |",
614
614
  "| --- | --- | --- | --- |",
615
615
  ...componentRows,
616
616
  "",
@@ -1,10 +1,10 @@
1
+ import { execFile } from "node:child_process";
1
2
  import { EventEmitter } from "node:events";
2
3
  import { copyFile, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3
- import { execFile } from "node:child_process";
4
- import { promisify } from "node:util";
5
4
  import { tmpdir } from "node:os";
6
5
  import { join, resolve } from "node:path";
7
6
  import { DatabaseSync } from "node:sqlite";
7
+ import { promisify } from "node:util";
8
8
  import { describe, expect, it, vi } from "vitest";
9
9
  import {
10
10
  attachRefreshWorkerCleanup,
@@ -1,8 +1,8 @@
1
1
  import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
2
2
  import { join, resolve } from "node:path";
3
3
  import { expect, it } from "vitest";
4
- import { prepareMultiProviderFixture } from "./sqlite-read-model-multi-provider-fixture.js";
5
4
  import { rebuildSqliteReadModel, SqliteReadModelFileSystem } from "./sqlite-read-model.js";
5
+ import { prepareMultiProviderFixture } from "./sqlite-read-model-multi-provider-fixture.js";
6
6
 
7
7
  it.each([
8
8
  "draft",
@@ -0,0 +1,75 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { usagePricingAudit } from "./sqlite-read-model-canonical.js";
3
+
4
+ describe("SQLite pricing provenance", () => {
5
+ it("retains catalog provenance when cache-write telemetry keeps a token estimate unavailable", () => {
6
+ const audit = usagePricingAudit(
7
+ {
8
+ model: "gpt-a",
9
+ provider: "openai",
10
+ runtime: { service_tier: null },
11
+ tokens: {
12
+ input: 10,
13
+ cached_input: 0,
14
+ cache_write_input: null,
15
+ output: 5,
16
+ reasoning: 0,
17
+ total: 15,
18
+ },
19
+ cost: { usd: null, brl: null, fx_rate: null },
20
+ } as never,
21
+ { run: { model: "gpt-a", client: "codex" } } as never,
22
+ {
23
+ updated_at: "2026-08-04T00:00:00.000Z",
24
+ models: [
25
+ {
26
+ id: "gpt-a",
27
+ provider: "openai",
28
+ aliases: [],
29
+ input_per_million_usd: 2,
30
+ cached_input_per_million_usd: 0.2,
31
+ cache_write_input_per_million_usd: 3,
32
+ output_per_million_usd: 8,
33
+ reasoning_per_million_usd: 8,
34
+ reasoning_billed_separately: false,
35
+ long_context_threshold_tokens: null,
36
+ long_context_input_multiplier: 1,
37
+ long_context_output_multiplier: 1,
38
+ source_label: "fixture-openai",
39
+ source_url: "https://example.test/openai",
40
+ notes: [],
41
+ },
42
+ ],
43
+ } as never,
44
+ null,
45
+ );
46
+ expect(audit).toMatchObject({
47
+ calculatedUsd: null,
48
+ effectiveUsd: null,
49
+ pricingModel: "gpt-a",
50
+ pricingSource: "fixture-openai",
51
+ });
52
+ });
53
+
54
+ it("keeps a recorded cost authoritative when no token calculation is available", () => {
55
+ const audit = usagePricingAudit(
56
+ {
57
+ model: "provider-only-model",
58
+ provider: "openai",
59
+ runtime: { service_tier: null },
60
+ tokens: { input: 10, cached_input: 0, output: 5, reasoning: 0, total: 15 },
61
+ cost: { usd: 0.012, brl: 0.06, fx_rate: 5 },
62
+ } as never,
63
+ { run: { model: "provider-only-model", client: "codex" } } as never,
64
+ { updated_at: "2026-08-04T00:00:00.000Z", models: [] } as never,
65
+ null,
66
+ );
67
+ expect(audit).toMatchObject({
68
+ calculatedUsd: null,
69
+ recordedUsd: 0.012,
70
+ effectiveUsd: 0.012,
71
+ effectiveBrl: 0.06,
72
+ pricingModel: null,
73
+ });
74
+ });
75
+ });
@@ -701,8 +701,8 @@ export function usagePricingAudit(
701
701
  recordedUsd !== null && calculatedUsd !== null
702
702
  ? Math.round((recordedUsd - calculatedUsd) * 1_000_000) / 1_000_000
703
703
  : null,
704
- pricingModel: priced?.pricing_model ?? null,
705
- pricingSource: priced?.pricing_source ?? null,
704
+ pricingModel: priced?.pricing_model ?? pricingModel?.id ?? null,
705
+ pricingSource: priced?.pricing_source ?? pricingModel?.source_label ?? null,
706
706
  fxRate: record.cost.fx_rate ?? fxRate?.rate ?? null,
707
707
  };
708
708
  }